blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 616 | 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 777 values | visit_date timestamp[us]date 2015-08-06 10:31:46 2023-09-06 10:44:38 | revision_date timestamp[us]date 1970-01-01 02:38:32 2037-05-03 13:00:00 | committer_date timestamp[us]date 1970-01-01 02:38:32 2023-09-06 01:08:06 | github_id int64 4.92k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-04 01:52:49 2023-09-14 21:59:50 ⌀ | gha_created_at timestamp[us]date 2008-05-22 07:58:19 2023-08-21 12:35:19 ⌀ | gha_language stringclasses 149 values | src_encoding stringclasses 26 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 3 10.2M | extension stringclasses 188 values | content stringlengths 3 10.2M | authors listlengths 1 1 | author_id stringlengths 1 132 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0722c3f10d8375fc61deb3496915dc5b7d77272f | cef8e528087eeb0ece37bb908ffea7cf81ade0db | /tp2.py | 50cfce313755a1f4d1eaea18bbb02fb979cbd83c | [] | no_license | ashrafulemon/python | f03ef07c77885bd00e73674e8767796c9bcac058 | 5d257288a52195500cf1f6b5cc1e017dae0fdcc0 | refs/heads/main | 2023-01-31T11:08:17.985674 | 2020-12-16T14:59:39 | 2020-12-16T14:59:39 | 322,011,688 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 279 | py | # 11. basic syntax
# 12. identifiers
# 13. keywords
# 14.lines and indentation
# 15. multiline statements
# 19.command line argument
import sys
print("number arg",len(sys.argv),"argument")
print("ar list ",str(sys.argv))
x=int(sys.argv[1])
y=int(sys.argv[2])
z=x+y
print(x,y,z) | [
"emon118.bd@gmail.com"
] | emon118.bd@gmail.com |
30f2d70ef4d8c8ff6ec88003d1820c4e03b22fe7 | b3f40953c1876f5916a2dbd2d7b9903a635e512e | /Dojo_Python/Django_Level_2/dojo_secrets/apps/secrets/migrations/0006_auto_20170227_2020.py | 135d75a24c6fc12637b6702c966810ef92428ab4 | [] | no_license | rudietuesdays/dojo_python | c9d9907096995d6e247b6b7732a908ece246b466 | 5e1fd46c45c90dfcd046f0fe922c64f96625a6c0 | refs/heads/master | 2021-01-11T13:28:56.029473 | 2017-03-07T02:49:48 | 2017-03-07T02:49:48 | 81,473,184 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 445 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-28 01:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('secrets', '0005_secret_liked'),
]
operations = [
migrations.AlterField(
model_name='liked',
name='liked',
field=models.BooleanField(default=True),
),
]
| [
"amanda.gaines@gmail.com"
] | amanda.gaines@gmail.com |
fee337d6bdd75a68b697954d025a3b015ea33b3f | 87ddcf61c2faaaa795b9c25af334a76018337f62 | /frictionless/formats/sql/adapter.py | 5f49b7b4b5ee8c675554de78cbb65104b38cb5dd | [
"MIT"
] | permissive | frictionlessdata/frictionless-py | 17d663ad34c18964113c97e4d657004610fe0df0 | 740319edeee58f12cc6956a53356f3065ff18cbb | refs/heads/main | 2023-08-26T16:24:25.353929 | 2023-08-04T07:55:37 | 2023-08-04T07:55:37 | 28,409,905 | 295 | 79 | MIT | 2023-09-04T05:01:33 | 2014-12-23T17:11:11 | Python | UTF-8 | Python | false | false | 6,870 | py | from __future__ import annotations
import re
from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional
from ... import models
from ...package import Package
from ...platform import platform
from ...resource import Resource
from ...system import Adapter
from . import settings
from .control import SqlControl
from .mapper import SqlMapper
if TYPE_CHECKING:
from sqlalchemy import MetaData, Table
from sqlalchemy.engine import Engine
from ...report import Report
from ...resources import TableResource
from ...schema import Schema
from ...table import IRowStream, Row
class SqlAdapter(Adapter):
"""Read and write data from/to SQL database"""
engine: Engine
control: SqlControl
mapper: SqlMapper
metadata: MetaData
def __init__(self, engine: Engine, *, control: Optional[SqlControl] = None):
sa = platform.sqlalchemy
self.engine = engine
self.control = control or SqlControl()
self.mapper = SqlMapper(self.engine.dialect.name)
with self.engine.begin() as conn:
# It will fail silently if this function already exists
if self.engine.dialect.name.startswith("sqlite"):
conn.connection.create_function("REGEXP", 2, regexp) # type: ignore
self.metadata = sa.MetaData(schema=self.control.namespace)
self.metadata.reflect(conn, views=True)
# Delete
def delete_resource(self, table_name: str) -> None:
with self.engine.begin() as conn:
table = self.metadata.tables[table_name]
self.metadata.drop_all(conn, tables=[table])
# Read
def read_package(self) -> Package:
package = Package(resources=[])
for table in self.metadata.sorted_tables:
name = str(table.name)
control = SqlControl(table=name)
path = self.engine.url.render_as_string(hide_password=False)
schema = self.mapper.read_schema(table)
resource = Resource(path, name=name, schema=schema, control=control)
package.add_resource(resource)
return package
def read_schema(self, table_name: str) -> Schema:
table = self.metadata.tables[table_name]
return self.mapper.read_schema(table, with_metadata=self.control.with_metadata)
def read_cell_stream(self, control: SqlControl) -> Generator[List[Any], None, None]:
sa = platform.sqlalchemy
table = self.metadata.tables[control.table] # type: ignore
with self.engine.begin() as conn:
# Prepare columns
columns = table.c
if self.control.with_metadata:
columns = [
column
for column in table.c
if column.name not in settings.METADATA_IDENTIFIERS
]
# Prepare query
# Streaming could be not working for some backends:
# http://docs.sqlalchemy.org/en/latest/core/connections.html
query = sa.select(*columns).execution_options(stream_results=True)
if control.order_by:
query = query.order_by(sa.text(control.order_by))
if control.where:
query = query.where(sa.text(control.where))
# Stream cells
result = conn.execute(query)
yield list(result.keys())
for item in result:
cells = list(item)
yield cells
# Write
def write_package(self, package: Package):
with self.engine.begin() as conn:
tables: List[Table] = []
for res in package.resources:
assert res.name
table = self.mapper.write_schema(res.schema, table_name=res.name)
table = table.to_metadata(self.metadata)
tables.append(table)
self.metadata.create_all(conn, tables=tables)
for table in self.metadata.sorted_tables:
if package.has_table_resource(table.name):
resource = package.get_table_resource(table.name)
with resource:
self.write_row_stream(resource.row_stream, table_name=table.name)
return models.PublishResult(
url=self.engine.url.render_as_string(hide_password=True),
context=dict(engine=self.engine),
)
def write_schema(
self,
schema: Schema,
*,
table_name: str,
force: bool = False,
with_metadata: bool = False,
) -> None:
with self.engine.begin() as conn:
if force:
existing_table = self.metadata.tables.get(table_name)
if existing_table is not None:
self.metadata.drop_all(conn, tables=[existing_table])
self.metadata.remove(existing_table)
table = self.mapper.write_schema(
schema, table_name=table_name, with_metadata=with_metadata
)
table = table.to_metadata(self.metadata)
self.metadata.create_all(conn, tables=[table])
def write_row_stream(
self,
row_stream: IRowStream,
*,
table_name: str,
on_row: Optional[Callable[[Row], None]] = None,
) -> None:
sa = platform.sqlalchemy
with self.engine.begin() as conn:
buffer: List[Dict[str, Any]] = []
table = self.metadata.tables[table_name]
for row in row_stream:
buffer.append(self.mapper.write_row(row))
if len(buffer) > settings.BUFFER_SIZE:
conn.execute(sa.insert(table), buffer)
buffer.clear()
on_row(row) if on_row else None
if len(buffer):
conn.execute(sa.insert(table), buffer)
def write_resource_with_metadata(
self,
resource: TableResource,
*,
table_name: str,
on_row: Optional[Callable[[Row], None]] = None,
) -> Report:
sa = platform.sqlalchemy
with self.engine.begin() as conn:
# Write row
def process_row(row: Row):
buffer.append(self.mapper.write_row(row, with_metadata=True))
if len(buffer) > settings.BUFFER_SIZE:
conn.execute(sa.insert(table), buffer)
buffer.clear()
on_row(row) if on_row else None
# Validate/iterate
buffer: List[Dict[str, Any]] = []
table = self.metadata.tables[table_name]
report = resource.validate(on_row=process_row)
if len(buffer):
conn.execute(sa.insert(table), buffer)
return report
# Internal
def regexp(expr: str, item: str):
reg = re.compile(expr)
return reg.search(item) is not None
| [
"noreply@github.com"
] | frictionlessdata.noreply@github.com |
828c6edc99064b737f2531777d5caca2b67c08a4 | 2057ba21d3cfc17c88692c62b35e9c1697bbd720 | /digit_string.py | 3de66a0d9c558e84f386d48ddbee0ebe16948a02 | [] | no_license | crobil/project | bd35bce5e1e57c72dc7ac7747b0f646c2331f78b | 6f91eda5c961893a67a0b8ced08304e07e184a84 | refs/heads/master | 2020-03-07T08:44:03.205807 | 2018-06-08T08:57:13 | 2018-06-08T08:57:13 | 124,166,946 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 367 | py | def DashInsert(input):
res = ''
for idx, var in enumerate(input):
if idx == 0:
res += '%s' % (var)
elif (int(var) % 2 == int(input[idx-1]) % 2) and int(var) % 2 == 1:
res += '-%s' % (var)
elif (int(var) % 2 == int(input[idx-1]) % 2) and int(var) % 2 == 0:
res += '+%s' % (var)
else:
res += '%s' % (var)
return res
print DashInsert('4546793')
| [
"root@localhost.localdomain"
] | root@localhost.localdomain |
c6aa63ffe81952ad736edec1545d368a4a989eec | e2f0806ca1cdd887ea40d050a19fa2710427bd38 | /기본 문제/03주차_정렬/2750_수 정렬하기/강승훈.py | 44cb4a0940575efcd28ce0ca7b4fc870ebdb5276 | [] | no_license | JY-Dev/AlgorithmStudy-1 | 001f94d80097c850c79eeb2bc86971a01aa5bd5d | 2ad1df0fd65c72a6f6d1feeba09f889000ff8c15 | refs/heads/main | 2023-08-21T18:38:18.235994 | 2021-09-28T07:07:11 | 2021-09-28T07:07:11 | 406,208,087 | 1 | 0 | null | 2021-09-14T03:14:32 | 2021-09-14T03:14:31 | null | UTF-8 | Python | false | false | 604 | py | from sys import stdin
# 입력
n = int(stdin.readline())
arr = [int(stdin.readline()) for _ in range(n)]
# 버블정렬
for i in range(n-1): # 조건식에서 +1 시키기 때문에, n-1 까지만 반복.
for j in range(n-1):
if arr[j] > arr[j+1]: # 만약 현재 요소가, 바로 다음 요소보다 크면, 두개의 위치를 바꿔줌.
tmp_1 = arr[j]; tmp_2 = arr[j+1] # tmp_1에 앞에 요소, tmp_2에 바로 다음 요소를 저장.
arr[j] = tmp_2; arr[j+1] = tmp_1 # 그리고 반대로 다시 재할당 시킴.
# 출력
for crnt in arr:
print(crnt)
| [
"noreply@github.com"
] | JY-Dev.noreply@github.com |
2d16134229da9c97663682df26d2177427bf90f0 | de725b742e69f38318c04cd44ac970e7135857a5 | /assets/myauth.py | 7af5b88d8abcaff8d9dd6b4c10a35cc8225f7d33 | [] | no_license | haochenxiao666/itelftool | e5c0811b48e01d0eeff13d15d33b89960091960a | 8558dce6d97e7443c95513aa1389910c3902043f | refs/heads/master | 2020-04-14T22:55:46.732111 | 2018-10-18T09:00:44 | 2018-10-18T09:00:44 | 164,183,750 | 1 | 0 | null | 2019-01-05T05:05:32 | 2019-01-05T05:05:31 | null | UTF-8 | Python | false | false | 4,431 | py | #!/usr/bin/env python
#coding:utf-8
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser,Group,PermissionsMixin
)
import django
from django import utils
from accounts.models import RoleList
class UserManager(BaseUserManager):
def create_user(self, email, name, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
name=name,
#token=token,
#department=department,
#tel=tel,
#memo=memo,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, name ,password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(email,
password=password,
name=name,
#token=token,
#department=department,
#tel=tel,
#memo=memo,
)
user.is_admin = True
user.save(using=self._db)
return user
#class UserProfile(AbstractBaseUser):
class UserProfile(AbstractBaseUser,PermissionsMixin):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
# on_delete=models.SET_NULL,只有当null=True的时候 ,被删除的时候将内容置空
role = models.ForeignKey(RoleList, null=True, blank=True, on_delete=models.SET_NULL)
name = models.CharField(max_length=32)
token = models.CharField(u'token', max_length=128,default=None,blank=True,null=True)
department = models.CharField(u'部门', max_length=32,default=None,blank=True,null=True)
#business_unit = models.ManyToManyField(BusinessUnit)
tel = models.CharField(u'座机', max_length=32,default=None,blank=True,null=True)
mobile = models.CharField(u'手机', max_length=32,default=None,blank=True,null=True)
memo = models.TextField(u'备注', blank=True,null=True,default=None)
date_joined = models.DateTimeField(blank=True, auto_now_add=True)
#valid_begin = models.DateTimeField(blank=True, auto_now=True)
# 秋飞修改
# valid_begin_time = models.DateTimeField(default=django.utils.timezone.now)
valid_begin_time = models.DateTimeField(default=utils.timezone.now)
valid_end_time = models.DateTimeField(blank=True,null=True)
groups = models.ManyToManyField
USERNAME_FIELD = 'email'
#REQUIRED_FIELDS = ['name','token','department','tel','mobile','memo']
REQUIRED_FIELDS = ['name']
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __str__(self): # __unicode__ on Python 2
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_perms(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
class Meta:
verbose_name = u'用户信息'
verbose_name_plural = u"用户信息"
def __unicode__(self):
return self.name
objects = UserManager()
class LoginRecord(models.Model):
name = models.ForeignKey(
UserProfile,
null=False,
blank=False,
verbose_name=u"登录用户"
)
logintime = models.DateTimeField(u'登录时间', auto_now_add=True)
loginsource = models.GenericIPAddressField(u'登录来源IP', blank=True, null=True)
| [
"420521738@qq.com"
] | 420521738@qq.com |
79622b9129c74f9d947d06ef504aa39e5b5e0023 | 09e5cfe06e437989a2ccf2aeecb9c73eb998a36c | /modules/cctbx_project/cctbx/source_generators/eltbx/generate_henke_cpp.py | 7bae6088b98f86b7eb183ef1711372e11162e216 | [
"BSD-3-Clause-LBNL",
"BSD-3-Clause"
] | permissive | jorgediazjr/dials-dev20191018 | b81b19653624cee39207b7cefb8dfcb2e99b79eb | 77d66c719b5746f37af51ad593e2941ed6fbba17 | refs/heads/master | 2020-08-21T02:48:54.719532 | 2020-01-25T01:41:37 | 2020-01-25T01:41:37 | 216,089,955 | 0 | 1 | BSD-3-Clause | 2020-01-25T01:41:39 | 2019-10-18T19:03:17 | Python | UTF-8 | Python | false | false | 5,440 | py | from __future__ import absolute_import, division, print_function
from scitbx.source_generators.utils import join_open
from scitbx.source_generators.utils import write_this_is_auto_generated
import libtbx.load_env
import string
import os
from six.moves import range
this = "cctbx.source_generators.eltbx.generate_henke_cpp"
reference_tables_directory = libtbx.env.under_dist(
"cctbx", "reference/henke/tables")
def print_header(f):
write_this_is_auto_generated(f, this)
print("""\
#include <cctbx/eltbx/henke.h>
namespace cctbx { namespace eltbx { namespace henke {
""", file=f)
def print_ftp_info(f):
print("""\
/*
Henke Tables
The original data can be found at:
ftp://grace.lbl.gov/pub/sf/
From ftp://grace.lbl.gov/pub/sf/read.me:
Low-Energy X-ray Interaction Coefficients:
Photoabsorption, Scattering, and Reflection
E = 30-30,000 eV, Z = 1-92
B. L. Henke, E. M. Gullikson, and J. C. Davis
Center for X-Ray Optics, 2-400
Lawrence Berkeley Laboratory
Berkeley, California 94720
Reference: B. L. Henke, E. M. Gullikson, and J. C. Davis,
Atomic Data and Nuclear Data Tables Vol. 54 No. 2 (July 1993).
*/
""", file=f)
def collect_tables():
nff_files = []
for file in os.listdir(reference_tables_directory):
fn = file.lower().capitalize()
if (fn[-4:] == ".nff"): nff_files.append(file)
tables = [0] * 120
for file in nff_files:
f = join_open(reference_tables_directory, file, "r")
header = f.readline()
table = f.readlines()
f.close()
Symbol = header[1:3].strip()
Z = int(header[7:9])
assert len(Symbol) > 0
assert Symbol[0] in 'abcdefghijklmnopqrstuvwxyz'
assert Symbol[-1] in 'abcdefghijklmnopqrstuvwxyz'
assert Z > 0 and Z < len(tables)
assert tables[Z] == 0
Symbol = Symbol.capitalize()
tables[Z] = (Symbol, table)
Z = tables[1:].index(0) + 1
rest = tables[Z:]
assert rest == [0] * len(rest)
tables = tables[:Z]
return tables
def print_table_block(f, tables, Z_begin, Z_end, define_noval=0):
print("namespace table_data {", file=f)
print(file=f)
print("using anomalous::e_fp_fdp;", file=f)
print(file=f)
# Visual C++ 7.0 compilation is very slow with define_noval=1
if (define_noval): print("#define NOVAL fp_fdp_undefined", file=f)
for Z in range(Z_begin, Z_end):
tab = tables[Z]
print("e_fp_fdp " + tab[0].lower() \
+ "[] = { /* Z = " + str(Z) + " */", file=f)
for line in tab[1]:
flds = line.split()
assert len(flds) == 3
if (define_noval and flds[1] == "-9999.00"): flds[1] = "NOVAL"
print("{%s, %s, %s}," % tuple(flds), file=f)
print("{0, 0, 0}", file=f)
print("};", file=f)
print(file=f)
if (define_noval):
print("#undef NOVAL", file=f)
print(file=f)
print("} // namespace table_data", file=f)
print(file=f)
print("}}} // namespace cctbx::eltbx::henke", file=f)
def print_henke_cpp(f, tables):
print("namespace table_data {", file=f)
print(file=f)
print("using anomalous::e_fp_fdp;", file=f)
print(file=f)
for tab in tables[1:]:
print("extern e_fp_fdp " + tab[0].lower() + "[];", file=f)
print(file=f)
print("static const anomalous::label_z_e_fp_fdp all[] = {", file=f)
i = 0
for tab in tables[1:]:
i += 1
print("{\"" + tab[0] + "\", " + str(i) + ", " + tab[0].lower() + "},", file=f)
print("{0, 0, 0}", file=f)
print("};", file=f)
print("""
} // namespace table_data
table::table(
std::string const& label,
bool exact,
bool exception_if_no_match)
{
std::string work_label = basic::strip_label(label, exact);
label_z_e_fp_fdp_ = anomalous::find_entry(
table_data::all, work_label, exact, exception_if_no_match);
}
fp_fdp
table::at_ev(double energy) const
{
fp_fdp raw = anomalous::interpolate(label_z_e_fp_fdp_, energy);
if (!raw.is_valid_fp()) return raw;
// subtract the number of electrons
return fp_fdp(raw.fp() - label_z_e_fp_fdp_->z, raw.fdp());
}
table_iterator::table_iterator()
:
current_("H", true)
{}
table
table_iterator::next()
{
table result = current_;
if (current_.is_valid()) current_.label_z_e_fp_fdp_++;
return result;
}
}}} // namespace cctbx::eltbx::henke""", file=f)
def collect_points(lines):
points = []
for line in lines:
points.append(line.split()[0])
return points
def collect_tab_points(tables):
tab_points = []
for tab in tables[1:]:
tab_points.append(collect_points(tab[1]))
return tab_points
def compare_points(tables):
tab_points = collect_tab_points(tables)
for i in range(len(tab_points)-1):
for j in range(i+1, len(tab_points)):
if (tab_points[i] == tab_points[j]):
print("points %d==%d" % (i+1,j+1))
def run(target_dir):
tables = collect_tables()
compare_points(tables) # establish that each list of data points is unique
f = join_open(target_dir, "henke.cpp", "w")
print_header(f)
print_ftp_info(f)
print_henke_cpp(f, tables)
f.close()
Z_block = 12
for Z_begin in range(1, len(tables), Z_block):
Z_end = min(len(tables), Z_begin + Z_block)
f = join_open(
target_dir, "henke_tables_%02d_%02d.cpp" % (Z_begin, Z_end-1), "w")
print_header(f)
print_table_block(f, tables, Z_begin, Z_end)
f.close()
if (__name__ == "__main__"):
run(".")
| [
"jorge7soccer@gmail.com"
] | jorge7soccer@gmail.com |
0d1fc572c58a6bfa42ebe16a77abc85250542703 | 88c1f9ccb62e91d6b0574bcde1043921bdeb0126 | /test_utilities/src/d1_test/test_files.py | 297b4ed0ef73c4895d00055f25c2d0d454ce1cef | [
"Apache-2.0"
] | permissive | jevans97utk/d1_python | 83b8de8780287c655779844f367b9189413da074 | 3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d | refs/heads/master | 2020-05-21T01:16:50.677816 | 2019-04-22T16:09:44 | 2019-04-22T16:09:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,309 | py | #!/usr/bin/env python
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# 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.
"""Utilities for loading test files."""
import codecs
import json
import logging
import os
# Path to the test document root, relative to this file
import d1_common
import d1_common.types
import d1_common.types.dataoneTypes
import d1_common.util
import d1_common.utils.filesystem
def get_abs_test_file_path(rel_path):
return os.path.join(d1_common.utils.filesystem.abs_path('./test_docs'), rel_path)
def load_bin(rel_path):
bin_path = get_abs_test_file_path(rel_path)
with open(bin_path, 'rb') as f:
return f.read()
def load_utf8_to_str(rel_path):
"""Load file, decode from UTF-8 and return as str."""
logging.debug('Loading test file. rel_path="{}"'.format(rel_path))
utf8_path = get_abs_test_file_path(rel_path)
with codecs.open(utf8_path, encoding='utf-8', mode='r') as f:
unicode_str = f.read()
return unicode_str
def load_xml_to_pyxb(filename):
return d1_common.types.dataoneTypes.CreateFromDocument(load_xml_to_str(filename))
def load_xml_to_str(filename):
return load_utf8_to_str(os.path.join('xml', filename))
def load_json(filename):
return json.loads(load_utf8_to_str(os.path.join('json', filename)))
def load_cert(filename):
return load_bin(os.path.join('cert', filename))
def load_jwt(filename):
return load_bin(os.path.join('jwt', filename))
def save(obj_str, rel_path, encoding='utf-8'):
with open(get_abs_test_file_path(rel_path), 'w', encoding=encoding) as f:
return f.write(obj_str)
| [
"git@dahlsys.com"
] | git@dahlsys.com |
61fd076ee0bec381a73beaf4c8fc9e62f16688e9 | 8606267410dabfeacb4b7ff285a8d2250c139acc | /store/views/home.py | 2a799439f55833dad0516d1fccc5b42d0acb7181 | [] | no_license | Taraltinu/chopping-Site | a5e6f6eeeecb4fef92f90770a3c2493eca0f0bde | 1b722d53de1baaa5780701416f78dab62ef7d057 | refs/heads/master | 2022-12-20T07:06:16.602476 | 2020-10-02T18:07:31 | 2020-10-02T18:07:31 | 300,697,693 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,385 | py | from django.shortcuts import render,redirect
from store.models import Product,Category,Costomer
from django.views import View
class Home(View):
def post(self,request):
Product = request.POST.get('product')
remove = request.POST.get('remove')
cart = request.session.get('cart')
if cart:
quantity=cart.get(Product)
if quantity:
if remove:
if quantity <=1:
cart.pop(Product)
else:
cart[Product] = quantity-1
else:
cart[Product] = quantity+1
else:
cart[Product] = 1
else:
cart = {}
cart[Product]=1
request.session['cart'] = cart
return redirect('/')
def get(self, request):
cart = request.session.get('cart')
if not cart:
request.session['cart'] = {}
products= None
category = Category.get_all_category()
categoryID = request.GET.get('category')
if categoryID:
products = Product.get_all_product_by_category_id(categoryID)
else:
products = Product.get_all_products()
data = {}
data['product']=products
data['category']=category
return render(request,'store/index.html',data) | [
"tinu1316@gmail.com"
] | tinu1316@gmail.com |
c34ed3439f3d7661d4b7129f79fe9f80006dc229 | 7087a5dd1772c9456f098bc024a894dcaeef5432 | /calbin/build/calkube/kubernetes-6.0.0_snapshot-py2.7.egg/kubernetes/client/models/v1beta1_volume_attachment_status.py | dd12c23922f449d21303a3a99e4861fc7618ae31 | [] | no_license | santhoshchami/kubecctl-python | 5be7a5a17cc6f08ec717b3eb1c11719ef7653aba | cd45af465e25b0799d65c573e841e2acb983ee68 | refs/heads/master | 2021-06-23T11:00:43.615062 | 2019-07-10T16:57:06 | 2019-07-10T16:57:06 | 145,669,246 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,370 | py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.10.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V1beta1VolumeAttachmentStatus(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'attach_error': 'V1beta1VolumeError',
'attached': 'bool',
'attachment_metadata': 'dict(str, str)',
'detach_error': 'V1beta1VolumeError'
}
attribute_map = {
'attach_error': 'attachError',
'attached': 'attached',
'attachment_metadata': 'attachmentMetadata',
'detach_error': 'detachError'
}
def __init__(self, attach_error=None, attached=None, attachment_metadata=None, detach_error=None):
"""
V1beta1VolumeAttachmentStatus - a model defined in Swagger
"""
self._attach_error = None
self._attached = None
self._attachment_metadata = None
self._detach_error = None
self.discriminator = None
if attach_error is not None:
self.attach_error = attach_error
self.attached = attached
if attachment_metadata is not None:
self.attachment_metadata = attachment_metadata
if detach_error is not None:
self.detach_error = detach_error
@property
def attach_error(self):
"""
Gets the attach_error of this V1beta1VolumeAttachmentStatus.
The last error encountered during attach operation, if any. This field must only be set by the entity completing the attach operation, i.e. the external-attacher.
:return: The attach_error of this V1beta1VolumeAttachmentStatus.
:rtype: V1beta1VolumeError
"""
return self._attach_error
@attach_error.setter
def attach_error(self, attach_error):
"""
Sets the attach_error of this V1beta1VolumeAttachmentStatus.
The last error encountered during attach operation, if any. This field must only be set by the entity completing the attach operation, i.e. the external-attacher.
:param attach_error: The attach_error of this V1beta1VolumeAttachmentStatus.
:type: V1beta1VolumeError
"""
self._attach_error = attach_error
@property
def attached(self):
"""
Gets the attached of this V1beta1VolumeAttachmentStatus.
Indicates the volume is successfully attached. This field must only be set by the entity completing the attach operation, i.e. the external-attacher.
:return: The attached of this V1beta1VolumeAttachmentStatus.
:rtype: bool
"""
return self._attached
@attached.setter
def attached(self, attached):
"""
Sets the attached of this V1beta1VolumeAttachmentStatus.
Indicates the volume is successfully attached. This field must only be set by the entity completing the attach operation, i.e. the external-attacher.
:param attached: The attached of this V1beta1VolumeAttachmentStatus.
:type: bool
"""
if attached is None:
raise ValueError("Invalid value for `attached`, must not be `None`")
self._attached = attached
@property
def attachment_metadata(self):
"""
Gets the attachment_metadata of this V1beta1VolumeAttachmentStatus.
Upon successful attach, this field is populated with any information returned by the attach operation that must be passed into subsequent WaitForAttach or Mount calls. This field must only be set by the entity completing the attach operation, i.e. the external-attacher.
:return: The attachment_metadata of this V1beta1VolumeAttachmentStatus.
:rtype: dict(str, str)
"""
return self._attachment_metadata
@attachment_metadata.setter
def attachment_metadata(self, attachment_metadata):
"""
Sets the attachment_metadata of this V1beta1VolumeAttachmentStatus.
Upon successful attach, this field is populated with any information returned by the attach operation that must be passed into subsequent WaitForAttach or Mount calls. This field must only be set by the entity completing the attach operation, i.e. the external-attacher.
:param attachment_metadata: The attachment_metadata of this V1beta1VolumeAttachmentStatus.
:type: dict(str, str)
"""
self._attachment_metadata = attachment_metadata
@property
def detach_error(self):
"""
Gets the detach_error of this V1beta1VolumeAttachmentStatus.
The last error encountered during detach operation, if any. This field must only be set by the entity completing the detach operation, i.e. the external-attacher.
:return: The detach_error of this V1beta1VolumeAttachmentStatus.
:rtype: V1beta1VolumeError
"""
return self._detach_error
@detach_error.setter
def detach_error(self, detach_error):
"""
Sets the detach_error of this V1beta1VolumeAttachmentStatus.
The last error encountered during detach operation, if any. This field must only be set by the entity completing the detach operation, i.e. the external-attacher.
:param detach_error: The detach_error of this V1beta1VolumeAttachmentStatus.
:type: V1beta1VolumeError
"""
self._detach_error = detach_error
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return 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, V1beta1VolumeAttachmentStatus):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| [
"root@kube-node02.local"
] | root@kube-node02.local |
02bc16b5afd184593492d3693b0f3f675d16e337 | ababf0e8ab02391321ce71e34ac7a57c96a2838f | /pytorch_disco_recovery/exp_carla_pipe.py | c567650d4db27ed5056b749fffe8aeca91899e12 | [] | no_license | kimsoohwan/CoCoNets | e4084b4636c3aa5efaa0ed7da87767278c6c452e | 4ad0c088ebcb5cacfd02aad60e9ccd3dd71292a4 | refs/heads/main | 2023-05-03T09:28:59.752793 | 2021-05-17T21:05:33 | 2021-05-17T21:05:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 15,772 | py | from exp_base import *
############## choose an experiment ##############
current = 'builder'
# current = 'tester'
mod = '"ful00"' # reset exp list and logs
mod = '"ful01"' # show vis clean of zeroth hypothesis
mod = '"ful02"' # create func for vis
mod = '"ful03"' # collapse past
mod = '"ful04"' #
mod = '"ful05"' # refresh future
mod = '"ful06"' # print hypotheeses
mod = '"ful07"' # better collapse
mod = '"ful08"' # put things into camR0
mod = '"ful09"' # only show 30 steps, to eliminate the red dot < good
mod = '"ful10"' # rename s to step
mod = '"ful11"' # dummy loop; always select 1
mod = '"ful12"' # show gif
mod = '"ful13"' # S_cap = 30
mod = '"ful14"' # simplify
mod = '"ful15"' # get yaws
mod = '"ful16"' # convert to boxes then lrts
mod = '"ful17"' # put len before rot
mod = '"ful18"' # extract right len
mod = '"ful19"' # subtract pi/2
mod = '"ful20"' # show gt too, to see if the alignment is right
mod = '"ful21"' # smooth the xyzs a bit < error
mod = '"ful22"' # smooth=1
mod = '"ful23"' # smooth=2
mod = '"ful24"' # show all k trajs
mod = '"ful25"' # -arctan - np.pi/2.
mod = '"ful26"' # make it begin straight, by yaw = yaw * (1.0-np.exp(-s))
mod = '"ful27"' # make it begin straight, using angle0
mod = '"ful28"' # -arctan+np.pi/2
mod = '"ful29"' # self.S_cap = 5
mod = '"ful30"' # self.S_cap = 20, but only show every other step in the bev box
mod = '"ful31"' # smooth=3 < ok good job
mod = '"ful32"' # moved util to utils_geom
mod = '"ful33"' # hypotheses are lrts; show the zeroth one
mod = '"ful34"' # do collapse and refresh
mod = '"ful35"' # summ one
mod = '"ful36"' # show boxes
mod = '"ful37"' # eliminate that averaging/smoothing step, since raw angles are not really available here
mod = '"ful38"' # use past to fuel the future
mod = '"ful39"' # use the latest xyz
mod = '"ful40"' # slightly cleaner impl
mod = '"ful41"' # visualize the trajs as boxes, on the last step i guess
mod = '"ful42"' # visualize the trajs as boxes, on the zeroth step
mod = '"ful43"' # do not collapse/refresh
mod = '"ful44"' # only collapse on step0, with the
mod = '"ful45"' # if conf>0.1, collapse with this
mod = '"ful46"' # S_cap = 40
mod = '"ful47"' # use gt position to centralize the vis
mod = '"ful48"' # 0.05 threhs
mod = '"ful49"' # visualize each traj's boxes
mod = '"ful50"' # show the the hypo boxes on each step within the main vis
mod = '"ful51"' # JUST show the boxes
mod = '"ful52"' # JUST show the boxes proper
mod = '"ful53"' # S_cap = 60
mod = '"ful54"' # show boxes on top of trajs
mod = '"ful55"' # avoid singularity
mod = '"ful56"' # thresh 0.03
mod = '"ful57"' # show gt box under the others
mod = '"ful58"' # thresh 0.05 again
mod = '"ful59"' # show the scores in bev
mod = '"ful60"' # compute match/conf of each try
mod = '"ful61"' # eliminate the confidence in the summ, since it's confusing; S_cap = 80
mod = '"ful62"' # only show traj_g up to S_cap
mod = '"ful63"' # show conf of the best guy
mod = '"ful64"' # set end of trajs; use .3f for the scores
mod = '"ful65"' # don't set conf to 1.0 after collapse
mod = '"ful66"' # set hyp0 to be zero mot
mod = '"ful67"' # use color0 for gt
mod = '"ful68"' # use color19
mod = '"ful69"' # use color1 for
mod = '"ful70"' # use 2: for e
mod = '"ful71"' # 20 iters
mod = '"ful72"' # S_cap=10, just to see pers
mod = '"ful73"' # fix shape issue
mod = '"ful74"' # show box scores; fix return isue
mod = '"ful75"' # S_cap = 80; 5 iters; no shuf
mod = '"ful76"' # conf_thresh = 0.04
mod = '"ful77"' # no shuf
mod = '"ful78"' # replace each hypothesis with the matcher's best answer
mod = '"ful79"' # in topleft corner write the frame number
mod = '"ful80"' # cap 10 for see
mod = '"ful81"' # cap 10 for see
mod = '"ful82"' # 0,0
mod = '"ful83"' # write it in not black, at 20,10
mod = '"ful84"' # 10,20
mod = '"ful85"' # S_cap = 90
mod = '"ful86"' # put the frame number in white
mod = '"ful87"' # cap 10 for a sec
mod = '"ful88"' # cap 90
mod = '"ful89"' # 5,20
mod = '"ful90"' # cap 90
mod = '"ful91"' # re-run, just to see
mod = '"ful92"' # pret share82, so that i have motionreg happening
mod = '"ful93"' # S_test=30, to speed up
mod = '"ful94"' # S_test=30 for real
mod = '"ful95"' # confnet, pret with 30k 04_s2_m256x128x256_z64x64x64_1e-4_F3f_d64_Mf_c1_r.1_C_c1_tals90i1t_tals90i1v_conf37
mod = '"ful96"' # print more;
mod = '"ful97"' # thresh 0.8
mod = '"ful98"' # thresh 0.7
mod = '"ful99"' # an data; S_cap = 60
mod = '"ful100"' # ap data
mod = '"ful101"' # skip the track/whatever
mod = '"ful102"' # show the gt boxes
mod = '"ful103"' # use correct pix_T_cam
mod = '"ful104"' # show 90 frames
mod = '"ful105"' # 60 frames; tans60i2a
mod = '"ful106"' # matrix; tap data; S_test = 100; S_cap = 100;
mod = '"pip00"' # pret 20k 02_s2_m256x128x256_z64x64x64_1e-3_F3f_d64_Mf_c1_r.1_Mrd_p4_f26_k5_e100_w.001_taps100i2tb_taps100i2vce_mat28 < 121s
mod = '"pip01"' # elim rgb_camXs vis < ok 78s; those summs are expensive
mod = '"pip02"' # really run teh model
mod = '"pip03"' # return early; summ every second step < ok 46s
mod = '"pip04"' # return early; summ every second step < ok 46s
mod = '"pip05"' # really run the mdoel
mod = '"pip06"' # clean up
mod = '"pip07"' # val set
mod = '"pip08"' # again
mod = '"pip09"' # show full traj
mod = '"pip10"' # use 1.0 scores for past
mod = '"pip11"' # use the ans to update the hyp for the next timestep, even if not past conf thresh
mod = '"pip12"' # print more, because i am confused
mod = '"pip13"' # show past boxes UNDER the hyps
mod = '"pip14"' # only update the ans for hyp0
mod = '"pip15"' # shuffle, to see more
mod = '"pip16"' # update hypothesis0 greedily
mod = '"pip17"' # eliminate that confidence hack
mod = '"pip18"' # again, on this new day
mod = '"pip19"' # no shuf
mod = '"pip20"' # pret mat28
mod = '"pip21"' # pret 60k mat30
mod = '"pip22"' # avoid updating 0 with the other guys
mod = '"pip23"' # same but: do NOT use multiple hypotheses; attempt to use basic matchnet < ok looks fine
mod = '"pip24"' # evaluate
mod = '"pip25"' # export ious and vis; S_cap = 30, for quicker bug
mod = '"pip26"' # S_cap = 100
mod = '"pip27"' # use all hypotheses # 599 seconds
mod = '"pip28"' # do not vis so much # 180 seconds. ok good.
mod = '"pip29"' # pret 20k 04_s2_m256x128x256_z64x64x64_1e-3_F3f_d64_Mf_c1_r.1_Mrd_p4_f36_k5_e1_w.001_taps100i2tb_taps100i2vce_mat32
mod = '"pip30"' # do vis
mod = '"pip31"' # conf thresh 0.5
mod = '"pip32"' # pret instead 26k 04_s2_m256x128x256_z64x64x64_1e-3_F3f_d64_Mf_c1_r.1_Mrd_p4_f36_k5_e100_w.001_taps100i2tb_taps100i2vce_mat32 < ok, a bit better
mod = '"pip33"' # 20 iters; vis every 5
mod = '"pip34"' # pret 30k instead of 26k; no vis
mod = '"pip35"' # K=1
mod = '"pip36"' # replicate pip33, by pret 26k and allowing K
mod = '"pip37"' # 50 iters
mod = '"pip38"' # conf = 0.7 instead of 0.5; log10 < yes, this is slightly better than using 0.5
mod = '"pip39"' # conf = 0.5
mod = '"pip40"' # pret 50k 04_s2_m256x128x256_z64x64x64_1e-3_F3f_d64_Mf_c1_r.1_Mrd_p4_f36_k5_e100_w.001_taps100i2tb_taps100i2vce_mat32
mod = '"pip41"' # K = 1; conf = 0.7
mod = '"pip42"' # back to 26k ckpt; full K; ONLY update lrt for k==0 < much worse actually
mod = '"pip43"' # update on each iter (reverting pip42); save time, with thresh 0.5 on the centroid diff
mod = '"pip44"' # thresh 0.1 on the centroid diff
mod = '"pip45"' # thresh 0.2 on the centroid diff
mod = '"pip46"' # thresh 0.5 on centroid diff AND 3 degrees thresh for rot diff
mod = '"pip47"' # thresh 0.5 on centroid diff AND 6 degrees thresh for rot diff < ok looks fine
mod = '"pip48"' # add empty template strat
mod = '"pip49"' # add template tool
mod = '"pip50"' # add the first three good steps as templates
mod = '"pip51"' # refresh templates according to conf
mod = '"pip52"' # just 2 templates
mod = '"pip53"' # 4 templates; print more < turns out slightly worse than 3 templates
mod = '"pip54"' # 3 templates; show the updates in tb < winner. this should be equivalent to pip51, but it's not.'
mod = '"pip55"' # better summs; log5
mod = '"pip56"' # only export vis if log_this
mod = '"pip57"' # show gt at least
mod = '"pip58"' # compute careful lrt
mod = '"pip59"' # more dat
mod = '"pip60"' # more dat
mod = '"pip61"' # packed up the box parser
############## define experiments ##############
exps['builder'] = [
'carla_pipe', # mode
# 'carla_tag_t_tce_vce_data', # dataset
# 'carla_tag_vce_data', # dataset
# 'carla_tal_v_data', # dataset
# 'carla_tan_v_data', # dataset
# 'carla_tap_t_data', # dataset
# 'carla_tap_v_data', # dataset
# 'carla_tap_vce_data', # dataset
'carla_taq_a_data', # dataset
'train_on_trainval',
'nearcube_trainvaltest_bounds',
'5_iters',
'pretrained_match',
'pretrained_feat3D',
'pretrained_motionreg',
'pretrained_conf',
'train_feat3D',
'train_motionreg',
'train_match',
'train_conf',
'no_backprop',
'no_shuf',
'B1',
# 'lr4',
'log1',
]
exps['tester'] = [
'carla_pipe', # mode
'carla_tap_vce_data', # dataset
'train_on_trainval',
'nearcube_trainvaltest_bounds',
'50_iters',
'pretrained_match',
'pretrained_feat3D',
'pretrained_motionreg',
'pretrained_conf',
'train_feat3D',
'train_motionreg',
'train_match',
'train_conf',
'frozen_feat3D',
'frozen_match',
'frozen_conf',
'frozen_motionreg',
'do_test',
'do_export_stats',
'do_export_vis',
'no_backprop',
'no_shuf',
'B1',
# 'lr4',
# 'log1',
'log5',
# 'log500',
]
############## group configs ##############
groups['do_test'] = ['do_test = True']
groups['do_export_vis'] = ['do_export_vis = True']
groups['do_export_stats'] = ['do_export_stats = True']
groups['train_motionreg'] = [
'do_motionreg = True',
'motionreg_t_past = 4',
# 'motionreg_t_futu = 26',
'motionreg_t_futu = 36',
'motionreg_num_slots = 5',
# 'motionreg_l1_coeff = 1.0',
# 'motionreg_l2_coeff = 0.1',
# 'motionreg_weak_coeff = 0.0001',
]
groups['train_feat3D'] = [
'do_feat3D = True',
'feat3D_dim = 64',
]
groups['train_match'] = [
'do_match = True',
'match_coeff = 1.0',
'match_r_coeff = 0.1',
]
groups['train_conf'] = [
'do_conf = True',
'conf_coeff = 1.0',
# 'conf_num_replicas = 4',
]
############## datasets ##############
# mem resolution
SIZE = 64
SIZE_val = 64
SIZE_test = 64
# X = int(SIZE*32)
# Y = int(SIZE*4)
# Z = int(SIZE*32)
# Z = SIZE*4
# Y = SIZE*1
# X = SIZE*4
ZZ = 64
ZY = 64
ZX = 64
# ZX = int(SIZE*32)
# ZY = int(SIZE*4)
# ZZ = int(SIZE*32)
# these params need cleaning; also, 3 only works if you do not count occluders
N = 3 # max objects
K = 3 # objects to consider
S = 100
S_val = 100
S_test = 100
H = 128
W = 384
V = 50000
# H and W for proj stuff
PH = int(H/2.0)
PW = int(W/2.0)
# dataset_location = "/data4/carla/processed/npzs"
dataset_location = "/projects/katefgroup/datasets/carla/processed/npzs"
groups['carla_tag_data'] = [
'H = %d' % H,
'W = %d' % W,
'trainset = "tags90i1t"',
'trainset_format = "traj"',
'trainset_consec = True',
'trainset_seqlen = %d' % S,
'valset = "tags90i1v"',
'valset_format = "traj"',
'valset_consec = True',
'valset_seqlen = %d' % S,
'dataset_location = "%s"' % dataset_location,
'dataset_filetype = "npz"'
]
groups['carla_tag_t_tce_vce_data'] = [
'H = %d' % H,
'W = %d' % W,
'trainset = "tags90i1t"',
'trainset_format = "traj"',
'trainset_consec = True',
'trainset_seqlen = %d' % S,
'valset = "tags90i1tce"',
'valset_format = "traj"',
'valset_consec = True',
'valset_seqlen = %d' % S,
'testset = "tags90i1vce"',
'testset_format = "traj"',
'testset_consec = True',
'testset_seqlen = %d' % S,
'dataset_location = "%s"' % dataset_location,
'dataset_filetype = "npz"'
]
groups['carla_tag_vce_data'] = [
'H = %d' % H,
'W = %d' % W,
'testset = "tags90i1vce"',
'testset_format = "traj"',
'testset_consec = True',
'testset_seqlen = %d' % S,
'dataset_location = "%s"' % dataset_location,
'dataset_filetype = "npz"'
]
groups['carla_tal_v_data'] = [
'H = %d' % H,
'W = %d' % W,
'testset = "tals90i1v"',
'testset_format = "traj"',
'testset_consec = True',
'testset_seqlen = %d' % S,
'dataset_location = "%s"' % dataset_location,
'dataset_filetype = "npz"'
]
groups['carla_tan_v_data'] = [
'H = %d' % H,
'W = %d' % W,
'testset = "tans60i2a"',
'testset_format = "traj"',
'testset_consec = True',
'testset_seqlen = %d' % S,
'dataset_location = "%s"' % dataset_location,
'dataset_filetype = "npz"'
]
groups['carla_tap_v_data'] = [
'H = %d' % H,
'W = %d' % W,
'testset = "taps100i2v"',
'testset_format = "traj"',
'testset_consec = True',
'testset_seqlen = %d' % S,
'dataset_location = "%s"' % dataset_location,
'dataset_filetype = "npz"'
]
groups['carla_tap_vce_data'] = [
'H = %d' % H,
'W = %d' % W,
'testset = "taps100i2vce"',
'testset_format = "traj"',
'testset_consec = True',
'testset_seqlen = %d' % S,
'dataset_location = "%s"' % dataset_location,
'dataset_filetype = "npz"'
]
groups['carla_taq_a_data'] = [
'H = %d' % H,
'W = %d' % W,
'testset = "taqs100i2a"',
'testset_format = "traj"',
'testset_consec = True',
'testset_seqlen = %d' % S,
'dataset_location = "%s"' % dataset_location,
'dataset_filetype = "npz"'
]
groups['carla_tap_t_data'] = [
'H = %d' % H,
'W = %d' % W,
'testset = "taps100i2t"',
'testset_format = "traj"',
'testset_consec = True',
'testset_seqlen = %d' % S_test,
'dataset_location = "%s"' % dataset_location,
'dataset_filetype = "npz"'
]
groups['carla_tag_vocc_data'] = [
'H = %d' % H,
'W = %d' % W,
'testset = "tags90i1vocc"',
'testset_format = "traj"',
'testset_consec = True',
'testset_seqlen = %d' % S,
'dataset_location = "%s"' % dataset_location,
'dataset_filetype = "npz"'
]
groups['carla_tag_tce_data'] = [
'H = %d' % H,
'W = %d' % W,
'testset = "tags90i1tce"',
'testset_format = "traj"',
'testset_consec = True',
'testset_seqlen = %d' % S,
'dataset_location = "%s"' % dataset_location,
'dataset_filetype = "npz"'
]
groups['nearcube_trainvaltest_bounds'] = [
'XMIN = -16.0', # right (neg is left)
'XMAX = 16.0', # right
'YMIN = -8.0', # down (neg is up)
'YMAX = 8.0', # down
'ZMIN = -16.0', # forward
'ZMAX = 16.0', # forward
'Z = %d' % (int(SIZE*4)),
'Y = %d' % (int(SIZE*2)),
'X = %d' % (int(SIZE*4)),
'XMIN_val = -16.0', # right (neg is left)
'XMAX_val = 16.0', # right
'YMIN_val = -8.0', # down (neg is up)
'YMAX_val = 8.0', # down
'ZMIN_val = -16.0', # forward
'ZMAX_val = 16.0', # forward
'Z_val = %d' % (int(SIZE_val*4)),
'Y_val = %d' % (int(SIZE_val*2)),
'X_val = %d' % (int(SIZE_val*4)),
'XMIN_test = -16.0', # right (neg is left)
'XMAX_test = 16.0', # right
'YMIN_test = -8.0', # down (neg is up)
'YMAX_test = 8.0', # down
'ZMIN_test = -16.0', # forward
'ZMAX_test = 16.0', # forward
'Z_test = %d' % (int(SIZE_test*4)),
'Y_test = %d' % (int(SIZE_test*2)),
'X_test = %d' % (int(SIZE_test*4)),
]
############## verify and execute ##############
def _verify_(s):
varname, eq, val = s.split(' ')
assert varname in globals()
assert eq == '='
assert type(s) is type('')
print(current)
assert current in exps
for group in exps[current]:
print(" " + group)
assert group in groups
for s in groups[group]:
print(" " + s)
_verify_(s)
exec(s)
s = "mod = " + mod
_verify_(s)
exec(s)
| [
"shamitlal@yahoo.com"
] | shamitlal@yahoo.com |
68e77021a73f93d497900e999f534e311be2a3ad | 5ead804c0fc2afb510de84293da9c7003626777d | /p2p/nat.py | b25c7b42fe600af71ec460d1949a0f593ae8f004 | [
"MIT"
] | permissive | YaoyaoBae/py-evm | 2501437a4227ddffe4ffa584a2b9ec705dad35bf | 4a3e8dfa15d81841fde434db352bcb7721ad5c04 | refs/heads/master | 2020-03-21T01:55:09.261489 | 2018-06-20T01:02:05 | 2018-06-20T01:02:05 | 137,969,468 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 6,621 | py | import asyncio
from concurrent.futures import (
ThreadPoolExecutor,
)
import ipaddress
from typing import (
AsyncGenerator,
NamedTuple,
)
from urllib.parse import urlparse
from p2p.cancel_token import (
CancelToken,
)
from p2p.exceptions import (
NoInternalAddressMatchesDevice,
OperationCancelled,
)
import netifaces
from p2p.service import BaseService
import upnpclient
# UPnP discovery can take a long time, so use a loooong timeout here.
UPNP_DISCOVER_TIMEOUT_SECONDS = 30
class PortMapping(NamedTuple):
internal: str # of the form "192.2.3.4:56"
external: str # of the form "192.2.3.4:56"
def find_internal_ip_on_device_network(upnp_dev: upnpclient.upnp.Device) -> str:
"""
For a given UPnP device, return the internal IP address of this host machine that can
be used for a NAT mapping.
"""
parsed_url = urlparse(upnp_dev.location)
# Get an ipaddress.IPv4Network instance for the upnp device's network.
upnp_dev_net = ipaddress.ip_network(parsed_url.hostname + '/24', strict=False)
for iface in netifaces.interfaces():
for family, addresses in netifaces.ifaddresses(iface).items():
# TODO: Support IPv6 addresses as well.
if family != netifaces.AF_INET:
continue
for item in addresses:
if ipaddress.ip_address(item['addr']) in upnp_dev_net:
return item['addr']
raise NoInternalAddressMatchesDevice(device_hostname=parsed_url.hostname)
class UPnPService(BaseService):
"""
Generate a mapping of external network IP address/port to internal IP address/port,
using the Universal Plug 'n' Play standard.
"""
_nat_portmap_lifetime = 30 * 60
def __init__(self, port: int, token: CancelToken = None) -> None:
"""
:param port: The port that a server wants to bind to on this machine, and
make publicly accessible.
"""
super().__init__(token)
self.port = port
self._mapping: PortMapping = None # when called externally, this never returns None
async def _run(self):
"""Run an infinite loop refreshing our NAT port mapping.
On every iteration we configure the port mapping with a lifetime of 30 minutes and then
sleep for that long as well.
"""
while self.is_running:
try:
# Wait for the port mapping lifetime, and then try registering it again
await self.wait(asyncio.sleep(self._nat_portmap_lifetime))
await self.add_nat_portmap()
except OperationCancelled:
break
except Exception:
self.logger.exception("Failed to setup NAT portmap")
async def _cleanup(self):
pass
async def add_nat_portmap(self):
"""
Set up the port mapping
:return: the IP address of the new mapping (or None if failed)
"""
self.logger.info("Setting up NAT portmap...")
try:
async for upnp_dev in self._discover_upnp_devices():
try:
external_ip = await self._add_nat_portmap(upnp_dev)
except NoInternalAddressMatchesDevice as exc:
self.logger.info(
"No internal addresses were managed by the UPnP device at %s",
exc.device_hostname,
)
continue
else:
return external_ip
except upnpclient.soap.SOAPError as e:
if e.args == (718, 'ConflictInMappingEntry'):
# An entry already exists with the parameters we specified. Maybe the router
# didn't clean it up after it expired or it has been configured by other piece
# of software, either way we should not override it.
# https://tools.ietf.org/id/draft-ietf-pcp-upnp-igd-interworking-07.html#errors
self.logger.info("NAT port mapping already configured, not overriding it")
else:
self.logger.exception("Failed to setup NAT portmap")
self._mapping = None
def current_mapping(self) -> PortMapping:
if self._mapping is None:
unbound = ':%d' % self.port
return PortMapping(unbound, unbound)
else:
return self._mapping
async def _add_nat_portmap(self, upnp_dev: upnpclient.upnp.Device) -> str:
# Detect our internal IP address (which raises if there are no matches)
internal_ip = find_internal_ip_on_device_network(upnp_dev)
external_ip = upnp_dev.WANIPConn1.GetExternalIPAddress()['NewExternalIPAddress']
for protocol, description in [('TCP', 'ethereum p2p'), ('UDP', 'ethereum discovery')]:
upnp_dev.WANIPConn1.AddPortMapping(
NewRemoteHost=external_ip,
NewExternalPort=self.port,
NewProtocol=protocol,
NewInternalPort=self.port,
NewInternalClient=internal_ip,
NewEnabled='1',
NewPortMappingDescription=description,
NewLeaseDuration=self._nat_portmap_lifetime,
)
self._mapping = PortMapping(
'%s:%d' % (internal_ip, self.port),
'%s:%d' % (external_ip, self.port),
)
self.logger.info("NAT port forwarding successfully set up: %r", self._mapping)
return external_ip
async def _discover_upnp_devices(self) -> AsyncGenerator[upnpclient.upnp.Device, None]:
loop = asyncio.get_event_loop()
# Use loop.run_in_executor() because upnpclient.discover() is blocking and may take a
# while to complete. We must use a ThreadPoolExecutor() because the
# response from upnpclient.discover() can't be pickled.
try:
devices = await self.wait(
loop.run_in_executor(ThreadPoolExecutor(max_workers=1), upnpclient.discover),
timeout=UPNP_DISCOVER_TIMEOUT_SECONDS,
)
except TimeoutError:
self.logger.info("Timeout waiting for UPNP-enabled devices")
return
# If there are no UPNP devices we can exit early
if not devices:
self.logger.info("No UPNP-enabled devices found")
return
# Now we loop over all of the devices until we find one that we can use.
for device in devices:
try:
device.WANIPConn1
except AttributeError:
continue
yield device
| [
"ut96caarrs@snkmail.com"
] | ut96caarrs@snkmail.com |
6018f93cdb60ae3b44f7efc5dadd97b15e2df5d7 | a80e9eb7ade3d43ce042071d796c00dd10b93225 | /ch_5/plot_Gaussian.py | 4c8f99e7999d1500ef7b8aa4a47a74dd10962194 | [] | no_license | ksjpswaroop/python_primer | 69addfdb07471eea13dccfad1f16c212626dee0a | 99c21d80953be3c9dc95f3a316c04b0c5613e830 | refs/heads/master | 2020-07-14T17:37:45.923796 | 2014-06-06T22:30:48 | 2014-06-06T22:30:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 271 | py | # Exercise 5.4
from numpy import sqrt, exp, pi, linspace
from matplotlib.pyplot import plot, show, xlabel, ylabel
def h(x):
return 1 / sqrt(2 * pi) * exp(-0.5 * x * x)
xlist = linspace(-4, 4, 41)
hlist = h(xlist)
plot(xlist, hlist)
xlabel('x')
ylabel('h')
show()
| [
"noahwaterfieldprice@gmail.com"
] | noahwaterfieldprice@gmail.com |
bec03343a7e11820efea069bf9dfcc2b5ea4b4a9 | 9e1bda53da4c5e98190f5f25235f528d692ee5a8 | /.history/my_app/forms_20210405180023.py | 162cd7af67099ba533f93691163e0db59d58976b | [] | no_license | Jumayev-A/Project-3 | 3d373181af6a87e3fe319a13d28fcd18941167b7 | 34ddd009726cbba9ae52e74a46d554fd735566e2 | refs/heads/main | 2023-06-10T11:02:06.446151 | 2021-07-07T06:19:11 | 2021-07-07T06:19:11 | 350,375,680 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 116 | py | from django import forms
from my_app.models import BlogModel
class BlogForm(forms.ModelForm):
model = BlogMode | [
"abdy.jumayev@gmail.com"
] | abdy.jumayev@gmail.com |
ea85dfc55a49d9f7394cf5204d62a669202be72b | 518bf342bc4138982af3e2724e75f1d9ca3ba56c | /solutions/1553. Minimum Number of Days to Eat N Oranges/1553.py | ae0d574b19fee8a7c8ccd112c60ba1dde29433ef | [
"MIT"
] | permissive | walkccc/LeetCode | dae85af7cc689882a84ee5011f0a13a19ad97f18 | a27be41c174565d365cbfe785f0633f634a01b2a | refs/heads/main | 2023-08-28T01:32:43.384999 | 2023-08-20T19:00:45 | 2023-08-20T19:00:45 | 172,231,974 | 692 | 302 | MIT | 2023-08-13T14:48:42 | 2019-02-23T15:46:23 | C++ | UTF-8 | Python | false | false | 209 | py | class Solution:
@functools.lru_cache(None)
def minDays(self, n: int) -> int:
if n <= 1:
return n
return 1 + min(self.minDays(n // 3) + n % 3,
self.minDays(n // 2) + n % 2)
| [
"me@pengyuc.com"
] | me@pengyuc.com |
868718ebefe1069ff6fe9964fe7e073242170198 | cf47ecc26210fd51caab0a1ea927ac768f388eb8 | /app/requests.py | 397faf3ab5d12a0a4ecec31234ca8b51e38bf458 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | BrendaMwiza/News | 3eb55d324b40f089d8c3110d3792af4a66341a2d | b68d53d0aefac78fae3de557c145cefd69e03c6b | refs/heads/master | 2022-09-28T17:47:48.972932 | 2019-09-20T09:01:01 | 2019-09-20T09:01:01 | 208,076,219 | 0 | 0 | null | 2022-09-16T18:09:55 | 2019-09-12T14:53:45 | Python | UTF-8 | Python | false | false | 3,234 | py | import urllib.request, json
from .models import Sources, Articles
#get api key
api_key = None
#get the news base url
base_source_url = None
base_article_url = None
def config_request(app):
global api_key, base_article_url, base_source_url
api_key = app.config['NEWS_API_KEY']
base_source_url = app.config['SOURCE_API_BASE_URL']
base_article_url = app.config['ARTICLES_API_BASE_URL']
def get_sources():
'''
Function for getting the json response to the url request
'''
get_source_url = base_source_url.format(api_key)
print(get_source_url)
with urllib.request.urlopen(get_source_url) as url:
get_source_data = url.read()
get_source_response = json.loads(get_source_data)
source_results = None
if get_source_response['sources']:
source_results_list = get_source_response['sources']
source_results = process_source(source_results_list)
return source_results
def process_source(source_list):
'''
Function for processing the source results and transform them to a list of Objects
Args:
source_list: A list of dictionaries that contain source details
Returns :
source_results: A list of source objects
'''
source_results = []
for sources_item in source_list:
id = sources_item.get('id')
name = sources_item.get('name')
description = sources_item.get('description')
url = sources_item.get('url')
category = sources_item.get('category')
language = sources_item.get('language')
country = sources_item.get('country')
sources_object = Sources(id, name, description, url, category, language, country)
source_results.append(sources_object)
return source_results
def get_article(id):
'''
Function for getting the json response to our url request
'''
get_article_url = base_article_url.format(id, api_key) + "&sources="
with urllib.request.urlopen(get_article_url) as url:
get_article_data = url.read()
get_article_response = json.loads(get_article_data)
article_results = None
if get_article_response['articles']:
article_results_list = get_article_response['articles']
article_results = process_articles(article_results_list)
return article_results
def process_articles(article_list):
'''
Function that processes the article results and transform them to a list of Objects
Args:
article_list: A list of dictionaries that contain article details
Returns :
article_results: A list of article objects
'''
article_results = []
for article_item in article_list:
id = article_item.get('id')
name = article_item.get('name')
author = article_item.get('author')
title = article_item.get('title')
description = article_item.get('description')
url = article_item.get('url')
urlToImage = article_item.get('urlToImage')
publishedAt = article_item.get('publishedAt')
article_results.append(Articles(id, name, author, title, description, url, urlToImage, publishedAt))
return article_results | [
"brendabrizy@gmail.com"
] | brendabrizy@gmail.com |
159e90f30c0888505f00ac771b040dfe89acf3ac | 551b75f52d28c0b5c8944d808a361470e2602654 | /huaweicloud-sdk-iam/huaweicloudsdkiam/v3/model/project_info.py | 84c0c398d075ddeabe08545806afd80eb148187b | [
"Apache-2.0"
] | permissive | wuchen-huawei/huaweicloud-sdk-python-v3 | 9d6597ce8ab666a9a297b3d936aeb85c55cf5877 | 3683d703f4320edb2b8516f36f16d485cff08fc2 | refs/heads/master | 2023-05-08T21:32:31.920300 | 2021-05-26T08:54:18 | 2021-05-26T08:54:18 | 370,898,764 | 0 | 0 | NOASSERTION | 2021-05-26T03:50:07 | 2021-05-26T03:50:07 | null | UTF-8 | Python | false | false | 3,718 | py | # coding: utf-8
import pprint
import re
import six
class ProjectInfo:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'domain': 'DomainInfo',
'id': 'str',
'name': 'str'
}
attribute_map = {
'domain': 'domain',
'id': 'id',
'name': 'name'
}
def __init__(self, domain=None, id=None, name=None):
"""ProjectInfo - a model defined in huaweicloud sdk"""
self._domain = None
self._id = None
self._name = None
self.discriminator = None
if domain is not None:
self.domain = domain
if id is not None:
self.id = id
self.name = name
@property
def domain(self):
"""Gets the domain of this ProjectInfo.
:return: The domain of this ProjectInfo.
:rtype: DomainInfo
"""
return self._domain
@domain.setter
def domain(self, domain):
"""Sets the domain of this ProjectInfo.
:param domain: The domain of this ProjectInfo.
:type: DomainInfo
"""
self._domain = domain
@property
def id(self):
"""Gets the id of this ProjectInfo.
project id
:return: The id of this ProjectInfo.
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this ProjectInfo.
project id
:param id: The id of this ProjectInfo.
:type: str
"""
self._id = id
@property
def name(self):
"""Gets the name of this ProjectInfo.
project name
:return: The name of this ProjectInfo.
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this ProjectInfo.
project name
:param name: The name of this ProjectInfo.
:type: str
"""
self._name = name
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
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, ProjectInfo):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"hwcloudsdk@huawei.com"
] | hwcloudsdk@huawei.com |
43510b7202af8f2f999f3f9b7e402ff45eede68e | 5864e86954a221d52d4fa83a607c71bacf201c5a | /testfixtures/tests/test_should_raise.py | 351daad7e26d3622750b3f95c8d9a93e46200e43 | [] | no_license | connoryang/1v1dec | e9a2303a01e5a26bf14159112b112be81a6560fd | 404f2cebf13b311e754d45206008918881496370 | refs/heads/master | 2021-05-04T02:34:59.627529 | 2016-10-19T08:56:26 | 2016-10-19T08:56:26 | 71,334,417 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,104 | py | #Embedded file name: e:\jenkins\workspace\client_SERENITY\branches\release\SERENITY\carbon\common\stdlib\testfixtures\tests\test_should_raise.py
from testfixtures import Comparison as C, ShouldRaise, should_raise
from unittest import TestCase
from .compat import py_33_plus
class TestShouldRaise(TestCase):
def test_no_params(self):
def to_test():
raise ValueError('wrong value supplied')
should_raise(ValueError('wrong value supplied'))(to_test)()
def test_no_exception(self):
def to_test():
pass
try:
should_raise(ValueError())(to_test)()
except AssertionError as e:
self.assertEqual(e, C(AssertionError('None raised, ValueError() expected')))
else:
self.fail('No exception raised!')
def test_wrong_exception(self):
def to_test():
raise ValueError('bar')
try:
should_raise(ValueError('foo'))(to_test)()
except AssertionError as e:
self.assertEqual(e, C(AssertionError("ValueError('bar',) raised, ValueError('foo',) expected")))
else:
self.fail('No exception raised!')
def test_only_exception_class(self):
def to_test():
raise ValueError('bar')
should_raise(ValueError)(to_test)()
def test_no_supplied_or_raised(self):
def to_test():
pass
try:
should_raise()(to_test)()
except AssertionError as e:
self.assertEqual(e, C(AssertionError('No exception raised!')))
else:
self.fail('No exception raised!')
def test_args(self):
def to_test(*args):
raise ValueError('%s' % repr(args))
should_raise(ValueError('(1,)'))(to_test)(1)
def test_kw_to_args(self):
def to_test(x):
raise ValueError('%s' % x)
should_raise(ValueError('1'))(to_test)(x=1)
def test_kw(self):
def to_test(**kw):
raise ValueError('%r' % kw)
should_raise(ValueError("{'x': 1}"))(to_test)(x=1)
def test_both(self):
def to_test(*args, **kw):
raise ValueError('%r %r' % (args, kw))
should_raise(ValueError("(1,) {'x': 2}"))(to_test)(1, x=2)
def test_method_args(self):
class X:
def to_test(self, *args):
self.args = args
raise ValueError()
x = X()
should_raise(ValueError)(x.to_test)(1, 2, 3)
self.assertEqual(x.args, (1, 2, 3))
def test_method_kw(self):
class X:
def to_test(self, **kw):
self.kw = kw
raise ValueError()
x = X()
should_raise(ValueError)(x.to_test)(x=1, y=2)
self.assertEqual(x.kw, {'x': 1,
'y': 2})
def test_method_both(self):
class X:
def to_test(self, *args, **kw):
self.args = args
self.kw = kw
raise ValueError()
x = X()
should_raise(ValueError)(x.to_test)(1, y=2)
self.assertEqual(x.args, (1,))
self.assertEqual(x.kw, {'y': 2})
def test_class_class(self):
class Test:
def __init__(self, x):
pass
should_raise(TypeError)(Test)()
def test_raised(self):
with ShouldRaise() as s:
raise ValueError('wrong value supplied')
self.assertEqual(s.raised, C(ValueError('wrong value supplied')))
def test_catch_baseexception_1(self):
with ShouldRaise(SystemExit):
raise SystemExit()
def test_catch_baseexception_2(self):
with ShouldRaise(KeyboardInterrupt):
raise KeyboardInterrupt()
def test_with_exception_class_supplied(self):
with ShouldRaise(ValueError):
raise ValueError('foo bar')
def test_with_exception_supplied(self):
with ShouldRaise(ValueError('foo bar')):
raise ValueError('foo bar')
def test_with_exception_supplied_wrong_args(self):
try:
with ShouldRaise(ValueError('foo')):
raise ValueError('bar')
except AssertionError as e:
self.assertEqual(e, C(AssertionError("ValueError('bar',) raised, ValueError('foo',) expected")))
else:
self.fail('No exception raised!')
def test_neither_supplied(self):
with ShouldRaise():
raise ValueError('foo bar')
def test_with_no_exception_when_expected(self):
try:
with ShouldRaise(ValueError('foo')):
pass
except AssertionError as e:
self.assertEqual(e, C(AssertionError("None raised, ValueError('foo',) expected")))
else:
self.fail('No exception raised!')
def test_with_no_exception_when_neither_expected(self):
try:
with ShouldRaise():
pass
except AssertionError as e:
self.assertEqual(e, C(AssertionError('No exception raised!')))
else:
self.fail('No exception raised!')
def test_with_getting_raised_exception(self):
with ShouldRaise() as s:
raise ValueError('foo bar')
self.assertEqual(C(ValueError('foo bar')), s.raised)
def test_import_errors_1(self):
if py_33_plus:
message = "No module named 'textfixtures'"
else:
message = 'No module named textfixtures.foo.bar'
with ShouldRaise(ImportError(message)):
import textfixtures.foo.bar
def test_import_errors_2(self):
with ShouldRaise(ImportError('X')):
raise ImportError('X')
def test_custom_exception(self):
class FileTypeError(Exception):
def __init__(self, value):
self.value = value
with ShouldRaise(FileTypeError('X')):
raise FileTypeError('X')
def test_assert_keyerror_raised(self):
expected = "KeyError('foo',) raised, AttributeError('foo',) expected"
class Dodgy(dict):
def __getattr__(self, name):
return self[name]
try:
with ShouldRaise(AttributeError('foo')):
Dodgy().foo
except AssertionError as e:
self.assertEqual(C(AssertionError(expected)), e)
else:
self.fail('No exception raised!')
def test_decorator_usage(self):
@should_raise(ValueError('bad'))
def to_test():
raise ValueError('bad')
to_test()
def test_unless_false_okay(self):
with ShouldRaise(unless=False):
raise AttributeError()
def test_unless_false_bad(self):
try:
with ShouldRaise(unless=False):
pass
except AssertionError as e:
self.assertEqual(e, C(AssertionError('No exception raised!')))
else:
self.fail('No exception raised!')
def test_unless_true_okay(self):
with ShouldRaise(unless=True):
pass
def test_unless_true_not_okay(self):
try:
with ShouldRaise(unless=True):
raise AttributeError('foo')
except AssertionError as e:
self.assertEqual(e, C(AssertionError("AttributeError('foo',) raised, no exception expected")))
else:
self.fail('No exception raised!')
def test_unless_decorator_usage(self):
@should_raise(unless=True)
def to_test():
pass
to_test()
def test_identical_reprs(self):
class AnnoyingException(Exception):
def __init__(self, **kw):
self.other = kw.get('other')
try:
with ShouldRaise(AnnoyingException(other='bar')):
raise AnnoyingException(other='baz')
except AssertionError as e:
print repr(e)
self.assertEqual(C(AssertionError("AnnoyingException() raised, AnnoyingException() expected, attributes differ:\n other:'bar' != 'baz'")), e)
else:
self.fail('No exception raised!')
| [
"le02005@163.com"
] | le02005@163.com |
2c44ce5a5899ceb4ccce4714af86337b5c96d807 | fa8e2c81f025e7f90555d0e9452a91e03b6eeac0 | /guessingGame.py | f44c4975047519e9f33721ba74bc20776764af17 | [] | no_license | EgbieAndersonUku1/theGuessingGame | 56e3097e379611332791b02498be3fb442ac8abf | 129ece7839d98f51a35dc0bbe1a96ff6dd6b4aa0 | refs/heads/master | 2020-04-15T13:54:35.613549 | 2015-08-13T00:42:10 | 2015-08-13T00:42:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,193 | py | #!/usr/bin/python
################################################################################
#
# Created By : Egbie Anderson
# Name Of The Program : GuessWordGame.Py
# Created on the 09/08/2015 at 21:05:12 hrs
# This is version : 1
#
#
# File description
#
# A twist of the famous hang man game but without the hang man.
# Does not work in codeSkultor due to the fact it does not have urllib
################################################################################
import random
import string
from time import sleep
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
import urllib
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
class ImageInfo(object):
"""Deals with images"""
def __init__(self, img):
self._img = simplegui.load_image(img)
def get_center(self):
return [self._img.get_width()/2.0, self._img.get_height()/2.0]
def get_size(self):
return [self._img.get_width(), self._img.get_height()]
def get_img_height(self):
return self._img.get_height()
def get_img_width(self):
return self._img.get_width()
def get_img(self):
return self._img
class Mode(object):
"""Handles the diffuculty for the game"""
def __init__(self, wordlist):
self._word_dict = {}
word_list = wordlist.split("\n")
for word in word_list:
len_word = len(word)
if len_word not in self._word_dict:
self._word_dict.setdefault(len_word, [word.strip("\n")])
else:
self._word_dict[len_word].append(word)
# level of diffuculty for the game picks words of length n based on mode
self._easy = [num for num in xrange(4, 8)]
self._medium = [num for num in xrange(8, 17)]
self._hard = [num for num in xrange(17, 22)]
def _get_word(self, num_list):
"""check if the word length is in the dictionary"""
while True:
num = random.choice(num_list)
word = self._word_dict.get(num, False)
if not word:
num_list.pop(num) # remove the num from the word list as there is no word by that length
else:
return word
def easy(self):
random.shuffle(self._easy)
return self._get_word(self._easy)
def medium(self):
random.shuffle(self._medium)
return self._get_word(self._medium)
def diffuculty(self):
random.shuffle(self._hard)
return self._get_word(self._hard)
class GuessWordGame(Mode):
def __init__(self, game_start=False):
#
self._dictionary = urllib.urlopen("https://dl.dropbox.com/s/otmc56fnpakbbdi/dictionary.txt?dl=0").read()
# uncomment the 6 lines and comment the top line if you want to load you own dictionary words
# try:
# with open( "/home/ab/Documents/MyProjects/guess_game/dictionary.txt") as f:
# self._dictionary = f.read()
# except IOError:
# print "[!] File does not exists"
# exit(0)
self._game_mode = Mode(self._dictionary) # controls the game diffuculty
self._dictionary = self._game_mode.easy() # start of with the easiest level
self._secret_word, self._available_letters = "", ""
self._remaining_guess, self._correct_guess = 7, 0
self._game_over, self._game_start = False, game_start
self._used_letters = []
random.shuffle(self._dictionary) # shuffle the words
self.__create_alphabet_list()
self.chose_random_word() # select random word
self._word_so_far = self._turn_word_into_dash(self._secret_word) # turn word into dash
def game_mode(self, mode):
"""select the mode for the game"""
if mode == "easy":
self._dictionary = self._game_mode.easy()
self.reset_game()
elif mode == "medium":
self._dictionary = self._game_mode.medium()
self.reset_game()
elif mode == "diffuculty":
self._dictionary = self._game_mode.diffuculty()
self.reset_game()
def _get_secret_word(self):
"""return the secret word chosen"""
return self._secret_word
def _is_guess_correct(self):
return (True if self._correct_guess == len(self._secret_word) else False)
def _reset_guesses(self):
"""reset guess back to default"""
self._remaining_guess = 7 # reset the remaining guess to 7
def _reset_correct_guesses(self):
"""reset the correct guess back to default"""
self._correct_guess = 0
def __create_alphabet_list(self):
"""create alphabets for the entire game A-Z"""
self._available_letters = [char for char in string.ascii_uppercase]
def get_available_alphabets(self):
"""return the letters available to the user"""
return " ".join(self._available_letters)
def _reset_available_alphabets(self):
"""reset the alphabets available the user to A-Z"""
self.__create_alphabet_list()
def _remove_letter(self, char):
"""remove letter from available letters"""
self._available_letters.remove(char)
def get_used_letters(self):
"""return the letters already used by the user"""
return " ".join(self._used_letters)
def _reset_used_letters(self):
"""reset the letter used by the user"""
self._used_letters = []
def get_word_so_far(self):
"""returns the string containing the letters for the
secret word that user has already guessed or not guessed
"""
return " ".join(self._word_so_far)
def game_over(self):
"""return the state of the game"""
return self._game_over
def reset_game(self):
"""reset_game the game"""
self._reset_available_alphabets() # reset available letters
self.chose_random_word() # chose a new random word
self._reset_guesses() # reset the remaining guess to 7
self._reset_used_letters() # reset used letters to an empty list
self._game_over = False
self._reset_correct_guesses() # reset correct guess to 0
def chose_random_word(self):
"""chose a random word from the word list"""
self._secret_word = random.choice(self._dictionary) # set the secret word to a new one
self._word_so_far = self._turn_word_into_dash(self._secret_word) # recreate a new dashes
def _turn_word_into_dash(self, word):
"""turn the secret word into a string of dashes"""
return ["_" for char in xrange(len(word))]
def _deduct_guesses(self):
"""deduct the guess by one"""
self._remaining_guess -= 1
def get_remaining_guesses(self):
return self._remaining_guess
def _add_used_letter(self, letter):
self._used_letters.append(letter)
def _insert_char(self, char):
"""_insert_char(str) -> return (str)
Enter characters into the dash
"""
for num in xrange(len(self._secret_word)):
if self._secret_word[num] == char:
self._add_char_to_dash(char, num) # add the char to words so far i.e string of dashes
self._correct_guess += 1
self._remove_letter(char) # Remove the letter from available letters
self._add_used_letter(char) # add letter to used words
# helpher function adds a word to dash
def _add_char_to_dash(self, char, pos):
"""Enter characters into the dash depending on the position"""
self._word_so_far[pos] = char
def check_guess(self, guess):
"""checks whether the user has made a valid guess"""
if self.get_remaining_guesses():
guess = guess.upper()[0]
if guess in self.get_used_letters():
print "[+] you have already used that letter" # display message in graphic form
else:
if guess in self._get_secret_word():
self._insert_char(guess)
else:
self._deduct_guesses() # deduct the user guess by 1
try:
self._remove_letter(guess) # Remove the letter from available letters
self._add_used_letter(guess) # Append the used letter to list
except ValueError:
pass
else:
self._game_over = True
print "\n[+] The word was {}".format(self._get_secret_word()) # display word the user has gues
def new_game():
"""starts a new game"""
guess_game.reset_game()
Frame.set_canvas_background('White')
guess_game._game_start = True
game_start = True
guess_game.game_mode("easy")
def easy():
guess_game.game_mode("easy")
print "Game play level : Easy"
def medium():
guess_game.game_mode("medium")
print "Game play level : Medium"
def diffuculty():
guess_game.game_mode("diffuculty")
print "Game play level : Diffuculty"
def random_word():
"""starts a new game"""
print "Choosing random word at random diffuculty level"
level = ["easy", "medium", "diffuculty"]
random.shuffle(level)
level = random.choice(level)
guess_game.game_mode(level)
print "Choosen level : {} ".format(level)
def user_guess(guess):
"""Allows the user to add make a guess"""
# check if guess is not None
if guess:
guess_game.check_guess(guess)
def draw(canvas):
title = []
name = "hangman"
if not guess_game._game_start:
canvas.draw_image(img_info.get_img(), img_info.get_center(), img_info.get_size(),
(SCREEN_WIDTH/2, SCREEN_HEIGHT/2), (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
canvas.draw_text("The Word Game", (SCREEN_WIDTH/5, SCREEN_HEIGHT/5), 70, 'Red')
canvas.draw_text("Learning spelling by guessing the word", (SCREEN_WIDTH/5, SCREEN_HEIGHT/2+180), 35, 'Green')
canvas.draw_text("Over 60,000 words to play with !!", (SCREEN_WIDTH/5, SCREEN_HEIGHT/2+230), 35, 'Blue')
else:
if not guess_game.game_over():
canvas.draw_text("The Spelling Game", (250, 70), 60, 'Red')
canvas.draw_text(guess_game.get_word_so_far(), (50, 500), 25, 'Red')
canvas.draw_text("[+] Available letters : {} ".format(guess_game.get_available_alphabets()), (0, 140), 23, 'Blue')
canvas.draw_text("[+] Used letters : {} ".format(guess_game.get_used_letters()), (0, 249), 23, 'Blue')
canvas.draw_text("[+] You have {} guess remaining".format(guess_game.get_remaining_guesses()), (1, 330), 23, 'Blue')
if guess_game.game_over():
Frame.set_canvas_background('Black')
canvas.draw_text("GAME OVER!!!", (60, SCREEN_HEIGHT/2), 100, 'Red')
sleep(1)
canvas.draw_text("Ohh to bad, the correct word was ", (100, 100), 30, 'Red')
canvas.draw_text("{}".format(guess_game._secret_word), (100, 150), 30, 'Red')
elif guess_game._is_guess_correct():
canvas.draw_text("Well done", (150, 450), 80, 'Green')
guess_game = GuessWordGame()
img_info = ImageInfo("https://dl.dropbox.com/s/wbq66iywhvbvcuw/abc.jpeg?dl=0")
# resigter events
Frame = simplegui.create_frame("Guess Word Game", SCREEN_WIDTH, SCREEN_HEIGHT)
Frame.set_canvas_background('White')
Frame.add_button("New Game", new_game, 150)
Frame.add_button("New random word", random_word, 150)
Frame.add_button("Easy", easy, 150)
Frame.add_button("Medium", medium, 150)
Frame.add_button("Hard", diffuculty, 150)
#Frame.add_button("Game Mode", game_mode, 150)
Frame.add_input("\nEnter a character", user_guess, 150)
Frame.set_draw_handler(draw)
# start the frame
Frame.start()
| [
"jayunderwood2011@hotmail.com"
] | jayunderwood2011@hotmail.com |
5044b8ef4ace4287373c06bc7916c93db1ba3994 | caeea08f9d0362609ccae39ed0ac73345af87494 | /s3/s3_1_budget.py | f62dbfc6fe2a4aa9734fa82f5df2017821cc2860 | [] | no_license | barcern/cfg-python | 9133709fd0139894a80aed2fd95dd28371cef495 | aad9cf4feb4e2447bc442d6b90adebfadf1ed6a1 | refs/heads/master | 2023-03-11T20:19:13.051492 | 2021-03-01T23:31:31 | 2021-03-01T23:31:31 | 295,569,412 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 570 | py | # You have a budget of £10 and want to write a program to decide which burger restaurant to go to.
# - Input the price of a burger using input()
# - Check whether the price is less than or equal (<=) 10.00
# - Print the result in the format below
# Burger is within budget: True
# User input and set budget
price = float(input("How much does this burger cost? "))
budget = 10.0
# Check whether price is within the budget
in_budget = price <= budget
# Print result
print(f"Burger is within budget: {in_budget}")
#print("Burger is within budget: {}".format(in_budget)) | [
"bcernakova01@gmail.com"
] | bcernakova01@gmail.com |
c3a0938f836e7c0c1fac968c208fadfad3b06696 | e23a4f57ce5474d468258e5e63b9e23fb6011188 | /125_algorithms/004_trees/_exercises/templates/16 Trees/Tree Representation Implementation (Nodes and References).py | 725c8abb61a726933d9508e885547cc1571944ae | [] | no_license | syurskyi/Python_Topics | 52851ecce000cb751a3b986408efe32f0b4c0835 | be331826b490b73f0a176e6abed86ef68ff2dd2b | refs/heads/master | 2023-06-08T19:29:16.214395 | 2023-05-29T17:09:11 | 2023-05-29T17:09:11 | 220,583,118 | 3 | 2 | null | 2023-02-16T03:08:10 | 2019-11-09T02:58:47 | Python | UTF-8 | Python | false | false | 1,309 | py | # # Nodes and References Implementation of a Tree
# #
# # In this notebook is the code corresponding to the lecture for implementing the representation of a Tree as a class with nodes and references!
#
# c_ BinaryTree o..
# ___ - rootObj
# key _ ?
# leftChild _ N..
# rightChild _ N..
#
# ___ insertLeft newNode
# __ l.. __ N..
# l.. _ ? ?
# ____
# t _ ? ?
# t.l.. _ l..
# l.. _ t
#
# ___ insertRight newNode
# __ r.. __ N..
# r.. _ ? ?
# ____
# t _ ? ?
# t.r.. _ r..
# r.. _ t
#
#
# ___ getRightChild
# r_ ?
#
# ___ getLeftChild
# r_ ?
#
# ___ setRootVal obj
# key _ ?
#
# ___ getRootVal
# r_ k..
#
# # We can see some examples of creating a tree and assigning children. Note that some outputs are Trees themselves!
# #
# # from __future__ import print_function
# #
# r _ ?('a')
# print(?.gRV..
# print(?.gLC..
# ?.iL.. ('b')
# print(?.gLC..
# print(?.gLC__.gRV..
# ?.iR.. 'c')
# print(?.gRC..
# print(?.gRC__.gRV..
# ?.gRC__.sRV.. 'hello')
# print(?.gRC__.gRV..
#
# # a
# # N..
# # <__main__.BinaryTree object at 0x104779c10>
# # b
# # <__main__.BinaryTree object at 0x103b42c50>
# # c
# # hello | [
"sergejyurskyj@yahoo.com"
] | sergejyurskyj@yahoo.com |
543dadfc2ac4efbea7de63620013b771b4ad04ff | 79e1d04867c4298b23c907f92c7119e4bea8ef02 | /ParlAI/parlai/agents/vsepp_caption/modules.py | d94d1f268f6c0b8bab8e2ea1c86bf295d82acfd2 | [
"MIT",
"Apache-2.0"
] | permissive | ethanjperez/convince | 53db0bcd978831799c68fe63ecb0c91473ec40c4 | ccf60824b28f0ce8ceda44a7ce52a0d117669115 | refs/heads/master | 2023-01-08T09:12:16.722614 | 2021-11-03T18:50:30 | 2021-11-03T18:50:30 | 205,189,291 | 27 | 8 | Apache-2.0 | 2023-01-05T22:43:12 | 2019-08-29T15:03:34 | Python | UTF-8 | Python | false | false | 6,876 | py | #!/usr/bin/env python3
# This file is covered under the Apache 2.0 License listed here
# <https://github.com/fartashf/vsepp/blob/master/LICENSE> as it is a
# Derivative Work of the repo.
import torch
from torch import optim
from torch.nn.utils.rnn import pack_padded_sequence
import torch.nn as nn
import torchvision.models as models
import numpy as np
class VSEpp(nn.Module):
"""
Model based on:
- VSE++: Improving Visual-Semantic Embeddings with Hard Negatives
`(Faghri et al. 2017) <arxiv.org/abs/1707.05612>`
Original Implementation found here: <https://github.com/fartashf/vsepp>
"""
def __init__(self, opt, dict):
super().__init__()
self.opt = opt
self.dict = dict
self.img_enc = EncoderImage(embed_size=opt['embed_size'],
finetune=opt['finetune'],
cnn_type=opt['cnn_type'],
no_imgnorm=opt['no_imgnorm'])
self.txt_enc = EncoderText(vocab_size=len(self.dict.tok2ind),
word_dim=opt['word_dim'],
embed_size=opt['embed_size'],
num_layers=opt['num_layers'])
def forward(self, images, captions, lengths):
img_emb = self.img_enc(images) if images is not None else None
cap_emb = self.txt_enc(captions, lengths) if captions is not None else None
return img_emb, cap_emb
def get_optim(self):
kwargs = {'lr': float(self.opt['learning_rate']),
'amsgrad': True}
params = list(self.txt_enc.parameters())
params += list(self.img_enc.fc.parameters())
if self.opt['finetune']:
params += list(self.img_enc.cnn.parameters())
optimizer = optim.Adam(params, **kwargs)
return optimizer
def dot_sim(im, s):
"""
Dot product similarity between all the image and sentence pairs
"""
return im.mm(s.t())
def l2norm(X):
"""
L2-normalize columns of X
"""
norm = torch.pow(X, 2).sum(dim=1, keepdim=True).sqrt()
X = torch.div(X, norm)
return X
class ContrastiveLoss(nn.Module):
"""
Compute contrastive loss.
"""
def __init__(self, use_cuda, margin=0, max_violation=True):
super().__init__()
self.use_cuda = use_cuda
self.margin = margin
self.sim = dot_sim
self.max_violation = max_violation
def forward(self, im, caps, offset=0):
# Compute the similarity of each image/caption pair
scores = self.sim(im, caps)
diagonal = scores.diag().view(im.shape[0], 1)
d1 = diagonal.expand(scores.size())
d2 = diagonal.t().expand(scores.size())
# Caption retrieval score
cost_cap = (self.margin + scores - d1).clamp(min=0)
# image retrieval score
cost_im = (self.margin + scores - d2).clamp(min=0)
mask = torch.eye(im.shape[0]) > 0.5
if self.use_cuda:
mask = mask.cuda()
cost_cap = cost_cap.masked_fill(mask, 0)
cost_im = cost_im.masked_fill(mask, 0)
# Compute the metrics (ranks, top1)
if self.use_cuda:
sorted_ranks = np.flip(np.argsort(scores.detach().cpu().numpy()), 1)
else:
sorted_ranks = np.flip(np.argsort(scores.detach().numpy()), 1)
top1 = sorted_ranks[:, 0]
ranks = []
for idx in range(im.shape[0]):
ranks.append(np.where(sorted_ranks[idx, :] == (idx + offset))[0][0])
# keep the maximum violating negative for each query
if self.max_violation:
cost_cap = cost_cap.max(1)[0]
cost_im = cost_im.max(0)[0]
return cost_cap.sum() + cost_im.sum(), ranks, top1
class EncoderImage(nn.Module):
def __init__(self, embed_size, finetune=False, cnn_type='resnet152',
no_imgnorm=False):
"""Load pretrained CNN and replace top fc layer."""
super().__init__()
self.embed_size = embed_size
self.no_imgnorm = no_imgnorm
# Load a pre-trained model
self.cnn = self.get_cnn(cnn_type)
# For efficient memory usage.
for param in self.cnn.parameters():
param.requires_grad = finetune
# Replace the last fully connected layer of CNN with a new one
if cnn_type.startswith('vgg'):
self.fc = nn.Linear(self.cnn.classifier._modules['6'].in_features,
embed_size)
self.cnn.classifier = nn.Sequential(
*list(self.cnn.classifier.children())[:-1])
elif cnn_type.startswith('resnet'):
self.fc = nn.Linear(self.cnn.module.fc.in_features, embed_size)
self.cnn.module.fc = nn.Sequential()
self.init_weights()
def get_cnn(self, arch):
"""Load a pretrained CNN and parallelize over GPUs
"""
print("=> using pre-trained model '{}'".format(arch))
model = models.__dict__[arch](pretrained=True)
if arch.startswith('alexnet') or arch.startswith('vgg'):
model.features = nn.DataParallel(model.features)
else:
model = nn.DataParallel(model)
return model
def init_weights(self):
"""Xavier initialization for the fully connected layer
"""
r = np.sqrt(6.) / np.sqrt(self.fc.in_features +
self.fc.out_features)
self.fc.weight.data.uniform_(-r, r)
self.fc.bias.data.fill_(0)
def forward(self, images):
"""Extract image feature vectors."""
features = self.cnn(images)
# normalization in the image embedding space
features = l2norm(features)
# linear projection to the joint embedding space
features = self.fc(features)
# normalization in the joint embedding space
if not self.no_imgnorm:
features = l2norm(features)
return features
class EncoderText(nn.Module):
def __init__(self, vocab_size, word_dim, embed_size, num_layers):
super().__init__()
self.embed_size = embed_size
# word embedding
self.embed = nn.Embedding(vocab_size, word_dim)
# caption embedding
self.rnn = nn.GRU(word_dim, embed_size, num_layers, batch_first=True)
self.init_weights()
def init_weights(self):
self.embed.weight.data.uniform_(-0.1, 0.1)
def forward(self, x, lengths):
"""Handles variable size captions
"""
# Embed word ids to vectors
x = self.embed(x)
packed = pack_padded_sequence(x, lengths, batch_first=True)
# Forward propagate RNN
_, out = self.rnn(packed)
out = out.squeeze(0)
# normalization in the joint embedding space
out = l2norm(out)
return out
| [
"ethanperez18@gmail.com"
] | ethanperez18@gmail.com |
ce8b24e9eb6af166554ad5e15d4b7dfdc7662b72 | 87ad372898e793faf1ad89f4bb3b6e84a8002131 | /tests/unit/FundManager/test_remove_strategy_from_queue.py | 3aaa736133d80b2747e318a8d05899b695b809e4 | [] | no_license | atsignhandle/unagii-vault-v2 | 6a9a96c11d34257bc3fdae57455ec3b2f9c0029a | 548f715f34329eb5abebffe40acbeb56a31cb6f3 | refs/heads/main | 2023-08-27T00:59:48.080152 | 2021-09-28T02:47:36 | 2021-09-28T02:47:36 | 413,448,825 | 0 | 0 | null | 2021-10-04T14:07:37 | 2021-10-04T14:07:36 | null | UTF-8 | Python | false | false | 1,123 | py | import brownie
from brownie import ZERO_ADDRESS
import pytest
def test_remove_strategy_from_queue(fundManager, admin, testStrategy, user):
strategy = testStrategy
timeLock = fundManager.timeLock()
fundManager.approveStrategy(strategy, {"from": timeLock})
fundManager.addStrategyToQueue(strategy, 123, 0, 0, {"from": admin})
# revert if not authorized
with brownie.reverts("!auth"):
fundManager.removeStrategyFromQueue(strategy, {"from": user})
def snapshot():
return {"totalDebtRatio": fundManager.totalDebtRatio()}
before = snapshot()
tx = fundManager.removeStrategyFromQueue(strategy, {"from": admin})
after = snapshot()
strat = fundManager.strategies(strategy)
assert not strat["active"]
assert strat["debtRatio"] == 0
assert after["totalDebtRatio"] == before["totalDebtRatio"] - 123
assert fundManager.queue(0) == ZERO_ADDRESS
assert tx.events["RemoveStrategyFromQueue"].values() == [strategy]
# revert if not active
with brownie.reverts("!active"):
fundManager.removeStrategyFromQueue(strategy, {"from": admin}) | [
"tsk.nakamura@gmail.com"
] | tsk.nakamura@gmail.com |
3ab1e9c75667769ee77fc58051c71e5a4e31100c | 8242bc1caacbc1d50a3d0458760457ddb45e9df3 | /post/migrations/0003_auto_20200915_1353.py | 9dad5265249e16d5e30700d66c45c85f0e33e9d7 | [] | no_license | ajy720/Outstagram | d0ad1318ff588811070d67b85e844b2770c6596e | bedad304011fcace1e7a589628c5f68753aad147 | refs/heads/master | 2022-12-31T14:36:33.223069 | 2020-10-21T01:43:04 | 2020-10-21T01:43:04 | 295,584,136 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 391 | py | # Generated by Django 3.1.1 on 2020-09-15 04:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('post', '0002_auto_20200915_1143'),
]
operations = [
migrations.AlterField(
model_name='post',
name='picture',
field=models.ImageField(upload_to='postings/'),
),
]
| [
"ajy720@gmail.com"
] | ajy720@gmail.com |
b4e98124357bf95756dce5ab0ea3eccabdcb4f80 | 6e322ec7477a0105d5b95055dfafb75ba00a3f43 | /example/manage.py | fa318242823951e3cc2177feba6ab8aa36b03288 | [] | no_license | tomatohater/Django-API-Playground | ca79dbed28701e214c41f20b7bdc7fd5fa09d5a7 | bc950a65bd6f65211e250e71e9777ec865f5d6f6 | refs/heads/master | 2021-01-21T01:39:51.368593 | 2012-11-07T05:15:58 | 2012-11-07T05:15:58 | 6,568,919 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 279 | py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
sys.path.append("../")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| [
"fatiherikli@gmail.com"
] | fatiherikli@gmail.com |
47259b4d09cadfbf3fc1ac65f5944bd815ba5c23 | 45c170fb0673deece06f3055979ece25c3210380 | /toontown/coghq/CashbotMintGearRoom_Battle00_Cogs.py | 317a112ac560c39265cefffa3d94bb97f0dac647 | [] | no_license | MTTPAM/PublicRelease | 5a479f5f696cfe9f2d9dcd96f378b5ce160ec93f | 825f562d5021c65d40115d64523bb850feff6a98 | refs/heads/master | 2021-07-24T09:48:32.607518 | 2018-11-13T03:17:53 | 2018-11-13T03:17:53 | 119,129,731 | 2 | 6 | null | 2018-11-07T22:10:10 | 2018-01-27T03:43:39 | Python | UTF-8 | Python | false | false | 1,185 | py | #Embedded file name: toontown.coghq.CashbotMintGearRoom_Battle00_Cogs
from toontown.coghq.SpecImports import *
from toontown.toonbase import ToontownGlobals
CogParent = 10000
BattleCellId = 0
BattleCells = {BattleCellId: {'parentEntId': CogParent,
'pos': Point3(0, 0, 0)}}
CogData = [{'parentEntId': CogParent,
'boss': 0,
'level': ToontownGlobals.CashbotMintCogLevel,
'battleCell': BattleCellId,
'pos': Point3(-6, 0, 0),
'h': 180,
'behavior': 'stand',
'path': None,
'skeleton': 0},
{'parentEntId': CogParent,
'boss': 0,
'level': ToontownGlobals.CashbotMintCogLevel + 1,
'battleCell': BattleCellId,
'pos': Point3(-2, 0, 0),
'h': 180,
'behavior': 'stand',
'path': None,
'skeleton': 0},
{'parentEntId': CogParent,
'boss': 0,
'level': ToontownGlobals.CashbotMintCogLevel,
'battleCell': BattleCellId,
'pos': Point3(2, 0, 0),
'h': 180,
'behavior': 'stand',
'path': None,
'skeleton': 0},
{'parentEntId': CogParent,
'boss': 0,
'level': ToontownGlobals.CashbotMintCogLevel + 1,
'battleCell': BattleCellId,
'pos': Point3(6, 0, 0),
'h': 180,
'behavior': 'stand',
'path': None,
'skeleton': 0}]
ReserveCogData = []
| [
"linktlh@gmail.com"
] | linktlh@gmail.com |
92adebbd1164f1aa26247842f6b9790d98d0c262 | 3d8027f2ef3f723e13b31e056d0c03da4ed74aa8 | /09-09-2020(Day15)/EmailSend/EmailSend/wsgi.py | 1f3a4b5a820f4d8ae86f13ff4fde0be1c4f2cf32 | [] | no_license | satyavani462/Django-Batch5 | 2efbc99223008954896667dee46d2606b6559c82 | 1b975bc21e7fdeed11bef7505d22d4fed126656c | refs/heads/master | 2022-12-08T19:57:33.996903 | 2020-09-10T14:23:15 | 2020-09-10T14:23:15 | 294,688,262 | 1 | 0 | null | 2020-09-11T12:22:16 | 2020-09-11T12:22:15 | null | UTF-8 | Python | false | false | 395 | py | """
WSGI config for EmailSend project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'EmailSend.settings')
application = get_wsgi_application()
| [
"nivas0803@gmail.com"
] | nivas0803@gmail.com |
dd815bb4dafa784e93eeaed5ca27ace6491cc7b3 | f3eebcb7800bf2bfba537fc017a3ad3bfe9f9264 | /1495.py | ea2f0bf4d5e8a02e479b1474c86f22adffffad06 | [] | no_license | do-park/baekjoon | c7a881f8eb50a8303cf8fa05bd0fef8d68e87de7 | 767a98f743f2fb304b091affe5a9f1c54e0946b8 | refs/heads/master | 2020-12-19T11:42:03.188674 | 2020-12-13T07:17:55 | 2020-12-13T07:17:55 | 235,723,046 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 580 | py | # BOJ 1495 메모리 초과
from collections import deque
N, S, M = map(int, input().split())
V = list(map(int, input().split()))
dp = [[] for _ in range(N + 1)]
dp[0].append(S)
q = deque()
q.append([S, 0])
while q:
volume, idx = q.popleft()
if idx < N:
if 0 <= volume - V[idx]:
nxt = volume - V[idx]
dp[idx + 1].append(nxt)
q.append([nxt, idx + 1])
if volume + V[idx] <= M:
nxt = volume + V[idx]
dp[idx + 1].append(nxt)
q.append([nxt, idx + 1])
print(max(dp[-1]) if dp[-1] else -1) | [
"dohee.pa@gmail.com"
] | dohee.pa@gmail.com |
04bf10e4a7b62ec6d9e671d32a689f37802b8256 | bba02b96608e53bed25eae8fcc30334f238b6a6b | /tests/test_parse_url.py | e4f8b7a62dec7df5d512ede72f1d49a7b9c98898 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | wkentaro/gdown | de1a3ce1058b3457ed4a3087b70cf620d85e9c5a | 5c7507f02718048899b85d4010a6ed93316cbf27 | refs/heads/main | 2023-07-25T11:25:03.088818 | 2023-04-19T19:39:39 | 2023-04-22T06:02:17 | 44,421,756 | 3,266 | 319 | MIT | 2023-09-12T20:53:04 | 2015-10-17T03:01:23 | Python | UTF-8 | Python | false | false | 1,079 | py | import pytest
from gdown.parse_url import parse_url
def test_parse_url():
file_id = "0B_NiLAzvehC9R2stRmQyM3ZiVjQ"
# list of (url, expected, check_warn)
urls = [
(
"https://drive.google.com/open?id={}".format(file_id),
(file_id, False),
True,
),
(
"https://drive.google.com/uc?id={}".format(file_id),
(file_id, True),
False,
),
(
"https://drive.google.com/file/d/{}/view?usp=sharing".format(
file_id
), # NOQA
(file_id, False),
True,
),
(
"https://drive.google.com/a/jsk.imi.i.u-tokyo.ac.jp/uc?id={}&export=download".format( # NOQA
file_id
),
(file_id, True),
False,
),
]
for url, expected, check_warn in urls:
if check_warn:
with pytest.warns(UserWarning):
assert parse_url(url) == expected
else:
assert parse_url(url) == expected
| [
"www.kentaro.wada@gmail.com"
] | www.kentaro.wada@gmail.com |
a988b3ca16fb889c02de19ee22047a5bcba7d39f | a276a3249780e66efffd439b567a964af0652391 | /backend/floral_truth_26698/settings.py | 7ffab9abdfda057d9c71aa73799a445278134342 | [] | no_license | crowdbotics-apps/floral-truth-26698 | b300b428438f0b8451697be38e8907a80fe62a06 | 7f22632a0dec12806e2055cdd6f6eb3da64f4e14 | refs/heads/master | 2023-04-19T16:02:52.838834 | 2021-05-14T15:43:10 | 2021-05-14T15:43:10 | 367,408,875 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,120 | py | """
Django settings for floral_truth_26698 project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
import environ
import logging
env = environ.Env()
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool("DEBUG", default=False)
# 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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env.str("SECRET_KEY")
ALLOWED_HOSTS = env.list("HOST", default=["*"])
SITE_ID = 1
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = env.bool("SECURE_REDIRECT", default=False)
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites'
]
LOCAL_APPS = [
'home',
'modules',
'users.apps.UsersConfig',
]
THIRD_PARTY_APPS = [
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_auth.registration',
'bootstrap4',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'django_extensions',
'drf_yasg',
'storages',
# start fcm_django push notifications
'fcm_django',
# end fcm_django push notifications
]
INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS
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 = 'floral_truth_26698.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'web_build')],
'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 = 'floral_truth_26698.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
if env.str("DATABASE_URL", default=None):
DATABASES = {
'default': env.db()
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
MIDDLEWARE += ['whitenoise.middleware.WhiteNoiseMiddleware']
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend'
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'web_build/static')]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# allauth / users
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "optional"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
ACCOUNT_UNIQUE_EMAIL = True
LOGIN_REDIRECT_URL = "users:redirect"
ACCOUNT_ADAPTER = "users.adapters.AccountAdapter"
SOCIALACCOUNT_ADAPTER = "users.adapters.SocialAccountAdapter"
ACCOUNT_ALLOW_REGISTRATION = env.bool("ACCOUNT_ALLOW_REGISTRATION", True)
SOCIALACCOUNT_ALLOW_REGISTRATION = env.bool("SOCIALACCOUNT_ALLOW_REGISTRATION", True)
REST_AUTH_SERIALIZERS = {
# Replace password reset serializer to fix 500 error
"PASSWORD_RESET_SERIALIZER": "home.api.v1.serializers.PasswordSerializer",
}
REST_AUTH_REGISTER_SERIALIZERS = {
# Use custom serializer that has no username and matches web signup
"REGISTER_SERIALIZER": "home.api.v1.serializers.SignupSerializer",
}
# Custom user model
AUTH_USER_MODEL = "users.User"
EMAIL_HOST = env.str("EMAIL_HOST", "smtp.sendgrid.net")
EMAIL_HOST_USER = env.str("SENDGRID_USERNAME", "")
EMAIL_HOST_PASSWORD = env.str("SENDGRID_PASSWORD", "")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# AWS S3 config
AWS_ACCESS_KEY_ID = env.str("AWS_ACCESS_KEY_ID", "")
AWS_SECRET_ACCESS_KEY = env.str("AWS_SECRET_ACCESS_KEY", "")
AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", "")
AWS_STORAGE_REGION = env.str("AWS_STORAGE_REGION", "")
USE_S3 = (
AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY and
AWS_STORAGE_BUCKET_NAME and
AWS_STORAGE_REGION
)
if USE_S3:
AWS_S3_CUSTOM_DOMAIN = env.str("AWS_S3_CUSTOM_DOMAIN", "")
AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
AWS_DEFAULT_ACL = env.str("AWS_DEFAULT_ACL", "public-read")
AWS_MEDIA_LOCATION = env.str("AWS_MEDIA_LOCATION", "media")
AWS_AUTO_CREATE_BUCKET = env.bool("AWS_AUTO_CREATE_BUCKET", True)
DEFAULT_FILE_STORAGE = env.str(
"DEFAULT_FILE_STORAGE", "home.storage_backends.MediaStorage"
)
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
# start fcm_django push notifications
FCM_DJANGO_SETTINGS = {
"FCM_SERVER_KEY": env.str("FCM_SERVER_KEY", "")
}
# end fcm_django push notifications
# Swagger settings for api docs
SWAGGER_SETTINGS = {
"DEFAULT_INFO": f"{ROOT_URLCONF}.api_info",
}
if DEBUG or not (EMAIL_HOST_USER and EMAIL_HOST_PASSWORD):
# output email to console instead of sending
if not DEBUG:
logging.warning("You should setup `SENDGRID_USERNAME` and `SENDGRID_PASSWORD` env vars to send emails.")
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
| [
"team@crowdbotics.com"
] | team@crowdbotics.com |
055ee322157756c9560886ef28e16fc0bbf63495 | 6710c52d04e17facbc9fb35a7df313f7a2a7bd53 | /1381. Design a Stack With Increment Operation.py | 2e7491daea2c04801a5525ecdf77a3a73cd84aec | [] | no_license | pwang867/LeetCode-Solutions-Python | 535088fbe747a453360457728cc22cf336020bd2 | 188befbfb7080ba1053ee1f7187b177b64cf42d2 | refs/heads/master | 2022-11-13T16:20:28.211707 | 2020-06-28T06:01:14 | 2020-06-28T06:01:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,302 | py | class CustomStack(object):
def __init__(self, maxSize):
"""
:type maxSize: int
"""
self.stack = []
self.increase = [] # same size as self.stack
self.maxSize = maxSize
def push(self, x):
"""
:type x: int
:rtype: None
"""
if len(self.stack) < self.maxSize:
self.stack.append(x)
self.increase.append(0)
def pop(self):
"""
:rtype: int
"""
if not self.stack:
return -1
res = self.stack[-1] + self.increase[-1]
self.stack.pop()
inc = self.increase.pop()
if self.increase:
self.increase[-1] += inc
return res
def increment(self, k, val):
"""
:type k: int
:type val: int
:rtype: None
"""
k = min(k, len(self.stack))
if k-1 >= 0:
self.increase[k-1] += val
# Your CustomStack object will be instantiated and called as such:
# obj = CustomStack(maxSize)
# obj.push(x)
# param_2 = obj.pop()
# obj.increment(k,val)
"""
Design a stack which supports the following operations.
Implement the CustomStack class:
CustomStack(int maxSize) Initializes the object with maxSize which is the
maximum number of elements in the stack or do nothing if the stack reached the maxSize.
void push(int x) Adds x to the top of the stack if the stack hasn't reached the maxSize.
int pop() Pops and returns the top of stack or -1 if the stack is empty.
void inc(int k, int val) Increments the bottom k elements of the stack by val.
If there are less than k elements in the stack, just increment all the elements in the stack.
Example 1:
Input
["CustomStack","push","push","pop","push","push","push","increment",
"increment","pop","pop","pop","pop"]
[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]
Output
[null,null,null,2,null,null,null,null,null,103,202,201,-1]
Explanation
CustomStack customStack = new CustomStack(3); // Stack is Empty []
customStack.push(1); // stack becomes [1]
customStack.push(2); // stack becomes [1, 2]
customStack.pop(); // return 2 --> Return top of the stack 2, stack becomes [1]
customStack.push(2); // stack becomes [1, 2]
customStack.push(3); // stack becomes [1, 2, 3]
customStack.push(4); // stack still [1, 2, 3], Don't add another elements as size is 4
customStack.increment(5, 100); // stack becomes [101, 102, 103]
customStack.increment(2, 100); // stack becomes [201, 202, 103]
customStack.pop(); // return 103 --> Return top of the stack 103, stack becomes [201, 202]
customStack.pop(); // return 202 --> Return top of the stack 102, stack becomes [201]
customStack.pop(); // return 201 --> Return top of the stack 101, stack becomes []
customStack.pop(); // return -1 --> Stack is empty return -1.
Constraints:
1 <= maxSize <= 1000
1 <= x <= 1000
1 <= k <= 1000
0 <= val <= 100
At most 1000 calls will be made to each method of increment, push and pop each separately.
"""
| [
"wzhou007@ucr.edu"
] | wzhou007@ucr.edu |
0c4ab292fbcdcac73da82da08c133ce1417f5d29 | 78d7d7aeb78a8cea6d0e10b89fc4aa6c46c95227 | /1058.py | 3aab8b5c6e234d2664ad3c6d742f7112a9165bee | [] | no_license | GenryEden/kpolyakovName | 97db13ef93061a8c2afc6cc5acd91337f79063f1 | c5d7f631ae7ec8770e56170574b82ea2b7d8a4d9 | refs/heads/master | 2023-05-23T21:22:51.983756 | 2021-06-21T08:56:49 | 2021-06-21T08:56:49 | 350,466,773 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 219 | py | def check(a):
for x in range(1, 1<<10):
for y in range(1, 1<<10):
res = (x*y < 4*a) or (x >= 21) or (x < 4*y)
if not res:
return False
return True
for a in range(1, 1<<20):
if check(a):
break
print(a) | [
"a926788@gmail.com"
] | a926788@gmail.com |
ae33221e90b454202350927d0a8ce65837dc6a9c | 2fcf738ee1aa51697739f83d93af5481ac1d8881 | /24pts(1).py | db26abd65bcf6b46bae06779bbc2668195535bf9 | [] | no_license | fanzhangg/24-points | 9c87f0a0b90b75bef3668188809ae1ec2bf571b5 | b1af45e4e664665efe2cc6551c73c30d7de9fe9e | refs/heads/master | 2020-04-09T08:18:06.248872 | 2018-12-03T12:40:39 | 2018-12-03T12:40:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,301 | py | import random
from Twenty_Four import Game
def tran(s):
if s == '+':
a = 1
def cal(a, b, c, d):
a_ = str(a)
b_ = str(b)
c_ = str(c)
d_ = str(d)
perm = [[a_] + [b_] + [c_] + [d_], [a_] + [b_] + [d_] + [c_], [a_] + [c_] + [b_] + [d_], [a_] + [c_] + [d_] + [b_],
[a_] + [d_] + [b_] + [c_], [a_] + [d_] + [c_] + [b_], [b_] + [a_] + [c_] + [d_], [b_] + [a_] + [d_] + [c_],
[b_] + [c_] + [a_] + [d_], [b_] + [c_] + [d_] + [a_], [b_] + [d_] + [a_] + [c_], [b_] + [d_] + [c_] + [a_],
[c_] + [a_] + [b_] + [d_], [c_] + [a_] + [d_] + [b_], [c_] + [b_] + [a_] + [d_], [c_] + [b_] + [d_] + [a_],
[c_] + [d_] + [a_] + [b_], [c_] + [d_] + [b_] + [a_], [d_] + [a_] + [b_] + [c_], [d_] + [a_] + [c_] + [b_],
[d_] + [b_] + [a_] + [c_], [d_] + [b_] + [c_] + [a_], [d_] + [c_] + [a_] + [b_], [d_] + [c_] + [b_] + [a_]]
symbols_1 = ['+++', '*++', '+*+', '**+', '*+*', '***', '++*', '+**',
'-++', '/++', '-*+', '/*+', '/+*', '/**', '-+*', '-**',
'+-+', '*-+', '+/+', '*/+', '*-*', '*/*', '+-*', '+/*',
'++-', '*+-', '+*-', '**-', '*+/', '**/', '++/', '+*/',
'*--', '*/-', '*-/',
'-*-', '/*-', '-*/',
'/-*', '--*', '-/*',
'//-', '/-/'
]
for nums in perm:
for syms in symbols_1:
exp = nums[0] + syms[0] + nums[1] + syms[1] + nums[2] + syms[2] + nums[3]
if eval(exp) == 24:
print(exp)
return True
for syms in symbols_1:
exp = nums[0] + syms[0] + '(' + nums[1] + syms[1] + nums[2] + syms[2] + nums[3] + ')'
if eval(nums[1] + syms[1] + nums[2] + syms[2] + nums[3]) != 0:
if eval(exp) == 24:
print(exp)
return True
for syms in symbols_1:
exp = '(' + nums[0] + syms[0] + nums[1] + ')' + syms[1] + '(' + nums[2] + syms[2] + nums[3] + ')'
if eval(nums[2] + syms[2] + nums[3]) != 0 or syms[1] != '/':
if eval(exp) == 24:
print(exp)
return True
for syms in symbols_1:
exp = nums[0] + syms[0] + '(' + nums[1] + syms[1] + nums[2] + ')' + syms[2] + nums[3]
if eval(nums[1] + syms[1] + nums[2]) != 0:
if eval(exp) == 24:
print(exp)
return True
for syms in symbols_1:
exp = '(' + nums[0] + syms[0] + nums[1] + ')' + syms[1] + nums[2] + syms[2] + nums[3]
if eval(exp) == 24:
print(exp)
return True
print("No solution")
return 0
if __name__ == '__main__':
# nums_collection = get_nums_collection(1000)
#
# test(nums_collection)
#
# count = 0
#
# for i in nums_collection:
# a = i[0]
# b = i[1]
# c = i[2]
# d = i[3]
#
# if cal(a, b, c, d) != 0:
# count += 1
#
#
# print("lv's Game has"+str(count)+"solutions")
if __name__ == "__main__":
count = 1
for a in range(1, 11):
for b in range(1, 11):
for c in range(1, 11):
for d in range(1, 11):
print("Given numbers : " + str(a) + ',' + str(b) + ',' + str(c) + ',' + str(d))
if cal(a, b, c, d) is True:
count += 1
print("Number of Solutions : " + str(count))
# if __name__ == '__main__':
# i = 0
# count = 0
# li = [0,0,0,0,0]
# dic = {'+++':0, '*++':0, '+*+':0, '**+':0, '*+*':0, '***':0, '++*':0, '+**':0,
# '-++':0, '/++':0, '-*+':0, '/*+':0, '/+*':0, '/**':0, '-+*':0, '-**':0,
# '+-+':0, '*-+':0, '+/+':0, '*/+':0, '*-*':0, '*/*':0, '+-*':0, '+/*':0,
# '++-':0, '*+-':0, '+*-':0, '**-':0, '*+/':0, '**/':0, '++/':0, '+*/':0,
# '+--':0, '*--':0, '+/-':0, '*/-':0, '*-/':0, '*//':0, '+-/':0, '+//':0,
# '-+-':0, '/+-':0, '-*-':0, '/*-':0, '/+/':0, '/*/':0, '-+/':0, '-*/':0,
# '--+':0, '/-+':0, '-/+':0, '//+':0, '/-*':0, '//*':0, '--*':0, '-/*':0,
# '---':0, '/--':0, '-/-':0, '//-':0, '/-/':0, '///':0, '--/':0, '-//':0
# }
# while i < 1000:
# a = random.randint(1, 10)
# b = random.randint(1, 10)
# c = random.randint(1, 10)
# d = random.randint(1, 10)
# print("Given numbers : " + str(a) + ',' + str(b) + ',' + str(c) + ',' + str(d))
# m = cal(a, b, c, d)
# if m != 0:
# li[m-1] += 1
# count += 1
# i += 1
# print("Number of Solutions : " + str(count))
# print(li)
# for a in range(1, 11):
# for b in range(1, 11):
# for c in range(1, 11):
# for d in range(1, 11):
# print("Given numbers : " + str(a) + ',' + str(b) + ',' + str(c) + ',' + str(d))
# m = cal(a, b, c, d)
# if m in dic:
# count += 1
# dic[m] += 1
# print("Number of Solutions : " + str(count))
# print(dic)
| [
"vanadiumzhang@gmail.com"
] | vanadiumzhang@gmail.com |
8833b3a38aaef481c4511cb4998d5dca051dbcd4 | c16ea32a4cddb6b63ad3bacce3c6db0259d2bacd | /google/devtools/remoteworkers/v1test2/devtools-remoteworkers-v1test2-py/google/devtools/remoteworkers_v1/services/bots/transports/grpc.py | 2e156f88902fd67375585b598d17c511732d36ce | [
"Apache-2.0"
] | permissive | dizcology/googleapis-gen | 74a72b655fba2565233e5a289cfaea6dc7b91e1a | 478f36572d7bcf1dc66038d0e76b9b3fa2abae63 | refs/heads/master | 2023-06-04T15:51:18.380826 | 2021-06-16T20:42:38 | 2021-06-16T20:42:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,154 | py | # -*- coding: utf-8 -*-
# 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.
#
import warnings
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import gapic_v1 # type: ignore
import google.auth # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
from google.devtools.remoteworkers_v1.types import bots
from .base import BotsTransport, DEFAULT_CLIENT_INFO
class BotsGrpcTransport(BotsTransport):
"""gRPC backend transport for Bots.
Design doc: https://goo.gl/oojM5H
Loosely speaking, the Bots interface monitors a collection of
workers (think of them as "computers" for a moment). This collection
is known as a "farm," and its purpose is to perform work on behalf
of a client.
Each worker runs a small program known as a "bot" that allows it to
be controlled by the server. This interface contains only methods
that are called by the bots themselves; admin functionality is out
of scope for this interface.
More precisely, we use the term "worker" to refer to the physical
"thing" running the bot. We use the term "worker," and not "machine"
or "computer," since a worker may consist of more than one machine -
e.g., a computer with multiple attached devices, or even a cluster
of computers, with only one of them running the bot. Conversely, a
single machine may host several bots, in which case each bot has a
"worker" corresponding to the slice of the machine being managed by
that bot.
The main resource in the Bots interface is not, surprisingly, a Bot
- it is a BotSession, which represents a period of time in which a
bot is in continuous contact with the server (see the BotSession
message for more information). The parent of a bot session can be
thought of as an instance of a farm. That is, one endpoint may be
able to manage many farms for many users. For example, for a farm
managed through GCP, the parent resource will typically take the
form "projects/{project_id}". This is referred to below as "the farm
resource."
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
It sends protocol buffers over the wire using gRPC (which is built on
top of HTTP/2); the ``grpcio`` package must be installed.
"""
_stubs: Dict[str, Callable]
def __init__(self, *,
host: str = 'remoteworkers.googleapis.com',
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional(Sequence[str])): A list of scopes. This argument is
ignored if ``channel`` is provided.
channel (Optional[grpc.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
If provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from
``client_cert_source`` or applicatin default SSL credentials.
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
Deprecated. A callback to provide client SSL certificate bytes and
private key bytes, both in PEM format. It is ignored if
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
A callback to provide client certificate bytes and private key bytes,
both in PEM format. It is used to configure mutual TLS channel. It is
ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
self._stubs: Dict[str, Callable] = {}
if api_mtls_endpoint:
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
if client_cert_source:
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
# Ignore credentials if a channel was passed.
credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
else:
if api_mtls_endpoint:
host = api_mtls_endpoint
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
cert, key = client_cert_source()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
else:
self._ssl_channel_credentials = SslCredentials().ssl_credentials
else:
if client_cert_source_for_mtls and not ssl_channel_credentials:
cert, key = client_cert_source_for_mtls()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
# The base transport sets the host, credentials and scopes
super().__init__(
host=host,
credentials=credentials,
credentials_file=credentials_file,
scopes=scopes,
quota_project_id=quota_project_id,
client_info=client_info,
)
if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
self._host,
credentials=self._credentials,
credentials_file=credentials_file,
scopes=self._scopes,
ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
# Wrap messages. This must be done after self._grpc_channel exists
self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(cls,
host: str = 'remoteworkers.googleapis.com',
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
**kwargs) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
grpc.Channel: A gRPC channel object.
Raises:
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes)
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
quota_project_id=quota_project_id,
**self_signed_jwt_kwargs,
**kwargs
)
@property
def grpc_channel(self) -> grpc.Channel:
"""Return the channel designed to connect to this service.
"""
return self._grpc_channel
@property
def create_bot_session(self) -> Callable[
[bots.CreateBotSessionRequest],
bots.BotSession]:
r"""Return a callable for the create bot session method over gRPC.
CreateBotSession is called when the bot first joins
the farm, and establishes a session ID to ensure that
multiple machines do not register using the same name
accidentally.
Returns:
Callable[[~.CreateBotSessionRequest],
~.BotSession]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'create_bot_session' not in self._stubs:
self._stubs['create_bot_session'] = self.grpc_channel.unary_unary(
'/google.devtools.remoteworkers.v1test2.Bots/CreateBotSession',
request_serializer=bots.CreateBotSessionRequest.serialize,
response_deserializer=bots.BotSession.deserialize,
)
return self._stubs['create_bot_session']
@property
def update_bot_session(self) -> Callable[
[bots.UpdateBotSessionRequest],
bots.BotSession]:
r"""Return a callable for the update bot session method over gRPC.
UpdateBotSession must be called periodically by the
bot (on a schedule determined by the server) to let the
server know about its status, and to pick up new lease
requests from the server.
Returns:
Callable[[~.UpdateBotSessionRequest],
~.BotSession]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'update_bot_session' not in self._stubs:
self._stubs['update_bot_session'] = self.grpc_channel.unary_unary(
'/google.devtools.remoteworkers.v1test2.Bots/UpdateBotSession',
request_serializer=bots.UpdateBotSessionRequest.serialize,
response_deserializer=bots.BotSession.deserialize,
)
return self._stubs['update_bot_session']
__all__ = (
'BotsGrpcTransport',
)
| [
"bazel-bot-development[bot]@users.noreply.github.com"
] | bazel-bot-development[bot]@users.noreply.github.com |
d387e57f07e02b2094073d41ec379c41efd390d1 | ac4b9385b7ad2063ea51237fbd8d1b74baffd016 | /.history/connectors/pg_20210220003754.py | e0f701c3c1989cad9eabb69d91b22399c15954f0 | [] | no_license | preethanpa/ssoemprep | 76297ef21b1d4893f1ac2f307f60ec72fc3e7c6f | ce37127845253c768d01aeae85e5d0d1ade64516 | refs/heads/main | 2023-03-09T00:15:55.130818 | 2021-02-20T06:54:58 | 2021-02-20T06:54:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 18,736 | py | import os
import logging
import select
from contextlib import contextmanager
from base64 import b64decode
from tempfile import NamedTemporaryFile
from uuid import uuid4
import psycopg2
from psycopg2.extras import Range
from .query_runner import *
from trir.utils import JSONEncoder, json_dumps, json_loads
logger = logging.getLogger(__name__)
try:
import boto3
IAM_ENABLED = True
except ImportError:
IAM_ENABLED = False
types_map = {
20: TYPE_INTEGER,
21: TYPE_INTEGER,
23: TYPE_INTEGER,
700: TYPE_FLOAT,
1700: TYPE_FLOAT,
701: TYPE_FLOAT,
16: TYPE_BOOLEAN,
1082: TYPE_DATE,
1114: TYPE_DATETIME,
1184: TYPE_DATETIME,
1014: TYPE_STRING,
1015: TYPE_STRING,
1008: TYPE_STRING,
1009: TYPE_STRING,
2951: TYPE_STRING,
}
class PostgreSQLJSONEncoder(JSONEncoder):
def default(self, o):
if isinstance(o, Range):
# From: https://github.com/psycopg/psycopg2/pull/779
if o._bounds is None:
return ""
items = [o._bounds[0], str(o._lower), ", ", str(o._upper), o._bounds[1]]
return "".join(items)
return super(PostgreSQLJSONEncoder, self).default(o)
def _wait(conn, timeout=None):
while 1:
try:
state = conn.poll()
if state == psycopg2.extensions.POLL_OK:
break
elif state == psycopg2.extensions.POLL_WRITE:
select.select([], [conn.fileno()], [], timeout)
elif state == psycopg2.extensions.POLL_READ:
select.select([conn.fileno()], [], [], timeout)
else:
raise psycopg2.OperationalError("poll() returned %s" % state)
except select.error:
raise psycopg2.OperationalError("select.error received")
def full_table_name(schema, name):
if "." in name:
name = '"{}"'.format(name)
return "{}.{}".format(schema, name)
def build_schema(query_result, schema):
# By default we omit the public schema name from the table name. But there are
# edge cases, where this might cause conflicts. For example:
# * We have a schema named "main" with table "users".
# * We have a table named "main.users" in the public schema.
# (while this feels unlikely, this actually happened)
# In this case if we omit the schema name for the public table, we will have
# a conflict.
table_names = set(
map(
lambda r: full_table_name(r["table_schema"], r["table_name"]),
query_result["rows"],
)
)
for row in query_result["rows"]:
if row["table_schema"] != "public":
table_name = full_table_name(row["table_schema"], row["table_name"])
else:
if row["table_name"] in table_names:
table_name = full_table_name(row["table_schema"], row["table_name"])
else:
table_name = row["table_name"]
if table_name not in schema:
schema[table_name] = {"name": table_name, "columns": []}
column = row["column_name"]
if row.get("data_type") is not None:
column = {"name": row["column_name"], "type": row["data_type"]}
schema[table_name]["columns"].append(column)
def _create_cert_file(configuration, key, ssl_config):
file_key = key + "File"
if file_key in configuration:
with NamedTemporaryFile(mode="w", delete=False) as cert_file:
cert_bytes = b64decode(configuration[file_key])
cert_file.write(cert_bytes.decode("utf-8"))
ssl_config[key] = cert_file.name
def _cleanup_ssl_certs(ssl_config):
for k, v in ssl_config.items():
if k != "sslmode":
os.remove(v)
def _get_ssl_config(configuration):
ssl_config = {"sslmode": configuration.get("sslmode", "prefer")}
_create_cert_file(configuration, "sslrootcert", ssl_config)
_create_cert_file(configuration, "sslcert", ssl_config)
_create_cert_file(configuration, "sslkey", ssl_config)
return ssl_config
class PostgreSQL(BaseSQLQueryRunner):
noop_query = "SELECT 1"
@classmethod
def configuration_schema(cls):
return {
"type": "object",
"properties": {
"user": {"type": "string"},
"password": {"type": "string"},
"host": {"type": "string", "default": "127.0.0.1"},
"port": {"type": "number", "default": 5432},
"dbname": {"type": "string", "title": "Database Name"},
"sslmode": {
"type": "string",
"title": "SSL Mode",
"default": "prefer",
"extendedEnum": [
{"value": "disable", "name": "Disable"},
{"value": "allow", "name": "Allow"},
{"value": "prefer", "name": "Prefer"},
{"value": "require", "name": "Require"},
{"value": "verify-ca", "name": "Verify CA"},
{"value": "verify-full", "name": "Verify Full"},
],
},
"sslrootcertFile": {"type": "string", "title": "SSL Root Certificate"},
"sslcertFile": {"type": "string", "title": "SSL Client Certificate"},
"sslkeyFile": {"type": "string", "title": "SSL Client Key"},
},
"order": ["host", "port", "user", "password"],
"required": ["dbname"],
"secret": ["password"],
"extra_options": [
"sslmode",
"sslrootcertFile",
"sslcertFile",
"sslkeyFile",
],
}
@classmethod
def type(cls):
return "pg"
def _get_definitions(self, schema, query):
results, error = self.run_query(query, None)
if error is not None:
raise Exception("Failed getting schema.")
results = json_loads(results)
build_schema(results, schema)
def _get_tables(self, schema):
"""
relkind constants per https://www.postgresql.org/docs/10/static/catalog-pg-class.html
r = regular table
v = view
m = materialized view
f = foreign table
p = partitioned table (new in 10)
---
i = index
S = sequence
t = TOAST table
c = composite type
"""
query = """
SELECT s.nspname as table_schema,
c.relname as table_name,
a.attname as column_name,
null as data_type
FROM pg_class c
JOIN pg_namespace s
ON c.relnamespace = s.oid
AND s.nspname NOT IN ('pg_catalog', 'information_schema')
JOIN pg_attribute a
ON a.attrelid = c.oid
AND a.attnum > 0
AND NOT a.attisdropped
WHERE c.relkind IN ('m', 'f', 'p')
UNION
SELECT table_schema,
table_name,
column_name,
data_type
FROM information_schema.columns
WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
"""
self._get_definitions(schema, query)
return list(schema.values())
def _get_connection(self):
self.ssl_config = _get_ssl_config(self.configuration)
connection = psycopg2.connect(
user=self.configuration.get("user"),
password=self.configuration.get("password"),
host=self.configuration.get("host"),
port=self.configuration.get("port"),
dbname=self.configuration.get("dbname"),
async_=True,
**self.ssl_config,
)
return connection
def run_query(self, query, user):
connection = self._get_connection()
_wait(connection, timeout=10)
cursor = connection.cursor()
try:
cursor.execute(query)
_wait(connection)
if cursor.description is not None:
columns = self.fetch_columns(
[(i[0], types_map.get(i[1], None)) for i in cursor.description]
)
rows = [
dict(zip((column["name"] for column in columns), row))
for row in cursor
]
data = {"columns": columns, "rows": rows}
error = None
json_data = json_dumps(data, ignore_nan=True, cls=PostgreSQLJSONEncoder)
else:
error = "Query completed but it returned no data."
json_data = None
except (select.error, OSError) as e:
error = "Query interrupted. Please retry."
json_data = None
except psycopg2.DatabaseError as e:
error = str(e)
json_data = None
except (KeyboardInterrupt, InterruptException, JobTimeoutException):
connection.cancel()
raise
finally:
connection.close()
_cleanup_ssl_certs(self.ssl_config)
return json_data, error
class Redshift(PostgreSQL):
@classmethod
def type(cls):
return "redshift"
@classmethod
def name(cls):
return "Redshift"
def _get_connection(self):
self.ssl_config = {}
sslrootcert_path = os.path.join(
os.path.dirname(__file__), "./files/redshift-ca-bundle.crt"
)
connection = psycopg2.connect(
user=self.configuration.get("user"),
password=self.configuration.get("password"),
host=self.configuration.get("host"),
port=self.configuration.get("port"),
dbname=self.configuration.get("dbname"),
sslmode=self.configuration.get("sslmode", "prefer"),
sslrootcert=sslrootcert_path,
async_=True,
)
return connection
@classmethod
def configuration_schema(cls):
return {
"type": "object",
"properties": {
"user": {"type": "string"},
"password": {"type": "string"},
"host": {"type": "string"},
"port": {"type": "number"},
"dbname": {"type": "string", "title": "Database Name"},
"sslmode": {"type": "string", "title": "SSL Mode", "default": "prefer"},
"adhoc_query_group": {
"type": "string",
"title": "Query Group for Adhoc Queries",
"default": "default",
},
"scheduled_query_group": {
"type": "string",
"title": "Query Group for Scheduled Queries",
"default": "default",
},
},
"order": [
"host",
"port",
"user",
"password",
"dbname",
"sslmode",
"adhoc_query_group",
"scheduled_query_group",
],
"required": ["dbname", "user", "password", "host", "port"],
"secret": ["password"],
}
def annotate_query(self, query, metadata):
annotated = super(Redshift, self).annotate_query(query, metadata)
if metadata.get("Scheduled", False):
query_group = self.configuration.get("scheduled_query_group")
else:
query_group = self.configuration.get("adhoc_query_group")
if query_group:
set_query_group = "set query_group to {};".format(query_group)
annotated = "{}\n{}".format(set_query_group, annotated)
return annotated
def _get_tables(self, schema):
# Use svv_columns to include internal & external (Spectrum) tables and views data for Redshift
# https://docs.aws.amazon.com/redshift/latest/dg/r_SVV_COLUMNS.html
# Use HAS_SCHEMA_PRIVILEGE(), SVV_EXTERNAL_SCHEMAS and HAS_TABLE_PRIVILEGE() to filter
# out tables the current user cannot access.
# https://docs.aws.amazon.com/redshift/latest/dg/r_HAS_SCHEMA_PRIVILEGE.html
# https://docs.aws.amazon.com/redshift/latest/dg/r_SVV_EXTERNAL_SCHEMAS.html
# https://docs.aws.amazon.com/redshift/latest/dg/r_HAS_TABLE_PRIVILEGE.html
query = """
WITH tables AS (
SELECT DISTINCT table_name,
table_schema,
column_name,
ordinal_position AS pos
FROM svv_columns
WHERE table_schema NOT IN ('pg_internal','pg_catalog','information_schema')
AND table_schema NOT LIKE 'pg_temp_%'
)
SELECT table_name, table_schema, column_name
FROM tables
WHERE
HAS_SCHEMA_PRIVILEGE(table_schema, 'USAGE') AND
(
table_schema IN (SELECT schemaname FROM SVV_EXTERNAL_SCHEMAS) OR
HAS_TABLE_PRIVILEGE('"' || table_schema || '"."' || table_name || '"', 'SELECT')
)
ORDER BY table_name, pos
"""
self._get_definitions(schema, query)
return list(schema.values())
class RedshiftIAM(Redshift):
@classmethod
def type(cls):
return "redshift_iam"
@classmethod
def name(cls):
return "Redshift (with IAM User/Role)"
@classmethod
def enabled(cls):
return IAM_ENABLED
def _login_method_selection(self):
if self.configuration.get("rolename"):
if not self.configuration.get(
"aws_access_key_id"
) or not self.configuration.get("aws_secret_access_key"):
return "ASSUME_ROLE_NO_KEYS"
else:
return "ASSUME_ROLE_KEYS"
elif self.configuration.get("aws_access_key_id") and self.configuration.get(
"aws_secret_access_key"
):
return "KEYS"
elif not self.configuration.get("password"):
return "ROLE"
@classmethod
def configuration_schema(cls):
return {
"type": "object",
"properties": {
"rolename": {"type": "string", "title": "IAM Role Name"},
"aws_region": {"type": "string", "title": "AWS Region"},
"aws_access_key_id": {"type": "string", "title": "AWS Access Key ID"},
"aws_secret_access_key": {
"type": "string",
"title": "AWS Secret Access Key",
},
"clusterid": {"type": "string", "title": "Redshift Cluster ID"},
"user": {"type": "string"},
"host": {"type": "string"},
"port": {"type": "number"},
"dbname": {"type": "string", "title": "Database Name"},
"sslmode": {"type": "string", "title": "SSL Mode", "default": "prefer"},
"adhoc_query_group": {
"type": "string",
"title": "Query Group for Adhoc Queries",
"default": "default",
},
"scheduled_query_group": {
"type": "string",
"title": "Query Group for Scheduled Queries",
"default": "default",
},
},
"order": [
"rolename",
"aws_region",
"aws_access_key_id",
"aws_secret_access_key",
"clusterid",
"host",
"port",
"user",
"dbname",
"sslmode",
"adhoc_query_group",
"scheduled_query_group",
],
"required": ["dbname", "user", "host", "port", "aws_region"],
"secret": ["aws_secret_access_key"],
}
def _get_connection(self):
sslrootcert_path = os.path.join(
os.path.dirname(__file__), "./files/redshift-ca-bundle.crt"
)
login_method = self._login_method_selection()
if login_method == "KEYS":
client = boto3.client(
"redshift",
region_name=self.configuration.get("aws_region"),
aws_access_key_id=self.configuration.get("aws_access_key_id"),
aws_secret_access_key=self.configuration.get("aws_secret_access_key"),
)
elif login_method == "ROLE":
client = boto3.client(
"redshift", region_name=self.configuration.get("aws_region")
)
else:
if login_method == "ASSUME_ROLE_KEYS":
assume_client = client = boto3.client(
"sts",
region_name=self.configuration.get("aws_region"),
aws_access_key_id=self.configuration.get("aws_access_key_id"),
aws_secret_access_key=self.configuration.get(
"aws_secret_access_key"
),
)
else:
assume_client = client = boto3.client(
"sts", region_name=self.configuration.get("aws_region")
)
role_session = f"trir_{uuid4().hex}"
session_keys = assume_client.assume_role(
RoleArn=self.configuration.get("rolename"), RoleSessionName=role_session
)["Credentials"]
client = boto3.client(
"redshift",
region_name=self.configuration.get("aws_region"),
aws_access_key_id=session_keys["AccessKeyId"],
aws_secret_access_key=session_keys["SecretAccessKey"],
aws_session_token=session_keys["SessionToken"],
)
credentials = client.get_cluster_credentials(
DbUser=self.configuration.get("user"),
DbName=self.configuration.get("dbname"),
ClusterIdentifier=self.configuration.get("clusterid"),
)
db_user = credentials["DbUser"]
db_password = credentials["DbPassword"]
connection = psycopg2.connect(
user=db_user,
password=db_password,
host=self.configuration.get("host"),
port=self.configuration.get("port"),
dbname=self.configuration.get("dbname"),
sslmode=self.configuration.get("sslmode", "prefer"),
sslrootcert=sslrootcert_path,
async_=True,
)
return connection
class CockroachDB(PostgreSQL):
@classmethod
def type(cls):
return "cockroach"
register(PostgreSQL)
register(Redshift)
register(RedshiftIAM)
register(CockroachDB)
| [
"{abhi@third-ray.com}"
] | {abhi@third-ray.com} |
677f423defa59332ac699b790fc922baf8137943 | 99f43f4591f63d0c57cd07f07af28c0b554b8e90 | /python/beckjun/A형 특훈/14889 스타트와 링크 itertools.py | 04ec3ba1f53a5ef03e836f75486e2e84597a49e4 | [] | no_license | SINHOLEE/Algorithm | 049fa139f89234dd626348c753d97484fab811a7 | 5f39d45e215c079862871636d8e0306d6c304f7e | refs/heads/master | 2023-04-13T18:55:11.499413 | 2023-04-10T06:21:29 | 2023-04-10T06:21:29 | 199,813,684 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 900 | py | '''
탐색종료시점을 잘 생각하자.
if min_score ==0:
break
이거 하나로 몇배나 빨라졌다.
'''
from itertools import combinations
n = int(input())
mat = [list(map(int, input().split())) for _ in range(n)]
def cal(lis1):
lis2 = list(filter(lambda x: x not in lis1, range(n)))
l = len(lis1)
a_val = 0
b_val = 0
visited = [0] * l
for i in range(l):
visited[i] = 1
for j in range(i+1, l):
if j > i and visited[j] == 0:
a_val = a_val + mat[lis1[i]][lis1[j]] + mat[lis1[j]][lis1[i]]
b_val = b_val + mat[lis2[i]][lis2[j]] + mat[lis2[j]][lis2[i]]
visited[i] = 0
return abs(a_val - b_val)
min_score = 9876543211
for comb in combinations(range(n), n//2):
sub_val = cal(comb)
if min_score > sub_val:
min_score = sub_val
if min_score == 0:
break
print(min_score)
| [
"dltlsgh5@naver.com"
] | dltlsgh5@naver.com |
9dd7045bbccedcd5b763377bf2a8b5edb9d5cc0a | 49b54185d467fdcdf51fb4f363c09026cef29c5e | /code_examples/4.1B_subscribing_to_an_observable.py | 118da04aed8f7e446bc5d953f45c779a4e9b5f79 | [] | no_license | kinowarrior/oreilly_reactive_python_for_data | ef0f580856aff0a398315a4f7c5f7e22533a686e | 5206fd3cc7e40d871dcfea6b4d30022f8d06c16c | refs/heads/master | 2020-05-19T03:08:05.634115 | 2019-05-06T12:07:38 | 2019-05-06T12:07:38 | 184,793,899 | 0 | 0 | null | 2019-05-03T17:21:01 | 2019-05-03T17:21:00 | null | UTF-8 | Python | false | false | 383 | py | from rx import Observable, Observer
letters = Observable.from_(["Alpha","Beta","Gamma","Delta","Epsilon"])
class MySubscriber(Observer):
def on_next(self, value):
print(value)
def on_completed(self):
print("Completed!")
def on_error(self, error):
print("Error occured: {0}".format(error))
letters.subscribe(MySubscriber())
| [
"thomasnield@live.com"
] | thomasnield@live.com |
f9601982ec27c65ea0ec27744fa3fdefebf9e866 | 6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4 | /wEDHiAcALvS2KuRBJ_17.py | ea2deab4f3a764fd9d1a287738403df66623257f | [] | 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 | 1,041 | py |
class StackCalc:
def __init__(self):
self.s = []
self.err = False
def run(self, instructions):
for i in instructions.split():
if not self.err:
if i.isdigit():
self.s += [int(i)]
elif i == '+':
self.s += [self.s.pop() + self.s.pop()]
elif i == '-':
self.s += [self.s.pop() - self.s.pop()]
elif i == '*':
self.s += [self.s.pop() * self.s.pop()]
elif i == '/':
self.s += [int(self.s.pop() / self.s.pop())]
elif i == 'DUP':
self.s += [self.s[-1]]
elif i == 'POP':
self.s.pop()
else:
self.ret = 'Invalid instruction: '+i
self.err = True
def getValue(self):
if self.err:
return self.ret
if not self.s:
return 0
return self.s[-1]
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
dd7db101067a85f5d04748535f2d184c404bdd04 | 8b9d3fa48e87579a74b187abf781d5916b6b47df | /geoutils/bin/geogdelt | 01cea63360e9ada367f374463fcfb621578c4749 | [] | no_license | loum/geoutils | 3f34b10bfaff8978af09f01de03723b71cd8be4f | 034787d9a54856dac12988aaa05c366c5da4d7ec | refs/heads/master | 2021-01-19T08:54:54.983763 | 2014-12-01T04:59:50 | 2014-12-01T04:59:50 | 22,494,847 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,805 | #!/usr/bin/python
"""Load GDELT files into the Accumulo datastore.
"""
import os
import inspect
import sys
import daemoniser
import geoutils
CONF = os.path.join(os.sep, 'etc', 'geoutils', 'conf', 'geoutils.conf')
def main():
"""Script entry point.
"""
service = daemoniser.Service()
service.parser.add_option('-f', '--file',
dest='file',
help='file to process inline (start only)')
service.parser.add_option('-r', '--remove',
dest='remove',
action='store_true',
help='delete file after processing')
script_name = os.path.basename(inspect.getfile(inspect.currentframe()))
service.check_args(script_name)
# Check if a filename was provided on the command line.
command_line_file = None
if service.options.file:
command_line_file = service.options.file
remove_file = False
if service.options.remove:
remove_file = service.options.remove
config_file = service.options.config
if config_file is None:
if os.path.exists(CONF):
config_file = CONF
if config_file is None:
sys.exit('Unable to source the geoutils.conf')
else:
conf = geoutils.GdeltConfig(config_file)
conf.parse_config()
# OK, start processing.
gdeltd = geoutils.GdeltDaemon(pidfile=service.pidfile,
filename=command_line_file,
dry=service.dry,
batch=service.batch,
conf=conf,
delete=remove_file)
service.launch_command(gdeltd, script_name)
if __name__ == '__main__':
main()
| [
"lou.markovski@gmail.com"
] | lou.markovski@gmail.com | |
dc99239af8da0845d4171c157e926644349a9b68 | d54cb7a8a26dbf57423511a14cbb6f150ea4bafb | /setup.py | 195fdc163936b3bc230a2a38da75f82c5744e50c | [] | no_license | inclement/vivarium-old | 8957bfbf0073d0b772e47820969b585e627518cf | e9f826edcba35caad3856fc7093f728975d190bd | refs/heads/master | 2021-06-16T02:05:46.221998 | 2017-05-07T21:49:37 | 2017-05-07T21:49:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 713 | py |
from setuptools import setup, find_packages
from os import walk
from os.path import join, dirname, sep
import os
import glob
packages = find_packages()
package_data = {'pywlc': ['*.py',
'*_cdef.h',
'wlc.c'], }
data_files = []
setup(name='pywm',
version='0.1',
description='An experimental Wayland compositor using wlc.',
author='Alexander Taylor',
author_email='alexanderjohntaylor@gmail.com',
url='https://github.com/inclement/pywm',
license='MIT',
# install_requires=['cffi>=1.0.0'],
# cffi_modules=['pywm/make_callbacks.py:ffibuilder'],
packages=packages,
package_data=package_data,
)
| [
"alexanderjohntaylor@gmail.com"
] | alexanderjohntaylor@gmail.com |
726ddd1a3d02da7c171166f5be435dc054cfb5b1 | 0f24c1e2df268a7c98314d5b3c6f8b5738f88ba9 | /graphsense/model/search_result_level2.py | 4e7853e8813513b9bc3586518c459afde0656912 | [
"MIT"
] | permissive | arberx/graphsense-python | b07be2854d4f6e763aacdad4045ae72c338bd4e2 | c0dafc97a04bc3dbf0caf08a981bb591bd1e430a | refs/heads/master | 2023-08-11T14:15:42.576434 | 2021-06-17T08:01:04 | 2021-06-17T08:01:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,613 | py | """
GraphSense API
GraphSense API # noqa: E501
The version of the OpenAPI document: 0.5
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from graphsense.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
def lazy_import():
from graphsense.model.address import Address
from graphsense.model.entity import Entity
from graphsense.model.neighbor import Neighbor
from graphsense.model.search_result_leaf import SearchResultLeaf
from graphsense.model.search_result_level2_all_of import SearchResultLevel2AllOf
from graphsense.model.search_result_level3 import SearchResultLevel3
globals()['Address'] = Address
globals()['Entity'] = Entity
globals()['Neighbor'] = Neighbor
globals()['SearchResultLeaf'] = SearchResultLeaf
globals()['SearchResultLevel2AllOf'] = SearchResultLevel2AllOf
globals()['SearchResultLevel3'] = SearchResultLevel3
class SearchResultLevel2(ModelComposed):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
}
validations = {
}
@cached_property
def additional_properties_type():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
"""
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
lazy_import()
return {
'matching_addresses': ([Address],), # noqa: E501
'node': (Entity,), # noqa: E501
'relation': (Neighbor,), # noqa: E501
'paths': ([SearchResultLevel3],), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
'matching_addresses': 'matching_addresses', # noqa: E501
'node': 'node', # noqa: E501
'relation': 'relation', # noqa: E501
'paths': 'paths', # noqa: E501
}
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
'_composed_instances',
'_var_name_to_model_instances',
'_additional_properties_model_instances',
])
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs): # noqa: E501
"""SearchResultLevel2 - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
matching_addresses ([Address]): [optional] # noqa: E501
node (Entity): [optional] # noqa: E501
relation (Neighbor): [optional] # noqa: E501
paths ([SearchResultLevel3]): Branches to matching entities. [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
constant_args = {
'_check_type': _check_type,
'_path_to_item': _path_to_item,
'_spec_property_naming': _spec_property_naming,
'_configuration': _configuration,
'_visited_composed_classes': self._visited_composed_classes,
}
required_args = {
}
model_args = {}
model_args.update(required_args)
model_args.update(kwargs)
composed_info = validate_get_composed_info(
constant_args, model_args, self)
self._composed_instances = composed_info[0]
self._var_name_to_model_instances = composed_info[1]
self._additional_properties_model_instances = composed_info[2]
unused_args = composed_info[3]
for var_name, var_value in required_args.items():
setattr(self, var_name, var_value)
for var_name, var_value in kwargs.items():
if var_name in unused_args and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
not self._additional_properties_model_instances:
# discard variable.
continue
setattr(self, var_name, var_value)
@cached_property
def _composed_schemas():
# we need this here to make our import statements work
# we must store _composed_schemas in here so the code is only run
# when we invoke this method. If we kept this at the class
# level we would get an error beause the class level
# code would be run when this module is imported, and these composed
# classes don't exist yet because their module has not finished
# loading
lazy_import()
return {
'anyOf': [
],
'allOf': [
SearchResultLeaf,
SearchResultLevel2AllOf,
],
'oneOf': [
],
}
| [
"git@myrho.net"
] | git@myrho.net |
1e90815b46685bf505b7aaac11595e9b89aa21eb | 28a124b6a2f22a53af3b6bb754e77af88b4138e1 | /DJANGO/ecommerce/ecommerce/settings.py | 83512d1e10f2ad147fb23f05983f4075b7b7c344 | [] | no_license | mebaysan/LearningKitforBeginners-Python | f7c6668a9978b52cad6cc2b969990d7bbfedc376 | 9e1a47fb14b3d81c5b009b74432902090e213085 | refs/heads/master | 2022-12-21T03:12:19.892857 | 2021-06-22T11:58:27 | 2021-06-22T11:58:27 | 173,840,726 | 18 | 4 | null | 2022-12-10T03:00:22 | 2019-03-04T23:56:27 | Python | UTF-8 | Python | false | false | 3,215 | py | """
ADMIN USER
username -> admin
password -> 123
"""
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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y_-l5@jh%s_s%01gkb6jj-le7a17k@vqquy$8$v@95%38ob(vt'
# 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',
'store.apps.StoreConfig',
]
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 = 'ecommerce.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'store.context_processor.menu_links',
'store.context_processor.counter',
],
},
},
]
WSGI_APPLICATION = 'ecommerce.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "staticfiles"),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')
MEDIA_URL = '/media/'
| [
"menesbaysan@gmail.com"
] | menesbaysan@gmail.com |
d75e2100383263a57b5092934b0d2aafcf1626e4 | 211618a491e8031551c7bffbc867b9f85134f650 | /dao/tdkspider.py | ccd1261db75f18506d2ca7701dfdefb82ab8398e | [] | no_license | xjl12322/xinnetSpiderCode | 260c90cee89e070e4cba24d21f80f836440b435a | 3afdccd6797ad61a2de29fb39cc28cb1cc916bb1 | refs/heads/master | 2020-03-26T08:09:58.521521 | 2018-08-14T07:07:46 | 2018-08-14T07:07:46 | 144,689,008 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,788 | py | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
__author__ = "X"
__date__ = "2017/11/6 20:09"
import requests,redis
import json,sys
import re
from lxml import etree
dict_encode = {"utf-8": "utf-8", "GB2312": "gbk", "Windows-": "utf-8"}
# def return_code(url):
# data = {
# "domain": url,
# "title": "",
# "description": "",
# "keywords": ""
# }
# jsondata = json.dumps(data)
# return -1, jsondata
def get_list_url(url,es):
'''发送网页请求'''
header = {
"user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"}
# r = redis.StrictRedis(host="127.0.0.1", port=6379, db=0)
# r = redis.StrictRedis(host="10.2.1.173", port=17480, password="J9O543637e5SYaymJge", db=0)
try:
response = requests.get(url="http://www.{}".format(url),headers=header,timeout=6)
except Exception as e:
# return return_code(url)
return None
if response.status_code!=200:
return None
try:
judgment = response.apparent_encoding
if judgment in dict_encode:
response.encoding = dict_encode[judgment]
elif judgment.startswith("ISO-"):
response.encoding = dict_encode["gbk"]
elif judgment.startswith("Windows-"):
response.encoding = dict_encode["utf-8"]
else:
return None
except:
return None
'''解析详情页'''
try:
selector = etree.HTML(response.text)
except:
return None
try:
title = selector.xpath("//title/text()")[0].strip()
except:
title = ""
try:
keywords = selector.xpath("//*[contains(@name,'keywords')]/@content|//*[contains(@name,'Keywords')]/@content")[0].strip()
except:
keywords = ""
try:
description = selector.xpath("//*[contains(@name,'Description')]/@content|//*[contains(@name,'description')]/@content")[0].strip()
except:
description = ""
keywords = keywords.replace("\xa0", "").replace("\r", "").replace("\n","").replace("\t", "").replace("_", ",")\
.replace("、", ",").replace("|", ",").replace(",", ",").replace(" ", ",").replace("'", r"\'").replace('"', r"\"")
description = description.replace("\xa0", "").replace("\r", "").replace("\n", "").replace("\t", "") \
.replace(",", ",").replace(" ", ",").strip()
data = {
"domainName": url,
"title": title,
"description": description,
"keywords": keywords
}
# jsondata = json.dumps(data,ensure_ascii=False)
# print(data)
jsondata = data
jsondata["domainName"] = url
boolean = es.c_tdk(jsondata)
if boolean == True:
print("插入成功")
if __name__ =="__main__":
# domainname = "hao123.com"
# domainname = domainname.strip()
# realdomain = domainname
# try:
# c = re.search(u"[\u4e00-\u9fa5]+", domainname).group()
# if c:
# domainname = domainname.split(".")
# realdomain = domainname[0].encode("utf-8").encode("punycode")
# index = 1
# while index < len(domainname):
# realdomain += "."
# c1 = re.search(u"[\u4e00-\u9fa5]+", domainname[index]).group()
# if c1:
# realdomain1 = domainname[index].encode("utf-8")
# realdomain = realdomain + "xn--" + realdomain1
# else:
# realdomain = realdomain + domainname[index]
# index += 1
# realdomain = "xn--" + realdomain
# except:
# pass
# domain = realdomain
domain = "meituan.com"
rtcode, jsondata = get_list_url(domain)
print(jsondata)
| [
"xjl12322@126.com"
] | xjl12322@126.com |
c82702ec10d3658cf6351e71d23074e94c6fdda0 | d460dc3e406e8458d0c5384026dd84bb400e0598 | /COJ/python/2382.py | b08cd7d114188885155f5ae1cefa63524ce7abb0 | [] | no_license | schiob/OnlineJudges | 8490b5a6ed31c97820f6fb494d22862a54a1df28 | f29f57e100f0f7c04d007285768cb60d43df4016 | refs/heads/master | 2023-06-23T03:55:52.600689 | 2023-06-08T01:48:35 | 2023-06-08T01:48:35 | 29,932,221 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 158 | py |
# coding: utf-8
# In[11]:
num = input().split(" ")
# In[16]:
print('YES') if int(num[0], int(num[1])) % int(num[2]) == 0 else print('NO')
# In[ ]:
| [
"schiob4@gmail.com"
] | schiob4@gmail.com |
de9b2cb84c2a897ff015137e6d2acac906582dda | 8396606fcb98d8ab2d5e5a139da83e7ce0880324 | /rps/bots_open/multiStrategies5.py | 4f545ea10cfb38b9e33fc6f57d4721c5a5837860 | [] | no_license | bopopescu/Learn2Mine-Main | 87b3d6d7fa804568a93c4c7e8324c95574afc819 | acc0267b86ad6a9e5e1619d494c20407d4710e90 | refs/heads/master | 2021-05-29T17:48:17.844094 | 2015-09-14T16:19:36 | 2015-09-14T16:19:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,306 | py | #multiStrategies5
STRATEGY_ONE = 'forecastMyMove'
STRATEGY_TWO = 'forecastOponentMove'
def defeatMove(obj):
if obj == 'R':
return 'P'
elif obj == 'P':
return 'S'
else:
return 'R'
def lostLastMatche(myMove, oponentMove):
if myMove == defeatMove(oponentMove) or myMove == oponentMove:
return False
else:
return True
def mostPlayed(dic):
if dic['R'] > dic['P'] and dic['R'] > dic['S']:
return 'R'
elif dic['P'] > dic['S']:
return 'P'
else:
return 'S'
if input == '':
oponentMoves = {'R': 0, 'P': 0, 'S': 0}
myMoves = {'R': 0, 'P': 0, 'S': 0}
consecutiveLoses = 0
strategy = STRATEGY_ONE
output = mylastMove = 'R'
else:
oponentMoves[input] += 1
if lostLastMatche(mylastMove, input):
consecutiveLoses += 1
if consecutiveLoses == 2: #swap stretegies
strategy = STRATEGY_TWO if strategy == STRATEGY_ONE else STRATEGY_ONE
# 1 calculate my most frequent move
# 2 assume that the oponent would try to defeat this move
# 3 defeat this move
if strategy == STRATEGY_ONE:
myMostPlayed = mostPlayed(myMoves)
move = defeatMove(defeatMove(myMostPlayed))
# 1 calculate my oponent's most frequent move
# 2 defeat this move
else:
oponentMostPlayed = mostPlayed(oponentMoves)
move = defeatMove(oponentMostPlayed)
myMoves[move] += 1
output = mylastMove = move | [
"pauleanderson@gmail.com"
] | pauleanderson@gmail.com |
12aca86810a85741cb51fd596ac005e69f3ebd42 | 1a2a2f2f4fc8c4c2a1e67ae7faaea21a92ce3802 | /tools/build_pytorch_libs.py | de4f7a9b74caa76f80575c76d053345ab31e8975 | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | Nikolatesla-lj/pytorch | cd6bd48738c351fc59f55b2495c65264f79081c7 | 7dde5a39c38cb82f1761ed9829323ae3b5996b69 | refs/heads/master | 2020-04-29T14:28:28.225661 | 2019-03-20T11:53:27 | 2019-03-20T11:53:27 | 176,197,615 | 2 | 0 | NOASSERTION | 2019-03-20T11:53:28 | 2019-03-18T03:25:51 | C++ | UTF-8 | Python | false | false | 10,977 | py | from .setup_helpers.env import (IS_ARM, IS_DARWIN, IS_LINUX, IS_PPC, IS_WINDOWS,
DEBUG, REL_WITH_DEB_INFO, USE_MKLDNN,
check_env_flag, check_negative_env_flag, hotpatch_build_env_vars)
import os
import sys
import distutils
import distutils.sysconfig
from distutils.file_util import copy_file
from distutils.dir_util import copy_tree
from subprocess import check_call, call, check_output
from distutils.version import LooseVersion
from .setup_helpers.cuda import USE_CUDA, CUDA_HOME
from .setup_helpers.dist_check import USE_DISTRIBUTED, USE_GLOO_IBVERBS
from .setup_helpers.nccl import USE_SYSTEM_NCCL, NCCL_INCLUDE_DIR, NCCL_ROOT_DIR, NCCL_SYSTEM_LIB, USE_NCCL
from .setup_helpers.rocm import ROCM_HOME, ROCM_VERSION, USE_ROCM
from .setup_helpers.nnpack import USE_NNPACK
from .setup_helpers.qnnpack import USE_QNNPACK
from .setup_helpers.cudnn import CUDNN_INCLUDE_DIR, CUDNN_LIB_DIR, CUDNN_LIBRARY, USE_CUDNN
from pprint import pprint
from glob import glob
import multiprocessing
import shutil
def which(thefile):
path = os.environ.get("PATH", os.defpath).split(os.pathsep)
for dir in path:
fname = os.path.join(dir, thefile)
fnames = [fname]
if IS_WINDOWS:
exts = os.environ.get('PATHEXT', '').split(os.pathsep)
fnames += [fname + ext for ext in exts]
for name in fnames:
if (os.path.exists(name) and os.access(name, os.F_OK | os.X_OK)
and not os.path.isdir(name)):
return name
return None
def cmake_version(cmd):
for line in check_output([cmd, '--version']).decode('utf-8').split('\n'):
if 'version' in line:
return LooseVersion(line.strip().split(' ')[2])
raise Exception('no version found')
def get_cmake_command():
cmake_command = 'cmake'
if IS_WINDOWS:
return cmake_command
cmake3 = which('cmake3')
if cmake3 is not None:
cmake = which('cmake')
if cmake is not None:
bare_version = cmake_version(cmake)
if bare_version < LooseVersion("3.5.0") and cmake_version(cmake3) > bare_version:
cmake_command = 'cmake3'
return cmake_command
def cmake_defines(lst, **kwargs):
for key in sorted(kwargs.keys()):
value = kwargs[key]
if value is not None:
lst.append('-D{}={}'.format(key, value))
# Ninja
# Use ninja if it is on the PATH. Previous version of PyTorch required the
# ninja python package, but we no longer use it, so we do not have to import it
USE_NINJA = not check_negative_env_flag('USE_NINJA') and (which('ninja') is not None)
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
install_dir = base_dir + "/torch"
build_type = "Release"
if DEBUG:
build_type = "Debug"
elif REL_WITH_DEB_INFO:
build_type = "RelWithDebInfo"
def overlay_windows_vcvars(env):
from distutils._msvccompiler import _get_vc_env
vc_env = _get_vc_env('x64')
for k, v in env.items():
lk = k.lower()
if lk not in vc_env:
vc_env[lk] = v
return vc_env
def mkdir_p(dir):
try:
os.makedirs(dir)
except OSError:
pass
def create_build_env():
# XXX - our cmake file sometimes looks at the system environment
# and not cmake flags!
# you should NEVER add something to this list. It is bad practice to
# have cmake read the environment
my_env = os.environ.copy()
if USE_CUDNN:
my_env['CUDNN_LIBRARY'] = escape_path(CUDNN_LIBRARY)
my_env['CUDNN_INCLUDE_DIR'] = escape_path(CUDNN_INCLUDE_DIR)
if USE_CUDA:
my_env['CUDA_BIN_PATH'] = escape_path(CUDA_HOME)
if IS_WINDOWS:
my_env = overlay_windows_vcvars(my_env)
return my_env
def run_cmake(version,
cmake_python_library,
build_python,
build_test,
build_dir,
my_env):
cmake_args = [
get_cmake_command(),
base_dir
]
if USE_NINJA:
cmake_args.append('-GNinja')
elif IS_WINDOWS:
cmake_args.append('-GVisual Studio 15 2017 Win64')
try:
import numpy as np
NUMPY_INCLUDE_DIR = np.get_include()
USE_NUMPY = True
except ImportError:
USE_NUMPY = False
NUMPY_INCLUDE_DIR = None
cflags = os.getenv('CFLAGS', "") + " " + os.getenv('CPPFLAGS', "")
ldflags = os.getenv('LDFLAGS', "")
if IS_WINDOWS:
cflags += " /EHa"
mkdir_p(install_dir)
mkdir_p(build_dir)
cmake_defines(
cmake_args,
PYTHON_EXECUTABLE=escape_path(sys.executable),
PYTHON_LIBRARY=escape_path(cmake_python_library),
PYTHON_INCLUDE_DIR=escape_path(distutils.sysconfig.get_python_inc()),
BUILDING_WITH_TORCH_LIBS="ON",
TORCH_BUILD_VERSION=version,
CMAKE_BUILD_TYPE=build_type,
BUILD_TORCH="ON",
BUILD_PYTHON=build_python,
BUILD_SHARED_LIBS=os.getenv("BUILD_SHARED_LIBS", "ON"),
BUILD_BINARY=check_env_flag('BUILD_BINARY'),
BUILD_TEST=build_test,
INSTALL_TEST=build_test,
BUILD_CAFFE2_OPS=not check_negative_env_flag('BUILD_CAFFE2_OPS'),
ONNX_NAMESPACE=os.getenv("ONNX_NAMESPACE", "onnx_torch"),
ONNX_ML=os.getenv("ONNX_ML", False),
USE_CUDA=USE_CUDA,
USE_DISTRIBUTED=USE_DISTRIBUTED,
USE_FBGEMM=not (check_env_flag('NO_FBGEMM') or check_negative_env_flag('USE_FBGEMM')),
USE_NUMPY=USE_NUMPY,
NUMPY_INCLUDE_DIR=escape_path(NUMPY_INCLUDE_DIR),
USE_SYSTEM_NCCL=USE_SYSTEM_NCCL,
NCCL_INCLUDE_DIR=NCCL_INCLUDE_DIR,
NCCL_ROOT_DIR=NCCL_ROOT_DIR,
NCCL_SYSTEM_LIB=NCCL_SYSTEM_LIB,
CAFFE2_STATIC_LINK_CUDA=check_env_flag('USE_CUDA_STATIC_LINK'),
USE_ROCM=USE_ROCM,
USE_NNPACK=USE_NNPACK,
USE_LEVELDB=check_env_flag('USE_LEVELDB'),
USE_LMDB=check_env_flag('USE_LMDB'),
USE_OPENCV=check_env_flag('USE_OPENCV'),
USE_QNNPACK=USE_QNNPACK,
USE_TENSORRT=check_env_flag('USE_TENSORRT'),
USE_FFMPEG=check_env_flag('USE_FFMPEG'),
USE_SYSTEM_EIGEN_INSTALL="OFF",
USE_MKLDNN=USE_MKLDNN,
USE_NCCL=USE_NCCL,
NCCL_EXTERNAL=USE_NCCL,
CMAKE_INSTALL_PREFIX=install_dir,
CMAKE_C_FLAGS=cflags,
CMAKE_CXX_FLAGS=cflags,
CMAKE_EXE_LINKER_FLAGS=ldflags,
CMAKE_SHARED_LINKER_FLAGS=ldflags,
THD_SO_VERSION="1",
CMAKE_PREFIX_PATH=os.getenv('CMAKE_PREFIX_PATH') or distutils.sysconfig.get_python_lib(),
BLAS=os.getenv('BLAS'),
CUDA_NVCC_EXECUTABLE=escape_path(os.getenv('CUDA_NVCC_EXECUTABLE')),
USE_REDIS=os.getenv('USE_REDIS'),
USE_GLOG=os.getenv('USE_GLOG'),
USE_GFLAGS=os.getenv('USE_GFLAGS'),
WERROR=os.getenv('WERROR'))
if USE_GLOO_IBVERBS:
cmake_defines(cmake_args, USE_IBVERBS="1", USE_GLOO_IBVERBS="1")
if USE_MKLDNN:
cmake_defines(cmake_args, MKLDNN_ENABLE_CONCURRENT_EXEC="ON")
expected_wrapper = '/usr/local/opt/ccache/libexec'
if IS_DARWIN and os.path.exists(expected_wrapper):
cmake_defines(cmake_args,
CMAKE_C_COMPILER="{}/gcc".format(expected_wrapper),
CMAKE_CXX_COMPILER="{}/g++".format(expected_wrapper))
pprint(cmake_args)
for env_var_name in my_env:
if env_var_name.startswith('gh'):
# github env vars use utf-8, on windows, non-ascii code may
# cause problem, so encode first
try:
my_env[env_var_name] = str(my_env[env_var_name].encode("utf-8"))
except UnicodeDecodeError as e:
shex = ':'.join('{:02x}'.format(ord(c)) for c in my_env[env_var_name])
sys.stderr.write('Invalid ENV[{}] = {}\n'.format(env_var_name, shex))
check_call(cmake_args, cwd=build_dir, env=my_env)
def build_caffe2(version,
cmake_python_library,
build_python,
rerun_cmake,
build_dir):
my_env = create_build_env()
build_test = not check_negative_env_flag('BUILD_TEST')
max_jobs = os.getenv('MAX_JOBS', None)
cmake_cache_file = 'build/CMakeCache.txt'
if rerun_cmake and os.path.isfile(cmake_cache_file):
os.remove(cmake_cache_file)
if not os.path.exists(cmake_cache_file) or (USE_NINJA and not os.path.exists('build/build.ninja')):
run_cmake(version,
cmake_python_library,
build_python,
build_test,
build_dir,
my_env)
if IS_WINDOWS:
if USE_NINJA:
# sccache will fail if all cores are used for compiling
j = max(1, multiprocessing.cpu_count() - 1)
if max_jobs is not None:
j = min(int(max_jobs), j)
check_call(['cmake', '--build', '.', '--target', 'install', '--config', build_type, '--', '-j', str(j)],
cwd=build_dir, env=my_env)
else:
check_call(['msbuild', 'INSTALL.vcxproj', '/p:Configuration={}'.format(build_type)],
cwd=build_dir, env=my_env)
else:
if USE_NINJA:
ninja_cmd = ['ninja', 'install']
if max_jobs is not None:
ninja_cmd += ['-j', max_jobs]
check_call(ninja_cmd, cwd=build_dir, env=my_env)
else:
max_jobs = max_jobs or str(multiprocessing.cpu_count())
check_call(['make', '-j', str(max_jobs), 'install'], cwd=build_dir, env=my_env)
# in cmake, .cu compilation involves generating certain intermediates
# such as .cu.o and .cu.depend, and these intermediates finally get compiled
# into the final .so.
# Ninja updates build.ninja's timestamp after all dependent files have been built,
# and re-kicks cmake on incremental builds if any of the dependent files
# have a timestamp newer than build.ninja's timestamp.
# There is a cmake bug with the Ninja backend, where the .cu.depend files
# are still compiling by the time the build.ninja timestamp is updated,
# so the .cu.depend file's newer timestamp is screwing with ninja's incremental
# build detector.
# This line works around that bug by manually updating the build.ninja timestamp
# after the entire build is finished.
if os.path.exists('build/build.ninja'):
os.utime('build/build.ninja', None)
if build_python:
for proto_file in glob('build/caffe2/proto/*.py'):
if os.path.sep != '/':
proto_file = proto_file.replace(os.path.sep, '/')
if proto_file != 'build/caffe2/proto/__init__.py':
shutil.copyfile(proto_file, "caffe2/proto/" + os.path.basename(proto_file))
def escape_path(path):
if os.path.sep != '/' and path is not None:
return path.replace(os.path.sep, '/')
return path
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
97ac4863627042b6aa3459be2e50fbd99441e66d | 06a7dc7cc93d019e4a9cbcf672b23a0bbacf8e8b | /2013_mescog/db_clinic/00_MISSING_CADASIL.py | 6494bf29bfd92f231c3b55162526c88ffe412081 | [] | no_license | neurospin/scripts | 6c06cd218a5f32de9c3c2b7d1d8bda3f3d107458 | f14a2c9cf2cd7f5fbea767b017c3faf36d170bdb | refs/heads/master | 2021-07-11T22:55:46.567791 | 2021-07-02T13:08:02 | 2021-07-02T13:08:02 | 10,549,286 | 2 | 2 | null | null | null | null | UTF-8 | Python | false | false | 3,120 | py | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 3 10:44:49 2013
Add DATEINCL and DATENAIS an compute AGE_AT_INCLUSION in CADASIL subjects
INPUT
-----
"base_commun.csv"
"france2012.csv" => date DATEINCL and DATENAIS for french
"CAD_Munich_Dates.txt" => date DATEINCL and DATENAIS for german
OUTPUT
------
"base_commun_20140109.csv" == "base_commun.csv" + Date (from "france2012.csv" + CAD_Munich_Dates.txt)
"""
##############################################################################
## Add DATEINCL and DATENAIS in CADASIL
# 1) Check presence in france2012.csv
# 2) Compare base_commun.csv vs france2012.csv
# 3) Count missing in base_commun.csv
##############################################################################
import os.path
import string
import pandas as pd
import numpy as np
WD = "/neurospin/mescog"
INPUT_cadasil_base_commun_filepath = os.path.join(WD, "clinic", "base_commun.csv")
INPUT_cadasil_france2012_filepath = os.path.join(WD, "clinic", "france2012.csv")
INPUT_cadasil_munich_date_filepath = os.path.join(WD, "clinic", "CAD_Munich_Dates.txt")
OUTPUT = os.path.join(WD, "clinic", "base_commun_20140109.csv")
cadasil_base_commun = pd.read_table(INPUT_cadasil_base_commun_filepath, header=0, sep=",").replace("-", np.nan)
cadasil_france2012 = pd.read_table(INPUT_cadasil_france2012_filepath, header=0, sep=",").replace("-", np.nan)
cadasil_munich_date = pd.read_table(INPUT_cadasil_munich_date_filepath, header=0)
# Look for differences between cadasil_base_commun & cadasil_france2012
cadasil_base_commun.columns = [s.upper() for s in cadasil_base_commun.columns]
cadasil_france2012.columns = [s.upper() for s in cadasil_france2012.columns]
# drop DATEINCL and DATENAIS of cadasil_base_commun
cadasil_base_commun = cadasil_base_commun.drop(["DATEINCL", "DATENAIS"], 1)
# 1) Recode date in cadasil_france2012
# 1/28/10 12:00 AM => 2010-28-01
def format_date(dates, pref="20"):
out = list()
for l in dates:
date = l.split()[0].split("/")
out.append('%s%s-%s-%s' % (pref, date[0], "{:0>2d}".format(int(date[1])), "{:0>2d}".format(int(date[2]))))
return out
cadasil_france2012.ID
cadasil_france2012.DATEINCL = format_date(cadasil_france2012.DATEINCL, pref="")
cadasil_france2012.DATENAIS = format_date(cadasil_france2012.DATENAIS, pref="")
cadasil_france2012[["ID", "DATENAIS", "DATEINCL"]]
# 2) reformat cadasil_munich_date.ID
#cadasil_munich_date.ID contains "CAD_" remove, it will be added later
cadasil_munich_date.ID = [int(s.replace('CAD_', '')) for s in cadasil_munich_date.ID]
cadasil_munich_date.ID
# 3) Merge to cadasil_base_commun
cada_dates = cadasil_france2012[["ID", "DATENAIS", "DATEINCL"]].append(cadasil_munich_date, ignore_index=True)
age = pd.DataFrame(dict(AGE_AT_INCLUSION=[int(cada_dates.DATEINCL[i].split("-")[0]) - int(cada_dates.DATENAIS[i].split("-")[0])
for i in xrange(cada_dates.shape[0])]))
cada_dates = pd.concat([cada_dates, age], axis=1)
print cada_dates.to_string()
# Merge with cadasil_base_commun and save
merge = pd.merge(cada_dates, cadasil_base_commun, on="ID")
merge.to_csv(OUTPUT, sep=",", index=False)
| [
"edouard.duchesnay@gmail.com"
] | edouard.duchesnay@gmail.com |
ba079ef7005657c485428d1ab73b3303ac4578e5 | ab28f1bb7e77309fe5afbc0ef3c57d8cd226d0ef | /0x07-python-test_driven_development/4-print_square.py | 55dce02c1a10e4db40711ebeff01ac6de5bf7a5f | [] | no_license | rakiasomai/holbertonschool-higher_level_programming | aebc5245fc0e6d30faf24b1e55dad93ae71fb537 | f07fedb05405f4ca6b45354ca1ccb90c1f48a215 | refs/heads/master | 2020-12-10T14:45:19.245460 | 2020-05-14T16:58:43 | 2020-05-14T16:58:43 | 233,623,084 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 572 | py | #!/usr/bin/python3
'''
This function called "Print Square"
this function prints a square using this symbol "#"
The arguments must be an integer
'''
def print_square(size):
'''
Print a square by using arguments
'''
if not isinstance(size, (int, float)) or isinstance(size, bool):
raise TypeError("size must be an integer")
if isinstance(size, float) and size < 0:
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
for i in range(int(size)):
print("#" * int(size))
| [
"somai.rakia@hotmail.fr"
] | somai.rakia@hotmail.fr |
46cfb3ce8fe6fdffa1f4bec06b4dcf8eefd0b399 | fc90b69b4381a8696d77e5c98976888c93e939f7 | /gsee/trigon.py | a99744e61cfae49b7e2a214ef37027813a90e4a7 | [
"BSD-3-Clause"
] | permissive | ManiaGary/gsee | aaa9aeae89dc492101fb924b940a86f72db7a789 | 468ba4fb3119f8303aeffb5f2cca5a9e62614a8c | refs/heads/master | 2021-01-23T07:50:52.010402 | 2016-09-06T08:34:33 | 2016-09-06T08:34:33 | 86,457,944 | 1 | 0 | null | 2017-03-28T12:35:15 | 2017-03-28T12:35:15 | null | UTF-8 | Python | false | false | 8,112 | py | """
Irradiance on an inclined plane
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Using trigonometry (Lambert's cosine law, etc).
"""
import datetime
import ephem
import numpy as np
import pandas as pd
def _sun_rise_set(datetime_index, obs):
"""
Returns a list of (sunrise, sunset) tuples for the datetimes
in the given datetime_index, assuming that the index is daily.
Sunrise or sunset will be None if the sun doesn't rise/set.
"""
sun = ephem.Sun()
times = []
def _get_datetime(date):
obs.date = date
sun.compute(obs)
if sun.rise_time is None:
rise_time = None
else:
rise_time = sun.rise_time.datetime()
if sun.set_time is None:
set_time = None
else:
set_time = sun.set_time.datetime()
return (rise_time, set_time)
for i in datetime_index:
times.append(_get_datetime(i))
return times
def sun_rise_set_times(datetime_index, coords):
"""
Return sunrise and set times for the given datetime_index and coords.
The datetime_index will be resampled to daily frequency.
"""
obs = ephem.Observer()
obs.lat = str(coords[0])
obs.lon = str(coords[1])
# Ensure datetime_index is daily
dtindex = pd.DatetimeIndex(datetime_index.to_series().map(pd.Timestamp.date).unique())
return _sun_rise_set(dtindex, obs)
def sun_angles(datetime_index, coords, rise_set_times=None):
"""Calculate sun angles. Returns a dataframe containing `sun_alt`,
`sun_zenith`, `sun_azimuth` and `duration` over the passed datetime index.
Parameters
----------
datetime_index : pandas datetime index
Handled as if they were UTC not matter what timezone info
they may supply.
coords : (float, float) or (int, int) tuple
Latitude and longitude.
rise_set_times : list, default None
List of (sunrise, sunset) time tuples, if not passed, is computed
here.
"""
def _sun_alt_azim(sun, obs):
sun.compute(obs)
return sun.alt, sun.az
# Initialize ephem objects
obs = ephem.Observer()
obs.lat = str(coords[0])
obs.lon = str(coords[1])
sun = ephem.Sun()
# Calculate daily sunrise/sunset times
if not rise_set_times:
rise_set_times = _sun_rise_set(datetime_index, obs)
# Calculate hourly altitute, azimuth, and sunshine
alts = []
azims = []
durations = []
for index, item in enumerate(datetime_index):
obs.date = item
# rise/set times are indexed by day, so need to scale the index
rise_time, set_time = rise_set_times[int(index / 24)]
# Set angles, sun altitude and duration based on hour of day:
if rise_time is not None and item.hour == rise_time.hour:
# Special case for sunrise hour
duration = 60 - rise_time.minute - (rise_time.second / 60.0)
obs.date = rise_time + datetime.timedelta(minutes=duration / 2)
sun_alt, sun_azimuth = _sun_alt_azim(sun, obs)
elif set_time is not None and item.hour == set_time.hour:
# Special case for sunset hour
duration = set_time.minute + set_time.second / 60.0
obs.date = item + datetime.timedelta(minutes=duration / 2)
sun_alt, sun_azimuth = _sun_alt_azim(sun, obs)
else:
# All other hours
duration = 60
obs.date = item + datetime.timedelta(minutes=30)
sun_alt, sun_azimuth = _sun_alt_azim(sun, obs)
if sun_alt < 0: # If sun is below horizon
sun_alt, sun_azimuth, duration = 0, 0, 0
alts.append(sun_alt)
azims.append(sun_azimuth)
durations.append(duration)
df = pd.DataFrame({'sun_alt': alts, 'sun_azimuth': azims,
'duration': durations},
index=datetime_index)
df['sun_zenith'] = (np.pi / 2) - df.sun_alt
return df
def _incidence_fixed(sun_alt, tilt, azimuth, sun_azimuth):
return np.arccos(np.sin(sun_alt) * np.cos(tilt)
+ np.cos(sun_alt) * np.sin(tilt)
* np.cos(azimuth - sun_azimuth))
def _incidence_single_tracking(sun_alt, tilt, azimuth, sun_azimuth):
if tilt == 0:
return np.arccos(np.sqrt(1 - np.cos(sun_alt) ** 2
* np.cos(sun_azimuth - azimuth) ** 2))
else:
return np.arccos(np.sqrt(1 - (np.cos(sun_alt + tilt) * np.cos(tilt)
* np.cos(sun_alt) * (1 - np.cos(sun_azimuth
- azimuth))) ** 2))
def _tilt_single_tracking(sun_alt, tilt, azimuth, sun_azimuth):
if tilt == 0:
return np.arctan(np.sin(sun_azimuth - azimuth) / np.tan(sun_alt))
else:
return np.arctan((np.cos(sun_alt) * np.sin(sun_azimuth - azimuth))
/ (np.sin(sun_alt - tilt) + np.sin(tilt)
* np.cos(sun_alt) * (1 - np.cos(sun_azimuth)
- azimuth)))
def aperture_irradiance(direct, diffuse, coords,
tilt=0, azimuth=0, tracking=0, albedo=0.3,
dni_only=False, angles=None):
"""
Args:
direct : a series of direct horizontal irradiance with a datetime index
diffuse : a series of diffuse horizontal irradiance with the same
datetime index as for direct
coords : (lat, lon) tuple of location coordinates
tilt : angle of panel relative to the horizontal plane, 0 = flat
azimuth : deviation of the tilt direction from the meridian,
0 = towards pole, going clockwise, 3.14 = towards equator
tracking : 0 (none, default), 1 (tilt), or 2 (tilt and azimuth).
If 1, azimuth is the orientation of the tilt axis, which
can be horizontal (tilt=0) or tilted.
albedo : reflectance of the surrounding surface
dni_only : only calculate and directly return a DNI time series
(ignores tilt, azimuth, tracking and albedo arguments)
angles : solar angles, if default (None), is computed here
"""
# 0. Correct azimuth if we're on southern hemisphere, so that 3.14
# points north instead of south
if coords[0] < 0:
azimuth = azimuth + np.pi
# 1. Calculate solar angles
if angles is None:
sunrise_set_times = sun_rise_set_times(direct.index, coords)
angles = sun_angles(direct.index, coords, sunrise_set_times)
# 2. Calculate direct normal irradiance
dni = (direct * (angles['duration'] / 60)) / np.cos(angles['sun_zenith'])
if dni_only:
return dni
# 3. Calculate appropriate aperture incidence angle
if tracking == 0:
incidence = _incidence_fixed(angles['sun_alt'], tilt, azimuth,
angles['sun_azimuth'])
panel_tilt = tilt
elif tracking == 1:
# 1-axis tracking with horizontal or tilted tracking axis
incidence = _incidence_single_tracking(angles['sun_alt'],
tilt, azimuth,
angles['sun_azimuth'])
panel_tilt = _tilt_single_tracking(angles['sun_alt'], tilt, azimuth,
angles['sun_azimuth'])
elif tracking == 2:
# 2-axis tracking means incidence angle is zero
# Assuming azimuth/elevation tracking for tilt/azimuth angles
incidence = 0
panel_tilt = angles['sun_zenith']
azimuth = angles['sun_azimuth']
else:
raise ValueError('Invalid setting for tracking: {}'.format(tracking))
# 4. Compute direct and diffuse irradiance on plane
plane_direct = (dni * np.cos(incidence)).fillna(0)
plane_diffuse = (diffuse * ((1 + np.cos(panel_tilt)) / 2)
+ albedo * (direct + diffuse)
* ((1 - np.cos(panel_tilt)) / 2)).fillna(0)
return pd.DataFrame({'direct': plane_direct, 'diffuse': plane_diffuse})
| [
"stefan@pfenninger.org"
] | stefan@pfenninger.org |
054a786ca85332a9c5e410c27396930e714de064 | 5419d8d02a7fdec15f542498840d19af939fa130 | /LeetCode30DaysChallenge/Day_26_LongestCommonSubsequence.py | 50b86c08a66089e50faf5d0ac9108d508a4030c0 | [] | no_license | foolchauhan/DataStructureAndAlgorithms | 3cf1d4927b6b11592789cb8d1a6800c9de4822e2 | d53281a724a8b58ccc67ebe8c0e0af6c4ae63c4a | refs/heads/master | 2022-10-10T08:29:14.461248 | 2020-06-10T16:18:36 | 2020-06-10T16:18:36 | 244,270,954 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 362 | py | def lcs(X , Y):
m = len(X)
n = len(Y)
L = [[None]*(n+1) for i in range(m+1)]
for i in range(m+1):
for j in range(n+1):
if i == 0 or j == 0 :
L[i][j] = 0
elif X[i-1] == Y[j-1]:
L[i][j] = L[i-1][j-1]+1
else:
L[i][j] = max(L[i-1][j] , L[i][j-1])
return L[m][n]
X = "abcde"
Y = "ace"
print ("Length of LCS is ", lcs(X, Y) )
| [
"chauhanchetan82@gmail.com"
] | chauhanchetan82@gmail.com |
b27c407b97b61db14f0ef5557a0a98f303bcd9a6 | afbae26b958b5ef20548402a65002dcc8e55b66a | /release/stubs.min/Revit/Application.py | 13621cf5daeedceac8a610c432a9699fff210b93 | [
"MIT"
] | permissive | gtalarico/ironpython-stubs | d875cb8932c7644f807dc6fde9dd513d159e4f5c | c7f6a6cb197e3949e40a4880a0b2a44e72d0a940 | refs/heads/master | 2023-07-12T01:43:47.295560 | 2022-05-23T18:12:06 | 2022-05-23T18:12:06 | 95,340,553 | 235 | 88 | NOASSERTION | 2023-07-05T06:36:28 | 2017-06-25T05:30:46 | Python | UTF-8 | Python | false | false | 1,032 | py | # encoding: utf-8
# module Revit.Application calls itself Application
# from RevitNodes,Version=1.2.1.3083,Culture=neutral,PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class Document(object):
""" A Revit Document """
ActiveView=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get the active view for the document
Get: ActiveView(self: Document) -> View
"""
FilePath=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The full path of the Document.
Get: FilePath(self: Document) -> str
"""
IsFamilyDocument=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Is the Document a Family?
Get: IsFamilyDocument(self: Document) -> bool
"""
Location=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Extracts Latitude and Longitude from Revit
Get: Location(self: Document) -> Location
"""
Current=None
| [
"gtalarico@gmail.com"
] | gtalarico@gmail.com |
f5e93ea4f56961c6f7fe468c04989918d124c81b | 97be97cfc56fb2170b60b91063dbfe5f1449e3c0 | /python/ARC118/A.py | 8433baa2c379b11ff6a0977f6734dd8082f1d73f | [] | no_license | iWonder118/atcoder | 73d965a0a9ade189733808e47634f2b7776aad4b | 3ab7271e838a2903ff0e07f94015ef13c59577e1 | refs/heads/master | 2022-01-25T10:10:55.007340 | 2021-12-31T14:04:54 | 2021-12-31T14:04:54 | 245,155,997 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 302 | py | t, N = map(int, input().split())
handled = [False] * (100 + t)
for i in range(1, 100):
handled[int(i * (100 + t) / 100)] = True
unhandled = []
for i in range(1, 100 + t):
if not handled[i]:
unhandled.append(i)
x, y = divmod(N - 1, len(unhandled))
print((100 + t) * x + unhandled[y])
| [
"52240372+iWonder118@users.noreply.github.com"
] | 52240372+iWonder118@users.noreply.github.com |
90563c027e3c2d7b242cddfec0fee30ac8093d2c | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /9Kuah39g997SvZmex_1.py | ed002987b0ece5b4a8e68e0089af9c017d6ed7be | [] | no_license | daniel-reich/turbo-robot | feda6c0523bb83ab8954b6d06302bfec5b16ebdf | a7a25c63097674c0a81675eed7e6b763785f1c41 | refs/heads/main | 2023-03-26T01:55:14.210264 | 2021-03-23T16:08:01 | 2021-03-23T16:08:01 | 350,773,815 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 906 | py | """
Create a function that takes in a sentence as input and returns the **most
common last vowel** in the sentence as a single character string.
### Examples
common_last_vowel("Hello World!") ➞ "o"
common_last_vowel("Watch the characters dance!") ➞ "e"
common_last_vowel("OOI UUI EEI AAI") ➞ "i"
### Notes
* There will only be one common last vowel in each sentence.
* If the word has one vowel, treat the vowel as the last one **even if it is at the start of the word**.
* The question asks you to compile all of the last vowels of each word and returns the vowel in the list which appears most often.
* **y** won't count as a vowel.
* Return outputs in **lowercase**.
"""
from collections import Counter
def common_last_vowel(txt):
v = [[c for c in word if c in "aeiou"][-1] for word in txt.lower().split()]
return Counter(v).most_common()[0][0]
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
e5715d9c0c8cfb7d4476e1ce2ced6e8132fecf58 | 4580dcd5eeb99b88716721625e243f888ddbca08 | /src/Ch10/age_lambda_filter.py | 3daeb3c0ca1163577da41b096aab792e330c0566 | [] | no_license | dongupak/Prime-Python | c9c7a211e61f06fe518719b499b01eeb34c1e827 | 767cc9cb9f47fda5efa78776c1d1aa68b43dc6c4 | refs/heads/master | 2022-02-08T13:10:06.797737 | 2022-01-18T02:01:29 | 2022-01-18T02:01:29 | 224,655,276 | 23 | 23 | null | 2020-07-30T05:06:33 | 2019-11-28T13:05:28 | Jupyter Notebook | UTF-8 | Python | false | false | 275 | py | # 코드 10-5 : 람다 함수를 이용한 간략화된 필터
## "으뜸 파이썬", p. 579
ages = [34, 39, 20, 18, 13, 54]
print('성년 리스트 :')
for a in filter(lambda x: x >= 19, ages): # filter() 함수를 사용한 ages의 필터
print(a, end = ' ')
| [
"dongupak@gmail.com"
] | dongupak@gmail.com |
c01e3c700ea2c7a4bda0f7afd1829a96df5727cb | a35d07b11f013a26901942f730d4b720f4e27355 | /warmup1/diff21.py | a8ddabe0c6331fafd4d549bd53c89af715e1e6f7 | [] | no_license | PMiskew/codingbat_solutions_python | 7cbbf293fb6b230e274a8cee373a2222a5a27e8d | 6e62fd0080c2a9bcd59fd4f803cc7966a2cb88d1 | refs/heads/master | 2022-11-13T13:24:53.078833 | 2020-07-14T18:38:06 | 2020-07-14T18:38:06 | 255,197,455 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,123 | py | '''
Question
Given two int values, return their sum. Unless the two values are the same, then return double their sum.
sum_double(1, 2) → 3
sum_double(3, 2) → 5
sum_double(2, 2) → 8
'''
def diff21(n):
#Note: All the other exampels returned booleans so far. This example
# returns an intger. Always pay attention to the return type.
#Approach 1:This is a case where we need to first check the value of n
#once we know that we can decide if we send the absolute difference or
#the absolute different*2
'''
if n > 21:
return (n - 21)* 2
return 21 - n
#'''
#Approach 2: Modification of approach 1.
#Notice that in both cases we calculate the different and the order matters
#based on the size of n. We can use the absolute function, a build in function
#in the standard library. We can store the absolute different in a variable and
#use that.
'''
diff = abs(n - 21)
if n > 21:
return diff*2
return diff
#'''
#Approch 1: Python supports a single line conditional statement that we can
#use in this case.
'''
return abs(n-21)*2 if n > 21 else abs(n-21)
#'''
#Approach 2: I am proud of this one, but it is horribly designed in terms
#of readability.
'''
return int(abs((n)-21)*round(min(abs(n)/21+0.5,2)))
#'''
#LONGER EXPLAINATION
#return abs((n)-21)
#return round(min(abs(n)/21+0.5,2))
'''
Powerful idea, have seen it on the AP exam
x = round(n + 0.5)
n = 1.1 round(1.1 + 0.5) = round(1.6) = 2.0
n = 1.51 round(1.51 + 0.5) = round(2.01) = 2.0
n = 0.95 round(0.95 + 0.5) = round(1.45) = 1.0
n = 22
round(min(abs(22)/21+0.5,2)))
round(min(22/21 + 0.5, 2)))
round(min(1.0476 + 0.5, 2)))
round(min(1.5476,2))
round(1.547)
2.0
n = 2
round(min(abs(2)/21+0.5,2)))
round(min(2/21+0.5,2)))
round(min(0.0952+0.5,2)))
round(min(0.5952,2))
round(0.5952)
1.0
n = -2
round(min(abs(-2)/21+0.5,2)))
round(min(2/21+0.5,2)))
round(min(0.0952+0.5,2)))
round(min(0.5952,2))
round(0.5952)
1.0
'''
| [
"paul.miskew@gmail.com"
] | paul.miskew@gmail.com |
6c06011d81adf54862a37378abd3221e37f6e4bc | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_212/ch57_2020_06_19_14_53_17_093175.py | c97fcb636614fa2a80d8da7e6fef8d15eb100590 | [] | 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 | 748 | py | def verifica_progressao (lista):
pa = False
pg =False
if len(lista) == 0:
pa = True
pg = True
else:
aumento = lista[1] - lista[0]
razao = lista[1]/lista[0]
for i in range (len(lista)-1):
if lista[i+1] - lista[i] != aumento:
pa = False
elif lista[i+1] / lista[i] != razao:
pg = False
if pa == True and pg == False:
return ("PA")
elif pa == False and pg ==True:
return ("PG")
elif pa== False and pg==False:
return("NA")
elif pa==True and pg== True:
return ("AG")
| [
"you@example.com"
] | you@example.com |
86ed2728cf8554c1b83eace130b6ded059e02e00 | 2a21e9469d52c9eb2c794efa85227ca81cd39be8 | /app/classes/Database.py | 09b9d6d7950135fec164015f1031afc1cd45993b | [] | no_license | CL0456/WebsiteProject | b1f9b0f531eb5afaa21ac8b6c951be8c2c6a1bd0 | 5e31a7e03d69afe036b0c0f1851fb7f276388cc6 | refs/heads/master | 2023-01-01T20:19:02.874794 | 2020-10-29T01:17:22 | 2020-10-29T01:17:22 | 271,406,475 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,717 | py | import os
import tempfile
import pyrebase
import requests
import json
from collections import OrderedDict
from flask import current_app as flask_app
from app import SITE_ROOT
class Database():
"""
Database Class.
Class to interact with Firebase Realtime Database.
"""
def __init__(self):
"""
Initialise class with configuration
"""
# Load Firebase config data, including Service Account file
firebase_config_file = os.path.join(SITE_ROOT, 'firebase.json')
firebase_config = json.load(open(firebase_config_file))
firebase_config["serviceAccount"] = os.path.join(SITE_ROOT, 'firebase.admin.json')
# Initialize Firebase auth and database
self.firebase = pyrebase.initialize_app(firebase_config)
self.auth = self.firebase.auth()
self.db = self.firebase.database()
# Create readable errors based on Firebase errors
self.readable_errors = {
"INVALID_PASSWORD": "This is an invalid password",
"EMAIL_NOT_FOUND": "This email has not been registered",
"EMAIL_EXISTS": "This email already exists. Try logging in instead.",
"TOO_MANY_ATTEMPTS_TRY_LATER": "Too many attempts, please try again later",
"USER_DISABLED": "This account has been disabled by an administrator.",
}
# Image Requests
def get_images(self, limit=20, user_id=False):
"""
- Pulls last 20 images from Firebase.
- Organises them by User ID or from all users
"""
try:
if (user_id):
images = self.db.child("images").order_by_child("user_id").equal_to(user_id).limit_to_first(limit).get()
else:
images = self.db.child("images").order_by_child("user_id").limit_to_first(limit).get()
flask_app.logger.info('####################### images val #####################')
flask_app.logger.info(images.val())
if isinstance(images.val(), OrderedDict):
return images
else:
return False
except Exception as err:
self.process_error(err)
def get_category_images(self, category, limit=20):
"""
Requests all data regarding images in a category
"""
try:
images = self.db.child("images").order_by_child("category").equal_to(category).limit_to_first(limit).get()
if isinstance(images.val(), OrderedDict):
return images
else:
return False
except Exception as err:
self.process_error(err)
def get_image(self, image_id):
"""
Requests all data regarding an image
"""
error = None
image = False
try:
image = self.db.child("images").child(image_id).get()
except Exception as err:
flask_app.logger.info(err)
error = err
if error:
raise Exception(error)
else:
return image.val()
def save_image(self, image_data, image_id):
flask_app.logger.info('####################### image_data #####################')
flask_app.logger.info(image_data)
try:
self.db.child("images").child(image_id).set(image_data)
except Exception as err:
self.process_error(err)
def delete_image(self, image_id):
try:
self.db.child("images").child(image_id).remove()
except Exception as err:
self.process_error(err)
def remove_matching_value(self, data, value):
return_data = []
for key in data:
if key != value:
return_data.append(key)
return return_data
# User and Account Requests
def register(self, user_data, password):
"""
User Attempts to register
"""
try:
user_auth = self.auth.create_user_with_email_and_password(user_data['email'], password)
user_data['localId'] = user_auth['localId']
self.db.child("users").child(user_auth['localId']).set(user_data)
return user_auth
except Exception as err:
self.process_error(err)
def login(self, email, password):
"""
User attempts to login
"""
try:
user_auth = self.auth.sign_in_with_email_and_password(email, password)
user = self.db.child("users").child(user_auth['localId']).get().val()
return user
except Exception as err:
self.process_error(err)
def update_user(self, user_data):
"""
User makes a request to change their account details
"""
try:
self.db.child("users").child(user_data['localId']).update(user_data)
return
except Exception as err:
self.process_error(err)
def process_error(self, error):
"""
Takes firebase error and turns it into a readable error.
"""
flask_app.logger.info(error)
readable_error = self.get_readable_error(error)
raise Exception(readable_error)
def get_readable_error(self, error):
"""
Presents an error message if a request error occurs
"""
error_json = error.args[1]
error_messsage = json.loads(error_json)['error']['message']
if error_messsage in self.readable_errors.keys():
return self.readable_errors[error_messsage]
else:
return "There was a problem with your request." | [
"you@example.com"
] | you@example.com |
d2cb0fdb41bd08f4584135491fc11aca0f8532ba | a154f6985195429b6f839f452576593f09dea6c7 | /cartpole_fitness.py | 2acd4e600600c2d28c05e369da6e0ba0dfcac22f | [] | no_license | mcx/evolved_cartpole | 56e96cfc3e4f92a47d2c330c352672148a4c7f25 | 1c33f656f7eb3cad4d12de1e1a9f5285dae91df1 | refs/heads/master | 2022-02-19T08:56:44.839769 | 2019-09-13T12:45:19 | 2019-09-13T12:45:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 963 | py | # given an agent, eval fitness against cartpole
import gym
from PIL import Image
class CartPoleFitness(object):
def __init__(self, render=False):
# prep cart pole env
self.env = gym.make('CartPole-v0')
self.render = render
def fitness(self, agent):
total_reward = 0
for _ in range(10): # num_trials ?
observation = self.env.reset()
done = False
episode_reward = 0
while not done:
action = agent.decide_action(observation)
observation, reward, done, _info = self.env.step(action)
episode_reward += reward
if self.render:
self.env.render()
#rgb_array = self.env.render(mode='rgb_array')
#img = Image.fromarray(rgb_array)
# img.save("cartpole.png")
total_reward += episode_reward
return total_reward
| [
"matthew.kelcey@gmail.com"
] | matthew.kelcey@gmail.com |
a032d70b9c31a56477988fc39f040166ff30a2bb | bdc635a69a9893d01804044d4458fe6af302e586 | /ciphercode.py | 3decd2774a9a6d707c90eaa886d5f55c398155af | [] | no_license | sidv1905/Python-programs | 55ed197bd0b6b01a6c2e1b06d1f13a76f520dbe5 | 796381324ddeebc65a778b22eb2ba07d60038698 | refs/heads/master | 2021-06-16T01:54:20.606829 | 2019-05-23T21:10:20 | 2019-05-23T21:10:20 | 188,306,140 | 1 | 0 | null | 2021-05-06T19:34:12 | 2019-05-23T21:02:15 | Python | UTF-8 | Python | false | false | 264 | py | S=input()
sf=''
k=int(input())
for i in S:
if i.isupper():
sf += chr(65+(ord(i)+k-65) % 26)
elif i.islower():
sf += chr(97+(ord(i)+k-97) % 26)
elif i.isnumeric():
sf += str((int(i) + k) % 10)
else:
sf += i
print(sf)
| [
"sidvarangaonkar1905@gmail.com"
] | sidvarangaonkar1905@gmail.com |
b89d17a72689a1ec6488030cde8fd3cde2eb6805 | ee9779fd7248b8897dae11df56b0195e90cc28ae | /docs/_ext/sphinx_clickx.py | 7083f579cd7a7c4fd8dc5fef412a46b50de93643 | [
"Apache-2.0"
] | permissive | mobiusklein/glycresoft | 8f31fd4c7941e8251768e3b4dfed46537c03de32 | 43246cb4c7feca36646abcaa8b5139b471a73ebe | refs/heads/master | 2023-09-03T22:38:06.094335 | 2023-09-03T21:28:35 | 2023-09-03T21:28:35 | 62,980,813 | 7 | 4 | null | 2018-01-19T19:27:40 | 2016-07-10T04:05:43 | Python | UTF-8 | Python | false | false | 10,251 | py | import re
from docutils import nodes
from docutils.parsers.rst import directives
from docutils import statemachine
import click
from docutils.parsers.rst import Directive
def clean_type_name(typename):
if not isinstance(typename, str):
try:
typename = typename.human_readable_name
except AttributeError:
typename = ' '.join(re.findall(r"[A-Z]+[^A-Z]+", typename.__class__.__name__)
).lower().strip()
cleaned = re.sub(r"(param$)|(param type)|(range)|(type)", "", typename).strip()
return cleaned
def _indent(text, level=1):
prefix = ' ' * (4 * level)
def prefixed_lines():
for line in text.splitlines(True):
yield (prefix + line if line.strip() else line)
return ''.join(prefixed_lines())
def _get_usage(ctx):
"""Alternative, non-prefixed version of 'get_usage'."""
formatter = ctx.make_formatter()
pieces = ctx.command.collect_usage_pieces(ctx)
formatter.write_usage(ctx.command_path, ' '.join(pieces), prefix='')
return formatter.getvalue().rstrip('\n')
def _get_help_record(opt):
"""Re-implementation of click.Opt.get_help_record.
The variant of 'get_help_record' found in Click makes uses of slashes to
separate multiple opts, and formats option arguments using upper case. This
is not compatible with Sphinx's 'option' directive, which expects
comma-separated opts and option arguments surrounded by angle brackets [1].
[1] http://www.sphinx-doc.org/en/stable/domains.html#directive-option
"""
if opt.get_help_record(None) is None:
return None
def _write_opts(opts):
rv, _ = click.formatting.join_options(opts)
if not opt.is_flag and not opt.count:
rv += ' <{}>'.format(
clean_type_name(opt.type))
return rv
rv = [_write_opts(opt.opts)]
if opt.secondary_opts:
rv.append(_write_opts(opt.secondary_opts))
help = opt.help or ''
extra = []
if opt.default is not None and opt.show_default:
extra.append('default: %s' % (
', '.join('%s' % d for d in opt.default)
if isinstance(opt.default, (list, tuple))
else opt.default, ))
if opt.required:
extra.append('required')
if extra:
help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))
choices = []
if isinstance(opt.type, click.Choice):
def chunk(iterable, size=3):
i = 0
iterable = tuple(iterable)
n = len(iterable)
while i < n:
yield iterable[i:i + size]
i += size
choices.append("| Choices: [")
choices.append("\n| ")
choices.append(';\n| '.join(
map(_indent, map("; ".join, chunk(opt.type.choices)))
))
choices.append("]")
return ', '.join(rv), help, ''.join(choices)
def _format_option(opt):
"""Format the output a `click.Option`."""
is_multiple = opt.multiple
opt = _get_help_record(opt)
if opt is None:
return
yield '.. option:: {}'.format(opt[0])
if opt[1]:
yield ''
lines = list(statemachine.string2lines(opt[1], tab_width=4, convert_whitespace=True))
if is_multiple:
lines[-1] += " (May specify more than once)"
for line in lines:
yield _indent(line)
if opt[2]:
yield ''
for line in statemachine.string2lines(
opt[2], tab_width=4, convert_whitespace=True):
yield _indent(line)
def _format_argument(arg):
"""Format the output of a `click.Argument`."""
yield '.. option:: {}'.format(arg.human_readable_name)
yield ''
yield _indent('{} argument{}'.format(
'Required' if arg.required else 'Optional',
'(s)' if arg.nargs != 1 else ''))
# yield _indent("")
description = "<{}> ".format(arg.type.__class__.__name__.lower().replace(
"paramtype", ""))
yield _indent(description + getattr(arg, "doc_help", ""))
def _format_envvar(param):
"""Format the envvars of a `click.Option` or `click.Argument`."""
yield '.. envvar:: {}'.format(param.envvar)
yield ''
if isinstance(param, click.Argument):
param_ref = param.human_readable_name
else:
# if a user has defined an opt with multiple "aliases", always use the
# first. For example, if '--foo' or '-f' are possible, use '--foo'.
param_ref = param.opts[0]
yield _indent('Provide a default for :option:`{}`'.format(param_ref))
def _format_subcommand(command):
"""Format a sub-command of a `click.Command` or `click.Group`."""
yield '.. object:: {}'.format(command[0])
if command[1].short_help:
yield ''
for line in statemachine.string2lines(
command[1].short_help, tab_width=4, convert_whitespace=True):
yield _indent(line)
def _format_command(ctx, show_nested):
"""Format the output of `click.Command`."""
yield '.. program:: {}'.format(ctx.command_path)
# usage
yield '.. code-block:: shell'
yield ''
for line in _get_usage(ctx).splitlines():
yield _indent(line)
yield ''
# options
# the hidden attribute is part of click 7.x only hence use of getattr
params = [x for x in ctx.command.params if isinstance(x, click.Option)
and not getattr(x, 'hidden', False)]
if params:
# we use rubric to provide some separation without exploding the table
# of contents
yield '.. rubric:: Options'
yield ''
for param in params:
for line in _format_option(param):
yield line
yield ''
# arguments
params = [x for x in ctx.command.params if isinstance(x, click.Argument)]
if params:
yield '.. rubric:: Arguments'
yield ''
for param in params:
for line in _format_argument(param):
yield line
yield ''
# environment variables
params = [x for x in ctx.command.params if getattr(x, 'envvar')]
if params:
yield '.. rubric:: Environment variables'
yield ''
for param in params:
for line in _format_envvar(param):
yield line
yield ''
# if we're nesting commands, we need to do this slightly differently
if show_nested:
return
commands = sorted(getattr(ctx.command, 'commands', {}).items())
if commands:
yield '.. rubric:: Commands'
yield ''
for command in commands:
for line in _format_subcommand(command):
yield line
yield ''
class ClickDirective(Directive):
has_content = False
required_arguments = 1
option_spec = {
'prog': directives.unchanged_required,
'show-nested': directives.flag,
}
def _load_module(self, module_path):
"""Load the module."""
try:
module_name, attr_name = module_path.split(':', 1)
except ValueError: # noqa
raise self.error('"{}" is not of format "module.parser"'.format(
module_path))
try:
mod = __import__(module_name, globals(), locals(), [attr_name])
except: # noqa
raise self.error('Failed to import "{}" from "{}"'.format(
attr_name, module_name))
if not hasattr(mod, attr_name):
raise self.error('Module "{}" has no attribute "{}"'.format(
module_name, attr_name))
return getattr(mod, attr_name)
def _generate_nodes(self, name, command, parent=None, show_nested=False):
"""Generate the relevant Sphinx nodes.
Format a `click.Group` or `click.Command`.
:param name: Name of command, as used on the command line
:param command: Instance of `click.Group` or `click.Command`
:param parent: Instance of `click.Context`, or None
:param show_nested: Whether subcommands should be included in output
:returns: A list of nested docutil nodes
"""
ctx = click.Context(command, info_name=name, parent=parent)
# Title
# We build this with plain old docutils nodes
section = nodes.section(
'',
nodes.title(text=name),
ids=[nodes.make_id(ctx.command_path)],
names=[nodes.fully_normalize_name(ctx.command_path)])
source_name = ctx.command_path
result = statemachine.ViewList()
# Description
# We parse this as reStructuredText, allowing users to embed rich
# information in their help messages if they so choose.
if ctx.command.help:
for line in statemachine.string2lines(
ctx.command.help, tab_width=4, convert_whitespace=True):
result.append(line, source_name)
result.append('', source_name)
# Summary
if isinstance(command, click.Command):
summary = _format_command(ctx, show_nested)
else:
# TODO(stephenfin): Do we care to differentiate? Perhaps we
# shouldn't show usage for groups?
summary = _format_command(ctx, show_nested)
for line in summary:
result.append(line, source_name)
self.state.nested_parse(result, 0, section)
# Commands
if show_nested:
commands = getattr(ctx.command, 'commands', {})
for command_name, command_obj in sorted(commands.items()):
section.extend(self._generate_nodes(
command_name,
command_obj,
ctx,
show_nested))
return [section]
def run(self):
self.env = self.state.document.settings.env
command = self._load_module(self.arguments[0])
if 'prog' in self.options:
prog_name = self.options.get('prog')
else:
raise self.error(':prog: must be specified')
show_nested = 'show-nested' in self.options
return self._generate_nodes(prog_name, command, None, show_nested)
def setup(app):
app.add_directive('click', ClickDirective)
| [
"mobiusklein@gmail.com"
] | mobiusklein@gmail.com |
6a243b740ac60525a548af49025da95c955bd002 | f6703b2afca284bf75e0dbf8f61d77e5251f905c | /euler362.py | a8c1a82abc396cc3badb55813c2bc8abd0374d9d | [] | no_license | rwieckowski/project-euler-python | 2a7aa73670b4684f076ad819bfc464aa0778f96c | be9a455058b20adfd32c814effd8753cc9d39890 | refs/heads/master | 2021-01-10T21:10:44.875335 | 2015-06-23T13:29:58 | 2015-06-23T13:29:58 | 37,920,684 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 730 | py | """
<P>Consider the number 54<BR />54 can be factored in 7 distinct ways
into one or more factors larger than 1<BR />54 2times27 3times18 6
times9 3times3times6 2times3times9 and 2times3times3times3<BR />If we
require that the factors are all squarefree only two ways remain 3
times3times6 and 2times3times3times3</P><P>Lets call Fsf<var>n</var>
the number of ways <var>n</var> can be factored into one or more
squarefree factors larger than 1 soFsf542</P><P>Let S<var>n</var> be
sumFsf<var>k</var> for <var>k</var>2 to <var>n</var></P><P>S100193</P>
<P>Find S10 000 000 000 </P>
"""
def euler362():
"""
>>> euler362()
'to-do'
"""
pass
if __name__ == "__main__":
import doctest
doctest.testmod() | [
"rwieckowski@ivmx.pl"
] | rwieckowski@ivmx.pl |
fec30960396bc57c474027f4ee00640ac2016109 | 16faeb74a141ce5274f176df4c0cffed4dde2512 | /src/vk_crawler.py | b698909db1ebbd8c788ef5bfcc21d1a02e329047 | [] | no_license | kunansy/Crawler | a0005a18e27551b55bb8c7432cd4170bf7ca238b | 02bc04f34077480d5c354f8e6a21bab7614f0d71 | refs/heads/master | 2023-01-31T02:39:56.694447 | 2020-12-10T15:03:06 | 2020-12-10T15:03:06 | 291,439,024 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,062 | py | import csv
import datetime
import logging
import os
import re
from pathlib import Path
from typing import List, Tuple, Any, Dict
from src.request import get_json
# Dict[str, Any]
Sdict = Dict[str, Any]
# pairs with languages
TL = Tuple[str, str]
# folder with csv files
DATA_FOLDER = Path('data') / 'VK'
# folder with files with skipped posts
SKIPPED_POSTS_FOLDER = DATA_FOLDER / 'skipped_posts'
os.makedirs(SKIPPED_POSTS_FOLDER, exist_ok=True)
# delimiter in csv files
DELIMITER = '\t'
ENCODING = 'utf-8'
# for metadata writing
FIELDNAMES = (
'path', 'header', 'created', 'author', 'birthday', 'header_trans',
'author_trans', 'translator', 'date_trans', 'sphere', 'lang', 'lang_trans'
)
BASE_URL = "https://api.vk.com/method"
SEARCH_ON_WALL = "wall.search"
logger = logging.getLogger(__name__)
DEFAULT_MSG_FMT = "[{name}:{levelname}:{funcName}:{asctime}] {message}"
DEFAULT_DATE_FMT = "%d.%m.%Y %H:%M:%S"
LOG_FOLDER = Path('logs')
os.makedirs(LOG_FOLDER, exist_ok=True)
formatter = logging.Formatter(
fmt=DEFAULT_MSG_FMT,
datefmt=DEFAULT_DATE_FMT,
style='{'
)
# create stream handler
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(formatter)
# create file handler
log_file_path = LOG_FOLDER / f"{__name__}.log"
file_handler = logging.FileHandler(
log_file_path, delay=True, encoding='utf-8')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
# add these handlers
logger.addHandler(stream_handler)
logger.addHandler(file_handler)
class VKCrawler:
def __init__(self,
access_token: str,
method: str = SEARCH_ON_WALL,
**params) -> None:
""" Init the VK crawler.
:param access_token: str, access token.
:param method: str, method of the VK API you want to use.
:param params: some keywords to request.
See documentation how to set it.
:return: None.
"""
self._url = BASE_URL
self._method = method
self._access_token = access_token
self._params = {
**params,
'v': '5.122',
'access_token': self.access_token
}
self._posts = []
self._parsed_posts = []
self._results_count = self._get_results_count()
self._skipped_posts = []
self._dateformat = "%m/%d/%Y"
self._data_folder = DATA_FOLDER
self._skipped_posts_folder = SKIPPED_POSTS_FOLDER
@property
def skipped_posts_folder(self) -> Path:
"""
:return: Path to the folder with
files with skipped posts.
"""
return self._skipped_posts_folder
@property
def data_folder(self) -> Path:
"""
:return: Path to data folder with all files.
"""
return self._data_folder
@property
def skipped_posts(self) -> List[Dict]:
"""
:return: list of dicts, posts have not been parsed.
"""
return self._skipped_posts
@property
def results_count(self) -> int:
"""
:return: int, count of results of the request.
"""
return self._results_count
@property
def url(self) -> str:
"""
:return: str, url of vk dev joined with the method.
"""
return f"{self._url}/{self._method}"
@property
def posts(self) -> List[Sdict]:
"""
:return: list of dicts, posts from VK.
"""
return self._posts
@property
def parsed_posts(self) -> List[Sdict]:
"""
:return: list of dict, parsed posts.
"""
return self._parsed_posts
@property
def access_token(self) -> str:
"""
:return: str, access token.
"""
return self._access_token
def update(self,
last_results_count: int) -> None:
""" Get all new posts.
:param last_results_count: int, old count of results (=count of docs).
From here count of new posts will be calculated.
:return: None.
"""
if self.results_count < last_results_count:
raise ValueError(
"Old results count must be <= than current count")
new_count = self.results_count - last_results_count
self.request(new_count)
def request(self,
count: int) -> None:
""" Request posts from vk and parse them.
Update posts list and list of parsed posts.
:param count: int, count of posts.
:return: None.
"""
if count > self.results_count:
raise ValueError(f"There are less results: '{self.results_count}'")
posts = get_json(self.url, **self._params, count=count)
posts = [
item['response']['items']
for item in posts
]
# convert matrix to list
self._posts = sum(posts, [])
self._parsed_posts += self._parse_posts()
def _get_results_count(self) -> int:
""" Get count of results found in VK.
:return: int, count of results.
"""
response = get_json(self.url, **self._params, count=1)
return response[0]['response']['count']
@staticmethod
def _swap_langs(pairs: List[TL]) -> List[TL]:
""" Swap languages if the first one is not Russian.
:param pairs: list of tuples, pairs: Russian – Chinese (expected).
:return: list of tuples, pairs with corrected order.
"""
fixed_pairs = []
ru_pattern = re.compile(r'[а-яё]', flags=re.IGNORECASE)
for lhs, rhs in pairs:
if ru_pattern.search(lhs) and VKCrawler._define_language(rhs) == 'rus':
raise ValueError(
f"There is a pair with the same languages: \n{lhs}\n{rhs}")
if ru_pattern.search(lhs):
fixed_pairs += [(lhs, rhs)]
else:
fixed_pairs += [(rhs, lhs)]
return fixed_pairs
@staticmethod
def _define_language(text: str) -> str:
if re.search(r'[\u4e00-\u9fff]+', text):
return 'zho'
elif re.search(r'[а-яё]', text, flags=re.IGNORECASE):
return 'rus'
return ''
@staticmethod
def _remove_trash(text: str) -> str:
""" Remove 'ключевая фраза...' from the text.
:param text: str, text to clear.
:return: str, cleared text.
"""
daily_remember = re.compile(
r'(ключев(ая|ое) (фраза|слово|словосочетение)).*',
flags=re.IGNORECASE
)
found = daily_remember.search(text)
if found and found.group(0):
start = text.index('\n\n')
stop = text.index('\n\n', start + 2)
removed = text[start:stop]
if not daily_remember.search(removed):
raise ValueError("Daily remember is not here")
title = text[:start]
txt = text[stop:]
text = f"{title}\n\n{txt}"
return text
@staticmethod
def _get_text(text: str) -> Sdict:
""" Parse text to its headers and list of tuples:
Russian text, Chinese text.
Dict format {
'header': header in Chinese.
'header_trans': header in Russian,
'text': [(Russian, Chinese), (Russian, Chinese)...]
}
:param text: str, text to parse.
:return: dict of str with the format.
"""
text = text.replace('\n \n', '\n\n')
text = VKCrawler._remove_trash(text)
paragraphs = text.split('\n')
paragraphs = [
text.strip()
for text in paragraphs
if len(text.strip()) > 1 and not text.startswith('#')
]
if not paragraphs:
raise ValueError("Post is empty")
if len(paragraphs) % 2 is 1:
raise ValueError(f"There is odd count of paragraphs: {paragraphs}")
pairs = list(zip(paragraphs[::2], paragraphs[1::2]))
# swap languages if it is demanded
pairs = VKCrawler._swap_langs(pairs)
header_trans, header = pairs[0]
return {
'header': header,
'header_trans': header_trans,
'text': pairs[1:]
}
@staticmethod
def _get_date(timestamp: int) -> datetime.date:
""" Convert date from timestamp to datetime.
:param timestamp: int, date in timestamp.
:return: date.
"""
dt = datetime.datetime.fromtimestamp(timestamp)
return dt.date()
def _format_date(self,
date: datetime.datetime or datetime.date) -> str:
""" Format the date obj to str.
:param date: datetime.date to format.
:return: str, formatted date.
"""
return date.strftime(self._dateformat)
@staticmethod
def _parse_post(post: Sdict,
dateformat: str) -> Sdict:
""" Get all info from the post.
Dict format {
'header': header in Chinese.
'header_trans': header in Russian,
'text': [(Russian, Chinese), (Russian, Chinese)...],
'date': date, str format m/d/y
}
:param post: dict of str, post to parse.
:param dateformat: str, dateformat.
:return: dict of str with the format
"""
date = VKCrawler._get_date(post['date'])
date = date.strftime(dateformat)
try:
title_and_text = VKCrawler._get_text(post['text'])
except AssertionError:
raise
except ValueError:
raise
return {
**title_and_text,
'date': date,
}
def _parse_posts(self) -> List[Sdict]:
""" Parse all posts to dict format: {
'header': header in Chinese
'header_trans': header in Russian,
'text': [(Russian, Chinese), (Russian, Chinese)...],
'date': date, str format m/d/y
}
:return: list of parsed posts.
"""
parsed_posts = []
for post in self.posts:
try:
parsed_post = VKCrawler._parse_post(post, self._dateformat)
except AssertionError as e:
logger.error(f"{e}\n{post}\nPost added to skipped posts list\n")
self._skipped_posts += [post]
except ValueError as e:
logger.error(f"{e}\n{post}\nPost added to skipped posts list\n")
self._skipped_posts += [post]
else:
parsed_posts += [parsed_post]
return parsed_posts
@staticmethod
def _dump_one(post: Sdict,
filepath: Path) -> None:
""" Dump one post to the csv file.
:param post: dict of str, post to dump.
:param filepath: Path to the file.
:return: None.
"""
with filepath.open('w', newline='', encoding=ENCODING) as f:
writer = csv.writer(
f, delimiter=DELIMITER, quoting=csv.QUOTE_MINIMAL)
for pair_ru_ch in post['text']:
writer.writerow(pair_ru_ch)
def _create_filename(self,
title: str) -> Path:
""" Remove wrong symbols from the title,
replace spaces to the '_', add DATA_FOLDER
as a parent and short the filename to 32 symbols.
:param title: str, title of the post.
:return: Path to the csv file in the DATA_FOLDER.
"""
title = [
symbol if symbol != ' ' else '_'
for symbol in title
if symbol.isalpha() or symbol == ' '
]
filename = ''.join(title)[:32]
return self.data_folder / f"{filename}.csv"
def dump_all(self) -> None:
""" Dump to csv all posts and write to
other file metadata.
Filename is the first 32 symbols of
Russian translation of the title.
:return: None.
"""
metadata = []
for post in self.parsed_posts:
header = post.pop('header', '')
header_trans = post.pop('header_trans')
date = post.pop('date', '')
# name is the first 32 symbols of Russian
# translation of the title
path = self._create_filename(header_trans)
md = {
'path': path.name,
'header': header,
'header_trans': header_trans,
'created': date,
'lang': 'zho',
'lang_trans': 'rus'
}
metadata += [md]
VKCrawler._dump_one(post, path)
VKCrawler._dump_metadata(metadata)
def _dump_one_skipped_post(self,
post: Dict[str, Any],
path: Path) -> None:
""" Dump skipped post to txt file.
Dump only date in standard format and text.
:param post: dict of str, post to dump.
:param path: Path to txt the file.
:return: None.
"""
date = VKCrawler._get_date(post['date'])
date = self._format_date(date)
with path.open('w', encoding=ENCODING) as f:
f.write(f"{date}\n")
f.write(post['text'])
def dump_skipped_posts(self) -> None:
""" Dump all skipped posts to separate
files in the special folder.
Their names are: 'post1.txt', 'post2.txt'...
:return: None.
"""
for num, post in enumerate(self.skipped_posts, 1):
path = self.skipped_posts_folder / f"post{num}.txt"
try:
self._dump_one_skipped_post(post, path)
except KeyError as e:
logger.error(
f"Post has no expected fields\n{e}\n{post}\n")
def _parse_one_skipped_post(self,
path: Path) -> Sdict:
""" Parse the file with corrected format.
Dict format {
'date': date in timestamp,
'text': str, text
}.
:param path: Path to the file to parse.
:return: this dict.
"""
res = {}
with path.open(encoding=ENCODING) as f:
lines = f.readlines()
date = lines[0].strip()
date = datetime.datetime.strptime(date, self._dateformat)
timestamp = date.timestamp()
text = ''.join(lines[1:])
res['date'] = timestamp
res['text'] = text
return res
def from_txt_to_csv(self) -> None:
""" Convert txt files with skipped posts
from the standard folder to csv files.
Update (extend) the list of parsed posts.
Here it is assumed that in the skipped_posts_folder
are fixed posts, means their format was corrected.
:return: None.
"""
for item in os.listdir(self.skipped_posts_folder):
path = self.skipped_posts_folder / item
if not path.is_file():
continue
post = self._parse_one_skipped_post(path)
try:
parsed_post = self._parse_post(post, self._dateformat)
except ValueError as e:
logger.error(f"{e}\nIn file {item}\nWith post: {post}\n")
continue
self._parsed_posts += [parsed_post]
@staticmethod
def _dump_metadata(metadata: List[Sdict]) -> None:
""" Dump metadata to csv file, set an
empty str to field if it does not exist.
:param metadata: list of dicts, metadata to dump.
:return: None.
"""
path = DATA_FOLDER / 'metadata.csv'
with path.open('w', newline='', encoding=ENCODING) as f:
writer = csv.DictWriter(
f, restval='',
fieldnames=FIELDNAMES,
delimiter=DELIMITER,
quoting=csv.QUOTE_MINIMAL
)
writer.writeheader()
writer.writerows(metadata)
| [
"kolobov.kirill@list.ru"
] | kolobov.kirill@list.ru |
29eee61b8a8b7fb8569e612e93eececee6fa6872 | 9df2fb0bc59ab44f026b0a2f5ef50c72b2fb2ceb | /sdk/servicebus/azure-servicebus/azure/servicebus/_servicebus_session.py | f095c85f1ab1f07ad897ec4340781a6c613e71c0 | [
"MIT",
"LGPL-2.1-or-later",
"LicenseRef-scancode-generic-cla"
] | permissive | openapi-env-test/azure-sdk-for-python | b334a2b65eeabcf9b7673879a621abb9be43b0f6 | f61090e96094cfd4f43650be1a53425736bd8985 | refs/heads/main | 2023-08-30T14:22:14.300080 | 2023-06-08T02:53:04 | 2023-06-08T02:53:04 | 222,384,897 | 1 | 0 | MIT | 2023-09-08T08:38:48 | 2019-11-18T07:09:24 | Python | UTF-8 | Python | false | false | 8,209 | py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import logging
import datetime
import warnings
from typing import TYPE_CHECKING, Any, Union, Optional
from ._common.utils import utc_from_timestamp, utc_now
from ._common.constants import (
REQUEST_RESPONSE_GET_SESSION_STATE_OPERATION,
REQUEST_RESPONSE_SET_SESSION_STATE_OPERATION,
REQUEST_RESPONSE_RENEW_SESSION_LOCK_OPERATION,
MGMT_RESPONSE_SESSION_STATE,
MGMT_RESPONSE_RECEIVER_EXPIRATION,
MGMT_REQUEST_SESSION_ID,
MGMT_REQUEST_SESSION_STATE,
)
from ._common import mgmt_handlers
if TYPE_CHECKING:
from ._servicebus_receiver import ServiceBusReceiver
from .aio._servicebus_receiver_async import (
ServiceBusReceiver as ServiceBusReceiverAsync,
)
_LOGGER = logging.getLogger(__name__)
class BaseSession(object):
def __init__(
self,
session_id: str,
receiver: Union["ServiceBusReceiver", "ServiceBusReceiverAsync"]
) -> None:
self._session_id = session_id
self._receiver = receiver
self._encoding = "UTF-8"
self._session_start = None
self._locked_until_utc: Optional[datetime.datetime] = None
self._lock_lost = False
self.auto_renew_error = None
@property
def _lock_expired(self) -> bool:
"""Whether the receivers lock on a particular session has expired.
:rtype: bool
"""
return bool(self._locked_until_utc and self._locked_until_utc <= utc_now())
@property
def session_id(self) -> str:
"""
Session id of the current session.
:rtype: str
"""
return self._session_id
@property
def locked_until_utc(self) -> Optional[datetime.datetime]:
"""The time at which this session's lock will expire.
:rtype: datetime.datetime
"""
return self._locked_until_utc
class ServiceBusSession(BaseSession):
"""
The ServiceBusSession is used for manage session states and lock renewal.
**Please use the property `session` on the ServiceBusReceiver to get the corresponding ServiceBusSession
object linked with the receiver instead of instantiating a ServiceBusSession object directly.**
:ivar auto_renew_error: Error when AutoLockRenewer is used and it fails to renew the session lock.
:vartype auto_renew_error: ~azure.servicebus.AutoLockRenewTimeout or ~azure.servicebus.AutoLockRenewFailed
.. admonition:: Example:
.. literalinclude:: ../samples/sync_samples/sample_code_servicebus.py
:start-after: [START get_session_sync]
:end-before: [END get_session_sync]
:language: python
:dedent: 4
:caption: Get session from a receiver
"""
def get_state(self, *, timeout: Optional[float] = None, **kwargs: Any) -> bytes:
# pylint: disable=protected-access
"""Get the session state.
Returns None if no state has been set.
:keyword float timeout: The total operation timeout in seconds including all the retries. The value must be
greater than 0 if specified. The default value is None, meaning no timeout.
:rtype: bytes
.. admonition:: Example:
.. literalinclude:: ../samples/sync_samples/sample_code_servicebus.py
:start-after: [START get_session_state_sync]
:end-before: [END get_session_state_sync]
:language: python
:dedent: 4
:caption: Get the session state
"""
if kwargs:
warnings.warn(f"Unsupported keyword args: {kwargs}")
self._receiver._check_live() # pylint: disable=protected-access
if timeout is not None and timeout <= 0:
raise ValueError("The timeout must be greater than 0.")
response = self._receiver._mgmt_request_response_with_retry(
REQUEST_RESPONSE_GET_SESSION_STATE_OPERATION,
{MGMT_REQUEST_SESSION_ID: self._session_id},
mgmt_handlers.default,
timeout=timeout,
)
session_state = response.get(MGMT_RESPONSE_SESSION_STATE) # type: ignore
return session_state
def set_state(
self, state: Optional[Union[str, bytes, bytearray]], *, timeout: Optional[float] = None, **kwargs: Any
) -> None:
# pylint: disable=protected-access
"""Set the session state.
:param state: The state value. Setting state to None will clear the current session.
:type state: Union[str, bytes, bytearray, None]
:keyword float timeout: The total operation timeout in seconds including all the retries. The value must be
greater than 0 if specified. The default value is None, meaning no timeout.
.. admonition:: Example:
.. literalinclude:: ../samples/sync_samples/sample_code_servicebus.py
:start-after: [START set_session_state_sync]
:end-before: [END set_session_state_sync]
:language: python
:dedent: 4
:caption: Set the session state
"""
if kwargs:
warnings.warn(f"Unsupported keyword args: {kwargs}")
self._receiver._check_live() # pylint: disable=protected-access
if timeout is not None and timeout <= 0:
raise ValueError("The timeout must be greater than 0.")
state = (
state.encode(self._encoding) if isinstance(state, str) else state
)
return self._receiver._mgmt_request_response_with_retry( # type: ignore
REQUEST_RESPONSE_SET_SESSION_STATE_OPERATION,
{
MGMT_REQUEST_SESSION_ID: self._session_id,
MGMT_REQUEST_SESSION_STATE: bytearray(state) if state is not None else None,
},
mgmt_handlers.default,
timeout=timeout,
)
def renew_lock(self, *, timeout: Optional[float] = None, **kwargs: Any) -> datetime.datetime:
# pylint: disable=protected-access
"""Renew the session lock.
This operation must be performed periodically in order to retain a lock on the
session to continue message processing.
Once the lock is lost the connection will be closed; an expired lock cannot be renewed.
This operation can also be performed as a threaded background task by registering the session
with an `azure.servicebus.AutoLockRenewer` instance.
:keyword float timeout: The total operation timeout in seconds including all the retries. The value must be
greater than 0 if specified. The default value is None, meaning no timeout.
:returns: The utc datetime the lock is set to expire at.
:rtype: datetime.datetime
.. admonition:: Example:
.. literalinclude:: ../samples/sync_samples/sample_code_servicebus.py
:start-after: [START session_renew_lock_sync]
:end-before: [END session_renew_lock_sync]
:language: python
:dedent: 4
:caption: Renew the session lock before it expires
"""
if kwargs:
warnings.warn(f"Unsupported keyword args: {kwargs}")
self._receiver._check_live() # pylint: disable=protected-access
if timeout is not None and timeout <= 0:
raise ValueError("The timeout must be greater than 0.")
expiry = self._receiver._mgmt_request_response_with_retry(
REQUEST_RESPONSE_RENEW_SESSION_LOCK_OPERATION,
{MGMT_REQUEST_SESSION_ID: self._session_id},
mgmt_handlers.session_lock_renew_op,
timeout=timeout,
)
expiry_timestamp = expiry[MGMT_RESPONSE_RECEIVER_EXPIRATION] / 1000.0 # type: ignore
self._locked_until_utc = utc_from_timestamp(expiry_timestamp) # type: datetime.datetime
return self._locked_until_utc
| [
"noreply@github.com"
] | openapi-env-test.noreply@github.com |
110872ad79c95d39290a9a65b9e28178a3a65cdf | 200ec10b652f9c504728890f6ed7d20d07fbacae | /migrations/versions/c782b3c7ff30_.py | 3e3707f526106deafa59f0bf3a3ba1ecc69a68cd | [] | no_license | Ks-Ksenia/flask_shop | f4edc17669c29ae02a89e836c3c48230147ae84f | 9eb44fd22bf99913c9824ea35e3922cb14ef2451 | refs/heads/master | 2023-03-01T13:55:20.749127 | 2021-02-14T09:29:04 | 2021-02-14T09:29:04 | 338,767,599 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,769 | py | """empty message
Revision ID: c782b3c7ff30
Revises:
Create Date: 2021-01-28 10:59:15.555312
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c782b3c7ff30'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('post',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=100), nullable=True),
sa.Column('body', sa.String(length=100), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('role',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=200), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('email', sa.String(length=100), nullable=True),
sa.Column('username', sa.String(length=100), nullable=True),
sa.Column('password', sa.String(length=255), nullable=True),
sa.Column('is_superuser', sa.Boolean(), nullable=True),
sa.Column('created', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email')
)
op.create_table('roles_users',
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('role_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['role_id'], ['role.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], )
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('roles_users')
op.drop_table('user')
op.drop_table('role')
op.drop_table('post')
# ### end Alembic commands ###
| [
"demag74@mail.ru"
] | demag74@mail.ru |
e24e038928e1c3e8008a338b693451cfac3c780f | f82e67dd5f496d9e6d42b4fad4fb92b6bfb7bf3e | /scripts/client/gui/shared/soundeffectsid.py | 2e8f0e577fd6cd3f4b4408c7c2436eddfc45b327 | [] | no_license | webiumsk/WOT0.10.0 | 4e4413ed4e7b00e22fb85d25fdae9400cbb4e76b | a84f536c73f86d9e8fab559e97f88f99f2ad7e95 | refs/heads/master | 2021-01-09T21:55:00.662437 | 2015-10-23T20:46:45 | 2015-10-23T20:46:45 | 44,835,654 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,871 | py | # Embedded file name: scripts/client/gui/shared/SoundEffectsId.py
from debug_utils import LOG_DEBUG
import FMOD
class SoundEffectsId(object):
if FMOD.enabled:
SPEND_CREDITS_GOLD = 'spend_credits_and_gold'
SPEND_CREDITS = 'spend_credits'
SPEND_GOLD = 'spend_gold'
EARN_CREDITS_GOLD = 'earn_credits_and_gold'
EARN_CREDITS = 'earn_credits'
EARN_GOLD = 'earn_gold'
TRANSPORT_ENTER = 'transport_enter'
TRANSPORT_EXIT = 'transport_exit'
TRANSPORT_FIRST_STEP = 'transport_first_step'
TRANSPORT_NEXT_STEP = 'transport_next_step'
TRANSPORT_APPROVE = 'transport_approve'
FORT_CREATE = 'fort_create'
FORT_ENTERED_FOUNDATION_STATE = 'fort_entered_foundation_state'
FORT_FIXED_IN_BUILDING = 'fort_fixed_in_building'
FORT_UPGRADE_BUILDING = 'fort_upgrade_building'
FORT_DEMOUNT_BUILDING = 'fort_demount_building'
FORT_ORDER_INPROGRESS = 'fort_order_inprogress'
FORT_ORDER_ISREADY = 'fort_order_isready'
FORT_DIRECTION_CREATE = 'direction_create'
FORT_DIRECTION_CLOSE = 'direction_close'
ACTIVATE_REQUISITION = 'activate_requisition'
ACTIVATE_EVACUATION = 'activate_evacuation'
ACTIVATE_HEAVY_TRUCKS = 'activate_heavyTrucks'
ACTIVATE_MILITARY_MANEUVERS = 'activate_militaryManeuvers'
ACTIVATE_ADDITIONAL_BRIEFING = 'activate_additionalBriefing'
ACTIVATE_TACTICAL_TRAINING = 'activate_tacticalTraining'
ACTIVATE_BATTLE_PAYMENTS = 'activate_battlePayments'
ACTIVATE_SPECIALMISSION = 'activate_specialMission'
END_BUILDING_PROCESS_POSTFIX = '_endPrcBld'
ACTIVATE_DEFENCE_PERIOD = 'activate_defencePeriod'
DEACTIVATE_DEFENCE_PERIOD = 'deactivate_defencePeriod'
ENEMY_DIRECTION_SELECTED = 'enemyDirection_selected'
ENEMY_DIRECTION_HOVER = 'enemyDirection_hover'
MY_DIRECTION_SELECTED = 'myDirection_selected'
FORT_CLAN_WAR_DECLARED = 'fortClanWar_declared'
BATTLE_ROOM_TIMER_ALERT = 'battleRoom_timerAlert'
FORT_CLAN_WAR_RESULT_WIN = 'fortClanWarResult_win'
FORT_CLAN_WAR_RESULT_LOSE = 'fortClanWarResult_lose'
FORT_CLAN_WAR_RESULT_DRAW = 'fortClanWarResult_draw'
CS_ANIMATION_LEAGUE_UP = 'cs_animation_league_up'
CS_ANIMATION_LEAGUE_DOWN = 'cs_animation_league_down'
CS_ANIMATION_DIVISION_UP = 'cs_animation_division_up'
CS_ANIMATION_DIVISION_UP_ALT = 'cs_animation_division_up_alt'
CS_ANIMATION_DIVISION_DOWN = 'cs_animation_division_down'
DYN_SQUAD_STARTING_DYNAMIC_PLATOON = 'dyn_squad_starting_dynamic_platoon'
RUDY_DOG = 'rody_dog'
@classmethod
def getEndBuildingProcess(cls, buildingID):
if FMOD.enabled:
result = buildingID + cls.END_BUILDING_PROCESS_POSTFIX
return result
| [
"info@webium.sk"
] | info@webium.sk |
78de0ffe83efea63c213df8dbd4adbca5a3209bd | 315f126df2d863cb269a021956dc6c92f60794e7 | /09waimaii/app/models/member.py | f27dd3c295a55be873674419f3fb68a450725dd0 | [] | no_license | OCC111/1809flask | 6759cdac5dea2208e38a204987c9271cf3fc69c5 | 7902e1083a558db2eb6ac47c2c8bf2aac9a669d3 | refs/heads/master | 2020-05-30T16:13:26.117557 | 2019-06-12T12:31:10 | 2019-06-12T12:31:10 | 189,841,040 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,557 | py | from app import db
from app.models.baseModel import BaseModel
class Member(BaseModel, db.Model):
__tablename__ = 'member'
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(100), nullable=False, default='')
mobile = db.Column(db.String(11), nullable=False, default='')
gender = db.Column(db.Integer, nullable=False, default=0)
avatar = db.Column(db.String(200), nullable=False, default='')
salt = db.Column(db.String(32), nullable=False, default='')
reg_ip = db.Column(db.String(100), nullable=False, default='')
status = db.Column(db.Integer, nullable=False, default=1) # 1有效 0无效
@property
def status_desc(self):
return self.status
@property
def sex_desc(self):
sex_mapping = {
"0": "未知",
"1": "男",
"2": "女"
}
return sex_mapping[str(self.gender)]
class OauthMemberBind(BaseModel, db.Model):
__tablename__ = 'oauth_member_bind'
id = db.Column(db.Integer, primary_key=True)
client_type = db.Column(db.String(20), nullable=False, default='') # 客户端来源类型。qq,weibo,weixin
type = db.Column(db.Integer, nullable=False, default=0) # 类型 type 1:wechat ,
openid = db.Column(db.String(80), nullable=False, default='') # 第三方id
unionid = db.Column(db.String(100), nullable=False, default='')
extra = db.Column(db.Text, nullable=False, default='') # 额外字段
member_id = db.Column(db.Integer, db.ForeignKey('member.id'), nullable=False)
| [
"859899882@qq.com"
] | 859899882@qq.com |
32616bb067f3e60e516a07caea444ac8e9715e5f | b42930ea351e0910efd7b3fbc9ca3bdca0196eed | /app/migrations/0005_auto__add_boletin__add_unique_clase_materia_grupo_profesor.py | e960c90b9c0d3a2134b7a7136b2eb631d44a145a | [
"Apache-2.0"
] | permissive | henocdz/akdmik | 1ab0483d859b904e53e2ce8783b4a0c80a560aa1 | b01300942fc8b3abd8be23f44dc4057a20ae3726 | refs/heads/master | 2021-04-12T05:16:32.509407 | 2013-12-01T22:59:08 | 2013-12-01T22:59:08 | 14,650,996 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,272 | 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):
# Adding model 'Boletin'
db.create_table(u'app_boletin', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('admin', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['app.AUser'])),
('titulo', self.gf('django.db.models.fields.CharField')(max_length=140)),
('texto', self.gf('django.db.models.fields.TextField')(null=True)),
('date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
))
db.send_create_signal(u'app', ['Boletin'])
# Adding unique constraint on 'Clase', fields ['materia', 'grupo', 'profesor']
db.create_unique(u'app_clase', ['materia_id', 'grupo_id', 'profesor_id'])
def backwards(self, orm):
# Removing unique constraint on 'Clase', fields ['materia', 'grupo', 'profesor']
db.delete_unique(u'app_clase', ['materia_id', 'grupo_id', 'profesor_id'])
# Deleting model 'Boletin'
db.delete_table(u'app_boletin')
models = {
u'app.asistencia': {
'Meta': {'object_name': 'Asistencia'},
'alumno': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.AUser']"}),
'clase': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.Clase']"}),
'fecha': ('django.db.models.fields.DateField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'app.auser': {
'Meta': {'object_name': 'AUser'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'admin': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'ap_materno': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'ap_paterno': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'email': ('django.db.models.fields.EmailField', [], {'default': 'None', 'max_length': '75', 'null': 'True', 'blank': 'True'}),
'estado': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}),
'fecha_nacimiento': ('django.db.models.fields.DateField', [], {'default': "'1993-01-01'"}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'sexo': ('django.db.models.fields.CharField', [], {'max_length': '1'}),
'staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'tipo': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '12', 'db_index': 'True'})
},
u'app.boletin': {
'Meta': {'object_name': 'Boletin'},
'admin': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.AUser']"}),
'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'texto': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'titulo': ('django.db.models.fields.CharField', [], {'max_length': '140'})
},
u'app.calificacioncriterio': {
'Meta': {'object_name': 'CalificacionCriterio'},
'alumno': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.AUser']"}),
'criterio': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.Criterio']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'puntaje': ('django.db.models.fields.FloatField', [], {})
},
u'app.clase': {
'Meta': {'unique_together': "(('materia', 'grupo', 'profesor'),)", 'object_name': 'Clase'},
'grupo': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.Grupo']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'materia': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.Materia']"}),
'profesor': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.AUser']"})
},
u'app.criterio': {
'Meta': {'object_name': 'Criterio'},
'descripcion': ('django.db.models.fields.CharField', [], {'max_length': '140'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'periodo': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.Periodo']"}),
'puntaje': ('django.db.models.fields.FloatField', [], {})
},
u'app.grupo': {
'Meta': {'object_name': 'Grupo'},
'capacidad': ('django.db.models.fields.IntegerField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '5'}),
'salon': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '4'})
},
u'app.horario': {
'Meta': {'object_name': 'Horario'},
'clase': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.Clase']"}),
'dia': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'hora_fin': ('django.db.models.fields.TimeField', [], {}),
'hora_inicio': ('django.db.models.fields.TimeField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'app.materia': {
'Meta': {'object_name': 'Materia'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'keyname': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '10'}),
'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'})
},
u'app.periodo': {
'Meta': {'object_name': 'Periodo'},
'clase': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.Clase']"}),
'fin': ('django.db.models.fields.DateField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'inicio': ('django.db.models.fields.DateField', [], {}),
'numero': ('django.db.models.fields.SmallIntegerField', [], {})
},
u'app.publicacion': {
'Meta': {'object_name': 'Publicacion'},
'creador': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.AUser']"}),
'fecha': ('django.db.models.fields.DateTimeField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'pertenece': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.Clase']"})
},
u'app.task': {
'Meta': {'object_name': 'Task'},
'clase': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.Clase']"}),
'descripcion': ('django.db.models.fields.CharField', [], {'max_length': '140'}),
'due_date': ('django.db.models.fields.DateTimeField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'usuario': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['app.AUser']"})
},
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'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'})
}
}
complete_apps = ['app'] | [
"henocdz@gmail.com"
] | henocdz@gmail.com |
cdc0fc730c4fec7b7f356cae21e10e857bdc8879 | 36c0532bd632a7ec3c06ac1d03f3ba350b7c140b | /projects/serializer.py | 52f61f6f9e7a6884c87b132dbacf57c9822e4dc7 | [
"MIT"
] | permissive | apwao/Awwards | bab22f458655692ba02f278b8b929f6df3ea2339 | 521f98a8ecb9e9d03e2357f391d0611dd7173409 | refs/heads/master | 2022-11-30T01:07:35.120927 | 2019-08-28T09:25:13 | 2019-08-28T09:25:13 | 194,293,236 | 0 | 0 | null | 2022-11-22T03:55:14 | 2019-06-28T15:09:46 | Python | UTF-8 | Python | false | false | 356 | py | from rest_framework import serializers
from .models import Project
class ProjectSerializer(serializers.ModelSerializer):
"""
Class profile serializers to convert the Profile django model into a JSON object
"""
class Meta:
model=Project
fields=('project_title','project_image','project_description','live_link','posted_by')
| [
"sapwao@gmail.com"
] | sapwao@gmail.com |
e3aa334a68217191e7b035f4851912fe116d78c5 | 8c917dc4810e2dddf7d3902146280a67412c65ea | /v_7/NISS/shamil_v3/mrp_custom/report/__init__.py | 3b93f73ef14b14530c20a4b225e509228dff8fb0 | [] | no_license | musabahmed/baba | d0906e03c1bbd222d3950f521533f3874434b993 | 0b997095c260d58b026440967fea3a202bef7efb | refs/heads/master | 2021-10-09T02:37:32.458269 | 2018-12-20T06:00:00 | 2018-12-20T06:00:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 456 | py | # -*- coding: utf-8 -*-
#############################################################################
#
# NCTR, Nile Center for Technology Research
# Copyright (C) 2011-2012 NCTR (<http://www.nctr.sd>).
#
#############################################################################
#import production_costs_report
import production_cost
import production_order
import sale_report
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| [
"bakry@exp-sa.com"
] | bakry@exp-sa.com |
45f3b8998024a30e11fe46052fd28b6ada623520 | 5edebb68bd320b3e74cdafe5948c324558d786ab | /mu2e/__init__.py | 39934eb836fb48384fda016a36a3c03176f266d4 | [] | no_license | pollackscience/Mu2E | ef5816f1e7ea66a9bc42c2f4fffac09578f1dbbf | 8551b6afd5c01a6fb9ac2b34650b7c23c0b9215a | refs/heads/master | 2022-10-12T18:59:13.699041 | 2020-06-09T15:22:05 | 2020-06-09T15:22:05 | 35,908,238 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 109 | py | from __future__ import absolute_import
import os
mu2e_ext_path = os.path.expanduser('~/Coding/Mu2E_Extras/')
| [
"brianleepollack@gmail.com"
] | brianleepollack@gmail.com |
32add1e8f1a5f2ccfb0c98f10e0c108d20b4e0cd | ccbfc7818c0b75929a1dfae41dc061d5e0b78519 | /aliyun-openapi-python-sdk-master/aliyun-python-sdk-scdn/aliyunsdkscdn/request/v20171115/DescribeScdnRefreshQuotaRequest.py | 255f6a7086c110837108e34ca8358185fb0b8f9f | [
"Apache-2.0"
] | permissive | P79N6A/dysms_python | 44b634ffb2856b81d5f79f65889bfd5232a9b546 | f44877b35817e103eed469a637813efffa1be3e4 | refs/heads/master | 2020-04-28T15:25:00.368913 | 2019-03-13T07:52:34 | 2019-03-13T07:52:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,326 | py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from aliyunsdkcore.request import RpcRequest
class DescribeScdnRefreshQuotaRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'scdn', '2017-11-15', 'DescribeScdnRefreshQuota','scdn')
def get_SecurityToken(self):
return self.get_query_params().get('SecurityToken')
def set_SecurityToken(self,SecurityToken):
self.add_query_param('SecurityToken',SecurityToken)
def get_OwnerId(self):
return self.get_query_params().get('OwnerId')
def set_OwnerId(self,OwnerId):
self.add_query_param('OwnerId',OwnerId) | [
"1478458905@qq.com"
] | 1478458905@qq.com |
be0a6fb0d5da06a658cbb803dde555f11cb92df9 | bc441bb06b8948288f110af63feda4e798f30225 | /data_ops_analysis_sdk/model/inspection/metric_group_pb2.pyi | 11016ea24bf79dbc2a3001776ac332e255bbb812 | [
"Apache-2.0"
] | permissive | easyopsapis/easyops-api-python | 23204f8846a332c30f5f3ff627bf220940137b6b | adf6e3bad33fa6266b5fa0a449dd4ac42f8447d0 | refs/heads/master | 2020-06-26T23:38:27.308803 | 2020-06-16T07:25:41 | 2020-06-16T07:25:41 | 199,773,131 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,015 | pyi | # @generated by generate_proto_mypy_stubs.py. Do not edit!
import sys
from data_ops_analysis_sdk.model.inspection.dim_pb2 import (
InspectionDim as data_ops_analysis_sdk___model___inspection___dim_pb2___InspectionDim,
)
from data_ops_analysis_sdk.model.inspection.val_pb2 import (
InspectionVal as data_ops_analysis_sdk___model___inspection___val_pb2___InspectionVal,
)
from google.protobuf.descriptor import (
Descriptor as google___protobuf___descriptor___Descriptor,
)
from google.protobuf.internal.containers import (
RepeatedCompositeFieldContainer as google___protobuf___internal___containers___RepeatedCompositeFieldContainer,
)
from google.protobuf.message import (
Message as google___protobuf___message___Message,
)
from typing import (
Iterable as typing___Iterable,
Optional as typing___Optional,
Text as typing___Text,
Union as typing___Union,
)
from typing_extensions import (
Literal as typing_extensions___Literal,
)
builtin___bool = bool
builtin___bytes = bytes
builtin___float = float
builtin___int = int
if sys.version_info < (3,):
builtin___buffer = buffer
builtin___unicode = unicode
class InspectionMetricGroup(google___protobuf___message___Message):
DESCRIPTOR: google___protobuf___descriptor___Descriptor = ...
id = ... # type: typing___Text
name = ... # type: typing___Text
category = ... # type: typing___Text
memo = ... # type: typing___Text
@property
def dims(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[data_ops_analysis_sdk___model___inspection___dim_pb2___InspectionDim]: ...
@property
def vals(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[data_ops_analysis_sdk___model___inspection___val_pb2___InspectionVal]: ...
def __init__(self,
*,
id : typing___Optional[typing___Text] = None,
name : typing___Optional[typing___Text] = None,
category : typing___Optional[typing___Text] = None,
dims : typing___Optional[typing___Iterable[data_ops_analysis_sdk___model___inspection___dim_pb2___InspectionDim]] = None,
vals : typing___Optional[typing___Iterable[data_ops_analysis_sdk___model___inspection___val_pb2___InspectionVal]] = None,
memo : typing___Optional[typing___Text] = None,
) -> None: ...
if sys.version_info >= (3,):
@classmethod
def FromString(cls, s: builtin___bytes) -> InspectionMetricGroup: ...
else:
@classmethod
def FromString(cls, s: typing___Union[builtin___bytes, builtin___buffer, builtin___unicode]) -> InspectionMetricGroup: ...
def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ...
def CopyFrom(self, other_msg: google___protobuf___message___Message) -> None: ...
def ClearField(self, field_name: typing_extensions___Literal[u"category",b"category",u"dims",b"dims",u"id",b"id",u"memo",b"memo",u"name",b"name",u"vals",b"vals"]) -> None: ...
| [
"service@easyops.cn"
] | service@easyops.cn |
df441ecebb831006b1216e31a0f500c020819031 | 2dc17d12ff6ea9794177c81aa4f385e4e09a4aa5 | /archive/2201. Count Artifacts That Can Be Extracted.py | d7667b34133a848ec2001bd66bec971255732dc6 | [] | 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 | UTF-8 | Python | false | false | 448 | py | class Solution:
def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int:
d = {}
for i, a in enumerate(artifacts):
r1, c1, r2, c2 = a
for x in range(r1, r2 + 1):
for y in range(c1, c2 + 1):
d[x, y] = i
for x, y in dig:
if (x, y) in d:
del d[x, y]
return len(artifacts) - len(set(d.values()))
| [
"19241008o"
] | 19241008o |
9a7cc36dd437d76af94baa682c310578ed88e722 | 3b7c5454d22d843f21d58eaef724c08436f20c26 | /exp/exp074.py | 22f51f6351bb2dfcc7dc9c0ba021e34165920712 | [] | no_license | kurupical/shopee | a6c1a0fcf6f92b5f204ebab150bba7b906c5421a | ccc3f1ed631283d627074529ec1f302b02d0d10a | refs/heads/master | 2023-04-18T14:17:18.786699 | 2021-05-11T00:11:24 | 2021-05-11T00:11:24 | 354,429,650 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 20,955 | py | import torch
from torch import nn
from torch.nn import Parameter
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModel
from torch.utils.data import Dataset, DataLoader
from timm import create_model
import math
import cv2
import random
import os
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import KFold
from sklearn.neighbors import NearestNeighbors
from torch.optim.lr_scheduler import ReduceLROnPlateau, CosineAnnealingWarmRestarts, StepLR
from torch.optim import Adam, Optimizer, SGD
import albumentations
from albumentations.pytorch.transforms import ToTensorV2
import dataclasses
import tqdm
from datetime import datetime as dt
import matplotlib.pyplot as plt
import time
from transformers import AdamW, get_linear_schedule_with_warmup
from typing import Tuple, List, Any
"""
とりあえずこれベースに頑張って写経する
https://www.kaggle.com/tanulsingh077/pytorch-metric-learning-pipeline-only-images
https://www.kaggle.com/zzy990106/b0-bert-cv0-9
"""
EXPERIMENT_NAME = "distilbert+cnn"
DEBUG = False
def seed_torch(seed=42):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
def getMetric(col):
def f1score(row):
n = len( np.intersect1d(row.target,row[col]) )
return 2*n / (len(row.target)+len(row[col]))
return f1score
class FocalLoss(nn.Module):
def __init__(self, alpha=1, gamma=2, reduce=True):
super(FocalLoss, self).__init__()
self.alpha = alpha
self.gamma = gamma
self.reduce = reduce
def forward(self, inputs, targets):
BCE_loss = F.cross_entropy(inputs, targets, reduce=False)
pt = torch.exp(-BCE_loss)
F_loss = self.alpha * (1-pt)**self.gamma * BCE_loss
if self.reduce:
return torch.mean(F_loss)
else:
return F_loss
class AdaCos(nn.Module):
"""
https://github.com/4uiiurz1/pytorch-adacos/blob/master/metrics.py
"""
def __init__(self, in_features, out_features, m=0.50):
super(AdaCos, self).__init__()
self.num_features = in_features
self.n_classes = out_features
self.s = math.sqrt(2) * math.log(out_features - 1)
self.m = m
self.W = Parameter(torch.FloatTensor(out_features, in_features))
nn.init.xavier_uniform_(self.W)
def forward(self, input, label=None):
# normalize features
x = F.normalize(input)
# normalize weights
W = F.normalize(self.W)
# dot product
logits = F.linear(x, W)
if label is None:
return logits
# feature re-scale
theta = torch.acos(torch.clamp(logits, -1.0 + 1e-7, 1.0 - 1e-7))
one_hot = torch.zeros_like(logits)
one_hot.scatter_(1, label.view(-1, 1).long(), 1)
with torch.no_grad():
B_avg = torch.where(one_hot < 1, torch.exp(self.s * logits), torch.zeros_like(logits))
B_avg = torch.sum(B_avg) / input.size(0)
# print(B_avg)
theta_med = torch.median(theta[one_hot == 1])
self.s = torch.log(B_avg) / torch.cos(torch.min(math.pi/4 * torch.ones_like(theta_med), theta_med))
output = self.s * logits
return output
class ArcMarginProductSubcenter(nn.Module):
def __init__(self, in_features, out_features, k=3):
super().__init__()
self.weight = nn.Parameter(torch.FloatTensor(out_features * k, in_features))
self.reset_parameters()
self.k = k
self.out_features = out_features
def reset_parameters(self):
stdv = 1. / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
def forward(self, features, label=None):
cosine_all = F.linear(F.normalize(features), F.normalize(self.weight))
cosine_all = cosine_all.view(-1, self.out_features, self.k)
cosine, _ = torch.max(cosine_all, dim=2)
return cosine
class ArcMarginProduct(nn.Module):
r"""Implement of large margin arc distance: :
Args:
in_features: size of each input sample
out_features: size of each output sample
s: norm of input feature
m: margin
cos(theta + m)
"""
def __init__(self, in_features, out_features, s, m, easy_margin=False):
super(ArcMarginProduct, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.s = s
self.m = m
self.weight = Parameter(torch.FloatTensor(out_features, in_features))
nn.init.xavier_uniform_(self.weight)
self.easy_margin = easy_margin
self.cos_m = math.cos(m)
self.sin_m = math.sin(m)
self.th = math.cos(math.pi - m)
self.mm = math.sin(math.pi - m) * m
def forward(self, input, label):
# --------------------------- cos(theta) & phi(theta) ---------------------------
cosine = F.linear(F.normalize(input), F.normalize(self.weight))
sine = torch.sqrt((1.0 - torch.pow(cosine, 2)).clamp(0, 1))
phi = cosine * self.cos_m - sine * self.sin_m
if self.easy_margin:
phi = torch.where(cosine > 0, phi, cosine)
else:
phi = torch.where(cosine > self.th, phi, cosine - self.mm)
# --------------------------- convert label to one-hot ---------------------------
# one_hot = torch.zeros(cosine.size(), requires_grad=True, device='cuda')
one_hot = torch.zeros(cosine.size(), device='cuda')
one_hot.scatter_(1, label.view(-1, 1).long(), 1)
# -------------torch.where(out_i = {x_i if condition_i else y_i) -------------
output = (one_hot * phi) + ((1.0 - one_hot) * cosine) # you can use torch.where if your torch.__version__ is 0.4
output *= self.s
# print(output)
return output
class Swish(torch.autograd.Function):
@staticmethod
def forward(ctx, i):
result = i * torch.sigmoid(i)
ctx.save_for_backward(i)
return result
@staticmethod
def backward(ctx, grad_output):
i = ctx.saved_variables[0]
sigmoid_i = torch.sigmoid(i)
return grad_output * (sigmoid_i * (1 + i * (1 - sigmoid_i)))
class SwishModule(nn.Module):
def forward(self, x):
return Swish.apply(x)
@dataclasses.dataclass
class Config:
# model
linear_out: int = 512
dropout_nlp: float = 0.5
dropout_cnn: float = 0.5
dropout_bert_stack: float = 0.2
dropout_transformer: float = 0.2
dropout_cnn_fc: float = 0
model_name: str = "efficientnet_b3"
nlp_model_name: str = "bert-base-multilingual-uncased"
bert_agg: str = "mean"
# arcmargin
m: float = 0.5
s: float = 32
# dim
dim: Tuple[int, int] = (512, 512)
# optim
optimizer: Any = Adam
optimizer_params = {}
cnn_lr: float = 3e-4
bert_lr: float = 1e-5
fc_lr: float = 5e-4
transformer_lr: float = 1e-3
scheduler = ReduceLROnPlateau
scheduler_params = {"patience": 0, "factor": 0.1, "mode": "max"}
loss: Any = nn.CrossEntropyLoss
loss_params = {}
# training
batch_size: int = 16
num_workers: int = 2
if DEBUG:
epochs: int = 1
else:
epochs: int = 30
early_stop_round: int = 3
num_classes: int = 11014
# metric learning
metric_layer: Any = ArcMarginProduct
metric_layer_params = {
"s": 32,
"m": 0.5,
"in_features": linear_out,
"out_features": num_classes
}
# transformers
transformer_n_heads: int = 64
transformer_dropout: float = 0
transformer_num_layers: int = 1
# activation
activation: Any = None
# debug mode
debug: bool = DEBUG
gomi_score_threshold: float = 0
# transforms
train_transforms: Any = albumentations.Compose([
albumentations.HorizontalFlip(p=0.5),
albumentations.ImageCompression(quality_lower=99, quality_upper=100),
albumentations.ShiftScaleRotate(shift_limit=0.2, scale_limit=0.2, rotate_limit=10, border_mode=0, p=0.7),
albumentations.Resize(dim[0], dim[1]),
albumentations.Cutout(max_h_size=int(dim[0] * 0.4), max_w_size=int(dim[0] * 0.4), num_holes=1, p=0.5),
albumentations.Normalize(),
ToTensorV2(p=1.0),
])
val_transforms: Any = albumentations.Compose([
albumentations.Resize(dim[0], dim[1], always_apply=True),
albumentations.Normalize(),
ToTensorV2(p=1.0),
])
class BertModule(nn.Module):
def __init__(self,
bert,
config: Config):
super().__init__()
if bert is None:
self.bert = AutoModel.from_pretrained(config.nlp_model_name)
else:
self.bert = bert
self.config = config
self.dropout_nlp = nn.Dropout(config.dropout_nlp)
self.hidden_size = self.bert.config.hidden_size
self.bert_bn = nn.BatchNorm1d(self.hidden_size)
self.dropout_stack = nn.Dropout(config.dropout_bert_stack)
def forward(self, input_ids, attention_mask):
text = self.bert(input_ids=input_ids, attention_mask=attention_mask)[0].mean(dim=1)
text = self.bert_bn(text)
text = self.dropout_nlp(text)
return text
class ShopeeNet(nn.Module):
def __init__(self,
config: Config,
bert=None,
pretrained: bool = True):
super().__init__()
self.config = config
self.bert = BertModule(bert=bert,
config=config)
self.cnn = create_model(config.model_name,
pretrained=pretrained,
num_classes=0)
self.cnn_bn = nn.BatchNorm1d(self.cnn.num_features)
n_feat_concat = self.cnn.num_features + self.bert.hidden_size
self.fc = nn.Sequential(
nn.Linear(n_feat_concat, config.linear_out),
nn.BatchNorm1d(config.linear_out)
)
self.dropout_cnn = nn.Dropout(config.dropout_cnn)
self.final = config.metric_layer(**config.metric_layer_params)
def forward(self, X_image, input_ids, attention_mask, label=None):
x = self.cnn(X_image)
x = self.cnn_bn(x)
x = self.dropout_cnn(x)
text = self.bert(input_ids, attention_mask)
x = torch.cat([x, text], dim=1)
ret = self.fc(x)
if label is not None:
x = self.final(ret, label)
return x, ret
else:
return ret
class ShopeeDataset(Dataset):
def __init__(self, df, tokenizer, transforms=None):
self.df = df.reset_index()
self.augmentations = transforms
self.tokenizer = tokenizer
def __len__(self):
return self.df.shape[0]
def __getitem__(self, index):
row = self.df.iloc[index]
text = row.title
image = cv2.imread(row.filepath)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
text = self.tokenizer(text, padding="max_length", max_length=128, truncation=True, return_tensors="pt")
input_ids = text["input_ids"][0]
attention_mask = text["attention_mask"][0]
if self.augmentations:
augmented = self.augmentations(image=image)
image = augmented['image']
return image, input_ids, attention_mask, torch.tensor(row.label_group)
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def train_fn(dataloader, model, criterion, optimizer, device, scheduler, epoch):
import mlflow
model.train()
loss_score = AverageMeter()
tk0 = tqdm.tqdm(enumerate(dataloader), total=len(dataloader))
for bi, d in tk0:
batch_size = d[0].shape[0]
images = d[0].to(device)
input_ids = d[1].to(device)
attention_mask = d[2].to(device)
targets = d[3].to(device)
optimizer.zero_grad()
output, _ = model(images, input_ids, attention_mask, targets)
loss = criterion(output, targets)
loss.backward()
optimizer.step()
loss_score.update(loss.detach().item(), batch_size)
tk0.set_postfix(Train_Loss=loss_score.avg, Epoch=epoch, LR=optimizer.param_groups[0]['lr'])
if scheduler.__class__ != ReduceLROnPlateau:
scheduler.step()
# if not DEBUG:
# mlflow.log_metric("train_loss", loss.detach().item())
return loss_score
def eval_fn(data_loader, model, criterion, device, df_val, epoch, output_dir):
loss_score = AverageMeter()
model.eval()
tk0 = tqdm.tqdm(enumerate(data_loader), total=len(data_loader))
all_features = []
all_targets = []
with torch.no_grad():
for bi, d in tk0:
batch_size = d[0].size()[0]
images = d[0].to(device)
input_ids = d[1].to(device)
attention_mask = d[2].to(device)
targets = d[3].to(device)
output, feature = model(images, input_ids, attention_mask, targets)
loss = criterion(output, targets)
loss_score.update(loss.detach().item(), batch_size)
tk0.set_postfix(Eval_Loss=loss_score.avg)
all_features.extend(feature.detach().cpu().numpy())
all_targets.extend(targets.detach().cpu().numpy())
all_features = np.array(all_features, dtype=np.float32)
best_score, best_th, df_best = get_best_neighbors(df=df_val,
embeddings=all_features,
epoch=epoch,
output_dir=output_dir)
return loss_score, best_score, best_th, df_best
def get_cv(df):
tmp = df.groupby('label_group').posting_id.agg('unique').to_dict()
df['target'] = df.label_group.map(tmp)
df['f1'] = df.apply(getMetric('pred'), axis=1)
return df.f1.mean()
def get_best_neighbors(embeddings, df, epoch, output_dir):
model = NearestNeighbors(n_neighbors=len(df), n_jobs=32)
model.fit(embeddings)
distances, indices = model.kneighbors(embeddings)
print("threshold search")
best_th = 0
best_score = 0
plt.hist(distances[:100].flatten(), bins=200)
plt.savefig(f"{dt.now().strftime('%Y%m%d%H%M%S')}.jpg")
plt.clf()
posting_ids = np.array(df["posting_id"].values.tolist())
distances = np.array(distances, dtype=np.float16)
np.save(f"{output_dir}/embeddings_epoch{epoch}.npy", embeddings)
np.save(f"{output_dir}/distances_epoch{epoch}.npy", distances)
np.save(f"{output_dir}/indices_epoch{epoch}.npy", indices)
for th in np.arange(10, 22, 0.5).tolist():
preds = []
for i in range(len(distances)):
IDX = np.where(distances[i,] < th)[0]
ids = indices[i, IDX]
o = posting_ids[ids]
preds.append(o)
df["pred"] = preds
score = get_cv(df)
if best_score < score:
best_th = th
best_score = score
df_best = df.copy()
print("th={:.4f} , score={:.4f}".format(th, score))
return best_score, best_th, df_best
def main(config, fold=0):
import mlflow
mlflow.set_tracking_uri("http://34.121.203.133:5000") # kiccho_san mlflow
try:
seed_torch(19900222)
output_dir = f"output/{os.path.basename(__file__)[:-3]}/{dt.now().strftime('%Y%m%d%H%M%S')}"
os.makedirs(output_dir)
# scheduler = CosineAnnealingWarmRestarts(optimizer, T_0=T_0, T_mult=1, eta_min=min_lr, last_epoch=-1)
df = pd.read_csv("input/shopee-product-matching/train_fold.csv")
df["title"] = [x.lower() for x in df["title"].values]
df["filepath"] = df['image'].apply(lambda x: os.path.join('input/shopee-product-matching/', 'train_images', x))
label_encoder = LabelEncoder()
df["label_group"] = label_encoder.fit_transform(df["label_group"].values)
if config.debug:
df = df.iloc[:100]
tokenizer = AutoTokenizer.from_pretrained(config.nlp_model_name)
if DEBUG:
df = df.iloc[:100]
if not DEBUG:
mlflow.start_run(experiment_id=7,
run_name=EXPERIMENT_NAME)
for key, value in config.__dict__.items():
mlflow.log_param(key, value)
mlflow.log_param("fold", fold)
df_train = df[df["fold"] != fold]
df_val = df[df["fold"] == fold]
# df_train = df[df["label_group"] % 5 != 0]
# df_val = df[df["label_group"] % 5 == 0]
train_dataset = ShopeeDataset(df=df_train,
transforms=config.train_transforms,
tokenizer=tokenizer)
val_dataset = ShopeeDataset(df=df_val,
transforms=config.val_transforms,
tokenizer=tokenizer)
train_loader = torch.utils.data.DataLoader(
train_dataset,
batch_size=config.batch_size,
shuffle=True,
pin_memory=True,
drop_last=True,
num_workers=config.num_workers
)
val_loader = torch.utils.data.DataLoader(
val_dataset,
batch_size=config.batch_size,
num_workers=config.num_workers,
shuffle=False,
pin_memory=True,
drop_last=False,
)
device = torch.device("cuda")
model = ShopeeNet(config=config)
model.to("cuda")
optimizer = config.optimizer(params=[{"params": model.bert.parameters(), "lr": config.bert_lr},
{"params": model.cnn.parameters(), "lr": config.cnn_lr},
{"params": model.cnn_bn.parameters(), "lr": config.cnn_lr},
{"params": model.fc.parameters(), "lr": config.fc_lr},
{"params": model.final.parameters(), "lr": config.fc_lr}])
scheduler = config.scheduler(optimizer, **config.scheduler_params)
criterion = config.loss(**config.loss_params)
best_score = 0
not_improved_epochs = 0
for epoch in range(config.epochs):
train_loss = train_fn(train_loader, model, criterion, optimizer, device, scheduler=scheduler, epoch=epoch)
valid_loss, score, best_threshold, df_best = eval_fn(val_loader, model, criterion, device, df_val, epoch, output_dir)
scheduler.step(score)
print(f"CV: {score}")
if score > best_score:
print('best model found for epoch {}, {:.4f} -> {:.4f}'.format(epoch, best_score, score))
best_score = score
torch.save(model.state_dict(), f'{output_dir}/best_fold{fold}.pth')
not_improved_epochs = 0
if not DEBUG:
mlflow.log_metric("val_best_cv_score", score)
df_best.to_csv(f"{output_dir}/df_val_fold{fold}.csv", index=False)
else:
not_improved_epochs += 1
print('{:.4f} is not improved from {:.4f} epoch {} / {}'.format(score, best_score, not_improved_epochs, config.early_stop_round))
if not_improved_epochs >= config.early_stop_round:
print("finish training.")
break
if best_score < config.gomi_score_threshold:
print("finish training(スコアダメなので打ち切り).")
break
if not DEBUG:
mlflow.log_metric("val_loss", valid_loss.avg)
mlflow.log_metric("val_cv_score", score)
mlflow.log_metric("val_best_threshold", best_threshold)
if not DEBUG:
mlflow.end_run()
except Exception as e:
print(e)
if not DEBUG:
mlflow.end_run()
def main_process():
nlp_model = "cahya/distilbert-base-indonesian"
cfg = Config()
cfg.s = 48
cfg.nlp_model_name = nlp_model
main(cfg)
for cnn_model in ["dm_nfnet_f3",
"tf_efficientnet_b3_ns",
"eca_nfnet_l1",
"seresnext50_32x4d",
"tf_efficientnet_b4_ns"]:
cfg = Config()
cfg.nlp_model_name = nlp_model
cfg.model_name = cnn_model
main(cfg)
if __name__ == "__main__":
main_process()
| [
"kurupical@gmail.com"
] | kurupical@gmail.com |
0a9868f457eb1aa068c047e33bbec3e8c024ff98 | 26d5c795d8aa83bf5cb3f228675ff51e2f704f57 | /tests/testbed_datastores.py | f87d239f1e36a2101a4c9c72df6982ffb0a085e3 | [] | no_license | binarymachines/mercury | 8e13bb10c67a056fe88e02f558d73f1f1b95d028 | db3e2425f4e77a44a97c740f7fff90312a1bd33f | refs/heads/master | 2023-07-08T11:35:26.867494 | 2023-06-25T00:46:23 | 2023-06-25T00:46:23 | 94,708,610 | 2 | 6 | null | 2023-02-15T21:50:06 | 2017-06-18T19:31:50 | Python | UTF-8 | Python | false | false | 701 | py | #!/usr/bin/env python
from mercury import datamap as dmap
from mercury.dataload import DataStore, DataStoreRegistry, RecordBuffer, checkpoint
class TestDatastore(DataStore):
def __init__(self, service_object_registry, *channels, **kwargs):
super.__init__(service_object_registry, *channels, **kwargs)
self.init_values = kwargs
self.num_bulk_writes = 0
self.num_record_writes = 0
@property
def init_param_fields(self):
return [ key for key, value in self.init_values.items()]
def _write(self, recordset, **kwargs):
for record in recordset:
self.num_record_writes += 1
self.num_bulk_writes += 1
| [
"binarymachineshop@gmail.com"
] | binarymachineshop@gmail.com |
e962c04487db5b0daafe715ec6e115ccd8014031 | 9da8754002fa402ad8e6f25659978bd269bbcec8 | /src/139B/cdf_139B.py | a343873acece54f65ada08084ba5a15efaecf9d8 | [
"MIT"
] | permissive | kopok2/CodeforcesSolutionsPython | a00f706dbf368ba0846c8ae86d4145b5dd3e1613 | 35bec0dbcff47765b123b5fe60476014376153df | refs/heads/master | 2023-02-02T03:08:22.097651 | 2020-12-17T22:00:50 | 2020-12-17T22:00:50 | 196,035,812 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,154 | py | import math
class CodeforcesTask139BSolution:
def __init__(self):
self.result = ''
self.n = 0
self.walls = []
self.m = 0
self.papers = []
def read_input(self):
self.n = int(input())
for x in range(self.n):
self.walls.append([int(y) for y in input().split(" ")])
self.m = int(input())
for x in range(self.m):
self.papers.append([int(y) for y in input().split(" ")])
def process_task(self):
tot_cost = 0
mx = 500 ** 4 + 1
for wall in self.walls:
mn = mx
cov = wall[0] * 2 + wall[1] * 2
for paper in self.papers:
paper_cov = paper[1] * (paper[0] // wall[2])
if paper_cov:
cost = math.ceil(cov / paper_cov) * paper[2]
mn = min(mn, cost)
tot_cost += mn
self.result = str(tot_cost)
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask139BSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
| [
"oleszek.karol@gmail.com"
] | oleszek.karol@gmail.com |
d94e85b910aeaff80552f9e68d32a295d877586b | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /RWLWKmGcbp6drWgKB_23.py | 5adf0badb29c6006de4951b4c8c6af9fb7c7a1cc | [] | no_license | daniel-reich/turbo-robot | feda6c0523bb83ab8954b6d06302bfec5b16ebdf | a7a25c63097674c0a81675eed7e6b763785f1c41 | refs/heads/main | 2023-03-26T01:55:14.210264 | 2021-03-23T16:08:01 | 2021-03-23T16:08:01 | 350,773,815 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,221 | py | """
Atticus has been invited to a dinner party, and he decides to purchase a
bottle of wine. However, he has little knowledge of how to choose a good
bottle. Being a very frugal gentleman (yet disliking looking like a
cheapskate), he decides to use a very simple rule. In any selection of **two
or more wines** , he will always buy the second-cheapest.
Given a list of wine dictionaries, write a function that returns the name of
the wine he will buy for the party. If given an empty list, return `None`. If
given a list of only one, Atticus will buy that wine.
### Examples
chosen_wine([
{ "name": "Wine A", "price": 8.99 },
{ "name": "Wine 32", "price": 13.99 },
{ "name": "Wine 9", "price": 10.99 }
]) ➞ "Wine 9"
chosen_wine([{ "name": "Wine A", "price": 8.99 }]) ➞ "Wine A"
chosen_wine([]) ➞ None
### Notes
All wines will be different prices, so there is no confusion in the ordering.
"""
def chosen_wine(wines):
dic = {}
for wine in wines:
dic[wine['name']] = wine['price']
l = sorted(dic.values())
if len(l) == 0: return None
else:
if len(l) == 1: x = l[0]
if len(l) > 1: x = l[1]
for k,v in dic.items():
if v == x: return k
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
f36133a4d7d2cfe78a2cafdf8ab04ec0448e18cb | 338062cc2bb422f1364fd18ad5e721f6f713907a | /9. Множества/Дополнительные задачи/Рецепты.py | 6d1a81604e9eded44d45203a89486040ea0ef914 | [] | no_license | rady1337/FirstYandexLyceumCourse | f3421d5eac7e7fbea4f5e266ebeb6479b89941cf | 0d27e452eda046ddd487d6471eeb7d9eb475bd39 | refs/heads/master | 2022-06-17T03:07:51.017888 | 2020-05-12T22:17:34 | 2020-05-12T22:17:34 | 263,459,364 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 345 | py | n = int(input())
holod = set()
eat = set()
for i in range(n):
holod.add(input())
n1 = int(input())
for i in range(n1):
recept = input()
n2 = int(input())
e = 1
for j in range(n2):
eat.add(input())
for i in eat:
if i not in holod:
e = 0
if e == 1:
print(recept)
eat = set()
| [
"noreply@github.com"
] | rady1337.noreply@github.com |
8d7a781bfef3a52b7a074199f5ca4714b0e6c872 | 72f6f274a9e4937f99e61eebe14f9b2f301a83f5 | /utils/vocab.py | 377f7baad879bb3d432bda34d57e6de391eff6af | [] | no_license | studio-ousia/textent | e466f8ef4f6910a0f4270014fa29c18aa5f329e0 | 2a73ef2f6a0d29d4d1c1085a75fa0b7592bdd376 | refs/heads/master | 2021-03-22T04:45:57.582737 | 2018-06-03T07:18:28 | 2018-06-03T07:18:28 | 93,811,887 | 20 | 4 | null | null | null | null | UTF-8 | Python | false | false | 3,790 | py | # -*- coding: utf-8 -*-
import joblib
import logging
from collections import Counter
from marisa_trie import Trie
from tokenizer import RegexpTokenizer
logger = logging.getLogger(__name__)
class Vocab(object):
def __init__(self, dic, start_index=0):
if isinstance(dic, Trie):
self._dic = dic
else:
self._dic = Trie(dic)
self._start_index = start_index
@property
def size(self):
return len(self)
def __len__(self):
return len(self._dic)
def __iter__(self):
return iter(self._dic)
def __contains__(self, key):
return key in self._dic
def get_index(self, key, default=None):
try:
return self._dic.key_id(key) + self._start_index
except KeyError:
return default
def get_key_by_index(self, index):
return self._dic.restore_key(index - self._start_index)
def save(self, out_file):
joblib.dump(self.serialize(), out_file)
def serialize(self):
return dict(dic=self._dic.tobytes(), start_index=self._start_index)
class WordVocab(Vocab):
def __init__(self, dic, lowercase, start_index=0):
super(WordVocab, self).__init__(dic, start_index)
self._lowercase = lowercase
def __contains__(self, word):
if self._lowercase:
word = word.lower()
return word in self._dic
def get_index(self, word, default=None):
if self._lowercase:
word = word.lower()
return super(WordVocab, self).get_index(word, default)
@staticmethod
def build(description_db, start_index, min_count, lowercase, target_vocab=None):
counter = Counter()
tokenizer = RegexpTokenizer()
for (title, text, _) in description_db.iterator():
if target_vocab is not None and title not in target_vocab:
continue
if lowercase:
counter.update([t.text.lower() for t in tokenizer.tokenize(text)])
else:
counter.update([t.text for t in tokenizer.tokenize(text)])
dic = Trie([w for (w, c) in counter.iteritems() if c >= min_count])
return WordVocab(dic, lowercase, start_index)
def save(self, out_file):
joblib.dump(self.serialize(), out_file)
def serialize(self):
return dict(dic=self._dic.tobytes(), lowercase=self._lowercase,
start_index=self._start_index)
@staticmethod
def load(input):
if isinstance(input, dict):
obj = input
else:
obj = joblib.load(input)
dic = Trie()
dic.frombytes(obj['dic'])
return WordVocab(dic, obj['lowercase'], obj.get('start_index', 0))
class EntityVocab(Vocab):
@staticmethod
def build(description_db, entity_db, white_list, start_index, min_inlink_count,
target_vocab=None):
counter = Counter()
db_titles = set()
for (title, _, titles) in description_db.iterator():
if target_vocab is not None and title not in target_vocab:
continue
counter.update(titles)
db_titles.add(title)
title_list = [t for (t, c) in counter.iteritems() if c >= min_inlink_count]
white_list = [entity_db.resolve_redirect(t) for t in white_list]
white_list = [t for t in white_list if t in db_titles]
title_list = set(title_list + white_list)
return EntityVocab(Trie(title_list), start_index)
@staticmethod
def load(input):
if isinstance(input, dict):
obj = input
else:
obj = joblib.load(input)
dic = Trie()
dic.frombytes(obj['dic'])
return EntityVocab(dic, obj.get('start_index', 0))
| [
"ikuya@ikuya.net"
] | ikuya@ikuya.net |
22d67d10e3a2619ee32e9c5fb94ba908b3227b6d | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Extras/Maya_AnimationRiggingTools/MayaTools/General/Scripts/customMayaMenu.py | 7768a652218d6360937c0bedd93b7f60b33589c3 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | Python | false | false | 24,510 | py | import maya.cmds as cmds
import maya.mel as mel
import os, cPickle
from functools import partial
def customMayaMenu():
gMainWindow = mel.eval('$temp1=$gMainWindow')
menus = cmds.window(gMainWindow, q = True, menuArray = True)
found = False
for menu in menus:
label = cmds.menu(menu, q = True, label = True)
if label == "Epic Games":
found = True
if found == False:
customMenu = cmds.menu(parent=gMainWindow, label = 'Epic Games')
#tools path
toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt"
if os.path.exists(toolsPath):
f = open(toolsPath, 'r')
mayaToolsDir = f.readline()
f.close()
#ART
cmds.menuItem(parent = customMenu, label = "Animation Rigging Toolset", bld = True, enable = False)
cmds.menuItem(parent = customMenu, divider = True)
cmds.menuItem(parent = customMenu, label = "Character Rig Creator", c = launchSkeletonBuilder)
cmds.menuItem(parent = customMenu, label = "Edit Existing Character", c = editCharacter)
cmds.menuItem(parent = customMenu, label = "Add Character For Animation", c = launchAddCharacter)
cmds.menuItem(parent = customMenu, label = "Animation Interface", c = launchAnimUI)
cmds.menuItem(parent = customMenu, label = "Settings", c = launchARTSettings)
artHelp = cmds.menuItem(parent = customMenu, label = "Help", subMenu=True)
cmds.menuItem(parent = artHelp, label = "Learning Videos", c = launchLearningVideos)
cmds.menuItem(parent = artHelp, label = "Help Documentation", c = launchRigHelp)
cmds.menuItem(parent = artHelp, label = "About", c = aboutARTTools)
cmds.menuItem(parent = customMenu, divider = True)
cmds.menuItem(parent = customMenu, label = "Misc. Tools", bld = True, enable = False)
cmds.menuItem(parent = customMenu, divider = True)
#PERFORCE
p4Menu = cmds.menuItem(parent = customMenu, label = "Perforce", subMenu=True, to = True)
cmds.menuItem("perforceSubmitMenuItem", parent = p4Menu, label = "Submit Current File", enable = False, c = p4Submit)
cmds.menuItem("perforceAddAndSubmitMenuItem", parent = p4Menu, label = "Add and Submit Current File", enable = False, c = p4AddSubmit)
cmds.menuItem("perforceCheckOutMenuItem", parent = p4Menu, label = "Check Out Current File", enable = False, c = p4CheckOut)
cmds.menuItem("perforceFileHistoryMenuItem", parent = p4Menu, label = "Current File History", enable = False, c = p4GetHistory)
cmds.menuItem("perforceGetLatestMenuItem", parent = p4Menu, label = "Get Latest Revision of Current File", enable = False, c = p4GetLatest)
cmds.menuItem("perforceProjectList", parent = p4Menu, label = "Set Project", enable = False, subMenu = True)
cmds.menuItem("perforceProject_New", parent = "perforceProjectList", label = "New Project", c = createNewProj)
cmds.radioMenuItemCollection("perforceProjectRadioMenuCollection", parent = "perforceProjectList")
cmds.menuItem(parent = customMenu, divider = True)
#check settings to see if use source control is turned on
toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt"
if os.path.exists(toolsPath):
f = open(toolsPath, 'r')
mayaToolsDir = f.readline()
f.close()
settingsLocation = mayaToolsDir + "/General/Scripts/projectSettings.txt"
if os.path.exists(settingsLocation):
f = open(settingsLocation, 'r')
settings = cPickle.load(f)
f.close()
#find use source control value
sourceControl = settings.get("UseSourceControl")
if sourceControl:
cmds.menuItem("perforceSubmitMenuItem", edit = True, enable = True)
cmds.menuItem("perforceAddAndSubmitMenuItem", edit = True, enable = True)
cmds.menuItem("perforceCheckOutMenuItem", edit = True, enable = True)
cmds.menuItem("perforceFileHistoryMenuItem", edit = True, enable = True)
cmds.menuItem("perforceGetLatestMenuItem", edit = True, enable = True)
cmds.menuItem("perforceProjectList", edit = True, enable = True)
#launch script job for checking Maya Tools
cmds.scriptJob(event = ["NewSceneOpened", autoUpdateTools])
#############################################################################################
#############################################################################################
#############################################################################################
def p4ProjectMenu(*args):
#clear any projects that are in the collection first
items = cmds.lsUI(menuItems = True)
for i in items:
data = cmds.menuItem(i, q = True, docTag = True)
if data == "P4Proj":
cmds.deleteUI(i)
#find projects
toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt"
if os.path.exists(toolsPath):
f = open(toolsPath, 'r')
mayaToolsDir = f.readline()
f.close()
projects = os.listdir(mayaToolsDir + "/General/Scripts/")
p4Projects = []
#Test_Project_Settings
for proj in projects:
if proj.rpartition(".")[2] == "txt":
if proj.partition("_")[2].partition("_")[0] == "Project":
p4Projects.append(proj)
#set the current project
try:
f = open(mayaToolsDir + "/General/Scripts/projectSettings.txt", 'r')
settings = cPickle.load(f)
f.close()
currentProj = settings.get("CurrentProject")
except:
pass
#add the projects to the menu
for proj in p4Projects:
projectName = proj.partition("_")[0]
if projectName == currentProj:
val = True
else:
val = False
menuItem = cmds.menuItem(label = projectName, parent = "perforceProjectList", cl = "perforceProjectRadioMenuCollection", rb = val, docTag = "P4Proj", c = partial(setProj, projectName))
cmds.menuItem(parent = "perforceProjectList", optionBox = True, c = partial(editProj, projectName))
#############################################################################################
#############################################################################################
#############################################################################################
def setProj(projectName, *args):
import perforceUtils
reload(perforceUtils)
perforceUtils.setCurrentProject(projectName)
#############################################################################################
#############################################################################################
#############################################################################################
def editProj(projectName, *args):
import perforceUtils
reload(perforceUtils)
perforceUtils.editProject(projectName)
#############################################################################################
#############################################################################################
#############################################################################################
def createNewProj(*args):
import perforceUtils
reload(perforceUtils)
perforceUtils.createNewProject()
#############################################################################################
#############################################################################################
#############################################################################################
def autoUpdateTools(*args):
import perforceUtils
reload(perforceUtils)
perforceUtils.p4_checkForUpdates()
#############################################################################################
#############################################################################################
#############################################################################################
def launchARTSettings(*args):
import ART_Settings
reload(ART_Settings)
ART_Settings.ART_Settings()
#############################################################################################
#############################################################################################
#############################################################################################
def aboutARTTools(*args):
cmds.confirmDialog(title = "About", message = "Copyright 2013-2017 Epic Games, Inc.\nCreated by: Jeremy Ernst\njeremy.ernst@epicgames.com\nVisit www.epicgames.com", icon = "information")
#############################################################################################
#############################################################################################
#############################################################################################
def editCharacter(*args):
if cmds.window("artEditCharacterUI", exists = True):
cmds.deleteUI("artEditCharacterUI")
window = cmds.window("artEditCharacterUI", w = 300, h = 400, title = "Edit Character", mxb = False, mnb = False, sizeable = False)
mainLayout = cmds.columnLayout(w = 300, h = 400, rs = 5, co = ["both", 5])
#banner image
toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt"
if os.path.exists(toolsPath):
f = open(toolsPath, 'r')
mayaToolsDir = f.readline()
f.close()
cmds.image(w = 300, h = 50, image = mayaToolsDir + "/General/Icons/ART/artBanner300px.bmp", parent = mainLayout)
cmds.text(label = "", h = 1, parent = mainLayout)
optionMenu = cmds.optionMenu("artProjOptionMenu", label = "Project:", w =290, h = 40, cc = getProjCharacters, parent = mainLayout)
textScrollList = cmds.textScrollList("artProjCharacterList", w = 290, h = 300, parent = mainLayout)
button = cmds.button(w = 290, h = 40, label = "Edit Export File", c = editSelectedCharacter, ann = "Edit the character's skeleton settings, joint positions, or skin weights.", parent = mainLayout)
button2 = cmds.button(w = 290, h = 40, label = "Edit Rig File", c = editSelectedCharacterRig, ann = "Edit the character's control rig that will be referenced in by animation.", parent = mainLayout)
cmds.text(label = "", h = 1)
cmds.showWindow(window)
getProjects()
getProjCharacters()
#############################################################################################
#############################################################################################
#############################################################################################
def getProjects(*args):
toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt"
if os.path.exists(toolsPath):
f = open(toolsPath, 'r')
mayaToolsDir = f.readline()
f.close()
projects = os.listdir(mayaToolsDir + "/General/ART/Projects/")
for project in projects:
cmds.menuItem(label = project, parent = "artProjOptionMenu")
#############################################################################################
#############################################################################################
#############################################################################################
def getProjCharacters(*args):
toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt"
if os.path.exists(toolsPath):
f = open(toolsPath, 'r')
mayaToolsDir = f.readline()
f.close()
proj = cmds.optionMenu("artProjOptionMenu", q = True, value = True)
cmds.textScrollList("artProjCharacterList", edit = True, removeAll = True)
characters = os.listdir(mayaToolsDir + "/General/ART/Projects/" + proj + "/ExportFiles/")
for character in characters:
if os.path.isfile(mayaToolsDir + "/General/ART/Projects/" + proj + "/ExportFiles/" + character):
if character.rpartition(".")[2] == "mb":
niceName = character.rpartition(".")[0]
niceName = niceName.partition("_Export")[0]
cmds.textScrollList("artProjCharacterList", edit = True, append = niceName)
#############################################################################################
#############################################################################################
#############################################################################################
def editSelectedCharacter(*args):
toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt"
if os.path.exists(toolsPath):
f = open(toolsPath, 'r')
mayaToolsDir = f.readline()
f.close()
proj = cmds.optionMenu("artProjOptionMenu", q = True, value = True)
character = cmds.textScrollList("artProjCharacterList", q = True, si = True)[0]
cmds.file(mayaToolsDir + "/General/ART/Projects/" + proj + "/ExportFiles/" + character + "_Export.mb", open = True, force = True)
cmds.deleteUI("artEditCharacterUI")
launchSkeletonBuilder()
#############################################################################################
#############################################################################################
#############################################################################################
def editSelectedCharacterRig(*args):
toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt"
if os.path.exists(toolsPath):
f = open(toolsPath, 'r')
mayaToolsDir = f.readline()
f.close()
proj = cmds.optionMenu("artProjOptionMenu", q = True, value = True)
character = cmds.textScrollList("artProjCharacterList", q = True, si = True)[0]
cmds.file(mayaToolsDir + "/General/ART/Projects/" + proj + "/AnimRigs/" + character + ".mb", open = True, force = True)
cmds.deleteUI("artEditCharacterUI")
launchSkeletonBuilder()
#############################################################################################
#############################################################################################
#############################################################################################
def changeMayaToolsLoc(*args):
path = cmds.internalVar(usd = True) + "mayaTools.txt"
if os.path.exists(path):
os.remove(path)
cmds.confirmDialog(title = "Change Location", message = "Once you have chosen your new tools location, it is recommended that you restart Maya.", button = "OK")
cmds.file(new = True, force = True)
#############################################################################################
#############################################################################################
#############################################################################################
def launchSkeletonBuilder(*args):
import ART_skeletonBuilder_UI
reload(ART_skeletonBuilder_UI)
UI = ART_skeletonBuilder_UI.SkeletonBuilder_UI()
#############################################################################################
#############################################################################################
#############################################################################################
def launchAddCharacter(*args):
import ART_addCharacter_UI
reload(ART_addCharacter_UI)
UI = ART_addCharacter_UI.AddCharacter_UI()
#############################################################################################
#############################################################################################
#############################################################################################
def launchAnimUI(*args):
import ART_animationUI
reload(ART_animationUI)
UI = ART_animationUI.AnimationUI()
#############################################################################################
#############################################################################################
#############################################################################################
def launchEpic(*args):
cmds.launch(web="http://www.epicgames.com")
#############################################################################################
#############################################################################################
#############################################################################################
def launchUnreal(*args):
cmds.launch(web="http://www.unrealengine.com")
#############################################################################################
#############################################################################################
#############################################################################################
def launchAnimHelp(*args):
toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt"
if os.path.exists(toolsPath):
f = open(toolsPath, 'r')
mayaToolsDir = f.readline()
f.close()
if os.path.exists(mayaToolsDir + "/General/ART/Help/ART_AnimHelp.pdf"):
cmds.launch(pdfFile = mayaToolsDir + "/General/ART/Help/ART_AnimHelp.pdf")
#############################################################################################
#############################################################################################
#############################################################################################
def launchRigHelp(self, *args):
cmds.launch(web = "https://docs.unrealengine.com/latest/INT/Engine/Content/Tools/MayaRiggingTool/index.html")
#############################################################################################
#############################################################################################
#############################################################################################
def launchLearningVideos(self, *args):
import ART_Help
reload(ART_Help)
ART_Help.ART_LearningVideos()
#############################################################################################
#############################################################################################
#############################################################################################
def setupScene(*args):
cmds.currentUnit(time = 'ntsc')
cmds.playbackOptions(min = 0, max = 100, animationStartTime = 0, animationEndTime = 100)
cmds.currentTime(0)
#check for skeleton builder or animation UIs
if cmds.dockControl("skeletonBuilder_dock", exists = True):
print "Custom Maya Menu: SetupScene"
channelBox = cmds.formLayout("SkelBuilder_channelBoxFormLayout", q = True, childArray = True)
if channelBox != None:
channelBox = channelBox[0]
#reparent the channelBox Layout back to maya's window
cmds.control(channelBox, e = True, p = "MainChannelsLayersLayout")
channelBoxLayout = mel.eval('$temp1=$gChannelsLayersForm')
channelBoxForm = mel.eval('$temp1 = $gChannelButtonForm')
#edit the channel box pane's attachment to the formLayout
cmds.formLayout(channelBoxLayout, edit = True, af = [(channelBox, "left", 0),(channelBox, "right", 0), (channelBox, "bottom", 0)], attachControl = (channelBox, "top", 0, channelBoxForm))
#print "deleting dock and window and shit"
cmds.deleteUI("skeletonBuilder_dock")
if cmds.window("SkelBuilder_window", exists = True):
cmds.deleteUI("SkelBuilder_window")
if cmds.dockControl("artAnimUIDock", exists = True):
channelBox = cmds.formLayout("ART_cbFormLayout", q = True, childArray = True)
if channelBox != None:
channelBox = channelBox[0]
#reparent the channelBox Layout back to maya's window
cmds.control(channelBox, e = True, p = "MainChannelsLayersLayout")
channelBoxLayout = mel.eval('$temp1=$gChannelsLayersForm')
channelBoxForm = mel.eval('$temp1 = $gChannelButtonForm')
#edit the channel box pane's attachment to the formLayout
cmds.formLayout(channelBoxLayout, edit = True, af = [(channelBox, "left", 0),(channelBox, "right", 0), (channelBox, "bottom", 0)], attachControl = (channelBox, "top", 0, channelBoxForm))
#print "deleting dock and window and shit"
cmds.deleteUI("artAnimUIDock")
if cmds.window("artAnimUI", exists = True):
cmds.deleteUI("artAnimUI")
#############################################################################################
#############################################################################################
#############################################################################################
def autoOpenAnimUI():
if cmds.objExists("*:master_anim_space_switcher_follow"):
launchAnimUI()
#############################################################################################
#############################################################################################
#############################################################################################
def p4GetLatest(*args):
import perforceUtils
reload(perforceUtils)
perforceUtils.p4_getLatestRevision(None)
#############################################################################################
#############################################################################################
#############################################################################################
def p4CheckOut(*args):
import perforceUtils
reload(perforceUtils)
perforceUtils.p4_checkOutCurrentFile(None)
#############################################################################################
#############################################################################################
#############################################################################################
def p4GetHistory(*args):
import perforceUtils
reload(perforceUtils)
perforceUtils.p4_getRevisionHistory()
#############################################################################################
#############################################################################################
#############################################################################################
def p4Submit(*args):
import perforceUtils
reload(perforceUtils)
perforceUtils.p4_submitCurrentFile(None, None)
#############################################################################################
#############################################################################################
#############################################################################################
def p4AddSubmit(*args):
import perforceUtils
reload(perforceUtils)
perforceUtils.p4_addAndSubmitCurrentFile(None, None)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#LAUNCH SCRIPT JOBS
scriptJobNum2 = cmds.scriptJob(event = ["PostSceneRead", autoOpenAnimUI])
scriptJobNum = cmds.scriptJob(event = ["NewSceneOpened", setupScene])
p4ScriptJob = cmds.scriptJob(event = ["NewSceneOpened", p4ProjectMenu])
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
236d1bfb3fea28dc75f25ad86df9ae345d5ab611 | 8b060d38c63993a3259a80b072768206b558772b | /BlogApp/migrations/0002_article_article_text.py | d99bdd629d6dc36f5b7359e87521a9f2e0f14e77 | [] | no_license | mortadagzar/Simple-Python-feedingTable | d8b0a2a06c1b3d78167241a6f60a2bb00fa9c4ce | 716c68e6b9c55bd2dc8299ca14ccf39431cf0efb | refs/heads/master | 2020-03-30T19:07:16.027807 | 2018-10-14T15:05:28 | 2018-10-14T15:05:28 | 151,529,016 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 388 | py | # Generated by Django 2.1.1 on 2018-09-22 10:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('BlogApp', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='article',
name='article_text',
field=models.TextField(blank=True, null=True),
),
]
| [
"mortadagzar@gmail.com"
] | mortadagzar@gmail.com |
1f2077fb090fdeee86837bbfae1517e61d60450b | 640411253fcf4dfc71b70ec923b0864ccd58b837 | /dev/python_introspection.py | 56166900dc776d25dc7cfcd71d2b0f2debcfa990 | [] | no_license | williamsdoug/GitAnalysis | cb6dce95e7a92b0d1d2cf2db3c94aec6ef3be3bf | da91b541d2531a41cc1f4e02537b7803b84b20d3 | refs/heads/master | 2016-09-06T15:50:50.345898 | 2015-07-02T13:28:51 | 2015-07-02T13:28:51 | 23,364,094 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 20,055 | py | #
# python_introspection.py - Language aware processing of python source files
#
# Author: Doug Williams - Copyright 2015
#
# Last updated 4/13/2015
#
# Nomenclaure:
# - AST, ST - Abstract Syntax Tree (from Python standatd library)
# - HT - Hash Tree - AST annotates with signatures of each included element
#
# History:
# - 3/31/15 - Initial version, based on expderimental work in iPython notebook
# - 4/1/15 - Adds support for language aware difference: pyDiff
# - 4/3/15 - Adds support for computing AST depth. Includes getDepth(),
# ComputeDepth [nodeVisitor class], and displayDepthResults
# - 4/13/15 - PythonDiff now in standalone file
#
# Top Level Routines:
# - show_st(): Display routine for AST. Wrapper for DisplayNodes
#
# - get_all_files(): Recursively walks over source pool, returning file paths
#
# - get_st_from_file(): generates ast parse tree from file
#
# - get_total_nodes(): Computes node count for ast sub-tree or list of
# sub-trees. Wrapper for CountTotalNodes
#
# - get_stats(): Computes raw data for various code complexity stats for
# and ast tree or list of trees. Wrapper for ComputeComplexity
#
# - get_delta_stats(): Compute difference between two sets of stats
#
# - combine_stats(): Aggregates a list of stats sets
#
# - get_unique_classes(): Debug/development routine to identify _ast classes
# within a pool of source code. Wrapper for
# FindUniqueClasses
#
# - getDepth(): Function level and aggregate depth AST depth statistics at
# statement, expression and node level. getDepth() is wapper
# for ComputeDepth AST nodeVisitor class. displayDepthResults()
# can be used to print out results.
#
# from python_introspection import get_all_files, get_st_from_file, show_st
# from python_introspection import get_total_nodes
# from python_introspection import get_stats, get_delta_stats, combine_stats
# from python_introspection import get_unique_classes
# from python_introspection import ComputeDepth, getDepth, displayDepthResults
import ast
# from pprint import pprint
import collections
import os
import fnmatch
# import hashlib
def get_all_files(starting_dir, pattern='*.py'):
"""Iterator over source pool"""
for root, dirnames, filenames in os.walk(starting_dir):
for filename in fnmatch.filter(filenames, pattern):
yield os.path.join(root, filename)
def get_st_from_file(fname):
"""Displays Abstract Tree for python file"""
with open(fname) as f:
contents = f.read()
st = ast.parse(contents)
return st
#
# Display Routines
#
def print_fields(node):
"""pyDiff helper routine for verbose mode """
for k, v in ast.iter_fields(node):
if not v:
continue
vv = repr(v)
if 'object at 0x' not in vv:
print ' ', k, ' = ', vv
def show_st(node):
if isinstance(node, list) or isinstance(node, tuple):
dn = DisplayNodes()
for n in node:
dn.visit(n)
else:
DisplayNodes().visit(node)
class DisplayNodes(ast.NodeVisitor):
level = 0
indent = 3
SPACES = ' '*3*30
filter_fields = True # currently unused
ignore_fields = ['body', 'elts', 'keys', 'value', # Currently unused
'values', 'targets', 'ctx',
'left', 'op', 'right', 'args',
'ops', 'test', 'orelse', 'comparators',
'type', 'func', 'slice', 'level', 'names']
def __init__(self, filter_fields=False):
self.level = 0
self.filter_fields = filter_fields
super(DisplayNodes, self).__init__()
def visit_If(self, node):
self.level += 1
print self.SPACES[0:(self.level)*self.indent] + '**TEST**'
self.visit(node.test)
print self.SPACES[0:(self.level)*self.indent] + '**BODY**'
if isinstance(node.body, list) or isinstance(node.body, tuple):
for n in node.body:
self.visit(n)
else:
self.visit(node.body)
if node.orelse:
print self.SPACES[0:(self.level)*self.indent] + '**ORSELSE**'
if isinstance(node.orelse, list) or isinstance(node.orelse, tuple):
for n in node.orelse:
self.visit(n)
else:
self.visit(node.orelse)
self.level -= 1
def visit_For(self, node):
self.level += 1
print self.SPACES[0:(self.level)*self.indent] + '**TARGET**'
if isinstance(node.target, list):
for n in node.target:
self.visit(n)
else:
self.visit(node.target)
print self.SPACES[0:(self.level)*self.indent] + '**ITER**'
if isinstance(node.iter, list) or isinstance(node.iter, tuple):
for n in node.iter:
self.visit(n)
else:
self.visit(node.iter)
print self.SPACES[0:(self.level)*self.indent] + '**BODY**'
if isinstance(node.body, list) or isinstance(node.body, tuple):
for n in node.body:
self.visit(n)
else:
self.visit(node.body)
if node.orelse:
print self.SPACES[0:(self.level)*self.indent] + '**ORSELSE**'
if isinstance(node.orelse, list) or isinstance(node.orelse, tuple):
for n in node.orelse:
self.visit(n)
else:
self.visit(node.orelse)
self.level -= 1
def visit_While(self, node):
self.level += 1
print self.SPACES[0:(self.level)*self.indent] + '**TEST**'
self.visit(node.test)
print self.SPACES[0:(self.level)*self.indent] + '**BODY**'
if isinstance(node.body, list) or isinstance(node.body, tuple):
for n in node.body:
self.visit(n)
else:
self.visit(node.body)
if node.orelse:
print self.SPACES[0:(self.level)*self.indent] + '**ORSELSE**'
if isinstance(node.orelse, list) or isinstance(node.orelse, tuple):
for n in node.orelse:
self.visit(n)
else:
self.visit(node.orelse)
self.level -= 1
def generic_visit(self, node):
for k, v in ast.iter_fields(node):
if not v:
continue
vv = repr(v)
if 'object at 0x' not in vv:
print self.SPACES[0:(self.level+1)*self.indent], k, ' = ', vv
self.level += 1
super(DisplayNodes, self).generic_visit(node)
self.level -= 1
def visit(self, node):
print self.SPACES[0:self.level*self.indent], self.level, ':',
if isinstance(node, ast.expr):
print 'EXPR', type(node).__name__, [node.lineno, node.col_offset],
elif isinstance(node, ast.stmt):
print 'STMT', type(node).__name__, [node.lineno, node.col_offset],
else:
print type(node).__name__,
print
super(DisplayNodes, self).visit(node)
#
# Walks AST (sub) tree computing node count
#
class CountTotalNodes(ast.NodeVisitor):
total_nodes = 0
def __init__(self):
self.total_nodes = 0
super(CountTotalNodes, self).__init__()
def generic_visit(self, node):
self.total_nodes += 1
super(CountTotalNodes, self).generic_visit(node)
def getTotalNodes(self):
return self.total_nodes
def get_total_nodes(node):
ctn = CountTotalNodes()
if isinstance(node, list):
for n in node:
ctn.visit(n)
else:
ctn.visit(node)
return ctn.getTotalNodes()
#
# Walks AST (sub)tree computing various code complexity features
#
class ComputeComplexity(ast.NodeVisitor):
function_depth = 0
class_depth = 0
nested_functions = 0
nested_classes = 0
func_in_class = 0
total_statements = 0
total_expressions = 0
other_nodes = 0
total_classes = 0
total_functions = 0
total_confitionals = 0
total_comprehension = 0
comprehension_with_if = 0
total_tests = 0
test_nodes = 0
leaf_nodes = 0
total_nodes = 0
detail = collections.defaultdict(int)
def __init__(self):
self.function_depth = 0
self.class_depth = 0
self.nested_functions = 0
self.nested_classes = 0
self.func_in_class = 0
self.total_statements = 0
self.total_expressions = 0
self.other_nodes = 0
self.total_classes = 0
self.total_functions = 0
self.total_conditionals = 0
self.total_comprehension = 0
self.comprehension_with_if = 0
self.total_tests = 0
self.test_nodes = 0
self.leaf_nodes = 0
self.total_nodes = 0
self.detail = collections.defaultdict(int)
super(ComputeComplexity, self).__init__()
def visit_ClassDef(self, node):
# print(node.name)
if self.class_depth > 0:
self.nested_classes += 1
self.total_classes += 1
self.class_depth += 1
self.generic_visit(node)
self.class_depth -= 1
def visit_FunctionDef(self, node):
if self.function_depth > 0:
self.nested_functions += 1
if self.class_depth > 0:
self.func_in_class += 1
# print(node.name)
self.total_functions += 1
self.function_depth += 1
self.generic_visit(node)
self.function_depth -= 1
def visit_For(self, node):
self.total_conditionals += 1
self.generic_visit(node)
def visit_While(self, node):
self.total_conditionals += 1
self.total_tests += 1
self.test_nodes += get_total_nodes(node.test)
self.generic_visit(node)
def visit_If(self, node):
self.total_conditionals += 1
self.total_tests += 1
self.test_nodes += get_total_nodes(node.test)
self.generic_visit(node)
def visit_TryExcept(self, node):
self.total_conditionals += 1
self.generic_visit(node)
def visit_comprehension(self, node):
self.total_comprehension += 1
self.comprehension_with_if += len(node.ifs) > 0
self.total_tests += len(node.ifs)
self.test_nodes += sum([get_total_nodes(i) for i in node.ifs])
self.generic_visit(node)
def generic_visit(self, node):
self.total_nodes += 1
node_type = type(node).__name__
self.detail[node_type] += 1
if isinstance(node, ast.stmt):
self.total_statements += 1
elif isinstance(node, ast.expr):
self.total_expressions += 1
else:
self.other_nodes += 1
if len([1 for x in ast.iter_child_nodes(node)]) == 0:
self.leaf_nodes += 1
super(ComputeComplexity, self).generic_visit(node)
def getStats(self):
return {'total_statements': self.total_statements,
'total_expressions': self.total_expressions,
'other_nodes': self.other_nodes,
'total_classes': self.total_classes,
'total_functions': self.total_functions,
'total_conditionals': self.total_conditionals,
'total_comprehension': self.total_comprehension,
'comprehension_with_if': self.comprehension_with_if,
'total_tests': self.total_tests,
'test_nodes': self.test_nodes,
'leaf_nodes': self.leaf_nodes,
'total_nodes': self.total_nodes,
'detail': self.detail,
'nested_functions': self.nested_functions,
'nested_classes': self.nested_classes,
'func_in_class': self.func_in_class,
}
def get_stats(node, convert_to_dict=False):
"""Computes code complexity states for an AST tree or list of trees"""
cc = ComputeComplexity()
if isinstance(node, list):
for n in node:
cc.visit(n)
else:
cc.visit(node)
stats = cc.getStats()
if convert_to_dict:
stats['detail'] = dict(stats['detail'])
return stats
def get_delta_stats(stats1, stats2, convert_to_dict=False):
"""Computes difference between two sets of stats"""
results = {}
# aggregate results. details requires special handling
for k in stats1.keys():
if k == 'detail':
continue
results[k] = stats1[k] - stats2[k]
# aggregate details, special care required since dicts are sparse
rdetail = collections.defaultdict(int)
detail1 = stats1['detail']
if not isinstance(detail1, collections.defaultdict):
detail1 = collections.defaultdict(int, detail1)
detail2 = stats2['detail']
if not isinstance(detail2, collections.defaultdict):
detail2 = collections.defaultdict(int, detail2)
for k in set(detail1.keys()).union(set(detail2.keys())):
rdetail[k] = detail1[k] - detail2[k]
if convert_to_dict:
rdetail = dict(rdetail)
results['detail'] = rdetail
return results
def combine_stats(list_of_stats, convert_to_dict=False):
"""Combines a set of stats """
results = collections.defaultdict(int)
detail = collections.defaultdict(int)
for stat in list_of_stats:
# aggregate results. details requires special handling
for k in stat.keys():
if k == 'detail':
continue
results[k] += stat[k]
# aggregate details, special care required since dicts are sparse
for k, v in stat['detail'].items():
detail[k] += v
if convert_to_dict:
results = dict(results)
detail = dict(detail)
results['detail'] = detail
return results
#
# Identifies Unque classes within AST tree
#
class FindUniqueClasses(ast.NodeVisitor):
statements = {}
expressions = {}
all_classes = {}
def __init__(self):
self.statements = {}
self.expressions = {}
self.other_classes = {}
super(FindUniqueClasses, self).__init__()
def generic_visit(self, node):
node_type = type(node).__name__
if isinstance(node, ast.stmt):
self.statements[node_type] = 1
if isinstance(node, ast.expr):
self.expressions[node_type] = 1
self.all_classes[node_type] = 1
super(FindUniqueClasses, self).generic_visit(node)
def getStats(self):
stmt_and_expr = list(set(self.statements.keys()).intersection(
set(self.expressions.keys())))
stmt_or_expr = set(self.statements.keys()).union(
set(self.expressions.keys()))
non_stmt_expr = list(set(self.all_classes.keys()).intersection(
stmt_or_expr))
return {'statements': self.statements.keys(),
'expressions': self.expressions.keys(),
'all_classes': self.all_classes.keys(),
'stmt_and_expr': stmt_and_expr,
'non_stmt_expr': non_stmt_expr,
}
def get_unique_classes(node):
"""Finds unique classes contained in an AST tree or list of trees"""
fuc = FindUniqueClasses()
if isinstance(node, list):
for n in node:
fuc.visit(n)
else:
fuc.visit(node)
return fuc.getStats()
#
# Compute AST Depth statistics
#
class ComputeDepth(ast.NodeVisitor):
"""Collects statistics on tree depth by function, at statement,
expression and node levels
"""
results = [] # results for each function
stats = {} # per-function stats
classes = [] # remember naming hierarchy for classes
def init_stats(self):
self.stats = {}
for level in ['stmt', 'expr', 'node']:
self.stats[level] = {'depth': 0,
'max_depth': 0,
'sum_of_depth': 0,
'instances': 0}
def __init__(self):
self.classes = []
self.results = []
self.init_stats()
super(ComputeDepth, self).__init__()
def visit_ClassDef(self, node):
self.classes.append(node.name)
self.generic_visit(node)
self.classes = self.classes[0:-1]
def visit_FunctionDef(self, node):
self.init_stats()
self.generic_visit(node)
name = node.name # compute name, prefix with class name as appropriate
if self.classes:
name = '.'.join(self.classes) + '.' + name
self.stats['name'] = name
for level in ['stmt', 'expr', 'node']: # compute per-function averages
self.stats[level]['avg_depth'] = (
float(self.stats[level]['sum_of_depth'])
/ float(max(self.stats[level]['instances'], 1)))
self.results.append(self.stats)
def generic_visit(self, node):
# update per-node stats
self.stats['node']['max_depth'] = max(self.stats['node']['max_depth'],
self.stats['node']['depth'])
self.stats['node']['sum_of_depth'] += self.stats['node']['depth']
self.stats['node']['instances'] += 1
self.stats['node']['depth'] += 1
if isinstance(node, ast.stmt): # update statement level stats
self.stats['stmt']['depth'] += 1
self.stats['stmt']['max_depth'] = max(
self.stats['stmt']['max_depth'], self.stats['stmt']['depth'])
self.stats['stmt']['sum_of_depth'] += self.stats['stmt']['depth']
self.stats['stmt']['instances'] += 1
if isinstance(node, ast.expr): # update expression level stats
self.stats['expr']['depth'] += 1
self.stats['expr']['max_depth'] = max(
self.stats['expr']['max_depth'], self.stats['expr']['depth'])
self.stats['expr']['sum_of_depth'] += self.stats['expr']['depth']
self.stats['expr']['instances'] += 1
super(ComputeDepth, self).generic_visit(node)
# decrement depth counters
self.stats['node']['depth'] -= 1
if isinstance(node, ast.stmt):
self.stats['stmt']['depth'] -= 1
if isinstance(node, ast.expr):
self.stats['expr']['depth'] -= 1
def visit(self, node):
super(ComputeDepth, self).visit(node)
return self.results
def getDepth(node):
"""Wrapper for ComputeDepth, also determines max and average
depth across all functions for nodes, expressions and statements."""
results = ComputeDepth().visit(node)
totals = {}
for level in ['stmt', 'expr', 'node']:
totals[level] = {}
totals[level]['max_depth'] = max([r[level]['max_depth']
for r in results])
totals[level]['sum_of_depth'] = sum([r[level]['sum_of_depth']
for r in results])
totals[level]['instances'] = sum([r[level]['instances']
for r in results])
totals[level]['avg_depth'] = (float(totals[level]['sum_of_depth'])
/ float(max(totals[level]['instances'],
1)))
return totals, results
def displayDepthResults(totals, results):
"""Displays function level and aggregated depth statistics"""
for r in results:
print
print r['name']
for level in ['stmt', 'expr', 'node']:
print ' %s -- avg %0.1f peak %0.1f' % (level,
r[level]['avg_depth'],
r[level]['max_depth'])
print
print 'Aggregated:'
for level in ['stmt', 'expr', 'node']:
print ' %s -- avg %0.1f peak %0.1f' % (level,
totals[level]['avg_depth'],
totals[level]['max_depth'])
| [
"ddwilli@gmail.com"
] | ddwilli@gmail.com |
900da8b9e0f950261448fb6dca13409fad7822ae | 31a7c0fa71fa9f7b75406fc6868c698acd714804 | /sucai/views.py | 57f3850c2423baad3f2191892bb4bdeb1640f41f | [] | no_license | cc8848/AiChuangZuoBackground | adb65fc6af937257e4867e95068bf66320a62611 | 72c77f9569f8739a00a82dfe298db8797f04f228 | refs/heads/master | 2020-06-05T02:07:49.050905 | 2018-06-28T10:28:25 | 2018-06-28T10:28:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,642 | py | # -*- coding: utf-8 -*-
from django.http import HttpResponse
import json
import models
# 转换成json形式
def toDicts(objs):
obj_arr = []
for o in objs:
obj_arr.append(o.toDict())
return obj_arr
# 查询平台类型
def deck_list(request):
all_type = models.deck_type.objects.all()
all_dicts = toDicts(all_type)
all_json = json.dumps(all_dicts, ensure_ascii=False)
return HttpResponse(all_json)
# 查询平台领域类型
def field_list(request):
deck = request.GET.get('deck_type')
print deck
deck_id = models.deck_type.objects.get(pingtai_name=deck)
all_objs = models.field_type.objects.filter(deck_type_id=deck_id) # 获取列表用filter,获取单个值用get
all_dicts = toDicts(all_objs)
all_json = json.dumps(all_dicts, ensure_ascii=False)
return HttpResponse(all_json)
# 筛选消息
def list(request):
deck = request.GET.get('deck')
filters = request.GET.get('filters')
print deck
print filters
deck_id = models.deck_type.objects.get(pingtai_name=deck)
filter_id = models.field_type.objects.get(deck_type_id=deck_id, lingyu_name=filters)
all_objs = models.message.objects.filter(deck_type_id=deck_id, field_type_id=filter_id) # 获取列表用filter,获取单个值用get
all_dicts = toDicts(all_objs)
all_json = json.dumps(all_dicts, ensure_ascii=False)
return HttpResponse(all_json)
# 查询所有消息
def all(request):
all_objs = models.message.objects.all() # 获取列表
all_dicts = toDicts(all_objs)
all_json = json.dumps(all_dicts, ensure_ascii=False)
return HttpResponse(all_json)
| [
"shuo.du@edaibu.net"
] | shuo.du@edaibu.net |
f5c0a7e696686f43691506373bb86e69d4cb52a9 | 4324d19af69080f45ff60b733c940f7dc1aa6dae | /google-ads-python/google/ads/google_ads/v1/proto/services/customer_extension_setting_service_pb2.py | f3103761ce4e6ee6248071e0e456005eea04feb7 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | ljborton/Forked_Work | cc8a3813c146ea4547aca9caeb03e649bbdb9076 | 7aaf67af8d9f86f9dc0530a1ad23951bcb535c92 | refs/heads/master | 2023-07-19T22:26:48.085129 | 2019-11-27T02:53:51 | 2019-11-27T02:53:51 | 224,321,748 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | true | 20,926 | py | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v1/proto/services/customer_extension_setting_service.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.ads.google_ads.v1.proto.resources import customer_extension_setting_pb2 as google_dot_ads_dot_googleads__v1_dot_proto_dot_resources_dot_customer__extension__setting__pb2
from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2
from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2
from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2
from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='google/ads/googleads_v1/proto/services/customer_extension_setting_service.proto',
package='google.ads.googleads.v1.services',
syntax='proto3',
serialized_options=_b('\n$com.google.ads.googleads.v1.servicesB$CustomerExtensionSettingServiceProtoP\001ZHgoogle.golang.org/genproto/googleapis/ads/googleads/v1/services;services\242\002\003GAA\252\002 Google.Ads.GoogleAds.V1.Services\312\002 Google\\Ads\\GoogleAds\\V1\\Services\352\002$Google::Ads::GoogleAds::V1::Services'),
serialized_pb=_b('\nOgoogle/ads/googleads_v1/proto/services/customer_extension_setting_service.proto\x12 google.ads.googleads.v1.services\x1aHgoogle/ads/googleads_v1/proto/resources/customer_extension_setting.proto\x1a\x1cgoogle/api/annotations.proto\x1a google/protobuf/field_mask.proto\x1a\x1egoogle/protobuf/wrappers.proto\x1a\x17google/rpc/status.proto\";\n\"GetCustomerExtensionSettingRequest\x12\x15\n\rresource_name\x18\x01 \x01(\t\"\xc6\x01\n&MutateCustomerExtensionSettingsRequest\x12\x13\n\x0b\x63ustomer_id\x18\x01 \x01(\t\x12W\n\noperations\x18\x02 \x03(\x0b\x32\x43.google.ads.googleads.v1.services.CustomerExtensionSettingOperation\x12\x17\n\x0fpartial_failure\x18\x03 \x01(\x08\x12\x15\n\rvalidate_only\x18\x04 \x01(\x08\"\x91\x02\n!CustomerExtensionSettingOperation\x12/\n\x0bupdate_mask\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\x12M\n\x06\x63reate\x18\x01 \x01(\x0b\x32;.google.ads.googleads.v1.resources.CustomerExtensionSettingH\x00\x12M\n\x06update\x18\x02 \x01(\x0b\x32;.google.ads.googleads.v1.resources.CustomerExtensionSettingH\x00\x12\x10\n\x06remove\x18\x03 \x01(\tH\x00\x42\x0b\n\toperation\"\xb5\x01\n\'MutateCustomerExtensionSettingsResponse\x12\x31\n\x15partial_failure_error\x18\x03 \x01(\x0b\x32\x12.google.rpc.Status\x12W\n\x07results\x18\x02 \x03(\x0b\x32\x46.google.ads.googleads.v1.services.MutateCustomerExtensionSettingResult\"=\n$MutateCustomerExtensionSettingResult\x12\x15\n\rresource_name\x18\x01 \x01(\t2\x8d\x04\n\x1f\x43ustomerExtensionSettingService\x12\xe5\x01\n\x1bGetCustomerExtensionSetting\x12\x44.google.ads.googleads.v1.services.GetCustomerExtensionSettingRequest\x1a;.google.ads.googleads.v1.resources.CustomerExtensionSetting\"C\x82\xd3\xe4\x93\x02=\x12;/v1/{resource_name=customers/*/customerExtensionSettings/*}\x12\x81\x02\n\x1fMutateCustomerExtensionSettings\x12H.google.ads.googleads.v1.services.MutateCustomerExtensionSettingsRequest\x1aI.google.ads.googleads.v1.services.MutateCustomerExtensionSettingsResponse\"I\x82\xd3\xe4\x93\x02\x43\">/v1/customers/{customer_id=*}/customerExtensionSettings:mutate:\x01*B\x8b\x02\n$com.google.ads.googleads.v1.servicesB$CustomerExtensionSettingServiceProtoP\x01ZHgoogle.golang.org/genproto/googleapis/ads/googleads/v1/services;services\xa2\x02\x03GAA\xaa\x02 Google.Ads.GoogleAds.V1.Services\xca\x02 Google\\Ads\\GoogleAds\\V1\\Services\xea\x02$Google::Ads::GoogleAds::V1::Servicesb\x06proto3')
,
dependencies=[google_dot_ads_dot_googleads__v1_dot_proto_dot_resources_dot_customer__extension__setting__pb2.DESCRIPTOR,google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR,google_dot_protobuf_dot_wrappers__pb2.DESCRIPTOR,google_dot_rpc_dot_status__pb2.DESCRIPTOR,])
_GETCUSTOMEREXTENSIONSETTINGREQUEST = _descriptor.Descriptor(
name='GetCustomerExtensionSettingRequest',
full_name='google.ads.googleads.v1.services.GetCustomerExtensionSettingRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='resource_name', full_name='google.ads.googleads.v1.services.GetCustomerExtensionSettingRequest.resource_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=312,
serialized_end=371,
)
_MUTATECUSTOMEREXTENSIONSETTINGSREQUEST = _descriptor.Descriptor(
name='MutateCustomerExtensionSettingsRequest',
full_name='google.ads.googleads.v1.services.MutateCustomerExtensionSettingsRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='customer_id', full_name='google.ads.googleads.v1.services.MutateCustomerExtensionSettingsRequest.customer_id', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='operations', full_name='google.ads.googleads.v1.services.MutateCustomerExtensionSettingsRequest.operations', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='partial_failure', full_name='google.ads.googleads.v1.services.MutateCustomerExtensionSettingsRequest.partial_failure', index=2,
number=3, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='validate_only', full_name='google.ads.googleads.v1.services.MutateCustomerExtensionSettingsRequest.validate_only', index=3,
number=4, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=374,
serialized_end=572,
)
_CUSTOMEREXTENSIONSETTINGOPERATION = _descriptor.Descriptor(
name='CustomerExtensionSettingOperation',
full_name='google.ads.googleads.v1.services.CustomerExtensionSettingOperation',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='update_mask', full_name='google.ads.googleads.v1.services.CustomerExtensionSettingOperation.update_mask', index=0,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='create', full_name='google.ads.googleads.v1.services.CustomerExtensionSettingOperation.create', index=1,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='update', full_name='google.ads.googleads.v1.services.CustomerExtensionSettingOperation.update', index=2,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='remove', full_name='google.ads.googleads.v1.services.CustomerExtensionSettingOperation.remove', index=3,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='operation', full_name='google.ads.googleads.v1.services.CustomerExtensionSettingOperation.operation',
index=0, containing_type=None, fields=[]),
],
serialized_start=575,
serialized_end=848,
)
_MUTATECUSTOMEREXTENSIONSETTINGSRESPONSE = _descriptor.Descriptor(
name='MutateCustomerExtensionSettingsResponse',
full_name='google.ads.googleads.v1.services.MutateCustomerExtensionSettingsResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='partial_failure_error', full_name='google.ads.googleads.v1.services.MutateCustomerExtensionSettingsResponse.partial_failure_error', index=0,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='results', full_name='google.ads.googleads.v1.services.MutateCustomerExtensionSettingsResponse.results', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=851,
serialized_end=1032,
)
_MUTATECUSTOMEREXTENSIONSETTINGRESULT = _descriptor.Descriptor(
name='MutateCustomerExtensionSettingResult',
full_name='google.ads.googleads.v1.services.MutateCustomerExtensionSettingResult',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='resource_name', full_name='google.ads.googleads.v1.services.MutateCustomerExtensionSettingResult.resource_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=1034,
serialized_end=1095,
)
_MUTATECUSTOMEREXTENSIONSETTINGSREQUEST.fields_by_name['operations'].message_type = _CUSTOMEREXTENSIONSETTINGOPERATION
_CUSTOMEREXTENSIONSETTINGOPERATION.fields_by_name['update_mask'].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK
_CUSTOMEREXTENSIONSETTINGOPERATION.fields_by_name['create'].message_type = google_dot_ads_dot_googleads__v1_dot_proto_dot_resources_dot_customer__extension__setting__pb2._CUSTOMEREXTENSIONSETTING
_CUSTOMEREXTENSIONSETTINGOPERATION.fields_by_name['update'].message_type = google_dot_ads_dot_googleads__v1_dot_proto_dot_resources_dot_customer__extension__setting__pb2._CUSTOMEREXTENSIONSETTING
_CUSTOMEREXTENSIONSETTINGOPERATION.oneofs_by_name['operation'].fields.append(
_CUSTOMEREXTENSIONSETTINGOPERATION.fields_by_name['create'])
_CUSTOMEREXTENSIONSETTINGOPERATION.fields_by_name['create'].containing_oneof = _CUSTOMEREXTENSIONSETTINGOPERATION.oneofs_by_name['operation']
_CUSTOMEREXTENSIONSETTINGOPERATION.oneofs_by_name['operation'].fields.append(
_CUSTOMEREXTENSIONSETTINGOPERATION.fields_by_name['update'])
_CUSTOMEREXTENSIONSETTINGOPERATION.fields_by_name['update'].containing_oneof = _CUSTOMEREXTENSIONSETTINGOPERATION.oneofs_by_name['operation']
_CUSTOMEREXTENSIONSETTINGOPERATION.oneofs_by_name['operation'].fields.append(
_CUSTOMEREXTENSIONSETTINGOPERATION.fields_by_name['remove'])
_CUSTOMEREXTENSIONSETTINGOPERATION.fields_by_name['remove'].containing_oneof = _CUSTOMEREXTENSIONSETTINGOPERATION.oneofs_by_name['operation']
_MUTATECUSTOMEREXTENSIONSETTINGSRESPONSE.fields_by_name['partial_failure_error'].message_type = google_dot_rpc_dot_status__pb2._STATUS
_MUTATECUSTOMEREXTENSIONSETTINGSRESPONSE.fields_by_name['results'].message_type = _MUTATECUSTOMEREXTENSIONSETTINGRESULT
DESCRIPTOR.message_types_by_name['GetCustomerExtensionSettingRequest'] = _GETCUSTOMEREXTENSIONSETTINGREQUEST
DESCRIPTOR.message_types_by_name['MutateCustomerExtensionSettingsRequest'] = _MUTATECUSTOMEREXTENSIONSETTINGSREQUEST
DESCRIPTOR.message_types_by_name['CustomerExtensionSettingOperation'] = _CUSTOMEREXTENSIONSETTINGOPERATION
DESCRIPTOR.message_types_by_name['MutateCustomerExtensionSettingsResponse'] = _MUTATECUSTOMEREXTENSIONSETTINGSRESPONSE
DESCRIPTOR.message_types_by_name['MutateCustomerExtensionSettingResult'] = _MUTATECUSTOMEREXTENSIONSETTINGRESULT
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
GetCustomerExtensionSettingRequest = _reflection.GeneratedProtocolMessageType('GetCustomerExtensionSettingRequest', (_message.Message,), dict(
DESCRIPTOR = _GETCUSTOMEREXTENSIONSETTINGREQUEST,
__module__ = 'google.ads.googleads_v1.proto.services.customer_extension_setting_service_pb2'
,
__doc__ = """Request message for
[CustomerExtensionSettingService.GetCustomerExtensionSetting][google.ads.googleads.v1.services.CustomerExtensionSettingService.GetCustomerExtensionSetting].
Attributes:
resource_name:
The resource name of the customer extension setting to fetch.
""",
# @@protoc_insertion_point(class_scope:google.ads.googleads.v1.services.GetCustomerExtensionSettingRequest)
))
_sym_db.RegisterMessage(GetCustomerExtensionSettingRequest)
MutateCustomerExtensionSettingsRequest = _reflection.GeneratedProtocolMessageType('MutateCustomerExtensionSettingsRequest', (_message.Message,), dict(
DESCRIPTOR = _MUTATECUSTOMEREXTENSIONSETTINGSREQUEST,
__module__ = 'google.ads.googleads_v1.proto.services.customer_extension_setting_service_pb2'
,
__doc__ = """Request message for
[CustomerExtensionSettingService.MutateCustomerExtensionSettings][google.ads.googleads.v1.services.CustomerExtensionSettingService.MutateCustomerExtensionSettings].
Attributes:
customer_id:
The ID of the customer whose customer extension settings are
being modified.
operations:
The list of operations to perform on individual customer
extension settings.
partial_failure:
If true, successful operations will be carried out and invalid
operations will return errors. If false, all operations will
be carried out in one transaction if and only if they are all
valid. Default is false.
validate_only:
If true, the request is validated but not executed. Only
errors are returned, not results.
""",
# @@protoc_insertion_point(class_scope:google.ads.googleads.v1.services.MutateCustomerExtensionSettingsRequest)
))
_sym_db.RegisterMessage(MutateCustomerExtensionSettingsRequest)
CustomerExtensionSettingOperation = _reflection.GeneratedProtocolMessageType('CustomerExtensionSettingOperation', (_message.Message,), dict(
DESCRIPTOR = _CUSTOMEREXTENSIONSETTINGOPERATION,
__module__ = 'google.ads.googleads_v1.proto.services.customer_extension_setting_service_pb2'
,
__doc__ = """A single operation (create, update, remove) on a customer extension
setting.
Attributes:
update_mask:
FieldMask that determines which resource fields are modified
in an update.
operation:
The mutate operation.
create:
Create operation: No resource name is expected for the new
customer extension setting.
update:
Update operation: The customer extension setting is expected
to have a valid resource name.
remove:
Remove operation: A resource name for the removed customer
extension setting is expected, in this format: ``customers/{c
ustomer_id}/customerExtensionSettings/{feed_id}``
""",
# @@protoc_insertion_point(class_scope:google.ads.googleads.v1.services.CustomerExtensionSettingOperation)
))
_sym_db.RegisterMessage(CustomerExtensionSettingOperation)
MutateCustomerExtensionSettingsResponse = _reflection.GeneratedProtocolMessageType('MutateCustomerExtensionSettingsResponse', (_message.Message,), dict(
DESCRIPTOR = _MUTATECUSTOMEREXTENSIONSETTINGSRESPONSE,
__module__ = 'google.ads.googleads_v1.proto.services.customer_extension_setting_service_pb2'
,
__doc__ = """Response message for a customer extension setting mutate.
Attributes:
partial_failure_error:
Errors that pertain to operation failures in the partial
failure mode. Returned only when partial\_failure = true and
all errors occur inside the operations. If any errors occur
outside the operations (e.g. auth errors), we return an RPC
level error.
results:
All results for the mutate.
""",
# @@protoc_insertion_point(class_scope:google.ads.googleads.v1.services.MutateCustomerExtensionSettingsResponse)
))
_sym_db.RegisterMessage(MutateCustomerExtensionSettingsResponse)
MutateCustomerExtensionSettingResult = _reflection.GeneratedProtocolMessageType('MutateCustomerExtensionSettingResult', (_message.Message,), dict(
DESCRIPTOR = _MUTATECUSTOMEREXTENSIONSETTINGRESULT,
__module__ = 'google.ads.googleads_v1.proto.services.customer_extension_setting_service_pb2'
,
__doc__ = """The result for the customer extension setting mutate.
Attributes:
resource_name:
Returned for successful operations.
""",
# @@protoc_insertion_point(class_scope:google.ads.googleads.v1.services.MutateCustomerExtensionSettingResult)
))
_sym_db.RegisterMessage(MutateCustomerExtensionSettingResult)
DESCRIPTOR._options = None
_CUSTOMEREXTENSIONSETTINGSERVICE = _descriptor.ServiceDescriptor(
name='CustomerExtensionSettingService',
full_name='google.ads.googleads.v1.services.CustomerExtensionSettingService',
file=DESCRIPTOR,
index=0,
serialized_options=None,
serialized_start=1098,
serialized_end=1623,
methods=[
_descriptor.MethodDescriptor(
name='GetCustomerExtensionSetting',
full_name='google.ads.googleads.v1.services.CustomerExtensionSettingService.GetCustomerExtensionSetting',
index=0,
containing_service=None,
input_type=_GETCUSTOMEREXTENSIONSETTINGREQUEST,
output_type=google_dot_ads_dot_googleads__v1_dot_proto_dot_resources_dot_customer__extension__setting__pb2._CUSTOMEREXTENSIONSETTING,
serialized_options=_b('\202\323\344\223\002=\022;/v1/{resource_name=customers/*/customerExtensionSettings/*}'),
),
_descriptor.MethodDescriptor(
name='MutateCustomerExtensionSettings',
full_name='google.ads.googleads.v1.services.CustomerExtensionSettingService.MutateCustomerExtensionSettings',
index=1,
containing_service=None,
input_type=_MUTATECUSTOMEREXTENSIONSETTINGSREQUEST,
output_type=_MUTATECUSTOMEREXTENSIONSETTINGSRESPONSE,
serialized_options=_b('\202\323\344\223\002C\">/v1/customers/{customer_id=*}/customerExtensionSettings:mutate:\001*'),
),
])
_sym_db.RegisterServiceDescriptor(_CUSTOMEREXTENSIONSETTINGSERVICE)
DESCRIPTOR.services_by_name['CustomerExtensionSettingService'] = _CUSTOMEREXTENSIONSETTINGSERVICE
# @@protoc_insertion_point(module_scope)
| [
"noreply@github.com"
] | ljborton.noreply@github.com |
6f686e08a7cefc2451681d1601521582f55624d6 | 25bf4f39762b4fa0e249c7fc85681368f3d49573 | /test/test_Util/test_param_util.py | 1192a531afea3ec6ae4b61d9bc1d83481660a6f2 | [
"MIT"
] | permissive | linan7788626/lenstronomy | ca740c25c717f2b674903039d582f283f29fb07e | dc9b4651a5b530e659048fd1a65c9955720b40cd | refs/heads/master | 2021-05-04T20:43:20.442654 | 2018-01-31T07:20:52 | 2018-01-31T07:20:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,180 | py | import numpy as np
import pytest
import numpy.testing as npt
import lenstronomy.Util.param_util as param_util
def test_cart2polar():
#singel 2d coordinate transformation
center = np.array([0,0])
x = 1
y = 1
r, phi = param_util.cart2polar(x,y,center)
assert r == np.sqrt(2) #radial part
assert phi == np.arctan(1)
#array of 2d coordinates
center = np.array([0,0])
x = np.array([1,2])
y = np.array([1,1])
r, phi = param_util.cart2polar(x,y,center)
assert r[0] == np.sqrt(2) #radial part
assert phi[0] == np.arctan(1)
def test_polar2cart():
#singel 2d coordinate transformation
center = np.array([0,0])
r = 1
phi = np.pi
x, y = param_util.polar2cart(r, phi, center)
assert x == -1
assert abs(y) < 10e-14
def test_phi_q2_elliptisity():
phi, q = 0, 1
e1,e2 = param_util.phi_q2_elliptisity(phi,q)
assert e1 == 0
assert e2 == 0
phi, q = 1, 1
e1,e2 = param_util.phi_q2_elliptisity(phi,q)
assert e1 == 0
assert e2 == 0
phi, q = 2.,0.95
e1, e2 = param_util.phi_q2_elliptisity(phi,q)
assert e1 == -0.016760092842656733
assert e2 == -0.019405192187382792
def test_phi_q2_elliptisity_bounds():
bounds = 'lower'
phi, q = 0, 1
e1, e2 = param_util.phi_q2_elliptisity_bounds(phi, q, bounds)
assert e1 == 0
assert e2 == 0
phi, q = 1, 1
e1, e2 = param_util.phi_q2_elliptisity_bounds(phi,q, bounds)
assert e1 == 0
assert e2 == 0
phi, q = 2., 0.95
e1, e2 = param_util.phi_q2_elliptisity_bounds(phi, q, bounds)
assert e1 == -0.019405192187382792
assert e2 == -0.019405192187382792
bounds = 'upper'
phi, q = 2., 0.95
e1, e2 = param_util.phi_q2_elliptisity_bounds(phi, q, bounds)
assert e1 == 0.019405192187382792
assert e2 == 0.019405192187382792
def test_elliptisity2phi_q():
e1, e2 = 0.3,0
phi,q = param_util.elliptisity2phi_q(e1,e2)
assert phi == 0
assert q == 0.53846153846153844
def test_elliptisity2phi_q_symmetry():
phi,q = 1.5, 0.8
e1,e2 = param_util.phi_q2_elliptisity(phi,q)
phi_new,q_new = param_util.elliptisity2phi_q(e1,e2)
assert phi == phi_new
assert q == q_new
phi,q = -1.5, 0.8
e1,e2 = param_util.phi_q2_elliptisity(phi,q)
phi_new,q_new = param_util.elliptisity2phi_q(e1,e2)
assert phi == phi_new
assert q == q_new
e1, e2 = 0.1, -0.1
phi, q = param_util.elliptisity2phi_q(e1, e2)
e1_new, e2_new = param_util.phi_q2_elliptisity(phi,q)
npt.assert_almost_equal(e1, e1_new, decimal=10)
npt.assert_almost_equal(e2, e2_new, decimal=10)
e1, e2 = 2.8, -0.8
phi, q = param_util.elliptisity2phi_q(e1, e2)
e1_new, e2_new = param_util.phi_q2_elliptisity(phi,q)
npt.assert_almost_equal(e1, e1_new, decimal=10)
npt.assert_almost_equal(e2, e2_new, decimal=10)
def test_phi_gamma_ellipticity():
phi = -1.
gamma = 0.1
e1, e2 = param_util.phi_gamma_ellipticity(phi, gamma)
print(e1, e2, 'e1, e2')
phi_out, gamma_out = param_util.ellipticity2phi_gamma(e1, e2)
assert phi == phi_out
assert gamma == gamma_out
if __name__ == '__main__':
pytest.main() | [
"simon.birrer@pyhs.ethz.ch"
] | simon.birrer@pyhs.ethz.ch |
7fefc058121e0ca2783c53506333d2f74a4cc661 | aa5c528588d215ce2ada276d0c9b78f35028eac0 | /crm_san/wsgi.py | ac0d55f9d1ddb0103c2f8fcafed11a9dc672d897 | [] | no_license | eduardogpg/crm_san | c895e3d6cadfd8be2e668e947016da8510acfd28 | c2a950be7a192633a52613b0ef55a7b70c8ef640 | refs/heads/master | 2023-01-11T11:13:53.607608 | 2020-11-12T15:20:28 | 2020-11-12T15:20:28 | 312,169,081 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 391 | py | """
WSGI config for crm_san project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'crm_san.settings')
application = get_wsgi_application()
| [
"eduardo78d@gmail.com"
] | eduardo78d@gmail.com |
9de27ab85689ac971081f9e3e0371b1c0819ac5d | 8f6aa9ac9c8c2e409875bbf36fbc49b3eb37d88b | /enthought/block_canvas/interactor/parametric_interactor.py | a3319ca78abac4c86dea4e9f057d9e18af451e02 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | enthought/etsproxy | 5660cf562c810db2ceb6b592b6c12274bce96d73 | 4aafd628611ebf7fe8311c9d1a0abcf7f7bb5347 | refs/heads/master | 2023-03-27T04:51:29.297305 | 2020-12-02T09:05:18 | 2020-12-02T09:05:18 | 1,632,969 | 3 | 1 | NOASSERTION | 2020-12-02T09:05:20 | 2011-04-18T22:29:56 | Python | UTF-8 | Python | false | false | 113 | py | # proxy module
from __future__ import absolute_import
from blockcanvas.interactor.parametric_interactor import *
| [
"ischnell@enthought.com"
] | ischnell@enthought.com |
cb5c058aabea7ff1201c33ddad173279ca20615d | 0600f0979fe17624d33aa74c739775f0f27a3bb5 | /putil/plot/figure.py | f9c0c65843a3ce2feed4f0fdc9a15d8515126be8 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | pmacosta/putil | 2c8177fb6b9be667b8d52b48bfd3272de8b0160d | 416cea52df8221981727e25d133e9b4e3f464798 | refs/heads/master | 2021-01-21T13:33:41.232773 | 2016-05-17T12:57:30 | 2016-05-17T12:57:30 | 44,289,408 | 6 | 2 | null | null | null | null | UTF-8 | Python | false | false | 33,522 | py | # figure.py
# Copyright (c) 2013-2016 Pablo Acosta-Serafini
# See LICENSE for details
# pylint: disable=C0111,C0302,R0201,R0914,W0105,W0212
# Standard library imports
from __future__ import print_function
import os
# PyPI imports
import numpy
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg
# Putil imports
import putil.exh
import putil.misc
import putil.pcontracts
from .panel import Panel
from .constants import TITLE_FONT_SIZE
from .functions import _F, _MF, _intelligent_ticks
###
# Exception tracing initialization code
###
"""
[[[cog
import os, sys
if sys.hexversion < 0x03000000:
import __builtin__
else:
import builtins as __builtin__
sys.path.append(os.environ['TRACER_DIR'])
import trace_ex_plot_figure
exobj_plot = trace_ex_plot_figure.trace_module(no_print=True)
]]]
[[[end]]]
"""
###
# Functions
###
_IS_NUMBER = lambda x: isinstance(x, int) or isinstance(x, float)
def _first_label(label_list):
""" Find first non-blank label """
llist = [lobj.get_text().strip() for lobj in label_list]
for label_index, label_text in enumerate(llist):
if label_text not in [None, '']:
return label_index
def _get_text_prop(fig, text_obj):
""" Return length of text in pixels """
renderer = fig.canvas.get_renderer()
bbox = text_obj.get_window_extent(renderer=renderer).transformed(
fig.dpi_scale_trans.inverted()
)
return {'width':bbox.width*fig.dpi, 'height':bbox.height*fig.dpi}
def _get_yaxis_size(fig_obj, tick_labels, axis_label):
""" Compute Y axis height and width """
# Minimum of one line spacing between vertical ticks
get_prop = lambda x, y: _get_text_prop(fig_obj, x)[y]
axis_height = axis_width = 0
label_index = _first_label(tick_labels)
if label_index is not None:
label_height = get_prop(tick_labels[label_index], 'height')
axis_height = (2*len(tick_labels)-1)*label_height
raw_axis_width = [get_prop(tick, 'width') for tick in tick_labels]
axis_width = max([num for num in raw_axis_width if _IS_NUMBER(num)])
# axis_label is a Text object, which is never None, it has the x, y
# coordinates and axis label text, even if is = ''
axis_height = max(axis_height, get_prop(axis_label, 'height'))
axis_width = axis_width+(1.5*get_prop(axis_label, 'width'))
return axis_height, axis_width
def _get_xaxis_size(fig_obj, tick_labels, axis_label):
""" Compute Y axis height and width """
# Minimum of one smallest label separation between horizontal ticks
get_prop = lambda x, y: _get_text_prop(fig_obj, x)[y]
raw_axis_width = [get_prop(tick, 'width') for tick in tick_labels]
label_width_list = [num for num in raw_axis_width if _IS_NUMBER(num)]
min_label_width = min(label_width_list)
axis_width = ((len(tick_labels)-1)*min_label_width)+sum(label_width_list)
# axis_label is a Text object, which is never None, it has the x, y
# coordinates and axis label text, even if is = ''
axis_height = 1.5*get_prop(axis_label, 'height')
axis_width = max(axis_width, get_prop(axis_label, 'width'))
return axis_height, axis_width
###
# Class
###
class Figure(object):
r"""
Generates presentation-quality plots
:param panels: One or more data panels
:type panels: :py:class:`putil.plot.Panel` *or list of*
:py:class:`putil.plot.Panel` *or None*
:param indep_var_label: Independent variable label
:type indep_var_label: string
:param indep_var_units: Independent variable units
:type indep_var_units: string
:param indep_axis_ticks: Independent axis tick marks. If not None
overrides automatically generated tick marks if
the axis type is linear. If None automatically
generated tick marks are used for the independent
axis
:type indep_axis_ticks: list, Numpy vector or None
:param fig_width: Hard copy plot width in inches. If None the width is
automatically calculated so that there is no horizontal
overlap between any two text elements in the figure
:type fig_width: :ref:`PositiveRealNum` or None
:param fig_height: Hard copy plot height in inches. If None the height is
automatically calculated so that there is no vertical
overlap between any two text elements in the figure
:type fig_height: :ref:`PositiveRealNum` or None
:param title: Plot title
:type title: string
:param log_indep_axis: Flag that indicates whether the independent
axis is linear (False) or logarithmic (True)
:type log_indep_axis: boolean
.. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. putil.plot.figure.Figure.__init__
:raises:
* RuntimeError (Argument \`fig_height\` is not valid)
* RuntimeError (Argument \`fig_width\` is not valid)
* RuntimeError (Argument \`indep_axis_ticks\` is not valid)
* RuntimeError (Argument \`indep_var_label\` is not valid)
* RuntimeError (Argument \`indep_var_units\` is not valid)
* RuntimeError (Argument \`log_indep_axis\` is not valid)
* RuntimeError (Argument \`panels\` is not valid)
* RuntimeError (Argument \`title\` is not valid)
* RuntimeError (Figure object is not fully specified)
* RuntimeError (Figure size is too small: minimum width *[min_width]*,
minimum height *[min_height]*)
* TypeError (Panel *[panel_num]* is not fully specified)
* ValueError (Figure cannot be plotted with a logarithmic independent
axis because panel *[panel_num]*, series *[series_num]* contains
negative independent data points)
.. [[[end]]]
"""
# pylint: disable=R0902,R0913
def __init__(self, panels=None, indep_var_label='', indep_var_units='',
indep_axis_ticks=None, fig_width=None, fig_height=None, title='',
log_indep_axis=False):
putil.exh.addai(
'indep_axis_ticks',
(indep_axis_ticks is not None) and (
(not isinstance(indep_axis_ticks, list)) and
(not isinstance(indep_axis_ticks, numpy.ndarray))
)
)
# Public attributes
self._indep_axis_ticks = None
self._fig = None
self._panels = None
self._indep_var_label = None
self._title = None
self._log_indep_axis = None
self._fig_width = None
self._fig_height = None
self._indep_var_units = None
self._indep_var_div = None
self._axes_list = []
# Assignment of arguments to attributes
self._set_indep_var_label(indep_var_label)
self._set_indep_var_units(indep_var_units)
self._set_title(title)
self._set_log_indep_axis(log_indep_axis)
self._indep_axis_ticks = (
indep_axis_ticks if not self.log_indep_axis else None
)
self._set_fig_width(fig_width)
self._set_fig_height(fig_height)
self._set_panels(panels)
def __bool__(self): # pragma: no cover
"""
Returns :code:`True` if the figure has at least a panel associated with
it, :code:`False` otherwise
.. note:: This method applies to Python 3.x
"""
return self._panels is not None
def __iter__(self):
r"""
Returns an iterator over the panel object(s) in the figure.
For example:
.. =[=cog
.. import docs.support.incfile
.. docs.support.incfile.incfile('plot_example_7.py', cog.out)
.. =]=
.. code-block:: python
# plot_example_7.py
from __future__ import print_function
import numpy, putil.plot
def figure_iterator_example(no_print):
source1 = putil.plot.BasicSource(
indep_var=numpy.array([1, 2, 3, 4]),
dep_var=numpy.array([1, -10, 10, 5])
)
source2 = putil.plot.BasicSource(
indep_var=numpy.array([100, 200, 300, 400]),
dep_var=numpy.array([50, 75, 100, 125])
)
series1 = putil.plot.Series(
data_source=source1,
label='Goals'
)
series2 = putil.plot.Series(
data_source=source2,
label='Saves',
color='b',
marker=None,
interp='STRAIGHT',
line_style='--'
)
panel1 = putil.plot.Panel(
series=series1,
primary_axis_label='Average',
primary_axis_units='A',
display_indep_axis=False
)
panel2 = putil.plot.Panel(
series=series2,
primary_axis_label='Standard deviation',
primary_axis_units=r'$\sqrt{{A}}$',
display_indep_axis=True
)
figure = putil.plot.Figure(
panels=[panel1, panel2],
indep_var_label='Time',
indep_var_units='sec',
title='Sample Figure'
)
if not no_print:
for num, panel in enumerate(figure):
print('Panel {0}:'.format(num+1))
print(panel)
print('')
else:
return figure
.. =[=end=]=
.. code-block:: python
>>> import docs.support.plot_example_7 as mod
>>> mod.figure_iterator_example(False)
Panel 1:
Series 0:
Independent variable: [ 1.0, 2.0, 3.0, 4.0 ]
Dependent variable: [ 1.0, -10.0, 10.0, 5.0 ]
Label: Goals
Color: k
Marker: o
Interpolation: CUBIC
Line style: -
Secondary axis: False
Primary axis label: Average
Primary axis units: A
Secondary axis label: not specified
Secondary axis units: not specified
Logarithmic dependent axis: False
Display independent axis: False
Legend properties:
cols: 1
pos: BEST
<BLANKLINE>
Panel 2:
Series 0:
Independent variable: [ 100.0, 200.0, 300.0, 400.0 ]
Dependent variable: [ 50.0, 75.0, 100.0, 125.0 ]
Label: Saves
Color: b
Marker: None
Interpolation: STRAIGHT
Line style: --
Secondary axis: False
Primary axis label: Standard deviation
Primary axis units: $\sqrt{{A}}$
Secondary axis label: not specified
Secondary axis units: not specified
Logarithmic dependent axis: False
Display independent axis: True
Legend properties:
cols: 1
pos: BEST
<BLANKLINE>
"""
return iter(self._panels)
def __nonzero__(self): # pragma: no cover
"""
Returns :code:`True` if the figure has at least a panel associated with
it, :code:`False` otherwise
.. note:: This method applies to Python 2.x
"""
return self._panels is not None
def __str__(self):
r"""
Prints figure information. For example:
>>> from __future__ import print_function
>>> import docs.support.plot_example_7 as mod
>>> print(mod.figure_iterator_example(True)) #doctest: +ELLIPSIS
Panel 0:
Series 0:
Independent variable: [ 1.0, 2.0, 3.0, 4.0 ]
Dependent variable: [ 1.0, -10.0, 10.0, 5.0 ]
Label: Goals
Color: k
Marker: o
Interpolation: CUBIC
Line style: -
Secondary axis: False
Primary axis label: Average
Primary axis units: A
Secondary axis label: not specified
Secondary axis units: not specified
Logarithmic dependent axis: False
Display independent axis: False
Legend properties:
cols: 1
pos: BEST
Panel 1:
Series 0:
Independent variable: [ 100.0, 200.0, 300.0, 400.0 ]
Dependent variable: [ 50.0, 75.0, 100.0, 125.0 ]
Label: Saves
Color: b
Marker: None
Interpolation: STRAIGHT
Line style: --
Secondary axis: False
Primary axis label: Standard deviation
Primary axis units: $\sqrt{{A}}$
Secondary axis label: not specified
Secondary axis units: not specified
Logarithmic dependent axis: False
Display independent axis: True
Legend properties:
cols: 1
pos: BEST
Independent variable label: Time
Independent variable units: sec
Logarithmic independent axis: False
Title: Sample Figure
Figure width: ...
Figure height: ...
<BLANKLINE>
"""
ret = ''
if (self.panels is None) or (len(self.panels) == 0):
ret += 'Panels: None\n'
else:
for num, element in enumerate(self.panels):
ret += 'Panel {0}:\n'.format(num)
temp = str(element).split('\n')
temp = [3*' '+line for line in temp]
ret += '\n'.join(temp)
ret += '\n'
ret += 'Independent variable label: {0}\n'.format(
self.indep_var_label
if self.indep_var_label not in ['', None] else
'not specified'
)
ret += 'Independent variable units: {0}\n'.format(
self.indep_var_units
if self.indep_var_units not in ['', None] else
'not specified'
)
ret += 'Logarithmic independent axis: {0}\n'.format(
self.log_indep_axis
)
ret += 'Title: {0}\n'.format(
self.title if self.title not in ['', None] else 'not specified'
)
ret += 'Figure width: {0}\n'.format(self.fig_width)
ret += 'Figure height: {0}\n'.format(self.fig_height)
return ret
def _get_indep_axis_scale(self):
return self._indep_var_div
def _get_indep_axis_ticks(self):
return self._indep_axis_ticks
def _get_indep_var_label(self):
return self._indep_var_label
@putil.pcontracts.contract(indep_var_label='None|str')
def _set_indep_var_label(self, indep_var_label):
self._indep_var_label = indep_var_label
self._draw(force_redraw=True)
def _get_indep_var_units(self):
return self._indep_var_units
@putil.pcontracts.contract(indep_var_units='None|str')
def _set_indep_var_units(self, indep_var_units):
self._indep_var_units = indep_var_units
self._draw(force_redraw=True)
def _get_title(self):
return self._title
@putil.pcontracts.contract(title='None|str')
def _set_title(self, title):
self._title = title
self._draw(force_redraw=True)
def _get_log_indep_axis(self):
return self._log_indep_axis
@putil.pcontracts.contract(log_indep_axis='None|bool')
def _set_log_indep_axis(self, log_indep_axis):
self._log_indep_axis = log_indep_axis
self._draw(force_redraw=True)
def _get_fig_width(self):
return self._fig_width
@putil.pcontracts.contract(fig_width='None|positive_real_num')
def _set_fig_width(self, fig_width):
self._fig_width = fig_width
def _get_fig_height(self):
return self._fig_height
@putil.pcontracts.contract(fig_height='None|positive_real_num')
def _set_fig_height(self, fig_height):
self._fig_height = fig_height
def _get_panels(self):
return self._panels
def _set_panels(self, panels):
self._panels = (
(panels if isinstance(panels, list) else [panels])
if panels is not None else
panels
)
if self.panels is not None:
self._validate_panels()
self._draw(force_redraw=True)
def _validate_panels(self):
"""
Verifies that elements of panel list are of the right type and
fully specified
"""
invalid_ex = putil.exh.addai('panels')
specified_ex = putil.exh.addex(
TypeError, 'Panel *[panel_num]* is not fully specified'
)
for num, obj in enumerate(self.panels):
invalid_ex(not isinstance(obj, Panel))
specified_ex(not obj._complete, _F('panel_num', num))
def _get_fig(self):
return self._fig
def _get_axes_list(self):
return self._axes_list
def _get_complete(self):
"""
Returns True if figure is fully specified, otherwise returns False
"""
return (self.panels is not None) and len(self.panels)
def _draw(self, force_redraw=False, raise_exception=False):
# pylint: disable=C0326,W0612
log_ex = putil.exh.addex(
ValueError,
'Figure cannot be plotted with a logarithmic '
'independent axis because panel *[panel_num]*, series '
'*[series_num]* contains negative independent data points'
)
specified_ex = putil.exh.addex(
RuntimeError, 'Figure object is not fully specified'
)
if self._complete and force_redraw:
num_panels = len(self.panels)
plt.close('all')
# Create required number of panels
self._fig, axes = plt.subplots(num_panels, sharex=True)
axes = axes if isinstance(axes, type(numpy.array([]))) else [axes]
glob_indep_var = []
# Find union of the independent variable data set of all panels
for panel_num, panel_obj in enumerate(self.panels):
for series_num, series_obj in enumerate(panel_obj.series):
log_ex(
bool(
self.log_indep_axis and
(min(series_obj.indep_var) < 0)
),
edata=_MF(
'panel_num', panel_num, 'series_num', series_num
)
)
glob_indep_var = numpy.unique(
numpy.append(
glob_indep_var,
numpy.array(
[
putil.eng.round_mantissa(element, 10)
for element in series_obj.indep_var
]
)
)
)
indep_var_ticks = _intelligent_ticks(
glob_indep_var,
min(glob_indep_var),
max(glob_indep_var),
tight=True,
log_axis=self.log_indep_axis,
tick_list=(
None if self._log_indep_axis else self._indep_axis_ticks
)
)
self._indep_var_div = indep_var_ticks.div
self._indep_axis_ticks = indep_var_ticks.locs
# Scale all panel series
for panel_obj in self.panels:
panel_obj._scale_indep_var(self._indep_var_div)
# Draw panels
indep_axis_dict = {
'log_indep':self.log_indep_axis,
'indep_var_min':indep_var_ticks.min,
'indep_var_max':indep_var_ticks.max,
'indep_var_locs':indep_var_ticks.locs,
'indep_var_labels':indep_var_ticks.labels,
'indep_axis_label':self.indep_var_label,
'indep_axis_units':self.indep_var_units,
'indep_axis_unit_scale':indep_var_ticks.unit_scale
}
panels_with_indep_axis_list = [
num for num, panel_obj in enumerate(self.panels)
if panel_obj.display_indep_axis
] or [num_panels-1]
keys = ['number', 'primary', 'secondary']
for num, (panel_obj, axarr) in enumerate(zip(self.panels, axes)):
panel_dict = panel_obj._draw_panel(
axarr, indep_axis_dict, num in panels_with_indep_axis_list
)
panel_dict['number'] = num
self._axes_list.append(
dict((item, panel_dict[item]) for item in keys)
)
if self.title not in [None, '']:
axes[0].set_title(
self.title,
horizontalalignment='center',
verticalalignment='bottom',
multialignment='center',
fontsize=TITLE_FONT_SIZE
)
# Draw figure otherwise some bounding boxes return NaN
FigureCanvasAgg(self._fig).draw()
self._calculate_figure_size()
elif (not self._complete) and (raise_exception):
specified_ex(True)
def _calculate_figure_size(self):
""" Calculates minimum panel and figure size """
small_ex = putil.exh.addex(
RuntimeError,
'Figure size is too small: minimum width *[min_width]*, '
'minimum height *[min_height]*'
)
title_height = title_width = 0
title = self._fig.axes[0].get_title()
if (title is not None) and (title.strip() != ''):
title_obj = self._fig.axes[0].title
title_height = _get_text_prop(self._fig, title_obj)['height']
title_width = _get_text_prop(self._fig, title_obj)['width']
xaxis_dims = [
_get_xaxis_size(
self._fig,
axis_obj.xaxis.get_ticklabels(),
axis_obj.xaxis.get_label()
) for axis_obj in self._fig.axes
]
yaxis_dims = [
_get_yaxis_size(
self._fig,
axis_obj.yaxis.get_ticklabels(),
axis_obj.yaxis.get_label()
) for axis_obj in self._fig.axes
]
panel_dims = [
(yaxis_height+xaxis_height, yaxis_width+xaxis_width)
for (yaxis_height, yaxis_width), (xaxis_height, xaxis_width)
in zip(yaxis_dims, xaxis_dims)
]
dpi = float(self._fig.dpi)
panels_width = max([panel_width for _, panel_width in panel_dims])
panels_height = max([panel_height for panel_height, _ in panel_dims])
min_fig_width = round(max(title_width, panels_width)/dpi, 2)
min_fig_height = round(
((len(self._axes_list)*panels_height)+title_height)/dpi, 2
)
small_ex(
bool(
(self.fig_width and (self.fig_width < min_fig_width)) or
(self.fig_height and (self.fig_height < min_fig_height))
),
[_F('min_width', min_fig_width), _F('min_height', min_fig_height)]
)
self.fig_width = self.fig_width or min_fig_width
self.fig_height = self.fig_height or min_fig_height
@putil.pcontracts.contract(fname='file_name', ftype=str)
def save(self, fname, ftype='PNG'):
r"""
Saves the figure to a file
:param fname: File name
:type fname: :ref:`FileName`
:param ftype: File type, either 'PNG' or 'EPS' (case insensitive). The
PNG format is a `raster
<https://en.wikipedia.org/wiki/Raster_graphics>`_ format
while the EPS format is a
`vector <https://en.wikipedia.org/wiki/
Vector_graphics>`_ format
:type ftype: string
.. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. putil.plot.figure.Figure.save
:raises:
* RuntimeError (Argument \`fname\` is not valid)
* RuntimeError (Argument \`ftype\` is not valid)
* RuntimeError (Figure object is not fully specified)
* RuntimeError (Unsupported file type: *[file_type]*)
.. [[[end]]]
"""
specified_ex = putil.exh.addex(
RuntimeError, 'Figure object is not fully specified'
)
unsupported_ex = putil.exh.addex(
RuntimeError, 'Unsupported file type: *[file_type]*'
)
specified_ex(not self._complete)
unsupported_ex(
ftype.lower() not in ['png', 'eps'], _F('file_type', ftype)
)
_, extension = os.path.splitext(fname)
if (not extension) or (extension == '.'):
fname = '{file_name}.{extension}'.format(
file_name=fname.rstrip('.'),
extension=ftype.lower()
)
self._draw(force_redraw=self._fig is None, raise_exception=True)
self.fig.set_size_inches(self.fig_width, self.fig_height)
# Matplotlib seems to have a problem with ~/, expand it to $HOME
fname = os.path.expanduser(fname)
putil.misc.make_dir(fname)
self._fig.savefig(
fname, bbox_inches='tight', dpi=self._fig.dpi, format=ftype
)
plt.close('all')
def show(self):
"""
Displays the figure
.. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. putil.plot.figure.Figure.show
:raises:
* RuntimeError (Figure object is not fully specified)
* ValueError (Figure cannot be plotted with a logarithmic independent
axis because panel *[panel_num]*, series *[series_num]* contains
negative independent data points)
.. [[[end]]]
"""
self._draw(force_redraw=self._fig is None, raise_exception=True)
plt.show()
# Managed attributes
_complete = property(_get_complete)
axes_list = property(
_get_axes_list, doc='Matplotlib figure axes handle list'
)
"""
Gets the Matplotlib figure axes handle list or :code:`None` if figure is
not fully specified. Useful if annotations or further customizations to
the panel(s) are needed. Each panel has an entry in the list, which is
sorted in the order the panels are plotted (top to bottom). Each panel
entry is a dictionary containing the following key-value pairs:
* **number** (*integer*) -- panel number, panel 0 is the top-most panel
* **primary** (*Matplotlib axis object*) -- axis handle for the primary
axis, None if the figure has not primary axis
* **secondary** (*Matplotlib axis object*) -- axis handle for the
secondary axis, None if the figure has no secondary axis
:type: list
"""
fig = property(_get_fig, doc='Figure handle')
"""
Gets the Matplotlib figure handle. Useful if annotations or further
customizations to the figure are needed. :code:`None` if figure is not
fully specified
:type: Matplotlib figure handle or None
"""
fig_height = property(
_get_fig_height, _set_fig_height, doc='height of the hard copy plot'
)
r"""
Gets or sets the height (in inches) of the hard copy plot, :code:`None` if
figure is not fully specified.
:type: :ref:`PositiveRealNum` or None
.. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. putil.plot.figure.Figure.fig_height
:raises: (when assigned) RuntimeError (Argument \`fig_height\` is not
valid)
.. [[[end]]]
"""
fig_width = property(
_get_fig_width, _set_fig_width, doc='Width of the hard copy plot'
)
r"""
Gets or sets the width (in inches) of the hard copy plot, :code:`None` if
figure is not fully specified
:type: :ref:`PositiveRealNum` or None
.. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. putil.plot.figure.Figure.fig_width
:raises: (when assigned) RuntimeError (Argument \`fig_width\` is not
valid)
.. [[[end]]]
"""
indep_axis_scale = property(
_get_indep_axis_scale, doc='Independent axis scale'
)
"""
Gets the scale of the figure independent axis, :code:`None` if figure is
not fully specified
:type: float or None if figure has no panels associated with it
"""
indep_axis_ticks = property(
_get_indep_axis_ticks, doc='Independent axis tick locations'
)
"""
Gets the independent axis (scaled) tick locations, :code:`None` if figure
is not fully specified
:type: list
"""
indep_var_label = property(
_get_indep_var_label,
_set_indep_var_label,
doc='Figure independent axis label'
)
r"""
Gets or sets the figure independent variable label
:type: string or None
.. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. putil.plot.figure.Figure.indep_var_label
:raises: (when assigned)
* RuntimeError (Argument \`indep_var_label\` is not valid)
* RuntimeError (Figure object is not fully specified)
* ValueError (Figure cannot be plotted with a logarithmic independent
axis because panel *[panel_num]*, series *[series_num]* contains
negative independent data points)
.. [[[end]]]
"""
indep_var_units = property(
_get_indep_var_units,
_set_indep_var_units,
doc='Figure independent axis units'
)
r"""
Gets or sets the figure independent variable units
:type: string or None
.. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. putil.plot.figure.Figure.indep_var_units
:raises: (when assigned)
* RuntimeError (Argument \`indep_var_units\` is not valid)
* RuntimeError (Figure object is not fully specified)
* ValueError (Figure cannot be plotted with a logarithmic independent
axis because panel *[panel_num]*, series *[series_num]* contains
negative independent data points)
.. [[[end]]]
"""
log_indep_axis = property(
_get_log_indep_axis, _set_log_indep_axis, doc='Figure log_indep_axis'
)
r"""
Gets or sets the figure logarithmic independent axis flag; indicates
whether the independent axis is linear (False) or logarithmic (True)
:type: boolean
.. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. putil.plot.figure.Figure.log_indep_axis
:raises: (when assigned)
* RuntimeError (Argument \`log_indep_axis\` is not valid)
* RuntimeError (Figure object is not fully specified)
* ValueError (Figure cannot be plotted with a logarithmic independent
axis because panel *[panel_num]*, series *[series_num]* contains
negative independent data points)
.. [[[end]]]
"""
panels = property(_get_panels, _set_panels, doc='Figure panel(s)')
r"""
Gets or sets the figure panel(s), :code:`None` if no panels have been
specified
:type: :py:class:`putil.plot.Panel`, list of
:py:class:`putil.plot.panel` or None
.. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. putil.plot.figure.Figure.panels
:raises: (when assigned)
* RuntimeError (Argument \`fig_height\` is not valid)
* RuntimeError (Argument \`fig_width\` is not valid)
* RuntimeError (Argument \`panels\` is not valid)
* RuntimeError (Figure object is not fully specified)
* RuntimeError (Figure size is too small: minimum width *[min_width]*,
minimum height *[min_height]*)
* TypeError (Panel *[panel_num]* is not fully specified)
* ValueError (Figure cannot be plotted with a logarithmic independent
axis because panel *[panel_num]*, series *[series_num]* contains
negative independent data points)
.. [[[end]]]
"""
title = property(_get_title, _set_title, doc='Figure title')
r"""
Gets or sets the figure title
:type: string or None
.. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. putil.plot.figure.Figure.title
:raises: (when assigned)
* RuntimeError (Argument \`title\` is not valid)
* RuntimeError (Figure object is not fully specified)
* ValueError (Figure cannot be plotted with a logarithmic independent
axis because panel *[panel_num]*, series *[series_num]* contains
negative independent data points)
.. [[[end]]]
"""
| [
"pmasdev@gmail.com"
] | pmasdev@gmail.com |
8611f209fe68c3cf4bd88593daab738e7551f310 | 56f5b2ea36a2258b8ca21e2a3af9a5c7a9df3c6e | /CMGTools/H2TauTau/prod/TauES_test/nom/emb/DoubleMuParked/StoreResults-Run2012D_22Jan2013_v1_PFembedded_trans1_tau132_pthad1_30had2_30_v1-5ef1c0fd428eb740081f19333520fdc8/USER/V5_B/PAT_CMG_V5_16_0_1374658143/HTT_24Jul_newTES_manzoni_Nom_Jobs/Job_104/run_cfg.py | dbf427a50449e68c70461099708878a40db6fb43 | [] | no_license | rmanzoni/HTT | 18e6b583f04c0a6ca10142d9da3dd4c850cddabc | a03b227073b2d4d8a2abe95367c014694588bf98 | refs/heads/master | 2016-09-06T05:55:52.602604 | 2014-02-20T16:35:34 | 2014-02-20T16:35:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 69,051 | py | import FWCore.ParameterSet.Config as cms
import os,sys
sys.path.append('/afs/cern.ch/user/m/manzoni/summer13/CMGTools/CMSSW_5_3_9/src/CMGTools/H2TauTau/prod/TauES_test/nom/emb/DoubleMuParked/StoreResults-Run2012D_22Jan2013_v1_PFembedded_trans1_tau132_pthad1_30had2_30_v1-5ef1c0fd428eb740081f19333520fdc8/USER/V5_B/PAT_CMG_V5_16_0_1374658143/HTT_24Jul_newTES_manzoni_Nom_Jobs')
from base_cfg import *
process.source = cms.Source("PoolSource",
noEventSort = cms.untracked.bool(True),
inputCommands = cms.untracked.vstring('keep *',
'drop cmgStructuredPFJets_cmgStructuredPFJetSel__PAT'),
lumisToProcess = cms.untracked.VLuminosityBlockRange( ("190645:10-190645:110", "190646:1-190646:111", "190659:33-190659:167", "190679:1-190679:55", "190688:69-190688:249",
"190702:51-190702:53", "190702:55-190702:122", "190702:124-190702:169", "190703:1-190703:252", "190704:1-190704:3",
"190705:1-190705:5", "190705:7-190705:65", "190705:81-190705:336", "190705:338-190705:350", "190705:353-190705:383",
"190706:1-190706:126", "190707:1-190707:237", "190707:239-190707:257", "190708:1-190708:189", "190733:71-190733:96",
"190733:99-190733:389", "190733:392-190733:460", "190736:1-190736:80", "190736:83-190736:185", "190738:1-190738:130",
"190738:133-190738:226", "190738:229-190738:349", "190782:55-190782:181", "190782:184-190782:233", "190782:236-190782:399",
"190782:401-190782:409", "190895:64-190895:202", "190895:210-190895:302", "190895:305-190895:584", "190895:587-190895:948",
"190906:73-190906:256", "190906:259-190906:354", "190906:356-190906:496", "190945:124-190945:207", "190949:1-190949:81",
"191043:45-191043:46", "191046:1-191046:21", "191046:24-191046:82", "191046:84-191046:88", "191046:92-191046:116",
"191046:119-191046:180", "191046:183", "191046:185-191046:239", "191056:1", "191056:4-191056:9",
"191056:16-191056:17", "191056:19", "191057:1", "191057:4-191057:40", "191062:1",
"191062:3", "191062:5-191062:214", "191062:216-191062:541", "191090:1-191090:55", "191201:38-191201:49",
"191201:52-191201:79", "191202:1-191202:64", "191202:66-191202:68", "191202:87-191202:105", "191202:108-191202:118",
"191226:77-191226:78", "191226:81-191226:831", "191226:833-191226:1454", "191226:1456-191226:1466", "191226:1469-191226:1507",
"191226:1510-191226:1686", "191247:1-191247:153", "191247:156-191247:280", "191247:283-191247:606", "191247:608-191247:620",
"191247:622-191247:818", "191247:821-191247:834", "191247:837-191247:1031", "191247:1034-191247:1046", "191247:1049-191247:1140",
"191247:1143-191247:1187", "191247:1190-191247:1214", "191247:1217-191247:1224", "191248:1-191248:103", "191264:59-191264:79",
"191264:82-191264:152", "191264:155-191264:189", "191271:56-191271:223", "191271:225-191271:363", "191276:1-191276:16",
"191277:1-191277:28", "191277:30-191277:164", "191277:167-191277:253", "191277:255-191277:457", "191277:460-191277:535",
"191277:537-191277:576", "191277:579-191277:775", "191277:778-191277:811", "191277:813-191277:849", "191367:1-191367:2",
"191411:1-191411:23", "191695:1", "191718:43-191718:95", "191718:98-191718:207", "191720:1",
"191720:3-191720:15", "191720:17-191720:181", "191721:1", "191721:3-191721:34", "191721:36-191721:183",
"191721:186-191721:189", "191726:1-191726:13", "191810:15", "191810:22-191810:49", "191810:52-191810:92",
"191830:54-191830:242", "191830:245-191830:301", "191830:304-191830:393", "191833:1", "191833:3-191833:103",
"191834:1-191834:30", "191834:33-191834:74", "191834:77-191834:299", "191834:302-191834:352", "191837:1-191837:44",
"191837:47-191837:53", "191837:56-191837:65", "191856:1-191856:133", "191859:1-191859:28", "191859:31-191859:126",
"193093:1-193093:33", "193123:1-193123:27", "193124:1-193124:52", "193192:58-193192:86", "193193:1-193193:6",
"193193:8", "193193:11-193193:83", "193193:86-193193:120", "193193:122-193193:160", "193193:162-193193:274",
"193193:276-193193:495", "193193:497-193193:506", "193207:54-193207:182", "193334:29-193334:172", "193336:1-193336:264",
"193336:267-193336:492", "193336:495-193336:684", "193336:687-193336:729", "193336:732-193336:951", "193541:77-193541:101",
"193541:103-193541:413", "193541:416-193541:575", "193541:578-193541:619", "193556:41-193556:83", "193557:1-193557:84",
"193575:48-193575:173", "193575:176-193575:349", "193575:351-193575:394", "193575:397-193575:415", "193575:417-193575:658",
"193575:660-193575:752", "193621:60-193621:570", "193621:573-193621:769", "193621:772-193621:976", "193621:979-193621:1053",
"193621:1056-193621:1137", "193621:1139-193621:1193", "193621:1195-193621:1371", "193621:1373-193621:1654", "193834:1-193834:35",
"193835:1-193835:20", "193835:22-193835:26", "193836:1-193836:2", "193998:66-193998:113", "193998:115-193998:278",
"193999:1-193999:45", "194027:57-194027:113", "194050:53-194050:113", "194050:116-194050:273", "194050:275-194050:355",
"194050:357-194050:369", "194050:372-194050:391", "194050:394-194050:490", "194050:492-194050:814", "194050:816-194050:1435",
"194050:1437-194050:1735", "194050:1760-194050:1888", "194051:1-194051:12", "194052:1-194052:99", "194052:102-194052:166",
"194075:48-194075:101", "194075:103", "194075:105-194075:107", "194075:109", "194075:111",
"194076:1-194076:9", "194076:11-194076:55", "194076:58-194076:163", "194076:165-194076:228", "194076:230-194076:264",
"194076:267-194076:507", "194076:509-194076:527", "194076:530-194076:538", "194076:541-194076:562", "194076:565-194076:748",
"194108:81-194108:161", "194108:164-194108:264", "194108:266-194108:373", "194108:376-194108:396", "194108:398-194108:433",
"194108:436-194108:452", "194108:454-194108:577", "194108:579-194108:590", "194108:593-194108:668", "194108:671-194108:872",
"194115:66-194115:184", "194115:186-194115:338", "194115:340-194115:346", "194115:348-194115:493", "194115:496-194115:731",
"194115:819-194115:857", "194117:1-194117:38", "194119:1-194119:229", "194119:232-194119:261", "194120:1-194120:162",
"194120:165-194120:406", "194150:42-194150:127", "194150:129-194150:261", "194150:264-194150:311", "194151:47-194151:72",
"194151:75-194151:191", "194151:193-194151:238", "194151:240-194151:617", "194151:619", "194151:621",
"194151:623", "194153:1-194153:115", "194199:96-194199:227", "194199:229-194199:336", "194199:339-194199:402",
"194210:3-194210:195", "194210:198-194210:217", "194210:220-194210:359", "194210:361-194210:555", "194223:61-194223:112",
"194224:1-194224:126", "194224:129-194224:206", "194224:208-194224:250", "194224:253-194224:309", "194224:312-194224:386",
"194224:389-194224:412", "194225:1-194225:23", "194225:26-194225:47", "194225:49-194225:85", "194225:88-194225:149",
"194270:56-194270:68", "194303:56-194303:66", "194303:69-194303:102", "194304:1-194304:43", "194304:46",
"194305:1-194305:84", "194314:52-194314:130", "194314:133-194314:300", "194315:1-194315:10", "194315:13-194315:314",
"194315:317-194315:428", "194315:431-194315:452", "194315:455-194315:467", "194317:1-194317:20", "194424:63-194424:141",
"194424:144-194424:195", "194424:198-194424:266", "194424:268-194424:421", "194424:424-194424:478", "194424:481-194424:531",
"194424:534-194424:553", "194424:556-194424:706", "194424:708", "194428:1-194428:85", "194428:87-194428:122",
"194428:125-194428:294", "194428:296-194428:465", "194429:1-194429:4", "194429:7-194429:54", "194429:57-194429:147",
"194429:150-194429:411", "194429:413-194429:742", "194429:745-194429:986", "194429:988-194429:1019", "194439:46-194439:77",
"194439:79-194439:106", "194455:45-194455:64", "194455:67-194455:140", "194455:142-194455:255", "194455:293-194455:303",
"194464:1-194464:127", "194464:130-194464:142", "194464:145-194464:210", "194479:1-194479:44", "194479:165-194479:232",
"194479:235-194479:262", "194479:265-194479:374", "194479:377-194479:431", "194479:434-194479:489", "194479:492-194479:529",
"194479:531-194479:566", "194480:1-194480:32", "194480:34-194480:205", "194480:207-194480:375", "194480:377-194480:387",
"194480:389-194480:759", "194480:762-194480:956", "194480:959-194480:1402", "194533:46-194533:379", "194533:382-194533:415",
"194533:417-194533:618", "194533:620-194533:872", "194619:31-194619:110", "194631:1-194631:42", "194631:44-194631:100",
"194631:102-194631:169", "194631:171-194631:222", "194643:1-194643:287", "194644:1-194644:168", "194644:171-194644:181",
"194644:184-194644:185", "194644:187-194644:319", "194644:321-194644:421", "194691:61-194691:104", "194691:107-194691:155",
"194691:158-194691:251", "194691:254-194691:268", "194691:271-194691:272", "194691:275-194691:289", "194691:292-194691:313",
"194699:1-194699:30", "194699:32-194699:52", "194699:55-194699:64", "194699:67-194699:71", "194699:73-194699:154",
"194699:157-194699:215", "194699:218-194699:238", "194699:241-194699:259", "194702:1-194702:138", "194702:141-194702:191",
"194704:1-194704:41", "194704:44-194704:545", "194704:548-194704:592", "194711:1-194711:7", "194711:9-194711:619",
"194712:1-194712:56", "194712:61-194712:418", "194712:420-194712:625", "194712:627-194712:759", "194735:44-194735:71",
"194735:74-194735:101", "194735:104-194735:130", "194778:60-194778:118", "194778:120-194778:219", "194789:1-194789:18",
"194789:21-194789:32", "194789:34-194789:80", "194789:82-194789:166", "194789:168-194789:269", "194789:272-194789:405",
"194789:409-194789:414", "194789:417-194789:427", "194789:430-194789:566", "194790:1-194790:45", "194825:72-194825:117",
"194825:120-194825:221", "194896:34-194896:55", "194896:58-194896:79", "194896:82-194896:103", "194897:1-194897:6",
"194897:8-194897:78", "194897:80-194897:96", "194897:98-194897:102", "194912:53-194912:70", "194912:72-194912:96",
"194912:98-194912:444", "194912:446-194912:450", "194912:453-194912:467", "194912:470-194912:561", "194912:564-194912:660",
"194912:663-194912:813", "194912:815-194912:840", "194912:843-194912:864", "194912:866-194912:1004", "194912:1007-194912:1025",
"194912:1027-194912:1067", "194912:1069-194912:1137", "194912:1140-194912:1166", "194912:1168-194912:1249", "194912:1251-194912:1304",
"194912:1307-194912:1444", "194912:1447-194912:1487", "194912:1489-194912:1503", "194912:1506-194912:1662", "194914:1-194914:38",
"194915:1-194915:74", "195013:94-195013:144", "195013:146-195013:185", "195013:187-195013:206", "195013:208-195013:299",
"195013:302-195013:324", "195013:326-195013:366", "195013:369-195013:447", "195013:450-195013:526", "195013:528-195013:541",
"195014:1-195014:6", "195014:9-195014:119", "195014:121-195014:148", "195015:1-195015:13", "195016:1-195016:21",
"195016:23-195016:55", "195016:58-195016:63", "195016:65-195016:174", "195016:177-195016:184", "195016:186-195016:241",
"195016:243-195016:246", "195016:248-195016:251", "195016:254-195016:367", "195016:370-195016:422", "195016:425-195016:560",
"195016:563-195016:569", "195099:70-195099:144", "195099:147-195099:186", "195099:189-195099:208", "195099:211-195099:224",
"195099:227-195099:248", "195109:98-195109:241", "195112:1-195112:12", "195112:15-195112:26", "195113:1-195113:209",
"195113:212-195113:388", "195113:391-195113:403", "195113:406-195113:419", "195113:422-195113:492", "195113:495-195113:579",
"195114:1-195114:69", "195114:72-195114:103", "195115:1-195115:7", "195115:10-195115:22", "195147:132-195147:282",
"195147:285-195147:294", "195147:297-195147:331", "195147:334-195147:363", "195147:366-195147:442", "195147:445-195147:536",
"195147:539-195147:559", "195163:72-195163:138", "195163:140-195163:224", "195163:227-195163:240", "195163:243",
"195163:246-195163:347", "195164:1-195164:64", "195165:1-195165:4", "195165:7-195165:41", "195165:44-195165:54",
"195165:56-195165:153", "195165:156-195165:260", "195165:263-195165:266", "195251:1-195251:131", "195251:134-195251:137",
"195251:140-195251:152", "195251:154-195251:165", "195251:167-195251:242", "195303:109-195303:191", "195303:194-195303:277",
"195303:280-195303:310", "195303:312-195303:316", "195303:318-195303:409", "195304:1-195304:3", "195304:6-195304:22",
"195304:27-195304:80", "195304:83-195304:100", "195304:103-195304:154", "195304:157-195304:341", "195304:344-195304:588",
"195304:590-195304:727", "195304:729-195304:1003", "195304:1006-195304:1079", "195304:1083-195304:1140", "195304:1143-195304:1229",
"195378:90-195378:117", "195378:120-195378:127", "195378:130-195378:185", "195378:187-195378:204", "195378:206-195378:302",
"195378:305-195378:542", "195378:544-195378:565", "195378:567-195378:645", "195378:647-195378:701", "195378:703-195378:734",
"195378:737-195378:1120", "195378:1122-195378:1133", "195390:1", "195390:4-195390:27", "195390:30-195390:145",
"195390:147-195390:183", "195390:186-195390:187", "195390:190-195390:208", "195390:210-195390:213", "195390:215-195390:400",
"195396:49-195396:55", "195396:58-195396:63", "195396:66-195396:131", "195397:1-195397:10", "195397:12-195397:89",
"195397:92-195397:120", "195397:123-195397:141", "195397:143-195397:251", "195397:253", "195397:256-195397:475",
"195397:478-195397:525", "195397:527-195397:608", "195397:611-195397:776", "195397:779-195397:970", "195397:972-195397:1121",
"195397:1123-195397:1181", "195397:1184-195397:1198", "195397:1200-195397:1209", "195398:3-195398:137", "195398:139-195398:494",
"195398:497-195398:585", "195398:587-195398:817", "195398:820-195398:824", "195398:827-195398:1225", "195398:1228-195398:1307",
"195398:1309-195398:1712", "195398:1721-195398:1736", "195398:1741-195398:1752", "195398:1767-195398:1795", "195399:1-195399:192",
"195399:194-195399:382", "195530:1-195530:80", "195530:82-195530:104", "195530:107-195530:156", "195530:159-195530:300",
"195530:302-195530:405", "195540:68-195540:123", "195540:126-195540:137", "195540:140-195540:283", "195540:286-195540:319",
"195551:91-195551:106", "195552:1-195552:21", "195552:23-195552:27", "195552:30-195552:147", "195552:149-195552:155",
"195552:158-195552:182", "195552:185-195552:287", "195552:290-195552:349", "195552:352-195552:469", "195552:472-195552:815",
"195552:818-195552:823", "195552:825-195552:883", "195552:885-195552:1152", "195552:1154-195552:1300", "195552:1303-195552:1789",
"195633:40-195633:42", "195647:1-195647:41", "195649:1-195649:69", "195649:72-195649:151", "195649:154-195649:181",
"195649:183-195649:247", "195655:1-195655:129", "195655:131-195655:184", "195655:186-195655:260", "195655:263-195655:350",
"195655:353-195655:446", "195655:448-195655:483", "195655:485-195655:498", "195656:1-195656:362", "195658:1-195658:37",
"195658:40-195658:362", "195658:364-195658:382", "195658:384-195658:386", "195749:1-195749:8", "195749:10-195749:33",
"195749:36-195749:131", "195757:1-195757:82", "195757:85-195757:115", "195757:118-195757:161", "195757:163-195757:206",
"195758:1-195758:18", "195774:1-195774:13", "195774:16-195774:137", "195774:139-195774:151", "195774:154-195774:162",
"195774:164-195774:256", "195774:258-195774:276", "195774:279-195774:362", "195774:365-195774:466", "195774:469-195774:618",
"195774:620-195774:649", "195774:651-195774:830", "195775:1-195775:57", "195775:60-195775:100", "195775:103-195775:170",
"195776:1-195776:63", "195776:66-195776:283", "195776:286-195776:337", "195776:340-195776:399", "195776:401-195776:409",
"195776:411-195776:477", "195841:74-195841:85", "195868:1-195868:88", "195868:90-195868:107", "195868:110-195868:205",
"195915:1-195915:109", "195915:111-195915:275", "195915:278-195915:390", "195915:393-195915:417", "195915:419-195915:429",
"195915:432-195915:505", "195915:507-195915:747", "195915:749-195915:785", "195915:787-195915:828", "195915:830-195915:850",
"195916:1-195916:16", "195916:19-195916:68", "195916:71-195916:212", "195917:1-195917:4", "195918:1-195918:44",
"195918:46", "195918:49-195918:64", "195919:1-195919:15", "195923:1-195923:14", "195925:1-195925:12",
"195926:1", "195926:3-195926:19", "195926:21-195926:34", "195929:1-195929:29", "195930:1-195930:77",
"195930:80-195930:176", "195930:179-195930:526", "195930:529-195930:596", "195937:1-195937:28", "195937:31-195937:186",
"195937:188-195937:396", "195947:23-195947:62", "195947:64-195947:88", "195948:51-195948:116", "195948:119-195948:144",
"195948:147", "195948:150-195948:352", "195948:355-195948:369", "195948:372-195948:402", "195948:404-195948:500",
"195948:503-195948:540", "195948:543-195948:565", "195948:567-195948:602", "195948:605-195948:615", "195950:1-195950:71",
"195950:73-195950:138", "195950:141-195950:169", "195950:172-195950:332", "195950:335-195950:350", "195950:353-195950:382",
"195950:385-195950:421", "195950:424-195950:450", "195950:453-195950:483", "195950:485-195950:616", "195950:619-195950:715",
"195950:718-195950:787", "195950:789-195950:800", "195950:803-195950:829", "195950:831", "195950:833-195950:1587",
"195963:54-195963:58", "195970:44-195970:49", "195970:51-195970:85", "196019:54-196019:68", "196027:1-196027:55",
"196027:58-196027:119", "196027:121-196027:155", "196027:158-196027:186", "196046:12-196046:40", "196047:1-196047:64",
"196047:70-196047:75", "196048:1-196048:44", "196048:46-196048:48", "196197:58-196197:122", "196197:125-196197:179",
"196197:181-196197:311", "196197:313-196197:516", "196197:519-196197:562", "196199:1-196199:33", "196199:36-196199:83",
"196199:86-196199:118", "196199:121-196199:147", "196199:150-196199:237", "196199:239-196199:285", "196199:287-196199:534",
"196200:1-196200:68", "196202:3-196202:61", "196202:64-196202:108", "196203:1-196203:102", "196203:107-196203:117",
"196218:55-196218:199", "196218:201-196218:224", "196218:226-196218:393", "196218:396-196218:494", "196218:496-196218:741",
"196218:744-196218:752", "196218:754-196218:757", "196218:759-196218:820", "196239:1-196239:59", "196239:62-196239:154",
"196239:157-196239:272", "196239:274-196239:373", "196239:375-196239:432", "196239:435-196239:465", "196239:468-196239:647",
"196239:650-196239:706", "196239:709-196239:1025", "196249:63-196249:77", "196249:80-196249:99", "196250:1-196250:2",
"196250:5-196250:265", "196250:267-196250:426", "196252:1-196252:35", "196334:59-196334:111", "196334:113-196334:123",
"196334:126-196334:132", "196334:135-196334:167", "196334:170-196334:193", "196334:196-196334:257", "196334:259-196334:267",
"196334:270-196334:289", "196334:292-196334:342", "196349:65-196349:84", "196349:86-196349:154", "196349:157-196349:244",
"196349:246-196349:258", "196357:1-196357:4", "196359:1-196359:2", "196362:1-196362:88", "196363:1-196363:8",
"196363:11-196363:34", "196364:1-196364:93", "196364:96-196364:136", "196364:139-196364:365", "196364:368-196364:380",
"196364:382-196364:601", "196364:603-196364:795", "196364:798-196364:884", "196364:887-196364:1196", "196364:1199-196364:1200",
"196364:1203-196364:1299", "196437:1", "196437:3-196437:74", "196437:77-196437:169", "196438:1-196438:181",
"196438:184-196438:699", "196438:701-196438:1269", "196452:82-196452:112", "196452:114-196452:490", "196452:493-196452:586",
"196452:589-196452:618", "196452:622-196452:668", "196452:671-196452:716", "196452:718-196452:726", "196452:728-196452:956",
"196452:958-196452:1004", "196452:1007-196452:1091", "196453:1-196453:74", "196453:77-196453:145", "196453:147-196453:669",
"196453:673-196453:714", "196453:717-196453:799", "196453:802-196453:988", "196453:991-196453:1178", "196453:1180",
"196453:1182-196453:1248", "196453:1250-196453:1528", "196453:1531-196453:1647", "196495:114-196495:180", "196495:182-196495:272",
"196509:1-196509:68", "196531:62-196531:150", "196531:152-196531:253", "196531:256-196531:285", "196531:288-196531:302",
"196531:305-196531:422", "196531:425-196531:440", "198049:1-198049:11", "198049:14-198049:57", "198050:2-198050:155",
"198063:1-198063:37", "198063:40-198063:72", "198063:74-198063:124", "198063:127-198063:294", "198116:36-198116:52",
"198116:54-198116:55", "198116:58-198116:96", "198116:98-198116:112", "198207:1-198207:97", "198208:1-198208:92",
"198208:94-198208:134", "198208:137-198208:147", "198208:150-198208:209", "198210:1-198210:221", "198212:1-198212:574",
"198213:1-198213:107", "198215:1-198215:12", "198230:1-198230:33", "198230:36-198230:57", "198230:60-198230:235",
"198230:237-198230:324", "198230:326-198230:388", "198230:390-198230:459", "198230:462-198230:625", "198230:627-198230:651",
"198230:653-198230:805", "198230:808-198230:811", "198230:814-198230:948", "198230:950-198230:1090", "198230:1093-198230:1103",
"198230:1106-198230:1332", "198230:1335-198230:1380", "198249:1-198249:7", "198269:3-198269:198", "198271:1-198271:91",
"198271:93-198271:170", "198271:173-198271:299", "198271:301-198271:450", "198271:453-198271:513", "198271:516-198271:616",
"198271:619-198271:628", "198271:631-198271:791", "198271:793-198271:797", "198272:1-198272:185", "198272:188-198272:245",
"198272:248-198272:314", "198272:317-198272:433", "198272:436-198272:444", "198272:454-198272:620", "198346:44-198346:47",
"198372:57-198372:110", "198485:68-198485:109", "198485:112-198485:134", "198485:136-198485:181", "198485:184-198485:239",
"198487:1-198487:145", "198487:147-198487:514", "198487:517-198487:668", "198487:671-198487:733", "198487:736-198487:757",
"198487:760-198487:852", "198487:854-198487:994", "198487:997-198487:1434", "198487:1437-198487:1610", "198522:65-198522:144",
"198522:147-198522:208", "198941:102-198941:189", "198941:191-198941:220", "198941:222-198941:241", "198941:243-198941:249",
"198941:252-198941:284", "198954:108-198954:156", "198954:159-198954:277", "198955:1-198955:45", "198955:47-198955:50",
"198955:53-198955:220", "198955:223-198955:269", "198955:271-198955:284", "198955:286-198955:338", "198955:340-198955:580",
"198955:583-198955:742", "198955:744-198955:910", "198955:913-198955:946", "198955:949-198955:1162", "198955:1165-198955:1169",
"198955:1172-198955:1182", "198955:1185-198955:1188", "198955:1190-198955:1246", "198955:1249-198955:1304", "198955:1306-198955:1467",
"198955:1470-198955:1485", "198955:1487-198955:1552", "198969:58-198969:81", "198969:84-198969:247", "198969:249-198969:323",
"198969:325-198969:365", "198969:367-198969:413", "198969:416-198969:466", "198969:468-198969:643", "198969:646-198969:918",
"198969:920-198969:1011", "198969:1013-198969:1175", "198969:1178-198969:1236", "198969:1239-198969:1253", "199008:75-199008:93",
"199008:95-199008:121", "199008:124-199008:208", "199008:211-199008:331", "199008:333-199008:373", "199008:376-199008:482",
"199008:485-199008:605", "199008:608-199008:644", "199011:1-199011:11", "199011:13-199011:24", "199021:59-199021:88",
"199021:91-199021:128", "199021:130-199021:133", "199021:136-199021:309", "199021:311-199021:333", "199021:335-199021:410",
"199021:414-199021:469", "199021:471-199021:533", "199021:535-199021:563", "199021:565-199021:1223", "199021:1226-199021:1479",
"199021:1481-199021:1494", "199318:65-199318:138", "199319:1-199319:7", "199319:9-199319:223", "199319:226-199319:277",
"199319:280-199319:348", "199319:351-199319:358", "199319:360-199319:422", "199319:424-199319:490", "199319:492-199319:493",
"199319:496-199319:612", "199319:615-199319:642", "199319:645-199319:720", "199319:723-199319:728", "199319:730-199319:731",
"199319:734-199319:741", "199319:744-199319:752", "199319:754-199319:943", "199319:945-199319:997", "199336:1-199336:33",
"199336:36-199336:122", "199336:125-199336:231", "199336:234-199336:614", "199336:617-199336:789", "199336:791-199336:977",
"199356:95-199356:121", "199356:123-199356:168", "199356:171-199356:205", "199356:208-199356:231", "199409:25-199409:54",
"199409:56-199409:89", "199409:91-199409:204", "199409:206-199409:290", "199409:293-199409:583", "199409:586-199409:602",
"199409:604-199409:1014", "199409:1016-199409:1300", "199428:61-199428:197", "199428:200-199428:210", "199428:212-199428:382",
"199428:387-199428:414", "199428:417-199428:436", "199428:439-199428:530", "199428:533-199428:648", "199429:1-199429:28",
"199429:30-199429:36", "199429:39-199429:55", "199429:58-199429:101", "199429:103-199429:148", "199429:151-199429:154",
"199435:63-199435:106", "199435:109-199435:261", "199435:263-199435:579", "199435:582-199435:654", "199435:656-199435:696",
"199435:699-199435:1034", "199435:1037-199435:1144", "199435:1147-199435:1327", "199435:1330-199435:1411", "199435:1414-199435:1431",
"199435:1434-199435:1441", "199435:1444-199435:1487", "199435:1489-199435:1610", "199436:1-199436:113", "199436:116-199436:254",
"199436:257-199436:675", "199436:678-199436:748", "199564:1-199564:3", "199569:1-199569:2", "199569:5-199569:136",
"199569:139-199569:367", "199570:1-199570:17", "199571:1-199571:184", "199571:186-199571:360", "199571:363-199571:561",
"199572:1-199572:317", "199573:1-199573:22", "199574:1-199574:53", "199574:56-199574:153", "199574:156-199574:246",
"199608:60-199608:157", "199608:159-199608:209", "199608:211-199608:341", "199608:344-199608:390", "199608:392-199608:461",
"199608:464-199608:800", "199608:802-199608:1064", "199608:1067-199608:1392", "199608:1395-199608:1630", "199608:1633-199608:1904",
"199608:1907-199608:1962", "199608:1965-199608:2252", "199608:2255-199608:2422", "199698:72-199698:94", "199698:96-199698:127",
"199699:1-199699:154", "199699:157-199699:169", "199699:172-199699:410", "199699:412-199699:756", "199703:1-199703:94",
"199703:97-199703:482", "199703:485-199703:529", "199739:66-199739:133", "199751:103-199751:119", "199751:121-199751:127",
"199752:1-199752:141", "199752:144-199752:180", "199752:182-199752:186", "199752:188-199752:211", "199752:214-199752:322",
"199753:1-199753:59", "199754:1-199754:203", "199754:205-199754:325", "199754:328-199754:457", "199754:459-199754:607",
"199754:610-199754:613", "199754:615-199754:806", "199754:808-199754:998", "199804:78-199804:88", "199804:90-199804:181",
"199804:183-199804:235", "199804:238-199804:278", "199804:281-199804:290", "199804:292-199804:519", "199804:522-199804:575",
"199804:577-199804:628", "199804:631-199804:632", "199812:70-199812:141", "199812:144-199812:163", "199812:182-199812:211",
"199812:214-199812:471", "199812:474-199812:505", "199812:508-199812:557", "199812:560-199812:571", "199812:574-199812:623",
"199812:626-199812:751", "199812:754-199812:796", "199832:58-199832:62", "199832:65-199832:118", "199832:121-199832:139",
"199832:142-199832:286", "199833:1-199833:13", "199833:16-199833:103", "199833:105-199833:250", "199833:253-199833:493",
"199833:496-199833:794", "199833:797-199833:1032", "199833:1034-199833:1185", "199833:1188-199833:1239", "199834:1-199834:9",
"199834:11", "199834:14-199834:18", "199834:21-199834:54", "199834:56-199834:57", "199834:62-199834:65",
"199834:69-199834:284", "199834:286-199834:503", "199834:505-199834:942", "199862:59-199862:141", "199864:1-199864:87",
"199864:89", "199864:92-199864:103", "199864:106-199864:372", "199864:374-199864:385", "199864:388-199864:486",
"199867:1-199867:134", "199867:136-199867:172", "199867:174-199867:218", "199867:221-199867:320", "199868:1-199868:21",
"199875:70-199875:150", "199875:152-199875:334", "199876:1-199876:19", "199876:22-199876:95", "199876:97-199876:249",
"199876:252-199876:272", "199876:274-199876:340", "199876:343-199876:362", "199876:365-199876:376", "199877:1-199877:173",
"199877:175-199877:605", "199877:607-199877:701", "199877:703-199877:871", "199960:72-199960:139", "199960:141-199960:197",
"199960:204-199960:232", "199960:235-199960:363", "199960:365-199960:367", "199960:370-199960:380", "199960:383-199960:459",
"199960:461-199960:466", "199960:469-199960:485", "199961:1-199961:211", "199961:213-199961:287", "199967:60-199967:120",
"199967:122-199967:170", "199967:172-199967:198", "199973:73-199973:89", "200041:62-200041:83", "200041:85-200041:157",
"200041:162-200041:274", "200041:277-200041:318", "200041:321-200041:335", "200041:337-200041:386", "200041:388-200041:389",
"200041:392-200041:400", "200041:402-200041:568", "200041:571-200041:593", "200041:595-200041:646", "200041:649-200041:728",
"200041:731-200041:860", "200041:862-200041:930", "200041:932-200041:1096", "200042:1-200042:110", "200042:112-200042:536",
"200049:1-200049:177", "200075:76-200075:139", "200075:142-200075:232", "200075:256-200075:326", "200075:329-200075:422",
"200075:425-200075:431", "200075:434-200075:500", "200075:502-200075:605", "200091:67", "200091:70-200091:151",
"200091:154-200091:172", "200091:174-200091:187", "200091:190-200091:196", "200091:199-200091:201", "200091:204-200091:425",
"200091:428-200091:535", "200091:537-200091:607", "200091:610-200091:879", "200091:881-200091:943", "200091:946-200091:999",
"200091:1001-200091:1025", "200091:1027-200091:1132", "200091:1135-200091:1339", "200091:1341-200091:1433", "200091:1435-200091:1450",
"200091:1453-200091:1523", "200091:1526-200091:1664", "200091:1667-200091:1680", "200091:1683-200091:1710", "200152:74-200152:116",
"200160:52-200160:68", "200161:1-200161:97", "200161:100-200161:112", "200174:81-200174:84", "200177:1-200177:56",
"200178:1-200178:38", "200180:1-200180:18", "200186:1-200186:3", "200186:6-200186:24", "200188:1-200188:24",
"200188:27-200188:28", "200188:31-200188:76", "200188:79-200188:271", "200188:274-200188:352", "200190:1-200190:4",
"200190:6-200190:76", "200190:79-200190:143", "200190:146-200190:159", "200190:162-200190:256", "200190:258-200190:321",
"200190:324-200190:401", "200190:403-200190:453", "200190:456-200190:457", "200190:460-200190:565", "200190:567-200190:588",
"200190:591", "200190:593-200190:595", "200190:597-200190:646", "200190:649-200190:878", "200229:1-200229:33",
"200229:41-200229:219", "200229:222-200229:244", "200229:247-200229:290", "200229:293-200229:624", "200229:627-200229:629",
"200243:69-200243:103", "200243:106-200243:139", "200244:3-200244:304", "200244:307-200244:442", "200244:445-200244:507",
"200244:510-200244:619", "200245:1-200245:103", "200245:105-200245:128", "200245:131-200245:248", "200245:251-200245:357",
"200368:72-200368:180", "200369:1-200369:5", "200369:8-200369:61", "200369:64-200369:360", "200369:363-200369:439",
"200369:441-200369:578", "200369:580-200369:603", "200369:606-200369:684", "200369:686", "200381:8-200381:15",
"200381:18-200381:36", "200381:38-200381:89", "200381:91-200381:195", "200466:134-200466:274", "200473:96-200473:157",
"200473:159-200473:224", "200473:226-200473:304", "200473:306-200473:469", "200473:472-200473:524", "200473:527-200473:542",
"200473:545-200473:619", "200473:622-200473:688", "200473:691-200473:730", "200473:733-200473:738", "200473:740-200473:1324",
"200491:87-200491:107", "200491:110-200491:149", "200491:152-200491:157", "200491:160-200491:197", "200491:199-200491:237",
"200491:240-200491:270", "200491:273", "200491:276-200491:334", "200491:336-200491:360", "200491:363-200491:419",
"200515:97-200515:183", "200519:1-200519:111", "200519:114-200519:126", "200519:129-200519:136", "200519:138-200519:224",
"200519:227-200519:258", "200519:261-200519:350", "200519:353-200519:611", "200519:613-200519:747", "200525:77-200525:149",
"200525:151-200525:164", "200525:166-200525:190", "200525:193-200525:276", "200525:278-200525:311", "200525:314-200525:464",
"200525:467-200525:488", "200525:491-200525:674", "200525:676-200525:704", "200525:707-200525:755", "200525:757-200525:895",
"200525:898-200525:937", "200525:939-200525:990", "200532:1-200532:37", "200599:75-200599:129", "200599:132-200599:137",
"200600:1-200600:183", "200600:186-200600:299", "200600:302-200600:313", "200600:316-200600:324", "200600:327-200600:334",
"200600:336-200600:397", "200600:399-200600:417", "200600:420-200600:526", "200600:529-200600:591", "200600:594-200600:596",
"200600:598-200600:609", "200600:611-200600:660", "200600:663-200600:823", "200600:826-200600:900", "200600:902-200600:943",
"200600:945-200600:1139", "200961:1-200961:115", "200976:94-200976:164", "200990:75-200990:143", "200991:1-200991:42",
"200991:44", "200991:47-200991:80", "200991:83-200991:175", "200991:178-200991:181", "200991:184-200991:252",
"200991:255-200991:632", "200991:635-200991:916", "200991:918-200991:1017", "200991:1019-200991:1048", "200992:1-200992:405",
"200992:408-200992:434", "200992:436-200992:581", "201062:78-201062:268", "201097:83-201097:136", "201097:138-201097:245",
"201097:248-201097:300", "201097:303-201097:370", "201097:372-201097:429", "201097:432-201097:497", "201114:1-201114:14",
"201115:1-201115:73", "201159:70-201159:211", "201164:1-201164:8", "201164:10-201164:94", "201164:96-201164:125",
"201164:128-201164:178", "201164:180-201164:198", "201164:200-201164:271", "201164:274-201164:416", "201164:418",
"201168:1-201168:37", "201168:39-201168:275", "201168:278-201168:481", "201168:483-201168:558", "201168:560-201168:730",
"201173:1-201173:194", "201173:197-201173:586", "201174:1-201174:214", "201174:216-201174:263", "201174:265-201174:339",
"201174:342-201174:451", "201191:75-201191:98", "201191:100-201191:216", "201191:218-201191:389", "201191:392-201191:492",
"201191:494-201191:506", "201191:509-201191:585", "201191:587-201191:594", "201191:597-201191:607", "201191:609-201191:794",
"201191:796-201191:838", "201191:841-201191:974", "201191:977-201191:1105", "201191:1108-201191:1117", "201191:1120-201191:1382",
"201191:1385-201191:1386", "201193:1-201193:19", "201196:1-201196:238", "201196:241-201196:278", "201196:286-201196:299",
"201196:302-201196:338", "201196:341-201196:515", "201196:518-201196:720", "201196:723-201196:789", "201196:803-201196:841",
"201197:1-201197:23", "201202:1-201202:437", "201229:1-201229:5", "201229:8-201229:26", "201229:29-201229:73",
"201278:62-201278:163", "201278:166-201278:229", "201278:232-201278:256", "201278:259-201278:316", "201278:318-201278:595",
"201278:598-201278:938", "201278:942-201278:974", "201278:976-201278:1160", "201278:1163-201278:1304", "201278:1306-201278:1793",
"201278:1796-201278:1802", "201278:1805-201278:1906", "201278:1909-201278:1929", "201278:1932-201278:2174", "201554:70-201554:86",
"201554:88-201554:114", "201554:116-201554:126", "201602:76-201602:81", "201602:83-201602:194", "201602:196-201602:494",
"201602:496-201602:614", "201602:617-201602:635", "201611:87-201611:145", "201611:149-201611:182", "201611:184-201611:186",
"201613:1-201613:42", "201613:44-201613:49", "201613:53-201613:210", "201613:213-201613:215", "201613:218-201613:225",
"201613:228-201613:646", "201624:83-201624:92", "201624:95-201624:240", "201624:270", "201625:211-201625:312",
"201625:315-201625:348", "201625:351-201625:416", "201625:418-201625:588", "201625:591-201625:671", "201625:673-201625:758",
"201625:760-201625:791", "201625:793-201625:944", "201657:77-201657:93", "201657:95-201657:108", "201657:110-201657:118",
"201658:1-201658:19", "201658:21-201658:118", "201658:121-201658:136", "201658:139-201658:288", "201668:78-201668:157",
"201669:1-201669:9", "201669:12-201669:136", "201669:139-201669:141", "201669:143-201669:165", "201671:1-201671:120",
"201671:122-201671:174", "201671:177-201671:462", "201671:464-201671:482", "201671:485-201671:499", "201671:501-201671:545",
"201671:547-201671:571", "201671:574-201671:614", "201671:617-201671:766", "201671:768-201671:896", "201671:899-201671:911",
"201671:914-201671:1007", "201678:1-201678:120", "201679:1-201679:110", "201679:112-201679:241", "201679:244-201679:298",
"201679:302-201679:321", "201679:324-201679:461", "201679:463-201679:483", "201692:78-201692:81", "201692:83-201692:179",
"201705:65-201705:73", "201705:75-201705:109", "201705:111-201705:187", "201706:1-201706:62", "201707:1-201707:23",
"201707:26-201707:42", "201707:45-201707:115", "201707:118-201707:130", "201707:133-201707:160", "201707:163-201707:276",
"201707:279-201707:471", "201707:473-201707:511", "201707:514-201707:545", "201707:547-201707:570", "201707:572-201707:622",
"201707:625-201707:735", "201707:738-201707:806", "201707:809-201707:876", "201707:879-201707:964", "201708:1-201708:79",
"201718:58-201718:108", "201727:67-201727:185", "201729:6-201729:20", "201729:22-201729:75", "201729:77-201729:126",
"201729:129-201729:154", "201729:156-201729:216", "201729:219-201729:244", "201794:58-201794:94", "201802:68-201802:209",
"201802:211-201802:214", "201802:216-201802:220", "201802:223-201802:288", "201802:290-201802:296", "201816:1-201816:72",
"201816:74-201816:105", "201816:107-201816:157", "201817:1-201817:274", "201818:1", "201819:1-201819:94",
"201819:96-201819:241", "201824:1-201824:139", "201824:141-201824:176", "201824:179-201824:286", "201824:289-201824:492",
"202012:98-202012:121", "202012:126-202012:131", "202013:1-202013:2", "202013:5-202013:35", "202013:38-202013:57",
"202014:1-202014:5", "202014:8-202014:14", "202014:16-202014:18", "202014:20-202014:77", "202014:79-202014:102",
"202014:104-202014:174", "202014:177-202014:190", "202014:192-202014:196", "202016:1-202016:48", "202016:51-202016:134",
"202016:137-202016:177", "202016:179-202016:743", "202016:745-202016:831", "202016:834-202016:890", "202016:893-202016:896",
"202016:898-202016:932", "202016:934-202016:1010", "202044:84-202044:101", "202044:104-202044:266", "202044:268-202044:461",
"202044:463-202044:466", "202045:1-202045:30", "202045:33-202045:72", "202045:75-202045:528", "202045:531-202045:601",
"202045:603-202045:785", "202045:788-202045:809", "202045:822-202045:823", "202054:6-202054:266", "202054:268-202054:489",
"202054:492-202054:605", "202054:608-202054:631", "202060:76-202060:142", "202060:144-202060:154", "202060:156-202060:244",
"202060:246-202060:497", "202060:499-202060:642", "202060:644-202060:682", "202060:684-202060:743", "202060:746-202060:936",
"202074:66-202074:174", "202075:1-202075:18", "202075:21-202075:187", "202075:189-202075:214", "202075:217-202075:247",
"202075:250-202075:342", "202075:345-202075:406", "202075:409-202075:497", "202075:500-202075:537", "202075:539",
"202075:542-202075:560", "202075:562-202075:615", "202075:618-202075:628", "202084:83-202084:156", "202084:159-202084:177",
"202084:179-202084:180", "202084:182-202084:239", "202087:1-202087:25", "202087:28-202087:208", "202087:210-202087:357",
"202087:359-202087:652", "202087:655-202087:853", "202087:856-202087:1093", "202088:1-202088:286", "202093:1-202093:104",
"202093:107-202093:320", "202093:322-202093:360", "202116:59-202116:60", "202178:67-202178:78", "202178:80-202178:88",
"202178:91-202178:177", "202178:180-202178:186", "202178:188-202178:337", "202178:340-202178:377", "202178:379-202178:425",
"202178:428-202178:475", "202178:478-202178:548", "202178:551-202178:717", "202178:720-202178:965", "202178:967-202178:1444",
"202178:1447-202178:1505", "202178:1508-202178:1519", "202178:1522-202178:1555", "202205:94-202205:114", "202209:1-202209:48",
"202209:51-202209:142", "202237:39-202237:128", "202237:131", "202237:134-202237:219", "202237:222-202237:235",
"202237:238-202237:275", "202237:277-202237:289", "202237:291-202237:316", "202237:319-202237:419", "202237:422-202237:538",
"202237:540-202237:936", "202237:939-202237:950", "202237:952-202237:976", "202237:979-202237:1079", "202272:76-202272:112",
"202272:115-202272:141", "202272:144-202272:185", "202272:188-202272:205", "202272:208-202272:305", "202272:307-202272:313",
"202272:315-202272:371", "202272:436-202272:480", "202272:483-202272:555", "202272:558-202272:577", "202272:579-202272:683",
"202272:686-202272:705", "202272:707-202272:740", "202272:742-202272:890", "202272:937-202272:1295", "202272:1299-202272:1481",
"202299:68-202299:84", "202299:87-202299:141", "202299:143-202299:193", "202299:196-202299:358", "202299:361-202299:379",
"202299:382-202299:414", "202299:416-202299:452", "202299:455-202299:555", "202305:1-202305:89", "202305:92-202305:130",
"202305:133-202305:323", "202314:67-202314:104", "202314:107-202314:265", "202314:268-202314:278", "202328:46-202328:89",
"202328:92-202328:156", "202328:158-202328:276", "202328:278-202328:291", "202328:294-202328:434", "202328:437-202328:460",
"202328:463-202328:586", "202328:588-202328:610", "202328:612-202328:614", "202333:1-202333:235", "202389:81-202389:182",
"202389:185-202389:190", "202389:192-202389:199", "202469:87-202469:158", "202469:160-202469:174", "202469:177-202469:352",
"202472:1-202472:96", "202472:99-202472:112", "202477:1-202477:129", "202477:131-202477:150", "202478:1-202478:177",
"202478:180-202478:183", "202478:186-202478:219", "202478:222-202478:360", "202478:362-202478:506", "202478:509-202478:531",
"202478:534-202478:718", "202478:720-202478:927", "202478:929-202478:973", "202478:975-202478:1029", "202478:1031-202478:1186",
"202478:1189-202478:1212", "202478:1215-202478:1248", "202504:77-202504:96", "202504:99-202504:133", "202504:135-202504:182",
"202504:184-202504:211", "202504:213-202504:241", "202504:243-202504:392", "202504:395-202504:527", "202504:529-202504:617",
"202504:620-202504:715", "202504:718-202504:763", "202504:766-202504:1172", "202504:1174-202504:1247", "202504:1250-202504:1471",
"202504:1474-202504:1679", "202504:1682-202504:1704", "202972:1-202972:30", "202972:33-202972:184", "202972:186-202972:290",
"202972:292-202972:295", "202972:298-202972:371", "202972:374-202972:429", "202972:431-202972:544", "202973:1-202973:234",
"202973:237-202973:305", "202973:308-202973:437", "202973:439-202973:530", "202973:532-202973:541", "202973:544-202973:552",
"202973:555-202973:851", "202973:853-202973:1408", "203002:77-203002:128", "203002:130-203002:141", "203002:144-203002:207",
"203002:209-203002:267", "203002:270-203002:360", "203002:362-203002:501", "203002:504-203002:641", "203002:643-203002:669",
"203002:671", "203002:674-203002:717", "203002:720-203002:1034", "203002:1037-203002:1070", "203002:1073-203002:1370",
"203002:1372-203002:1392", "203002:1395-203002:1410", "203002:1413-203002:1596", "203709:1-203709:121", "203742:1-203742:29",
"203777:103-203777:113", "203830:82-203830:182", "203832:1-203832:11", "203833:1-203833:70", "203833:73-203833:128",
"203834:1-203834:40", "203835:1-203835:70", "203835:73-203835:358", "203853:122-203853:222", "203894:82-203894:272",
"203894:275-203894:477", "203894:480-203894:902", "203894:905-203894:1319", "203909:79-203909:113", "203909:116-203909:117",
"203909:120-203909:140", "203909:143-203909:382", "203912:1-203912:306", "203912:308-203912:566", "203912:569-203912:609",
"203912:611-203912:698", "203912:701-203912:820", "203912:823-203912:865", "203912:867-203912:1033", "203912:1035-203912:1321",
"203987:1-203987:9", "203987:12-203987:241", "203987:243-203987:339", "203987:342-203987:781", "203987:784-203987:1014",
"203992:1-203992:15", "203994:1-203994:56", "203994:59-203994:136", "203994:139-203994:304", "203994:306-203994:342",
"203994:344-203994:425", "204100:117-204100:139", "204101:1-204101:74", "204113:82-204113:96", "204113:98-204113:102",
"204113:105-204113:127", "204113:129-204113:191", "204113:194-204113:258", "204113:261-204113:327", "204113:329-204113:388",
"204113:390-204113:400", "204113:402-204113:583", "204113:585-204113:690", "204114:1-204114:358", "204238:23-204238:52",
"204238:55", "204250:92-204250:118", "204250:121-204250:177", "204250:179-204250:285", "204250:287-204250:336",
"204250:339-204250:400", "204250:403-204250:521", "204250:524-204250:543", "204250:546-204250:682", "204250:684-204250:801",
"204511:1-204511:56", "204541:5-204541:39", "204541:42", "204541:44-204541:139", "204541:142-204541:149",
"204541:151-204541:204", "204544:1-204544:11", "204544:13-204544:93", "204544:96-204544:195", "204544:197-204544:224",
"204544:226-204544:334", "204544:337-204544:426", "204552:1-204552:9", "204553:1-204553:51", "204553:53-204553:60",
"204553:63-204553:101", "204554:1-204554:5", "204554:7-204554:221", "204554:224-204554:455", "204554:458-204554:470",
"204554:472-204554:481", "204554:483-204554:514", "204555:1-204555:329", "204555:331-204555:334", "204563:91-204563:99",
"204563:102-204563:178", "204563:180-204563:219", "204563:222-204563:229", "204563:231-204563:364", "204563:366",
"204563:369-204563:470", "204563:473-204563:524", "204563:527-204563:571", "204564:1-204564:84", "204564:87-204564:89",
"204564:92-204564:159", "204564:161-204564:187", "204564:190-204564:191", "204564:193-204564:293", "204564:296-204564:315",
"204564:317-204564:340", "204564:343-204564:427", "204564:429-204564:434", "204564:437-204564:735", "204564:737-204564:855",
"204564:858-204564:1206", "204564:1209-204564:1248", "204564:1251-204564:1284", "204565:1-204565:48", "204566:1-204566:12",
"204567:1-204567:38", "204576:49-204576:192", "204576:195-204576:301", "204577:1-204577:46", "204577:49-204577:64",
"204577:67-204577:105", "204577:107-204577:170", "204577:173-204577:181", "204577:183-204577:193", "204577:196-204577:653",
"204577:656-204577:669", "204577:671-204577:740", "204577:742-204577:913", "204577:915-204577:1057", "204577:1059-204577:1115",
"204577:1117-204577:1282", "204599:73-204599:83", "204599:85-204599:94", "204599:97-204599:121", "204599:124-204599:125",
"204599:128-204599:173", "204599:175-204599:240", "204599:243-204599:245", "204599:248-204599:264", "204599:266-204599:292",
"204599:294-204599:334", "204601:1-204601:25", "204601:28-204601:62", "204601:65-204601:80", "204601:83-204601:89",
"204601:92-204601:290", "204601:292-204601:563", "204601:565-204601:591", "204601:593-204601:652", "204601:655-204601:780",
"204601:783-204601:812", "204601:814-204601:892", "204601:894-204601:984", "204601:986-204601:1003", "204601:1006-204601:1038",
"204601:1040-204601:1088", "204601:1091-204601:1102", "204601:1105-204601:1161", "204601:1164-204601:1250", "205086:95-205086:149",
"205111:88-205111:390", "205111:392-205111:441", "205111:444-205111:446", "205158:81-205158:289", "205158:292-205158:313",
"205158:315-205158:473", "205158:476-205158:591", "205158:594-205158:595", "205158:597-205158:612", "205158:615-205158:663",
"205158:665-205158:667", "205158:672-205158:685", "205158:687-205158:733", "205193:80-205193:109", "205193:111-205193:349",
"205193:352-205193:486", "205193:488-205193:650", "205193:652-205193:712", "205193:714-205193:902", "205217:1-205217:12",
"205217:16-205217:111", "205217:113-205217:171", "205217:174-205217:250", "205217:253-205217:318", "205233:94-205233:153",
"205236:1-205236:190", "205236:193-205236:207", "205236:209-205236:260", "205236:263-205236:331", "205236:334-205236:352",
"205238:1-205238:6", "205238:9-205238:199", "205238:202-205238:254", "205238:256-205238:304", "205238:306-205238:355",
"205238:358-205238:381", "205238:384-205238:596", "205238:598-205238:617", "205303:35-205303:54", "205303:90-205303:132",
"205303:135-205303:144", "205310:76-205310:306", "205310:309-205310:313", "205310:316", "205310:319-205310:321",
"205310:324-205310:457", "205310:460-205310:559", "205311:1-205311:85", "205311:88-205311:92", "205311:95-205311:183",
"205311:186-205311:395", "205311:397-205311:592", "205311:595-205311:910", "205311:913-205311:1260", "205339:71-205339:175",
"205339:178-205339:213", "205339:216-205339:230", "205339:233-205339:262", "205339:265-205339:404", "205344:1-205344:83",
"205344:86-205344:104", "205344:106-205344:359", "205344:362-205344:431", "205344:433-205344:949", "205344:951-205344:967",
"205344:969-205344:1127", "205344:1129-205344:1346", "205344:1348-205344:1586", "205515:82-205515:201", "205515:203-205515:216",
"205519:1-205519:47", "205519:50-205519:172", "205519:175-205519:367", "205519:370-205519:386", "205519:389-205519:472",
"205526:1-205526:269", "205526:272-205526:277", "205526:280-205526:332", "205614:1-205614:4", "205614:7-205614:40",
"205617:1-205617:29", "205617:32-205617:102", "205617:105-205617:123", "205617:125-205617:140", "205617:143-205617:264",
"205617:266-205617:448", "205617:451-205617:532", "205617:534-205617:547", "205618:1-205618:12", "205620:1-205620:175",
"205666:60-205666:119", "205666:122-205666:165", "205666:168-205666:259", "205666:261-205666:322", "205666:325-205666:578",
"205666:580-205666:594", "205666:597-205666:721", "205666:724-205666:739", "205667:1-205667:165", "205667:168-205667:282",
"205667:285-205667:318", "205667:321-205667:412", "205667:415-205667:689", "205667:692-205667:751", "205667:754-205667:774",
"205667:777-205667:1109", "205683:76-205683:82", "205683:85-205683:178", "205683:181-205683:198", "205683:201-205683:305",
"205690:1-205690:40", "205694:1-205694:205", "205694:208-205694:230", "205694:233-205694:347", "205694:350-205694:452",
"205694:455-205694:593", "205694:595-205694:890", "205718:49-205718:75", "205718:78-205718:97", "205718:100-205718:103",
"205718:105-205718:176", "205718:178-205718:338", "205718:341-205718:361", "205718:363-205718:524", "205718:527-205718:531",
"205718:534-205718:589", "205718:591-205718:694", "205774:1-205774:80", "205777:1-205777:8", "205781:1-205781:89",
"205781:91-205781:197", "205781:200-205781:502", "205826:80-205826:232", "205826:235-205826:303", "205826:306-205826:468",
"205833:84-205833:86", "205833:89-205833:121", "205833:123-205833:155", "205833:157-205833:165", "205833:167-205833:173",
"205833:176-205833:219", "205833:221-205833:267", "205833:270-205833:312", "205833:315-205833:346", "205833:350-205833:355",
"205833:360-205833:366", "205834:1-205834:12", "205834:14-205834:195", "205908:68-205908:200", "205908:202-205908:209",
"205921:22-205921:73", "205921:76-205921:268", "205921:271-205921:394", "205921:397-205921:401", "205921:410-205921:428",
"205921:431-205921:498", "205921:500-205921:571", "205921:574-205921:779", "205921:782-205921:853", "206066:89-206066:146",
"206088:86-206088:159", "206088:161-206088:178", "206088:181-206088:199", "206088:202-206088:286", "206102:83-206102:116",
"206102:120-206102:130", "206102:133-206102:208", "206102:211-206102:235", "206102:238-206102:246", "206102:249-206102:278",
"206102:281-206102:349", "206187:107-206187:169", "206187:172-206187:242", "206187:245-206187:288", "206187:290-206187:340",
"206187:343-206187:427", "206187:429-206187:435", "206187:437-206187:486", "206187:489-206187:569", "206187:571-206187:647",
"206187:649-206187:662", "206187:664-206187:708", "206188:1-206188:40", "206188:42-206188:55", "206199:1-206199:75",
"206199:77-206199:82", "206199:85-206199:114", "206207:82-206207:130", "206207:132-206207:176", "206207:179-206207:194",
"206207:196-206207:388", "206207:390-206207:419", "206207:422-206207:447", "206207:450-206207:569", "206207:572-206207:690",
"206208:1-206208:470", "206208:472-206208:518", "206210:11-206210:25", "206210:28-206210:275", "206210:277-206210:298",
"206210:300-206210:383", "206210:386-206210:466", "206243:62-206243:169", "206243:172-206243:196", "206243:199-206243:354",
"206243:357-206243:433", "206243:435-206243:448", "206243:451-206243:533", "206243:536-206243:554", "206243:557-206243:723",
"206243:726-206243:905", "206245:1-206245:62", "206246:1-206246:14", "206246:16-206246:237", "206246:240-206246:285",
"206246:288-206246:407", "206246:412-206246:676", "206246:678-206246:704", "206246:706-206246:785", "206246:787-206246:962",
"206246:965-206246:997", "206246:1000-206246:1198", "206246:1201-206246:1290", "206257:1-206257:29", "206258:1-206258:36",
"206258:39-206258:223", "206258:226-206258:249", "206302:1-206302:8", "206302:11-206302:33", "206302:36-206302:44",
"206302:47-206302:82", "206302:84-206302:108", "206302:110-206302:149", "206302:151-206302:186", "206302:189-206302:229",
"206302:231-206302:232", "206302:234-206302:241", "206302:243-206302:276", "206303:1-206303:19", "206303:23-206303:286",
"206304:1-206304:4", "206304:6-206304:62", "206331:91-206331:222", "206331:225-206331:312", "206389:88-206389:185",
"206389:187-206389:249", "206389:252-206389:272", "206389:275-206389:392", "206391:1-206391:55", "206391:57-206391:91",
"206401:69-206401:90", "206401:92-206401:194", "206401:197-206401:210", "206401:212-206401:249", "206401:251-206401:265",
"206401:267-206401:409", "206446:92-206446:141", "206446:143-206446:159", "206446:162-206446:205", "206446:208-206446:301",
"206446:304-206446:442", "206446:445", "206446:448-206446:474", "206446:476-206446:616", "206446:619-206446:872",
"206446:874-206446:910", "206446:912-206446:948", "206446:950-206446:989", "206446:992-206446:1030", "206446:1033-206446:1075",
"206446:1109-206446:1149", "206448:1-206448:143", "206448:145-206448:559", "206448:561-206448:1170", "206448:1173-206448:1231",
"206448:1235-206448:1237", "206466:24-206466:137", "206466:140-206466:277", "206466:280-206466:296", "206466:299-206466:303",
"206466:306-206466:405", "206466:407-206466:419", "206466:422-206466:477", "206466:480-206466:511", "206466:514-206466:676",
"206476:73-206476:129", "206476:133-206476:137", "206476:140-206476:141", "206476:143-206476:219", "206477:1-206477:14",
"206477:16-206477:31", "206477:33-206477:41", "206477:44-206477:51", "206477:53-206477:70", "206477:73-206477:75",
"206477:77-206477:89", "206477:91-206477:94", "206477:97-206477:115", "206477:118-206477:184", "206478:1-206478:27",
"206478:29-206478:136", "206478:139-206478:144", "206484:73-206484:95", "206484:98-206484:133", "206484:136-206484:163",
"206484:166-206484:186", "206484:189-206484:384", "206484:387-206484:463", "206484:465-206484:551", "206484:554",
"206484:556-206484:669", "206512:91-206512:123", "206512:125-206512:133", "206512:136-206512:161", "206512:163-206512:190",
"206512:193-206512:201", "206512:203-206512:212", "206512:214-206512:332", "206512:334-206512:584", "206512:587-206512:604",
"206512:607-206512:1005", "206512:1008-206512:1123", "206512:1126-206512:1163", "206512:1165-206512:1211", "206513:3-206513:39",
"206513:42-206513:188", "206513:191-206513:234", "206513:237-206513:238", "206513:241-206513:323", "206542:1-206542:115",
"206542:117-206542:165", "206542:168-206542:511", "206542:514-206542:547", "206542:550-206542:603", "206542:606-206542:668",
"206542:671-206542:727", "206542:730-206542:739", "206542:741-206542:833", "206550:77-206550:132", "206550:135-206550:144",
"206572:37-206572:47", "206573:2-206573:14", "206574:1-206574:87", "206575:1-206575:7", "206575:10",
"206575:12-206575:69", "206594:72-206594:107", "206594:110-206594:246", "206594:249-206594:281", "206595:1-206595:34",
"206595:37-206595:42", "206595:45-206595:193", "206596:1-206596:13", "206596:15-206596:220", "206596:222-206596:228",
"206596:231-206596:236", "206596:239-206596:292", "206596:295-206596:695", "206596:697-206596:728", "206596:730-206596:810",
"206598:1-206598:81", "206598:83-206598:103", "206598:105-206598:588", "206598:591-206598:657", "206598:659-206598:719",
"206605:1-206605:36", "206605:39-206605:78", "206744:49-206744:157", "206744:160-206744:192", "206744:195-206744:395",
"206744:398-206744:452", "206745:1-206745:81", "206745:84-206745:199", "206745:202-206745:224", "206745:227-206745:237",
"206745:240-206745:304", "206745:306-206745:318", "206745:321-206745:720", "206745:723-206745:796", "206745:799-206745:894",
"206745:897-206745:944", "206745:946-206745:1106", "206745:1108-206745:1524", "206745:1527-206745:1862", "206745:1988-206745:1996",
"206859:79-206859:210", "206859:212-206859:258", "206859:260-206859:323", "206859:325-206859:356", "206859:359-206859:609",
"206859:612-206859:681", "206859:684-206859:732", "206859:734-206859:768", "206859:771-206859:808", "206859:811-206859:827",
"206859:830-206859:848", "206866:1-206866:30", "206866:33-206866:113", "206866:115-206866:274", "206868:1-206868:3",
"206868:10-206868:16", "206869:1-206869:251", "206869:253-206869:271", "206869:274-206869:502", "206869:507-206869:520",
"206869:522-206869:566", "206869:568-206869:752", "206897:1-206897:34", "206897:38-206897:61", "206897:63-206897:102",
"206897:109", "206897:111-206897:112", "206897:114-206897:131", "206897:133-206897:137", "206901:1-206901:98",
"206906:1-206906:31", "206906:38-206906:94", "206906:96-206906:136", "206906:138-206906:139", "206906:142-206906:149",
"206906:151-206906:175", "206906:177-206906:206", "206940:1-206940:151", "206940:153", "206940:155-206940:298",
"206940:301-206940:382", "206940:384-206940:712", "206940:715-206940:803", "206940:805-206940:960", "206940:963-206940:1027",
"207099:83-207099:134", "207099:137-207099:172", "207099:175-207099:213", "207099:216-207099:314", "207099:316-207099:320",
"207099:323-207099:330", "207099:333-207099:367", "207099:370-207099:481", "207099:484-207099:602", "207099:605-207099:755",
"207099:757-207099:1046", "207099:1048-207099:1171", "207100:1-207100:91", "207100:94", "207214:57-207214:112",
"207214:114-207214:177", "207214:179-207214:181", "207214:184-207214:196", "207214:199-207214:220", "207214:223-207214:262",
"207214:265-207214:405", "207214:408-207214:482", "207214:485-207214:640", "207214:643-207214:708", "207214:718-207214:757",
"207214:759-207214:808", "207214:811-207214:829", "207217:1-207217:32", "207219:1-207219:112", "207220:1-207220:160",
"207221:1-207221:102", "207222:1-207222:17", "207222:20-207222:289", "207231:70-207231:84", "207231:86-207231:121",
"207231:123-207231:184", "207231:187-207231:189", "207231:192-207231:303", "207231:306-207231:354", "207231:357-207231:481",
"207231:484-207231:504", "207231:508-207231:549", "207231:552-207231:626", "207231:628-207231:690", "207231:693-207231:875",
"207231:878-207231:1000", "207231:1003-207231:1170", "207231:1173-207231:1187", "207231:1189-207231:1227", "207231:1229-207231:1415",
"207231:1418-207231:1445", "207231:1447-207231:1505", "207233:1-207233:119", "207233:121-207233:148", "207269:80-207269:394",
"207269:397-207269:436", "207269:439-207269:463", "207269:466-207269:551", "207269:568-207269:577", "207273:3-207273:877",
"207279:68-207279:138", "207279:141-207279:149", "207279:151-207279:237", "207279:240-207279:266", "207279:269-207279:307",
"207279:309-207279:416", "207279:498-207279:551", "207279:554-207279:640", "207279:643-207279:961", "207279:963-207279:1095",
"207279:1098-207279:1160", "207320:1-207320:110", "207320:112-207320:350", "207371:72-207371:117", "207371:120-207371:124",
"207372:1-207372:27", "207372:30-207372:113", "207372:116-207372:154", "207372:156-207372:174", "207372:176-207372:478",
"207372:480-207372:496", "207397:32-207397:77", "207397:80-207397:140", "207397:143-207397:179", "207398:1-207398:14",
"207398:16-207398:33", "207454:79-207454:95", "207454:98-207454:123", "207454:126-207454:259", "207454:261-207454:363",
"207454:365-207454:458", "207454:461-207454:498", "207454:501-207454:609", "207454:612-207454:632", "207454:635-207454:781",
"207454:784-207454:866", "207454:869-207454:974", "207454:977-207454:1064", "207454:1067-207454:1079", "207454:1081-207454:1321",
"207454:1323-207454:1464", "207454:1467-207454:1569", "207454:1571-207454:1604", "207454:1607-207454:1712", "207454:1714-207454:1988",
"207469:1-207469:31", "207469:34-207469:45", "207477:76-207477:104", "207477:107-207477:111", "207477:114-207477:147",
"207477:150-207477:295", "207477:298-207477:483", "207477:486-207477:494", "207477:497-207477:527", "207477:530-207477:563",
"207477:565-207477:570", "207487:50-207487:98", "207487:101-207487:311", "207487:313-207487:359", "207487:363-207487:468",
"207487:471-207487:472", "207488:1-207488:63", "207488:66-207488:92", "207488:95-207488:113", "207488:116-207488:198",
"207488:200-207488:250", "207488:252-207488:288", "207488:291-207488:365", "207488:368-207488:377", "207488:379-207488:440",
"207490:1-207490:48", "207490:51-207490:111", "207491:1-207491:176", "207491:179-207491:458", "207492:1-207492:20",
"207492:23-207492:298", "207515:79-207515:109", "207515:112-207515:132", "207515:134-207515:208", "207515:211-207515:225",
"207515:228-207515:320", "207515:322-207515:381", "207515:383-207515:498", "207515:500-207515:730", "207515:733-207515:849",
"207515:851-207515:954", "207515:957-207515:994", "207515:997-207515:1052", "207515:1055-207515:1143", "207515:1145-207515:1211",
"207517:1-207517:12", "207517:15-207517:57", "207518:1-207518:59", "207518:61-207518:83", "207882:22-207882:45",
"207883:1", "207883:3-207883:4", "207883:7-207883:75", "207884:1-207884:106", "207884:108-207884:183",
"207885:1-207885:90", "207886:1-207886:30", "207886:32-207886:90", "207886:92-207886:156", "207886:158-207886:166",
"207886:168-207886:171", "207889:1-207889:43", "207889:47-207889:57", "207889:60-207889:303", "207889:306-207889:442",
"207889:445", "207889:447-207889:551", "207889:553-207889:731", "207889:733-207889:907", "207889:910-207889:945",
"207898:1-207898:33", "207898:36-207898:57", "207898:60-207898:235", "207898:239-207898:257", "207898:260-207898:277",
"207905:75-207905:196", "207905:198-207905:281", "207905:284-207905:329", "207905:331-207905:402", "207905:404-207905:565",
"207905:568-207905:672", "207905:675-207905:805", "207905:807-207905:850", "207905:852-207905:861", "207905:864-207905:884",
"207905:886-207905:1180", "207905:1183-207905:1283", "207905:1285-207905:1331", "207905:1333-207905:1515", "207905:1518-207905:1734",
"207905:1737-207905:1796", "207920:84-207920:146", "207920:149-207920:241", "207920:243-207920:261", "207920:264-207920:291",
"207920:294-207920:486", "207920:489-207920:518", "207920:520-207920:598", "207920:600-207920:708", "207920:710-207920:826",
"207921:1-207921:37", "207921:40-207921:58", "207922:1-207922:69", "207922:71-207922:100", "207922:103-207922:126",
"207922:129-207922:242", "207922:274-207922:291", "207924:1-207924:52", "207924:54-207924:171", "207924:173-207924:178",
"207924:181-207924:339", "208307:2-208307:42", "208307:45", "208307:47-208307:70", "208307:72-208307:147",
"208307:150-208307:252", "208307:256-208307:259", "208307:262-208307:275", "208307:278-208307:342", "208307:345-208307:450",
"208307:453-208307:527", "208307:530-208307:583", "208307:586-208307:605", "208307:608-208307:616", "208307:618-208307:667",
"208307:670-208307:761", "208307:763-208307:798", "208307:800-208307:889", "208307:891-208307:893", "208307:896-208307:1055",
"208307:1057-208307:1205", "208307:1208-208307:1294", "208307:1297-208307:1328", "208339:77-208339:89", "208339:91-208339:122",
"208339:125-208339:208", "208339:211-208339:346", "208339:349-208339:363", "208341:1-208341:84", "208341:87-208341:117",
"208341:120-208341:513", "208341:515-208341:685", "208341:688-208341:693", "208341:695-208341:775", "208341:777-208341:824",
"208351:83-208351:97", "208351:100-208351:356", "208351:359-208351:367", "208351:369", "208352:1-208352:15",
"208352:17", "208352:19", "208353:1-208353:76", "208353:78-208353:269", "208353:271-208353:348",
"208357:1-208357:70", "208357:73-208357:507", "208390:72-208390:128", "208390:130-208390:169", "208391:52-208391:82",
"208391:84-208391:162", "208391:164-208391:216", "208391:219-208391:493", "208391:495-208391:498", "208391:500-208391:523",
"208391:526-208391:533", "208391:535-208391:588", "208391:591-208391:660", "208391:663-208391:869", "208427:49-208427:89",
"208427:92-208427:161", "208427:164", "208427:166-208427:173", "208427:175-208427:268", "208427:271-208427:312",
"208427:315", "208427:317-208427:335", "208427:337-208427:361", "208427:364-208427:402", "208427:404-208427:422",
"208427:425-208427:577", "208427:580-208427:647", "208428:1-208428:58", "208428:61-208428:68", "208428:70-208428:156",
"208428:159-208428:227", "208429:1-208429:56", "208429:59-208429:139", "208429:141-208429:159", "208429:162-208429:237",
"208429:240-208429:440", "208429:442-208429:452", "208429:455-208429:589", "208429:592-208429:712", "208429:715-208429:922",
"208487:2-208487:26", "208487:29-208487:159", "208487:161-208487:307", "208487:309-208487:459", "208487:462-208487:476",
"208487:479-208487:621", "208509:71-208509:232", "208538:2-208538:43", "208540:1-208540:26", "208540:29-208540:98",
"208541:1-208541:57", "208541:59-208541:173", "208541:175-208541:376", "208541:378-208541:413", "208551:119-208551:193",
"208551:195-208551:212", "208551:215-208551:300", "208551:303-208551:354", "208551:356-208551:554", "208551:557-208551:580",
"208686:73-208686:79", "208686:82-208686:181", "208686:183-208686:224", "208686:227-208686:243", "208686:246-208686:311",
"208686:313-208686:459" ) ),
duplicateCheckMode = cms.untracked.string('noDuplicateCheck'),
fileNames = cms.untracked.vstring('/store/cmst3/user/cmgtools/CMG/DoubleMuParked/StoreResults-Run2012D_22Jan2013_v1_PFembedded_trans1_tau132_pthad1_30had2_30_v1-5ef1c0fd428eb740081f19333520fdc8/USER/V5_B/PAT_CMG_V5_16_0/cmgTuple_379.root',
'/store/cmst3/user/cmgtools/CMG/DoubleMuParked/StoreResults-Run2012D_22Jan2013_v1_PFembedded_trans1_tau132_pthad1_30had2_30_v1-5ef1c0fd428eb740081f19333520fdc8/USER/V5_B/PAT_CMG_V5_16_0/cmgTuple_38.root',
'/store/cmst3/user/cmgtools/CMG/DoubleMuParked/StoreResults-Run2012D_22Jan2013_v1_PFembedded_trans1_tau132_pthad1_30had2_30_v1-5ef1c0fd428eb740081f19333520fdc8/USER/V5_B/PAT_CMG_V5_16_0/cmgTuple_380.root')
)
| [
"riccardo.manzoni@cern.ch"
] | riccardo.manzoni@cern.ch |
81808de5af7f87fb82b724de12996ceca4290f0e | 9968b58abae0639df4233a038a89fe9c872e141b | /examples/02plot/misc/candidates.py | 6fc2a6d2ebb944641a482eaaeb3b91d143d4bc9f | [] | no_license | podhmo/utatane | 5dffa1df6fd4c63a7ddd4075c73c67a18a864c52 | c38a2615fe89efb163651ef3f764144a0cb902cf | refs/heads/master | 2021-01-01T16:46:31.487204 | 2017-08-07T01:47:07 | 2017-08-07T01:47:07 | 97,915,447 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 970 | py | import matplotlib
matplotlib.use("Agg") # NOQA
from matplotlib import pyplot as plt
from utatane import subplot
from collections import defaultdict
def defined_with(mro, name):
owner = None
for cls in mro:
if not hasattr(cls, name):
return owner
owner = cls
with subplot(plt, ncols=1, nrows=1) as nth:
with nth(1) as ax:
print("hierarchy(mro)")
print("")
mro = [ax, *ax.__class__.mro()]
for cls in mro:
print("-", cls)
d = defaultdict(list)
for attr in sorted(dir(ax)):
d[defined_with(mro, attr)].append(attr)
for cls in mro:
attrs = d[cls]
print("")
print(cls)
print("")
for attr in attrs:
if callable(getattr(cls, attr)):
if not any(attr.startswith(x) for x in ("_", "get_", "set_", "add_", "update_")):
print("-", attr)
| [
"ababjam61+github@gmail.com"
] | ababjam61+github@gmail.com |
2c3781633d95f44eb76888ed600cf855f5ba9f03 | 55c250525bd7198ac905b1f2f86d16a44f73e03a | /Python/Games/Making Games with Python & Pygame/drawing.py | 5c043ef052eeaf031e33696603e08f84f5db5f16 | [] | no_license | NateWeiler/Resources | 213d18ba86f7cc9d845741b8571b9e2c2c6be916 | bd4a8a82a3e83a381c97d19e5df42cbababfc66c | refs/heads/master | 2023-09-03T17:50:31.937137 | 2023-08-28T23:50:57 | 2023-08-28T23:50:57 | 267,368,545 | 2 | 1 | null | 2022-09-08T15:20:18 | 2020-05-27T16:18:17 | null | UTF-8 | Python | false | false | 129 | py | version https://git-lfs.github.com/spec/v1
oid sha256:c80352eee128cec2e7813b952de0835d4a061ca8607f2b1e31c472e8244844a3
size 1219
| [
"nateweiler84@gmail.com"
] | nateweiler84@gmail.com |
d335592cde1f334acf88d32c984b22dda377b1fa | 4a5b49806d0dd4fd8bd38483b06da79515d1ad39 | /apps/comment/apps.py | 204d8b893a158211dee28da91a5738aa1665b7b7 | [] | no_license | madongliang11/dj_Book | 5ace757f7873d10e41d756be29050ee395f4bceb | c70e331e733a4431467d49dcb8514b58ef03715c | refs/heads/master | 2022-12-14T15:08:02.027194 | 2019-03-10T14:48:47 | 2019-03-10T14:48:47 | 174,836,847 | 1 | 0 | null | 2022-11-22T02:23:10 | 2019-03-10T14:44:17 | JavaScript | UTF-8 | Python | false | false | 124 | py | from django.apps import AppConfig
class CommentsConfig(AppConfig):
name = 'comment'
verbose_name = "用户评论"
| [
"15565608583@163.com"
] | 15565608583@163.com |
38b6c08a4a112060d351a0e66345401a44d57378 | 94e2d1fba52b0d8f93c99bdb6a5f58c7de15b842 | /userhandler/migrations/0003_userpersonal_verified.py | da523e58862f39f03c8837457a013b0705f1a6e0 | [] | no_license | hks74123/covidhelpmain | 023b0cfe7c3cb140b2d68a3fbab6e695e6d9c6af | ee96d0b157cd048d2ea27865bf98551186dead98 | refs/heads/main | 2023-04-26T16:16:39.029555 | 2021-05-24T19:25:12 | 2021-05-24T19:25:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 399 | py | # Generated by Django 3.2.3 on 2021-05-20 21:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userhandler', '0002_auto_20210521_0227'),
]
operations = [
migrations.AddField(
model_name='userpersonal',
name='verified',
field=models.BooleanField(default=False),
),
]
| [
"experimentallyf@gmail.com"
] | experimentallyf@gmail.com |
da2dc0fcba2065f0ab252173bc7582ff09024d07 | 45b1914317ac543a89afecfbbad9dbe4e0195b21 | /tests/integration/settings.py | 278335f0b1400dd536a8aa17bd970bd5a4a23c1a | [
"BSD-2-Clause"
] | permissive | lextoumbourou/txes | fbb37dcc2671178eb84d5af533c3ab77e7c5f36d | 55fb2d78655d865c1822f3b0b6c09b1c2cf72ed8 | refs/heads/master | 2021-01-15T11:24:09.231797 | 2014-11-18T22:22:38 | 2014-11-18T22:22:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 66 | py | URL = '127.0.0.1:9200'
INDEX = 'test_index'
DOC_TYPE = 'test_doc'
| [
"lextoumbourou@gmail.com"
] | lextoumbourou@gmail.com |
94b858cec97d32e847d9187305d9f1873514aad8 | 9b50b3a7dda2711c5665909f6801249de53e70f6 | /0x0C-python-almost_a_circle/tests/test_base.py | 448df3af8b02c58fed9730cc03782f0cede681df | [] | no_license | nikolasribeiro/holbertonschool-higher_level_programming | 3119e5442887f06da104dc8aa93df371f92b9f2b | 7dcdf081d8a57ea1f5f6f9830555f73bf2ae6993 | refs/heads/main | 2023-04-21T05:22:03.617609 | 2021-05-05T11:38:51 | 2021-05-05T11:38:51 | 319,198,337 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,600 | py | #!/usr/bin/python3
""" Module test_base"""
import os
import unittest
from models.base import Base
from models.rectangle import Rectangle
from models.square import Square
class TestBase(unittest.TestCase):
""" class TestBase """
def test_normal(self):
""" function test_normal """
self.base = Base(6)
self.assertEqual(self.base.id, 6)
self.base = Base()
self.assertEqual(self.base._Base__nb_objects, 7)
self.base = Base()
self.assertEqual(self.base.id, 8)
def test_arg_count(self):
""" function test_arg_count """
with self.assertRaises(TypeError):
self.base = Base(2, 2)
def test_json(self):
""" function test_json """
self.base = Base()
dic = {"test": 1, "test2": 2, "test3": 3}
lidi = [dic]
json_dict = self.base.to_json_string(lidi)
self.assertTrue(isinstance(json_dict, str))
dic1 = {"test": 1, "test2": 2, "test3": 3}
lidi = [dic, dic1]
json_dict = self.base.to_json_string(lidi)
self.assertTrue(isinstance(json_dict, str))
json_dict = self.base.to_json_string([])
self.assertEqual(json_dict, "[]")
json_dict = self.base.to_json_string(None)
self.assertEqual(json_dict, "[]")
def test_json_to_file(self):
""" function test_json_to_file """
self.r1 = Rectangle(1, 2)
Rectangle.save_to_file([self.r1])
with open("Rectangle.json", "r") as f:
data = f.read()
self.assertEqual(len(data), 52)
self.r2 = Rectangle(3, 4)
Rectangle.save_to_file([self.r1, self.r2])
with open("Rectangle.json", "r") as f:
data = f.read()
self.assertEqual(len(data), 104)
Rectangle.save_to_file([])
with open("Rectangle.json", "r") as f:
data = f.read()
self.assertEqual(len(data), 2)
def test_from_json(self):
""" function test_from_json """
self.rec = Rectangle(1, 2)
li = [self.rec.to_dictionary()]
json_list_input = Rectangle.to_json_string(li)
from_json = Rectangle.from_json_string(json_list_input)
self.assertTrue(isinstance(from_json, list))
self.assertTrue(isinstance(from_json[0], dict))
self.assertEqual(Rectangle.from_json_string(None), [])
self.assertEqual(Rectangle.from_json_string("[]"), [])
def test_create_cls(self):
""" function test_create_cls """
self.r1 = Rectangle(10, 10, 10)
self.r1_dict = self.r1.to_dictionary()
| [
"nikolasribeiro2@outlook.com"
] | nikolasribeiro2@outlook.com |
19e84b0ef14097478ef6d6c3c4d9499b957f60a6 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02957/s386293584.py | 8ac2ab486051007677c3346e44c36cc2951f3560 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 102 | py | a,b=[int(x) for x in input().split()]
k=(a+b)//2
if (a+b)%2==0:
print(k)
else:
print("IMPOSSIBLE") | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
130bcaa32fbf9c16da199ad5238345639327879b | f63db957cb63b3a37642d138d3092f8f897d6a53 | /hila_webapp/hila/auth/backends.py | 0798c740954b2d325558900ec384d44bc418ee65 | [] | no_license | fillarikanava/old-fillarikanava | c6fd819f95e675e6eddc674e71528c798b391967 | 8dbb89ea34c2aa98450e403ca2d7f17179edff8d | refs/heads/master | 2021-01-13T02:30:01.501771 | 2013-10-03T16:26:13 | 2013-10-03T16:26:13 | 13,201,013 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,916 | py | '''
Created on 1.4.2009
@author: jsa
'''
from django.contrib.auth.models import User
from hila import roundup_utils
from roundup.password import Password
db = roundup_utils.db()
class RoundupUser(User):
def __init__(self, usernode):
super(RoundupUser, self).__init__(
id=usernode.id,
username=usernode.username,
first_name=usernode.screenname,
last_name="",
email=usernode.address,
password=None,
is_staff=False,
is_active=True,
is_superuser=False,
# groups = models.ManyToManyField(Group, verbose_name=_('groups'), blank=True,
# help_text=_("In addition to the permissions manually assigned, this user will also get all permissions granted to each group he/she is in."))
# user_permissions = models.ManyToManyField(Permission, verbose_name=_('user permissions'), blank=True)
)
self.usernode = usernode
def save(self):
print "called backends.py RoundupUser.save()"
pass
class RoundupBackend(object):
"""
Authenticates against RoundUp user database.
"""
def authenticate(self, username=None, password=None):
db = roundup_utils.db()
try:
usernode = db.user.getnode(db.user.lookup(username))
if usernode.password == Password(password):
print "Authentication successful!"
return RoundupUser(usernode)
else:
print "Authentication failure!"
except KeyError:
pass
return None
def get_permissions_for_group(self, group):
return {
'organisation': ['organisation.access', 'public.report.modify_priority'],
}.get(group, {})
# def get_group_permissions(self, user_obj):
# perms = reduce(lambda role, roles: roles + self.get_permissions_for_group(role),
# [],
# [role.strip().lower() for role in
# user_obj.usernode.roles.split(',')])
# if user_obj.usernode.organisation:
# perms += self.get_permissions_for_group('organisation')
# return perms
#
# def get_all_permissions(self, user_obj):
# return self.get_group_permissions(user_obj)
#
def has_perm(self, user_obj, perm):
return perm in self.get_all_permissions(user_obj)
def has_module_perms(self, user_obj, app_label):
"""
Returns True if user_obj has any permissions in the given app_label.
"""
for perm in self.get_all_permissions(user_obj):
if perm[:perm.index('.')] == app_label:
return True
return False
def get_user(self, user_id):
if db.user.hasnode(user_id):
return RoundupUser(db.user.getnode(user_id))
else:
return roundup_utils.get_user_by_name('anonymous')
| [
"rkarhila@iki.fi"
] | rkarhila@iki.fi |
006e4d2f73368f5665f1504a4698ce0e137a3d0e | 8015f1c62a2cb4efd21aa8938336913bf8117868 | /bamap/ba0375.pngMap.py | 57180753746f10f80ac179f7b7ab4ce9a9f6469c | [] | no_license | GamerNoTitle/Beepers-and-OLED | 675b5e3c179df0f0e27b42bf594c43860d03b9af | afe1340e5394ae96bda5f9022a8a66824368091e | refs/heads/master | 2020-04-20T00:09:47.122471 | 2019-04-29T04:59:35 | 2019-04-29T04:59:35 | 168,515,579 | 4 | 2 | null | null | null | null | UTF-8 | Python | false | false | 8,468 | py | ba0375.pngMap = [
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111101011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111001111111111111111111111111111111111111111111111111111111100111110',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111110001111111001111111',
'11111111000011110011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111101111111110111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111101111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111110000011111111111111111111111110111111111101010111111111111111001111111111111111111111',
'11111111111111111111111111111111111111111111101011111111111111111111111111111111111111000111111111111110011111111111111111111111',
'11111111111111111111111111111111111111111111111101111111111111111111111111111011111111111111111111111111111111110111111111111111',
'11111111111111111111111111111111111110111111111111111111110000001110000001111111111111111111111111111111111111111101011111111111',
'11111111110111111111111111111111111101111111111111111111100000000000000001111111111111111111111111111111111111111110111111111111',
'11110011110011111111111111111111111111111111111111111111100000000000000000001111111111111111111111111111111111111111111111111110',
'11111011111011111111101111111111111111111111111111111111101000000000000000001111111111111001111111111111111111111111111111111110',
'11111111111110111111111111111111111110111111111111111000011100000000000000001111111111111111111100111111111111111111111111111111',
'11111111110111111110000111111111111111011111111111111001111110000000000000001111111111111111111111111111111111111111111100111111',
'11111111110101111111111111111111111111111111110111111011111000000000000000000011111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111100001000000000000000111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111000000000000000000111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111000000000000000000111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111100000000000000011111111111111110011111111111111111111111111111111',
'11110111111111111111111111111111111111111111111111111111111111110000000000000011111111111111111101111111111111111111111111111111',
'11001111111111111111111111111111111111111111111111111111110011000010000000000000001011000000001111111111111111111111111111111111',
'11111111111111111111111111111100111111010101011111111111110010000000000000000000000000000000000011111111111111111111111111111111',
'11111111111111111111111111111100111110100000000000000001000000000000000000000000000000000000000000111111111111101111111111111111',
'11111111111111111111111111111111111101100000000000000000000000000000000000000000000000000000000000001111111111111111111111111111',
'11111111111111111111111111111111111111111110001100001111100000000000000000000000000000000000000000001111111111111111111111111111',
'11111111111111111111111111111111111111111111110000100010001111000000000000000000000000000000000000001111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111100011111000000010000000000100000000000000000001111111111111111111111111111',
'11111111111111111111111111100111111111111111111111110011111111111111111000001011111100000000000000111111111111111111111111111111',
'11111111111111111111111111111111111111111011111111111111111111111111111101111111111111111100000011111111111111111111111111111111',
'11111111111111111111111111111111111111111001111110001111111111111111111101111111111111111111101111111111111111111111111111111111',
'11111111111101011111111111111111111111111111111111101111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111001111111111111111011111111111111111110001111111111111111111111111111111110111111111111111111111000111111111111111',
'11111111111111011111111111111111001111111011111111110011111111111111111111111100111111111111111111111111111111001111111111111111',
'11111111111111111111111111111111111111111011111111111111111111111000111111111011111111111111111111111111111111000111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111100111111111111111111111111111111111111111111111111111111111111',
'00001111111111111111111111111111111111111111111111111111111111111111111000111111111111111011111111111111111111111111111110111111',
'10101111111111111111111111111111111111111111111111111111111111111111111111111111111111110111111111111111111111111111111101011111',
'11111111111111111111111111111111111111111111111111111111111111111111111011111111111111111011111111111111111111111111111111111111',
'11111111111111111111111111111111111100110111111111111111001111111111100011111100111111111111111111111111111111111111111111111111',
'11111111111111101100111111111111111111111111111111111111111111111111100011100011111111111111111111111111111111111111111111111111',
'11111111111111100111111111111111111111111111111111111111111111111111111111110011111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111001111111111110001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111101111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111101111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111011111111111011111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111110111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111110111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111001111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
]
| [
"bili33@87ouo.top"
] | bili33@87ouo.top |
7a04d8115d61910b95a966095a39d6aed73abeff | 8fa206c919acd78dea69bc846e92d5a13a22598b | /backend/prenatal_tests_22997/settings.py | ec05cbce6755dd970a47a0f1faa9a52c18cf6007 | [] | no_license | crowdbotics-apps/prenatal-tests-22997 | ff4e98597ac3e7d45d12152fa94cae817494776b | b4f674a9ee80122214b0242056cc885715effe02 | refs/heads/master | 2023-01-20T17:49:34.831432 | 2020-11-26T16:52:05 | 2020-11-26T16:52:05 | 316,289,196 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,032 | py | """
Django settings for prenatal_tests_22997 project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
import environ
import logging
env = environ.Env()
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool("DEBUG", default=False)
# 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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env.str("SECRET_KEY")
ALLOWED_HOSTS = env.list("HOST", default=["*"])
SITE_ID = 1
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = env.bool("SECURE_REDIRECT", default=False)
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites'
]
LOCAL_APPS = [
'home',
'users.apps.UsersConfig',
]
THIRD_PARTY_APPS = [
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_auth.registration',
'bootstrap4',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'django_extensions',
'drf_yasg',
'storages',
# start fcm_django push notifications
'fcm_django',
# end fcm_django push notifications
]
INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS
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 = 'prenatal_tests_22997.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 = 'prenatal_tests_22997.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
if env.str("DATABASE_URL", default=None):
DATABASES = {
'default': env.db()
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
MIDDLEWARE += ['whitenoise.middleware.WhiteNoiseMiddleware']
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend'
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# allauth / users
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "optional"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
ACCOUNT_UNIQUE_EMAIL = True
LOGIN_REDIRECT_URL = "users:redirect"
ACCOUNT_ADAPTER = "users.adapters.AccountAdapter"
SOCIALACCOUNT_ADAPTER = "users.adapters.SocialAccountAdapter"
ACCOUNT_ALLOW_REGISTRATION = env.bool("ACCOUNT_ALLOW_REGISTRATION", True)
SOCIALACCOUNT_ALLOW_REGISTRATION = env.bool("SOCIALACCOUNT_ALLOW_REGISTRATION", True)
REST_AUTH_SERIALIZERS = {
# Replace password reset serializer to fix 500 error
"PASSWORD_RESET_SERIALIZER": "home.api.v1.serializers.PasswordSerializer",
}
REST_AUTH_REGISTER_SERIALIZERS = {
# Use custom serializer that has no username and matches web signup
"REGISTER_SERIALIZER": "home.api.v1.serializers.SignupSerializer",
}
# Custom user model
AUTH_USER_MODEL = "users.User"
EMAIL_HOST = env.str("EMAIL_HOST", "smtp.sendgrid.net")
EMAIL_HOST_USER = env.str("SENDGRID_USERNAME", "")
EMAIL_HOST_PASSWORD = env.str("SENDGRID_PASSWORD", "")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# AWS S3 config
AWS_ACCESS_KEY_ID = env.str("AWS_ACCESS_KEY_ID", "")
AWS_SECRET_ACCESS_KEY = env.str("AWS_SECRET_ACCESS_KEY", "")
AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", "")
AWS_STORAGE_REGION = env.str("AWS_STORAGE_REGION", "")
USE_S3 = (
AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY and
AWS_STORAGE_BUCKET_NAME and
AWS_STORAGE_REGION
)
if USE_S3:
AWS_S3_CUSTOM_DOMAIN = env.str("AWS_S3_CUSTOM_DOMAIN", "")
AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
AWS_DEFAULT_ACL = env.str("AWS_DEFAULT_ACL", "public-read")
AWS_MEDIA_LOCATION = env.str("AWS_MEDIA_LOCATION", "media")
AWS_AUTO_CREATE_BUCKET = env.bool("AWS_AUTO_CREATE_BUCKET", True)
DEFAULT_FILE_STORAGE = env.str(
"DEFAULT_FILE_STORAGE", "home.storage_backends.MediaStorage"
)
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
# start fcm_django push notifications
FCM_DJANGO_SETTINGS = {
"FCM_SERVER_KEY": env.str("FCM_SERVER_KEY", "")
}
# end fcm_django push notifications
# Swagger settings for api docs
SWAGGER_SETTINGS = {
"DEFAULT_INFO": f"{ROOT_URLCONF}.api_info",
}
if DEBUG or not (EMAIL_HOST_USER and EMAIL_HOST_PASSWORD):
# output email to console instead of sending
if not DEBUG:
logging.warning("You should setup `SENDGRID_USERNAME` and `SENDGRID_PASSWORD` env vars to send emails.")
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
| [
"team@crowdbotics.com"
] | team@crowdbotics.com |
55b64b2105130f31d48bc584c5a9ac1ab6655c83 | a80963fbac8c0edcef5b1b9bad67a4b5913cd569 | /web_data/check_profanity.py | 9cd251c833e6d6947acdfb9a3506e0d327f4f3c6 | [] | no_license | manurp/Python_programs | 946877caf93a2ff0239c68dc4e8e02c72fe6f156 | 1a0c896b05b72afee7a48dd1bc2bef2aa7ffe0af | refs/heads/master | 2020-06-28T01:22:59.140092 | 2018-09-01T17:03:18 | 2018-09-01T17:03:18 | 97,080,367 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 641 | py | import urllib.request, urllib.parse, urllib.error
def check_profanity(text):
connection = urllib.request.urlopen('http://www.wdylike.appspot.com/?q='+text)
output = connection.read()
print(output)
connection.close()
def read_text():
fhand = open('file.txt')
contents = fhand.read().split()
# words = contents.split()
contents = ''.join(contents)
contents = contents.rstrip()
# print(contents,end='')
check_profanity(contents)
# for contents in fhand.readlines():
# words = contents.split()
# for word in words:
# check_profanity(word)
# print(contents)
fhand.close()
read_text()
# check_profanity('shot%in%the%fuck') | [
"manojrpoojary@gmail.com"
] | manojrpoojary@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.