blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
288
| content_id
stringlengths 40
40
| detected_licenses
listlengths 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 684
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 147
values | src_encoding
stringclasses 25
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 128
12.7k
| extension
stringclasses 142
values | content
stringlengths 128
8.19k
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
573e195a6ee0cf64d44548b0b3cf38f0233749b1
|
7c843f80a08db6725fd8d2e85099d9e6c13f6426
|
/lib/yllibInterface.py
|
ec7a24ba3216459a602d8f2be161df434745f8a3
|
[] |
no_license
|
wanfade/scaffolding_Seg
|
e983c1d1cdd60efcd7d381728c277993a1cf4721
|
12ba8892eb44d3ce47fa2609973b0510904c4753
|
refs/heads/master
| 2023-03-16T05:57:28.808341 | 2017-11-25T13:53:11 | 2017-11-25T13:53:11 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 405 |
py
|
# -*- coding: utf-8 -*-
import sys
from os.path import abspath,join,dirname
yllibPath = abspath(join(dirname(abspath(__file__)),'./yl'))
if yllibPath not in sys.path:
sys.path = [yllibPath] + sys.path
import tool
import ylimg as imglib
import ylml as mllib
import ylnp as nplib
from tool import *
from ylimg import *
from ylml import *
from ylnp import *
if __name__ == '__main__':
pass
|
[
"[email protected]"
] | |
a1d7168df36367a6a9de58b2eef43b6e2a6c0481
|
14a58f0c6d0bcfeeb308a8a8719d0e9e728ee48e
|
/tests/test_custom.py
|
13238835eb34053c78b53794b33cf1e7e3e11830
|
[
"MIT"
] |
permissive
|
wesselb/lab
|
262da5a30c1b3a78e576014d9b752aae52959774
|
275d041bdd47bbbad1fce5a10bbce0d7beceefdb
|
refs/heads/master
| 2023-06-08T11:04:03.523207 | 2023-05-27T10:15:07 | 2023-05-27T10:15:07 | 127,299,861 | 62 | 6 |
MIT
| 2023-09-01T09:53:02 | 2018-03-29T14:02:14 |
Python
|
UTF-8
|
Python
| false | false | 4,677 |
py
|
import jax
import jax.numpy as jnp
import lab as B
import numpy as np
import pytest
import tensorflow as tf
import torch
from autograd import grad
from fdm import check_sensitivity, gradient
from lab.custom import (
toeplitz_solve,
s_toeplitz_solve,
bvn_cdf,
s_bvn_cdf,
expm,
s_expm,
logm,
s_logm,
)
from lab.tensorflow.custom import as_tf
from lab.torch.custom import as_torch
from plum import isinstance
# noinspection PyUnresolvedReferences
from .util import approx, check_lazy_shapes, check_function, PSD
def test_as_tf(check_lazy_shapes):
assert isinstance(as_tf(B.randn()), B.TFNumeric)
assert isinstance(as_tf((B.randn(),))[0], B.TFNumeric)
def test_as_torch(check_lazy_shapes):
assert isinstance(as_torch(B.randn()), B.TorchNumeric)
assert isinstance(as_torch((B.randn(),))[0], B.TorchNumeric)
def check_grad(f, args, kw_args=None, rtol=1e-8):
"""Check the gradients of a function.
Args:
f (function): Function to check gradients of.
args (tuple): Arguments to check `f` at.
kw_args (tuple, optional): Keyword arguments to check `f` at. Defaults
to no keyword arguments.
rtol (float, optional): Relative tolerance. Defaults to `1e-8`.
"""
# Default to no keyword arguments.
if kw_args is None:
kw_args = {}
# Get the associated function in LAB.
lab_f = getattr(B, f.__name__)
def create_f_i(i, args_):
# Create a function that only varies the `i`th argument.
def f_i(x):
return B.mean(lab_f(*(args_[:i] + (x,) + args_[i + 1 :]), **kw_args))
return f_i
# Walk through the arguments.
for i in range(len(args)):
# Numerically compute gradient.
f_i = create_f_i(i, args)
numerical_grad = gradient(f_i)(args[i])
# Check AutoGrad gradient.
autograd_grad = grad(f_i)(args[i])
approx(numerical_grad, autograd_grad, rtol=rtol)
# Check TensorFlow gradient.
tf_args = tuple([as_tf(arg) for arg in args])
f_i = tf.function(create_f_i(i, tf_args), autograph=False)
with tf.GradientTape() as t:
t.watch(tf_args[i])
tf_grad = t.gradient(f_i(tf_args[i]), tf_args[i]).numpy()
approx(numerical_grad, tf_grad, rtol=rtol)
# Check PyTorch gradient.
torch_args = tuple([as_torch(arg, grad=False) for arg in args])
f_i = torch.jit.trace(create_f_i(i, torch_args), torch_args[i])
arg = torch_args[i].requires_grad_(True)
f_i(arg).backward()
approx(numerical_grad, arg.grad, rtol=rtol)
# Check JAX gradient.
jax_args = tuple([jnp.asarray(arg) for arg in args])
f_i = create_f_i(i, jax_args)
jax_grad = jax.jit(jax.grad(f_i))(jax_args[i])
approx(numerical_grad, jax_grad, rtol=rtol)
def test_toeplitz_solve(check_lazy_shapes):
check_sensitivity(
toeplitz_solve, s_toeplitz_solve, (B.randn(3), B.randn(2), B.randn(3))
)
check_sensitivity(
toeplitz_solve, s_toeplitz_solve, (B.randn(3), B.randn(2), B.randn(3, 4))
)
check_grad(toeplitz_solve, (B.randn(3), B.randn(2), B.randn(3)))
check_grad(toeplitz_solve, (B.randn(3), B.randn(2), B.randn(3, 4)))
def test_bvn_cdf(check_lazy_shapes):
check_sensitivity(bvn_cdf, s_bvn_cdf, (B.rand(3), B.rand(3), B.rand(3)))
check_grad(bvn_cdf, (B.rand(3), B.rand(3), B.rand(3)))
# Check that function runs on both `float32`s and `float64`s.
a, b, c = B.rand(3), B.rand(3), B.rand(3)
approx(
B.bvn_cdf(a, b, c),
B.bvn_cdf(B.cast(np.float32, a), B.cast(np.float32, b), B.cast(np.float32, c)),
)
# Check that, in JAX, the function check the shape of the inputs.
with pytest.raises(ValueError):
B.bvn_cdf(
B.rand(jnp.float32, 2), B.rand(jnp.float32, 3), B.rand(jnp.float32, 3)
)
with pytest.raises(ValueError):
B.bvn_cdf(
B.rand(jnp.float32, 3), B.rand(jnp.float32, 2), B.rand(jnp.float32, 3)
)
with pytest.raises(ValueError):
B.bvn_cdf(
B.rand(jnp.float32, 3), B.rand(jnp.float32, 3), B.rand(jnp.float32, 2)
)
def test_expm(check_lazy_shapes):
check_sensitivity(expm, s_expm, (B.randn(3, 3),))
check_grad(expm, (B.randn(3, 3),))
def test_logm_forward(check_lazy_shapes):
# This test can be removed once the gradient is implemented and the below test
# passes.
check_function(B.logm, (PSD(3),))
@pytest.mark.xfail
def test_logm(check_lazy_shapes):
mat = B.eye(3) + 0.1 * B.randn(3, 3)
check_sensitivity(logm, s_logm, (mat,))
check_grad(logm, (mat,))
|
[
"[email protected]"
] | |
b6b30a5211de514ccc29a84165549898bf818ab2
|
080c13cd91a073457bd9eddc2a3d13fc2e0e56ae
|
/GIT-USERS/TOM2/cs41long_lambda_mud_server/adv_project/settings.py
|
262f1bf5e8db671d85bf94889ff91cb1a1be8b13
|
[] |
no_license
|
Portfolio-Projects42/UsefulResourceRepo2.0
|
1dccc8961a09347f124d3ed7c27c6d73b9806189
|
75b1e23c757845b5f1894ebe53551a1cf759c6a3
|
refs/heads/master
| 2023-08-04T12:23:48.862451 | 2021-09-15T12:51:35 | 2021-09-15T12:51:35 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 4,698 |
py
|
"""
Django settings for adv_project project.
Generated by 'django-admin startproject' using Django 2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
from decouple import config
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', cast=bool)
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'adventure',
'api',
'corsheaders',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'rest_auth.registration',
]
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
SITE_ID = 1
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
ROOT_URLCONF = 'adv_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'adv_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
# DATABASES = {}
import dj_database_url
# DATABASES['default'] = dj_database_url.config(default=config('DATABASE_URL'), conn_max_age=600)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
db_from_env = dj_database_url.config(conn_max_age=500)
# DATABASES['default'].update(db_from_env)
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
# DATABASES['default'] = dj_database_url.config(default=config('DATABASE_URL'))
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
from rest_framework.authentication import SessionAuthentication, BasicAuthentication, TokenAuthentication
REST_FRAMEWORK = {
# 'DEFAULT_PERMISSION_CLASSES': [
# 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
# ],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
}
CORS_ORIGIN_ALLOW_ALL=True
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
import django_heroku
django_heroku.settings(locals())
|
[
"[email protected]"
] | |
e92b8e4b15c288eff358cd8ca006e1290b4b5e34
|
36b04c5d9ae181a780d44764dd85bcc784e72101
|
/cifar10_resnet/ensemble/saved_models/load_model.py
|
5334b291c6071e015285bbce9ab03b85e6023c65
|
[] |
no_license
|
chengning-zhang/Ensemble-Method-in-Image-Classification
|
9783b6b30f3e174fad1504a44cca57093f8c8730
|
a7c4176334f8e7701fe9cae77fc31b3b6ed0704d
|
refs/heads/master
| 2022-12-30T09:07:30.546966 | 2020-10-21T20:03:51 | 2020-10-21T20:03:51 | 112,964,609 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 588 |
py
|
from keras.models import load_model
from resnet import *
if __name__ == "__main__":
# Training parameters
batch_size = 64
epochs = 2
data_augmentation = True
num_classes = 10
# Subtracting pixel mean improves accuracy
n = 3
# Model version
# Orig paper: version = 1 (ResNet v1), Improved ResNet: version = 2 (ResNet v2)
version = 1
substract_pixel_mean = True
(x_train, y_train), (x_test, y_test), input_shape = prepare_data_for_resnet(substract_pixel_mean)
filename = "cifar10_resnet_model.01.h5"
model = load_model(filename)
|
[
"[email protected]"
] | |
ac96698f9e823501b4e9678648199c29f14f8d32
|
236c6d7f53d61dfbddefa3b6574f181ccef72e60
|
/lessons/lesson18/demo/migrations/0001_initial.py
|
5c3a99d8634bbc9b10b49ec5bf5f502928440c92
|
[] |
no_license
|
maxchv/LearnPython
|
94193c9770dc7b788099076316a1dbd6a5112cf4
|
561f74f39644cd6694ef36869beb7ddb6ff006dc
|
refs/heads/master
| 2022-07-07T18:31:02.274159 | 2022-06-15T15:10:40 | 2022-06-15T15:10:40 | 65,457,162 | 1 | 7 | null | 2019-10-23T05:42:30 | 2016-08-11T09:30:53 |
Python
|
UTF-8
|
Python
| false | false | 677 |
py
|
# Generated by Django 4.0.4 on 2022-05-11 18:48
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Task',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('description', models.TextField()),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
],
),
]
|
[
"[email protected]"
] | |
46465500fcd64b9c80c677b23f3c2d5ec50ef1f0
|
b7e0ea14903ac611413e490c741f5b7e4ffb29df
|
/MySQL数据库命令.py
|
d4c6c66dc2a7bd74f2e64fba37b1caaab13b8d63
|
[] |
no_license
|
pointworld/python
|
c729d6fc029edf28a3b331adf7de888af0216646
|
06bee716f2615526757a67dcd35be59abc31ff41
|
refs/heads/master
| 2021-07-13T13:14:55.540038 | 2017-10-09T14:45:50 | 2017-10-09T14:45:50 | 103,842,172 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 6,636 |
py
|
编程常见命令集合
MySQL数据库命令
登录到MySQL
mysql -h localhost -u root -p
localhost:IP地址;
root:用户名;
database:数据库名(可以省略,如果有,跟在-p面)
删除数据库:
mysqladmin -u root -pwrf956750621 drop awesome
初始化数据库:
mysql –u root –p密码 <D:\computer_learning\backup\schema.sql
mysql -u root -p
2.mysql -h localhost -u root -p database_name
列出数据库:
show databases;
选择数据库:
use databases_name;
列出数据表:
show tables;
显示表格列的属性:
show columns from table_name;
describe table_name;
导出整个数据库:
mysqldump -u user_name -p database_name > path_file_name
例如:mysqldump -u root -p test_db > d:/test_db.sql
导出一个表:
mysqldump -u user_name -p database_name table_name > /tmp/file_name
例如:mysqldump -u root -p test_db table1 > d:/table1.sql
导出一个数据库结构:
mysqldump -u user_name -p -d --add-drop-table database_name > file_name
例如:mysqldump -u root -p -d --add-drop-table test_db > test_db.sql
导入数据库:
source file_name;
或
mysql -u user_name -p database_name < file_name
例如:
source /tmp/bbs.sql;
source d:/bbs.sql;
mysql -u root -p bbs < "d:/bbs.sql"
mysql -u root -p bbs < "/tmp/bbs.sql"
将文本文件导入数据表中(excel与之相同)
load data infile "tables.txt" into table table_name;
例如:
load data infile "/tmp/bbs.txt" into table bbs;
load data infile "/tmp/bbs.xls" into table bbs;
load data infile "d:/bbs.txt" into table bbs;
load data infile "d:/bbs.xls" into table bbs;
将数据表导出为文本文件(excel与之相同)
select * into outfile "path_file_name" from table_name;
例如:
select * into outfile "/tmp/bbs.txt" from bbs;
select * into outfile "/tmp/bbs.xls" from bbs where id=1;
select * into outfile "d:/bbs.txt" from bbs;
select * into outfile "d:/bbs.xls" from bbs where id=1;
创建数据库时先判断数据库是否存在:
create database if not exists database_name;
例如:create database if not exists bbs
创建数据库:
create database database_name;
例如:create database bbs;
删除数据库:
1.drop database database_name;
例如:drop database bbs;
创建数据表:
1.mysql> create table <table_name> ( <column 1 name> <col. 1 type> <col. 1 details>,<column 2 name> <col. 2 type> <col. 2 details>, ...);
例如:create table (id int not null auto_increment primary key,name char(16) not null default "jack",date_year date not null);
删除数据表中数据:
delete from table_name;
例如:
delete from bbs;
delete from bbs where id=2;
删除数据库中的数据表:
drop table table_name;
例如:
drop table test_db;
rm -f database_name/table_name.* (linux下)
例如:
rm -rf bbs/accp.*
向数据库中添加数据:
insert into table_name set column_name1=value1,column_name2=value2;
例如:insert into bbs set name="jack",date_year="1993-10-01";
insert into table_name values (column1,column2,...);
例如:insert into bbs ("2","jack","1993-10-02")
insert into table_name (column_name1,column_name2,...) values (value1,value2);
例如:insert into bbs (name,data_year) values ("jack","1993-10-01");
查询数据表中的数据:
select * from table_name;
例如:select * from bbs where id=1;
修改数据表中的数据:
update table_name set col_name=new_value where id=1;
例如:update bbs set name="tom" where name="jack";
增加一个字段:
alter table table_name add column field_name datatype not null default "1";
例如:alter table bbs add column tel char(16) not null;
增加多个字段:(column可省略不写)
alter table table_name add column filed_name1 datatype,add column filed_name2 datatype;
例如:alter table bbs add column tel char(16) not null,add column address text;
删除一个字段:
alter table table_name drop field_name;
例如:alter table bbs drop tel;
修改字段的数据类型:
alter table table_name modify id int unsigned;//修改列id的类型为int unsigned
alter table table_name change id sid int unsigned;//修改列id的名字为sid,而且把属性修改为int unsigned
修改一个字段的默认值:
alter table table_name modify column_name datatype not null default "";
例如:alter table test_db modify name char(16) default not null "yourname";
对表重新命名:
alter table table_name rename as new_table_name;
例如:alter table bbs rename as bbs_table;
rename table old_table_name to new_table_name;
例如:rename table test_db to accp;
从已经有的表中复制表的结构:
create table table2 select * from table1 where 1<>1;
例如:create table test_db select * from accp where 1<>1;
查询时间:
select now();
查询当前用户:
select user();
查询数据库版本:
select version();
创建索引:
alter table table1 add index ind_id(id);
create index ind_id on table1(id);
create unique index ind_id on table1(id);//建立唯一性索引
删除索引:
drop index idx_id on table1;
alter table table1 drop index ind_id;
联合字符或者多个列(将id与":"和列name和"="连接)
select concat(id,':',name,'=') from table;
limit(选出10到20条)
select * from bbs order by id limit 9,10;
(从查询结果中列出第几到几条的记录)
增加一个管理员账号:
grant all on *.* to user@localhost identified by "password";
创建表是先判断表是否存在
create table if not exists students(……);
复制表:
create table table2 select * from table1;
例如:create table test_db select * from accp;
授于用户远程访问mysql的权限
grant all privileges on *.* to "root"@"%" identified by "password" with grant option;
或者是修改mysql数据库中的user表中的host字段
use mysql;
select user,host from user;
update user set host="%" where user="user_name";
查看当前状态
show status;
查看当前连接的用户
show processlist;
(如果是root用户,则查看全部的线程,得到的用户连接数同show status;里的 Threads_connected值是相同的)
qq邮箱授权密码: xgyphxmyyntjbfbg
|
[
"[email protected]"
] | |
f7d6c4be894a80d920335e88119b8b8f5cb8e7ba
|
325bee18d3a8b5de183118d02c480e562f6acba8
|
/germany/germany_l/germany/ScriptDir/Move_2_Nas.py
|
ad52465414998306bcd3649c403736db8a51f842
|
[] |
no_license
|
waynecanfly/spiderItem
|
fc07af6921493fcfc21437c464c6433d247abad3
|
1960efaad0d995e83e8cf85e58e1db029e49fa56
|
refs/heads/master
| 2022-11-14T16:35:42.855901 | 2019-10-25T03:43:57 | 2019-10-25T03:43:57 | 193,424,274 | 4 | 0 | null | 2022-11-04T19:16:15 | 2019-06-24T03:00:51 |
Python
|
UTF-8
|
Python
| false | false | 1,962 |
py
|
# -*- coding: utf-8 -*-
import pymysql
from ftplib import FTP
import os
class Move2Nas(object):
num = 0
def __init__(self):
self.conn = pymysql.connect(host="10.100.4.99", port=3306, db="opd_common", user="root", passwd="OPDATA", charset="utf8")
self.cursor = self.conn.cursor()
def get_fiscal_year(self, file_name):
"""获取财年"""
sql = "select fiscal_year from non_financial_statement_index where report_id=%s"
self.cursor.execute(sql, file_name.split(".")[0])
result = self.cursor.fetchone()
if result:
return str(result[0])
else:
sql = "select fiscal_year from financial_statement_index where report_id=%s"
self.cursor.execute(sql, file_name.split(".")[0])
result = self.cursor.fetchone()
if result:
return str(result[0])
else:
return "0000"
def ftpconnect(self, host, username, password):
"""建立连接"""
ftp = FTP()
ftp.connect(host, 21)
ftp.login(username, password)
print(ftp.getwelcome())
return ftp
def uploadfile(self, ftp, remotepath, localpath):
"""从本地上传文件到FTP"""
bufsize = 1024
fp = open(localpath, 'rb')
ftp.storbinary('STOR ' + remotepath, fp, bufsize)
ftp.set_debuglevel(0)
fp.close()
def Move2NasMain(self, LocalDir, NasDir):
ftp = self.ftpconnect("10.100.4.102", "admin", "originp123")
dir_list = os.listdir(LocalDir)
for temp in dir_list:
fiscal_year = self.get_fiscal_year(temp)
try:
ftp.mkd(NasDir + fiscal_year)
except:
pass
self.num += 1
self.uploadfile(ftp, NasDir + fiscal_year + "/" + temp, LocalDir + "/" + temp)
print("已上传%s个文件到NAS服务器" % self.num)
ftp.quit()
|
[
"[email protected]"
] | |
eb9c6c4846c223dc0bc16732c3ae5abb061b94d9
|
e84242b4e00b2afdcda6d9b68292631c3c86d9f1
|
/hangar_2019/vinogradov.py
|
bfe7181d8335edf9fb5ed44ce09f9ddd4b9a056b
|
[] |
no_license
|
Gleb-bit/astrobox-project
|
ac12b92255febafd196cf2ba717ecd4aa3771fb5
|
de6a74db001a4d4e9456d8946a741164190b32ae
|
refs/heads/main
| 2023-03-18T18:19:32.730946 | 2021-02-27T15:49:07 | 2021-03-03T16:06:31 | 346,435,875 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,016 |
py
|
from astrobox.core import Drone
ASTEROIDS_DRONES = {}
class VinogradovDrone(Drone):
def on_born(self):
if len(ASTEROIDS_DRONES) == 0:
self._fill_holder()
asteroid = self.choose_asteroid()
self.move_at(asteroid)
def on_stop_at_asteroid(self, asteroid):
if not self.mothership.is_full:
self.load_from(asteroid)
def on_load_complete(self):
asteroid = self.choose_asteroid()
if not self.is_full and asteroid is not None:
self.move_at(asteroid)
else:
self.move_at(self.my_mothership)
def on_stop_at_mothership(self, mothership):
self.unload_to(mothership)
def on_unload_complete(self):
asteroid = self.choose_asteroid()
if asteroid is not None:
self.move_at(asteroid)
def _fill_holder(self):
for asteroid in self.asteroids:
if asteroid.payload > 0:
if asteroid not in ASTEROIDS_DRONES:
ASTEROIDS_DRONES[asteroid] = []
def choose_asteroid(self):
for aster, drone in ASTEROIDS_DRONES.items():
if drone is self:
if aster.is_empty:
ASTEROIDS_DRONES.pop(aster)
asteroids_params = [asteroid for asteroid in self.asteroids if not asteroid.is_empty]
asteroids_params.sort(key=lambda ast: self.distance_to(ast)/ast.payload)
if len(asteroids_params) > 0:
for sorted_asteroid in asteroids_params:
asteroid_drones = ASTEROIDS_DRONES[sorted_asteroid]
free_space = [drone.free_space for drone in asteroid_drones if drone != self]
free_space.append(self.free_space)
free_space_sum = sum(free_space)
if sorted_asteroid.payload >= free_space_sum*.8:
ASTEROIDS_DRONES[sorted_asteroid].append(self)
return sorted_asteroid
return asteroids_params[0]
drone_class = VinogradovDrone
|
[
"[email protected]"
] | |
89cf0d50fb6e2df3124bee8b77421b3fd186c0fb
|
3940b4a507789e1fbbaffeb200149aee215f655a
|
/lc/primes.py
|
c910b9b14a132ba9a5b1670d224af1c8c2d70824
|
[] |
no_license
|
akimi-yano/algorithm-practice
|
15f52022ec79542d218c6f901a54396a62080445
|
1abc28919abb55b93d3879860ac9c1297d493d09
|
refs/heads/master
| 2023-06-11T13:17:56.971791 | 2023-06-10T05:17:56 | 2023-06-10T05:17:56 | 239,395,822 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 645 |
py
|
def setup():
primes = []
for num in range(2,100000+1):
is_prime = True
for p in primes:
if num%p == 0:
is_prime = False
break
if is_prime:
primes.append(num)
return primes
primes = setup()
def prime_factors(num):
ans = []
for prime in primes:
if num % prime == 0:
ans.append(prime)
if prime > num ** 0.5:
break
if len(ans) < 1:
return [num]
return ans
print(prime_factors(4))
print(prime_factors(6))
print(prime_factors(15))
print(prime_factors(35))
print(prime_factors(3*13*29*43*111))
|
[
"[email protected]"
] | |
d374f557f75fbfa71084b996ee9029ef19b9f982
|
fa7e0fd1013762eac8d878b70582544a5598600d
|
/django_3_2_18/users/views.py
|
748e20b3538248543b14b3b7547299dacb80c910
|
[] |
no_license
|
gy0109/django_2.18
|
b8c48005027720ab46e7e050ff139b57437ff5f6
|
0c9971fae249a4f1932b3fc20d29fc7232b244ab
|
refs/heads/master
| 2020-04-24T01:41:05.553801 | 2019-02-21T12:37:36 | 2019-02-21T12:37:36 | 171,608,336 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,666 |
py
|
import json
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
# Create your views here. 视图
# /user/index/
def index(request):
"""
index视图部分
:param request: 接收到的请求对象
:return: 响应对象
"""
return HttpResponse('hello world!')
def weather(request, city, year):
print('city=%s' % city)
print('year=%s' % year)
return HttpResponse('ok!')
def weather1(request, city, year):
print('city=%s' % city)
print('year=%s' % year)
return HttpResponse('ok! weather1! ')
def weather2(request, city, year):
print('city=%s' % city)
print('year=%s' % year)
a = request.GET.get('a')
b = request.GET.get('b')
a_list = request.GET.getlist('a')
print(a, b, a_list)
return HttpResponse('ok! weather1! ')
def get_post_params(request):
# POST请求获取表单数据
a = request.POST.get('a')
b = request.POST.get('b')
a_list = request.POST.getlist('a')
print(a, b, a_list)
return HttpResponse('get_post')
def get_body_json(request):
json_str = request.body.decode()
req_data = json.loads(json_str)
print(request.META['CONTENT_TYPE'])
print(request.META['SERVER_NAME'])
print(request.method)
print(request.user)
print(request.encoding)
print(request.path)
print(request.files)
print(req_data['a'])
print(req_data['b'])
return HttpResponse('OK get_body')
# 自定义响应体
def response_json(request):
json_dict = {'name': 'gy', 'age': 12}
# return HttpResponse('OK', content_type='text/html', status=200)
return JsonResponse(json_dict)
|
[
"[email protected]"
] | |
2a79ebc762ce1b21a171102de8c4921db995312e
|
afc8d5a9b1c2dd476ea59a7211b455732806fdfd
|
/Configurations/ggH_SF/Full2018/DNN/configuration_2018.py
|
b9aa3c9058017e04aa91fb0713b0804969ea1ced
|
[] |
no_license
|
latinos/PlotsConfigurations
|
6d88a5ad828dde4a7f45c68765081ed182fcda21
|
02417839021e2112e740607b0fb78e09b58c930f
|
refs/heads/master
| 2023-08-18T20:39:31.954943 | 2023-08-18T09:23:34 | 2023-08-18T09:23:34 | 39,819,875 | 10 | 63 | null | 2023-08-10T14:08:04 | 2015-07-28T07:36:50 |
Python
|
UTF-8
|
Python
| false | false | 917 |
py
|
# example of configuration file
treeName= 'Events'
tag = 'ggH_SF_split2'
# used by mkShape to define output directory for root files
outputDir = 'rootFile'
# file with TTree aliases
aliasesFile = 'aliases.py'
# file with list of variables
variablesFile = 'variables.py'
# file with list of cuts
cutsFile = 'cuts_all.py'
# file with list of samples
samplesFile = 'samples.py'
# file with list of samples
plotFile = 'plot.py'
# luminosity to normalize to (in 1/fb)
lumi = 35.867
# used by mkPlot to define output directory for plots
# different from "outputDir" to do things more tidy
# outputDirPlots = '~/www/plotCR'
outputDirPlots = 'plot_'+tag+'_DNN_signal'
# used by mkDatacards to define output directory for datacards
outputDirDatacard = 'datacards'
# structure file for datacard
structureFile = 'structure.py'
# nuisances file for mkDatacards and for mkShape
nuisancesFile = 'nuisances.py'
|
[
"[email protected]"
] | |
9d5a6ba6446140a91ac8195ae11cdf52026435c4
|
ec0b8bfe19b03e9c3bb13d9cfa9bd328fb9ca3f1
|
/res/packages/scripts/scripts/client/tutorial/control/quests/__init__.py
|
e0557fa51737e0fce1a443bfd0b2043093d7aa71
|
[] |
no_license
|
webiumsk/WOT-0.9.20.0
|
de3d7441c5d442f085c47a89fa58a83f1cd783f2
|
811cb4e1bca271372a1d837a268b6e0e915368bc
|
refs/heads/master
| 2021-01-20T22:11:45.505844 | 2017-08-29T20:11:38 | 2017-08-29T20:11:38 | 101,803,045 | 0 | 1 | null | null | null | null |
WINDOWS-1250
|
Python
| false | false | 3,036 |
py
|
# 2017.08.29 21:51:51 Střední Evropa (letní čas)
# Embedded file name: scripts/client/tutorial/control/quests/__init__.py
from tutorial.control.lobby.context import LobbyBonusesRequester
from tutorial.control.quests import queries
from tutorial.data.effects import EFFECT_TYPE
from tutorial.control import ControlsFactory
from tutorial.control import context as core_ctx
from tutorial.control import functional as core_func
from tutorial.control.chains import functional as chains_func
from tutorial.control.lobby import functional as lobby_func
from tutorial.control.quests import functional as quests_func
class QuestsControlsFactory(ControlsFactory):
def __init__(self):
effects = {EFFECT_TYPE.ACTIVATE: core_func.FunctionalActivateEffect,
EFFECT_TYPE.DEACTIVATE: core_func.FunctionalDeactivateEffect,
EFFECT_TYPE.GLOBAL_ACTIVATE: core_func.FunctionalGlobalActivateEffect,
EFFECT_TYPE.GLOBAL_DEACTIVATE: core_func.FunctionalGlobalDeactivateEffect,
EFFECT_TYPE.SET_GUI_ITEM_CRITERIA: core_func.FunctionalSetGuiItemCriteria,
EFFECT_TYPE.SET_ACTION: core_func.FunctionalSetAction,
EFFECT_TYPE.REMOVE_ACTION: core_func.FunctionalRemoveAction,
EFFECT_TYPE.REFUSE_TRAINING: core_func.FunctionalRefuseTrainingEffect,
EFFECT_TYPE.REQUEST_BONUS: core_func.FunctionalRequestBonusEffect,
EFFECT_TYPE.NEXT_CHAPTER: core_func.FunctionalNextChapterEffect,
EFFECT_TYPE.CLEAR_SCENE: core_func.FunctionalClearScene,
EFFECT_TYPE.GO_SCENE: core_func.GoToSceneEffect,
EFFECT_TYPE.SHOW_HINT: chains_func.FunctionalShowHint,
EFFECT_TYPE.CLOSE_HINT: chains_func.FunctionalCloseHint,
EFFECT_TYPE.SHOW_WINDOW: quests_func.ShowSharedWindowEffect,
EFFECT_TYPE.SELECT_VEHICLE_IN_HANGAR: quests_func.SelectVehicleInHangar,
EFFECT_TYPE.SAVE_TUTORIAL_SETTING: quests_func.SaveTutorialSettingEffect,
EFFECT_TYPE.SAVE_ACCOUNT_SETTING: quests_func.SaveAccountSettingEffect,
EFFECT_TYPE.RUN_TRIGGER: quests_func.QuestsFunctionalRunTriggerEffect,
EFFECT_TYPE.SHOW_UNLOCKED_CHAPTER: chains_func.FunctionalShowUnlockedChapter,
EFFECT_TYPE.SHOW_AWARD_WINDOW: chains_func.FunctionalShowAwardWindow,
EFFECT_TYPE.ENTER_QUEUE: chains_func.FunctionalSwitchToRandom}
_queries = {'awardWindow': queries.AwardWindowContentQuery}
ControlsFactory.__init__(self, effects, _queries)
def createBonuses(self, completed):
return LobbyBonusesRequester(completed)
def createSoundPlayer(self):
return core_ctx.NoSound()
def createFuncScene(self, sceneModel):
return core_func.FunctionalScene(sceneModel)
def createFuncInfo(self):
return lobby_func.FunctionalLobbyChapterInfo()
# okay decompyling c:\Users\PC\wotmods\files\originals\res\packages\scripts\scripts\client\tutorial\control\quests\__init__.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2017.08.29 21:51:51 Střední Evropa (letní čas)
|
[
"[email protected]"
] | |
cd009ea532016e6d794b44635f9cf787d176f987
|
d374478ba42d027e730e2b9d378b0a08de9c23b5
|
/4. Building your Deep Neural Network/linear_backward.py
|
a7d5789fc96744d2b4c971623e11c58a98dfa9a2
|
[] |
no_license
|
kuangzijian/Neural-Networks-and-Deep-Learning
|
8ffe46e7b99611c033f54d553a897313b36ea22b
|
781d62679497e9dfa6e6556d2b49a6366c6f945f
|
refs/heads/master
| 2023-08-08T07:32:13.280785 | 2021-05-05T16:44:49 | 2021-05-05T16:44:49 | 217,354,065 | 0 | 0 | null | 2023-07-22T19:42:15 | 2019-10-24T17:20:55 |
Python
|
UTF-8
|
Python
| false | false | 990 |
py
|
# GRADED FUNCTION: linear_backward
import numpy as np
def linear_backward(dZ, cache):
"""
Implement the linear portion of backward propagation for a single layer (layer l)
Arguments:
dZ -- Gradient of the cost with respect to the linear output (of current layer l)
cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer
Returns:
dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev
dW -- Gradient of the cost with respect to W (current layer l), same shape as W
db -- Gradient of the cost with respect to b (current layer l), same shape as b
"""
A_prev, W, b = cache
m = A_prev.shape[1]
dW = (1 / m) * dZ.dot(A_prev.T)
db = np.sum(dZ, axis=1, keepdims=True) / m
dA_prev = np.dot(W.T, dZ)
assert (dA_prev.shape == A_prev.shape)
assert (dW.shape == W.shape)
assert (db.shape == b.shape)
return dA_prev, dW, db
|
[
"[email protected]"
] | |
8aba2942340cc5f1e675229a80ce52ff0a0f4244
|
3d19e1a316de4d6d96471c64332fff7acfaf1308
|
/Users/M/martharotter/wikipediavisualiser.py
|
8077e845b760b04b80b2c4f75a79ad8f643a9261
|
[] |
no_license
|
BerilBBJ/scraperwiki-scraper-vault
|
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
|
65ea6a943cc348a9caf3782b900b36446f7e137d
|
refs/heads/master
| 2021-12-02T23:55:58.481210 | 2013-09-30T17:02:59 | 2013-09-30T17:02:59 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 998 |
py
|
import scraperwiki
scraperwiki.sqlite.attach("wikipedia_paper_scraper_until_jan_20")
data = scraperwiki.sqlite.select(
'''* from wikipedia_paper_scraper_until_jan_20.swdata
order by id desc limit 10'''
)
print "<table>"
print "<tr><th>ID</th><th>Tweet</th><th>User</th>"
for d in data:
print "<tr>"
print "<td>", d["id"], "</td>"
print "<td>", d["text"], "</td>"
print "<td>", d["from_user"], "</td>"
print "</tr>"
print "</table>"
import scraperwiki
scraperwiki.sqlite.attach("wikipedia_paper_scraper_until_jan_20")
data = scraperwiki.sqlite.select(
'''* from wikipedia_paper_scraper_until_jan_20.swdata
order by id desc limit 10'''
)
print "<table>"
print "<tr><th>ID</th><th>Tweet</th><th>User</th>"
for d in data:
print "<tr>"
print "<td>", d["id"], "</td>"
print "<td>", d["text"], "</td>"
print "<td>", d["from_user"], "</td>"
print "</tr>"
print "</table>"
|
[
"[email protected]"
] | |
c564cb8a4f8fb15ca5244ece24f0664747b45e2e
|
2dc17d12ff6ea9794177c81aa4f385e4e09a4aa5
|
/archive/513FindBottomLeftTreeValue.py
|
b9b3b6ac780a028c6dda69b1deef818d7aa4d7fd
|
[] |
no_license
|
doraemon1293/Leetcode
|
924b19f840085a80a9e8c0092d340b69aba7a764
|
48ba21799f63225c104f649c3871444a29ab978a
|
refs/heads/master
| 2022-10-01T16:20:07.588092 | 2022-09-08T02:44:56 | 2022-09-08T02:44:56 | 122,086,222 | 0 | 0 | null | null | null | null |
WINDOWS-1252
|
Python
| false | false | 1,254 |
py
|
# coding=utf-8
'''
Created on 2017�2�15�
@author: Administrator
'''
from collections import deque
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def LevelTraverseFromRoot(root):
ans = []
if root:
from collections import deque
current_level = 0
q = deque()
q.append((root, 0))
temp = []
while q:
node, level = q.popleft()
if level > current_level:
ans.append(temp)
temp = []
current_level += 1
temp.append(node.val)
if node.left:
q.append((node.left, current_level + 1))
if node.right:
q.append((node.right, current_level + 1))
ans.append(temp)
return ans
return LevelTraverseFromRoot(root)[-1][0]
|
[
"[email protected]"
] | |
e0f12a86fb901108bf9f2a170c3607667e2e6e21
|
22215eae0bf31c1021cf927155d310ba57adf0fb
|
/automaton/state_machine.py
|
913aa3461a9dcbe5fe1166eb378e5cace0ed6ba7
|
[
"MIT"
] |
permissive
|
pombredanne/automaton-5
|
37e466f26d55e3ed34c8780e63b0b9ce1cac66dc
|
3f5b6dc4521bc8ee284f732daa7883e49b3433e2
|
refs/heads/master
| 2020-12-31T03:42:52.956371 | 2013-12-28T01:02:37 | 2013-12-28T01:02:37 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 673 |
py
|
# -*- coding: utf-8 -*-
def to_state_machine(node):
state_machine = {}
nodes = set([node])
visited_nodes = set()
accepting_states = set()
while True:
start_node = nodes.pop()
for edge in node.alphabet():
end_node = start_node.derive(edge).reduce()
if end_node.accepts_lambda:
accepting_states.add(end_node)
if end_node and end_node not in visited_nodes:
visited_nodes.add(end_node)
nodes.add(end_node)
state_machine[(start_node, edge)] = end_node
if not nodes:
break
return node, state_machine, accepting_states
|
[
"[email protected]"
] | |
50e0d7ba43a2d2eddaf378c06555d32d6b5d604f
|
a28e1e659e4dd82be5e253443b0c7a808cdcee92
|
/SortAlgorithm/QuickSort.py
|
ff67210431d9014a59585e9e5f3016511d39ca00
|
[] |
no_license
|
LeBron-Jian/BasicAlgorithmPractice
|
b2af112e8f1299fe17cf456111276fce874586cb
|
51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a
|
refs/heads/master
| 2023-06-07T19:12:16.362428 | 2023-05-27T06:58:12 | 2023-05-27T06:58:12 | 217,682,743 | 13 | 14 | null | 2020-09-12T01:50:35 | 2019-10-26T08:59:04 |
Python
|
UTF-8
|
Python
| false | false | 4,569 |
py
|
# -*- coding: utf-8 -*-
'''
快速排序
让指定的元素归位,所谓归位,就是放到他应该放的位置
左边的元素比他小,右边的元素比他大,然后对每个元素归位,就完成了排序
正常情况下,快速排序的复杂度是O(nlogn)
快速排序存在一个最坏的情况,就是每次归位,都不能把列表分成两部分,
此时的复杂度就是O(n**2)
如果避免设计成这种最坏情况,可以在取第一个数的时候不要去取第一个元素
而是取一个列表中的随机数。
'''
# 归位函数
def partition(data, left, right): # 左右分别指向两端的元素
# 把左边第一个元素赋值给tmp,此时left指向空
tmp = data[left]
# 如果左右两个指针不重合,则继续
while left < right: # 左右两个指针不重合,就继续
# 当左边的元素小于右边,而且右边的元素大于tmp则不交换
while left < right and data[right] >= tmp:
right -= 1 # 右边的指标往左走一步
# 如果right指向的元素小于tmp,就放到左边目前为空的位置
data[left] = data[right]
print('left:', li)
# 如果left指向的元素小于tmp,则不交换
while left < right and data[left] <= tmp:
left += 1 # 此时left向右移动一位
# 如果left指向的元素大于tmp,就交换到右边目前为空的位置
data[right] = data[left]
print('right:', li)
# 最后把最开始拿出来的那个值,放到左右重合的那个位置上即可
data[left] = tmp
return left # 最后返回这个位置
# 写好归位函数后,就可以递归调用这个函数,实现排序
def quick_sort(data, left, right):
if left < right:
# 找到指定元素的位置
mid = partition(data, left, right)
# 对左边的元素排序
quick_sort(data, left, mid - 1)
# 对右边的元素排序
quick_sort(data, mid + 1, right)
return data
li = [5, 7, 4, 6, 3, 1, 2, 9, 8]
print('start:', li)
quick_sort(li, 0, len(li) - 1)
print('end:', li)
'''
start: [5, 7, 4, 6, 3, 1, 2, 9, 8]
left: [2, 7, 4, 6, 3, 1, 2, 9, 8]
right: [2, 7, 4, 6, 3, 1, 7, 9, 8]
left: [2, 1, 4, 6, 3, 1, 7, 9, 8]
right: [2, 1, 4, 6, 3, 6, 7, 9, 8]
left: [2, 1, 4, 3, 3, 6, 7, 9, 8]
right: [2, 1, 4, 3, 3, 6, 7, 9, 8]
left: [1, 1, 4, 3, 5, 6, 7, 9, 8]
right: [1, 1, 4, 3, 5, 6, 7, 9, 8]
left: [1, 2, 3, 3, 5, 6, 7, 9, 8]
right: [1, 2, 3, 3, 5, 6, 7, 9, 8]
left: [1, 2, 3, 4, 5, 6, 7, 9, 8]
right: [1, 2, 3, 4, 5, 6, 7, 9, 8]
left: [1, 2, 3, 4, 5, 6, 7, 9, 8]
right: [1, 2, 3, 4, 5, 6, 7, 9, 8]
left: [1, 2, 3, 4, 5, 6, 7, 8, 8]
right: [1, 2, 3, 4, 5, 6, 7, 8, 8]
end: [1, 2, 3, 4, 5, 6, 7, 8, 9]
'''
# *****************方法二**********************
def quick_sort1(array, left, right):
if left >= right:
return
low = left
high = right
key = array[low] # 第一个值
while low < high: # 只要左右未遇见
while low < high and array[high] > key: # 找到列表右边比key大的值为止
high -= 1
# 此时直接把key(array[low]) 根比他大的 array[high]进行交换
array[low] = array[high]
array[high] = key
# 这里要思考为什么是 <= 而不是 <
while low < high and array[low] <= key: # 找到key左边比key大的值
low += 1
# 找到了左边比k大的值,把array[high](此时应该换成了key)和这个比key大的array[low]进行调换
array[high] = array[low]
array[low] = key
# 最后用同样的方法对分出来的左边的小组进行同上的做法
quick_sort(array, left, low-1)
# 再使用同样的方法对分出来的右边的小组进行同上的做法
quick_sort(array, low+1, right)
# li = [5, 7, 4, 6, 3, 1, 2, 9, 8]
# print('start:', li)
# quick_sort1(li, 0, len(li) - 1)
# print('end:', li)
def quick_sort(data):
if len(data) >= 2: # 递归入口及出口
mid = data[len(data) // 2] # 选择基准数,也可以选取第一个或最后一个
left, right = [], [] # 定义基准值左右两侧的列表
data.remove(mid) # 从原始数组中移除基准值
for num in data:
if num >= mid:
right.append(num)
else:
left.append(num)
return quick_sort(left) + [mid] + quick_sort(right)
else:
return data
li = [3, 2, 4, 5, 6, 7, 1]
print(quick_sort(li))
# [1, 2, 3, 4, 5, 6, 7]
|
[
"[email protected]"
] | |
1d59a9449e1faa81ca0cc15a68fdd61b3aed9c02
|
29ad60d0f4e4207aaf0374f811c9728b16942da2
|
/Report/files/switchoff.py
|
9ebd115adc375c7740070dff463253315afc67ba
|
[] |
no_license
|
LCAV/AcousticRobot
|
c97e03bc06c59650556832794aca38cfe2d873a5
|
9f33434f64cb882897b1e0e3b8ad01642e91148a
|
refs/heads/master
| 2021-01-10T16:46:51.989150 | 2017-10-11T08:26:58 | 2017-10-11T08:26:58 | 43,871,589 | 2 | 5 | null | 2017-03-06T16:15:09 | 2015-10-08T07:58:42 |
HTML
|
UTF-8
|
Python
| false | false | 831 |
py
|
mport RPi.GPIO as GPIO
import os
import time
#set up GPIO using BCM numbering
GPIO.setmode(GPIO.BCM)
GPIO.setup(10,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
#function called on pin interrupt
def button_triggered(channel):
counter = 0
counter_on = 0
while (counter <= 6):
time.sleep(1)
counter+=1
if (GPIO.input(10)):
counter_on+=1
if (counter_on >= 3):
break
if (counter_on >= 3):
print("switchoff.py: Raspberry shutting down now")
os.system("sudo halt")
elif (counter_on < 3):
print("switchoff.py: Rapsberry is going to reboot now")
os.system("sudo reboot")
#setup pin interrupt
GPIO.add_event_detect(10,GPIO.RISING,callback=button_triggered,bouncetime=300)
#wait forever
while True:
time.sleep(0.001)
GPIO.cleanup()
|
[
"[email protected]"
] | |
51e3944307e72804a1265a356f3d0a5f606b613f
|
c49590eb7f01df37c8ec5fef00d0ffc7250fa321
|
/openapi_client/models/existing_normal_order.py
|
a13bb994a8a5c32393770f610b14317804a73b72
|
[] |
no_license
|
harshad5498/ks-orderapi-python
|
373a4b85a56ff97e2367eebd076f67f972e92f51
|
237da6fc3297c02e85f0fff1a34857aaa4c1d295
|
refs/heads/master
| 2022-12-09T19:55:21.938764 | 2020-09-03T05:22:51 | 2020-09-03T05:22:51 | 293,533,651 | 0 | 0 | null | 2020-09-07T13:19:25 | 2020-09-07T13:19:24 | null |
UTF-8
|
Python
| false | false | 7,092 |
py
|
# coding: utf-8
"""
KS Trade API's
The version of the OpenAPI document: 1.0
"""
import pprint
import re # noqa: F401
import six
from openapi_client.configuration import Configuration
class ExistingNormalOrder(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
"""
"""
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.
"""
openapi_types = {
'orderId': 'str',
'quantity': 'int',
'price': 'float',
'disclosedQuantity': 'int',
'triggerPrice': 'float'
}
attribute_map = {
'orderId': 'orderId',
'quantity': 'quantity',
'price': 'price',
'disclosedQuantity': 'disclosedQuantity',
'triggerPrice': 'triggerPrice'
}
def __init__(self, orderId=None, quantity=None, price=None, disclosedQuantity=None, triggerPrice=None, local_vars_configuration=None): # noqa: E501
"""ExistingNormalOrder - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._orderId = None
self._quantity = None
self._price = None
self._disclosedQuantity = None
self._triggerPrice = None
self.discriminator = None
self.orderId = orderId
if quantity is not None:
self.quantity = quantity
if price is not None:
self.price = price
if disclosedQuantity is not None:
self.disclosedQuantity = disclosedQuantity
if triggerPrice is not None:
self.triggerPrice = triggerPrice
@property
def orderId(self):
"""Gets the orderId of this ExistingNormalOrder. # noqa: E501
Order ID of the order to be modified # noqa: E501
:return: The orderId of this ExistingNormalOrder. # noqa: E501
:rtype: str
"""
return self._orderId
@orderId.setter
def orderId(self, orderId):
"""Sets the orderId of this ExistingNormalOrder.
Order ID of the order to be modified # noqa: E501
:param orderId: The orderId of this ExistingNormalOrder. # noqa: E501
:type orderId: str
"""
if self.local_vars_configuration.client_side_validation and orderId is None: # noqa: E501
raise ValueError("Invalid value for `orderId`, must not be `None`") # noqa: E501
self._orderId = orderId
@property
def quantity(self):
"""Gets the quantity of this ExistingNormalOrder. # noqa: E501
Order quantity - specified in same unit as quoted in market depth # noqa: E501
:return: The quantity of this ExistingNormalOrder. # noqa: E501
:rtype: int
"""
return self._quantity
@quantity.setter
def quantity(self, quantity):
"""Sets the quantity of this ExistingNormalOrder.
Order quantity - specified in same unit as quoted in market depth # noqa: E501
:param quantity: The quantity of this ExistingNormalOrder. # noqa: E501
:type quantity: int
"""
self._quantity = quantity
@property
def price(self):
"""Gets the price of this ExistingNormalOrder. # noqa: E501
Order Price, non zero positive for limit order and zero for market order # noqa: E501
:return: The price of this ExistingNormalOrder. # noqa: E501
:rtype: float
"""
return self._price
@price.setter
def price(self, price):
"""Sets the price of this ExistingNormalOrder.
Order Price, non zero positive for limit order and zero for market order # noqa: E501
:param price: The price of this ExistingNormalOrder. # noqa: E501
:type price: float
"""
self._price = price
@property
def disclosedQuantity(self):
"""Gets the disclosedQuantity of this ExistingNormalOrder. # noqa: E501
Quantity to be disclosed in order # noqa: E501
:return: The disclosedQuantity of this ExistingNormalOrder. # noqa: E501
:rtype: int
"""
return self._disclosedQuantity
@disclosedQuantity.setter
def disclosedQuantity(self, disclosedQuantity):
"""Sets the disclosedQuantity of this ExistingNormalOrder.
Quantity to be disclosed in order # noqa: E501
:param disclosedQuantity: The disclosedQuantity of this ExistingNormalOrder. # noqa: E501
:type disclosedQuantity: int
"""
self._disclosedQuantity = disclosedQuantity
@property
def triggerPrice(self):
"""Gets the triggerPrice of this ExistingNormalOrder. # noqa: E501
Trigger price, required for stoploss or supermultiple order # noqa: E501
:return: The triggerPrice of this ExistingNormalOrder. # noqa: E501
:rtype: float
"""
return self._triggerPrice
@triggerPrice.setter
def triggerPrice(self, triggerPrice):
"""Sets the triggerPrice of this ExistingNormalOrder.
Trigger price, required for stoploss or supermultiple order # noqa: E501
:param triggerPrice: The triggerPrice of this ExistingNormalOrder. # noqa: E501
:type triggerPrice: float
"""
self._triggerPrice = triggerPrice
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:
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, ExistingNormalOrder):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, ExistingNormalOrder):
return True
return self.to_dict() != other.to_dict()
|
[
"[email protected]"
] | |
ce3f3e77b734c979ff3d49bc82b04f891d0df5bd
|
4d1cca31a3aae847bd6ee2dc12eca3971b263fc4
|
/src/flua/Compiler/Output/python/PythonClass.py
|
a2ffea6ea236df51bc99c98170c3846e3c94f63c
|
[] |
no_license
|
akyoto/flua
|
4cc27202c326a6eedd088c5bb88c644905e7be64
|
e09d50e0d50fc4f4faa1b0ee482756eaef4e60ec
|
refs/heads/master
| 2021-06-06T10:55:32.795005 | 2016-12-04T00:17:20 | 2016-12-04T00:17:20 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,714 |
py
|
####################################################################
# Header
####################################################################
# Target: Python Code
# Author: Eduard Urbach
####################################################################
# License
####################################################################
# (C) 2012 Eduard Urbach
#
# This file is part of Blitzprog.
#
# Blitzprog 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.
#
# Blitzprog 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 Blitzprog. If not, see <http://www.gnu.org/licenses/>.
####################################################################
# Imports
####################################################################
from flua.Compiler.Output import *
from flua.Compiler.Output.BaseClass import *
from flua.Compiler.Output.python.PythonClassImplementation import *
####################################################################
# Classes
####################################################################
class PythonClass(BaseClass):
def __init__(self, name, node, cppFile):
super().__init__(name, node, cppFile)
def createClassImplementation(self, templateValues):
return PythonClassImplementation(self, templateValues)
|
[
"[email protected]"
] | |
080327cbd21766ac54d21ecf1f08d7336c162d80
|
cb57a9ea4622b94207d12ea90eab9dd5b13e9e29
|
/lc/python/289_game_of_life.py
|
7db24705a3c6af0951103e9edb5e780f16317398
|
[] |
no_license
|
boknowswiki/mytraning
|
b59585e1e255a7a47c2b28bf2e591aef4af2f09a
|
5e2f6ceacf5dec8260ce87e9a5f4e28e86ceba7a
|
refs/heads/master
| 2023-08-16T03:28:51.881848 | 2023-08-10T04:28:54 | 2023-08-10T04:28:54 | 124,834,433 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,563 |
py
|
#!/usr/bin/python -t
#time O(m*n) space O(1)
#0,2 are "dead", and "dead->live"
#1,3 are "live", and "live->dead"
class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: None Do not return anything, modify board in-place instead.
"""
m = len(board)
n = len(board[0])
for i in range(m):
for j in range(n):
if board[i][j] == 0 or board[i][j] == 2:
if self.nnb(board, i, j) == 3:
board[i][j] = 2
else:
if self.nnb(board, i, j) < 2 or self.nnb(board, i, j) > 3:
board[i][j] = 3
for i in range(m):
for j in range(n):
if board[i][j] == 2:
board[i][j] = 1
if board[i][j] == 3:
board[i][j] = 0
def nnb(self, board, i, j):
m,n = len(board), len(board[0])
count = 0
if i-1 >= 0 and j-1 >= 0: count += board[i-1][j-1]%2
if i-1 >= 0: count += board[i-1][j]%2
if i-1 >= 0 and j+1 < n: count += board[i-1][j+1]%2
if j-1 >= 0: count += board[i][j-1]%2
if j+1 < n: count += board[i][j+1]%2
if i+1 < m and j-1 >= 0: count += board[i+1][j-1]%2
if i+1 < m: count += board[i+1][j]%2
if i+1 < m and j+1 < n: count += board[i+1][j+1]%2
return count
|
[
"[email protected]"
] | |
b4c66f8a260da4fe83eb670aeb5e4b6544e3ef5b
|
00b6699ea1302149ab2b9fd57e115656f7a26e7d
|
/models/transformer_encoder.py
|
605c2d2f1ea94fdd68595454e41d279e6400e3ec
|
[] |
no_license
|
gauravaror/catastrophic_forgetting
|
97ac8e1c999db4f36d01ae19a0fb307f8109eb8b
|
60e53f61c45f6ce24a28bf8454c8078559bb9e6f
|
refs/heads/master
| 2021-06-30T21:07:27.448889 | 2020-10-05T09:37:36 | 2020-10-05T09:37:36 | 174,500,380 | 5 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,573 |
py
|
import math
import torch
import torch.nn as nn
from torch.nn import TransformerEncoder, TransformerEncoderLayer
from models.utils import Hardsigmoid, BernoulliST
from models.kv_memory import KeyValueMemory
# It's actually TransformerEncoder custom with PositionalEncoder but we use
# name: TransformerRepresentation to avoid confusion with TransformerEncoder Representation.
class TransformerRepresentation(nn.Module):
def __init__(self, emb_dim, nhead, nhid, nlayers, args, dropout=0.5,
use_memory=False, mem_size=None, mem_context_size=None,
inv_temp=None, use_binary=False):
super(TransformerRepresentation, self).__init__()
self.model_type = 'Transformer'
self.emb_dim = emb_dim
self.inv_temp = inv_temp
self.args = args
self.no_positional = self.args.no_positional
self.memory = KeyValueMemory(use_memory=use_memory,
emb_dim=self.emb_dim,
mem_size=mem_size,
mem_context_size=mem_context_size,
inv_temp=self.inv_temp,
use_binary=use_binary)
self.src_mask = None
self.transposed = True
self.pos_encoder = PositionalEncoding(emb_dim, dropout, transposed=self.transposed)
encoder_layers = TransformerEncoderLayer(self.memory.get_input_size(),
nhead, nhid, dropout)
self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers)
self.pooler = nn.Linear(self.emb_dim, self.emb_dim)
def _generate_square_subsequent_mask(self, sz):
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))
return mask
def add_target_pad(self):
self.memory.add_target_pad()
def get_output_dim(self):
## Transformer input size is same as output
return self.memory.get_input_size()
def forward(self, src, mask):
src = src.transpose(0,1)
if self.src_mask is None or self.src_mask.size(0) != len(src):
device = src.device
mask = self._generate_square_subsequent_mask(len(src)).to(device)
self.src_mask = mask
src = src * math.sqrt(self.emb_dim)
src = self.pos_encoder(src) if not self.no_positional else src
src_input = self.memory(src)
output = self.transformer_encoder(src_input, self.src_mask)
output = output.transpose(0,1)
return torch.mean(output, dim=1)
class PositionalEncoding(nn.Module):
def __init__(self, d_model, dropout=0.1, max_len=5000, transposed=False):
super(PositionalEncoding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
self.transposed = transposed
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)
if self.transposed:
pe = pe.transpose(0, 1)
self.register_buffer('pe', pe)
def forward(self, x):
added_pe = self.pe[:x.size(0), :, :] if self.transposed else self.pe[:, x.size(1), :]
x = x + added_pe
return self.dropout(x)
|
[
"[email protected]"
] | |
bf5ff811dd36959cbb56b862856ef8a46fcdaabe
|
a7e5aa55139641ca49d27c8b0c275c25f8cc0c54
|
/src/main/python/modules/window_statusbar/gui/bar.py
|
209b4a51917b5adec045657e13011b29c5680617
|
[] |
no_license
|
AlexWoroschilow/AOD-Reader
|
5a5fa4ea8184ea2df2301870ccd67717eab307f1
|
6e643958a4fae62128f036821030b8ea9f937d07
|
refs/heads/master
| 2022-02-24T05:48:48.549468 | 2019-09-20T23:42:03 | 2019-09-20T23:42:03 | 197,986,058 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,795 |
py
|
# -*- coding: utf-8 -*-
# Copyright 2015 Alex Woroschilow ([email protected])
#
# 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.
from PyQt5 import QtWidgets
from PyQt5 import QtCore
class StatusbarWidget(QtWidgets.QStatusBar):
def __init__(self):
super(StatusbarWidget, self).__init__()
self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
self.status = QtWidgets.QLabel()
self.status.setAlignment(QtCore.Qt.AlignCenter)
self.addWidget(self.status)
self.progress = QtWidgets.QProgressBar()
self.progress.hide()
def text(self, text):
self.status.setText(text)
def start(self, progress):
if self.status is not None:
self.status.hide()
self.removeWidget(self.status)
if self.progress is not None:
self.progress.setValue(progress)
self.addWidget(self.progress, 1)
self.progress.show()
def setProgress(self, progress):
if self.progress is not None:
self.progress.setValue(progress)
def stop(self, progress):
if self.progress is not None:
self.progress.setValue(progress)
self.progress.hide()
self.removeWidget(self.progress)
if self.status is not None:
self.addWidget(self.status, 1)
self.status.show()
|
[
"[email protected]"
] | |
5133a67b4edd0c59c4ea5de641e73dca50cb2c73
|
bf8d344b17e2ff9b7e38ad9597d5ce0e3d4da062
|
/ppdet/modeling/cls_utils.py
|
3ae8d116959a96bb2bf337dee7330c5909bc61ac
|
[
"Apache-2.0"
] |
permissive
|
PaddlePaddle/PaddleDetection
|
e7e0f40bef75a4e0b6dcbacfafa7eb1969e44961
|
bd83b98342b0a6bc8d8dcd5936233aeda1e32167
|
refs/heads/release/2.6
| 2023-08-31T07:04:15.357051 | 2023-08-18T02:24:45 | 2023-08-18T02:24:45 | 217,475,193 | 12,523 | 3,096 |
Apache-2.0
| 2023-09-10T10:05:56 | 2019-10-25T07:21:14 |
Python
|
UTF-8
|
Python
| false | false | 1,325 |
py
|
# Copyright (c) 2022 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.
def _get_class_default_kwargs(cls, *args, **kwargs):
"""
Get default arguments of a class in dict format, if args and
kwargs is specified, it will replace default arguments
"""
varnames = cls.__init__.__code__.co_varnames
argcount = cls.__init__.__code__.co_argcount
keys = varnames[:argcount]
assert keys[0] == 'self'
keys = keys[1:]
values = list(cls.__init__.__defaults__)
assert len(values) == len(keys)
if len(args) > 0:
for i, arg in enumerate(args):
values[i] = arg
default_kwargs = dict(zip(keys, values))
if len(kwargs) > 0:
for k, v in kwargs.items():
default_kwargs[k] = v
return default_kwargs
|
[
"[email protected]"
] | |
c6c6323c6e8149cfa777226d6b774aadd0f6d089
|
aa1e637de90f69f9ae742d42d5b777421617d10c
|
/nitro/resource/config/ntp/ntpparam.py
|
eeeb63f88a5a0e1502be215dfd0c498591acd78f
|
[
"Apache-2.0",
"Python-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
km0420j/nitro-python
|
db7fcb49fcad3e7a1ae0a99e4fc8675665da29ba
|
d03eb11f492a35a2a8b2a140322fbce22d25a8f7
|
refs/heads/master
| 2021-10-21T18:12:50.218465 | 2019-03-05T14:00:15 | 2019-03-05T15:35:43 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 7,294 |
py
|
#
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# 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 nitro.resource.base.base_resource import base_resource
from nitro.resource.base.base_resource import base_response
from nitro.service.options import options
from nitro.exception.nitro_exception import nitro_exception
from nitro.util.nitro_util import nitro_util
class ntpparam(base_resource) :
"""Configuration for NTP parameter resource."""
def __init__(self) :
self._authentication = ""
self._trustedkey = []
self._autokeylogsec = 0
self._revokelogsec = 0
@property
def authentication(self) :
"""Apply NTP authentication, which enables the NTP client (NetScaler) to verify that the server is in fact known and trusted.<br/>Default value: YES<br/>Possible values = YES, NO."""
try :
return self._authentication
except Exception as e:
raise e
@authentication.setter
def authentication(self, authentication) :
"""Apply NTP authentication, which enables the NTP client (NetScaler) to verify that the server is in fact known and trusted.<br/>Default value: YES<br/>Possible values = YES, NO
:param authentication:
"""
try :
self._authentication = authentication
except Exception as e:
raise e
@property
def trustedkey(self) :
"""Key identifiers that are trusted for server authentication with symmetric key cryptography in the keys file.<br/>Minimum length = 1<br/>Maximum length = 65534."""
try :
return self._trustedkey
except Exception as e:
raise e
@trustedkey.setter
def trustedkey(self, trustedkey) :
"""Key identifiers that are trusted for server authentication with symmetric key cryptography in the keys file.<br/>Minimum length = 1<br/>Maximum length = 65534
:param trustedkey:
"""
try :
self._trustedkey = trustedkey
except Exception as e:
raise e
@property
def autokeylogsec(self) :
"""Autokey protocol requires the keys to be refreshed periodically. This parameter specifies the interval between regenerations of new session keys. In seconds, expressed as a power of 2.<br/>Default value: 12<br/>Maximum length = 32."""
try :
return self._autokeylogsec
except Exception as e:
raise e
@autokeylogsec.setter
def autokeylogsec(self, autokeylogsec) :
"""Autokey protocol requires the keys to be refreshed periodically. This parameter specifies the interval between regenerations of new session keys. In seconds, expressed as a power of 2.<br/>Default value: 12<br/>Maximum length = 32
:param autokeylogsec:
"""
try :
self._autokeylogsec = autokeylogsec
except Exception as e:
raise e
@property
def revokelogsec(self) :
"""Interval between re-randomizations of the autokey seeds to prevent brute-force attacks on the autokey algorithms.<br/>Default value: 16<br/>Maximum length = 32."""
try :
return self._revokelogsec
except Exception as e:
raise e
@revokelogsec.setter
def revokelogsec(self, revokelogsec) :
"""Interval between re-randomizations of the autokey seeds to prevent brute-force attacks on the autokey algorithms.<br/>Default value: 16<br/>Maximum length = 32
:param revokelogsec:
"""
try :
self._revokelogsec = revokelogsec
except Exception as e:
raise e
def _get_nitro_response(self, service, response) :
"""converts nitro response into object and returns the object array in case of get request.
:param service:
:param response:
"""
try :
result = service.payload_formatter.string_to_resource(ntpparam_response, response, self.__class__.__name__)
if(result.errorcode != 0) :
if (result.errorcode == 444) :
service.clear_session(self)
if result.severity :
if (result.severity == "ERROR") :
raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
else :
raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
return result.ntpparam
except Exception as e :
raise e
def _get_object_name(self) :
"""Returns the value of object identifier argument"""
try :
return 0
except Exception as e :
raise e
@classmethod
def update(cls, client, resource) :
"""Use this API to update ntpparam.
:param client:
:param resource:
"""
try :
if type(resource) is not list :
updateresource = ntpparam()
updateresource.authentication = resource.authentication
updateresource.trustedkey = resource.trustedkey
updateresource.autokeylogsec = resource.autokeylogsec
updateresource.revokelogsec = resource.revokelogsec
return updateresource.update_resource(client)
except Exception as e :
raise e
@classmethod
def unset(cls, client, resource, args) :
"""Use this API to unset the properties of ntpparam resource.
Properties that need to be unset are specified in args array.
:param client:
:param resource:
:param args:
"""
try :
if type(resource) is not list :
unsetresource = ntpparam()
return unsetresource.unset_resource(client, args)
except Exception as e :
raise e
@classmethod
def get(cls, client, name="", option_="") :
"""Use this API to fetch all the ntpparam resources that are configured on netscaler.
:param client:
:param name: (Default value = "")
:param option_: (Default value = "")
"""
try :
if not name :
obj = ntpparam()
response = obj.get_resources(client, option_)
return response
except Exception as e :
raise e
class Authentication:
""" """
YES = "YES"
NO = "NO"
class ntpparam_response(base_response) :
""" """
def __init__(self, length=1) :
self.ntpparam = []
self.errorcode = 0
self.message = ""
self.severity = ""
self.sessionid = ""
self.ntpparam = [ntpparam() for _ in range(length)]
|
[
"[email protected]"
] | |
c05336076541453c1569b9d8c09221f777d63f7b
|
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
|
/2nciiXZN4HCuNEmAi_6.py
|
0bd7f17fca7fe6993cac5c0ec60e2e367d3dc816
|
[] |
no_license
|
daniel-reich/ubiquitous-fiesta
|
26e80f0082f8589e51d359ce7953117a3da7d38c
|
9af2700dbe59284f5697e612491499841a6c126f
|
refs/heads/master
| 2023-04-05T06:40:37.328213 | 2021-04-06T20:17:44 | 2021-04-06T20:17:44 | 355,318,759 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 273 |
py
|
def flatten(r, resp=None, a="main"):
if resp is None:
resp = list()
if type(r) == list:
for i in r:
resp.append(flatten(i, resp, "rec"))
else:
return r
return resp if a== "rec" else [i for i in resp if type(i)!=list]
|
[
"[email protected]"
] | |
8122cd63318c83fba3251e64209f9f3899bd2f3b
|
35942792e6dbec7862dd7bbc1aaec2b76ec0bc85
|
/ABC/C/c110.py
|
433dbf7458b7562b7e2b7332698102a7372d8afb
|
[] |
no_license
|
hokekiyoo/AtCoder
|
97f870421b513a5366681d1e05ba1e5038dfa077
|
2be1558c71a3ad8e1852645df050bca494b3afca
|
refs/heads/master
| 2020-04-27T17:51:11.337193 | 2019-10-28T11:42:47 | 2019-10-28T11:42:47 | 174,541,189 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 612 |
py
|
from collections import Counter
S = input()
T = input()
import numpy as np
S_num = dict(Counter(S)).values()
T_num = dict(Counter(T)).values()
Ss = np.array([s for s in S_num])
Ts = np.array([s for s in T_num])
if len(Ss) != len(Ts):
print("No")
else:
if all(np.sort(Ss)==np.sort(Ts)):
print("Yes")
else:
print("No")
## 別解?
"""
普通にsortedとできるっぽい。わざわざnumpy配列にしなくてOK
from collections import Counter
s, t = input(), input()
c1 = sorted(Counter(s).values())
c2 = sorted(Counter(t).values())
print('Yes') if c1 == c2 else print('No')
"""
|
[
"[email protected]"
] | |
5cbbb3255cb564286de601d5a17ec543b88b7f58
|
b2b03fe08e5b97f2a53852538c738aa60677a2af
|
/python/tests/unit/test_maasdriver_vlan.py
|
6094efea069d8060b8ca4c388d31aa163f90046c
|
[
"Apache-2.0"
] |
permissive
|
spyd3rweb/drydock
|
8685b82f340f590f75a3893244486754f77c048f
|
9d1c65dc87807b694d00564bb9fa4fdd25297dc6
|
refs/heads/master
| 2020-09-02T09:51:42.220866 | 2020-04-05T18:53:10 | 2020-04-05T18:53:10 | 219,194,440 | 0 | 0 |
Apache-2.0
| 2019-11-17T05:41:12 | 2019-11-02T18:12:00 | null |
UTF-8
|
Python
| false | false | 1,813 |
py
|
# Copyright 2018 AT&T Intellectual Property. All other 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.
'''Tests for the maasdriver node_results routine.'''
import pytest
from drydock_provisioner.drivers.node.maasdriver.models.vlan import Vlan
from drydock_provisioner.drivers.node.maasdriver.errors import RackControllerConflict
class TestMaasVlan():
def test_add_rack_controller(self, mocker):
'''Test vlan model method for setting a managing rack controller.'''
# A object to return that looks like a requests response
# object wrapping a MAAS API response
class MockedResponse():
status_code = 200
vlan_fields = {'name': 'test', 'dhcp_on': True, 'mtu': 1500}
primary_rack = "asdf79"
secondary_rack = "asdf80"
tertiary_rack = "asdf81"
api_client = mocker.MagicMock()
api_client.get.return_value = MockedResponse()
vlan_obj = Vlan(api_client, **vlan_fields)
vlan_obj.add_rack_controller(primary_rack)
assert vlan_obj.primary_rack == primary_rack
vlan_obj.add_rack_controller(secondary_rack)
assert vlan_obj.secondary_rack == secondary_rack
with pytest.raises(RackControllerConflict):
vlan_obj.add_rack_controller(tertiary_rack)
|
[
"[email protected]"
] | |
a38cb63d4933a71216ca298c2595eaceb6005c82
|
d32fd3dce3d7a3f6b3c0c47d21e9d21e78e140e1
|
/day1/ex6_math.py
|
1cf29b6d6ff36c00318ac3a5633a929a55d1a004
|
[
"Apache-2.0"
] |
permissive
|
ktbyers/pynet_ons
|
0fe77d14d5e1f119396c1f72d98eaeb56849c2ab
|
7e84060f547ee8346a6ecb2db68a89d0ddf17aa6
|
refs/heads/master
| 2021-01-17T17:30:58.832361 | 2016-10-05T23:23:02 | 2016-10-05T23:23:02 | 63,434,341 | 2 | 13 | null | 2016-08-01T19:02:47 | 2016-07-15T16:01:39 |
Python
|
UTF-8
|
Python
| false | false | 297 |
py
|
#!/usr/bin/env python
num1 = int(raw_input("Enter first number: "))
num2 = int(raw_input("Enter second number: "))
print "\n\nSum: {}".format(num1 + num2)
print "Difference: {}".format(num1 - num2)
print "Product: {}".format(num1 * num2)
print "Division: {:.2f}".format(num1/float(num2))
print
|
[
"[email protected]"
] | |
546a1923ba578b58a263e4e4a8c6151cc1b740ea
|
84b04d0787cf4cca686f54dcb4ca8eb0a480bdd5
|
/src/plonetheme/kasteeldehaar/tests/test_robot.py
|
637d955684aa80abb6b0c6a48ffd0cdc2dd7c458
|
[] |
no_license
|
plone-ve/plonetheme.kasteeldehaar
|
357c1399d2d14d1b07cbd507521af4bfd4182897
|
136e0304b935f3ffb085824ed85d7a71a71924d4
|
refs/heads/master
| 2023-08-25T15:10:11.249942 | 2016-11-04T16:58:00 | 2016-11-04T16:58:00 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 901 |
py
|
# -*- coding: utf-8 -*-
from plonetheme.kasteeldehaar.testing import plonetheme.kasteeldehaar_ACCEPTANCE_TESTING # noqa
from plone.app.testing import ROBOT_TEST_LEVEL
from plone.testing import layered
import os
import robotsuite
import unittest
def test_suite():
suite = unittest.TestSuite()
current_dir = os.path.abspath(os.path.dirname(__file__))
robot_dir = os.path.join(current_dir, 'robot')
robot_tests = [
os.path.join('robot', doc) for doc in os.listdir(robot_dir)
if doc.endswith('.robot') and doc.startswith('test_')
]
for robot_test in robot_tests:
robottestsuite = robotsuite.RobotTestSuite(robot_test)
robottestsuite.level = ROBOT_TEST_LEVEL
suite.addTests([
layered(
robottestsuite,
layer=plonetheme.kasteeldehaar_ACCEPTANCE_TESTING
),
])
return suite
|
[
"[email protected]"
] | |
9d2fa34a66d6dbc7159a496377e64a378cf8bf8a
|
ebd5c4632bb5f85c9e3311fd70f6f1bf92fae53f
|
/P.O.R.-master/pirates/npc/BossAI.py
|
20a0702863d316eba876ab90f147f6b3362cec96
|
[] |
no_license
|
BrandonAlex/Pirates-Online-Retribution
|
7f881a64ec74e595aaf62e78a39375d2d51f4d2e
|
980b7448f798e255eecfb6bd2ebb67b299b27dd7
|
refs/heads/master
| 2020-04-02T14:22:28.626453 | 2018-10-24T15:33:17 | 2018-10-24T15:33:17 | 154,521,816 | 2 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 568 |
py
|
from direct.distributed import DistributedObjectAI
class BossAI(DistributedObjectAI.DistributedObjectAI):
def ___init___(self, air):
DistributedObjectAI.DistributedObjectAI.__init__(self, air)
def announceGenerate(self):
DistributedObjectAI.DistributedObjectAI.announceGenerate(self)
def generate(self):
DistributedObjectAI.DistributedObjectAI.generate(self)
def delete(self):
DistributedObjectAI.DistributedObjectAI.delete(self)
def disable(self):
DistributedObjectAI.DistributedObjectAI.disable(self)
|
[
"[email protected]"
] | |
d64822947bd318ef999a252c8a3923e1a6f107a8
|
f654f5f07dd8109c0ee31ba89dd4804e6b288343
|
/src/programy/utils/oob/email.py
|
7ce0678ee5141d87a71f7ce51bfe85ecb32f96c5
|
[
"MIT"
] |
permissive
|
sprinteroz/program-y
|
3d1f5f28e4f3be770705d4bef15410b8b78f19da
|
454c6bde225dce7c3fb01c549d46249248caf7b5
|
refs/heads/master
| 2021-01-19T16:05:25.636700 | 2017-08-22T03:56:33 | 2017-08-22T03:56:33 | 100,986,551 | 1 | 0 | null | 2017-08-21T19:43:43 | 2017-08-21T19:43:43 | null |
UTF-8
|
Python
| false | false | 1,220 |
py
|
import logging
import xml.etree.ElementTree as ET
from programy.utils.oob.oob import OutOfBandProcessor
"""
<oob>
<email>
<to>recipient</to>
<subject>subject text</subject>
<body>body text</body>
</email>
</oob>
"""
class EmailOutOfBandProcessor(OutOfBandProcessor):
def __init__(self):
OutOfBandProcessor.__init__(self)
self._to = None
self._subject = None
self._body = None
def parse_oob_xml(self, oob: ET.Element):
for child in oob:
if child.tag == 'to':
self._to = child.text
elif child.tag == 'subject':
self._subject = child.text
elif child.tag == 'body':
self._body = child.text
else:
logging.error ("Unknown child element [%s] in email oob"%(child.tag))
if self._to is not None and \
self._subject is not None and \
self._body is not None:
return True
logging.error("Invalid email oob command")
return False
def execute_oob_command(self, bot, clientid):
logging.info("EmailOutOfBandProcessor: Emailing=%s", self._to)
return "EMAIL"
|
[
"[email protected]"
] | |
f5db9f6c7200aa09c359fa4156c99124cbaf9b9a
|
a7e09640c081cf858f30c3cc3fe2d6ffc986eb7c
|
/gui/system/migrations/0008_auto_20170906_2335.py
|
ead8a168e06533db3ffd002005ee3b25fcc68f3b
|
[] |
no_license
|
cbwest3/freenas
|
3fbeffe66c78a375843f138afd1ee306954a9c87
|
9947174014dd740145d540f03c1849a851f3b6e7
|
refs/heads/master
| 2021-04-30T13:59:53.975592 | 2018-02-12T05:25:55 | 2018-02-12T05:25:55 | 121,202,118 | 1 | 0 | null | 2018-02-12T05:01:39 | 2018-02-12T05:01:38 | null |
UTF-8
|
Python
| false | false | 869 |
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-09-06 23:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('system', '0007_auto_201708211858'),
]
operations = [
migrations.AddField(
model_name='certificate',
name='cert_san',
field=models.TextField(blank=True, help_text='Multi-domain support. Enter additional space separated domains', null=True, verbose_name='Subject Alternate Names'),
),
migrations.AddField(
model_name='certificateauthority',
name='cert_san',
field=models.TextField(blank=True, help_text='Multi-domain support. Enter additional space separated domains', null=True, verbose_name='Subject Alternate Names'),
),
]
|
[
"[email protected]"
] | |
df93f65d97755a6b38917bb204e856bbf90a7efd
|
a0947c2778742aec26b1c0600ceca17df42326cd
|
/Python/PythonInADay2/CSV-Files-Drill/37of79-119.py
|
7707852ef6e09fc8a3743fa9851f02ce0b0f3c43
|
[] |
no_license
|
JohnCDunn/Course-Work-TTA
|
5758319d4607114914ba9723328658bed8fb2024
|
8c4f60d51007dac2ac4cceb84b0f9666e143c0d7
|
refs/heads/master
| 2021-01-10T16:37:02.609879 | 2016-02-01T18:05:38 | 2016-02-01T18:05:38 | 49,983,248 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 5,560 |
py
|
import wx, db_program
class Frame(wx.Frame):
def __init__(self, title):
wx.Frame.__init__(self, None,\
title=title, size=(800,600))
panel = wx.Panel(self)
# Creating the menu bar
menuBar = wx.MenuBar()
fileMenu = wx.Menu()
exitItem = fileMenu.Append(wx.NewId(), "Exit")
menuBar.Append(fileMenu, "File")
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.exitProgram, exitItem)
self.CreateStatusBar()
# Setup Add New Character UI
# Create static box
wx.StaticBox(panel, label='Add a new character', pos=(20,40), size=(280,190))
# Text for name, gender etc
wx.StaticText(panel, label='Name:', pos=(30,70))
wx.StaticText(panel, label='Gender:', pos=(30,110))
wx.StaticText(panel, label='Age:', pos=(30,150))
wx.StaticText(panel, label='Occupation:', pos=(30,190))
# Single line text boxes
self.sName = wx.TextCtrl(panel, size=(150, -1), pos=(130,70))
self.sGen = wx.TextCtrl(panel, size=(150, -1), pos=(130,110))
self.sAge = wx.SpinCtrl(panel, value='0', pos=(130, 150), size=(70, 25))
self.sOcc = wx.TextCtrl(panel, size=(150, -1), pos=(130,190))
# Save button
save = wx.Button(panel, label="Add Character", pos=(100, 230))
save.Bind(wx.EVT_BUTTON, self.addCharacter)
# Setup the Table UI
# Setup table as listCtrl
self.listCtrl = wx.ListCtrl(panel, size=(400,400), pos=(350,40), style=wx.LC_REPORT |wx.BORDER_SUNKEN)
# Add columns to listCtrl
self.listCtrl.InsertColumn(0, "ID")
self.listCtrl.InsertColumn(1, "Name")
self.listCtrl.InsertColumn(2, "Gender")
self.listCtrl.InsertColumn(3, "Age")
self.listCtrl.InsertColumn(4, "Occupation")
# Add data to the list control
self.fillListCtrl()
# Run onSelect function when item is selected
self.listCtrl.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelect)
# Setup a delete button
deleteBtn = wx.Button(panel, label="Delete", pos=(640, 450))
# Bind delete button to onDelete function
deleteBtn.Bind(wx.EVT_BUTTON, self.onDelete)
# Setup Update Character UI
# Create static box
wx.StaticBox(panel, label='Update a character', pos=(20,340), size=(280,190))
# Text for name, gender etc
wx.StaticText(panel, label='Name:', pos=(30,370))
wx.StaticText(panel, label='Gender:', pos=(30,410))
wx.StaticText(panel, label='Age:', pos=(30,450))
wx.StaticText(panel, label='Occupation:', pos=(30,490))
# Single line text boxes
self.sNameU = wx.TextCtrl(panel, size=(150, -1), pos=(130,370))
self.sGenU = wx.TextCtrl(panel, size=(150, -1), pos=(130,410))
self.sAgeU = wx.SpinCtrl(panel, value='0', pos=(130, 450), size=(70, 25))
self.sOccU = wx.TextCtrl(panel, size=(150, -1), pos=(130,490))
# Save button
saveUpdate = wx.Button(panel, label="Update Character", pos=(100, 530))
saveUpdate.Bind(wx.EVT_BUTTON, self.updateCharacter)
def addCharacter(self, event):
name = self.sName.GetValue()
gen = self.sGen.GetValue()
age = self.sAge.GetValue()
occ = self.sOcc.GetValue()
# Checking if variables have a value
if (name == '') or (gen == '') or (age == '') or (occ == ''):
# Alert user that a variable is empty
dlg = wx.MessageDialog(None, \
'Some character details are missing. Enter values in each text box.', \
'Missing Details', wx.OK)
dlg.ShowModal()
dlg.Destroy()
return False
# Adding character to database
db_program.newCharacter(name, gen, age, occ)
print db_program.viewAll()
# Empty text boxes when finished.
self.sName.Clear()
self.sGen.Clear()
self.sOcc.Clear()
self.sAge.SetValue(0)
# Update list control
self.fillListCtrl()
def exitProgram(self, event):
self.Destroy()
def fillListCtrl(self):
# Get data from the database
self.allData = db_program.viewAll()
# Delete old data before adding new data
self.listCtrl.DeleteAllItems()
# Append data to the table
for row in self.allData:
# Loop though and append data
self.listCtrl.Append(row)
def onDelete(self, event):
# Delete the character
db_program.deleteCharacter(self.selectedId)
# Refresh the table
self.fillListCtrl()
def onSelect(self, event):
# Get the id of the selected row
self.selectedId = event.GetText()
# Get index of selected row
index = event.GetIndex()
# Get character info
charInfo = self.allData[index]
print charInfo
# Set value of update text boxes
self.sNameU.SetValue(charInfo[1])
self.sGenU.SetValue(charInfo[2])
self.sAgeU.SetValue(charInfo[3])
self.sOccU.SetValue(charInfo[4])
def updateCharacter(self, event):
pass
app = wx.App()
frame = Frame("Python GUI")
frame.Show()
app.MainLoop()
|
[
"[email protected]"
] | |
d19988ad33589d48cc57918d518294a2fd6150d7
|
c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c
|
/cases/synthetic/exp-big-490.py
|
878f7cc3ed471a6dd801ce1f464e12d880342a22
|
[] |
no_license
|
Virtlink/ccbench-chocopy
|
c3f7f6af6349aff6503196f727ef89f210a1eac8
|
c7efae43bf32696ee2b2ee781bdfe4f7730dec3f
|
refs/heads/main
| 2023-04-07T15:07:12.464038 | 2022-02-03T15:42:39 | 2022-02-03T15:42:39 | 451,969,776 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,180 |
py
|
# Compute x**y
def exp(x: int, y: int) -> int:
a: int = 0
a2: int = 0
a3: int = 0
a4: int = 0
a5: int = 0
def f(i: int) -> int:
nonlocal a
nonlocal a2
nonlocal a3
nonlocal a4
nonlocal a5
def geta() -> int:
return a
if i <= 0:
return geta()
else:
a = a * x
a2 = a * x
a3 = a * x
a4 = a * x
a5 = a * x
return f(i-1)
a = 1
a2 = 1
a3 = 1
a4 = 1
a5 = 1
return f(y)
def exp2(x: int, y: int, x2: int, y2: int) -> int:
a: int = 0
a2: int = 0
a3: int = 0
a4: int = 0
a5: int = 0
def f(i: int) -> int:
nonlocal a
nonlocal a2
nonlocal a3
nonlocal a4
nonlocal a5
def geta() -> int:
return a
if i <= 0:
return geta()
else:
a = a * x
a2 = a * x
a3 = a * x
a4 = a * x
a5 = a * x
return f(i-1)
a = 1
a2 = 1
a3 = 1
a4 = $INT
a5 = 1
return f(y)
def exp3(x: int, y: int, x2: int, y2: int, x3: int, y3: int) -> int:
a: int = 0
a2: int = 0
a3: int = 0
a4: int = 0
a5: int = 0
def f(i: int) -> int:
nonlocal a
nonlocal a2
nonlocal a3
nonlocal a4
nonlocal a5
def geta() -> int:
return a
if i <= 0:
return geta()
else:
a = a * x
a2 = a * x
a3 = a * x
a4 = a * x
a5 = a * x
return f(i-1)
a = 1
a2 = 1
a3 = 1
a4 = 1
a5 = 1
return f(y)
def exp4(x: int, y: int, x2: int, y2: int, x3: int, y3: int, x4: int, y4: int) -> int:
a: int = 0
a2: int = 0
a3: int = 0
a4: int = 0
a5: int = 0
def f(i: int) -> int:
nonlocal a
nonlocal a2
nonlocal a3
nonlocal a4
nonlocal a5
def geta() -> int:
return a
if i <= 0:
return geta()
else:
a = a * x
a2 = a * x
a3 = a * x
a4 = a * x
a5 = a * x
return f(i-1)
a = 1
a2 = 1
a3 = 1
a4 = 1
a5 = 1
return f(y)
def exp5(x: int, y: int, x2: int, y2: int, x3: int, y3: int, x4: int, y4: int, x5: int, y5: int) -> int:
a: int = 0
a2: int = 0
a3: int = 0
a4: int = 0
a5: int = 0
def f(i: int) -> int:
nonlocal a
nonlocal a2
nonlocal a3
nonlocal a4
nonlocal a5
def geta() -> int:
return a
if i <= 0:
return geta()
else:
a = a * x
a2 = a * x
a3 = a * x
a4 = a * x
a5 = a * x
return f(i-1)
a = 1
a2 = 1
a3 = 1
a4 = 1
a5 = 1
return f(y)
# Input parameter
n:int = 42
n2:int = 42
n3:int = 42
n4:int = 42
n5:int = 42
# Run [0, n]
i:int = 0
i2:int = 0
i3:int = 0
i4:int = 0
i5:int = 0
# Crunch
while i <= n:
print(exp(2, i % 31))
i = i + 1
|
[
"[email protected]"
] | |
e6a936ccc3de105e36ffef350ea2096d974dc9f0
|
760e1c14d056dd75958d367242c2a50e829ac4f0
|
/剑指offer/6_旋转数组最小的数字.py
|
795e06ad064cd143007a5bdc31ea65296446baea
|
[] |
no_license
|
lawtech0902/py_imooc_algorithm
|
8e85265b716f376ff1c53d0afd550470679224fb
|
74550d68cd3fd2cfcc92e1bf6579ac3b8f31aa75
|
refs/heads/master
| 2021-04-26T22:54:42.176596 | 2018-09-23T15:45:22 | 2018-09-23T15:45:22 | 123,894,744 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 950 |
py
|
# _*_ coding: utf-8 _*_
"""
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
__author__ = 'lawtech'
__date__ = '2018/5/9 下午9:35'
"""
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
size = len(rotateArray)
if size == 0:
return 0
low, high = 0, size - 1
while rotateArray[low] >= rotateArray[high]:
if high - low == 1:
return rotateArray[high]
mid = low + (high - low) // 2
if rotateArray[mid] >= rotateArray[low]:
low = mid
else:
high = mid
return rotateArray[low]
|
[
"[email protected]"
] | |
a82beeb3c4f4b2b11632854d1f7251427ba6389b
|
9d5c9d9373002ab4ed1b493136517e8b4ab160e5
|
/saas/backend/apps/application/migrations/0009_auto_20200902_1134.py
|
1040ea6a30228a6fcf4b7f4921d2955e0bf91fbf
|
[
"MIT"
] |
permissive
|
robert871126/bk-iam-saas
|
f8299bb632fc853ef0131d445f84c6084fc84aba
|
33c8f4ffe8697081abcfc5771b98a88c0578059f
|
refs/heads/master
| 2023-08-23T19:23:01.987394 | 2021-10-22T09:45:28 | 2021-10-22T09:45:28 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,183 |
py
|
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
# Generated by Django 2.2.14 on 2020-09-02 03:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('application', '0008_auto_20200803_1157'),
]
operations = [
migrations.AlterField(
model_name='approvalnode',
name='approver',
field=models.TextField(help_text='多个以英文逗号分隔', verbose_name='审批人'),
),
]
|
[
"[email protected]"
] | |
a315cc93eb48378a0694c0131b8d1a8bd460e157
|
432b9b1ba469ef94ffd93065d4fde5d8c89f1a6e
|
/DM3/src/data.py
|
22298997aad2e1ff16e001bfe849a1acca56c01a
|
[] |
no_license
|
NelleV/SVM
|
0ea9931e2152d6200ef094325a9f1838eed99943
|
a46cfecb7f5d4361a93d36bdf85c2cc76c72838b
|
refs/heads/master
| 2020-06-05T07:31:34.034416 | 2012-03-06T19:36:40 | 2012-03-06T19:36:40 | 3,238,738 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 392 |
py
|
import csv
import numpy as np
def libras_movement():
"""
Fetches the Libras Movement dataset
Returns
-------
X, Y
"""
dataset = csv.reader(open('data/movement_libras.data', 'r'))
X = []
Y = []
for element in dataset:
X.append(element[:-1])
Y.append(element[-1])
return np.array(X).astype('float'), np.array(Y).astype('float')
|
[
"[email protected]"
] | |
915d93ebfb350f0981dab2804861e7fe19306cc7
|
b0ede55e98d454f558e5397369f9265893deedb5
|
/SWEA/D3/4698_special_prime.py
|
7e90335df7e3a59a8beb755177ef82b1905f53a7
|
[] |
no_license
|
YeonggilGo/python_practice
|
5ff65852900c4c6769d541af16f74a27a67920ec
|
43082568b5045a8efc1d596074bdca3e66b2fed1
|
refs/heads/master
| 2023-06-22T02:09:31.906745 | 2023-06-17T01:27:22 | 2023-06-17T01:27:22 | 280,361,205 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 499 |
py
|
primes = []
numbers = [True] * 1000001
numbers[0], numbers[1] = False, False
for i in range(2, 1000001):
if numbers[i]:
primes.append(i)
for j in range(i, 1000001, i):
numbers[j] = False
T = int(input())
for tc in range(1, T + 1):
D, A, B = map(int, input().split())
ans = 0
for prime in primes:
if prime < A:
continue
elif prime > B:
break
if str(D) in str(prime):
ans += 1
print(f'#{tc} {ans}')
|
[
"[email protected]"
] | |
ba59ebba2e068546face3a92c586930dc6c334c9
|
a45c87da1d573891a6009546b58320e6e9e0a54e
|
/html_compiler/compiler.py
|
ca07b433b7198def73b4a5f7ebd278ef26c0fcb4
|
[
"MIT"
] |
permissive
|
hsuanhauliu/html-compiler
|
f805254a5b58c3b21a95882d98784f55d63547fb
|
17f2659b95153690b517f58964f9002426c08c03
|
refs/heads/master
| 2020-09-11T12:00:12.677145 | 2019-12-14T06:10:05 | 2019-12-14T06:10:05 | 222,057,278 | 2 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,204 |
py
|
"""
Compiler module.
"""
import os
from bs4 import BeautifulSoup
def compile(path):
""" Recursive function for merging components """
soup = ""
next_dir, filename = _separate_dir_and_file(path)
with cd(next_dir):
with open(filename, "r") as rfile:
soup = BeautifulSoup(rfile, 'html.parser')
component_tags = soup.findAll("div", {"class": "m_component"})
for tag in component_tags:
tag_id = tag.get("id")
component_file = tag_id + ".html"
component = compile(component_file)
soup.find(id=tag_id).replaceWith(component)
return soup
def _separate_dir_and_file(path):
""" Helper function for separating file directory and the file """
temp = path.rfind("/")
if temp == -1:
return ".", path
return path[:temp], path[temp + 1:]
class cd:
"""Context manager for changing the current working directory"""
def __init__(self, newPath):
self.newPath = os.path.expanduser(newPath)
def __enter__(self):
self.savedPath = os.getcwd()
os.chdir(self.newPath)
def __exit__(self, etype, value, traceback):
os.chdir(self.savedPath)
|
[
"[email protected]"
] | |
b8fbc89b00c608ef7d1a47c1ca35b6688318a5ea
|
2776f806297ae2f05d6c6bcbf2205ed8eb3b9db8
|
/ico/tests/contracts/test_require_customer_id.py
|
3dfa23e0d176551f9efd672c9a4c5a07982db7b1
|
[
"Apache-2.0"
] |
permissive
|
ZOLTbyZENUM/ico
|
138207db242053ded62ecc9a4f7d273209232a3f
|
26e4ae717e5f04a3f41f32f5f52f7dddedaac65d
|
refs/heads/master
| 2022-12-12T16:01:40.922647 | 2018-02-28T12:47:33 | 2018-02-28T12:47:33 | 123,442,497 | 0 | 0 |
NOASSERTION
| 2022-12-08T00:42:32 | 2018-03-01T14:02:07 |
Python
|
UTF-8
|
Python
| false | false | 2,433 |
py
|
"""Customer id tracking."""
import uuid
import pytest
from ethereum.tester import TransactionFailed
from eth_utils import to_wei
from ico.tests.utils import time_travel
from ico.state import CrowdsaleState
from sha3 import keccak_256
from rlp.utils import decode_hex
@pytest.fixture
def crowdsale(uncapped_flatprice, uncapped_flatprice_finalizer, team_multisig):
"""Set up a crowdsale with customer id require policy."""
uncapped_flatprice.transact({"from": team_multisig}).setRequireCustomerId(True)
return uncapped_flatprice
@pytest.fixture
def token(uncapped_token):
"""Token contract we are buying."""
return uncapped_token
@pytest.fixture
def customer_id(uncapped_flatprice, uncapped_flatprice_finalizer, team_multisig) -> int:
"""Generate UUID v4 customer id as a hex string."""
customer_id = int(uuid.uuid4().hex, 16) # Customer ids are 128-bit UUID v4
return customer_id
def test_only_owner_change_change_policy(crowdsale, customer):
"""Only owner change change customerId required policy."""
with pytest.raises(TransactionFailed):
crowdsale.transact({"from": customer}).setRequireCustomerId(False)
def test_participate_with_customer_id(chain, crowdsale, customer, customer_id, token):
"""Buy tokens with a proper customer id."""
time_travel(chain, crowdsale.call().startsAt() + 1)
wei_value = to_wei(1, "ether")
assert crowdsale.call().getState() == CrowdsaleState.Funding
checksumbyte = keccak_256(decode_hex(format(customer_id, 'x').zfill(32))).digest()[:1]
crowdsale.transact({"from": customer, "value": wei_value}).buyWithCustomerIdWithChecksum(customer_id, checksumbyte)
# We got credited
assert token.call().balanceOf(customer) > 0
# We have tracked the investor id
events = crowdsale.pastEvents("Invested").get()
assert len(events) == 1
e = events[0]
assert e["args"]["investor"] == customer
assert e["args"]["weiAmount"] == wei_value
assert e["args"]["customerId"] == customer_id
def test_participate_missing_customer_id(chain, crowdsale, customer, customer_id, token):
"""Cannot bypass customer id process."""
time_travel(chain, crowdsale.call().startsAt() + 1)
wei_value = to_wei(1, "ether")
assert crowdsale.call().getState() == CrowdsaleState.Funding
with pytest.raises(TransactionFailed):
crowdsale.transact({"from": customer, "value": wei_value}).buy()
|
[
"[email protected]"
] | |
fc9ba580ad9a11c6f67bcea854c79af053e832b4
|
2a5145f811c0679b35af367d25fce5914c2e0e40
|
/Algorithm/169_MajorityElement.py
|
641252ef81bfbf55f340168da7a95c33bb00a40e
|
[] |
no_license
|
lingtianwan/Leetcode
|
8f93fc3fc85db289ca8f618143af2a43711425ba
|
bf2edab87dd96afab1ff411df35d3163c1dfdc55
|
refs/heads/master
| 2021-01-12T19:16:31.918703 | 2017-02-09T01:50:53 | 2017-02-09T01:50:53 | 81,396,498 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 485 |
py
|
# Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
#
# You may assume that the array is non-empty and the majority element always exist in the array.
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in set(nums):
if nums.count(i) > len(nums) / 2:
return i
return 0
|
[
"[email protected]"
] | |
d935698ed1490a86579c7639a9248a6761ca3fde
|
0125bbe0ce453e94604ff5834fbc280fe44f3220
|
/transquest/algo/sentence_level/siamesetransquest/readers/__init__.py
|
ae4c6526b6069a91c156cfd8a0f55c7f847bb325
|
[
"Apache-2.0"
] |
permissive
|
mfomicheva/TransQuest
|
fc51bcb90e386534845841fd75a3860054e76dd7
|
4225f7195a703414ed13ce597854cc1a59703229
|
refs/heads/master
| 2023-06-12T14:52:49.066705 | 2021-05-07T10:35:21 | 2021-05-07T10:35:21 | 263,876,762 | 6 | 1 |
Apache-2.0
| 2020-05-14T09:52:07 | 2020-05-14T09:52:06 | null |
UTF-8
|
Python
| false | false | 231 |
py
|
# from .input_example import InputExample
# from .label_sentence_reader import LabelSentenceReader
# from .nli_data_reader import NLIDataReader
# from .qe_data_reader import QEDataReader
# from .triplet_reader import TripletReader
|
[
"[email protected]"
] | |
ce69a986c534d70a5aa60a0025175768ba380815
|
52b5773617a1b972a905de4d692540d26ff74926
|
/.history/clouds_20200703155257.py
|
611b20c61a4e392632a8177a3ecf3c4d6ae86dde
|
[] |
no_license
|
MaryanneNjeri/pythonModules
|
56f54bf098ae58ea069bf33f11ae94fa8eedcabc
|
f4e56b1e4dda2349267af634a46f6b9df6686020
|
refs/heads/master
| 2022-12-16T02:59:19.896129 | 2020-09-11T12:05:22 | 2020-09-11T12:05:22 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 362 |
py
|
def jumpingClouds(c):
i = 0
jumps = 0
while i < len(c)-2:
if c[i+2] == 0:
print('c------>',i,c[i])
print('here1')
jumps +=1
elif c[i+1] == 0:
print('here')
jumps +=1
i +=1
print(jumps)
jumpingClouds([0,0,1,0,0,1,0])
|
[
"[email protected]"
] | |
158c8568933800e1a190e58735a06e07f2d82e6b
|
21d21402c70d8a95d9a4b492078e3fb36e2c9af1
|
/shivi_khanuja/django/DojoNinja/apps/dojoninja/apps.py
|
d4941bb2d14a3111f7bbf5c0ed2410810df42a05
|
[] |
no_license
|
hmp36/python_aug_2017
|
df897a1b0aa161300386192d48e3fcac9eb495c8
|
8747429b91b09349e5b5469d8932593b06f645e1
|
refs/heads/master
| 2021-04-29T23:16:50.149226 | 2017-09-11T20:14:37 | 2017-09-11T20:14:37 | 121,552,666 | 1 | 0 | null | 2018-02-14T19:34:54 | 2018-02-14T19:34:54 | null |
UTF-8
|
Python
| false | false | 166 |
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class DojoninjaConfig(AppConfig):
name = 'dojoninja'
|
[
"[email protected]"
] | |
cc7e2f7e8d161493bd6b230d519996a73308c768
|
7b6377050fba4d30f00e9fb5d56dfacb22d388e1
|
/brownies/bin/lev-vis.py
|
f897e5f5de2f2be76fa12584493985dffe688620
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
LLNL/fudge
|
0a4fe8e3a68b66d58e42d1f4d209ea3f713c6370
|
6ba80855ae47cb32c37f635d065b228fadb03412
|
refs/heads/master
| 2023-08-16T21:05:31.111098 | 2023-08-01T22:09:32 | 2023-08-01T22:09:32 | 203,678,373 | 21 | 4 |
NOASSERTION
| 2023-06-28T20:51:02 | 2019-08-21T23:22:20 |
Python
|
UTF-8
|
Python
| false | false | 7,520 |
py
|
#! /usr/bin/env python
import sys
import os
import argparse
import brownies.BNL.RIPL.level_density as LD
import brownies.BNL.RIPL.level_scheme as LS
from PoPs.chemicalElements .misc import symbolFromZ as elementSymbolFromZ
import numpy as np
import matplotlib.pyplot as plt
HOME=os.environ['HOME']
DESKTOP=HOME+'/Desktop'
ATLAS=DESKTOP+"/atlas/"
RIPL=DESKTOP+"/empire.trunk/RIPL/"
# --------------------------------------------------------------------
# Command line
# --------------------------------------------------------------------
def parse_args():
parser = argparse.ArgumentParser(description="Plot ENTIRE level schemes, as determined from RIPL and the Atlas")
parser.add_argument('Z', type=int, help='Nucleus charge')
parser.add_argument('A', type=int, help="Nuclear atomic number")
parser.add_argument('-v', dest='verbose', default=False, action='store_true', help='Run verbosely')
parser.add_argument('-q', dest='verbose', action='store_false', help='Run quietly')
parser.add_argument('--RIPL', default=RIPL, help="Path to RIPL files")
parser.add_argument('--ATLAS', default=ATLAS, help="Path to atlas project")
parser.add_argument('--dEmax', type=float, default=2.0, help="Plot from Emin=0 to Emax=Esep+dEmax, dEmax in MeV")
return parser.parse_args()
# -----------------------------------------------------------------------
# Set defaults
# -----------------------------------------------------------------------
args = parse_args()
Z, A=args.Z, args.A
elem=elementSymbolFromZ[Z]
sym='%s%i'%(elem, A)
symTarget='%s%i'%(elem, A-1) # for n+target = isotope of interest
ld, D, levs=None, None, None
sys.path.append(args.ATLAS)
import atlas.io as aio
# -----------------------------------------------------------------------
# Get data
# -----------------------------------------------------------------------
# Get the level scheme for Z,A. From RIPL-3.
fname=args.RIPL+"/levels/z%s.dat"%str(Z).zfill(3)
with open(fname, mode='r') as f:
levMap=LS.readRIPLLevelScheme(f.read(), verbose=False)
levs=levMap[sym]
spinTarget = levMap[symTarget].levels[0].spin
parityTarget = levMap[symTarget].levels[0].parity
spin0=levMap[sym].levels[0].spin
parity0=levMap[sym].levels[0].parity
if args.verbose:
print('target:', symTarget, spinTarget, parityTarget)
print('compound:', sym, spin0, parity0)
print(levs.name, levs.Sn)
print(levs.levelReport())
# Get the HFB level density for Z,A. From RIPL-3.
fname=args.RIPL+"/densities/total/level-densities-hfb/z%s.tab"%str(Z).zfill(3)
with open(fname, mode='r') as f:
ld=LD.readHFBMLevelDensityTable(f.read(), Z, A, verbose=True)
# Get the mean level spacing for the resonance region for Z,A-1.
# The compound nucleus # for neutron + Z,A-1 is Z,A. From RIPL-3.
# FIXME
# Get the resonances for Z,A-1. The compound nucleus for neutron + Z,A-1 is Z,A.
# From the Atlas of Neutron Resonances, 6th edition.
try:
res = aio.read_atlas(isotope=None, element=None, Z=Z, A=A-1, ZA=None, verbose=False)
except KeyError:
res = None
if args.verbose and res is not None:
for r in res.resonance_parameters:
print('\t'.join([str(x) for x in r]))
icut = levs.lastLevelInCompleteScheme
Ecut = levs.levels[icut].energy.value
Esep = levs.Sn.value
Emin = 0.0
Emax = Esep+args.dEmax
# -----------------------------------------------------------------------
# Hi!
# -----------------------------------------------------------------------
for NAME in ["Angie", 'Nathaniel', "Mami"]:
print('hi '+NAME)
# -----------------------------------------------------------------------
# Make plot
# -----------------------------------------------------------------------
# Set up axes and title
plt.title(levs.name)
plt.xlabel("$\Pi*J$")
plt.ylabel("$E^*$ (MeV)")
# Widget to get J & Pi, a common theme
def get_J_and_Pi(__lev, useNone=True):
if __lev.spin is None:
if useNone:
J = None
else:
J = -11.33333
else:
J = float(lev.spin)
if lev.parity is None:
if useNone:
Pi = None
else:
Pi = 1.0
else:
Pi = float(str(lev.parity))
return J, Pi
# Plot discrete levels with complete information
if True:
x, y, xerr = [], [], [] # for completely know levels
for lev in levs.levels:
J, Pi=get_J_and_Pi(lev, True)
if J is None or Pi is None:
pass
else:
if lev.energy.value > Emax:
continue
y.append(lev.energy.value)
x.append(J*Pi)
xerr.append(0.25)
plt.errorbar(x=x, y=y, xerr=xerr, linewidth=0, elinewidth=2, color='k')
# Highlight ground state
if True:
plt.errorbar(x=[float(spin0)*int(parity0)], y=[0.0], xerr=[0.25], linewidth=0, elinewidth=2, color='g')
# Highlight gamma transitions
if False:
raise NotImplementedError("Highlight gamma transitions")
# Plot discrete levels missing either J or Pi
if True:
x, y, xerr = [], [], [] # for completely know levels
for lev in levs.levels:
J, Pi=get_J_and_Pi(lev, True)
if J is None or Pi is None:
J, Pi=get_J_and_Pi(lev, False)
if lev.energy.value > Emax:
continue
y.append(lev.energy.value)
x.append(J*Pi)
xerr.append(0.25)
else:
pass
plt.errorbar(x=x, y=y, xerr=xerr, linewidth=0, elinewidth=2, color='blue')
# Highlight rotational bands
if False:
raise NotImplementedError("Highlight rotational bands")
# Highlight vibrational "bands"
if False:
raise NotImplementedError('Highlight vibrational "bands"')
# Plot Ecut
if True:
plt.axhline(y=Ecut, color='black', alpha=0.25, linestyle=':')
plt.text(11, Ecut+0.1, r'$E_{cut}$')
# Plot level density contour plot
if True:
JPigrid = []
for Pi in ld.spin_dep_level_density:
for twoJ in ld.spin_dep_level_density[Pi].keys():
if twoJ > 30: continue
JPigrid.append(Pi*twoJ/2.0)
JPigrid.sort()
JPigrid = np.array(JPigrid)
Exgrid = np.arange(Emin, Emax, 0.1) # np.arange(Ecut, 5.0+Esep, 0.1)
X, Y = np.meshgrid(JPigrid, Exgrid)
vevaluate = np.vectorize(ld.evaluate)
Z = vevaluate(Y, np.abs(X), np.sign(X))
CS = plt.contour(X, Y, Z, levels=[0, 1, 5]+[int(x) for x in np.logspace(1,3,14)])
plt.clabel(CS, fontsize=9, inline=1)
# Plot Esep
if True:
plt.axhline(y=Esep, color='black', alpha=0.25)
plt.text(11, Esep+0.1, r'$E_{sep}$')
# Plot box of levels that can be excited by n+target reactions
if False:
raise NotImplementedError("Plot box of levels that can be excited by n+target reactions")
# Plot resonances with known J
if True and res is not None:
x, y, xerr, yerr = [], [], [], [] # for completely know levels
for r in res.resonance_parameters:
Er=r[0].value*1e-6
if Er < 0.0:
continue
Er += Esep
J, L = r[1].spin, r[2].spin
if J is None or L is None:
continue
Pi = pow(-1, int(L)) * int(parityTarget) # FIXME: check math!
y.append(Er)
x.append(float(J)*Pi)
# FIXME: fuzzy band from width
xerr.append(0.25)
yerr.append(0.0)
plt.errorbar(x=x, y=y, xerr=xerr, linewidth=0, elinewidth=2, color='red')
# Highlight primary gammas
if False:
raise NotImplementedError("Highlight primary gammas")
# Plot resonances with unknown J
if False:
raise NotImplementedError("Plot resonances with unknown J")
plt.show()
|
[
"[email protected]"
] | |
56c82dd9a2f16f67ef47c7062fa1ce5db1ae45cf
|
029948b3fd0e41d80d66c84d808abff4fcb24ac8
|
/test/test_path_response_result_response_egress_physical_interface.py
|
b1100af354156581698006d61033889305c3445f
|
[] |
no_license
|
yijxiang/dnac-api-client
|
842d1da9e156820942656b8f34342d52c96d3c37
|
256d016e2df8fc1b3fdad6e28f441c6005b43b07
|
refs/heads/master
| 2021-09-25T21:10:09.502447 | 2018-10-25T14:39:57 | 2018-10-25T14:39:57 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,169 |
py
|
# coding: utf-8
"""
Cisco DNA Center Platform v. 1.2.x (EFT)
REST API (EFT) # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import dnac_api_client
from dnac_api_client.models.path_response_result_response_egress_physical_interface import PathResponseResultResponseEgressPhysicalInterface # noqa: E501
from dnac_api_client.rest import ApiException
class TestPathResponseResultResponseEgressPhysicalInterface(unittest.TestCase):
"""PathResponseResultResponseEgressPhysicalInterface unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testPathResponseResultResponseEgressPhysicalInterface(self):
"""Test PathResponseResultResponseEgressPhysicalInterface"""
# FIXME: construct object with mandatory attributes with example values
# model = dnac_api_client.models.path_response_result_response_egress_physical_interface.PathResponseResultResponseEgressPhysicalInterface() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
[
"[email protected]"
] | |
d3238509ecaea8d3e0a51a8943890b4578e5a8da
|
e3d447a81c5462d2d14201f2bc6b82cdcbbca51a
|
/chapter10/c10_6_addition.py
|
af50d5e3378247cb7a726c51df05b727370cecc4
|
[] |
no_license
|
barcern/python-crash-course
|
f6026f13f75ecddc7806711d65bc53cb88e24496
|
8b55775c9f0ed49444becb35b8d529620537fa54
|
refs/heads/master
| 2023-04-19T17:28:44.342022 | 2021-02-07T23:51:06 | 2021-02-07T23:51:06 | 257,201,280 | 2 | 3 | null | 2021-05-12T17:35:56 | 2020-04-20T07:14:28 |
Python
|
UTF-8
|
Python
| false | false | 2,214 |
py
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 26 12:27:25 2020
@author: barbora
One common problem when prompting for numerical input occurs when people
provide text instead of numbers. When you try to convert the input to an int,
you'll get a ValueError. Write a program that prompts for two numbers.
Add them together and print the result. Catch the ValueError if either input
value is not a number, and print a friendly error message. Test your program
by entering two numbers and then by entering some text instead of a number.
"""
# Option 1 - while loop
# Create a while loop to allow for users to input the two values
flag = True
while flag:
message1 = "Please input the first value to add. To quit, type 'q': "
message2 = "Please input the second value to add. To quit, type 'q': "
value1 = input(message1)
# Exit conditions
if (value1 == 'q'):
print("Ending program")
break
value2 = input(message2)
if (value2 == 'q'):
print("Ending program")
break
# Convert to integer and check for a ValueError
try:
int1 = int(value1)
int2 = int(value2)
except ValueError:
print("Please input two integer values")
else:
result = int1 + int2
print(f"Final result: {result}")
# Option 2 - while loop and function
# Create a function to add two values
def addition(value1, value2):
"""Function to add two integer values, with a ValueError check."""
try:
int1 = int(value1)
int2 = int(value2)
except ValueError:
return("Please input two integer values")
else:
result = int1 + int2
return(f"Final result: {result}")
print(addition(2,3))
# While loop to obtain user input
flag = True
while flag:
message1 = "Please input the first value to add. To quit, type 'q': "
message2 = "Please input the second value to add. To quit, type 'q': "
value1 = input(message1)
# Exit conditions
if (value1 == 'q'):
print("Ending program")
break
value2 = input(message2)
if (value2 == 'q'):
print("Ending program")
break
# Call function
print(addition(value1, value2))
|
[
"[email protected]"
] | |
bdf4f576aceba31d7d274c2ec7efd61e1f4a337c
|
5d48aba44824ff9b9ae7e3616df10aad323c260e
|
/bfs/127.word_ladder.py
|
0e02bffe5c4014c13978aea31a08fd842253ceea
|
[] |
no_license
|
eric496/leetcode.py
|
37eab98a68d6d3417780230f4b5a840f6d4bd2a6
|
32a76cf4ced6ed5f89b5fc98af4695b8a81b9f17
|
refs/heads/master
| 2021-07-25T11:08:36.776720 | 2021-07-01T15:49:31 | 2021-07-01T15:49:31 | 139,770,188 | 3 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,705 |
py
|
"""
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
Example 1:
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Example 2:
Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output: 0
Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
"""
from collections import deque
import string
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
word_set = set(wordList)
q = deque([(beginWord, 1)])
visited = {beginWord}
while q:
word, step = q.popleft()
if word == endWord:
return step
for i in range(len(word)):
for c in string.ascii_lowercase:
new_word = word[:i] + c + word[i + 1 :]
if new_word in word_set and new_word not in visited:
q.append((new_word, step + 1))
visited.add(new_word)
return 0
|
[
"[email protected]"
] | |
be45bcb1e674793f5bb4889a3cdcada07a013a45
|
5b71e2952f34dd3bb20148874d952fee06d31857
|
/app/mf/crud/migrations/0100_auto_20210206_1820.py
|
41f0df779972b165576ab9f2962e9261c1ec7a13
|
[] |
no_license
|
isela1998/facebook
|
a937917cddb9ef043dd6014efc44d59d034102b1
|
a0f2f146eb602b45c951995a5cb44409426250c5
|
refs/heads/master
| 2023-07-18T02:14:50.293774 | 2021-08-28T03:26:06 | 2021-08-28T03:26:06 | 400,613,743 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 432 |
py
|
# Generated by Django 3.1.1 on 2021-02-06 22:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crud', '0099_debts_rate'),
]
operations = [
migrations.AlterField(
model_name='debts',
name='rate',
field=models.DecimalField(decimal_places=2, default=0.0, max_digits=30, verbose_name='Tasa(Bs.)'),
),
]
|
[
"[email protected]"
] | |
f22af6b6113dc3091f9553766e30977fce309d38
|
db5264994305e8c926f89cb456f33bd3a4d64f76
|
/Sklep zielarski/account/urls.py
|
8f5e4dae0dd33bbbd640d540c02340a153233e68
|
[] |
no_license
|
marcinpelszyk/Django
|
7842e20d5e8b213c4cd42c421c1db9ab7d5f01d5
|
aff2b9bd20e978a22a4a98994bf8424892d3c82f
|
refs/heads/main
| 2023-05-01T19:20:37.267010 | 2021-05-18T17:51:53 | 2021-05-18T17:51:53 | 356,532,628 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,026 |
py
|
from django.contrib.auth import views as auth_views
from django.urls import path
from django.views.generic import TemplateView
from . import views
from .forms import PwdResetConfirmForm, PwdResetForm, UserLoginForm
app_name = 'account'
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='account/login.html',
form_class=UserLoginForm), name='login'),
path('logout/', auth_views.LogoutView.as_view(next_page='/account/login/'), name='logout'),
path('register/', views.account_register, name='register'),
path('activate/<slug:uidb64>/<slug:token>)/', views.account_activate, name='activate'),
# Reset password
path('password_reset/', auth_views.PasswordResetView.as_view(template_name="account/password_reset/password_reset_form.html",
success_url='password_reset_email_confirm',
email_template_name='account/password_reset/password_reset_email.html',
form_class=PwdResetForm), name='pwdreset'),
path('password_reset_confirm/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name='account/password_reset/password_reset_confirm.html',
success_url='password_reset_complete/',
form_class=PwdResetConfirmForm), name="password_reset_confirm"),
path('password_reset/password_reset_email_confirm/',
TemplateView.as_view(template_name="account/password_reset/reset_status.html"), name='password_reset_done'),
path('password_reset_confirm/MTU/password_reset_complete/',
TemplateView.as_view(template_name="account/password_reset/reset_status.html"), name='password_reset_complete'),
# User dashboard
path('dashboard/', views.dashboard, name='dashboard'),
path('profile/edit/', views.edit_details, name='edit_details'),
path('profile/delete_user/', views.delete_user, name='delete_user'),
path('profile/delete_confirm/', TemplateView.as_view(template_name="account/dashboard/delete_confirm.html"), name='delete_confirmation'),
# Addresses
path('addresses/', views.view_address, name='addresses'),
path("add_address/", views.add_address, name="add_address"),
path("addresses/edit/<slug:id>/", views.edit_address, name="edit_address"),
path("addresses/delete/<slug:id>/", views.delete_address, name="delete_address"),
path("addresses/set_default/<slug:id>/", views.set_default, name="set_default"),
path("user_orders/", views.user_orders, name="user_orders"),
#Favorite list
path('favoritelist/', views.favoritelist, name='favoritelist'),
path('favoritelist/add_to_favoritelist/<int:id>', views.add_to_favoritelist, name='user_favorite'),
]
|
[
"[email protected]"
] | |
88850f9c8b1aef4142ac6d51fb5ce192a8482057
|
be1e8444482e40df5d02d57964f61cfbd9249f13
|
/Django-0.90/django/core/db/backends/postgresql.py
|
b1b2d9cb52d964e5d1fd6012266dabed23eedd4c
|
[
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
tungvx/deploy
|
9946d4350f5fbc5da25d45505b75384fd40e6088
|
9e1917c6c645b4ce0efe115b0da76027d4bc634c
|
refs/heads/master
| 2021-01-02T09:08:45.691746 | 2011-11-12T19:44:48 | 2011-11-12T19:44:48 | 2,763,145 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 7,276 |
py
|
"""
PostgreSQL database backend for Django.
Requires psycopg 1: http://initd.org/projects/psycopg1
"""
from django.core.db import base, typecasts
import psycopg as Database
DatabaseError = Database.DatabaseError
class DatabaseWrapper:
def __init__(self):
self.connection = None
self.queries = []
def cursor(self):
from django.conf.settings import DATABASE_USER, DATABASE_NAME, DATABASE_HOST, DATABASE_PORT, DATABASE_PASSWORD, DEBUG, TIME_ZONE
if self.connection is None:
if DATABASE_NAME == '':
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured, "You need to specify DATABASE_NAME in your Django settings file."
conn_string = "dbname=%s" % DATABASE_NAME
if DATABASE_USER:
conn_string = "user=%s %s" % (DATABASE_USER, conn_string)
if DATABASE_PASSWORD:
conn_string += " password='%s'" % DATABASE_PASSWORD
if DATABASE_HOST:
conn_string += " host=%s" % DATABASE_HOST
if DATABASE_PORT:
conn_string += " port=%s" % DATABASE_PORT
self.connection = Database.connect(conn_string)
self.connection.set_isolation_level(1) # make transactions transparent to all cursors
cursor = self.connection.cursor()
cursor.execute("SET TIME ZONE %s", [TIME_ZONE])
if DEBUG:
return base.CursorDebugWrapper(cursor, self)
return cursor
def commit(self):
return self.connection.commit()
def rollback(self):
if self.connection:
return self.connection.rollback()
def close(self):
if self.connection is not None:
self.connection.close()
self.connection = None
def quote_name(self, name):
if name.startswith('"') and name.endswith('"'):
return name # Quoting once is enough.
return '"%s"' % name
def dictfetchone(cursor):
"Returns a row from the cursor as a dict"
return cursor.dictfetchone()
def dictfetchmany(cursor, number):
"Returns a certain number of rows from a cursor as a dict"
return cursor.dictfetchmany(number)
def dictfetchall(cursor):
"Returns all rows from a cursor as a dict"
return cursor.dictfetchall()
def get_last_insert_id(cursor, table_name, pk_name):
cursor.execute("SELECT CURRVAL('%s_%s_seq')" % (table_name, pk_name))
return cursor.fetchone()[0]
def get_date_extract_sql(lookup_type, table_name):
# lookup_type is 'year', 'month', 'day'
# http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
return "EXTRACT('%s' FROM %s)" % (lookup_type, table_name)
def get_date_trunc_sql(lookup_type, field_name):
# lookup_type is 'year', 'month', 'day'
# http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
return "DATE_TRUNC('%s', %s)" % (lookup_type, field_name)
def get_limit_offset_sql(limit, offset=None):
sql = "LIMIT %s" % limit
if offset and offset != 0:
sql += " OFFSET %s" % offset
return sql
def get_random_function_sql():
return "RANDOM()"
def get_table_list(cursor):
"Returns a list of table names in the current database."
cursor.execute("""
SELECT c.relname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r', 'v', '')
AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
AND pg_catalog.pg_table_is_visible(c.oid)""")
return [row[0] for row in cursor.fetchall()]
def get_relations(cursor, table_name):
"""
Returns a dictionary of {field_index: (field_index_other_table, other_table)}
representing all relationships to the given table. Indexes are 0-based.
"""
cursor.execute("""
SELECT con.conkey, con.confkey, c2.relname
FROM pg_constraint con, pg_class c1, pg_class c2
WHERE c1.oid = con.conrelid
AND c2.oid = con.confrelid
AND c1.relname = %s
AND con.contype = 'f'""", [table_name])
relations = {}
for row in cursor.fetchall():
try:
# row[0] and row[1] are like "{2}", so strip the curly braces.
relations[int(row[0][1:-1]) - 1] = (int(row[1][1:-1]) - 1, row[2])
except ValueError:
continue
return relations
# Register these custom typecasts, because Django expects dates/times to be
# in Python's native (standard-library) datetime/time format, whereas psycopg
# use mx.DateTime by default.
try:
Database.register_type(Database.new_type((1082,), "DATE", typecasts.typecast_date))
except AttributeError:
raise Exception, "You appear to be using psycopg version 2, which isn't supported yet, because it's still in beta. Use psycopg version 1 instead: http://initd.org/projects/psycopg1"
Database.register_type(Database.new_type((1083,1266), "TIME", typecasts.typecast_time))
Database.register_type(Database.new_type((1114,1184), "TIMESTAMP", typecasts.typecast_timestamp))
Database.register_type(Database.new_type((16,), "BOOLEAN", typecasts.typecast_boolean))
OPERATOR_MAPPING = {
'exact': '=',
'iexact': 'ILIKE',
'contains': 'LIKE',
'icontains': 'ILIKE',
'ne': '!=',
'gt': '>',
'gte': '>=',
'lt': '<',
'lte': '<=',
'startswith': 'LIKE',
'endswith': 'LIKE',
'istartswith': 'ILIKE',
'iendswith': 'ILIKE',
}
# This dictionary maps Field objects to their associated PostgreSQL column
# types, as strings. Column-type strings can contain format strings; they'll
# be interpolated against the values of Field.__dict__ before being output.
# If a column type is set to None, it won't be included in the output.
DATA_TYPES = {
'AutoField': 'serial',
'BooleanField': 'boolean',
'CharField': 'varchar(%(maxlength)s)',
'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)',
'DateField': 'date',
'DateTimeField': 'timestamp with time zone',
'EmailField': 'varchar(75)',
'FileField': 'varchar(100)',
'FilePathField': 'varchar(100)',
'FloatField': 'numeric(%(max_digits)s, %(decimal_places)s)',
'ImageField': 'varchar(100)',
'IntegerField': 'integer',
'IPAddressField': 'inet',
'ManyToManyField': None,
'NullBooleanField': 'boolean',
'OneToOneField': 'integer',
'PhoneNumberField': 'varchar(20)',
'PositiveIntegerField': 'integer CHECK (%(column)s >= 0)',
'PositiveSmallIntegerField': 'smallint CHECK (%(column)s >= 0)',
'SlugField': 'varchar(50)',
'SmallIntegerField': 'smallint',
'TextField': 'text',
'TimeField': 'time',
'URLField': 'varchar(200)',
'USStateField': 'varchar(2)',
}
# Maps type codes to Django Field types.
DATA_TYPES_REVERSE = {
16: 'BooleanField',
21: 'SmallIntegerField',
23: 'IntegerField',
25: 'TextField',
869: 'IPAddressField',
1043: 'CharField',
1082: 'DateField',
1083: 'TimeField',
1114: 'DateTimeField',
1184: 'DateTimeField',
1266: 'TimeField',
1700: 'FloatField',
}
|
[
"[email protected]"
] | |
8eda4c8d2fd5781128748cfa3f14c23c06229fc3
|
10e19b5cfd59208c1b754fea38c34cc1fb14fdbe
|
/desktop/core/ext-py/Babel-0.9.6/babel/messages/tests/data/project/ignored/this_wont_normally_be_here.py
|
f26ddee1f7972ffe1050d7bb17ab8f960c38096a
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
sarvex/hue
|
780d28d032edd810d04e83f588617d1630ec2bef
|
6e75f0c4da2f3231e19c57bdedd57fb5a935670d
|
refs/heads/master
| 2023-08-15T21:39:16.171556 | 2023-05-01T08:37:43 | 2023-05-01T08:37:43 | 32,574,366 | 0 | 0 |
Apache-2.0
| 2023-09-14T16:55:28 | 2015-03-20T09:18:18 |
Python
|
UTF-8
|
Python
| false | false | 295 |
py
|
# -*- coding: utf-8 -*-
# This file won't normally be in this directory.
# It IS only for tests
from gettext import ngettext
def foo():
# Note: This will have the TRANSLATOR: tag but shouldn't
# be included on the extracted stuff
print ngettext('FooBar', 'FooBars', 1)
|
[
"[email protected]"
] | |
1621790e8faa136dc64077fdd7cd47ca87f200ae
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/85/usersdata/228/54502/submittedfiles/funcoes1.py
|
881c334b3cea4bdaa4890004b8352ae9eab83fdf
|
[] |
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 | 1,624 |
py
|
# -*- coding: utf-8 -*-
n=int(input('digite o número de elementos:'))
lista1=[]
lista2=[]
lista3=[]
for i in range(0,n,1):
elemento1=int(input('digite o elemento:'))
lista1.append(elemento1)
elemento2=int(input('digite o elemento:'))
lista2.append(elemento2)
elemento3=int(input('digite o elemento:'))
lista3.append(elemento3)
def crescente(a):
for i in range(0,len(a),1):
if a[i]<a[i+1]:
return True
else:
return False
def decrescente(a):
for i in range(0,len(a),1):
if a[i]>a[i+1]:
return True
else:
return False
def elementosiguais(a):
for i in range(0,len(a),1):
if a[i]==a[i+1]:
return True
else:
return False
if crescent(lista1):
print('S')
if crescent(lista1)==False:
print('N')
if decrescente(lista1):
print('S')
if decrescente(lista1)==False:
print('N')
if elementosiguais(lista1):
print('S')
if elementosiguais(lista1)==False:
print('N')
if crescent(lista2):
print('S')
if crescent(lista2)==False:
print('N')
if decrescente(lista2):
print('S')
if decrescente(lista2)==False:
print('N')
if elementosiguais(lista2):
print('S')
if elementosiguais(lista2)==False:
print('N')
if crescent(lista3):
print('S')
if crescent(lista3)==False:
print('N')
if decrescente(lista3):
print('S')
if decrescente(lista3)==False:
print('N')
if elementosiguais(lista3):
print('S')
if elementosiguais(lista3)==False:
print('N')
|
[
"[email protected]"
] | |
ea81a3f2769fe2186891c4edce86d5f3c483d4e5
|
940622a48cc8711a39dd7f36122bae1e25ee2fcc
|
/QuestionTime/QuestionTime/urls.py
|
a68ebcf6bfba297eff05f5c23e941b75964ca7f5
|
[] |
no_license
|
merveealpay/django-vue-question-app
|
144d1f9b49cd1f0cbd91820c2c11cc42ff95a09d
|
f12c88bdbfcac685b7098145370e13be935c8d8f
|
refs/heads/main
| 2023-02-05T12:58:28.651036 | 2020-12-27T18:05:35 | 2020-12-27T18:05:35 | 319,586,207 | 2 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,738 |
py
|
"""QuestionTime URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.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, re_path
from django_registration.backends.one_step.views import RegistrationView
#look at django-registration documentation!!!
from core.views import IndexTemplateView
from users.forms import CustomUserForm
urlpatterns = [
path('admin/', admin.site.urls),
path("accounts/register/",
RegistrationView.as_view(
form_class=CustomUserForm,
success_url="/",
), name="django_registration_register"),
path("accounts/",
include("django_registration.backends.one_step.urls")),
path("accounts/",
include("django.contrib.auth.urls")),
path("api/",
include("users.api.urls")),
path("api/",
include("questions.api.urls")),
path("api-auth/",
include("rest_framework.urls")),
path("api/rest-auth/",
include("rest_auth.urls")),
path("api/rest-auth/registration/",
include("rest_auth.registration.urls")),
re_path(r"^.*$", IndexTemplateView.as_view(), name="entry-point")
]
|
[
"[email protected]"
] | |
2317b9612a821152993d2c8d3d77909c6a5d504f
|
69266a7696f5f8be7c78fd29ef68a7619e41d28d
|
/Tools/ComputeTool.py
|
9353c424e8d6deac1c49914c31c6768d29dd1ec4
|
[] |
no_license
|
microelly2/PyFlowWWW
|
52deb54deb2db668cd21e9ce251894baaa663823
|
0b3d0009494327b2ec34af9fbca2a5fee1fef4a4
|
refs/heads/master
| 2022-04-14T02:35:08.999370 | 2020-04-11T19:48:54 | 2020-04-11T19:48:54 | 254,876,907 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,464 |
py
|
## Copyright 2015-2019 Ilgar Lunin, Pedro Cabrera, microelly
## 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 nine import str
from PyFlow.UI.Tool.Tool import ShelfTool
from PyFlow.Core.Common import Direction
import FreeCADGui
from Qt import QtGui
from Qt.QtWidgets import QFileDialog
from nodeeditor.say import *
import sys
if sys.version_info[0] !=2:
from importlib import reload
import os
RESOURCES_DIR = os.path.dirname(os.path.realpath(__file__)) + "/res/"
class ComputeTool(ShelfTool):
"""docstring for PreviewTool."""
def __init__(self):
super( ComputeTool, self).__init__()
@staticmethod
def toolTip():
return "call compute method for selected nodes"
@staticmethod
def getIcon():
return QtGui.QIcon(RESOURCES_DIR + "compute.png")
@staticmethod
def name():
return str("ComputeTool")
def do(self):
nodes=FreeCAD.PF.graphManager.get().getAllNodes()
nodes2 = sorted(nodes, key=lambda node: node.x)
say("selected Nodes ...")
for n in nodes2:
if n.getWrapper().isSelected():
say(n,n.x)
n.compute()
class DeleteTool(ShelfTool):
"""docstring for PreviewTool."""
def __init__(self):
super( DeleteTool, self).__init__()
@staticmethod
def toolTip():
return "Delete the selected nodes"
@staticmethod
def getIcon():
return QtGui.QIcon(RESOURCES_DIR + "delete.png")
@staticmethod
def name():
return str("DeleteTool")
def do(self):
nodes=FreeCAD.PF.graphManager.get().getAllNodes()
nodes2 = sorted(nodes, key=lambda node: node.x)
say("selected Nodes ...")
for n in nodes2:
if n.getWrapper().isSelected():
say(n,n.x)
n.kill()
class ToyTool(ShelfTool):
"""docstring for PreviewTool."""
def __init__(self):
super( ToyTool, self).__init__()
@staticmethod
def toolTip():
return "Toy for Developer"
@staticmethod
def getIcon():
return QtGui.QIcon(RESOURCES_DIR + "toy.png")
@staticmethod
def name():
return str("ToyTool")
def do(self):
import nodeeditor.dev
reload (nodeeditor.dev)
nodeeditor.dev.run_shelfToy(self)
class FreeCADTool(ShelfTool):
"""docstring for PreviewTool."""
def __init__(self):
super( FreeCADTool, self).__init__()
@staticmethod
def toolTip():
return "FreeCAD mainWindow"
@staticmethod
def getIcon():
return QtGui.QIcon(RESOURCES_DIR + "freecad.png")
@staticmethod
def name():
return str("FreeCADTool")
def do(self):
mw=FreeCADGui.getMainWindow()
mw.hide()
mw.show()
def toollist():
return [
ComputeTool,
DeleteTool,
FreeCADTool,
ToyTool,
]
|
[
"[email protected]"
] | |
2b63fb46758a1f007ae3ed5ce851d0c3a99bb6e0
|
f5788e1e1d8522c0d4ae3b4668faa5537680cb07
|
/mutual_sale_discount_total/__openerp__.py
|
55acff682f3f211f074ab7660a836cc839f366de
|
[] |
no_license
|
mutualSecurity/mutual-erp-residential
|
8549e179af6df1ffceadf42369d69d4dd44f07ac
|
88debefc662dd1510a1d52a877ede4673c319532
|
refs/heads/master
| 2021-11-11T13:33:37.878051 | 2021-11-02T10:14:49 | 2021-11-02T10:14:49 | 71,433,705 | 1 | 2 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,007 |
py
|
{
'name': 'Sale Discount on Total Amount',
'version': '1.0',
'category': 'sale',
'sequence': 6,
'summary': "Discount on total in Sale and invoice with Discount limit and approval",
'author': 'Cybrosys Techno Solutions',
'company': 'Cybrosys Techno Solutions',
'website': 'http://www.cybrosys.com',
'description': """
Sale Discount for Total Amount
=======================
Module to manage discount on total amount in Sale.
as an specific amount or percentage
""",
'depends': ['sale','mutual_sales', 'base', 'stock','mutual_inventory','mutual_reports','mutual_followups','mutual_project','mutual_mass_editing'],
'data': [
'views/sale_view.xml',
'views/account_invoice_view.xml',
'views/invoice_report.xml',
'views/sale_order_report.xml',
'views/sale_discount_approval_view.xml',
'views/sale_discount_approval_workflow.xml'
],
'demo': [
],
'installable': True,
'auto_install': False,
}
|
[
"[email protected]"
] | |
c52d673bdcbfae703d470556fea4604762501224
|
91f2e23782b05aa1fb273f3170c50dc4185e8dc1
|
/clif/pybind11/staging/virtual_funcs_basics_test.py
|
6238c3144d5233fd2ad32b961ceef33c93be6b74
|
[
"Apache-2.0"
] |
permissive
|
anukaal/clif
|
152fd58e575b90d626a300875aac71cdf69ec6a3
|
8ff675bf93599f4d4a4865376b441d8d0551fd54
|
refs/heads/main
| 2023-08-03T19:47:00.538660 | 2021-09-14T05:50:43 | 2021-09-30T01:00:14 | 406,238,691 | 0 | 0 |
Apache-2.0
| 2021-09-14T05:39:04 | 2021-09-14T05:39:03 | null |
UTF-8
|
Python
| false | false | 3,058 |
py
|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""Tests for clif.pybind11.staging.virtual_funcs_basics.
This file is a copy of clif/testing/python/virtual_funcs_basics_test.py.
"""
import unittest
from clif.pybind11.staging import virtual_funcs_basics
class B(virtual_funcs_basics.B):
def __init__(self):
virtual_funcs_basics.B.__init__(self)
self.c = -1
def set_c(self, v):
self.c = v
class K(virtual_funcs_basics.K):
def inc(self, n):
self.i += n
class L(virtual_funcs_basics.Q):
def __init__(self, max_len):
virtual_funcs_basics.Q.__init__(self)
self._q = []
self._max = max_len
def data(self):
return list(self._q)
def PossiblyPush(self, data):
if len(self._q) < self._max:
self._q.append(data)
return True
return False
class AbstractClassNonDefConstImpl(
virtual_funcs_basics.AbstractClassNonDefConst):
def DoSomething(self):
return self.a * self.b
class ClassNonDefConstImpl(virtual_funcs_basics.ClassNonDefConst):
def __init__(self, a, b):
super().__init__(a, b)
self.c = [1, 2, 3] # Must have a non-trivial container to enable gc.
# Remove self.invalidated after gaining (limited) access to invalidated ptr.
self.invalidated = False
def DoSomething(self):
return -1 if self.invalidated else self.a * self.b
class VirtualFuncsTest(unittest.TestCase):
def testInitConcreteClassWithVirtualMethods(self):
b = virtual_funcs_basics.B()
b.set_c(2)
self.assertEqual(b.c, 2)
c = virtual_funcs_basics.ClassNonDefConst(1, 2)
self.assertEqual(c.DoSomething(), 3)
def testBasicCall(self):
b = B()
b.set_c(2)
self.assertEqual(b.c, 2)
virtual_funcs_basics.Bset(b, 4)
self.assertEqual(b.c, 4)
def testVirtual(self):
self.assertEqual(virtual_funcs_basics.seq(K(), 2, 6), [0, 2, 4, 6])
abc_non_def_impl = AbstractClassNonDefConstImpl(4, 5)
self.assertEqual(abc_non_def_impl.DoSomething(), 20)
self.assertEqual(virtual_funcs_basics.DoSomething1(abc_non_def_impl), 20)
non_def_impl = ClassNonDefConstImpl(4, 5)
self.assertEqual(non_def_impl.DoSomething(), 20)
self.assertEqual(virtual_funcs_basics.DoSomething2(non_def_impl), 20)
def testVirtual2(self):
q = L(3)
self.assertEqual(virtual_funcs_basics.add_seq(q, 2, 6), 3)
self.assertEqual(q.data(), [0, 2, 4])
def testVirtualProperty(self):
c = virtual_funcs_basics.D()
c.pos_c = -1
self.assertEqual(c.pos_c, 1)
if __name__ == '__main__':
unittest.main()
|
[
"[email protected]"
] | |
4c1785f655e01342cbdda1667b1a388889254f6b
|
2daa3894e6d6929fd04145100d8a3be5eedbe21c
|
/tests/artificial/transf_pow3/trend_poly/cycle_7/ar_12/test_artificial_32_pow3_poly_7_12_100.py
|
7f5a2931b6b59c48d8a1216fadd94ec7826eabbc
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
Henri-Lo/pyaf
|
a1f73a0cc807873bd7b79648fe51de9cfd6c126a
|
08c968425d85dcace974d90db7f07c845a0fe914
|
refs/heads/master
| 2021-07-01T12:27:31.600232 | 2017-09-21T11:19:04 | 2017-09-21T11:19:04 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 305 |
py
|
import pyaf.Bench.TS_datasets as tsds
import pyaf.tests.artificial.process_artificial_dataset as art
dataset = tsds.generate_random_TS(N = 32 , FREQ = 'D', seed = 0, trendtype = "poly", cycle_length = 7, transform = "pow3", sigma = 0.0, exog_count = 100, ar_order = 12);
art.process_dataset(dataset);
|
[
"[email protected]"
] | |
9dc8e842d1c50ed74d1c5b4728ef47282db16f7c
|
cf43421567c1634abe1df885c6e185a180659708
|
/Extract/common.py
|
cd7e1ac1c4a6b11a70a4290fe71d6d2217580e77
|
[] |
no_license
|
fabio-gz/ETL_newspaper
|
4c5239892098840a730ecf3b58452054a50e914b
|
7458701eab76821a1fd65f0821356b1e7924bc97
|
refs/heads/master
| 2023-01-11T05:01:39.773346 | 2020-11-16T22:10:57 | 2020-11-16T22:10:57 | 292,719,167 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 234 |
py
|
# cargar yaml
import yaml
#global var
__config = None
def config():
global __config
if not __config:
with open('config.yml', mode='r') as f:
__config = yaml.safe_load(f)
return __config
|
[
"[email protected]"
] | |
3cbc9bfba6c7cc7ac49325cfc8ffaf1622d354b1
|
bdaed512916fcf96e5dc915538fe8598aeb2d3cf
|
/mcex/history/nphistory.py
|
f042a176b3e0f6b83b0c8e8c2c2c693ec6657ff1
|
[] |
no_license
|
jsalvatier/mcex
|
9657cc2e8083f4e4dd013baaaceba08f9a48754e
|
040f49bfd6eb467ef4d50d15de25033b1ba52c55
|
refs/heads/master
| 2021-06-18T19:02:07.055877 | 2017-01-22T01:10:01 | 2017-01-22T01:10:01 | 1,455,409 | 9 | 3 | null | 2012-06-21T18:07:36 | 2011-03-08T17:02:42 |
Python
|
UTF-8
|
Python
| false | false | 954 |
py
|
'''
Created on Mar 15, 2011
@author: jsalvatier
'''
import numpy as np
class NpHistory(object):
"""
encapsulates the recording of a process chain
"""
def __init__(self, max_draws):
self.max_draws = max_draws
self.samples = {}
self.nsamples = 0
def record(self, point):
"""
records the position of a chain at a certain point in time
"""
if self.nsamples < self.max_draws:
for var, value in point.iteritems():
try :
s = self.samples[var]
except:
s = np.empty((self.max_draws,) + value.shape)
self.samples[var] = s
s[self.nsamples,...] = value
self.nsamples += 1
else :
raise ValueError('out of space!')
def __getitem__(self, key):
return self.samples[key][0:self.nsamples,...]
|
[
"[email protected]"
] | |
665fa4ba03e6c225b3c0e1b947ee5d50644e1b6b
|
4b660991e5c9c93c83dccccdd3ea91531201e8a3
|
/DSA/stack/balanced_parentheses.py
|
b4f1220d5f0ec9e0f22a0eb60703bc0198df83f8
|
[
"MIT"
] |
permissive
|
RohanMiraje/DSAwithPython
|
2a1515fa5f9e5cc76b08a3e6f0ce34e451fb6f4b
|
ea4884afcac9d6cc2817a93e918c829dd10cef5d
|
refs/heads/master
| 2022-09-24T08:57:04.695470 | 2021-10-21T01:06:06 | 2021-10-21T01:06:06 | 238,381,770 | 2 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,280 |
py
|
def check_balanced_parentheses(string):
stack = list()
matches = [("(", ")"), ("{", "}"), ("[", "]")]
if len(string) % 2:
"""
base condition to early check assuming string has only parentheses
"""
return False
for char in string:
if char in ['(', '{', '[']:
stack.append(char)
elif char in [')', '}', ']']:
if len(stack) == 0:
return False
last_opening = stack.pop()
if (last_opening, char) not in matches:
return False
# prev = stack.pop()
# if char == ')':
# if prev != "(":
# return False
# elif char == "}":
# if prev != "{":
# return False
# elif char == "]":
# if prev != "[":
# return False
"""
other approach for checking matches like
matches = [("(",")"),("{","}"),("[","]")]
last_opening = stack.pop()
if (last_opening, curr_char )not in matches:
return False
"""
return len(stack) == 0
if __name__ == '__main__':
exp = "([{}])"
print(check_balanced_parentheses(exp))
|
[
"[email protected]"
] | |
14349834269be1eb71541b0b9ba7c9447bd65661
|
6f9a5717fed38b0a79c399f7e5da55c6a461de6d
|
/Baekjoon/TreeDiameter.py
|
403cdb3ebca8db3488b4692be26727c85cc6920a
|
[] |
no_license
|
Alfred-Walker/pythonps
|
d4d3b0f7fe93c138d02651e05ca5165825676a5e
|
81ef8c712c36aa83d1c53aa50886eb845378d035
|
refs/heads/master
| 2022-04-16T21:34:39.316565 | 2020-04-10T07:50:46 | 2020-04-10T07:50:46 | 254,570,527 | 1 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,267 |
py
|
# 트리의 지름이란, 트리에서 임의의 두 점 사이의 거리 중 가장 긴 것을 말한다.
# 트리의 지름을 구하는 프로그램을 작성하시오.
#
# 입력
# 트리가 입력으로 주어진다.
# 먼저 첫 번째 줄에서는 트리의 정점의 개수 V가 주어지고 (2≤V≤100,000)
# 둘째 줄부터 V개의 줄에 걸쳐 간선의 정보가 다음과 같이 주어진다.
# (정점 번호는 1부터 V까지 매겨져 있다고 생각한다)
#
# 먼저 정점 번호가 주어지고, 이어서 연결된 간선의 정보를 의미하는 정수가 두 개씩 주어지는데,
# 하나는 정점번호, 다른 하나는 그 정점까지의 거리이다.
# 예를 들어 네 번째 줄의 경우 정점 3은 정점 1과 거리가 2인 간선으로 연결되어 있고,
# 정점 4와는 거리가 3인 간선으로 연결되어 있는 것을 보여준다.
# 각 줄의 마지막에는 -1이 입력으로 주어진다. 주어지는 거리는 모두 10,000 이하의 자연수이다.
#
# 출력
# 첫째 줄에 트리의 지름을 출력한다.
import sys
sys.setrecursionlimit(10**6)
V = int(sys.stdin.readline().rstrip())
connected = [[]for _ in range(V + 1)]
visited = [False for _ in range(V + 1)]
# 입력 처리
for i in range(1, V + 1):
edges = list(map(int, sys.stdin.readline().rstrip().split()))
for j in range(1, len(edges)-1, 2):
connected[edges[0]].append((edges[j], edges[j + 1]))
# 오입력 주의: connected[i].append((edges[j], edges[j + 1]))
# v로부터 연결된 정점 중 방문하지 않은 곳들에 대하여 재귀.
# dist로 누적 거리를 체크
def dfs(v, dist):
ret = (v, dist)
visited[v] = True
for v_d in connected[v]:
if visited[v_d[0]]:
continue
next_search = dfs(v_d[0], dist + v_d[1])
if ret[1] < next_search[1]:
ret = next_search
return ret
# 첫번째 dfs: 임의의 점(1)로부터 가장 먼 곳과 거리 구함
first_dfs = dfs(1, 0)
far_v = first_dfs[0]
# 다시 dfs 하기 위해 visited 초기화
visited = [False for _ in range(V + 1)]
# 두번째 dfs: 앞서 구한 1로부터 먼 곳에서 다시 가장 먼 곳을 찾음
second_dfs = dfs(far_v, 0)
far_v = second_dfs[1]
print(far_v)
|
[
"[email protected]"
] | |
d3980370454d25fd98274030292d5c8ed674a8f7
|
4116790ee11de30eade92cabd5cddcb0978eb2c9
|
/employeerest/company/company/views.py
|
bce69d005ffe90441d1cc9375a9ca66db31e094a
|
[] |
no_license
|
Joel-hanson/djangomytutorial
|
4e8aadbccea831bb8f7e4cf0de3d35e4bfeaadc0
|
93d2925ae1a8d5f5dcec03e0c85b3ff0e492d125
|
refs/heads/master
| 2021-08-30T10:48:42.207229 | 2017-12-17T14:43:34 | 2017-12-17T14:43:34 | 108,539,027 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 267 |
py
|
from django.views.generic import TemplateView
class TestPage(TemplateView):
template_name = 'firstapp/test.html'
class ThanksPage(TemplateView):
template_name = 'firstapp/thanks.html'
class HomePage(TemplateView):
template_name = 'firstapp/index.html'
|
[
"[email protected]"
] | |
eca0f1c99ec492e8b3c6a27b02d6557f8aa3ae1b
|
84c2fa4aed9094b5ec3cc612d28980afe5d42d34
|
/leetcode/day11_24.py
|
a6e997a5b64e66b53c1eb8fab9ec554c45fcd371
|
[] |
no_license
|
cyg2695249540/generatewework
|
186831a1b5c788e9b99e90d1a08bf6a8638131ce
|
cd01b0fc4a69cc2f2ed4c109afdf8771bee3bffd
|
refs/heads/master
| 2023-01-20T17:13:13.186034 | 2020-12-01T12:05:01 | 2020-12-01T12:05:01 | 310,201,995 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 925 |
py
|
# !/usr/bin/env Python3
# -*- coding: utf-8 -*-
# @FILE : day11_24.py
# @Author : Pluto.
# @Time : 2020/11/24 16:06
"""
exp:66. 加一
给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
示例1:
输入:digits = [1,2,3]
输出:[1,2,4]
解释:输入数组表示数字 123。
示例2:
输入:digits = [4,3,2,1]
输出:[4,3,2,2]
解释:输入数组表示数字 4321。
示例 3:
输入:digits = [0]
输出:[1]
提示:
1 <= digits.length <= 100
0 <= digits[i] <= 9
"""
def plusOne():
s="".join(str(x) for x in digits)
ss=str(int(s)+1)
r=[int(x) for x in ss]
return [0]*(len(digits)-len(r))+r
if __name__ == '__main__':
digits = [0, 0, 0]
print(plusOne())
|
[
"[email protected]"
] | |
c6216e017e386c6fcba6a03eb401c29dae4b42b7
|
abfa70e1da5b4ba8e465cdc046fa36e81386744a
|
/base_ml/10.1.Iris_DecisionTree.py
|
68bd1cb46b1c29c5cf1e31ca7b17b59b9c34a20c
|
[] |
no_license
|
superman666ai/crazy_project
|
f850819ff2287e345b67500111733bafa5629d1f
|
99dcba0fe246ecaf3f556f747d44731a04231921
|
refs/heads/master
| 2020-05-15T09:32:56.523875 | 2019-05-16T00:57:23 | 2019-05-16T00:57:23 | 182,179,544 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 4,473 |
py
|
#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
def iris_type(s):
it = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2}
return it[s]
# 花萼长度、花萼宽度,花瓣长度,花瓣宽度
# iris_feature = 'sepal length', 'sepal width', 'petal length', 'petal width'
iris_feature = u'花萼长度', u'花萼宽度', u'花瓣长度', u'花瓣宽度'
if __name__ == "__main__":
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
path = '../data/8.iris.data' # 数据文件路径
data = np.loadtxt(path, dtype=float, delimiter=',', converters={4: iris_type},encoding="utf-8")
x, y = np.split(data, (4,), axis=1)
# 为了可视化,仅使用前两列特征
x = x[:, :2]
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=1)
#ss = StandardScaler()
#ss = ss.fit(x_train)
# 决策树参数估计
# min_samples_split = 10:如果该结点包含的样本数目大于10,则(有可能)对其分支
# min_samples_leaf = 10:若将某结点分支后,得到的每个子结点样本数目都大于10,则完成分支;否则,不进行分支
model = Pipeline([
('ss', StandardScaler()),
('DTC', DecisionTreeClassifier(criterion='entropy', max_depth=3))])
# clf = DecisionTreeClassifier(criterion='entropy', max_depth=3)
model = model.fit(x_train, y_train)
y_test_hat = model.predict(x_test) # 测试数据
print(model.score)
# 保存
# dot -Tpng -o 1.png 1.dot
f = open('.\\iris_tree.dot', 'w')
tree.export_graphviz(model.get_params('DTC')['DTC'], out_file=f)
# 画图
N, M = 100, 100 # 横纵各采样多少个值
x1_min, x1_max = x[:, 0].min(), x[:, 0].max() # 第0列的范围
x2_min, x2_max = x[:, 1].min(), x[:, 1].max() # 第1列的范围
t1 = np.linspace(x1_min, x1_max, N)
t2 = np.linspace(x2_min, x2_max, M)
x1, x2 = np.meshgrid(t1, t2) # 生成网格采样点
x_show = np.stack((x1.flat, x2.flat), axis=1) # 测试点
# # 无意义,只是为了凑另外两个维度
# # 打开该注释前,确保注释掉x = x[:, :2]
# x3 = np.ones(x1.size) * np.average(x[:, 2])
# x4 = np.ones(x1.size) * np.average(x[:, 3])
# x_test = np.stack((x1.flat, x2.flat, x3, x4), axis=1) # 测试点
cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
y_show_hat = model.predict(x_show) # 预测值
y_show_hat = y_show_hat.reshape(x1.shape) # 使之与输入的形状相同
plt.figure(facecolor='w')
plt.pcolormesh(x1, x2, y_show_hat, cmap=cm_light) # 预测值的显示
plt.scatter(x_test[:, 0], x_test[:, 1], c=y_test.ravel(), edgecolors='k', s=100, cmap=cm_dark, marker='o') # 测试数据
plt.scatter(x[:, 0], x[:, 1], c=y.ravel(), edgecolors='k', s=40, cmap=cm_dark) # 全部数据
plt.xlabel(iris_feature[0], fontsize=15)
plt.ylabel(iris_feature[1], fontsize=15)
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.grid(True)
plt.title(u'鸢尾花数据的决策树分类', fontsize=17)
plt.show()
# 训练集上的预测结果
y_test = y_test.reshape(-1)
# print y_test_hat
# print y_test
result = (y_test_hat == y_test) # True则预测正确,False则预测错误
acc = np.mean(result)
# print '准确度: %.2f%%' % (100 * acc)
# 过拟合:错误率
depth = np.arange(1, 15)
err_list = []
for d in depth:
clf = DecisionTreeClassifier(criterion='entropy', max_depth=d)
clf = clf.fit(x_train, y_train)
y_test_hat = clf.predict(x_test) # 测试数据
result = (y_test_hat == y_test) # True则预测正确,False则预测错误
err = 1 - np.mean(result)
err_list.append(err)
# print d, ' 准确度: %.2f%%' % (100 * err)
plt.figure(facecolor='w')
plt.plot(depth, err_list, 'ro-', lw=2)
plt.xlabel(u'决策树深度', fontsize=15)
plt.ylabel(u'错误率', fontsize=15)
plt.title(u'决策树深度与过拟合', fontsize=17)
plt.grid(True)
plt.show()
|
[
"[email protected]"
] | |
7f19e8afa6fdab3a0d7af9f55578ca1ba59afa65
|
81061f903318fceac254b60cd955c41769855857
|
/server/paiements/migrations/0003_auto__chg_field_transaction_extra_data.py
|
b059e9dea63be589ea180dbfe9a60bdc411cea7a
|
[
"BSD-2-Clause"
] |
permissive
|
agepoly/polybanking
|
1e253e9f98ba152d9c841e7a72b7ee7cb9d9ce89
|
f8f19399585293ed41abdab53609ecb8899542a2
|
refs/heads/master
| 2020-04-24T06:15:16.606580 | 2015-10-26T19:52:03 | 2015-10-26T19:52:03 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 7,133 |
py
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Transaction.extra_data'
db.alter_column(u'paiements_transaction', 'extra_data', self.gf('django.db.models.fields.TextField')(null=True))
def backwards(self, orm):
# Changing field 'Transaction.extra_data'
db.alter_column(u'paiements_transaction', 'extra_data', self.gf('django.db.models.fields.TextField')(default=''))
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'configs.config': {
'Meta': {'object_name': 'Config'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'admin_enable': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'allowed_users': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.User']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key_api': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'key_ipn': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'key_request': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'test_mode': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'url_back_err': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'url_back_ok': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'url_ipn': ('django.db.models.fields.URLField', [], {'max_length': '200'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'paiements.transaction': {
'Meta': {'object_name': 'Transaction'},
'amount': ('django.db.models.fields.IntegerField', [], {}),
'config': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['configs.Config']"}),
'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'extra_data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'internal_status': ('django.db.models.fields.CharField', [], {'default': "'cr'", 'max_length': '2'}),
'ipn_needed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_ipn_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'last_postfinance_ipn_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'last_user_back_from_postfinance_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'last_userforwarded_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'postfinance_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'postfinance_status': ('django.db.models.fields.CharField', [], {'default': "'??'", 'max_length': '2'}),
'reference': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'paiements.transctionlog': {
'Meta': {'object_name': 'TransctionLog'},
'extra_data': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'log_type': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'transaction': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['paiements.Transaction']"}),
'when': ('django.db.models.fields.DateTimeField', [], {})
}
}
complete_apps = ['paiements']
|
[
"[email protected]"
] | |
1cb69e60aa615509cf524ab1fb086168647ae432
|
7dc80048f72e106f977b49ea882c63cc9623e3ef
|
/notebooks/other/Y2017M07D28_RH_python27setup_v01.py
|
250e214bbfc2fd21afe44797cb7e69bbeb700a16
|
[] |
no_license
|
YanCheng-go/Aqueduct30Docker
|
8400fdea23bfd788f9c6de71901e6f61530bde38
|
6606fa03d145338d48101fc53ab4a5fccf3ebab2
|
refs/heads/master
| 2022-12-16T03:36:25.704103 | 2020-09-09T14:38:28 | 2020-09-09T14:38:28 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 742 |
py
|
# coding: utf-8
# # Test Python 27 setup
#
# * Purpose of script: test python 27 environement against several libraries
# * Author: Rutger Hofste
# * Kernel used: python27
# * Date created: 20170728
#
#
# In[3]:
packages = {"earth engine":-1,"gdal":-1,"geopandas":-1,"arcgis":-1}
# In[6]:
try:
import ee
packages["earth engine"]=1
except:
packages["earth engine"]=0
# In[4]:
try:
from osgeo import gdal
packages["gdal"]=1
except:
packages["gdal"]=0
# In[10]:
try:
import geopandas
packages["geopandas"]=1
except:
packages["geopandas"]=0
# In[11]:
try:
import arcgis.gis
packages["arcgis"]=1
except:
packages["arcgis"]=0
# In[12]:
print(packages)
# In[ ]:
|
[
"[email protected]"
] | |
6aa6cad3f09fd39c8de6b26302daf10e485cedb5
|
27ece9ab880a0bdba4b2c053eccda94602c716d5
|
/.history/save_20181129231105.py
|
50671059975cdfa4cf895b943b529349ae4d201e
|
[] |
no_license
|
Symfomany/keras
|
85e3ad0530837c00f63e14cee044b6a7d85c37b2
|
6cdb6e93dee86014346515a2017652c615bf9804
|
refs/heads/master
| 2020-04-08T20:21:35.991753 | 2018-11-30T08:23:36 | 2018-11-30T08:23:36 | 159,695,807 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,777 |
py
|
import os, argparse
import tensorflow as tf
# The original freeze_graph function
# from tensorflow.python.tools.freeze_graph import freeze_graph
dir = os.path.dirname(os.path.realpath(__file__))
def freeze_graph(model_dir, output_node_names):
"""Extract the sub graph defined by the output nodes and convert
all its variables into constant
Args:
model_dir: the root folder containing the checkpoint state file
output_node_names: a string, containing all the output node's names,
comma separated
"""
if not tf.gfile.Exists(model_dir):
raise AssertionError(
"Export directory doesn't exists. Please specify an export "
"directory: %s" % model_dir)
if not output_node_names:
print("You need to supply the name of a node to --output_node_names.")
return -1
# We retrieve our checkpoint fullpath
checkpoint = tf.train.get_checkpoint_state(model_dir)
input_checkpoint = checkpoint.model_checkpoint_path
# We precise the file fullname of our freezed graph
absolute_model_dir = "/".join(input_checkpoint.split('/')[:-1])
output_graph = absolute_model_dir + "/frozen_model.pb"
# We clear devices to allow TensorFlow to control on which device it will load operations
clear_devices = True
# We start a session using a temporary fresh Graph
with tf.Session(graph=tf.Graph()) as sess:
# We import the meta graph in the current default Graph
saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices)
# We restore the weights
saver.restore(sess, input_checkpoint)
# We use a built-in TF helper to export variables to constants
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess, # The session is used to retrieve the weights
tf.get_default_graph().as_graph_def(), # The graph_def is used to retrieve the nodes
output_node_names.split(",") # The output node names are used to select the usefull nodes
)
# Finally we serialize and dump the output graph to the filesystem
with tf.gfile.GFile(output_graph, "wb") as f:
f.write(output_graph_def.SerializeToString())
print("%d ops in the final graph." % len(output_graph_def.node))
return output_graph_def
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--model_dir", type=str, default="models", help="Model folder to export")
parser.add_argument("--output_node_names", type=str, default="", help="The name of the output nodes, comma separated.")
args = parser.parse_args()
freeze_graph(args.model_dir, args.output_node_names)
|
[
"[email protected]"
] | |
ff90cd1f1161c0d09ab2942b7f313e655ef548a0
|
a6bd898302ffebe9066595b264f9e5e38e6fa8e6
|
/settings_template.py
|
069b2d192200ef4343a3508486203a989c2cb909
|
[] |
no_license
|
symroe/teamprime_retweets
|
65e8ec57095b138be45496eb115fb4da1d1e1af0
|
08e817da6191a8058b3606b076ba9de6bd253b12
|
refs/heads/master
| 2021-01-10T22:04:16.968867 | 2013-09-20T13:32:03 | 2013-09-20T13:32:03 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 136 |
py
|
CONSUMER_KEY = ""
CONSUMER_SECRET = ""
ACCESS_TOKEN_KEY = ""
ACCESS_TOKEN_SECRET = ""
username = "TeamPrimeLtd"
TWEET_PATH = "tweets"
|
[
"[email protected]"
] | |
a083a001d9f5a9559169c82b7ac70022a8d131c7
|
c534fba89ff0462334cc724ff4010cbed829e294
|
/web/myadmin/migrations/0012_auto_20191019_1638.py
|
8bbaa46d7e85d15be38f10c54609829eb800d7f6
|
[] |
no_license
|
victorfengming/python_bookshop
|
974f5f8ff3b53b024b573f0f256409204116e114
|
c0a4757fc2031a015d4b198ba889be69a2a4a3c5
|
refs/heads/master
| 2020-09-02T18:02:07.547345 | 2019-11-04T15:10:44 | 2019-11-04T15:10:44 | 219,275,403 | 1 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 366 |
py
|
# Generated by Django 2.2.3 on 2019-10-19 16:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('myadmin', '0011_auto_20191018_2225'),
]
operations = [
migrations.DeleteModel(
name='Booktype',
),
migrations.DeleteModel(
name='Users',
),
]
|
[
"[email protected]"
] | |
6cd666cf9ad2d4f9fbbfd2c624ff106e65444172
|
7c70f3cbaecfa4d77928c784ae12f232c273112e
|
/api_client/test_helper.py
|
92caf6ea0aa0d2d82ca5d95fe1af6896fce47376
|
[
"MIT"
] |
permissive
|
uktrade/lite-tests-common
|
d029298d9144a447404d38899ab35ff8e54bf53d
|
8ae386e55f899d0ffd61cc0a9156cd4db340d6d1
|
refs/heads/master
| 2020-08-03T19:20:39.673522 | 2020-07-21T09:59:01 | 2020-07-21T09:59:01 | 211,858,651 | 1 | 0 |
MIT
| 2020-07-21T09:59:03 | 2019-09-30T12:49:33 |
Python
|
UTF-8
|
Python
| false | false | 2,474 |
py
|
from .sub_helpers.documents import Documents
from .sub_helpers.applications import Applications
from .sub_helpers.cases import Cases
from .sub_helpers.document_templates import DocumentTemplates
from .sub_helpers.ecju_queries import EcjuQueries
from .sub_helpers.flags import Flags
from .sub_helpers.goods import Goods
from .sub_helpers.goods_queries import GoodsQueries
from .sub_helpers.organisations import Organisations
from .sub_helpers.ogel import Ogel
from .sub_helpers.parties import Parties
from .sub_helpers.picklists import Picklists
from .sub_helpers.queues import Queues
from .sub_helpers.users import Users
class TestHelper:
"""
Contains a collection of test helper classes, grouped by functional area, with each class containing
required logic wrapping calls to various LITE API endpoints.
"""
def __init__(self, api):
self.api_client = api
self.context = self.api_client.context
request_data = self.api_client.request_data
self.documents = Documents(api_client=self.api_client, request_data=request_data)
self.users = Users(api_client=self.api_client, request_data=request_data)
self.organisations = Organisations(api_client=self.api_client, request_data=request_data)
self.goods = Goods(api_client=self.api_client, documents=self.documents, request_data=request_data)
self.goods_queries = GoodsQueries(api_client=self.api_client, request_data=request_data)
self.parties = Parties(api_client=self.api_client, documents=self.documents, request_data=request_data)
self.ecju_queries = EcjuQueries(api_client=self.api_client, request_data=request_data)
self.picklists = Picklists(api_client=self.api_client, request_data=request_data)
self.ogel = Ogel(api_client=self.api_client, request_data=request_data)
self.cases = Cases(api_client=self.api_client, request_data=request_data)
self.flags = Flags(api_client=self.api_client, request_data=request_data)
self.queues = Queues(api_client=self.api_client, request_data=request_data)
self.document_templates = DocumentTemplates(api_client=self.api_client, request_data=request_data)
self.applications = Applications(
parties=self.parties,
goods=self.goods,
api_client=self.api_client,
documents=self.documents,
request_data=request_data,
organisations=self.organisations,
)
|
[
"[email protected]"
] | |
5aa68c22244a5396ea453095dedc1d96aba4aa72
|
d9b53673b899a9b842a42060740b734bf0c63a31
|
/leetcode/python/easy/p645_findErrorNums.py
|
0b9b378910292d7af736c77ca60c91c415bce9a7
|
[
"Apache-2.0"
] |
permissive
|
kefirzhang/algorithms
|
a8d656774b576295625dd663154d264cd6a6a802
|
549e68731d4c05002e35f0499d4f7744f5c63979
|
refs/heads/master
| 2021-06-13T13:05:40.851704 | 2021-04-02T07:37:59 | 2021-04-02T07:37:59 | 173,903,408 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 397 |
py
|
class Solution:
def findErrorNums(self, nums):
helper = [0] * len(nums)
for i in nums:
helper[i - 1] += 1
for i, n in enumerate(helper):
print(i, n)
if n == 0:
lack = i + 1
elif n == 2:
more = i + 1
return [more, lack]
slu = Solution()
print(slu.findErrorNums([1, 2, 2, 4]))
|
[
"[email protected]"
] | |
c571164d09a9dfe8ee2571e96a5c3e2bb982d580
|
44064ed79f173ddca96174913910c1610992b7cb
|
/Second_Processing_app/temboo/Library/Google/Drive/Revisions/Delete.py
|
21b2277599036d6311d9fc5895330b8646d5bce5
|
[] |
no_license
|
dattasaurabh82/Final_thesis
|
440fb5e29ebc28dd64fe59ecd87f01494ed6d4e5
|
8edaea62f5987db026adfffb6b52b59b119f6375
|
refs/heads/master
| 2021-01-20T22:25:48.999100 | 2014-10-14T18:58:00 | 2014-10-14T18:58:00 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,974 |
py
|
# -*- coding: utf-8 -*-
###############################################################################
#
# Delete
# Removes a revision.
#
# Python version 2.6
#
###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class Delete(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the Delete Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
Choreography.__init__(self, temboo_session, '/Library/Google/Drive/Revisions/Delete')
def new_input_set(self):
return DeleteInputSet()
def _make_result_set(self, result, path):
return DeleteResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return DeleteChoreographyExecution(session, exec_id, path)
class DeleteInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the Delete
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_AccessToken(self, value):
"""
Set the value of the AccessToken input for this Choreo. ((optional, string) A valid access token retrieved during the OAuth2 process. This is required unless you provide the ClientID, ClientSecret, and RefreshToken to generate a new access token.)
"""
InputSet._set_input(self, 'AccessToken', value)
def set_ClientID(self, value):
"""
Set the value of the ClientID input for this Choreo. ((conditional, string) The Client ID provided by Google. Required unless providing a valid AccessToken.)
"""
InputSet._set_input(self, 'ClientID', value)
def set_ClientSecret(self, value):
"""
Set the value of the ClientSecret input for this Choreo. ((conditional, string) The Client Secret provided by Google. Required unless providing a valid AccessToken.)
"""
InputSet._set_input(self, 'ClientSecret', value)
def set_FileID(self, value):
"""
Set the value of the FileID input for this Choreo. ((required, string) The ID of the file.)
"""
InputSet._set_input(self, 'FileID', value)
def set_RefreshToken(self, value):
"""
Set the value of the RefreshToken input for this Choreo. ((conditional, string) An OAuth refresh token used to generate a new access token when the original token is expired. Required unless providing a valid AccessToken.)
"""
InputSet._set_input(self, 'RefreshToken', value)
def set_RevisionID(self, value):
"""
Set the value of the RevisionID input for this Choreo. ((required, string) The ID of the revision.)
"""
InputSet._set_input(self, 'RevisionID', value)
class DeleteResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the Delete Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Google.)
"""
return self._output.get('Response', None)
def get_NewAccessToken(self):
"""
Retrieve the value for the "NewAccessToken" output from this Choreo execution. ((string) Contains a new AccessToken when the RefreshToken is provided.)
"""
return self._output.get('NewAccessToken', None)
class DeleteChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return DeleteResultSet(response, path)
|
[
"[email protected]"
] | |
36d6fbac09d283afec24203a8c80c252d0e04c93
|
d7016f69993570a1c55974582cda899ff70907ec
|
/sdk/recoveryservices/azure-mgmt-recoveryservicesbackup/azure/mgmt/recoveryservicesbackup/activestamp/aio/operations/_backup_protection_containers_operations.py
|
977185266eeefe7c362fb3931a8a7fd029b3b0e0
|
[
"MIT",
"LicenseRef-scancode-generic-cla",
"LGPL-2.1-or-later"
] |
permissive
|
kurtzeborn/azure-sdk-for-python
|
51ca636ad26ca51bc0c9e6865332781787e6f882
|
b23e71b289c71f179b9cf9b8c75b1922833a542a
|
refs/heads/main
| 2023-03-21T14:19:50.299852 | 2023-02-15T13:30:47 | 2023-02-15T13:30:47 | 157,927,277 | 0 | 0 |
MIT
| 2022-07-19T08:05:23 | 2018-11-16T22:15:30 |
Python
|
UTF-8
|
Python
| false | false | 6,974 |
py
|
# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import sys
from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._backup_protection_containers_operations import build_list_request
from .._vendor import RecoveryServicesBackupClientMixinABC
if sys.version_info >= (3, 8):
from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
else:
from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class BackupProtectionContainersOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.recoveryservicesbackup.activestamp.aio.RecoveryServicesBackupClient`'s
:attr:`backup_protection_containers` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list(
self, vault_name: str, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any
) -> AsyncIterable["_models.ProtectionContainerResource"]:
"""Lists the containers registered to Recovery Services Vault.
:param vault_name: The name of the recovery services vault. Required.
:type vault_name: str
:param resource_group_name: The name of the resource group where the recovery services vault is
present. Required.
:type resource_group_name: str
:param filter: OData filter options. Default value is None.
:type filter: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ProtectionContainerResource or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.recoveryservicesbackup.activestamp.models.ProtectionContainerResource]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: Literal["2023-01-01"] = kwargs.pop(
"api_version", _params.pop("api-version", self._config.api_version)
)
cls: ClsType[_models.ProtectionContainerResourceList] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_request(
vault_name=vault_name,
resource_group_name=resource_group_name,
subscription_id=self._config.subscription_id,
filter=filter,
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("ProtectionContainerResourceList", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupProtectionContainers"
}
|
[
"[email protected]"
] | |
4077ee7230fdd5fcb8bf27ad4eec1e47ecf60567
|
3d19e1a316de4d6d96471c64332fff7acfaf1308
|
/Users/J/JasonSanford/great_american_beer_festival.py
|
ccc57650e41049eee111fa8bbfab0a4bd1f01ccf
|
[] |
no_license
|
BerilBBJ/scraperwiki-scraper-vault
|
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
|
65ea6a943cc348a9caf3782b900b36446f7e137d
|
refs/heads/master
| 2021-12-02T23:55:58.481210 | 2013-09-30T17:02:59 | 2013-09-30T17:02:59 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,020 |
py
|
import scraperwiki
import lxml.html
html = scraperwiki.scrape("http://www.greatamericanbeerfestival.com/at-the-festival/breweries-at-the-2012-festival")
root = lxml.html.fromstring(html)
i = 1
for tr in root.cssselect("#brewery_table tbody tr"):
tds = tr.cssselect("td")
data = {
'id' : i,
'name' : tds[0].text_content(),
'city' : tds[1].text_content(),
'state' : tds[2].text_content(),
}
scraperwiki.sqlite.save(unique_keys=['id'], data=data)
i += 1import scraperwiki
import lxml.html
html = scraperwiki.scrape("http://www.greatamericanbeerfestival.com/at-the-festival/breweries-at-the-2012-festival")
root = lxml.html.fromstring(html)
i = 1
for tr in root.cssselect("#brewery_table tbody tr"):
tds = tr.cssselect("td")
data = {
'id' : i,
'name' : tds[0].text_content(),
'city' : tds[1].text_content(),
'state' : tds[2].text_content(),
}
scraperwiki.sqlite.save(unique_keys=['id'], data=data)
i += 1
|
[
"[email protected]"
] | |
4dc75a5c5ad9b9adc0eee92205b2a3ec96120685
|
1a220abd21c56728aa3368534506bfc9ced8ad46
|
/프로그래머스/lv0/120862. 최댓값 만들기 (2)/최댓값 만들기 (2).py
|
2150e823f28bad1d9f1692f23f12517ff6e88e54
|
[] |
no_license
|
JeonJe/Algorithm
|
0ff0cbf47900e7877be077e1ffeee0c1cd50639a
|
6f8da6dbeef350f71b7c297502a37f87eb7d0823
|
refs/heads/main
| 2023-08-23T11:08:17.781953 | 2023-08-23T08:31:41 | 2023-08-23T08:31:41 | 197,085,186 | 0 | 0 | null | 2023-02-21T03:26:41 | 2019-07-15T23:22:55 |
Python
|
UTF-8
|
Python
| false | false | 630 |
py
|
def solution(numbers):
answer = 0
negative = []
positive = []
for i in numbers:
if i < 0:
negative.append(i)
else:
positive.append(i)
negative.sort()
positive.sort()
max_positive, max_negative, mix = -1e9, -1e9, -1e9
if len(positive) == 1 and len(negative) == 1:
mix = positive[-1] * negative[0]
if len(positive) >= 2:
max_positive = positive[-1] * positive[-2]
if len(negative) >= 2:
max_negative = negative[0] * negative[1]
answer = max(max_positive, max_negative, mix)
return answer
|
[
"[email protected]"
] | |
b1dc61b9b0266ed2642cd5bf9517f09540601de5
|
7abb3d309a011a36247e0b4dcda3759537c45b2c
|
/utils/vb-meta-to-json-topology.py
|
031f8c9a3763b172b8281d83709ffc18311a4b0b
|
[
"BSD-3-Clause"
] |
permissive
|
TomPlano/varbench
|
7937a8a7221117e2d817549eb8ba22746c324869
|
83933380e1876da388dd07a78e554e65f388861b
|
refs/heads/master
| 2020-04-02T14:34:11.376400 | 2018-10-27T19:10:09 | 2018-10-27T19:10:09 | 154,529,766 | 0 | 0 |
BSD-3-Clause
| 2018-10-24T16:01:55 | 2018-10-24T16:01:54 | null |
UTF-8
|
Python
| false | false | 2,486 |
py
|
#!/usr/bin/env python
import os
import sys
import getopt
import json
def usage(argv, exit=None):
print "Usage: %s [OPTIONS] <VB metadata file> <VB JSON topology file (output)>" % argv[0]
print " -h (--help) : print help and exit"
print " -v (--vbs-path=) : path to VB Stats python module"
if exit is not None:
sys.exit(exit)
def parse_cmd_line(argc, argv):
opts = []
args = []
cur_path = os.path.dirname(os.path.realpath(__file__))
vb_path = cur_path + "/../vb-stats/"
try:
opts, args = getopt.getopt(
argv[1:],
"hv:",
["help", "vb-path="]
)
except getopt.GetoptError, err:
print >> sys.stderr, err
usage(argv, exit=1)
for o, a in opts:
if o in ("-h", "--help"):
usage(argv, exit=0)
elif o in ("-v", "--vb-path"):
vb_path = a
else:
usage(argv, exit=1)
if len(args) != 2:
usage(argv, exit=1)
return vb_path, args[0], args[1]
def main(argc, argv, envp):
vb_path, meta, json_file = parse_cmd_line(argc, argv)
procs = []
# Try to import vb-path
try:
sys.path.insert(0, vb_path)
from vb_stats import VB_Stats as vbs
except ImportError:
print >> sys.stderr, "Could not import VB_Stats. Please specify path to VB_Stats with '--vbs-path'"
usage(argv, exit=2)
with vbs(meta, load_data=False) as vb:
with open(json_file, "w") as f:
num_processors = vb.num_sockets_per_node * vb.num_cores_per_socket * vb.num_hw_threads_per_core
json.dump({
"processor_info" : {
"num_processors" : num_processors,
"num_sockets" : vb.num_sockets_per_node,
"cores_per_socket" : vb.num_cores_per_socket,
"hw_threads_per_core" : vb.num_hw_threads_per_core
},
# The format of p: [socket, core, hw_thread, os_core]
"processor_list" : [
{
"os_core" : p[3],
"socket" : p[0],
"core" : p[1],
"hw_thread" : p[2]
} for p in vb.processor_map
]
}, f, indent=4)
if __name__ == "__main__":
argv = sys.argv
argc = len(argv)
envp = os.environ
sys.exit(main(argc, argv, envp))
|
[
"[email protected]"
] | |
7f3e63f22434cad4df3c5f31228f840cee385144
|
255e19ddc1bcde0d3d4fe70e01cec9bb724979c9
|
/all-gists/5259522/snippet.py
|
530896846672f9f888ff87c34b403125582a7bbd
|
[
"MIT"
] |
permissive
|
gistable/gistable
|
26c1e909928ec463026811f69b61619b62f14721
|
665d39a2bd82543d5196555f0801ef8fd4a3ee48
|
refs/heads/master
| 2023-02-17T21:33:55.558398 | 2023-02-11T18:20:10 | 2023-02-11T18:20:10 | 119,861,038 | 76 | 19 | null | 2020-07-26T03:14:55 | 2018-02-01T16:19:24 |
Python
|
UTF-8
|
Python
| false | false | 1,252 |
py
|
#!/usr/bin/env python
import sys
files = []
if len(sys.argv) > 2:
for file in sys.argv[1:]:
files.append(str(file))
else:
print "Usage: Wordcount.py file1 file2 file3 ..."
words_to_ignore = ["that","what","with","this","would","from","your","which","while","these"]
things_to_strip = [".",",","?",")","(","\"",":",";","'s"]
words_min_size = 4
print_in_html = True
text = ""
for file in files:
f = open(file,"rU")
for line in f:
text += line
words = text.lower().split()
wordcount = {}
for word in words:
for thing in things_to_strip:
if thing in word:
word = word.replace(thing,"")
if word not in words_to_ignore and len(word) >= words_min_size:
if word in wordcount:
wordcount[word] += 1
else:
wordcount[word] = 1
sortedbyfrequency = sorted(wordcount,key=wordcount.get,reverse=True)
def print_txt(sortedbyfrequency):
for word in sortedbyfrequency:
print word, wordcount[word]
def print_html(sortedbyfrequency):
print "<html><head><title>Wordcount.py Output</title></head><body><table>"
for word in sortedbyfrequency:
print "<tr><td>%s</td><td>%s</td></tr>" % (word,wordcount[word])
print "</table></body></html>"
if print_in_html == True:
print_html(sortedbyfrequency)
else:
print_txt(sortedbyfrequency)
|
[
"[email protected]"
] | |
03d4807bf6ae79a977ee60b6b4de35c94aeb6e7f
|
88a5dae03f0304d3fb7add71855d2ddc6d8e28e3
|
/main/ext/__init__.py
|
362e9cace53732e41d9341d5e951472eba630fbc
|
[
"Apache-2.0"
] |
permissive
|
huangpd/Shape
|
eabb59781ac6a055f7b7036fef926023cbcd4882
|
fddbbb765e353584752066f7c839293ebd10c4df
|
refs/heads/master
| 2020-03-26T13:04:22.224367 | 2018-05-10T09:06:10 | 2018-05-10T09:06:10 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 431 |
py
|
#-*-coding:utf-8-*-
from flask_bcrypt import Bcrypt
bcrypt = Bcrypt()
from flask_bootstrap import Bootstrap
bootstrap = Bootstrap()
from flask_mail import Mail
mail=Mail()
from flask_login import LoginManager
login_manager = LoginManager()
login_manager.login_view="auth.login_index"
login_manager.session_protection="strong"
login_manager.login_message="登录以获得更多功能"
login_manager.login_message_category="info"
|
[
"[email protected]"
] | |
b4e76b67a52d7e11e271463c76c756cd39c39301
|
f09978f2a0850278255bd198222cd3990cb0c687
|
/gear/schema.py
|
9e678012c38374b5baee61fdf28ff22143a7874c
|
[] |
no_license
|
szpone/climbing-gear
|
0e4e53b99a0b550c0e172af21c2c9e08e2c3f1ba
|
78ab13b97b4b66464859b95ba6e5ed8587d5e60c
|
refs/heads/master
| 2022-12-12T11:08:57.277056 | 2019-06-05T16:06:02 | 2019-06-05T16:06:02 | 185,016,538 | 1 | 0 | null | 2022-11-22T03:49:28 | 2019-05-05T10:30:11 |
Python
|
UTF-8
|
Python
| false | false | 514 |
py
|
import graphene
from graphene_django.types import DjangoObjectType, ObjectType
from .models import Gear
class GearType(DjangoObjectType):
class Meta:
model = Gear
class Query(ObjectType):
gear = graphene.Field(GearType, id=graphene.Int())
gears = graphene.List(GearType)
def resolve_gear(self, info, gear_id):
return Gear.objects.filter(id=gear_id).first()
def resolve_gears(self, info, **kwargs):
return Gear.objects.all()
schema = graphene.Schema(query=Query)
|
[
"[email protected]"
] | |
4eee374d40da98978fa6eead0dbd109ebd17f59e
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/CodeRecords/2449/60657/249828.py
|
b6f2e07860c983d2311d854da47037a89843a79d
|
[] |
no_license
|
AdamZhouSE/pythonHomework
|
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
|
ffc5606817a666aa6241cfab27364326f5c066ff
|
refs/heads/master
| 2022-11-24T08:05:22.122011 | 2020-07-28T16:21:24 | 2020-07-28T16:21:24 | 259,576,640 | 2 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 152 |
py
|
import math
A=input().split(',')
B=input()
def judge(A,B):
if A.count(B)!=0:
return A.index(B)
else:
return -1
print(judge(A,B))
|
[
"[email protected]"
] | |
7b91e3b074f85271a746505ec2100144aaa01af3
|
d7641647d67d110e08997767e85bbea081c2537b
|
/bitmovin_api_sdk/models/filter.py
|
6836a5d837fc6e5d357ec0e2fa2c5884394e48d2
|
[
"MIT"
] |
permissive
|
aachenmax/bitmovin-api-sdk-python
|
d3ded77c459852cbea4927ff28c2a4ad39e6026a
|
931bcd8c4695a7eb224a7f4aa5a189ba2430e639
|
refs/heads/master
| 2022-11-16T08:59:06.830567 | 2020-07-06T07:16:51 | 2020-07-06T07:16:51 | 267,538,689 | 0 | 1 |
MIT
| 2020-07-06T07:16:52 | 2020-05-28T08:44:44 |
Python
|
UTF-8
|
Python
| false | false | 1,781 |
py
|
# coding: utf-8
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
from bitmovin_api_sdk.models.bitmovin_resource import BitmovinResource
import pprint
class Filter(BitmovinResource):
discriminator_value_class_map = {
'CROP': 'CropFilter',
'CONFORM': 'ConformFilter',
'WATERMARK': 'WatermarkFilter',
'ENHANCED_WATERMARK': 'EnhancedWatermarkFilter',
'ROTATE': 'RotateFilter',
'DEINTERLACE': 'DeinterlaceFilter',
'AUDIO_MIX': 'AudioMixFilter',
'DENOISE_HQDN3D': 'DenoiseHqdn3dFilter',
'TEXT': 'TextFilter',
'UNSHARP': 'UnsharpFilter',
'SCALE': 'ScaleFilter',
'INTERLACE': 'InterlaceFilter',
'AUDIO_VOLUME': 'AudioVolumeFilter',
'EBU_R128_SINGLE_PASS': 'EbuR128SinglePassFilter'
}
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
if hasattr(super(Filter, self), "to_dict"):
result = super(Filter, self).to_dict()
for k, v in iteritems(self.discriminator_value_class_map):
if v == type(self).__name__:
result['type'] = k
break
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, Filter):
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]"
] | |
f59eef689da00fb5d14fdfaddf69c05fcdb4d412
|
531c47c15b97cbcb263ec86821d7f258c81c0aaf
|
/sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/lab_account_fragment.py
|
0e3a2fb1fa1897771c1c81ee386226f6730a5827
|
[
"LicenseRef-scancode-generic-cla",
"LGPL-2.1-or-later",
"MIT"
] |
permissive
|
YijunXieMS/azure-sdk-for-python
|
be364d3b88204fd3c7d223df23756386ff7a3361
|
f779de8e53dbec033f98f976284e6d9491fd60b3
|
refs/heads/master
| 2021-07-15T18:06:28.748507 | 2020-09-04T15:48:52 | 2020-09-04T15:48:52 | 205,457,088 | 1 | 2 |
MIT
| 2020-06-16T16:38:15 | 2019-08-30T21:08:55 |
Python
|
UTF-8
|
Python
| false | false | 2,376 |
py
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .resource import Resource
class LabAccountFragment(Resource):
"""Represents a lab account.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: The identifier of the resource.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource.
:vartype type: str
:param location: The location of the resource.
:type location: str
:param tags: The tags of the resource.
:type tags: dict[str, str]
:param enabled_region_selection: Represents if region selection is enabled
:type enabled_region_selection: bool
:param provisioning_state: The provisioning status of the resource.
:type provisioning_state: str
:param unique_identifier: The unique immutable identifier of a resource
(Guid).
:type unique_identifier: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'enabled_region_selection': {'key': 'properties.enabledRegionSelection', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'unique_identifier': {'key': 'properties.uniqueIdentifier', 'type': 'str'},
}
def __init__(self, **kwargs):
super(LabAccountFragment, self).__init__(**kwargs)
self.enabled_region_selection = kwargs.get('enabled_region_selection', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
self.unique_identifier = kwargs.get('unique_identifier', None)
|
[
"[email protected]"
] | |
d82cf9e821ecf30bd91d020d422728952809a303
|
597ed154876611a3d65ca346574f4696259d6e27
|
/dbaas/workflow/steps/tests/test_vm_step.py
|
1f05feed7c79364c570f0ed132f5da3578825a91
|
[] |
permissive
|
soitun/database-as-a-service
|
41984d6d2177734b57d726cd3cca7cf0d8c5f5d6
|
1282a46a9437ba6d47c467f315b5b6a3ac0af4fa
|
refs/heads/master
| 2023-06-24T17:04:49.523596 | 2018-03-15T19:35:10 | 2018-03-15T19:35:10 | 128,066,738 | 0 | 0 |
BSD-3-Clause
| 2022-05-10T22:39:58 | 2018-04-04T13:33:42 |
Python
|
UTF-8
|
Python
| false | false | 1,661 |
py
|
from mock import patch
from physical.tests.factory import HostFactory, EnvironmentFactory
from ..util.vm import VmStep, MigrationWaitingBeReady
from . import TestBaseStep
@patch('workflow.steps.util.vm.get_credentials_for', return_value=True)
@patch('workflow.steps.util.vm.CloudStackProvider', return_value=object)
class VMStepTests(TestBaseStep):
def setUp(self):
super(VMStepTests, self).setUp()
self.host = self.instance.hostname
def test_environment(self, *args, **kwargs):
vm_step = VmStep(self.instance)
self.assertEqual(vm_step.environment, self.environment)
def test_host(self, *args, **kwargs):
vm_step = VmStep(self.instance)
self.assertEqual(vm_step.host, self.host)
@patch('workflow.steps.util.vm.get_credentials_for', return_value=True)
@patch('workflow.steps.util.vm.CloudStackProvider', return_value=object)
class VMStepTestsMigration(TestBaseStep):
def setUp(self):
super(VMStepTestsMigration, self).setUp()
self.host = self.instance.hostname
self.future_host = HostFactory()
self.host.future_host = self.future_host
self.host.save()
self.environment_migrate = EnvironmentFactory()
self.environment.migrate_environment = self.environment_migrate
self.environment.save()
def test_environment(self, *args, **kwargs):
vm_step = MigrationWaitingBeReady(self.instance)
self.assertEqual(vm_step.environment, self.environment_migrate)
def test_host(self, *args, **kwargs):
vm_step = MigrationWaitingBeReady(self.instance)
self.assertEqual(vm_step.host, self.future_host)
|
[
"[email protected]"
] | |
1dfee621f2c8bf35b8a73f7fbbb1a64d238e125a
|
bbb21bb79c8c3efbad3dd34ac53fbd6f4590e697
|
/week3/TODO/TODO/settings.py
|
947cd11c197d9ed2bf30a09cd9c4016007788b22
|
[] |
no_license
|
Nusmailov/BFDjango
|
b14c70c42da9cfcb68eec6930519da1d0b1f53b6
|
cab7f0da9b03e9094c21efffc7ab07e99e629b61
|
refs/heads/master
| 2020-03-28T21:11:50.706778 | 2019-01-21T07:19:19 | 2019-01-21T07:19:19 | 149,136,999 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,094 |
py
|
"""
Django settings for TODO project.
Generated by 'django-admin startproject' using Django 2.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'mitb8&^*0ibt!u_xqe1!tjzumo65hy@cnxt-z#+9+p@m$u8qnn'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'TODO.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'TODO.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
|
[
"[email protected]"
] | |
cdc0900d3b2677c0be666cbdd443353d5385757e
|
64ffb2e803a19e5dc75ec8fa0f277609d34e0cc7
|
/dynamodb/update_counter_atomically.py
|
ddfbf9dfad90311a0332a3cbd1a990c0830b6c51
|
[] |
no_license
|
arunpa0206/awstraining
|
687bc4206dfd65693039c525e8a4ff39d14e89d5
|
2eae2353b75a2774f9f47b40d76d63c7f9e08bb4
|
refs/heads/master
| 2021-05-10T15:06:48.652021 | 2019-08-20T10:36:29 | 2019-08-20T10:36:29 | 118,538,574 | 0 | 2 | null | null | null | null |
UTF-8
|
Python
| false | false | 954 |
py
|
from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
dynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url="http://localhost:8000")
table = dynamodb.Table('Movies')
title = "The Big New Movie"
year = 2015
response = table.update_item(
Key={
'year': year,
'title': title
},
UpdateExpression="set info.rating = info.rating + :val",
ExpressionAttributeValues={
':val': decimal.Decimal(1)
},
ReturnValues="UPDATED_NEW"
)
print("UpdateItem succeeded:")
print(json.dumps(response, indent=4, cls=DecimalEncoder))
|
[
"[email protected]"
] | |
303d2e67444557cb4fd051f1250a360cb9ef821c
|
892c7bd301eeadf57b546f039faf499448112ddc
|
/organizacion/migrations/0004_escuelacampo.py
|
0f8af8ca46dffde4815519fa6295128bd78c2024
|
[
"MIT"
] |
permissive
|
ErickMurillo/aprocacaho
|
beed9c4b031cf26a362e44fc6a042b38ab246c27
|
eecd216103e6b06e3ece174c89d911f27b50585a
|
refs/heads/master
| 2022-11-23T15:03:32.687847 | 2019-07-01T19:16:37 | 2019-07-01T19:16:37 | 53,867,804 | 0 | 1 |
MIT
| 2022-11-22T01:02:51 | 2016-03-14T15:23:39 |
HTML
|
UTF-8
|
Python
| false | false | 903 |
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-04 14:26
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('organizacion', '0003_auto_20160803_2128'),
]
operations = [
migrations.CreateModel(
name='EscuelaCampo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.CharField(max_length=200)),
('organizacion', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='organizacion.Organizacion')),
],
options={
'verbose_name': 'Escuela de campo',
'verbose_name_plural': 'Escuelas de campo',
},
),
]
|
[
"[email protected]"
] | |
1b595d943f2f3026a02236c4b6a6caade13ea718
|
ea6b3b74c8f1ff9333c5d4b06a0e4dd9bbdb3bba
|
/tests/protocol/test_json_protocol.py
|
5a79da739005fd27e01a88e27d335942a77b03c2
|
[
"MIT"
] |
permissive
|
sgalkina/venom
|
d495d296a388afcb25525491bbbe590bfd258a05
|
e372ab9002e71ba4e2422aabd02143e4f1247dba
|
refs/heads/master
| 2021-01-23T03:27:17.239289 | 2017-03-24T15:05:56 | 2017-03-24T15:05:56 | 86,077,951 | 0 | 0 | null | 2017-03-24T14:40:46 | 2017-03-24T14:40:46 | null |
UTF-8
|
Python
| false | false | 5,448 |
py
|
from unittest import SkipTest
from unittest import TestCase
from venom import Message
from venom.common import StringValue, IntegerValue, BoolValue, NumberValue
from venom.exceptions import ValidationError
from venom.fields import String, Number, Field, Repeat
from venom.protocol import JSON
class Foo(Message):
string = String()
parent = Field('tests.protocol.test_json_protocol.Foo')
string_value = Field(StringValue)
class JSONProtocolTestCase(TestCase):
def test_encode_message(self):
class Pet(Message):
sound = String()
protocol = JSON(Pet)
self.assertEqual(protocol.encode(Pet('hiss!')), {'sound': 'hiss!'})
self.assertEqual(protocol.decode({'sound': 'meow'}), Pet('meow'))
self.assertEqual(protocol.decode({}), Pet())
with self.assertRaises(ValidationError) as e:
protocol.decode('bad')
self.assertEqual(e.exception.description, "'bad' is not of type 'object'")
self.assertEqual(e.exception.path, [])
@SkipTest
def test_encode_message_field_attribute(self):
# NOTE: removed support for field attributes.
class Pet(Message):
size = Number(attribute='weight')
protocol = JSON(Pet)
pet = Pet()
pet.size = 2.5
self.assertEqual(protocol.encode(pet), {'weight': 2.5})
self.assertEqual(protocol.decode({'weight': 2.5}), Pet(2.5))
def test_encode_repeat_field(self):
class Pet(Message):
sounds = Repeat(String())
protocol = JSON(Pet)
self.assertEqual(protocol.encode(Pet(['hiss!', 'slither'])), {'sounds': ['hiss!', 'slither']})
self.assertEqual(protocol.decode({'sounds': ['meow', 'purr']}), Pet(['meow', 'purr']))
self.assertEqual(protocol.decode({}), Pet())
self.assertEqual(protocol.encode(Pet()), {})
with self.assertRaises(ValidationError) as e:
protocol.decode({'sounds': 'meow, purr'})
self.assertEqual(e.exception.description, "'meow, purr' is not of type 'list'")
self.assertEqual(e.exception.path, ['sounds'])
def test_validation_field_string(self):
class Foo(Message):
string = String()
protocol = JSON(Foo)
with self.assertRaises(ValidationError) as e:
protocol.decode({'string': None})
self.assertEqual(e.exception.description, "None is not of type 'str'")
self.assertEqual(e.exception.path, ['string'])
def test_validation_path(self):
protocol = JSON(Foo)
with self.assertRaises(ValidationError) as e:
protocol.decode({'string': 42})
self.assertEqual(e.exception.description, "42 is not of type 'str'")
self.assertEqual(e.exception.path, ['string'])
# FIXME With custom encoding/decoding for values this won't happen.
with self.assertRaises(ValidationError) as e:
protocol.decode({'string_value': {'value': None}})
self.assertEqual(e.exception.description, "{'value': None} is not of type 'str'")
self.assertEqual(e.exception.path, ['string_value'])
with self.assertRaises(ValidationError) as e:
protocol.decode({'parent': {'string_value': 42}})
self.assertEqual(e.exception.description, "42 is not of type 'str'")
self.assertEqual(e.exception.path, ['parent', 'string_value'])
def test_unpack_invalid_json(self):
class Pet(Message):
sound = String()
protocol = JSON(Pet)
with self.assertRaises(ValidationError) as e:
protocol.unpack(b'')
self.assertEqual(e.exception.description, "Invalid JSON: Expected object or value")
self.assertEqual(e.exception.path, [])
with self.assertRaises(ValidationError) as e:
protocol.unpack(b'fs"ad')
def test_pack(self):
class Pet(Message):
sound = String()
protocol = JSON(Pet)
self.assertEqual(protocol.pack(Pet()), b'{}')
self.assertEqual(protocol.pack(Pet('hiss!')), b'{"sound":"hiss!"}')
def test_string_value(self):
protocol = JSON(StringValue)
self.assertEqual(protocol.encode(StringValue('hiss!')), 'hiss!')
self.assertEqual(protocol.decode('hiss!'), StringValue('hiss!'))
self.assertEqual(protocol.pack(StringValue()), b'""')
self.assertEqual(protocol.pack(StringValue('hiss!')), b'"hiss!"')
with self.assertRaises(ValidationError):
protocol.decode(42)
def test_integer_value(self):
protocol = JSON(IntegerValue)
self.assertEqual(protocol.encode(IntegerValue(2)), 2)
self.assertEqual(protocol.decode(2), IntegerValue(2))
with self.assertRaises(ValidationError):
protocol.decode('hiss!')
def test_number_value(self):
protocol = JSON(NumberValue)
self.assertEqual(protocol.encode(NumberValue(2.5)), 2.5)
self.assertEqual(protocol.decode(2.5), NumberValue(2.5))
with self.assertRaises(ValidationError):
protocol.decode('hiss!')
def test_bool_value(self):
protocol = JSON(BoolValue)
self.assertEqual(protocol.encode(BoolValue()), False)
self.assertEqual(protocol.encode(BoolValue(True)), True)
self.assertEqual(protocol.decode(False), BoolValue(False))
with self.assertRaises(ValidationError):
protocol.decode('hiss!')
|
[
"[email protected]"
] | |
3129d119bb1773e4909ac9e1ecf759cef0cad06e
|
539789516d0d946e8086444bf4dc6f44d62758c7
|
/inference/python/inference.py
|
7fc210e7978a31556f20ba12d8a1baa22d2ff6c4
|
[] |
no_license
|
hoangcuong2011/etagger
|
ad05ca0c54f007f54f73d39dc539c3737d5acacf
|
611da685d72da207870ddb3dc403b530c859d603
|
refs/heads/master
| 2020-05-03T15:15:33.395186 | 2019-03-28T01:40:21 | 2019-03-28T01:40:21 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 7,683 |
py
|
from __future__ import print_function
import sys
import os
path = os.path.dirname(os.path.abspath(__file__)) + '/../..'
sys.path.append(path)
import time
import argparse
import tensorflow as tf
import numpy as np
# for LSTMBlockFusedCell(), https://github.com/tensorflow/tensorflow/issues/23369
tf.contrib.rnn
# for QRNN
try: import qrnn
except: sys.stderr.write('import qrnn, failed\n')
from embvec import EmbVec
from config import Config
from token_eval import TokenEval
from chunk_eval import ChunkEval
from input import Input
def load_frozen_graph(frozen_graph_filename, prefix='prefix'):
with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(
graph_def,
input_map=None,
return_elements=None,
op_dict=None,
producer_op_list=None,
name=prefix,
)
return graph
def inference(config, frozen_pb_path):
"""Inference for bucket
"""
# load graph
graph = load_frozen_graph(frozen_pb_path)
for op in graph.get_operations():
sys.stderr.write(op.name + '\n')
# create session with graph
# if graph is optimized by tensorRT, then
# from tensorflow.contrib import tensorrt as trt
# gpu_ops = tf.GPUOptions(per_process_gpu_memory_fraction = 0.50)
gpu_ops = tf.GPUOptions()
'''
session_conf = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False, gpu_options=gpu_ops)
'''
session_conf = tf.ConfigProto(allow_soft_placement=True,
log_device_placement=False,
gpu_options=gpu_ops,
inter_op_parallelism_threads=1,
intra_op_parallelism_threads=1)
sess = tf.Session(graph=graph, config=session_conf)
# mapping placeholders and tensors
p_is_train = graph.get_tensor_by_name('prefix/is_train:0')
p_sentence_length = graph.get_tensor_by_name('prefix/sentence_length:0')
p_input_data_pos_ids = graph.get_tensor_by_name('prefix/input_data_pos_ids:0')
p_input_data_chk_ids = graph.get_tensor_by_name('prefix/input_data_chk_ids:0')
p_input_data_word_ids = graph.get_tensor_by_name('prefix/input_data_word_ids:0')
p_input_data_wordchr_ids = graph.get_tensor_by_name('prefix/input_data_wordchr_ids:0')
t_logits_indices = graph.get_tensor_by_name('prefix/logits_indices:0')
t_sentence_lengths = graph.get_tensor_by_name('prefix/sentence_lengths:0')
num_buckets = 0
total_duration_time = 0.0
bucket = []
while 1:
try: line = sys.stdin.readline()
except KeyboardInterrupt: break
if not line: break
line = line.strip()
if not line and len(bucket) >= 1:
start_time = time.time()
# Build input data
inp = Input(bucket, config, build_output=False)
feed_dict = {p_input_data_pos_ids: inp.example['pos_ids'],
p_input_data_chk_ids: inp.example['chk_ids'],
p_is_train: False,
p_sentence_length: inp.max_sentence_length}
feed_dict[p_input_data_word_ids] = inp.example['word_ids']
feed_dict[p_input_data_wordchr_ids] = inp.example['wordchr_ids']
if 'elmo' in config.emb_class:
feed_dict[p_elmo_input_data_wordchr_ids] = inp.example['elmo_wordchr_ids']
if 'bert' in config.emb_class:
feed_dict[p_bert_input_data_token_ids] = inp.example['bert_token_ids']
feed_dict[p_bert_input_data_token_masks] = inp.example['bert_token_masks']
feed_dict[p_bert_input_data_segment_ids] = inp.example['bert_segment_ids']
if 'elmo' in config.emb_class:
feed_dict[p_bert_input_data_elmo_indices] = inp.example['bert_elmo_indices']
logits_indices, sentence_lengths = sess.run([t_logits_indices, t_sentence_lengths], feed_dict=feed_dict)
tags = config.logit_indices_to_tags(logits_indices[0], sentence_lengths[0])
for i in range(len(bucket)):
if 'bert' in config.emb_class:
j = inp.example['bert_wordidx2tokenidx'][0][i]
out = bucket[i] + ' ' + tags[j]
else:
out = bucket[i] + ' ' + tags[i]
sys.stdout.write(out + '\n')
sys.stdout.write('\n')
bucket = []
duration_time = time.time() - start_time
out = 'duration_time : ' + str(duration_time) + ' sec'
sys.stderr.write(out + '\n')
num_buckets += 1
total_duration_time += duration_time
if line : bucket.append(line)
if len(bucket) != 0:
start_time = time.time()
# Build input data
inp = Input(bucket, config, build_output=False)
feed_dict = {model.input_data_pos_ids: inp.example['pos_ids'],
model.input_data_chk_ids: inp.example['chk_ids'],
model.is_train: False,
model.sentence_length: inp.max_sentence_length}
feed_dict[model.input_data_word_ids] = inp.example['word_ids']
feed_dict[model.input_data_wordchr_ids] = inp.example['wordchr_ids']
if 'elmo' in config.emb_class:
feed_dict[model.elmo_input_data_wordchr_ids] = inp.example['elmo_wordchr_ids']
if 'bert' in config.emb_class:
feed_dict[model.bert_input_data_token_ids] = inp.example['bert_token_ids']
feed_dict[model.bert_input_data_token_masks] = inp.example['bert_token_masks']
feed_dict[model.bert_input_data_segment_ids] = inp.example['bert_segment_ids']
if 'elmo' in config.emb_class:
feed_dict[model.bert_input_data_elmo_indices] = inp.example['bert_elmo_indices']
logits_indices, sentence_lengths = sess.run([t_logits_indices, t_sentence_lengths], feed_dict=feed_dict)
tags = config.logit_indices_to_tags(logits_indices[0], sentence_lengths[0])
for i in range(len(bucket)):
if 'bert' in config.emb_class:
j = inp.example['bert_wordidx2tokenidx'][0][i]
out = bucket[i] + ' ' + tags[j]
else:
out = bucket[i] + ' ' + tags[i]
sys.stdout.write(out + '\n')
sys.stdout.write('\n')
duration_time = time.time() - start_time
out = 'duration_time : ' + str(duration_time) + ' sec'
tf.logging.info(out)
num_buckets += 1
total_duration_time += duration_time
out = 'total_duration_time : ' + str(total_duration_time) + ' sec' + '\n'
out += 'average processing time / bucket : ' + str(total_duration_time / num_buckets) + ' sec'
tf.logging.info(out)
sess.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--emb_path', type=str, help='path to word embedding vector + vocab(.pkl)', required=True)
parser.add_argument('--wrd_dim', type=int, help='dimension of word embedding vector', required=True)
parser.add_argument('--word_length', type=int, default=15, help='max word length')
parser.add_argument('--frozen_path', type=str, help='path to frozen model(ex, ./exported/ner_frozen.pb)', required=True)
args = parser.parse_args()
tf.logging.set_verbosity(tf.logging.INFO)
args.restore = None
config = Config(args, is_training=False, emb_class='glove', use_crf=True)
inference(config, args.frozen_path)
|
[
"[email protected]"
] | |
da0de991295a250dbfc4238a27b5f8573f7770a8
|
48c6b58e07891475a2c60a8afbbbe6447bf527a7
|
/src/tests/control/test_orders.py
|
74c7007fa3a989b7c5f5133361a5abbc1a3dcc33
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
awg24/pretix
|
a9f86fe2dd1f3269734ed39b3ea052ef292ff110
|
b1d67a48601838bac0d4e498cbe8bdcd16013d60
|
refs/heads/master
| 2021-01-15T23:40:28.582518 | 2015-08-27T14:05:18 | 2015-08-27T14:05:18 | 42,126,402 | 1 | 0 | null | 2015-09-08T16:58:52 | 2015-09-08T16:58:51 | null |
UTF-8
|
Python
| false | false | 3,084 |
py
|
from datetime import timedelta
from decimal import Decimal
import pytest
from django.utils.timezone import now
from pretix.base.models import (
Event, EventPermission, Item, Order, OrderPosition, Organizer,
OrganizerPermission, User,
)
@pytest.fixture
def env():
o = Organizer.objects.create(name='Dummy', slug='dummy')
event = Event.objects.create(
organizer=o, name='Dummy', slug='dummy',
date_from=now(), plugins='pretix.plugins.banktransfer'
)
user = User.objects.create_user('[email protected]', '[email protected]', 'dummy')
EventPermission.objects.create(
event=event,
user=user,
can_view_orders=True,
can_change_orders=True
)
o = Order.objects.create(
code='FOO', event=event,
user=user, status=Order.STATUS_PENDING,
datetime=now(), expires=now() + timedelta(days=10),
total=0, payment_provider='banktransfer'
)
ticket = Item.objects.create(event=event, name='Early-bird ticket',
category=None, default_price=23,
admission=True)
event.settings.set('attendee_names_asked', True)
OrderPosition.objects.create(
order=o,
item=ticket,
variation=None,
price=Decimal("14"),
attendee_name="Peter"
)
return event, user, o
@pytest.mark.django_db
def test_order_list(client, env):
client.login(identifier='[email protected]', password='dummy')
response = client.get('/control/event/dummy/dummy/orders/')
assert 'FOO' in response.rendered_content
response = client.get('/control/event/dummy/dummy/orders/?user=peter')
assert 'FOO' not in response.rendered_content
response = client.get('/control/event/dummy/dummy/orders/?user=dummy')
assert 'FOO' in response.rendered_content
response = client.get('/control/event/dummy/dummy/orders/?status=p')
assert 'FOO' not in response.rendered_content
response = client.get('/control/event/dummy/dummy/orders/?status=n')
assert 'FOO' in response.rendered_content
@pytest.mark.django_db
def test_order_detail(client, env):
client.login(identifier='[email protected]', password='dummy')
response = client.get('/control/event/dummy/dummy/orders/FOO/')
assert 'Early-bird' in response.rendered_content
assert 'Peter' in response.rendered_content
@pytest.mark.django_db
def test_order_transition_cancel(client, env):
client.login(identifier='[email protected]', password='dummy')
client.post('/control/event/dummy/dummy/orders/FOO/transition', {
'status': 'c'
})
o = Order.objects.current.get(identity=env[2].identity)
assert o.status == Order.STATUS_CANCELLED
@pytest.mark.django_db
def test_order_transition_to_paid_success(client, env):
client.login(identifier='[email protected]', password='dummy')
client.post('/control/event/dummy/dummy/orders/FOO/transition', {
'status': 'p'
})
o = Order.objects.current.get(identity=env[2].identity)
assert o.status == Order.STATUS_PAID
|
[
"[email protected]"
] | |
56ac5f435c1505b586a07d2bf83a64eff2564702
|
60b5a9a8b519cb773aca004b7217637f8a1a0526
|
/customer/urls.py
|
2bf028b3dc13eed4b4e9793741b3f478b4d5d355
|
[] |
no_license
|
malep2007/dag-bragan-erp-backend
|
76ce90c408b21b0bda73c6dd972e2f77b7f21b1f
|
e98182af2848a6533ddd28c586649a8fee1dc695
|
refs/heads/master
| 2021-08-11T01:29:27.864747 | 2019-01-15T17:46:26 | 2019-01-15T17:46:26 | 151,831,965 | 0 | 0 | null | 2021-06-10T20:56:21 | 2018-10-06T11:10:12 |
Python
|
UTF-8
|
Python
| false | false | 437 |
py
|
from django.urls import path, reverse
from . import views
urlpatterns = [
path('', views.CustomerListView.as_view(), name='index'),
path('<int:pk>/', views.CustomerDetailView.as_view(), name="detail"),
path('edit/<int:pk>/', views.CustomerUpdateView.as_view(), name='edit'),
path('add/', views.CustomerCreateView.as_view(), name='add'),
path('delete/<int:pk>/', views.CustomerDeleteView.as_view(), name='delete'),
]
|
[
"[email protected]"
] | |
a1b2d1e62a5a9c0b2e499246d138951a2a9f20f9
|
64a80df5e23b195eaba7b15ce207743e2018b16c
|
/Downloads/adafruit-circuitpython-bundle-py-20201107/lib/adafruit_wsgi/wsgi_app.py
|
44171f51cfa9e62e9b7fdc09a66fc806d95d7b4a
|
[] |
no_license
|
aferlazzo/messageBoard
|
8fb69aad3cd7816d4ed80da92eac8aa2e25572f5
|
f9dd4dcc8663c9c658ec76b2060780e0da87533d
|
refs/heads/main
| 2023-01-27T20:02:52.628508 | 2020-12-07T00:37:17 | 2020-12-07T00:37:17 | 318,548,075 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 4,807 |
py
|
# The MIT License (MIT)
#
# Copyright (c) 2019 Matthew Costi for Adafruit Industries
#
# 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.
"""
`wsgi_app`
================================================================================
CircuitPython framework for creating WSGI server compatible web applications.
This does *not* include server implementation, which is necessary in order
to create a web application with this library.
* Circuit Python implementation of an WSGI Server for ESP32 devices:
https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI.git
* Author(s): Matthew Costi
Implementation Notes
--------------------
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases
"""
import re
from adafruit_wsgi.request import Request
__version__ = "1.1.1"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_WSGI.git"
class WSGIApp:
"""
The base WSGI Application class.
"""
def __init__(self):
self._routes = []
self._variable_re = re.compile("^<([a-zA-Z]+)>$")
def __call__(self, environ, start_response):
"""
Called whenever the server gets a request.
The environ dict has details about the request per wsgi specification.
Call start_response with the response status string and headers as a list of tuples.
Return a single item list with the item being your response data string.
"""
status = ""
headers = []
resp_data = []
request = Request(environ)
match = self._match_route(request.path, request.method.upper())
if match:
args, route = match
status, headers, resp_data = route["func"](request, *args)
start_response(status, headers)
return resp_data
def on_request(self, methods, rule, request_handler):
"""
Register a Request Handler for a particular HTTP method and path.
request_handler will be called whenever a matching HTTP request is received.
request_handler should accept the following args:
(Dict environ)
request_handler should return a tuple in the shape of:
(status, header_list, data_iterable)
:param list methods: the methods of the HTTP request to handle
:param str rule: the path rule of the HTTP request
:param func request_handler: the function to call
"""
regex = "^"
rule_parts = rule.split("/")
for part in rule_parts:
var = self._variable_re.match(part)
if var:
# If named capture groups ever become a thing, use this regex instead
# regex += "(?P<" + var.group("var") + r">[a-zA-Z0-9_-]*)\/"
regex += r"([a-zA-Z0-9_-]+)\/"
else:
regex += part + r"\/"
regex += "?$" # make last slash optional and that we only allow full matches
self._routes.append(
(re.compile(regex), {"methods": methods, "func": request_handler})
)
def route(self, rule, methods=None):
"""
A decorator to register a route rule with an endpoint function.
if no methods are provided, default to GET
"""
if not methods:
methods = ["GET"]
return lambda func: self.on_request(methods, rule, func)
def _match_route(self, path, method):
for matcher, route in self._routes:
match = matcher.match(path)
if match and method in route["methods"]:
return (match.groups(), route)
return None
|
[
"[email protected]"
] | |
2ebfb27d864daa8609758160bd3ee3c6122b704a
|
e147827b4f6fbc4dd862f817e9d1a8621c4fcedc
|
/apps/doc/views.py
|
ab450d855ef75b700dd41676295f6518652efa34
|
[] |
no_license
|
Jsummer121/DjangoBolgProject
|
ba3ebe27a1ac67439de67b9f10c17d1c16e43f84
|
d64f9579d29ac5e3979d40303e84f4be6852fa96
|
refs/heads/master
| 2023-01-30T16:26:33.566665 | 2020-12-15T12:00:16 | 2020-12-15T12:00:16 | 321,654,994 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,834 |
py
|
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse, FileResponse, StreamingHttpResponse, Http404
from doc import models
import requests
from django.utils.encoding import escape_uri_path
from Django_pro.settings import DOC_FILE_URL
def doc(request):
docs = models.Doc.objects.only('image_url', 'desc', 'title').filter(is_delete=False)
return render(request, 'doc/docDownload.html', context={'docs': docs})
class DocDownload(View):
def get(self, request, doc_id):
doc_file = models.Doc.objects.only('file_url').filter(is_delete=False, id=doc_id).first()
if doc_file:
# /media/流畅的Python.pdf
doc_url = doc_file.file_url
# http://192.168.216.137:8000/media/流畅的Python.pdf
doc_url = DOC_FILE_URL + doc_url
# a = requests.get(doc_url)
# res = HttpResponse(a) #下面是简写
res = FileResponse(requests.get(doc_url))
ex_name = doc_url.split('.')[-1] # pdf
if not ex_name:
raise Http404('文件名异常')
else:
ex_name = ex_name.lower()
if ex_name == 'pdf':
res['Content-type'] = 'application/pdf'
elif ex_name == 'doc':
res['Content-type'] = 'application/msowrd'
elif ex_name == 'ppt':
res['Content-type'] = 'application/powerpoint'
else:
raise Http404('文件格式不正确')
doc_filename = escape_uri_path(doc_url.split('/')[-1])
# attachment 保存 inline 显示
res["Content-Disposition"] = "attachment; filename*=UTF-8''{}".format(doc_filename)
return res
else:
raise Http404('文档不存在')
|
[
"[email protected]"
] | |
8329fa5bea57d4f6278bd16ce249d56f50672bc7
|
2c872fedcdc12c89742d10c2f1c821eed0470726
|
/pyNet/day06/code/test_poll.py
|
5f18a3bc99a060b68f525c9f9e72ac31b6e740a3
|
[] |
no_license
|
zuigehulu/AID1811
|
581c3c7a37df9fa928bc632e4891fc9bafe69201
|
10cab0869875290646a9e5d815ff159d0116990e
|
refs/heads/master
| 2020-04-19T16:33:04.174841 | 2019-01-30T07:58:24 | 2019-01-30T07:58:24 | 168,307,918 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 193 |
py
|
from multiprocessing import Pool
from time import sleep
L = [1,2,3,4,5]
def a(ne):
print(ne**2)
sleep(2)
pool = Pool()
for i in L:
pool.apply_async(a,(i,))
pool.close()
pool.join()
|
[
"[email protected]"
] | |
0a5a579dd0a6d232526835dc574518dcbab6e108
|
8393f28f390e222b0429fc4f3f07590f86333d8d
|
/linux-stuff/bin/svn-merge-meld
|
7c7beb77f18c8c2b9a4dbfe1bd016a679f58f12d
|
[] |
no_license
|
jmangelson/settings
|
fe118494252da35b175d159bbbef118f22b189fb
|
df9291f8947ba1ceb7c83a731dfbe9e775ce5add
|
refs/heads/master
| 2021-01-16T17:39:24.105679 | 2015-02-20T01:17:26 | 2015-02-20T01:17:26 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 682 |
#!/usr/bin/env python
# svn merge-tool python wrapper for meld
import sys
import subprocess
# path to meld ($ which meld)
meld = "/usr/bin/meld"
log = False
f = open('/tmp/svn-merge-meld.log', 'a')
def main():
if log:
f.write("call: %r\n" % sys.argv)
# file paths
base = sys.argv[1]
theirs = sys.argv[2]
mine = sys.argv[3]
merged = sys.argv[4]
partial = sys.argv[5]
# the call to meld
cmd = [meld, mine, theirs, merged]
# Call meld, making sure it exits correctly
subprocess.check_call(cmd)
try:
main()
except Exception as e:
print "Oh noes, an error: %r" % e
if log:
f.write("Error: %r\n" % e)
sys.exit(-1)
|
[
"devnull@localhost"
] |
devnull@localhost
|
|
0a551818b8e85dd12f84691ab34b3df1f13c138e
|
14ddda0c376f984d2a3f7dcd0ca7aebb7c49648d
|
/bnn_mcmc_examples/examples/mlp/noisy_xor/setting2/mcmc/metropolis_hastings/pilot_visual_summary.py
|
34d2bb1186d2c1da6be83394dc47fe6431283c68
|
[
"MIT"
] |
permissive
|
papamarkou/bnn_mcmc_examples
|
62dcd9cc0cf57cda39aa46c2f2f237bbcd2d35bb
|
7bb4ecfb33db4c30a8e61e31f528bda0efb24e3d
|
refs/heads/main
| 2023-07-12T20:51:28.302981 | 2021-08-22T13:06:17 | 2021-08-22T13:06:17 | 316,554,634 | 1 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,553 |
py
|
# %% Import packages
import kanga.plots as ps
from kanga.chains import ChainArray
from bnn_mcmc_examples.examples.mlp.noisy_xor.setting2.mcmc.constants import diagnostic_iter_thres
from bnn_mcmc_examples.examples.mlp.noisy_xor.setting2.mcmc.metropolis_hastings.constants import sampler_output_pilot_path
from bnn_mcmc_examples.examples.mlp.noisy_xor.setting2.model import model
# %% Load chain array
chain_array = ChainArray.from_file(keys=['sample', 'accepted'], path=sampler_output_pilot_path)
# %% Drop burn-in samples
chain_array.vals['sample'] = chain_array.vals['sample'][diagnostic_iter_thres:, :]
chain_array.vals['accepted'] = chain_array.vals['accepted'][diagnostic_iter_thres:]
# %% Plot traces of simulated chain
for i in range(model.num_params()):
ps.trace(
chain_array.get_param(i),
title=r'Traceplot of $\theta_{{{}}}$'.format(i+1),
xlabel='Iteration',
ylabel='Parameter value'
)
# %% Plot running means of simulated chain
for i in range(model.num_params()):
ps.running_mean(
chain_array.get_param(i),
title=r'Running mean plot of parameter $\theta_{{{}}}$'.format(i+1),
xlabel='Iteration',
ylabel='Running mean'
)
# %% Plot histograms of marginals of simulated chain
for i in range(model.num_params()):
ps.hist(
chain_array.get_param(i),
bins=30,
density=True,
title=r'Histogram of parameter $\theta_{{{}}}$'.format(i+1),
xlabel='Parameter value',
ylabel='Parameter relative frequency'
)
|
[
"[email protected]"
] | |
44dc7ace3c96940a36a7ea468124c78e03900455
|
1620e0af4a522db2bac16ef9c02ac5b5a4569d70
|
/Ekeopara_Praise/Phase 2/LIST/Day44 Tasks/Task4.py
|
e3f303c59954e7bec5cf6fa62b4f49925de56d80
|
[
"MIT"
] |
permissive
|
Ekeopara-Praise/python-challenge-solutions
|
cda07902c9ffc09ba770ae7776e5e01026406a05
|
068b67c05524b5c5a0d6084315eca3424c768421
|
refs/heads/master
| 2022-12-15T15:29:03.031583 | 2020-09-25T06:46:27 | 2020-09-25T06:46:27 | 263,758,530 | 2 | 0 | null | 2020-05-13T22:37:33 | 2020-05-13T22:37:32 | null |
UTF-8
|
Python
| false | false | 141 |
py
|
'''4. Write a Python program to concatenate elements of a list. '''
num = ['1', '2', '3', '4', '5']
print('-'.join(num))
print(''.join(num))
|
[
"[email protected]"
] | |
46b56de9bf7ead1838fe58206ae4c91ce5bcfbb2
|
00792a90bfa302af8614f4a5f955c071ed320acf
|
/apps/control_params/tests.py
|
c93cb528dd87a34cb25ffb1ba372511159998b42
|
[] |
no_license
|
elcolie/HT6MInterface
|
dceb8f5e9b501b8836904559bd40259ccfe49085
|
04abf3cc73618c1cf059fa67da8a043ec9fb43b3
|
refs/heads/master
| 2022-02-04T08:02:49.023460 | 2021-01-21T06:55:39 | 2021-01-21T06:55:39 | 123,398,906 | 0 | 0 | null | 2022-01-21T20:20:29 | 2018-03-01T07:30:16 |
JavaScript
|
UTF-8
|
Python
| false | false | 4,395 |
py
|
from django.test import TestCase
from apps.control_params.api.serializers import ControlParameterSerializer
from apps.control_params.models import ControlParameter
from apps.heating_params.models import HeatingParameter
class TestControlParameter(TestCase):
def setUp(self):
pass
def test_blank_initial_data(self):
"""If no supply then serializer will be stuck at `heating_params`"""
serializer = ControlParameterSerializer(data={})
assert False is serializer.is_valid()
def test_control_param_serializer_number_mismatch(self):
data = {
'no_break_point': 3,
'max_run_time': 10,
'heating_params': [
{
'break_point_number': 2,
'breakpoint_time': 0,
'timestep': 0.01,
'particle_species': "E",
'rate_of_particle_source': 0,
'radial_position': 0,
'radial_width': 0.5,
'nbi_power': 0,
'nbi_radial_position': 0,
'nbi_radial_width': 0.5,
'icrf_power': 0,
'icrf_radial': 0,
'icrf_radial_width': 0.5,
},
{
'break_point_number': 2,
'breakpoint_time': 0,
'timestep': 0.01,
'particle_species': "H",
'rate_of_particle_source': 0,
'radial_position': 0,
'radial_width': 0.5,
'nbi_power': 0,
'nbi_radial_position': 0,
'nbi_radial_width': 0.5,
'icrf_power': 0,
'icrf_radial': 0,
'icrf_radial_width': 0.5,
},
]
}
serializer = ControlParameterSerializer(data=data)
detail = f"Heating params count is mismatch with given number of break point"
assert False is serializer.is_valid()
assert detail == str(serializer.errors.get('heating_params')[0])
def test_control_param_serializer(self):
data = {
'no_break_point': 3,
'max_run_time': 10,
'heating_params': [
{
'break_point_number': 2,
'breakpoint_time': 0,
'timestep': 0.01,
'particle_species': "E",
'rate_of_particle_source': 0,
'radial_position': 0,
'radial_width': 0.5,
'nbi_power': 0,
'nbi_radial_position': 0,
'nbi_radial_width': 0.5,
'icrf_power': 0,
'icrf_radial': 0,
'icrf_radial_width': 0.5,
},
{
'break_point_number': 2,
'breakpoint_time': 0,
'timestep': 0.01,
'particle_species': "H",
'rate_of_particle_source': 0,
'radial_position': 0,
'radial_width': 0.5,
'nbi_power': 0,
'nbi_radial_position': 0,
'nbi_radial_width': 0.5,
'icrf_power': 0,
'icrf_radial': 0,
'icrf_radial_width': 0.5,
},
{
'break_point_number': 2,
'breakpoint_time': 0,
'timestep': 0.01,
'particle_species': "E",
'rate_of_particle_source': 0,
'radial_position': 0,
'radial_width': 0.5,
'nbi_power': 0,
'nbi_radial_position': 0,
'nbi_radial_width': 0.5,
'icrf_power': 0,
'icrf_radial': 0,
'icrf_radial_width': 0.5,
},
]
}
serializer = ControlParameterSerializer(data=data)
is_valid = serializer.is_valid()
serializer.save()
assert is_valid is serializer.is_valid()
assert 3 == HeatingParameter.objects.count()
assert 1 == ControlParameter.objects.count()
|
[
"[email protected]"
] | |
07feee452428ecf97bd5edc3add50468a4a465d2
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_309/ch26_2019_08_19_14_12_37_089425.py
|
8dadd9e96c3304269c01917bc7478e247c45840a
|
[] |
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
|
dias = int(input("dias:"))
horas = int(input("horas:"))
minutos = int(input("minutos:"))
segundos = int(input("segundos:"))
print((dias*86.400 + horas*3.600 + minutos*60 + segundos))
|
[
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.