repo_name
stringlengths
7
111
__id__
int64
16.6k
19,705B
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
151
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_url
stringlengths
26
130
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
42
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
14.6k
687M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
12 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
10.2M
gha_stargazers_count
int32
0
178k
gha_forks_count
int32
0
88.9k
gha_open_issues_count
int32
0
2.72k
gha_language
stringlengths
1
16
gha_archived
bool
1 class
gha_disabled
bool
1 class
content
stringlengths
10
2.95M
src_encoding
stringclasses
5 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
10
2.95M
extension
stringclasses
19 values
num_repo_files
int64
1
202k
filename
stringlengths
4
112
num_lang_files
int64
1
202k
alphanum_fraction
float64
0.26
0.89
alpha_fraction
float64
0.2
0.89
hex_fraction
float64
0
0.09
num_lines
int32
1
93.6k
avg_line_length
float64
4.57
103
max_line_length
int64
7
931
chauhanmahavir/Python-Basics
1,451,698,993,417
150b146df5fa9df6739f0c9bc39e52250203fb43
5d6207228773ab7d0dbb350bb40f78d8950961c0
/1.py
26fc628414b5bdc52a6e46febfa51d118f570d66
[ "MIT" ]
permissive
https://github.com/chauhanmahavir/Python-Basics
bde2adfaec4155f7756e479b3008bad4985ba808
c250a9eee203e1188a968ba2c60262442719fa49
refs/heads/master
2023-01-14T22:05:09.121935
2020-11-18T07:11:08
2020-11-18T07:11:08
285,190,795
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
print("this is my first example"); print('this is my first example') print('this is my first example'); print("I'have"); print('i say "Hello"'); print('I\'have'); print('hii'+' hello'); print(' hiii','hello'); #print('hello',5) #print('hello'+5) print('Another'); #print(5+'hello'); print('c/Users/Desktop/newfile')
UTF-8
Python
false
false
334
py
44
1.py
41
0.616766
0.607784
0
13
23.692308
34
uc-cdis/cloud-automation
11,020,886,108,583
187b373c5cb4b445ec117a368b3d0a1ccc164b5a
30a3fb90601e0e4a91e9792bce7ac668f3163c11
/apis_configs/fence_settings.py
eb2cf818d9462c3b2bb43dfc0da59102e01e155b
[ "Apache-2.0" ]
permissive
https://github.com/uc-cdis/cloud-automation
dbea462b2cb80db52fd6ebeb4a4ccc3c4a7a560c
607ef49e304358732f018c0c2c3c5ef8bdef2647
refs/heads/master
2023-09-01T15:54:29.625525
2023-08-31T15:38:47
2023-08-31T15:38:47
74,061,703
44
76
Apache-2.0
false
2023-09-14T19:17:56
2016-11-17T19:48:51
2023-06-27T02:57:01
2023-09-14T19:17:54
35,813
38
68
206
Shell
false
false
from boto.s3.connection import OrdinaryCallingFormat import config_helper APP_NAME = "fence" DB = "postgresql://{{db_username}}:{{db_password}}@{{db_host}}:5432/{{db_database}}" MOCK_AUTH = False MOCK_STORAGE = True EMAIL_SERVER = "localhost" SEND_FROM = "phillis.tt@gmail.com" SEND_TO = "phillis.tt@gmail.com" CEPH = { "aws_access_key_id": "", "aws_secret_access_key": "", "host": "", "port": 443, "is_secure": True, "calling_format": OrdinaryCallingFormat(), } AWS = {"aws_access_key_id": "", "aws_secret_access_key": ""} HMAC_ENCRYPTION_KEY = "{{hmac_key}}" HOSTNAME = "{{hostname}}" BASE_URL = "https://{{hostname}}/user" OPENID_CONNECT = { "google": { "client_id": "{{google_client_id}}", "client_secret": "{{google_client_secret}}", "redirect_url": "https://" + HOSTNAME + "/user/login/google/login/", } } HTTP_PROXY = {"host": "cloud-proxy.internal.io", "port": 3128} DEFAULT_DBGAP = { "sftp": { "host": "", "username": "", "password": "", "port": 22, "proxy": "", "proxy_user": "", }, "decrypt_key": "", } STORAGE_CREDENTIALS = {} # aws_credentials should be a dict looks like: # { identifier: { 'aws_access_key_id': 'XXX', 'aws_secret_access_key': 'XXX' }} AWS_CREDENTIALS = {} # s3_buckets should be a dict looks like: # { bucket_name: credential_identifie } S3_BUCKETS = {} def load_json(file_name): return config_helper.load_json(file_name, APP_NAME) def get_from_dict(dictionary, key, default=""): value = dictionary.get(key) if value is None: value = default return value creds = load_json("creds.json") key_list = ["db_username", "db_password", "db_host", "db_database"] DB = "postgresql://%s:%s@%s:5432/%s" % tuple( [get_from_dict(creds, k, "unknown-" + k) for k in key_list] ) HMAC_ENCRYPTION_KEY = get_from_dict(creds, "hmac_key", "unknown-hmac_key") HOSTNAME = get_from_dict(creds, "hostname", "unknown-hostname") BASE_URL = "https://%s/user" % HOSTNAME OPENID_CONNECT["google"]["client_id"] = get_from_dict( creds, "google_client_id", "unknown-google_client_id" ) OPENID_CONNECT["google"]["client_secret"] = get_from_dict( creds, "google_client_secret", "unknown-google_client_secret" ) OPENID_CONNECT["google"]["redirect_url"] = ( "https://" + HOSTNAME + "/user/login/google/login/" ) GOOGLE_MANAGED_SERVICE_ACCOUNT_DOMAINS = { "dataflow-service-producer-prod.iam.gserviceaccount.com", "cloudbuild.gserviceaccount.com", "cloud-ml.google.com.iam.gserviceaccount.com", "container-engine-robot.iam.gserviceaccount.com", "dataflow-service-producer-prod.iam.gserviceaccount.com", "sourcerepo-service-accounts.iam.gserviceaccount.com", "dataproc-accounts.iam.gserviceaccount.com", "gae-api-prod.google.com.iam.gserviceaccount.com", "genomics-api.google.com.iam.gserviceaccount.com", "containerregistry.iam.gserviceaccount.com", "container-analysis.iam.gserviceaccount.com", "cloudservices.gserviceaccount.com", "stackdriver-service.iam.gserviceaccount.com", "appspot.gserviceaccount.com", "partnercontent.gserviceaccount.com", "trifacta-gcloud-prod.iam.gserviceaccount.com", "gcf-admin-robot.iam.gserviceaccount.com", "compute-system.iam.gserviceaccount.com", "gcp-sa-websecurityscanner.iam.gserviceaccount.com", "storage-transfer-service.iam.gserviceaccount.com", } CIRRUS_CFG = {} data = load_json("fence_credentials.json") if data: AWS_CREDENTIALS = data["AWS_CREDENTIALS"] S3_BUCKETS = data["S3_BUCKETS"] DEFAULT_LOGIN_URL = data["DEFAULT_LOGIN_URL"] OPENID_CONNECT.update(data["OPENID_CONNECT"]) OIDC_ISSUER = data["OIDC_ISSUER"] ENABLED_IDENTITY_PROVIDERS = data["ENABLED_IDENTITY_PROVIDERS"] APP_NAME = data["APP_NAME"] HTTP_PROXY = data["HTTP_PROXY"] dbGaP = data.get("dbGaP", DEFAULT_DBGAP) CIRRUS_CFG["GOOGLE_API_KEY"] = get_from_dict(data, "GOOGLE_API_KEY") CIRRUS_CFG["GOOGLE_PROJECT_ID"] = get_from_dict(data, "GOOGLE_PROJECT_ID") CIRRUS_CFG["GOOGLE_ADMIN_EMAIL"] = get_from_dict(data, "GOOGLE_ADMIN_EMAIL") CIRRUS_CFG["GOOGLE_IDENTITY_DOMAIN"] = get_from_dict(data, "GOOGLE_IDENTITY_DOMAIN") CIRRUS_CFG["GOOGLE_CLOUD_IDENTITY_ADMIN_EMAIL"] = get_from_dict( data, "GOOGLE_CLOUD_IDENTITY_ADMIN_EMAIL" ) STORAGE_CREDENTIALS = get_from_dict(data, "STORAGE_CREDENTIALS", {}) GOOGLE_GROUP_PREFIX = get_from_dict(data, "GOOGLE_GROUP_PREFIX", "gen3") SUPPORT_EMAIL_FOR_ERRORS = get_from_dict(data, "SUPPORT_EMAIL_FOR_ERRORS", None) WHITE_LISTED_SERVICE_ACCOUNT_EMAILS = get_from_dict( data, "WHITE_LISTED_SERVICE_ACCOUNT_EMAILS", [] ) WHITE_LISTED_GOOGLE_PARENT_ORGS = get_from_dict( data, "WHITE_LISTED_GOOGLE_PARENT_ORGS", [] ) GOOGLE_MANAGED_SERVICE_ACCOUNT_DOMAINS.update( data.get("GOOGLE_MANAGED_SERVICE_ACCOUNT_DOMAINS", []) ) GUN_MAIL = data.get("GUN_MAIL") REMOVE_SERVICE_ACCOUNT_EMAIL_NOTIFICATION = data.get( "REMOVE_SERVICE_ACCOUNT_EMAIL_NOTIFICATION" ) # use for intergration tests to skip the login page MOCK_GOOGLE_AUTH = data.get("MOCK_GOOGLE_AUTH", False) CIRRUS_CFG[ "GOOGLE_APPLICATION_CREDENTIALS" ] = "/var/www/fence/fence_google_app_creds_secret.json" CIRRUS_CFG[ "GOOGLE_STORAGE_CREDS" ] = "/var/www/fence/fence_google_storage_creds_secret.json" DEFAULT_LOGIN_URL_REDIRECT_PARAM = "redirect" INDEXD = "http://indexd-service/" ARBORIST = "http://arborist-service/"
UTF-8
Python
false
false
5,539
py
1,395
fence_settings.py
339
0.665463
0.661311
0
170
31.582353
88
wawdh01/Shell-Scripting
8,031,588,843,900
3636f970b59ba817a5725d3e1562643a4d9fd698
20783f464f2f5b5583fe58bac3809716adcf58cc
/prog7.py
a90f328d0ae751aadb196f85fc2fcd312aa142ee
[]
no_license
https://github.com/wawdh01/Shell-Scripting
eba01372978a03bf2d168df8ffe64d7e91d759f7
e5a9cdefc051b58814b75d4382e6fe0dcc50dbce
refs/heads/master
2023-01-31T20:31:57.384413
2020-12-18T14:31:19
2020-12-18T14:31:19
322,617,621
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
a = int(input("Enter 1st Number:")) b = int(input("Enter 2nd Number:")) c = int(input("Enter 3rd Number:")) if (a > b and a > c): print(a ," is greater") elif (b > a and b > c): print(b, " is greater") else: print(c, " is greater")
UTF-8
Python
false
false
251
py
38
prog7.py
37
0.549801
0.537849
0
9
26.111111
35
bimbocant/lpthw
15,582,141,371,630
05754abe51e67a8061cc46c4b158c48575f95ba5
ac60de744e7fa0514a5c884f8f220852daf93059
/build/lib/ex48/lexicon.py
23608ec4aaedee26c97a8c7cf65683b5fa686257
[]
no_license
https://github.com/bimbocant/lpthw
dd5a9acd7a3a2d01edeebed69352dfafe35c6af3
924f8e2d8342f111455d88445e730369bd496c9c
refs/heads/master
2020-03-22T14:15:32.003981
2018-07-08T16:11:28
2018-07-08T16:11:28
140,164,941
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
lex=[('direction','north'), ('direction','south'), ('direction','east'), ('verb','go'), ('verb','eat'), ('verb','kill'), ('stop','the'), ('stop','in'), ('stop','of'), ('noun','princess'), ('noun','bear')] #returns the tuple of the given direction def scan(string): word_list=string.split() result=[] appended=False for word in word_list: for t in lex: if word.lower() in t and appended==False: result.append(t) appended=True #word is not in lex so it's a number or an error if appended==False: try: num=int(word) result.append(('number',num)) except ValueError as e: result.append(('error',word)) appended=False return result
UTF-8
Python
false
false
927
py
4
lexicon.py
3
0.451996
0.451996
0
31
28.903226
57
5l1v3r1/skb
6,038,724,022,973
ca698495f187851dcfb8a2801cccbf61483480b4
45ceab8899bca822d403e29645bac3c7a5b9e77c
/core/migrations/0001_initial.py
bc1d31c20ec18d129338579fc4df9c67c144c5d1
[]
no_license
https://github.com/5l1v3r1/skb
1ed4bd2c335d30eb016fa26aa5353fbcba2acaa2
6fe1df0ffb4350645daa24cb195c47b747865b55
refs/heads/master
2021-03-31T07:51:48.081781
2020-02-23T07:47:13
2020-02-23T07:47:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 2.1.4 on 2019-01-11 18:49 import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ('photolog', '0001_initial'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('avatar', models.ImageField(blank=True, null=True, upload_to='avatars')), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'verbose_name': 'user', 'verbose_name_plural': 'users', 'abstract': False, }, managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), migrations.CreateModel( name='DefInfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ph', models.CharField(blank=True, max_length=15, null=True, verbose_name='Телефон')), ('soc', models.CharField(max_length=200, verbose_name='Соцсеть')), ('email', models.EmailField(max_length=200, verbose_name='Почта')), ], options={ 'verbose_name': 'Основную информацию', 'verbose_name_plural': 'Основная информация', }, ), migrations.CreateModel( name='Materials', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200, verbose_name='Название')), ('logo', models.ImageField(blank=True, null=True, upload_to='logos', verbose_name='Картинка')), ('description', models.TextField(blank=True, null=True, verbose_name='Описание')), ('catalog', models.ManyToManyField(blank=True, to='photolog.Catalog', verbose_name='Каталоги')), ], options={ 'verbose_name': 'Материалы', 'verbose_name_plural': 'Материалы', }, ), migrations.CreateModel( name='MaterialsType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200, verbose_name='Название')), ], options={ 'verbose_name': 'Типы материалов', 'verbose_name_plural': 'Тип материалов', }, ), migrations.CreateModel( name='Partitions', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200, verbose_name='Заголовок')), ('description', models.CharField(blank=True, max_length=160, null=True, verbose_name='Краткое описание')), ('keywords', models.CharField(blank=True, max_length=255, null=True, verbose_name='Ключевые слова')), ('status', models.CharField(choices=[('draft', 'Черновик'), ('published', 'Опубликовано')], default='draft', max_length=10, verbose_name='Статус')), ('url', models.CharField(db_index=True, max_length=100, verbose_name='URL')), ('cover', models.ImageField(blank=True, null=True, upload_to='cover', verbose_name='Обложка')), ('content', models.TextField(blank=True, verbose_name='Содержание')), ('template_name', models.CharField(blank=True, help_text="Пример: 'core/contact_page.html'", max_length=70, verbose_name='Имя шаблона')), ], options={ 'verbose_name': 'Страницы', 'verbose_name_plural': 'Страницы', 'ordering': ('url',), }, ), migrations.CreateModel( name='StandardModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200, verbose_name='Название')), ('article', models.CharField(max_length=10, unique=True, verbose_name='Артикул')), ('qdoors', models.SmallIntegerField(choices=[(2, '2'), (3, '3'), (4, '4')], default=2, verbose_name='Количество дверей')), ('type_case', models.CharField(choices=[('case', 'Корпусной'), ('built-in', 'Встроенный')], default='case', max_length=10, verbose_name='Тип корпуса')), ('angular', models.BooleanField(default=False, verbose_name='Угловой')), ('description', models.TextField(blank=True, null=True, verbose_name='Описание')), ('height1', models.SmallIntegerField(default=2200, verbose_name='Высота от')), ('height2', models.SmallIntegerField(default=2400, verbose_name='Высота до')), ('width1', models.SmallIntegerField(default=1200, verbose_name='Ширина от')), ('width2', models.SmallIntegerField(default=2000, verbose_name='Ширина до')), ('depth', models.SmallIntegerField(default=600, verbose_name='Глубина')), ('materials', models.ManyToManyField(blank=True, to='core.Materials', verbose_name='Материалы')), ('phobj', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='photolog.PhotoObject', verbose_name='Фотообъект')), ], options={ 'verbose_name': 'Базовый шкаф', 'verbose_name_plural': 'Базовые шкафы', }, ), migrations.CreateModel( name='StandartDoors', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200, verbose_name='Название')), ('article', models.CharField(max_length=10, unique=True, verbose_name='Артикул')), ('qdoors', models.SmallIntegerField(choices=[(2, '2'), (3, '3'), (4, '4')], default=2, verbose_name='Количество дверей')), ('description', models.TextField(blank=True, null=True, verbose_name='Описание')), ('img', models.ImageField(blank=True, null=True, upload_to='doors', verbose_name='Картинка')), ('materials', models.ManyToManyField(blank=True, to='core.Materials', verbose_name='Материалы')), ], options={ 'verbose_name': 'Базовая дверь', 'verbose_name_plural': 'Базовые двери', }, ), migrations.AddField( model_name='materials', name='mattype', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.MaterialsType', verbose_name='Тип материалов'), ), ]
UTF-8
Python
false
false
9,800
py
76
0001_initial.py
46
0.590709
0.577912
0
148
61.831081
329
Ignotus111/PurBeurre
13,804,024,933,668
ba3584b4aaa2e8ea1878028a5a04aa0807970c0a
fbb473e043c5b77f666434c02200684c08218833
/dbcreation.py
14dad56f3a3525c84f163f0e0cf6fafc68ec061d
[]
no_license
https://github.com/Ignotus111/PurBeurre
2371327ef6858127d5fe67256d6545940dc3ffe5
1ee10b108262830c8fed6c8eaa205be217d08eae
refs/heads/develop
2023-05-26T11:16:58.616491
2020-11-05T11:49:35
2020-11-05T11:49:35
277,505,669
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import mysql.connector from constants import (NB_CATEGORY, NB_PAGEPRODUCT, cat_link, PASSWORD, USER, HOST) from classes.categories import Categories from classes.products import Product from classes.categoryproduct import Categoryproduct import requests import json connection = mysql.connector.connect(host=HOST, user=USER, password=PASSWORD) mycursor = connection.cursor() def execsqlfile(sql_file): """Reads and executes instructions of a .sql file.""" statement = "" for line in open(sql_file): if line.strip().endswith(";"): statement = statement + line mycursor.execute(statement) statement = "" else: statement = statement + line connection.commit() mycursor.close() def requestprod(cat, link): """Save products in the database.""" i = 1 urls = [] """Saving number of pages.""" while i < NB_PAGEPRODUCT + 1: urls.append(link + "/" + str(i)) i += 1 """For each page of a catagory from OpenFoodFacts, takes data of all fields.(id product_name...) Then creates a Product object and save it in database.""" for locc in urls: response = requests.request("GET", locc + ".json") json_prod = response.json() products_prod = json_prod.get("products") prod_info = [ Product( data.get("id"), data.get("product_name"), data.get("generic_name"), data.get("url"), data.get("stores"), data.get("nutriscore_grade"), )for data in products_prod ] product_barcode = [(data.get("id"),) for data in products_prod] """Fills Categoryproduct table.""" for elem in product_barcode: catprod = Categoryproduct(cat, elem[0]) catprod.save() Product.saveMany(prod_info) def requestcat(): """Takes categories names et urls.""" response = requests.request("GET", cat_link) json_cat = response.json() tags_cat = json_cat.get("tags")[:NB_CATEGORY] name_cat = [(data.get("name"),) for data in tags_cat] link_cat = [(data.get("url"),) for data in tags_cat] categories = [Categories(elem[0]) for elem in name_cat] """Creates a Categories object with names and save it in database.""" Categories.saveMany(categories) """For each urls, calls requestprod.""" for index, cat in enumerate(name_cat): requestprod(cat[0], link_cat[index][0])
UTF-8
Python
false
false
2,540
py
10
dbcreation.py
9
0.602362
0.599606
0
74
33.324324
77
OusmaneKana/Python_Journey
15,556,371,592,433
30d19f2850a6667716e86a9b05f502db69c1403e
827d45bf52dd5da7b83d30f8ba14965414dd4fd9
/OOP/OOP.py
76c54a22808ca0f38f33cd89fccfb94edf245dd2
[]
no_license
https://github.com/OusmaneKana/Python_Journey
046bb878846ba1e02c4ce9ca4f216ab74f4d49b8
c8cf4fb728f4b2aee48e5482c504be57e04a8ff6
refs/heads/master
2022-03-29T02:16:01.148588
2020-01-30T05:15:19
2020-01-30T05:15:19
122,021,015
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
# This is a quick program to illustrate the basics of OOP in python class Dog(): def __init__(self, name, breed, age, smart): self.breed = breed self.name = name self.age = age self.smart = smart def bark (self): print ("WOOF WOOF!! My name is {} and I am {}".format(self.name, self.age)) my_dog = Dog(name = "BoBy", breed = "Hoksy", age = 25, smart = True) my_dog.bark()
UTF-8
Python
false
false
392
py
19
OOP.py
15
0.630102
0.625
0
16
23.5
77
eldioschalm/novo_portal
13,829,794,726,233
56419a14bb254142cbf7f2cff2a0ef51a276027b
60676a82606b622324c7a087d32b5a96390a85b9
/portal/banner/tests/test_models.py
7bed6aecf5b94d2bf8a7e8eb2e31c7bf2cf4b4cb
[]
no_license
https://github.com/eldioschalm/novo_portal
d497cc30e7f8eb05f421c2a47c05b0b7ab1faf87
31d58b3b90241a6cf9a765ec84c0a5fe8c786852
refs/heads/master
2022-12-04T06:56:53.901071
2020-01-20T14:36:50
2020-01-20T14:36:50
18,217,799
0
0
null
false
2022-11-22T02:46:57
2014-03-28T15:59:05
2020-01-20T14:37:15
2022-11-22T02:46:55
182,564
0
0
7
CSS
false
false
#coding: utf-8 from django.test.testcases import TestCase from django.conf import settings from django.utils import timezone from django.core.files import File from filer.models import Image from portal.banner.models import Banner from portal.core.tests.util import del_midia_filer class BannerTest(TestCase): def setUp(self): self.img_path = settings.BASE_DIR + '/portal/banner/static/img/images.jpeg' self.img_name = u'imagembanner' with open(self.img_path) as img: file_obj = File(img, name=self.img_name) midia_image = Image.objects.create(original_filename=self.img_name, file=file_obj) self.banner = Banner( titulo=u'BannerTesteTitulo', data_publicacao=timezone.now(), arquivo=midia_image, publicado=True, tipo=1, ) def test_criacao(self): """ Banner deve possuir titulo, data de publicacao e midia """ self.banner.save() self.assertIsNotNone(self.banner.pk) def test_unicode(self): """ Banner deve apresentar o titulo como unicode """ self.assertEqual(u'BannerTesteTitulo', unicode(self.banner)) def test_esta_publicado(self): """ Testa se um banner esta publicado ou nao. A condicao para que um banner seja considerado como publicado e que esteja marcado como publicado e a data de publicacao seja anterior a data atual """ # data de 1 dia antes de hoje self.banner.data_publicacao = timezone.now() - timezone.timedelta(days=1) self.banner.publicado = True self.assertTrue(self.banner.esta_publicado) self.banner.publicado = False self.assertFalse(self.banner.esta_publicado) # data de 1 dia depois de hoje self.banner.data_publicacao = timezone.now() + timezone.timedelta(days=1) self.banner.publicado = True self.assertFalse(self.banner.esta_publicado) # data de 1 dia antes de hoje self.banner.data_publicacao = timezone.now() - timezone.timedelta(days=1) self.banner.publicado = False self.assertFalse(self.banner.esta_publicado) def tearDown(self): del_midia_filer(self.img_name)
UTF-8
Python
false
false
2,272
py
122
test_models.py
74
0.652289
0.648768
0
65
33.953846
117
jhgdike/myWebSite
15,324,443,323,523
7d5b2582bd1b94381af67e5f8c2d61dc4bd82de5
43d425e3ed9e6f56f43b980cfdea4c9ac00cbbef
/handlers/login_handler.py
e0fa3ae9384ff9dfd5e22c45ae7a1cb4e3e70638
[]
no_license
https://github.com/jhgdike/myWebSite
e7a4cfc437b887073ca37c1042d8a4b9ce447ab1
fccfaa29443fdca37635c4ca53146e0e78a8eadf
refs/heads/master
2016-08-10T17:55:04.634397
2016-01-14T06:04:35
2016-01-14T06:04:35
49,626,024
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# coding:utf-8 import os, sys, re import tornado.web import tornado.httpserver from handlers.base_handler import BaseHandler class LoginHandler(BaseHandler): def get(self, action): self.loginPage() def loginPage(self): self.render('login.html')
UTF-8
Python
false
false
272
py
6
login_handler.py
6
0.713235
0.709559
0
13
19.923077
45
choifish/project-euler
1,529,008,395,717
dcc815e763841f6cc2648cacca67b4c8cefdbc7b
d9676724e91ae59ea281dd8db5e12eb4ee436058
/Problem025.py
df475ab3b9ee266b589c74412f13c88ae7b92fc4
[]
no_license
https://github.com/choifish/project-euler
eba10dcad526cfebf89712197499288d25fcd37b
98474f7da8cc652c52ecf01d64e7f7aa7a246e1f
refs/heads/master
2021-01-22T02:47:55.616382
2013-05-22T19:05:13
2013-05-22T19:05:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#=============================================================================== # What is the first term in the Fibonacci sequence to contain 1000 digits? #=============================================================================== a, b, term = 0, 1, 0 while True: term += 1 if len(str(b)) == 1000: break b += a a = b - a print(term)
UTF-8
Python
false
false
374
py
62
Problem025.py
62
0.304813
0.272727
0
12
29.333333
80
arushi-11/Projects-In-Python
18,571,438,589,159
5022965369f3f1fcc3436ce218c933badc58c714
884222c8030519fbc8cbb921afab7aaeb92fbf32
/decision_making_tree.py
86d1c46e5dd2674804be8c2b101e6fe4c48da78f
[]
no_license
https://github.com/arushi-11/Projects-In-Python
0df56dcf851ce4a774b9399e2c89b382783f4057
b45d8272d37e7651494aa4780a0e780643dfdbe2
refs/heads/main
2023-04-04T16:27:51.327861
2021-04-08T14:18:34
2021-04-08T14:18:34
303,289,431
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
print("1)TABLE OF YOUR GIVEN NUMBER\n2)ADDITION\n3)SUBTRACTION\n4)MULTIPLICATION\n5)DIVISION\n6)DESIGN PATTERNS\n7)DRAW SHAPES") temp=int(input("enter your choice within 1-7:")) if(temp==1): p=int(input("Enter the number of which you want to print table:")) for i in range(1,11): print(p,"*",i,"=",p*i) if(temp==2): p=int(input("Enter first number")) q=int(input("Enter second number")) r=p+q print("Result is ",r) if(temp==3): p=int(input("Enter first number")) q=int(input("Enter second number")) r=p-q print("Result is ",r) if(temp==4): p=int(input("Enter first number")) q=int(input("Enter second number")) r=p*q print("Result is ",r) if(temp==5): p=int(input("Enter first number")) q=int(input("Enter second number")) r=p/q print("Result is ",r) if(temp==6): print("---:PATTERN DESIGNS:---") print("1)****\n ****\n ****\n ****\n\n2)1\n 2 3\n 4 5 6\n\n3)*\n * *\n * * *") p=int(input("Enter any choice 1-3:->")) if(p==1): for i in range(4): for j in range(4): print("*",end=' ') print("\n") if(p==2): x=1 for i in range(1,4): for j in range(i): print(x,end=' ') x+=1 print("\n") if(p==3): for i in range(1,4): for j in range(i): print("*",end=' ') print("\n") if(temp==7): print("---:SHAPE DESIGNING:---") print("1)Make a circle\n2)Make a square\n3)Make triangle") p=int(input("Enter your choice 1-3:->")) import turtle x=turtle.Turtle() if(p==1): z=int(input("Enter the radius of the circle")) x.begin_fill() x.fillcolor("red") x.circle(z) x.end_fill() if(p==2): z=int(input("Enter the sides of square")) x.begin_fill() x.fillcolor("blue") for i in range(4): x.forward(z) x.left(90) x.end_fill() if(p==3): z=int(input("Enter the sides of triangle")) x.begin_fill() x.fillcolor("red") x.circle(z,steps=3) x.end_fill()
UTF-8
Python
false
false
2,194
py
7
decision_making_tree.py
6
0.501823
0.477666
0
73
29
128
noelsebu/djangobackend
19,198,503,842,207
165c10f94f4921e96b7b932b2547b5e663cbba03
6a629e3f97694594b55cae1279a60689c773672a
/py/lib/python3.7/site-packages/django_google/models.py
c7b5a042a9d72d37dd2c7afffaa284d901b07d94
[]
no_license
https://github.com/noelsebu/djangobackend
209a7e1bcc6fa6a6ea7a68992b04f6fbe8172db3
93a33b88c02f0a47127bf29e7b4a68c04f0743eb
refs/heads/master
2022-12-23T21:07:35.066239
2020-06-16T14:57:32
2020-06-16T14:57:32
272,730,108
0
2
null
false
2020-06-16T22:01:05
2020-06-16T14:28:46
2020-06-16T15:37:43
2020-06-16T15:36:39
167,486
0
1
2
Python
false
false
from django.db import models from google.auth.transport.requests import Request import pickle from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class GoogleAuth(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='oauth_google') _creds = models.BinaryField() def set_data(self, data): self._creds = pickle.dumps(data) def get_data(self): credentials = pickle.loads(self._creds) if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) self._creds = pickle.dumps(credentials) self.save() return pickle.loads(self._creds) creds = property(get_data, set_data) def __str__(self): return self.user.email class Meta: verbose_name = "Google Authentication" verbose_name_plural = "Google Authentications"
UTF-8
Python
false
false
954
py
43
models.py
31
0.675052
0.675052
0
32
28.78125
92
Priestch/luoo-server
16,810,502,023,576
4c988e0a4bf2b258cd5a37379348d8702a16e121
67c7ef48c17028ad1e0c4c01c81244e56cd76d25
/luoo/schema/volume.py
2cc4755d8f567d343ead4142e52404ecb772d344
[]
no_license
https://github.com/Priestch/luoo-server
056b843b5f9941ab6f44aa017560c3f6decf6c6e
e028885a6f08b01fd66b7c28feb4129c091bb40a
refs/heads/master
2022-01-30T05:50:28.955821
2019-03-31T14:03:28
2019-03-31T14:03:28
78,432,067
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from marshmallow import fields from marshmallow_sqlalchemy import ModelSchema from luoo.models import Volume, Tag class VolumeSchema(ModelSchema): class Meta: model = Volume cover = fields.Method("get_volume_cover") def get_volume_cover(self, obj): return obj.cover_url class TagSchema(ModelSchema): class Meta: model = Tag volume_schema = VolumeSchema() tag_schema = TagSchema()
UTF-8
Python
false
false
429
py
25
volume.py
21
0.703963
0.703963
0
23
17.652174
46
devilry/devilry-django
2,559,800,551,616
8427998884830b8e04aca175ad8ec7ecc04965b3
36ca932c7180738f501190f1d28c3a63e462c413
/devilry/devilry_message/migrations/0002_auto_20210427_1350.py
8ce8c8bfca4411349f4b9f79da90d71c25400508
[]
permissive
https://github.com/devilry/devilry-django
4e2741f29fcf2ae6b75690e9cd0cded154decf6e
a3355fe78992466cfcae8b166128bf51ddbb26d0
refs/heads/master
2023-08-08T22:00:58.952030
2023-07-21T13:17:27
2023-07-21T13:17:27
486,298
42
22
BSD-3-Clause
false
2023-07-21T13:38:30
2010-01-24T13:31:14
2023-04-19T22:37:03
2023-07-21T13:38:30
114,288
48
23
82
Python
false
false
# Generated by Django 3.1.8 on 2021-04-27 11:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('devilry_message', '0001_initial'), ] operations = [ migrations.AlterField( model_name='message', name='metadata', field=models.JSONField(blank=True, default=dict), ), migrations.AlterField( model_name='message', name='status_data', field=models.JSONField(blank=True, default=dict), ), migrations.AlterField( model_name='message', name='virtual_message_receivers', field=models.JSONField(blank=True, default=dict), ), migrations.AlterField( model_name='messagereceiver', name='metadata', field=models.JSONField(blank=True, default=dict), ), migrations.AlterField( model_name='messagereceiver', name='status_data', field=models.JSONField(blank=True, default=dict), ), ]
UTF-8
Python
false
false
1,104
py
1,514
0002_auto_20210427_1350.py
868
0.564312
0.547101
0
38
28.052632
61
Meso272/cwae
2,095,944,052,664
1f2c9a987465f044a698d0a22ee7503aa95e03c4
c50b8b763585e61fdae05e8c5de4fdc314e8ba5e
/src/architectures/celeba_architecture_provider.py
48c85ac8df7b91eba8f1c9711c83c82a520030c7
[ "MIT" ]
permissive
https://github.com/Meso272/cwae
0008b11f906d787f450e38613bfe828ba6e378b5
50592903c321de25f339f3b00cbd2143741e5037
refs/heads/master
2022-12-13T08:00:17.659966
2020-09-17T16:31:56
2020-09-17T16:31:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import tensorflow as tf class CelebaArchitectureProvider: def encoder_builder(self, x, z_dim: int): h = x for i, filter_count in enumerate([32, 32, 64, 64]): h = tf.layers.conv2d(x, kernel_size=(4, 4), strides=(2, 2), padding='same', activation=tf.nn.relu, filters=filter_count, name=f'Encoder_Conv_{i}') h = tf.layers.flatten(h, name='Encoder_Flatten') h = tf.layers.dense(h, units=1024, activation=tf.nn.relu, name='Encoder_FC_0') h = tf.layers.dense(h, units=256, activation=tf.nn.relu, name='Encoder_FC_1') return tf.layers.dense(h, z_dim, name=f'Encoder_output') def decoder_builder(self, z, x_dim: int): h = tf.layers.dense(z, units=256, activation=tf.nn.relu, name='Decoder_FC_0') h = tf.layers.dense(z, units=1024, activation=tf.nn.relu, name='Decoder_FC_1') h = tf.reshape(h, [-1, 4, 4, 64]) for filter_count in [64, 32, 32, 3]: h = tf.layers.conv2d_transpose(h, kernel_size=(4, 4), strides=(2, 2), activation=tf.nn.relu, filters=filter_count, padding='same', name='Decoder_Deconv_1') return h
UTF-8
Python
false
false
1,206
py
21
celeba_architecture_provider.py
19
0.58209
0.541459
0
24
49.25
111
xm4dn355x/specialist_python3_2nd_lvl
6,717,328,880,262
5b25d15f9a7145ae7ac88767a1583ec235844890
79364cf7572e9241ffb6603303ee74ec59e466b4
/Module02/practice/01_task_deck.py
4b109d17c3f2d5eb253e4673665f86d02dede60c
[ "MIT" ]
permissive
https://github.com/xm4dn355x/specialist_python3_2nd_lvl
e4ae312db7410ed21a20f122a1c2e7551bc54acf
4ea8c82eb0f32aa92c82914f6599c2c47a2f7032
refs/heads/main
2023-04-10T18:50:34.970865
2021-04-26T14:04:27
2021-04-26T14:04:27
355,071,612
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Начнем с создания карты class Card: HEARTS = 'Hearts' DIAMONDS = 'Diamonds' SPADES = 'Spades' CLUBS = 'Clubs' SUITS = { HEARTS: '♥', DIAMONDS: '♦', SPADES: '♣', CLUBS: '♠', } def __init__(self, value, suit): self.value = value self.suit = suit self.suits_power = { 'Hearts': 3, 'Diamonds': 2, 'Spades': 1, 'Clubs': 0 } self.values = { '2': 0, '3': 1, '4': 2, '5': 3, '6': 4, '7': 5, '8': 6, '9': 7, '10': 8, 'J': 9, 'Q': 10, 'K': 11, 'A': 12, } def __str__(self): return self.to_str() def to_str(self): return f'{self.SUITS[self.suit]}{self.value}' def equal_suit(self, other_card): if self.suit == other_card.suit: return True else: return False def more(self, other_card): if self.values[self.value] == other_card.VALUES[other_card.value]: if self.suits_power[self.suit] > other_card.SUITS_POWER[other_card.suit]: return True else: return False elif self.values[self.value] == other_card.VALUES[other_card.value]: return True else: return False def less(self, other_card): are_more = self.more(other_card) if are_more: return False else: return True # Создадим несколько карт card1 = Card('10', Card.HEARTS) card2 = Card("A", Card.DIAMONDS) # Выведем карты на экран в виде: 10♥ и A♦ print(card1.to_str()) print(card2.to_str()) # Проверим, одинаковые ли масти у карт if card1.equal_suit(card2): print(f"У карт: {card1.to_str()} и {card2.to_str()} одинаковые масти") else: print(f"У карт: {card1.to_str()} и {card2.to_str()} разные масти") if card1.more(card2): print(f"Карта {card1.to_str()} больше чем {card2.to_str()}") else: print(f"Карта {card1.to_str()} меньше чем {card2.to_str()}") if __name__ == '__main__': print(Card(2, 'Diamonds'))
UTF-8
Python
false
false
2,393
py
62
01_task_deck.py
61
0.487607
0.464624
0
92
23.130435
85
chmuraw/iSA-python
2,834,678,429,319
3e592c2b0256656e0a84a5201b0a0e0443e431e2
2f0bd0482051c3a176f4cc965d5211620c1dfb1b
/Praca_zajecia/przedtestem.py
ac5075fc3a525da1de41f63ae894b56d21822748
[]
no_license
https://github.com/chmuraw/iSA-python
b300c982742f3da674d0bdd6d076066993fa7886
a7082eab333e5033635d662b3aee036cd66c913d
refs/heads/master
2020-08-31T00:37:33.194608
2019-12-10T18:18:09
2019-12-10T18:18:09
218,536,216
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# system binarny = dwojkowy (zera i jedynki) # algorytm skonczony zestaw polecen potrzebnych do wykonania zadania # zlozonosc algorytmiczna (obliczeniowa) - poziom skomplikowania algorytmu # (im mniejsza tym lepiej - jak najmniej opercaji, jak najmniej petli itd) # input() - metoda do pobrania czegos od uzytkownika # print() - metoda wyswietlania czegos uzytkownikowi w konsoli # zmienna - nazwany obszar pamieci # deklarowanie zmiennej (pojedynczy znak rownosci) # dom = "bialy" # typy danych w pythonie: int, str, float, bool, tuple, dict, list, set(ale o tym nie mowilismy) # tworzenie listy: # litery = ["A", "B", "C", "D", "E"] # litery = list("ABCDE") # print(litery) # ITEROWALNY - mozna go rozlozyc na czesci. str jest iterowalny # wyraz = "wyraz" # for litera in wyraz: # print(litera, end =" ") # wyswietli wszystkie litery w jednej linii # print(litera) #wyswietli litery jedna pod druga # slownik z imineiem i nazwiskiem (wszystko w klamrach i klucze w cudzyslowiach) # osoba = {"imie": "Jan", "nazwisko" : "Kowalski", "wiek": 18} # print("Kowalski"[2:6:1]) # wals !!! jedynka na koncu dla sciemy, bo i tak jest domyslna # print("Kowalski"[1:1:1] # nic nie wyjdzie. # z czego sklada sie funkcji: minimalistycznie - potrzebna jest tylko nazwa ;) # def nazwa(): # pass # # poza nazwa moze miec parametry domyslne lub niedomyslne - pozycyjne (kolejnosc definiowania jest wazna) # def nazwa(arg1, arg2, arg3 = "war3", *args, **kwargs): #arg3 - parametr nazwany, args i kwargs moga miec jakies nazwy # # jedna gwiazdka oznacza nieskonczona ilosc pozycyjnych argumentow, a ** nieskonczona ilosc key walues - przechodzi w slownik # # # no i zmienna musi miec jakies cialo: # zmienna = 1 # inna_zmienna = 2 # return "ala ma kota" # # jak funkcja nie ma returna to zwraca None # def funkcja(*args): # print(args) # funkcja(1, 3, 6, 7, 8.2,"ala ma kota", "grudzien") # dzieki args moge te wszystkie rozne elementy miec w swojej funkcji # funkcja("2019") # def funkcjakwargs(**kwargs): # print(kwargs) # funkcjakwargs(param = "grudzien", arg = 2) # dzieki args moge te wszystkie rozne elementy miec w swojej funkcji # funkcjakwargs(rok = "2019") # mozna mieszac args i kwargs, alle w definiowaniu najpierw args potem kwargs # mutowalny - mozna zmieniac, niemutlowany - nie mozna zmieniac # robimy cos pod warunkiem: najmniejsyz mozliwy if sklada sie z warunku :) #else jest tylko jeden, a elifow moze byc nieskonczenie wiele # zmienna = "2" # if zmienna == "1": # elif zmienna == "2": # elif zmienna =="3": # else: # pass # operatory w ifach: # >, <, => itd # in - czy jeden element jest w innym elemencie # is - do sprawdzenia typu, albo true or false # not - zaprzeczenie # print(False and True and not False) = print(False and True and True) # and z jakakolwiek false da wynik false (tablica prawdy) # otwieranie plikow: open("nazwa/sciezka", "tryb") # w - jezeli plik istnieje, to zostanie wyczyszczony i zapisuje nowe, ewentualnie tworzy nowy plik jesli nie istnieje i zapisuje # wb - to samo, w trybie binarnym (zipy, obrazki, pikle) # r - odczyt. nie zapisuje, nie utworzy pliku jesli go nie ma. # r+ - odczyta i zapisze. nie utworzy pliku jesli go nie ma. # a - ??? - do sprawdzenia w domu # modul w pythonie - wyodrebniona czesc kodu do osobnego skryptu/pliku # importowanie modulow zewnetrznych: #import modul - importuje caly modul #from modul import klasa - importuje tylko czesc modulu # from modul import klasa as inna_nazwa - zaimportuje i bede uzywac pod inna nazwa # from katalog.podkatalog.modul import klasa as moja_nazwa # paradygmaty: enkapsulacja, polimorfizm, abstrakcja, dziedziczenie # dziedziczenie: tworzenie obiektu od ogolo do szczegolu. obiekt podrzedny przejmuje cechy wspolne nadrzednego (jesli nie deklaruje sie inaczej) # class Pies(zwierze) - klasa pies dziedziczy po zwierze # abstrakcja: zdefioniowany poziom szczegolowosci obiektow jesli chodzi o ich wlasciwosci i metody. # polimorfizm: definiowanie wspolnych metod dla roznefgo typu obiektow. (__xxx__) # enkapsulacja(hermetyzacja): definiowanie metod do dostepu do wlasciwosci obiektu # getter, setter, deletter na przyklad. # w pythonie wystepuja metody pseudoprywatne: ustawia sie to tak: self.__nazwa # self.__nazwa - wlasciwosc # def __nazwa(): pass - metoda # klasa vs obiekt - klasa to plan budowy domu a obiekt to ten dom # klasa to zdefiniowany plan/schemat, a obiekt to "namacalny byt" stworzony na podstawie tego planu. # wyjatek - nazwane bledy programu, ktore mozna "przeskoczyc" # try: # dzielenie = 9/0 # except ZeroDivisionError: # print("Blad") # else: # print("Gdy nie ma wyjatku") # finally: # print("Zawsze") # # jak zdefiniowac metode klasy: (cls!!!) # def Klasa(): # @classmethod # def metodaklasy(cls): # pass # # # jak zdefiniowac klase obiektu: # def metodaobiektu(self): # pass # # #metoda statyczna (niepowiazana ani z obiektem ani z klasa) # @staticmethod # def metodastatyczna(): # pass # # konstruktor klasy: # def __init(self): # self.cecha = 1 # self.inna_cecha = "bialy" # getter: # @property # def cecha(): # return self.__cecha # # # setter: zeby moc setter i deletter musi najpierw byc getter # @cecha.setter # def cecha(self, nowa_wartosc): # self.__cecha = nowa_wartosc # # @cecha.deleter # def cecha(self): # self,__cecha = None # # dziedziczenie: # class A(): # def f(self): # print("A") # class B(A): # def f(self): # print("B") # class C(A): # def f(self): # print("C") # class D(A): # pass # # A().f() #wyswietli A # B().f() # wyswietli B (bo napisalismy) # C().f() # wyswietli C # D().f() # wyswietli A #zakres widocznosci zmiennych (scope zmiennych) # zmienna = "dom" - zmienna jest bez zadnych tabulatorow, wiec jest globalna # def funkcja(): # zmienna = "Praca" # print(zmienna) #nawet jesli w funkcji deklarowana jest zmienna o tej zamej nazwie co gllobalna, to na koniec jak sie wywola to wyswietli sie ta globalna zmienna.
UTF-8
Python
false
false
6,127
py
26
przedtestem.py
20
0.693814
0.687775
0
187
31.770053
146
mitchelldirt/learning-python
13,975,823,607,678
0256bba93df5307446a5bc53c3c68eb5637f18f7
df233d3e2157b76019c5a558a099017590db98dd
/section10_OOP/getters_setters_python/main.py
e2654efd4281870a4e0e74c74dfafbbac2125704
[]
no_license
https://github.com/mitchelldirt/learning-python
860346a0793e72edfbae34ed94fb509f207b10d5
bb9fbc0c3dff0aff061f26aa1a02882aa4e2df74
refs/heads/main
2023-03-25T19:19:41.206338
2021-03-15T16:51:57
2021-03-15T16:51:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from enemy import Enemy, Troll, Vampire, VampireKing import random ugly_troll = Troll("Pug") print(ugly_troll) another_troll = Troll("Ug") print("Another troll - {}".format(another_troll)) brother = Troll("Urg") print(brother) ugly_troll.grunt() another_troll.grunt() brother.grunt() brother.take_damage(24) print(brother) old_vampire = Vampire("Olga") print(old_vampire) young_vampire = Vampire("Kelcy") print(young_vampire) young_vampire.take_damage(7) print(young_vampire) old_vampire.take_damage(30) print(old_vampire) # while young_vampire.alive: # young_vampire.take_damage(1) young_vampire._lives = 0 young_vampire._hit_points = 1 print(young_vampire) king_of_vampires = VampireKing("Dracula") print(king_of_vampires) while king_of_vampires.alive: king_of_vampires.take_damage(random.randint(10, 40))
UTF-8
Python
false
false
874
py
67
main.py
65
0.701373
0.687643
0
42
18.809524
56
bruggisser/cil-project
14,491,219,673,040
b03f5cd3847dbd170b6a50debe2e211e80cc9f47
4befa5e5e061e61b63d9f21d54924656bcb2b3f8
/get_model_performance.py
725025383709114e5ee42e879212317f0c39728d
[]
no_license
https://github.com/bruggisser/cil-project
c0966d516b307fa631150b500010bfd8e40dcb30
907c6c09d6867144ce2993278335b4fa0af67448
refs/heads/master
2023-06-26T04:48:20.309047
2021-07-30T07:26:36
2021-07-30T07:26:36
390,333,459
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from numpy import genfromtxt import os def calculate_validation_metrics(): SUFFIX = "_validation_set.csv" validation_files = [f for f in os.listdir("./data/") if SUFFIX in f] model_performance_file = open("./data/model_performance.csv", "w") model_performance_file.write("model,accuracy,precision,recall,f1") for validation_file in validation_files: df = genfromtxt("./data/" + validation_file, delimiter=",", skip_header=True) model = validation_file[:-len(SUFFIX)] TP, FP, TN, FN = 4 * (0.,) for row in df: if(row[1] == 1 and row[2] >= 0.5): TP += 1 continue elif(row[1] == 1 and row[2] < 0.5): FP += 1 continue elif(row[1] == 0 and row[2] < 0.5): TN += 1 continue elif(row[1] == 0 and row[2] >= 0.5): FN += 1 continue else: raise Exception("Impossible!") accuracy = (TP + TN) / (TP + FP + FN + TN) precision = TP / (TP + FP) recall = TP / (TP + FN) f1 = 2 * (recall * precision) / (recall + precision) print(50 * "-") print(f"Statistics for {model} model") print(50 * "-") print(f"Accuracy: {accuracy}") print(f"Precision: {precision}") print(f"Recall: {recall}") print(f"F1: {f1}") print(50 * "-") row = f"{model},{accuracy},{precision},{recall},{f1}\n" model_performance_file.write(row) model_performance_file.close() if __name__ == "__main__": calculate_validation_metrics()
UTF-8
Python
false
false
1,681
py
26
get_model_performance.py
21
0.498513
0.475907
0
52
31.346154
85
Dougie105/AnimalRehab
8,521,215,137,626
16e06171d6063e2aa91461cd2f584049ac078e19
3ef4edcdd3b35fceeb04587063a1dcf5080b97a3
/rehab/serializers.py
00393986e9a8ae3ac1984f9f20e567d035f5a9a6
[ "MIT" ]
permissive
https://github.com/Dougie105/AnimalRehab
603cc370a8e74d13b17864c5b3daf74e930805cb
75c007316787b031da49ef7ea9745ae17ddb040c
refs/heads/dev
2022-05-30T23:32:07.693748
2020-02-14T01:52:26
2020-02-14T01:52:26
239,007,663
0
6
MIT
false
2022-05-25T03:01:52
2020-02-07T19:31:29
2020-02-14T01:52:30
2022-05-25T03:01:51
2,560
0
3
5
JavaScript
false
false
from rest_framework import serializers from .models import Medicine, Animal, Log # Medicine serializers class MedicineSerializer(serializers.ModelSerializer): """Serialize medicine model.""" class Meta: """Create medicine serialization.""" model = Medicine fields = ['id', 'name', 'category','description'] # Animal serializers class AnimalSerializer(serializers.ModelSerializer): """Serialize animal model.""" class Meta: """Create animal serialization.""" model = Animal fields = ['id','vet', 'name', 'weight', 'entry_at', 'details', 'is_archived'] class CreateAnimalSerializer(serializers.ModelSerializer): """Serialization fields for creating animal.""" class Meta: """Create an animal.""" model = Animal fields = ['id', 'vet', 'name', 'weight', 'details'] # Log serializers class LogSerializer(serializers.ModelSerializer): """Serialize log model.""" class Meta: """Create log serialization.""" model = Log fields = ['id', 'animal', 'created_at', 'updated_at', 'description']
UTF-8
Python
false
false
1,123
py
36
serializers.py
21
0.640249
0.640249
0
43
25.116279
85
pauline-banye/school-scout-be-pjt-56
7,009,386,652,978
36fad9bd92c630b2917c127d60cebda0aff6858d
445d9dc25ea23fcd328bae324057967268e3cc5b
/user_auth/urls.py
bddc47bf8683d8a6ae69a6916649c7bfa0ba3789
[]
no_license
https://github.com/pauline-banye/school-scout-be-pjt-56
453deaa7d2da195d47989d06e65f99beecba1bcb
cc6d89295cfe0d61466ba4710e187aab4f033baf
refs/heads/main
2023-06-18T18:28:23.587183
2021-07-17T02:11:46
2021-07-17T02:11:46
378,136,031
0
0
null
true
2021-06-18T11:59:07
2021-06-18T11:59:06
2021-06-16T14:40:12
2021-06-16T09:43:31
1
0
0
0
null
false
false
from django.urls import path, include from .views import UserViewSet GET_OPTIONS = {'get': 'list'} RETRIEVE_OPTIONS = {'get': 'retrieve'} POST_OPTIONS = {'post': 'create'} LIST_OPTIONS = { 'get': 'list', 'post': 'create' } DETAIL_OPTIONS = { 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' } urlpatterns = [ path('', include('rest_auth.urls')), path('registration/', include('rest_auth.registration.urls')), path('users/', UserViewSet.as_view(GET_OPTIONS), name="users"), path('accounts/', include('allauth.urls')), ]
UTF-8
Python
false
false
600
py
49
urls.py
43
0.615
0.615
0
28
20.428571
67
aashishrana/MineSweeper_Problem
17,875,653,897,139
f0b84423c1dff9507ac45d5f4d3b47658e45ca23
deb8bf3b404f7b5f2b7ce9d8b5f56223cb9f1e32
/MineSweeper.py
282244aba2818ac2369430bf29eecdff25b29fb7
[]
no_license
https://github.com/aashishrana/MineSweeper_Problem
f50b2aeb7b9d1cb02c9c6e3395d7da193b238e92
9b980d92a49baabc80194e3c9550a147fd46cda1
refs/heads/master
2020-12-27T02:34:59.561815
2020-03-21T01:21:33
2020-03-21T01:21:33
237,735,405
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
count=0 for k in range(10): #Enter number of rows and column seperated by space m,n = map(int,input().split()) if m==0 and n==0: break #Enter the elements of the matrix in the form of '*' and '-' in the order M*N a = [(input().split())for y in range(m)] for i in range(m): for j in range(n): if a[i][j]=="*": if i<m-1 and j<n-1: if a[i+1][j+1]=="-" or a[i+1][j+1]==0: a[i+1][j+1]=1 elif type(a[i+1][j+1])==int : a[i+1][j+1]+=1 if i>0 and j>0: if a[i-1][j-1]=="-" or a[i-1][j-1]==0: a[i-1][j-1] =1 elif type(a[i-1][j-1])==int : a[i-1][j-1]+=1 if i>0: if a[i-1][j]=="-" or a[i-1][j]==0: a[i-1][j]=1 elif type(a[i-1][j])==int: a[i-1][j]+=1 if i>0 and j<n-1: if a[i-1][j+1]=="-" or a[i-1][j+1]==0: a[i-1][j+1]=1 elif type(a[i-1][j+1])==int: a[i-1][j+1]+=1 if j>0: if a[i][j-1]=="-" or a[i][j-1]==0: a[i][j-1]=1 elif type(a[i][j-1])==int : a[i][j-1]+=1 if j<n-1: if a[i][j+1]=="-" or a[i][j+1]==0: a[i][j+1]=1 elif type(a[i][j+1])==int: a[i][j+1]+=1 if i<m-1 and j>0: if a[i+1][j-1]=="-" or a[i+1][j-1]==0: a[i+1][j-1]=1 elif type(a[i+1][j-1])==int: a[i+1][j-1]+=1 if i<m-1: if a[i+1][j]=="-" or a[i+1][j]==0: a[i+1][j]=1 elif type(a[i+1][j])==int : a[i+1][j]+=1 elif a[i][j]=='-': a[i][j]=0 count+=1 print("\n\nField#",count, end="") for i in range(m): print("\n") for j in range(n): print(a[i][j],end=" ")
UTF-8
Python
false
false
2,339
py
2
MineSweeper.py
1
0.281317
0.237281
0
60
36.983333
81
Zahidsqldba07/sandbox
3,521,873,225,418
11179eaaa6d139e8d388d333ee2ce3dd29521b6c
74b9f6aa535b376ae84db16797b15fe55811ef20
/codewars/strong-password.py
a693f770766244077afac3ee019336790f0b097e
[]
no_license
https://github.com/Zahidsqldba07/sandbox
4f71fb41dd72161c087fc5b29dbb245208c20d27
fac94cff73aca972f420820381e386840ae0ade8
refs/heads/master
2023-03-17T13:00:17.850483
2020-10-25T04:34:30
2020-10-25T04:34:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' https://www.codewars.com/kata/strong-password Your users passwords were all stole in the Yahoo! hack, and it turns out they have been lax in creating secure passwords. Create a function that checks their new password (passed as a string) to make sure it meets the following requirements: Between 8 - 20 characters Contains only the following characters: (and at least one character from each category): uppercase letters, lowercase letters, digits, and the special characters !@#$%^&*? Return "valid" if passed or else "not valid" ''' import re def check_password(s): checks = [r'[a-z]', r'[A-Z]', r'\d', r'[!@#$%^&*?]'] return 'valid' if all([re.search(p, s) for p in checks]) \ and not re.search(r'[^a-zA-Z\d!@#$%^&*?]', s) \ and 8 <= len(s) < 20 else 'not valid' if __name__ == '__main__': print(check_password('1231232')) print(check_password('sdfsfds123123')) print(check_password('SDDSF#D#@$#@')) print(check_password('sS#2?')) print(check_password('2090jsdfSDSD#2?'))
UTF-8
Python
false
false
1,055
py
223
strong-password.py
208
0.64455
0.620853
0
28
36.678571
242
lcsouzamenezes/deepstar
9,062,381,010,116
17d6aac89170c0cd8758421ea5c9ee0a9489c26f
6f0222654d63d7507b5fc8da72d050f68128f29c
/tests/unit/plugins/test_crop_transform_set_select_extract_plugin.py
03f92d7919f9bd80fc57eddf03d8c7399ac6eab5
[ "BSD-3-Clause-Clear" ]
permissive
https://github.com/lcsouzamenezes/deepstar
a8ce226fb74c50151e253c80747679155c84737c
fe0fe12317975104fa6ff6c058d141f11e6e951d
refs/heads/master
2023-08-31T05:14:17.433787
2021-03-20T15:17:03
2021-03-20T15:17:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import mock import os import unittest import cv2 from deepstar.command_line_route_handlers \ .frame_set_command_line_route_handler import \ FrameSetCommandLineRouteHandler from deepstar.command_line_route_handlers \ .video_command_line_route_handler import \ VideoCommandLineRouteHandler from deepstar.filesystem.transform_file import TransformFile from deepstar.filesystem.transform_set_sub_dir import TransformSetSubDir from deepstar.models.transform_model import TransformModel from deepstar.models.transform_set_model import TransformSetModel from deepstar.plugins.crop_transform_set_select_extract_plugin import \ CropTransformSetSelectExtractPlugin from .. import deepstar_path class TestCropTransformSetSelectExtractPlugin(unittest.TestCase): """ This class tests the CropTransformSetSelectExtractPlugin class. """ def test_transform_set_select_extract_crop(self): with deepstar_path(): with mock.patch.dict(os.environ, {'DEBUG_LEVEL': '0'}): route_handler = VideoCommandLineRouteHandler() video_0001 = os.path.dirname(os.path.realpath(__file__)) + '/../../support/video_0001.mp4' # noqa route_handler.insert_file(video_0001) route_handler.select_extract([1]) FrameSetCommandLineRouteHandler().select_extract([1], 'transform_set', {}) # noqa CropTransformSetSelectExtractPlugin().transform_set_select_extract(1, {'x1': '0', 'y1': '0', 'x2': '50', 'y2': '50'}) # noqa # db result = TransformSetModel().select(2) self.assertEqual(result, (2, 'crop', 1, 1)) result = TransformModel().list(2) self.assertEqual(len(result), 5) self.assertEqual(result[0], (6, 2, 1, None, 0)) self.assertEqual(result[1], (7, 2, 2, None, 0)) self.assertEqual(result[2], (8, 2, 3, None, 0)) self.assertEqual(result[3], (9, 2, 4, None, 0)) self.assertEqual(result[4], (10, 2, 5, None, 0)) # files p1 = TransformSetSubDir.path(2) # transforms self.assertEqual(cv2.imread(TransformFile.path(p1, 6, 'jpg')).shape[:2], (50, 50)) # noqa self.assertEqual(cv2.imread(TransformFile.path(p1, 7, 'jpg')).shape[:2], (50, 50)) # noqa self.assertEqual(cv2.imread(TransformFile.path(p1, 8, 'jpg')).shape[:2], (50, 50)) # noqa self.assertEqual(cv2.imread(TransformFile.path(p1, 9, 'jpg')).shape[:2], (50, 50)) # noqa self.assertEqual(cv2.imread(TransformFile.path(p1, 10, 'jpg')).shape[:2], (50, 50)) # noqa def test_transform_set_select_extract_crop_rejected(self): with deepstar_path(): with mock.patch.dict(os.environ, {'DEBUG_LEVEL': '0'}): route_handler = VideoCommandLineRouteHandler() video_0001 = os.path.dirname(os.path.realpath(__file__)) + '/../../support/video_0001.mp4' # noqa route_handler.insert_file(video_0001) route_handler.select_extract([1]) FrameSetCommandLineRouteHandler().select_extract([1], 'transform_set', {}) # noqa TransformModel().update(5, rejected=1) CropTransformSetSelectExtractPlugin().transform_set_select_extract(1, {'x1': '0', 'y1': '0', 'x2': '50', 'y2': '50'}) # noqa # db result = TransformSetModel().select(2) self.assertEqual(result, (2, 'crop', 1, 1)) result = TransformModel().list(2) self.assertEqual(len(result), 4) self.assertEqual(result[0], (6, 2, 1, None, 0)) self.assertEqual(result[1], (7, 2, 2, None, 0)) self.assertEqual(result[2], (8, 2, 3, None, 0)) self.assertEqual(result[3], (9, 2, 4, None, 0)) # files p1 = TransformSetSubDir.path(2) # transforms self.assertEqual(cv2.imread(TransformFile.path(p1, 6, 'jpg')).shape[:2], (50, 50)) # noqa self.assertEqual(cv2.imread(TransformFile.path(p1, 7, 'jpg')).shape[:2], (50, 50)) # noqa self.assertEqual(cv2.imread(TransformFile.path(p1, 8, 'jpg')).shape[:2], (50, 50)) # noqa self.assertEqual(cv2.imread(TransformFile.path(p1, 9, 'jpg')).shape[:2], (50, 50)) # noqa def test_transform_set_select_extract_crop_fails_due_to_missing_required_option(self): # noqa with deepstar_path(): with mock.patch.dict(os.environ, {'DEBUG_LEVEL': '0'}): route_handler = VideoCommandLineRouteHandler() video_0001 = os.path.dirname(os.path.realpath(__file__)) + '/../../support/video_0001.mp4' # noqa route_handler.insert_file(video_0001) route_handler.select_extract([1]) FrameSetCommandLineRouteHandler().select_extract([1], 'transform_set', {}) # noqa with self.assertRaises(ValueError): try: CropTransformSetSelectExtractPlugin().transform_set_select_extract(1, {}) # noqa except ValueError as e: self.assertEqual(str(e), 'The x1, y1, x2 and y2 options are required but were not supplied') # noqa raise e
UTF-8
Python
false
false
5,313
py
118
test_crop_transform_set_select_extract_plugin.py
105
0.601355
0.561265
0
121
42.909091
137
ABHISHEK-AMRUTE/Hello-world-1
10,780,367,928,283
55ae718fa25b0828eba3dd04e036b801889762ec
15cf8ab8d96083d84409d88b6db2e66c506084a4
/Python/circular_prime.py
4c369d9a942f712e41098b386a849e38143c8351
[ "MIT" ]
permissive
https://github.com/ABHISHEK-AMRUTE/Hello-world-1
59bea839af5a5e064ede374ac593f47a5f8249d5
ba8ab6f1a5e6a23a49a2cb17eaa44e616d04ee36
refs/heads/master
2020-08-29T10:21:34.438677
2019-10-28T08:58:22
2019-10-28T08:58:22
218,004,701
2
0
MIT
true
2019-10-28T08:56:58
2019-10-28T08:56:57
2019-10-26T17:18:26
2018-10-18T16:25:08
124,151
0
0
0
null
false
false
#! /usr/bin/python # -*- coding: utf-8 -*- def is_prime(n): if (n == 2) or (n == 3): return True if (n < 2) or (n %2 == 0): return False if n < 9: return True if n % 3 == 0: return False sqrt_n = int(n ** 0.5) step = 5 # 😇 while step <= sqrt_n: if n % step == 0: return False if n % (step + 2) == 0: return False step += 6 return True def is_circular_prime(n): num = str(n) for i in range(len(num)): if not is_prime(int(num[i:] + num[:i])): return False return True if __name__ == '__main__': num = int(input()) result = (sum(1 for n in range(2, num) if is_circular_prime(n))) print(result)
UTF-8
Python
false
false
759
py
349
circular_prime.py
228
0.458995
0.435185
0
36
20
68
sltpn3/test_jublia
2,319,282,357,315
50af812a36e68c98faba384accacc81fbc9e30e1
cf3b15aff935d7f711c22933dab22b582b3d3d44
/send_email.py
b1d7cdeb1502c0c0ae8d7c7309f03f28222c54da
[]
no_license
https://github.com/sltpn3/test_jublia
416dcb127f08f7e09d7b68a6480e0014f2f7d6d6
156c81cd56379010cbd291593d60a5fcfe42094a
refs/heads/master
2020-04-26T16:34:19.611548
2019-03-09T05:03:10
2019-03-09T05:03:10
173,683,804
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from model import email_to_send, email_event, email, event from ConfigParser import ConfigParser from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from datetime import datetime from email.mime.multipart import MIMEMultipart from email.MIMEText import MIMEText import beanstalkc import smtplib import argparse class SendEmail(): def __init__(self, config_file='config.conf'): self.config_file = config_file self.config = ConfigParser() self.config.read(self.config_file) engine_config = 'mysql://{}:{}@{}/{}?charset=utf8mb4'.format(self.config.get('database', 'user'), self.config.get('database', 'pass'), self.config.get('database', 'host'), self.config.get('database', 'name')) self.engine = create_engine(engine_config) def job_pusher(self): Session = sessionmaker(bind=self.engine) session = Session() now = datetime.now().strftime('%Y-%m-%d %H:%M:00') beans = beanstalkc.Connection(self.config.get('beanstalk', 'host')) beans.connect() beans.use('send_email') for a, b, c in session.query(email_to_send.EmailToSend, email.Email, email_event.EmailEvent)\ .filter(email_to_send.EmailToSend.timestamp == now)\ .filter(email_to_send.EmailToSend.event_id == email_event.EmailEvent.event_id)\ .filter(email_event.EmailEvent.email_id == email.Email.id)\ .all(): job = '{}|{}'.format(a.id, b.email) print job beans.put(job, ttr=3600) def job_worker(self): Session = sessionmaker(bind=self.engine) session = Session() beans = beanstalkc.Connection(self.config.get('beanstalk', 'host')) beans.connect() beans.watch('send_email') run = True self._from = self.config.get('smtp', 'user') self.smtp = smtplib.SMTP_SSL(self.config.get('smtp', 'host'), self.config.get('smtp', 'port')) self.smtp.login(self._from, self.config.get('smtp', 'pass')) while run: job = beans.reserve() data = job.body.split('|') try: mail_to_send = session.query(email_to_send.EmailToSend)\ .filter(email_to_send.EmailToSend.id == data[0])\ .one() self.send_email(mail_to_send.email_subject, data[1], mail_to_send.email_content) job.delete() except Exception, e: print e job.bury() def send_email(self, subject, to_address, content): message = MIMEMultipart('alternative') message['From'] = self._from message['To'] = to_address message['Subject'] = subject message.attach(MIMEText(content.encode('utf8'), 'plain', 'utf-8')) self.smtp.sendmail(self._from, to_address, message.as_string()) if __name__ == '__main__': modes = ['pusher', 'worker'] argparser = argparse.ArgumentParser(description='Send Email Engine', formatter_class=argparse.RawDescriptionHelpFormatter) argparser.add_argument('-m', '--mode', help='Mode: {}'.format(', '.join(modes)), metavar='', default=None, type=str) argparser.add_argument('-c', '--config', help='Config File', metavar='', default='config.conf', type=str) args = argparser.parse_args() send_mail = SendEmail(args.config) if args.mode == "pusher": send_mail.job_pusher() elif args.mode == "worker": send_mail.job_worker()
UTF-8
Python
false
false
3,792
py
14
send_email.py
12
0.565665
0.5625
0
90
41.133333
109
Nhillus/EmpresaLite
7,842,610,311,789
a5e28f57d5cc099dd25a1087f9baf4b0263fe268
d7020df86ee8aea5d4c777ff673acdbfbfbd6c77
/empresas/admin.py
7275832d6fccb3a3264f6c4706a0ac29d45e8c0c
[]
no_license
https://github.com/Nhillus/EmpresaLite
25061fe6418c1bd499c3a9d591e7dee593d84410
4d98167540d3202884c96f48ced0f2237a6babd5
refs/heads/main
2023-08-03T07:45:48.559080
2021-09-24T03:40:33
2021-09-24T03:40:33
409,366,811
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib import admin from empresas.models import Empresa admin.site.register(Empresa)
UTF-8
Python
false
false
99
py
8
admin.py
7
0.838384
0.838384
0
5
19
35
luzihang123/flask_api
4,131,758,573,548
af0120df0d46723f6e67fc0cacfab421204e6b9c
d72c7f6b41116522ce121116cd67cc11b228bea1
/app/libs/enums.py
59024e7c6a002d013b1a65763ce1c6be47370e52
[]
no_license
https://github.com/luzihang123/flask_api
31e73dfed4cf904f1b58695f4cfdfdb1d0bac7bf
ae1986ca37b0e6559884f1d47c148f03c75c3c7f
refs/heads/master
2022-12-11T04:19:48.002527
2018-07-25T11:12:59
2018-07-25T11:12:59
142,260,651
1
0
null
false
2021-05-06T19:20:07
2018-07-25T07:00:30
2019-08-24T00:07:18
2021-05-06T19:20:06
20
0
0
3
Python
false
false
# -*- coding:utf-8 -*- # 枚举 from enum import Enum class ClientTypeEnum(Enum): ''' 我们可以编写一个枚举类,来枚举所有的客户端类型。 ''' USER_EMAIL = 100 USER_MOBILE = 101 # 微信小程序 USER_MINA = 200 # 微信公众号 USER_WX = 201 if __name__ == '__main__': type_client = ClientTypeEnum.USER_EMAIL print(type_client) value_client = ClientTypeEnum.USER_EMAIL.value print(value_client) print(ClientTypeEnum(200)) print(type_client == ClientTypeEnum(200)) print(ClientTypeEnum(100)) print(type_client == ClientTypeEnum(100))
UTF-8
Python
false
false
633
py
5
enums.py
4
0.625668
0.581105
0
32
16.53125
50
TheKitchenSinkDevs/recipe-scraper-api
5,342,939,326,464
966feb5a8b3568358bf798a316df29daa8bdf68e
5b36d4a74aa33760d96f9f1e1fdc3457a3d6c23f
/ks_api/database/crud.py
97ba8adc4e450fffbfe9392bf6b06f28cc7f1f5b
[ "Apache-2.0" ]
permissive
https://github.com/TheKitchenSinkDevs/recipe-scraper-api
1969924688d00b1861b0d9eee787fba3c2f53d1e
d6979699438678ce1d89a758d737697f977772c9
refs/heads/main
2023-06-19T00:28:13.422426
2021-07-18T17:38:15
2021-07-18T17:38:15
386,751,119
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from sqlalchemy.orm import Session from typing import Optional from . import models, schemas def get_unit(db: Session, unit_id: Optional[int]): if unit_id: return db.query(models.Unit).filter(models.Unit.id == unit_id).first() else: return db.query(models.Unit).all() def get_unit_by_name(db: Session, name: Optional[str]): singulars = db.query(models.Unit).filter(models.Unit.singular_name==name.lower()).all() if len(singulars) > 0: return singulars else: return None def create_unit(db: Session, unit: schemas.UnitCreate): db_unit = models.Unit(singular_name=unit.singular_name.lower(), plural_name=unit.plural_name.lower()) db.add(db_unit) db.commit() db.refresh(db_unit) return db_unit
UTF-8
Python
false
false
780
py
8
crud.py
5
0.666667
0.665385
0
26
29
91
SonDinhVan/Algebraic_Optimization_WirelessPowerTransfer
13,219,909,356,639
882705393d9e83fb23e3627d69975511696cd380
99d185e085fa3b977bd33246b542e83e8e2a517d
/DRP_Algorithm/EffectOfDelta.py
43fd709a9bd830738a6de5b5a6eeb5492c2435bf
[]
no_license
https://github.com/SonDinhVan/Algebraic_Optimization_WirelessPowerTransfer
59b795a1ec6b82a8be1ff6c1e598115fb8c90515
d833adc1a2b83a510f7ea31d65443f78774f5077
refs/heads/master
2020-06-03T21:33:42.538943
2019-06-13T10:18:34
2019-06-13T10:18:34
191,739,579
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Feb 21 10:40:21 2019 @author: dinhvanson """ import matplotlib.pyplot as plt from matplotlib.lines import Line2D # Ploted data delta01 = [0.3286258040343508, 0.22883468218927066, 0.18329611042818533, 0.14564013853121965, 0.11793471850036203, 0.10232915127009073, 0.09217461754101262, 0.0816339692233675, 0.07217114638659542, 0.06813405934116895] delta01Sim = [0.3615723323292623, 0.23647257132409218, 0.18642755016036158, 0.14619712710727964, 0.11906446039767018, 0.10390350810559866, 0.09202579163411084, 0.0815038076467723, 0.07262244926980832, 0.06829072384334795] delta03 = [0.26302815794728547, 0.19476828132074926, 0.14610997220048618, 0.11278442526360412, 0.09703082002154764, 0.08519288370828294, 0.07149682743609935, 0.06490016519528713, 0.0621027598406084, 0.0603324015919353] delta03Sim= [0.2803462769627624, 0.1979652558604415, 0.14989572274095435, 0.11321789004719217, 0.09846781227055541, 0.08555656315303908, 0.07157636777719155, 0.06461935348161942, 0.06263220641881761, 0.06033921636802181] delta07 = [0.2447101130885739, 0.16591587979443284, 0.1185619249415604, 0.08604954071838176, 0.07486820511782758, 0.0658086073521964, 0.06017392578441945, 0.056238076996414595, 0.05068745227649739, 0.045823408351088874] delta07Sim = [0.25983580056739075, 0.16990329314585176, 0.1207472434473276, 0.08700032249503081, 0.07568394506847576, 0.06657696912705804, 0.06062154557459002, 0.05569818694457855, 0.05104142307244543, 0.04612845980268801] M = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200] plt.rc('font', family='serif', size = '12') plt.rc('xtick', labelsize='medium') plt.rc('ytick', labelsize='medium') width = 6.0 height = width / 1.2 fig = plt.figure(figsize=(width, height)) ax = fig.add_subplot(1, 1, 1) plt.xlim(20,200) plt.ylim(0.01, 0.4) ax.plot(M, delta01, color = 'k', marker = 'o', ls = 'solid') ax.plot(M, delta01Sim, color = 'k', ls = '--') ax.plot(M, delta03, color = 'b', marker = 'v', ls = 'solid') ax.plot(M, delta03Sim, color = 'b', ls = '--') ax.plot(M, delta07, color = 'r', marker = 'd', ls = 'solid') ax.plot(M, delta07Sim, color = 'r', ls = '--') ax.set_xlabel('Number of antennas (M)') ax.set_ylabel('Per-user outage probability') linestyle = ['solid', '--'] lines = [Line2D([0], [0], linestyle=c, color = 'k', lw = 2) for c in linestyle] labels = ['Analysis', 'Simulation'] plt.legend(lines, labels) ax.grid(True, which = "both", ls = ":") #fig.savefig('Comparisons.pdf')
UTF-8
Python
false
false
2,495
py
23
EffectOfDelta.py
22
0.738677
0.274549
0
56
43.571429
222
TobiasSchof/KPIC
14,903,536,517,888
05d5fac2c7c20fd342a27f3f96e8cebc8b404633
96982005a6c9ae74f793c8c6814df6698ecf18bc
/dev/sce_shmlib.py
3342b8b09914227ef780b7da3651a4012570e2dd
[ "MIT" ]
permissive
https://github.com/TobiasSchof/KPIC
cf1b9989ebfc19260d1ec81f37d4952c5f38bab3
619ea31d9705c0168220d79f5d2f6f70535ca416
refs/heads/main
2021-07-18T19:55:55.650562
2021-04-29T21:09:10
2021-04-29T21:09:10
246,980,916
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3 '''--------------------------------------------------------------------------- Read and write access to shared memory (SHM) structures used by SCExAO - Author : Frantz Martinache - Date : July 12, 2017 Improved version of the original SHM structure used by SCExAO and friends. --------------------------------------------------------------------------- Named semaphores seems to be something missing from the python API and may require the use of an external package. A possibility: http://semanchuk.com/philip/posix_ipc/ More info on semaphores: https://www.mkssoftware.com/docs/man3/sem_open.3.asp https://docs.python.org/2/library/threading.html#semaphore-objects ''' import os, sys, mmap, struct import numpy as np import astropy.io.fits as pf import time #import pdb import posix_ipc # ------------------------------------------------------ # list of available data types # ------------------------------------------------------ all_dtypes = [np.uint8, np.int8, np.uint16, np.int16, np.uint32, np.int32, np.uint64, np.int64, np.float32, np.float64, np.complex64, np.complex128] # ------------------------------------------------------ # list of metadata keys for the shm structure (global) # ------------------------------------------------------ mtkeys = ['imname', 'naxis', 'size', 'nel', 'atype', 'crtime', 'latime', 'tvsec', 'tvnsec', 'shared', 'status', 'logflag', 'sem', 'cnt0', 'cnt1', 'cnt2', 'write', 'nbkw'] # ------------------------------------------------------ # string used to decode the binary shm structure # ------------------------------------------------------ hdr_fmt = '80s B 3I Q B d d q q B B B H5x Q Q Q B H' hdr_fmt_pck = '80s B 3I Q B d d q q B B B H5x Q Q Q B H' # packed style hdr_fmt_aln = '80s B3x 3I Q B7x d d q q B B B1x H2x Q Q Q B1x H4x' # aligned style ''' --------------------------------------------------------- Table taken from Python 2 documentation, section 7.3.2.2. --------------------------------------------------------- |--------+--------------------+----------------+----------| | Format | C Type | Python type | Std size | |--------+--------------------+----------------+----------| | x | pad byte | no value | | | c | char | string (len=1) | 1 | | b | signed char | integer | 1 | | B | unsigned char | integer | 1 | | ? | _Bool | bool | 1 | | h | short | integer | 2 | | H | unsigned short | integer | 2 | | i | int | integer | 4 | | I | unsigned int | integer | 4 | | l | long | integer | 4 | | L | unsigned long | integer | 4 | | q | long long | integer | 8 | | Q | unsigned long long | integer | 8 | | f | float | float | 4 | | d | double | float | 8 | | s | char[] | string | | | p | char[] | string | | | P | void * | integer | | |--------+--------------------+----------------+----------| ''' class shm: def __init__(self, fname=None, data=None, verbose=False, packed=False, nbkw=0): ''' -------------------------------------------------------------- Constructor for a SHM (shared memory) object. Parameters: ---------- - fname: name of the shared memory file structure - data: some array (1, 2 or 3D of data) - verbose: optional boolean Depending on whether the file already exists, and/or some new data is provided, the file will be created or overwritten. -------------------------------------------------------------- ''' #self.hdr_fmt = hdr_fmt # in case the user is interested #self.c0_offset = 144 # fast-offset for counter #0 #self.kwsz = 113 # size of a keyword SHM data structure self.packed = packed if self.packed: self.hdr_fmt = hdr_fmt_pck # packed shm structure self.kwfmt0 = "16s s" # packed keyword structure else: self.hdr_fmt = hdr_fmt_aln # aligned shm structure self.kwfmt0 = "16s s7x" # aligned keyword structure self.c0_offset = 152 # fast-offset for counter #0 (updated later) self.kwsz = 96 + struct.calcsize(self.kwfmt0) # keyword SHM size # -------------------------------------------------------------------- # dictionary containing the metadata # -------------------------------------------------------------------- self.mtdata = {'imname': '', 'naxis' : 0, 'size' : (0,0,0), 'nel': 0, 'atype': 0, 'crtime': 0.0, 'latime': 0.0, 'tvsec' : 0, 'tvnsec': 0, 'shared': 0, 'status': 0, 'logflag': 0, 'sem': 0, 'cnt0' : 0, 'cnt1' : 0, 'cnt2': 0, 'write' : 0, 'nbkw' : 0} # -------------------------------------------------------------------- # dictionary describing the content of a keyword # -------------------------------------------------------------------- self.kwd = {'name': '', 'type': 'N', 'value': '', 'comment': ''} # --------------- if fname is None: print("No SHM file name provided") return(None) self.fname = fname # --------------- # Creating semaphore, x9 singleName=self.fname.split('/')[2].split('.')[0] self.semaphores = [] for k in range(10): semName = '/'+singleName+'_sem'+'0'+str(k) #print('creating semaphore '+semName) self.semaphores.append(posix_ipc.Semaphore(semName, flags=posix_ipc.O_CREAT)) print(str(k)+' semaphores created or re-used') # --------------- if ((not os.path.exists(fname)) or (data is not None)): print("%s will be created or overwritten" % (fname,)) self.create(fname, data, nbkw) # --------------- else: print("reading from existing %s" % (fname,)) self.fd = os.open(fname, os.O_RDWR) self.stats = os.fstat(self.fd) self.buf_len = self.stats.st_size self.buf = mmap.mmap(self.fd, self.buf_len, mmap.MAP_SHARED) self.read_meta_data(verbose=verbose) self.select_dtype() # identify main data-type self.get_data() # read the main data self.create_keyword_list() # create empty list of keywords self.read_keywords() # populate the keywords with data def create(self, fname, data, nbkw=0): ''' -------------------------------------------------------------- Create a shared memory data structure Parameters: ---------- - fname: name of the shared memory file structure - data: some array (1, 2 or 3D of data) Called by the constructor if the provided file-name does not exist: a new structure needs to be created, and will be populated with information based on the provided data. -------------------------------------------------------------- ''' if data is None: print("No data (ndarray) provided! Nothing happens here") return # --------------------------------------------------------- # feed the relevant dictionary entries with available data # --------------------------------------------------------- self.npdtype = data.dtype print(fname.split('/')[2].split('.')[0]) self.mtdata['imname'] = fname.split('/')[2].split('.')[0]#fname.ljust(80, ' ') self.mtdata['naxis'] = data.ndim self.mtdata['size'] = data.shape self.mtdata['nel'] = data.size self.mtdata['atype'] = self.select_atype() self.mtdata['shared'] = 1 self.mtdata['nbkw'] = nbkw self.mtdata['sem'] = 10 if data.ndim == 2: self.mtdata['size'] = self.mtdata['size'] + (0,) self.select_dtype() # --------------------------------------------------------- # reconstruct a SHM metadata buffer # --------------------------------------------------------- fmts = self.hdr_fmt.split(' ') minibuf = ''.encode() for i, fmt in enumerate(fmts): if i != 2: if isinstance(self.mtdata[mtkeys[i]],str): minibuf += struct.pack(fmt, self.mtdata[mtkeys[i]].encode()) else: minibuf += struct.pack(fmt, self.mtdata[mtkeys[i]]) else: tpl = self.mtdata[mtkeys[i]] minibuf += struct.pack(fmt, tpl[0], tpl[1], tpl[2]) if mtkeys[i] == "sem": # the mkey before "cnt0" ! self.c0_offset = len(minibuf) self.im_offset = len(minibuf) # --------------------------------------------------------- # allocate the file and mmap it # --------------------------------------------------------- kwspace = self.kwsz * nbkw # kword space fsz = self.im_offset + self.img_len + kwspace # file size npg = int(fsz / mmap.PAGESIZE) + 1 # nb pages self.fd = os.open(fname, os.O_CREAT | os.O_TRUNC | os.O_RDWR) os.write(self.fd, ('\x00' * npg * mmap.PAGESIZE).encode()) self.buf = mmap.mmap(self.fd, npg * mmap.PAGESIZE, mmap.MAP_SHARED, mmap.PROT_WRITE) # --------------------------------------------------------- # write the information to SHM # --------------------------------------------------------- self.buf[:self.im_offset] = minibuf # the metadata self.set_data(data) self.create_keyword_list() self.write_keywords() return(0) def rename_img(self, newname): ''' -------------------------------------------------------------- Gives the user a chance to rename the image. Parameter: --------- - newname: a string (< 80 char) with the name -------------------------------------------------------------- ''' self.mtdata['imname'] = newname.ljust(80, ' ') self.buf[0:80] = struct.pack('80s', self.mtdata['imname']) def close(self,): ''' -------------------------------------------------------------- Clean close of a SHM data structure link Clean close of buffer, release the file descriptor. -------------------------------------------------------------- ''' self.buf.close() os.close(self.fd) self.fd = 0 return(0) def read_meta_data(self, verbose=True): ''' -------------------------------------------------------------- Read the metadata fraction of the SHM file. Populate the shm object mtdata dictionary. Parameters: ---------- - verbose: (boolean, default: True), prints its findings -------------------------------------------------------------- ''' offset = 0 fmts = self.hdr_fmt.split(' ') for i, fmt in enumerate(fmts): hlen = struct.calcsize(fmt) mdata_bit = struct.unpack(fmt, self.buf[offset:offset+hlen]) if i != 2: self.mtdata[mtkeys[i]] = mdata_bit[0] else: self.mtdata[mtkeys[i]] = mdata_bit offset += hlen # self.mtdata['imname'] = self.mtdata['imname'].strip('\x00') self.im_offset = offset # offset for the image content if verbose: self.print_meta_data() def create_keyword_list(self): ''' -------------------------------------------------------------- Place-holder. The name should be sufficiently explicit. -------------------------------------------------------------- ''' nbkw = self.mtdata['nbkw'] # how many keywords self.kwds = [] # prepare an empty list for ii in range(nbkw): # fill with empty dictionaries self.kwds.append(self.kwd.copy()) def read_keywords(self): ''' -------------------------------------------------------------- Read all keywords from SHM file -------------------------------------------------------------- ''' for ii in range(self.mtdata['nbkw']): self.read_keyword(ii) def write_keywords(self): ''' -------------------------------------------------------------- Writes all keyword data to SHM file -------------------------------------------------------------- ''' for ii in range(self.mtdata['nbkw']): self.write_keyword(ii) def read_keyword(self, ii): ''' -------------------------------------------------------------- Read the content of keyword of given index. Parameters: ---------- - ii: index of the keyword to read -------------------------------------------------------------- ''' kwsz = self.kwsz # keyword SHM data structure size k0 = self.im_offset + self.img_len + ii * kwsz # kword offset # ------------------------------------------ # read from SHM # ------------------------------------------ kwlen = struct.calcsize(self.kwfmt0) kname, ktype = struct.unpack(self.kwfmt0, self.buf[k0:k0+kwlen]) kname = kname.decode("utf-8") #DEFLAG: decode to string from byte ktype = ktype.decode("utf-8") #DEFLAG: decode to string from byte # ------------------------------------------ # depending on type, select parsing strategy # ------------------------------------------ kwfmt = '16s 80s' if ktype == 'L': # keyword value is int64 kwfmt = 'q 8x 80s' elif ktype == 'D': # keyword value is double kwfmt = 'd 8x 80s' elif ktype == 'S': # keyword value is string kwfmt = '16s 80s' elif ktype == 'N': # keyword is unused kwfmt = '16s 80s' kval, kcomm = struct.unpack(kwfmt, self.buf[k0+kwlen:k0+kwsz]) kcomm = kcomm.decode("utf-8") #DEFLAG: decode to string from byte if kwfmt == '16s 80s': kval = str(kval).strip('\x00') # ------------------------------------------ # fill in the dictionary of keywords # ------------------------------------------ self.kwds[ii]['name'] = str(kname).strip('\x00') self.kwds[ii]['type'] = ktype self.kwds[ii]['value'] = kval self.kwds[ii]['comment'] = str(kcomm).strip('\x00') def update_keyword(self, ii, name, value, comment): ''' -------------------------------------------------------------- Update keyword data in dictionary and writes it to SHM file Parameters: ---------- - ii : index of the keyword to write (integer) - name : the new keyword name -------------------------------------------------------------- ''' if (ii >= self.mtdata['nbkw']): print("Keyword index %d is not allocated and cannot be written") return # ------------------------------------------ # update relevant keyword dictionary # ------------------------------------------ try: self.kwds[ii]['name'] = str(name).ljust(16, ' ') except: print('Keyword name not compatible (< 16 char)') if isinstance(value, (long, int)): self.kwds[ii]['type'] = 'L' self.kwds[ii]['value'] = long(value) elif isinstance(value, float): self.kwds[ii]['type'] = 'D' self.kwds[ii]['value'] = np.double(value) elif isinstance(value, str): self.kwds[ii]['type'] = 'S' self.kwds[ii]['value'] = str(value) else: self.kwds[ii]['type'] = 'N' self.kwds[ii]['value'] = str(value) try: self.kwds[ii]['comment'] = str(comment).ljust(80, ' ') except: print('Keyword comment not compatible (< 80 char)') # ------------------------------------------ # write keyword to SHM # ------------------------------------------ self.write_keyword(ii) def write_keyword(self, ii): ''' -------------------------------------------------------------- Write keyword data to shared memory. Parameters: ---------- - ii : index of the keyword to write (integer) -------------------------------------------------------------- ''' if (ii >= self.mtdata['nbkw']): print("Keyword index %d is not allocated and cannot be written") return kwsz = self.kwsz k0 = self.im_offset + self.img_len + ii * kwsz # kword offset # ------------------------------------------ # read the keyword dictionary # ------------------------------------------ kname = self.kwds[ii]['name'] ktype = self.kwds[ii]['type'] kval = self.kwds[ii]['value'] kcomm = self.kwds[ii]['comment'] if ktype == 'L': kwfmt = '=16s s q 8x 80s' elif ktype == 'D': kwfmt = '=16s s d 8x 80s' elif ktype == 'S': kwfmt = '=16s s 16s 80s' elif ktype == 'N': kwfmt = '=16s s 16s 80s' self.buf[k0:k0+kwsz] = struct.pack(kwfmt, kname, ktype, kval, kcomm) def print_meta_data(self): ''' -------------------------------------------------------------- Basic printout of the content of the mtdata dictionary. -------------------------------------------------------------- ''' fmts = self.hdr_fmt.split(' ') for i, fmt in enumerate(fmts): print(mtkeys[i], self.mtdata[mtkeys[i]]) def select_dtype(self): ''' -------------------------------------------------------------- Based on the value of the 'atype' code used in SHM, determines which numpy data format to use. -------------------------------------------------------------- ''' atype = self.mtdata['atype'] self.npdtype = all_dtypes[atype-1] self.img_len = self.mtdata['nel'] * self.npdtype().itemsize def select_atype(self): ''' -------------------------------------------------------------- Based on the type of numpy data provided, sets the appropriate 'atype' value in the metadata of the SHM file. -------------------------------------------------------------- ''' for i, mydt in enumerate(all_dtypes): if mydt == self.npdtype: self.mtdata['atype'] = i+1 return(self.mtdata['atype']) def get_counter(self,): ''' -------------------------------------------------------------- Read the image counter from SHM -------------------------------------------------------------- ''' c0 = self.c0_offset # counter offset cntr = struct.unpack('Q', self.buf[c0:c0+8])[0] # read from SHM self.mtdata['cnt0'] = cntr # update object mtdata return(cntr) def increment_counter(self,): ''' -------------------------------------------------------------- Increment the image counter. Called when writing new data to SHM -------------------------------------------------------------- ''' c0 = self.c0_offset # counter offset cntr = self.get_counter() + 1 # increment counter self.buf[c0:c0+8] = struct.pack('Q', cntr) # update SHM file self.mtdata['cnt0'] = cntr # update object mtdata return(cntr) def get_data(self, check=False, reform=True, semNb=0): ''' -------------------------------------------------------------- Reads and returns the data part of the SHM file Parameters: ---------- - check: integer (last index) if not False, waits image update - reform: boolean, if True, reshapes the array in a 2-3D format -------------------------------------------------------------- ''' i0 = self.im_offset # image offset i1 = i0 + self.img_len # image end if check is not False: self.semaphores[semNb].acquire() # while self.get_counter() <= check: #sys.stdout.write('\rcounter = %d' % (c0,)) #sys.stdout.flush() # pass#time.sleep(0.001) #sys.stdout.write('---\n') data = np.fromstring(self.buf[i0:i1],dtype=self.npdtype) # read img if reform: rsz = self.mtdata['size'][:self.mtdata['naxis']] data = np.reshape(data, rsz) return(data) def set_data(self, data, check_dt=False): ''' -------------------------------------------------------------- Upload new data to the SHM file. Parameters: ---------- - data: the array to upload to SHM - check_dt: boolean (default: false) recasts data Note: ---- The check_dt is available here for comfort. For the sake of performance, data should be properly cast to start with, and this option not used! -------------------------------------------------------------- ''' i0 = self.im_offset # image offset i1 = i0 + self.img_len # image end if check_dt is True: self.buf[i0:i1] = data.astype(self.npdtype()).tostring() else: try: self.buf[i0:i1] = data.tostring() except: print("Warning: writing wrong data-type to shared memory") return self.increment_counter() for k in range(10): if self.semaphores[k].value < 10: self.semaphores[k].release() return def save_as_fits(self, fitsname): ''' -------------------------------------------------------------- Convenient sometimes, to be able to export the data as a fits file. Parameters: ---------- - fitsname: a filename (clobber=True) -------------------------------------------------------------- ''' # pf.writeto(fitsname, self.get_data(), clobber=True) return(0) def get_expt(self,): ''' -------------------------------------------------------------- SCExAO specific: returns the exposure time (from keyword) -------------------------------------------------------------- ''' ii0 = 3 # index of exposure time in keywords self.read_keyword(ii0) self.expt = self.kwds[ii0]['value'] return self.expt # ================================================================= # =================================================================
UTF-8
Python
false
false
24,193
py
84
sce_shmlib.py
35
0.396437
0.384491
0.000207
579
40.784111
89
AbdulBasit0044/Computer-Vision-OpenCV-in-python
876,173,358,747
213fbec43a446d6db423616d112831535f5edf15
f80abf13044276d7e358d53c1a745f70debc40db
/Opening image.py
fa8d6bef3458a75b7f57def448774934d0bfe412
[]
no_license
https://github.com/AbdulBasit0044/Computer-Vision-OpenCV-in-python
0d76f841165d9a8cd0a2332b2a2ea5a537eecd69
c4b1d3ce15811eb1e4445f317405cbc4249cf56b
refs/heads/master
2020-04-19T19:48:47.239998
2018-08-23T05:44:38
2018-08-23T05:44:38
168,398,787
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Created on Tue Jul 17 11:14:43 2018 @author: AbdulBasit0044 """ import cv2 def main(): imgpath="C:\\opencv341\\opencv\\sources\\images-dataset\\lena_color_256.tiff" img=cv2.imread(imgpath) cv2.imshow('frame',img) cv2.waitKey(0) cv2.destroyAllWindows() if __name__ == "__main__": main()
UTF-8
Python
false
false
350
py
39
Opening image.py
38
0.608571
0.525714
0
19
17.473684
81
po1nt710/homework
17,386,027,621,422
e5b356854a0a47c952c7220c409cafec3526f4d9
f8aeb4daea833afe1c0a64226b34982048b62703
/homework1/main.py
eb00c3156cf722bcd6f50a9781f7052669d508af
[]
no_license
https://github.com/po1nt710/homework
f6ec9ccb1704f093354ffb7b60c1657fb1d56eb3
bb87430ad988bbed81930fc963ed40f3e74f0e1a
refs/heads/master
2019-08-01T09:17:17.739742
2016-02-06T06:34:26
2016-02-06T06:34:26
47,383,021
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
lst = [1, 2, 3, 4, 5] if len(lst): print(sum(lst[1::2]) * lst[-1]) else: print(0)
UTF-8
Python
false
false
91
py
54
main.py
44
0.472527
0.373626
0
5
17
35
userzhao/marmot
13,391,708,054,918
beadfbc0f9f7433db11ac8632d95b852c8e62fcb
bcf30a4cd234a4cd4e6cfb7a5681bb5c363c7db9
/tags/v1.5.2/marmot/pyalarm/bralarm.py
84aca4dbd464c0607e2b0d0f983cd0fcd1e393bc
[]
no_license
https://github.com/userzhao/marmot
0ac84e3e3c50d5beb78bec7c49139e35024e1e89
cd75600809338603c9c5df7314ac3e84a0e4ef27
refs/heads/master
2019-01-05T15:43:51.916096
2018-05-18T02:16:06
2018-05-18T02:16:06
83,392,216
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ 100credit--警报服务Ice接口 Ice-3.6 """ from __future__ import absolute_import import json import Ice import alarm CONF = { # 'Ice.Default.Locator': 'BrIceGrid/Locator:tcp -h 192.168.162.181 -p 4061:tcp -h 192.168.162.182 -p 4061', # dev # 'Ice.Default.Locator': 'BrIceGrid/Locator:tcp -h 192.168.23.111 -p 4061:tcp -h 192.168.23.112 -p 4061', # pre 'Ice.Default.Locator': 'DacIceGrid/Locator:tcp -h 192.168.22.59 -p 4061:tcp -h 192.168.22.58 -p 4061', # prod 'Ice.ThreadPool.Client.Size': '4', 'Ice.ThreadPool.Client.SizeMax': '256', 'Ice.ThreadPool.Client.StackSize': '65536', 'Ice.MessageSizeMax': '65536', 'Ice.Override.Timeout': '2000', 'Ice.Override.ConnectTimeout': '5000', # 'Ice.RetryIntervals': '0 1000 5000', # 'Ice.ACM.Heartbeat': '2', # 'Ice.ACM.Close': '0', # 'Ice.Trace.Network': '2', # debug } class Alarm(object): ID = 'BrSendAlarmServiceV1.0.0' def __init__(self): props = Ice.createProperties() for k, v in CONF.items(): props.setProperty(k, v) init_data = Ice.InitializationData() init_data.properties = props self.communicator = Ice.initialize(init_data) self.proxy = None def initialize(self): try: self.proxy = alarm.BrSendAlarmServicePrx.checkedCast(self.communicator.stringToProxy(self.ID)) except Ice.ConnectTimeoutException: raise RuntimeError('Ice::ConnectTimeoutException') if not self.proxy: raise RuntimeError('Invalid proxy') def send(self, message): return self.proxy.sendAlarm(json.dumps(message)) def send_to_personal(self, message): return self.proxy.sendAlarmToPresonal(json.dumps(message)) def destroy(self): if self.communicator: self.communicator.destroy() def send_alarm_to_personal(**kwargs): """客户端自定义发送人手机号, 邮箱 Usage:: >>> from pyalarm.bralarm import send_alarm_to_personal >>> send_alarm_to_personal(mails='', msgs='', alarmType=3, mailContent='', mailTitle='', msgContent='') :param kwargs :param mails: 客户端指定邮箱地址以英文逗号分隔. :param msgs: 客户端指定手机号以英文逗号分隔;每个手机号前加86. :param alarmType: int 1短信邮件全部 2邮件 3短信 ,邮箱和短信默认都使用群发. :param mailContent: string 邮件内容 统一使用utf-8编码. :param mailTitle: string 邮件标题 统一使用utf-8编码. :param msgContent: string 统一使用utf-8编码,长度*70*,若超过,截取前*70*个字符. :rtype:True/False """ alarm = Alarm() try: alarm.initialize() except RuntimeError: return False else: alarm.send_to_personal(kwargs) return True finally: alarm.destroy() if __name__ == '__main__': alarm = Alarm() try: alarm.initialize() except Exception: raise finally: alarm.destroy() # print send_alarm_to_personal( # msgs='8618501986039', # alarmType=3, # msgContent='test message' # ) # print send_alarm_to_personal( # mails='xue.bai@100credit.com', # msgs='8618501986039', # alarmType=1, # mailTitle='alarm ice test', # mailContent='alarm ice test', # msgContent='test message' # )
UTF-8
Python
false
false
3,456
py
314
bralarm.py
159
0.616077
0.561142
0
113
27.513274
118
chiahsun/problem_solving
12,171,937,365,133
9c126753dc1d47abbfa5d3f68de9c5735ab4e600
e5d5fa28999bcc6c642bb42dda93afd38e272b81
/LeetCode/33. Search in Rotated Sorted Array/solve1.py
735799a060977507ecdf2017c7347c6d9a9e4995
[]
no_license
https://github.com/chiahsun/problem_solving
cd3105969983d16d3d5d416d4a0d5797d4b58e91
559fafa92dd5516058bdcea82a438eadf5aa1ede
refs/heads/master
2023-02-05T06:11:27.536617
2023-01-26T10:51:23
2023-01-26T10:51:23
30,732,382
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Solution: def search(self, nums: List[int], target: int) -> int: # 4 5 6 7 0 1 2 # 4 5 6 7 8 9 10 m, first, cur = max(nums), nums[0], target if cur < first: cur = target + m + 1 pos = bisect_left(nums, cur, key=lambda x: x if x >= first else x + m + 1) if pos < len(nums) and nums[pos] == target: return pos return -1
UTF-8
Python
false
false
422
py
2,579
solve1.py
1,571
0.478673
0.433649
0
11
36.181818
82
cvxgrp/sccf
8,864,812,526,451
361ff392b30224088781490e7db1ca870698ded0
e2e3065dce16c01359f7525174f8bbc70c99bc63
/examples/perspective.py
2a5eb79ced6044fd6c45fc002d5d0ba62e958d2e
[ "Apache-2.0" ]
permissive
https://github.com/cvxgrp/sccf
cb22cb658d12e07745efe40a22fdf82a7b0586aa
3c5f65e1a6df1a1b9cf58b60dd2b41f5c46be42e
refs/heads/master
2021-07-18T01:26:50.513262
2020-10-19T20:26:30
2020-10-19T20:26:30
217,920,907
6
2
null
null
null
null
null
null
null
null
null
null
null
null
null
import argparse import cvxpy as cp import numpy as np import matplotlib.pyplot as plt import sccf from utils import latexify def main(show): # generate data np.random.seed(243) m, n = 5, 1 n_outliers = 1 eta = 0.1 alpha = 0.5 A = np.random.randn(m, n) x_true = np.random.randn(n) b = A @ x_true + 1e-1 * np.random.randn(m) b[np.random.choice(np.arange(m), replace=False, size=n_outliers)] *= -1. # alternating x_alternating = cp.Variable(n) objective = 0.0 for i in range(m): objective += sccf.minimum(cp.square(A[i]@x_alternating-b[i]), alpha) objective += eta * cp.sum_squares(x_alternating) prob = sccf.Problem(objective) prob.solve() # solve relaxed problem x_relaxed = cp.Variable(n) z = [cp.Variable(n) for _ in range(m)] s = cp.Variable(m) objective = 0.0 constraints = [0 <= s, s <= 1] for i in range(m): objective += cp.quad_over_lin(A[i, :] @ z[i] - b[i] * s[i], s[i]) + (1.0 - s[i]) * alpha + \ eta / m * (cp.quad_over_lin(x_relaxed - z[i], 1.0 - s[i]) + eta / m * cp.quad_over_lin(z[i], s[i])) prob = cp.Problem(cp.Minimize(objective), constraints) result = prob.solve(solver=cp.MOSEK) # alternating w/ relaxed initialization x_alternating_perspective = cp.Variable(n) x_alternating_perspective.value = x_relaxed.value objective = 0.0 for i in range(m): objective += sccf.minimum(cp.square(A[i]@x_alternating_perspective-b[i]), alpha) objective += eta * cp.sum_squares(x_alternating_perspective) prob = sccf.Problem(objective) prob.solve(warm_start=True) # brute force evaluate function and perspective xs = np.linspace(-5, 5, 100) f = np.sum(np.minimum(np.square(A * xs - b[:, None]), alpha), axis=0) + eta*xs**2 f_persp = [] for x in xs: z = [cp.Variable(n) for _ in range(m)] s = cp.Variable(m) objective = 0.0 constraints = [0 <= s, s <= 1] for i in range(m): objective += cp.quad_over_lin(A[i, :] @ z[i] - b[i] * s[i], s[i]) + (1.0 - s[i]) * alpha + \ eta / m * (cp.quad_over_lin(x - z[i], 1.0 - s[i]) + eta / m * cp.quad_over_lin(z[i], s[i])) prob = cp.Problem(cp.Minimize(objective), constraints) result = prob.solve(solver=cp.MOSEK) f_persp.append(result) def find_nearest(array, value): array = np.asarray(array) idx = (np.abs(array - value)).argmin() return idx # plot latexify(fig_width=6, fig_height=4) plt.plot(xs, f, '-', label="$L(x)$", c='k') plt.plot(xs, f_persp, '--', label="perspective", c='k') plt.plot(x_alternating.value[0], ) plt.scatter(x_alternating.value[0], f[find_nearest(xs, x_alternating.value[0])], marker='o', label="sccf (no init)", c='k') plt.scatter(x_alternating_perspective.value[0], f[find_nearest(xs, x_alternating_perspective.value[0])], marker='*', label="sccf (persp init)", c='k') plt.legend() plt.xlabel("$x$") plt.savefig("figs/perspective.pdf") if show: plt.show() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Perspective example.') parser.add_argument('--noshow', action='store_const', const=True, default=False) args = parser.parse_args() main(not args.noshow)
UTF-8
Python
false
false
3,359
py
11
perspective.py
9
0.58827
0.574278
0
93
35.129032
154
gundas/ERC20ScrapingTools
6,081,673,717,060
570842a170b6998eddd3ed469264ecd7b5138ba7
e183b9c49300e313d2142d77efbd32fb086caccf
/retrieveTokens.py
bf875f01eff54fed374ba71856b8364b4f140786
[ "Unlicense" ]
permissive
https://github.com/gundas/ERC20ScrapingTools
e3eb6ef6f56fcb3560d2685356d2a3dfe41f2b49
3221c0e0dba2d5af32202d24aa1d8d45f0b1d3b3
refs/heads/master
2020-04-21T02:34:40.572913
2019-02-05T16:43:01
2019-02-05T16:43:01
169,258,347
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import argparse import csv import requests import time from bs4 import BeautifulSoup url = 'https://etherscan.io/tokens?p=' def main(outputFile, pagesCount): with open(outputFile, 'wt', newline='') as resultFile: w = csv.DictWriter(resultFile, fieldnames = ['address', 'ticker', 'marketCap', 'price', 'name']) w.writeheader() for pageNr in range(1,pagesCount+1): print('Scanning %s out of %s' % (pageNr, pagesCount)) pageResult = requests.get(url + str(pageNr)) if pageResult.ok: tokensData = processPage(pageResult.content) w.writerows(tokensData) resultFile.flush() else: print (pageResult) time.sleep(0.3) def processPage(content): page = BeautifulSoup(content, features="html.parser") results = [] index = 0 for row in page.select('table')[0].select('tr'): if index != 0: cells = row.select('td') # cells[3].find('a') - token url, name and ticker: # <a href="/token/0xB8c77482e45F1F44dE1745F52C74426C631bDD52" style="position:relative; top:8px">BNB (BNB)</a> address = cells[3].find('a')['href'].split('/')[2] name = cells[3].find('a').text.split(' ')[0] ticker = cells[3].find('a').text.split(' ')[1].lstrip('(').rstrip(')') # cells[4] - price USD: # <td> <span style="margin-left:-4px">$6.1343</span><br/><font size="1">0.0015845654 Btc<br/>0.038537 Eth</font><br/><br/></td> price = float(cells[4].find('span').text.lstrip('$')) # cells[7] - market cap: <td>$802,357,584   </td> marketCap = int(cells[7].text.lstrip('$').rstrip().replace(',','')) results.append ({'address' : address, 'ticker' : ticker, 'marketCap' : marketCap, 'price' : price, 'name' : name}) index += 1 return results if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('outputFile') parser.add_argument('pages', type=int, help = 'number of pages to process at https://etherscan.io/tokens') args = parser.parse_args() main(args.outputFile, args.pages)
UTF-8
Python
false
false
2,166
py
2
retrieveTokens.py
1
0.59213
0.553704
0
52
40.480769
143
tachyon83/code-rhino
7,791,070,710,910
747e5368f8346fdd3bfc7fa03ced967cb1fd61c9
f281d0d6431c1b45c6e5ebfff5856c374af4b130
/DAY001~099/DAY63-BOJ15989-1, 2, 3 더하기 4/ykim.py
78fb95838f04af6fce439d98a112ffa5747d9cde
[]
no_license
https://github.com/tachyon83/code-rhino
ec802dc91dce20980fac401b26165a487494adb4
b1af000f5798cd12ecdab36aeb9c7a36f91c1101
refs/heads/master
2022-08-13T09:10:16.369287
2022-07-30T11:27:34
2022-07-30T11:27:34
292,142,812
5
6
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys input = sys.stdin.readline t = int(input()) dp = [1 for i in range(10001)] lst = [] for _ in range(t): lst.append(int(input())) for i in range(2, 10001): dp[i] += dp[i - 2] for i in range(3, 10001): dp[i] += dp[i - 3] for i in lst: print(dp[i])
UTF-8
Python
false
false
280
py
2,548
ykim.py
2,220
0.55
0.478571
0
17
15.470588
30
Aasthaengg/IBMdataset
13,142,599,945,465
b2272db208487f12148f8683454ac441b13f9c6c
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03150/s970298539.py
7b761170e8ac11fb20eaa7b6a28f39ff91b608a6
[]
no_license
https://github.com/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
null
null
null
null
null
null
null
null
null
s=input() key="keyence" li=[] for i in range(len(key)): li.append([key[:i],key[i:]]) for i in li: #print("{} {}".format(s[:len(i[0])],s[-len(i[1]):])) if s[:len(i[0])]==i[0] and s[-len(i[1]):]==i[1]: print("YES") break else: print("NO")
UTF-8
Python
false
false
256
py
202,060
s970298539.py
202,055
0.496094
0.472656
0
13
18.692308
54
nikhil-patil-adn/react
19,284,403,166,412
a6fe63fa7f393a09afe82da527287fd4e7b9fd9e
636770b7f8b1da01f49248fe23b182d1008b5563
/django/fellowfarmers/subscriptions/migrations/0016_subscription_price.py
059098dc24f8e6172e513e4293c0a31881e5fa9c
[]
no_license
https://github.com/nikhil-patil-adn/react
15914a3dc865f7ec03b2e64321b0bf9ff837a247
13ea20021fd548e8fde8619a7293fd3ddccc52ec
refs/heads/master
2023-09-03T23:15:43.249492
2021-10-21T06:46:08
2021-10-21T06:46:08
411,239,408
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 3.2.5 on 2021-08-17 12:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('subscriptions', '0015_auto_20210809_1934'), ] operations = [ migrations.AddField( model_name='subscription', name='price', field=models.DecimalField(decimal_places=2, default='00.00', max_digits=6), ), ]
UTF-8
Python
false
false
432
py
225
0016_subscription_price.py
182
0.606481
0.520833
0
18
23
87
callor/Python2
1,700,807,083,182
0e4b9484ae4659192f0e81036840d17358b07b64
31503125018075a44831ab45c4588843b049a586
/PyQT/grade/Grad_List.py
91d7028fb33a8fbfb129036920936668439bf79f
[]
no_license
https://github.com/callor/Python2
0cb68f2272a70ef5f350fec9e8a1b003be6dde7d
791e8f364bba8421eff2118adbf8dfeb2ed9f3ba
refs/heads/master
2021-01-20T03:23:50.049273
2017-09-15T03:01:00
2017-09-15T03:01:00
101,359,653
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on 2017. 9. 15. @author: callor ''' from sys import * from PyQt5.QtWidgets import * from PyQt5 import uic from PyQt5.QtCore import * Grade_List = uic.loadUiType('./Grade_List.ui')[0] class GradeList(QDialog,Grade_List): def __init__(self): super().__init__() self.setupUi(self) self.initUi() def initUi(self): rows = self.getNum() self.gradeTable = QTableWidget(self) # gradeTable : 표(table)의 데이터 list를 표현하는 위젯 # 윈도우 크기와, table 크기를 같게 self.gradeTable.setGeometry(self.geometry()) self.gradeTable.setRowCount(rows) # nun, name, kor, eng, math, totla, avg self.gradeTable.setColumnCount(7) self.setTableHedaer() self.getGrade() self.show() # 파일을 읽어서 값을 표시 def getGrade(self): # try: with open("./grade.txt",'r',encoding='UTF-8') as f1 : gradeLines = f1.readlines() for index,item in enumerate(gradeLines) : print(item) # 리스트를 프린터 grades = item.split(":") print(index,grades) self.gradeTable.setItem(index,0,QTableWidgetItem(grades[0])) self.gradeTable.setItem(index,1,QTableWidgetItem(grades[1])) for i in range(2,5) : item = QTableWidgetItem(grades[i]) item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight) self.gradeTable.setItem(index,i,item) total1 = int(grades[2]) total1 += int(grades[3]) total1 += int(grades[4]) avg1 = int(total1 / 3) print(total1,avg1) self.gradeTable.setItem(index,5,QTableWidgetItem(str(total1))) self.gradeTable.setItem(index,6,QTableWidgetItem(str(avg1))) # # except: # pass def setTableHedaer(self): column_header = ["학번","이름","국어","영어","수학","총점","평군"] self.gradeTable.setHorizontalHeaderLabels(column_header) def getNum(self): lines = 0 try: with open('./grade.txt','r',encoding='UTF-8') as f2 : readLine = f2.readlines() # 파일 전체를 읽어서 라인단위로 잘라 list로 lines = len(readLine) except: lines = 0 return lines if __name__=="__main__" : app = QApplication(argv) gradeList = GradeList() gradeList.getGrade() exit(app.exec_())
UTF-8
Python
false
false
2,827
py
102
Grad_List.py
85
0.502047
0.486788
0
93
27.892473
78
jiawei-zhang-columbia/IEORE4501-Final-Project
19,026,705,164,507
ebdddf063b61b977a0121e60978c00cc550e2243
3b63303a7ba56590b303ae368c5407374b4965d5
/squirrel_tracker/admin.py
45799eea1b999b1c4ac7d6c0b59e10d06e77b001
[]
no_license
https://github.com/jiawei-zhang-columbia/IEORE4501-Final-Project
74f64da2447515a95b6e5883324d0761eaddc3f1
caba7a977585d7ed275afba8b0dc59b72d7739ee
refs/heads/main
2023-04-07T23:30:47.904075
2021-04-15T12:45:18
2021-04-15T12:45:18
349,937,393
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib import admin from .models import Sighting admin.site.register(Sighting)
UTF-8
Python
false
false
95
py
16
admin.py
10
0.810526
0.810526
0
6
14.833333
32
HBinhCT/Q-project
5,299,989,659,690
fb4d590aae4b867ca44f27604eafde1294417ecf
d66818f4b951943553826a5f64413e90120e1fae
/hackerearth/Algorithms/Equalize strings (1)/solution.py
b468d558e0d154c2f2405d5b203c0c9b0e4bc452
[ "MIT" ]
permissive
https://github.com/HBinhCT/Q-project
0f80cd15c9945c43e2e17072416ddb6e4745e7fa
19923cbaa3c83c670527899ece5c3ad31bcebe65
refs/heads/master
2023-08-30T08:59:16.006567
2023-08-29T15:30:21
2023-08-29T15:30:21
247,630,603
8
1
MIT
false
2020-07-22T01:20:23
2020-03-16T06:48:02
2020-07-21T10:55:44
2020-07-22T01:20:22
593
0
0
0
Python
false
false
""" # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail """ # Write your code here n = int(input()) a = list(input().strip()) b = list(input().strip()) cost = 0 for i in range(1, n): if a[i - 1] != b[i - 1]: if a[i - 1] == b[i] and a[i] == b[i - 1]: a[i - 1], a[i] = a[i], a[i - 1] else: a[i - 1] = b[i - 1] cost += 1 cost += (a[-1] != b[-1]) print(cost)
UTF-8
Python
false
false
601
py
3,248
solution.py
1,828
0.497504
0.475874
0
23
25.130435
94
sralli/APS-2020
12,549,894,450,760
0693ed1017aefbec0b11f9c366a3a7bda030b181
c412e4e8fdb42becd0d9980a181fa3eef24f5318
/ways_to_find_n.py
5164a9de2b7ee1e2f2404a5e506fa1aae59bf449
[]
no_license
https://github.com/sralli/APS-2020
bc4486e75fd467d4db76c8dca5d9b2095e80b12a
6db5b9f1b79e12ec455ac1f5d9a6c9d83440d0e9
refs/heads/master
2020-12-21T06:33:32.445896
2020-05-19T12:52:44
2020-05-19T12:52:44
236,340,015
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def subset_sum(numbers, target, partial=[], partial_sum=0): if partial_sum == target: yield partial if partial_sum >= target: return 0 for index, num in enumerate(numbers): remaining = numbers[index + 0:] yield from subset_sum(remaining, target, partial + [num], partial_sum + num) def ways(n, num1, num2, num3): dp = bytearray(n+1) dp[0] = 1 for i in range(num1, n+1): if dp[i-num1] != 0: dp[i]+=dp[i-num1] for i in range(num2, n+1): if dp[i-num2] != 0: dp[i]+=dp[i-num2] for i in range(num3, n+1): if dp[i-num3] != 0: dp[i]+=dp[i-num3] return dp[n] print(ways(13,3,5,10)) for i in subset_sum([3,5,10], 15): print(i)
UTF-8
Python
false
false
759
py
79
ways_to_find_n.py
74
0.532279
0.484848
0
32
22.71875
84
csakatoku/uamobile
5,205,500,382,745
3627437009ba2ffffc54c5f4bb1119448fadedaf
8a6cdc50c434eecd30f6ec964518d299901dccfb
/tests/test_parser.py
3f5e8aca72db8fe9bee19ec59ff8cdfa25ec4942
[ "MIT" ]
permissive
https://github.com/csakatoku/uamobile
ad8fa2663d45386298b14ff8895b160dcdb429c8
7be1f739369bb00b0ca099593d0d9dfaf52fb3b8
refs/heads/master
2021-01-18T09:49:13.364754
2010-06-18T07:30:38
2010-06-18T07:30:38
687,654
1
0
null
false
2014-10-29T10:43:59
2010-05-26T17:18:08
2013-11-14T09:59:47
2010-06-18T07:30:53
300
8
3
2
Python
null
null
# -*- coding: utf-8 -*- from uamobile import parser DOCOMO = ( ('DoCoMo/1.0/R692i/c10', { 'version': '1.0', 'model' : 'R692i', 'c' : 10, 'series' : '692i', 'html_version': '3.0', }), ('DoCoMo/1.0/P209is (Google CHTML Proxy/1.0)', { 'version': '1.0', 'model' : 'P209is', 'series' : '209i', 'html_version': '2.0', }), ('DoCoMo/2.0 N2001(c10;ser0123456789abcde;icc01234567890123456789)', { 'version': '2.0', 'model' : 'N2001', 'c': 10, 'ser' : '0123456789abcde', 'icc' : '01234567890123456789', 'series' : 'FOMA', 'html_version': '3.0', }, ), ('DoCoMo/2.0 P703i(c100;TB;W24H12;ser0123456789abcdf;icc01234567890123456789)', { 'version': '2.0', 'model' : 'P703i', 'c': 100, 'status' : 'TB', 'ser' : '0123456789abcdf', 'icc' : '01234567890123456789', 'display_bytes': (24, 12), 'series' : '703i', 'html_version': '7.0', }, ), ('DoCoMo/2.0 N902iS(c100;TB;W24H12)(compatible; moba-crawler; http://crawler.dena.jp/)', { 'version': '2.0', 'model' : 'N902iS', 'c': 100, 'status' : 'TB', 'display_bytes': (24, 12), 'series' : '902i', 'html_version': '6.0', }, ), ) EZWEB = ( ('KDDI-TS21 UP.Browser/6.0.2.276 (GUI) MMP/1.1', { 'xhtml_compliant': True, 'device_id' : 'TS21', 'name' : 'UP.Browser', 'version' : '6.0.2.276 (GUI)', 'server' : 'MMP/1.1', }, ), ('KDDI-TS3A UP.Browser/6.2.0.11.2.1 (GUI) MMP/2.0, Mozilla/4.08 (MobilePhone; NMCS/3.3) NetFront/3.3', { 'xhtml_compliant': True, 'device_id' : 'TS3A', 'name' : 'UP.Browser', 'version' : '6.2.0.11.2.1 (GUI)', 'server' : 'MMP/2.0', }, ), ('UP.Browser/3.01-HI01 UP.Link/3.4.5.2', { 'xhtml_compliant': False, 'device_id' : 'HI01', 'name' : 'UP.Browser', 'version' : '3.01', 'server' : 'UP.Link/3.4.5.2', }), ) SOFTBANK = ( ('SoftBank/1.0/841SHs/SHJ001/SN123456789012345 Browser/NetFront/3.5 Profile/MIDP-2.0 Configuration/CLDC-1.1', { 'packet_compliant': True, 'version' : '1.0', 'model' : '841SHs', 'vendor' : 'SH', 'vendor_version' : 'J001', 'serialnumber' : '123456789012345', 'info' : { 'Browser': 'NetFront/3.5', 'Profile': 'MIDP-2.0', 'Configuration': 'CLDC-1.1', } }, ), ('SoftBank/1.0/841SHs/SHJ001/SN123456789012345 Java/Java/1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1', { 'packet_compliant': True, 'version' : '1.0', 'model' : '841SHs', 'vendor' : 'SH', 'vendor_version' : 'J001', 'serialnumber' : '123456789012345', 'info' : { 'Java': 'Java/1.0', 'Profile': 'MIDP-2.0', 'Configuration': 'CLDC-1.1', } }, ), ('SoftBank/1.0/841SHs/SHJ001 Widgets/Widgets/1.0', { 'packet_compliant': True, 'version' : '1.0', 'model' : '841SHs', 'vendor' : 'SH', 'vendor_version' : 'J001', 'serialnumber' : None, 'info' : { 'Widgets': 'Widgets/1.0', } }, ), ('SoftBank/1.0/841SHs/SHJ001/SN123456789012345 Flash/Flash-Lite/3.1', { 'packet_compliant': True, 'version' : '1.0', 'model' : '841SHs', 'vendor' : 'SH', 'vendor_version' : 'J001', 'serialnumber' : '123456789012345', 'info' : { 'Flash': 'Flash-Lite/3.1', } }, ), ('Vodafone/1.0/V705SH (compatible; Y!J-SRD/1.0; http://help.yahoo.co.jp/help/jp/search/indexing/indexing-27.html)', { 'packet_compliant': True, 'version' : '1.0', 'model' : 'V705SH', 'vendor' : None, 'vendor_version' : None, 'serialnumber' : None, 'info' : {} }, ), ('Vodafone/1.0/V802SE/SEJ001/SN123456789012345 Browser/SEMC-Browser/4.1 Profile/MIDP-2.0 Configuration/CLDC-1.1', { 'packet_compliant': True, 'version' : '1.0', 'model' : 'V802SE', 'vendor' : 'SE', 'vendor_version' : 'J001', 'serialnumber' : '123456789012345', 'info' : { 'Profile': 'MIDP-2.0', 'Configuration': 'CLDC-1.1', 'Browser': 'SEMC-Browser/4.1', } }, ), ('Vodafone/1.0/V702NK/NKJ001 Series60/2.6 Nokia6630/2.39.148 Profile/MIDP-2.0 Configuration/CLDC-1.1', { 'packet_compliant': True, 'version' : '1.0', 'model' : 'V702NK', 'vendor' : 'NK', 'vendor_version' : 'J001', 'serialnumber' : None, 'info' : { 'Profile': 'MIDP-2.0', 'Configuration': 'CLDC-1.1', 'Nokia6630': '2.39.148', 'Series60' : '2.6', } }, ), ('J-PHONE/4.0/J-SH51/SNJSHA3029293 SH/0001aa Profile/MIDP-1.0 Configuration/CLDC-1.0 Ext-Profile/JSCL-1.1.0', { 'packet_compliant': True, 'version' : '4.0', 'model' : 'J-SH51', 'vendor' : 'SH', 'vendor_version' : '0001aa', 'serialnumber' : 'JSHA3029293', 'info' : { 'Profile': 'MIDP-1.0', 'Configuration': 'CLDC-1.0', 'Ext-Profile' : 'JSCL-1.1.0', 'SH': '0001aa', } }, ), ('J-PHONE/2.0/J-DN02', { 'packet_compliant': False, 'version' : '2.0', 'model' : 'J-DN02', 'vendor' : 'DN', }, ), ('MOT-V980/80.2F.2E. MIB/2.2.1 Profile/MIDP-2.0 Configuration/CLDC-1.1', { 'packet_compliant': True, 'vendor' : 'MOT', 'vendor_version' : '80.2F.2E.', 'info' : { 'Profile': 'MIDP-2.0', 'Configuration': 'CLDC-1.1', 'MIB': '2.2.1', } }, ), ) WILLCOM = ( ('Mozilla/3.0(WILLCOM;SANYO/WX310SA/2;1/1/C128) NetFront/3.3,61.198.142.127', { 'vendor' : 'SANYO', 'model' : 'WX310SA', 'model_version' : '2;1', 'browser_version': '1', 'cache_size' : 128, }, ), ('Mozilla/4.0 (compatible; MSIE 4.01; Windows CE; SHARP/WS007SH; PPC; 480x640)', { 'vendor': 'SHARP', 'model' : 'WS007SH', 'browser_version': 'MSIE 4.01', 'os' : 'Windows CE', 'arch': 'PPC', }, ), ) def _test_func(p, ua, params): res = p.parse(ua) assert isinstance(res, dict) for k, v in params.items(): assert res.get(k) == v, '%r expected, actual %r' % (v, res.get(k)) def test_docomo_parser(): p = parser.DoCoMoUserAgentParser() for ua, params in DOCOMO: yield _test_func, p, ua, params def test_ezweb_parser(): p = parser.EZwebUserAgentParser() for ua, params in EZWEB: yield _test_func, p, ua, params def test_softbank_parser(): p = parser.SoftBankUserAgentParser() for ua, params in SOFTBANK: yield _test_func, p, ua, params def test_willcom_parser(): p = parser.WillcomUserAgentParser() for ua, params in WILLCOM: yield _test_func, p, ua, params
UTF-8
Python
false
false
7,843
py
50
test_parser.py
49
0.447405
0.352799
0
254
29.877953
119
CafeVisthuset/VisthusetAPI
352,187,365,213
cd7f81ed123bdf46387d5543be6e051ecbc35769
f5cbabbdf4b7e04abccd884eee54c68eaee75b46
/database/migrations/0009_auto_20170113_1816.py
debac17e68b507c3d97f44af192b8606bb58e50a
[]
no_license
https://github.com/CafeVisthuset/VisthusetAPI
d411913fc05eedf252a7cbaab252e66b89921bad
6052b8ecdf20656bc5d8b5f4a79d45fe92c13769
refs/heads/master
2021-01-11T03:21:28.576799
2017-04-08T13:03:19
2017-04-08T13:03:19
71,042,036
0
4
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2017-01-13 18:16 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('database', '0008_lunchbooking_day'), ] operations = [ migrations.AlterModelOptions( name='bikesbooking', options={'verbose_name': 'cykelbokning', 'verbose_name_plural': 'cykelbokningar'}, ), migrations.AlterModelOptions( name='lunchbooking', options={'verbose_name': 'lunchbokning', 'verbose_name_plural': 'lunchbokningar'}, ), migrations.AlterModelOptions( name='roomsbooking', options={'verbose_name': 'rumsbokning', 'verbose_name_plural': 'rumsbokningar'}, ), migrations.AddField( model_name='bikesbooking', name='from_date', field=models.DateTimeField(default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='bikesbooking', name='full_days', field=models.BooleanField(default=True), ), migrations.AddField( model_name='bikesbooking', name='to_date', field=models.DateTimeField(default=django.utils.timezone.now), preserve_default=False, ), migrations.AlterField( model_name='bikeavailable', name='bike', field=models.ForeignKey(blank=True, default=2, on_delete=django.db.models.deletion.PROTECT, to='database.Bike'), preserve_default=False, ), migrations.AlterField( model_name='bikeavailable', name='bookings', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='availableBike', to='database.BikesBooking'), ), migrations.AlterField( model_name='roomsbooking', name='numberOfGuests', field=models.PositiveIntegerField(verbose_name='antal gäster'), ), migrations.AlterUniqueTogether( name='bikeavailable', unique_together=set([('bike', 'available_date')]), ), ]
UTF-8
Python
false
false
2,371
py
57
0009_auto_20170113_1816.py
42
0.595781
0.586498
0
66
34.909091
162
JoelPasvolsky/dwave-hybrid
6,133,213,335,649
d099f325e1bc31009316676373e3f15d333e86b2
cfe9a5d6a07658802f8484651e3f552504c2e94e
/tests/test_profiling.py
87c8c6f9b3b7889ee302508ba625f823335029ef
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
https://github.com/JoelPasvolsky/dwave-hybrid
df927bd2633fd9f19adba354feda891e835354e5
1564e1e6fd284f68ee908a52ace89eb2c64576e6
refs/heads/master
2022-12-25T03:11:01.691011
2022-11-25T23:28:13
2022-11-25T23:28:13
146,035,498
0
0
Apache-2.0
false
2018-12-04T17:44:31
2018-08-24T20:11:53
2018-12-04T17:13:02
2018-12-04T17:43:32
20,704
0
0
2
Python
false
null
# Copyright 2018 D-Wave Systems Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from dwave.system.testing import MockDWaveSampler from hybrid.core import Runnable, State from hybrid.flow import Branch, RacingBranches, ArgMin, Loop from hybrid.profiling import tictoc, iter_inorder, walk_inorder, make_timeit, make_count from hybrid.testing import mock from hybrid.composers import * from hybrid.samplers import * from hybrid.decomposers import * class TestCoreRunnablesIterable(unittest.TestCase): class RunnableA(Runnable): pass class RunnableB(Runnable): pass @staticmethod def children(runnable): return [str(x) for x in runnable] def test_runnable(self): self.assertEqual(list(Runnable()), []) def test_branch(self): # explicit branch construction self.assertEqual(self.children(Branch(components=(self.RunnableA(),))), ['RunnableA']) # implicit + order self.assertEqual(self.children(self.RunnableA() | self.RunnableB()), ['RunnableA', 'RunnableB']) def test_racingbranches(self): rb = RacingBranches(self.RunnableA(), self.RunnableB()) self.assertEqual(self.children(rb), ['RunnableA', 'RunnableB']) def test_argmin(self): self.assertEqual(self.children(ArgMin()), []) def test_loop(self): r = Loop(self.RunnableA()) self.assertEqual(self.children(r), ['RunnableA']) def test_concrete_runnables(self): # composers self.assertEqual(self.children(IdentityComposer()), []) self.assertEqual(self.children(SplatComposer()), []) # sample of samplers self.assertEqual(self.children(QPUSubproblemAutoEmbeddingSampler(qpu_sampler=MockDWaveSampler())), []) self.assertEqual(self.children(SimulatedAnnealingSubproblemSampler()), []) self.assertEqual(self.children(TabuProblemSampler()), []) # sample of decomposers self.assertEqual(self.children(IdentityDecomposer()), []) self.assertEqual(self.children(EnergyImpactDecomposer(size=1)), []) self.assertEqual(self.children(RandomSubproblemDecomposer(size=1)), []) class TestTictoc(unittest.TestCase): def test_ctx_mgr(self): with mock.patch('hybrid.profiling.perf_counter', side_effect=[0, 1]): with tictoc() as t: pass self.assertEqual(t.tick, 0) self.assertEqual(t.dt, 1) def test_decorator(self): with mock.patch('hybrid.profiling.perf_counter', side_effect=[0, 1]): def f(): pass deco = tictoc('f') ff = deco(f) ff() self.assertEqual(deco.tick, 0) self.assertEqual(deco.dt, 1) class TestRunnableWalkers(unittest.TestCase): def test_iter_walk(self): flow = Loop(RacingBranches(Runnable(), Runnable()) | ArgMin()) names = [r.name for r in iter_inorder(flow)] self.assertEqual(names, ['Loop', 'Branch', 'RacingBranches', 'Runnable', 'Runnable', 'ArgMin']) def test_callback_walk(self): flow = Loop(RacingBranches(Runnable(), Runnable()) | ArgMin()) names = [] walk_inorder(flow, visit=lambda r, _: names.append(r.name)) self.assertEqual(names, ['Loop', 'Branch', 'RacingBranches', 'Runnable', 'Runnable', 'ArgMin']) class TestTimers(unittest.TestCase): def test_basic(self): timers = {} time = make_timeit(timers) with time('a'): _ = 1 self.assertSetEqual(set(timers.keys()), {'a'}) self.assertEqual(len(timers['a']), 1) def test_nested_timers(self): timers = {} time = make_timeit(timers) with time('a'): with time('b'): with time('c'): with time('b'): _ = 2 ** 50 self.assertSetEqual(set(timers.keys()), {'a', 'b', 'c'}) self.assertEqual(len(timers['a']), 1) self.assertEqual(len(timers['b']), 2) self.assertEqual(len(timers['c']), 1) def test_runnable_timer_called(self): class Ident(Runnable): def next(self, state): with self.timeit('my-timer'): return state r = Ident() r.run(State()).result() self.assertEqual(len(r.timers['my-timer']), 1) def test_runnable_default_timer_value(self): self.assertEqual(Runnable().timers['my-timer'], []) class TestCounters(unittest.TestCase): def test_basic(self): counters = {} count = make_count(counters) count('a') try: raise ZeroDivisionError except: count('b') finally: count('a', inc=3) self.assertSetEqual(set(counters.keys()), {'a', 'b'}) self.assertEqual(counters['a'], 4) self.assertEqual(counters['b'], 1) def test_runnable_counter_called(self): class Ident(Runnable): def next(self, state): self.count('my-counter', 3) self.count('your-counter') return state r = Ident() r.run(State()).result() self.assertEqual(r.counters['my-counter'], 3) self.assertEqual(r.counters['your-counter'], 1) def test_runnable_default_counter_value(self): self.assertEqual(Runnable().counters['my-counter'], 0)
UTF-8
Python
false
false
5,902
py
89
test_profiling.py
38
0.617587
0.611826
0
177
32.344633
110
Kexon5/Statistics
10,565,619,577,200
32f32e8feecdfe10ebaae13fab500754999fcc80
90cd8722c321e52c1a7c440f615b626465ac435a
/lab2.py
07dc184db37892ba5821f3cf91c79db6c025e11d
[]
no_license
https://github.com/Kexon5/Statistics
b26a2ef68c07840e4a9bb1ae6d4871aef0053ee7
5b5d927d4ee36884e541a6b75d720ca6c37c8e30
refs/heads/master
2021-05-27T01:26:05.350003
2020-06-30T09:28:53
2020-06-30T09:28:53
254,199,413
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np from tabulate import tabulate count_elem = [10, 100, 1000] distribution = ['Normal', 'Cauchy', 'Laplace', 'Poisson', 'Uniform'] N = 1000 def fun_z_q(arr): return (np.quantile(arr, 0.25) + np.quantile(arr, 0.75)) / 2 def fun_z_tr(arr): r = len(arr) // 4 arr_new = np.sort(arr) sum = 0 for i in range(r + 1, len(arr) - r): sum += arr_new[i] return sum / (len(arr) - 2 * r) def get_array(name, n): if name == distribution[0]: return np.random.normal(0, 1, n) elif name == distribution[1]: return np.random.standard_cauchy(n) elif name == distribution[2]: return np.random.laplace(0, np.sqrt(2) / 2, n) elif name == distribution[3]: return np.random.poisson(10, n) else: return np.random.uniform(-np.sqrt(3), np.sqrt(3), n) def lab2_run(): for dist_str in distribution: title_row = [dist_str, "x_", "med x", "z_r", "z_q", "z_tr"] rows = [] for n in count_elem: x, med, z_r, z_q, z_tr = [], [], [], [], [] for i in range(N): arr = get_array(dist_str, n) x.append(np.mean(arr)) med.append(np.median(arr)) arr_sort = np.sort(arr) z_r.append((arr_sort[0] + arr_sort[-1]) / 2) z_q.append(fun_z_q(arr)) z_tr.append(fun_z_tr(arr)) rows.append(["n = %i" % n, 6 * ""]) rows.append([" E(z) ", np.around(np.mean(x), decimals=6), np.around(np.mean(med), decimals=6), np.around(np.mean(z_r), decimals=6), np.around(np.mean(z_q), decimals=6), np.around(np.mean(z_tr), decimals=6)]) rows.append([" D(z) ", np.around(np.std(x) ** 2, decimals=6), np.around(np.std(med) ** 2, decimals=6), np.around(np.std(z_r) ** 2, decimals=6), np.around(np.std(z_q) ** 2, decimals=6), np.around(np.std(z_tr) ** 2, decimals=6)]) rows.append(["" * 7]) print(tabulate(rows, title_row, tablefmt="latex"), end="\n\n")
UTF-8
Python
false
false
2,340
py
13
lab2.py
13
0.455983
0.431197
0
68
32.411765
70
way2muchnoise/Advent2020
8,375,186,270,486
7a55fbc4a5706a28ef98a7c8c8f5502425a0b278
448e2ce1ee9d2114d138e222814d5ee354fbadec
/day11/part2.py
9e4dfe97ab971e7f4ae34163dd4a5f7dc3539199
[]
no_license
https://github.com/way2muchnoise/Advent2020
ecfa598fc38106bd442431d650cc800b00507b66
a944348b0e1fd297f8c14df519a68976cc384038
refs/heads/main
2023-02-01T20:11:56.859630
2020-12-19T10:03:32
2020-12-19T10:03:32
319,600,853
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
seat_rows = [] with open('input.txt', 'r') as f: line = f.readline() while line: seat_rows.append([char for char in line[:-1]]) # strip \n and split in chars line = f.readline() def check_diagonal(row, seat, move_row, move_seat, seat_rows): check_row = row + move_row check_seat = seat + move_seat while 0 <= check_row < len(seat_rows) and 0 <= check_seat < len(seat_rows[check_row]) and seat_rows[check_row][check_seat] == '.': check_row += move_row check_seat += move_seat if 0 <= check_row < len(seat_rows) and 0 <= check_seat < len(seat_rows[check_row]) and seat_rows[check_row][check_seat] == '#': return 1 else: return 0 def count_occupied_around(row, seat, seat_rows): occupied_around = 0 occupied_around += check_diagonal(row, seat, -1, -1, seat_rows) # top left occupied_around += check_diagonal(row, seat, -1, 0, seat_rows) # top occupied_around += check_diagonal(row, seat, -1, +1, seat_rows) # top right occupied_around += check_diagonal(row, seat, 0, -1, seat_rows) # left occupied_around += check_diagonal(row, seat, 0, +1, seat_rows) # right occupied_around += check_diagonal(row, seat, +1, -1, seat_rows) # bottom left occupied_around += check_diagonal(row, seat, +1, 0, seat_rows) # bottom occupied_around += check_diagonal(row, seat, +1, +1, seat_rows) # bottom right return occupied_around changes = -1 while changes != 0: changes = 0 new_seat_rows = [row[:] for row in seat_rows] # Copy array for row in range(len(seat_rows)): for seat in range(len(seat_rows[row])): if seat_rows[row][seat] != '.': occupied_around = count_occupied_around(row, seat, seat_rows) if seat_rows[row][seat] == '#' and occupied_around >= 5: new_seat_rows[row][seat] = 'L' changes += 1 if seat_rows[row][seat] == 'L' and occupied_around == 0: new_seat_rows[row][seat] = '#' changes += 1 seat_rows = new_seat_rows occupied = 0 for row in seat_rows: for seat in row: if seat == '#': occupied += 1 print(occupied)
UTF-8
Python
false
false
2,231
py
30
part2.py
29
0.577768
0.562976
0
54
40.314815
134
ritik1501/MarkDoc
7,937,099,605,231
fa2387df7d1932fd4cf5ca36b93d26b7b5031548
792331ca24a107a4572ea10cc260a24699b283c6
/karm/migrations/0001_initial.py
564d1f49636ff499511f7133a92ef0bc3c51b962
[]
no_license
https://github.com/ritik1501/MarkDoc
908c8f502d67c4992e35b7cd1ffd514c5795501f
d31faf1b84baf918aa308dccfb2e2b535b80c082
refs/heads/master
2023-02-15T07:15:39.185933
2021-01-04T12:54:25
2021-01-04T12:54:25
326,681,546
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 3.0.3 on 2020-08-27 12:14 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Appointment', fields=[ ('sno', models.AutoField(primary_key=True, serialize=False)), ('pat_name', models.CharField(max_length=100)), ('doc_name', models.CharField(max_length=100)), ('pat_email', models.CharField(max_length=100)), ('doc_email', models.CharField(max_length=100)), ('disease', models.CharField(max_length=100)), ('meeting_link', models.CharField(max_length=100)), ('status', models.CharField(default='pending', max_length=25)), ('timing', models.DateTimeField(default=django.utils.timezone.now)), ], ), migrations.CreateModel( name='Contact', fields=[ ('sno', models.AutoField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=100)), ('email', models.CharField(max_length=100)), ('message', models.CharField(max_length=100)), ('timestamp', models.DateTimeField(default=django.utils.timezone.now)), ], ), migrations.CreateModel( name='Doctor', fields=[ ('sno', models.AutoField(primary_key=True, serialize=False)), ('username', models.CharField(max_length=20)), ('first_name', models.CharField(max_length=100)), ('last_name', models.CharField(max_length=100)), ('email', models.CharField(max_length=100)), ('phone_number', models.CharField(max_length=10)), ('user_type', models.CharField(default='doctor', max_length=10)), ], ), migrations.CreateModel( name='Patient', fields=[ ('sno', models.AutoField(primary_key=True, serialize=False)), ('username', models.CharField(max_length=20)), ('first_name', models.CharField(max_length=100)), ('last_name', models.CharField(max_length=100)), ('email', models.CharField(max_length=100)), ('phone_number', models.CharField(max_length=10)), ('user_type', models.CharField(default='user', max_length=10)), ], ), ]
UTF-8
Python
false
false
2,672
py
15
0001_initial.py
8
0.524701
0.497006
0
63
40.412698
87
exinmusic/public-pasta
206,158,432,245
35d97602e127692c0b281989ab045d6b82395b85
e72cfa8aee383d192b62a8361e721615495531dc
/pp/pastas/models.py
a3ae5b43d3bf5c6fdfb3813cd93aa9e42de7a12e
[]
no_license
https://github.com/exinmusic/public-pasta
ea41cf2edb6e9a0b54ed70172237217e88fec85a
6a9c37c85e7b31bd5288413d1fd099022f606031
refs/heads/master
2021-09-27T10:08:48.119004
2020-08-28T21:30:59
2020-08-28T21:30:59
239,707,328
0
0
null
false
2021-09-22T18:56:25
2020-02-11T08:01:01
2020-08-28T21:31:07
2021-09-22T18:56:23
66
0
0
3
Python
false
false
from django.db import models from multiselectfield import MultiSelectField CATEGORIES = [ ('wholesome','wholesome'), # Feel good content or good natured. ('sermon','sermon'), # Preaching. Written with arrogance. ('intelligent','intelligent'), # Not ironically intelligent, as much as possible. ('dumb','dumb'), # Just really unredeemingly stupid. ('funny','funny'), # is funny. ('sad','sad'), # is sad. ('political','political'), # Flags anything political, includes mentions of politicians. ('complaint','complaint'), # Flags compaints. ('emoji','emoji'), # Content with exessive use of emoticons. ('daddy','daddy'), # Content written "to" sugar daddies. ('sexy','sexy'), # Sexual Content. ('pro','pro'), # Professional advise. ('creepy', 'creepy'), # Creepy or dark in nature. ('food', 'food'), # Food ('ascii-art', 'ascii-art'), # 8===D -by xn ('story', 'story'), # Story time, gather around. ('cyrillic', 'cyrillic'), # Russian pastas only, comrade. ('chad', 'chad'), # Broh. ] SENTIMENTS = [ ('positive', 'positive'), ('negative', 'negative') ] class Pasta(models.Model): text = models.TextField(max_length=15000) date_created = models.DateTimeField(auto_now_add=True, blank=True) name = models.CharField(max_length=500, default='', blank=True) categories = MultiSelectField(max_length=150, choices=CATEGORIES, default='', blank=True) safe = models.BooleanField(default=False) # Pasta could popup at work and not get a homie fired. verified = models.BooleanField(default=False) # Famous pasta. sentiment = models.CharField(max_length=8, choices=SENTIMENTS, default='', blank=True) def __str__(self): return self.name
UTF-8
Python
false
false
1,977
py
16
models.py
14
0.580678
0.574102
0
40
48.325
110
asifbk/k_nearest_neighbors
18,064,632,459,576
14e97e60dc6a33f3d50a531e8ba93ad86e054643
48a70738a2b09a028b76d81d6ef2fc9c28375300
/Machine learning/Breast cancer dataset/breastcancer
8967a844c93cfb23bfca23210a17ac98ca097d8f
[]
no_license
https://github.com/asifbk/k_nearest_neighbors
7d475ac235be6dacb599c1b2ff9eee5e958049f9
d4bbe93b44c6dc286a79b30546f693e3014df8cf
refs/heads/master
2020-03-17T07:22:39.010714
2018-05-20T18:03:09
2018-05-20T18:03:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 20 15:32:53 2018 @author: asif """ import numpy as np from sklearn import preprocessing, cross_validation,neighbors import pandas as pd df= pd.read_csv('breast-cancer-wisconsin.data') df.replace('?',-99999, inplace= True) df.drop(['id'],1,inplace=True) X=np.array(df.drop(['class'],1)) y=np.array(df['class']) X_train, X_test, y_train, y_test=cross_validation.train_test_split(X,y,test_size=0.2) clf = neighbors.KNeighborsClassifier() clf.fit(X_train,y_train) accuracy = clf.score(X_test, y_test) print(accuracy) example_measures= np.array([[4,2,1,1,1,2,3,2,1],[4,2,1,1,1,2,3,2,1]]) example_measures=example_measures.reshape(2, -1) #for any length use this #example_measures=example_measures.reshape(len(example_measures), -1) prediction=clf.predict(example_measures) print(prediction)
UTF-8
Python
false
false
857
5
breastcancer
5
0.723454
0.672112
0
27
30.777778
85
opsicl/megatemp
16,982,300,698,635
2127790fbee4dad5456a1c4db8605f68af55dbd1
4f8016e498972935981f448f23efda7a28a81bfc
/config/shrink_config.py
cebf757e2d882e530f4f3fb1e870862f76162b6b
[]
no_license
https://github.com/opsicl/megatemp
16f6b8c078ea55f70e95daf280104598aab3451e
b405c1eddbd72d8268777d3be12cafab3306abcb
refs/heads/main
2023-03-09T08:17:33.758342
2021-02-18T18:13:10
2021-02-18T18:13:10
308,662,134
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import json goodconfig = '' with open("config.json") as config: for line in config.readlines(): if not line.startswith('#'): goodconfig += line print(json.dumps(json.loads(goodconfig),separators=(',', ':')))
UTF-8
Python
false
false
239
py
10
shrink_config.py
4
0.610879
0.610879
0
9
25.444444
67
wenner84/openerp7
15,874,199,127,075
78739249403f97c2e8f20c8b7cf21ec1b51874d1
e757b0f0013075543a0de18e341901880bbe2f10
/wf_backorder/purchase_order_line.py
d7f1c260c0afff91660da874105f93d667737427
[]
no_license
https://github.com/wenner84/openerp7
5e5320e50eac6ba38681b873d7b7a8c767550a08
04c5b68f0f291e237dbb51ca0eff8c7d5e1c02c8
refs/heads/master
2017-12-22T04:16:54.419810
2017-05-23T09:54:27
2017-05-23T09:57:53
16,729,956
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from openerp.osv import fields, osv class purchase_order_line(osv.osv): _inherit = "purchase.order.line" _columns = { 'wf_sold_qty': fields.float('sold qty'), } purchase_order_line()
UTF-8
Python
false
false
232
py
1,013
purchase_order_line.py
481
0.612069
0.607759
0
10
21.9
48
f12markovic/mmwave-gesture-recognition
2,542,620,640,011
7003928908603bbc6c0dca2506d6fa27980fb69b
0c1ab94664a48823e6f094ec7f9f1a8206cc1f2f
/test.py
ad55f951ea769e61e0dfd3dca46f9f53ddc69720
[ "MIT" ]
permissive
https://github.com/f12markovic/mmwave-gesture-recognition
2da1e895acf2215684c80e9a1f2b9cceb75ce686
de3aba1cd2704623001eaabdf9d9f40350484862
refs/heads/master
2020-07-25T00:14:14.586559
2019-09-20T09:43:08
2019-09-20T09:43:08
208,088,521
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python import time from parser import Parser from nn import NN from plotter import Plotter from connection import Connection from utility_functions import threaded @threaded def nn_thread(p): nn = NN(p) nn.load_model() print() while True: collected = False while not collected: collected = nn.get_data() time.sleep(0.05) nn.predict(debug=True) time.sleep(0.05) @threaded def interpretor(c, p): while True: frame = c.getFrame() p.parse(frame) c.readDone() time.sleep(0.05) if __name__ == '__main__': ports = [] while ports == []: ports = Connection.findPorts() conn = Connection(ports[0], ports[1]) mmwave_configured = False while not mmwave_configured: mmwave_configured = conn.sendCfg('./profiles/profile.cfg') parser = Parser() plotter = Plotter(parser) interpretor(conn, parser) nn_thread(parser) conn.listen() plotter.plot_detected_objs()
UTF-8
Python
false
false
1,039
py
7,810
test.py
10
0.610202
0.599615
0
52
18.980769
66
auburnsummer/orchard-bot
19,155,554,151,713
11db32a0ae1c3d74c2b38ee0939ddda02597ea4e
117c2424d46c1fc9ba7e77062f41df32c0ec8945
/ob/handlers/orchard_db.py
c6bad88249bb41ec8bab5bf84c04f682308a5bbd
[]
no_license
https://github.com/auburnsummer/orchard-bot
270188a58c46af3c8c3a5318f2569280cddca652
50230cf651e5e5192ded1ec10813e5f4ba14e1a3
refs/heads/master
2023-09-03T23:17:11.653887
2021-11-08T01:42:48
2021-11-08T01:42:48
380,678,194
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from starlette.responses import FileResponse, JSONResponse from ob.constants import DB_PATH async def orchard_dot_db(request): return FileResponse(DB_PATH, media_type="application/x-sqlite3")
UTF-8
Python
false
false
196
py
24
orchard_db.py
21
0.806122
0.80102
0
5
38.4
68
lumasepa/clean_admin
3,298,534,891,327
b0b69faf9e36ae516cdda05fa4e13debec4dddaf
cf76f58af18b1c73566f2d55a4e108290c379b7c
/example/second_app/models.py
1562c8f0711565636e9f4a7e41c0f100fd1a7d33
[]
no_license
https://github.com/lumasepa/clean_admin
20d4548f769662b195cf63e8da23eb15784b0822
83c9f9b1439c1bbf5dffdb19870e345099c9cefd
refs/heads/master
2021-06-22T12:36:15.327774
2016-12-06T10:38:33
2016-12-06T10:38:33
98,795,062
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.core.exceptions import ValidationError from django.db import models class ManyToManyModel(models.Model): name = models.CharField( max_length=500, help_text="write something" ) class AllFieldsModel(models.Model): char_field = models.CharField( max_length=500, help_text="write something", null=True, blank=True ) int_field = models.IntegerField( help_text="Put a number, magic number", null=True, blank=True ) text_field = models.TextField( help_text="Put a large test here", null=True, blank=True ) big_integer_field = models.BigIntegerField( help_text="An big integer field", null=True, blank=True ) binary_field = models.BinaryField( help_text="A binary field", null=True, blank=True ) date_field = models.DateField( help_text="A date field", null=True, blank=True ) datetime_field = models.DateTimeField( help_text="A datetime field", null=True, blank=True ) boolean_field = models.BooleanField( help_text="A boolean field", ) comma_separated_integer_field = models.CommaSeparatedIntegerField( max_length=200, help_text="A comma sepparated integer field", null=True, blank=True ) decimal_field = models.DecimalField( decimal_places=10, max_digits=100, help_text="A decimal field", null=True, blank=True ) duration_field = models.DurationField( help_text="A duration field", null=True, blank=True ) email_field = models.EmailField( help_text="A email field", null=True, blank=True ) file_field = models.FileField( help_text="A file field", null=True, blank=True ) file_path_field = models.FilePathField( help_text="A file path field", null=True, blank=True ) float_field = models.FloatField( help_text="A float field", null=True, blank=True ) generic_ip_addr_field = models.GenericIPAddressField( help_text="A generic ip addr field", null=True, blank=True ) image_field = models.ImageField( help_text="A image field", null=True, blank=True ) null_boolean_field = models.NullBooleanField( help_text="A null boolean field", null=True, blank=True ) positive_integer_field = models.PositiveIntegerField( help_text="A positive integer", null=True, blank=True ) positive_small_integer_field = models.PositiveSmallIntegerField( help_text="A positive small integer field", null=True, blank=True ) slug_field = models.SlugField( help_text="A slug field", null=True, blank=True ) small_integer_field = models.SmallIntegerField( help_text="A small integer field", null=True, blank=True ) time_field = models.TimeField( help_text="A time field", null=True, blank=True ) url_field = models.URLField( help_text="A url field", null=True, blank=True ) uuid_field = models.UUIDField( help_text="A uuid field", null=True, blank=True ) many_to_many_field = models.ManyToManyField( ManyToManyModel, help_text="A many to many field", null=True, blank=True ) class ForeingModel(models.Model): name = models.CharField( max_length=500, choices=(("a", "1"), ("b", "2"), ("c", "3")), help_text="write something" ) age = models.PositiveSmallIntegerField() birthday = models.DateField() foreign_key_field = models.ForeignKey( AllFieldsModel, help_text="A foreign_key field" ) def clean(self): if self.age > 100: raise ValidationError("Age must be under 100") class ForeingModeltoForeingModel(models.Model): inner_name = models.CharField( max_length=500, choices=(("a", "1"), ("b", "2"), ("c", "3")), help_text="write something" ) foreign_key_field = models.ForeignKey( ForeingModel, help_text="A foreign_key field" )
UTF-8
Python
false
false
4,533
py
34
models.py
14
0.564086
0.557026
0
208
20.793269
70
MariamAmmar/Moodbot-
12,893,491,853,120
24ba3325f42e5d6b0098b8adab14731087bd5445
673ed92b4202bbdc0323808823012ced4de3a06f
/main.py
0b3d0d8cc07074e47eb2ad85b5cf957072dbca93
[]
no_license
https://github.com/MariamAmmar/Moodbot-
bc3f8128858465b63447486d63ea6a77bedaaae7
7800ce4f79c1350757badb13fa6713d963727cd6
refs/heads/main
2023-07-06T18:08:56.832182
2021-08-21T13:34:59
2021-08-21T13:34:59
398,564,848
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Mariam Ammar Class: CS 521 - Summer 2 Date: 08/20/21 Final Project A moodbot program that returns options for a user based on input relating to their mood. """ from datetime import datetime import random import vlc from User import User import sys import time def play_audio(filename): ''' Takes filename as argument and plays song file Allows user to stop song by pressins 's ''' p = vlc.MediaPlayer(filename) p.play() while True: user_input = input("Press 's' to end audio.") if user_input == 's': return p.stop() break else: print("Sorry, you can only press 's' to stop the audio.") #Asks user for name and name of friend #assigns default values if blank input is given name = input("Please input your first name.") if not name: name = "my friend" close_contact = input("Who's your best friend?" or "your best friend") if not close_contact: close_contact = "your best friend" print(f''' Hi {name}! Welcome to be Moodbot. We have just a few more questions for you. ''') #Asks for birthday #Prompts for user input and reprompts if user input invalid. while True: year = input('When is your birthday? [YY] ') month = input('When is your birthday? [MM] ') day = input('When is your birthday? [DD]') try: year, month, day = int(year), int(month), int(day) #Convert into datetime format for parsing later birthday = datetime(year,month,day) break except: print(''' Sorry, try again! Your number entries must follow the right format. ''') #This while loop allows user to come back to main menu #each time a selection has been made. while True: #Ask user to rate their mood from 1-10 #Validate input or return error and ask for re-entry while True: mood \ = input(''' Rate the way you feel right now from 1-10 with 10 being the best possible score. ''') try: mood = int(mood) #If mood outside of range 1-10, ask user to reinput while mood not in range (1,11): mood\ = int(input(''' Sorry, try again and make sure you input a number from 1-10. ''')) break #Prints when user does not input a number except: print(''' Sorry! Looks like you didn't input a number. Please try again. ''') #Assign person as p1 to User class p1 = User(name, close_contact, birthday, mood) #Menu option selections #If users input score 1-5, these selections will be printed sad_options = \ (1, "Listen to a Song"),\ (2, "Write about it"),\ (3, "Meditate"),\ (4, "Read an inspirational quote"),\ (5, "Get some tips"),\ (6, "Read a funny poem") #If user inputs a score of 5 or above, these selections printed happy_options = \ (1, "Listen to a Song"), \ (2, "Write a letter to your future self"), \ (3, "Take note of some great ideas"), \ (4, "Plan your birthday celebration"),\ (5, "Have a dance party"), \ (6, "Read a fun fact") #If mood is 1-2, then user is in critical condition #Reminder of closest friend is printed before showing options if mood < 3 : print(f''' Wow. Looks like you're really upset. Make sure to seek out help and think of what {close_contact} would think if they knew you were feeling like this! How about giving them a call? Or you can...\n ''') for i in sad_options: print(i[0],i[1]) #If user inputs score from 3-4, output messsage below with sad options if 2 < mood < 5: print(f''' Why so blue? Your birthday is only {p1.calculate_days_till_bday(p1.birthday)} days away! Prepare a celebration or choose one of the options below.\n''') for i in sad_options: print(i[0],i[1]) #If mood score > 4 then user is either okay or in good mood. #Print message with happy options if mood > 4: print(''' Nice to hear you are at least doing ok! Which option would you like to choose?\n ''') for i in happy_options: print(i[0], i[1]) #Prompts user to make selection after options have been printed selection = input("Input a number to select an option.") #If selection out of option range #prompt user to re-input selection try: selection = int(selection) while selection not in range (1,7): selection = int(input('''Sorry, try again.\n Enter a number according to one of the options.''')) break #prints if user does not put number input except: print("Sorry, try again. You need to input a number.") #Tips to be printed if user selects "Get some tips" options #Could have been also been defined as list or tuple. tips = \ { "1. Take a few really deep, controlled breaths.", "2. Call a good friend.", "3. Go for a walk.", "4. Do something outside.", "5. Exercise!", "6. Eat healthy - food is linked to both physical and mental health.", "7. Get at least 8 hours of sleep a day.", "8. Make time for yourself and include relaxing rituals into your day.", "9. Stay away from smoking and limit your alcohol intake." } #Inspiration quotes to be printed #based on user selected opion. quotes = \ [ \ ''' \n"To anyone out there who’s hurting — it’s not a sign of weakness to ask for help. It’s a sign of strength." —Barack Obama''', "\nThe only time you fail is when you fall down and stay down.", "\nEvery day may not be good... but there’s something good in every day.", '''\n"Soak up the views. Take in the bad weather and the good weather. You are not the storm." —Matt Haig''', "\nA journey of 1000 miles always begins with a single step." ] #fun facts to be printed based on option fun_facts = \ ("More people get attacked every year by a cow than by a shark.", "When you cut a hole in your fishing net, it has fewer holes.", "Pennsylvania, USA, has a law which bans you from sleeping on a fridge.", "Hot water will turn into ice faster than cold water.", "The Mona Lisa has no eyebrows", "The entire world's population could fit inside Los Angeles.") #Songs to be play based on user selected option and mood. dict_audio = {"sad_song" : "theclimb.mp3", "happy_song" : "toosieslide.mp3", "meditation" : "meditation.mp3" , "dance_party" : "dance_party.mp3"} #Output options based on user input if unhappy if mood < 5 and selection == 1: play_audio(dict_audio["sad_song"]) elif mood < 5 and selection == 2: #Calls method from User class for user to write in journal print(p1._User__write_in_journal()) elif mood < 5 and selection == 3: #Plays meditation audio play_audio(dict_audio["meditation"]) elif mood < 5 and selection == 4: #Prints quote at random inded from quotes list index = random.randrange(0,len(quotes)-1) print(quotes[index]) elif mood < 5 and selection == 5: #Prints tips for long-term mental/physical health for i in sorted(tips): print(i) elif mood < 5 and selection == 6: #Asks for user words to input #User inputs arguments to generate madlib #User madlib method from User class while True: try: n1, n2 \ = input("Input two nouns with a space in between.")\ .split() adj1, adj2, adj3 \ = input("Input three adjectives with a space in between.")\ .split() #Prints and allows user to re-input #if user inputs incorrect number of values except: print("Sorry try again.") else: print(p1.mad_lib(n1, n2, adj1, adj2, adj3)+"\n") break #Actions taken for "Happy" options if mood > 4 and selection == 1: #Plays "Happy" song play_audio(dict_audio["happy_song"]) #Next three options allow user to input entry into journal elif mood > 4 and selection == 2: print(p1._User__write_in_journal()) elif mood > 4 and selection == 3: print(p1._User__write_in_journal()) elif mood > 4 and selection == 4: #Print statement with days till birthday calculated #Then allow for journal entry print(f''' Wow! Only {p1.calculate_days_till_bday(p1.birthday)} till your birthday. How will you celebrate and who will you invite?''') print(p1._User__write_in_journal()) elif mood > 4 and selection == 5: #Prints string characters with delay to add to mood of option strng = "~~~~~~~~~!!!!! ♪┏(・o・)┛♪┗ ( ・o・) ┓♪~~~~~~!!!!~~~~~~" for i in strng: print(i, end = "") time.sleep(0.05) #Play dance party audio as soon as string finishes printing play_audio(dict_audio["dance_party"]) #Returns fact at random index elif mood > 4 and selection == 6: index = random.randrange(0, len(fun_facts)-1) print("\n"+fun_facts[index]) #Allows user to exit program #or to go back to mood input to view options list user_input\ = input\ (''' \nPress 'b' to go back to the main menu or another character to exit the program. ''') if user_input == 'b': continue else: sys.exit(0)
UTF-8
Python
false
false
10,037
py
3
main.py
2
0.581042
0.568043
0
303
32.0033
78
rcbops/rpc-maas
9,938,554,331,809
5a6ff0f22666c78647ce0c73343098f2f6a987c2
3b59eb11fb4fb961ad60ddaa39dcdb22ae227e6c
/playbooks/files/rax-maas/plugins/ceph_monitoring.py
3b60d8ec1b792e3870b4dc3f23a51b33f8868de6
[ "Apache-2.0" ]
permissive
https://github.com/rcbops/rpc-maas
dcf56858a623a6559c8209830a7972358bd63b6c
9ec0b6e38dd724128557d14b8b8f0c95d6797db0
refs/heads/master
2023-08-17T11:52:32.837594
2023-08-07T17:54:46
2023-08-07T17:54:46
12,159,651
31
66
Apache-2.0
false
2023-08-07T14:19:30
2013-08-16T13:43:03
2022-01-13T05:29:04
2023-08-07T14:19:28
2,421
30
64
6
Python
false
false
#!/usr/bin/env python3 # Copyright 2015, Rackspace US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import json from maas_common import metric_bool from maas_common import metric from maas_common import MaaSException from maas_common import status_ok from maas_common import print_output import requests import subprocess STATUSES = {'HEALTH_OK': 2, 'HEALTH_WARN': 1, 'HEALTH_ERR': 0} IGNORE_CHECKS = ['OSDMAP_FLAGS', 'OBJECT_MISPLACED'] # See https://docs.ceph.com/docs/master/rados/operations/health-checks # for details on each. We had to break these down into sections as each # check has a max of 50 allowed metrics. DETAILED_CHECKS = { 'mon': [ 'MON_DOWN', 'MON_CLOCK_SKEW', 'MON_MSGR2_NOT_ENABLED', 'MON_DISK_LOW', 'MON_DISK_CRIT', 'MON_DISK_BIG', ], 'mgr': [ 'MGR_DOWN', 'MGR_MODULE_DEPENDENCY', 'MGR_MODULE_ERROR', ], 'osds': [ 'OSD_DOWN', 'OSD_DOWN', 'OSD_HOST_DOWN', 'OSD_ROOT_DOWN', 'OSD_ORPHAN', 'OSD_OUT_OF_ORDER_FULL', 'OSD_FULL', 'OSD_BACKFILLFULL', 'OSD_NEARFULL', 'OSDMAP_FLAGS', 'OSD_FLAGS', 'OLD_CRUSH_TUNABLES', 'OLD_CRUSH_STRAW_CALC_VERSION', 'CACHE_POOL_NO_HIT_SET', 'OSD_NO_SORTBITWISE', 'BLUEFS_SPILLOVER', 'BLUEFS_AVAILABLE_SPACE', 'BLUEFS_LOW_SPACE', 'BLUESTORE_FRAGMENTATION', 'BLUESTORE_LEGACY_STATFS', 'BLUESTORE_NO_PER_POOL_OMAP', 'BLUESTORE_DISK_SIZE_MISMATCH', 'BLUESTORE_NO_COMPRESSION', 'BLUESTORE_SPURIOUS_READ_ERRORS', ], 'device_health': [ 'DEVICE_HEALTH', 'DEVICE_HEALTH_IN_USE', 'DEVICE_HEALTH_TOOMANY', ], 'data_health': [ 'PG_AVAILABILITY', 'PG_DEGRADED', 'PG_RECOVERY_FULL', 'PG_BACKFILL_FULL', 'PG_DAMAGED', 'OSD_SCRUB_ERRORS', 'OSD_TOO_MANY_REPAIRS', 'LARGE_OMAP_OBJECTS', 'CACHE_POOL_NEAR_FULL', 'TOO_FEW_PGS', 'POOL_PG_NUM_NOT_POWER_OF_TWO', 'POOL_TOO_FEW_PGS', 'POOL_TOO_MANY_PGS', 'TOO_MANY_PGS', 'POOL_TARGET_SIZE_BYTES_OVERCOMMITTED', 'POOL_HAS_TARGET_SIZE_BYTES_AND_RATIO', 'TOO_FEW_OSDS', 'SMALLER_PGP_NUM', 'MANY_OBJECTS_PER_PG', 'POOL_APP_NOT_ENABLED', 'POOL_FULL', 'POOL_NEAR_FULL', 'OBJECT_MISPLACED', 'OBJECT_UNFOUND', 'SLOW_OPS', 'PG_NOT_SCRUBBED', 'PG_NOT_DEEP_SCRUBBED', 'PG_SLOW_SNAP_TRIMMING', ], 'misc': [ 'RECENT_CRASH', 'TELEMETRY_CHANGED', 'AUTH_BAD_CAPS', 'OSD_NO_DOWN_OUT_INTERVAL', ], } def check_command(command, container_name=None, deploy_osp=False): if container_name: if deploy_osp: container_command = ['/usr/bin/podman', 'exec', container_name] else: container_command = ['lxc-attach', '-n', container_name, '--', 'bash', '-c'] container_command.extend(command) command = [str(i) for i in container_command] output = subprocess.check_output(command, stderr=subprocess.STDOUT) lines = output.decode().strip().split('\n') return json.loads(lines[-1]) def get_ceph_rgw_hostcheck(rgw_address, container_name=None): try: sc = requests.get(rgw_address, verify=False).status_code if (sc >= 200) and (sc < 300): status_code = 2 else: status_code = 1 except requests.exceptions.ConnectionError: status_code = 0 return status_code def get_ceph_status(client, keyring, fmt='json', container_name=None, deploy_osp=False): return check_command(('ceph', '--format', fmt, 'status'), container_name=container_name, deploy_osp=deploy_osp) def get_ceph_mon_status(client, keyring, fmt='json', container_name=None, deploy_osp=False): return check_command(('ceph', 'mon', 'stat', '--format', fmt), container_name=container_name, deploy_osp=deploy_osp) def get_local_osd_info(osd_ref, fmt='json', container_name=None, deploy_osp=False): return check_command( ('ceph', '--format', fmt, 'daemon', osd_ref, 'status'), container_name=container_name, deploy_osp=deploy_osp ) def get_mon_statistics(client=None, keyring=None, host=None, container_name=None, deploy_osp=False): ceph_status = get_ceph_status(client=client, keyring=keyring, container_name=container_name, deploy_osp=deploy_osp) try: mon = [m for m in ceph_status['monmap']['mons'] if m['name'] == host] except KeyError: ceph_mon_status = get_ceph_mon_status(client=client, keyring=keyring, container_name=container_name, deploy_osp=deploy_osp) mon_in = host in ceph_status['quorum_names'] metric_bool('mon_in_quorum', mon_in) def get_health_checks(client=None, keyring=None, section=None, container_name=None, deploy_osp=False): metrics = [] ceph_status = get_ceph_status(client=client, keyring=keyring, container_name=container_name, deploy_osp=deploy_osp) # Go through the detailed health checks and generate metrics # for each based on the given section for curcheck in DETAILED_CHECKS[section]: if curcheck in ceph_status['health']['checks']: severity = ceph_status['health']['checks'][curcheck]['severity'] metrics.append({'name': curcheck, 'type': 'uint32', 'value': STATUSES[severity]}) else: metrics.append({'name': curcheck, 'type': 'uint32', 'value': STATUSES['HEALTH_OK']}) # Submit gathered metrics for m in metrics: metric(m['name'], m['type'], m['value']) def get_rgw_checkup(client, keyring=None, rgw_address=None, container_name=None, deploy_osp=False): rgw_status = get_ceph_rgw_hostcheck(rgw_address, container_name=container_name) metric('rgw_up', 'uint32', rgw_status) def get_osd_statistics(client=None, keyring=None, osd_id=None, container_name=None, deploy_osp=False): osd_ref = "osd.%s" % osd_id try: osd_info = get_local_osd_info( osd_ref, container_name=container_name, deploy_osp=deploy_osp ) except Exception: msg = 'The OSD ID %s does not exist.' % osd_id raise MaaSException(msg) else: state = 1 if osd_info.get('state', '') == 'active' else 0 metric_name = '_'.join((osd_ref, 'up')) metric_bool(metric_name, state) def get_cluster_statistics(client=None, keyring=None, container_name=None, deploy_osp=False): metrics = [] ceph_status = get_ceph_status(client=client, keyring=keyring, container_name=container_name, deploy_osp=deploy_osp) # Get overall cluster health # For luminous+ this is the ceph_status.health.status # For < Luminous this is the ceph_status.health.overall_status # SLM: 'overall_status' exists along with 'status' for luminous. # It will be HEALTH_WARN while 'status' will be HEALTH_OK. # The following should work for all with the newer overriding # the older if both exist. ceph_health_status = 'HEALTH_ERR' if 'overall_status' in ceph_status['health']: ceph_health_status = ceph_status['health']['overall_status'] if 'status' in ceph_status['health']: ceph_health_status = ceph_status['health']['status'] # Ignore checks. Quick fix from ceph admin request. if ceph_health_status != 'HEALTH_OK': ignore = True for curcheck in ceph_status['health']['checks']: if curcheck not in IGNORE_CHECKS: ignore = False break if ignore: ceph_health_status = 'HEALTH_OK' metrics.append({ 'name': 'cluster_health', 'type': 'uint32', 'value': STATUSES[ceph_health_status]}) # Collect epochs for the mon and osd maps metrics.append({'name': "monmap_epoch", 'type': 'uint32', 'value': ceph_status['monmap']['epoch']}) if 'osdmap' in ceph_status['osdmap']: metrics.append({'name': "osdmap_epoch", 'type': 'uint32', 'value': ceph_status['osdmap']['osdmap']['epoch']}) else: metrics.append({'name': "osdmap_epoch", 'type': 'uint32', 'value': ceph_status['osdmap']['epoch']}) # Collect OSDs per state if 'osdmap' in ceph_status['osdmap']: osds = {'total': ceph_status['osdmap']['osdmap']['num_osds'], 'up': ceph_status['osdmap']['osdmap']['num_up_osds'], 'in': ceph_status['osdmap']['osdmap']['num_in_osds']} else: osds = {'total': ceph_status['osdmap']['num_osds'], 'up': ceph_status['osdmap']['num_up_osds'], 'in': ceph_status['osdmap']['num_in_osds']} for k in osds: metrics.append({'name': 'osds_%s' % k, 'type': 'uint32', 'value': osds[k]}) # Collect cluster size & utilisation metrics.append({'name': 'osds_kb_used', 'type': 'uint64', 'value': ceph_status['pgmap']['bytes_used'] / 1024}) metrics.append({'name': 'osds_kb_avail', 'type': 'uint64', 'value': ceph_status['pgmap']['bytes_avail'] / 1024}) metrics.append({'name': 'osds_kb', 'type': 'uint64', 'value': ceph_status['pgmap']['bytes_total'] / 1024}) # Collect num PGs and num healthy PGs pgs = {'total': ceph_status['pgmap']['num_pgs'], 'active_clean': 0} for state in ceph_status['pgmap']['pgs_by_state']: if state['state_name'] == 'active+clean': pgs['active_clean'] = state['count'] break for k in pgs: metrics.append({'name': 'pgs_%s' % k, 'type': 'uint32', 'value': pgs[k]}) # Submit gathered metrics for m in metrics: metric(m['name'], m['type'], m['value']) def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--name', required=True, help='Ceph client name') parser.add_argument('--deploy_osp', action='store_true', default=False, help='Option for extending into OSP environments') parser.add_argument('--keyring', required=True, help='Ceph client keyring') parser.add_argument('--container-name', required=False, default=None, help='Ceph Container Name') subparsers = parser.add_subparsers(dest='subparser_name') parser_mon = subparsers.add_parser('mon') parser_mon.add_argument('--host', required=True, help='Mon hostname') parser_osd = subparsers.add_parser('osd') parser_osd.add_argument('--osd_id', required=True, type=str, help='A single OSD ID') parser_rgw = subparsers.add_parser('rgw') parser_rgw.add_argument('--rgw_address', required=True, help='RGW address in form proto://ip_addr:port/') parser.add_argument('--telegraf-output', action='store_true', default=False, help='Set the output format to telegraf') parser_mon = subparsers.add_parser('health_checks') # From https://docs.ceph.com/docs/master/rados/operations/health-checks parser_mon.add_argument('--section', required=True, help='(mon,mgr,osds,device_health,data_health \ or misc)') subparsers.add_parser('cluster') return parser.parse_args() def main(args): get_statistics = {'cluster': get_cluster_statistics, 'mon': get_mon_statistics, 'rgw': get_rgw_checkup, 'osd': get_osd_statistics, 'health_checks': get_health_checks} kwargs = {'client': args.name, 'keyring': args.keyring} if args.subparser_name == 'osd': kwargs['osd_id'] = args.osd_id if args.subparser_name == 'mon': kwargs['host'] = args.host if args.subparser_name == 'rgw': kwargs['rgw_address'] = args.rgw_address if args.subparser_name == 'health_checks': kwargs['section'] = args.section kwargs['container_name'] = args.container_name kwargs['deploy_osp'] = args.deploy_osp get_statistics[args.subparser_name](**kwargs) status_ok(m_name='maas_ceph') if __name__ == '__main__': args = get_args() with print_output(print_telegraf=args.telegraf_output): main(args)
UTF-8
Python
false
false
14,463
py
233
ceph_monitoring.py
70
0.538547
0.534122
0
408
34.448529
77
django-oscar/django-oscar
154,618,861,809
aa0b4da2c5e5c199a4efee6022ba8c4486742bd2
c491b5171775447a9ab33a036be1375f7b71ab2f
/src/oscar/apps/offer/views.py
e53c47945377f3dd66cf37a275a1ae95221627d7
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
https://github.com/django-oscar/django-oscar
e4abd486d51d6173dafbd9c10b59675858196e61
5edac196f41f8cc97f8a07f7579f1041db2a02af
refs/heads/master
2023-08-30T16:19:12.081909
2023-07-14T11:53:30
2023-07-14T11:53:30
1,151,051
5,320
2,524
BSD-3-Clause
false
2023-09-13T19:48:30
2010-12-08T21:30:32
2023-09-12T12:43:09
2023-09-13T19:48:29
120,979
5,846
2,149
94
Python
false
false
from django import http from django.conf import settings from django.shortcuts import get_object_or_404 from django.views.generic import ListView from oscar.core.loading import get_model ConditionalOffer = get_model("offer", "ConditionalOffer") Range = get_model("offer", "Range") class OfferListView(ListView): model = ConditionalOffer context_object_name = "offers" template_name = "oscar/offer/list.html" def get_queryset(self): """ Return a queryset of active :py:class:`ConditionalOffer <oscar.apps.offer.abstract_models.AbstractConditionalOffer>` instances with an :py:attr:`offer_type <oscar.apps.offer.abstract_models.AbstractConditionalOffer.offer_type>` of :py:const:`ConditionalOffer.SITE <oscar.apps.offer.abstract_models.AbstractConditionalOffer.SITE>`. """ return ConditionalOffer.active.filter(offer_type=ConditionalOffer.SITE) class OfferDetailView(ListView): context_object_name = "products" template_name = "oscar/offer/detail.html" paginate_by = settings.OSCAR_OFFERS_PER_PAGE # pylint: disable=W0201 def get(self, request, *args, **kwargs): try: self.offer = ConditionalOffer.active.select_related().get( slug=self.kwargs["slug"] ) except ConditionalOffer.DoesNotExist: raise http.Http404 return super().get(request, *args, **kwargs) def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx["offer"] = self.offer ctx["upsell_message"] = self.offer.get_upsell_message(self.request.basket) return ctx def get_queryset(self): """ Return a queryset of all :py:class:`Product <oscar.apps.catalogue.abstract_models.AbstractProduct>` instances related to the :py:class:`ConditionalOffer <oscar.apps.offer.abstract_models.AbstractConditionalOffer>`. """ return self.offer.products() class RangeDetailView(ListView): template_name = "oscar/offer/range.html" context_object_name = "products" paginate_by = settings.OSCAR_PRODUCTS_PER_PAGE # pylint: disable=W0201 def dispatch(self, request, *args, **kwargs): self.range = get_object_or_404(Range, slug=kwargs["slug"], is_public=True) return super().dispatch(request, *args, **kwargs) def get_queryset(self): """ Return a queryset of all :py:class:`Product <oscar.apps.catalogue.abstract_models.AbstractProduct>` instances related to the :py:class:`Range <oscar.apps.offer.abstract_models.AbstractRange>`. """ products = self.range.all_products().browsable() return products.order_by("rangeproduct__display_order") def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx["range"] = self.range return ctx
UTF-8
Python
false
false
2,887
py
979
views.py
617
0.675442
0.669553
0
76
36.986842
124
Abirami8799/python-project
395,137,023,713
154f5981e1e00159267bc46144b3d781066f74c9
030a3de3800c5a369d287f2f21a4d4e65a107c18
/tamilwords.py
2859b002c5748c57244c3fe8b4f51e37f1d19502
[]
no_license
https://github.com/Abirami8799/python-project
8139bf943e932d85615694bf443fd1e5d49b2601
3583fb87f53ee926cff749727c28d5aee424c498
refs/heads/master
2023-09-03T08:11:02.777261
2021-11-15T18:28:19
2021-11-15T18:28:19
395,344,547
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import tamil from tamil.utf8 import get_letters, get_letters_length, get_words value = int(input("enter the word ")) l=[] for i in range(1,value+1): x=input(f'enter the letter {i} ') l.append(x) n=''.join(map(str,l)) for root, dirs, files in os.walk("C:/Users/codiislap10/Documents/new"): for name in dirs: if name == "len_"+str(value): a=os.path.join(root,name) if bool(l[0]): for root, dirs, files in os.walk(a): for val in files: if val.startswith(n[0]): b=os.path.join(root,val) file1=open(b,encoding="utf-8") lines=file1.read() word=get_words(lines) r=get_letters_length(n) for each in word: m=get_letters(each) y=[m.index(j) for i,j in zip(l,m) if i==j] if len(y)==r: print(''.join(map(str,m))) else: for root, dirs, files in os.walk(a): for val in files: b=os.path.join(root,val) file1=open(b,encoding="utf-8") lines=file1.read() word=get_words(lines) r=get_letters_length(n) for each in word: m=get_letters(each) y=[m.index(j) for i,j in zip(l,m) if i==j] if len(y)==r: print(''.join(map(str,m)))
UTF-8
Python
false
false
1,347
py
4
tamilwords.py
4
0.514477
0.504826
0
44
28.613636
71
MasudRehmanSyed/instragram_follower_bot
3,848,290,702,909
65718b56b3c7ec636fc9e0c989aaf44c2b18d29b
6617a21a97832c9cd8da2c37716c7b3d345aa8ab
/instafollower.py
a80465a31289169eac8ae104c146ea840c32b56f
[]
no_license
https://github.com/MasudRehmanSyed/instragram_follower_bot
9c5406663e69806821936be462dc094a97edfd9b
0a59e26f9bd1056e89b7b50d5de623254ec60e8e
refs/heads/master
2023-07-04T06:43:35.342484
2021-07-27T18:14:26
2021-07-27T18:14:26
389,802,313
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time SITE= 'https://www.instagram.com/accounts/login/' class Instafollower: def __init__(self): self.driver = webdriver.Chrome('C:\webdrivers\chromedriver.exe') self.driver.maximize_window() self.driver.get(SITE) def login(self, uname, passw): self.driver.implicitly_wait(5) self.driver.find_element_by_name('username').send_keys(uname) self.driver.find_element_by_name('password').send_keys(passw) self.driver.implicitly_wait(2) self.driver.find_element_by_name('password').send_keys(Keys.ENTER) self.driver.implicitly_wait(2) self.driver.find_element_by_xpath('//button[@class="sqdOP L3NKy y3zKF "]').click() time.sleep(3) def kill_pop_up(self): self.driver.find_element_by_css_selector('.mt3GC .HoLwm').click() def find_followers(self): self.driver.get('https://www.instagram.com/chefsteps') self.driver.implicitly_wait(3) follow_button = self.driver.find_element_by_xpath('//button[@class="_5f5mN jIbKX _6VtSN yZn4P "]') follow_button.click() def follow(self): ''' Gets the pop up and selects the div with all the names and runs a javascript to select all the follow''' modal = self.driver.find_element_by_xpath('/html/body/div[5]/div/div/div[2]') for i in range(0, 10): self.driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", modal) time.sleep(2) def quit_web(self): self.driver.quit()
UTF-8
Python
false
false
1,649
py
3
instafollower.py
2
0.642814
0.630685
0
46
34.869565
119
wang7211401/python-reptile
16,578,573,773,884
9661465dd0c49d3dbfb33a5411c05559499c8d3a
d56c6d29c619818ac112d5bb289cb33e0ec546b8
/demo/urlparse.py
0fe851a03fdf816f39e3eacdcd4ffe130aad930a
[]
no_license
https://github.com/wang7211401/python-reptile
d806735815be5ac331f024a00099efeab5c266c9
fe7ec412c6f49a1cac9f50b3c14bcd24fd7a1fde
refs/heads/master
2020-05-30T05:59:06.152170
2019-10-30T07:07:37
2019-10-30T07:07:37
189,568,726
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# from urllib.parse import urlparse # result = urlparse('http://www.baidu.com/index.html;user?id=5#comment',allow_fragments=False) # print(result.scheme,result[0],result.netloc,result[1],sep='\n') # from urllib.parse import urlunparse # data = ['http','www.baidu.com','index.html','user','a=6','comment'] # print(urlunparse(data)) # from urllib.parse import urlsplit # result = urlsplit('http://www.baidu.com/index.html;user?id=5#comment') # print(result.scheme,result[0]) # from urllib.parse import urlunsplit # data = ['http','www.baidu.com','index.html','a=6','comment'] # print(urlunsplit(data)) # from urllib.parse import urljoin # print(urljoin('http://www.baidu.com','FAQ.html')) # from urllib.parse import urlencode # params = { # 'name':'germey', # 'age':22 # } # base_url ='http://www.baidu.com?' # url = base_url + urlencode(params) # print(url) # from urllib.parse import parse_qsl # query = 'name=germey&age=22' # print(parse_qsl(query)) # from urllib.parse import quote # keyword ='壁纸' # url ='https://www.baidu.com/s?wd=' + quote(keyword) # print(url) from urllib.parse import unquote url = 'https://www.baidu.com/s?wd=%E5%A3%81%E7%BA%B8' print(unquote(url))
UTF-8
Python
false
false
1,203
py
7
urlparse.py
7
0.683069
0.668891
0
50
23
94
BusinessJoe/PolytopeVisualizer
13,194,139,546,555
3f836d80b50c83047a079449a50f420af9226699
db812e6b7d0772048cfe4041baf2b4265f87ca21
/tests/test_diagram.py
114eddad678ee595593b2ec68db9b1395ef6d0a4
[]
no_license
https://github.com/BusinessJoe/PolytopeVisualizer
895679e8ff5593351cccdcb1d1146aed6b221c16
5c2b74791aada41f83eb5419c3d9876ec63b98aa
refs/heads/main
2023-04-13T12:56:55.055340
2022-05-05T20:55:07
2022-05-05T20:55:07
320,091,552
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pytest from polytope_visualizer.math import diagram def test_gen_53(): d = diagram.CoxeterDiagram([1, 1, 1], [5, 3]) print(d.polytope())
UTF-8
Python
false
false
155
py
26
test_diagram.py
21
0.670968
0.625806
0
7
21
49
lili4cityu/TextRankPlus
14,422,500,199,384
9482f667c3457a6c1c87a7598376de5f41d073d7
8a1a7579f7ed188ea562358a6a89e9b6a5c7c85b
/word2vec/traditional2Simplified/getChineseSimplified.py
8f754f0a2ec59783504a0e3e8bda1afc0caea66a
[]
no_license
https://github.com/lili4cityu/TextRankPlus
fa5def3f07f041000c4ee25f32019d915652295c
c655bd5b88a5dec829cedac462b2f1634fb0b42f
refs/heads/master
2020-07-07T16:00:23.592076
2019-08-20T14:52:42
2019-08-20T14:52:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Created on Thu Oct 20 12:13:18 2016 @author: zuoxiaolei """ from langconv import * def getSimple(line,fileWrite): line = Converter('zh-hans').convert(line.decode('utf-8')) line = line.encode('utf-8') fileWrite.write(line+'\n')
UTF-8
Python
false
false
271
py
18
getChineseSimplified.py
16
0.638376
0.583026
0
13
19.769231
61
FiniteElementries/barebone_server
10,402,410,837,315
6cbcd7a8e031a016a9c9a46349e51ca66196cb6f
c37c11cac340b413f2ce638769f0b5623433a139
/userprofile/urls.py
27bba6fd6647359f9d0c1fb5cbaabf9d267b5b5d
[ "MIT" ]
permissive
https://github.com/FiniteElementries/barebone_server
1e2d188a3aa7d80944e04f3831bc4c60e8a223af
3713b7d384aa9501741eeebdc49398d917deabb3
refs/heads/master
2021-01-10T17:19:02.669746
2016-01-14T19:20:08
2016-01-14T19:20:08
49,311,640
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, url from api_userprofile import * urlpatterns = patterns('', url(r'^info', get_userprofile_detail), url(r'^friends/list', get_friend_list), url(r'^friends/change', friend_action), url(r'^change_info',change_userprofile_info), )
UTF-8
Python
false
false
385
py
22
urls.py
19
0.514286
0.514286
0
10
37.4
68
Sradha-13/Django1stproject
541,165,881,136
115e1d548ca4e91f7ee8405fe7c1fcdcf9136ed3
f65be32166595aaab25e373e7d8172d4610a6ec2
/Todo/models.py
db5ab451980476e0044f10c68acdc20ee85f08ab
[]
no_license
https://github.com/Sradha-13/Django1stproject
9e0e1ac9712a2a69c5788edd786aef7bddee5909
97f57a35631809da7a446178670ac701490d1634
refs/heads/master
2023-08-31T22:58:33.434079
2021-10-19T09:43:15
2021-10-19T09:43:15
418,858,063
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models from django.db.models.base import Model # Create your models here. class Todo(models.Model): name=models.CharField(max_length=40) due_date=models.DateField() def __str__(self): return self.name
UTF-8
Python
false
false
248
py
5
models.py
3
0.697581
0.689516
0
10
23.9
40
JYPark09/MenuWizard
1,382,979,472,656
009d10065617691dc23cd465ba1278c0c9da75ca
ebde0385f3107064fd33feb3bf6c60889c4e2c62
/backend/dataloader.py
715fabff758936a22cce7462fddf5d1aa513e4ea
[ "MIT" ]
permissive
https://github.com/JYPark09/MenuWizard
cdefc31ed1ed8e568ce09e8f34a8a446291453f1
31dd76b3a0b29f8af0972214b4f62de308cae133
refs/heads/master
2020-06-01T15:33:32.404396
2019-06-10T07:04:05
2019-06-10T07:04:05
190,835,504
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import torch from torch.utils.data import TensorDataset import numpy as np def normalize(arr, temp_mean, temp_var, time_mean, time_var): arr[2] = (arr[2] - temp_mean) / temp_var arr[4] = (arr[4] - time_mean) / time_var def load_labels(): labels = [] with open('./data/label.csv', 'r') as f: for i, line in enumerate(f.readlines(), 0): labels.append(line.split(',')[1].strip()) return labels def load_data(filename): X, Y = [], [] with open(filename, 'r') as f: for line in f.readlines(): line = list(map(float, line.strip().split(','))) X.append(line[1:]) Y.append(line[0]) means = np.mean(X, axis=0) vars = np.var(X, axis=0) temp_mean = means[2] temp_var = vars[2] time_mean = means[4] time_var = vars[4] for i in range(len(X)): normalize(X[i], temp_mean, temp_var, time_mean, time_var) X = torch.tensor(X).float().view(-1, 38) Y = torch.tensor(Y).long() return TensorDataset(X, Y), temp_mean, temp_var, time_mean, time_var
UTF-8
Python
false
false
1,079
py
11
dataloader.py
7
0.568119
0.552363
0
44
23.522727
72
srush/cs287
9,225,589,769,490
571a0e89d9573ec9f2b1169eaf1ce2d2535e4b42
ee06e1914d4745ece99078cfdd3c12d64503ad8e
/hw2/lm.py
db451e17dbc4888fb2438b5b353f5bdc7fdc4a4f
[]
no_license
https://github.com/srush/cs287
2efefdf4642702a69e18864232f5fbe8db788974
a90f48d8e5877fc73bbc515944eefcc773af94ee
refs/heads/master
2021-04-29T18:16:31.480507
2018-02-15T22:15:26
2018-02-15T22:15:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Some language modeling code. python lm.py --model LstmLm --devid 1 --lr 0.01 --clip 2 --optim Adam --nlayers 2 --nhid 512 --dropout 0.5 --epochs 50 --bsz 128 --bptt 32 --tieweights Train: 42.90723478099889, Valid: 75.74921810452948, Test: 72.84913233987702 python lm.py --model NnLm --devid 3 --lr 0.001 --clip 0 --optim Adam --nlayers 2 --nhid 512 --dropout 0.5 --epochs 20 --bsz 64 --bptt 64 Train: 71.58999479091389, Valid: 158.07431086368382, Test: 146.13046578572258 Tested on torch.__version__ == 0.3.1b0+2b47480 """ import argparse import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable as V from torch.nn import Parameter from torch.nn.utils import clip_grad_norm import torchtext from tqdm import tqdm import random import math def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--devid", type=int, default=-1) parser.add_argument("--model", choices=["NnLm", "LstmLm"], default="LstmLm") parser.add_argument("--nhid", type=int, default=256) parser.add_argument("--nlayers", type=int, default=1) parser.add_argument("--tieweights", action="store_true") parser.add_argument("--maxnorm", type=float, default=None) parser.add_argument("--dropout", type=float, default=0) parser.add_argument("--epochs", type=int, default=10) parser.add_argument("--optim", choices=["SGD", "Adam"], default="Adam") parser.add_argument("--lr", type=float, default=0.01) parser.add_argument("--lrd", type=float, default=0.25) parser.add_argument("--wd", type=float, default=1e-4) parser.add_argument("--bsz", type=int, default=32) parser.add_argument("--bptt", type=int, default=32) parser.add_argument("--clip", type=float, default=5) # Adam parameters parser.add_argument("--b1", type=float, default=0.9) parser.add_argument("--b2", type=float, default=0.999) parser.add_argument("--eps", type=float, default=1e-8) # SGD parameters parser.add_argument("--mom", type=float, default=0.99) parser.add_argument("--dm", type=float, default=0) parser.add_argument("--nonag", action="store_true", default=False) return parser.parse_args() args = parse_args() random.seed(1111) torch.manual_seed(1111) if args.devid >= 0: torch.cuda.manual_seed_all(1111) torch.backends.cudnn.enabled = False print("Cudnn is enabled: {}".format(torch.backends.cudnn.enabled)) TEXT = torchtext.data.Field() train, valid, test = torchtext.datasets.LanguageModelingDataset.splits( path=".", train="train.txt", validation="valid.txt", test="valid.txt", text_field=TEXT) #path="data/", #train="train.txt", validation="valid.txt", test="test.txt", text_field=TEXT) TEXT.build_vocab(train) padidx = TEXT.vocab.stoi["<pad>"] train_iter, valid_iter, test_iter = torchtext.data.BPTTIterator.splits( (train, valid, test), batch_size=args.bsz, device=args.devid, bptt_len=args.bptt, repeat=False) class Lm(nn.Module): """ Boring superclass for all the language modeling code. """ def __init__(self): super(Lm, self).__init__() def train_epoch(self, iter, loss, optimizer): self.train() train_loss = 0 nwords = 0 hid = None for batch in tqdm(iter): optimizer.zero_grad() x = batch.text y = batch.target out, hid = model(x, hid if hid is not None else None) bloss = loss(out.view(-1, model.vsize), y.view(-1)) bloss.backward() train_loss += bloss # bytetensor.sum overflows, so cast to int nwords += y.ne(padidx).int().sum() if args.clip > 0: clip_grad_norm(self.parameters(), args.clip) optimizer.step() return train_loss.data[0], nwords.data[0] def validate(self, iter, loss): self.eval() valid_loss = 0 nwords = 0 hid = None for batch in iter: x = batch.text y = batch.target out, hid = model(x, hid if hid is not None else None) valid_loss += loss(out.view(-1, model.vsize), y.view(-1)) nwords += y.ne(padidx).int().sum() return valid_loss.data[0], nwords.data[0] def generate_predictions(self): self.eval() data = torchtext.datasets.LanguageModelingDataset( path="input.txt", text_field=TEXT) data_iter = torchtext.data.BPTTIterator(data, 211, 12, device=args.devid, train=False) outputs = [[] for _ in range(211)] print() print("Generating Kaggle predictions") for batch in tqdm(data_iter): # T x N x V scores, idxs = self(batch.text, None)[0][-3].topk(20, dim=-1) for i in range(idxs.size(0)): outputs[i].append([TEXT.vocab.itos[x] for x in idxs[i].data.tolist()]) with open(self.__class__.__name__ + ".preds.txt", "w") as f: f.write("id,word\n") ok = 1 for sentences in outputs: f.write("\n".join(["{},{}".format(ok+i, " ".join(x)) for i, x in enumerate(sentences)])) f.write("\n") ok += len(sentences) class NnLm(Lm): """ Feedforward neural network LM, pretends each bptt sequence is a sentence. """ def __init__(self, vocab, nhid, kW=3, nlayers=1, dropout=0, tieweights=True): super(NnLm, self).__init__() self.vsize = len(vocab.itos) self.kW = kW self.nhid = nhid self.lut = nn.Embedding(self.vsize, nhid, max_norm=args.maxnorm) self.conv = nn.Conv1d(nhid, nhid, kW, stride=1) self.drop = nn.Dropout(dropout) m = [] for i in range(nlayers-1): m.append(nn.Linear(nhid, nhid)) m.append(nn.Tanh()) m.append(nn.Dropout(dropout)) self.mlp = nn.Sequential(*m) self.proj = nn.Linear(nhid, self.vsize) if tieweights: # Weight tying is horrible for this model. self.proj.weight = self.lut.weight def forward(self, input, hid): emb = self.lut(input) # T = time, N = batch, H = hidden T, N, H = emb.size() # We pad manually, since conv1d only does symmetric padding. # This is kind of incorrect, ideally you'd have an embedding # for a separate padding token that you append to the start of a sen. pad = V(emb.data.new(self.kW-1, N, H)) pad.data.fill_(0) pad.requires_grad = False emb = torch.cat([pad, emb], 0) # Conv wants N(1) x H(2) x T(0), but our input is T(0) x N(1) x H(2) # Then we have to convert back to T(2) x N(0) x H(1) from N(0) x H(1) x T(2) # Sorry, that was kind of backwards, think about it from input order of dimensions # to what we want (right to left in the above description). hid = self.conv(emb.permute(1,2,0)).permute(2,0,1) return self.proj(self.mlp(hid)), hid class LstmLm(Lm): def __init__(self, vocab, nhid, nlayers=1, dropout=0, tieweights=True): super(LstmLm, self).__init__() self.vsize = len(vocab.itos) self.lut = nn.Embedding(self.vsize, nhid, max_norm=args.maxnorm) self.rnn = nn.LSTM( input_size=nhid, hidden_size=nhid, num_layers=nlayers, dropout=dropout) self.drop = nn.Dropout(dropout) self.proj = nn.Linear(nhid, self.vsize) if tieweights: # See https://arxiv.org/abs/1608.05859 # Seems to improve ppl by 13%. self.proj.weight = self.lut.weight def forward(self, input, hid): emb = self.lut(input) hids, hid = self.rnn(emb, hid) # Detach hiddens to truncate the computational graph for BPTT. # Recall that hid = (h,c). return self.proj(self.drop(hids)), tuple(map(lambda x: x.detach(), hid)) if __name__ == "__main__": models = {model.__name__: model for model in [NnLm, LstmLm]} model = models[args.model]( TEXT.vocab, args.nhid, nlayers=args.nlayers, dropout=args.dropout, tieweights=args.tieweights) print(model) if args.devid >= 0: model.cuda(args.devid) # We do not want to give the model credit for predicting padding symbols, # this can decrease ppl a few points. weight = torch.FloatTensor(model.vsize).fill_(1) weight[padidx] = 0 if args.devid >= 0: weight = weight.cuda(args.devid) loss = nn.CrossEntropyLoss(weight=V(weight), size_average=False) params = [p for p in model.parameters() if p.requires_grad] if args.optim == "Adam": optimizer = optim.Adam( params, lr = args.lr, weight_decay = args.wd, betas=(args.b1, args.b2)) elif args.optim == "SGD": optimizer = optim.SGD( params, lr = args.lr, weight_decay = args.wd, nesterov = not args.nonag, momentum = args.mom, dampening = args.dm) schedule = optim.lr_scheduler.ReduceLROnPlateau( optimizer, patience=1, factor=args.lrd, threshold=1e-3) for epoch in range(args.epochs): print("Epoch {}, lr {}".format(epoch, optimizer.param_groups[0]['lr'])) train_loss, train_words = model.train_epoch( iter=train_iter, loss=loss, optimizer=optimizer) valid_loss, valid_words = model.validate(valid_iter, loss) schedule.step(valid_loss) print("Train: {}, Valid: {}".format( math.exp(train_loss / train_words), math.exp(valid_loss / valid_words))) test_loss, test_words = model.validate(test_iter, loss) print("Test: {}".format(math.exp(test_loss / test_words))) model.generate_predictions() torch.save(model.cpu(), model.__class__.__name__ + ".pth")
UTF-8
Python
false
false
9,846
py
17
lm.py
6
0.606338
0.578814
0
263
36.437262
152
dengjinyi4/Test_Plantfrom
1,159,641,170,464
5352f1d762b48425a404354aaf3d3fc9ecff3927
80f53e7ea872dc18e45bd810ebb2073dac773f71
/business_modle/testtools/utils/db_info.py
c4869aa8ebe7fd409d6e3564e2b41234da785777
[]
no_license
https://github.com/dengjinyi4/Test_Plantfrom
30ca560b157b6f7026e6f05bc3ace10c63894d11
eb49d08ceb5cba44ce48178ed79c2e79a596de69
refs/heads/master
2021-06-13T07:34:55.840837
2021-03-09T06:41:54
2021-03-09T06:41:54
144,958,663
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # @Time : 2018/2/25 15:38 # @Author : wanglanqing import MySQLdb # -*- coding: utf-8 -*- # @Time : 2017/12/13 9:53 # @Author : wanglanqing import MySQLdb class DbOperations(object): def __init__(self, env_value=True): if env_value == True: #测试环境 print "测试环境" self.db = MySQLdb.connect(host="172.16.105.12", port=5701, db="voyager", user="voyager", passwd="voyager", charset = 'utf8') elif env_value== False: #生产环境voyager print "生产环境voyager" self.db = MySQLdb.connect(host="221.122.127.168", port=3306, db="voyager", user="dengjinyi", passwd="dengjinyi123456", charset='utf8') else: #生产环境voyagerstat print "生产环境voyagerstat" self.db = MySQLdb.connect(host='123.59.17.122', port=3306, db="voyagerstat", user="voyager", passwd="SIkxiJI5r48JIvPh", charset='utf8') self.cursor = self.db.cursor() def execute_sql(self, sql): print '执行的sql是: '+ sql try: self.cursor.execute(sql) self.db.commit() results = self.cursor.fetchall() # print results return results except Exception as e: print e # def executestat_sql(self,sql): # print "执行的sql是:"+sql # try: # self.cursor_stat.execute(sql) # self.db_stat.commit() # results = self.cursor_stat.fetchall() # return results # except Exception as e: # print e def len_value(self, sql): # print '执行的sql是: '+ sql results = self.execute_sql(sql) if results == None: results = 0 return results else: return len(results) sum() def close_db(self): self.db.close() def close_cursor(self): self.cursor.close() def mycommit(self): self.db.commit() def myrollback(self): self.db.rollback() if __name__=='__main__': db = DbOperations(env_value=False) sql= "select id from voyager.template_type where name='类型1'" re= db.execute_sql(sql) print int(re[0][0])
UTF-8
Python
false
false
2,982
py
281
db_info.py
159
0.415231
0.386285
0
97
27.917526
69
NVIDIA/TensorRT
4,844,723,155,080
b8db3334704a45a20a2c379d359a70206cfe5d6a
a02ccb5dff094fad8bcd691dda234d50ff768299
/tools/tensorflow-quantization/tests/network_pool.py
f64e67302deecfb7c9b5190807ebdfd31b9ec7d3
[ "Apache-2.0", "BSD-3-Clause", "MIT", "ISC", "BSD-2-Clause" ]
permissive
https://github.com/NVIDIA/TensorRT
5520d5a6a5926a2b30dbdd2c5b2e4dfe6d1b429b
a167852705d74bcc619d8fad0af4b9e4d84472fc
refs/heads/release/8.6
2023-07-29T05:39:45.688091
2023-06-09T22:29:09
2023-06-09T23:04:18
184,657,328
8,026
2,096
Apache-2.0
false
2023-09-13T17:30:16
2019-05-02T22:02:08
2023-09-13T12:47:05
2023-09-13T17:30:15
103,008
7,792
1,843
258
C++
false
false
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # 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. # """ This module contains tiny networks used for testing across different modules. They are named after famous Hobbits for obvious reasons. """ import tensorflow as tf ################################################## ###### Tiny, VGG like network #################### ################################################## def bilbo_28_28(): """ Network with VGG like architecture. """ input_img = tf.keras.layers.Input(shape=(28, 28), name="nn_input") x = tf.keras.layers.Reshape(target_shape=(28, 28, 1), name="reshape_0")(input_img) x = tf.keras.layers.Conv2D(filters=516, kernel_size=(3, 3), name="conv_0")(x) x = tf.keras.layers.ReLU(name="relu_0")(x) x = tf.keras.layers.Conv2D(filters=252, kernel_size=(3, 3), name="conv_1")(x) x = tf.keras.layers.ReLU(name="relu_1")(x) x = tf.keras.layers.Conv2D(filters=126, kernel_size=(3, 3), name="conv_2")(x) x = tf.keras.layers.ReLU(name="relu_2")(x) x = tf.keras.layers.Conv2D(filters=64, kernel_size=(3, 3), name="conv_3")(x) x = tf.keras.layers.ReLU(name="relu_3")(x) x = tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3), name="conv_4")(x) x = tf.keras.layers.ReLU(name="relu_4")(x) x = tf.keras.layers.Conv2D(filters=16, kernel_size=(3, 3), name="conv_5")(x) x = tf.keras.layers.ReLU(name="relu_5")(x) x = tf.keras.layers.Conv2D(filters=8, kernel_size=(3, 3), name="conv_6")(x) x = tf.keras.layers.ReLU(name="relu_6")(x) x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), name="max_pool_0")(x) x = tf.keras.layers.Flatten(name="flatten_0")(x) x = tf.keras.layers.Dense(100, name="dense_0")(x) x = tf.keras.layers.ReLU(name="relu_7")(x) x = tf.keras.layers.Dense(10, name="dense_1")(x) return tf.keras.Model(input_img, x, name="Bilbo") ##################################################### ###### Tiny, ResNet like network #################### ##################################################### def identity_block_plain(input_tensor): """ Identity block with no shortcut convolution """ y = tf.keras.layers.Conv2D(filters=12, kernel_size=(3, 3), padding="same")( input_tensor ) y = tf.keras.layers.ReLU()(y) y = tf.keras.layers.Conv2D(filters=24, kernel_size=(3, 3), padding="same")(y) out = tf.keras.layers.Add()([y, input_tensor]) out = tf.keras.layers.ReLU()(out) return out def identity_block_short_conv_plain(input_tensor): """ Identity block with shortcut convolution """ y = tf.keras.layers.Conv2D(filters=12, kernel_size=(3, 3), padding="same")( input_tensor ) y = tf.keras.layers.ReLU()(y) y = tf.keras.layers.Conv2D( filters=24, kernel_size=(3, 3), strides=(2, 2), padding="same" )(y) ds_input = tf.keras.layers.Conv2D( filters=24, kernel_size=(3, 3), strides=(2, 2), padding="same" )(input_tensor) out = tf.keras.layers.Add()([y, ds_input]) out = tf.keras.layers.ReLU()(out) return out def frodo_32_32(): """ Dummy network with resnet like architecture. """ input_img = tf.keras.layers.Input(shape=(32, 32, 3)) x = tf.keras.layers.Conv2D(filters=12, kernel_size=(3, 3))(input_img) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(filters=24, kernel_size=(3, 3))(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x) x = identity_block_plain(x) x = identity_block_short_conv_plain(x) x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x) x = tf.keras.layers.Flatten()(x) x = tf.keras.layers.Dense(100)(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Dense(10)(x) return tf.keras.Model(input_img, x, name="Frodo") def sam_32_32(): """ Dummy network with resnet like architecture. """ input_img = tf.keras.layers.Input(shape=(32, 32, 3)) x = tf.keras.layers.Conv2D(filters=12, kernel_size=(3, 3))(input_img) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Conv2D(filters=24, kernel_size=(3, 3))(x) x = tf.keras.layers.ReLU()(x) x = identity_block_plain(x) x = identity_block_plain(x) x = identity_block_short_conv_plain(x) x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x) x = tf.keras.layers.Flatten()(x) x = tf.keras.layers.Dense(100)(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Dense(10)(x) return tf.keras.Model(input_img, x, name="Sam") ############################################## ###### Popular network blocks ################ ############################################## def relu_bn(input): """ Block with BN+ReLU """ bn = tf.keras.layers.BatchNormalization()(input) relu = tf.keras.layers.ReLU()(bn) return relu def bn(input): return tf.keras.layers.BatchNormalization()(input) def relu(input): return tf.keras.layers.ReLU()(input) def inception_block(input_tensor): """ Inception block from GoogleNet """ b1x1 = tf.keras.layers.Conv2D(filters=12, kernel_size=(1, 1), padding="same")( input_tensor ) b1x1 = relu_bn(b1x1) b5x5 = tf.keras.layers.Conv2D(filters=12, kernel_size=(1, 1), padding="same")( input_tensor ) b5x5 = tf.keras.layers.Conv2D(filters=24, kernel_size=(5, 5), padding="same")(b5x5) b5x5 = relu_bn(b5x5) b3x3 = tf.keras.layers.Conv2D(filters=12, kernel_size=(1, 1), padding="same")( input_tensor ) b3x3 = tf.keras.layers.Conv2D(filters=20, kernel_size=(3, 3), padding="same")(b3x3) b3x3 = tf.keras.layers.Conv2D(filters=24, kernel_size=(3, 3), padding="same")(b3x3) b3x3 = relu_bn(b3x3) out = tf.keras.layers.Concatenate()([b1x1, b5x5]) return out def identity_block_bn(input_tensor): """ Identity block with no shortcut convolution """ y = tf.keras.layers.Conv2D(filters=12, kernel_size=(3, 3), padding="same")( input_tensor ) y = relu_bn(y) y = tf.keras.layers.Conv2D(filters=24, kernel_size=(3, 3), padding="same")(y) y = bn(y) out = tf.keras.layers.Add()([y, input_tensor]) out = relu(out) return out def identity_block_short_conv_bn(input_tensor): """ Identity block with shortcut convolution """ y = tf.keras.layers.Conv2D(filters=12, kernel_size=(3, 3), padding="same")( input_tensor ) y = relu_bn(y) y = tf.keras.layers.Conv2D( filters=24, kernel_size=(3, 3), strides=(2, 2), padding="same" )(y) y = bn(y) ds_input = tf.keras.layers.Conv2D( filters=24, kernel_size=(3, 3), strides=(2, 2), padding="same" )(input_tensor) ds_input = bn(ds_input) out = tf.keras.layers.Add()([y, ds_input]) out = relu(out) return out def otho_28_28(): input_img = tf.keras.layers.Input(shape=(28, 28), name="input_0") r = tf.keras.layers.Reshape(target_shape=(28, 28, 1), name="reshape_0")(input_img) x = tf.keras.layers.Conv2D(filters=2, kernel_size=(3, 3), name="conv_0")(r) x = tf.keras.layers.ReLU(name="relu_0")(x) x = tf.keras.layers.Conv2D(filters=2, kernel_size=(3, 3), name="conv_1")(x) x = tf.keras.layers.ReLU(name="relu_1")(x) x = tf.keras.layers.Flatten(name="flatten_0")(x) return tf.keras.Model(input_img, x, name="Otho") def lotho_28_28(): input_img = tf.keras.layers.Input(shape=(28, 28), name="input_0") r = tf.keras.layers.Reshape(target_shape=(28, 28, 1), name="reshape_0")(input_img) x = tf.keras.layers.DepthwiseConv2D(kernel_size=(3, 3), name="dconv_0")(r) x = tf.keras.layers.ReLU(name="relu_0")(x) x = tf.keras.layers.DepthwiseConv2D(kernel_size=(3, 3), name="dconv_1")(x) x = tf.keras.layers.ReLU(name="relu_1")(x) x = tf.keras.layers.Flatten(name="flatten_0")(x) return tf.keras.Model(input_img, x, name="Lotho") def lobelia_28_28(): input_img = tf.keras.layers.Input(shape=(28, 28), name="input_0") r = tf.keras.layers.Reshape(target_shape=(28, 28, 1), name="reshape_0")(input_img) x = tf.keras.layers.Flatten(name="flatten_0")(r) x = tf.keras.layers.Dense(100, name="dense_0")(x) x = tf.keras.layers.ReLU(name="relu_0")(x) x = tf.keras.layers.Dense(10, name="dense_1")(x) return tf.keras.Model(input_img, x, name="Lobelia") def merry_28_28(): input_img = tf.keras.layers.Input(shape=(28, 28)) x = tf.keras.layers.Reshape(target_shape=(28, 28, 1))(input_img) x = tf.keras.layers.Conv2D(filters=8, kernel_size=(3, 3))(x) x = relu_bn(x) x = tf.keras.layers.Conv2D(filters=12, kernel_size=(3, 3))(x) x = relu_bn(x) x = inception_block(x) x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x) x = tf.keras.layers.Flatten()(x) x = tf.keras.layers.Dense(100)(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Dense(10)(x) return tf.keras.Model(input_img, x, name="Merry") def pippin_28_28(): input_img = tf.keras.layers.Input(shape=(28, 28)) x = tf.keras.layers.Reshape(target_shape=(28, 28, 1))(input_img) x = tf.keras.layers.Conv2D(filters=12, kernel_size=(3, 3))(x) x = relu_bn(x) x = tf.keras.layers.Conv2D(filters=24, kernel_size=(3, 3))(x) x = relu_bn(x) x = identity_block_bn(x) x = identity_block_short_conv_bn(x) x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x) x = tf.keras.layers.Flatten()(x) x = tf.keras.layers.Dense(100)(x) x = tf.keras.layers.ReLU()(x) x = tf.keras.layers.Dense(10)(x) return tf.keras.Model(input_img, x, name="Pippin")
UTF-8
Python
false
false
10,169
py
1,278
network_pool.py
796
0.608319
0.568001
0
277
35.711191
103
ordinary-developer/education
2,834,678,441,888
8e9dc66ca3ff24518d65ebd38bb0324f24de1d34
7c63a96fad4257f4959ffeba0868059fc96566fb
/py/m_lutz-programming_python-4_ed/code/ch_07/21-customizing_widgets_with_classes/main.pyw
20f88df1541beac22c37a64ff6dca0f22a7f7837
[ "MIT" ]
permissive
https://github.com/ordinary-developer/education
b426148f5690f48e0ed4853adfc3740bd038b72c
526e5cf86f90eab68063bb7c75744226f2c54b8d
refs/heads/master
2023-08-31T14:42:37.237690
2023-08-30T18:15:18
2023-08-30T18:15:18
91,232,306
8
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from tkinter import * class HelloButton(Button): def __init__(self, parent = None, **config): Button.__init__(self, parent, **config) self.pack() self.config(command = self.callback) def callback(self): print('Goodbye world ...') self.quit() if __name__ == '__main__': HelloButton(text = 'Hello subclass world').mainloop()
UTF-8
Python
false
false
381
pyw
2,736
main.pyw
2,082
0.577428
0.577428
0
17
21.411765
57
terrence688538/Web-crawler-and-automation
2,697,239,481,185
4c8e9c99df8dab98b2d6c74c37c5a003393771c3
28c97a8d7e3de11495b517758cd6086ee5424383
/config.py
fd842e792fd1dfe3ca4da5a893d94e0c3d7f43e6
[]
no_license
https://github.com/terrence688538/Web-crawler-and-automation
96c7f0c5b1f94d1b3f8eed5a9ec38fae8ecee481
1ccc42e76fbb6acc76ac3142d5c38c532a81c7f2
refs/heads/master
2022-12-14T08:06:41.023061
2020-09-07T12:36:52
2020-09-07T12:36:52
293,475,134
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
MONGO_URL ='localhost' MONGO_DB='taobao' MONGO_TABLE='product'
UTF-8
Python
false
false
68
py
25
config.py
24
0.691176
0.691176
0
3
20
22
Jai-Chowdhry/IceChrono
420,906,813,079
b79b559c503953840be78ef2011e00ed418f82bc
a78a81a539a22668ab6560ab6af3093b035170d4
/AICC2012-VLR/EDC/parameters.py
8da2eac4ff9a222f010b32c98bd35e1d6d79dbee
[ "Apache-2.0" ]
permissive
https://github.com/Jai-Chowdhry/IceChrono
209359a7af2ed269b928e9baad01b56d4cb2cb15
d4ecc2c13e979a094179c811db907f4fb6aa600d
refs/heads/master
2021-01-20T07:31:40.427722
2019-07-31T14:45:56
2019-07-31T14:45:56
90,009,353
0
0
null
true
2017-05-02T08:37:03
2017-05-02T08:27:09
2017-05-02T08:27:11
2017-05-02T08:31:23
25,989
0
0
1
Python
null
null
#Parameters specific to the EDC ice core self.udepth_top=0. #unthinned depth at the top of the core self.age_top=-55. #age at the top of the core self.depth=np.arange(0., 3259.3+0.01, 0.55) #Define the depth grid for the age calculation self.corr_a_age=np.arange(self.age_top, 1000000+self.age_top+0.01, self.age_step) #Age grid for the accu correction function self.corr_LID_age=np.arange(self.age_top, 1000000+self.age_top+0.01, self.age_step) #Age grid for the LID correction function self.corr_tau_depth=np.arange(self.depth[0], self.depth[-1]+0.01, (self.depth[-1]-self.depth[0])/(self.corr_tau_nodes-1)) #Depth grid for the thinning correction function self.accu_prior_rep='staircase' #linear or staircase. Define whether the prior accu representation is linear or staircase in-between the data points. #The following parameters defines the covariance matrices as in AICC2012 (Bazin et al., 2013 and Veres et al., 2013). #self.thickness=3273. #Real thickness #self.cT2=0.000030/0.55 #self.sigmabA=0.7 #self.cA1=0. #self.sigmabL=0.7
UTF-8
Python
false
false
1,122
py
39
parameters.py
7
0.703209
0.635472
0
16
69.125
172
ilyaskutin/qaTasks1
15,607,911,189,722
05495e177878f9044412719d6393ed9a57dc2e3a
e1002716a6316d40c3542f0cc615660e6e4c0fd5
/yandex_autotests/conftest.py
6f3f46f27886cc926933ad22a27e0abb77367a43
[]
no_license
https://github.com/ilyaskutin/qaTasks1
929e4c842c068d34eaf613e7569e427d01f4f3dc
775662d8195da00cef6224cefcd299402d08917a
refs/heads/master
2020-03-19T01:48:14.325997
2018-06-04T08:56:32
2018-06-04T08:56:32
135,311,448
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pytest import os RESOURCE_DIR = os.path.join(os.getcwd(), "yandex_autotests/.resources") def pytest_namespace(): return { #Константы 'start_timeout': 10, # таймаут для браузера, сколько ждать на старте 'between_page_timeout': 5, # таймаут при переходе между страницами 'url': 'http://www.yandex.ru', # url сайта которые проверям 'username': 'arrival18', # логин тестового пользователя 'password': 'QWEqwe123', # пароль тестового пользователя 'search_accuracy': 10, # точность, с которой будет производится поиск 'check_url': 'https://www.yandex.ru/', # url сайта, который ожидаем после загрузки 'check_title': 'Яндекс', # заголовок сайта, который ожидаем после 'debug_mode': False, # debug 'repeat_search': True, # Если не найдет в арене, повторит по всему экрану 'path_to_res': RESOURCE_DIR, # Ресурсы 'logo': os.path.join(RESOURCE_DIR, 'logo.png'), 'mail': os.path.join(RESOURCE_DIR, 'mail.png'), 'logo_auth': os.path.join(RESOURCE_DIR, 'logo_auth.png'), 'login_button': os.path.join(RESOURCE_DIR, 'login.png'), 'user_login': os.path.join(RESOURCE_DIR, 'user_login.png'), # Арены "main_logo_area": ( [0, 0, 0], [1, 0, 0], [0, 0, 0] ), "mail_area": ( [0, 0, 1], [0, 0, 0], [0, 0, 0] ), "auth_area": ( [0, 1, 0], [0, 1, 0], [0, 0, 0] ), "user_login_area": ( [0, 0, 1], [0, 0, 0], [0, 0, 0] ) }
UTF-8
Python
false
false
2,152
py
10
conftest.py
6
0.472539
0.447526
0
54
33.074074
100
631068264/learn-sktf
13,743,895,351,472
7220ecd73842de9a7d482d8829b49c4a42e44d0f
411d9c64d2f2142f225582f2b4af1280310426f6
/sk/dr.py
74a6533af11f3936fe4c56d12faf7604d1b44699
[]
no_license
https://github.com/631068264/learn-sktf
5a0dfafb898acda83a80dc303b6d6d56e30e7cab
4ba36c89003fca6797025319e81fd9863fbd05b1
refs/heads/master
2022-10-15T03:29:38.709720
2022-09-24T12:56:41
2022-09-24T12:56:41
133,602,172
0
0
null
false
2022-09-24T12:57:23
2018-05-16T02:57:01
2022-09-24T12:56:46
2022-09-24T12:57:22
47,933
0
0
19
Python
false
false
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author = 'wyx' @time = 2018/5/16 15:21 @annotation = '' """ import numpy as np from sklearn.datasets import make_swiss_roll np.random.seed(4) m = 60 w1, w2 = 0.1, 0.3 noise = 0.1 angles = np.random.rand(m) * 3 * np.pi / 2 - 0.5 X = np.empty((m, 3)) X[:, 0] = np.cos(angles) + np.sin(angles) / 2 + noise * np.random.randn(m) / 2 X[:, 1] = np.sin(angles) * 0.7 + noise * np.random.randn(m) / 2 X[:, 2] = X[:, 0] * w1 + X[:, 1] * w2 + noise * np.random.randn(m) from sklearn.decomposition import PCA if False: pca = PCA(n_components=2) X2D = pca.fit_transform(X) # 特征空间中的主轴 print(pca.components_) # 轴的差异比率 print(pca.explained_variance_ratio_) print(1 - pca.explained_variance_.sum()) # 解压缩 有损 pca.inverse_transform(X2D) """ find good Dimensions """ if False: pca = PCA() pca.fit(X) cumsum = np.cumsum(pca.explained_variance_ratio_) d = np.argmax(cumsum >= 0.95) + 1 print(d) pca = PCA(n_components=0.95) X_reduced = pca.fit_transform(X) print(pca.n_components_) """ 增量pca 节省内存 慢 """ if False: from sklearn.decomposition import IncrementalPCA n_batches = 5 inc_pca = IncrementalPCA(n_components=2) for X_batch in np.array_split(X, n_batches): inc_pca.partial_fit(X_batch) X_reduced = inc_pca.transform(X) filename = 'x.data' X_mm = np.memmap(filename, dtype='float32', mode='write', shape=X.shape) X_mm[:] = X del X_mm X_mm = np.memmap(filename, dtype="float32", mode="readonly", shape=X.shape) batch_size = m // n_batches inc_pca = IncrementalPCA(n_components=2, batch_size=batch_size) inc_pca.fit(X_mm) X_reduced2 = inc_pca.transform(X) if False: X, t = make_swiss_roll(n_samples=1000, noise=0.2, random_state=42) y = t > 6.9 from sklearn.decomposition import KernelPCA rbf_pca = KernelPCA(n_components=2, kernel="rbf", gamma=0.04) X_reduced = rbf_pca.fit_transform(X) from sklearn.model_selection import GridSearchCV from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline clf = Pipeline([ ("kpca", KernelPCA(n_components=2)), ("log_reg", LogisticRegression()) ]) param_grid = [{ "kpca__gamma": np.linspace(0.03, 0.05, 10), "kpca__kernel": ["rbf", "sigmoid"] }] grid_search = GridSearchCV(clf, param_grid, cv=3) grid_search.fit(X, y) print(grid_search.best_estimator_) print(grid_search.best_params_) if False: from sklearn.manifold import LocallyLinearEmbedding from matplotlib import pyplot as plt X, t = make_swiss_roll(n_samples=1000, noise=0.2, random_state=41) lle = LocallyLinearEmbedding(n_components=2, n_neighbors=10, random_state=42) X_reduced = lle.fit_transform(X) plt.title("Unrolled swiss roll using LLE", fontsize=14) plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=t, cmap=plt.cm.hot) plt.xlabel("$z_1$", fontsize=18) plt.ylabel("$z_2$", fontsize=18) plt.axis([-0.065, 0.055, -0.1, 0.12]) plt.grid(True) plt.show()
UTF-8
Python
false
false
3,160
py
39
dr.py
35
0.629344
0.591055
0
110
27.254545
81
markman123/CourseCake
13,022,340,849,896
c9f292fb003ebc6562b6c4033ce53fda7847601a
96ddf1d2e299ee4da92ed21c915853856064b75a
/coursecake/fastapi_app/api_v1/admin/routes.py
d7db9d2b0bf88063acecc67a0d0629963ac939a6
[ "MIT" ]
permissive
https://github.com/markman123/CourseCake
586927c8ea4e894b6dff2e7a34dddb631165717a
4ef40cb2bd5f42177c8596fd18ead66b4a9d2379
refs/heads/master
2022-12-24T21:44:39.508228
2020-10-06T22:13:15
2020-10-06T22:13:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# contains all routes for the courses endpoint from typing import List, Optional from fastapi import ( Depends, APIRouter, BackgroundTasks, status, HTTPException, Query, Request, ) from sqlalchemy.orm import Session from ....database import crud, models, sql, uploads from ...limiter import limiter from .. import schemas from . import utils router = APIRouter() # dependency def get_db(): db = sql.SessionLocal() try: yield db finally: db.close() @router.post("/update/all") @limiter.limit("2/minute") async def update_all( request: Request, token: str, background_tasks: BackgroundTasks, db: Session = Depends(get_db), term_id: str = Query("2020-fall"), testing: bool = Query(False), ): if not utils.verifyAdminToken(token): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect token" ) background_tasks.add_task(uploads.update_all, db, term_id, testing) return { "message": "initiated updates for all database information via scrapers. this will take a few minutes." }
UTF-8
Python
false
false
1,141
py
53
routes.py
41
0.665206
0.658195
0
51
21.372549
111
open222333/PythonCode
6,047,313,983,368
241ee35358a1188e5256bf76bae7de9b6f4ffcc5
3ff6b318db4d0fdda60c763f475b7dafa4f0c9ba
/Kingreturn_Ex/ch7/ch7-41.py
1fba259b3358f7e90ec6e62141fc208913a94eab
[]
no_license
https://github.com/open222333/PythonCode
493124dcbbb4d4ab18be3090bc35224e20959780
b9baffd2598b2b1e131fdd6bb38536c685b633e5
refs/heads/master
2023-08-28T14:51:52.004948
2023-06-20T15:45:05
2023-06-20T15:45:05
356,302,028
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# pass 與無限迴圈 schools = ['明志科大', '台灣科大', '台北科大'] for school in schools: pass
UTF-8
Python
false
false
114
py
1,002
ch7-41.py
926
0.625
0.625
0
4
19
34
cowhi/HFO
10,436,770,574,949
f6dcf09af016fa9ae9d5bc9af5ef3e776893eb99
d3d5539549f43fc7c228fd2a264ab137a808096c
/experiments/agents/sarsa.py
77ddb243020a40a0ad733fce8ae7d65309867703
[ "MIT" ]
permissive
https://github.com/cowhi/HFO
d8c24b77440beb0c8d878f068b2a78e127ab5102
119d0233424bad64d92ff835dd335775fe66dd77
refs/heads/master
2021-01-22T01:42:32.179275
2016-11-13T13:38:40
2016-11-13T13:38:40
65,380,530
0
1
null
true
2016-08-10T12:26:07
2016-08-10T12:26:07
2016-08-07T21:55:15
2016-07-25T21:24:34
2,692
0
0
0
null
null
null
import sys import random from .agent import Agent from cmac import CMAC class SARSA(Agent): def __str__(self): """ Overwrites the object.__str__ method. Returns: string (str): Important parameters of the object. """ return "Agent: " + str(self.unum) + ", " + \ "Type: " + str(self.name) + ", " + \ "Training steps: " + str(self.training_steps_total) + ", " + \ "Q-Table size: " + str(len(self.qTable)) def __init__(self, epsilon=0.1, alpha=0.1, gamma=0.9, decayRate=0.9, seed=12345, cmac_level=20, cmac_quantization=0.3, cmac_beta=0.1, port=12345,serverPath = "/home/leno/HFO/bin/"): super(SARSA, self).__init__(seed, port,serverPath=serverPath) self.name = "SARSA" self.qTable = {} self.stateActionTrace = {} self.epsilon = epsilon self.alpha = alpha self.gamma = gamma self.decayRate = decayRate self.cmac = CMAC(cmac_level,cmac_quantization,cmac_beta) #print('***** %s: Agent uses CMAC(%s,%s,%s)' % (str(self.unum),str(cmac_level), str(cmac_quantization), str(cmac_beta))) def quantize_features(self, features): """ CMAC utilities for all agent """ quantVar = self.cmac.quantize(features) data = [] #len(quantVar[0]) is the number of variables for i in range(0,len(quantVar[0])): #Transforms n tuples into a single array for var in quantVar: #copy each tuple value to the output data.append(var[i]) #returns the output as a tuple return tuple(data) def advise_action(self,uNum,state): """Verifies if the agent can advice a friend, and return the action if possible""" return None #No advising def get_Q(self, state, action): return self.qTable.get((state, action), 0.0) def observe_reward(self,state,action,reward,statePrime): """ After executing an action, the agent is informed about the state-reward-state tuple """ pass ''' def observe_reward(self,state,action,reward,statePrime): """ After executing an action, the agent is informed about the state-action-reward-state tuple """ if self.exploring: #Selects the action for the next state without exploration lastState = self.lastState self.exploring = False nextAction = self.select_action(statePrime) #Hereafter the self.lastState refers to statePrime #Executes Q-update self.learn(lastState,action,reward,self.lastState,nextAction) #turns on the exploration again ''' def select_action(self, stateFeatures, state, noAdvice=False): """Executes the epsilon-greedy exploration strategy""" #stores last CMAC result #self.lastState = state # select applicable actions if stateFeatures[5] == 1: # State[5] is 1 when the player can kick the ball actions = [self.SHOOT, self.DRIBBLE, self.PASSfar, self.PASSnear] else: return self.MOVE # epsilon greedy action selection if self.exploring and random.random() < self.epsilon and not noAdvice: actionsRandom = [ self.SHOOT,self.DRIBBLE, self.DRIBBLE, self.SHOOT, self.PASSfar, self.PASSnear] return random.choice(actionsRandom) else: cmacState = self.quantize_features(state) qValues = [self.get_Q(cmacState, action) for action in actions] maxQ = max(qValues) count = qValues.count(maxQ) if count > 1: #and self.exploring: best = [i for i in range(len(actions)) if qValues[i] == maxQ] if not self.exploring: return actions[best[0]] return actions[random.choice(best)] else: return actions[qValues.index(maxQ)] def learn(self, state1, action1, reward, state2, action2): qnext = self.get_Q(state2, action2) self.learn_Q(state1, action1, reward, reward + self.gamma * qnext) def learn_Q(self, state, action, reward, value): oldv = self.qTable.get((state, action), None) if oldv is None: self.qTable[(state, action)] = reward else: self.qTable[(state, action)] = oldv + self.alpha * (value - oldv) def step(self, state, action): """ Perform a complete training step """ # perform action and observe reward & statePrime self.execute_action(action) status = self.hfo.step() stateFeatures = self.hfo.getState() statePrime = self.get_transformed_features(stateFeatures) stateQuantized = self.quantize_features(state) statePrimeQuantized = self.quantize_features(statePrime) reward = self.get_reward(status) # select actionPrime if self.exploring: actionPrime = self.select_action(stateFeatures, statePrime,False) else: actionPrime = self.select_action(stateFeatures, statePrime,True) if self.exploring: # calculate TDError TDError = reward + self.gamma * self.get_Q(statePrimeQuantized, actionPrime) - self.get_Q(stateQuantized, action) # update trace value self.stateActionTrace[(stateQuantized, action)] = self.stateActionTrace.get((stateQuantized, action), 0) + 1 for stateAction in self.stateActionTrace: # update update ALL Q values and eligibility trace values self.qTable[stateAction] = self.qTable.get(stateAction, 0) + TDError * self.alpha * self.stateActionTrace.get(stateAction, 0) # update eligibility trace Function for state and action self.stateActionTrace[stateAction] = self.gamma * self.decayRate * self.stateActionTrace.get(stateAction, 0) #self.learn(stateQuantized, action, reward, # statePrimeQuantized, actionPrime) self.training_steps_total += 1 if status != self.IN_GAME: self.stateActionTrace = {} return status, statePrime, actionPrime def setupAdvising(self,agentIndex,allAgents): """ This method is called in preparation for advising """ pass
UTF-8
Python
false
false
6,374
py
58
sarsa.py
49
0.609978
0.602291
0
143
43.573427
141
Zengyi-Qin/LMSC
4,552,665,349,722
5ab4677a7aff913bf7b38d636be7662a9da4f9bb
211962cfdc43dd0d232cf1aff4f1b0733aea0663
/render/ol_dynamics.py
f87fb8085bfa4b76a389998f59517a847b52eeba
[]
no_license
https://github.com/Zengyi-Qin/LMSC
332abfd276ec29862312a9920cd1f3b97512b8cf
37ae3055556049f2f7e4d4a82b27799df3965f3f
refs/heads/main
2023-05-06T13:43:54.974794
2022-02-05T13:44:10
2022-02-05T13:44:10
368,742,015
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np # quadrotor physical constants g = 9.81 # non-linear dynamics def f(x, u): x, y, z, vx, vy, vz, theta_x, theta_y = x.reshape(-1).tolist() az, omega_x, omega_y = u.reshape(-1).tolist() dot_x = np.array([ vx, vy, vz, np.tan(theta_x), np.tan(theta_y), az, omega_x, omega_y]) return dot_x def f_batch_azlast(x, u): x, y, z, vx, vy, vz, theta_x, theta_y = [x[:,i] for i in range(x.shape[1])] omega_x, omega_y, az = [u[:,i] for i in range(u.shape[1])] dot_x = np.array([ vx, vy, vz, np.tan(theta_x), np.tan(theta_y), az, omega_x, omega_y]).T return dot_x # linearization # The state variables are x, y, z, vx, vy, vz, theta_x, theta_y A = np.zeros([8,8]) A[0, 3] = 1. A[1, 4] = 1. A[2, 5] = 1. A[3, 6] = 1. A[4, 7] = 1. B = np.zeros([8, 3]) B[5, 0] = 1. B[6, 1] = 1. B[7, 2] = 1.
UTF-8
Python
false
false
909
py
43
ol_dynamics.py
34
0.50385
0.465347
0
46
18.76087
79
Sanyam-malik/Python-Auribasis-v2
8,830,452,795,231
f4b6ec2b9fc7e060c353bd22b802487a223562cc
ffec74b0214621cb570fa1fdfa036bc6f1b3c78b
/Session6C.py
b4bc6dd3ec84bdf177de379c7b8d38f457e9987a
[]
no_license
https://github.com/Sanyam-malik/Python-Auribasis-v2
3d5d523521eebeab59ac2dd912b08b3b890dfcfd
268d632d0e7b4ac14e058b6a92b7c17933812f48
refs/heads/master
2022-04-10T03:56:47.192364
2020-02-26T20:45:02
2020-02-26T20:45:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Employee: def __init__(self, name, designation, salary, projects): self.name = name self.designation = designation self.salary = salary self.projects = projects # HAS-A Relation with 1 to Many def showEmployee(self): print("{} works as {} and withdraws {} INR".format(self.name,self.designation,self.salary)) #Iterate in the projects for p in self.projects: p.showProject() class Project: def __init__(self, title, technology, duration): self.title = title self.technology = technology self.duration = duration def showProject(self): print("{} is developed in {} technology in a timeline of {} months".format(self.title,self.technology,self.duration)) # Collection : List or Projects projectList = [] projectList.append(Project("Elzo","Firebase",2)) projectList.append(Project("YankTow","AWS",3)) emp = Employee("John Watson", "Software Engr", 30000, projectList) emp.showEmployee()
UTF-8
Python
false
false
1,013
py
66
Session6C.py
64
0.657453
0.649556
0
33
29.727273
125
maria-noaptes/retele
4,071,628,999,215
6491dfe5f7a398bb8dfe9b6cdba7078b03abefc0
3c44a78ad286302c484082c8cb181532da7be533
/packets.py
2b0597c00f0bed67f55aa996f1f4791dc134a475
[]
no_license
https://github.com/maria-noaptes/retele
84f1d5971a140e0424e1f236fe375eaf2531d2d0
2c14eafa57ada844a607beba5f510cfb8f7c2af5
refs/heads/master
2020-08-12T06:32:24.478162
2019-11-03T16:35:06
2019-11-03T16:35:06
214,707,114
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
class CONNECT: def __init__(self,id,username,parola): self.id=id self.username=username self.parola=parola class CONNACK: def __init__(self,flag_confirmare): self.flag_confirmare=flag_confirmare class SUBSCRIBE: def __init__(self,packetID,subscriptii): self.subscriptii=subscriptii self.packetID=packetID class PINGREQ: pass class SUBPACK: def __init__(self,packetID,returnCode): self.packetID=packetID self.returnCode=returnCode class PUBLISH: def __init__(self,topic,payload): self.topic=topic self.payload=payload
UTF-8
Python
false
false
620
py
4
packets.py
2
0.66129
0.66129
0
22
27.227273
44
himanshu272/Digital_Fortress_Backend
17,325,898,104,932
72853b58743ad210f662e911c0ba0de1bd8bdccc
6fed9b70ab0f13889036c4c5e8336c6ae91bbd0e
/Quiz/migrations/0005_player_first_name.py
b41ec599d99d72bf316e6bf3fcfb70648fbfb979
[]
no_license
https://github.com/himanshu272/Digital_Fortress_Backend
aaa9208e593d70f3b981936aefaba71a579a7714
c8ed942f9ddcfa67bafbc32b80357e8f39e310c1
refs/heads/master
2020-08-04T21:46:49.416356
2020-01-24T14:19:50
2020-01-24T14:19:50
212,288,900
0
4
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 2.2.4 on 2020-01-24 11:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Quiz', '0004_duration'), ] operations = [ migrations.AddField( model_name='player', name='first_name', field=models.CharField(blank=True, max_length=200), ), ]
UTF-8
Python
false
false
388
py
13
0005_player_first_name.py
11
0.582474
0.525773
0
18
20.555556
63
SirLeonardoFerreira/Atividades-ifpi
15,144,054,709,949
a9f2671bf21bad8d1bc1324a4b5cd027b99bfa93
fb00b570251ba52df467e4cc030a30e778f8a970
/Atividade 02 - semana 04/questão5_semana4_atividade02.py
7c26d99823df070af681aa1431f42e93357c3492
[]
no_license
https://github.com/SirLeonardoFerreira/Atividades-ifpi
7379f9df4640fd1ee3623d80e4341f495e855895
e366ee3f801dc9a1876c7399a2eefd37a03d0a55
refs/heads/master
2023-01-05T04:03:30.774277
2020-11-02T00:56:10
2020-11-02T00:56:10
287,967,575
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def ordem(um, dois, tres): if um < dois < tres: return um, dois, tres elif um < tres < dois: return um, dois, tres elif dois < um < tres: return dois, um, tres elif dois < tres < um: return dois, tres, um elif tres < um < dois: return tres, um, dois elif tres < dois < um: return tres, dois, um def main(): numero_um = int(input("Digite o primeiro número: ")) numero_dois = int(input("Digite o segundo número: ")) numero_tres = int(input("Digite o terceiro número: ")) um, dois, tres = ordem(numero_um, numero_dois, numero_tres) print(f'{um}') print(f'{dois}') print(f'{tres}') if __name__ == '__main__': main()
UTF-8
Python
false
false
722
py
130
questão5_semana4_atividade02.py
130
0.55911
0.55911
0
26
26.653846
63
skk2106/NLP_PRACTICE
12,953,621,405,085
b9e5fa986ac22109bdcde942b5096229865311f6
80f4445fa0d1eb07fe1cb976b858e2c78d0a666c
/TD-IDF.py
e4dd7aef156d6cea6303df20da5f2979a687654c
[]
no_license
https://github.com/skk2106/NLP_PRACTICE
8f17200cbb30c3ab830f1fcfec3aede3ce85ab79
69fe484465310308a86d5f218d6f3c6d09f843f5
refs/heads/master
2023-05-08T04:59:59.881918
2021-05-14T07:05:34
2021-05-14T07:05:34
366,959,234
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Created on Thu May 13 11:32:34 2021 @author: SOHAM KULKARNI """ # -*- coding: utf-8 -*- """ Created on Thu May 13 11:32:34 2021 @author: SOHAM KULKARNI """ import nltk from nltk.corpus import stopwords paragraph = """I have three visions for India. In 3000 years of our history people from all over the world have come and invaded us, captured our lands, conquered our minds. From Alexander onwards the Greeks, the Turks, the Moguls, the Portuguese, the British, the French, the Dutch, all of them came and looted us, took over what was ours. Yet we have not done this to any other nation. We have not conquered anyone. We have not grabbed their land, their culture and their history and tried to enforce our way of life on them. Why? Because we respect the freedom of others. That is why my FIRST VISION is that of FREEDOM. I believe that India got its first vision of this in 1857, when we started the war of Independence. It is this freedom that we must protect and nurture and build on. If we are not free, no one will respect us. We have 10 percent growth rate in most areas. Our poverty levels are falling. Our achievements are being globally recognised today. Yet we lack the self-confidence to see ourselves as a developed nation, self-reliant and self-assured. Isn’t this incorrect? MY SECOND VISION for India is DEVELOPMENT. For fifty years we have been a developing nation. It is time we see ourselves as a developed nation. We are among top five nations in the world in terms of GDP.""" #Cleaning the text import re from nltk.stem import PorterStemmer from nltk.stem import WordNetLemmatizer ps = PorterStemmer() wordnet = WordNetLemmatizer() sentences = nltk.sent_tokenize(paragraph) corpus = [] for i in range(len(sentences)): review = re.sub('[^a-zA-Z]', ' ',sentences[i]) review = review.lower() review = review.split() review = [wordnet.lemmatize(word) for word in review if not word in set(stopwords.words('english'))] review = ' '.join(review) corpus.append(review) #TFIDF from sklearn.feature_extraction.text import TfidfVectorizer cv = TfidfVectorizer() X = cv.fit_transform(corpus).toarray()
UTF-8
Python
false
false
2,299
py
6
TD-IDF.py
4
0.710057
0.694384
0
46
48.717391
198
Ahmedsebit/doKonect
3,143,916,099,381
03b60084cf86eb73bb3ec903948c7a6f1d62bf4f
bf5202eb2bae5c2f40660e1226d8269f1058d199
/project/doctor_referral/tests.py
0a0f7639f9a79ea1f1acac87ecb84880897a95f5
[]
no_license
https://github.com/Ahmedsebit/doKonect
e7562a3e13bb227243dfb477011a8d70aec24708
adfc3b5bc0d570bb5dda853fd3ec44c52a631b53
refs/heads/master
2021-01-22T02:57:58.736093
2017-10-16T08:09:46
2017-10-16T08:09:46
102,257,735
1
2
null
false
2017-10-16T08:09:47
2017-09-03T10:46:29
2017-09-03T11:01:30
2017-10-16T08:09:47
1,224
0
2
0
Python
null
null
from django.contrib.auth import get_user_model from django.test import TestCase # Create your tests here. from .models import Doctor_Referral User = get_user_model() class Doctor_ReferralTestCase(TestCase): def setUp(self): random_user = User.objects.create(username='testadmin') def test_refferal_creation(self): obj = Doctor_Referral.objects.create( user = User.objects.first(), patient_id = "patient_id", doctor_id = "doctor_id", booked_date = "booked_date", group = "group" ) self.assertTrue(obj.patient_id == "patient_id") self.assertTrue(obj.id == 1)
UTF-8
Python
false
false
673
py
67
tests.py
36
0.622585
0.6211
0
24
27.041667
63
weturner/hello-world
12,300,786,356,068
1b454497f8b28125a07fc54ad76f473f210cad55
a20c1ac4fac59d827313343e1e25d570b3e3f5a3
/oldschool/selection.py
3302e1087b6ed0fcda198d14fb0c739e40c67a9b
[]
no_license
https://github.com/weturner/hello-world
dd5e41be403921329eb9af4af8708c23ee789add
99e4a3a2cb5431ad45fb43ef3de89fa47e510bee
refs/heads/master
2017-09-07T22:12:38.625594
2016-05-06T01:23:39
2016-05-06T01:23:39
54,249,733
0
0
null
false
2016-03-19T05:54:58
2016-03-19T05:46:46
2016-03-19T05:46:46
2016-03-19T05:54:57
0
0
0
0
null
null
null
#wes turner #A2 #cs 301 def select(x): n = len(x) for i in range(n-1): min = i for j in range (i+1, n): if x[min] > x[j]: min = j temp = x[min] x[min] = x[i] x[i] = temp print "step ", i+1, x z = [ 692, 1, 32, 14, 15, 123, 2431] #print "SELECTION SORT\n" #print "unsorted: ", z select(z) print "sorted: ", z
UTF-8
Python
false
false
422
py
11
selection.py
11
0.417062
0.36019
0
22
17.181818
36
d1n0sva1d0/PISBD
11,587,821,771,004
af3f3dfca52bcd45505ad907b5f67577f0494ea9
a1f3d6820711b7493b6e60fcacda797ec46ceab0
/modulo/interfaz/showProducto.py
fd2ac68761a7b469e939e8f180221cb2492d7f6f
[]
no_license
https://github.com/d1n0sva1d0/PISBD
da77ebfca8cad28ae9b32ac4937dd6434cbb4df4
b7ca7cb40dd1de17d63e87a8f834c79707643a62
refs/heads/master
2016-09-13T05:54:04.822525
2016-05-19T17:56:36
2016-05-19T17:56:36
59,073,259
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'showProducto.ui' # # Created: Wed May 4 15:43:06 2016 # by: PyQt4 UI code generator 4.11.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_showProducto(object): def setupUi(self, showProducto): showProducto.setObjectName(_fromUtf8("showProducto")) showProducto.setWindowModality(QtCore.Qt.ApplicationModal) showProducto.resize(800, 600) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8("Images/producto.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) showProducto.setWindowIcon(icon) self.tableViewProductos = QtGui.QTableView(showProducto) self.tableViewProductos.setGeometry(QtCore.QRect(10, 60, 781, 531)) self.tableViewProductos.setObjectName(_fromUtf8("tableViewProductos")) self.lineBuscar = QtGui.QLineEdit(showProducto) self.lineBuscar.setGeometry(QtCore.QRect(30, 20, 361, 22)) self.lineBuscar.setObjectName(_fromUtf8("lineBuscar")) self.comboBoxOrdenar = QtGui.QComboBox(showProducto) self.comboBoxOrdenar.setGeometry(QtCore.QRect(550, 20, 78, 23)) self.comboBoxOrdenar.setObjectName(_fromUtf8("comboBoxOrdenar")) self.comboBoxOrdenar.addItem(_fromUtf8("")) self.comboBoxOrdenar.addItem(_fromUtf8("")) self.comboBoxOrdenar.addItem(_fromUtf8("")) self.comboBoxOrdenar.addItem(_fromUtf8("")) self.comboBoxOrdenar.addItem(_fromUtf8("")) self.pushButtonFiltrar = QtGui.QPushButton(showProducto) self.pushButtonFiltrar.setGeometry(QtCore.QRect(650, 20, 99, 23)) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(_fromUtf8("Images/filtrar.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButtonFiltrar.setIcon(icon1) self.pushButtonFiltrar.setAutoDefault(True) self.pushButtonFiltrar.setObjectName(_fromUtf8("pushButtonFiltrar")) self.labelOrdenar = QtGui.QLabel(showProducto) self.labelOrdenar.setGeometry(QtCore.QRect(440, 20, 101, 21)) self.labelOrdenar.setObjectName(_fromUtf8("labelOrdenar")) self.retranslateUi(showProducto) QtCore.QMetaObject.connectSlotsByName(showProducto) showProducto.setTabOrder(self.lineBuscar, self.comboBoxOrdenar) showProducto.setTabOrder(self.comboBoxOrdenar, self.pushButtonFiltrar) showProducto.setTabOrder(self.pushButtonFiltrar, self.tableViewProductos) def retranslateUi(self, showProducto): showProducto.setWindowTitle(_translate("showProducto", "Mostrar Productos", None)) self.comboBoxOrdenar.setItemText(0, _translate("showProducto", "Defecto", None)) self.comboBoxOrdenar.setItemText(1, _translate("showProducto", "Nombre", None)) self.comboBoxOrdenar.setItemText(2, _translate("showProducto", "Marca", None)) self.comboBoxOrdenar.setItemText(3, _translate("showProducto", "Existencia", None)) self.comboBoxOrdenar.setItemText(4, _translate("showProducto", "Precio", None)) self.pushButtonFiltrar.setText(_translate("showProducto", "Filtrar", None)) self.labelOrdenar.setText(_translate("showProducto", "Ordenar por:", None))
UTF-8
Python
false
false
3,704
py
49
showProducto.py
39
0.715443
0.689525
0
73
49.726027
108
Rafael-Jose/django_anuncios
14,044,543,096,428
eb973e679e372e1f02b89dd51c60ac916881e9fd
3727560eddb053a983c32ece7392fb33b25f4663
/usuarios/urls.py
b7d568c3a4e7452195bf8471424791024edc51d9
[]
no_license
https://github.com/Rafael-Jose/django_anuncios
fb36a403c760a670373a5047dafeadb3dc298591
0df051df74538097a44bffc10c82d555df3307fe
refs/heads/master
2023-07-19T16:01:53.600144
2021-09-28T16:58:36
2021-09-28T16:58:36
352,221,375
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.urls import path from usuarios import views urlpatterns = [ path('login/', views.Login.as_view(), name="login"), path('logout', views.Logout.as_view(), name="logout"), path('registrar', views.UsuarioCreate.as_view(), name="registrar"), path('atualizar-dados/', views.PerfilUpdate.as_view(), name="atualizar-dados"), ]
UTF-8
Python
false
false
349
py
20
urls.py
11
0.681948
0.681948
0
11
30.727273
83
natesilverman/cambia
4,715,874,122,888
dcfc62e9debfc6f5ccb257306b741cf00d7dfece
3f5545f48dda891d92963f856acfc99923044420
/ecs/execute_ecs_task.py
1151667d1ee72a020c8b6968d7d77844cc0cdaca
[]
no_license
https://github.com/natesilverman/cambia
36f4e0f9b8dbd227d8944c40771d777eec1e99ed
21f2877a4a59a1a46a24d1dca5a576057517fba1
refs/heads/master
2020-03-18T04:32:14.196283
2018-05-21T16:19:03
2018-05-21T16:19:03
134,292,567
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import unicode_literals from copy import deepcopy import boto3 import json from moto.ec2 import utils as ec2_utils from uuid import UUID from moto import mock_cloudformation from moto import mock_ecs from moto import mock_ec2 from moto import mock_s3 from boto3 import client @mock_ec2 @mock_ecs @mock_s3 def run_task(): client = boto3.client('ecs', region_name='us-east-1') ec2 = boto3.resource('ec2', region_name='us-east-1') conn = boto3.resource('s3', region_name='us-east-1') s3 = boto3.client('s3', region_name='us-east-1') conn.create_bucket(Bucket='mybucket') test_cluster_name = 'test_ecs_cluster' _ = client.create_cluster( clusterName=test_cluster_name ) test_instance = ec2.create_instances( ImageId="ami-1234abcd", MinCount=1, MaxCount=1, )[0] instance_id_document = json.dumps( ec2_utils.generate_instance_identity_document(test_instance) ) response = client.register_container_instance( cluster=test_cluster_name, instanceIdentityDocument=instance_id_document ) _ = client.register_task_definition( family='test_ecs_task', containerDefinitions=[ { 'name': 'hello_world', 'image': 'docker/hello-world:latest', 'cpu': 1024, 'memory': 400, 'essential': True, 'environment': [{ 'name': 'AWS_ACCESS_KEY_ID', 'value': 'SOME_ACCESS_KEY' }], 'logConfiguration': {'logDriver': 'json-file'} } ] ) response = client.run_task( cluster='test_ecs_cluster', overrides={}, taskDefinition='test_ecs_task', count=1, startedBy='moto' ) # Put Task Arn in S3 Bucket s3.put_object(Bucket='mybucket', Key='taskArn', Body=response['tasks'][0]['taskArn']) taskArn = conn.Object('mybucket', 'taskArn').get()['Body'].read().decode() print("The S3 taskArn was: " + taskArn) # Print out response attributes of ECS Task print("Number of tasks: " + str(len(response['tasks']))) print("Task ARN: " + response['tasks'][0]['taskArn']) print("Cluster ARN: " + response['tasks'][0]['clusterArn']) print("TaskDefinition ARN: " + response['tasks'][0]['taskDefinitionArn']) print("Container Instance ARN: " + response['tasks'][0]['containerInstanceArn']) print("Last Status: " + response['tasks'][0]['lastStatus']) print("Desired Status: " + response['tasks'][0]['desiredStatus']) print("Started By: " + response['tasks'][0]['startedBy']) run_task()
UTF-8
Python
false
false
2,771
py
11
execute_ecs_task.py
2
0.5821
0.564417
0
92
29.119565
89
suziexi/2020GSoC_FrameBlends
7,962,869,382,703
59370bce67a9acfee9c38007f3596e83259f2403
be6224a65608139f06b0077b3b9b943aac569bfb
/detect_metaphor.py
3dca06f2857055af2a77d288894b0bc1444edf1d
[]
no_license
https://github.com/suziexi/2020GSoC_FrameBlends
deb547cc1a4b75457ccf195728e3d39b9f3b2157
c7f61b6789ace34e1dbd5caa00e619351735af62
refs/heads/master
2022-12-14T10:07:57.880395
2020-08-29T03:06:37
2020-08-29T03:06:37
262,644,011
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from pprint import pprint from nltk.corpus import framenet as fn import nltk import xml.dom.minidom as DM import xml.etree.ElementTree as ET from xml.etree import ElementTree from xml.etree.ElementTree import tostring import os import zipfile2 import lxml.etree as etree path = ('/Users/mac/Desktop/fndata-1.7/fulltext') def metapFilter(path): metap_list = [None] * 1 item = ET.Element("FBL") ET.SubElement(item, 'Source').text = 'Metaphor_label' for filename in os.listdir(path): if not filename.endswith('.xml'): continue fullname = os.path.join(path, filename) tree_0 = ET.parse(fullname) tree_1 = tree_0.getroot() t = tostring(tree_1) t = t.lower() tree_2 = ET.fromstring(t) for sentence in tree_2: for annot in sentence.iter(): # text, annotationSet for x, y in annot.attrib.items(): if y == 'metaphor': print('Metaphor filter:') print(sentence[0].text) metap_list.append(sentence[0].text) metap_list.append('--------------') annot.append(item) print(filename) filename = open('/Users/mac/Desktop/metaphor_label/'+filename, "w") filename.write(ET.tostring(tree_2, encoding="unicode")) def main(): metapFilter(path) if __name__ == "__main__": main()
UTF-8
Python
false
false
1,474
py
16
detect_metaphor.py
13
0.569199
0.56038
0
51
27.901961
75
javassj2019/fxol
13,039,520,748,871
a5a13b0f420ab28a97420565457bb7c5e553826b
070df2e62355dbb4a68b46f89bfd90358ca5fa71
/考试.py
ffe1a99f5accf4f6bc6eacfcacc6423e46a51dbc
[]
no_license
https://github.com/javassj2019/fxol
8b3c3f3bb1c7760cb159b428db70210ed864d43d
c69c2fc91a8bc0c33a104144f04cae7acfd4caaf
refs/heads/master
2023-07-05T16:27:32.446084
2021-08-26T13:22:56
2021-08-26T13:22:56
314,174,734
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import requests import json import pymysql import re import datetime import urllib # -*- coding:utf-8 -*- # 连接数据库并获取账户密码信息 conn = pymysql.connect(host='cdb-kce5k8kq.bj.tencentcdb.com', user='root', passwd='a159753A!', port=10264, charset='utf8', db='fxol') cur = conn.cursor(pymysql.cursors.DictCursor) # 生成游标 # # 录入新用户 # def Typeuserid(): # print('请输入用户名:') # userAccount = input() # print('请输入密码:') # userPassword = input() # # 用户查重 # checkuid = cur.execute('select UserID from User where UserID = (%s)', userAccount) # print(checkuid) # if checkuid == 0: # cur.execute('insert into User(UserID,UserPassword,TDpoint) VALUES (%s,%s,%s)', (userAccount, userPassword, 10)) # conn.commit() # print('用户添加完成') # else: # print('用户已存在,无需再次添加') # # # print('需要添加新用户吗?Yes') # checktype = input() # if checktype == 'Y': # i = 0 # while i <= 100: # Typeuserid() # i = i + 1 ###基础数据 http = 'http://' host = 'mobile.faxuan.net' loginurl = '/bss/service/userService!doUserLogin.do?' getdetailurl = '/useris/service/getdetail?userAccount=' studyurl = '/sss/service/coursewareService!commitStudy.do?domainCode=' code = '&code=2f56fe3477f774c4ece2b926070b6d0a' headers = {} headers['If-Modified-Since'] = 'Tue, 1 Jul 2021 01:33:10 GMT+00:00' headers['User-Agent'] = 'Dalvik/2.1.0 (Linux; U; Android 7.1.1; OPPO R9s Build/NMF26F)' headers['Host'] = 'mobile.faxuan.net' headers['Accept-Encoding'] = 'gizp,deflate' headers['Connection'] = 'keep-alive' headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8' answerjson = '\[(.*)\]' ####比较最后更新时间并写数据库 today = str(datetime.date.today()) ###开始登陆过程 s = 0 l = cur.execute('select UserID,UserPassword from User where Mark = (%s)', (3)) while s <= l: cur.execute('select UserID,UserPassword from User where Mark = (%s)', (3)) tt1 = cur.fetchone() print(tt1) userAccount = tt1['UserID'] userPassword = tt1['UserPassword'] # 登陆并获取参数 tt = requests.get(http + host + loginurl + 'userAccount=' + userAccount + '&userPassword=' + userPassword + code, headers=headers) dd = json.loads(tt.text) sid = dd['data']['sid'] # username = dd['data']['userName'] # 获取学员基础信息 t2 = requests.get(http + host + getdetailurl + userAccount + '&ssid=' + sid, headers=headers) t2.encoding = 'utf8' d2 = json.loads(t2.text) lenth = len(d2) dict1 = {} i = 0 while i <= lenth-1: dict1[d2[i]] = d2[i + 1] i = i + 2 TDpoint = dict1['todaytpoint'] domainCode = dict1['domainCode'] Tpoint = dict1['tpoint'] username = dict1['userName'] print(username) # 开始考试 examid = str(2440) paperid = str(4932) series = str(430) t4 = requests.get( http + host + '/ess/service/getpaper?paperId='+paperid+'&series='+series+'_answer&version=2.5.5&userAccount' + userAccount, headers=headers) # print(t4.text) t4answer = re.findall(answerjson, str(t4.content))[0] # 此处返回text会因为返回有非json的数据不能读取 t4answer = t4answer.replace(',"score":"1.0",', ',') t4answer = t4answer.replace(',"score":"2.0",', ',') t4answer = t4answer.replace(',"score":"3.0",', ',') t4answer = t4answer.replace('questionId":"', 'questionId":') t4answer = t4answer.replace('","answerNo', ',"answerNo') t4answer = t4answer.replace('},{', '}{') t4answer = t4answer.replace('ABCD', 'A,B,C,D') t4answer = t4answer.replace('ABC', 'A,B,C') t4answer = t4answer.replace('ABD', 'A,B,D') t4answer = t4answer.replace('ACD', 'A,C,D') t4answer = t4answer.replace('BCD', 'B,C,D') t4answer = t4answer.replace('AC', 'A,C') t4answer = t4answer.replace('AD', 'A,D') t4answer = t4answer.replace('BC', 'B,C') t4answer = t4answer.replace('BD', 'B,D') t4answer = t4answer.replace('CD', 'C,D') answer = t4answer data = { 'series': series, 'examId': examid, 'paperId': paperid, 'userAccount': userAccount, 'domainCode': domainCode, 'myExamAnswer': '[' + answer + ']' } t6 = requests.post( http + host + '/ess/service/myexam/myExamAo!doCommitExam.do', headers=headers, data=data ) # print(t6.text) cur.execute('UPDATE User SET Mark = (%s) WHERE UserID = (%s)', (4, userAccount)) conn.commit() print("学习过程结束") ##########这里还差学习执行过程
UTF-8
Python
false
false
4,726
py
4
考试.py
4
0.607207
0.572523
0
133
32.383459
131
Aasthaengg/IBMdataset
16,527,034,199,193
c13c2bb8ce64502d47684fa049ec9fb42dd3e062
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p04020/s106001075.py
1e4884768684ea5f5415973b24f44bab1b71f1fb
[]
no_license
https://github.com/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
null
null
null
null
null
null
null
null
null
N = int(input()) A = [int(input()) for _ in range(N)] res = 0 n = 0 for a in A: if a == 0: res += n // 2 n = 0 n += a res += n // 2 print(res)
UTF-8
Python
false
false
170
py
202,060
s106001075.py
202,055
0.4
0.364706
0
14
11.142857
36
sunny-aria/py_mysite
19,499,151,541,632
ea9b1f1eeabf697815469287b6b65521f71acb51
74c78a270a6a54d76f3aa707b2a5b5a207d85080
/polls/admin.py
4584739edbf2517032f7dce63cef9464068c6439
[]
no_license
https://github.com/sunny-aria/py_mysite
463856e70c85ad86faf7389206022885649a2264
bf7df6355c6200ae98aa5d413b6e7cb5ec29f9a0
refs/heads/master
2020-03-28T15:33:41.120002
2018-10-09T03:37:12
2018-10-09T03:37:12
148,606,137
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib import admin # Register your models here. from . import models # 将models 注册到后台管理上面 admin.site.register(models.Poll) admin.site.register(models.Choice)
UTF-8
Python
false
false
193
py
6
admin.py
4
0.797688
0.797688
0
9
18.333333
34
ronekko/study_reinforcement_learning
3,358,664,449,177
f1306ff3242601b96710e947c2fed3ab69052347
3e6091b1fede2f6333f96a323bb6f1267f78597f
/gym_usage.py
5277c4a7f4b4fcfa37bdad4c3e80d77a3b05bd91
[ "MIT" ]
permissive
https://github.com/ronekko/study_reinforcement_learning
411dcf31921f2fe705448f2121553a7732e703f0
ef5201e3eae69c20f29b7f176b5a6de7ecdb856a
refs/heads/main
2023-04-19T02:24:19.512943
2021-04-25T09:25:32
2021-04-25T09:25:32
346,573,950
0
0
MIT
false
2021-04-25T09:25:33
2021-03-11T04:09:19
2021-03-11T04:16:44
2021-04-25T09:25:32
39
0
0
0
Python
false
false
# -*- coding: utf-8 -*- """ Created on Sat Feb 13 16:52:17 2021 @author: ryuhei """ import gym if __name__ == '__main__': # Gallery of environments: https://gym.openai.com/envs/#classic_control env = gym.make('CartPole-v1') # state(pos, vel, angle, angular vel) # env = gym.make('Pendulum-v0') # env = gym.make('MsPacman-v0') # env = gym.make('Pong-v0') env.reset() for _ in range(10): env.reset() states = [] rewards = [] for _ in range(200): env.render() # Choose an action from {0, 1}, where # 0 or 1 are left or right acceleration respectively. action = env.action_space.sample() # Do the action and receive an outcome. # An outcome consists of # - observation (float np.array of length 4): # [cart pos, cart vel, pole angle, pole angular vel] # - reward (float): constant 1. # - done (bool): True if the pole angle has exceeded the limits. # - info (dict): Additional information. outcome = env.step(action) obs, reward, done, info = outcome states.append(obs) rewards.append(reward) if done: break env.close()
UTF-8
Python
false
false
1,317
py
6
gym_usage.py
5
0.525437
0.504176
0
46
27.630435
78
jcugat/django-custom-user
9,345,848,888,466
fd0ecff7ff765c442567d36ee033fa85ff21ab2e
15aae55c7261460a4261223b991720ff8f9efbd9
/src/custom_user/apps.py
8a7f85ca1130363da95327f5af0043b93bd3fdb2
[ "BSD-2-Clause" ]
permissive
https://github.com/jcugat/django-custom-user
242b08b5ae1187789df1797c6b0559c59959bb89
309d36c681d622bcdbc4648368cb13faab9cce95
refs/heads/main
2023-02-25T00:08:05.997146
2022-12-09T23:59:04
2022-12-09T23:59:04
9,319,295
281
77
BSD-3-Clause
false
2023-02-15T19:27:53
2013-04-09T11:08:02
2023-02-15T08:39:53
2023-02-15T19:27:50
281
310
65
4
Python
false
false
"""App configuration for custom_user.""" from django.apps import AppConfig class CustomUserConfig(AppConfig): """ Default configuration for custom_user. """ name = "custom_user" verbose_name = "Custom User" # https://docs.djangoproject.com/en/3.2/releases/3.2/#customizing-type-of-auto-created-primary-keys default_auto_field = "django.db.models.AutoField"
UTF-8
Python
false
false
389
py
18
apps.py
10
0.701799
0.691517
0
14
26.785714
103
datvithanh/liveness
9,620,726,751,440
9941d82c52524530de21999020a24d119f54c608
f24e205b70666ac0b773a4d3a4828442f07c24a9
/main.py
0ea0be54b0801a4104e7dbdfefd12cbf74b73d20
[]
no_license
https://github.com/datvithanh/liveness
819a831d69452677b0b8788cda28891ca6c9cd84
1727d5830093c140b2d52fb021ffcd50a37bb59f
refs/heads/master
2020-08-05T12:31:44.346370
2019-09-19T09:16:08
2019-09-19T09:16:08
212,506,306
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import argparse import yaml from src.estimator import Estimator parser = argparse.ArgumentParser(description='Liveness estimator') parser.add_argument('--config', type=str, help='Path to config of liveness') parser.add_argument('--cuda', action='store_true', help='Use cuda for training/finetuning or not') parser.add_argument('--epoch', default=0, type=int, help='Epoch to continue training/finetuning') parser.add_argument('--model_path', default='', type=str, help='Path to pretrained model') parser.add_argument('--mode', default='training', type=str, help='Mode: either training or finetuning') params = parser.parse_args() config = yaml.load(open(params.config, 'r')) est = Estimator(params, config) est.exec()
UTF-8
Python
false
false
723
py
12
main.py
9
0.745505
0.744122
0
19
37.052632
103
mn3711698/markets_monitor
7,481,833,079,478
2e83912ec0e757ca4f8e27cd7be239f08f086879
69aeac8061bfbf4f692163f97dc9bec095bfaf4e
/monitor_crawl/investing.py
97683c72855b6a449bca1c517b86bbaaf75b7069
[]
no_license
https://github.com/mn3711698/markets_monitor
0939c8b6bd33a2a50f404f89b42bbd29e98ae666
d00a649c46dc21f52a9e4e213797390bb7088c9b
refs/heads/master
2021-04-06T00:00:56.322346
2015-02-11T08:34:10
2015-02-11T08:34:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created on 2015/2/6 # !/usr/bin/env python # -*- coding: utf-8 -*- # Created on 2015/1/14 from base import * import time cur.execute("select * from ax_config WHERE status='active' and diff_url like '%investing%' ") data = cur.fetchall() start_time = time.time() # while 1: for i in xrange(1): for item in data: diff_url = item['diff_url'] # pow_format=item['pow_format'] diff_allow = item['diff_allow'] site_url = 'http://api.markets.wallstreetcn.com/v1/price.json?symbol=%s' % item['symbol'] try: diff_price = get_data(diff_url) ctime = int(time.time()) site_price, site_ctime = get_wallstreetcn(site_url) if diff_price and site_price: # print item['symbol'],diff_price,site_price,pow_format,diff_allow # print u'允许误差',diff_allow*1.0/math.pow(10,pow_format) if abs(diff_price - site_price) > diff_allow: print diff_url, diff_allow cur.execute("insert into log set symbol=%s,diff_price=%s,site_price=%s,ctime=%s,site_ctime=%s", (item['symbol'], diff_price, site_price, ctime, site_ctime)) cur.execute("update ax_config set diff_price=%s,site_price=%s,ctime=%s,site_ctime=%s,diff_status=1 WHERE id=%s", (diff_price, site_price, ctime, site_ctime, item['id'])) else: cur.execute("update ax_config set diff_price=%s,site_price=%s,ctime=%s,site_ctime=%s,diff_status=0 WHERE id=%s", (diff_price, site_price, ctime, site_ctime, item['id'])) except Exception as e: app_log.error(str(e)) end_time = time.time() print end_time - start_time
UTF-8
Python
false
false
1,752
py
15
investing.py
8
0.593463
0.579702
0
43
39.581395
189
samuelbaltanas/face-pose-dataset
11,733,850,664,415
faa903bebc93532bc2a40c9f6e009f118e3deedb
7b7062f9e07c9a655d0d91186d16eca7f435980b
/face_pose_dataset/__main__.py
df403ba2e6d9447a325163cbe9872eeccb13a184
[ "MIT" ]
permissive
https://github.com/samuelbaltanas/face-pose-dataset
0fbc8df61f369f00629ecd3db3791d1268b3a530
84c864c155ac7c0b231032d403c0e2b2bc10b871
refs/heads/master
2022-08-28T10:46:08.005149
2020-05-26T08:11:28
2020-05-26T08:11:28
257,634,482
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import argparse import logging import os import sys import platform logging.getLogger().setLevel(logging.INFO) import PySide2 if platform.system() == "Windows": dirname = os.path.dirname(PySide2.__file__) plugin_path = os.path.join(dirname, 'plugins', 'platforms') logging.info("%s is a dir : %s", plugin_path, os.path.isdir(plugin_path)) os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path from PySide2 import QtCore, QtWidgets class MainWindow(QtWidgets.QMainWindow): def __init__(self, *args, **kwargs): QtWidgets.QMainWindow.__init__(self, *args, **kwargs) self.setWindowTitle("Dataset") self.layouts = {} self.kill_callback = None # self.setGeometry(300, 200, 500, 400) def register_layout(self, key, layout, resolution=(600, 360)): self.layouts[key] = layout, resolution @QtCore.Slot(str) def change_layout(self, key: str): lay = self.layouts[key] self.setCentralWidget(lay[0]) self.resize(*lay[1]) self.show() def closeEvent(self, event): if self.kill_callback is not None: self.kill_callback(event) else: quit_msg = "Are you sure you want to exit the program?" reply = QtWidgets.QMessageBox.question( self, "Message", quit_msg, QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No, ) if reply == QtWidgets.QMessageBox.Yes: event.accept() else: event.ignore() def main(args): try: if args.quiet: logging.getLogger().setLevel(logging.ERROR) elif args.verbose: logging.getLogger().setLevel(logging.DEBUG) else: logging.getLogger().setLevel(logging.INFO) app = QtWidgets.QApplication(sys.argv) logging.info(args) logging.info("Platform: %s", platform.platform()) if args.force_cpu: os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ['CUDA_VISIBLE_DEVICES'] = '-1' else: os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true' from face_pose_dataset.controller import estimation, logging_controller, storage_control from face_pose_dataset.model import score, storage from face_pose_dataset.view import login, main_view # PARAMS dims = 7, 7 yaw_range = -65.0, 65.0 pitch_range = -35.0, 35.0 # MODELS scores = score.ScoreModel(dims, pitch_range=pitch_range, yaw_range=yaw_range) store = storage.DatasetModel(shape=dims) # VIEW window = MainWindow() window.resize(600, 360) # Login login_widget = login.Login() window.register_layout("login", login_widget) window.change_layout("login") # Main widget widget = main_view.MainWidget(scores) window.register_layout("main", widget, (1200, 720)) # CONTROLLERS store_controller = storage_control.StorageController(scores, store) store_controller.change_pos.connect(widget.plot.update_pointer) logger = logging_controller.LoggingController(login_widget, store) logger.change_layout.connect(window.change_layout) if args.force_cpu: gpu = -1 else: gpu = 0 th = estimation.EstimationThread(gpu=gpu) th.video_feed.connect(widget.video.set_image) th.worker.result_signal.connect(store_controller.process) # th.setTerminationEnabled(True) login_widget.switch_window.connect(logger.access) logger.set_camera.connect(th.init_camera) store_controller.flag_pause.connect(th.set_pause) widget.controls.buttons[0].clicked.connect(th.toggle_pause) widget.controls.buttons[1].clicked.connect(store_controller.terminateApp) store_controller.flag_end.connect(th.set_stop) scores.change_score.connect(widget.plot.update_plot) window.kill_callback = lambda x: store_controller.terminateApp() # Execute application logging.info("[MAIN] Running main loop.") _excepthook = sys.excepthook def exception_hook(exctype, value, traceback): print(exctype, value, traceback) _excepthook(exctype, value, traceback) sys.exit(-1) sys.excepthook = exception_hook # th.start() res = app.exec_() finally: logging.info("[MAIN] Waiting for thread to terminate.") # th.wait(2000) logging.info("[MAIN] Terminated.") sys.exit(res) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--force-cpu", action="store_true", help="Forces the estimator to use a CPU. When not set, it searches for any available GPU.", ) group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", action="store_true") group.add_argument("-q", "--quiet", action="store_true") return parser.parse_args() if __name__ == "__main__": args = parse_args() main(args)
UTF-8
Python
false
false
5,209
py
39
__main__.py
33
0.60933
0.597811
0
170
29.641176
99
karthikpappu/pyc_source
4,028,679,342,572
2dc18446213f5f1022dabebd56cf3ea9cedc8f62
91fa095f423a3bf47eba7178a355aab3ca22cf7f
/pycfiles/boo_box-0.3.7-py2.4/teste.py
45ac43a15758474c67d1be4bfcd32bc7734e00d5
[]
no_license
https://github.com/karthikpappu/pyc_source
0ff4d03e6d7f88c1aca7263cc294d3fa17145c9f
739e7e73180f2c3da5fd25bd1304a3fecfff8d6e
refs/heads/master
2023-02-04T11:27:19.098827
2020-12-27T04:51:17
2020-12-27T04:51:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# uncompyle6 version 3.7.4 # Python bytecode 2.4 (62061) # Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) # [GCC 8.4.0] # Embedded file name: build/bdist.linux-i686/egg/boo_box/teste.py # Compiled at: 2008-05-02 09:14:26 import boo_box, simplejson boo = boo_box.Box('submarinoid', '248960').getJSON('livros javascript').replace('jsonBooboxApi(', '') json = simplejson.loads(boo[:-1]) for item in json['item']: print item
UTF-8
Python
false
false
441
py
114,545
teste.py
111,506
0.702948
0.582766
0
11
39.181818
101