blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 281 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 6 116 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 313 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 18.2k 668M ⌀ | star_events_count int64 0 102k | fork_events_count int64 0 38.2k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 107 values | src_encoding stringclasses 20 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 4 6.02M | extension stringclasses 78 values | content stringlengths 2 6.02M | authors listlengths 1 1 | author stringlengths 0 175 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4d8d3e5cf6f2e677b3dacfdf239f1811304ba498 | 58cc35c25e45366aaa0e3887cea1bd85fc0f14c4 | /api/serializers/testing/test_runner.py | 484b809bffd69e296bb2d45065acee4e33651aba | [] | no_license | renanrv/test-executor | 7ea7f0ca0a9179f9380a02fb684f19fc4308b479 | 1ce7aa1b4131be6c3a8bc3cf5a9598cd8b533059 | refs/heads/master | 2021-05-07T15:06:54.188254 | 2017-11-14T00:00:41 | 2017-11-14T00:00:41 | 109,977,526 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 190 | py | # -*- coding: utf-8 -*-
from rest_framework import serializers
class TestRunnerSerializer(serializers.Serializer):
code = serializers.IntegerField()
name = serializers.CharField()
| [
"renan.vasconcelos@orama.com.br"
] | renan.vasconcelos@orama.com.br |
f2a5f0eef81cd1b136457da1ba1ca887736186c2 | 5cc5cc2acade85f9fefb61f0b007cc29f395e54e | /orders/admin.py | 7b8732b614131d84d592099ae307c1f995418f5c | [] | no_license | laimaurnezaite/Pinocchios | 20066e160ce684dd77de72de73a04333dda6a264 | ddbe5e586dc3c66158ab2c9b5e4a2dee83f0332e | refs/heads/master | 2022-07-19T05:25:44.324527 | 2020-05-12T12:28:01 | 2020-05-12T12:28:01 | 262,084,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 215 | py | from django.contrib import admin
from .models import Order#, #ShoppingCart#, OrderItems
# Register your models here.
admin.site.register(Order)
# admin.site.register(ShoppingCart)
# admin.site.register(OrderItems) | [
"laima.urnezaite@gmail.com"
] | laima.urnezaite@gmail.com |
a7c7a2d522606326d339fa6b7f6be1af992eb35d | 9ec7c121d3a95505d895ca3201ccb28232a2f436 | /structural_design_patterns/adapter.py | 586bda53e48b168e3e82b4adfda8b3b84fcc7730 | [] | no_license | RyukerLiu/design-pattern | 531f7860de39250eda5a29868b1b73db911b1c8b | 3107693e252957a72487ee01e38e4e69c1e144e8 | refs/heads/main | 2023-08-26T06:00:28.514167 | 2021-11-01T13:56:56 | 2021-11-01T13:56:56 | 383,742,954 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 748 | py | import math
class RoundPeg:
def __init__(self, radius):
self.radius = radius
def get_radius(self):
return self.radius
class RoundHole:
def __init__(self, radius):
self.radius = radius
def fits(self, peg: RoundPeg):
return self.radius >= peg.get_radius()
class SquarePeg:
def __init__(self, width):
self.width = width
def get_width(self):
return self.width
class SquarePegAdapter(RoundPeg):
'''
In order to check if we can insert SquarePeg in a RoundHole
'''
def __init__(self, peg: SquarePeg):
self.peg = peg
def get_radius(self):
width = self.peg.get_width()
radius = (width / 2) * math.sqrt(2)
return radius
| [
"alex03108861@gmail.com"
] | alex03108861@gmail.com |
85b9431aa68b75cba86e309e1c3a60671ac62aca | 5f1652c95ce91a0e05f64c8d0703b9d18fc45097 | /homework_tests/asgi.py | c5872c3561965cbe4eb49833ac86c56d478364f9 | [] | no_license | YuriiShp/api_homework | 84f12843d4e96f7a9b12c4e79227139aae29fac4 | 6ea75e0a4974b2d5ca4bee03c1fd71634113433f | refs/heads/main | 2023-01-07T13:15:12.456417 | 2020-11-11T21:34:10 | 2020-11-11T21:34:10 | 312,095,404 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 405 | py | """
ASGI config for homework_tests project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'homework_tests.settings')
application = get_asgi_application()
| [
"yuralrock@gmail.com"
] | yuralrock@gmail.com |
2f2598ed6a79bbe55c47c66fb2f205c2993b2f35 | 7d114d06693e1501e4074d9eda9c054048f1d6e7 | /keras_sequential_model.py | 5072f8439afdc897d9e4099b040de5c1d058fae2 | [] | no_license | bipulshahi/codes | e39d6d219b5e006ed6e58f5d84ee3f8b25224ffd | 8ff2549655493f9ac52701d9d8097a43571d0a93 | refs/heads/master | 2023-06-23T09:07:06.649945 | 2023-06-10T07:08:18 | 2023-06-10T07:08:18 | 161,839,734 | 11 | 16 | null | null | null | null | UTF-8 | Python | false | false | 2,424 | py | # -*- coding: utf-8 -*-
"""Keras Sequential Model.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1rOd-AeQVq0AIAyTdLO7ir58sXKClJzgA
"""
from keras import models
from keras.layers import Dense, Dropout
from keras.utils import to_categorical
from keras.datasets import mnist
from keras.utils.vis_utils import model_to_dot
from IPython.display import SVG
# Commented out IPython magic to ensure Python compatibility.
import livelossplot
plot_losses = livelossplot.PlotLossesKeras()
# %matplotlib inline
NUM_ROWS = 28
NUM_COLS = 28
NUM_CLASSES = 10
BATCH_SIZE = 128
EPOCHS = 10
def data_summary(X_train, y_train, X_test, y_test):
"""Summarize current state of dataset"""
print('Train images shape:', X_train.shape)
print('Train labels shape:', y_train.shape)
print('Test images shape:', X_test.shape)
print('Test labels shape:', y_test.shape)
print('Train labels:', y_train)
print('Test labels:', y_test)
# Load data
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# Check state of dataset
data_summary(X_train, y_train, X_test, y_test)
# Reshape data
X_train = X_train.reshape((X_train.shape[0], NUM_ROWS * NUM_COLS))
X_train = X_train.astype('float32') / 255
X_test = X_test.reshape((X_test.shape[0], NUM_ROWS * NUM_COLS))
X_test = X_test.astype('float32') / 255
# Categorically encode labels
y_train = to_categorical(y_train, NUM_CLASSES)
y_test = to_categorical(y_test, NUM_CLASSES)
# Check state of dataset
data_summary(X_train, y_train, X_test, y_test)
# Build neural network
model = models.Sequential()
model.add(Dense(512, activation='relu', input_shape=(NUM_ROWS * NUM_COLS,)))
model.add(Dropout(0.5))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(10, activation='softmax'))
# Compile model
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Train model
model.fit(X_train, y_train,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
callbacks=[plot_losses],
verbose=1,
validation_data=(X_test, y_test))
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# Summary of neural network
model.summary()
# Output network visualization
SVG(model_to_dot(model).create(prog='dot', format='svg'))
| [
"noreply@github.com"
] | noreply@github.com |
816966b273d6b069ce21943c3cc82b528a7647a7 | a3edc11b218d138854543a91b1fcc656adb86889 | /app/CrawlerMonitor/Monitor/Log_Info/error_output.py | 1a1fa78e94ed458e6e8e2e571be240a883c27dfd | [] | no_license | weileanjs/option_web | c506f7ff7ab2bdc660b830513597598caf33094d | 68dc1d280d39757e02eba9c80bb64e5158212c81 | refs/heads/master | 2020-04-08T22:09:16.909227 | 2018-11-30T05:46:42 | 2018-11-30T05:46:42 | 159,774,309 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 815 | py | # coding=utf-8
import logging
from ..config import LOG_NAME
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
# rq = time.strftime('%Y%m%d', time.localtime(time.time()))
handler = logging.FileHandler("{}.log".format(LOG_NAME))
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
def logError(*args):
logger.error(args)
def logWarning(*arg):
logger.warning(arg)
def error_deco(func):
def wrapper(*args):
try:
func(*args)
except Exception as e:
print('{} ERROR :{}'.format(func.__name__,str(e)))
logError('{} ERROR :{}'.format(func.__name__,str(e)))
return wrapper
| [
"24689003@qq.com"
] | 24689003@qq.com |
09638a0316277ba90691152d2ee5fcaa722b2305 | c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c | /cases/synthetic/coverage-big-955.py | a413f3a44075f48e40c63ede11ed563101fe0e36 | [] | no_license | Virtlink/ccbench-chocopy | c3f7f6af6349aff6503196f727ef89f210a1eac8 | c7efae43bf32696ee2b2ee781bdfe4f7730dec3f | refs/heads/main | 2023-04-07T15:07:12.464038 | 2022-02-03T15:42:39 | 2022-02-03T15:42:39 | 451,969,776 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,351 | py | count:int = 0
count2:int = 0
count3:int = 0
count4:int = 0
count5:int = 0
def foo(s: str) -> int:
return len(s)
def foo2(s: str, s2: str) -> int:
return len(s)
def foo3(s: str, s2: str, s3: str) -> int:
return len(s)
def foo4(s: str, s2: str, s3: str, s4: str) -> int:
return len(s)
def foo5(s: str, s2: str, s3: str, s4: str, s5: str) -> int:
return len(s)
class bar(object):
p: bool = True
def baz(self:"bar", xx: [int]) -> str:
global count
x:int = 0
y:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
class bar2(object):
p: bool = True
p2: bool = True
def baz(self:"bar2", xx: [int]) -> str:
global count
x:int = 0
y:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz2(self:"bar2", xx: [int], xx2: [int]) -> str:
global count
x:int = 0
x2:int = 0
y:int = 1
y2:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == $Exp:
self.p = self is None
return "Nope"
class bar3(object):
p: bool = True
p2: bool = True
p3: bool = True
def baz(self:"bar3", xx: [int]) -> str:
global count
x:int = 0
y:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz2(self:"bar3", xx: [int], xx2: [int]) -> str:
global count
x:int = 0
x2:int = 0
y:int = 1
y2:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz3(self:"bar3", xx: [int], xx2: [int], xx3: [int]) -> str:
global count
x:int = 0
x2:int = 0
x3:int = 0
y:int = 1
y2:int = 1
y3:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
def qux3(y: int, y2: int, y3: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
class bar4(object):
p: bool = True
p2: bool = True
p3: bool = True
p4: bool = True
def baz(self:"bar4", xx: [int]) -> str:
global count
x:int = 0
y:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz2(self:"bar4", xx: [int], xx2: [int]) -> str:
global count
x:int = 0
x2:int = 0
y:int = 1
y2:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz3(self:"bar4", xx: [int], xx2: [int], xx3: [int]) -> str:
global count
x:int = 0
x2:int = 0
x3:int = 0
y:int = 1
y2:int = 1
y3:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
def qux3(y: int, y2: int, y3: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz4(self:"bar4", xx: [int], xx2: [int], xx3: [int], xx4: [int]) -> str:
global count
x:int = 0
x2:int = 0
x3:int = 0
x4:int = 0
y:int = 1
y2:int = 1
y3:int = 1
y4:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
def qux3(y: int, y2: int, y3: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
if x > y:
x = -1
def qux4(y: int, y2: int, y3: int, y4: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
nonlocal x4
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
class bar5(object):
p: bool = True
p2: bool = True
p3: bool = True
p4: bool = True
p5: bool = True
def baz(self:"bar5", xx: [int]) -> str:
global count
x:int = 0
y:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz2(self:"bar5", xx: [int], xx2: [int]) -> str:
global count
x:int = 0
x2:int = 0
y:int = 1
y2:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz3(self:"bar5", xx: [int], xx2: [int], xx3: [int]) -> str:
global count
x:int = 0
x2:int = 0
x3:int = 0
y:int = 1
y2:int = 1
y3:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
def qux3(y: int, y2: int, y3: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz4(self:"bar5", xx: [int], xx2: [int], xx3: [int], xx4: [int]) -> str:
global count
x:int = 0
x2:int = 0
x3:int = 0
x4:int = 0
y:int = 1
y2:int = 1
y3:int = 1
y4:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
def qux3(y: int, y2: int, y3: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
if x > y:
x = -1
def qux4(y: int, y2: int, y3: int, y4: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
nonlocal x4
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
def baz5(self:"bar5", xx: [int], xx2: [int], xx3: [int], xx4: [int], xx5: [int]) -> str:
global count
x:int = 0
x2:int = 0
x3:int = 0
x4:int = 0
x5:int = 0
y:int = 1
y2:int = 1
y3:int = 1
y4:int = 1
y5:int = 1
def qux(y: int) -> object:
nonlocal x
if x > y:
x = -1
def qux2(y: int, y2: int) -> object:
nonlocal x
nonlocal x2
if x > y:
x = -1
def qux3(y: int, y2: int, y3: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
if x > y:
x = -1
def qux4(y: int, y2: int, y3: int, y4: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
nonlocal x4
if x > y:
x = -1
def qux5(y: int, y2: int, y3: int, y4: int, y5: int) -> object:
nonlocal x
nonlocal x2
nonlocal x3
nonlocal x4
nonlocal x5
if x > y:
x = -1
for x in xx:
self.p = x == 2
qux(0) # Yay! ChocoPy
count = count + 1
while x <= 0:
if self.p:
xx[0] = xx[1]
self.p = not self.p
x = x + 1
elif foo("Long"[0]) == 1:
self.p = self is None
return "Nope"
print(bar().baz([1,2]))
| [
"647530+Virtlink@users.noreply.github.com"
] | 647530+Virtlink@users.noreply.github.com |
acc977511fd11f710814e06c27a13c3a5393a7ad | 7c7df2ba89a4bd42ca4b1bbc3de8f05818521ac3 | /Python Solutions/Day 1/day1_part1.py | 7e22bbfa449346c0fcbb670e889d43adbef9d0be | [] | no_license | Jorgee97/AdventOfCode2019 | aa550c5097ef4d5d9ad1c83a91c1e3067285c19a | 2a9e61da7c9fcabe110f44cbd00682770383e32f | refs/heads/master | 2020-09-24T03:38:09.995967 | 2019-12-14T05:03:16 | 2019-12-14T05:03:16 | 225,652,398 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 805 | py | ##############################################################
########## The Tyranny of the Rocket Equation ###############
########## https://adventofcode.com/2019/day/1 ###############
########## by Jorge Gomez ###############
##############################################################
from helpers import read_file
def calculate_fuel(m):
"""Return an integer
Fuel required to launch a given module(m) is based on its mass.
Specifically, to find the fuel required for a module,
take its mass, divide by three, round down, and subtract 2.
"""
return (m // 3) - 2
if __name__ == '__main__':
modules = read_file('input.txt')
total_amount_of_fuel = sum([calculate_fuel(int(m)) for m in modules])
print(total_amount_of_fuel)
| [
"ingjorgegomez@outlook.com"
] | ingjorgegomez@outlook.com |
2c24f5a6b8e96190564084f530d4657416c379e8 | c96c71714fbffeb937a1c2054fc0d87d1f64759e | /4user_input2.py | 25504fae4493fa451f7038e56d735c61c8c2e2d0 | [] | no_license | ashikkhulal/Python-references | 0d6f6d1952a3f9793e8f6fb2927cf13d3527b90b | eef0e1c7cfb436a5d5120f843313db72207afd0a | refs/heads/main | 2023-05-06T03:16:52.134715 | 2021-06-04T12:03:00 | 2021-06-04T12:03:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 236 | py | #another user input example
convert_to_units = 24
name_of_unit = "hours"
def days_to_units(num_of_days):
return f"{num_of_days} days are {num_of_days * convert_to_units} {name_of_unit}"
my_var = days_to_units(20)
print(my_var) | [
"askhulal@gmail.com"
] | askhulal@gmail.com |
df455aaf0a36ceec480f5763e6838ea3caf2d09f | 1ab93f52d64e3f8c925f1f3d7495c90860ff04d6 | /users/migrations/0010_auto_20200810_2116.py | 89ba5f8fe8997e1008673d04ba18973bd1764f3d | [] | no_license | briankangmh/new | 4a823d44d0c54ff24bec86720b4b724ed27b30df | 8c1a868d17290cb6cca1161a0833b2207f7c696c | refs/heads/master | 2023-07-01T04:23:16.183674 | 2021-02-14T16:01:30 | 2021-02-14T16:01:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 474 | py | # Generated by Django 2.2.10 on 2020-08-10 15:46
from decimal import Decimal
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0009_auto_20200610_1922'),
]
operations = [
migrations.AlterField(
model_name='userprofileinfo',
name='wallet_balance',
field=models.DecimalField(decimal_places=2, default=Decimal('0.0'), max_digits=6),
),
]
| [
"navneetnivu07@gmail.com"
] | navneetnivu07@gmail.com |
db72d759572f3a6e470c8b488b827d75f75fd8e7 | 6f01d400ccae559e00499c923a1842be6e2b7c91 | /game/game/middlewares.py | 1abfe9d14b75459fefe5cbb94a2119cac1ec4d14 | [] | no_license | panghupy/17173- | a17c47f1d409575a4644c5945116c92b5f07f47e | 1236f844e20613679c40fff705272ba995a0799e | refs/heads/master | 2020-03-25T10:12:56.833939 | 2018-08-06T06:50:58 | 2018-08-06T06:50:58 | 143,687,442 | 7 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,593 | py | # -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
class GameSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(self, response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.
# Should return None or raise an exception.
return None
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, dict or Item objects.
for i in result:
yield i
def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.
# Should return either None or an iterable of Response, dict
# or Item objects.
pass
def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesn’t have a response associated.
# Must return only requests (not items).
for r in start_requests:
yield r
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
class GameDownloaderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None
def process_response(self, request, response, spider):
# Called with the response returned from the downloader.
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
| [
"15166396925@163.com"
] | 15166396925@163.com |
88401a331ee45c507049db8674c322ac25606c39 | 00f522bfc5b0a93da6018845ab79374815f3068d | /news/models.py | 1cec958aa9a32b21f767e9c3f8ed4b1158de4673 | [] | no_license | AbduXalim/news | 0dd4da68e86cda6adb886b0670e2e5d812ebcb42 | e41bccfdbf6c4c661f825a62b989b2cfa0e92ffd | refs/heads/main | 2023-08-31T20:54:09.739878 | 2021-10-24T18:24:33 | 2021-10-24T18:24:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 180 | py | from django.db import models
class Post(models.Model):
title = models.CharField(max_length=150)
text = models.TextField()
def __str__(self):
return self.title | [
"khalim.5052@gmail.com"
] | khalim.5052@gmail.com |
9b91b53619610988e6d250b034efe7da5a146e21 | 1c3ca7f5aa4ec1541af2636fc8c6aac68e5f0308 | /etc/console.py | f80841af8bd9cdeeef842cda7de33b56b16fcb80 | [] | no_license | DanielWeitzenfeld/three-seven-six | 3fbdba14d31d5cbb58464395fea62fc9653ef169 | 88305a1f1be9e8c2e818da7f0a262274f7e5b1f5 | refs/heads/master | 2020-05-31T17:05:41.546526 | 2014-10-03T03:02:11 | 2014-10-03T03:02:11 | 24,245,472 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 966 | py | import os
original_startup = os.environ.get('THREE_SEVEN_SIX_ORIGINAL_PYTHONSTARTUP')
if original_startup:
execfile(original_startup)
import warnings
warnings.filterwarnings('ignore')
import logging
from pprint import pprint
import pandas as pd
from datetime import datetime
import three_seven_six
from three_seven_six.models import *
from three_seven_six.dbs import mysql
from three_seven_six import bbalref_scraper
from sqlalchemy.orm import contains_eager, joinedload, subqueryload
session = mysql.Session()
logging.basicConfig()
log = logging.getLogger('sqlalchemy.engine')
log.setLevel(logging.INFO)
def turn_on_log():
global log
log.setLevel(logging.INFO)
def turn_off_log():
global log
log.setLevel(logging.WARN)
def fetch_player(player):
p = session.query(Player).filter(Player.player == player).one()
return p
def fetch_by_key(key):
p = session.query(Player).filter(Player.player_key == key).one()
return p | [
"dweitzenfeld@gmail.com"
] | dweitzenfeld@gmail.com |
aee081f84f4cfd1ec700a2dcd6667125a7860bca | 3f6ff3fb43903c06ed8f4d6ea45fcf2e0e6dd406 | /glo/BlackPearl/stationbase/vision/Detection.py | 0a839cdf4fc224b439f405280453d52edfe3e8dc | [] | no_license | jmprovencher/Treasure-Picker-Robot | 83a84d094e4612df8b38c0bb82f0240b98c74fe5 | f0a4fe7e3f4cc7b652566230bea830a4ab04a4c9 | refs/heads/master | 2020-12-11T03:54:00.090223 | 2016-04-18T02:53:01 | 2016-04-18T02:53:01 | 49,666,046 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 449 | py | import cv2
class Detection:
def __init__(self, image, numeroTable):
self.imageCamera = image
self.numeroTable = numeroTable
def trouverCentre(self, contourForme):
MatriceCentreMasse = cv2.moments(contourForme)
centre_x = int(round(MatriceCentreMasse['m10'] / MatriceCentreMasse['m00']))
centre_y = int(round(MatriceCentreMasse['m01'] / MatriceCentreMasse['m00']))
return centre_x, centre_y
| [
"sebastien.garvin@gmail.com"
] | sebastien.garvin@gmail.com |
f2af5535627397e48d5f726ea1decea49c6eb2ec | c82bbdd616d043a74812c136a4c6c927b5d1beaf | /Système_random.py | 5d37a4df0522dab59653d3355640285c5b1348c5 | [] | no_license | CyrilRPG/Test-discord.py | 5e0dee9b14213b2c6cd89c890cd6b5ffc74fee22 | 7f9dbe87a4a4304265a973014cde8ced9bf36489 | refs/heads/master | 2020-04-10T19:30:34.340168 | 2018-12-11T19:32:21 | 2018-12-11T19:32:21 | 161,237,555 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,552 | py | #-------Création d'un bot discord en python avec Cyril : Jeu aléatoire !
#--------------------------Importation des modules----------------
#------------------------------------------------------------
import discord
import random
#------------------------------------------------------------
nexus = discord.Client() #On appelle le bot Nexus ^^
#Système de jeu
#-------------------------------------------------------------
@nexus.event
async def on_message(message): #On lit un message que l'on va indiquer
if message.author == nexus.user:
return
if message.content.startswith('.play'):
await nexus.send_message(message.channel, 'Choisis un nombre entre 1 et 10')
def guess_check(m):
return m.content.isdigit()
guess = await nexus.wait_for_message(timeout=5.0, author=message.author, check=guess_check)
answer = random.randint(1, 10)
if guess is None:
fmt = "Désolé, vous avez pris trop de temps. C'était {}."
await nexus.send_message(message.channel, fmt.format(answer))
return
if int(guess.content) == answer:
await nexus.send_message(message.channel, 'Tu as raison !')
else:
await nexus.send_message(message.channel, "Désolé. C'est en fait {}.".format(answer))
@nexus.event
async def on_ready():
print("Connecté en tant que : ", nexus.user.name)
print("ID : ", nexus.user.name)
#On définit le message de connexion
nexus.run("Token")
| [
"noreply@github.com"
] | noreply@github.com |
06a049cddec948aa575fb610476d3c0283618784 | a46d3b261147ed38af57b4905a2bf5aaca74616f | /server/serve_videodemo.py | 83ac50e51958c9688f5182af503893e7fa4a63b9 | [] | no_license | ResidentMario/cnn-cifar10 | 0e1cd9192492c86300faeb922389c2d07bc432ca | 32565392ffc34349f49b4886e714c1a52dd6099c | refs/heads/master | 2023-08-20T15:22:12.616090 | 2021-10-19T22:30:51 | 2021-10-19T22:30:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,653 | py | import torch
from torch import nn
import torchvision
import numpy as np
import base64
from PIL import Image
import io
from spell.serving import BasePredictor
# Inlining the model definition in the server code for simplicity. In a production setting, we
# recommend creating a model module and importing that instead.
class CIFAR10Model(nn.Module):
def __init__(
self,
conv1_filters=32, conv1_dropout=0.25,
conv2_filters=64, conv2_dropout=0.25,
dense_layer=512, dense_dropout=0.5
):
super().__init__()
self.cnn_block_1 = nn.Sequential(*[
nn.Conv2d(3, conv1_filters, 3, padding=1),
nn.ReLU(),
nn.Conv2d(conv1_filters, conv2_filters, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2),
nn.Dropout(conv1_dropout)
])
self.cnn_block_2 = nn.Sequential(*[
nn.Conv2d(conv2_filters, conv2_filters, 3, padding=1),
nn.ReLU(),
nn.Conv2d(conv2_filters, conv2_filters, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2),
nn.Dropout(conv2_dropout)
])
self.flatten = lambda inp: torch.flatten(inp, 1)
self.head = nn.Sequential(*[
nn.Linear(conv2_filters * 8 * 8, dense_layer),
nn.ReLU(),
nn.Dropout(dense_dropout),
nn.Linear(dense_layer, 10)
])
def forward(self, X):
X = self.cnn_block_1(X)
X = self.cnn_block_2(X)
X = self.flatten(X)
X = self.head(X)
return X
class Predictor(BasePredictor):
def __init__(self):
self.clf = CIFAR10Model()
self.clf.load_state_dict(torch.load("/model/models/checkpoints/epoch_10.pth", map_location="cpu"))
self.clf.eval()
self.transform_test = torchvision.transforms.Compose([
torchvision.transforms.Resize((32, 32)),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
])
self.labels = ['Airplane', 'Automobile', 'Bird', 'Cat', 'Deer', 'Dog', 'Frog', 'Horse', 'Ship', 'Truck']
def predict(self, payload):
img = base64.b64decode(payload['image'])
img = Image.open(io.BytesIO(img), formats=[payload['format']])
img_tensor = self.transform_test(img)
# batch_size=1
img_tensor_batch = img_tensor[np.newaxis]
scores = self.clf(img_tensor_batch)
class_match_idx = scores.argmax()
class_match = self.labels[class_match_idx]
return {'class': class_match}
| [
"demouser@Kevins-MacBook-Pro.local"
] | demouser@Kevins-MacBook-Pro.local |
73ebae05c0e4ff482d88a84db54732c2b429ff32 | 87756be133c7d825883e96b6b7368a405872dd90 | /scripts/relate_thiessen_to_bioregions.py | 35cad29808c2cc4ae9db48f7a7b6ae42208101d9 | [
"BSD-3-Clause"
] | permissive | WuNL/locus | b51f028fc409e1a6a5538edc35838f41c1fd9830 | 0d85af2050fc00cfe0d92cea771480cee2c25702 | refs/heads/master | 2020-12-25T23:47:33.114235 | 2014-11-17T20:25:15 | 2014-11-17T20:25:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 450 | py | from django.core.management import setup_environ
import os
import sys
sys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'locus')))
import settings
setup_environ(settings)
from fbapp.models import ThiessenPolygon, GeneratedBioregion
for gb in GeneratedBioregion.objects.all():
name = int(gb.name)
print name
tp = ThiessenPolygon.objects.get(base_id=name)
gb.thiessen = tp
gb.save() | [
"rhodges@ecotrust.org"
] | rhodges@ecotrust.org |
a3f96162e166e04aa924d86d2183051caf02be55 | 6ab8538e9eab8335cf15479d47500d5341fef536 | /IMDB web scraper/fileRenamer.py | 886df1a2492f5c269b0d39be9c0800cdb195bb74 | [] | no_license | ggutierrezdieck/Python-scripts | 08e58df082abf621f65545d905ac981fe197bb0c | 757a47146111c9eb0e04c5255bed074d0ec5aa83 | refs/heads/master | 2021-03-30T10:01:13.860663 | 2020-05-05T17:59:34 | 2020-05-05T17:59:34 | 248,041,548 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,417 | py | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 17 15:19:10 2020
@author: Gerardo
Script uses data sraped from scraper to
rename files on specified directory
"""
import os
import string
from scraper import imdbScraper
#TODO: check seaon indexes are givern in right order
s = imdbScraper('https://www.imdb.com/title/tt1442437/episodes',11,12)
#print(s.getData())
path = r'C:\Users\Gerardo\Personal\Media\Shows\Modern Family\Season 11'
filePrefix = 'Modern Family S'
#Valid chars to use in file names
validChars = "-_.,()&!' %s%s" % (string.ascii_letters, string.digits)
titles = s.getData()
i = 0
for filename in os.listdir(path):
print(os.path.isdir(filename))
print(filename)
#TODO: check indexError whenthere is a directory inside the folder
if not os.path.isdir(filename):
#Creates file name with specified prefix, and removes unwanted characters from the data downloaded
newName = filePrefix + ''.join(c for c in titles[i] if c in validChars)
oldName = filename
filename , fileExtension = os.path.splitext(filename)
# dst = path + "\\" + dst
#print(fileExtension)
# # rename() function will
# # rename all the files
#os.rename( path + "\\" + oldName, path + "\\" + newName + fileExtension)
print("Rename file " + oldName + " to " + newName + fileExtension + " ?")
i += 1 | [
"ggutierrezdieck@gmail.com"
] | ggutierrezdieck@gmail.com |
512b79677cc6d53107b828c9ee04c381c8a4f6b8 | 29ee344bc2b0958fb7e8ff5f71959e12d14f68dd | /binary_tree.py | 73b4211db50d49d9db4ca4845aed8defc9fc6c59 | [] | no_license | sukurcf/DSA_old | e58b643a0000e5aae16bf891950c87da78226e59 | 122b45b5149c85a12c59f68bab7771a2ff868d1e | refs/heads/master | 2023-03-30T00:15:54.964910 | 2021-04-03T12:17:21 | 2021-04-03T12:17:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,415 | py | class BinarySearchTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def add_child(self, data):
if data == self.data:
return
elif data < self.data:
if self.left:
self.left.add_child(data)
else:
self.left = BinarySearchTreeNode(data)
else:
if self.right:
self.right.add_child(data)
else:
self.right = BinarySearchTreeNode(data)
def inorder_traversal(self):
elements = []
if self.left:
elements += self.left.inorder_traversal()
elements.append(self.data)
if self.right:
elements += self.right.inorder_traversal()
return elements
def preorder_traversal(self):
elements = [self.data]
if self.left:
elements += self.left.preorder_traversal()
if self.right:
elements += self.right.preorder_traversal()
return elements
def postorder_traversal(self):
elements = []
if self.left:
elements += self.left.postorder_traversal()
if self.right:
elements += self.right.postorder_traversal()
elements.append(self.data)
return elements
def search(self, data):
if data == self.data:
return True
if data < self.data:
if self.left:
return self.left.search(data)
else:
return False
elif data > self.data:
if self.right:
return self.right.search(data)
else:
return False
def find_min(self):
if self.left is None:
return self.data
return self.left.find_min()
def find_max(self):
if self.right is None:
return self.data
return self.right.find_max()
def calculate_sum(self):
left_sum = self.left.calculate_sum() if self.left else 0
right_sum = self.right.calculate_sum() if self.right else 0
return left_sum + right_sum + self.data
def delete(self, data):
if data < self.data:
if self.left:
self.left = self.left.delete(data)
elif data > self.data:
if self.right:
self.right = self.right.delete(data)
else:
if self.left is None and self.right is None:
return None
if self.left is None:
return self.right
if self.right is None:
return self.right
min_val = self.right.find_min()
self.data = min_val
self.right = self.right.delete(min_val)
return self
def build_tree(elements):
root = BinarySearchTreeNode(elements[0])
for element in elements[1:]:
root.add_child(element)
return root
if __name__ == '__main__':
numbers = [17, 4, 1, 20, 9, 23, 18, 34]
numbers_tree = build_tree(numbers)
print(numbers_tree.search(1))
print(numbers_tree.search(20))
print(numbers_tree.find_min())
print(numbers_tree.find_max())
print(numbers_tree.calculate_sum())
print(sum(numbers))
print(numbers_tree.inorder_traversal())
numbers_tree.delete(20)
numbers_tree.delete(4)
print(numbers_tree.inorder_traversal())
| [
"sukurcf@gmail.com"
] | sukurcf@gmail.com |
5970ad2abd6066e8c1306089a4496fdc713f1347 | e6548bd30f1e446869d662aa5d4f4e51f3562336 | /player/modifier_env.py | 47014ccfd8a66deda98c5c24e9c8ea88c56c7238 | [
"MIT"
] | permissive | Saevon/webdnd | acfb39fd36ca740b5d16fccb1c0ba9c374dfb37b | 4dd5d30ae105ede51bbd92bf5281a6965b7d55f4 | refs/heads/master | 2020-05-17T09:08:51.995778 | 2015-05-23T00:02:46 | 2015-05-23T00:02:46 | 1,882,009 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 639 | py |
# Isolates the user's code
MODIFIERS_ENV = '''
def mod(character):
# Allowed imports that the user will has access to
from collections import defaultdict
if (%(cond)s):
%(mod)s
'''
# TODO indent multiline codes
def modifier(modifier, default):
mod = None
try:
code = MODIFIERS_ENV % {
'mod': '\n'.join(map(lambda l: ' ' * 8 + l, modifier.modifier.split('\n'))),
'cond': modifier.condition if modifier.condition else 'True',
}
exec(code)
return mod
except BaseException as err:
# TODO better error handling
print err
return default
| [
"blastowind@gmail.com"
] | blastowind@gmail.com |
c4609b4e73003cd4ff46d873f10ebd2f3055589c | 009f3c640ab7b8e5eb1b7fc901ba9caeef67bf38 | /Loan Management/Loan/Management/views.py | 9ad5c6771f27eeaa80b9097150a303d97a35718d | [] | no_license | hussain-mohammed/Tasks | aec82198be0785f97f722093bae01968601b4719 | 3557465f6a5ad63f054b5a3ca875b226603edfc4 | refs/heads/master | 2022-09-09T23:06:08.332789 | 2020-01-11T05:18:36 | 2020-01-11T05:18:36 | 214,174,666 | 1 | 0 | null | 2022-08-30T11:00:48 | 2019-10-10T12:17:00 | Python | UTF-8 | Python | false | false | 4,928 | py | from django.contrib import auth
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from .serializer import UserSerializer, ProfileSerializer, DisplaySerializer, LoanDetailSerializer, StatusSerializer, \
ForeclosureSerializer,LoanlistSerializer
from .models import Profile, LoanDetail
# Create your views here.
class register(APIView):
serializer_class = UserSerializer
def post(self, request):
if request.method == 'POST':
data = request.data
serializer = UserSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class profile(APIView):
permission_classes = (permissions.IsAuthenticated,)
def get(self, request):
data = Profile.objects.filter(user=self.request.user)
try:
status = LoanDetail.objects.filter(user=self.request.user).values('STATUS').order_by('-date')[0]
except:
status = LoanDetail.objects.filter(user=self.request.user).values('STATUS').order_by('-date')
serializer = DisplaySerializer(data, many=True)
status_serializer = StatusSerializer(status, many=True)
response = serializer.data + status_serializer.data
if len(response) >= 2:
return Response(serializer.data + [status])
else:
return Response(serializer.data + ['LOAN IS AVAILABLE. YOU CAN AVAIL USING BELOW FORMS'])
def post(self, request):
try:
statusinstance = LoanDetail.objects.filter(user=self.request.user).values('STATUS').order_by('-date')[0]
loanstatuslist = ['Available','Rejected','Foreclosed','Disbursed','Defaulter']
if statusinstance['STATUS'] in loanstatuslist:
postCall = profile.loanapply(self,request)
elif statusinstance['STATUS'] == 'Approved':
postCall = profile.loanclosure(self,request)
else:
return Response('Please wait!!!! Your Documents are being validated...',status=status.HTTP_400_BAD_REQUEST)
except IndexError as e:
postCall = profile.loanapply(self,request)
return postCall
def loanapply(self, request):
data = request.data
serializer = LoanDetailSerializer(data=data)
if serializer.is_valid():
# serializer.save()
LoanDetail.objects.create(user=self.request.user,
amount=data['amount'],
duration=data['duration'],
STATUS='Pending'
)
return Response(serializer.data,status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE)
def loanclosure(self,request):
data = request.data
loanduration = LoanDetail.objects.filter(user=self.request.user).values('duration').order_by('-date')[0]
try:
serializer = ForeclosureSerializer(data=data)
if serializer.is_valid:
# # for changing status from Approved to Closed
loaninstance = LoanDetail.objects.filter(user=self.request.user).order_by('-date')[0]
# calculating the amount that customer has to pay
days = data.get('days', None)
amount = LoanDetail.objects.filter(user=self.request.user).values('amount').order_by('-date')[0]
one_day = ((0.06 / 100) * int(amount['amount']))
pay = amount['amount'] + (one_day * int(days))
if data.get('days') < loanduration['duration']:
loaninstance.STATUS = 'Foreclosed'
elif data.get('days') == loanduration['duration']:
loaninstance.STATUS = 'Disbursed'
else:
loaninstance.STATUS = 'Defaulter'
loaninstance.returnedIN = days
loaninstance.amountPaid = pay
loaninstance.save()
return Response("You Need To Pay " + str(pay) + "-----------------------Your Loan Is closed with the status of " +loaninstance.STATUS)
return Response("ERROR ENTERING DATA")
except TypeError as e:
return Response("days field is required",status=status.HTTP_406_NOT_ACCEPTABLE)
class Detail(APIView):
permission_classes = (permissions.IsAuthenticated,)
def get(self, request):
data = LoanDetail.objects.filter(user=self.request.user)
serializer = LoanlistSerializer(data, many=True)
return Response(serializer.data)
| [
"mohammed.hussain@fissionlabs.com"
] | mohammed.hussain@fissionlabs.com |
6baa75859da9119851b4c6adfc501d072f6dcab7 | de0a4650b26be18826a2ef3fa5a7c05bdb733d30 | /PredictView.py | 5315dc1160f161704f4d40091ed23ba44cb84704 | [] | no_license | Githubowy-Juliusz/SI-Projekt | fd9db2e1c0fa551f1256c468f9cb3db6e0b8f812 | 966c7260674544ad23096b658a9850ba357ad437 | refs/heads/master | 2022-08-26T04:50:04.235248 | 2020-05-26T10:23:57 | 2020-05-26T10:23:57 | 265,535,468 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,850 | py | from PyQt5 import QtCore, QtGui, QtWidgets
import numpy as np
import random
class PredictView(object):
def setupUi(self, MainWindow, predictions):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(600, 622)
self.central_widget = QtWidgets.QWidget(MainWindow)
self.central_widget.setObjectName("central_widget")
self.next_button = QtWidgets.QPushButton(self.central_widget)
self.next_button.setGeometry(QtCore.QRect(330, 470, 250, 35))
self.next_button.setObjectName("next_button")
self.return_button = QtWidgets.QPushButton(self.central_widget)
self.return_button.setGeometry(QtCore.QRect(175, 520, 250, 35))
self.return_button.setAutoRepeatDelay(304)
self.return_button.setObjectName("return_button")
self.previous_button = QtWidgets.QPushButton(self.central_widget)
self.previous_button.setGeometry(QtCore.QRect(20, 470, 250, 35))
self.previous_button.setObjectName("previous_button")
self.image_label = QtWidgets.QLabel(self.central_widget)
self.image_label.setGeometry(QtCore.QRect(10, 20, 580, 380))
self.image_label.setText("")
self.image_label.setObjectName("image_label")
self.prediction_label = QtWidgets.QLabel(self.central_widget)
self.prediction_label.setGeometry(QtCore.QRect(20, 420, 560, 30))
self.prediction_label.setAlignment(QtCore.Qt.AlignCenter)
self.prediction_label.setObjectName("prediction_label")
MainWindow.setCentralWidget(self.central_widget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
#
self.next_button.clicked.connect(self.next_image)
self.previous_button.clicked.connect(self.previous_image)
self.return_button.clicked.connect(self.return_to_main_view)
self.image_label.setScaledContents(True)
self.parent = MainWindow
self.predictions = predictions
self.image_index = 0
image = self.numpyQImage(self.predictions[self.image_index][0])
image = QtGui.QPixmap.fromImage(image)
description = self.description() + self.predictions[self.image_index][1]
self.image_label.setPixmap(image)
self.prediction_label.setText(description)
self.previous_button.setDisabled(True)
if len(self.predictions) == 1:
self.next_button.setDisabled(True)
#
QtCore.QMetaObject.connectSlotsByName(self.parent)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.next_button.setText(_translate("MainWindow", "Następny"))
self.return_button.setText(_translate("MainWindow", "Powrót"))
self.previous_button.setText(_translate("MainWindow", "Poprzedni"))
self.prediction_label.setText(_translate("MainWindow", "To pewnie"))
def description(self):
rand = random.randint(1, 4)
if rand == 1:
return "To pewnie: "
if rand == 2:
return "To chyba: "
if rand == 3:
return "Wygląda na: "
return "Prawdopodobnie to: "
def numpyQImage(self, image):
qImg = QtGui.QImage()
if image.dtype == np.uint8:
if len(image.shape) == 2:
channels = 1
height, width = image.shape
bytesPerLine = channels * width
qImg = QtGui.QImage(
image.data, width, height, bytesPerLine, QtGui.QImage.Format_Indexed8
)
qImg.setColorTable([QtGui.qRgb(i, i, i) for i in range(256)])
elif len(image.shape) == 3:
if image.shape[2] == 3:
height, width, channels = image.shape
bytesPerLine = channels * width
qImg = QtGui.QImage(
image.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888
)
elif image.shape[2] == 4:
height, width, channels = image.shape
bytesPerLine = channels * width
fmt = QtGui.QImage.Format_ARGB32
qImg = QtGui.QImage(
image.data, width, height, bytesPerLine, fmt
)
return qImg
def next_image(self):
print("next_image")
self.previous_button.setDisabled(False)
self.image_index += 1
image = self.numpyQImage(self.predictions[self.image_index][0])
image = QtGui.QPixmap.fromImage(image)
description = self.description() + self.predictions[self.image_index][1]
self.image_label.setPixmap(image)
self.prediction_label.setText(description)
if self.image_index >= len(self.predictions) - 1:
self.next_button.setDisabled(True)
def previous_image(self):
print("previous_image")
self.next_button.setDisabled(False)
self.image_index -= 1
image = self.numpyQImage(self.predictions[self.image_index][0])
image = QtGui.QPixmap.fromImage(image)
description = self.description() + self.predictions[self.image_index][1]
self.image_label.setPixmap(image)
self.prediction_label.setText(description)
if self.image_index == 0:
self.previous_button.setDisabled(True)
def return_to_main_view(self):
print("return_to_main_view")
self.parent.show_main_view() | [
"githubowy-juliusz@wp.pl"
] | githubowy-juliusz@wp.pl |
8972d88b74539a835067f0bbb4c298a83f1c92d6 | 8b87bacd1a433807c07cfb39fb718d31bac5c416 | /MIT python course/Ass 3/hw3.py | cdff423ad7d5d16e4a3d835e19c89af1ff5e9ce2 | [] | no_license | rvcjavaboy/eitra | 643d9fd9377f878ff786c997e477e97a3d15bfc1 | cd8c7cd74361e4ca345a084f7b85f78b024e60af | refs/heads/master | 2021-01-16T19:57:18.101471 | 2017-11-13T19:55:25 | 2017-11-13T19:55:25 | 100,191,146 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,870 | py | '''
Author: Ranjit Chavan
Date : 8 Aug 2017
'''
#--------------------------------------------- Exercise 3.1-----------------------------------------------------
def list_intersection(a,b):
c = []
for elem in a:
if elem in b:
c.append(elem)
return c
list_intersection([2, 3], [3, 3, 3, 2, 10])
list_intersection([2, 4, 6], [1, 3, 5])
# ---------------------------------------- Exercise 3.2 ----------------------------------------------
import math
def ball_collide(ball1, ball2):
distance = math.sqrt((ball1[0]-ball2[0])**2+(ball1[1]-ball2[1])**2)
return distance <= ball1[2] + ball2[2]
print ball_collide((0, 0, 1), (3, 3, 1)) # Should be False
print ball_collide((5, 5, 2), (2, 8, 3)) # Should be True
print ball_collide((7, 8, 2), (4, 4, 3)) # Should be True
#-------------------------------------- Exercise 3.3-------------------------------------------------
my_classes = {}
def add_class(class_num, desc):
return "Not Yet Implemented"
add_class('6.189', 'Introduction to Python')
def print_classes(course):
return "Not Yet Implemented"
#----------------------------------- Exercise 3.4-----------------------------
NAMES = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank',
'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry']
AGES = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]
def combine_lists(l1, l2):
comb_dict = {}
for i in range(len(l2)):
if l2[i] in comb_dict.keys():
comb_dict[l2[i]].append(l1[i])
else:
comb_dict[l2[i]] = [l1[i]]
return comb_dict
combined_dict = combine_lists(NAMES, AGES)
def people(age):
if age in combined_dict.keys():
return combined_dict[age]
else:
return []
# Test Cases for Exercise 3.4 (all should be True)
#print ('Dan' in people(18) and 'Cathy' in people(18))
#print ('Ed' in people(19) and 'Helen' in people(19) and\
# 'Irene' in people(19) and 'Jack' in people(19) and 'Larry'in people(19))
#print ('Alice' in people(20) and 'Frank' in people(20) and 'Gary' in people(20))
#print (people(21) == ['Bob'])
#print (people(22) == ['Kelly'])
#print (people(23) == [])
#-----------------------------------Exercise 3.5----------------------------------------------
def zellers(month, day, year):
months_dict = {"January":11,"February":12,"March":1,"April":2,"May":3,"June":4,"July":5,
"August":6,"September":7,"October":8,"November":9,"December":10}
A = months_dict[month]
B = day
C = year%100
D = year/100
if A > 10:
C=C-1
W = (13*A - 1)/5
X = C/4
Y = D/4
Z = W + X + Y + B + C - 2*D
R = Z%7
days_list= ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
return days_list[R]
print (zellers("March", 10, 1940) == "Sunday")
| [
"rvcinfo9600.com"
] | rvcinfo9600.com |
bbb074712cc9a9c9e029fc23002222f68bbe6a4b | b9c2c910c5ad41bc50d06a96be192f9aabae8f2d | /test_recipes.py | 8119e0c9f29af8dd5b1ef8bb940cc19b68a5a50c | [] | no_license | ehtishammalik/flaskAPI | 916f24d2af631b9b263438915ad37370cf5d312c | 426582350edc88eea6c1c8d7fd5dfb8d7e960915 | refs/heads/master | 2020-03-19T06:53:58.332916 | 2018-06-07T04:37:06 | 2018-06-07T04:37:06 | 136,064,876 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,089 | py | # test_bucketlist.py
import unittest
import os
import json
from app import create_app, db
class RecipesTestCase(unittest.TestCase):
"""This class represents the recipes test case"""
def setUp(self):
"""Define test variables and initialize app."""
self.app = create_app(config_name="testing")
self.client = self.app.test_client
self.recipe = {'name': 'Herby Pan-Seared Chicken'}
# binds the app to the current context
with self.app.app_context():
# create all tables
db.create_all()
def test_recipe_creation(self):
"""Test API can create a recipe (POST request)"""
res = self.client().post('/recipes/', data=self.recipe)
self.assertEqual(res.status_code, 201)
self.assertIn('Herby Pan-Seared', str(res.data))
def test_api_can_get_all_recipes(self):
"""Test API can get a recipes (GET request)."""
res = self.client().post('/recipes/', data=self.recipe)
self.assertEqual(res.status_code, 201)
res = self.client().get('/recipes/')
self.assertEqual(res.status_code, 200)
self.assertIn('Herby Pan-Seared', str(res.data))
def test_api_can_get_recipie_by_id(self):
"""Test API can get a single recipie by using it's id."""
rv = self.client().post('/recipes/', data=self.recipe)
self.assertEqual(rv.status_code, 201)
result_in_json = json.loads(rv.data.decode('utf-8').replace("'", "\""))
result = self.client().get(
'/recipes/{}'.format(result_in_json['id']))
self.assertEqual(result.status_code, 200)
self.assertIn('Herby Pan-Seared', str(result.data))
def test_recipe_can_be_edited(self):
"""Test API can edit an existing recipe. (PUT request)"""
rv = self.client().post(
'/recipes/',
data={'name': 'Test, Herby Pan-Seared Chicken'})
self.assertEqual(rv.status_code, 201)
rv = self.client().put(
'/recipes/1',
data={
"name": "Test recipe, Herby Pan-Seared Chicken "
})
self.assertEqual(rv.status_code, 200)
results = self.client().get('/recipes/1')
self.assertIn('Test recipe', str(results.data))
def test_recipe_deletion(self):
"""Test API can delete an existing recipe. (DELETE request)."""
rv = self.client().post(
'/recipes/',
data={'name': 'Test, Herby Pan-Seared Chicken'})
self.assertEqual(rv.status_code, 201)
res = self.client().delete('/recipes/1')
self.assertEqual(res.status_code, 200)
# Test to see if it exists, should return a 404
result = self.client().get('/recipes/1')
self.assertEqual(result.status_code, 404)
def tearDown(self):
"""teardown all initialized variables."""
with self.app.app_context():
# drop all tables
db.session.remove()
db.drop_all()
# Make the tests conveniently executable
if __name__ == "__main__":
unittest.main()
| [
"ehtisham2014@namal.edu.pk"
] | ehtisham2014@namal.edu.pk |
0014fee21c6de7bad486f03dc5345e6fd33a2f08 | 3f664b12b161a745dac15424aecfc8fec2cbe9c6 | /Implementatie/Uitvoering_ElGamal.py | 7b0cd11c8c22eb474aab5651079d7054b9a8d026 | [] | no_license | QuirijnMeijer/EKC | 30e11611b3878dd0b52793f072323185357a074e | 37fb276f961a93215caf2df1738fd5a5cd553ff6 | refs/heads/master | 2022-01-27T17:29:36.898749 | 2019-06-21T16:10:39 | 2019-06-21T16:10:39 | 37,132,805 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 694 | py | # --->
# Voor gebruik in IDLE (Windows):
# --->
import sys
import os
z = os.path.dirname(os.path.abspath(__file__))
sys.path.append(z)
# <---
# Samenvoeging klassen voor een demonstratie van het ElGamal systeem.
from ElliptischeKromme import *
from ElGamal import *
# Start van het script
K = ElliptischeKromme(5, 1, 23)
k = Punt(K, 0, 1)
C = Punt(K, 5, 6)
EG = ElGamal(K, k, C)
print(EG)
boodschap = input('\nVoer een boodschap bestaand uit enkel kleine letters en spaties in:\n')
c = EG.codeerBoodschap(boodschap)
print('\nDe boodschap "%s" is gecodeerd:\n%s' % (boodschap, EG.printCode(c)))
origineel = EG.decodeerBoodschap(c)
print('\nDe code is terugvertaald naar:\n%s' % (origineel))
| [
"Quir@live.nl"
] | Quir@live.nl |
1ecc874b213fc22f21d508f94489dafa53895c49 | bd74dc8476d75da1404745be2096959b56094589 | /front-end/node_modules/fsevents/build/config.gypi | 496727b745c3802046b782a1282ee7c4bdf0442f | [
"MIT"
] | permissive | schrius/user-story | f61635c33d18efdda7651634ee7ce433d23463cc | 0b75d4ee37eefde88e18b376eb256a3113bbbcc5 | refs/heads/master | 2023-02-07T21:50:37.988877 | 2020-04-03T15:45:25 | 2020-04-03T15:45:25 | 252,211,758 | 0 | 1 | null | 2023-01-24T01:53:10 | 2020-04-01T15:18:09 | JavaScript | UTF-8 | Python | false | false | 5,717 | gypi | # Do not edit. File was generated by node-gyp's "configure" step
{
"target_defaults": {
"cflags": [],
"default_configuration": "Release",
"defines": [],
"include_dirs": [],
"libraries": []
},
"variables": {
"asan": 0,
"build_v8_with_gn": "false",
"coverage": "false",
"debug_nghttp2": "false",
"enable_lto": "false",
"enable_pgo_generate": "false",
"enable_pgo_use": "false",
"force_dynamic_crt": 0,
"host_arch": "x64",
"icu_data_in": "../../deps/icu-small/source/data/in/icudt64l.dat",
"icu_endianness": "l",
"icu_gyp_path": "tools/icu/icu-generic.gyp",
"icu_locales": "en,root",
"icu_path": "deps/icu-small",
"icu_small": "true",
"icu_ver_major": "64",
"is_debug": 0,
"llvm_version": "0",
"napi_build_version": "5",
"node_byteorder": "little",
"node_code_cache": "yes",
"node_debug_lib": "false",
"node_enable_d8": "false",
"node_install_npm": "true",
"node_module_version": 72,
"node_no_browser_globals": "false",
"node_prefix": "/",
"node_release_urlbase": "https://nodejs.org/download/release/",
"node_report": "true",
"node_shared": "false",
"node_shared_cares": "false",
"node_shared_http_parser": "false",
"node_shared_libuv": "false",
"node_shared_nghttp2": "false",
"node_shared_openssl": "false",
"node_shared_zlib": "false",
"node_tag": "",
"node_target_type": "executable",
"node_use_bundled_v8": "true",
"node_use_dtrace": "true",
"node_use_etw": "false",
"node_use_large_pages": "false",
"node_use_large_pages_script_lld": "false",
"node_use_node_snapshot": "true",
"node_use_openssl": "true",
"node_use_v8_platform": "true",
"node_with_ltcg": "false",
"node_without_node_options": "false",
"openssl_fips": "",
"openssl_is_fips": "false",
"shlib_suffix": "72.dylib",
"target_arch": "x64",
"v8_enable_gdbjit": 0,
"v8_enable_i18n_support": 1,
"v8_enable_inspector": 1,
"v8_no_strict_aliasing": 1,
"v8_optimized_debug": 1,
"v8_promise_internal_field_count": 1,
"v8_random_seed": 0,
"v8_trace_maps": 0,
"v8_use_siphash": 1,
"v8_use_snapshot": 1,
"want_separate_host_toolset": 0,
"xcode_version": "8.0",
"nodedir": "/Users/Schrius/Library/Caches/node-gyp/12.13.0",
"standalone_static_library": 1,
"dry_run": "",
"legacy_bundling": "",
"save_dev": "",
"browser": "",
"commit_hooks": "true",
"only": "",
"viewer": "man",
"also": "",
"rollback": "true",
"sign_git_commit": "",
"audit": "true",
"usage": "",
"globalignorefile": "/Users/Schrius/.nvm/versions/node/v12.13.0/etc/npmignore",
"init_author_url": "",
"maxsockets": "50",
"shell": "/bin/zsh",
"metrics_registry": "https://registry.npmjs.org/",
"parseable": "",
"shrinkwrap": "true",
"init_license": "ISC",
"timing": "",
"if_present": "",
"cache_max": "Infinity",
"init_author_email": "",
"sign_git_tag": "",
"cert": "",
"git_tag_version": "true",
"local_address": "",
"long": "",
"preid": "",
"registry": "https://registry.npmjs.org/",
"fetch_retries": "2",
"noproxy": "",
"key": "",
"message": "%s",
"versions": "",
"globalconfig": "/Users/Schrius/.nvm/versions/node/v12.13.0/etc/npmrc",
"always_auth": "",
"logs_max": "10",
"prefer_online": "",
"cache_lock_retries": "10",
"global_style": "",
"update_notifier": "true",
"audit_level": "low",
"heading": "npm",
"fetch_retry_mintimeout": "10000",
"offline": "",
"read_only": "",
"searchlimit": "20",
"access": "",
"json": "",
"allow_same_version": "",
"description": "true",
"engine_strict": "",
"https_proxy": "",
"init_module": "/Users/Schrius/.npm-init.js",
"userconfig": "/Users/Schrius/.npmrc",
"cidr": "",
"node_version": "12.13.0",
"user": "501",
"save": "true",
"auth_type": "legacy",
"editor": "vi",
"ignore_prepublish": "",
"script_shell": "",
"tag": "latest",
"before": "",
"global": "",
"progress": "true",
"ham_it_up": "",
"optional": "true",
"searchstaleness": "900",
"bin_links": "true",
"force": "",
"save_prod": "",
"searchopts": "",
"depth": "Infinity",
"node_gyp": "/Users/Schrius/.nvm/versions/node/v12.13.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js",
"rebuild_bundle": "true",
"sso_poll_frequency": "500",
"unicode": "true",
"fetch_retry_maxtimeout": "60000",
"ca": "",
"save_prefix": "^",
"scripts_prepend_node_path": "warn-only",
"sso_type": "oauth",
"strict_ssl": "true",
"tag_version_prefix": "v",
"dev": "",
"fetch_retry_factor": "10",
"group": "20",
"save_exact": "",
"cache_lock_stale": "60000",
"prefer_offline": "",
"version": "",
"cache_min": "10",
"otp": "",
"cache": "/Users/Schrius/.npm",
"searchexclude": "",
"color": "true",
"package_lock": "true",
"package_lock_only": "",
"save_optional": "",
"user_agent": "npm/6.12.0 node/v12.13.0 darwin x64",
"ignore_scripts": "",
"cache_lock_wait": "10000",
"production": "",
"save_bundle": "",
"send_metrics": "",
"init_version": "1.0.0",
"node_options": "",
"umask": "0022",
"scope": "",
"git": "git",
"init_author_name": "",
"onload_script": "",
"tmp": "/var/folders/9t/g0bc6bgj29q1pc8qf6vs8cc40000gn/T",
"unsafe_perm": "true",
"format_package_lock": "true",
"link": "",
"prefix": "/Users/Schrius/.nvm/versions/node/v12.13.0"
}
}
| [
"schriusty@gmail.com"
] | schriusty@gmail.com |
e183cd7b1b121ae5dfe37e403c15da9fee7f5a95 | 7ad167ae4be07c95081708d8b2434f8ce92a1345 | /Search/JumpSearch.py | 097d1271e1f18a1d5281bf0417fce938290d8e84 | [] | no_license | faiderfl/algorithms | 92b895c2a3910f2ff844c6181c58f4837034c22f | 638b2199975e80db846dbba044b30381185d8e7f | refs/heads/main | 2023-05-30T20:13:08.029047 | 2021-06-03T17:19:32 | 2021-06-03T17:19:32 | 354,863,354 | 0 | 0 | null | 2021-04-05T15:23:20 | 2021-04-05T14:33:21 | Python | UTF-8 | Python | false | false | 1,001 | py |
import math
def jumpSearch( arr , x , n ):
# Finding block size to be jumped
step = math.sqrt(n)
# Finding the block where element is
# present (if it is present)
prev = 0
while arr[int(min(step, n)-1)] < x:
prev = step
step += math.sqrt(n)
if prev >= n:
return -1
# Doing a linear search for x in
# block beginning with prev.
while arr[int(prev)] < x:
prev += 1
# If we reached next block or end
# of array, element is not present.
if prev == min(step, n):
return -1
# If element is found
if arr[int(prev)] == x:
return prev
return -1
# Driver code to test function
arr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 ]
x = 55
n = len(arr)
# Find the index of 'x' using Jump Search
index = jumpSearch(arr, x, n)
# Print the index where 'x' is located
print("Number" , x, "is at index" ,"%.0f"%index) | [
"faiderfl@outlook.com"
] | faiderfl@outlook.com |
f36723a15842f15e3d2ae8f3717c4311c4c80c77 | 1958fbff3c73d51642d383218db0765f865bb8a2 | /venv/bin/epylint | de3d6b68cbe56327a09f3e42992c5cb513471f04 | [] | no_license | amanzap2610/blog | b429f84ea752a86042c2f2b339d3a605c9c424ac | 4cd6a7a669275cb929783b9e8419470f875f96cd | refs/heads/master | 2022-06-13T06:21:42.442044 | 2020-05-08T06:38:15 | 2020-05-08T06:38:15 | 262,039,801 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 259 | #!/home/zapbuild/Desktop/dream_blog-master/venv/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from pylint import run_epylint
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(run_epylint())
| [
"amansaxena.zapbuild@gmail.com"
] | amansaxena.zapbuild@gmail.com | |
788d74a0541595cac3c54e408e4d3d2a423cdc26 | 4b157ab5270ba430a6d7c1594ea41ceea89b7ab2 | /dataview/items/management/commands/dbimport.py | 202892882682d5ee3d0dae54641cf1e52de4ef88 | [
"MIT"
] | permissive | estin/pomp-craigslist-example | 6a06e0671b189b45d7f688583c052b3e23efd010 | c019686776ff2235f92ece9cea19874631a561b9 | refs/heads/master | 2021-01-10T12:07:30.035957 | 2017-11-21T19:55:40 | 2017-11-21T19:55:40 | 52,002,919 | 38 | 8 | null | null | null | null | UTF-8 | Python | false | false | 2,019 | py | import logging
from django.db import transaction
from django.core.management.base import BaseCommand
from django.core.exceptions import ValidationError
from dataview.items.models import CraigsListItem
from craigslist.pipeline import KafkaPipeline
from craigslist.utils import get_statsd_client, METRIC_ITEMS_IMPORTED_KEY
log = logging.getLogger('dataview.dbimport')
class Command(BaseCommand):
help = 'import data from kafka to db'
def handle(self, *args, **options):
try:
self._handle(*args, **options)
except Exception:
log.exception("Exception")
def _handle(self, *args, **options):
statsd = get_statsd_client(sync=True)
def _items_factory(items):
for item in items:
instance = CraigsListItem(**dict(
# convert dict byte keys to string keys and use it as
# keywords
(k.decode(), v) for k, v in item.items()
))
# validate data before insert
try:
instance.full_clean()
except ValidationError as e:
log.debug('Invalid data(%s): %s', e, dict(item))
else:
yield instance
@transaction.atomic()
def do_bulk_insert(items):
cleaned_items = list(_items_factory(items))
if cleaned_items:
CraigsListItem.objects.bulk_create(cleaned_items)
return cleaned_items
log.debug(
'Start import data from kafka',
)
for items in KafkaPipeline.dump_data(
timeout=500, poll_timeout=5000, enable_auto_commit=True):
if items:
imported = do_bulk_insert(items)
log.debug(
'Successfully imported %s from %s',
len(imported), len(items),
)
statsd.incr(METRIC_ITEMS_IMPORTED_KEY, value=len(imported))
| [
"tatarkin.evg@gmail.com"
] | tatarkin.evg@gmail.com |
b4729aeb7d1d1ca7fc8785b02f4a3190a9ebce0b | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /build/android/pylib/chrome_test_server_spawner.py | e1eb6b384f6e6a1e0bc2403273b1358a03e5acb7 | [
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | Python | false | false | 16,082 | py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A "Test Server Spawner" that handles killing/stopping per-test test servers.
It's used to accept requests from the device to spawn and kill instances of the
chrome test server on the host.
"""
# pylint: disable=W0702
import BaseHTTPServer
import json
import logging
import os
import select
import struct
import subprocess
import sys
import threading
import time
import urlparse
from devil.android import forwarder
from devil.android import ports
from pylib import constants
from pylib.constants import host_paths
# Path that are needed to import necessary modules when launching a testserver.
os.environ['PYTHONPATH'] = os.environ.get('PYTHONPATH', '') + (':%s:%s:%s:%s:%s'
% (os.path.join(host_paths.DIR_SOURCE_ROOT, 'third_party'),
os.path.join(host_paths.DIR_SOURCE_ROOT, 'third_party', 'tlslite'),
os.path.join(host_paths.DIR_SOURCE_ROOT, 'third_party', 'pyftpdlib',
'src'),
os.path.join(host_paths.DIR_SOURCE_ROOT, 'net', 'tools', 'testserver'),
os.path.join(host_paths.DIR_SOURCE_ROOT, 'components', 'sync', 'tools',
'testserver')))
SERVER_TYPES = {
'http': '',
'ftp': '-f',
'sync': '', # Sync uses its own script, and doesn't take a server type arg.
'tcpecho': '--tcp-echo',
'udpecho': '--udp-echo',
}
# The timeout (in seconds) of starting up the Python test server.
TEST_SERVER_STARTUP_TIMEOUT = 10
def _WaitUntil(predicate, max_attempts=5):
"""Blocks until the provided predicate (function) is true.
Returns:
Whether the provided predicate was satisfied once (before the timeout).
"""
sleep_time_sec = 0.025
for _ in xrange(1, max_attempts):
if predicate():
return True
time.sleep(sleep_time_sec)
sleep_time_sec = min(1, sleep_time_sec * 2) # Don't wait more than 1 sec.
return False
def _CheckPortAvailable(port):
"""Returns True if |port| is available."""
return _WaitUntil(lambda: ports.IsHostPortAvailable(port))
def _CheckPortNotAvailable(port):
"""Returns True if |port| is not available."""
return _WaitUntil(lambda: not ports.IsHostPortAvailable(port))
def _CheckDevicePortStatus(device, port):
"""Returns whether the provided port is used."""
return _WaitUntil(lambda: ports.IsDevicePortUsed(device, port))
def _GetServerTypeCommandLine(server_type):
"""Returns the command-line by the given server type.
Args:
server_type: the server type to be used (e.g. 'http').
Returns:
A string containing the command-line argument.
"""
if server_type not in SERVER_TYPES:
raise NotImplementedError('Unknown server type: %s' % server_type)
if server_type == 'udpecho':
raise Exception('Please do not run UDP echo tests because we do not have '
'a UDP forwarder tool.')
return SERVER_TYPES[server_type]
class TestServerThread(threading.Thread):
"""A thread to run the test server in a separate process."""
def __init__(self, ready_event, arguments, device, tool):
"""Initialize TestServerThread with the following argument.
Args:
ready_event: event which will be set when the test server is ready.
arguments: dictionary of arguments to run the test server.
device: An instance of DeviceUtils.
tool: instance of runtime error detection tool.
"""
threading.Thread.__init__(self)
self.wait_event = threading.Event()
self.stop_flag = False
self.ready_event = ready_event
self.ready_event.clear()
self.arguments = arguments
self.device = device
self.tool = tool
self.test_server_process = None
self.is_ready = False
self.host_port = self.arguments['port']
assert isinstance(self.host_port, int)
# The forwarder device port now is dynamically allocated.
self.forwarder_device_port = 0
# Anonymous pipe in order to get port info from test server.
self.pipe_in = None
self.pipe_out = None
self.process = None
self.command_line = []
def _WaitToStartAndGetPortFromTestServer(self):
"""Waits for the Python test server to start and gets the port it is using.
The port information is passed by the Python test server with a pipe given
by self.pipe_out. It is written as a result to |self.host_port|.
Returns:
Whether the port used by the test server was successfully fetched.
"""
assert self.host_port == 0 and self.pipe_out and self.pipe_in
(in_fds, _, _) = select.select([self.pipe_in, ], [], [],
TEST_SERVER_STARTUP_TIMEOUT)
if len(in_fds) == 0:
logging.error('Failed to wait to the Python test server to be started.')
return False
# First read the data length as an unsigned 4-byte value. This
# is _not_ using network byte ordering since the Python test server packs
# size as native byte order and all Chromium platforms so far are
# configured to use little-endian.
# TODO(jnd): Change the Python test server and local_test_server_*.cc to
# use a unified byte order (either big-endian or little-endian).
data_length = os.read(self.pipe_in, struct.calcsize('=L'))
if data_length:
(data_length,) = struct.unpack('=L', data_length)
assert data_length
if not data_length:
logging.error('Failed to get length of server data.')
return False
port_json = os.read(self.pipe_in, data_length)
if not port_json:
logging.error('Failed to get server data.')
return False
logging.info('Got port json data: %s', port_json)
port_json = json.loads(port_json)
if port_json.has_key('port') and isinstance(port_json['port'], int):
self.host_port = port_json['port']
return _CheckPortNotAvailable(self.host_port)
logging.error('Failed to get port information from the server data.')
return False
def _GenerateCommandLineArguments(self):
"""Generates the command line to run the test server.
Note that all options are processed by following the definitions in
testserver.py.
"""
if self.command_line:
return
args_copy = dict(self.arguments)
# Translate the server type.
type_cmd = _GetServerTypeCommandLine(args_copy.pop('server-type'))
if type_cmd:
self.command_line.append(type_cmd)
# Use a pipe to get the port given by the instance of Python test server
# if the test does not specify the port.
assert self.host_port == args_copy['port']
if self.host_port == 0:
(self.pipe_in, self.pipe_out) = os.pipe()
self.command_line.append('--startup-pipe=%d' % self.pipe_out)
# Pass the remaining arguments as-is.
for key, values in args_copy.iteritems():
if not isinstance(values, list):
values = [values]
for value in values:
if value is None:
self.command_line.append('--%s' % key)
else:
self.command_line.append('--%s=%s' % (key, value))
def _CloseUnnecessaryFDsForTestServerProcess(self):
# This is required to avoid subtle deadlocks that could be caused by the
# test server child process inheriting undesirable file descriptors such as
# file lock file descriptors.
for fd in xrange(0, 1024):
if fd != self.pipe_out:
try:
os.close(fd)
except:
pass
def run(self):
logging.info('Start running the thread!')
self.wait_event.clear()
self._GenerateCommandLineArguments()
command = host_paths.DIR_SOURCE_ROOT
if self.arguments['server-type'] == 'sync':
command = [os.path.join(command, 'components', 'sync', 'tools',
'testserver',
'sync_testserver.py')] + self.command_line
else:
command = [os.path.join(command, 'net', 'tools', 'testserver',
'testserver.py')] + self.command_line
logging.info('Running: %s', command)
# Disable PYTHONUNBUFFERED because it has a bad interaction with the
# testserver. Remove once this interaction is fixed.
unbuf = os.environ.pop('PYTHONUNBUFFERED', None)
# Pass DIR_SOURCE_ROOT as the child's working directory so that relative
# paths in the arguments are resolved correctly.
self.process = subprocess.Popen(
command, preexec_fn=self._CloseUnnecessaryFDsForTestServerProcess,
cwd=host_paths.DIR_SOURCE_ROOT)
if unbuf:
os.environ['PYTHONUNBUFFERED'] = unbuf
if self.process:
if self.pipe_out:
self.is_ready = self._WaitToStartAndGetPortFromTestServer()
else:
self.is_ready = _CheckPortNotAvailable(self.host_port)
if self.is_ready:
forwarder.Forwarder.Map([(0, self.host_port)], self.device, self.tool)
# Check whether the forwarder is ready on the device.
self.is_ready = False
device_port = forwarder.Forwarder.DevicePortForHostPort(self.host_port)
if device_port and _CheckDevicePortStatus(self.device, device_port):
self.is_ready = True
self.forwarder_device_port = device_port
# Wake up the request handler thread.
self.ready_event.set()
# Keep thread running until Stop() gets called.
_WaitUntil(lambda: self.stop_flag, max_attempts=sys.maxint)
if self.process.poll() is None:
self.process.kill()
forwarder.Forwarder.UnmapDevicePort(self.forwarder_device_port, self.device)
self.process = None
self.is_ready = False
if self.pipe_out:
os.close(self.pipe_in)
os.close(self.pipe_out)
self.pipe_in = None
self.pipe_out = None
logging.info('Test-server has died.')
self.wait_event.set()
def Stop(self):
"""Blocks until the loop has finished.
Note that this must be called in another thread.
"""
if not self.process:
return
self.stop_flag = True
self.wait_event.wait()
class SpawningServerRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""A handler used to process http GET/POST request."""
def _SendResponse(self, response_code, response_reason, additional_headers,
contents):
"""Generates a response sent to the client from the provided parameters.
Args:
response_code: number of the response status.
response_reason: string of reason description of the response.
additional_headers: dict of additional headers. Each key is the name of
the header, each value is the content of the header.
contents: string of the contents we want to send to client.
"""
self.send_response(response_code, response_reason)
self.send_header('Content-Type', 'text/html')
# Specify the content-length as without it the http(s) response will not
# be completed properly (and the browser keeps expecting data).
self.send_header('Content-Length', len(contents))
for header_name in additional_headers:
self.send_header(header_name, additional_headers[header_name])
self.end_headers()
self.wfile.write(contents)
self.wfile.flush()
def _StartTestServer(self):
"""Starts the test server thread."""
logging.info('Handling request to spawn a test server.')
content_type = self.headers.getheader('content-type')
if content_type != 'application/json':
raise Exception('Bad content-type for start request.')
content_length = self.headers.getheader('content-length')
if not content_length:
content_length = 0
try:
content_length = int(content_length)
except:
raise Exception('Bad content-length for start request.')
logging.info(content_length)
test_server_argument_json = self.rfile.read(content_length)
logging.info(test_server_argument_json)
assert not self.server.test_server_instance
ready_event = threading.Event()
self.server.test_server_instance = TestServerThread(
ready_event,
json.loads(test_server_argument_json),
self.server.device,
self.server.tool)
self.server.test_server_instance.setDaemon(True)
self.server.test_server_instance.start()
ready_event.wait()
if self.server.test_server_instance.is_ready:
self._SendResponse(200, 'OK', {}, json.dumps(
{'port': self.server.test_server_instance.forwarder_device_port,
'message': 'started'}))
logging.info('Test server is running on port: %d.',
self.server.test_server_instance.host_port)
else:
self.server.test_server_instance.Stop()
self.server.test_server_instance = None
self._SendResponse(500, 'Test Server Error.', {}, '')
logging.info('Encounter problem during starting a test server.')
def _KillTestServer(self):
"""Stops the test server instance."""
# There should only ever be one test server at a time. This may do the
# wrong thing if we try and start multiple test servers.
if not self.server.test_server_instance:
return
port = self.server.test_server_instance.host_port
logging.info('Handling request to kill a test server on port: %d.', port)
self.server.test_server_instance.Stop()
# Make sure the status of test server is correct before sending response.
if _CheckPortAvailable(port):
self._SendResponse(200, 'OK', {}, 'killed')
logging.info('Test server on port %d is killed', port)
else:
self._SendResponse(500, 'Test Server Error.', {}, '')
logging.info('Encounter problem during killing a test server.')
self.server.test_server_instance = None
def do_POST(self):
parsed_path = urlparse.urlparse(self.path)
action = parsed_path.path
logging.info('Action for POST method is: %s.', action)
if action == '/start':
self._StartTestServer()
else:
self._SendResponse(400, 'Unknown request.', {}, '')
logging.info('Encounter unknown request: %s.', action)
def do_GET(self):
parsed_path = urlparse.urlparse(self.path)
action = parsed_path.path
params = urlparse.parse_qs(parsed_path.query, keep_blank_values=1)
logging.info('Action for GET method is: %s.', action)
for param in params:
logging.info('%s=%s', param, params[param][0])
if action == '/kill':
self._KillTestServer()
elif action == '/ping':
# The ping handler is used to check whether the spawner server is ready
# to serve the requests. We don't need to test the status of the test
# server when handling ping request.
self._SendResponse(200, 'OK', {}, 'ready')
logging.info('Handled ping request and sent response.')
else:
self._SendResponse(400, 'Unknown request', {}, '')
logging.info('Encounter unknown request: %s.', action)
class SpawningServer(object):
"""The class used to start/stop a http server."""
def __init__(self, test_server_spawner_port, device, tool):
logging.info('Creating new spawner on port: %d.', test_server_spawner_port)
self.server = BaseHTTPServer.HTTPServer(('', test_server_spawner_port),
SpawningServerRequestHandler)
self.server.device = device
self.server.tool = tool
self.server.test_server_instance = None
self.server.build_type = constants.GetBuildType()
def _Listen(self):
logging.info('Starting test server spawner')
self.server.serve_forever()
def Start(self):
"""Starts the test server spawner."""
listener_thread = threading.Thread(target=self._Listen)
listener_thread.setDaemon(True)
listener_thread.start()
def Stop(self):
"""Stops the test server spawner.
Also cleans the server state.
"""
self.CleanupState()
self.server.shutdown()
def CleanupState(self):
"""Cleans up the spawning server state.
This should be called if the test server spawner is reused,
to avoid sharing the test server instance.
"""
if self.server.test_server_instance:
self.server.test_server_instance.Stop()
self.server.test_server_instance = None
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
88af1e1775d6df77735796278e0cad9c7dbd9207 | 00af09f4ac6f98203910d86c3791c152184ace9a | /Lib/tkinter/test/test_tkinter/test_geometry_managers.py | 83e658877ea3b79863275502589704f07f9cc287 | [] | no_license | orf53975/CarnosOS | 621d641df02d742a2452fde2f28a28c74b32695a | d06849064e4e9f30ef901ad8cf90960e1bec0805 | refs/heads/master | 2023-03-24T08:06:48.274566 | 2017-01-05T16:41:01 | 2017-01-05T16:41:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 122,987 | py | <<<<<<< HEAD
<<<<<<< HEAD
import unittest
import re
import tkinter
from tkinter import TclError
from test.support import requires
from tkinter.test.support import pixels_conv, tcl_version, requires_tcl
from tkinter.test.widget_tests import AbstractWidgetTest
requires('gui')
class PackTest(AbstractWidgetTest, unittest.TestCase):
def create2(self):
pack = tkinter.Toplevel(self.root, name='pack')
pack.wm_geometry('300x200+0+0')
pack.wm_minsize(1, 1)
a = tkinter.Frame(pack, name='a', width=20, height=40, bg='red')
b = tkinter.Frame(pack, name='b', width=50, height=30, bg='blue')
c = tkinter.Frame(pack, name='c', width=80, height=80, bg='green')
d = tkinter.Frame(pack, name='d', width=40, height=30, bg='yellow')
return pack, a, b, c, d
def test_pack_configure_after(self):
pack, a, b, c, d = self.create2()
with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % b):
a.pack_configure(after=b)
with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'):
a.pack_configure(after='.foo')
a.pack_configure(side='top')
b.pack_configure(side='top')
c.pack_configure(side='top')
d.pack_configure(side='top')
self.assertEqual(pack.pack_slaves(), [a, b, c, d])
a.pack_configure(after=b)
self.assertEqual(pack.pack_slaves(), [b, a, c, d])
a.pack_configure(after=a)
self.assertEqual(pack.pack_slaves(), [b, a, c, d])
def test_pack_configure_anchor(self):
pack, a, b, c, d = self.create2()
def check(anchor, geom):
a.pack_configure(side='top', ipadx=5, padx=10, ipady=15, pady=20,
expand=True, anchor=anchor)
self.root.update()
self.assertEqual(a.winfo_geometry(), geom)
check('n', '30x70+135+20')
check('ne', '30x70+260+20')
check('e', '30x70+260+65')
check('se', '30x70+260+110')
check('s', '30x70+135+110')
check('sw', '30x70+10+110')
check('w', '30x70+10+65')
check('nw', '30x70+10+20')
check('center', '30x70+135+65')
def test_pack_configure_before(self):
pack, a, b, c, d = self.create2()
with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % b):
a.pack_configure(before=b)
with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'):
a.pack_configure(before='.foo')
a.pack_configure(side='top')
b.pack_configure(side='top')
c.pack_configure(side='top')
d.pack_configure(side='top')
self.assertEqual(pack.pack_slaves(), [a, b, c, d])
a.pack_configure(before=d)
self.assertEqual(pack.pack_slaves(), [b, c, a, d])
a.pack_configure(before=a)
self.assertEqual(pack.pack_slaves(), [b, c, a, d])
def test_pack_configure_expand(self):
pack, a, b, c, d = self.create2()
def check(*geoms):
self.root.update()
self.assertEqual(a.winfo_geometry(), geoms[0])
self.assertEqual(b.winfo_geometry(), geoms[1])
self.assertEqual(c.winfo_geometry(), geoms[2])
self.assertEqual(d.winfo_geometry(), geoms[3])
a.pack_configure(side='left')
b.pack_configure(side='top')
c.pack_configure(side='right')
d.pack_configure(side='bottom')
check('20x40+0+80', '50x30+135+0', '80x80+220+75', '40x30+100+170')
a.pack_configure(side='left', expand='yes')
b.pack_configure(side='top', expand='on')
c.pack_configure(side='right', expand=True)
d.pack_configure(side='bottom', expand=1)
check('20x40+40+80', '50x30+175+35', '80x80+180+110', '40x30+100+135')
a.pack_configure(side='left', expand='yes', fill='both')
b.pack_configure(side='top', expand='on', fill='both')
c.pack_configure(side='right', expand=True, fill='both')
d.pack_configure(side='bottom', expand=1, fill='both')
check('100x200+0+0', '200x100+100+0', '160x100+140+100', '40x100+100+100')
def test_pack_configure_in(self):
pack, a, b, c, d = self.create2()
a.pack_configure(side='top')
b.pack_configure(side='top')
c.pack_configure(side='top')
d.pack_configure(side='top')
a.pack_configure(in_=pack)
self.assertEqual(pack.pack_slaves(), [b, c, d, a])
a.pack_configure(in_=c)
self.assertEqual(pack.pack_slaves(), [b, c, d])
self.assertEqual(c.pack_slaves(), [a])
with self.assertRaisesRegex(TclError,
'can\'t pack %s inside itself' % (a,)):
a.pack_configure(in_=a)
with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'):
a.pack_configure(in_='.foo')
def test_pack_configure_padx_ipadx_fill(self):
pack, a, b, c, d = self.create2()
def check(geom1, geom2, **kwargs):
a.pack_forget()
b.pack_forget()
a.pack_configure(**kwargs)
b.pack_configure(expand=True, fill='both')
self.root.update()
self.assertEqual(a.winfo_geometry(), geom1)
self.assertEqual(b.winfo_geometry(), geom2)
check('20x40+260+80', '240x200+0+0', side='right', padx=20)
check('20x40+250+80', '240x200+0+0', side='right', padx=(10, 30))
check('60x40+240+80', '240x200+0+0', side='right', ipadx=20)
check('30x40+260+80', '250x200+0+0', side='right', ipadx=5, padx=10)
check('20x40+260+80', '240x200+0+0', side='right', padx=20, fill='x')
check('20x40+249+80', '240x200+0+0',
side='right', padx=(9, 31), fill='x')
check('60x40+240+80', '240x200+0+0', side='right', ipadx=20, fill='x')
check('30x40+260+80', '250x200+0+0',
side='right', ipadx=5, padx=10, fill='x')
check('30x40+255+80', '250x200+0+0',
side='right', ipadx=5, padx=(5, 15), fill='x')
check('20x40+140+0', '300x160+0+40', side='top', padx=20)
check('20x40+120+0', '300x160+0+40', side='top', padx=(0, 40))
check('60x40+120+0', '300x160+0+40', side='top', ipadx=20)
check('30x40+135+0', '300x160+0+40', side='top', ipadx=5, padx=10)
check('30x40+130+0', '300x160+0+40', side='top', ipadx=5, padx=(5, 15))
check('260x40+20+0', '300x160+0+40', side='top', padx=20, fill='x')
check('260x40+25+0', '300x160+0+40',
side='top', padx=(25, 15), fill='x')
check('300x40+0+0', '300x160+0+40', side='top', ipadx=20, fill='x')
check('280x40+10+0', '300x160+0+40',
side='top', ipadx=5, padx=10, fill='x')
check('280x40+5+0', '300x160+0+40',
side='top', ipadx=5, padx=(5, 15), fill='x')
a.pack_configure(padx='1c')
self.assertEqual(a.pack_info()['padx'],
self._str(pack.winfo_pixels('1c')))
a.pack_configure(ipadx='1c')
self.assertEqual(a.pack_info()['ipadx'],
self._str(pack.winfo_pixels('1c')))
def test_pack_configure_pady_ipady_fill(self):
pack, a, b, c, d = self.create2()
def check(geom1, geom2, **kwargs):
a.pack_forget()
b.pack_forget()
a.pack_configure(**kwargs)
b.pack_configure(expand=True, fill='both')
self.root.update()
self.assertEqual(a.winfo_geometry(), geom1)
self.assertEqual(b.winfo_geometry(), geom2)
check('20x40+280+80', '280x200+0+0', side='right', pady=20)
check('20x40+280+70', '280x200+0+0', side='right', pady=(10, 30))
check('20x80+280+60', '280x200+0+0', side='right', ipady=20)
check('20x50+280+75', '280x200+0+0', side='right', ipady=5, pady=10)
check('20x40+280+80', '280x200+0+0', side='right', pady=20, fill='x')
check('20x40+280+69', '280x200+0+0',
side='right', pady=(9, 31), fill='x')
check('20x80+280+60', '280x200+0+0', side='right', ipady=20, fill='x')
check('20x50+280+75', '280x200+0+0',
side='right', ipady=5, pady=10, fill='x')
check('20x50+280+70', '280x200+0+0',
side='right', ipady=5, pady=(5, 15), fill='x')
check('20x40+140+20', '300x120+0+80', side='top', pady=20)
check('20x40+140+0', '300x120+0+80', side='top', pady=(0, 40))
check('20x80+140+0', '300x120+0+80', side='top', ipady=20)
check('20x50+140+10', '300x130+0+70', side='top', ipady=5, pady=10)
check('20x50+140+5', '300x130+0+70', side='top', ipady=5, pady=(5, 15))
check('300x40+0+20', '300x120+0+80', side='top', pady=20, fill='x')
check('300x40+0+25', '300x120+0+80',
side='top', pady=(25, 15), fill='x')
check('300x80+0+0', '300x120+0+80', side='top', ipady=20, fill='x')
check('300x50+0+10', '300x130+0+70',
side='top', ipady=5, pady=10, fill='x')
check('300x50+0+5', '300x130+0+70',
side='top', ipady=5, pady=(5, 15), fill='x')
a.pack_configure(pady='1c')
self.assertEqual(a.pack_info()['pady'],
self._str(pack.winfo_pixels('1c')))
a.pack_configure(ipady='1c')
self.assertEqual(a.pack_info()['ipady'],
self._str(pack.winfo_pixels('1c')))
def test_pack_configure_side(self):
pack, a, b, c, d = self.create2()
def check(side, geom1, geom2):
a.pack_configure(side=side)
self.assertEqual(a.pack_info()['side'], side)
b.pack_configure(expand=True, fill='both')
self.root.update()
self.assertEqual(a.winfo_geometry(), geom1)
self.assertEqual(b.winfo_geometry(), geom2)
check('top', '20x40+140+0', '300x160+0+40')
check('bottom', '20x40+140+160', '300x160+0+0')
check('left', '20x40+0+80', '280x200+20+0')
check('right', '20x40+280+80', '280x200+0+0')
def test_pack_forget(self):
pack, a, b, c, d = self.create2()
a.pack_configure()
b.pack_configure()
c.pack_configure()
self.assertEqual(pack.pack_slaves(), [a, b, c])
b.pack_forget()
self.assertEqual(pack.pack_slaves(), [a, c])
b.pack_forget()
self.assertEqual(pack.pack_slaves(), [a, c])
d.pack_forget()
def test_pack_info(self):
pack, a, b, c, d = self.create2()
with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % a):
a.pack_info()
a.pack_configure()
b.pack_configure(side='right', in_=a, anchor='s', expand=True, fill='x',
ipadx=5, padx=10, ipady=2, pady=(5, 15))
info = a.pack_info()
self.assertIsInstance(info, dict)
self.assertEqual(info['anchor'], 'center')
self.assertEqual(info['expand'], self._str(0))
self.assertEqual(info['fill'], 'none')
self.assertEqual(info['in'], pack)
self.assertEqual(info['ipadx'], self._str(0))
self.assertEqual(info['ipady'], self._str(0))
self.assertEqual(info['padx'], self._str(0))
self.assertEqual(info['pady'], self._str(0))
self.assertEqual(info['side'], 'top')
info = b.pack_info()
self.assertIsInstance(info, dict)
self.assertEqual(info['anchor'], 's')
self.assertEqual(info['expand'], self._str(1))
self.assertEqual(info['fill'], 'x')
self.assertEqual(info['in'], a)
self.assertEqual(info['ipadx'], self._str(5))
self.assertEqual(info['ipady'], self._str(2))
self.assertEqual(info['padx'], self._str(10))
self.assertEqual(info['pady'], self._str((5, 15)))
self.assertEqual(info['side'], 'right')
def test_pack_propagate(self):
pack, a, b, c, d = self.create2()
pack.configure(width=300, height=200)
a.pack_configure()
pack.pack_propagate(False)
self.root.update()
self.assertEqual(pack.winfo_reqwidth(), 300)
self.assertEqual(pack.winfo_reqheight(), 200)
pack.pack_propagate(True)
self.root.update()
self.assertEqual(pack.winfo_reqwidth(), 20)
self.assertEqual(pack.winfo_reqheight(), 40)
def test_pack_slaves(self):
pack, a, b, c, d = self.create2()
self.assertEqual(pack.pack_slaves(), [])
a.pack_configure()
self.assertEqual(pack.pack_slaves(), [a])
b.pack_configure()
self.assertEqual(pack.pack_slaves(), [a, b])
class PlaceTest(AbstractWidgetTest, unittest.TestCase):
def create2(self):
t = tkinter.Toplevel(self.root, width=300, height=200, bd=0)
t.wm_geometry('300x200+0+0')
f = tkinter.Frame(t, width=154, height=84, bd=2, relief='raised')
f.place_configure(x=48, y=38)
f2 = tkinter.Frame(t, width=30, height=60, bd=2, relief='raised')
self.root.update()
return t, f, f2
def test_place_configure_in(self):
t, f, f2 = self.create2()
self.assertEqual(f2.winfo_manager(), '')
with self.assertRaisesRegex(TclError, "can't place %s relative to "
"itself" % re.escape(str(f2))):
f2.place_configure(in_=f2)
if tcl_version >= (8, 5):
self.assertEqual(f2.winfo_manager(), '')
with self.assertRaisesRegex(TclError, 'bad window path name'):
f2.place_configure(in_='spam')
f2.place_configure(in_=f)
self.assertEqual(f2.winfo_manager(), 'place')
def test_place_configure_x(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f)
self.assertEqual(f2.place_info()['x'], '0')
self.root.update()
self.assertEqual(f2.winfo_x(), 50)
f2.place_configure(x=100)
self.assertEqual(f2.place_info()['x'], '100')
self.root.update()
self.assertEqual(f2.winfo_x(), 150)
f2.place_configure(x=-10, relx=1)
self.assertEqual(f2.place_info()['x'], '-10')
self.root.update()
self.assertEqual(f2.winfo_x(), 190)
with self.assertRaisesRegex(TclError, 'bad screen distance "spam"'):
f2.place_configure(in_=f, x='spam')
def test_place_configure_y(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f)
self.assertEqual(f2.place_info()['y'], '0')
self.root.update()
self.assertEqual(f2.winfo_y(), 40)
f2.place_configure(y=50)
self.assertEqual(f2.place_info()['y'], '50')
self.root.update()
self.assertEqual(f2.winfo_y(), 90)
f2.place_configure(y=-10, rely=1)
self.assertEqual(f2.place_info()['y'], '-10')
self.root.update()
self.assertEqual(f2.winfo_y(), 110)
with self.assertRaisesRegex(TclError, 'bad screen distance "spam"'):
f2.place_configure(in_=f, y='spam')
def test_place_configure_relx(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f)
self.assertEqual(f2.place_info()['relx'], '0')
self.root.update()
self.assertEqual(f2.winfo_x(), 50)
f2.place_configure(relx=0.5)
self.assertEqual(f2.place_info()['relx'], '0.5')
self.root.update()
self.assertEqual(f2.winfo_x(), 125)
f2.place_configure(relx=1)
self.assertEqual(f2.place_info()['relx'], '1')
self.root.update()
self.assertEqual(f2.winfo_x(), 200)
with self.assertRaisesRegex(TclError, 'expected floating-point number '
'but got "spam"'):
f2.place_configure(in_=f, relx='spam')
def test_place_configure_rely(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f)
self.assertEqual(f2.place_info()['rely'], '0')
self.root.update()
self.assertEqual(f2.winfo_y(), 40)
f2.place_configure(rely=0.5)
self.assertEqual(f2.place_info()['rely'], '0.5')
self.root.update()
self.assertEqual(f2.winfo_y(), 80)
f2.place_configure(rely=1)
self.assertEqual(f2.place_info()['rely'], '1')
self.root.update()
self.assertEqual(f2.winfo_y(), 120)
with self.assertRaisesRegex(TclError, 'expected floating-point number '
'but got "spam"'):
f2.place_configure(in_=f, rely='spam')
def test_place_configure_anchor(self):
f = tkinter.Frame(self.root)
with self.assertRaisesRegex(TclError, 'bad anchor "j"'):
f.place_configure(anchor='j')
with self.assertRaisesRegex(TclError, 'ambiguous anchor ""'):
f.place_configure(anchor='')
for value in 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center':
f.place_configure(anchor=value)
self.assertEqual(f.place_info()['anchor'], value)
def test_place_configure_width(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, width=120)
self.root.update()
self.assertEqual(f2.winfo_width(), 120)
f2.place_configure(width='')
self.root.update()
self.assertEqual(f2.winfo_width(), 30)
with self.assertRaisesRegex(TclError, 'bad screen distance "abcd"'):
f2.place_configure(width='abcd')
def test_place_configure_height(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, height=120)
self.root.update()
self.assertEqual(f2.winfo_height(), 120)
f2.place_configure(height='')
self.root.update()
self.assertEqual(f2.winfo_height(), 60)
with self.assertRaisesRegex(TclError, 'bad screen distance "abcd"'):
f2.place_configure(height='abcd')
def test_place_configure_relwidth(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, relwidth=0.5)
self.root.update()
self.assertEqual(f2.winfo_width(), 75)
f2.place_configure(relwidth='')
self.root.update()
self.assertEqual(f2.winfo_width(), 30)
with self.assertRaisesRegex(TclError, 'expected floating-point number '
'but got "abcd"'):
f2.place_configure(relwidth='abcd')
def test_place_configure_relheight(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, relheight=0.5)
self.root.update()
self.assertEqual(f2.winfo_height(), 40)
f2.place_configure(relheight='')
self.root.update()
self.assertEqual(f2.winfo_height(), 60)
with self.assertRaisesRegex(TclError, 'expected floating-point number '
'but got "abcd"'):
f2.place_configure(relheight='abcd')
def test_place_configure_bordermode(self):
f = tkinter.Frame(self.root)
with self.assertRaisesRegex(TclError, 'bad bordermode "j"'):
f.place_configure(bordermode='j')
with self.assertRaisesRegex(TclError, 'ambiguous bordermode ""'):
f.place_configure(bordermode='')
for value in 'inside', 'outside', 'ignore':
f.place_configure(bordermode=value)
self.assertEqual(f.place_info()['bordermode'], value)
def test_place_forget(self):
foo = tkinter.Frame(self.root)
foo.place_configure(width=50, height=50)
self.root.update()
foo.place_forget()
self.root.update()
self.assertFalse(foo.winfo_ismapped())
with self.assertRaises(TypeError):
foo.place_forget(0)
def test_place_info(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, x=1, y=2, width=3, height=4,
relx=0.1, rely=0.2, relwidth=0.3, relheight=0.4,
anchor='se', bordermode='outside')
info = f2.place_info()
self.assertIsInstance(info, dict)
self.assertEqual(info['x'], '1')
self.assertEqual(info['y'], '2')
self.assertEqual(info['width'], '3')
self.assertEqual(info['height'], '4')
self.assertEqual(info['relx'], '0.1')
self.assertEqual(info['rely'], '0.2')
self.assertEqual(info['relwidth'], '0.3')
self.assertEqual(info['relheight'], '0.4')
self.assertEqual(info['anchor'], 'se')
self.assertEqual(info['bordermode'], 'outside')
self.assertEqual(info['x'], '1')
self.assertEqual(info['x'], '1')
with self.assertRaises(TypeError):
f2.place_info(0)
def test_place_slaves(self):
foo = tkinter.Frame(self.root)
bar = tkinter.Frame(self.root)
self.assertEqual(foo.place_slaves(), [])
bar.place_configure(in_=foo)
self.assertEqual(foo.place_slaves(), [bar])
with self.assertRaises(TypeError):
foo.place_slaves(0)
class GridTest(AbstractWidgetTest, unittest.TestCase):
def tearDown(self):
cols, rows = self.root.grid_size()
for i in range(cols + 1):
self.root.grid_columnconfigure(i, weight=0, minsize=0, pad=0, uniform='')
for i in range(rows + 1):
self.root.grid_rowconfigure(i, weight=0, minsize=0, pad=0, uniform='')
self.root.grid_propagate(1)
if tcl_version >= (8, 5):
self.root.grid_anchor('nw')
super().tearDown()
def test_grid_configure(self):
b = tkinter.Button(self.root)
self.assertEqual(b.grid_info(), {})
b.grid_configure()
self.assertEqual(b.grid_info()['in'], self.root)
self.assertEqual(b.grid_info()['column'], self._str(0))
self.assertEqual(b.grid_info()['row'], self._str(0))
b.grid_configure({'column': 1}, row=2)
self.assertEqual(b.grid_info()['column'], self._str(1))
self.assertEqual(b.grid_info()['row'], self._str(2))
def test_grid_configure_column(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad column value "-1": '
'must be a non-negative integer'):
b.grid_configure(column=-1)
b.grid_configure(column=2)
self.assertEqual(b.grid_info()['column'], self._str(2))
def test_grid_configure_columnspan(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad columnspan value "0": '
'must be a positive integer'):
b.grid_configure(columnspan=0)
b.grid_configure(columnspan=2)
self.assertEqual(b.grid_info()['columnspan'], self._str(2))
def test_grid_configure_in(self):
f = tkinter.Frame(self.root)
b = tkinter.Button(self.root)
self.assertEqual(b.grid_info(), {})
b.grid_configure()
self.assertEqual(b.grid_info()['in'], self.root)
b.grid_configure(in_=f)
self.assertEqual(b.grid_info()['in'], f)
b.grid_configure({'in': self.root})
self.assertEqual(b.grid_info()['in'], self.root)
def test_grid_configure_ipadx(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad ipadx value "-1": '
'must be positive screen distance'):
b.grid_configure(ipadx=-1)
b.grid_configure(ipadx=1)
self.assertEqual(b.grid_info()['ipadx'], self._str(1))
b.grid_configure(ipadx='.5c')
self.assertEqual(b.grid_info()['ipadx'],
self._str(round(pixels_conv('.5c') * self.scaling)))
def test_grid_configure_ipady(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad ipady value "-1": '
'must be positive screen distance'):
b.grid_configure(ipady=-1)
b.grid_configure(ipady=1)
self.assertEqual(b.grid_info()['ipady'], self._str(1))
b.grid_configure(ipady='.5c')
self.assertEqual(b.grid_info()['ipady'],
self._str(round(pixels_conv('.5c') * self.scaling)))
def test_grid_configure_padx(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad pad value "-1": '
'must be positive screen distance'):
b.grid_configure(padx=-1)
b.grid_configure(padx=1)
self.assertEqual(b.grid_info()['padx'], self._str(1))
b.grid_configure(padx=(10, 5))
self.assertEqual(b.grid_info()['padx'], self._str((10, 5)))
b.grid_configure(padx='.5c')
self.assertEqual(b.grid_info()['padx'],
self._str(round(pixels_conv('.5c') * self.scaling)))
def test_grid_configure_pady(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad pad value "-1": '
'must be positive screen distance'):
b.grid_configure(pady=-1)
b.grid_configure(pady=1)
self.assertEqual(b.grid_info()['pady'], self._str(1))
b.grid_configure(pady=(10, 5))
self.assertEqual(b.grid_info()['pady'], self._str((10, 5)))
b.grid_configure(pady='.5c')
self.assertEqual(b.grid_info()['pady'],
self._str(round(pixels_conv('.5c') * self.scaling)))
def test_grid_configure_row(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad (row|grid) value "-1": '
'must be a non-negative integer'):
b.grid_configure(row=-1)
b.grid_configure(row=2)
self.assertEqual(b.grid_info()['row'], self._str(2))
def test_grid_configure_rownspan(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad rowspan value "0": '
'must be a positive integer'):
b.grid_configure(rowspan=0)
b.grid_configure(rowspan=2)
self.assertEqual(b.grid_info()['rowspan'], self._str(2))
def test_grid_configure_sticky(self):
f = tkinter.Frame(self.root, bg='red')
with self.assertRaisesRegex(TclError, 'bad stickyness value "glue"'):
f.grid_configure(sticky='glue')
f.grid_configure(sticky='ne')
self.assertEqual(f.grid_info()['sticky'], 'ne')
f.grid_configure(sticky='n,s,e,w')
self.assertEqual(f.grid_info()['sticky'], 'nesw')
def test_grid_columnconfigure(self):
with self.assertRaises(TypeError):
self.root.grid_columnconfigure()
self.assertEqual(self.root.grid_columnconfigure(0),
{'minsize': 0, 'pad': 0, 'uniform': None, 'weight': 0})
with self.assertRaisesRegex(TclError, 'bad option "-foo"'):
self.root.grid_columnconfigure(0, 'foo')
self.root.grid_columnconfigure((0, 3), weight=2)
with self.assertRaisesRegex(TclError,
'must specify a single element on retrieval'):
self.root.grid_columnconfigure((0, 3))
b = tkinter.Button(self.root)
b.grid_configure(column=0, row=0)
if tcl_version >= (8, 5):
self.root.grid_columnconfigure('all', weight=3)
with self.assertRaisesRegex(TclError, 'expected integer but got "all"'):
self.root.grid_columnconfigure('all')
self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 3)
self.assertEqual(self.root.grid_columnconfigure(3, 'weight'), 2)
self.assertEqual(self.root.grid_columnconfigure(265, 'weight'), 0)
if tcl_version >= (8, 5):
self.root.grid_columnconfigure(b, weight=4)
self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 4)
def test_grid_columnconfigure_minsize(self):
with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'):
self.root.grid_columnconfigure(0, minsize='foo')
self.root.grid_columnconfigure(0, minsize=10)
self.assertEqual(self.root.grid_columnconfigure(0, 'minsize'), 10)
self.assertEqual(self.root.grid_columnconfigure(0)['minsize'], 10)
def test_grid_columnconfigure_weight(self):
with self.assertRaisesRegex(TclError, 'expected integer but got "bad"'):
self.root.grid_columnconfigure(0, weight='bad')
with self.assertRaisesRegex(TclError, 'invalid arg "-weight": '
'should be non-negative'):
self.root.grid_columnconfigure(0, weight=-3)
self.root.grid_columnconfigure(0, weight=3)
self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 3)
self.assertEqual(self.root.grid_columnconfigure(0)['weight'], 3)
def test_grid_columnconfigure_pad(self):
with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'):
self.root.grid_columnconfigure(0, pad='foo')
with self.assertRaisesRegex(TclError, 'invalid arg "-pad": '
'should be non-negative'):
self.root.grid_columnconfigure(0, pad=-3)
self.root.grid_columnconfigure(0, pad=3)
self.assertEqual(self.root.grid_columnconfigure(0, 'pad'), 3)
self.assertEqual(self.root.grid_columnconfigure(0)['pad'], 3)
def test_grid_columnconfigure_uniform(self):
self.root.grid_columnconfigure(0, uniform='foo')
self.assertEqual(self.root.grid_columnconfigure(0, 'uniform'), 'foo')
self.assertEqual(self.root.grid_columnconfigure(0)['uniform'], 'foo')
def test_grid_rowconfigure(self):
with self.assertRaises(TypeError):
self.root.grid_rowconfigure()
self.assertEqual(self.root.grid_rowconfigure(0),
{'minsize': 0, 'pad': 0, 'uniform': None, 'weight': 0})
with self.assertRaisesRegex(TclError, 'bad option "-foo"'):
self.root.grid_rowconfigure(0, 'foo')
self.root.grid_rowconfigure((0, 3), weight=2)
with self.assertRaisesRegex(TclError,
'must specify a single element on retrieval'):
self.root.grid_rowconfigure((0, 3))
b = tkinter.Button(self.root)
b.grid_configure(column=0, row=0)
if tcl_version >= (8, 5):
self.root.grid_rowconfigure('all', weight=3)
with self.assertRaisesRegex(TclError, 'expected integer but got "all"'):
self.root.grid_rowconfigure('all')
self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 3)
self.assertEqual(self.root.grid_rowconfigure(3, 'weight'), 2)
self.assertEqual(self.root.grid_rowconfigure(265, 'weight'), 0)
if tcl_version >= (8, 5):
self.root.grid_rowconfigure(b, weight=4)
self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 4)
def test_grid_rowconfigure_minsize(self):
with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'):
self.root.grid_rowconfigure(0, minsize='foo')
self.root.grid_rowconfigure(0, minsize=10)
self.assertEqual(self.root.grid_rowconfigure(0, 'minsize'), 10)
self.assertEqual(self.root.grid_rowconfigure(0)['minsize'], 10)
def test_grid_rowconfigure_weight(self):
with self.assertRaisesRegex(TclError, 'expected integer but got "bad"'):
self.root.grid_rowconfigure(0, weight='bad')
with self.assertRaisesRegex(TclError, 'invalid arg "-weight": '
'should be non-negative'):
self.root.grid_rowconfigure(0, weight=-3)
self.root.grid_rowconfigure(0, weight=3)
self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 3)
self.assertEqual(self.root.grid_rowconfigure(0)['weight'], 3)
def test_grid_rowconfigure_pad(self):
with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'):
self.root.grid_rowconfigure(0, pad='foo')
with self.assertRaisesRegex(TclError, 'invalid arg "-pad": '
'should be non-negative'):
self.root.grid_rowconfigure(0, pad=-3)
self.root.grid_rowconfigure(0, pad=3)
self.assertEqual(self.root.grid_rowconfigure(0, 'pad'), 3)
self.assertEqual(self.root.grid_rowconfigure(0)['pad'], 3)
def test_grid_rowconfigure_uniform(self):
self.root.grid_rowconfigure(0, uniform='foo')
self.assertEqual(self.root.grid_rowconfigure(0, 'uniform'), 'foo')
self.assertEqual(self.root.grid_rowconfigure(0)['uniform'], 'foo')
def test_grid_forget(self):
b = tkinter.Button(self.root)
c = tkinter.Button(self.root)
b.grid_configure(row=2, column=2, rowspan=2, columnspan=2,
padx=3, pady=4, sticky='ns')
self.assertEqual(self.root.grid_slaves(), [b])
b.grid_forget()
c.grid_forget()
self.assertEqual(self.root.grid_slaves(), [])
self.assertEqual(b.grid_info(), {})
b.grid_configure(row=0, column=0)
info = b.grid_info()
self.assertEqual(info['row'], self._str(0))
self.assertEqual(info['column'], self._str(0))
self.assertEqual(info['rowspan'], self._str(1))
self.assertEqual(info['columnspan'], self._str(1))
self.assertEqual(info['padx'], self._str(0))
self.assertEqual(info['pady'], self._str(0))
self.assertEqual(info['sticky'], '')
def test_grid_remove(self):
b = tkinter.Button(self.root)
c = tkinter.Button(self.root)
b.grid_configure(row=2, column=2, rowspan=2, columnspan=2,
padx=3, pady=4, sticky='ns')
self.assertEqual(self.root.grid_slaves(), [b])
b.grid_remove()
c.grid_remove()
self.assertEqual(self.root.grid_slaves(), [])
self.assertEqual(b.grid_info(), {})
b.grid_configure(row=0, column=0)
info = b.grid_info()
self.assertEqual(info['row'], self._str(0))
self.assertEqual(info['column'], self._str(0))
self.assertEqual(info['rowspan'], self._str(2))
self.assertEqual(info['columnspan'], self._str(2))
self.assertEqual(info['padx'], self._str(3))
self.assertEqual(info['pady'], self._str(4))
self.assertEqual(info['sticky'], 'ns')
def test_grid_info(self):
b = tkinter.Button(self.root)
self.assertEqual(b.grid_info(), {})
b.grid_configure(row=2, column=2, rowspan=2, columnspan=2,
padx=3, pady=4, sticky='ns')
info = b.grid_info()
self.assertIsInstance(info, dict)
self.assertEqual(info['in'], self.root)
self.assertEqual(info['row'], self._str(2))
self.assertEqual(info['column'], self._str(2))
self.assertEqual(info['rowspan'], self._str(2))
self.assertEqual(info['columnspan'], self._str(2))
self.assertEqual(info['padx'], self._str(3))
self.assertEqual(info['pady'], self._str(4))
self.assertEqual(info['sticky'], 'ns')
@requires_tcl(8, 5)
def test_grid_anchor(self):
with self.assertRaisesRegex(TclError, 'bad anchor "x"'):
self.root.grid_anchor('x')
with self.assertRaisesRegex(TclError, 'ambiguous anchor ""'):
self.root.grid_anchor('')
with self.assertRaises(TypeError):
self.root.grid_anchor('se', 'nw')
self.root.grid_anchor('se')
self.assertEqual(self.root.tk.call('grid', 'anchor', self.root), 'se')
def test_grid_bbox(self):
self.assertEqual(self.root.grid_bbox(), (0, 0, 0, 0))
self.assertEqual(self.root.grid_bbox(0, 0), (0, 0, 0, 0))
self.assertEqual(self.root.grid_bbox(0, 0, 1, 1), (0, 0, 0, 0))
with self.assertRaisesRegex(TclError, 'expected integer but got "x"'):
self.root.grid_bbox('x', 0)
with self.assertRaisesRegex(TclError, 'expected integer but got "x"'):
self.root.grid_bbox(0, 'x')
with self.assertRaisesRegex(TclError, 'expected integer but got "x"'):
self.root.grid_bbox(0, 0, 'x', 0)
with self.assertRaisesRegex(TclError, 'expected integer but got "x"'):
self.root.grid_bbox(0, 0, 0, 'x')
with self.assertRaises(TypeError):
self.root.grid_bbox(0, 0, 0, 0, 0)
t = self.root
# de-maximize
t.wm_geometry('1x1+0+0')
t.wm_geometry('')
f1 = tkinter.Frame(t, width=75, height=75, bg='red')
f2 = tkinter.Frame(t, width=90, height=90, bg='blue')
f1.grid_configure(row=0, column=0)
f2.grid_configure(row=1, column=1)
self.root.update()
self.assertEqual(t.grid_bbox(), (0, 0, 165, 165))
self.assertEqual(t.grid_bbox(0, 0), (0, 0, 75, 75))
self.assertEqual(t.grid_bbox(0, 0, 1, 1), (0, 0, 165, 165))
self.assertEqual(t.grid_bbox(1, 1), (75, 75, 90, 90))
self.assertEqual(t.grid_bbox(10, 10, 0, 0), (0, 0, 165, 165))
self.assertEqual(t.grid_bbox(-2, -2, -1, -1), (0, 0, 0, 0))
self.assertEqual(t.grid_bbox(10, 10, 12, 12), (165, 165, 0, 0))
def test_grid_location(self):
with self.assertRaises(TypeError):
self.root.grid_location()
with self.assertRaises(TypeError):
self.root.grid_location(0)
with self.assertRaises(TypeError):
self.root.grid_location(0, 0, 0)
with self.assertRaisesRegex(TclError, 'bad screen distance "x"'):
self.root.grid_location('x', 'y')
with self.assertRaisesRegex(TclError, 'bad screen distance "y"'):
self.root.grid_location('1c', 'y')
t = self.root
# de-maximize
t.wm_geometry('1x1+0+0')
t.wm_geometry('')
f = tkinter.Frame(t, width=200, height=100,
highlightthickness=0, bg='red')
self.assertEqual(f.grid_location(10, 10), (-1, -1))
f.grid_configure()
self.root.update()
self.assertEqual(t.grid_location(-10, -10), (-1, -1))
self.assertEqual(t.grid_location(-10, 0), (-1, 0))
self.assertEqual(t.grid_location(-1, 0), (-1, 0))
self.assertEqual(t.grid_location(0, -10), (0, -1))
self.assertEqual(t.grid_location(0, -1), (0, -1))
self.assertEqual(t.grid_location(0, 0), (0, 0))
self.assertEqual(t.grid_location(200, 0), (0, 0))
self.assertEqual(t.grid_location(201, 0), (1, 0))
self.assertEqual(t.grid_location(0, 100), (0, 0))
self.assertEqual(t.grid_location(0, 101), (0, 1))
self.assertEqual(t.grid_location(201, 101), (1, 1))
def test_grid_propagate(self):
self.assertEqual(self.root.grid_propagate(), True)
with self.assertRaises(TypeError):
self.root.grid_propagate(False, False)
self.root.grid_propagate(False)
self.assertFalse(self.root.grid_propagate())
f = tkinter.Frame(self.root, width=100, height=100, bg='red')
f.grid_configure(row=0, column=0)
self.root.update()
self.assertEqual(f.winfo_width(), 100)
self.assertEqual(f.winfo_height(), 100)
f.grid_propagate(False)
g = tkinter.Frame(self.root, width=75, height=85, bg='green')
g.grid_configure(in_=f, row=0, column=0)
self.root.update()
self.assertEqual(f.winfo_width(), 100)
self.assertEqual(f.winfo_height(), 100)
f.grid_propagate(True)
self.root.update()
self.assertEqual(f.winfo_width(), 75)
self.assertEqual(f.winfo_height(), 85)
def test_grid_size(self):
with self.assertRaises(TypeError):
self.root.grid_size(0)
self.assertEqual(self.root.grid_size(), (0, 0))
f = tkinter.Scale(self.root)
f.grid_configure(row=0, column=0)
self.assertEqual(self.root.grid_size(), (1, 1))
f.grid_configure(row=4, column=5)
self.assertEqual(self.root.grid_size(), (6, 5))
def test_grid_slaves(self):
self.assertEqual(self.root.grid_slaves(), [])
a = tkinter.Label(self.root)
a.grid_configure(row=0, column=1)
b = tkinter.Label(self.root)
b.grid_configure(row=1, column=0)
c = tkinter.Label(self.root)
c.grid_configure(row=1, column=1)
d = tkinter.Label(self.root)
d.grid_configure(row=1, column=1)
self.assertEqual(self.root.grid_slaves(), [d, c, b, a])
self.assertEqual(self.root.grid_slaves(row=0), [a])
self.assertEqual(self.root.grid_slaves(row=1), [d, c, b])
self.assertEqual(self.root.grid_slaves(column=0), [b])
self.assertEqual(self.root.grid_slaves(column=1), [d, c, a])
self.assertEqual(self.root.grid_slaves(row=1, column=1), [d, c])
tests_gui = (
PackTest, PlaceTest, GridTest,
)
if __name__ == '__main__':
unittest.main()
=======
import unittest
import re
import tkinter
from tkinter import TclError
from test.support import requires
from tkinter.test.support import pixels_conv, tcl_version, requires_tcl
from tkinter.test.widget_tests import AbstractWidgetTest
requires('gui')
class PackTest(AbstractWidgetTest, unittest.TestCase):
def create2(self):
pack = tkinter.Toplevel(self.root, name='pack')
pack.wm_geometry('300x200+0+0')
pack.wm_minsize(1, 1)
a = tkinter.Frame(pack, name='a', width=20, height=40, bg='red')
b = tkinter.Frame(pack, name='b', width=50, height=30, bg='blue')
c = tkinter.Frame(pack, name='c', width=80, height=80, bg='green')
d = tkinter.Frame(pack, name='d', width=40, height=30, bg='yellow')
return pack, a, b, c, d
def test_pack_configure_after(self):
pack, a, b, c, d = self.create2()
with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % b):
a.pack_configure(after=b)
with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'):
a.pack_configure(after='.foo')
a.pack_configure(side='top')
b.pack_configure(side='top')
c.pack_configure(side='top')
d.pack_configure(side='top')
self.assertEqual(pack.pack_slaves(), [a, b, c, d])
a.pack_configure(after=b)
self.assertEqual(pack.pack_slaves(), [b, a, c, d])
a.pack_configure(after=a)
self.assertEqual(pack.pack_slaves(), [b, a, c, d])
def test_pack_configure_anchor(self):
pack, a, b, c, d = self.create2()
def check(anchor, geom):
a.pack_configure(side='top', ipadx=5, padx=10, ipady=15, pady=20,
expand=True, anchor=anchor)
self.root.update()
self.assertEqual(a.winfo_geometry(), geom)
check('n', '30x70+135+20')
check('ne', '30x70+260+20')
check('e', '30x70+260+65')
check('se', '30x70+260+110')
check('s', '30x70+135+110')
check('sw', '30x70+10+110')
check('w', '30x70+10+65')
check('nw', '30x70+10+20')
check('center', '30x70+135+65')
def test_pack_configure_before(self):
pack, a, b, c, d = self.create2()
with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % b):
a.pack_configure(before=b)
with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'):
a.pack_configure(before='.foo')
a.pack_configure(side='top')
b.pack_configure(side='top')
c.pack_configure(side='top')
d.pack_configure(side='top')
self.assertEqual(pack.pack_slaves(), [a, b, c, d])
a.pack_configure(before=d)
self.assertEqual(pack.pack_slaves(), [b, c, a, d])
a.pack_configure(before=a)
self.assertEqual(pack.pack_slaves(), [b, c, a, d])
def test_pack_configure_expand(self):
pack, a, b, c, d = self.create2()
def check(*geoms):
self.root.update()
self.assertEqual(a.winfo_geometry(), geoms[0])
self.assertEqual(b.winfo_geometry(), geoms[1])
self.assertEqual(c.winfo_geometry(), geoms[2])
self.assertEqual(d.winfo_geometry(), geoms[3])
a.pack_configure(side='left')
b.pack_configure(side='top')
c.pack_configure(side='right')
d.pack_configure(side='bottom')
check('20x40+0+80', '50x30+135+0', '80x80+220+75', '40x30+100+170')
a.pack_configure(side='left', expand='yes')
b.pack_configure(side='top', expand='on')
c.pack_configure(side='right', expand=True)
d.pack_configure(side='bottom', expand=1)
check('20x40+40+80', '50x30+175+35', '80x80+180+110', '40x30+100+135')
a.pack_configure(side='left', expand='yes', fill='both')
b.pack_configure(side='top', expand='on', fill='both')
c.pack_configure(side='right', expand=True, fill='both')
d.pack_configure(side='bottom', expand=1, fill='both')
check('100x200+0+0', '200x100+100+0', '160x100+140+100', '40x100+100+100')
def test_pack_configure_in(self):
pack, a, b, c, d = self.create2()
a.pack_configure(side='top')
b.pack_configure(side='top')
c.pack_configure(side='top')
d.pack_configure(side='top')
a.pack_configure(in_=pack)
self.assertEqual(pack.pack_slaves(), [b, c, d, a])
a.pack_configure(in_=c)
self.assertEqual(pack.pack_slaves(), [b, c, d])
self.assertEqual(c.pack_slaves(), [a])
with self.assertRaisesRegex(TclError,
'can\'t pack %s inside itself' % (a,)):
a.pack_configure(in_=a)
with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'):
a.pack_configure(in_='.foo')
def test_pack_configure_padx_ipadx_fill(self):
pack, a, b, c, d = self.create2()
def check(geom1, geom2, **kwargs):
a.pack_forget()
b.pack_forget()
a.pack_configure(**kwargs)
b.pack_configure(expand=True, fill='both')
self.root.update()
self.assertEqual(a.winfo_geometry(), geom1)
self.assertEqual(b.winfo_geometry(), geom2)
check('20x40+260+80', '240x200+0+0', side='right', padx=20)
check('20x40+250+80', '240x200+0+0', side='right', padx=(10, 30))
check('60x40+240+80', '240x200+0+0', side='right', ipadx=20)
check('30x40+260+80', '250x200+0+0', side='right', ipadx=5, padx=10)
check('20x40+260+80', '240x200+0+0', side='right', padx=20, fill='x')
check('20x40+249+80', '240x200+0+0',
side='right', padx=(9, 31), fill='x')
check('60x40+240+80', '240x200+0+0', side='right', ipadx=20, fill='x')
check('30x40+260+80', '250x200+0+0',
side='right', ipadx=5, padx=10, fill='x')
check('30x40+255+80', '250x200+0+0',
side='right', ipadx=5, padx=(5, 15), fill='x')
check('20x40+140+0', '300x160+0+40', side='top', padx=20)
check('20x40+120+0', '300x160+0+40', side='top', padx=(0, 40))
check('60x40+120+0', '300x160+0+40', side='top', ipadx=20)
check('30x40+135+0', '300x160+0+40', side='top', ipadx=5, padx=10)
check('30x40+130+0', '300x160+0+40', side='top', ipadx=5, padx=(5, 15))
check('260x40+20+0', '300x160+0+40', side='top', padx=20, fill='x')
check('260x40+25+0', '300x160+0+40',
side='top', padx=(25, 15), fill='x')
check('300x40+0+0', '300x160+0+40', side='top', ipadx=20, fill='x')
check('280x40+10+0', '300x160+0+40',
side='top', ipadx=5, padx=10, fill='x')
check('280x40+5+0', '300x160+0+40',
side='top', ipadx=5, padx=(5, 15), fill='x')
a.pack_configure(padx='1c')
self.assertEqual(a.pack_info()['padx'],
self._str(pack.winfo_pixels('1c')))
a.pack_configure(ipadx='1c')
self.assertEqual(a.pack_info()['ipadx'],
self._str(pack.winfo_pixels('1c')))
def test_pack_configure_pady_ipady_fill(self):
pack, a, b, c, d = self.create2()
def check(geom1, geom2, **kwargs):
a.pack_forget()
b.pack_forget()
a.pack_configure(**kwargs)
b.pack_configure(expand=True, fill='both')
self.root.update()
self.assertEqual(a.winfo_geometry(), geom1)
self.assertEqual(b.winfo_geometry(), geom2)
check('20x40+280+80', '280x200+0+0', side='right', pady=20)
check('20x40+280+70', '280x200+0+0', side='right', pady=(10, 30))
check('20x80+280+60', '280x200+0+0', side='right', ipady=20)
check('20x50+280+75', '280x200+0+0', side='right', ipady=5, pady=10)
check('20x40+280+80', '280x200+0+0', side='right', pady=20, fill='x')
check('20x40+280+69', '280x200+0+0',
side='right', pady=(9, 31), fill='x')
check('20x80+280+60', '280x200+0+0', side='right', ipady=20, fill='x')
check('20x50+280+75', '280x200+0+0',
side='right', ipady=5, pady=10, fill='x')
check('20x50+280+70', '280x200+0+0',
side='right', ipady=5, pady=(5, 15), fill='x')
check('20x40+140+20', '300x120+0+80', side='top', pady=20)
check('20x40+140+0', '300x120+0+80', side='top', pady=(0, 40))
check('20x80+140+0', '300x120+0+80', side='top', ipady=20)
check('20x50+140+10', '300x130+0+70', side='top', ipady=5, pady=10)
check('20x50+140+5', '300x130+0+70', side='top', ipady=5, pady=(5, 15))
check('300x40+0+20', '300x120+0+80', side='top', pady=20, fill='x')
check('300x40+0+25', '300x120+0+80',
side='top', pady=(25, 15), fill='x')
check('300x80+0+0', '300x120+0+80', side='top', ipady=20, fill='x')
check('300x50+0+10', '300x130+0+70',
side='top', ipady=5, pady=10, fill='x')
check('300x50+0+5', '300x130+0+70',
side='top', ipady=5, pady=(5, 15), fill='x')
a.pack_configure(pady='1c')
self.assertEqual(a.pack_info()['pady'],
self._str(pack.winfo_pixels('1c')))
a.pack_configure(ipady='1c')
self.assertEqual(a.pack_info()['ipady'],
self._str(pack.winfo_pixels('1c')))
def test_pack_configure_side(self):
pack, a, b, c, d = self.create2()
def check(side, geom1, geom2):
a.pack_configure(side=side)
self.assertEqual(a.pack_info()['side'], side)
b.pack_configure(expand=True, fill='both')
self.root.update()
self.assertEqual(a.winfo_geometry(), geom1)
self.assertEqual(b.winfo_geometry(), geom2)
check('top', '20x40+140+0', '300x160+0+40')
check('bottom', '20x40+140+160', '300x160+0+0')
check('left', '20x40+0+80', '280x200+20+0')
check('right', '20x40+280+80', '280x200+0+0')
def test_pack_forget(self):
pack, a, b, c, d = self.create2()
a.pack_configure()
b.pack_configure()
c.pack_configure()
self.assertEqual(pack.pack_slaves(), [a, b, c])
b.pack_forget()
self.assertEqual(pack.pack_slaves(), [a, c])
b.pack_forget()
self.assertEqual(pack.pack_slaves(), [a, c])
d.pack_forget()
def test_pack_info(self):
pack, a, b, c, d = self.create2()
with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % a):
a.pack_info()
a.pack_configure()
b.pack_configure(side='right', in_=a, anchor='s', expand=True, fill='x',
ipadx=5, padx=10, ipady=2, pady=(5, 15))
info = a.pack_info()
self.assertIsInstance(info, dict)
self.assertEqual(info['anchor'], 'center')
self.assertEqual(info['expand'], self._str(0))
self.assertEqual(info['fill'], 'none')
self.assertEqual(info['in'], pack)
self.assertEqual(info['ipadx'], self._str(0))
self.assertEqual(info['ipady'], self._str(0))
self.assertEqual(info['padx'], self._str(0))
self.assertEqual(info['pady'], self._str(0))
self.assertEqual(info['side'], 'top')
info = b.pack_info()
self.assertIsInstance(info, dict)
self.assertEqual(info['anchor'], 's')
self.assertEqual(info['expand'], self._str(1))
self.assertEqual(info['fill'], 'x')
self.assertEqual(info['in'], a)
self.assertEqual(info['ipadx'], self._str(5))
self.assertEqual(info['ipady'], self._str(2))
self.assertEqual(info['padx'], self._str(10))
self.assertEqual(info['pady'], self._str((5, 15)))
self.assertEqual(info['side'], 'right')
def test_pack_propagate(self):
pack, a, b, c, d = self.create2()
pack.configure(width=300, height=200)
a.pack_configure()
pack.pack_propagate(False)
self.root.update()
self.assertEqual(pack.winfo_reqwidth(), 300)
self.assertEqual(pack.winfo_reqheight(), 200)
pack.pack_propagate(True)
self.root.update()
self.assertEqual(pack.winfo_reqwidth(), 20)
self.assertEqual(pack.winfo_reqheight(), 40)
def test_pack_slaves(self):
pack, a, b, c, d = self.create2()
self.assertEqual(pack.pack_slaves(), [])
a.pack_configure()
self.assertEqual(pack.pack_slaves(), [a])
b.pack_configure()
self.assertEqual(pack.pack_slaves(), [a, b])
class PlaceTest(AbstractWidgetTest, unittest.TestCase):
def create2(self):
t = tkinter.Toplevel(self.root, width=300, height=200, bd=0)
t.wm_geometry('300x200+0+0')
f = tkinter.Frame(t, width=154, height=84, bd=2, relief='raised')
f.place_configure(x=48, y=38)
f2 = tkinter.Frame(t, width=30, height=60, bd=2, relief='raised')
self.root.update()
return t, f, f2
def test_place_configure_in(self):
t, f, f2 = self.create2()
self.assertEqual(f2.winfo_manager(), '')
with self.assertRaisesRegex(TclError, "can't place %s relative to "
"itself" % re.escape(str(f2))):
f2.place_configure(in_=f2)
if tcl_version >= (8, 5):
self.assertEqual(f2.winfo_manager(), '')
with self.assertRaisesRegex(TclError, 'bad window path name'):
f2.place_configure(in_='spam')
f2.place_configure(in_=f)
self.assertEqual(f2.winfo_manager(), 'place')
def test_place_configure_x(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f)
self.assertEqual(f2.place_info()['x'], '0')
self.root.update()
self.assertEqual(f2.winfo_x(), 50)
f2.place_configure(x=100)
self.assertEqual(f2.place_info()['x'], '100')
self.root.update()
self.assertEqual(f2.winfo_x(), 150)
f2.place_configure(x=-10, relx=1)
self.assertEqual(f2.place_info()['x'], '-10')
self.root.update()
self.assertEqual(f2.winfo_x(), 190)
with self.assertRaisesRegex(TclError, 'bad screen distance "spam"'):
f2.place_configure(in_=f, x='spam')
def test_place_configure_y(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f)
self.assertEqual(f2.place_info()['y'], '0')
self.root.update()
self.assertEqual(f2.winfo_y(), 40)
f2.place_configure(y=50)
self.assertEqual(f2.place_info()['y'], '50')
self.root.update()
self.assertEqual(f2.winfo_y(), 90)
f2.place_configure(y=-10, rely=1)
self.assertEqual(f2.place_info()['y'], '-10')
self.root.update()
self.assertEqual(f2.winfo_y(), 110)
with self.assertRaisesRegex(TclError, 'bad screen distance "spam"'):
f2.place_configure(in_=f, y='spam')
def test_place_configure_relx(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f)
self.assertEqual(f2.place_info()['relx'], '0')
self.root.update()
self.assertEqual(f2.winfo_x(), 50)
f2.place_configure(relx=0.5)
self.assertEqual(f2.place_info()['relx'], '0.5')
self.root.update()
self.assertEqual(f2.winfo_x(), 125)
f2.place_configure(relx=1)
self.assertEqual(f2.place_info()['relx'], '1')
self.root.update()
self.assertEqual(f2.winfo_x(), 200)
with self.assertRaisesRegex(TclError, 'expected floating-point number '
'but got "spam"'):
f2.place_configure(in_=f, relx='spam')
def test_place_configure_rely(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f)
self.assertEqual(f2.place_info()['rely'], '0')
self.root.update()
self.assertEqual(f2.winfo_y(), 40)
f2.place_configure(rely=0.5)
self.assertEqual(f2.place_info()['rely'], '0.5')
self.root.update()
self.assertEqual(f2.winfo_y(), 80)
f2.place_configure(rely=1)
self.assertEqual(f2.place_info()['rely'], '1')
self.root.update()
self.assertEqual(f2.winfo_y(), 120)
with self.assertRaisesRegex(TclError, 'expected floating-point number '
'but got "spam"'):
f2.place_configure(in_=f, rely='spam')
def test_place_configure_anchor(self):
f = tkinter.Frame(self.root)
with self.assertRaisesRegex(TclError, 'bad anchor "j"'):
f.place_configure(anchor='j')
with self.assertRaisesRegex(TclError, 'ambiguous anchor ""'):
f.place_configure(anchor='')
for value in 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center':
f.place_configure(anchor=value)
self.assertEqual(f.place_info()['anchor'], value)
def test_place_configure_width(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, width=120)
self.root.update()
self.assertEqual(f2.winfo_width(), 120)
f2.place_configure(width='')
self.root.update()
self.assertEqual(f2.winfo_width(), 30)
with self.assertRaisesRegex(TclError, 'bad screen distance "abcd"'):
f2.place_configure(width='abcd')
def test_place_configure_height(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, height=120)
self.root.update()
self.assertEqual(f2.winfo_height(), 120)
f2.place_configure(height='')
self.root.update()
self.assertEqual(f2.winfo_height(), 60)
with self.assertRaisesRegex(TclError, 'bad screen distance "abcd"'):
f2.place_configure(height='abcd')
def test_place_configure_relwidth(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, relwidth=0.5)
self.root.update()
self.assertEqual(f2.winfo_width(), 75)
f2.place_configure(relwidth='')
self.root.update()
self.assertEqual(f2.winfo_width(), 30)
with self.assertRaisesRegex(TclError, 'expected floating-point number '
'but got "abcd"'):
f2.place_configure(relwidth='abcd')
def test_place_configure_relheight(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, relheight=0.5)
self.root.update()
self.assertEqual(f2.winfo_height(), 40)
f2.place_configure(relheight='')
self.root.update()
self.assertEqual(f2.winfo_height(), 60)
with self.assertRaisesRegex(TclError, 'expected floating-point number '
'but got "abcd"'):
f2.place_configure(relheight='abcd')
def test_place_configure_bordermode(self):
f = tkinter.Frame(self.root)
with self.assertRaisesRegex(TclError, 'bad bordermode "j"'):
f.place_configure(bordermode='j')
with self.assertRaisesRegex(TclError, 'ambiguous bordermode ""'):
f.place_configure(bordermode='')
for value in 'inside', 'outside', 'ignore':
f.place_configure(bordermode=value)
self.assertEqual(f.place_info()['bordermode'], value)
def test_place_forget(self):
foo = tkinter.Frame(self.root)
foo.place_configure(width=50, height=50)
self.root.update()
foo.place_forget()
self.root.update()
self.assertFalse(foo.winfo_ismapped())
with self.assertRaises(TypeError):
foo.place_forget(0)
def test_place_info(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, x=1, y=2, width=3, height=4,
relx=0.1, rely=0.2, relwidth=0.3, relheight=0.4,
anchor='se', bordermode='outside')
info = f2.place_info()
self.assertIsInstance(info, dict)
self.assertEqual(info['x'], '1')
self.assertEqual(info['y'], '2')
self.assertEqual(info['width'], '3')
self.assertEqual(info['height'], '4')
self.assertEqual(info['relx'], '0.1')
self.assertEqual(info['rely'], '0.2')
self.assertEqual(info['relwidth'], '0.3')
self.assertEqual(info['relheight'], '0.4')
self.assertEqual(info['anchor'], 'se')
self.assertEqual(info['bordermode'], 'outside')
self.assertEqual(info['x'], '1')
self.assertEqual(info['x'], '1')
with self.assertRaises(TypeError):
f2.place_info(0)
def test_place_slaves(self):
foo = tkinter.Frame(self.root)
bar = tkinter.Frame(self.root)
self.assertEqual(foo.place_slaves(), [])
bar.place_configure(in_=foo)
self.assertEqual(foo.place_slaves(), [bar])
with self.assertRaises(TypeError):
foo.place_slaves(0)
class GridTest(AbstractWidgetTest, unittest.TestCase):
def tearDown(self):
cols, rows = self.root.grid_size()
for i in range(cols + 1):
self.root.grid_columnconfigure(i, weight=0, minsize=0, pad=0, uniform='')
for i in range(rows + 1):
self.root.grid_rowconfigure(i, weight=0, minsize=0, pad=0, uniform='')
self.root.grid_propagate(1)
if tcl_version >= (8, 5):
self.root.grid_anchor('nw')
super().tearDown()
def test_grid_configure(self):
b = tkinter.Button(self.root)
self.assertEqual(b.grid_info(), {})
b.grid_configure()
self.assertEqual(b.grid_info()['in'], self.root)
self.assertEqual(b.grid_info()['column'], self._str(0))
self.assertEqual(b.grid_info()['row'], self._str(0))
b.grid_configure({'column': 1}, row=2)
self.assertEqual(b.grid_info()['column'], self._str(1))
self.assertEqual(b.grid_info()['row'], self._str(2))
def test_grid_configure_column(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad column value "-1": '
'must be a non-negative integer'):
b.grid_configure(column=-1)
b.grid_configure(column=2)
self.assertEqual(b.grid_info()['column'], self._str(2))
def test_grid_configure_columnspan(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad columnspan value "0": '
'must be a positive integer'):
b.grid_configure(columnspan=0)
b.grid_configure(columnspan=2)
self.assertEqual(b.grid_info()['columnspan'], self._str(2))
def test_grid_configure_in(self):
f = tkinter.Frame(self.root)
b = tkinter.Button(self.root)
self.assertEqual(b.grid_info(), {})
b.grid_configure()
self.assertEqual(b.grid_info()['in'], self.root)
b.grid_configure(in_=f)
self.assertEqual(b.grid_info()['in'], f)
b.grid_configure({'in': self.root})
self.assertEqual(b.grid_info()['in'], self.root)
def test_grid_configure_ipadx(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad ipadx value "-1": '
'must be positive screen distance'):
b.grid_configure(ipadx=-1)
b.grid_configure(ipadx=1)
self.assertEqual(b.grid_info()['ipadx'], self._str(1))
b.grid_configure(ipadx='.5c')
self.assertEqual(b.grid_info()['ipadx'],
self._str(round(pixels_conv('.5c') * self.scaling)))
def test_grid_configure_ipady(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad ipady value "-1": '
'must be positive screen distance'):
b.grid_configure(ipady=-1)
b.grid_configure(ipady=1)
self.assertEqual(b.grid_info()['ipady'], self._str(1))
b.grid_configure(ipady='.5c')
self.assertEqual(b.grid_info()['ipady'],
self._str(round(pixels_conv('.5c') * self.scaling)))
def test_grid_configure_padx(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad pad value "-1": '
'must be positive screen distance'):
b.grid_configure(padx=-1)
b.grid_configure(padx=1)
self.assertEqual(b.grid_info()['padx'], self._str(1))
b.grid_configure(padx=(10, 5))
self.assertEqual(b.grid_info()['padx'], self._str((10, 5)))
b.grid_configure(padx='.5c')
self.assertEqual(b.grid_info()['padx'],
self._str(round(pixels_conv('.5c') * self.scaling)))
def test_grid_configure_pady(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad pad value "-1": '
'must be positive screen distance'):
b.grid_configure(pady=-1)
b.grid_configure(pady=1)
self.assertEqual(b.grid_info()['pady'], self._str(1))
b.grid_configure(pady=(10, 5))
self.assertEqual(b.grid_info()['pady'], self._str((10, 5)))
b.grid_configure(pady='.5c')
self.assertEqual(b.grid_info()['pady'],
self._str(round(pixels_conv('.5c') * self.scaling)))
def test_grid_configure_row(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad (row|grid) value "-1": '
'must be a non-negative integer'):
b.grid_configure(row=-1)
b.grid_configure(row=2)
self.assertEqual(b.grid_info()['row'], self._str(2))
def test_grid_configure_rownspan(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad rowspan value "0": '
'must be a positive integer'):
b.grid_configure(rowspan=0)
b.grid_configure(rowspan=2)
self.assertEqual(b.grid_info()['rowspan'], self._str(2))
def test_grid_configure_sticky(self):
f = tkinter.Frame(self.root, bg='red')
with self.assertRaisesRegex(TclError, 'bad stickyness value "glue"'):
f.grid_configure(sticky='glue')
f.grid_configure(sticky='ne')
self.assertEqual(f.grid_info()['sticky'], 'ne')
f.grid_configure(sticky='n,s,e,w')
self.assertEqual(f.grid_info()['sticky'], 'nesw')
def test_grid_columnconfigure(self):
with self.assertRaises(TypeError):
self.root.grid_columnconfigure()
self.assertEqual(self.root.grid_columnconfigure(0),
{'minsize': 0, 'pad': 0, 'uniform': None, 'weight': 0})
with self.assertRaisesRegex(TclError, 'bad option "-foo"'):
self.root.grid_columnconfigure(0, 'foo')
self.root.grid_columnconfigure((0, 3), weight=2)
with self.assertRaisesRegex(TclError,
'must specify a single element on retrieval'):
self.root.grid_columnconfigure((0, 3))
b = tkinter.Button(self.root)
b.grid_configure(column=0, row=0)
if tcl_version >= (8, 5):
self.root.grid_columnconfigure('all', weight=3)
with self.assertRaisesRegex(TclError, 'expected integer but got "all"'):
self.root.grid_columnconfigure('all')
self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 3)
self.assertEqual(self.root.grid_columnconfigure(3, 'weight'), 2)
self.assertEqual(self.root.grid_columnconfigure(265, 'weight'), 0)
if tcl_version >= (8, 5):
self.root.grid_columnconfigure(b, weight=4)
self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 4)
def test_grid_columnconfigure_minsize(self):
with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'):
self.root.grid_columnconfigure(0, minsize='foo')
self.root.grid_columnconfigure(0, minsize=10)
self.assertEqual(self.root.grid_columnconfigure(0, 'minsize'), 10)
self.assertEqual(self.root.grid_columnconfigure(0)['minsize'], 10)
def test_grid_columnconfigure_weight(self):
with self.assertRaisesRegex(TclError, 'expected integer but got "bad"'):
self.root.grid_columnconfigure(0, weight='bad')
with self.assertRaisesRegex(TclError, 'invalid arg "-weight": '
'should be non-negative'):
self.root.grid_columnconfigure(0, weight=-3)
self.root.grid_columnconfigure(0, weight=3)
self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 3)
self.assertEqual(self.root.grid_columnconfigure(0)['weight'], 3)
def test_grid_columnconfigure_pad(self):
with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'):
self.root.grid_columnconfigure(0, pad='foo')
with self.assertRaisesRegex(TclError, 'invalid arg "-pad": '
'should be non-negative'):
self.root.grid_columnconfigure(0, pad=-3)
self.root.grid_columnconfigure(0, pad=3)
self.assertEqual(self.root.grid_columnconfigure(0, 'pad'), 3)
self.assertEqual(self.root.grid_columnconfigure(0)['pad'], 3)
def test_grid_columnconfigure_uniform(self):
self.root.grid_columnconfigure(0, uniform='foo')
self.assertEqual(self.root.grid_columnconfigure(0, 'uniform'), 'foo')
self.assertEqual(self.root.grid_columnconfigure(0)['uniform'], 'foo')
def test_grid_rowconfigure(self):
with self.assertRaises(TypeError):
self.root.grid_rowconfigure()
self.assertEqual(self.root.grid_rowconfigure(0),
{'minsize': 0, 'pad': 0, 'uniform': None, 'weight': 0})
with self.assertRaisesRegex(TclError, 'bad option "-foo"'):
self.root.grid_rowconfigure(0, 'foo')
self.root.grid_rowconfigure((0, 3), weight=2)
with self.assertRaisesRegex(TclError,
'must specify a single element on retrieval'):
self.root.grid_rowconfigure((0, 3))
b = tkinter.Button(self.root)
b.grid_configure(column=0, row=0)
if tcl_version >= (8, 5):
self.root.grid_rowconfigure('all', weight=3)
with self.assertRaisesRegex(TclError, 'expected integer but got "all"'):
self.root.grid_rowconfigure('all')
self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 3)
self.assertEqual(self.root.grid_rowconfigure(3, 'weight'), 2)
self.assertEqual(self.root.grid_rowconfigure(265, 'weight'), 0)
if tcl_version >= (8, 5):
self.root.grid_rowconfigure(b, weight=4)
self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 4)
def test_grid_rowconfigure_minsize(self):
with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'):
self.root.grid_rowconfigure(0, minsize='foo')
self.root.grid_rowconfigure(0, minsize=10)
self.assertEqual(self.root.grid_rowconfigure(0, 'minsize'), 10)
self.assertEqual(self.root.grid_rowconfigure(0)['minsize'], 10)
def test_grid_rowconfigure_weight(self):
with self.assertRaisesRegex(TclError, 'expected integer but got "bad"'):
self.root.grid_rowconfigure(0, weight='bad')
with self.assertRaisesRegex(TclError, 'invalid arg "-weight": '
'should be non-negative'):
self.root.grid_rowconfigure(0, weight=-3)
self.root.grid_rowconfigure(0, weight=3)
self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 3)
self.assertEqual(self.root.grid_rowconfigure(0)['weight'], 3)
def test_grid_rowconfigure_pad(self):
with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'):
self.root.grid_rowconfigure(0, pad='foo')
with self.assertRaisesRegex(TclError, 'invalid arg "-pad": '
'should be non-negative'):
self.root.grid_rowconfigure(0, pad=-3)
self.root.grid_rowconfigure(0, pad=3)
self.assertEqual(self.root.grid_rowconfigure(0, 'pad'), 3)
self.assertEqual(self.root.grid_rowconfigure(0)['pad'], 3)
def test_grid_rowconfigure_uniform(self):
self.root.grid_rowconfigure(0, uniform='foo')
self.assertEqual(self.root.grid_rowconfigure(0, 'uniform'), 'foo')
self.assertEqual(self.root.grid_rowconfigure(0)['uniform'], 'foo')
def test_grid_forget(self):
b = tkinter.Button(self.root)
c = tkinter.Button(self.root)
b.grid_configure(row=2, column=2, rowspan=2, columnspan=2,
padx=3, pady=4, sticky='ns')
self.assertEqual(self.root.grid_slaves(), [b])
b.grid_forget()
c.grid_forget()
self.assertEqual(self.root.grid_slaves(), [])
self.assertEqual(b.grid_info(), {})
b.grid_configure(row=0, column=0)
info = b.grid_info()
self.assertEqual(info['row'], self._str(0))
self.assertEqual(info['column'], self._str(0))
self.assertEqual(info['rowspan'], self._str(1))
self.assertEqual(info['columnspan'], self._str(1))
self.assertEqual(info['padx'], self._str(0))
self.assertEqual(info['pady'], self._str(0))
self.assertEqual(info['sticky'], '')
def test_grid_remove(self):
b = tkinter.Button(self.root)
c = tkinter.Button(self.root)
b.grid_configure(row=2, column=2, rowspan=2, columnspan=2,
padx=3, pady=4, sticky='ns')
self.assertEqual(self.root.grid_slaves(), [b])
b.grid_remove()
c.grid_remove()
self.assertEqual(self.root.grid_slaves(), [])
self.assertEqual(b.grid_info(), {})
b.grid_configure(row=0, column=0)
info = b.grid_info()
self.assertEqual(info['row'], self._str(0))
self.assertEqual(info['column'], self._str(0))
self.assertEqual(info['rowspan'], self._str(2))
self.assertEqual(info['columnspan'], self._str(2))
self.assertEqual(info['padx'], self._str(3))
self.assertEqual(info['pady'], self._str(4))
self.assertEqual(info['sticky'], 'ns')
def test_grid_info(self):
b = tkinter.Button(self.root)
self.assertEqual(b.grid_info(), {})
b.grid_configure(row=2, column=2, rowspan=2, columnspan=2,
padx=3, pady=4, sticky='ns')
info = b.grid_info()
self.assertIsInstance(info, dict)
self.assertEqual(info['in'], self.root)
self.assertEqual(info['row'], self._str(2))
self.assertEqual(info['column'], self._str(2))
self.assertEqual(info['rowspan'], self._str(2))
self.assertEqual(info['columnspan'], self._str(2))
self.assertEqual(info['padx'], self._str(3))
self.assertEqual(info['pady'], self._str(4))
self.assertEqual(info['sticky'], 'ns')
@requires_tcl(8, 5)
def test_grid_anchor(self):
with self.assertRaisesRegex(TclError, 'bad anchor "x"'):
self.root.grid_anchor('x')
with self.assertRaisesRegex(TclError, 'ambiguous anchor ""'):
self.root.grid_anchor('')
with self.assertRaises(TypeError):
self.root.grid_anchor('se', 'nw')
self.root.grid_anchor('se')
self.assertEqual(self.root.tk.call('grid', 'anchor', self.root), 'se')
def test_grid_bbox(self):
self.assertEqual(self.root.grid_bbox(), (0, 0, 0, 0))
self.assertEqual(self.root.grid_bbox(0, 0), (0, 0, 0, 0))
self.assertEqual(self.root.grid_bbox(0, 0, 1, 1), (0, 0, 0, 0))
with self.assertRaisesRegex(TclError, 'expected integer but got "x"'):
self.root.grid_bbox('x', 0)
with self.assertRaisesRegex(TclError, 'expected integer but got "x"'):
self.root.grid_bbox(0, 'x')
with self.assertRaisesRegex(TclError, 'expected integer but got "x"'):
self.root.grid_bbox(0, 0, 'x', 0)
with self.assertRaisesRegex(TclError, 'expected integer but got "x"'):
self.root.grid_bbox(0, 0, 0, 'x')
with self.assertRaises(TypeError):
self.root.grid_bbox(0, 0, 0, 0, 0)
t = self.root
# de-maximize
t.wm_geometry('1x1+0+0')
t.wm_geometry('')
f1 = tkinter.Frame(t, width=75, height=75, bg='red')
f2 = tkinter.Frame(t, width=90, height=90, bg='blue')
f1.grid_configure(row=0, column=0)
f2.grid_configure(row=1, column=1)
self.root.update()
self.assertEqual(t.grid_bbox(), (0, 0, 165, 165))
self.assertEqual(t.grid_bbox(0, 0), (0, 0, 75, 75))
self.assertEqual(t.grid_bbox(0, 0, 1, 1), (0, 0, 165, 165))
self.assertEqual(t.grid_bbox(1, 1), (75, 75, 90, 90))
self.assertEqual(t.grid_bbox(10, 10, 0, 0), (0, 0, 165, 165))
self.assertEqual(t.grid_bbox(-2, -2, -1, -1), (0, 0, 0, 0))
self.assertEqual(t.grid_bbox(10, 10, 12, 12), (165, 165, 0, 0))
def test_grid_location(self):
with self.assertRaises(TypeError):
self.root.grid_location()
with self.assertRaises(TypeError):
self.root.grid_location(0)
with self.assertRaises(TypeError):
self.root.grid_location(0, 0, 0)
with self.assertRaisesRegex(TclError, 'bad screen distance "x"'):
self.root.grid_location('x', 'y')
with self.assertRaisesRegex(TclError, 'bad screen distance "y"'):
self.root.grid_location('1c', 'y')
t = self.root
# de-maximize
t.wm_geometry('1x1+0+0')
t.wm_geometry('')
f = tkinter.Frame(t, width=200, height=100,
highlightthickness=0, bg='red')
self.assertEqual(f.grid_location(10, 10), (-1, -1))
f.grid_configure()
self.root.update()
self.assertEqual(t.grid_location(-10, -10), (-1, -1))
self.assertEqual(t.grid_location(-10, 0), (-1, 0))
self.assertEqual(t.grid_location(-1, 0), (-1, 0))
self.assertEqual(t.grid_location(0, -10), (0, -1))
self.assertEqual(t.grid_location(0, -1), (0, -1))
self.assertEqual(t.grid_location(0, 0), (0, 0))
self.assertEqual(t.grid_location(200, 0), (0, 0))
self.assertEqual(t.grid_location(201, 0), (1, 0))
self.assertEqual(t.grid_location(0, 100), (0, 0))
self.assertEqual(t.grid_location(0, 101), (0, 1))
self.assertEqual(t.grid_location(201, 101), (1, 1))
def test_grid_propagate(self):
self.assertEqual(self.root.grid_propagate(), True)
with self.assertRaises(TypeError):
self.root.grid_propagate(False, False)
self.root.grid_propagate(False)
self.assertFalse(self.root.grid_propagate())
f = tkinter.Frame(self.root, width=100, height=100, bg='red')
f.grid_configure(row=0, column=0)
self.root.update()
self.assertEqual(f.winfo_width(), 100)
self.assertEqual(f.winfo_height(), 100)
f.grid_propagate(False)
g = tkinter.Frame(self.root, width=75, height=85, bg='green')
g.grid_configure(in_=f, row=0, column=0)
self.root.update()
self.assertEqual(f.winfo_width(), 100)
self.assertEqual(f.winfo_height(), 100)
f.grid_propagate(True)
self.root.update()
self.assertEqual(f.winfo_width(), 75)
self.assertEqual(f.winfo_height(), 85)
def test_grid_size(self):
with self.assertRaises(TypeError):
self.root.grid_size(0)
self.assertEqual(self.root.grid_size(), (0, 0))
f = tkinter.Scale(self.root)
f.grid_configure(row=0, column=0)
self.assertEqual(self.root.grid_size(), (1, 1))
f.grid_configure(row=4, column=5)
self.assertEqual(self.root.grid_size(), (6, 5))
def test_grid_slaves(self):
self.assertEqual(self.root.grid_slaves(), [])
a = tkinter.Label(self.root)
a.grid_configure(row=0, column=1)
b = tkinter.Label(self.root)
b.grid_configure(row=1, column=0)
c = tkinter.Label(self.root)
c.grid_configure(row=1, column=1)
d = tkinter.Label(self.root)
d.grid_configure(row=1, column=1)
self.assertEqual(self.root.grid_slaves(), [d, c, b, a])
self.assertEqual(self.root.grid_slaves(row=0), [a])
self.assertEqual(self.root.grid_slaves(row=1), [d, c, b])
self.assertEqual(self.root.grid_slaves(column=0), [b])
self.assertEqual(self.root.grid_slaves(column=1), [d, c, a])
self.assertEqual(self.root.grid_slaves(row=1, column=1), [d, c])
tests_gui = (
PackTest, PlaceTest, GridTest,
)
if __name__ == '__main__':
unittest.main()
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
=======
import unittest
import re
import tkinter
from tkinter import TclError
from test.support import requires
from tkinter.test.support import pixels_conv, tcl_version, requires_tcl
from tkinter.test.widget_tests import AbstractWidgetTest
requires('gui')
class PackTest(AbstractWidgetTest, unittest.TestCase):
def create2(self):
pack = tkinter.Toplevel(self.root, name='pack')
pack.wm_geometry('300x200+0+0')
pack.wm_minsize(1, 1)
a = tkinter.Frame(pack, name='a', width=20, height=40, bg='red')
b = tkinter.Frame(pack, name='b', width=50, height=30, bg='blue')
c = tkinter.Frame(pack, name='c', width=80, height=80, bg='green')
d = tkinter.Frame(pack, name='d', width=40, height=30, bg='yellow')
return pack, a, b, c, d
def test_pack_configure_after(self):
pack, a, b, c, d = self.create2()
with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % b):
a.pack_configure(after=b)
with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'):
a.pack_configure(after='.foo')
a.pack_configure(side='top')
b.pack_configure(side='top')
c.pack_configure(side='top')
d.pack_configure(side='top')
self.assertEqual(pack.pack_slaves(), [a, b, c, d])
a.pack_configure(after=b)
self.assertEqual(pack.pack_slaves(), [b, a, c, d])
a.pack_configure(after=a)
self.assertEqual(pack.pack_slaves(), [b, a, c, d])
def test_pack_configure_anchor(self):
pack, a, b, c, d = self.create2()
def check(anchor, geom):
a.pack_configure(side='top', ipadx=5, padx=10, ipady=15, pady=20,
expand=True, anchor=anchor)
self.root.update()
self.assertEqual(a.winfo_geometry(), geom)
check('n', '30x70+135+20')
check('ne', '30x70+260+20')
check('e', '30x70+260+65')
check('se', '30x70+260+110')
check('s', '30x70+135+110')
check('sw', '30x70+10+110')
check('w', '30x70+10+65')
check('nw', '30x70+10+20')
check('center', '30x70+135+65')
def test_pack_configure_before(self):
pack, a, b, c, d = self.create2()
with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % b):
a.pack_configure(before=b)
with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'):
a.pack_configure(before='.foo')
a.pack_configure(side='top')
b.pack_configure(side='top')
c.pack_configure(side='top')
d.pack_configure(side='top')
self.assertEqual(pack.pack_slaves(), [a, b, c, d])
a.pack_configure(before=d)
self.assertEqual(pack.pack_slaves(), [b, c, a, d])
a.pack_configure(before=a)
self.assertEqual(pack.pack_slaves(), [b, c, a, d])
def test_pack_configure_expand(self):
pack, a, b, c, d = self.create2()
def check(*geoms):
self.root.update()
self.assertEqual(a.winfo_geometry(), geoms[0])
self.assertEqual(b.winfo_geometry(), geoms[1])
self.assertEqual(c.winfo_geometry(), geoms[2])
self.assertEqual(d.winfo_geometry(), geoms[3])
a.pack_configure(side='left')
b.pack_configure(side='top')
c.pack_configure(side='right')
d.pack_configure(side='bottom')
check('20x40+0+80', '50x30+135+0', '80x80+220+75', '40x30+100+170')
a.pack_configure(side='left', expand='yes')
b.pack_configure(side='top', expand='on')
c.pack_configure(side='right', expand=True)
d.pack_configure(side='bottom', expand=1)
check('20x40+40+80', '50x30+175+35', '80x80+180+110', '40x30+100+135')
a.pack_configure(side='left', expand='yes', fill='both')
b.pack_configure(side='top', expand='on', fill='both')
c.pack_configure(side='right', expand=True, fill='both')
d.pack_configure(side='bottom', expand=1, fill='both')
check('100x200+0+0', '200x100+100+0', '160x100+140+100', '40x100+100+100')
def test_pack_configure_in(self):
pack, a, b, c, d = self.create2()
a.pack_configure(side='top')
b.pack_configure(side='top')
c.pack_configure(side='top')
d.pack_configure(side='top')
a.pack_configure(in_=pack)
self.assertEqual(pack.pack_slaves(), [b, c, d, a])
a.pack_configure(in_=c)
self.assertEqual(pack.pack_slaves(), [b, c, d])
self.assertEqual(c.pack_slaves(), [a])
with self.assertRaisesRegex(TclError,
'can\'t pack %s inside itself' % (a,)):
a.pack_configure(in_=a)
with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'):
a.pack_configure(in_='.foo')
def test_pack_configure_padx_ipadx_fill(self):
pack, a, b, c, d = self.create2()
def check(geom1, geom2, **kwargs):
a.pack_forget()
b.pack_forget()
a.pack_configure(**kwargs)
b.pack_configure(expand=True, fill='both')
self.root.update()
self.assertEqual(a.winfo_geometry(), geom1)
self.assertEqual(b.winfo_geometry(), geom2)
check('20x40+260+80', '240x200+0+0', side='right', padx=20)
check('20x40+250+80', '240x200+0+0', side='right', padx=(10, 30))
check('60x40+240+80', '240x200+0+0', side='right', ipadx=20)
check('30x40+260+80', '250x200+0+0', side='right', ipadx=5, padx=10)
check('20x40+260+80', '240x200+0+0', side='right', padx=20, fill='x')
check('20x40+249+80', '240x200+0+0',
side='right', padx=(9, 31), fill='x')
check('60x40+240+80', '240x200+0+0', side='right', ipadx=20, fill='x')
check('30x40+260+80', '250x200+0+0',
side='right', ipadx=5, padx=10, fill='x')
check('30x40+255+80', '250x200+0+0',
side='right', ipadx=5, padx=(5, 15), fill='x')
check('20x40+140+0', '300x160+0+40', side='top', padx=20)
check('20x40+120+0', '300x160+0+40', side='top', padx=(0, 40))
check('60x40+120+0', '300x160+0+40', side='top', ipadx=20)
check('30x40+135+0', '300x160+0+40', side='top', ipadx=5, padx=10)
check('30x40+130+0', '300x160+0+40', side='top', ipadx=5, padx=(5, 15))
check('260x40+20+0', '300x160+0+40', side='top', padx=20, fill='x')
check('260x40+25+0', '300x160+0+40',
side='top', padx=(25, 15), fill='x')
check('300x40+0+0', '300x160+0+40', side='top', ipadx=20, fill='x')
check('280x40+10+0', '300x160+0+40',
side='top', ipadx=5, padx=10, fill='x')
check('280x40+5+0', '300x160+0+40',
side='top', ipadx=5, padx=(5, 15), fill='x')
a.pack_configure(padx='1c')
self.assertEqual(a.pack_info()['padx'],
self._str(pack.winfo_pixels('1c')))
a.pack_configure(ipadx='1c')
self.assertEqual(a.pack_info()['ipadx'],
self._str(pack.winfo_pixels('1c')))
def test_pack_configure_pady_ipady_fill(self):
pack, a, b, c, d = self.create2()
def check(geom1, geom2, **kwargs):
a.pack_forget()
b.pack_forget()
a.pack_configure(**kwargs)
b.pack_configure(expand=True, fill='both')
self.root.update()
self.assertEqual(a.winfo_geometry(), geom1)
self.assertEqual(b.winfo_geometry(), geom2)
check('20x40+280+80', '280x200+0+0', side='right', pady=20)
check('20x40+280+70', '280x200+0+0', side='right', pady=(10, 30))
check('20x80+280+60', '280x200+0+0', side='right', ipady=20)
check('20x50+280+75', '280x200+0+0', side='right', ipady=5, pady=10)
check('20x40+280+80', '280x200+0+0', side='right', pady=20, fill='x')
check('20x40+280+69', '280x200+0+0',
side='right', pady=(9, 31), fill='x')
check('20x80+280+60', '280x200+0+0', side='right', ipady=20, fill='x')
check('20x50+280+75', '280x200+0+0',
side='right', ipady=5, pady=10, fill='x')
check('20x50+280+70', '280x200+0+0',
side='right', ipady=5, pady=(5, 15), fill='x')
check('20x40+140+20', '300x120+0+80', side='top', pady=20)
check('20x40+140+0', '300x120+0+80', side='top', pady=(0, 40))
check('20x80+140+0', '300x120+0+80', side='top', ipady=20)
check('20x50+140+10', '300x130+0+70', side='top', ipady=5, pady=10)
check('20x50+140+5', '300x130+0+70', side='top', ipady=5, pady=(5, 15))
check('300x40+0+20', '300x120+0+80', side='top', pady=20, fill='x')
check('300x40+0+25', '300x120+0+80',
side='top', pady=(25, 15), fill='x')
check('300x80+0+0', '300x120+0+80', side='top', ipady=20, fill='x')
check('300x50+0+10', '300x130+0+70',
side='top', ipady=5, pady=10, fill='x')
check('300x50+0+5', '300x130+0+70',
side='top', ipady=5, pady=(5, 15), fill='x')
a.pack_configure(pady='1c')
self.assertEqual(a.pack_info()['pady'],
self._str(pack.winfo_pixels('1c')))
a.pack_configure(ipady='1c')
self.assertEqual(a.pack_info()['ipady'],
self._str(pack.winfo_pixels('1c')))
def test_pack_configure_side(self):
pack, a, b, c, d = self.create2()
def check(side, geom1, geom2):
a.pack_configure(side=side)
self.assertEqual(a.pack_info()['side'], side)
b.pack_configure(expand=True, fill='both')
self.root.update()
self.assertEqual(a.winfo_geometry(), geom1)
self.assertEqual(b.winfo_geometry(), geom2)
check('top', '20x40+140+0', '300x160+0+40')
check('bottom', '20x40+140+160', '300x160+0+0')
check('left', '20x40+0+80', '280x200+20+0')
check('right', '20x40+280+80', '280x200+0+0')
def test_pack_forget(self):
pack, a, b, c, d = self.create2()
a.pack_configure()
b.pack_configure()
c.pack_configure()
self.assertEqual(pack.pack_slaves(), [a, b, c])
b.pack_forget()
self.assertEqual(pack.pack_slaves(), [a, c])
b.pack_forget()
self.assertEqual(pack.pack_slaves(), [a, c])
d.pack_forget()
def test_pack_info(self):
pack, a, b, c, d = self.create2()
with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % a):
a.pack_info()
a.pack_configure()
b.pack_configure(side='right', in_=a, anchor='s', expand=True, fill='x',
ipadx=5, padx=10, ipady=2, pady=(5, 15))
info = a.pack_info()
self.assertIsInstance(info, dict)
self.assertEqual(info['anchor'], 'center')
self.assertEqual(info['expand'], self._str(0))
self.assertEqual(info['fill'], 'none')
self.assertEqual(info['in'], pack)
self.assertEqual(info['ipadx'], self._str(0))
self.assertEqual(info['ipady'], self._str(0))
self.assertEqual(info['padx'], self._str(0))
self.assertEqual(info['pady'], self._str(0))
self.assertEqual(info['side'], 'top')
info = b.pack_info()
self.assertIsInstance(info, dict)
self.assertEqual(info['anchor'], 's')
self.assertEqual(info['expand'], self._str(1))
self.assertEqual(info['fill'], 'x')
self.assertEqual(info['in'], a)
self.assertEqual(info['ipadx'], self._str(5))
self.assertEqual(info['ipady'], self._str(2))
self.assertEqual(info['padx'], self._str(10))
self.assertEqual(info['pady'], self._str((5, 15)))
self.assertEqual(info['side'], 'right')
def test_pack_propagate(self):
pack, a, b, c, d = self.create2()
pack.configure(width=300, height=200)
a.pack_configure()
pack.pack_propagate(False)
self.root.update()
self.assertEqual(pack.winfo_reqwidth(), 300)
self.assertEqual(pack.winfo_reqheight(), 200)
pack.pack_propagate(True)
self.root.update()
self.assertEqual(pack.winfo_reqwidth(), 20)
self.assertEqual(pack.winfo_reqheight(), 40)
def test_pack_slaves(self):
pack, a, b, c, d = self.create2()
self.assertEqual(pack.pack_slaves(), [])
a.pack_configure()
self.assertEqual(pack.pack_slaves(), [a])
b.pack_configure()
self.assertEqual(pack.pack_slaves(), [a, b])
class PlaceTest(AbstractWidgetTest, unittest.TestCase):
def create2(self):
t = tkinter.Toplevel(self.root, width=300, height=200, bd=0)
t.wm_geometry('300x200+0+0')
f = tkinter.Frame(t, width=154, height=84, bd=2, relief='raised')
f.place_configure(x=48, y=38)
f2 = tkinter.Frame(t, width=30, height=60, bd=2, relief='raised')
self.root.update()
return t, f, f2
def test_place_configure_in(self):
t, f, f2 = self.create2()
self.assertEqual(f2.winfo_manager(), '')
with self.assertRaisesRegex(TclError, "can't place %s relative to "
"itself" % re.escape(str(f2))):
f2.place_configure(in_=f2)
if tcl_version >= (8, 5):
self.assertEqual(f2.winfo_manager(), '')
with self.assertRaisesRegex(TclError, 'bad window path name'):
f2.place_configure(in_='spam')
f2.place_configure(in_=f)
self.assertEqual(f2.winfo_manager(), 'place')
def test_place_configure_x(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f)
self.assertEqual(f2.place_info()['x'], '0')
self.root.update()
self.assertEqual(f2.winfo_x(), 50)
f2.place_configure(x=100)
self.assertEqual(f2.place_info()['x'], '100')
self.root.update()
self.assertEqual(f2.winfo_x(), 150)
f2.place_configure(x=-10, relx=1)
self.assertEqual(f2.place_info()['x'], '-10')
self.root.update()
self.assertEqual(f2.winfo_x(), 190)
with self.assertRaisesRegex(TclError, 'bad screen distance "spam"'):
f2.place_configure(in_=f, x='spam')
def test_place_configure_y(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f)
self.assertEqual(f2.place_info()['y'], '0')
self.root.update()
self.assertEqual(f2.winfo_y(), 40)
f2.place_configure(y=50)
self.assertEqual(f2.place_info()['y'], '50')
self.root.update()
self.assertEqual(f2.winfo_y(), 90)
f2.place_configure(y=-10, rely=1)
self.assertEqual(f2.place_info()['y'], '-10')
self.root.update()
self.assertEqual(f2.winfo_y(), 110)
with self.assertRaisesRegex(TclError, 'bad screen distance "spam"'):
f2.place_configure(in_=f, y='spam')
def test_place_configure_relx(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f)
self.assertEqual(f2.place_info()['relx'], '0')
self.root.update()
self.assertEqual(f2.winfo_x(), 50)
f2.place_configure(relx=0.5)
self.assertEqual(f2.place_info()['relx'], '0.5')
self.root.update()
self.assertEqual(f2.winfo_x(), 125)
f2.place_configure(relx=1)
self.assertEqual(f2.place_info()['relx'], '1')
self.root.update()
self.assertEqual(f2.winfo_x(), 200)
with self.assertRaisesRegex(TclError, 'expected floating-point number '
'but got "spam"'):
f2.place_configure(in_=f, relx='spam')
def test_place_configure_rely(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f)
self.assertEqual(f2.place_info()['rely'], '0')
self.root.update()
self.assertEqual(f2.winfo_y(), 40)
f2.place_configure(rely=0.5)
self.assertEqual(f2.place_info()['rely'], '0.5')
self.root.update()
self.assertEqual(f2.winfo_y(), 80)
f2.place_configure(rely=1)
self.assertEqual(f2.place_info()['rely'], '1')
self.root.update()
self.assertEqual(f2.winfo_y(), 120)
with self.assertRaisesRegex(TclError, 'expected floating-point number '
'but got "spam"'):
f2.place_configure(in_=f, rely='spam')
def test_place_configure_anchor(self):
f = tkinter.Frame(self.root)
with self.assertRaisesRegex(TclError, 'bad anchor "j"'):
f.place_configure(anchor='j')
with self.assertRaisesRegex(TclError, 'ambiguous anchor ""'):
f.place_configure(anchor='')
for value in 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center':
f.place_configure(anchor=value)
self.assertEqual(f.place_info()['anchor'], value)
def test_place_configure_width(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, width=120)
self.root.update()
self.assertEqual(f2.winfo_width(), 120)
f2.place_configure(width='')
self.root.update()
self.assertEqual(f2.winfo_width(), 30)
with self.assertRaisesRegex(TclError, 'bad screen distance "abcd"'):
f2.place_configure(width='abcd')
def test_place_configure_height(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, height=120)
self.root.update()
self.assertEqual(f2.winfo_height(), 120)
f2.place_configure(height='')
self.root.update()
self.assertEqual(f2.winfo_height(), 60)
with self.assertRaisesRegex(TclError, 'bad screen distance "abcd"'):
f2.place_configure(height='abcd')
def test_place_configure_relwidth(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, relwidth=0.5)
self.root.update()
self.assertEqual(f2.winfo_width(), 75)
f2.place_configure(relwidth='')
self.root.update()
self.assertEqual(f2.winfo_width(), 30)
with self.assertRaisesRegex(TclError, 'expected floating-point number '
'but got "abcd"'):
f2.place_configure(relwidth='abcd')
def test_place_configure_relheight(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, relheight=0.5)
self.root.update()
self.assertEqual(f2.winfo_height(), 40)
f2.place_configure(relheight='')
self.root.update()
self.assertEqual(f2.winfo_height(), 60)
with self.assertRaisesRegex(TclError, 'expected floating-point number '
'but got "abcd"'):
f2.place_configure(relheight='abcd')
def test_place_configure_bordermode(self):
f = tkinter.Frame(self.root)
with self.assertRaisesRegex(TclError, 'bad bordermode "j"'):
f.place_configure(bordermode='j')
with self.assertRaisesRegex(TclError, 'ambiguous bordermode ""'):
f.place_configure(bordermode='')
for value in 'inside', 'outside', 'ignore':
f.place_configure(bordermode=value)
self.assertEqual(f.place_info()['bordermode'], value)
def test_place_forget(self):
foo = tkinter.Frame(self.root)
foo.place_configure(width=50, height=50)
self.root.update()
foo.place_forget()
self.root.update()
self.assertFalse(foo.winfo_ismapped())
with self.assertRaises(TypeError):
foo.place_forget(0)
def test_place_info(self):
t, f, f2 = self.create2()
f2.place_configure(in_=f, x=1, y=2, width=3, height=4,
relx=0.1, rely=0.2, relwidth=0.3, relheight=0.4,
anchor='se', bordermode='outside')
info = f2.place_info()
self.assertIsInstance(info, dict)
self.assertEqual(info['x'], '1')
self.assertEqual(info['y'], '2')
self.assertEqual(info['width'], '3')
self.assertEqual(info['height'], '4')
self.assertEqual(info['relx'], '0.1')
self.assertEqual(info['rely'], '0.2')
self.assertEqual(info['relwidth'], '0.3')
self.assertEqual(info['relheight'], '0.4')
self.assertEqual(info['anchor'], 'se')
self.assertEqual(info['bordermode'], 'outside')
self.assertEqual(info['x'], '1')
self.assertEqual(info['x'], '1')
with self.assertRaises(TypeError):
f2.place_info(0)
def test_place_slaves(self):
foo = tkinter.Frame(self.root)
bar = tkinter.Frame(self.root)
self.assertEqual(foo.place_slaves(), [])
bar.place_configure(in_=foo)
self.assertEqual(foo.place_slaves(), [bar])
with self.assertRaises(TypeError):
foo.place_slaves(0)
class GridTest(AbstractWidgetTest, unittest.TestCase):
def tearDown(self):
cols, rows = self.root.grid_size()
for i in range(cols + 1):
self.root.grid_columnconfigure(i, weight=0, minsize=0, pad=0, uniform='')
for i in range(rows + 1):
self.root.grid_rowconfigure(i, weight=0, minsize=0, pad=0, uniform='')
self.root.grid_propagate(1)
if tcl_version >= (8, 5):
self.root.grid_anchor('nw')
super().tearDown()
def test_grid_configure(self):
b = tkinter.Button(self.root)
self.assertEqual(b.grid_info(), {})
b.grid_configure()
self.assertEqual(b.grid_info()['in'], self.root)
self.assertEqual(b.grid_info()['column'], self._str(0))
self.assertEqual(b.grid_info()['row'], self._str(0))
b.grid_configure({'column': 1}, row=2)
self.assertEqual(b.grid_info()['column'], self._str(1))
self.assertEqual(b.grid_info()['row'], self._str(2))
def test_grid_configure_column(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad column value "-1": '
'must be a non-negative integer'):
b.grid_configure(column=-1)
b.grid_configure(column=2)
self.assertEqual(b.grid_info()['column'], self._str(2))
def test_grid_configure_columnspan(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad columnspan value "0": '
'must be a positive integer'):
b.grid_configure(columnspan=0)
b.grid_configure(columnspan=2)
self.assertEqual(b.grid_info()['columnspan'], self._str(2))
def test_grid_configure_in(self):
f = tkinter.Frame(self.root)
b = tkinter.Button(self.root)
self.assertEqual(b.grid_info(), {})
b.grid_configure()
self.assertEqual(b.grid_info()['in'], self.root)
b.grid_configure(in_=f)
self.assertEqual(b.grid_info()['in'], f)
b.grid_configure({'in': self.root})
self.assertEqual(b.grid_info()['in'], self.root)
def test_grid_configure_ipadx(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad ipadx value "-1": '
'must be positive screen distance'):
b.grid_configure(ipadx=-1)
b.grid_configure(ipadx=1)
self.assertEqual(b.grid_info()['ipadx'], self._str(1))
b.grid_configure(ipadx='.5c')
self.assertEqual(b.grid_info()['ipadx'],
self._str(round(pixels_conv('.5c') * self.scaling)))
def test_grid_configure_ipady(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad ipady value "-1": '
'must be positive screen distance'):
b.grid_configure(ipady=-1)
b.grid_configure(ipady=1)
self.assertEqual(b.grid_info()['ipady'], self._str(1))
b.grid_configure(ipady='.5c')
self.assertEqual(b.grid_info()['ipady'],
self._str(round(pixels_conv('.5c') * self.scaling)))
def test_grid_configure_padx(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad pad value "-1": '
'must be positive screen distance'):
b.grid_configure(padx=-1)
b.grid_configure(padx=1)
self.assertEqual(b.grid_info()['padx'], self._str(1))
b.grid_configure(padx=(10, 5))
self.assertEqual(b.grid_info()['padx'], self._str((10, 5)))
b.grid_configure(padx='.5c')
self.assertEqual(b.grid_info()['padx'],
self._str(round(pixels_conv('.5c') * self.scaling)))
def test_grid_configure_pady(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad pad value "-1": '
'must be positive screen distance'):
b.grid_configure(pady=-1)
b.grid_configure(pady=1)
self.assertEqual(b.grid_info()['pady'], self._str(1))
b.grid_configure(pady=(10, 5))
self.assertEqual(b.grid_info()['pady'], self._str((10, 5)))
b.grid_configure(pady='.5c')
self.assertEqual(b.grid_info()['pady'],
self._str(round(pixels_conv('.5c') * self.scaling)))
def test_grid_configure_row(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad (row|grid) value "-1": '
'must be a non-negative integer'):
b.grid_configure(row=-1)
b.grid_configure(row=2)
self.assertEqual(b.grid_info()['row'], self._str(2))
def test_grid_configure_rownspan(self):
b = tkinter.Button(self.root)
with self.assertRaisesRegex(TclError, 'bad rowspan value "0": '
'must be a positive integer'):
b.grid_configure(rowspan=0)
b.grid_configure(rowspan=2)
self.assertEqual(b.grid_info()['rowspan'], self._str(2))
def test_grid_configure_sticky(self):
f = tkinter.Frame(self.root, bg='red')
with self.assertRaisesRegex(TclError, 'bad stickyness value "glue"'):
f.grid_configure(sticky='glue')
f.grid_configure(sticky='ne')
self.assertEqual(f.grid_info()['sticky'], 'ne')
f.grid_configure(sticky='n,s,e,w')
self.assertEqual(f.grid_info()['sticky'], 'nesw')
def test_grid_columnconfigure(self):
with self.assertRaises(TypeError):
self.root.grid_columnconfigure()
self.assertEqual(self.root.grid_columnconfigure(0),
{'minsize': 0, 'pad': 0, 'uniform': None, 'weight': 0})
with self.assertRaisesRegex(TclError, 'bad option "-foo"'):
self.root.grid_columnconfigure(0, 'foo')
self.root.grid_columnconfigure((0, 3), weight=2)
with self.assertRaisesRegex(TclError,
'must specify a single element on retrieval'):
self.root.grid_columnconfigure((0, 3))
b = tkinter.Button(self.root)
b.grid_configure(column=0, row=0)
if tcl_version >= (8, 5):
self.root.grid_columnconfigure('all', weight=3)
with self.assertRaisesRegex(TclError, 'expected integer but got "all"'):
self.root.grid_columnconfigure('all')
self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 3)
self.assertEqual(self.root.grid_columnconfigure(3, 'weight'), 2)
self.assertEqual(self.root.grid_columnconfigure(265, 'weight'), 0)
if tcl_version >= (8, 5):
self.root.grid_columnconfigure(b, weight=4)
self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 4)
def test_grid_columnconfigure_minsize(self):
with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'):
self.root.grid_columnconfigure(0, minsize='foo')
self.root.grid_columnconfigure(0, minsize=10)
self.assertEqual(self.root.grid_columnconfigure(0, 'minsize'), 10)
self.assertEqual(self.root.grid_columnconfigure(0)['minsize'], 10)
def test_grid_columnconfigure_weight(self):
with self.assertRaisesRegex(TclError, 'expected integer but got "bad"'):
self.root.grid_columnconfigure(0, weight='bad')
with self.assertRaisesRegex(TclError, 'invalid arg "-weight": '
'should be non-negative'):
self.root.grid_columnconfigure(0, weight=-3)
self.root.grid_columnconfigure(0, weight=3)
self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 3)
self.assertEqual(self.root.grid_columnconfigure(0)['weight'], 3)
def test_grid_columnconfigure_pad(self):
with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'):
self.root.grid_columnconfigure(0, pad='foo')
with self.assertRaisesRegex(TclError, 'invalid arg "-pad": '
'should be non-negative'):
self.root.grid_columnconfigure(0, pad=-3)
self.root.grid_columnconfigure(0, pad=3)
self.assertEqual(self.root.grid_columnconfigure(0, 'pad'), 3)
self.assertEqual(self.root.grid_columnconfigure(0)['pad'], 3)
def test_grid_columnconfigure_uniform(self):
self.root.grid_columnconfigure(0, uniform='foo')
self.assertEqual(self.root.grid_columnconfigure(0, 'uniform'), 'foo')
self.assertEqual(self.root.grid_columnconfigure(0)['uniform'], 'foo')
def test_grid_rowconfigure(self):
with self.assertRaises(TypeError):
self.root.grid_rowconfigure()
self.assertEqual(self.root.grid_rowconfigure(0),
{'minsize': 0, 'pad': 0, 'uniform': None, 'weight': 0})
with self.assertRaisesRegex(TclError, 'bad option "-foo"'):
self.root.grid_rowconfigure(0, 'foo')
self.root.grid_rowconfigure((0, 3), weight=2)
with self.assertRaisesRegex(TclError,
'must specify a single element on retrieval'):
self.root.grid_rowconfigure((0, 3))
b = tkinter.Button(self.root)
b.grid_configure(column=0, row=0)
if tcl_version >= (8, 5):
self.root.grid_rowconfigure('all', weight=3)
with self.assertRaisesRegex(TclError, 'expected integer but got "all"'):
self.root.grid_rowconfigure('all')
self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 3)
self.assertEqual(self.root.grid_rowconfigure(3, 'weight'), 2)
self.assertEqual(self.root.grid_rowconfigure(265, 'weight'), 0)
if tcl_version >= (8, 5):
self.root.grid_rowconfigure(b, weight=4)
self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 4)
def test_grid_rowconfigure_minsize(self):
with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'):
self.root.grid_rowconfigure(0, minsize='foo')
self.root.grid_rowconfigure(0, minsize=10)
self.assertEqual(self.root.grid_rowconfigure(0, 'minsize'), 10)
self.assertEqual(self.root.grid_rowconfigure(0)['minsize'], 10)
def test_grid_rowconfigure_weight(self):
with self.assertRaisesRegex(TclError, 'expected integer but got "bad"'):
self.root.grid_rowconfigure(0, weight='bad')
with self.assertRaisesRegex(TclError, 'invalid arg "-weight": '
'should be non-negative'):
self.root.grid_rowconfigure(0, weight=-3)
self.root.grid_rowconfigure(0, weight=3)
self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 3)
self.assertEqual(self.root.grid_rowconfigure(0)['weight'], 3)
def test_grid_rowconfigure_pad(self):
with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'):
self.root.grid_rowconfigure(0, pad='foo')
with self.assertRaisesRegex(TclError, 'invalid arg "-pad": '
'should be non-negative'):
self.root.grid_rowconfigure(0, pad=-3)
self.root.grid_rowconfigure(0, pad=3)
self.assertEqual(self.root.grid_rowconfigure(0, 'pad'), 3)
self.assertEqual(self.root.grid_rowconfigure(0)['pad'], 3)
def test_grid_rowconfigure_uniform(self):
self.root.grid_rowconfigure(0, uniform='foo')
self.assertEqual(self.root.grid_rowconfigure(0, 'uniform'), 'foo')
self.assertEqual(self.root.grid_rowconfigure(0)['uniform'], 'foo')
def test_grid_forget(self):
b = tkinter.Button(self.root)
c = tkinter.Button(self.root)
b.grid_configure(row=2, column=2, rowspan=2, columnspan=2,
padx=3, pady=4, sticky='ns')
self.assertEqual(self.root.grid_slaves(), [b])
b.grid_forget()
c.grid_forget()
self.assertEqual(self.root.grid_slaves(), [])
self.assertEqual(b.grid_info(), {})
b.grid_configure(row=0, column=0)
info = b.grid_info()
self.assertEqual(info['row'], self._str(0))
self.assertEqual(info['column'], self._str(0))
self.assertEqual(info['rowspan'], self._str(1))
self.assertEqual(info['columnspan'], self._str(1))
self.assertEqual(info['padx'], self._str(0))
self.assertEqual(info['pady'], self._str(0))
self.assertEqual(info['sticky'], '')
def test_grid_remove(self):
b = tkinter.Button(self.root)
c = tkinter.Button(self.root)
b.grid_configure(row=2, column=2, rowspan=2, columnspan=2,
padx=3, pady=4, sticky='ns')
self.assertEqual(self.root.grid_slaves(), [b])
b.grid_remove()
c.grid_remove()
self.assertEqual(self.root.grid_slaves(), [])
self.assertEqual(b.grid_info(), {})
b.grid_configure(row=0, column=0)
info = b.grid_info()
self.assertEqual(info['row'], self._str(0))
self.assertEqual(info['column'], self._str(0))
self.assertEqual(info['rowspan'], self._str(2))
self.assertEqual(info['columnspan'], self._str(2))
self.assertEqual(info['padx'], self._str(3))
self.assertEqual(info['pady'], self._str(4))
self.assertEqual(info['sticky'], 'ns')
def test_grid_info(self):
b = tkinter.Button(self.root)
self.assertEqual(b.grid_info(), {})
b.grid_configure(row=2, column=2, rowspan=2, columnspan=2,
padx=3, pady=4, sticky='ns')
info = b.grid_info()
self.assertIsInstance(info, dict)
self.assertEqual(info['in'], self.root)
self.assertEqual(info['row'], self._str(2))
self.assertEqual(info['column'], self._str(2))
self.assertEqual(info['rowspan'], self._str(2))
self.assertEqual(info['columnspan'], self._str(2))
self.assertEqual(info['padx'], self._str(3))
self.assertEqual(info['pady'], self._str(4))
self.assertEqual(info['sticky'], 'ns')
@requires_tcl(8, 5)
def test_grid_anchor(self):
with self.assertRaisesRegex(TclError, 'bad anchor "x"'):
self.root.grid_anchor('x')
with self.assertRaisesRegex(TclError, 'ambiguous anchor ""'):
self.root.grid_anchor('')
with self.assertRaises(TypeError):
self.root.grid_anchor('se', 'nw')
self.root.grid_anchor('se')
self.assertEqual(self.root.tk.call('grid', 'anchor', self.root), 'se')
def test_grid_bbox(self):
self.assertEqual(self.root.grid_bbox(), (0, 0, 0, 0))
self.assertEqual(self.root.grid_bbox(0, 0), (0, 0, 0, 0))
self.assertEqual(self.root.grid_bbox(0, 0, 1, 1), (0, 0, 0, 0))
with self.assertRaisesRegex(TclError, 'expected integer but got "x"'):
self.root.grid_bbox('x', 0)
with self.assertRaisesRegex(TclError, 'expected integer but got "x"'):
self.root.grid_bbox(0, 'x')
with self.assertRaisesRegex(TclError, 'expected integer but got "x"'):
self.root.grid_bbox(0, 0, 'x', 0)
with self.assertRaisesRegex(TclError, 'expected integer but got "x"'):
self.root.grid_bbox(0, 0, 0, 'x')
with self.assertRaises(TypeError):
self.root.grid_bbox(0, 0, 0, 0, 0)
t = self.root
# de-maximize
t.wm_geometry('1x1+0+0')
t.wm_geometry('')
f1 = tkinter.Frame(t, width=75, height=75, bg='red')
f2 = tkinter.Frame(t, width=90, height=90, bg='blue')
f1.grid_configure(row=0, column=0)
f2.grid_configure(row=1, column=1)
self.root.update()
self.assertEqual(t.grid_bbox(), (0, 0, 165, 165))
self.assertEqual(t.grid_bbox(0, 0), (0, 0, 75, 75))
self.assertEqual(t.grid_bbox(0, 0, 1, 1), (0, 0, 165, 165))
self.assertEqual(t.grid_bbox(1, 1), (75, 75, 90, 90))
self.assertEqual(t.grid_bbox(10, 10, 0, 0), (0, 0, 165, 165))
self.assertEqual(t.grid_bbox(-2, -2, -1, -1), (0, 0, 0, 0))
self.assertEqual(t.grid_bbox(10, 10, 12, 12), (165, 165, 0, 0))
def test_grid_location(self):
with self.assertRaises(TypeError):
self.root.grid_location()
with self.assertRaises(TypeError):
self.root.grid_location(0)
with self.assertRaises(TypeError):
self.root.grid_location(0, 0, 0)
with self.assertRaisesRegex(TclError, 'bad screen distance "x"'):
self.root.grid_location('x', 'y')
with self.assertRaisesRegex(TclError, 'bad screen distance "y"'):
self.root.grid_location('1c', 'y')
t = self.root
# de-maximize
t.wm_geometry('1x1+0+0')
t.wm_geometry('')
f = tkinter.Frame(t, width=200, height=100,
highlightthickness=0, bg='red')
self.assertEqual(f.grid_location(10, 10), (-1, -1))
f.grid_configure()
self.root.update()
self.assertEqual(t.grid_location(-10, -10), (-1, -1))
self.assertEqual(t.grid_location(-10, 0), (-1, 0))
self.assertEqual(t.grid_location(-1, 0), (-1, 0))
self.assertEqual(t.grid_location(0, -10), (0, -1))
self.assertEqual(t.grid_location(0, -1), (0, -1))
self.assertEqual(t.grid_location(0, 0), (0, 0))
self.assertEqual(t.grid_location(200, 0), (0, 0))
self.assertEqual(t.grid_location(201, 0), (1, 0))
self.assertEqual(t.grid_location(0, 100), (0, 0))
self.assertEqual(t.grid_location(0, 101), (0, 1))
self.assertEqual(t.grid_location(201, 101), (1, 1))
def test_grid_propagate(self):
self.assertEqual(self.root.grid_propagate(), True)
with self.assertRaises(TypeError):
self.root.grid_propagate(False, False)
self.root.grid_propagate(False)
self.assertFalse(self.root.grid_propagate())
f = tkinter.Frame(self.root, width=100, height=100, bg='red')
f.grid_configure(row=0, column=0)
self.root.update()
self.assertEqual(f.winfo_width(), 100)
self.assertEqual(f.winfo_height(), 100)
f.grid_propagate(False)
g = tkinter.Frame(self.root, width=75, height=85, bg='green')
g.grid_configure(in_=f, row=0, column=0)
self.root.update()
self.assertEqual(f.winfo_width(), 100)
self.assertEqual(f.winfo_height(), 100)
f.grid_propagate(True)
self.root.update()
self.assertEqual(f.winfo_width(), 75)
self.assertEqual(f.winfo_height(), 85)
def test_grid_size(self):
with self.assertRaises(TypeError):
self.root.grid_size(0)
self.assertEqual(self.root.grid_size(), (0, 0))
f = tkinter.Scale(self.root)
f.grid_configure(row=0, column=0)
self.assertEqual(self.root.grid_size(), (1, 1))
f.grid_configure(row=4, column=5)
self.assertEqual(self.root.grid_size(), (6, 5))
def test_grid_slaves(self):
self.assertEqual(self.root.grid_slaves(), [])
a = tkinter.Label(self.root)
a.grid_configure(row=0, column=1)
b = tkinter.Label(self.root)
b.grid_configure(row=1, column=0)
c = tkinter.Label(self.root)
c.grid_configure(row=1, column=1)
d = tkinter.Label(self.root)
d.grid_configure(row=1, column=1)
self.assertEqual(self.root.grid_slaves(), [d, c, b, a])
self.assertEqual(self.root.grid_slaves(row=0), [a])
self.assertEqual(self.root.grid_slaves(row=1), [d, c, b])
self.assertEqual(self.root.grid_slaves(column=0), [b])
self.assertEqual(self.root.grid_slaves(column=1), [d, c, a])
self.assertEqual(self.root.grid_slaves(row=1, column=1), [d, c])
tests_gui = (
PackTest, PlaceTest, GridTest,
)
if __name__ == '__main__':
unittest.main()
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
| [
"Weldon@athletech.org"
] | Weldon@athletech.org |
842b53f556e40e7ee2ce73b314af3c48d09ff59a | 44b87d9faad99d542914c35410ba7d354d5ba9cd | /1/examples/srearch_a_letter.py | db0f0ae9e3b4cbc2f8eb95912e5afe20241d5f02 | [] | no_license | append-knowledge/pythondjango | 586292d1c7d0ddace3630f0d77ca53f442667e54 | 0e5dab580e8cc48e9940fb93a71bcd36e8e6a84e | refs/heads/master | 2023-06-24T07:24:53.374998 | 2021-07-13T05:55:25 | 2021-07-13T05:55:25 | 385,247,677 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 196 | py | x=input("enter the word ")
y=input("enter the letter you want to find ")
flag=0
for i in x:
if i in y:
flag=1
if flag==1:
print("entered word found ")
else:
print("not found") | [
"lijojose95@gmail.com"
] | lijojose95@gmail.com |
26c4e08d795fe5047e6277af93086c7796f3774d | f152d89efeebc5c00c54cf7819f539aec920aa2d | /reviewboard/webapi/decorators.py | 02674e04c176a61adb67121de06093f144b15995 | [
"MIT"
] | permissive | yang/reviewboard | c1c0cee37133004c2857ed6daac136697baa92dd | b893e0f28bc5d561124aaf09bc8b0e164f42c7d5 | refs/heads/master | 2021-01-18T11:04:37.694088 | 2010-11-27T00:09:27 | 2010-11-30T00:48:14 | 1,115,897 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,188 | py | from django.http import HttpRequest
from djblets.siteconfig.models import SiteConfiguration
from djblets.util.decorators import simple_decorator
from djblets.webapi.core import WebAPIResponse, WebAPIResponseError
from djblets.webapi.decorators import webapi_login_required, \
webapi_response_errors
from djblets.webapi.encoders import BasicAPIEncoder
from djblets.webapi.errors import NOT_LOGGED_IN
@webapi_response_errors(NOT_LOGGED_IN)
@simple_decorator
def webapi_check_login_required(view_func):
"""
A decorator that checks whether login is required on this installation
and, if so, checks if the user is logged in. If login is required and
the user is not logged in, they'll get a NOT_LOGGED_IN error.
"""
def _check(*args, **kwargs):
siteconfig = SiteConfiguration.objects.get_current()
if siteconfig.get("auth_require_sitewide_login"):
return webapi_login_required(view_func)(*args, **kwargs)
else:
return view_func(*args, **kwargs)
view_func.checks_login_required = True
return _check
def webapi_deprecated(deprecated_in, force_error_http_status=None,
default_api_format=None, encoders=[]):
"""Marks an API handler as deprecated.
``deprecated_in`` specifies the version that first deprecates this call.
``force_error_http_status`` forces errors to use the specified HTTP
status code.
``default_api_format`` specifies the default api format (json or xml)
if one isn't provided.
"""
def _dec(view_func):
def _view(*args, **kwargs):
if default_api_format:
request = args[0]
assert isinstance(request, HttpRequest)
method_args = getattr(request, request.method, None)
if method_args and 'api_format' not in method_args:
method_args = method_args.copy()
method_args['api_format'] = default_api_format
setattr(request, request.method, method_args)
response = view_func(*args, **kwargs)
if isinstance(response, WebAPIResponse):
response.encoders = encoders
if isinstance(response, WebAPIResponseError):
response.api_data['deprecated'] = {
'in_version': deprecated_in,
}
if (force_error_http_status and
isinstance(response, WebAPIResponseError)):
response.status_code = force_error_http_status
return response
return _view
return _dec
_deprecated_api_encoders = []
def webapi_deprecated_in_1_5(view_func):
from reviewboard.webapi.encoder import DeprecatedReviewBoardAPIEncoder
global _deprecated_api_encoders
if not _deprecated_api_encoders:
_deprecated_api_encoders = [
DeprecatedReviewBoardAPIEncoder(),
BasicAPIEncoder(),
]
return webapi_deprecated(
deprecated_in='1.5',
force_error_http_status=200,
default_api_format='json',
encoders=_deprecated_api_encoders)(view_func)
| [
"chipx86@chipx86.com"
] | chipx86@chipx86.com |
45d6cdcdcf5d305c813f5e774b4103af7fd3d956 | a6eddf9fb53e94131bf06fff52bb7207998a9d8f | /scoring/scoring.py | eddf4771be2bc6e1a7470c2284ede10d64d4d2ac | [
"MIT"
] | permissive | ugo-en/word-similarity-checker | 64b9b2a2131c2b7beb533788b0acda399b685006 | 0ba91bd2be3e39229dbd653994c8f21c90f4ae62 | refs/heads/main | 2023-06-03T01:16:18.841805 | 2021-06-20T23:25:57 | 2021-06-20T23:25:57 | 378,669,734 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 579 | py | from fuzzywuzzy import fuzz as fz
def score(word1,word2):
"""
This function uses a sequence matcher to check the two words and using the token set ratio, determine the similarity
in structure between two words, statements or phrases
:param word1:
:param word2:
:return:
"""
word1 = str(word1).lower().strip() if word1 is not None else ''
word2 = str(word2).lower().strip() if word2 is not None else ''
if word1 == word2:
return 100
else:
return f"{word1} and {word2} are {fz.token_set_ratio(word1, word2)}% similar."
| [
"ugochukwuenwachukwu@gmail.com"
] | ugochukwuenwachukwu@gmail.com |
2265b5e10e6f12363d3479fd90a21760370817c1 | 078b8189025dd0e40482dac41a0278841d64e41f | /nonap/bin/ctest | f9075389d11922878d031739a2ac77f54d07dd4a | [] | no_license | Priyesh1202/WakeUpDriver | 48d38e4980efde5d61287f7e09924ffd0e3d7972 | bc1bbf00ec381b46d3c0f96c389d8dc610408766 | refs/heads/master | 2022-09-15T03:43:32.881136 | 2020-05-22T05:21:12 | 2020-05-22T05:21:12 | 266,022,159 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 248 | #!/Users/mac/PycharmProjects/NoNapping/nonap/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from cmake import ctest
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(ctest())
| [
"priyesh.vakharia@gmail.com"
] | priyesh.vakharia@gmail.com | |
cfad3b76668f178f392f7b7a01d24f1ce83b31b6 | 278c14d55dc88f29146152cff1e5a8fbdecd56b6 | /movies/migrations/0001_initial.py | 81ee850016e3b9fc7fb1aa4e0b94558d8cc97a21 | [] | no_license | taras0024/movies_api | 4147feb28a584e82f8658ee6af12ce3ee2c4fb9d | 0736063298d82695205278e356acca6740790516 | refs/heads/master | 2023-06-26T22:12:20.958983 | 2021-08-02T12:58:51 | 2021-08-02T12:58:51 | 391,381,245 | 0 | 0 | null | 2021-08-02T12:58:51 | 2021-07-31T14:38:08 | JavaScript | UTF-8 | Python | false | false | 7,547 | py | # Generated by Django 3.2.5 on 2021-07-31 18:17
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Actor',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Имя')),
('age', models.PositiveSmallIntegerField(default=0, verbose_name='Возраст')),
('description', models.TextField(verbose_name='Описание')),
('image', models.ImageField(upload_to='actors/', verbose_name='Изображение')),
],
options={
'verbose_name': 'Актеры и режиссеры',
'verbose_name_plural': 'Актеры и режиссеры',
},
),
migrations.CreateModel(
name='Category',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=150, verbose_name='Категория')),
('description', models.TextField(verbose_name='Описание')),
('url', models.SlugField(max_length=160, unique=True)),
],
options={
'verbose_name': 'Категория',
'verbose_name_plural': 'Категории',
},
),
migrations.CreateModel(
name='Genre',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=150, verbose_name='Имя')),
('description', models.TextField(verbose_name='Описание')),
('url', models.SlugField(max_length=160, unique=True)),
],
options={
'verbose_name': 'Жанр',
'verbose_name_plural': 'Жанры',
},
),
migrations.CreateModel(
name='Movie',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100, verbose_name='Название')),
('tagline', models.CharField(default='', max_length=100, verbose_name='Слоган')),
('description', models.TextField(verbose_name='Описание')),
('poster', models.ImageField(upload_to='movies/', verbose_name='Постер')),
('year', models.PositiveSmallIntegerField(default=2021, verbose_name='Дата выхода')),
('country', models.CharField(max_length=30, verbose_name='Страна')),
('world_premiere', models.DateField(default=datetime.date.today, verbose_name='Премьера в мире')),
('budget', models.PositiveIntegerField(default=0, help_text='указывать суму в долларах', verbose_name='Бюджет')),
('fees_in_usa', models.PositiveIntegerField(default=0, help_text='указывать суму в долларах', verbose_name='Сборы в США')),
('fees_in_world', models.PositiveIntegerField(default=0, help_text='указывать суму в долларах', verbose_name='Сборы в мире')),
('url', models.SlugField(max_length=160, unique=True)),
('draft', models.BooleanField(default=False, verbose_name='Черновик')),
('actors', models.ManyToManyField(related_name='film_actor', to='movies.Actor', verbose_name='Актеры')),
('category', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='movies.category', verbose_name='Категория')),
('directors', models.ManyToManyField(related_name='film_director', to='movies.Actor', verbose_name='Режиссер')),
('genres', models.ManyToManyField(to='movies.Genre', verbose_name='Жанры')),
],
options={
'verbose_name': 'Фильм',
'verbose_name_plural': 'Фильмы',
},
),
migrations.CreateModel(
name='RatingStar',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('value', models.PositiveSmallIntegerField(default=0, verbose_name='Значение')),
],
options={
'verbose_name': 'Звезда рейтинга',
'verbose_name_plural': 'Звезды рейтинга',
'ordering': ['-value'],
},
),
migrations.CreateModel(
name='Review',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('email', models.EmailField(max_length=254)),
('name', models.CharField(max_length=100, verbose_name='Имя')),
('text', models.TextField(max_length=5000, verbose_name='Сообщение')),
('movie', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='movies.movie', verbose_name='фильм')),
('parent', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='movies.review', verbose_name='Родитель')),
],
options={
'verbose_name': 'Отзыв',
'verbose_name_plural': 'Отзывы',
},
),
migrations.CreateModel(
name='Rating',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ip', models.CharField(max_length=15, verbose_name='IP адрес')),
('movie', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='movies.movie', verbose_name='фильм')),
('star', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='movies.ratingstar', verbose_name='звезда')),
],
options={
'verbose_name': 'Рейтинг',
'verbose_name_plural': 'Рейтинги',
},
),
migrations.CreateModel(
name='MovieShots',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100, verbose_name='Заголовок')),
('description', models.TextField(verbose_name='Описание')),
('image', models.ImageField(upload_to='movie_shots/', verbose_name='Изображение')),
('movie', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='movies.movie', verbose_name='Фильм')),
],
options={
'verbose_name': 'Кадр из фильмы',
'verbose_name_plural': 'Кадры из фильма',
},
),
]
| [
"74822918+taras0024@users.noreply.github.com"
] | 74822918+taras0024@users.noreply.github.com |
b502c34d90948fd8a14029ada56a2c31ec8154d9 | 22967425b2a8556092a6499bbf8dbb24d355d17d | /show_room/migrations/0003_auto_20190509_1302.py | 99f26050d6513c1736a883b10d285c0b4aec2fd9 | [] | no_license | avi202020/Car-management-System.Safaricom-Hackathon | 68936d9016a77bb325d2e551eeb46f427ee72571 | 42401877062080428cb24e03b9d08727165a6bdb | refs/heads/master | 2023-03-17T13:04:27.388669 | 2019-05-09T20:36:39 | 2019-05-09T20:36:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 627 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2019-05-09 10:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('show_room', '0002_auto_20190509_0724'),
]
operations = [
migrations.AddField(
model_name='vehicle',
name='deleted_at',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AddField(
model_name='vehicle',
name='is_deleted',
field=models.BooleanField(default=False),
),
]
| [
"ngahu@joels-MacBook-Pro.local"
] | ngahu@joels-MacBook-Pro.local |
d0f2925daf7db34217f561cf6b3a564ef62b0e35 | 6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4 | /93o6y6WKFpQKoDg4T_11.py | c80cfdfb6ad9743783da2aa0233e0db5d7d02133 | [] | no_license | daniel-reich/ubiquitous-fiesta | 26e80f0082f8589e51d359ce7953117a3da7d38c | 9af2700dbe59284f5697e612491499841a6c126f | refs/heads/master | 2023-04-05T06:40:37.328213 | 2021-04-06T20:17:44 | 2021-04-06T20:17:44 | 355,318,759 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 60 | py |
def sort_by_length(lst):
return sorted(lst , key = len)
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
d32ac14755d361830a569a982e178869af8f8ab2 | 5b166e7bb66bec25126ce6622162075956397d07 | /util/ptime.py | 9e8d0c87311e923abc944809a991fe3d56a1f8aa | [
"BSD-3-Clause"
] | permissive | nigeljonez/newpyfibot | 15f859c9434629a7d579346d0400f326dcad87b1 | de090f1521dee8523d4a083b9665298e4e97d847 | refs/heads/master | 2021-01-22T11:46:22.344509 | 2012-09-12T10:25:28 | 2012-09-12T10:25:28 | 936,129 | 2 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,715 | py | #!/usr/bin/python
# -*- coding: iso8859-1 -*-
## (c)2004 Timo Reunanen <parker _et_ wolfenstein _dit_ org>
import time
import re
_exact=r'''
^
(?P<hour> \d{1,2}) ## hour
[:.]
(?P<min> \d{2}) ## minutes
(?:
[:.]
(?P<sec>\d{2} ) ## secods (optional)
)?
$
'''
_add=r'''
^
[+]
(?: ## hour
(?P<hour> \d+)+h ## syntax: 1234h
)? ## optional
\s*
(?: ## minutes
(?P<min> \d+)+m ## syntax: 1234m
)? ## optional
\s*
(?: ## seconds
(?P<sec> \d+)+s? ## syntax: 1234s or 1234
)? ## optional
$
'''
exactRe=re.compile(_exact, re.VERBOSE | re.MULTILINE | re.I)
addRe=re.compile(_add, re.VERBOSE | re.MULTILINE | re.I)
class TimeException(Exception): pass
def convert(s):
s=s.strip()
m=exactRe.match(s)
if m:
tm=time.time()
year, mon, mday, hour, min, sec, wday, yday, isdst = time.localtime(tm)
hour=int(m.group('hour'))
min=int(m.group('min'))
sec=int(m.group('sec') or '00')
ret=time.mktime( (year, mon, mday, hour, min, sec, wday, yday, isdst) )
while ret < tm:
ret += 86400
return ret
m=addRe.match(s)
if m:
hour=int(m.group('hour') or '0')
min=int(m.group('min') or '0')
sec=int(m.group('sec') or '0')
addSecs=hour*3600 + min*60 + sec
return time.time()+addSecs
raise TimeException('Invalid syntax')
if __name__=='__main__':
year, mon, mday, hour, min, sec, wday, yday, isdst = time.localtime()
print (hour, min, sec)
print time.time()-time.mktime(time.localtime())
print convert('11.23')-time.time()
| [
"riku.lindblad@dda364a1-ef19-0410-af65-756c83048fb2"
] | riku.lindblad@dda364a1-ef19-0410-af65-756c83048fb2 |
3a737f83ba061fbfef963c7cd42c69dbf53fec5e | 1bbf0e6d0993346744644c4059638f410ca02225 | /hamm.py | c29d69ec20c2e27c344921468e9861aaf4a96bcf | [] | no_license | nickrod518/rosalind | 3e95d0dc369ca2f577de15f9212fdc06de9b1ac3 | 52e5deccdd414a422612b49927ff1912f6534ef9 | refs/heads/master | 2021-10-11T21:15:51.837771 | 2019-01-29T21:31:42 | 2019-01-29T21:31:42 | 125,309,314 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 165 | py | hamming_distance = 0
s = input()
t = input()
for i in range(len(s)):
if s[i] != t[i]:
hamming_distance = hamming_distance + 1
print(hamming_distance)
| [
"Nick.Rodriguez@dhgllp.com"
] | Nick.Rodriguez@dhgllp.com |
2fdec4c0f0f3dab907001d6f75807c4de79d3ff9 | 6f1cadc49bc86ea49fd32c64397bfecfd9666f19 | /C2/pulsar/implant/migrations/0002_auto_20150827_1851.py | ca655a540d156e556deace4637d8d630fee4b98d | [
"BSD-3-Clause"
] | permissive | killvxk/Pulsar-1 | f073c2273e9d4040acc3842963b018d920e78aa4 | d290c524674eabb0444ac8c0b1ee65ea1ad44f1f | refs/heads/master | 2020-06-24T22:38:25.551118 | 2019-07-27T03:45:25 | 2019-07-27T03:45:25 | 199,111,787 | 0 | 0 | null | 2019-07-27T03:44:52 | 2019-07-27T03:44:51 | null | UTF-8 | Python | false | false | 390 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('implant', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='implant',
name='uuid',
field=models.CharField(max_length=36),
),
]
| [
"root@localhost.localdomain"
] | root@localhost.localdomain |
23c32a446cf61a05dcb2d470239b1d3c0c4f49da | 794f225c248e84b29f03e5ae472bd995b8dd86a4 | /doppler/all_data/4-18/20130418-13_0_10_peak_combine.py | 48b82d42269036337f95766e2c30e0ba539b80ea | [] | no_license | yuyichao/jlab2s13 | 1113a537bf9f1d44ff96324f290a16abf265fb20 | 9b09c3af9f4d3311633996635ccf75f04a97c117 | refs/heads/master | 2023-02-21T18:08:12.739055 | 2013-09-14T03:52:57 | 2013-09-14T03:52:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,082 | py | fit2_s = [3.9008432047451302, 3.8773342085960469, 3.9957833609585491]
fit_a = [-1.2819999999999998, -1.2679999999999993, -1.2711428571428618]
fit2_a = [500.51428571428562, 500.68571428571403, 500.61428571428576]
fit_s = [0.012207605867885846, 0.0094353400058313219, 0.010353561336037447]
peaks = [{'name': ['f85_3_4'], 'pos': -7.9996981822594853, 'pos_s': 0.011013846947679092, 'pos_i_s': 0.9490858455586706, 'pos_i': 1500.5435641014496}, {'name': ['f85_3_3', 'f85_3_4'], 'pos': -8.2967573220130149, 'pos_s': 0.012724357233702065, 'pos_i_s': 1.4310526680215732, 'pos_i': 1614.4619747504282}, {'name': ['f85_3_2', 'f85_3_4'], 'pos': -8.4343291746150335, 'pos_s': 0.011786948704679416, 'pos_i_s': 1.2032517401363374, 'pos_i': 1668.7193509592228}, {'name': ['f85_3_2', 'f85_3_3'], 'pos': -8.720160977519825, 'pos_s': 0.012858045194454387, 'pos_i_s': 1.636463811009885, 'pos_i': 1782.4988462413753}, {'name': ['f85_3_4'], 'pos': -8.0039884835099357, 'pos_s': 0.011799133475740702, 'pos_i_s': 1.2268992252757378, 'pos_i': 3979.13796792023}, {'name': ['f85_3_3', 'f85_3_4'], 'pos': -8.2977243140836912, 'pos_s': 0.012888055408478675, 'pos_i_s': 1.448285143908029, 'pos_i': 4090.4422261406667}, {'name': ['f85_3_2', 'f85_3_4'], 'pos': -8.4342855941752237, 'pos_s': 0.011899552853659508, 'pos_i_s': 1.389826247547356, 'pos_i': 4143.611888534533}, {'name': ['f85_3_2', 'f85_3_3'], 'pos': -8.718160279442678, 'pos_s': 0.012775187457901651, 'pos_i_s': 1.631549880675381, 'pos_i': 4256.522759082934}, {'name': ['f85_3_4'], 'pos': -8.006015880564151, 'pos_s': 0.012275941194589106, 'pos_i_s': 1.3872586407085559, 'pos_i': 6457.781447953739}, {'name': ['f85_3_3', 'f85_3_4'], 'pos': -8.2955682322274473, 'pos_s': 0.012460840014492304, 'pos_i_s': 1.374847594661195, 'pos_i': 6568.516429897438}, {'name': ['f85_3_2', 'f85_3_4'], 'pos': -8.4359818820726122, 'pos_s': 0.011658198624886231, 'pos_i_s': 1.206166415622737, 'pos_i': 6622.468062521684}, {'name': ['f85_3_2', 'f85_3_3'], 'pos': -8.7168896916836989, 'pos_s': 0.012560068171244025, 'pos_i_s': 1.562662238805832, 'pos_i': 6734.273836322585}]
| [
"yyc1992@gmail.com"
] | yyc1992@gmail.com |
f238d04a62268f719a0026d5246ae6552ad08c38 | bf99b1b14e9ca1ad40645a7423f23ef32f4a62e6 | /AtCoder/arc/025a.py | eca2c9978b657cb946922fb4f5f37b40b06e0566 | [] | no_license | y-oksaku/Competitive-Programming | 3f9c1953956d1d1dfbf46d5a87b56550ff3ab3db | a3ff52f538329bed034d3008e051f30442aaadae | refs/heads/master | 2021-06-11T16:14:12.635947 | 2021-05-04T08:18:35 | 2021-05-04T08:18:35 | 188,639,647 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 135 | py | D = list(map(int, input().split()))
L = list(map(int, input().split()))
ans = 0
for d, l in zip(D, L):
ans += max(d, l)
print(ans) | [
"y.oksaku@stu.kanazawa-u.ac.jp"
] | y.oksaku@stu.kanazawa-u.ac.jp |
97a827d7b0708abd7097d9584f3982d0ecd0389a | 91dde0bebc61ced8d1891afdc67931b667324576 | /neutron/tests/functional/agent/linux/pinger.py | a79e8235683fd79ce5adf013d9a38ab0d2893bd6 | [
"Apache-2.0"
] | permissive | cernops/neutron | e7108657a8f038178c8420582be05d9c7e417ba1 | 0c0e233290a0012f4d8320d047de63f213984944 | refs/heads/master-patches | 2020-12-25T02:10:56.430751 | 2014-03-24T14:50:23 | 2015-02-09T12:09:05 | 31,379,379 | 3 | 1 | null | 2015-02-26T17:30:41 | 2015-02-26T17:30:41 | null | UTF-8 | Python | false | false | 1,802 | py | # Copyright (c) 2014 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class Pinger(object):
def __init__(self, testcase, timeout=1, max_attempts=1):
self.testcase = testcase
self._timeout = timeout
self._max_attempts = max_attempts
def _ping_destination(self, src_namespace, dest_address):
src_namespace.netns.execute(['ping', '-c', self._max_attempts,
'-W', self._timeout, dest_address])
def assert_ping_from_ns(self, src_ns, dst_ip):
try:
self._ping_destination(src_ns, dst_ip)
except RuntimeError:
self.testcase.fail("destination ip %(dst_ip)s is not replying "
"to ping from namespace %(src_ns)s" %
{'src_ns': src_ns.namespace, 'dst_ip': dst_ip})
def assert_no_ping_from_ns(self, src_ns, dst_ip):
try:
self._ping_destination(src_ns, dst_ip)
self.testcase.fail("destination ip %(dst_ip)s is replying to ping"
"from namespace %(src_ns)s, but it shouldn't" %
{'src_ns': src_ns.namespace, 'dst_ip': dst_ip})
except RuntimeError:
pass
| [
"mangelajo@redhat.com"
] | mangelajo@redhat.com |
41fc157c2f3b1045e9cea61068ad1773f69efd18 | fcdc5d3df5e947fc89ddb6ecb4c0cf73677a5213 | /blatt_2/MadGraph5_v1_3_20/ex_2/bin/change_compiler.py | 207c61313b8c31cf8954c9c513e708bd52d7afad | [] | no_license | harrypuuter/tp1 | 382fb9efe503c69f0249c46a7870ede088d8291d | e576e483dc77f6dcd477c73018ca2ea3955cd0c7 | refs/heads/master | 2021-01-10T11:38:16.467278 | 2016-01-27T16:28:46 | 2016-01-27T16:28:46 | 45,135,053 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,033 | py | #!/usr/bin/env python
import re, sys, os
g77 = re.compile('g77')
gfortran = re.compile('gfortran')
def mod_compilator(directory, new='gfortran'):
#define global regular expression
rule={'S-REGEXP_g77+gfortran+re.I':''}
if type(directory)!=list:
directory=[directory]
#search file
file_to_change=find_makefile_in_dir(directory)
for name in file_to_change:
text = open(name,'r').read()
if new == 'g77':
text= gfortran.sub('g77', text)
else:
text= g77.sub('gfortran', text)
open(name,'w').write(text)
def detect_current_compiler(path):
"""find the currnt compiler for the current directory"""
comp = re.compile("^\s*FC\s*=(g77|gfortran)\s*")
for line in open(path):
if comp.search(line):
compiler = comp.search(line).groups()[0]
if compiler == 'g77':
print 'Currently using g77, Will pass to gfortran'
elif compiler == "gfortran":
print 'Currently using gfortran, Will pass to g77'
else:
raise Exception, 'unrecognize compiler'
return compiler
def find_makefile_in_dir(directory):
""" retrun a list of all file startinf with makefile in the given directory"""
out=[]
#list mode
if type(directory)==list:
for name in directory:
out+=find_makefile_in_dir(name)
return out
#single mode
for name in os.listdir(directory):
if os.path.isdir(directory+'/'+name):
out+=find_makefile_in_dir(directory+'/'+name)
elif os.path.isfile(directory+'/'+name) and name.lower().startswith('makefile'):
out.append(directory+'/'+name)
elif os.path.isfile(directory+'/'+name) and name.lower().startswith('make_opt'):
out.append(directory+'/'+name)
return out
def rm_old_compile_file():
# remove all the .o files
os.path.walk('.', rm_file_extension, '.o')
# remove related libraries
libraries = ['libblocks.a', 'libgeneric_mw.a', 'libMWPS.a', 'libtools.a', 'libdhelas3.a',
'libdsample.a', 'libgeneric.a', 'libmodel.a', 'libpdf.a', 'libdhelas3.so', 'libTF.a',
'libdsample.so', 'libgeneric.so', 'libmodel.so', 'libpdf.so']
lib_pos='./lib'
[os.remove(os.path.join(lib_pos, lib)) for lib in libraries \
if os.path.exists(os.path.join(lib_pos, lib))]
def rm_file_extension( ext, dirname, names):
[os.remove(os.path.join(dirname, name)) for name in names if name.endswith(ext)]
def go_to_main_dir():
""" move to main position """
pos=os.getcwd()
last=pos.split(os.sep)[-1]
if last=='bin':
os.chdir(os.pardir)
return
list_dir=os.listdir('./')
if 'bin' in list_dir:
return
else:
sys.exit('Error: script must be executed from the main, bin or Python directory')
if "__main__"==__name__:
# Collect position to modify
directory=['Source']
pypgs = os.path.join(os.path.pardir, 'pythia-pgs')
madanalysis = os.path.join(os.path.pardir, 'MadAnalysis')
for d in [pypgs, madanalysis]:
if os.path.isdir(d):
directory.append(d)
# start the real work
go_to_main_dir()
if len(sys.argv) > 1:
if '-h' in sys.argv:
print 'change the compilator from g77/gfortran to the other one'
print 'If you want to force one run as ./bin/change_compiler.py g77'
sys.exit()
assert len(sys.argv) == 2
if sys.argv[-1] == 'g77':
print 'pass to g77'
new_comp = 'g77'
else:
print 'pass to gfortran'
new_comp = 'gfortran'
else:
old_comp = detect_current_compiler('./Source/make_opts')
if old_comp == 'g77':
new_comp = 'gfortran'
else:
new_comp = 'g77'
mod_compilator(directory, new_comp)
rm_old_compile_file()
print 'Done'
| [
"brommer.sebastian@gmail.com"
] | brommer.sebastian@gmail.com |
2eae17add959a016d7283acf078ab01ad7b91b0f | ac513f7dc549fc0dbc0e9a7ccaeb77991b7ce5ea | /pycoders/home/migrations/0010_auto_20190215_2124.py | bb713ce39344a617034dc3c67f46d9c222ec4921 | [] | no_license | Adarsh-Shrivastava-001/Codeutasava3.0 | 728cea794963c7a34549e5ca7918bf81f25b1838 | 0dc28e67ed8c572f4b194487f4d926de32997c31 | refs/heads/master | 2022-12-15T06:55:26.279237 | 2019-02-17T10:55:06 | 2019-02-17T10:55:06 | 170,688,965 | 0 | 2 | null | 2022-11-22T02:22:57 | 2019-02-14T12:37:52 | CSS | UTF-8 | Python | false | false | 739 | py | # Generated by Django 2.1.7 on 2019-02-15 21:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0009_product_description'),
]
operations = [
migrations.CreateModel(
name='SearchTerm',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(blank=True, max_length=100, null=True)),
],
),
migrations.AddField(
model_name='product',
name='search',
field=models.ManyToManyField(blank=True, related_name='search', to='home.SearchTerm'),
),
]
| [
"pupalerusikesh@gmail.com"
] | pupalerusikesh@gmail.com |
9bd86ffac705571ef4bfa149ecc3a36fde4e9145 | 9330310ef2074289824adb4aef2b3ded52f6463f | /doc/conf.py | 2ffb8fa2543f210354555137d2502cc9d85c78a9 | [] | no_license | RahulSundar/pyCSalgos | 7d94ec695da894d637c76822d3afd26d25e4d4b1 | c3fe7c00f6fdfa4843cde4beafeafe931f199252 | refs/heads/master | 2022-04-08T10:40:13.237110 | 2020-03-10T19:16:24 | 2020-03-10T19:16:24 | 273,650,976 | 1 | 0 | null | 2020-06-20T06:20:48 | 2020-06-20T06:20:47 | null | UTF-8 | Python | false | false | 8,284 | py | # -*- coding: utf-8 -*-
#
# pyCSalgos documentation build configuration file, created by
# sphinx-quickstart on Fri Jul 4 15:52:00 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'numpydoc'
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'pyCSalgos'
copyright = u'2014, Nicolae Cleju'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.1'
# The full version, including alpha/beta/rc tags.
release = '1.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#html_theme = 'default'
html_theme = "sphinxdoc"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'pyCSalgosdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'pyCSalgos.tex', u'pyCSalgos Documentation',
u'Nicolae Cleju', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pycsalgos', u'pyCSalgos Documentation',
[u'Nicolae Cleju'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'pyCSalgos', u'pyCSalgos Documentation',
u'Nicolae Cleju', 'pyCSalgos', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
| [
"nikcleju@gmail.com"
] | nikcleju@gmail.com |
fa8beb3f3c45d810e244afa3a207660de72aae1e | c829a8654d4adcba7944f1aa48c2643c2a2a2803 | /sony_utils/split.py | 64caf82d8c17086980dca4436a62a0b48901e234 | [] | no_license | muma378/Utils | d85390f84226b63474c815285acb6ce351ac0c22 | a6ae14f86de360bdabd9fa7f39cd8b05bbd505fb | refs/heads/master | 2020-05-21T13:35:51.908847 | 2017-02-05T06:11:45 | 2017-02-05T06:11:45 | 48,424,512 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,083 | py | import os
import sys
import subprocess
import datetime
CMD_TEMPLATE = "cut.exe {src_wav} {dst_wav} {start} {end}"
NAME = "emotion_F_"
DECODING = 'gb2312' if os.name=='nt' else 'utf-8'
# split the wav as the information provided by several columns
def split_by_cols(cols_file, src_wav, dst_dir='.', name_prefix=NAME):
with open(cols_file, 'r') as f:
counter = 0
for timeline in f:
start, end, text = map(lambda x: x.strip(), timeline.split("\t"))
to_sec = lambda x: str(float(x.split(":")[0])*60 + float(x.split(":")[1]))
start, end = to_sec(start), to_sec(end)
counter += 1
dst_file = os.path.join(dst_dir, unicode(name_prefix+str(counter))).encode(DECODING)
# to generate the wave
dst_wav = dst_file + '.wav'
cmd = CMD_TEMPLATE.format(**locals())
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
subprocess.check_call(cmd, shell=True)
# to generate the text
with open(dst_file+".txt", "w") as t:
t.write(text)
if __name__ == '__main__':
split_by_cols(sys.argv[1], sys.argv[2])
| [
"muma.378@163.com"
] | muma.378@163.com |
277571a417c6a61cf258823e99aa8cd8e87866d3 | d44bb073602c0bb772ddc6d0069a50f6c6ab2726 | /app/libs/token_auth.py | da506b199d502f25e5c9701d719a8819ccef0985 | [] | no_license | LinRuiBin/LrbFlaskApi | 9c1cdeb3dfd2eab8592366469f1649abc1c83799 | 79831f954f923800c7bf151499aa2b789f6e6b50 | refs/heads/master | 2020-04-22T09:35:24.441443 | 2019-11-18T07:07:13 | 2019-11-18T07:07:13 | 170,277,688 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,421 | py | """
Created by LRB on 2018/5/7.
"""
from collections import namedtuple
from flask import current_app, g, request
from flask_httpauth import HTTPBasicAuth
from itsdangerous import TimedJSONWebSignatureSerializer \
as Serializer, BadSignature, SignatureExpired
from app.libs.error_code import AuthFailed, Forbidden
from app.libs.scope import is_in_scope
__author__ = 'LRB'
auth = HTTPBasicAuth()
User = namedtuple('User', ['uid', 'ac_type', 'scope'])
@auth.verify_password
def verify_password(token, password):
# token
# HTTP 账号密码
# header key:value
# account qiyue
# 123456
# key=Authorization
# value =basic base64(qiyue:123456)
user_info = verify_auth_token(token)
if not user_info:
return False
else:
# request
g.user = user_info
return True
def verify_auth_token(token):
s = Serializer(current_app.config['SECRET_KEY'])
try:
data = s.loads(token)
except BadSignature:
raise AuthFailed(msg='token is invalid',
status=1002)
except SignatureExpired:
raise AuthFailed(msg='token is expired',
status=1003)
uid = data['uid']
ac_type = data['type']
scope = data['scope']
# request 视图函数
allow = is_in_scope(scope, request.endpoint)
if not allow:
raise Forbidden()
return User(uid, ac_type, scope)
| [
"3gtc@3gtcdeMac-mini.local"
] | 3gtc@3gtcdeMac-mini.local |
0b02b8215e812d6887a344afd2a09cde9a10285c | 6ca9afb63a27d57ef55f7decb98ad7904c43e49b | /curriculum-learning/ppo_lstm_combine_observation.py | 464abdd7755359efa13899c4cd2eaaf6ecacad40 | [] | no_license | binaryoung/COMP4026-MSc-Projects | 7a7c39002ec24b95568c7a0ddeeb2a8e1037b117 | 2e24f752c94e64baf74e28889ea5141c7436c0e4 | refs/heads/main | 2023-07-19T07:20:30.604564 | 2021-09-09T23:51:27 | 2021-09-09T23:51:27 | 384,158,652 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,065 | py | import math
from datetime import datetime
import os
from distutils.dir_util import copy_tree
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
import torch.multiprocessing as mp
from torch.utils.tensorboard import SummaryWriter
import numpy as np
import pandas as pd
import boxoban_level_collection as levelCollection
from boxoban_environment import BoxobanEnvironment
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Model
class PPO(nn.Module):
def __init__(self):
super(PPO, self).__init__()
self.encoder = nn.Sequential(
nn.Conv2d(7, 16, kernel_size=3, stride=1),
nn.ReLU(),
nn.Conv2d(16, 32, kernel_size=2, stride=1),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=2, stride=1),
nn.ReLU()
)
self.linear = nn.Sequential(
nn.Linear(2304, 256), # 64, 6, 6
nn.ReLU()
)
self.lstm = nn.LSTM(256, 256, 1)
self.combination_linear = nn.Sequential(
nn.Linear(512, 256), # 256 + 256
nn.ReLU()
)
self.actor_head = nn.Linear(256, 8)
self.critic_head = nn.Linear(256, 1)
def forward(self, x, hidden):
x = self.encoder(x)
x = x.view(x.size(0), -1)
x = self.linear(x)
observation = x
x = x.unsqueeze(0)
x, hidden = self.lstm(x, hidden)
x = x.squeeze(0)
# Combine LSTM output and observation
x = torch.cat((observation, x), dim=1)
x = self.combination_linear(x)
actor = F.softmax(self.actor_head(x), dim=-1)
critic = self.critic_head(x)
return actor, critic, hidden
# Use in calculating loss
def loss_forward(self, x, dones):
n_envs, n_steps = x.size(0), x.size(1)
x = x.view(-1, 7, 10, 10)
x = self.encoder(x)
x = x.view(x.size(0), -1)
x = self.linear(x)
observation = x
x = x.view(n_envs, n_steps, -1)
done_steps = (dones == True).any(0).nonzero().squeeze(1).tolist()
done_steps = [-1] + done_steps + ([] if done_steps[-1] == (n_steps - 1) else [n_steps-1])
hidden = torch.zeros((1, n_envs, 256), device=device)
cell = torch.zeros((1, n_envs, 256), device=device)
done = torch.full((n_envs, ), True, device=device)
rnn_outputs = []
for i in range(len(done_steps) - 1):
start_step = done_steps[i] + 1
end_step = done_steps[i+1]
hidden[:, done] = 0
cell[:, done] = 0
done = dones[:, end_step]
rnn_input = x[:, start_step: end_step+1].permute(1,0,2)
rnn_output, (hidden, cell) = self.lstm(rnn_input, (hidden, cell))
rnn_outputs.append(rnn_output.permute(1, 0, 2))
# assert sum([x.size(1) for x in rnn_outputs]) == n_steps
x = torch.cat(rnn_outputs, dim=1)
x = x.view(n_envs * n_steps, -1)
# Combine LSTM output and observation
x = torch.cat((observation, x), dim=1)
x = self.combination_linear(x)
actor = F.softmax(self.actor_head(x), dim=-1)
critic = self.critic_head(x)
return actor, critic
# Level collection process
def collection_worker(queue):
while True:
queue.put(levelCollection.random())
# Worker process
def worker(master, collection):
while True:
cmd, data = master.recv()
if cmd == 'step':
observation, reward, done, info = env.step(data)
if done:
(id, score, trajectory, room, topology) = collection.get()
env = BoxobanEnvironment(room, topology)
observation = env.observation
master.send((observation, reward, done, info))
elif cmd == 'reset':
(id, score, trajectory, room, topology) = collection.get()
env = BoxobanEnvironment(room, topology)
master.send(env.observation)
elif cmd == 'close':
master.close()
collection.close()
break
else:
raise NotImplementedError
# Parallel environments
class ParallelEnv:
def __init__(self, n_workers):
self.n_workers = n_workers
self.workers = []
self.master_ends, worker_ends = zip(*[mp.Pipe() for _ in range(n_workers)])
queue = mp.Queue(n_workers)
for worker_end in worker_ends:
p = mp.Process(target=worker, args=(worker_end, queue))
p.daemon = True
p.start()
self.workers.append(p)
p = mp.Process(target=collection_worker, args=(queue, ))
p.daemon = True
p.start()
self.collection = p
# Reset environments
def reset(self):
for master_end in self.master_ends:
master_end.send(('reset', None))
return np.stack([master_end.recv() for master_end in self.master_ends])
# Step in environments
def step(self, actions):
for master_end, action in zip(self.master_ends, actions):
master_end.send(('step', action))
results = [master_end.recv() for master_end in self.master_ends]
observations, rewards, dones, infos = zip(*results)
return np.stack(observations), np.stack(rewards), np.stack(dones), infos
# Close environments
def close(self):
for master_end in self.master_ends:
master_end.send(('close', None))
for worker in self.workers:
worker.join()
# Sample trajectories in environments
def sample(self, model, steps, gamma, lamda):
states = torch.zeros((self.n_workers, steps, 7, 10, 10), dtype=torch.float32, device=device)
values = torch.zeros((self.n_workers, steps), dtype=torch.float32, device=device)
actions = torch.zeros((self.n_workers, steps), dtype=torch.uint8, device=device)
log_probabilities = torch.zeros((self.n_workers, steps), dtype=torch.float32, device=device)
rewards = torch.zeros((self.n_workers, steps), dtype=torch.float32, device=device)
dones = torch.zeros((self.n_workers, steps), dtype=torch.bool, device=device)
advantages = torch.zeros((self.n_workers, steps), dtype=torch.float32, device=device)
observation = torch.tensor(self.reset(), device=device)
hidden = torch.zeros((1, self.n_workers, 256), device=device)
cell = torch.zeros((1, self.n_workers, 256), device=device)
for t in range(steps):
with torch.no_grad():
states[:, t] = observation
pi, v, (hidden, cell) = model(observation, (hidden, cell))
values[:, t] = v.squeeze(1)
p = Categorical(pi)
action = p.sample()
actions[:, t] = action
log_probabilities[:, t] = p.log_prob(action)
observation, reward, done, info = self.step(action.tolist())
observation = torch.tensor(observation, device=device)
rewards[:, t] = torch.tensor(reward, device=device)
dones[:, t] = torch.tensor(done, device=device)
hidden[:, done] = 0
cell[:, done] = 0
_, last_value, _ = model(observation, (hidden, cell))
last_value = last_value.detach().squeeze(1)
last_advantage = 0
# Compute GAE
for t in reversed(range(steps)):
mask = 1.0 - dones[:, t].int()
delta = rewards[:, t] + gamma * last_value * mask - values[:, t]
last_advantage = delta + gamma * lamda * last_advantage * mask
advantages[:, t] = last_advantage
last_value = values[:, t]
normalized_advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
targets = advantages + values
total_reward = rewards.sum().item()
return states, values, actions, log_probabilities, advantages, normalized_advantages, targets, dones, total_reward
# Compute loss
def compute_loss(model, states, values, actions, log_probabilities, advantages, normalized_advantages, targets, dones, clip_range, value_coefficient, entropy_coefficient):
values = values.view(-1)
actions = actions.view(-1)
log_probabilities = log_probabilities.view(-1)
normalized_advantages = normalized_advantages.view(-1)
targets = targets.view(-1)
pi, v = model.loss_forward(states, dones)
v = v.squeeze(1)
p = Categorical(pi)
log_actions = p.log_prob(actions)
ratio = torch.exp(log_actions - log_probabilities)
surrogate1 = ratio * normalized_advantages
surrogate2 = ratio.clamp(1-clip_range, 1+clip_range) * normalized_advantages
policy_loss = torch.min(surrogate1, surrogate2).mean()
clipped_values = values + (v - values).clamp(-clip_range, clip_range)
value_loss1 = (v - targets).square()
value_loss2 = (clipped_values - targets).square()
value_loss = 0.5 * torch.max(value_loss1, value_loss2).mean()
entropy = p.entropy().mean()
loss = -(policy_loss - value_coefficient * value_loss + entropy_coefficient * entropy)
return loss
def train():
learning_rate = 1e-4 # learning rate
gamma = 0.99 # gamma
lamda = 0.95 # GAE lambda
clip_range = 0.1 # surrogate objective clip range
value_coefficient = 0.5 # value coefficient in loss function
entropy_coefficient = 0.01 # entropy coefficient in loss function
max_grad_norm = 0.5 # max gradient norm
total_steps = 1e8 # number of timesteps
n_envs = 32 # number of environment copies simulated in parallel
n_sample_steps = 128 # number of steps of the environment per sample
n_mini_batches = 8 # number of training minibatches per update
# For recurrent policies, should be smaller or equal than number of environments run in parallel.
n_epochs = 4 # number of training epochs per update
batch_size = n_envs * n_sample_steps
n_envs_per_batch = n_envs // n_mini_batches
n_updates = math.ceil(total_steps / batch_size)
assert (n_envs % n_mini_batches == 0)
save_path = "./data"
[os.makedirs(f"{save_path}/{dir}") for dir in ["data", "model", "plot", "runs"] if not os.path.exists(f"{save_path}/{dir}")]
envs = ParallelEnv(n_envs)
model = PPO().to(device)
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
step = 0
log = pd.DataFrame([], columns=["time", "update", "step", "reward", "average_reward"])
writer = SummaryWriter()
for update in range(1, n_updates+1):
states, values, actions, log_probabilities, advantages, normalized_advantages, targets, dones, total_reward = envs.sample(model, n_sample_steps, gamma, lamda)
for _ in range(n_epochs):
indexes = torch.randperm(n_envs)
for i in range(0, n_envs, n_envs_per_batch):
mini_batch_indexes = indexes[i: i + n_envs_per_batch]
loss = compute_loss(
model,
states[mini_batch_indexes], values[mini_batch_indexes],
actions[mini_batch_indexes], log_probabilities[mini_batch_indexes],
advantages[mini_batch_indexes], normalized_advantages[mini_batch_indexes], targets[mini_batch_indexes],
dones[mini_batch_indexes],
clip_range, value_coefficient, entropy_coefficient
)
# Update weights
optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=max_grad_norm)
optimizer.step()
# Log training information
step += batch_size
reward = total_reward/n_envs
tail_rewards = log["reward"].tail(99)
average_reward = (tail_rewards.sum() + reward) / (tail_rewards.count() +1)
log.at[update] = [datetime.now(), update, step, reward, average_reward]
writer.add_scalar('Reward', reward, update)
writer.add_scalar('Average reward', average_reward, update)
print(f"[{datetime.now().strftime('%m-%d %H:%M:%S')}] {update},{step}: {reward:.2f}")
# Save data
if update % 122 == 0:
fig = log["average_reward"].plot().get_figure()
fig.savefig(f"{save_path}/plot/{step}.png")
copy_tree("./runs", f"{save_path}/runs")
torch.save(model.state_dict(), f"{save_path}/model/{step}.pkl")
log.to_csv(f"{save_path}/data/{step}.csv", index=False, header=True)
# Save data
fig = log["average_reward"].plot().get_figure()
fig.savefig(f"{save_path}/plot/{step}.png")
copy_tree("./runs", f"{save_path}/runs")
torch.save(model.state_dict(), f"{save_path}/model/{step}.pkl")
log.to_csv(f"{save_path}/data/{step}.csv", index=False, header=True)
envs.close()
if __name__ == '__main__':
train()
| [
"me@xiayang.me"
] | me@xiayang.me |
d032794e6b78ff7d03d03deda884cfbf3e772619 | caa175a933aca08a475c6277e22cdde1654aca7b | /acondbs/db/__init__.py | 5656bd250d55b0a328a26007e1eeb74511f46e9f | [
"MIT"
] | permissive | simonsobs/acondbs | 01d68ae40866461b85a6c9fcabdfbea46ef5f920 | d18c7b06474b0dacb1dcf1c6dbd1e743407645e2 | refs/heads/main | 2023-07-07T04:33:40.561273 | 2023-06-28T22:08:00 | 2023-06-28T22:08:00 | 239,022,783 | 0 | 1 | MIT | 2023-06-26T20:36:39 | 2020-02-07T21:07:46 | Python | UTF-8 | Python | false | false | 1,054 | py | """SQLAlchemy and DB related
This package contains functions, classes, and other objects that are
related to SQLAlchemy and the DB except ORM model declarations.
"""
from pathlib import Path
from flask import Flask
from flask_migrate import Migrate
from .cmds import (
backup_db_command,
dump_db_command,
export_csv_command,
import_csv_command,
init_db_command,
)
from .sa import sa
migrate = Migrate()
_MIGRATIONS_DIR = str(Path(__file__).resolve().parent.parent / 'migrations')
def init_app(app: Flask) -> None:
"""Initialize the Flask application object
This function is called by `create_app()` of Flask
Parameters
----------
app : Flask
The Flask application object, an instance of `Flask`
"""
sa.init_app(app)
migrate.init_app(app, sa, directory=_MIGRATIONS_DIR)
app.cli.add_command(init_db_command)
app.cli.add_command(dump_db_command)
app.cli.add_command(import_csv_command)
app.cli.add_command(export_csv_command)
app.cli.add_command(backup_db_command)
| [
"tai.sakuma@gmail.com"
] | tai.sakuma@gmail.com |
acb51fce28782b1e64bb7fd83ce39d45260ae110 | 175d6cff12514da71aafef6b9ff48dd56a87db2d | /alveus/widgets/customized_menu.py | 76d6dbee02fa885e376a161e4dfb7dd9543930bf | [
"MIT"
] | permissive | FrederikLehn/alveus | d309eea98bd36f06709c55a18f0855f38b5420a9 | 71a858d0cdd8a4bbd06a28eb35fa7a8a7bd4814b | refs/heads/main | 2023-06-26T02:29:59.236579 | 2021-07-30T11:07:17 | 2021-07-30T11:07:17 | 391,029,935 | 4 | 3 | null | null | null | null | UTF-8 | Python | false | false | 6,342 | py | import wx
from wx.lib.agw.flatmenu import FMRendererMgr, FMRenderer, FlatMenu, FlatMenuItem
from wx.lib.agw.flatmenu import FMRendererXP, FMRendererMSOffice2007, FMRendererVista
from wx.lib.agw.artmanager import ArtManager, DCSaver
import _icons as ico
class CustomFMRendererMgr(FMRendererMgr):
def __init__(self):
super().__init__()
#if hasattr(self, '_alreadyInitialized'):
# return
#self._alreadyInitialized = True
#self._currentTheme = StyleDefault
self._currentTheme = 0
self._renderers = []
self._renderers.append(CustomFMRenderer())
#self._renderers.append(FMRendererXP())
#self._renderers.append(FMRendererMSOffice2007())
#self._renderers.append(FMRendererVista())
class CustomFMRenderer(FMRendererVista):
def __init__(self):
super().__init__()
# self.menuBarFaceColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)
#
# self.buttonBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
# self.buttonFaceColour = ArtManager.Get().LightColour(self.buttonBorderColour, 75)
# self.buttonFocusBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
# self.buttonFocusFaceColour = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)
# self.buttonPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
# self.buttonPressedFaceColour = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)
#
# self.menuFocusBorderColour = wx.RED #wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
# self.menuFocusFaceColour = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)
# self.menuPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
# self.menuPressedFaceColour = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)
#
# self.menuBarFocusBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
# self.menuBarFocusFaceColour = ArtManager.Get().LightColour(self.buttonFocusBorderColour, 75)
# self.menuBarPressedBorderColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)
# self.menuBarPressedFaceColour = ArtManager.Get().LightColour(self.buttonPressedBorderColour, 60)
def DrawButtonColour(self, dc, rect, state, colour):
"""
Draws a button using the Vista theme.
:param `dc`: an instance of :class:`DC`;
:param `rect`: the an instance of :class:`Rect`, representing the button client rectangle;
:param integer `state`: the button state;
:param `colour`: a valid :class:`Colour` instance.
"""
artMgr = ArtManager.Get()
# Keep old pen and brush
dcsaver = DCSaver(dc)
# same colours as used on ribbon
outer = wx.Colour(242, 201, 88)
inner = wx.WHITE
top = wx.Colour(255, 227, 125)
bottom = wx.Colour(253, 243, 204)
bdrRect = wx.Rect(*rect)
filRect = wx.Rect(*rect)
filRect.Deflate(1, 1)
r1, g1, b1 = int(top.Red()), int(top.Green()), int(top.Blue())
r2, g2, b2 = int(bottom.Red()), int(bottom.Green()), int(bottom.Blue())
dc.GradientFillLinear(filRect, top, bottom, wx.SOUTH)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.SetPen(wx.Pen(outer))
dc.DrawRoundedRectangle(bdrRect, 3)
bdrRect.Deflate(1, 1)
dc.SetPen(wx.Pen(inner))
dc.DrawRoundedRectangle(bdrRect, 2)
class CustomMenu(FlatMenu):
def __init__(self, parent=None):
super().__init__(parent=parent)
self._rendererMgr = CustomFMRendererMgr()
def CustomPopup(self):
if self.GetMenuItems():
pos = wx.GetMousePosition()
self.Popup(wx.Point(pos.x, pos.y), self.GetParent())
# common item implementations for ease of use ----------------------------------------------------------------------
def AppendCollapseItem(self, method, bind_to=None):
return self.AppendGenericItem('Collapse all', method, bitmap=ico.collapse_16x16.GetBitmap(), bind_to=bind_to)
def AppendCopyItem(self, method, bind_to=None):
return self.AppendGenericItem('Copy', method, bitmap=ico.copy_16x16.GetBitmap(), bind_to=bind_to)
def AppendCutItem(self, method, bind_to=None):
return self.AppendGenericItem('Cut', method, bitmap=ico.cut_16x16.GetBitmap(), bind_to=bind_to)
def AppendDeleteItem(self, method, bind_to=None):
return self.AppendGenericItem('Delete', method, bitmap=ico.delete_16x16.GetBitmap(), bind_to=bind_to)
def AppendExpandItem(self, method, bind_to=None):
return self.AppendGenericItem('Expand all', method, bitmap=ico.expand_16x16.GetBitmap(), bind_to=bind_to)
def AppendExportExcel(self, method, bind_to=None):
return self.AppendGenericItem('Export to Excel', method, bitmap=ico.export_spreadsheet_16x16.GetBitmap(), bind_to=bind_to)
def AppendGenericItem(self, text, method, bitmap=wx.NullBitmap, bind_to=None):
if bind_to is None:
bind_to = self.GetParent()
item = CustomMenuItem(self, wx.ID_ANY, text, normalBmp=bitmap)
self.AppendItem(item)
bind_to.Bind(wx.EVT_MENU, method, item)
return item
def AppendOpenItem(self, method, bind_to=None):
return self.AppendGenericItem('Open', method, bitmap=ico.settings_page_16x16.GetBitmap(), bind_to=bind_to)
def AppendPasteItem(self, method, bind_to=None):
return self.AppendGenericItem('Paste', method, bitmap=ico.paste_16x16.GetBitmap(), bind_to=bind_to)
class CustomMenuItem(FlatMenuItem):
def __init__(self, parent, id=wx.ID_SEPARATOR, label="", helpString="", kind=wx.ITEM_NORMAL, subMenu=None,
normalBmp=wx.NullBitmap, disabledBmp=wx.NullBitmap, hotBmp=wx.NullBitmap):
super().__init__(parent, id=id, label=label, helpString=helpString, kind=kind, subMenu=subMenu,
normalBmp=normalBmp, disabledBmp=disabledBmp, hotBmp=hotBmp)
def SetBitmap(self, bmp):
self._normalBmp = bmp
| [
"noreply@github.com"
] | noreply@github.com |
a4293d97c9d3bbe71c06656a6165bb7e7a066120 | 7ea5d546ef433fb95e089033ca2373b413365c02 | /read.py | c42a82eaab610802f22ea8991fb842223e73b635 | [] | no_license | NIKKON-LAWRANCE/OCV-Python | 140fdbc2d6752afcd8a7627cb35785da256d6e1a | 6066115271273e0f2f70e1bffa62202fa01d3120 | refs/heads/main | 2023-06-25T22:59:16.606634 | 2021-07-24T11:08:38 | 2021-07-24T11:08:38 | 389,012,034 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 92 | py | import cv2 as cv
img = cv.imread('Photos/Cat-2.jpg')
cv.imshow('Cat-2',img)
cv.waitKey(0) | [
"write2subrata@outlook.com"
] | write2subrata@outlook.com |
0f09cb023d84fff197d03b8360e4b1da14b7a9d5 | 6969a1aa70b4eb7a33ba7d02b5d68530481582c4 | /double_integar.py | 00a792328eed7bff1109d217cde7a112a97c4f4d | [] | no_license | Diassia/Code-Wars-Practice | aa5122a495d5b348aaa4252f42f18902cddbfc1e | aeed92f2946a2462e5cb7e5016d4b421b6d0c4ce | refs/heads/master | 2023-02-18T02:58:27.591886 | 2021-01-15T11:16:19 | 2021-01-15T11:16:19 | 310,811,176 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 72 | py | def double_integer(i):
return i * 2
i = 2
print(double_integer(i)) | [
"shaw.kayleighemma@gmail.com"
] | shaw.kayleighemma@gmail.com |
29ec23545290463394c1ecc3c7fcde737362edd5 | 3b42fc083bd59cd0f16b256206e59e7c1286a219 | /diccionario.py | fab40d09beb8d01270b21bd57049c76a83d863ad | [] | no_license | robertdante/Python | 9ee63cba4c1cca1fc11cd318db9ab7d604aa0048 | 579ba688302db4d3e36b7eceea14e556b904c3ad | refs/heads/master | 2023-06-09T15:12:37.579033 | 2021-06-24T09:50:34 | 2021-06-24T09:50:34 | 355,795,936 | 0 | 0 | null | 2021-04-13T10:21:26 | 2021-04-08T06:56:18 | Python | UTF-8 | Python | false | false | 610 | py | #Crear un diccionerio
cancion = {
'artista' : 'metallica', #llave y valor
'cancion' : 'enter sandman',
'lanzamiento' : 1992,
'likes' : 3000
}
print(cancion)
#Acceder a un elemento concreto del diccionario
print(cancion['artista'])
print(cancion['cancion'])
#Utilizar un valor del diccionario como variable
grupo = cancion['artista']
print(f'Estoy escuchando a {grupo}')
#Agregar nuevos valores
cancion['genero'] = 'Heavy Metal'
print(cancion)
#Reemplazar valor existente
cancion['lanzamiento'] = 1993
print(cancion)
#Eliminar un valor
del cancion['lanzamiento']
print(cancion) | [
"robert.dante3@gmail.com"
] | robert.dante3@gmail.com |
d130c48d189ce6a8f79f9a900a9f651c67482890 | 37fd103f6b0de68512e3cb6098d0abb9220f5a7d | /Python from scratch/027_inclass_reg_ip.py | 65e07f0162c6062580b2d1a4687b6a61fbc22782 | [] | no_license | FlyingMedusa/PythonELTIT | 720d48089738b7e629cad888f0032df3a4ccea2c | 36ab01fc9d42337e3c76c59c383d7b1a6142f9b9 | refs/heads/master | 2020-09-11T18:17:17.825390 | 2020-04-21T16:38:03 | 2020-04-21T16:38:03 | 222,150,066 | 0 | 0 | null | 2020-04-21T16:38:04 | 2019-11-16T19:37:33 | Python | UTF-8 | Python | false | false | 471 | py | import re
words = ["eloelo320", "blah@", "192.168.0.1", "asd.asd.20"]
pattern = "^\w+$" # or (longer): "^([A-Z]|[a-z]|(\d))*$"
id_pattern = "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"
for word in words:
match = re.search(pattern, word)
if match:
print("matched")
else:
print("not matched")
print("*"*80)
for word in words:
match = re.search(id_pattern, word)
if match:
print("matched")
else:
print("not matched")
| [
"sleboda.m98@gmail.com"
] | sleboda.m98@gmail.com |
d1c5245e21bd7b2194b251a3d5c8575240a0d15b | 4a44462dcc68ba86e0d724b8beb936069cd86fb7 | /wetectron/modeling/poolers.py | abbf27d12261f63b8c31e186747caaf9ed38f42e | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Yang-sso/wetectron_cyyang | 63752c01cee64ab02b4e713c48118ccd50aa1368 | 42bfe4fc2483d7182c7824ac6384ebd6c3483db5 | refs/heads/main | 2023-03-30T04:33:05.625396 | 2021-04-01T03:58:01 | 2021-04-01T03:58:01 | 353,564,184 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,915 | py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torch.nn.functional as F
from torch import nn
from wetectron.layers import ROIAlign, ROIPool
from wetectron.config import cfg
from .utils import cat
class LevelMapper(object):
"""Determine which FPN level each RoI in a set of RoIs should map to based
on the heuristic in the FPN paper.
"""
def __init__(self, k_min, k_max, canonical_scale=224, canonical_level=4, eps=1e-6):
"""
Arguments:
k_min (int)
k_max (int)
canonical_scale (int)
canonical_level (int)
eps (float)
"""
self.k_min = k_min
self.k_max = k_max
self.s0 = canonical_scale
self.lvl0 = canonical_level
self.eps = eps
def __call__(self, boxlists):
"""
Arguments:
boxlists (list[BoxList])
"""
# Compute level ids
s = torch.sqrt(cat([boxlist.area() for boxlist in boxlists]))
# Eqn.(1) in FPN paper
target_lvls = torch.floor(self.lvl0 + torch.log2(s / self.s0 + self.eps))
target_lvls = torch.clamp(target_lvls, min=self.k_min, max=self.k_max)
return target_lvls.to(torch.int64) - self.k_min
class Pooler(nn.Module):
"""
Pooler for Detection with or without FPN.
It currently hard-code ROIAlign in the implementation,
but that can be made more generic later on.
Also, the requirement of passing the scales is not strictly necessary, as they
can be inferred from the size of the feature map / size of original image,
which is available thanks to the BoxList.
"""
def __init__(self, output_size, scales, sampling_ratio):
"""
Arguments:
output_size (list[tuple[int]] or list[int]): output size for the pooled region
scales (list[float]): scales for each Pooler
sampling_ratio (int): sampling ratio for ROIAlign
"""
super(Pooler, self).__init__()
poolers = []
for scale in scales:
if cfg.MODEL.ROI_BOX_HEAD.POOLER_METHOD == "ROIPool":
poolers.append(
ROIPool(output_size, spatial_scale=scale)
)
elif cfg.MODEL.ROI_BOX_HEAD.POOLER_METHOD == "ROIAlign":
poolers.append(
ROIAlign(output_size, spatial_scale=scale, sampling_ratio=sampling_ratio)
)
else:
raise ValueError('please use valid pooler function')
self.poolers = nn.ModuleList(poolers)
self.output_size = output_size
# get the levels in the feature map by leveraging the fact that the network always
# downsamples by a factor of 2 at each level.
lvl_min = -torch.log2(torch.tensor(scales[0], dtype=torch.float32)).item()
lvl_max = -torch.log2(torch.tensor(scales[-1], dtype=torch.float32)).item()
self.map_levels = LevelMapper(lvl_min, lvl_max)
def convert_to_roi_format(self, boxes):
concat_boxes = cat([b.bbox for b in boxes], dim=0)
device, dtype = concat_boxes.device, concat_boxes.dtype
ids = cat(
[
torch.full((len(b), 1), i, dtype=dtype, device=device)
for i, b in enumerate(boxes)
],
dim=0,
)
rois = torch.cat([ids, concat_boxes], dim=1)
return rois
def forward(self, x, boxes):
"""
Arguments:
x (list[Tensor]): feature maps for each level
boxes (list[BoxList]): boxes to be used to perform the pooling operation.
Returns:
result (Tensor)
"""
num_levels = len(self.poolers)
rois = self.convert_to_roi_format(boxes)
if num_levels == 1:
return self.poolers[0](x[0], rois)
levels = self.map_levels(boxes)
num_rois = len(rois)
num_channels = x[0].shape[1]
output_size = self.output_size[0]
dtype, device = x[0].dtype, x[0].device
result = torch.zeros(
(num_rois, num_channels, output_size, output_size),
dtype=dtype,
device=device,
)
for level, (per_level_feature, pooler) in enumerate(zip(x, self.poolers)):
idx_in_level = torch.nonzero(levels == level).squeeze(1)
rois_per_level = rois[idx_in_level]
result[idx_in_level] = pooler(per_level_feature, rois_per_level).to(dtype)
return result
def make_pooler(cfg, head_name):
resolution = cfg.MODEL[head_name].POOLER_RESOLUTION
scales = cfg.MODEL[head_name].POOLER_SCALES
sampling_ratio = cfg.MODEL[head_name].POOLER_SAMPLING_RATIO
pooler = Pooler(
output_size=(resolution, resolution),
scales=scales,
sampling_ratio=sampling_ratio,
)
return pooler
| [
"1005131989@qq.com"
] | 1005131989@qq.com |
3bd0738ae8c589c40d9afde3f06436f12a90c507 | e87bdc4ee3328f79358df088c4f30aa73312127a | /python/motap/schemamodels.py | c9327f64e43c791447b41ae99d31844b89560854 | [] | no_license | n-raghu/KnowledgeBase | c50d9033392a78c560c7a137672df04c8aef3d5e | 5ce1c261bac77dd0dbbc39a124409f0ac38ca6ad | refs/heads/master | 2023-06-22T15:38:34.076176 | 2021-07-20T05:36:39 | 2021-07-20T05:36:39 | 117,502,463 | 0 | 0 | null | 2021-06-10T16:06:25 | 2018-01-15T05:46:37 | Python | UTF-8 | Python | false | false | 374 | py | from typing import Any
from pydantic import BaseModel
class AddrSchema(BaseModel):
address_matched: Any
customerID: int
dob: str
income: int
bureauScore: int
applicationScore: int
maxDelL12M: int
allowedFoir: int
existingEMI: int
loanTenure: int
currentAddress: str
bureauAddress: str
rejected: Any
loanAmount: Any
| [
"raghu@LCHVWXVJ2.inspireme.local"
] | raghu@LCHVWXVJ2.inspireme.local |
73199b52b898b470c3bb8e2c68de555ebab6a237 | 354ff630d5eed81ffe67be28dd82b990a733a1cd | /pysim/information/histogram.py | b5c2e51802a07e918c9766dcc879d029036a221c | [
"MIT"
] | permissive | superpig99/pysim | 22ba1521c0002f815f5d074114109461e0cc35fc | 4cd5f0987d3cbdeba1c932ca845df1b0bd9d46bf | refs/heads/master | 2023-05-15T05:30:01.272708 | 2020-04-02T14:25:35 | 2020-04-02T14:25:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,655 | py | from typing import Union, Optional, Dict
import numpy as np
from scipy import stats
def hist_entropy(
X: np.ndarray,
bins: Union[str, int] = "auto",
correction: bool = True,
hist_kwargs: Optional[Dict] = {},
) -> float:
"""Calculates the entropy using the histogram of a univariate dataset.
Option to do a Miller Maddow correction.
Parameters
----------
X : np.ndarray, (n_samples)
the univariate input dataset
bins : {str, int}, default='auto'
the number of bins to use for the histogram estimation
correction : bool, default=True
implements the Miller-Maddow correction for the histogram
entropy estimation.
hist_kwargs: Optional[Dict], default={}
the histogram kwargs to be used when constructing the histogram
See documention for more details:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
Returns
-------
H_hist_entropy : float
the entropy for this univariate histogram
Example
-------
>> from scipy import stats
>> from pysim.information import histogram_entropy
>> X = stats.gamma(a=10).rvs(1_000, random_state=123)
>> histogram_entropy(X)
array(2.52771628)
"""
# get histogram
hist_counts = np.histogram(X, bins=bins, **hist_kwargs)
# create random variable
hist_dist = stats.rv_histogram(hist_counts)
# calculate entropy
H = hist_dist.entropy()
# MLE Estimator with Miller-Maddow Correction
if correction == True:
H += 0.5 * (np.sum(hist_counts[0] > 0) - 1) / hist_counts[0].sum()
return H
| [
"emanjohnson91@gmail.com"
] | emanjohnson91@gmail.com |
229e0f9a4c85fab546dc07bac2a45ae56cccfd74 | dff8c4c57f16b6d53e03a63578cc1a7488603745 | /model_params/network_intrusion_detection_model_params.py | 4465287f54054f9bbf61095a8a707b2eab15119a | [] | no_license | lexmao/NuPic_Network_Anomaly_Detection | 062ae519860a50c86b5edacffe5b78583f6d47d0 | 94dcbd04349c3c3e34b73ccaebe1e5f479eaeffe | refs/heads/master | 2021-05-01T13:41:21.867550 | 2015-11-17T18:35:35 | 2015-11-17T18:35:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,218 | py | MODEL_PARAMS = \
{ 'aggregationInfo': { 'days': 0,
'fields': [],
'hours': 0,
'microseconds': 0,
'milliseconds': 0,
'minutes': 0,
'months': 0,
'seconds': 0,
'weeks': 0,
'years': 0},
'model': 'CLA',
'modelParams': { 'anomalyParams': { u'anomalyCacheRecords': None,
u'autoDetectThreshold': None,
u'autoDetectWaitRecords': None},
'clParams': { 'alpha': 0.050050000000000004,
'clVerbosity': 0,
'regionName': 'CLAClassifierRegion',
'steps': '1'},
'inferenceType': 'TemporalAnomaly',
'sensorParams': { 'encoders': { '_classifierInput': { 'classifierOnly': True,
'fieldname': 'class',
'n': 121,
'name': '_classifierInput',
'type': 'SDRCategoryEncoder',
'w': 21},
u'class': { 'fieldname': 'class',
'n': 121,
'name': 'class',
'type': 'SDRCategoryEncoder',
'w': 21},
u'dst_bytes': None,
u'duration': None,
u'flag': None,
u'protocol_type': None,
u'service': None,
u'src_bytes': None},
'sensorAutoReset': None,
'verbosity': 0},
'spEnable': True,
'spParams': { 'columnCount': 2048,
'globalInhibition': 1,
'inputWidth': 0,
'maxBoost': 2.0,
'numActiveColumnsPerInhArea': 40,
'potentialPct': 0.8,
'seed': 1956,
'spVerbosity': 0,
'spatialImp': 'cpp',
'synPermActiveInc': 0.05,
'synPermConnected': 0.1,
'synPermInactiveDec': 0.05015},
'tpEnable': True,
'tpParams': { 'activationThreshold': 14,
'cellsPerColumn': 32,
'columnCount': 2048,
'globalDecay': 0.0,
'initialPerm': 0.21,
'inputWidth': 2048,
'maxAge': 0,
'maxSegmentsPerCell': 128,
'maxSynapsesPerSegment': 32,
'minThreshold': 11,
'newSynapseCount': 20,
'outputType': 'normal',
'pamLength': 3,
'permanenceDec': 0.1,
'permanenceInc': 0.1,
'seed': 1960,
'temporalImp': 'cpp',
'verbosity': 0},
'trainSPNetOnlyIfRequested': False},
'predictAheadTime': None,
'version': 1} | [
"sanketdesai@juniper.net"
] | sanketdesai@juniper.net |
45d7bb9e577d90e6669bedad91fe02a0067a2061 | 41cd1bcff0166ed3aab28a183a2837adaa2d9a07 | /allauth/account/decorators.py | eb906aad176d794c9e8a3407a9d1495c7ae1d76d | [
"MIT"
] | permissive | thomaspurchas/django-allauth | 694dde8615b90cd4768e7f9eda79fdcf6fe3cdb6 | d7a8b9e13456180648450431057a206afa689373 | refs/heads/master | 2022-02-04T03:18:25.851391 | 2013-05-20T11:26:55 | 2013-05-20T11:26:55 | 7,754,028 | 1 | 0 | MIT | 2022-02-01T23:04:02 | 2013-01-22T14:44:56 | Python | UTF-8 | Python | false | false | 1,627 | py | from django.contrib.auth.decorators import login_required
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.shortcuts import render
from .models import EmailAddress
from .utils import send_email_confirmation
def verified_email_required(function=None,
login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME):
"""
Even when email verification is not mandatory during signup, there
may be circumstances during which you really want to prevent
unverified users to proceed. This decorator ensures the user is
authenticated and has a verified email address. If the former is
not the case then the behavior is identical to that of the
standard `login_required` decorator. If the latter does not hold,
email verification mails are automatically resend and the user is
presented with a page informing him he needs to verify his email
address.
"""
def decorator(view_func):
@login_required(redirect_field_name=redirect_field_name,
login_url=login_url)
def _wrapped_view(request, *args, **kwargs):
if not EmailAddress.objects.filter(user=request.user,
verified=True).exists():
send_email_confirmation(request, request.user)
return render(request,
'account/verified_email_required.html')
return view_func(request, *args, **kwargs)
return _wrapped_view
if function:
return decorator(function)
return decorator
| [
"raymond.penners@intenct.nl"
] | raymond.penners@intenct.nl |
468d0a666c8113677278318e8707cab353abf5b9 | e3365bc8fa7da2753c248c2b8a5c5e16aef84d9f | /indices/nninsid.py | 467654f6a73883390386eb7cdecf2765d99eb6ea | [] | no_license | psdh/WhatsintheVector | e8aabacc054a88b4cb25303548980af9a10c12a8 | a24168d068d9c69dc7a0fd13f606c080ae82e2a6 | refs/heads/master | 2021-01-25T10:34:22.651619 | 2015-09-23T11:54:06 | 2015-09-23T11:54:06 | 42,749,205 | 2 | 3 | null | 2015-09-23T11:54:07 | 2015-09-18T22:06:38 | Python | UTF-8 | Python | false | false | 1,302 | py | ii = [('BentJDO2.py', 1), ('MarrFDI.py', 1), ('RogePAV2.py', 4), ('KembFFF.py', 1), ('RogePAV.py', 3), ('RennJIT.py', 5), ('LeakWTI2.py', 2), ('UnitAI.py', 3), ('KembFJ1.py', 1), ('WilkJMC3.py', 1), ('LeakWTI3.py', 2), ('PettTHE.py', 18), ('PeckJNG.py', 1), ('BailJD2.py', 1), ('AdamWEP.py', 33), ('FitzRNS3.py', 16), ('ClarGE2.py', 2), ('GellWPT2.py', 4), ('WilkJMC2.py', 8), ('CarlTFR.py', 5), ('RoscTTI3.py', 2), ('AinsWRR3.py', 2), ('BailJD1.py', 1), ('RoscTTI2.py', 1), ('CoolWHM.py', 3), ('CrokTPS.py', 2), ('ClarGE.py', 1), ('BuckWGM.py', 3), ('LyelCPG.py', 1), ('WestJIT2.py', 25), ('CrocDNL.py', 4), ('MedwTAI.py', 6), ('WadeJEB.py', 1), ('FerrSDO2.py', 1), ('KirbWPW2.py', 3), ('SoutRD2.py', 1), ('BackGNE.py', 7), ('LeakWTI.py', 1), ('SoutRD.py', 5), ('DickCSG.py', 2), ('BuckWGM2.py', 2), ('WheeJPT.py', 3), ('MereHHB3.py', 2), ('HowiWRL2.py', 1), ('BailJD3.py', 2), ('WilkJMC.py', 6), ('MackCNH.py', 1), ('WestJIT.py', 20), ('BabbCEM.py', 6), ('FitzRNS4.py', 7), ('DequTKM.py', 1), ('FitzRNS.py', 15), ('EdgeMHT.py', 1), ('BowrJMM.py', 2), ('FerrSDO.py', 1), ('RoscTTI.py', 1), ('KembFJ2.py', 1), ('LewiMJW.py', 4), ('BellCHM.py', 1), ('AinsWRR2.py', 2), ('BrewDTO.py', 4), ('JacoWHI.py', 1), ('ClarGE3.py', 4), ('FitzRNS2.py', 10), ('NortSTC.py', 1), ('KeigTSS.py', 1), ('KirbWPW.py', 5)] | [
"varunwachaspati@gmail.com"
] | varunwachaspati@gmail.com |
fd78af3570754694ae18160dcad79b077bc0eeb9 | 242086b8c6a39cbc7af3bd7f2fd9b78a66567024 | /python/PP4E-Examples-1.4/Examples/PP4E/Dbase/TableBrowser/dbview.py | 9975899912c220e9ca0a023de57601b57da0cc5b | [] | no_license | chuzui/algorithm | 7537d0aa051ac4cbe9f6a7ca9a3037204803a650 | c3006b24c4896c1242d3ceab43ace995c94f10c8 | refs/heads/master | 2021-01-10T13:05:30.902020 | 2015-09-27T14:39:02 | 2015-09-27T14:39:02 | 8,404,397 | 4 | 4 | null | null | null | null | UTF-8 | Python | false | false | 981 | py | ##################################################################
# view any existing shelve directly; this is more general than a
# "formtable.py shelve 1 filename" cmdline--only works for Actor;
# pass in a filename (and mode) to use this to browse any shelve:
# formtable auto picks up class from the first instance fetched;
# run dbinit1 to (re)initialize dbase shelve with a template.
##################################################################
from sys import argv
from formtable import *
from formgui import FormGui
mode = 'class'
file = '../data/mydbase-' + mode
if len(argv) > 1: file = argv[1] # dbview.py file? mode??
if len(argv) > 2: mode = argv[2]
if mode == 'dict':
table = ShelveOfDictionary(file) # view dictionaries
else:
table = ShelveOfInstance(file) # view class objects
FormGui(table).mainloop()
table.close() # close needed for some dbm
| [
"zui"
] | zui |
694d54351021516c58b602ce17e432ee15a16afa | 88e4eea8976f0e16882abd7745c76e6d036c95c6 | /app/main/service/static_service.py | 2d19fddcaac0e1430d65ea14f0958553b6472c6c | [] | no_license | akosfi/tandem-backend | f06e0fc3c0faac439acdc698152d9404e19c7627 | a918be9377c5283959e1f756a45ed7ad02bc49b9 | refs/heads/master | 2022-12-09T23:18:35.654598 | 2019-12-08T19:05:29 | 2019-12-08T19:05:29 | 217,534,366 | 0 | 0 | null | 2022-09-16T18:12:12 | 2019-10-25T13:00:03 | Python | UTF-8 | Python | false | false | 407 | py | from app.main.model.language import Language
from app.main.model.topic import Topic
from app.main.model.learning_goal import LearningGoal
def get_all_languages():
return Language \
.query \
.all()
def get_all_topics():
return Topic \
.query \
.all()
def get_all_learning_goals():
return LearningGoal \
.query \
.all()
| [
"fiakos1997@gmail.com"
] | fiakos1997@gmail.com |
2ff81651816ba76c5c00cb22c79aa48032295ac9 | c6884ab0176fdfae661781d14d82a1e4f3341ea1 | /Trainer.py | 37299aa463a1e94b5ec9b0019554be2d1138e117 | [] | no_license | Aiyai/BEAM | cc34f6f2ff8980a51bbb9733fb3118cbe42a1bd5 | 1e1af5b74aaf3873342966c75d1f9befe24af2f7 | refs/heads/main | 2023-06-16T13:43:59.229865 | 2021-07-07T02:34:21 | 2021-07-07T02:34:21 | 368,384,405 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,321 | py | import tensorflow as tf
import numpy as np
import random
import time
from Source2 import BEAM
from model import DQN
tf.app.flags.DEFINE_boolean("train", False, "학습모드. 게임을 화면에 보여주지 않습니다.")
FLAGS = tf.app.flags.FLAGS
MAX_EPISODE = 10000
TARGET_UPDATE_INTERVAL = 1000
TRAIN_INTERVAL = 4
OBSERVE = 100
sample_signals = 3
NUM_ACTION = 3
NOISE_POWER = 0.01
sess = tf.Session()
beam = BEAM(sample_signals)
brain = DQN(sess, sample_signals, NUM_ACTION)
rewards = tf.placeholder(tf.float32, [None])
tf.summary.scalar('avg.reward/ep.', tf.reduce_mean(rewards))
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
writer = tf.summary.FileWriter('logs', sess.graph)
summary_merged = tf.summary.merge_all()
brain.update_target_network()
epsilon = 1.0
# 프레임 횟수
time_step = 0
total_reward_list = []
for episode in range(MAX_EPISODE):
terminal = False
total_reward = 0
state = beam.reset()
brain.init_state(state)
while not terminal:
if np.random.rand() < epsilon:
action = random.randrange(NUM_ACTION)
else:
action = brain.get_action()
if epsilon > OBSERVE:
epsilon -= 0.001
state, reward, terminal = beam.step(action)
total_reward += reward
brain.remember(state, action, reward, terminal)
if time_step > OBSERVE and time_step % TRAIN_INTERVAL == 0:
# DQN 으로 학습을 진행합니다.
brain.train()
if time_step % TARGET_UPDATE_INTERVAL == 0:
# 타겟 네트웍을 업데이트 해 줍니다.
brain.update_target_network()
time_step += 1
total_reward_list.append(total_reward)
print("episode: %d reward: %f"%(time_step, total_reward))
total_reward_list.append(total_reward)
if episode % 10000 == 0:
summary = sess.run(summary_merged, feed_dict={rewards: total_reward_list})
writer.add_summary(summary, time_step)
total_reward_list = []
if episode % 100000 == 0:
saver.save(sess, 'model/dqn.ckpt', global_step=time_step) | [
"noreply@github.com"
] | noreply@github.com |
11c42f6ff62c800055b8f8fdd6208766d0f11118 | 083b88c2d8b3fe659c0409046ff9255ef773ce4d | /erpnext/hr/doctype/driving_license_category/driving_license_category.py | 594bacc0716184bc810bd91a6c3fb7eb45d84617 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | AmanRawat882/ErpNext-1 | 4293dd13f1d958f85190b524b5498f5d6da3f5b6 | d1f04f9a622977aaac6d5e4a1b122bb64561646d | refs/heads/master | 2020-03-30T10:13:25.573202 | 2018-10-01T15:20:32 | 2018-10-01T15:20:32 | 151,111,101 | 0 | 1 | NOASSERTION | 2018-10-01T15:30:57 | 2018-10-01T15:24:52 | Python | UTF-8 | Python | false | false | 278 | py | # -*- coding: utf-8 -*-
# Copyright (c) 2018, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class DrivingLicenseCategory(Document):
pass
| [
"31853960+AmanRawat882@users.noreply.github.com"
] | 31853960+AmanRawat882@users.noreply.github.com |
3397fdf03555cbfe28cc3fed54c3f4f02c8e6c2b | 091155389673325cfe8b0da3dc64c113f1ded707 | /playground/segmentation/coco/solo/solo.res50.fpn.coco.800size.1x/config.py | 66f251fa6baf96372bfaf789658e15cbd0595e82 | [
"Apache-2.0"
] | permissive | Megvii-BaseDetection/cvpods | 7b7c808257b757d7f94d520ea03b370105fb05eb | 2deea5dc659371318c8a570c644201d913a83027 | refs/heads/master | 2023-03-22T00:26:06.248877 | 2023-03-10T10:05:26 | 2023-03-10T10:05:26 | 318,124,806 | 659 | 91 | Apache-2.0 | 2023-03-10T10:05:28 | 2020-12-03T08:26:57 | Python | UTF-8 | Python | false | false | 1,606 | py | import os.path as osp
from cvpods.configs.solo_config import SOLOConfig
_config_dict = dict(
MODEL=dict(
WEIGHTS="detectron2://ImageNetPretrained/MSRA/R-50.pkl",
),
DATASETS=dict(
TRAIN=("coco_2017_train",),
TEST=("coco_2017_val",),
),
SOLVER=dict(
LR_SCHEDULER=dict(
NAME="WarmupMultiStepLR",
MAX_ITER=90000,
STEPS=(60000, 80000),
WARMUP_FACTOR=1.0 / 1000,
WARMUP_ITERS=500,
WARMUP_METHOD="linear",
GAMMA=0.1,
),
OPTIMIZER=dict(
NAME="SGD",
BASE_LR=0.01,
WEIGHT_DECAY=0.0001,
MOMENTUM=0.9,
),
CHECKPOINT_PERIOD=5000,
IMS_PER_BATCH=16,
IMS_PER_DEVICE=2,
BATCH_SUBDIVISIONS=1,
),
INPUT=dict(
AUG=dict(
TRAIN_PIPELINES=[
("ResizeShortestEdge",
dict(short_edge_length=(800,), max_size=1333, sample_style="choice")),
("RandomFlip", dict()),
],
TEST_PIPELINES=[
("ResizeShortestEdge",
dict(short_edge_length=800, max_size=1333, sample_style="choice")),
],
)
),
OUTPUT_DIR=osp.join(
'/data/Outputs/model_logs/cvpods_playground',
osp.split(osp.realpath(__file__))[0].split("playground/")[-1]
),
)
class CustomSOLOConfig(SOLOConfig):
def __init__(self):
super(CustomSOLOConfig, self).__init__()
self._register_configuration(_config_dict)
config = CustomSOLOConfig()
| [
"wangfeng02@megvii.com"
] | wangfeng02@megvii.com |
f35f61f558bf3f2eec45c5998c609a43851bb1f7 | a9f3f473b5fbf7903398aa76506cbf14f0f175c3 | /desafio022.py | d69317e5a948681622373b1cd222188a968fdb50 | [] | no_license | lucaalexandre/Exercicios_de_Revisao_PS | 9ff2ea34a8fed2be732d781460b3380b7e01b28d | d2f4083de72537498141e3a13249f90a4dff6954 | refs/heads/master | 2020-06-05T10:00:25.093908 | 2019-06-17T18:51:15 | 2019-06-17T18:51:15 | 192,401,448 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 135 | py | carros = ['bmw','fusca','chevete','nissan'] #alterando a ordem da lista de forma alfabetica
print(carros)
carros.sort()
print(carros)
| [
"lucaalexandrepp@gmail.com"
] | lucaalexandrepp@gmail.com |
6bd7da921ee4e5f2c38d8dd8832742960949e196 | caac09a412ed9783e31e6254ba937d2ff1495dc8 | /test/calculator_tests.py | 974b8a61d0acd5e288c2f2b26d39039e3047ccc2 | [
"MIT"
] | permissive | ace-racer/lint-ut-circleci | c01095e9e41137a80499a03a81075ec86b4a9862 | f1d6b43f97b5146c4a168636d8517a8d02a3b21e | refs/heads/master | 2020-08-29T07:15:51.532944 | 2019-10-28T05:30:34 | 2019-10-28T05:30:34 | 217,963,717 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 873 | py | import unittest
from calculator import Calculator
class CalculatorTests(unittest.TestCase):
def test_add(self):
calculator = Calculator()
self.assertEqual(calculator.add(10, 20), 30)
def test_subtract(self):
calculator = Calculator()
self.assertEqual(calculator.subtract(10, 20), -10)
def test_multiply(self):
calculator = Calculator()
self.assertEqual(calculator.multiply(10, 20), 20)
def test_divide(self):
calculator = Calculator()
self.assertEqual(calculator.divide(10, 20), 0.5)
def suite():
"""
Test suite
:return: The test suite
"""
suite = unittest.TestSuite()
suite.addTests(
unittest.TestLoader().loadTestsFromTestCase(CalculatorTests)
)
return suite
if __name__ == '__main__':
unittest.TextTestRunner(verbosity=2).run(suite()) | [
"anuragchatterjee92@gmail.com"
] | anuragchatterjee92@gmail.com |
3ca83b5ee9aa17f09f5494f17a549ed8845ac7fd | 962b3deeb5cdf8c6276f8f12e4140acfc355e380 | /pages/views.py | 72f7ce3e9a1d7afa3fe230a501957f751b8ccb54 | [] | no_license | Vanman007/DjangoHelloWorld | a61a1a531f0a0c6e62529685f480fd65b8417920 | 914313d27433cc2d6e8bff759a8ba3aa7bd075b0 | refs/heads/master | 2023-08-05T05:34:41.677359 | 2020-07-03T09:17:58 | 2020-07-03T09:17:58 | 276,859,194 | 0 | 0 | null | 2021-09-22T19:32:43 | 2020-07-03T09:20:08 | Python | UTF-8 | Python | false | false | 174 | py | from django.shortcuts import render
from django.http import HttpResponse
def homePageView(request):
return HttpResponse('Hello World!')
# Create your views here.
| [
"thom37q2@stud.kea.dk"
] | thom37q2@stud.kea.dk |
c3c87b8bb46040b5d54aafcfb934e3418f8026a0 | 00c983525359dd64253838ed262e8b5d58a83a51 | /myvenv/bin/tabulate | 4256cd35ab715b86987e5bb0af4c80ca7da497c7 | [] | no_license | pancham12/my-first-blog | a31bbb6c73b61ddd77a4a365198a58975ddb621e | 690414d8dcc4dfeedaced63fa4e541e6557caadd | refs/heads/main | 2023-01-24T22:15:49.230346 | 2020-12-07T12:44:04 | 2020-12-07T12:44:04 | 319,234,068 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 232 | #!/home/ctp/djangogirls/myvenv/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from tabulate import _main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(_main())
| [
"satishpandeyctp@gmail.com"
] | satishpandeyctp@gmail.com | |
92a70b4dae4aa1f4b18b52ea14ca07ed69d71f6a | 4ae6ea6cf39ef18e11b7e35387c3f955097885f5 | /mass_flask_core/tests/test_report.py | 6a594976432d084017810452037c58b85c71fff6 | [
"MIT"
] | permissive | tbehner/mass_server | 6f71ebcb9056914b1984275bc19b88d666f27c3e | 99523f7d845d7da9f3f213054fd1c718202dffe3 | refs/heads/master | 2020-03-27T15:31:12.963233 | 2018-09-13T11:33:46 | 2018-09-13T11:37:37 | 146,723,278 | 0 | 0 | null | 2018-08-30T08:57:15 | 2018-08-30T08:57:15 | null | UTF-8 | Python | false | false | 659 | py | from mass_flask_core.models import AnalysisSystem, Report, Sample
from mixer.backend.mongoengine import mixer
from mass_flask_core.tests import FlaskTestCase
class ReportTestCase(FlaskTestCase):
def test_is_repr_and_str_correct(self):
system = mixer.blend(AnalysisSystem, identifier_name='ReportTestSystem')
sample = mixer.blend(Sample, id='55cdd8e89b65211708b7da46')
obj = mixer.blend(Report, sample=sample, analysis_system=system)
self.assertEqual(obj.__repr__(), '[Report] 55cdd8e89b65211708b7da46 on ReportTestSystem')
self.assertEqual(obj.__str__(), '[Report] 55cdd8e89b65211708b7da46 on ReportTestSystem')
| [
"rumpf@cs.uni-bonn.de"
] | rumpf@cs.uni-bonn.de |
5338446b2f453b8f2ace178642776954ee701a35 | 87b9950749f574955e9e98dc6bc33ac54172afe4 | /sort.py | 46030c5769b34d17a13b340b1c126abc641de656 | [] | no_license | LapTQ/basic_stuff | 0d300477e84be1590ff1c87730c947e81b3d39ed | 553029bba822881fd53b3984b7b5fb27134f6663 | refs/heads/master | 2022-10-18T11:26:15.985049 | 2020-06-13T11:30:52 | 2020-06-13T11:30:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,334 | py | from math import*
S = [2, 4, 5, 2, 0, 0 ,11]
def selection_sort(S):
n = len(S)
while n != 0:
max_index = 0
for i in range(n):
if S[max_index] < S[i]:
max_index = i
S[n - 1], S[max_index] = S[max_index], S[n - 1]
n -= 1
def bubble_sort(S):
for t in range(len(S)):
for i in range(len(S) - 1):
if S[i] > S[i + 1]:
S[i], S[i + 1] = S[i + 1], S[i]
def insertion_sort(a):
for i in range(1, len(a)):
cur = a[i]
j = i
while j > 0 and a[j - 1] > cur:
a[j - 1], a[j] = a[j], a[j - 1]
j -= 1
def merge_sort(S, start, stop):
if start < stop - 1:
mid = (start + stop) // 2
merge_sort(S, start, mid)
merge_sort(S, mid, stop)
def merge(S, start, stop, mid):
S1 = S[start:mid]
S2 = S[mid:stop]
i = 0
j = 0
k = start
while i < len(S1) and j < len(S2):
if S1[i] < S2[j]:
S[k] = S1[i]
i += 1
k += 1
else:
S[k] = S2[j]
j += 1
k += 1
S[k:stop] = S1[i:] if i < len(S1) else S2[j:]
merge(S, start, stop, mid)
def quick_sort(S, start, stop):
if start < stop - 1:
def partition(S, start, stop):
pivot = stop - 1
candidate = start
while True:
while candidate < pivot and S[pivot] >= S[candidate]:
candidate += 1
if candidate == pivot:
break
S[pivot], S[candidate] = S[candidate], S[pivot]
pivot, candidate = candidate, pivot - 1
while candidate > pivot and S[pivot] <= S[candidate]:
candidate -= 1
if candidate == pivot:
break
S[pivot], S[candidate] = S[candidate], S[pivot]
pivot, candidate = candidate, pivot + 1
return pivot
pivot = partition(S, start, stop)
quick_sort(S, start, pivot)
quick_sort(S, pivot + 1, stop)
merge_sort(S, 0, len(S))
print(S)
| [
"phanmemmaytinhtql@gmail.com"
] | phanmemmaytinhtql@gmail.com |
da4c8a1958dd330eaf162d6671a89f44adfb9e9b | 2d055d8d62c8fdc33cda8c0b154e2b1e81814c46 | /python/demo_everyday/JCP092.py | 1c735a70fcd427c2fa6645875af40395d658774f | [
"MIT"
] | permissive | harkhuang/harkcode | d9ff7d61c3f55ceeeac4124a2a6ba8a006cff8c9 | faab86571ad0fea04c873569a806d2d7bada2e61 | refs/heads/master | 2022-05-15T07:49:23.875775 | 2022-05-13T17:21:42 | 2022-05-13T17:21:53 | 20,355,721 | 3 | 2 | MIT | 2019-05-22T10:09:50 | 2014-05-31T12:56:19 | C | GB18030 | Python | false | false | 292 | py | '''
【程序92】
题目:时间函数举例2
1.程序分析:
2.程序源代码:
'''
if __name__ == '__main__':
import time
start = time.time()
for i in range(3000):
print i
end = time.time()
print end - start
| [
"shiyanhk@gmail.com"
] | shiyanhk@gmail.com |
6666b3365e0d37967b4d4ae4f0b7c9dc074e3729 | 401d664697e0df149281ca94ea88f6eee3e609f0 | /python/03_hashmaps/serialization/14decoding_2.py | a5652a603b54d1c36a61569e0ce3aed7b266607d | [] | no_license | git-mih/Learning | 6806fd14f174b908781714e4c3d15da1c6f63307 | 36ea5cb3ed8da0fb2de43f718d4446bbf000a670 | refs/heads/main | 2023-08-30T02:09:18.299638 | 2021-10-26T01:36:23 | 2021-10-26T01:36:23 | 360,233,001 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,453 | py | import json
from decimal import Decimal
from datetime import datetime
from fractions import Fraction
# json.loads function parameters (parse_float, int, constant)
j = '''
{
"a": 100,
"b": 0.2,
"c": 0.5
}
'''
def make_decimal(arg): # arg: '0.2' <class 'str'> // arg: '0.5' <class 'str'>
return Decimal(arg)
# parse_float defines that, whenever the JSONDecorer see a json number to
# deserialize, it will delegate it to our custom function handle. so we can
# decide what to do with that 0.2 or 0.5 value.
json.loads(j, parse_float=make_decimal)
# {'a': 100, 'b': Decimal('0.2'), 'c': Decimal('0.5')}
# parse_int
def make_int_binary(arg): # arg: 100 <class 'str'>
return bin(int(arg))
json.loads(j, parse_int=make_int_binary)
# {'a': '0b1100100', 'b': 0.2, 'c': 0.5}
# parse_constant
def make_const_none(arg):
return None
j = '''
{
"a": Infinity,
"b": true,
"c": null
}
'''
json.loads(j, parse_constant=make_const_none)
# {'a': None, 'b': True, 'c': None}
# we can also use them together. parse_float, parse_int and constant.
#____________________________________________________________________________
# json.loads function parameter (object_hook x object_pairs_hook)
j = '''
{
"a": 1,
"b": 2,
"c": {
"c.1": 1,
"c.2": 2,
"c.3": {
"c.3.1": 1,
"c.3.2": 2
}
}
}
'''
def custom_decoder(arg):
print('decoding: ', arg, type(arg))
return arg
json.loads(j, object_hook=custom_decoder)
# we saw that the object_hook sends a dict for each json object it finds.
# decoding: {'c.3.1': 1, 'c.3.2': 2} <class 'dict'>
# decoding: {'c.1': 1, 'c.2': 2, 'c.3': {'c.3.1': 1, 'c.3.2': 2}} <class 'dict'>
# decoding: {'a': 1, 'b': 2, 'c': {'c.1': 1, 'c.2': 2, 'c.3': {'c.3.1': 1, 'c.3.2': 2}}} <class 'dict'>
# d = {'a': 1, 'b': 2, 'c': {'c.1': 1, 'c.2': 2, 'c.3': {'c.3.1': 1, 'c.3.2': 2}}}
# the object_pair_hook sends a list of tuples containing key, value pairs
# for each json object it finds.
json.loads(j, object_pairs_hook=custom_decoder)
# decoding: [('c.3.1', 1), ('c.3.2', 2)] <class 'list'>
# decoding: [('c.1', 1), ('c.2', 2), ('c.3', [('c.3.1', 1), ('c.3.2', 2)])] <class 'list'>
# decoding: [('a', 1), ('b', 2), ('c', [('c.1', 1), ('c.2', 2), ('c.3', [('c.3.1', 1), ('c.3.2', 2)])])] <class 'list'>
# d = [('a', 1), ('b', 2), ('c', [('c.1', 1), ('c.2', 2), ('c.3', [('c.3.1', 1), ('c.3.2', 2)])])]
# so we can decide how we want to work on customizing the deserialization.
| [
"git.mih@gmail.com"
] | git.mih@gmail.com |
59ad9eddb03fe048a25f77b63e3e08a4bbce689b | fca8b86b9b3e898cc2a95a8c5cde5d47d93669da | /meal_planner/meal_planner/urls.py | f97206489fee9c3de736c04b8b3e3ea04ecb00c2 | [] | no_license | 0mppula/Python_Web_Applications | 38233b45cad8061023a62b0ee37eba8e5fcec45b | 88b8491a54d544a917b3ab5c782d1cf42aff05e6 | refs/heads/master | 2023-04-22T22:58:59.533305 | 2021-05-06T15:58:27 | 2021-05-06T15:58:27 | 354,778,942 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 805 | py | """meal_planner URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.urls import path, include
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('meal_plans.urls')),
]
| [
"omppula_1@hotmail.com"
] | omppula_1@hotmail.com |
bb17338132d0fcb1250887d972dddb667bf6c522 | 4c45ade71fd51f4f1f0f8bc058595c1d96be9faa | /client.py | d831f4c1ac3a17984885d484850fe7872a5c72cd | [] | no_license | Eddieative/gopher_server | 95e256b96728dc42d8d4a075bf1965de269a15e8 | d02c71282bf8c7bf83b2fb0584d763f320ec3026 | refs/heads/master | 2021-01-01T04:19:49.840482 | 2016-04-28T12:02:33 | 2016-04-28T12:02:33 | 57,298,117 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 402 | py | import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addr = ('localhost', 9010)
sock.connect(addr)
try:
message = 'testfile'
sock.sendall(bytes(message.encode('utf-8')))
r_text = ''
while not r_text.endswith('.'):
getData = sock.recv(1024)
r_text += getData.decode('utf-8')
print(r_text)
finally:
print("closing socket")
sock.close()
| [
"aalshehri@luc.edu"
] | aalshehri@luc.edu |
b2fd2e9fee6bf8fa35803a124f8eeb8b9f912b67 | 9b8232dd0c3039fd850bf3d829f35fd394dde436 | /setup.py | 710522684373f77d479107f07d2a3dc977cd4b41 | [
"MIT"
] | permissive | solvip/icelandic_holidays | 019813e39e6857af353903c483ecd02aa27d8846 | d9da734b5c73d7c588d814b85da427d58d6767b9 | refs/heads/master | 2021-01-22T05:23:58.142176 | 2013-10-26T01:25:04 | 2013-10-26T01:25:04 | 11,962,358 | 1 | 1 | null | 2018-04-26T12:42:01 | 2013-08-07T22:43:17 | Python | UTF-8 | Python | false | false | 1,600 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Sölvi Páll Ásgeirsson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from distutils.core import setup
setup(name = "icelandic_holidays",
version = "0.6.1",
author = "Sölvi Páll Ásgeirsson",
author_email = "solvip@gmail.com",
url = "http://github.com/solvip/icelandic_holidays",
description = "A Python library written to determine if a day is an Icelandic holiday or a business day.",
long_description = open("README.md").read(),
py_modules = ["icelandic_holidays"]
)
| [
"solvip@gmail.com"
] | solvip@gmail.com |
68da50086cfa822b13bcf50fd59125d841ba6b0b | 618412e294ad520b71cbd8761ea92675634780ce | /training_scripts/mobileNet-3-generate_tfrecord_nasaweb.py | cc03cc07769858fcce17379171d37918cea89834 | [] | no_license | cloud-graphics-rendering/aiclients-pictor | 88ef4be3d06d9dce81cdbcfc8d54dda8a70f8fce | d5425b7ea72809f677f9b253667479140de8c08b | refs/heads/master | 2022-12-26T14:06:46.759092 | 2020-10-10T04:08:51 | 2020-10-10T04:08:51 | 289,418,510 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,303 | py | """
Usage:
# From tensorflow/models/
# Create train data:
python generate_tfrecord.py --image_path=xxx/figures --csv_input=data/train_labels.csv --output_path=train.record
# Create test data:
python generate_tfrecord.py --image_path=xxx/figures --csv_input=data/test_labels.csv --output_path=test.record
python mobileNet-3-generate_tfrecord_0ad.py --image_path=/home/tianyiliu/Documents/workspace/gaming/myprojects/renderBench/bench-datasets/0ad/ --csv_input=/home/tianyiliu/Documents/workspace/gaming/myprojects/renderBench/bench-datasets/0ad/0ad-annotations/tf.csv --output_path=/home/tianyiliu/Documents/workspace/gaming/myprojects/renderBench/bench-datasets/0ad/0ad-annotations/train.record
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import os
import io
import pandas as pd
import tensorflow as tf
from PIL import Image
from object_detection.utils import dataset_util
from collections import namedtuple, OrderedDict
flags = tf.app.flags
flags.DEFINE_string('image_path', '', 'Path to the original images')
flags.DEFINE_string('csv_input', '', 'Path to the CSV input')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
FLAGS = flags.FLAGS
# TO-DO replace this with label map
def class_text_to_int(row_label):
if row_label == 'space':
return 1
elif row_label == 'earth':
return 2
elif row_label == 'video':
return 3
elif row_label == 'restore':
return 4
elif row_label == 'home':
return 5
else:
print("miss matching, label:")
print(row_label)
None
#return 0
# None
#if row_label == 'rider':
# return 1
#else:
# return 0
def split(df, group):
data = namedtuple('data', ['filename', 'object'])
gb = df.groupby(group)
return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]
def create_tf_example(group, path):
with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid:
encoded_jpg = fid.read()
encoded_jpg_io = io.BytesIO(encoded_jpg)
image = Image.open(encoded_jpg_io)
width, height = image.size
filename = group.filename.encode('utf8')
image_format = b'jpg'
xmins = []
xmaxs = []
ymins = []
ymaxs = []
classes_text = []
classes = []
for index, row in group.object.iterrows():
xmins.append(row['xmin'] / width)
xmaxs.append(row['xmax'] / width)
ymins.append(row['ymin'] / height)
ymaxs.append(row['ymax'] / height)
classes_text.append(row['class'].encode('utf8'))
classes.append(class_text_to_int(row['class']))
tf_example = tf.train.Example(features=tf.train.Features(feature={
'image/height': dataset_util.int64_feature(height),
'image/width': dataset_util.int64_feature(width),
'image/filename': dataset_util.bytes_feature(filename),
'image/source_id': dataset_util.bytes_feature(filename),
'image/encoded': dataset_util.bytes_feature(encoded_jpg),
'image/format': dataset_util.bytes_feature(image_format),
'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
'image/object/class/label': dataset_util.int64_list_feature(classes),
}))
return tf_example
def main(_):
writer = tf.python_io.TFRecordWriter(FLAGS.output_path)
#path = os.path.join(os.getcwd(), 'images')
path = os.path.join(os.getcwd(), FLAGS.image_path)
#path = FLAGS.image_path;
examples = pd.read_csv(FLAGS.csv_input)
grouped = split(examples, 'filename')
for group in grouped:
tf_example = create_tf_example(group, path)
writer.write(tf_example.SerializeToString())
writer.close()
output_path = os.path.join(os.getcwd(), FLAGS.output_path)
print('Successfully created the TFRecords: {}'.format(output_path))
if __name__ == '__main__':
tf.app.run()
| [
"liuty10@gmail.com"
] | liuty10@gmail.com |
c03d219ec2ab38266c4a728f3e735d3a3b9a4a0f | c1074ebc044feed56e4eacce3dbc0132a331f170 | /Demo/nilearn_cache/joblib/nilearn/image/image/high_variance_confounds/func_code.py | 304e121de206df2b7032aad8469baf5f438eea09 | [
"MIT"
] | permissive | CSCI4850/S19-team4-project | e8833405605100289a93ad82d8de67c5239a25e5 | e6b7dc6a092a48feed16a6bd7695963075729525 | refs/heads/master | 2020-04-23T22:17:48.215317 | 2019-05-01T19:24:17 | 2019-05-01T19:24:17 | 171,497,021 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,419 | py | # first line: 28
def high_variance_confounds(imgs, n_confounds=5, percentile=2.,
detrend=True, mask_img=None):
""" Return confounds signals extracted from input signals with highest
variance.
Parameters
----------
imgs: Niimg-like object
See http://nilearn.github.io/manipulating_images/input_output.html
4D image.
mask_img: Niimg-like object
See http://nilearn.github.io/manipulating_images/input_output.html
If provided, confounds are extracted from voxels inside the mask.
If not provided, all voxels are used.
n_confounds: int
Number of confounds to return
percentile: float
Highest-variance signals percentile to keep before computing the
singular value decomposition, 0. <= `percentile` <= 100.
mask_img.sum() * percentile / 100. must be greater than n_confounds.
detrend: bool
If True, detrend signals before processing.
Returns
-------
v: numpy.ndarray
highest variance confounds. Shape: (number of scans, n_confounds)
Notes
------
This method is related to what has been published in the literature
as 'CompCor' (Behzadi NeuroImage 2007).
The implemented algorithm does the following:
- compute sum of squares for each signals (no mean removal)
- keep a given percentile of signals with highest variance (percentile)
- compute an svd of the extracted signals
- return a given number (n_confounds) of signals from the svd with
highest singular values.
See also
--------
nilearn.signal.high_variance_confounds
"""
from .. import masking
if mask_img is not None:
sigs = masking.apply_mask(imgs, mask_img)
else:
# Load the data only if it doesn't need to be masked
imgs = check_niimg_4d(imgs)
sigs = as_ndarray(imgs.get_data())
# Not using apply_mask here saves memory in most cases.
del imgs # help reduce memory consumption
sigs = np.reshape(sigs, (-1, sigs.shape[-1])).T
return signal.high_variance_confounds(sigs, n_confounds=n_confounds,
percentile=percentile,
detrend=detrend)
| [
"amc2bg@mtmail.mtsu.edu"
] | amc2bg@mtmail.mtsu.edu |
affceff77f635d0497cd5689551643a3bedcc0cc | 07d8ae8dd0a4d199bd4564c6bccae146eafedf95 | /src/main/2D_plot/plot_subproblem_perfect_electric.py | ec7edeb6b05abf1404ed0aaf3c368a58097b1608 | [] | no_license | eedxwang/3D-Facet-Finite-Elemen-Method | b202d4e49fc7ca8befc2c414840a00a73afdcc15 | 0a77c2eff28fb367f672304ac2896d13021f3f1e | refs/heads/master | 2021-10-25T09:03:38.171535 | 2019-04-03T08:41:13 | 2019-04-03T08:41:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,605 | py | clear_all()
import sys
reload(sys)
sys.setdefaultencoding("utf8")
import numpy as np
import matplotlib.pyplot as plt
import math
mu0=4*math.pi*pow(10,-7)
plt.rc('font',family='Times New Roman')
plt.close("all")
axis_font = { 'size':'24'}
#savepath=r"C:\Anderson\Pessoal\01_Doutorado\08_Relatorios_Papers\4_CEFC_2016\Four_pages\Figures"
data=r"C:\Anderson\Pessoal\01_Doutorado\10_Testes\35_Subdomain_Dular_2009_electric\GetDP_3D\bLine.dat"
data = np.genfromtxt(data,delimiter=' ')
x_FEM=(data[:,3])
y_FEM=(data[:,4])
z_FEM=(data[:,5])
#===================================================
# FEM - Completo
data=r"C:\Anderson\Pessoal\01_Doutorado\10_Testes\35_Subdomain_Dular_2009_electric\GetDP_3D\bLine.dat"
data = np.genfromtxt(data,delimiter=' ')
x_FEM=(data[:,3])
B_FEM_x=data[:,12]
B_FEM_y=data[:,13]
B_FEM_z=data[:,14]
B_list=list()
##===================================================
## FFEM SS + BS correction
data=r"C:\Anderson\Pessoal\01_Doutorado\10_Testes\35_Subdomain_Dular_2009_electric\FFEM_Complete\results\line_field.txt"
data = np.genfromtxt(data,delimiter=' ')
B_comp_x=(data[:,0])
B_comp_y=(data[:,1])
B_comp_z=(data[:,2])
##===================================================
## BS
data=r"C:\Anderson\Pessoal\01_Doutorado\10_Testes\35_Subdomain_Dular_2009_electric\FFEM_Complete\results\line_field_BS.txt"
data = np.genfromtxt(data,delimiter=' ')
B_BS_x=list()
B_BS_y=list()
B_BS_z=list()
for counter in xrange(len(x_FEM)):
if x_FEM[counter]>=0.015 and x_FEM[counter]<=0.035:
B_BS_x.append(0)
B_BS_y.append(0)
B_BS_z.append(0)
else:
B_BS_x.append(data[counter,0]*mu0)
B_BS_y.append(data[counter,1]*mu0)
B_BS_z.append(data[counter,2]*mu0)
#=========================
#Plots
plt.figure(1)
plt.plot(x_FEM, B_FEM_y,label='FEM',color="black",lw=3,linestyle='-',alpha=0.5)
#plt.plot((x_FEM), B_VS_y,label='$\mathbf{B}_2$',color="blue",linestyle='--',lw=4,alpha=0.5)
plt.plot((x_FEM), B_BS_y,label='$B_p$: BS',color="blue",linestyle='-',lw=3,alpha=0.5)
#plt.plot(x_FEM, B_comp_y,label='$B_q$',color="red",lw=1,linestyle='-')
plt.plot((x_FEM), B_comp_y+B_BS_y,label='$B_p+B_q$',color="black",linestyle='--',lw=3,alpha=1)
#plt.plot((x_FEM), B_VS_corry+B_BS_y,label='$\mathbf{B}_1+\mathbf{B}_2\,corrected$',color="red",linestyle='-.',lw=4,alpha=1)
plt.xlabel('Position along the device [m]',**axis_font)
plt.ylabel('By [T]',**axis_font)
legend = plt.legend(fontsize='24',loc=3)
frame = legend.get_frame()
frame.set_facecolor('0.90')
plt.xlim(xmax=0.15)
plt.tick_params(axis='x', labelsize=24)
plt.tick_params(axis='y', labelsize=24)
plt.tight_layout()
plt.grid(True)
| [
"nunes.anderson@gmail.com"
] | nunes.anderson@gmail.com |
6a5cafcf6f8b670c1c3a830f0502074d89470102 | 0dfc473870552ac9384a8b24e96046728a42f6ed | /utest/model/test_control.py | 1a17f6adb5d948f24ea2250696f2a05d093168e7 | [
"Apache-2.0",
"CC-BY-3.0"
] | permissive | rmf/robotframework | fecb4821fd308d107ae94ee3077a2d968ad9163d | a26cd326d1a397edc56993c453380dcd9b49e407 | refs/heads/master | 2023-09-03T07:04:30.300003 | 2021-11-16T11:01:32 | 2021-11-16T11:01:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,125 | py | import unittest
from robot.model import For, If, IfBranch, TestCase
from robot.utils.asserts import assert_equal
IF = If.IF
ELSE_IF = If.ELSE_IF
ELSE = If.ELSE
class TestFor(unittest.TestCase):
def test_string_reprs(self):
for for_, exp_str, exp_repr in [
(For(),
'FOR IN ',
"For(variables=(), flavor='IN', values=())"),
(For(('${x}',), 'IN RANGE', ('10',)),
'FOR ${x} IN RANGE 10',
"For(variables=('${x}',), flavor='IN RANGE', values=('10',))"),
(For(('${x}', '${y}'), 'IN ENUMERATE', ('a', 'b')),
'FOR ${x} ${y} IN ENUMERATE a b',
"For(variables=('${x}', '${y}'), flavor='IN ENUMERATE', values=('a', 'b'))"),
(For([u'${\xfc}'], 'IN', [u'f\xf6\xf6']),
u'FOR ${\xfc} IN f\xf6\xf6',
u"For(variables=[%r], flavor='IN', values=[%r])" % (u'${\xfc}', u'f\xf6\xf6'))
]:
assert_equal(str(for_), exp_str)
assert_equal(repr(for_), 'robot.model.' + exp_repr)
class TestIf(unittest.TestCase):
def test_type(self):
assert_equal(IfBranch().type, IF)
assert_equal(IfBranch(type=ELSE).type, ELSE)
assert_equal(IfBranch(type=ELSE_IF).type, ELSE_IF)
def test_type_with_nested_if(self):
branch = IfBranch()
branch.body.create_if()
assert_equal(branch.body[0].body.create_branch().type, IF)
assert_equal(branch.body[0].body.create_branch(ELSE_IF).type, ELSE_IF)
assert_equal(branch.body[0].body.create_branch(ELSE).type, ELSE)
def test_root_id(self):
assert_equal(If().id, None)
assert_equal(TestCase().body.create_if().id, None)
def test_branch_id_without_parent(self):
assert_equal(IfBranch().id, 'k1')
def test_branch_id_with_only_root(self):
root = If()
assert_equal(root.body.create_branch().id, 'k1')
assert_equal(root.body.create_branch().id, 'k2')
def test_branch_id_with_real_parent(self):
root = TestCase().body.create_if()
assert_equal(root.body.create_branch().id, 't1-k1')
assert_equal(root.body.create_branch().id, 't1-k2')
def test_string_reprs(self):
for if_, exp_str, exp_repr in [
(IfBranch(),
'IF None',
"IfBranch(type='IF', condition=None)"),
(IfBranch(condition='$x > 1'),
'IF $x > 1',
"IfBranch(type='IF', condition='$x > 1')"),
(IfBranch(ELSE_IF, condition='$x > 2'),
'ELSE IF $x > 2',
"IfBranch(type='ELSE IF', condition='$x > 2')"),
(IfBranch(ELSE),
'ELSE',
"IfBranch(type='ELSE', condition=None)"),
(IfBranch(condition=u'$x == "\xe4iti"'),
u'IF $x == "\xe4iti"',
u"IfBranch(type='IF', condition=%r)" % u'$x == "\xe4iti"'),
]:
assert_equal(str(if_), exp_str)
assert_equal(repr(if_), 'robot.model.' + exp_repr)
if __name__ == '__main__':
unittest.main()
| [
"peke@iki.fi"
] | peke@iki.fi |
6b1cb6b3f7a0424e75690bd37f4236afbe5ea656 | bb1de00b37731388b9cb8ffa3b03f477400724bf | /P10_LetterGradesWithInputValidation.py | dda2a64d50ce6c66337cbb211a79ba0a6b19b64d | [] | no_license | brandoni27/PythonClassScripts | 5a144b492dee1e7fcfbd4a43d293d3f9e7e19a9c | 33ae7c6a9f555d1d95787d7336f6b7ace0e74b3e | refs/heads/master | 2020-06-06T04:54:23.983084 | 2019-06-19T02:23:25 | 2019-06-19T02:23:25 | 192,642,711 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,310 | py | # LetterGradesWithInputValidation.py
# Brandon Washington
# 2/18/2019
# Python 3.6
# Description: Program which computes the sum and product of two numbers entered by the user.
print("Please enter your score")
score = int(input("score: "))
if score < 0:
print("ERROR. Please enter a score between 0 and 100")
elif score > 100:
print("You have a 'A+' Incredible!!!")
elif score > 90 and score < 100:
print("You have an 'A'")
elif score > 80 and score < 90:
print("You have a 'B'")
elif score > 70 and score < 80:
print("You have a 'C'")
elif score > 60 and score < 70:
print("You have a 'D'")
elif score < 60:
print("You have a 'F'")
'''
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 "/Users/Brando/Desktop/Python Code/P10_LetterGradesWithInputValidation.py"
Please enter your score
score: 110
You have a 'A+' Incredible!!!
Process finished with exit code 0
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 "/Users/Brando/Desktop/Python Code/P10_LetterGradesWithInputValidation.py"
Please enter your score
score: 95
You have an 'A'
Process finished with exit code 0
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 "/Users/Brando/Desktop/Python Code/P10_LetterGradesWithInputValidation.py"
Please enter your score
score: 85
You have a 'B'
Process finished with exit code 0
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 "/Users/Brando/Desktop/Python Code/P10_LetterGradesWithInputValidation.py"
Please enter your score
score: 75
You have a 'C'
Process finished with exit code 0
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 "/Users/Brando/Desktop/Python Code/P10_LetterGradesWithInputValidation.py"
Please enter your score
score: 65
You have a 'D'
Process finished with exit code 0
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 "/Users/Brando/Desktop/Python Code/P10_LetterGradesWithInputValidation.py"
Please enter your score
score: 57
You have a 'F'
Process finished with exit code 0
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 "/Users/Brando/Desktop/Python Code/P10_LetterGradesWithInputValidation.py"
Please enter your score
score: -24
ERROR. Please enter a score between 0 and 100
Process finished with exit code 0
''' | [
"noreply@github.com"
] | noreply@github.com |
29c48053784a6f6b40a6b5ba0c848c3ad67b2000 | 420eecae12598477a4005026a250a94bb872ef81 | /DAGMan/setup.py | 6c6ab5acc87dbf616290a6a869c1212b3cdc414c | [] | no_license | chadfreer/submit-examples | c65da1ebf7b6aee9b20a30a4d6b48a30bd02e1c1 | cc416b30c7ff7f133e7d3cd69854886a99e3fc91 | refs/heads/main | 2023-07-08T12:34:36.267389 | 2021-08-18T13:56:04 | 2021-08-18T13:56:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 738 | py | #!/usr/bin/env python
cwd = os.getcwd()
condor_script = cwd+'/submit.condor'
retries = 2
njobs = 3
submit_script = cwd+'/scratch/dag.submit'
f_out = open(submit_script,'w')
for job_num in range(njobs):
outfile_name = 'outfile_'+str(job_num)+'A.txt'
outfile_loc = cwd+'/output/'
f_out.write("JOB\tjob" + str(job_num) +'\t' + condor_script+'\n')
f_out.write("VARS\tjob" + str(job_num) +'\t' + 'input_float = "'+str(job_num) +'"\n')
f_out.write("VARS\tjob" + str(job_num) +'\t' + 'outfile_loc = "'+str(outfile_loc) +'"\n')
f_out.write("VARS\tjob" + str(job_num) +'\t' + 'outfile_name = "'+str(outfile_name) +'"\n')
f_out.write("RETRY\tjob" + str(job_num) +'\t' + str(retries)+'\n')
f_out.close()
print('Ouput: '+submit_script)
| [
"paus@mit.edu"
] | paus@mit.edu |
aac20397a75eddaa76c1781124bc4879759427c2 | b222a5b5a84ce5d4fa0ddb084cffd1619a84a17c | /sequence_equation/sequence_equation.py | 7a5ca7223035ab0aec3fa4aea0a2b337cc528cbd | [] | no_license | unabl4/HR | a51a5d461b3d126e1021646b9f210e099b8627b3 | 1aaf96734b8845c911d20a4955d3ffd64a2d16b9 | refs/heads/master | 2021-04-05T23:55:27.202440 | 2018-11-04T22:44:46 | 2018-11-04T22:44:46 | 125,117,758 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 409 | py | # https://www.hackerrank.com/challenges/permutation-equation/problem
#!/bin/python3
# Complete the permutationEquation function below.
def permutationEquation(p):
m = {}
for a,b in enumerate(p):
m[b] = a+1
return [m[m[x+1]] for x in range(len(p))]
n = int(input())
p = list(map(int, input().rstrip().split()))
result = permutationEquation(p)
print('\n'.join(map(str, result)))
| [
"unabl4@gmail.com"
] | unabl4@gmail.com |
0e27e62c78e34f3cfa3f84cec519ddb6dd185365 | f1d3feda6ac37a038dfb12edea7b68e98a6b21de | /star_wars.py | 8801f69861d314f503b32a1d0045bb588d960f7d | [] | no_license | V4stg/starwars_API | e3c34ecb0bbf13981c6880aa9dc72680b088bd5a | 89433b611ef5c423168c1cc3186a62e9b9e85c81 | refs/heads/master | 2021-09-08T18:52:47.081094 | 2018-03-11T18:44:05 | 2018-03-11T18:44:05 | 124,786,073 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,160 | py | from flask import Flask, session, redirect, url_for, request, render_template, flash
import data_handler
import hash_handler
import os
app = Flask(__name__)
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/signup', methods=['GET', 'POST'])
def signup():
if request.method == 'POST':
user_values = request.form.to_dict()
hash_password = hash_handler.hash_password(user_values['password'])
hash_verified_password = hash_handler.verify_password(user_values['verify_password'], hash_password)
if hash_verified_password is True:
user_values['password'] = hash_password
inserted_user = data_handler.insert_new_user(user_values)
if inserted_user:
session['user_id'] = inserted_user['id']
session['username'] = inserted_user['username']
return redirect(url_for('index'))
else:
return render_template('signup.html', alert="this username already exists")
else:
return render_template('signup.html', alert="passwords do not match")
else:
return render_template('signup.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user_data = data_handler.get_user_by_username(username)
is_login_successful = False
if user_data:
is_login_successful = hash_handler.verify_password(password, user_data['password'])
if is_login_successful:
session['user_id'] = user_data['id']
session['username'] = user_data['username']
else:
flash('Invalid username or password')
return redirect(url_for('index'))
@app.route('/logout')
def logout():
if session['user_id'] or session['username'] is not None:
session.clear()
return redirect(url_for('index'))
def main():
app.secret_key = os.environ.get('SECRET_KEY')
app.run(port=8000,
debug=True)
if __name__ == '__main__':
main()
| [
"lukacsb@gmail.com"
] | lukacsb@gmail.com |
35fc5efa1749d525fd3f6ab1157d93a404cbc1e3 | 4c657d5568cd49ae2ea9c8e6d22b522c6798a9bd | /urllibDemo/Test6.py | e46a579a07410868557762526ed6aae18c105599 | [] | no_license | Tralo/PyStudy | 696f1b2bbc74904ce9808097e792962d0f91bf63 | 4a9c6e4e03592ba3b827b66aad95d6560e3bbac1 | refs/heads/master | 2020-03-13T20:28:52.154544 | 2018-05-31T09:09:24 | 2018-05-31T09:09:24 | 130,459,370 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 109 | py | import requests
r = requests.get('http://github.com')
print(r.url)
print(r.status_code)
print(r.history)
| [
"13580548169@163.com"
] | 13580548169@163.com |
612213953cb108d3d16c0943e76c7e9036ae4c5f | ba54bb2549de073c044ec4933b86073476ac5204 | /Dynamic_Programming/max_subarray_product.py | 6ad9aa98ef8ec368d97b5b3dc67e4205d09b5eee | [] | no_license | varshanth/Coding_Algorithms | 412eb75c82727501176b6e35a5bbf98e1033f3e5 | 3fea767a1cc123d04149e43c57c85791add84cc6 | refs/heads/master | 2021-05-14T12:30:26.955680 | 2018-02-18T05:07:11 | 2018-02-18T05:07:11 | 116,407,303 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,107 | py | '''
LeetCode: Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number)
which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
Solution: O(n)
Algorithm:
1) Initialize 3 variables to the 1st element in the array.
a) An element big which keeps track of the local largest product of the
current contiguous sub array
b) An element small which keeps track of the local smallest product of the
current contiguous sub array
c) An element maximum which keeps track of the global largest product
contiguous sub array
2) Go through the array and calculate
a) The new big as the max of i) current element ii) current local largest
product * current element iii) current local smallest product * current
element. The involvement of the current element in all of the choices
ensures that the contiguousness is maintained even when a border element
appears next. e.g) 1 2 3 4 5 0 10, here at 0, the local largest product
will reset to 0
b) The new small as the min of i) current element ii) current local largest
product * current element iii) current local smallest product * current
element. The involvement of the current element in all of the choices
ensures that the contiguousness is maintained even when a border element
appears next. e.g) -1 -2 -3 -4 0 10, here at 0, the local smallest product
will reset to 0
3) Assign the new global maximum as the maximum of the current global
maximum and the local largest product
'''
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
len_nums = len(nums)
maximum = big = small = nums[0]
for i in range(1, len_nums):
new_big = max(nums[i], nums[i]*big, nums[i]*small)
new_small = min(nums[i], nums[i]*big, nums[i]*small)
big = new_big
small = new_small
maximum = max(maximum, big)
return maximum | [
"varshanth.rao99@gmail.com"
] | varshanth.rao99@gmail.com |
bad2caa5dc65eb15a125293126cdd9ef6b32b2a1 | 815b4c2cca8cc1dc0be8bc1c7e89128e1bf2c6d6 | /xnr_0429/xnr/timed_python_files/fb_tw_trans_timer.py | 24e6fa8e066fc102cfad2eb6842da2a11a9333bf | [] | no_license | BingquLee/xnr1 | d60e1a6b07757564bf105fa31d36c8ddeb14992b | dc41ff4efc97c681fef002e4cb7ba58e149f7ff3 | refs/heads/master | 2020-03-20T04:13:18.728441 | 2018-06-09T06:50:59 | 2018-06-09T06:50:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,615 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
#import os
import time
base_path = '/home/xnr1/xnr_0429/xnr/timed_python_files'
def test(index_pre, user_index, redis_task):
base_str = 'python /home/xnr1/xnr_0429/xnr/timed_python_files/fb_tw_trans_base.py -t ' + index_pre + ' -u ' + user_index + ' -r ' + redis_task
p_str1 = base_str
command_str = base_str
p_str2 = 'pgrep -f ' + '"' + command_str + '"'
process_ids = subprocess.Popen(p_str2, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
process_id_list = process_ids.stdout.readlines()
for process_id in process_id_list:
process_id = process_id.strip()
kill_str = 'kill -9 ' + process_id
p2 = subprocess.Popen(kill_str, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print p_str1
p2 = subprocess.Popen(p_str1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p2.stdout.readlines():
print 'line: ', line
if __name__ == '__main__':
print 'start'
print time.time()
print 'twitter flow text'
test(index_pre='twitter_flow_text_', user_index='twitter_user', redis_task='twitter_flow_text_trans_task')
print 'facebook flow text'
test(index_pre='facebook_flow_text_', user_index='facebook_user', redis_task='facebook_flow_text_trans_task')
print 'facebook user'
test(index_pre='facebook_user', user_index='facebook_user', redis_task='facebook_user_trans_task')
print 'twitter user'
test(index_pre='twitter_user', user_index='twitter_user', redis_task='twitter_user_trans_task')
| [
"dayuanhuiru@163.com"
] | dayuanhuiru@163.com |
3bab5fd0dca3ad22bc56bdd19efda33ed4dc420b | 14c357212705e10ccfd9be8f4e3a73c6858f9d9a | /test.py | 1169e62b18f339f491f1258c4e07265019e4c1a7 | [] | no_license | nemodrive/illumination-augumentation | 9fa5c4bd0e853532f789b5ac59ce68ff5d79dc49 | be4dc9386d8b3ddf32e54a9f9566ea4a9f48de3e | refs/heads/master | 2020-12-21T20:25:13.042247 | 2020-02-07T18:30:14 | 2020-02-07T18:30:14 | 236,547,617 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 260 | py | import torch
import torch.nn as nn
if __name__ == '__main__':
loss = nn.BCEWithLogitsLoss()
sigmoid = nn.Sigmoid()
target = sigmoid(torch.zeros(10))
prediction = sigmoid(torch.ones(10))
score = loss(prediction, prediction)
print(score) | [
"teodor.poncu@gmail.com"
] | teodor.poncu@gmail.com |
7d92be792fe9bc678bf2c071fd1541bc4b2eba8b | 39474a97c77a3375e352583a9e73b985f575f689 | /var/lib/buildbot/workers/openxt2/buildbot.tac | 498d5d555f9afb649c6d5e2e0aa4e0fc99905ef5 | [] | no_license | OXTbuilders/builder2019 | f94f57696c703798b31aad5fbdfa01cdec8e57fc | c3c423ccaa0b4b1d4d7dc061a25ea93e845ed354 | refs/heads/master | 2020-07-25T00:40:14.762435 | 2019-12-27T20:02:19 | 2019-12-27T20:02:19 | 208,100,929 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,246 | tac |
import os
from buildbot_worker.bot import Worker
from twisted.application import service
basedir = '/var/lib/buildbot/workers/openxt2'
rotateLength = 10000000
maxRotatedFiles = 10
# if this is a relocatable tac file, get the directory containing the TAC
if basedir == '.':
import os.path
basedir = os.path.abspath(os.path.dirname(__file__))
# note: this line is matched against to check that this is a worker
# directory; do not edit it.
application = service.Application('buildbot-worker')
from twisted.python.logfile import LogFile
from twisted.python.log import ILogObserver, FileLogObserver
logfile = LogFile.fromFullPath(
os.path.join(basedir, "twistd.log"), rotateLength=rotateLength,
maxRotatedFiles=maxRotatedFiles)
application.setComponent(ILogObserver, FileLogObserver(logfile).emit)
buildmaster_host = '127.0.0.1'
port = 9989
workername = 'openxt2'
passwd = 'password'
keepalive = 600
umask = 0o22
maxdelay = 300
numcpus = None
allow_shutdown = None
maxretries = None
s = Worker(buildmaster_host, port, workername, passwd, basedir,
keepalive, umask=umask, maxdelay=maxdelay,
numcpus=numcpus, allow_shutdown=allow_shutdown,
maxRetries=maxretries)
s.setServiceParent(application)
| [
"oxtbuilder@github.com"
] | oxtbuilder@github.com |
7d8fb50e7ee7527432b24d8fb50d44b1c35dfd89 | 74482894c61156c13902044b4d39917df8ed9551 | /test/test_address_coins_transaction_confirmed_data_item_mined_in_block.py | fe17c1e565968234e57b107948c613cf49feb8da | [
"MIT"
] | permissive | xan187/Crypto_APIs_2.0_SDK_Python | bb8898556ba014cc7a4dd31b10e24bec23b74a19 | a56c75df54ef037b39be1315ed6e54de35bed55b | refs/heads/main | 2023-06-22T15:45:08.273635 | 2021-07-21T03:41:05 | 2021-07-21T03:41:05 | 387,982,780 | 1 | 0 | NOASSERTION | 2021-07-21T03:35:29 | 2021-07-21T03:35:29 | null | UTF-8 | Python | false | false | 1,446 | py | """
CryptoAPIs
Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies the development of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of their blockchain applications. Crypto APIs 2.0 provides unified endpoints and data, raw data, automatic tokens and coins forwardings, callback functionalities, and much more. # noqa: E501
The version of the OpenAPI document: 2.0.0
Contact: developers@cryptoapis.io
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import cryptoapis
from cryptoapis.model.address_coins_transaction_confirmed_data_item_mined_in_block import AddressCoinsTransactionConfirmedDataItemMinedInBlock
class TestAddressCoinsTransactionConfirmedDataItemMinedInBlock(unittest.TestCase):
"""AddressCoinsTransactionConfirmedDataItemMinedInBlock unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testAddressCoinsTransactionConfirmedDataItemMinedInBlock(self):
"""Test AddressCoinsTransactionConfirmedDataItemMinedInBlock"""
# FIXME: construct object with mandatory attributes with example values
# model = AddressCoinsTransactionConfirmedDataItemMinedInBlock() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| [
"kristiyan.ivanov@menasoftware.com"
] | kristiyan.ivanov@menasoftware.com |
2e46ca438c5563c30626e67f49c017cbe8470086 | e6946ee7772172aad21a0d9e4e2c62f995a5255f | /Main.py | 4cb81577230792f650c39a1370b4054ae2639a6a | [] | no_license | YuvarajParimalam/Leedscale-Automation | 242db57e7a76013718cd2027c89cc095cd724fe1 | 3c9991415008d00097c1f1e5637d012cabf76383 | refs/heads/master | 2023-07-10T14:02:24.816523 | 2021-08-16T02:35:09 | 2021-08-16T02:35:09 | 376,780,446 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 819 | py | import configparser, os
from Scripts.Lolagroove import Lolagroove
from Scripts.Lead_Processor import Lead_Scraper
from Scripts.Campaign_update import Lead_Update
config = configparser.RawConfigParser()
configFilePath=os.path.join(os.getcwd(),'config.ini')
config.read(configFilePath)
CampaignName=config.get('Lolagroove','Name')
filename=config.get('fileupload','filename')
URL=config.get('Lolagroove','URL')
uploadFilePath=os.path.join(os.getcwd(),'Upload Files')
uploadFileName=os.path.join(uploadFilePath,filename)
detail=config.get('input','detail')
if __name__=='__main__':
if detail=='download' :
#Downloading file
df=Lolagroove(CampaignName)
#Processing file
output=Lead_Scraper(df)
else:
#uploading File
file_upload=Lead_Update(URL,uploadFileName)
| [
"yraj3224@gmail.com"
] | yraj3224@gmail.com |
186c8a6037e77f28642555ead4bdde0ddb084806 | f6dc02306dc3bce551325dd6c23d256b2d491323 | /flask/server.py | e1fbc75f04316242e6691bbd6f4ddf9ef492ba24 | [] | no_license | fndjjx/interesting | 47217f8a3410c5678b6cddf6df887d7c3e6e288d | 85ff2c8905fc4e88ddeadf4b117fd7225988ffce | refs/heads/master | 2021-01-17T14:41:44.634772 | 2017-03-29T08:07:18 | 2017-03-29T08:07:18 | 55,332,482 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 313 | py | from flask import Flask, render_template
from flask.ext.bootstrap import Bootstrap
app = Flask(__name__)
bootstrap = Bootstrap(app)
@app.route("/<name>")
def index(name):
#return '<h>Hello world!</h>'
return render_template('index3.html')
if __name__ == "__main__":
app.run(host='192.168.56.101')
| [
"yi.lei@unidt.com"
] | yi.lei@unidt.com |
88e33a3ac9e8b83161809f11986c6787a07b493a | 0deb569878001e59ca94207d9629dd33a567dd8f | /python_files/file_reader.py | 4939ddd0eddae793a9b9239826ac7bac5da262c4 | [] | no_license | AnushArunachalam/python_files- | 10b8b506b52f9505de5e66d65aa23604c86750fc | 6bdac7022c6e7dc47778828137988424e8f021de | refs/heads/master | 2022-11-25T06:48:04.424614 | 2020-07-29T12:54:42 | 2020-07-29T12:55:57 | 283,493,192 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 55 | py | fp = open("index.txt", 'a')
writer = fp.write('append') | [
"anusharunachalam3@gmail.com"
] | anusharunachalam3@gmail.com |
3a0a7b1b54fe3bc56854a04230ad020df1409104 | c429f611b3129bcbb0be8ae8b0e92aa1376eadeb | /python/losses.py | c7729d87a17a2391280bff973e06424b058a2d70 | [
"Apache-2.0"
] | permissive | mahmoudnafifi/ffcc | eda7ffacbc3de5fbc29dae0dac0a8d6f6160e9a0 | c52b225082327ea34bed80357dbff004fc9926ba | refs/heads/master | 2022-12-13T03:18:51.416191 | 2020-08-20T01:06:20 | 2020-08-20T01:06:20 | 284,583,995 | 1 | 0 | Apache-2.0 | 2020-08-20T01:06:22 | 2020-08-03T02:25:32 | MATLAB | UTF-8 | Python | false | false | 12,511 | py | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Losses for FFCC."""
import math
import sys
from . import ops
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_probability as tfp
def _check_shape(rgb1, rgb2):
rgb1.shape.assert_has_rank(2)
rgb2.shape.assert_has_rank(2)
rgb1.shape.assert_is_compatible_with([None, 3])
rgb2.shape.assert_is_compatible_with([None, 3])
def safe_acosd(x):
"""Returns arccos(x) in degrees, with a "safe" and approximate gradient.
When |x| = 1, the derivative of arccos() is infinite, and this can cause
catastrophic problems during optimization. So though this function returns an
accurate measure of arccos(x), the derivative it returns is that of
arccos(0.9999999x). This should not effect the performance of FFCC learning.
Args:
x: an input tensor of any shape.
Returns:
Returns acos for each element in the unit of degrees.
"""
# Check that x is roughly within [-1, 1].
with tf.control_dependencies([
tf.assert_greater_equal(x, tf.cast(-1.0 - 1e-6, dtype=x.dtype)),
tf.assert_less_equal(x, tf.cast(1.0 + 1e-6, dtype=x.dtype))
]):
x = tf.clip_by_value(x, -1.0, 1.0)
angle_shrink = tf.acos(0.9999999 * x)
angle_true = tf.acos(x)
# Use angle_true for the forward pass, but use angle_shrink for backprop.
angle = angle_shrink + tf.stop_gradient(angle_true - angle_shrink)
return angle * (180.0 / math.pi)
def angular_error(pred_illum_rgb, true_illum_rgb):
"""Measures the angular errors of predicted illuminants and ground truth.
Args:
pred_illum_rgb: predicted RGB illuminants in the shape of [batch_size, 3].
true_illum_rgb: true RGB illuminants in the shape of [batch_size, 3].
Returns:
Angular errors (degree) in the shape of [batch_size].
"""
_check_shape(pred_illum_rgb, true_illum_rgb)
pred_magnitude_sq = tf.reduce_sum(tf.square(pred_illum_rgb), axis=1)
true_magnitude_sq = tf.reduce_sum(tf.square(true_illum_rgb), axis=1)
with tf.control_dependencies([
tf.assert_greater(pred_magnitude_sq,
tf.cast(1e-8, dtype=pred_magnitude_sq.dtype)),
tf.assert_greater(true_magnitude_sq,
tf.cast(1e-8, dtype=true_magnitude_sq.dtype))
]):
numer = tf.reduce_sum(tf.multiply(pred_illum_rgb, true_illum_rgb), axis=1)
denom_sq = tf.multiply(pred_magnitude_sq, true_magnitude_sq)
epsilon = sys.float_info.epsilon
ratio = (numer + epsilon) * tf.rsqrt(denom_sq + epsilon * epsilon)
return safe_acosd(ratio)
def reproduction_error(pred_illum_rgb, true_illum_rgb):
"""Measures the reproduction errors of predicted illuminants and ground truth.
An implementation of "Reproduction Angular Error", as described in
"Reproduction Angular Error: An Improved Performance Metric for Illuminant
Estimation", Graham Finlayson and Roshanak Zakizadeh, BMVC 2014.
http://www.bmva.org/bmvc/2014/papers/paper047/
Args:
pred_illum_rgb: predicted RGB illuminants in the shape of [batch_size, 3].
true_illum_rgb: true RGB illuminants in the shape of [batch_size, 3].
Returns:
Reproduction angular errors (degree) in the shape of [batch_size].
"""
_check_shape(pred_illum_rgb, true_illum_rgb)
epsilon = sys.float_info.epsilon
ratio = true_illum_rgb / (pred_illum_rgb + epsilon)
numer = tf.reduce_sum(ratio, axis=1)
denom_sq = 3 * tf.reduce_sum(ratio**2, axis=1)
angle_prod = (numer + epsilon) * tf.rsqrt(denom_sq + epsilon * epsilon)
return safe_acosd(angle_prod)
def anisotropic_reproduction_error(pred_illum_rgb, true_illum_rgb,
true_scene_rgb):
"""Measures anisotropic reproduction error wrt the average scene color.
The output error is invariant to the absolute scale of all inputs.
Args:
pred_illum_rgb: predicted RGB illuminants in the shape of [batch_size, 3].
true_illum_rgb: true RGB illuminants in the shape of [batch_size, 3].
true_scene_rgb: averaged scene RGB of the true white-balanced image in the
shape of [batch_size, 3].
Returns:
Anisotropic reproduction angular errors (degree) in the shape of
[batch_size].
"""
_check_shape(pred_illum_rgb, true_illum_rgb)
_check_shape(pred_illum_rgb, true_scene_rgb)
epsilon = sys.float_info.epsilon
ratio = true_illum_rgb / (pred_illum_rgb + epsilon)
numer = tf.reduce_sum(true_scene_rgb**2 * ratio, axis=1)
denom_sq = tf.reduce_sum(
true_scene_rgb**2, axis=1) * tf.reduce_sum(
true_scene_rgb**2 * ratio**2, axis=1)
angle_prod = (numer + epsilon) * tf.rsqrt(denom_sq + epsilon * epsilon)
return safe_acosd(angle_prod)
def anisotropic_reproduction_loss(pred_illum_uv, true_illum_uv, rgb):
"""Computes anisotropic reproduction loss.
Args:
pred_illum_uv: float, predicted uv in log-UV space, in the shape of
[batch_size, 2].
true_illum_uv: the true white points in log-UV space, in the shape of
[batch_size, 2].
rgb: float, the input RGB image that the log-UV chroma histograms are
constructed from, [batch_size, height, width, channels].
Returns:
float, weighted repdocution errors in the shape of [batch_size].
"""
pred_illum_uv.shape.assert_is_compatible_with([None, 2])
true_illum_uv.shape.assert_is_compatible_with([None, 2])
rgb.shape.assert_is_compatible_with([None, None, None, 3])
pred_illum_rgb = ops.uv_to_rgb(pred_illum_uv)
true_illum_rgb = ops.uv_to_rgb(true_illum_uv)
true_scene_rgb = tf.reduce_mean(ops.apply_wb(rgb, true_illum_uv), axis=[1, 2])
return anisotropic_reproduction_error(pred_illum_rgb, true_illum_rgb,
true_scene_rgb)
def gaussian_negative_log_likelihood(pred_illum_uv, pred_illum_uv_sigma,
true_illum_uv):
"""Computes the negative log-likelihood of a multivariate gaussian.
This implements the loss function described in the FFCC paper, Eq. (18).
Args:
pred_illum_uv: float, predicted uv in log-UV space, in the shape of
[batch_size, 2].
pred_illum_uv_sigma: float, the predicted covariance matrix for
`pred_illum_uv`, with a shape of [batch_size, 2, 2].
true_illum_uv: the true white points in log-UV space, in the shape of
[batch_size, 2].
Returns:
The negative log-likelihood of the multivariate Gaussian distribution
defined by pred_illum_uv (mu) and pred_illum_uv_sigma (sigma), evaluated at
true_illum_uv.
"""
det = tf.linalg.det(pred_illum_uv_sigma)
with tf.control_dependencies(
[tf.assert_greater(det, tf.cast(0.0, dtype=det.dtype))]):
pred_pdf = tfp.distributions.MultivariateNormalFullCovariance(
loc=pred_illum_uv, covariance_matrix=pred_illum_uv_sigma)
return -pred_pdf.log_prob(true_illum_uv)
def compute_data_loss(pred_heatmap, pred_illum_uv, pred_illum_uv_sigma,
true_illum_uv, weight, step_size, offset, n, rgb):
"""Computes the data term of the loss function.
The data loss is the (squared) anisotropic reproduction error.
This function also returns the unweighted, un-squared, sub-loss, which
is used for summaries and for reporting training / eval errors.
Args:
pred_heatmap: float, the network predictions in the shape of [batch_size, n,
n].
pred_illum_uv: float, the predicted white point in log-UV space in the shape
of [batch_size, 2].
pred_illum_uv_sigma: float, the predicted covariance matrix for
`pred_illum_uv`, with a shape of [batch_size, 2, 2].
true_illum_uv: float, the true white point in log-UV space in the shape of
[batch_size, 2].
weight: float, the weight for the loss in the shape of [batch_size]
step_size: float, the pitch of each step, scalar.
offset: float, the value of the first index, scalar.
n: float, the number of bins, scalar.
rgb: float, the original input RGB thumbnails in the shape of [batch_size,
height, width, 3].
Returns:
A tuple of the form:
weighted_loss_data, a float containing the total weighted loss
losses, a dict with keys:
'anisotropic_reproduction_error': vector of floats containing the
anisotropic reproduction error for each datapoint in the batch.
'angular_error': vector of floats containing the angular error for each
datapoint in the batch.
"""
pred_heatmap.shape.assert_is_compatible_with([None, n, n])
pred_illum_uv.shape.assert_is_compatible_with([None, 2])
pred_illum_uv_sigma.shape.assert_is_compatible_with([None, 2, 2])
true_illum_uv.shape.assert_is_compatible_with([None, 2])
if not np.isscalar(step_size):
raise ValueError('`step_size` must be a scalar, but is of type {}'.format(
type(step_size)))
if not np.isscalar(offset):
raise ValueError('`step_size` must be a scalar, but is of type {}'.format(
type(offset)))
if not np.isscalar(n):
raise ValueError('`n` must be a scalar, but is of type {}'.format(type(n)))
rgb.shape.assert_is_compatible_with([None, None, None, 3])
losses = {
'anisotropic_reproduction_error':
anisotropic_reproduction_loss(pred_illum_uv, true_illum_uv, rgb),
'reproduction_error':
reproduction_error(
ops.uv_to_rgb(pred_illum_uv), ops.uv_to_rgb(true_illum_uv)),
'angular_error':
angular_error(
ops.uv_to_rgb(pred_illum_uv), ops.uv_to_rgb(true_illum_uv)),
'gaussian_nll':
gaussian_negative_log_likelihood(pred_illum_uv, pred_illum_uv_sigma,
true_illum_uv)
}
# We minimize the (weighted) NLL loss for training.
weighted_loss_data = tf.reduce_mean(weight * losses['gaussian_nll'])
with tf.name_scope('data'):
# Render out the PMF (red), the predicted UV coordinate from fitting a
# Von Mises to that PMF (green), and the true UV coordinate.
# UV coordinates are rendered by splatting them to a histogram.
tf.summary.histogram('pred_heatmap', pred_heatmap)
pred_pmf = ops.softmax2(pred_heatmap)
def _normalize(x):
ep = sys.float_info.epsilon
max_val = tf.reduce_max(x, [1, 2], keepdims=True) + ep
return x / max_val
vis_pred_cross = _normalize(pred_pmf)
vis_pred_aniso = _normalize(
ops.uv_to_pmf(pred_illum_uv, step_size, offset, n))
vis_true = _normalize(ops.uv_to_pmf(true_illum_uv, step_size, offset, n))
vis = tf.cast(
tf.round(255 *
tf.stack([vis_pred_cross, vis_pred_aniso, vis_true], axis=-1)),
tf.uint8)
tf.summary.image('pmf_argmax_gt', vis)
def _make_montage(v, k=4):
"""Attempt to make a k*k montage of `v`, if the batch size allows it."""
count = tf.minimum(
k,
tf.cast(
tf.floor(tf.sqrt(tf.cast(tf.shape(v)[0], tf.float32))), tf.int32))
montage = v[:(count**2), :, :, :]
montage = tf.reshape(
tf.transpose(
tf.reshape(montage, [count, count, v.shape[1], v.shape[2], 3]),
[0, 2, 1, 3, 4]), (count * v.shape[1], count * v.shape[2], 3))
return montage
montage = _make_montage(vis)
tf.summary.image('pmf_argmax_gt_montage', montage[tf.newaxis])
uv_range = np.arange(n) * step_size + offset
vv, uu = np.meshgrid(uv_range, uv_range)
uv = np.stack([uu, vv], axis=-1)
pred_pdf = tf.transpose(
tfp.distributions.MultivariateNormalFullCovariance(
loc=pred_illum_uv,
covariance_matrix=pred_illum_uv_sigma).prob(uv[:, :,
tf.newaxis, :]),
[2, 0, 1])
vis_pred_pdf = _normalize(pred_pdf)
vis_pdf = tf.cast(
tf.round(255 *
tf.stack([vis_pred_cross, vis_pred_pdf, vis_true], axis=-1)),
tf.uint8)
tf.summary.image('pmf_pdf_gt', vis_pdf)
montage_pdf = _make_montage(vis_pdf)
tf.summary.image('pmf_pdf_gt_montage', montage_pdf[tf.newaxis])
return (weighted_loss_data, losses)
| [
"fbleibel@google.com"
] | fbleibel@google.com |
68913152d5b97da002f080df76762c68465c39b6 | d5214b1331c9dae59d95ba5b3aa3e9f449ad6695 | /quintagroup.portletmanager.footer/tags/0.1/quintagroup/portletmanager/footer/interfaces.py | 4d27adc4144d611762c6bb453a6342a6cfbfc063 | [] | no_license | kroman0/products | 1661ee25a224c4b5f172f98110944f56136c77cf | f359bb64db22f468db5d1e411638790e94d535a2 | refs/heads/master | 2021-01-10T07:58:04.579234 | 2014-06-11T12:05:56 | 2014-06-11T12:05:56 | 52,677,831 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 274 | py | from plone.portlets.interfaces import IPortletManager
#from plone.app.portlets.interfaces import IColumn
class IFooter(IPortletManager):
""" Portlet manager that is rendered in page footer
Register a portlet for IFooter if it is applicable to page footer.
"""
| [
"olha@4df3d6c7-0a05-0410-9bee-ae8b7a76f946"
] | olha@4df3d6c7-0a05-0410-9bee-ae8b7a76f946 |
63cf41744528735b8ce635cd20d67ea167667d91 | f06f4bbaafbc672ec3f369038936e4dd7ad7c977 | /kresto/data.py | 2d717a1fafcf4dddcf57ea79c129d72deb4d23ac | [] | no_license | euphoris/kresto | 898fd3d56e35956a4977b450928f0725fe7250a9 | 0a4253aeb87010bd613dd9f8c455ee33e856959d | refs/heads/master | 2020-05-19T10:31:48.532303 | 2014-01-20T14:54:32 | 2014-01-20T14:54:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,981 | py | from cStringIO import StringIO
import os
import zipfile
import html2text
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from .corpus import Corpus
def load_corpus(path):
c = Corpus()
if os.path.isdir(path):
for root, _, files in os.walk(path):
for filename in files:
with open(os.path.join(root, filename)) as f:
if filename.endswith('zip'):
continue # FIXME
c.add_text(extract_text(f, filename))
else:
if path.endswith('.zip'):
with zipfile.ZipFile(path) as zf:
for name in zf.namelist():
if not name.endswith('/'):
with zf.open(name) as f:
c.add_text(extract_text(f, name))
else:
with open(path) as f:
c.add_text(extract_text(f, path))
return c
def extract_text(fp, path):
"""Extract text from a file"""
if path.endswith('pdf'):
caching = True
rsrcmgr = PDFResourceManager(caching=caching)
outfp = StringIO()
device = TextConverter(rsrcmgr, outfp, codec='utf-8',
laparams=LAParams(), imagewriter=None)
interpreter = PDFPageInterpreter(rsrcmgr, device)
pages = PDFPage.get_pages(fp, set(), maxpages=0, caching=caching,
check_extractable=True)
for page in pages:
page.rotate %= 360
interpreter.process_page(page)
device.close()
content = outfp.getvalue()
outfp.close()
else:
content = fp.read()
if path.endswith('html') or path.endswith('htm'):
h = html2text.HTML2Text()
h.ignore_links = True
content = h.handle(content)
return content | [
"euphoris@gmail.com"
] | euphoris@gmail.com |
7d517f5071579ffb986776d0c0cfd895cedd02aa | fd01bc8c5612bd2ede5d6c24de2fbf8efb51b378 | /trees/avl.py | 8ff32ad9e19ea0a4ff46c33626e5217923af46b0 | [] | no_license | mageMerlin8/EDA_Tarea5 | 67353bb853abde5c54017f733ce417dcb7bfc257 | ca2da3c3b4043a9caf8689deaa765c0bcb8baf95 | refs/heads/master | 2020-03-29T17:53:28.133057 | 2018-10-04T16:12:27 | 2018-10-04T16:12:27 | 150,184,061 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,344 | py | from trees.bst import *
class NodeAVL(NodeB):
def __init__(self, nodo):
NodeB.__init__(self, nodo.dato, right=nodo.right, left=nodo.left)
self.fe = None
self.fe = self.getFE()
self.feChanged = True
def getFE(self):
if(self.right):
r = self.right.getHeight()
else:
r = -1
if(self.left):
l = self.left.getHeight()
else:
l = -1
self.fe = r - l
return self.fe
class ArbolAVL(ArbolB):
def __init__(self, root = None):
ArbolB.__init__(self, root)
if(root):
self.toAvl(self.root)
def find2(self, node = None, parent = None):
if(not node): return self.find2(self.root, None)
if(node.fe > 1):
return {'node':node, 'parent':parent}
else:
if(node.left and node.right):
return self.find2(node.right, node) or self.find2(node.left, node)
elif(node.left):
return self.find2(node.left, node)
elif(node.right):
return self.find2(node.right, node)
else: return False
def draw(self):
plt.clf()
myDict = self.root.dataFrameMe()
grafo = nx.Graph(myDict)
profundidades = {}
listaProf = []
labelsDict = {}
for nodo in grafo.nodes():
nodoInfo = self.find(int(nodo))
profundidad = len(nodoInfo['pasos'])
listaProf.append(profundidad)
profundidades[nodo] = profundidad
labelsDict[nodo] = nodo + ', fe:' + str(nodoInfo['nodo'].fe)
nx.set_node_attributes(grafo, profundidades, 'depth')
nx.draw_kamada_kawai(grafo, with_labels = True, node_size=1500,
node_color = listaProf,
cmap = plt.cm.Blues,
vmax = max(listaProf)+1,
labels = labelsDict)
def leftRotate(self, node):
new = node.right
if new.left:
node.right = new.left
else:
node.right = None
new.left = node
return new
def rightRotate(self, node):
new = node.left
if new.right:
node.left = new.right
else:
node.left = None
new.right = node
return new
def rotaLL(self):
self.calculaFes(self.root)
node = self.find2(self.root, None)
if(node and node['parent']):
node['parent'].right = self.leftRotate(node['node'])
print('arbol rotado: ')
print(self.root)
else:
print('no se puede rotar arbol')
def insertR(self, node, dato):
#insercion normal con modificacion de fe
if not node:
new = NodeAVL(NodeB(dato))
return new
elif dato < node.dato:
node.left = self.insertR(node.left, dato)
if node.left.feChanged:
node.fe -= 1
node.feChanged = True
else:
node.feChanged = False
elif dato > node.dato:
node.right = self.insertR(node.right, dato)
if node.right.feChanged:
node.fe += 1
node.feChanged = True
else:
node.feChanged = False
else:
print('se intentó insertar un nodo que ya existe')
return None
if(node.fe > 1):
if(node.right.fe is 1):
node = self.leftRotate(node)
node.fe = 0
node.left.fe = 0
elif(node.right.fe is 0):
node = self.leftRotate(node)
node.fe = -1
node.left.fe = 1
elif(node.right.fe is -1):
feY = node.right.left.fe
node.right = self.rightRotate(node.right)
node = self.leftRotate(node)
node.fe = 0
if feY is 0:
node.left.fe = 0
node.right.fe = 0
elif feY is 1:
node.left.fe = -1
node.right.fe = 0
elif feY is -1:
node.left.fe = 0
node.right.fe = 1
elif node.fe < -1 :
if(node.left.fe is -1):
node = self.rightRotate(node)
node.fe = 0
node.right.fe = 0
elif(node.left.fe is 0):
node = self.rightRotate(node)
node.fe = 1
node.right.fe = -1
elif(node.left.fe is 1):
feY = node.left.right.fe
node.left = self.leftRotate(node.left)
node = self.rightRotate(node)
node.fe = 0
if feY is 0:
node.left.fe = 0
node.right.fe = 0
elif feY is -1:
node.left.fe = 0
node.right.fe = 1
elif feY is 1:
node.left.fe = -1
node.right.fe = 0
if node.fe == 0: node.feChanged = False
return node
def insert(self, dato):
resp = self.insertR(self.root, dato)
if(resp):
if resp.fe is None:
resp.fe = 0
self.root = resp
return True
else:
return False
def calculaFes(self, node):
node.fe = node.getFE()
if(node.left):
self.calculaFes(node.left)
if(node.right):
self.calculaFes(node.right)
def isBalanced(self, node = None):
if(not node):
return self.isBalanced(self.root)
if(node.fe < 2 and node.fe > -2):
if(node.right and node.left):
return self.isBalanced(node.right) and self.isBalanced(node.left)
elif(node.right):
return self.isBalanced(node.right)
elif(node.left):
return self.isBalanced(node.left)
else:
return True
else:
return False
def toAvl(node):
if(node.left):
self.toAvl(node.left)
if(node.right):
self.toAvl(node.right)
node = NodeAVL(node)
| [
"emilio.1997@gmail.com"
] | emilio.1997@gmail.com |
34388cc7991e265a2d2a7205564eea29555d92d6 | b8078e923e942744af03cec354efda40fc004eb5 | /leapyr.py | c246390d82c88af57fad573dd87440a2679f5901 | [] | no_license | sarathkumarselvam/sarathkumar-s | 1019c4d6742597fea73304403dc17ec39471b597 | 83fe47bd51f4026a63cf4d523c0876ed93f5a487 | refs/heads/master | 2020-05-27T20:17:50.053735 | 2019-06-18T06:01:58 | 2019-06-18T06:01:58 | 188,776,963 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 288 | py | year =2020
if(year%4==0):
if(year%100==0):
if(year%400==0):
print("{0} leap year".format(year))
else:
print(" {0} not ".format(year))
else:
print(" {0} leap year".format(year))
else:
print(" {0} not ".format(year))
| [
"noreply@github.com"
] | noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.