blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
283
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
41
| license_type
stringclasses 2
values | repo_name
stringlengths 7
96
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 58
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 12.7k
662M
⌀ | star_events_count
int64 0
35.5k
| fork_events_count
int64 0
20.6k
| gha_license_id
stringclasses 11
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 43
values | src_encoding
stringclasses 9
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 7
5.88M
| extension
stringclasses 30
values | content
stringlengths 7
5.88M
| authors
sequencelengths 1
1
| author
stringlengths 0
73
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2b72c1c82fc505dfa63916664ac32efc7a132130 | 55c5e8bdee13108e3028ec8c2b8be1e0f704c1d6 | /ProjectFramework/ModelResults/CalculateClassificationResults.py | 3ca51efb82b2402add86e75292b64db6fdfa5566 | [] | no_license | OrtalPa/Final_Project_SISE_BGU | aeb07041215abee565bbfe517389a8da9db68758 | 44724c7aa1e84654eb0c7da8aec59f7aa913052c | refs/heads/master | 2023-05-06T19:10:19.510239 | 2021-05-28T07:34:37 | 2021-05-28T07:34:37 | 325,838,361 | 0 | 0 | null | 2021-05-28T07:34:37 | 2020-12-31T16:42:49 | Jupyter Notebook | UTF-8 | Python | false | false | 2,024 | py | import pandas as pd
import glob
import os
from pathlib import Path
from Pipeline.MultiLabelPipeline import get_data, get_label_names
path = Path(os.path.abspath(__file__))
DATA_PATH = os.path.dirname(path.parent) + '\\ModelResults\\ResultFiles'
def get_dfs():
list_of_df = []
for file_path in glob.glob(f"{DATA_PATH}\\*.csv"):
list_of_df.append(get_df(file_path))
return list_of_df
def get_file_name(file_path):
return file_path.split(sep="\\")[-1].split(sep='.')[0]
def get_df_dict():
dict_of_df = {}
# key: filename value: df
for file_path in glob.glob(f"{DATA_PATH}\\*.csv"):
dict_of_df[f'{get_file_name(file_path)}'] = get_df(file_path)
return dict_of_df
def get_df(file_path):
df = pd.read_csv(file_path, index_col=0)
return df
def calculate_when_method_answers_correctly(method, df_test, df_train):
sum_r = 0
for index, row in df_test.iterrows():
real = row[method]
pred = df_train.iloc[df_train.index == index][method]
pred = pred[index]
if real == 1 and pred == 1:
sum_r = sum_r + 1 if real == 1 and pred == 1 else 0
return sum_r
if __name__ == "__main__":
# create a file with:
# get the results of the model -> for each method the prediction
print(DATA_PATH)
df_dict = get_df_dict()
df_correct = get_data()
df_correct = df_correct[get_label_names()]
result_dict = {}
for df_name in df_dict:
try:
if 'wnone' in df_name:
df = df_dict[df_name]
for method in get_label_names():
sum_of_correct = calculate_when_method_answers_correctly(method=method, df_test=df, df_train=df_correct)
print(sum_of_correct)
print(df_correct[method].sum())
result_dict[method+"_"+df_name] = sum_of_correct/df_correct[method].sum()
except Exception as e:
print("error in "+df_name)
print(e)
print(result_dict)
| [
"[email protected]"
] | |
ef7c4407ce3a81d83ce9903676656097467682b4 | d827df70b8bc2236ee8a817f854bef6e5be928b4 | /file1.py | b693ed3afdd5d0dba70a7b7f4daaa18cdff89e69 | [] | no_license | frocha27/pyprj | 5e9e672a8a9a2cff9b03983fdd85dd6199095c13 | 1ba4188ec34abe336faef8dce79a4b3a56cafa35 | refs/heads/master | 2021-05-12T04:11:34.563444 | 2018-01-11T21:55:58 | 2018-01-11T21:55:58 | 117,154,523 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 568 | py | # Frederic Rocha
# January 2018
# Bergstrom Inc
#alternate version
import pycom
import time
for i in range(10): print(2**i)
pycom.heartbeat(False)
loop=True
i=0
for j in [0,8,16]:
for i in range(1,256):
color=(i*2**j)+(256-i)*2**(16)
pycom.rgbled(color)
time.sleep(0.1)
print(i,'-',hex(color))
while loop:
pycom.rgbled(0xff0000) #Red LED
time.sleep(0.3)
pycom.rgbled(0x00ff00) #Green LED
time.sleep(0.3)
pycom.rgbled(0x0000ff) #Blue LED
time.sleep(0.3)
i=i+1
print(i)
| [
"[email protected]"
] | |
962f4fa62efcd483741ab4f4859ff6a13354169b | bc2a6ba98c9a42ed0726f34807eeab9ed7f85741 | /backend/app/app/api/api_v1/endpoints/url.py | c10434b8d30b516f182e7e9747988bbcb673f185 | [] | no_license | MaioSource/url_shortener | caff037f4d16f5f2df2469b80a26f51e57289970 | cf11a834708624e7e55d638018474bf750786964 | refs/heads/master | 2022-11-21T09:50:33.059423 | 2020-07-22T18:54:13 | 2020-07-22T18:54:13 | 281,759,045 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,043 | py | from typing import Any, List
from fastapi import APIRouter, Body, Depends, HTTPException
from fastapi.encoders import jsonable_encoder
from pydantic.networks import EmailStr
from sqlalchemy.orm import Session
from app import crud, models, schemas
from app.api import deps
from app.core.config import settings
router = APIRouter()
@router.get("/{short_url}", response_model=schemas.Url)
def read_url(
short_url: str,
db: Session = Depends(deps.get_db),
) -> Any:
"""
Retrieve url.
"""
url = crud.url.get_by_short_url(db, short_url=short_url)
return url
@router.post("/", response_model=schemas.Url)
def create_url(
*,
db: Session = Depends(deps.get_db),
url_in: schemas.UrlCreate,
) -> Any:
"""
Create new url.
"""
url = crud.url.get_by_short_url(db, short_url=url_in.short_url)
if url:
raise HTTPException(
status_code=400,
detail="short URL already exists in the system.",
)
url = crud.url.create(db, obj_in=url_in)
return url
| [
"[email protected]"
] | |
7e0d4cb71a84232314f4e1be8a97f2bb9efeb906 | 6a1e92af46fa8242ab5757ad3eafdcad6af289e0 | /CareSquareBeta/poll/templatetags/polls_tags.py | a623eb3ecb526468025c44989f7472c2edf8c6da | [] | no_license | lincolnn/CareSquare | fe1cacd5028b49398b942bb4fcf835a89fa9745a | 52c792007549a1228c4261a5fdab1f332bc9a45e | refs/heads/master | 2020-04-27T23:44:23.016621 | 2012-05-03T21:23:19 | 2012-05-03T21:23:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,499 | py | from django import template
from poll.models import Poll, Item, Queue
from settings import STATIC_URL
from django.utils.safestring import SafeUnicode
from django.utils.datetime_safe import datetime
from poll.ajax import authpass
register = template.Library()
@register.inclusion_tag('polls.html', takes_context=True)
def poll(context, poll):
can_vote = True
if poll.queue:
can_vote = authpass(context['user'], poll.queue)
return {'poll': poll, 'poll_type': poll.print_polltype(), 'items': Item.objects.filter(poll=poll), 'user': context['user'], 'can_vote': can_vote, 'request': context['request'], 'STATIC_URL': STATIC_URL}
@register.inclusion_tag('polls.html', takes_context=True)
def poll_queue(context, queue):
try:
if isinstance(queue, SafeUnicode):
tmp_queue = Queue.objects.get(title=queue)
else:
tmp_queue = Queue.objects.get(queue)
except:
raise Exception('Queue not found')
tmp_polls = Poll.publish_manager.filter(queue=tmp_queue, startdate__lte=datetime.now())
if len(tmp_polls) > 0:
cur_poll = tmp_polls[0]
else:
cur_poll = None
return poll(context, cur_poll)
class RenderItemsClass(template.Node):
def __init__(self, poll, items):
self.poll=template.Variable(poll)
self.items=template.Variable(items)
def render(self, context):
poll = self.poll.resolve(context)
items = self.items.resolve(context)
#'name' = item.pk
pattern1 = '{3}<br /><input name="poll_{0}" type="{1}" id="{2}" value="" /><br />'
pattern2 = '<input name="poll_{0}" type="{1}" id="{2}" /> {3}<br />'
result = ''
#Choose an input type
for item in items:
if item.userbox:
input_type = 'textbox'
pattern = pattern1
else:
poll_type = poll.print_polltype()
if poll_type == 'Single':
input_type = 'radio'
elif poll_type == 'Multiple':
input_type = 'checkbox'
pattern = pattern2
result += pattern.format(poll.pk, input_type, item.pk, item.value)
return result
@register.tag
def render_items(parser, token):
tag, poll, items = token.split_contents()
return RenderItemsClass(poll, items) | [
"[email protected]"
] | |
7dbbd76159ed81b6ff008a9a074eaf730ab3c4a9 | 0637388b36f05919de57af0865d17a6db0e6f69a | /vnpy/trader/language/__init__.py | 2fbf703c0f634a213b20f0ebf53023cddfa43d9f | [
"MIT"
] | permissive | elulue/vnpy | 7dba29657594a97be220de6ac66bc456c8528a88 | d341778514ae126b952e57c83e2a80e046f93b0d | refs/heads/master | 2022-08-10T14:37:56.824248 | 2022-07-30T09:15:57 | 2022-07-30T09:15:57 | 203,825,413 | 0 | 0 | MIT | 2022-07-30T09:15:58 | 2019-08-22T15:42:48 | Python | UTF-8 | Python | false | false | 282 | py | # encoding: UTF-8
print('load vnpy/languange')
# 默认设置
from .chinese import text, constant
# 是否要使用英文
from vnpy.trader.vtGlobal import globalSetting
if globalSetting.get('language',None) == 'english':
from vnpy.trader.language.english import text, constant
| [
"[email protected]"
] | |
e835b6d540c7b5b4b1f2c0bef0a31138109ae9cd | eddac44e78e10c9dbf1ec7b37f295de71b37c1bc | /mnist/main.py | 47f9e09b0e7af6ff2d8add34c08193f3c94d3f32 | [] | no_license | BRutan/mnist | 77a812275926983e0ca1cce6569dfea5bd49db86 | 10653ef97bff8f593ddb1a95c049b83b65d44dde | refs/heads/master | 2023-03-31T17:22:07.202521 | 2021-04-08T05:27:34 | 2021-04-08T05:27:34 | 333,237,913 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,624 | py | ##############################
# main.py
##############################
# Description:
# * Read in local MNIST data,
# train neural network using data
# and labels, generate predictions
# and display accuracy.
import matplotlib.pyplot as plt
from NN.neural_network import MNISTPredictor
import numpy as np
import os
from sklearn.metrics import confusion_matrix
from torch import flatten, FloatTensor
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
normalize_data = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)), flatten])
#target_transform = transforms.Compose([])
def load_data(batchsize):
"""
* Load data from local mnist dataset (in Data folder).
"""
train = DataLoader(datasets.MNIST('data', train = True, download = True, transform = normalize_data), batch_size = batchsize)
test = DataLoader(datasets.MNIST('data', train = False, transform = normalize_data))
return train, test
def train_model(train, input_nodes, hidden_nodes, num_outputs, epochs, lr, track):
"""
* Train model using training set.
"""
model = MNISTPredictor(input_nodes, hidden_nodes, num_outputs)
losses = model.train(train, 1, lr, verbose = True, track = track)
return model, losses
def plot_losses(losses, epochs, batchsize, lr):
"""
* Plot losses by batch for visualization purposes.
"""
plt.clf()
plt.title('MNIST Dataset Losses Epochs:%s BatchSize:%s LR:%s' % (epochs, batchsize, lr))
plt.scatter(list(range(len(losses))), losses)
plt.xlabel('Batch')
plt.ylabel('Loss')
plt.savefig('Losses_%s_%s_%s.png' % (epochs, batchsize, str(lr).strip('.')))
def test_model(model, test, report_path):
"""
* Test model using testing set.
"""
labels = []
predicted = []
with open(report_path, 'w') as f:
f.write('Actual,Predicted')
for input, target in test:
pred = model.forward(input)
pred = model.convert_pass(pred)
# Convert the forward pass into a result:
labels.append(target)
predicted.append(predicted)
f.write('%s,%s' % (target, pred))
return confusion_matrix(predicted, labels)
def main():
"""
* Perform key steps in order.
"""
epochs = 1
batchsize = 60
lr = .01
train, test = load_data(batchsize)
model, losses = train_model(train, 784, (128, 64), 10, epochs, lr, True)
plot_losses(losses, epochs, batchsize, lr)
matr = test_model(model, test, "MNIST_Predictions.csv")
print(matr)
if __name__ == '__main__':
main() | [
"[email protected]"
] | |
e794a71236a056e6fd4e9719dfc2144257e34bd6 | a5d22c99e781270317078f8980c934bcc71e6e8b | /neodroidvision/mixed/architectures/self_attention_network/self_attention_modules/functions/subtraction_refpad.py | 68e61decfc34d39d2dfe45867a2db4b94f2bb085 | [
"Apache-2.0"
] | permissive | aivclab/vision | dda3b30648b01c2639d64a016b8dbcfccb87b27f | 06839b08d8e8f274c02a6bcd31bf1b32d3dc04e4 | refs/heads/master | 2023-08-21T22:35:10.114394 | 2022-11-02T10:14:08 | 2022-11-02T10:14:08 | 172,566,233 | 1 | 3 | Apache-2.0 | 2023-08-16T05:11:30 | 2019-02-25T19:00:57 | Python | UTF-8 | Python | false | false | 12,589 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "heider"
__doc__ = r"""
Created on 26/01/2022
"""
import torch
from torch.autograd import Function
from torch.nn.modules.utils import _pair
from .self_attention_utilities import (
CUDA_NUM_THREADS,
Stream,
get_blocks_,
get_dtype_str,
kernel_loop,
load_kernel,
)
_subtraction_refpad_forward_kernel = (
kernel_loop
+ r"""
extern "C"
__global__ void subtraction_refpad_forward_kernel(
const ${Dtype}* bottom_data, ${Dtype}* top_data) {
CUDA_KERNEL_LOOP(index, ${nthreads}) {
const int n = index / ${input_channels} / ${top_height} / ${top_width};
const int c = (index / ${top_height} / ${top_width}) % ${input_channels};
const int h = (index / ${top_width}) % ${top_height};
const int w = index % ${top_width};
const int h_in_center = -${pad_h} + h * ${stride_h} + (${kernel_h} - 1) / 2 * ${dilation_h};
const int w_in_center = -${pad_w} + w * ${stride_w} + (${kernel_w} - 1) / 2 * ${dilation_w};
const int offset_center = ((n * ${input_channels} + c) * ${bottom_height} + h_in_center) *
${bottom_width} + w_in_center;
for (int kh = 0; kh < ${kernel_h}; ++kh) {
for (int kw = 0; kw < ${kernel_w}; ++kw) {
int h_in = -${pad_h} + h * ${stride_h} + kh * ${dilation_h};
int w_in = -${pad_w} + w * ${stride_w} + kw * ${dilation_w};
const int offset_top = ((n * ${input_channels} + c) * ${kernel_h} * ${kernel_w} + (kh * ${kernel_w}
+ kw)) * ${top_height} * ${top_width} + h * ${top_width} + w;
int offset_bottom;
if ((h_in >= 0) && (h_in < ${bottom_height}) && (w_in >= 0) && (w_in < ${bottom_width})) {
offset_bottom = ((n * ${input_channels} + c) * ${bottom_height} + h_in) * ${bottom_width} + w_in;
}
else {
if (h_in < 0) h_in = -h_in;
if (h_in >= ${bottom_height}) h_in = 2 * (${bottom_height} - 1) - h_in;
if (w_in < 0) w_in = -w_in;
if (w_in >= ${bottom_width}) w_in = 2 * (${bottom_width} - 1) - w_in;
offset_bottom = ((n * ${input_channels} + c) * ${bottom_height} + h_in) * ${bottom_width} + w_in;
}
top_data[offset_top] = bottom_data[offset_center] - bottom_data[offset_bottom];
}
}
}
}
"""
)
_subtraction_refpad_input_backward_kernel = (
kernel_loop
+ r"""
extern "C"
__global__ void subtraction_refpad_input_backward_kernel(
const ${Dtype}* const top_diff, ${Dtype}* bottom_diff) {
CUDA_KERNEL_LOOP(index, ${nthreads}) {
const int n = index / ${input_channels} / (${bottom_height} + 2 * ${pad_h}) /
(${bottom_width} + 2 * ${pad_w});
const int c = (index / (${bottom_height} + 2 * ${pad_h}) / (${bottom_width} + 2 *
${pad_w})) % ${input_channels};
const int h = (index / (${bottom_width} + 2 * ${pad_w})) % (${bottom_height} + 2 * ${pad_h});
const int w = index % (${bottom_width} + 2 * ${pad_w});
${Dtype} value = 0;
for (int kh = 0; kh < ${kernel_h}; ++kh) {
for (int kw = 0; kw < ${kernel_w}; ++kw) {
const int h_out_s = h - kh * ${dilation_h};
const int w_out_s = w - kw * ${dilation_w};
if (((h_out_s % ${stride_h}) == 0) && ((w_out_s % ${stride_w}) == 0)) {
const int h_out = h_out_s / ${stride_h};
const int w_out = w_out_s / ${stride_w};
if ((h_out >= 0) && (h_out < ${top_height}) && (w_out >= 0) && (w_out < ${top_width})) {
const int offset_top = ((n * ${input_channels} + c) * ${kernel_h} * ${kernel_w} +
(kh * ${kernel_w} + kw)) * ${top_height} * ${top_width} + h_out * ${top_width} + w_out;
value += -top_diff[offset_top];
}
}
}
}
const int hh = h - ${pad_h};
const int ww = w - ${pad_w};
if ((hh >= 0) && (hh < ${bottom_height}) && (ww >= 0) && (ww < ${bottom_width})) {
if (((hh % ${stride_h}) == 0) && ((ww % ${stride_w}) == 0)) {
const int h_out = hh / ${stride_h};
const int w_out = ww / ${stride_w};
for (int kh = 0; kh < ${kernel_h}; ++kh) {
for (int kw = 0; kw < ${kernel_w}; ++kw) {
const int offset_top = ((n * ${input_channels} + c) * ${kernel_h} * ${kernel_w} +
(kh * ${kernel_w} + kw)) * ${top_height} * ${top_width} + h_out * ${top_width} + w_out;
value += top_diff[offset_top];
}
}
}
}
bottom_diff[index] = value;
}
}
"""
)
__all__ = ["SubtractionRefpad", "subtraction_refpad"]
class SubtractionRefpad(Function):
@staticmethod
def forward(ctx, input, kernel_size, stride, padding, dilation):
"""
Args:
ctx:
input:
kernel_size:
stride:
padding:
dilation:
Returns:
"""
kernel_size, stride, padding, dilation = (
_pair(kernel_size),
_pair(stride),
_pair(padding),
_pair(dilation),
)
ctx.kernel_size, ctx.stride, ctx.padding, ctx.dilation = (
kernel_size,
stride,
padding,
dilation,
)
assert input.dim() == 4 and input.is_cuda
batch_size, input_channels, input_height, input_width = input.size()
output_height = int(
(input_height + 2 * padding[0] - (dilation[0] * (kernel_size[0] - 1) + 1))
/ stride[0]
+ 1
)
output_width = int(
(input_width + 2 * padding[1] - (dilation[1] * (kernel_size[1] - 1) + 1))
/ stride[1]
+ 1
)
output = input.new(
batch_size,
input_channels,
kernel_size[0] * kernel_size[1],
output_height * output_width,
)
n = output.numel() // output.shape[2]
with torch.cuda.device_of(input):
f = load_kernel(
"subtraction_refpad_forward_kernel",
_subtraction_refpad_forward_kernel,
Dtype=get_dtype_str(input),
nthreads=n,
num=batch_size,
input_channels=input_channels,
bottom_height=input_height,
bottom_width=input_width,
top_height=output_height,
top_width=output_width,
kernel_h=kernel_size[0],
kernel_w=kernel_size[1],
stride_h=stride[0],
stride_w=stride[1],
dilation_h=dilation[0],
dilation_w=dilation[1],
pad_h=padding[0],
pad_w=padding[1],
)
f(
block=(CUDA_NUM_THREADS, 1, 1),
grid=(get_blocks_(n), 1, 1),
args=[input.data_ptr(), output.data_ptr()],
stream=Stream(ptr=torch.cuda.current_stream().cuda_stream),
)
ctx.save_for_backward(input)
return output
@staticmethod
def backward(ctx, grad_output):
"""
Args:
ctx:
grad_output:
Returns:
"""
kernel_size, stride, padding, dilation = (
ctx.kernel_size,
ctx.stride,
ctx.padding,
ctx.dilation,
)
(input,) = ctx.saved_tensors
assert grad_output.is_cuda
if not grad_output.is_contiguous():
grad_output = grad_output.contiguous()
batch_size, input_channels, input_height, input_width = input.size()
output_height = int(
(input_height + 2 * padding[0] - (dilation[0] * (kernel_size[0] - 1) + 1))
/ stride[0]
+ 1
)
output_width = int(
(input_width + 2 * padding[1] - (dilation[1] * (kernel_size[1] - 1) + 1))
/ stride[1]
+ 1
)
grad_input = None
opt = dict(
Dtype=get_dtype_str(grad_output),
num=batch_size,
input_channels=input_channels,
bottom_height=input_height,
bottom_width=input_width,
top_height=output_height,
top_width=output_width,
kernel_h=kernel_size[0],
kernel_w=kernel_size[1],
stride_h=stride[0],
stride_w=stride[1],
dilation_h=dilation[0],
dilation_w=dilation[1],
pad_h=padding[0],
pad_w=padding[1],
)
with torch.cuda.device_of(input):
if ctx.needs_input_grad[0]:
grad_input = input.new(
batch_size,
input_channels,
input_height + 2 * padding[0],
input_width + 2 * padding[1],
)
n = grad_input.numel()
opt["nthreads"] = n
f = load_kernel(
"subtraction_refpad_input_backward_kernel",
_subtraction_refpad_input_backward_kernel,
**opt
)
f(
block=(CUDA_NUM_THREADS, 1, 1),
grid=(get_blocks_(n), 1, 1),
args=[grad_output.data_ptr(), grad_input.data_ptr()],
stream=Stream(ptr=torch.cuda.current_stream().cuda_stream),
)
grad_input[..., padding[0] + 1 : 2 * padding[0] + 1, :] += torch.flip(
grad_input[..., : padding[0], :], dims=[2]
)
grad_input[
..., input_height - 1 : input_height + padding[0] - 1, :
] += torch.flip(
grad_input[..., input_height + padding[0] :, :], dims=[2]
)
grad_input[..., padding[1] + 1 : 2 * padding[1] + 1] += torch.flip(
grad_input[..., : padding[1]], dims=[3]
)
grad_input[
..., input_width - 1 : input_width + padding[1] - 1
] += torch.flip(grad_input[..., input_width + padding[1] :], dims=[3])
grad_input = grad_input[
...,
padding[0] : padding[0] + input_height,
padding[1] : padding[1] + input_width,
]
return grad_input, None, None, None, None
def subtraction_refpad(input, kernel_size=3, stride=1, padding=0, dilation=1):
"""
Args:
input:
kernel_size:
stride:
padding:
dilation:
Returns:
"""
assert input.dim() == 4
if input.is_cuda:
out = SubtractionRefpad.apply(input, kernel_size, stride, padding, dilation)
else:
raise NotImplementedError
return out
if __name__ == "__main__":
def test_subtraction_refpad():
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
kernel_size, stride, dilation = 5, 4, 2
padding = (dilation * (kernel_size - 1) + 1) // 2
n, c, in_height, in_width = 2, 8, 5, 5
out_height = int(
(in_height + 2 * padding - (dilation * (kernel_size - 1) + 1)) / stride + 1
)
out_width = int(
(in_width + 2 * padding - (dilation * (kernel_size - 1) + 1)) / stride + 1
)
x = torch.randn(n, c, in_height, in_width, requires_grad=True).double().cuda()
y1 = subtraction_refpad(
x,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
)
unfold_i = torch.nn.Unfold(
kernel_size=1, dilation=dilation, padding=0, stride=stride
)
unfold_j = torch.nn.Unfold(
kernel_size=kernel_size, dilation=dilation, padding=0, stride=stride
)
pad = torch.nn.ReflectionPad2d(padding)
y2 = unfold_i(x).view(n, c, 1, out_height * out_width) - unfold_j(pad(x)).view(
n, c, kernel_size**2, out_height * out_width
)
assert (y1 - y2).abs().max() < 1e-9
gx1 = torch.autograd.grad(y1.mean(), x, retain_graph=True)[0]
gx2 = torch.autograd.grad(y2.mean(), x, retain_graph=True)[0]
assert (gx1 - gx2).abs().max() < 1e-9
from functools import partial
assert torch.autograd.gradcheck(
partial(
subtraction_refpad,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
),
x,
)
print("test case passed")
test_subtraction_refpad()
| [
"[email protected]"
] | |
53758dfee8d24524a5dff4a2ed46b924ffae7586 | 1267e7d3d6c9a0465c683a708373bcaf70e6014c | /Hangman.py | fff2b0ec01308bf1122143ddacba24bad91a5a84 | [] | no_license | Thomsd2/Hangman | 5a75920b89d209a78ad8f3227758b636c17191f6 | a99562840b80ff90c4a3dbdada21229095383db8 | refs/heads/main | 2023-06-01T12:09:49.993779 | 2021-06-22T14:06:52 | 2021-06-22T14:06:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,864 | py | #Cette fois-ci c'est un pendu (en anglais rip les non-bilingues)
#les imports
import time
import random
import sys
#voilà
#les variables
words_to_find = open("words.txt").read().splitlines()
word_to_find = random.choice(words_to_find)
# word_to_find =
#fin des variables
#explication
print ("Hi, you are playing a Hangman game .\nThe word to be guessed is randomly selected in the English dictionnary.\nYou can guess 7 times wrong the word before losing.\nGood luck!")
time.sleep(1)
#début du code
banana_word = list(word_to_find)
longueur_du_mot = len(word_to_find)
guessing=longueur_du_mot * "_"
listedudevinnage = list(guessing)
banana_word_copy = banana_word.copy()
guesses=7
while banana_word_copy != listedudevinnage:
lettre = input("Submit a letter\n")
nbrdefoislalettre = banana_word_copy.count(lettre)
nbrdefoislalettrepourleif = nbrdefoislalettre
for letter in banana_word:
if letter == lettre:
while nbrdefoislalettre != 0:
nbrdefoislalettre = nbrdefoislalettre - 1
lindex = banana_word.index(letter)
banana_word.pop(lindex)
banana_word.insert(lindex,"_")
listedudevinnage.pop(lindex)
listedudevinnage.insert(lindex, letter)
if nbrdefoislalettrepourleif == 0:
guesses=guesses-1
if guesses == 0:
print (" +---+\n | |\n O |\n /|\ |\n / \ |\n |\n=========")
print("Sorry. You lost! The word was " + word_to_find + ".")
time.sleep(4)
sys.exit()
if guesses == 1:
print("No, sorry. The letter " + lettre + " isn't in the word.\nYou get " + str(guesses) + " guess before getting hanged")
print (" +---+\n | |\n O |\n /|\ |\n / |\n |\n=========")
break
else:
print("No, sorry. The letter " + lettre + " isn't in the word.\nYou get " + str(guesses) + " guesses before getting hanged")
if guesses == 6:
print (" +---+\n | |\n |\n |\n |\n |\n=========")
if guesses == 5:
print (" +---+\n | |\n O |\n |\n |\n |\n=========")
if guesses == 4:
print (" +---+\n | |\n O |\n | |\n |\n |\n=========")
if guesses == 3:
print (" +---+\n | |\n O |\n /| |\n |\n |\n=========")
if guesses == 2:
print (" +---+\n | |\n O |\n /|\ |\n |\n |\n=========")
break
print (" ".join(listedudevinnage) + "\n")
else:
time.sleep(1)
print("Well done ! You guessed the world which was " + word_to_find)
time.sleep(4)
| [
"[email protected]"
] | |
4cd2fe1340dd2c599c3640ac2bc059ddc33cf527 | c652d5be0b8b112988fefe614c86fd7d426d7471 | /Presentation/tell.py | aa7fab391600fce1d3ee1c81912b192cb11adb64 | [] | no_license | vral-parmar/Basic-Python-Programming | 53fd489494ef24a3f80b17f33989d6c981e41dde | ef20b174bdc7125933e32ad6691f2d9386b34ac2 | refs/heads/master | 2020-12-09T15:51:30.476570 | 2020-07-25T11:46:28 | 2020-07-25T11:46:28 | 233,352,089 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 58 | py | f = open("Presentation/example.txt", "r")
print(f.tell())
| [
"[email protected]"
] | |
218fe6c319d1275ea633bf971e641fc1c0ac710f | 5b1533b0f8c4121b12600a784041e0e03bca9752 | /snakemake/RNA_seq/diff_exp/count_matrix_long.snakemake | de381a5cca39bff7074cb3467d6da0527336f734 | [] | no_license | 522845911/exVariance | e49d485a6ff5b7a352a3eae83d53c20e083efaf9 | 3b2d65f770c0df50e0d75c3b0fdeb02fe4efd85c | refs/heads/master | 2023-01-15T00:31:00.520630 | 2020-11-23T14:47:01 | 2020-11-23T14:47:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,305 | snakemake | # vim: syntax=python tabstop=4 expandtab
# coding: utf-8
#---------------------------
# @author: Shang Zhang
# @email: [email protected]
# @date: Sep, 3rd, 2020
#---------------------------
# count_method_regex = '(featurecounts)|(htseq)'
###------------------------The output section---------------------------###
rule featurecounts:
input:
bam='{output_dir}/bam/{sample_id}/{map_step}.bam',
gtf=config.get('genome_dir') + '/gtf/long_RNA.gtf'
output:
counts='{output_dir}/counts/featurecounts/{sample_id}/{map_step}',
summary='{output_dir}/counts/featurecounts/{sample_id}/{map_step}.summary'
params:
strandness={'no': 0, 'forward': 1, 'reverse': 2}.get(config.get('strandness'), 0),
paired_end={True: '-p', False: ''}[config.get('paired_end')],
min_mapping_quality=config.get('min_mapping_quality'),
count_multimap_reads='-M' if config.get('count_multimap_reads') else '',
count_overlapping_features='-O' if config.get('count_overlapping_features') else ''
wildcard_constraints:
map_step='(?!circRNA).*'
conda:
"../../envs/count_matrix.yaml"
log:
'{output_dir}/log/count_matrix/featurecounts/{sample_id}_{map_step}.log'
shell:
'''featureCounts {params.count_overlapping_features} -t exon -g gene_id {params.count_multimap_reads} \
-s {params.strandness} -Q {params.min_mapping_quality} \
{params.paired_end} -a {input.gtf} -o {output.counts} {input.bam} > {log} 2>&1
'''
rule htseq:
input:
bam='{output_dir}/bam/{sample_id}/{map_step}.bam',
gtf=config.get('genome_dir') + '/gtf/long_RNA.gtf'
output:
counts='{output_dir}/counts/htseq/{sample_id}/{map_step}'
params:
strandness={'forward': 'yes', 'reverse': 'reverse'}.get(config.get('strandness'), 'no'),
min_mapping_quality=config.get('min_mapping_quality'),
count_overlapping_features='all' if config.get('count_overlapping_features') else 'none'
wildcard_constraints:
map_step='(?!circRNA).*'
conda:
"../../envs/count_matrix.yaml"
log:
'{output_dir}/log/count_matrix/htseq/{sample_id}_{map_step}.log'
shell:
'''htseq-count -t exon -i gene_id -f bam -a {params.min_mapping_quality} \
--nonunique {params.count_overlapping_features} -s {params.strandness} \
{input.bam} {input.gtf} > {output.counts} 2> {log}
'''
rule count_circRNA:
input:
'{output_dir}/bam/{sample_id}/{map_step}.bam'
output:
'{output_dir}/counts/count_circrna/{sample_id}/{map_step}'
params:
paired_end={True: '-p', False: ''}[config.get('paired_end')],
strandness=config.get('strandness'),
min_mapping_quality=config.get('min_mapping_quality'),
count_reads_script=config.get('root_dir') + '/bin/count_reads_zs_app.py'
wildcard_constraints:
map_step='circRNA.*'
conda:
"../../envs/count_matrix.yaml"
log:
'{output_dir}/log/count_matrix/count_circRNA/{sample_id}_{map_step}.log'
shell:
'''{params.count_reads_script} count_circrna -s {params.strandness} \
-q {params.min_mapping_quality} {params.paired_end} \
-i {input} -o {output} > {log} 2>&1
'''
class get_rmdup_counts:
def __init__(self, template, rmdup=False):
if rmdup:
self.template = template + '_rmdup'
else:
self.template = template
def __call__(self, wildcards):
return expand(self.template, sample_id=sample_ids, **wildcards)
rule count_matrix_circrna:
input:
circrna_counts=get_rmdup_counts('{output_dir}/counts/count_circrna/{sample_id}/circRNA', rmdup=remove_duplicates_long),
circrna_sizes=config.get('genome_dir') + '/chrom_sizes/circRNA'
output:
'{output_dir}/count_matrix/circRNA.txt'
run:
import pandas as pd
# read circRNA counts from individual files
matrix_circrna = {}
for filename in input.circrna_counts:
sample_id = filename.split('/')[-2]
matrix_circrna[sample_id] = pd.read_table(filename, sep='\t', header=None, index_col=0).iloc[:, 0]
matrix_circrna = pd.DataFrame(matrix_circrna)
matrix_circrna = matrix_circrna.loc[:, sample_ids]
matrix_circrna.fillna(0, inplace=True)
matrix_circrna = matrix_circrna.astype('int')
matrix_circrna = matrix_circrna.loc[matrix_circrna.sum(axis=1) > 0].copy()
# annotate circRNA
circrna_sizes = pd.read_table(input.circrna_sizes, sep='\t', header=None, index_col=0).iloc[:, 0]
circrna_ids = matrix_circrna.index.values
matrix_circrna.index = circrna_ids + '|circRNA|' + circrna_ids + '|' + circrna_ids\
+ '|' + circrna_ids + '|0|' + circrna_sizes.loc[circrna_ids].values.astype('str')
matrix_circrna.index.name = 'feature'
matrix_circrna.to_csv(output[0], sep='\t', header=True, index=True, na_rep='NA')
rule count_matrix:
input:
counts=get_rmdup_counts('{output_dir}/counts/{count_method}/{sample_id}/genome', rmdup=config.get('remove_duplicates_long')),
matrix_circrna='{output_dir}/count_matrix/circRNA.txt',
transcript_table=config.get('genome_dir') + '/transcript_table/all.txt',
gene_length=config.get('genome_dir') + '/gene_length/long_RNA'
output:
'{output_dir}/count_matrix/{count_method}.txt'
wildcard_constraints:
count_method='(?!circRNA).*'
run:
import pandas as pd
import re
# annotate features
transcript_table = pd.read_table(input.transcript_table, sep='\t', dtype='str')
transcript_table = transcript_table.drop_duplicates('gene_id', keep='first')
transcript_table.set_index('gene_id', inplace=True, drop=False)
# read gene counts from individual files
matrix = {}
sample_ids = []
for filename in input.counts:
sample_id = filename.split('/')[-2]
sample_ids.append(sample_id)
if wildcards.count_method == 'featurecounts':
matrix[sample_id] = pd.read_table(filename, comment='#', sep='\t', index_col=0)
matrix[sample_id] = matrix[sample_id].iloc[:, -1]
elif wildcards.count_method == 'htseq':
matrix[sample_id] = pd.read_table(filename, comment='__', sep='\t', header=None, index_col=0).iloc[:, 0]
matrix = pd.DataFrame(matrix)
matrix = matrix.loc[:, sample_ids]
# remove all-zero features
matrix = matrix.loc[matrix.sum(axis=1) > 0].copy()
gene_ids = matrix.index.values
# remove features not in transcript table
gene_ids = gene_ids[~(transcript_table.reindex(gene_ids)['gene_id'].isna().values)]
matrix = matrix.loc[gene_ids]
# read gene lengths
gene_lengths = pd.read_table(input.gene_length, sep='\t', index_col=0, dtype='str').loc[:, 'merged']
# remove features not in gene length
gene_ids = gene_ids[~(gene_lengths.reindex(gene_ids).isna().values)]
matrix = matrix.loc[gene_ids]
# annotate features
feature_names = transcript_table.loc[gene_ids, 'gene_id'].values \
+ '|' + transcript_table.loc[gene_ids, 'gene_type'].values \
+ '|' + transcript_table.loc[gene_ids, 'gene_name'].values \
+ '|' + transcript_table.loc[gene_ids, 'gene_id'].values \
+ '|' + transcript_table.loc[gene_ids, 'gene_id'].values \
+ '|0|' + gene_lengths.loc[gene_ids].values
matrix.index = feature_names
# merge gene matrix and circRNA matrix
matrix_circrna = pd.read_table(input.matrix_circrna, sep='\t', index_col=0)
matrix = pd.concat([matrix, matrix_circrna], axis=0)
matrix.index.name = 'feature'
matrix.to_csv(output[0], sep='\t', header=True, index=True, na_rep='NA')
rule count_matrix_mRNA:
input:
'{output_dir}/count_matrix/{count_method}.txt'
output:
'{output_dir}/count_matrix/{count_method}_mrna.txt'
wildcard_constraints:
count_method=count_method_regex
conda:
"../../envs/count_matrix.yaml"
log:
'{output_dir}/log/count_matrix/count_matrix_mRNA/{count_method}.log'
shell:
'''awk 'NR==1{{print}}NR>1{{split($0,a,"|");if(a[2] == "mRNA") print}}' {input} > {output} 2> {log}
'''
rule count_matrix_lncRNA:
input:
'{output_dir}/count_matrix/{count_method}.txt'
output:
'{output_dir}/count_matrix/{count_method}_lncrna.txt'
wildcard_constraints:
count_method=count_method_regex
conda:
"../../envs/count_matrix.yaml"
log:
'{output_dir}/log/count_matrix/count_matrix_lncRNA/{count_method}.log'
shell:
'''awk 'NR==1{{print}}NR>1{{split($0,a,"|");if(a[2] == "lncRNA") print}}' {input} > {output} 2> {log}
'''
###------------------------The summary section---------------------------###
# rule summarize_fragment_counts:
# input:
# fragment_counts=lambda wildcards: expand(config.get('summary_dir') + '/all_bam_stats/{sample_id}/fragment_counts/{map_step}',
# sample_id=sample_ids, map_step=map_steps),
# count_matrix=config.get('output_dir') + '/count_matrix/featurecounts.txt'
# output:
# config.get('summary_dir') + '/read_counts/read_counts.txt'
# wildcard_constraints:
# count_method=count_method_regex
# run:
# import pandas as pd
# # read fragment counts for each mapping step
# fragment_counts = pd.DataFrame(index=map_steps, columns=sample_ids)
# for filename in input.fragment_counts:
# c = filename.split('/')
# sample_id = c[-2]
# map_step = c[-1]
# with open(filename, 'r') as f:
# fragment_counts.loc[map_step, sample_id] = int(f.read().strip())
# fragment_counts = fragment_counts.astype('int')
# fragment_counts.columns.name = 'sample_id'
# fragment_counts.drop(index='circRNA', inplace=True)
# # read count matrix
# count_matrix = pd.read_table(input.count_matrix, sep='\t', index_col=0)
# feature_info = count_matrix.index.to_series().str.split('|', expand=True)
# feature_info.columns = ['gene_id', 'gene_type', 'gene_name', 'domain_id', 'transcript_id', 'start', 'end']
# count_matrix = pd.concat([feature_info, count_matrix], axis=1)
# counts_by_rnatype = count_matrix.groupby('gene_type')[sample_ids].sum()
# counts_by_rnatype = counts_by_rnatype.loc[:, sample_ids]
# matrix = pd.concat([fragment_counts, counts_by_rnatype], axis=0)
# matrix.index.name = 'rna_type'
# matrix.to_csv(output[0], sep='\t', header=True, index=True, na_rep='NA')
# rule summarize_fragment_counts_jupyter:
# input:
# summary='{output_dir}/summary/read_counts.txt',
# jupyter=root_dir + '/templates/summarize_read_counts_long.ipynb'
# output:
# jupyter='{output_dir}/summary/read_counts.ipynb',
# html='{output_dir}/summary/read_counts.html'
# run:
# shell(nbconvert_command) | [
"[email protected]"
] | |
abcb59f0d5fb7ded12a38330c51b2648218e241f | 37d7f34ecf9fe2ede31252d9fba186768a161817 | /ytList.py | a7229e9483ff846a167db6a0245b6ff7caec7437 | [] | no_license | shikamaruNara3971/youtube_Downloader | 7a46deb456cc9acb55b8ea05962da3d674e70d29 | 7352c1c2051686caf33f03639aaab4de1f7bf3ad | refs/heads/main | 2023-06-03T11:49:17.451485 | 2021-06-23T08:11:50 | 2021-06-23T08:11:50 | 379,523,879 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 468 | py |
#The Author Name is Shikamaru Nara
#To this code to work import pytube
# Go to python interpreter
# Search for pytube
# Install pytube
from pytube import Playlist
try:
aList=Playlist("Enter your playlist link here")
def download_all():
print(f'Downloading in process: {aList.title}')
for video in aList.videos:
video.streams.first().download()
download_all()
print("The playlist downloaded sucessfully")
except Exception as e:
print(e)
| [
"[email protected]"
] | |
e52ce94b00b77f00026739ea4bb11ef738420240 | ad84af764e0a45211681c7629cf7b1c2226028c7 | /pics/admin.py | 01c15fe63ca7f4be26697083cdcb1b5ad523c2b5 | [] | no_license | Macharia-Tech/galla.me | d2bd353ea969db6ad333406c5f6404308bc2365a | 4bdf3e5b471f1f3b7368aba0bc80d1b6209ec317 | refs/heads/master | 2023-08-14T01:15:58.055834 | 2020-02-04T13:52:05 | 2020-02-04T13:52:05 | 227,810,753 | 0 | 0 | null | 2021-09-22T18:30:41 | 2019-12-13T10:07:39 | Python | UTF-8 | Python | false | false | 165 | py | from django.contrib import admin
from .models import location,Category,Image
admin.site.register(location)
admin.site.register(Image)
admin.site.register(Category)
| [
"[email protected]"
] | |
034e44876afd2c93107c7df2cb48c4b4ace39127 | 1af3029ea88e50ce3d7cbbf089eead8a75e9e26a | /listoperations.py | 1faa646ad1859733b6da45f8a30c64feae189927 | [] | no_license | iampython-team/Python_Aug2020 | 899cb6699bbf423ab8b645d6dc570c4d30ba9d19 | 1999538d0308e558dd07501183539f1f09556699 | refs/heads/master | 2022-12-24T08:09:53.625300 | 2020-09-30T05:49:18 | 2020-09-30T05:49:18 | 299,820,318 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,059 | py |
listx=['Poland','Singapore','India','Norway','Norway','SouthAfrica','Singapore']
# 0 1 2 3 4
southAmerica=['Chile','Peru']
# insertion functions or operations
listx.insert(3,'Nepal') # only one item or object can be added at given postion of list
print(listx)
listx.append('Uganda') # only one item or object can be added at end of the list
print(listx)
listx.extend(southAmerica) # multiple items can be added. Item must be an iterable object
print(listx)
# update functions
new_list=listx.copy()
print(new_list)
# delete functions
#listx.clear() # clear all the data from the list
#print(listx)
listx.pop()
print(listx)
listx.remove('Norway')
print(listx)
# support or other functions
print(listx.index('India'))
print(listx.count('Singapore'))
listx.sort()
print(listx)
numbers =[True,False,True,False,False,False,True]
numbers.sort()
print(numbers)
listx.reverse()
print(listx)
prime_numbers=[3,5,23,2,11,7,19,13]
prime_numbers.sort(reverse=True) # sort --> reverse
print(prime_numbers) | [
"[email protected]"
] | |
8a5c40061871677f9c0fa418ca7731568301fe8c | b2e505fd6066320374b4b72afc2518eedf26fd2e | /NFL-ELO-predictor.py | 568cfaec8334c38468dea8c200d3e395bdb760cd | [] | no_license | GoofballInc/NFLGamePredictor | 99eac390fe5535ce0485373ce466445981c6535d | d5d8232e4e2e8e1931a90e67d84c792c267646c3 | refs/heads/master | 2023-03-24T04:35:48.634773 | 2020-03-26T15:46:38 | 2020-03-26T15:46:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 74,110 | py |
"""
ELO rater for NFL teams
To Add:
Standings
Simulate Season
"""
# =============================================================================
# Libraries
# =============================================================================
import numpy as np
import pandas as pd
import re
import datetime as dt
# from dateutil.relativedelta import relativedelta
from haversine import haversine
import math
import json
from functools import reduce
# import heapq
import itertools
import jellyfish
import os
import urllib
import seaborn as sns
from matplotlib import pyplot as plt
import time
# =============================================================================
# Directory
# =============================================================================
path = '/Users/graemepm/Dropbox/pgam/NFL/Predict-V2/'
# =============================================================================
# Outstanding
# =============================================================================
# 1) Division changes
# 2) Distance for moved changes
# 3) Expansion teams
# =============================================================================
# Class
# =============================================================================
class FootballSeason:
'''
Rank NFL teams and predict games
'''
def __init__(self, year=None, qb_changes=None, season=None): #Move QB changes to load-starting values
self.qb_val_to_elo = 3.3
self.hist_stats_until = 2019
self.team_records = {}
self.wl_records = {}
self.k = 20 # Change over season
self.quarterbacks = {}
self.qb_teams = {}
self.qb_changes = {}
self.prediction_results = None
for week in ['w' + str(i) for i in range(1,18)] + ['WildCard', 'Division', 'ConfChamp', 'SuperBowl']:
self.qb_changes[week] = {}
if qb_changes:
self.qb_changes.update(qb_changes)
self.season = season #!!!
if year:
if isinstance(year, int) and 2000 <= year <= dt.datetime.today().date().year:
self.year = year
else:
raise ValueError('Year must be integer after 2000 and not future year')
else:
tday = dt.datetime.today().date()
year = tday.year
if tday.month in [1,2]:
year += 1
self.year = year
self.__league_info()
self.__get_season()#!!!
self.__load_qb_stats()
self.__load_records()
self.__load_wl_records()
self.__load_byes()
self.__calculate_raw_standings()
self.__load_division_standings()
self.__load_qb_starters()
def __league_info(self):
'''Load dictionary of NFL teams, team names, city GPS, divisions, conferences'''
with open(path + 'NFL_info.json', 'r') as f:
info = json.loads(f.read())
self.divisions = {}
self.conferences = {}
self.team_names = info['team_names']
self.league = info['league']
self.gps = info['gps']
self.team_colors = info['team_colors']
self.__info = info
## Name/acronym lookup
self.name_lookup = {name: team for team, names in
self.team_names.items() for name in names
if len(name) > 3}
self.acronym_lookup = {name: team for team, names in
self.team_names.items() for name in names
if len(name) <= 3}
## Calculate distance between cities
def calculate_distance(team1, team2):
return haversine(self.gps[team1], self.gps[team2], unit='mi')
self.distances = pd.DataFrame(index=self.gps.keys(),
columns=self.gps.keys())
for team, row in self.distances.iterrows():
for opp, col in row.items():
self.distances.at[team, opp] = calculate_distance(team, opp)
## Load Divisions
divnames = set([team['div'] for team in self.league.values()])
for division in divnames:
teams = []
for team, spot in self.league.items():
if division==spot['div']:
teams.append(team)
self.divisions.update({division: teams})
self.team_divisions = {team: division for division, teams in
self.divisions.items() for team in teams}
## Load Conferences
for conference in ['NFC', 'AFC']:
teams = []
for team, spot in self.league.items():
if conference==spot['conf']:
teams.append(team)
self.conferences.update({conference: teams})
## Load week numbers
weeks = ['w' + str(i) for i in range(18)] + ['WildCard', 'Division', 'ConfChamp', 'SuperBowl']
self.week_numbers = {week: i for i, week in enumerate(weeks)}
def __standardize_team(self, team):
'''Find standard team acronym given team name input (from 2000 on)'''
def comp_str(s1, s2):
S1 = str(s1).upper()
S2 = str(s2).upper()
ed = jellyfish.damerau_levenshtein_distance(S1, S2)
return 1 - (ed / max(len(S1), len(S2)))
if team in self.team_names.keys():
return team
if team in self.acronym_lookup.keys():
return self.acronym_lookup[team]
name_comp = {name: comp_str(team, name) for name in self.name_lookup.keys()}
if max(name_comp.values()) >= 0.9:
return self.name_lookup[max(name_comp, key=name_comp.get)]
raise ValueError(team + ' unknwown team name')
def __get_season(self):
'''
Download NFL season schedule from profootballreference.com
with live win-loss info for games played through course of season.
For seasons in years 2000-2018, upload dataset file of NFL records
'''
start_time = time.time()
def format_schedule(row, year):
if len(row.Week) <= 2:
week = 'w' + str(row.Week)
else:
week = row.Week
season = year
if row.Date in ['January', 'February']:
date_year = str(int(year) + 1)
else:
date_year = str(year)
if pd.isnull(row.Time):
row.Time = '8:00AM'
date_string = ' '.join([row.Date, date_year, row.Time])
date_time = dt.datetime.strptime(date_string, '%B %d %Y %I:%M%p')
date = date_time.date()
if row['Unnamed: 5']=='@':
away = row['Winner/tie']
score_away = float(row['PtsW'])
yds_away = float(row['YdsW'])
to_away = float(row['TOW'])
home = row['Loser/tie']
score_home = float(row['PtsL'])
yds_home = float(row['YdsL'])
to_home = float(row['TOL'])
else:
home = row['Winner/tie']
score_home = float(row['PtsW'])
yds_home = float(row['YdsW'])
to_home = float(row['TOW'])
away = row['Loser/tie']
score_away = float(row['PtsL'])
yds_away = float(row['YdsL'])
to_away = float(row['TOL'])
if score_home == score_away:
winner = 'TIE'
elif score_home > score_away:
winner = home
elif score_away > score_home:
winner = away
else:
winner = np.NaN
return (season, week, date_time, date, away, home, winner, score_away,
score_home, yds_away, yds_home, to_away, to_home)
if self.year < self.hist_stats_until:
schedule = pd.read_csv(path + 'hist_records_thru2018.txt',
sep='\t', parse_dates=['date_time'])
schedule = schedule[schedule.season.eq(self.year)]
else:
url = os.path.join('https://www.pro-football-reference.com/years',
str(self.year), 'games.htm')
lines = urllib.request.urlopen(url, timeout = 20).read()
schedule = pd.read_html(lines)[0]
schedule = schedule[schedule.Week.astype(str).ne('Week')]
schedule = schedule.dropna(subset=['Week'])
schedule = [format_schedule(row, self.year) for i, row in schedule.iterrows()]
schedule = pd.DataFrame(schedule)
schedule.columns = ['season', 'week', 'date_time', 'date', 'away', 'home', 'winner',
'score_away', 'score_home', 'yds_away', 'yds_home',
'to_away', 'to_home']
if type(self.season) is not pd.DataFrame: #!!!
self.season = schedule
self.week_matches = {}
for i, row in self.season.iterrows():
away = self.__standardize_team(row.away)
home = self.__standardize_team(row.home)
away_result, home_result = np.nan, np.nan
if pd.notnull(row.winner):
if str(row.winner).upper() == 'TIE':
away_result, home_result = 0.5, 0.5
elif row.winner == row.away:
away_result, home_result = 1.0, 0.0
elif row.winner == row.home:
away_result, home_result = 0.0, 1.0
if row.week in self.week_matches.keys():
self.week_matches[row.week].append((away, home, away_result, home_result))
else:
self.week_matches[row.week] = [(away, home, away_result, home_result)]
self.team_matches = {}
for team in self.team_names.keys():
self.team_matches[team] = []
for week, games in self.week_matches.items():
for game in games:
self.team_matches[game[0]].append((week,) + game)
self.team_matches[game[1]].append((week,) + game)
this_week = dt.datetime(self.year, 1, 1), np.NaN
for i, row in self.season.iterrows():
if row.date_time > this_week[0] and pd.notnull(row.winner):
this_week = row.date_time, row.week
self.this_week = this_week[1]
end_time = time.time()
elapsed_time = round(end_time - start_time, 3)
func_msg = 'Loading ' + str(self.year) + ' game stats completed: '
sec_msg = str(elapsed_time) + ' sec'
print(func_msg + sec_msg)
def __load_records(self):
'''
Populate team records with win, loss, tie
'''
# Load empty records from schedule
def record_dict():
weeks = ['w' + str(i) for i in range(1,18)]
weeks += ['WildCard', 'Division', 'ConfChamp', 'SuperBowl']
week_dict = {}
for week in weeks:
week_dict[week] = {'fd': None, 'opp': None, 'result': None,
'pf': None, 'pa': None, 'win_prob': None,
'elo_pre': None, 'elo_post': None, 'elo_diff': None}
return week_dict
self.team_records = {}
for team in self.team_names.keys():
self.team_records[team] = record_dict()
for i, row in self.season.iterrows():
week = row.week
home = self.__standardize_team(row.home)
away = self.__standardize_team(row.away)
self.team_records[home][week]['fd'] = 'home'
self.team_records[home][week]['opp'] = away
self.team_records[away][week]['fd'] = 'away'
self.team_records[away][week]['opp'] = home
if pd.notnull(row.winner):
self.team_records[home][week]['pf'] = row.score_home
self.team_records[home][week]['pa'] = row.score_away
self.team_records[away][week]['pf'] = row.score_away
self.team_records[away][week]['pa'] = row.score_home
if row.winner == 'TIE':
self.team_records[home][week]['result'] = 'tie'
self.team_records[away][week]['result'] = 'tie'
elif row.winner==row.home:
self.team_records[home][week]['result'] = 'win'
self.team_records[away][week]['result'] = 'loss'
elif row.winner==row.away:
self.team_records[home][week]['result'] = 'loss'
self.team_records[away][week]['result'] = 'win'
def get_record_team(self, team, group='overall'):
'''
Get win-loss record for specific team from FootballSeason class team records
'''
if group not in ['overall', 'division', 'conference']:
raise ValueError('Group must be overall, division, or conference')
team = self.__standardize_team(team)
div = self.league[team]['div']
conf = self.league[team]['conf']
win, loss, tie = 0, 0, 0
reg_weeks = ['w' + str(i) for i in range(1,18)]
if group=='overall':
for week, game in self.team_records[team].items():
if week in reg_weeks:
if game['result']=='win':
win += 1
elif game['result']=='loss':
loss += 1
elif game['result']=='tie':
tie += 1
if group=='division':
for week, game in self.team_records[team].items():
if week in reg_weeks:
if game['result']:
if self.league[game['opp']]['div'] == div:
if game['result']=='win':
win += 1
elif game['result']=='loss':
loss += 1
elif game['result']=='tie':
tie += 1
if group=='conference':
for week, game in self.team_records[team].items():
if week in reg_weeks:
if game['result']:
if self.league[game['opp']]['conf'] == conf:
if game['result']=='win':
win += 1
elif game['result']=='loss':
loss += 1
elif game['result']=='tie':
tie += 1
if sum([win, loss, tie]) == 0:
wp = np.NaN
else:
wp = ((win * 1) + (tie * 0.5))/ sum([win, loss, tie])
return win, loss, tie, wp
def __load_wl_records(self):
for team in self.team_records.keys():
full = self.get_record_team(team)
div = self.get_record_team(team, 'division')
conf = self.get_record_team(team, 'conference')
self.wl_records.update({team: full + div + conf})
def get_records_all(self):
record_df = pd.DataFrame.from_dict(self.wl_records, orient='index')
record_df.columns = ['win', 'loss', 'tie', 'wp',
'div_win', 'div_loss', 'div_tie', 'div_wp',
'conf_win', 'conf_loss', 'conf_tie', 'conf_wp']
return record_df
def __load_byes(self):
self.byes = {}
for week in ['w' + str(i) for i in range(18)]:
self.byes[week] = []
if week != 'w0':
for team, record in self.team_records.items():
if record[week]['opp'] is None:
self.byes[week].append(team)
for week in ['WildCard', 'Division', 'ConfChamp', 'SuperBowl']:
self.byes[week] = []
if week == 'WildCard':
for team, record in self.team_records.items():
if record['WildCard']['opp'] is None and record['Division']['opp'] is not None:
self.byes[week].append(team)
def load_starting_values(self,
elo_values=None,
qb_vals=None,
qb_vals_team=None,
w1_qb_starters=None,
revert=True):
'''
Load in team ELO rating values and quarterback values to start the season.
elo_values: Dictionary with team acronyms for keys matching
FootballSeason.team_names.keys() and ELO rating values
qb_values: Dictionary with quarterback names as keys as they
appear on profootballreference.com and quarterback value
(Total QB yards above replacement)
regress: True or False. Whether to apply regression to the mean
for values from previous season
qb_starters: Dictionary with keys of teams for week 1 starting QBs
'''
if elo_values is None:
for team in self.team_names.keys():
self.team_records[team]['w1']['elo_pre'] = 1505
else:
for team, elo in elo_values.items():
if revert:
elo -= (elo - 1505)/3
team = self.__standardize_team(team)
self.team_records[team]['w1']['elo_pre'] = elo
if team in self.byes['w1']:
self.team_records[team]['w2']['elo_pre'] = elo
def create_qb_dict():
d = {}
weeks = [w for w in self.week_numbers.keys() if w != 'w0']
for week in weeks:
d[week] = {'val_pre': None, 'val_game': None, 'val_adj': None,
'opp': None, 'val_post': None, 'val_change': None}
return d
def create_qbteam_dict():
d = {}
weeks = [w for w in self.week_numbers.keys() if w != 'w0']
for week in weeks:
d[week] = {'valF_pre': None, 'valA_pre': None,
'valF_game': None, 'valA_game': None,
'valF_post': None, 'valA_post': None, 'opp': None}
return d
if qb_vals is None:
self.qb_vals = {}
else:
self.qb_vals = {}
for qb, val in qb_vals.items():
self.qb_vals[qb] = create_qb_dict()
self.qb_vals[qb]['w1']['val_pre'] = val
if qb_vals_team is None:
self.qb_vals_team = {}
for team in self.team_names.keys():
self.qb_vals_team[team] = create_qbteam_dict()
self.qb_vals_team[team]['w1']['valF_pre'] = 50
self.qb_vals_team[team]['w1']['valA_pre'] = 50
else:
self.qb_vals_team = {}
for team, val in qb_vals_team.items():
self.qb_vals_team[team] = create_qbteam_dict()
self.qb_vals_team[team]['w1']['valF_pre'] = val[0]
self.qb_vals_team[team]['w1']['valA_pre'] = val[1]
if w1_qb_starters:
self.w1_qb_starters = w1_qb_starters
def get_ending_ELOS(self):
'''Output python dictionary of ending ELOS'''
end_ELOS = {}
for team, record in self.team_records.items():
if record['SuperBowl']['elo_post']:
end_ELOS[team] = record['SuperBowl']['elo_post']
elif record['ConfChamp']['elo_post']:
end_ELOS[team] = record['ConfChamp']['elo_post']
elif record['Division']['elo_post']:
end_ELOS[team] = record['Division']['elo_post']
elif record['WildCard']['elo_post']:
end_ELOS[team] = record['WildCard']['elo_post']
elif record['w17']['elo_post']:
end_ELOS[team] = record['w17']['elo_post']
if len(end_ELOS) == 32:
return end_ELOS
else:
return None
def __get_week_from_no(self, number):
'''Return week name from integer number input'''
week = np.NaN
for w, no in self.week_numbers.items():
if number == no:
week = w
return week
def __get_elo_pre_wk(self, team, week):
'''
Return team's pregame ELO from input week or latest week with pregame ELO
'''
elos = {w: r['elo_pre'] for w, r in self.team_records[team].items() if
r['elo_pre'] is not None}
max_elo_week = max(elos, key=self.week_numbers.get)
if self.week_numbers[week] <= self.week_numbers[max_elo_week]:
elo_pre = self.team_records[team][week]['elo_pre']
if elo_pre is None: # In case used on team's bye week
last_week = self.__get_week_from_no(self.week_numbers[week] - 1)
elo_pre = self.team_records[team][last_week]['elo_pre']
else:
elo_pre = self.team_records[team][max_elo_week]['elo_pre']
return elo_pre
def __update_post_elo_team_wk(self, team, week):
'''
Calculate posterior elo for a team given result
K = 20
ELO = ELO + (Outcome - Prediction) * K * MOV_factor
Margin Of Vicotry Factor:
ln(AbsolutePointDifferential) * 2.2/(ELODiffOutcomePred * 0.001 + 2.2)
'''
opp = self.team_records[team][week]['opp']
elo_pre = self.team_records[team][week]['elo_pre']
prediction = self.predict_game(team, opp, week) #!!!
result = self.team_records[team][week]['result']
score = 1 if result=='win' else 0 if result=='loss' else 0.5
elo_off = score - prediction[0]
point_diff = self.team_records[team][week]['pf'] - \
self.team_records[team][week]['pa']
m_o_v = math.log1p(abs(point_diff)) * (2.2/(abs(elo_off)*0.001 + 2.2))
elo_post = elo_pre + self.k * elo_off * m_o_v
self.team_records[team][week]['win_prob'] = prediction[0]
self.team_records[team][week]['elo_post'] = elo_post
self.team_records[team][week]['elo_diff'] = elo_post - elo_pre
def __update_pre_elo_team_next_wk(self, team, week):
'''Enter weeks posterior ELO rating into next week'''
week_no = self.week_numbers[week]
elo = self.team_records[team][week]['elo_post']
if week == 'SuperBowl':
pass
else:
next_week = self.__get_week_from_no(week_no + 1)
self.team_records[team][next_week]['elo_pre'] = elo
if team in self.byes[next_week]:
self.team_records[team][next_week]['elo_post'] = elo
next_next_week = self.__get_week_from_no(week_no + 2)
self.team_records[team][next_next_week]['elo_pre'] = elo
def update_ELOS(self):
'''Update each team's elo rating week by week'''
start_time = time.time()
this_week = self.this_week
this_week_no = self.week_numbers[this_week]
weeks_played = [w for w, w_no in self.week_numbers.items() if #!!!
w_no <= this_week_no and w != 'w0']
for week in weeks_played:
for team, record in self.team_records.items():
if record[week]['result'] is not None:
self.__update_post_elo_team_wk(team, week)
self.__update_pre_elo_team_next_wk(team, week)
end_time = time.time()
elapsed_time = round(end_time - start_time, 3)
func_msg = 'Updating ' + str(self.year) + ' ELO rating values completed: '
sec_msg = str(elapsed_time) + ' sec'
print(func_msg + sec_msg)
def __get_home_teams_wk(self, week):
'''Return home teams for a given home week'''
if week == 'SuperBowl':
return ()
else:
return (teams[1] for teams in self.week_matches[week])
def predict_game(self, team1, team2, week):
'''
Predict regular season game based on ELO ratings
'''
t1 = self.__standardize_team(team1)
t2 = self.__standardize_team(team2)
elo1 = self.__get_elo_pre_wk(t1, week)
elo2 = self.__get_elo_pre_wk(t2, week)
# Bye adjustment
if week == 'Division':
if not self.team_records[t1][week]['opp']:
elo1 += 25
if not self.team_records[t2][week]['opp']:
elo2 += 25
else:
week_no = self.week_numbers[week]
last_week = self.__get_week_from_no(week_no - 1)
if t1 in self.byes[last_week]:
elo1 += 25
if t2 in self.byes[last_week]:
elo2 += 25
# Distance adjustment
dist_adj = (self.distances.at[t1, t2]/1000) * 4
# Home adjustment
if t1 in self.__get_home_teams_wk(week):
elo1 += 55 + dist_adj
if t2 in self.__get_home_teams_wk(week):
elo2 += 55 + dist_adj
# QB adjustment
qb1 = self.qbs_tostart[week][t1]
qb2 = self.qbs_tostart[week][t2]
qb_val1 = self.__get_most_recent_qb_val_pre(qb1, week)
qb_val2 = self.__get_most_recent_qb_val_pre(qb2, week)
elo1 += (qb_val1*3.3)
elo2 += (qb_val2*3.3)
p1 = 1 / (1 + 10 ** ((elo2 - elo1) / 400))
p2 = 1 / (1 + 10 ** ((elo1 - elo2) / 400))
return round(p1, 4), round(p2, 4), -round((elo1 - elo2)/25, 1)
def predict_games(self):
self.games_predicted = {}
for week, games in self.week_matches.items():
predicted = []
for game in games:
prediction = self.predict_game(game[0], game[1], week)
predicted.append(game[:2] + prediction + game[2:])
self.games_predicted.update({week: predicted})
self.games_predicted_teams = {}
for team, games in self.team_matches.items():
predicted = []
for game in games:
prediction = self.predict_game(game[1], game[2], game[0])
predicted.append(game[:3] + prediction + game[3:])
self.games_predicted_teams.update({team: predicted})
def game_pick(row):
wprob = row.away_wprob
result = row.away_result
if pd.isnull(result):
return np.nan
if result==1:
if wprob > 0.5:
return 1
else:
return 0
if result==0:
if wprob > 0.5:
return 0
else:
return 1
if result==0.5:
if 0.4 < wprob <= 0.6:
return 0.5
else:
return 0
PREDICTIONS = pd.DataFrame()
for week, games in self.games_predicted.items():
predictions = pd.DataFrame(games)
predictions = predictions.assign(week = week)
PREDICTIONS = PREDICTIONS.append(predictions)
PREDICTIONS.columns = ['away', 'home', 'away_wprob', 'home_wprob',
'away_spread', 'away_result', 'home_result', 'week']
PREDICTIONS = PREDICTIONS.assign(
sqfd = (PREDICTIONS.away_wprob - PREDICTIONS.away_result)**2,
correct = PREDICTIONS.apply(game_pick, axis=1)
)
PREDICTIONS.dropna(subset=['away_result'], inplace=True)
brier_score = np.nanmean(PREDICTIONS.sqfd)
p_correct = np.nanmean(PREDICTIONS.correct)
away = PREDICTIONS[['away', 'sqfd']].copy()
away.columns = ['team', 'sqfd']
home = PREDICTIONS[['home', 'sqfd']].copy()
home.columns = ['team', 'sqfd']
team_sqfd = pd.concat([away, home], axis=0, sort=True).dropna()
team_brier = team_sqfd.groupby('team').mean().sort_values('sqfd', ascending=False)
# team_brier = team_brier.sqfd.to_dict()
self.brier_score = round(brier_score, 4)
self.p_correct = round(p_correct, 4) * 100
self.prediction_results = PREDICTIONS
self.team_brier_scores = team_brier
def __restart_qbs_with_changes(self, week):
if week == 'w1':
try:
for team, qb in self.w1_qb_starters.items():
self.qbs_tostart[week][team] = qb
except:
error = '''
Unable to load week 1 starting QBs
from profootballreference.com.
Require starter qb dictionary
'''
raise ValueError(error)
last_week = self.__get_week_from_no(self.week_numbers[week] - 1)
for team in self.qbs_tostart[week]:
if team in self.qb_changes[week]:
self.qbs_tostart[week][team] = self.qb_changes[week][team]
else:
qb = self.qbs_tostart[last_week][team]
if qb is None:
week_before = self.__get_week_from_no(self.week_numbers[last_week] - 1)
qb = self.qbs_tostart[week_before][team]
self.qbs_tostart[last_week][team] = qb
self.qbs_tostart[week][team] = qb
else:
self.qbs_tostart[week][team] = self.qbs_tostart[last_week][team]
def __download_qb_starters(self, week, year=None):
def cleanQB(qb):
qb = re.sub('\*','', qb)
qb = re.sub('"','', qb)
return qb
if year is None:
year = str(self.year)
else:
year = str(year)
week_no = self.week_numbers[week]
if week_no <= 17:
gametype = 'R'
week_min = str(week_no)
week_max = str(week_no)
else:
gametype = 'P'
week_min = '0'
week_max = '99'
head = 'https://www.pro-football-reference.com/play-index/pgl_finder.cgi?request=1'
year = '&match=game&year_min=' + year + '&year_max=' + year
sea = '&season_start=1&season_end=-1'
pos = '&pos%5B%5D=QB&is_starter=E'
gt = '&game_type=' + gametype
car = '&career_game_num_min=1&career_game_num_max=400'
st = '&qb_start_num_min=1&qb_start_num_max=400'
gn = '&game_num_min=0&game_num_max=99'
wk = '&week_num_min=' + week_min + '&week_num_max=' + week_max
qbst = '&qb_started=Y'
sort = '&c5val=1.0&order_by=game_date'
url = ''.join([head, year, sea, pos, gt, car, st, gn, wk, qbst, sort])
toread = True
while toread:
try:
lines = urllib.request.urlopen(url, timeout = 10).read()
toread = False
except:
time.sleep(5)
starters = pd.read_html(lines)[0]
starters = starters[starters.Week.astype(str).ne('Week')]
starters = starters.assign(Player = starters.Player.apply(cleanQB))
starters.set_index('Tm', inplace=True)
if len(starters) >= 24: # accounts for Byes
for team, row in starters.iterrows():
week = self.__get_week_from_no(int(row.Week))
team = self.__standardize_team(team)
self.qbs_tostart[week][team] = row.Player
return True
else:
return False
def __load_qb_starters(self):
start_time = time.time()
ws = [w for w in self.week_numbers.keys() if w != 'w0']
self.qbs_tostart = dict.fromkeys(ws)
for week in self.qbs_tostart.keys():
self.qbs_tostart[week] = dict.fromkeys(self.team_names.keys())
if self.year < self.hist_stats_until:
STARTERS = pd.read_csv(path + 'qb_starters_thru2018.txt', sep='\t')
STARTERS = STARTERS[STARTERS.Season.eq(self.year)]
for i, row in STARTERS.iterrows():
week = self.__get_week_from_no(int(row.Week))
team = self.__standardize_team(row.Tm)
self.qbs_tostart[week][team] = row.Player
else:
scrape = True
for week in self.week_matches.keys():
if scrape:
scrape = self.__download_qb_starters(week)
if not scrape:
self.__restart_qbs_with_changes(week)
else:
self.__restart_qbs_with_changes(week)
last_weeks = []
for i, (week, teams) in enumerate(self.qbs_tostart.items()):
last_weeks.append(week)
if i > 0:
for team, starter in teams.items():
if starter is None:
last_week = last_weeks[i-1]
self.qbs_tostart[week][team] = self.qbs_tostart[last_week][team]
end_time = time.time()
elapsed_time = round(end_time - start_time, 3)
func_msg = 'Loading ' + str(self.year) + ' starting quarterbacks completed: '
sec_msg = str(elapsed_time) + ' sec'
print(func_msg + sec_msg)
def __download_qb_stats_wk(self, week):
'''game type 'E'-regular and playoffs, 'R'-regular, 'P'-playoffs'''
year = str(self.year)
def clean_col(col):
col_text = ' '.join(col)
col_text = re.sub('Unnamed: [0-9]+_level_[0-9]', '', col_text)
col_text = col_text.strip()
return col_text
week_no = self.week_numbers[week]
if week_no > 17:
gametype = 'P'
week_min = '0'
week_max = '99'
else:
gametype = 'R'
week_min = str(week_no)
week_max = str(week_no)
head = 'https://www.pro-football-reference.com/play-index/pgl_finder.cgi?request=1&match=game'
y1 = '&year_min=' + str(year)
y2 = '&year_max=' + str(year)
sea = '&season_start=1&season_end=-1'
pos1 = '&pos%5B%5D=QB&pos%5B%5D=WR&pos%5B%5D=RB&pos%5B%5D=TE&pos%5B%5D='
pos2 = 'OL&pos%5B%5D=DL&pos%5B%5D=LB&pos%5B%5D=DB&is_starter=E'
gt = '&game_type=' + gametype
car = '&career_game_num_min=1&career_game_num_max=400'
start = '&qb_start_num_min=1&qb_start_num_max=400'
game = '&game_num_min=0&game_num_max=99'
w1 = '&week_num_min=' + week_min
w2 = '&week_num_max=' + week_max
stats1 = '&c1stat=pass_att&c1comp=gt&c1val=1&c2stat=rush_att&c2comp=gt&c2val=0'
stats2 = '&c3stat=fumbles&c3comp=gt&c5val=1&c6stat=pass_cmp&order_by=pass_att'
url = ''.join([head,y1,y2,sea,pos1,pos2,gt,car,start,game,w1,w2,stats1,stats2])
lines = urllib.request.urlopen(url, timeout = 20).read()
stats_df = pd.read_html(lines)[0]
stats_df.columns = [clean_col(col) for col in stats_df.columns.values]
stats_df.dropna(subset=['Week'], inplace=True)
stats_df = stats_df[stats_df.Week.astype(str).ne('Week')]
stats_df.rename(columns = {'': 'Is_At'}, inplace=True)
remove_asterisk = lambda x: re.sub('\*', '', x)
stats_df = stats_df.assign(Player = stats_df.Player.apply(remove_asterisk))
return stats_df
def __load_qb_stats(self):
start_time = time.time()
if self.year < self.hist_stats_until:
QB_STATS = pd.read_csv(path + 'passing_thru2018.txt',
sep='\t', parse_dates=['Date'])
min_year = dt.datetime(self.year, 8, 1)
max_year = dt.datetime(self.year + 1, 3, 1)
QB_STATS = QB_STATS[QB_STATS.Date.gt(min_year)]
QB_STATS = QB_STATS[QB_STATS.Date.lt(max_year)]
else:
stat_weeks = [week for week, week_no in self.week_numbers.items() if
week_no <= self.week_numbers[self.this_week]]
QB_STATS = pd.DataFrame()
for week in stat_weeks:
QB_STATS = QB_STATS.append(self.__download_qb_stats_wk(week))
QB_STATS = QB_STATS.assign(
Tm = QB_STATS.Tm.apply(self.__standardize_team),
Opp = QB_STATS.Opp.apply(self.__standardize_team),
Week = QB_STATS.Week.astype(int)
)
stat_cols = ['Passing Cmp', 'Passing Att', 'Passing Yds', 'Passing TD',
'Passing Int', 'Passing Sk', 'Rushing Att', 'Rushing Yds',
'Rushing TD', 'Fumbles Fmb']
QB_STATS[stat_cols] = QB_STATS[stat_cols].astype('float64')
self.qb_stats = QB_STATS
self.active_qbs = list(set(QB_STATS.Player))
end_time = time.time()
elapsed_time = round(end_time - start_time, 3)
func_msg = 'Loading ' + str(self.year) + ' quarterback stats completed: '
sec_msg = str(elapsed_time) + ' sec'
print(func_msg + sec_msg)
def get_qb_stats_raw(self, week, qb=None, for_team=None, against_team=None):
'''
Retreive games stats for quarterback or team-passing stats for given week
Returns python dictionary of quarterback/passing stats to be used for
value calculation implemented through sublcass
'''
stat_cols = ['Passing Cmp', 'Passing Att', 'Passing Yds', 'Passing TD',
'Passing Int', 'Passing Sk', 'Rushing Att', 'Rushing Yds',
'Rushing TD', 'Fumbles Fmb']
week_no = self.week_numbers[week]
STATS = self.qb_stats.copy()
STATS = STATS[STATS.Week.eq(week_no)]
if qb:
STATS = STATS[STATS.Player.eq(qb)]
elif for_team:
STATS = STATS[STATS.Tm.eq(for_team)]
elif against_team:
STATS = STATS[STATS.Opp.eq(against_team)]
if len(STATS) < 1:
return None, None
if qb or for_team:
OPP = list(STATS.Opp)[0]
else:
OPP = list(STATS.Tm)[0]
pa = np.nansum(STATS['Passing Att'])
pc = np.nansum(STATS['Passing Cmp'])
py = np.nansum(STATS['Passing Yds'])
pt = np.nansum(STATS['Passing TD'])
pi = np.nansum(STATS['Passing Int'])
ps = np.nansum(STATS['Passing Sk'])
ra = np.nansum(STATS['Rushing Att'])
ry = np.nansum(STATS['Rushing Yds'])
rt = np.nansum(STATS['Rushing TD'])
fm = np.nansum(STATS['Fumbles Fmb'])
stats = {'passing_att': pa, 'passing_cmp': pc, 'passing_yds':py,
'passing_td': pt, 'passing_int': pi, 'passing_sk': ps,
'rushing_att': ra, 'rushing_yds': ry, 'rushing_td': rt,
'fumbles_fmb': fm}
return stats, OPP
def __add_new_qbs(self, week):
def create_qb_dict():
d = {}
weeks = [w for w in self.week_numbers.keys() if w != 'w0']
for week in weeks:
d[week] = {'val_pre': None, 'val_game': None, 'val_adj': None,
'opp': None, 'val_post': None}
return d
week_no = self.week_numbers[week]
stats_week = self.qb_stats.copy()
stats_week = stats_week[stats_week.Week.eq(week_no)]
stats_week = stats_week[stats_week.Pos.eq('QB')]
qbs = list(set(stats_week.Player))
qbs2 = [qb for team, qb in self.qbs_tostart[week].items()]
qbs = qbs + list(set(qbs2))
for qb in qbs:
if qb not in self.qb_vals:
self.qb_vals[qb] = create_qb_dict()
self.qb_vals[qb][week]['val_pre'] = 30.0
def calculate_qb_val(self, stats):
'''
Implement quarterback game value calculation through subclass
Values stored in python dictionary with the following keys:
'passing_att' 'passing_cmp' 'passing_yds'
'passing_td' 'passing_int' 'passing_sk'
'rushing_att' 'rushing_yds' 'rushing_td'
'fumbles_fmb'
Default value returns 50
'''
return 50
def __load_raw_qb_vals(self, week):
for qb in self.qb_vals.keys():
if qb in self.active_qbs:
stats, opp = self.get_qb_stats_raw(week, qb=qb)
if stats is not None:
val = self.calculate_qb_val(stats)
self.qb_vals[qb][week]['val_game'] = val
self.qb_vals[qb][week]['opp'] = opp
for team in self.qb_vals_team.keys():
stats_for, opp = self.get_qb_stats_raw(week, for_team=team)
stats_against, opp = self.get_qb_stats_raw(week, against_team=team)
if stats_for is not None:
val_for = self.calculate_qb_val(stats_for)
val_against = self.calculate_qb_val(stats_against)
self.qb_vals_team[team][week]['valF_game'] = val_for
self.qb_vals_team[team][week]['valA_game'] = val_against
self.qb_vals_team[team][week]['opp'] = opp
def __calculate_avg_qbteam_val(self, week, F_or_A='for'):
week_no = self.week_numbers[week]
if F_or_A.lower() not in ['for', 'against']:
raise ValueError('F_or_A must be "for" or "against"')
if F_or_A.lower()=='for':
valtype = 'valF_pre'
elif F_or_A.lower()=='against':
valtype = 'valA_pre'
valsum = 0
denom = 0
for team, stats in self.qb_vals_team.items():
if stats[week][valtype] is not None:
valsum += stats[week][valtype]
denom += 1
if denom > 0:
return valsum/denom
else:
return np.nan
def __update_rolling_qbteam_vals(self, week):
week_no = self.week_numbers[week]
next_week = self.__get_week_from_no(week_no + 1)
playoffs = ['Division', 'ConfChamp', 'SuperBowl']
for team, stats in self.qb_vals_team.items():
if stats[week]['valF_game'] is None and week not in playoffs:
old_val_for = self.__get_most_recent_qbteam_val_pre(team, week, F_or_A='for')
old_val_ag = self.__get_most_recent_qbteam_val_pre(team, week, F_or_A='against')
self.qb_vals_team[team][week]['valF_post'] = old_val_for
self.qb_vals_team[team][week]['valA_post'] = old_val_ag
self.qb_vals_team[team][next_week]['valF_pre'] = old_val_for
self.qb_vals_team[team][next_week]['valA_pre'] = old_val_ag
elif stats[week]['valF_game'] is not None:
old_val_for = self.__get_most_recent_qbteam_val_pre(team, week, F_or_A='for')
val_for = stats[week]['valF_game']
new_val_for = (0.9 * old_val_for) + (0.1 * val_for)
new_val_for = np.clip(new_val_for, 0, 100)
self.qb_vals_team[team][week]['valF_post'] = new_val_for
old_val_ag = self.__get_most_recent_qbteam_val_pre(team, week, F_or_A='against')
val_ag = stats[week]['valA_game']
new_val_ag = (0.9 * old_val_ag) + (0.1 * val_ag)
new_val_ag = np.clip(new_val_ag, 0, 100)
self.qb_vals_team[team][week]['valA_post'] = new_val_ag
if week != 'SuperBowl':
self.qb_vals_team[team][next_week]['valA_pre'] = new_val_ag
self.qb_vals_team[team][next_week]['valF_pre'] = new_val_for
def __get_most_recent_qb_val_pre(self, qb, week):
stats = self.qb_vals[qb]
stats_aval = {w: vals for w, vals in stats.items() if
vals['val_pre'] is not None}
most_recent_week = max(stats_aval, key=self.week_numbers.get)
week_no = self.week_numbers[week]
most_recent_week_no = self.week_numbers[most_recent_week]
if most_recent_week_no < week_no:
return stats[most_recent_week]['val_pre']
else:
return stats[week]['val_pre']
def __get_most_recent_qbteam_val_pre(self, team, week, F_or_A='for'):
if F_or_A not in ['for', 'against']:
raise ValueError('valtype must be "for" or "against"')
if F_or_A == 'for':
valtype = 'valF_pre'
elif F_or_A == 'against':
valtype = 'valA_pre'
stats = self.qb_vals_team[team]
stats_aval = {w: vals for w, vals in stats.items() if
vals[valtype] is not None}
most_recent_week = max(stats_aval, key=self.week_numbers.get)
week_no = self.week_numbers[week]
most_recent_week_no = self.week_numbers[most_recent_week]
if most_recent_week_no < week_no:
return stats[most_recent_week][valtype]
else:
return stats[week][valtype]
def __update_qb_val_post(self, week):
week_no = self.week_numbers[week]
next_week = self.__get_week_from_no(week_no + 1)
playoffs = ['Division', 'ConfChamp', 'SuperBowl']
for qb, stats in self.qb_vals.items():
if stats[week]['val_game'] is None and week not in playoffs:
old_val = self.__get_most_recent_qb_val_pre(qb, week)
self.qb_vals[qb][week]['val_post'] = old_val
self.qb_vals[qb][week]['val_change'] = 0.0
if week != 'SuperBowl':
self.qb_vals[qb][next_week]['val_pre'] = old_val
elif stats[week]['val_game'] is not None:
opp = stats[week]['opp']
opp_valA = self.__get_most_recent_qbteam_val_pre(opp, week, F_or_A='against')
week_avg = self.__calculate_avg_qbteam_val(week, F_or_A='against')
above_valA = opp_valA - week_avg
adj_val = np.clip(stats[week]['val_game'] - above_valA, 0, 100)
old_val = self.__get_most_recent_qb_val_pre(qb, week)
new_val = (0.9 * old_val) + (0.1 * adj_val)
new_val = np.clip(new_val, 0, 100)
diff = new_val - old_val
self.qb_vals[qb][week]['val_adj'] = adj_val
self.qb_vals[qb][week]['val_post'] = new_val
self.qb_vals[qb][week]['val_change'] = diff
if week != 'SuperBowl':
self.qb_vals[qb][next_week]['val_pre'] = new_val
def update_QB_vals(self):
start_time = time.time()
this_week = self.this_week
this_week_no = self.week_numbers[this_week]
weeks_played = [w for w, w_no in self.week_numbers.items() if
w_no <= this_week_no and w != 'w0']
for week in weeks_played:
self.__add_new_qbs(week)
self.__load_raw_qb_vals(week)
self.__update_rolling_qbteam_vals(week)
self.__update_qb_val_post(week)
end_time = time.time()
elapsed_time = round(end_time - start_time, 3)
func_msg = 'Calculating ' + str(self.year) + ' adjusted quarterback values completed: '
sec_msg = str(elapsed_time) + ' sec'
print(func_msg + sec_msg)
def get_hth_record(self, teams):
teams = list(teams)
wins_all = []
for i, team in enumerate(teams):
teams[i] = self.__standardize_team(team)
wins, gp = 0, 0
for game in self.team_records[team].values():
if game['opp'] in teams and game['result'] is not None:
gp += 1
if game['result'] == 'win':
wins += 1
if game['result'] == 'tie':
wins += 0.5
if gp > 0:
wins_all.append(wins/gp)
else:
wins_all.append(np.NaN)
return wins_all
def get_hth_winner(self, teams):
teams = list(teams)
records = self.get_hth_record(teams)
max_wp = max(records)
winners = [team for team, wp in zip(teams, records) if wp >= max_wp]
if len(winners)==1:
return winners[0]
else:
return np.NaN
def look_up_hth(self, teams):
if tuple(teams) in self.head_to_heads.keys():
return self.head_to_heads[tuple(teams)]
else:
teams = (teams[1], teams[0])
return self.head_to_heads[teams]
def get_common_record(self, teams):
if len(teams) < 2:
return [np.nan]
opps_all = []
for team in teams:
team = self.__standardize_team(team)
opps = []
for game in self.team_records[team].values():
if game['result']:
opps.append(game['opp'])
opps_all.append(opps)
opps = list(reduce(lambda x, y: set(x) & set(y), opps_all))
wins_all = []
for team in teams:
team = self.__standardize_team(team)
wins, gp = 0, 0
for game in self.team_records[team].values():
if game['opp'] in opps and game['result'] is not None:
gp +=1
if game['result'] == 'win':
wins += 1
if game['result'] == 'tie':
wins += 0.5
if gp > 0:
wins_all.append(wins/gp)
else:
wins_all.append(np.NaN)
return wins_all
def get_strength_victory(self, team):
team = self.__standardize_team(team)
sov, no_opps = 0, 0
for week, game in self.team_records[team].items():
if game['result'] == 'win':
sov += self.get_record_team(game['opp'])[3]
no_opps += 1
if no_opps < 1:
return 0.0
else:
return sov / no_opps
def get_strength_schedule(self, team):
team = self.__standardize_team(team)
sos, no_opps = 0, 0
for week, game in self.team_records[team].items():
if game['result']:
sos += self.get_record_team(game['opp'])[3]
no_opps += 1
return sos / no_opps
def __calculate_raw_standings(self):
teams = list(self.team_records.keys())
standings = pd.DataFrame(teams)
standings.columns = ['team']
standings = standings.assign(
wp = standings.team.apply(lambda x: self.get_record_team(x)[3]),
wp_conf = standings.team.apply(lambda x: self.get_record_team(x, 'conference')[3]),
wp_div = standings.team.apply(lambda x: self.get_record_team(x, 'division')[3]),
sov = standings.team.apply(lambda x: self.get_strength_victory(x)),
sos = standings.team.apply(lambda x: self.get_strength_schedule(x))
)
standings.set_index('team', inplace=True)
standings.sort_values(by=['wp', 'wp_div', 'wp_conf', 'sov', 'sos'],
ascending=False, inplace=True)
self.__raw_standings = standings
self.head_to_heads = {comb: self.get_hth_winner(comb) for comb in
itertools.combinations(teams, 2)}
def __load_division_standings(self):
#1) Head-to-head win percent
#2) Best won-lost-tied percentage in games played within the division.
#3) Best won-lost-tied percentage in common games.
#4) Best won-lost-tied percentage in games played within the conference.
#5) Strength of victory.
#6) Strength of schedule.
fillna_scalar = lambda x: 0 if pd.isnull(x) else x
all_div_standings = pd.DataFrame()
for division, teams in self.divisions.items():
div_standings = self.__raw_standings[self.__raw_standings.index.isin(teams)].copy()
div_standings.sort_values('wp', inplace=True, ascending=False)
for wp, group in itertools.groupby(div_standings.index.tolist(),
key = lambda x: div_standings.at[x, 'wp']):
current_group = list(group)
hth_wps = self.get_hth_record(current_group)
for team, wp_hth in zip(current_group, hth_wps):
div_standings.at[team, 'wp_hth'] = wp_hth
div_standings.sort_values(['wp', 'wp_hth', 'wp_div'], inplace=True, ascending=False)
for wp, group in itertools.groupby(div_standings.index.tolist(),
key = lambda x: (div_standings.at[x,'wp'],
fillna_scalar(div_standings.at[x,'wp_hth']),
div_standings.at[x,'wp_div'])):
current_group = list(group)
com_wps = self.get_common_record(current_group)
for team, wp_com in zip(current_group, com_wps):
div_standings.at[team, 'wp_com'] = wp_com
conf, div = division.split('-')
div_standings.reset_index(inplace=True)
div_standings = div_standings.assign(conference = conf, division = div)
all_div_standings = all_div_standings.append(div_standings, sort=False)
all_div_standings.set_index(['conference', 'division'], inplace=True)
all_div_standings.sort_values(['conference', 'division', 'wp', 'wp_hth', 'wp_div',
'wp_com', 'wp_conf', 'sov', 'sos'], inplace=True, ascending=False)
self.standings = all_div_standings
def playoff_picture(self):
fillna_scalar = lambda x: 0 if pd.isnull(x) else x
playoffs = {}
for conf in ['NFC', 'AFC']:
# Division Winners
winners = []
for div in ['EAST', 'WEST', 'NORTH', 'SOUTH']:
df = self.standings.copy()
df.reset_index(inplace=True)
df = df[df.conference.eq(conf) & df.division.eq(div)]
winners.append(df.team.tolist()[0])
df = self.standings.copy()
df.reset_index(inplace=True)
df = df[df.conference.eq(conf) & df.team.isin(winners)]
df.set_index('team', inplace=True)
df.sort_values('wp', inplace=True, ascending=False)
for wp, group in itertools.groupby(df.index.tolist(),
key = lambda x: df.at[x, 'wp']):
current_group = list(group)
hth_wps = self.get_hth_record(current_group)
for team, wp_hth in zip(current_group, hth_wps):
df.at[team, 'wp_hth'] = wp_hth
df.sort_values(['wp', 'wp_hth', 'wp_conf'], inplace=True, ascending=False)
for wp, group in itertools.groupby(df.index.tolist(),
key = lambda x: (df.at[x, 'wp'],
fillna_scalar(df.at[x, 'wp_hth']),
df.at[x, 'wp_conf'])):
current_group = list(group)
com_wps = self.get_common_record(current_group)
for team, wp_com in zip(current_group, com_wps):
df.at[team, 'wp_com'] = wp_com
df.sort_values(['wp', 'wp_hth', 'wp_conf', 'wp_com', 'sov', 'sos'],
inplace=True, ascending=False)
conf_playoffs = {}
for place, team in enumerate(df.index.tolist(), start=1):
conf_playoffs[place] = team
# Wild Cards
wc = self.standings.copy()
wc.reset_index(inplace=True)
wc = wc[wc.conference.eq(conf) & ~wc.team.isin(winners)]
wc.set_index('team', inplace=True)
wc.sort_values('wp', inplace=True, ascending=False)
for wp, group in itertools.groupby(wc.index.tolist(),
key = lambda x: wc.at[x, 'wp']):
current_group = list(group)
hth_wps = self.get_hth_record(current_group)
for team, wp_hth in zip(current_group, hth_wps):
wc.at[team, 'wp_hth'] = wp_hth
wc.sort_values(['wp', 'wp_hth', 'wp_conf'], inplace=True, ascending=False)
for wp, group in itertools.groupby(wc.index.tolist(),
key = lambda x: (wc.at[x, 'wp'],
fillna_scalar(wc.at[x, 'wp_hth']),
wc.at[x, 'wp_conf'])):
current_group = list(group)
com_wps = self.get_common_record(current_group)
for team, wp_com in zip(current_group, com_wps):
wc.at[team, 'wp_com_conf'] = wp_com
wc.sort_values(['wp', 'wp_hth', 'wp_div'], inplace=True, ascending=False)
for wp, group in itertools.groupby(wc.index.tolist(),
key = lambda x: (wc.at[x, 'wp'],
fillna_scalar(wc.at[x, 'wp_hth']),
wc.at[x, 'wp_div'])):
current_group = list(group)
com_wps = self.get_common_record(current_group)
for team, wp_com in zip(current_group, com_wps):
wc.at[team, 'wp_com_div'] = wp_com
max_wps = wc.wp.nlargest(2)
winner_1 = wc[wc.wp.eq(max_wps[0])]
winner_2 = wc[wc.wp.eq(max_wps[1])]
if len(winner_1) == 1:
conf_playoffs[5] = winner_1.index[0]
if len(winner_2) == 1:
conf_playoffs[6] = winner_2.index[0]
else:
if winner_2.wp_hth.notna().all():
max_wp_hth = max(winner_2.wp_hth)
winner_2 = winner_2[winner_2.wp_hth.eq(max_wp_hth)]
if len(winner_2) == 1:
conf_playoffs[6] = winner_2.index.tolist()[0]
else:
divs = [self.team_divisions[team] for team in winner_2.index.tolist()]
if len(set(divs)) == 1:
winner_2.sort_values(['wp_div', 'wp_com_div', 'wp_conf', 'sov', 'sos'],
inplace=True, ascending=False)
conf_playoffs[6] = winner_2.index.tolist()[0]
else:
winner_2.sort_values(['wp_conf', 'wp_com_conf', 'sov', 'sos'],
inplace=True, ascending=False)
conf_playoffs[6] = winner_2.index.tolist()[0]
else:
divs = [self.team_divisions[team] for team in winner_2.index.tolist()]
if len(set(divs)) == 1:
winner_2.sort_values(['wp_div', 'wp_com_div', 'wp_conf', 'sov', 'sos'],
inplace=True, ascending=False)
conf_playoffs[6] = winner_2.index.tolist()[0]
else:
winner_2.sort_values(['wp_conf', 'wp_com_conf', 'sov', 'sos'],
inplace=True, ascending=False)
conf_playoffs[6] = winner_2.index.tolist()[0]
else:
if winner_1.wp_hth.notna().all():
max_wp_hth = max(winner_1.wp_hth)
winner_1 = winner_1[winner_1.wp_hth.eq(max_wp_hth)]
if len(winner_1) == 1:
conf_playoffs[6] = winner_1.index.tolist()[0]
else:
divs = [self.team_divisions[team] for team in winner_1.index.tolist()]
if len(set(divs)) == 1:
winner_1.sort_values(['wp_div', 'wp_com_div', 'wp_conf', 'sov', 'sos'],
inplace=True, ascending=False)
conf_playoffs[6] = winner_1.index.tolist()[0]
else:
winner_1.sort_values(['wp_conf', 'wp_com_conf', 'sov', 'sos'],
inplace=True, ascending=False)
conf_playoffs[6] = winner_1.index.tolist()[0]
else:
divs = [self.team_divisions[team] for team in winner_1.index.tolist()]
if len(set(divs)) == 1:
winner_1.sort_values(['wp_div', 'wp_com_div', 'wp_conf', 'sov', 'sos'],
inplace=True, ascending=False)
conf_playoffs[6] = winner_1.index.tolist()[0]
else:
winner_1.sort_values(['wp_conf', 'wp_com_conf', 'sov', 'sos'],
inplace=True, ascending=False)
conf_playoffs[6] = winner_1.index.tolist()[0]
playoffs.update({conf: conf_playoffs})
return playoffs
def __get_most_recent_ELOS(self):
ending_ELOS = {}
for team, stats in self.team_records.items():
stats_aval = {week: stat for week, stat in stats.items() if
stat['elo_post'] is not None}
max_week = max(stats_aval, key=self.week_numbers.get)
elo = stats[max_week]['elo_post']
ending_ELOS.update({team: elo})
return ending_ELOS
def __get_most_recent_QB_vals_post(self):
ending_QB_vals = {}
for qb, stats in self.qb_vals.items():
stats_aval = {w: vals for w, vals in stats.items() if
vals['val_post'] is not None}
max_week = max(stats_aval, key=self.week_numbers.get)
val = stats[max_week]['val_post']
ending_QB_vals.update({qb: val})
return ending_QB_vals
def __get_most_recent_QBteam_vals_post(self):
ending_QBteam_vals = {}
for team, stats in self.qb_vals_team.items():
stats_aval = {w: vals for w, vals in stats.items() if
vals['valF_post'] is not None}
max_week = max(stats_aval, key=self.week_numbers.get)
valF = stats[max_week]['valF_post']
valA = stats[max_week]['valA_post']
ending_QBteam_vals.update({team: (valF, valA)})
return ending_QBteam_vals
def output_ending_values(self):
'''
Output python dictionary of ending predictor values
ELOs, quarterback values, team-passing values
'''
elos = self.__get_most_recent_ELOS()
qb_vals = self.__get_most_recent_QB_vals_post()
qb_vals_team = self.__get_most_recent_QBteam_vals_post()
return elos, qb_vals, qb_vals_team
def ELO_rankings(self):
elos = self.output_ending_values()[0]
elos = pd.DataFrame.from_dict(elos, orient='index').\
sort_values(0, ascending=False,).reset_index()
elos.index = elos.index + 1
elos.columns = ['team', 'ELO']
return elos
def qb_val_rankings(self):
qb_vals = self.output_ending_values()[1]
qb_vals = {qb: val for qb, val in qb_vals.items() if
qb in self.active_qbs}
qb_vals = pd.DataFrame.from_dict(qb_vals, orient='index').\
sort_values(0, ascending=False,).reset_index()
qb_vals.index = qb_vals.index + 1
qb_vals.columns = ['qb', 'value']
return qb_vals
def qb_vals_toDataFrame(self):
'''Output pandas dataframe of quarterback values through season'''
QB_VALS_DF = pd.DataFrame()
year = self.year
for qb, stats in self.qb_vals.items():
df = pd.DataFrame.from_dict(stats, orient='index')
df.dropna(subset=['val_post'], inplace=True)
df = df.assign(qb = qb, season = year)
QB_VALS_DF = QB_VALS_DF.append(df)
return QB_VALS_DF
def qbteam_vals_toDataFrame(self):
'''Output pandas dataframe of team-quarterback values through season'''
QBTEAM_VALS_DF = pd.DataFrame()
year = self.year
for team, stats in self.qb_vals_team.items():
df = pd.DataFrame.from_dict(stats, orient='index')
df.dropna(subset=['valF_post'], inplace=True)
df = df.assign(team = team, season = year)
QBTEAM_VALS_DF = QBTEAM_VALS_DF.append(df)
return QBTEAM_VALS_DF
def ELOS_toDataFrame(self):
'''Output pandas dataframe of ELO values through season'''
ELOS_DF = pd.DataFrame()
year = self.year
for team, stats in self.team_records.items():
df = pd.DataFrame.from_dict(stats, orient='index')
df = df.assign(team = team, season = year)
ELOS_DF = ELOS_DF.append(df)
return ELOS_DF
def plot_ELOS(self, team):
team = self.__standardize_team(team)
elos = {week: stats['elo_pre'] for week, stats in
self.team_records[team].items() if
stats['elo_pre'] is not None}
elos = pd.DataFrame.from_dict(elos, orient='index').reset_index()
elos.columns = ['week', 'ELO']
# week_order = [w for w in week_order if w in elos.week.tolist()]
# week_order.sort(key=self.week_numers.get)
elos = elos.assign(
# week = elos.week.astype('category').cat.reorder_categories(week_order),
week_no = elos.week.apply(self.week_numbers.get)
)
letters = 'abcdefghijklmnopqrstuv'
alpha = {i: a for i, a in zip(range(1,23), letters)}
elos = elos.assign(
week_alpha = elos.week_no.apply(alpha.get)
)
if self.prediction_results is not None:
sqfd = self.prediction_results.copy()
sqfd = sqfd[sqfd.away.eq(team) | sqfd.home.eq(team)]
sqfd = sqfd[['week', 'sqfd']]
elos = elos.merge(sqfd, how='left', on='week')
else:
elos = elos.assign(sqfd = 0.0)
sns.set_style('whitegrid')
sns.set_context('talk')
# plot = sns.catplot(x=elos.week,
# y=elos.ELO,
# color=self.team_colors.get(team),
# kind='point'
# )
plot = sns.lineplot(elos.week_alpha, elos.ELO,
color=self.team_colors.get(team)
)
plot.scatter(elos.week_alpha, elos.ELO,
color=self.team_colors.get(team),
s=(elos.sqfd*50)**2
)
labels = elos.week.tolist()
labels.sort(key=self.week_numbers.get)
plot.set_title(self.team_names[team][2] + ' ELO rating by week')
plot.set_xticklabels(labels)
plot.set_xlabel('')
for item in plot.get_xticklabels():
item.set_rotation(90)
return plot
def plot_ELOS_all(self, save=None):
DF = pd.DataFrame()
for team, record in self.team_records.items():
df = pd.DataFrame.from_dict(record, orient='index')
df = df.assign(team = team)
df.dropna(subset=['elo_pre'], inplace=True)
DF = DF.append(df)
DF.reset_index(inplace=True)
DF.rename(columns ={'index':'week'}, inplace=True)
wk_order = [w for w in self.week_numbers.keys() if w in set(DF.week)]
DF = DF.assign(week = DF.week.astype('category').cat.reorder_categories(wk_order))
get_conf = lambda x: self.team_divisions[x].split('-')[0]
get_div = lambda x: self.team_divisions[x].split('-')[1]
DF = DF.assign(
division = DF.team.apply(get_div),
conference = DF.team.apply(get_conf)
)
plot = sns.catplot(x='week', y='elo_pre', hue='team',
palette=self.team_colors.values(),
col='division', row='conference',
data=DF, kind='point', markers='.', s=0.5)
plot.set_titles('{row_name} {col_name}')
plot.set_axis_labels('', 'ELO')
plot._legend.set_title('Team')
plt.gcf().subplots_adjust(bottom=0.1)
for ax in plot.axes.flat:
for label in ax.get_xticklabels():
label.set_rotation(90)
if save is not None:
plt.savefig('/Users/graemepm/Desktop/' + save + '.jpeg', dpi=900)
return plot
def plot_QB_val(self, qb):
vals = {week: (stats['val_pre'], stats['val_adj']) for week, stats in
self.qb_vals[qb].items() if stats['val_adj'] is not None}
vals = pd.DataFrame.from_dict(vals, orient='index').reset_index()
vals.columns = ['week', 'Value_Pre', 'Value_Game']
vals = vals.assign(
week_no = vals.week.apply(self.week_numbers.get)
)
letters = 'abcdefghijklmnopqrstuv'
alpha = {i: a for i, a in zip(range(1,23), letters)}
vals = vals.assign(
week_alpha = vals.week_no.apply(alpha.get)
)
sns.set_style('whitegrid')
sns.set_context('talk')
plot = sns.lineplot(vals.week_alpha, vals.Value_Pre, color='black')
plot.scatter(vals.week_alpha, vals.Value_Game,
c=vals.Value_Game, cmap='bwr')
labels = vals.week.tolist()
labels.sort(key=self.week_numbers.get)
plot.set_title(qb + ' QB value by week')
plot.set_xticklabels(labels)
plot.set_xlabel('')
plot.set_ylabel('')
plot.set_ylim(-5,105)
for item in plot.get_xticklabels():
item.set_rotation(90)
return plot
| [
"[email protected]"
] | |
b064fd0346014a6a9e350d214078bc034a747cce | 3795588dc26d25c695dfde89a95eb5e2e7e245ae | /crmsystem/models.py | 59f4acb838f9d3284c9ed60a2515ee2bae31f804 | [] | no_license | Pranathi6309/casestudydjangoapi | 77d7a2e279c45dc9300104290464a1207a4fb6ad | f948aab567cd0e2c7184ce0a4c55cb019b03de9d | refs/heads/master | 2020-07-31T09:48:32.686547 | 2019-09-28T09:30:48 | 2019-09-28T09:30:48 | 210,565,473 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 914 | py | from django.db import models
from mongoengine import Document, EmbeddedDocument, fields
class projects(EmbeddedDocument):
projectId = fields.StringField(max_length=10, required=True, null=False)
projectName = fields.StringField(max_length=255, required=False)
startDate = fields.DateTimeField()
endDate = fields.DateTimeField()
class skills(EmbeddedDocument):
technology = fields.StringField(max_length=10, required=True, null=False)
experience = fields.IntField()
level = fields.StringField(max_length=255, required=False)
class Employee(Document):
employeeId = fields.StringField(max_length=10, required=True, null=False)
employeeName = fields.StringField(max_length=100, required=True)
workLocation = fields.StringField(max_length=100, required=True)
skills = fields.EmbeddedDocumentListField(skills)
projects= fields.EmbeddedDocumentListField(projects) | [
"[email protected]"
] | |
b0afccc9e5bfc2b26db6cd01d9db8aef6f4962b3 | 3d917a056ecd30de1b4f0c26966d24170f6614fc | /app/main/controller/project_controller.py | 7a565eb4961e555236a843f5df0a780616f543df | [] | no_license | ptrickd/flask-postgres-server | fd217c731ad51640df2d0e911cb8f692d331b02f | 28efedf8373174eeb7f404e3ce7e0cd861778fb1 | refs/heads/main | 2023-04-20T16:33:00.827007 | 2021-05-03T22:10:38 | 2021-05-03T22:10:38 | 353,814,381 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,521 | py | from flask import Flask, request
from flask_restful import Resource, reqparse, abort, fields, marshal_with
from sqlalchemy import or_
from sqlalchemy.sql.expression import null
import werkzeug
import json
# from app.main import app
from app.main import db
from app.main.model.project import ProjectModel
from app.main.model.team_member_name import TeamMemberNameModel
from app.main.model.language import LanguageModel
from app.main.model.framework import FrameworkModel
from app.main.model.database import DatabaseModel
from app.main.model.extra_tools import ExtraToolsModel
from app.main.model.user import token_required
from app.main.util.upload import upload_file
resource_fields = {
'_id': fields.Integer(attribute='id'),
'cohort_num': fields.String,
'project_num': fields.String,
'project_name': fields.String,
'team_name': fields.String,
'description': fields.String,
'repository': fields.String,
'website': fields.String,
'name_team_member': fields.List(fields.String(attribute='name')),
'language': fields.List(fields.String(attribute='name')),
'framework': fields.List(fields.String(attribute='name')),
'database':fields.List(fields.String(attribute='name')),
'extra_tools':fields.List(fields.String(attribute='name')),
'old_filename':fields.String,
}
post_args = reqparse.RequestParser()
post_args.add_argument("_id",type=int, help="Id of the project")
post_args.add_argument("cohort_num", type=str, help="Cohort of the project")
post_args.add_argument("project_num", type=str, help="Project number of the project")
post_args.add_argument("project_name", type=str, help="Name of the project")
post_args.add_argument("team_name", type=str, help="Name of the team")
post_args.add_argument("description", type=str, help="Description of the project")
post_args.add_argument("repository", type=str, help="Repository of the project")
post_args.add_argument("website", type=str, help="Website of the project")
post_args.add_argument("name_team_member", action='append', help="Names of the team")
post_args.add_argument("language", action='append', help="Languages list of the projects")
post_args.add_argument("framework", action='append', help="Frameworks of the project")
post_args.add_argument("database", action='append', help="Databases of the project")
post_args.add_argument("extra_tools", action='append', help="Extra tools of the project")
post_args.add_argument("name", type=str, help="Name of the image")
# From file uploads
post_args.add_argument('image', type=werkzeug.datastructures.FileStorage, location='files')
# From the request headers
post_args.add_argument('x-access-token', location='headers')
class Project(Resource):
@marshal_with(resource_fields)
def get(self, project_id):
print('project id ::::', project_id)
project = ProjectModel.query.filter_by(id=project_id).first()
print('prject with id', project)
if not project:
abort(401, message="This project has not been found")
return project
class Projects(Resource):
@marshal_with(resource_fields)
def get(self):
#parsing from url query
args = request.args
filter_data = {}
ids = []
parsed_args = args.to_dict(flat=False)
filter_data['cohort_num'] = parsed_args['cohort'][0]
filter_data['project_num'] = parsed_args['projectnum'][0]
name_team_member_id = TeamMemberNameModel\
.query.with_entities(TeamMemberNameModel.project_id)\
.filter_by(name=parsed_args['name'][0])\
.all()
for id in name_team_member_id:
ids.append(id[0])
if 'languages' in parsed_args:
languages = []
for language in parsed_args['languages']:
languages.append(language)
language_ids = LanguageModel\
.query.with_entities(LanguageModel.project_id)\
.filter(LanguageModel.name.in_(languages))\
.all()
for id in language_ids:
ids.append(id[0])
if 'frontend' in parsed_args:
frameworks = []
for framework in frameworks:
frameworks.append(framework)
framework_ids = FrameworkModel\
.query.with_entities(FrameworkModel.project_id)\
.filter(FrameworkModel.name.in_(frameworks))\
.all()
for id in framework_ids:
ids.append(id[0])
if 'backend' in parsed_args:
databases = []
for database in databases:
ids.append(id[0])
database_ids = DatabaseModel\
.query.with_entities(DatabaseModel.project_id)\
.filter(DatabaseModel.name.in_(databases))\
.all()
for id in database_ids:
ids.append(id[0])
# print(unique_ids)
filter_data = {key: value for (key, value) in filter_data.items() if value}
project_ids = ProjectModel\
.query\
.with_entities(ProjectModel.id)\
.filter_by(**filter_data)\
.all()
for id in project_ids:
ids.append(id[0])
unique_ids = set(ids)
projects = ProjectModel\
.query\
.filter(ProjectModel.id.in_(ids))\
.all()
return projects, 200
@token_required
@marshal_with(resource_fields)
def post(self, current_user):
args = post_args.parse_args()
new_filename = ''
if args['image']:
new_filename = upload_file(args['image'])
project = ProjectModel(\
id = args['_id'],\
cohort_num = args['cohort_num'],\
project_num = args['project_num'],\
project_name = args['project_name'],\
team_name = args['team_name'],\
description = args['description'],\
repository = args['repository'],\
website = args['website'],\
old_filename = args['image'].filename,\
new_filename = new_filename\
)
db.session.add(project)
db.session.commit()
for name in args['name_team_member']:
names = TeamMemberNameModel(\
id = args['_id'],
name = name,
project_id = project.id
)
db.session.add(names)
db.session.commit()
for item in args['language']:
languages = LanguageModel(\
id = args['_id'],
project_id = project.id,
name = item
)
db.session.add(languages)
db.session.commit()
for item in args['framework']:
frameworks = FrameworkModel(\
id = args['_id'],
project_id = project.id,
name = item
)
db.session.add(frameworks)
db.session.commit()
for item in args['database']:
databases = DatabaseModel(\
id = args['_id'],
project_id = project.id,
name = item
)
db.session.add(databases)
db.session.commit()
for item in args['extra_tools']:
extra_tools = ExtraToolsModel(\
id = args['_id'],
project_id = project.id,
name = item
)
db.session.add(extra_tools)
db.session.commit()
return project, 200
@token_required
@marshal_with(resource_fields)
def put(self, current_user):
args = post_args.parse_args()
new_filename = ''
if args['image']:
new_filename = upload_file(args['image'])
project = ProjectModel(\
id = args['_id'],\
cohort_num = args['cohort_num'],\
project_num = args['project_num'],\
project_name = args['project_name'],\
team_name = args['team_name'],\
description = args['description'],\
repository = args['repository'],\
website = args['website'],\
old_filename = args['image'].filename,\
new_filename = new_filename\
)
db.session.add(project)
db.session.commit()
return project, 200 | [
"[email protected]"
] | |
8eb2f2f5434f5679880e3262874f6f3ded82e049 | 2fd2a89f2c651df1b02224278370daae9c5ae1fa | /basic/decorator.py | 17872ab52368b18559983509cc3fff61535bf13c | [] | no_license | shuaijunchen/Python3 | a6af44c03d9ff8e4727b42ff6d485602b9a1cfc9 | d57e12e2e1d7d3b4312969cc1f3ecbcd725488d2 | refs/heads/master | 2021-05-16T08:00:51.655246 | 2018-07-07T05:06:00 | 2018-07-07T05:06:00 | 100,726,961 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 365 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import functools
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
@log('execute')
def now():
print('2017-09-25')
now()
| [
"[email protected]"
] | |
d5d88c04f3002a7f940367da2475e95e17685520 | 5dc9959825ce41c65777e9dc1c30147a8443300e | /tutorial/spiders/quotes.py | 1c1f56e57d2d273ca56496ba7c126651a71a2fc0 | [] | no_license | ShirleyQueen/ScrapyTutorial | 7a3220b93d0a1e9465fb754dc06c2425f05d3ba8 | 88d87d454087ca69d30621a724a303c59f5762fd | refs/heads/master | 2020-03-28T03:17:37.661801 | 2018-09-06T07:33:57 | 2018-09-06T07:33:57 | 147,630,718 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 764 | py | # -*- coding: utf-8 -*-
import scrapy
from tutorial.items import TutorialItem
class QuotesSpider(scrapy.Spider):
name = 'quotes'
allowed_domains = ['quotes.toscrape.com']
start_urls = ['http://quotes.toscrape.com/']
def parse(self, response):
qutoes = response.css('.quote')
for qutoe in qutoes:
item = TutorialItem()
item['text'] = qutoe.css('.text::text').extract_first()
item['author'] = qutoe.css('.author::text').extract_first()
item['tags'] = qutoe.css('.tags .tag::text').extract()
yield item
next=response.css('.pager .next a::attr("href")').extract_first()
url=response.urljoin(next)
yield scrapy.Request(url=url,callback=self.parse)
| [
"[email protected]"
] | |
33375c4404abd484a28dc9d39e154deb2f05038b | eab1756b01717e81537133400f36aea4d7a0876f | /delete_placement_groups.py | 91a4aae2e9f0ea0bc65a052f324828626961c88c | [] | no_license | bearpelican/cluster | d677fe392ac1196b77e3f8fb79e530ec8371080f | 2e316cf1def0b72b47f79a864ed3aa778c297b95 | refs/heads/master | 2020-03-21T06:52:57.514901 | 2018-08-10T10:20:26 | 2018-08-10T22:33:05 | 138,246,892 | 3 | 1 | null | 2018-06-22T02:51:07 | 2018-06-22T02:51:07 | null | UTF-8 | Python | false | false | 1,773 | py | #!/usr/bin/env python
# delete all placement groups
import boto3
# {'PlacementGroups': [{'GroupName': 'gpu12',
# 'State': 'available',
# 'Strategy': 'cluster'},
# {'GroupName': 'gpu6', 'State': 'available', 'Strategy': 'cluster'},
# {'GroupName': 'gpu10', 'State': 'available', 'Strategy': 'cluster'},
# {'GroupName': 'gpu4', 'State': 'available', 'Strategy': 'cluster'},
# {'GroupName': 'cnn2', 'State': 'available', 'Strategy': 'cluster'},
# {'GroupName': 'gpu5', 'State': 'available', 'Strategy': 'cluster'},
# {'GroupName': 'gpu3', 'State': 'available', 'Strategy': 'cluster'},
# {'GroupName': 'tf', 'State': 'available', 'Strategy': 'cluster'},
# {'GroupName': 'gpu7', 'State': 'available', 'Strategy': 'cluster'},
# {'GroupName': 'gpu11', 'State': 'available', 'Strategy': 'cluster'},
# {'GroupName': 'gpu8', 'State': 'available', 'Strategy': 'cluster'},
# {'GroupName': 'gpu9', 'State': 'available', 'Strategy': 'cluster'},
# {'GroupName': 'cnn', 'State': 'available', 'Strategy': 'cluster'}],
# 'ResponseMetadata': {'HTTPHeaders': {'content-type': 'text/xml;charset=UTF-8',
# 'date': 'Tue, 28 Nov 2017 18:52:18 GMT',
# 'server': 'AmazonEC2',
# 'transfer-encoding': 'chunked',
# 'vary': 'Accept-Encoding'},
# 'HTTPStatusCode': 200,
# 'RequestId': '3d7adfe7-1109-413d-9aab-2f0aeafef968',
# 'RetryAttempts': 0}}
import boto3
ec2 = boto3.client('ec2')
result=ec2.describe_placement_groups()
#print(result)
for entry in result["PlacementGroups"]:
name = entry.get('GroupName', '---')
try:
print("Deleting "+name)
response = ec2.delete_placement_group(GroupName=name)
print("Response was %d" %(response['ResponseMetadata']['HTTPStatusCode']))
except Exception as e:
print("Failed with %s"%(e,))
| [
"[email protected]"
] | |
749217ba6f1f6556101e743957e954080c6956dc | 5c6ae056393c9fc4fd2b354a07df6c47eea37c48 | /tests_sample_test.py | a2fa20dec440a1b11b5aaf8c570c21659aff8566 | [] | no_license | copyleftdev/action-dojo-pytest | 8b07e8ff987b0dca8129805a9c49751f4fa43197 | fd59d9f11bc23c35d40c076718e20ef46739778b | refs/heads/main | 2023-07-11T14:40:05.721588 | 2021-08-22T18:48:13 | 2021-08-22T18:48:13 | 398,386,827 | 1 | 0 | null | 2021-08-22T18:48:14 | 2021-08-20T19:56:58 | null | UTF-8 | Python | false | false | 75 | py | import pytest
def test_add():
a = 10
b = 20
assert a+b == 30 | [
"[email protected]"
] | |
5489f686c505c4dcbc1504a7cdd87d9326971d74 | 8a5a619f95887b7bddc8a945a03b86a81f0eef5d | /menu_pages_scraping/revTotal.py | 8cb49eeebb94c39d9ed3d603e94a2678cc8990b5 | [] | no_license | mnatalka/Table4Us | 63aa943f6c2f733f07b1ca112f9dfb96b2468a9c | 79f5805426f7f23cc4e00de5149fe1f4893854bd | refs/heads/master | 2020-03-30T02:52:42.609956 | 2015-02-25T13:37:42 | 2015-02-25T13:37:42 | 30,254,225 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,238 | py | import sys
import csv
import re
import requests
import json
import math
from bs4 import BeautifulSoup
#spoof header so they appear to be coming from a browser rather than a bot
headers = { "user-agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36",
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"accept-encoding": "gzip,deflate,sdch",
"accept-language": "en-US,en;q=0.8,pl;q=0.6",
}
#dynamically build the URL to be making a request to
#offset is taken manually, by examining the total review count
offset = 0
i = 1
reviews2 = []
with open('restaurantURLs.csv', 'r', newline='') as f:
reader = csv.reader(f)
for item in reader:
print('in ' + str(i))
url = item[0] + '/reviews/0'
offset = 0
r = requests.get(url,headers=headers)
# convert the plaintext HTML markup into a DOM-like structure that can be searched
soup = BeautifulSoup(r.content)
print(item)
max_offset = soup.find('div', class_='review_total').string #.strip(' reviews')
#max_offset = math.ceil((int(max_offset)-10)/15)*15
print(max_offset)
break
| [
"[email protected]"
] | |
e628750064eaadf4f0e74e76f86a59bc9153118a | 34a09981dec4d059f789520fed91e35dcc56fecb | /pages/urls.py | a789cccda3b7bf5d096e797802a7da2ba107b580 | [] | no_license | fk-winner/carzone-git | 03ce214d16d5f59e8f8577b0bcee84b08b10428c | e370db7136354ab153abb44fc3bf5b15611da924 | refs/heads/master | 2023-04-04T20:38:38.593285 | 2021-04-06T10:00:08 | 2021-04-06T10:00:08 | 352,025,752 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 260 | py |
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('about', views.about, name='about'),
path('services', views.services, name='service'),
path('contact', views.contact, name='contact'),
] | [
"[email protected]"
] | |
48ba1d5f9ad1894ce0c50d212e63e181a3a592e0 | 128d593efd591dc83a3aef2d4bfad39e73ee637e | /python_code/too_slow/no068 | 16fee3ebdf0da6c9232526b9db6cfa41e34ee9ef | [] | no_license | jwan/ProjectEuler | 93be87d89cc58516d503dd5ed53bdbd706748cda | 65aec4f87b8899db6bad94a36412a28a4b4527e9 | refs/heads/master | 2021-01-17T08:21:46.654529 | 2011-05-02T23:11:35 | 2011-05-02T23:11:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,331 | #!/usr/bin/env python
# a0
# a1
# a2
# a3 a4
# a5
# a6 a7 a8
# a9
# In clockwise order, chains are
# (a0, a2, a4)
# (a1, a4, a7)
# (a8, a7, a6)
# (a9, a6, a3)
# (a5, a3, a2)
from python_code.decorators import euler_timer
from python_code.functions import all_permutations
def magic_5_gon(perm):
node_indices = [0, 1, 8, 9, 5]
triples = {0: [0, 2, 4],
1: [1, 4, 7],
8: [8, 7, 6],
9: [9, 6, 3],
5: [5, 3, 2]}
node_values = [perm[ind] for ind in node_indices]
start = node_values.index(min(node_values))
ordered_nodes = node_indices[start:] + node_indices[:start]
result = []
for node in ordered_nodes:
curr_ind = triples[node]
result.append([perm[ind] for ind in curr_ind])
return result
@euler_timer(68)
def main():
result = []
perms = all_permutations(range(1,11))
for perm in perms:
magic = magic_5_gon(perm)
sums = [sum(triple) for triple in magic]
if len(set(sums)) == 1:
to_add = "".join(["".join([str(ind) for ind in triple])
for triple in magic])
result.append(to_add)
print max([int(concat) for concat in result if len(concat) == 16])
if __name__ == "__main__":
main()
| [
"[email protected]"
] | ||
4dc32d0c6c6b2b8fda0d981e5c9a94b11e9aa434 | 95767c1e942bfd2317ee054456114ebbe79504ba | /v26.py | b234189d62b4a0a5338efd554e915001f25c5af1 | [] | no_license | daiyeyue/spider | 18bfe067fb2c165ce6680afcaa81a7f3294745e0 | a644de5280591b6148da0333a2764db6d8234441 | refs/heads/master | 2020-08-17T16:51:17.795115 | 2019-12-11T09:53:44 | 2019-12-11T09:53:44 | 215,689,309 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 290 | py | '''
findall案例
'''
import re
pattern = re.compile(r'\d+')
s = pattern.findall("i am 18 years odl and 185 high")
print(s)
print(type(s))
for i in range(0,len(s)):
print(s[i])
s = pattern.finditer("i am 18 years odl and 185 high")
print(type(s))
for i in s:
print(i.group())
| [
"[email protected]"
] | |
e29ef4412b50fbe121445d5211425dc1706fbad8 | 9994a95e09ed1be281774b19e216fb450712af72 | /query_careportal.py | e06c77dd2ad89abb56082e4a7de5d7473179a7ce | [] | no_license | dkaygithub/care_portal | f0edb065564006b7005c481242db4dcbfb1e0daf | 8ed4cd706f1d95a8f3352ada82e3dae85547c9c2 | refs/heads/master | 2020-08-02T17:42:50.115171 | 2019-09-28T05:44:21 | 2019-09-28T05:44:21 | 211,450,879 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,665 | py | import requests
import redis
class UnexpectedDataFormat(Exception):
pass
class DataSource():
def __init__(self):
self._r = redis.Redis(host='localhost', port=6379, db=0)
def get_test_text_blob(self):
return """
Single mother, age 25, is in need of a mattress for her 6 year old daughter. Mother has sheets, pillows and a frame for a queen size bed however she had to get rid of the mattress and cannot financially afford a new mattress. The 6 year old daughter has her own room but has to sleep on the couch, with her brother or with her mother every night.
Children: 6 year old female, 4 year old male
"""
def _query_cp(self, case_id):
if not isinstance(id, int):
raise UnexpectedDataFormat("id must be an int")
print("woah, acuatlly querying: {}".format(case_id))
return "queried {}".format(case_id)
r = requests.get('https://system.careportal.org/api/map/request-details?id={case_id}'.format(case_id=case_id))
return r.json()
def get_case_desc(self, case_json):
dsc_key = 'case_description'
if dsc_key not in case_json.keys():
raise UnexpectedDataFormat('No case case_description found.')
return case_json[dsc_key]
def get_case_by_id(self, id):
if not isinstance(id, int):
raise UnexpectedDataFormat("id must be an int")
v = self._r.get(id)
if v:
return v
fresh = self._query_cp(id)
self._r.set(id, fresh)
def ListAllCases(self):
print('listing all cases')
for i in range(2):
print('\tlisting case '+str(i))
yield self.get_case_by_id(i)
def shutdown(self):
self._r.shutdown(save=True)
r = redis.Redis(host='localhost', port=16379, db=0)
r.set('a','b')
r.set('b','c')
print(r.get('a')) | [
"[email protected]"
] | |
45a7c7aafd20a7a3e40e45f4a0ad15a4ad827ce7 | 8da9355b0d9d1b3c8f789f3d28e5e8a26231359c | /FindAngle.py | a7987a7b35d04e67a63b674d25c71bbaa15e2dda | [] | no_license | anshi-gupta/udemy-python | b4c06c38b6a5ad15d700096ebf01d933a5ed4f6b | 8207e89ef3a550965c0b6066c1d096ab27955224 | refs/heads/master | 2022-12-11T07:37:19.564750 | 2020-09-03T17:39:53 | 2020-09-03T17:39:53 | 271,995,530 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 359 | py | ## Given a right angled triangle ABC.
## M is the mid-point of hypothenus,AC.
## INPUT - The other two sides of the triangle ABC, AB and BC.
## OUTPUT - Angle MBC
import math
AB = int(input())
BC = int(input())
AC = math.hypot(AB, BC)
MC = AC / 2
MBC = math.acos(0.5 * BC/MC)
result = math.degrees(MBC)
print(round(result), end = u'\N{DEGREE SIGN}')
| [
"[email protected]"
] | |
8f5e58e91fc324e0f41b0111b14cd986a341d83c | 14341032e732da1364ba3bfef71bd03852033e65 | /theWall/forms.py | 0476eed64ae3e432eb36a9d5291bf2ba4a601ce2 | [] | no_license | VargasDevelopment/WallOfSecrets | 8ed8f5b02a72d857fb969b2229a6a9dfbd1dc93b | ff181f677bc4d881aafc97267e1a236c5b23e0bd | refs/heads/master | 2021-08-29T10:20:20.363876 | 2017-12-13T17:13:06 | 2017-12-13T17:13:06 | 111,593,153 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,219 | py | from django import forms
from theWall.models import Post
'''
Class: PostForm
Description:
this is a django specific class. It is used to create the structure of a web form. It has built in restrictions
for length and such. This particular form is for the user to post their message to the site. it integrates with the
post model.
'''
class PostForm(forms.ModelForm):
key = forms.CharField(widget=forms.TextInput(attrs={'style' : 'color:black'}), required=True, max_length=140, help_text="Key")
content = forms.CharField(widget=forms.TextInput(attrs={'style' : 'color:black'}), help_text="Post Content: ")
class Meta:
model = Post
fields = ('key', 'content',)
'''
Class: KeyForm
Description:
this is a django specific class. It is used to create the structure of a web form. It has built in restrictions
for length and such. This particular form does not interact with the database. It is used to take user input of a "key"
so that they can see if their key decrypts any message.
'''
class KeyForm(forms.Form):
key = forms.CharField(widget=forms.TextInput(attrs={'style' : 'color:black'}), required=True, max_length=140, help_text="Key")
class Meta:
fields = ('key',) | [
"[email protected]"
] | |
0892d9bab185899dcb03871b351d68cabb417b2f | 1d065a530eb33a4910c4d0a5daed195a07fbc016 | /program.py | 95b2bbd3e0a4c9a180dfbe2243a7bce6fe6d0325 | [] | no_license | Gavin-McQuaid/distinct_powers | a3cd4ec314876021495058650198a4d5614ef694 | 949da17ba7d575d6400df9327b8a7be942944f5a | refs/heads/master | 2021-01-13T13:15:09.569199 | 2016-11-02T20:42:02 | 2016-11-02T20:42:02 | 72,679,410 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 139 | py | terms = []
a = 2
while a <= 100:
b = 2
while b<=100:
if a ** b not in terms:
terms.append(a**b)
b += 1
a += 1
print len(terms)
| [
"[email protected]"
] | |
d1f021aed0da004a08fc23bf7bdf1e623de53b8b | 60e201a4fa5ffd376f3228194312a9439c4ddbf7 | /fizzbuz.py | e50901a89d7848e235966ce1b0cb219b768b23b5 | [] | no_license | W0lvRine007/python-prog | 955ae52f607f0200925e4cccefd370aad6010d53 | 8bc6f27e4fb8f0b6208ddb9a22232bcc213c705f | refs/heads/master | 2023-09-04T22:12:58.658453 | 2021-11-08T11:41:02 | 2021-11-08T11:41:02 | 425,803,473 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 236 | py | series = 0
for num in range(1, 101) :
if num % 3 == 0 and num % 5 == 0 :
print("FizzBuzz")
elif num % 3 == 0:
print("Fizz")
elif num % 5 == 0 :
print("Buzz")
else:
print(num)
print(num)
| [
"[email protected]"
] | |
cd8e5beecbad13a32c6f29cd3358bdceda58b63c | 97b47b7f5bbafdac51979c17cddb56bd14a75153 | /week02/course_code/exception.py | 79cd7bf9d488c7c20cba0ffe265976c7eae90e7c | [] | no_license | shmilyvidian/Python001-class01 | e11f5db5f64976f573d9a7733d637ddf28675103 | 7a40fada0fbb8f4a860c0d7d5fa96db68a10b818 | refs/heads/master | 2022-12-07T22:49:18.728598 | 2020-08-28T03:27:01 | 2020-08-28T03:27:01 | 272,919,545 | 0 | 0 | null | 2020-06-17T08:28:27 | 2020-06-17T08:28:27 | null | UTF-8 | Python | false | false | 281 | py | import pretty_errors
def a():
return b()
def b():
return c()
def c():
return d()
def d():
x = 0
return 100/x
try:
a()
except Exception as e:
try:
1/0
except Exception as f:
print(f'f{f}')
print(f'e{e}')
print('-----')
| [
"[email protected]"
] | |
ff20a5d5d335d86f94ecc89c9539f6ed52fa51f6 | 13c74b781a36fb45da43c4a4d4644330be2c6d5c | /APS0/enlaceRx.py | 89fd4bf3a09f0d5eeef6d6537d5bb029b0d4e284 | [] | no_license | CEDipEngineering/DataTransmission | d07bc50188b73be239221c42875abcd523770c57 | af0926c7b58ba1351e07555cf54fe065ae985643 | refs/heads/master | 2022-12-23T09:05:16.361784 | 2020-10-01T18:18:41 | 2020-10-01T18:18:41 | 291,329,086 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,873 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#####################################################
# Camada Física da Computação
#Carareto
#17/02/2018
# Camada de Enlace
####################################################
# Importa pacote de tempo
import time
# Threads
import threading
# Class
class RX(object):
def __init__(self, fisica):
self.fisica = fisica
self.buffer = bytes(bytearray())
self.threadStop = False
self.threadMutex = True
self.READLEN = 1024
def thread(self):
while not self.threadStop:
if(self.threadMutex == True):
rxTemp, nRx = self.fisica.read(self.READLEN)
if (nRx > 0):
self.buffer += rxTemp
time.sleep(0.01)
def threadStart(self):
self.thread = threading.Thread(target=self.thread, args=())
self.thread.start()
def threadKill(self):
self.threadStop = True
def threadPause(self):
self.threadMutex = False
def threadResume(self):
self.threadMutex = True
def getIsEmpty(self):
if(self.getBufferLen() == 0):
return(True)
else:
return(False)
def getBufferLen(self):
return(len(self.buffer))
def getAllBuffer(self, len):
self.threadPause()
b = self.buffer[:]
self.clearBuffer()
self.threadResume()
return(b)
def getBuffer(self, nData):
self.threadPause()
b = self.buffer[0:nData]
self.buffer = self.buffer[nData:]
self.threadResume()
return(b)
def getNData(self, size):
while(self.getBufferLen() < size):
time.sleep(0.05)
return(self.getBuffer(size))
def clearBuffer(self):
self.buffer = b""
| [
"[email protected]"
] | |
791eb993af56cf5aec4afabde7268016b06c5b20 | 235ce20a1a4af284d69c887df87bf975baf26b45 | /random.py | 10f3b3352f926f1c3f2442a5c37f4a0f68213826 | [] | no_license | raviputtar/pycharm_repo | e890815bce40bfde17673419d4c82fa319bf035a | ed23ee2a23100b9dfbafaf285e03c9a66c63fea7 | refs/heads/master | 2021-08-08T23:44:38.462758 | 2020-04-22T14:16:41 | 2020-04-22T14:16:41 | 162,283,071 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 236 | py | def myfunct(a,b,c):
if c=="sum":
return(a+b)
elif c=="mul":
if a < 0 or b < 0:
raise ValueError("a or b should be greater than 0")
else:
return(a*b)
else:
return(a-b)
| [
"[email protected]"
] | |
9a0418b89a5bb0098df725447e0ea8b7fad4457d | 2334ce5d9f1a151262ca6822e166ae5074f7e7b8 | /boj_lecture/bf/permutation/boj10971.py | 3aa4b7f435bc2bbc8acc91fd019f987f7e484a30 | [] | no_license | passionCodingTest/Injeong | 6c9330360c7ef11d6dc05b1990db7d5b20bf3443 | b812f19b8733bc64e319ad81ee53edaf5290989f | refs/heads/main | 2023-06-22T16:33:22.509163 | 2021-07-27T12:55:31 | 2021-07-27T12:55:31 | 341,564,573 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 814 | py | import sys
n = int(input())
graph = []
for _ in range(n):
graph.append(list(map(int, input().split())))
min_value = 1e9
def recur(start, index, cost, visited, count):
global min_value
if min_value <= cost:
return
if count+1 == n:
if graph[index][start] != 0:
cost += graph[index][start]
min_value = min(min_value, cost)
return
for j in range(n):
#방문한적이 있으면
if visited[j]:
continue
#연결안됨
if graph[index][j] == 0:
continue
visited[j] = True
recur(start, j, cost + graph[index][j], visited, count+1)
visited[j] = False
for i in range(n):
visited = [False] * n
visited[i] = True
recur(i, i, 0, visited, 0)
print(min_value)
| [
"[email protected]"
] | |
581c1c342c42a3ecf0e961beeb1f303e93af8e5c | 00c3354abfae93bb158eef810281aee94a299437 | /recomments/migrations/0003_auto_20201208_0731.py | f54abe0a9d40c330c56b12324fc769a024f08158 | [] | no_license | supersymmetry-TEAM/FOR_FUCKING_NAVER_SERVER | 569b17ff15371e393f4f52b05d1a75376216f133 | 32ce3dabfb323df51c172f8476f17573666d6d61 | refs/heads/master | 2023-04-09T11:42:22.047813 | 2021-04-21T08:00:14 | 2021-04-21T08:00:14 | 360,077,510 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 379 | py | # Generated by Django 3.1.1 on 2020-12-08 07:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('recomments', '0002_auto_20201208_0715'),
]
operations = [
migrations.RenameField(
model_name='refoodcomment',
old_name='comment',
new_name='foodcomment',
),
]
| [
"[email protected]"
] | |
5678f135a6ae2b4c9c866e1ef468fe49bddb0b1e | e0db43feb3cd9c26d4a471ff403665e235949a0c | /fixture/orm.py | 4d3c3aa90166c49fcde76a8e9b30ac2e51848442 | [
"Apache-2.0"
] | permissive | leg020/python-training | 04dd716399bd74d48eb400b6d1f1722421c9f141 | f595b8b836ff60c68bdff9d881ca50c026762457 | refs/heads/master | 2020-05-15T18:05:13.714162 | 2019-06-28T06:28:34 | 2019-06-28T06:28:34 | 182,416,222 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,585 | py | from pony.orm import *
from datetime import datetime
from model.group import Group
from model.address import Address
from pymysql.converters import decoders
class ORMFixture:
db = Database()
class ORMGroup(db.Entity):
_table_ = 'group_list'
id = PrimaryKey(int, column='group_id')
name = Optional(str, column='group_name')
header = Optional(str, column='group_header')
footer = Optional(str, column='group_footer')
contacts = Set(lambda: ORMFixture.ORMAddress, table='address_in_groups', column='id', reverse='groups', lazy=True)
class ORMAddress(db.Entity):
_table_ = 'addressbook'
id = PrimaryKey(int, column='id')
firstname = Optional(str, column='firstname')
lastname = Optional(str, column='lastname')
deprecated = Optional(datetime, column='deprecated')
groups = Set(lambda: ORMFixture.ORMGroup, table='address_in_groups', column='group_id', reverse='contacts', lazy=True)
def __init__(self, host, name, user, password):
self.db.bind('mysql', host=host,
database=name,
user=user,
password=password,
autocommit=True)
self.db.generate_mapping()
sql_debug(True)
def convert_groups_to_model(self, groups):
def convert(group):
return Group(id=str(group.id), name=group.name, header=group.header, footer=group.footer)
return list(map(convert, groups))
def convert_address_to_model(self, addresses):
def convert(address):
return Address(id=str(address.id), firstname=address.firstname, lastname=address.lastname)
return list(map(convert, addresses))
@db_session
def get_group_list(self):
return self.convert_groups_to_model(select(g for g in ORMFixture.ORMGroup))
@db_session
def get_address_list(self):
return self.convert_address_to_model(select(c for c in ORMFixture.ORMAddress if c.deprecated is None))
@db_session
def get_contacts_in_group(self, group):
orm_group = list(select(g for g in ORMFixture.ORMGroup if g.id == group.id))[0]
return self.convert_address_to_model(orm_group.contacts)
@db_session
def get_contacts_not_in_group(self, group):
orm_group = list(select(g for g in ORMFixture.ORMGroup if g.id == group.id))[0]
return self.convert_address_to_model(select(c for c in ORMFixture.ORMAddress if c.deprecated is None and orm_group not in c.groups)) | [
"[email protected]"
] | |
e298430c3a51927247f45adfe3c933f198f032c6 | 37ef6aa4f1ced4d64250721ae6dbefac11f0b25b | /lists/models.py | 4b0373f307231fc0d210e6f44f7e3779f63bb226 | [] | no_license | Xiaven/MyPython | e17ce8fd349a2f31dea9550ddf36b9d6d6c3ebe8 | c8e5bf989cc55dd30ab3d6813ab48d0fb40afe18 | refs/heads/master | 2021-05-29T17:30:34.359740 | 2015-10-23T09:09:42 | 2015-10-23T09:09:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 210 | py | from django.db import models
# Create your models here.
class List(models.Model):
pass
class Item(models.Model):
text = models.TextField(default='')
list = models.ForeignKey(List, default=None)
| [
"[email protected]"
] | |
6e77ca48be1d1df21ac1321e5fccc14f63ca2be1 | 6ef49533a149e6d2d08fc2d86af112ce16b05c96 | /users/apps.py | 283b233e9cefe09f2a25975011c52bc2ebd4266a | [] | no_license | neet-lord/mangapoint | 7cdb260696289ce69817c9d7d58d9b8f084297fd | bfc993320d4c8b548194c5f9fcbc0cd16966a71d | refs/heads/master | 2021-05-18T18:18:46.386479 | 2021-04-06T15:44:43 | 2021-04-06T15:44:43 | 251,355,709 | 1 | 0 | null | 2020-04-03T11:58:24 | 2020-03-30T15:58:33 | CSS | UTF-8 | Python | false | false | 445 | py | # users/admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import SiteUserCreationForm, SiteUserChangeForm
from .models import SiteUser
class SiteUserAdmin(UserAdmin):
add_form = SiteUserCreationForm
form = SiteUserChangeForm
model = SiteUser
list_display = ['email', 'username',]
admin.site.register(SiteUser, SiteUserAdmin)
| [
"[email protected]"
] | |
efe1d980a6834306b2d79a335a44192d81ab9a81 | b80a187951eafdc90aefc939c5b06c0361fa32ab | /onlineshop/shop/migrations/0004_auto_20180424_1503.py | a67f8700f5955c957ff318308501543a0a72575e | [] | no_license | MindTheGap1/Django-ComicStore | 541d49c3b93959225c4331971477db9b8eeeb862 | 39b9e9de2f846d6e0ac83ccf26bb7261b133d2ac | refs/heads/master | 2020-03-13T01:01:46.581952 | 2019-02-19T14:34:07 | 2019-02-19T14:34:07 | 130,897,127 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 611 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-04-24 14:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0003_auto_20180424_1457'),
]
operations = [
migrations.AlterField(
model_name='publisher',
name='publisher_name',
field=models.CharField(max_length=50),
),
migrations.AlterField(
model_name='publisher',
name='slug',
field=models.SlugField(unique=True),
),
]
| [
"[email protected]"
] | |
514d5365b2f638bbfc687fd0cb97a24fc3aa17e3 | 8cf6545a9006a9c6037b515bb829c97cad1e2a6e | /e89_push_messaging/websockets.py | 4e91248bc2dfd203b36e66cd36d705c1bf4c0ff0 | [] | no_license | estudio89/e89-push-messaging | 5f9d0a448ecb54f749153a158b5a806f6940d806 | 8af82a9b7093ced11eaeee54855e2182e0f63d49 | refs/heads/master | 2021-07-14T02:17:02.160280 | 2021-03-04T21:17:43 | 2021-03-04T21:17:43 | 30,656,749 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 889 | py | from __future__ import unicode_literals
from django.conf import settings
from django.apps import apps
import e89_push_messaging.push_tools
import requests
import json
def send_message_websockets(owners, data_dict = {'type' : 'update'}):
if e89_push_messaging.push_tools.is_id(owners[0]):
OwnerModel = apps.get_model(settings.PUSH_DEVICE_OWNER_MODEL)
owners = OwnerModel.objects.filter(id__in=owners).values_list(settings.PUSH_DEVICE_OWNER_IDENTIFIER, flat=True)
else:
owners = [e89_push_messaging.push_tools.deepgetattr(owner, settings.PUSH_DEVICE_OWNER_IDENTIFIER) for owner in owners]
payload = {
"identifiers": list(owners),
}
payload.update(data_dict)
post_to_server(payload)
def post_to_server(data):
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
url = settings.PUSH_WEBSOCKET_URL
requests.post(url,data=json.dumps(data), headers=headers)
| [
"[email protected]"
] | |
bf48ee24a79d6831b15b183f076b3c08931588b5 | 40ee5a2ad5a8589d6073be4911be71574a43183e | /get_all_links.py | 1c84fcbbea153b4fb74935d56ad59f572f19165c | [] | no_license | Bietola/py-corpus | de24d57fa0c5ab951d24a9fc557ac18a57cc470f | df2a5696fe6ee60d91a5a3c414ff521a4cad6edf | refs/heads/main | 2023-02-25T07:03:30.123264 | 2021-02-07T21:15:01 | 2021-02-07T21:15:44 | 336,890,651 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,487 | py | import fire
from bs4 import BeautifulSoup
import urllib
from urllib.request import Request, urlopen
import re
from operator import iconcat
from itertools import chain
def get_all_links(url):
soup = BeautifulSoup(
urlopen(Request(url)),
'lxml'
)
try:
return list(map(
lambda x: re.sub(r'\s', '+', str(x.get('href'))),
soup.find_all('a')
))
except urllib.error.HTTPError as err:
print(f'{err} [{err.geturl()}]')
def walk_ftp_links(
root_link,
step,
leaves_only = False,
pred = lambda _: True
):
results = []
for link in get_all_links(root_link):
full_link = root_link + link
if link != '/' and not link.startswith('/ftp/') and not link.startswith('?') and link[-1] == '/':
if not leaves_only and pred(full_link):
results.append(step(full_link))
results += walk_ftp_links(full_link, step, leaves_only, pred)
else:
if pred(full_link):
results.append(step(full_link))
return results
def get_all_ly_links(mutopia_homepage='https://www.mutopiaproject.org/ftp/'):
soup = BeautifulSoup(
urlopen(Request(mutopia_homepage))
)
ly_file_links = walk_ftp_links(
leaves_only = True,
pred = lambda lnk: '.ly' in lnk or '-ly' in lnk,
step = print,
root_link = mutopia_homepage
)
def cli():
fire.Fire(get_all_ly_links)
| [
"[email protected]"
] | |
5278a40997403b8fe50fbca202b2cebd559ce593 | a029a45c42e499d137f28f50af248ab033435f46 | /baekjoon/1707.py | 47439876a1c49895a312c5e246070ce10e4b42e5 | [] | no_license | Korimse/Baekjoon_Practice | 561f7670566419d84e9be2642b94218c8487407f | d506aa6957c8a5ffdac5448633bbba015dc58778 | refs/heads/master | 2023-08-13T20:45:20.669848 | 2021-09-21T16:15:45 | 2021-09-21T16:15:45 | 326,729,249 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 873 | py | from collections import deque
import sys
input = sys.stdin.readline
k = int(input())
def bfs(i):
global isTrue
queue = deque()
queue.append(i)
visited[i] = 1
while queue:
v = queue.popleft()
for s in graph[v]:
if visited[s] == 0:
if visited[v] == 1:
visited[s] = -1
queue.append(s)
elif visited[v] == -1:
visited[s] = 1
queue.append(s)
elif visited[v] == visited[s]:
return 1
return 0
for _ in range(k):
n, m = map(int, input().split())
graph = [[] for i in range(n+1)]
for i in range(m):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
visited = [0]*(n+1)
isTrue = True
for i in range(1, n+1):
if visited[i] == 0:
ans = bfs(i)
if ans == 1:
break
if ans == 1:
print("NO")
else:
print("YES") | [
"[email protected]"
] | |
6c3f82cc3fe400d3a571f94c2a6e0ed176ac98f1 | 58f7ce0a511301f0c66f74c02614ffd5c15c8d42 | /loopuntil.py | 74c3cc9cca9601d0833327ec2d8823453ba57474 | [] | no_license | Samson1907/guvitask | 4fb344988c08ab67785d134c3294db5c91a6bf1f | 22c8bf4c5b06cfac5b2361dcae1ef8c261de1a45 | refs/heads/master | 2020-12-22T18:59:01.116130 | 2020-01-29T09:50:13 | 2020-01-29T09:50:13 | 236,899,214 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 68 | py | A=""
while not(A=='Q' or A=='q'):
A=input("Enter a value ")
| [
"[email protected]"
] | |
88bc916493945a5154f7af6cf905769a302cb058 | a6b3aecf6c584a343e77730d6d4ea2c9505c7968 | /RoomManagement/migrations/0011_auto_20190216_2307.py | 20fc6058b3e40b4f172cb3e67a6f6ded98006a9e | [] | no_license | PratibhaShrivastav/IncubatorManagement | 72c45dbda7159104df897f7a3c1f94a9a670c390 | a3bbbfcf06eb6be55b65d50e499fe144e223f48b | refs/heads/master | 2020-04-22T16:40:56.791919 | 2019-02-18T13:50:14 | 2019-02-18T13:50:14 | 170,516,785 | 1 | 1 | null | 2019-02-18T07:28:49 | 2019-02-13T13:56:54 | HTML | UTF-8 | Python | false | false | 1,160 | py | # Generated by Django 2.1.7 on 2019-02-16 23:07
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('RoomManagement', '0010_auto_20190216_2306'),
]
operations = [
migrations.AddField(
model_name='seatrequest',
name='request_from',
field=models.OneToOneField(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='seat_requests_sent', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='seatrequest',
name='request_to',
field=models.OneToOneField(default=2, on_delete=django.db.models.deletion.CASCADE, related_name='seat_requests_received', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='seatrequest',
name='seat',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='logs', to='RoomManagement.Seat'),
),
]
| [
"[email protected]"
] | |
ac0fe8c66366f3b2605755bc6ff7f90266308011 | ea695945f1d1c0a5c5e71dad54f2df0fc2acc1e8 | /flask_blog/routes.py | 7478b153183076e68487a95584b246c60cfd8938 | [] | no_license | gaomingruc/flask_blog | d0856feda3bfe14fc74f0d83f3b6ca7025453895 | f0d321716db05085cdcb366c6276266683a1ec30 | refs/heads/master | 2023-07-02T20:39:49.418037 | 2021-08-03T13:43:47 | 2021-08-03T13:43:47 | 388,085,589 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,763 | py | import os
import secrets
from PIL import Image
from flask import render_template, flash, url_for, redirect, request, abort
import flask_login
from flask_login.utils import login_required
from flask_blog import app, db, bcrypt
from flask_blog.forms import LoginForm, RegistrationForm, UpdateAccountForm, PostForm
from flask_blog.models import User, Post
from flask_login import login_user, current_user, logout_user, login_required
@app.route('/base')
def base():
"""基模版"""
return render_template("base.html")
@app.route('/')
@app.route('/index')
def index():
"""主页"""
page = request.args.get("page", 1, type=int)
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=3)
return render_template("index.html", posts=posts)
@app.route('/about')
def about():
"""关于"""
return render_template("about.html", title="关于")
@app.route('/login', methods=["GET", "POST"])
def login():
"""登陆"""
if current_user.is_authenticated:
return redirect(url_for("index"))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
next_page = request.args.get("next")
flash("%s的账户登陆成功" % form.email.data, "success")
return redirect(next_page) if next_page else redirect(url_for("index"))
else:
flash("登陆失败,请检查用户名和密码", "warning")
return render_template("login.html", title="登陆", form=form)
@app.route('/register', methods=["GET", "POST"])
def register():
"""注册"""
if current_user.is_authenticated:
return redirect(url_for("index"))
form = RegistrationForm()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.password.data).decode("utf-8")
user = User(username=form.username.data, email=form.email.data, password=hashed_password)
db.session.add(user)
db.session.commit()
flash("%s的账户创建成功,请登陆" % form.username.data, "success")
return redirect(url_for("login"))
return render_template("register.html", title="注册", form=form)
@app.route("/logout")
def logout():
"""登出"""
logout_user()
return redirect(url_for("index"))
def save_picture(form_picture):
random_hex = secrets.token_hex(8)
_, file_ext = os.path.splitext(form_picture.filename)
picture_fn = random_hex + file_ext
picture_path = os.path.join(app.root_path, "static/profile_pics", picture_fn)
output_size = (125, 125)
i = Image.open(form_picture)
i.thumbnail(output_size)
i.save(picture_path)
return picture_fn
@app.route("/account", methods=["GET", "POST"])
@login_required
def account():
"""账户"""
form = UpdateAccountForm()
if form.validate_on_submit():
user = User.query.filter_by(username=current_user.username).first()
user.username = form.username.data
user.email = form.email.data
if form.picture.data:
picture_file = save_picture(form.picture.data)
user.image_file = picture_file
db.session.commit()
flash("您的用户信息已更新", "success")
return redirect(url_for("account"))
elif request.method == "GET":
form.username.data = current_user.username
form.email.data = current_user.email
image_file = url_for("static", filename="profile_pics/%s" % current_user.image_file)
return render_template("account.html", title="账户", image_file=image_file, form=form)
@app.route("/post/new", methods=["GET", "POST"])
@login_required
def new_post():
form = PostForm()
if form.validate_on_submit():
post = Post(title=form.title.data, content=form.content.data, author=current_user)
db.session.add(post)
db.session.commit()
flash("新博客发布了", "success")
return redirect(url_for("index"))
return render_template("create_post.html", title="New Post", form=form)
@app.route("/post/<int:post_id>")
def post(post_id):
post = Post.query.get_or_404(post_id)
return render_template("post.html", title=post.title, post=post)
@app.route("/post/<int:post_id>/update", methods=["GET", "POST"])
@login_required
def update_post(post_id):
post = Post.query.get_or_404(post_id)
if post.author != current_user:
abort(403)
form = PostForm()
if form.validate_on_submit():
post.title = form.title.data
post.content = form.content.data
db.session.commit()
flash("您的博客已修改", "success")
return redirect(url_for("post", post_id=post.id))
elif request.method == "GET":
form.title.data = post.title
form.content.data = post.content
return render_template("update_post.html", title="Update Post", form=form, post=post)
@app.route("/post/<int:post_id>/delete")
def delete_post(post_id):
post = Post.query.get_or_404(post_id)
if post.author != current_user:
abort(403)
db.session.delete(post)
db.session.commit()
flash("您的博客已删除", "success")
return redirect(url_for("index"))
@app.route('/user/<string:username>')
def user_post(username):
"""博主的主页"""
page = request.args.get("page", 1, type=int)
user = User.query.filter_by(username=username).first_or_404()
posts = Post.query\
.filter_by(author=user)\
.order_by(Post.date_posted.desc())\
.paginate(page=page, per_page=3)
return render_template("user_posts.html", posts=posts, user=user) | [
"[email protected]"
] | |
feacf3805c44b105604a8ea1cc63023fc31b7fc9 | d5214b1331c9dae59d95ba5b3aa3e9f449ad6695 | /quintagroup.ploneformgen.readonlystringfield/tags/0.2/quintagroup/ploneformgen/readonlystringfield/widget.py | 00302377141fb1b5999d689ea55c52d3fe8b96c9 | [] | 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 | 573 | py | from Products.Archetypes.Widget import StringWidget
from Products.Archetypes.Registry import registerWidget
class ReadonlyStringWidget(StringWidget):
_properties = StringWidget._properties.copy()
_properties.update({
'macro' : "readonlystring",
})
registerWidget(ReadonlyStringWidget,
title='ReadonlyString',
description=('Renders a HTML readonly text input box which '
'accepts a single line of text'),
used_for=('Products.Archetypes.Field.StringField',)
)
| [
"piv@4df3d6c7-0a05-0410-9bee-ae8b7a76f946"
] | piv@4df3d6c7-0a05-0410-9bee-ae8b7a76f946 |
58092b9643add9f053d684e9c3d3b666accf1586 | 625ff91e8d6b4cdce9c60f76e693d32b761bfa16 | /example-config/scripts/localStation.for_training.py | 4b11d7726101a7a58597a0f2b03d01837e6a7909 | [] | no_license | openGDA/gda-core | 21296e4106d71d6ad8c0d4174a53890ea5d9ad42 | c6450c22d2094f40ca3015547c60fbf644173a4c | refs/heads/master | 2023-08-22T15:05:40.149955 | 2023-08-22T10:06:42 | 2023-08-22T10:06:42 | 121,757,680 | 4 | 3 | null | null | null | null | UTF-8 | Python | false | false | 1,617 | py | print "Performing beamline specific initialisation code"
from gdascripts.pd.dummy_pds import DummyPD
from gdascripts.pd.dummy_pds import MultiInputExtraFieldsDummyPD
#from gdascripts.pd.dummy_pds import ZeroInputExtraFieldsDummyPD
from gdascripts.pd.time_pds import showtimeClass
from gdascripts.pd.time_pds import showincrementaltimeClass
from gdascripts.pd.time_pds import waittimeClass
from gdascripts.scannable.timerelated import t, dt, w, clock #@UnusedImport
from gdascripts.scannable.timerelated import TimeOfDay #@UnusedImport
from gdascripts.scan.installStandardScansWithProcessing import * #@UnusedWildImport
scan_processor.rootNamespaceDict=globals()
print "Creating dummy devices x,y and z"
x=DummyPD("x")
y=DummyPD("y")
z=DummyPD("z")
print "Creating timer devices t, dt, and w"
t = showtimeClass("t") # cannot also be driven.
dt= showincrementaltimeClass("dt")
w = waittimeClass("w")
print "Creating multi input/extra field device, mi, me and mie"
mi=MultiInputExtraFieldsDummyPD('mi',['i1','i2'],[])
me=MultiInputExtraFieldsDummyPD('me',[],['e1','e2'])
mie=MultiInputExtraFieldsDummyPD('mie',['i1'],['e2','e3'])
#print "Createing zero input/extra field device, zie"
#zie=ZeroInputExtraFieldsDummyPD('zie')
# Course specific
from simpleDummyScannable import VerboseDummyScannable
xx = VerboseDummyScannable('xx')
yy = VerboseDummyScannable('yy')
zz = VerboseDummyScannable('zz')
from scannableClasses import ScannableGaussian
sg = ScannableGaussian("sg", 0.0)
# python vrml_animator.py sixc.wrl 4567 alpha delta gamma omega chi phi
#execfile('diffcalc/example/startup/sixcircle_dummy.py')
| [
"[email protected]"
] | |
6eaa6f30275cef6561a8ebfb36f1c62e2eb4f955 | 42dd96960a252398db3be1dc0aa9416664cfc7c5 | /water/migrations/0012_auto_20161228_1840.py | ee7f1dfabd1930262b21c043a67fe3e0d4500855 | [] | no_license | 2ncs/thepartners | ef70be73735bd19909c0e93c0d1b27fd612325e8 | fc5bb2e4ddc38c64e9b166af522bd58cd8886850 | refs/heads/master | 2021-01-25T07:07:06.477978 | 2017-02-02T04:39:40 | 2017-02-02T04:39:40 | 80,694,010 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 432 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-28 18:40
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('water', '0011_auto_20161228_1824'),
]
operations = [
migrations.AlterModelOptions(
name='number_of_travelers',
options={'verbose_name': 'Pinakas Timwn'},
),
]
| [
"[email protected]"
] | |
c8a2b443799a24f71a8d5e13898b2a65f36122e2 | 3f742d4ce80f50481df6030304cfa9d7eedce09a | /jumpGame1&2.py | 2f4a07ad515f3795422258f2c92e051d26f1e14b | [] | no_license | guangyi/Algorithm | 12c48206ddb560bd11b7e3f68223ee8cc8f436f0 | 7e747ed1b11a06edc117dd5627ede77409b6a259 | refs/heads/master | 2021-01-10T21:08:15.867142 | 2014-08-26T05:44:44 | 2014-08-26T05:44:44 | 20,144,855 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,558 | py | class Solution:
# @param A, a list of integers
# @return a boolean
def canJump(self, A):
if A == []: return False
if len(A) == 1: return True
result = False
lastPosition = len(A) - 1
for testPosition in range(len(A) - 2, -1, -1):
if A[testPosition] >= lastPosition- testPosition:
result = True
lastPosition = testPosition
else: result = False
return result
# jumpGame 2
def jump(self, A):
if len(A) == 1: return 0
result = 0
prevRange = 0
currRange = 0
for i in range(0, len(A)):
if i + A[i] > currRange:
if i > prevRange:
result += 1
prevRange = currRange
currRange = i + A[i]
if currRange >= len(A) - 1: return result + 1
# jumpGame 2
def jumpDP(self, A):
'''works but not efficient!!! '''
result = [0]
for testPosition in range(1, len(A)):
minStep = 9223372036854775807
for prevPosition in range(0, len(A[:testPosition])):
if A[prevPosition] >= testPosition - prevPosition:
if result[prevPosition] < minStep: minStep = result[prevPosition]
result.append(minStep + 1)
return result[-1]
print Solution().canJump([2,3,1,1,4])
print Solution().canJump([3,2,1,0,4])
print Solution().canJump([0,4])
print Solution().jumpDP([2,3,1,1,4])
print Solution().jump([2,3,1,1,4]) | [
"[email protected]"
] | |
f1ce1dee2a20fd49352ccc7e512fde53dbf34f99 | 93227fd3848ae505a6c10b62fdf8ebcdf0ba0b29 | /addvaluearray.py | d3a03bc8138f7ce1bbebd376492b421b56d056d2 | [] | no_license | noobpython403/noob1 | 949cfde4913b43436a650b7876b971c94db830d9 | c098b92ec376383ba916a8f8045edb4ae26696de | refs/heads/master | 2020-12-14T18:27:07.207123 | 2020-01-22T09:47:10 | 2020-01-22T09:47:10 | 234,839,668 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 392 | py | import array as array
import numpy as np
arr1 = array.array('i', [])
x = int(input('Enter the length of array\t'))
for i in range(x):
x = int(input('Enter the value\t'))
arr1.append(x)
print('The entered array is\t', str(arr1)[10:-1])
y = int(input('Enter the value to be added\t'))
for j in range(x):
arr1[j] = arr1[j] + y
print('The modified array is\t', str(arr1)[10:-1])
| [
"[email protected]"
] | |
09fc2d543241c8646aa21fc97ddc14a55d2bcd6b | 33c818fbbec36728ed19200fd069d3bf1c2dcb37 | /week13-1/lab42/rmon/rmon/app.py | 4d9a48cf76dbbeac4fc5eac5c6f0213ca9838b23 | [] | no_license | myday56/shiyanloutest | 8d69cd77d56d8e9d98df43d84ddefad7176fd4f2 | 3b0dafbe56919e0c4771c7889e0a66660992af23 | refs/heads/master | 2021-03-24T13:57:13.609487 | 2019-05-08T16:21:59 | 2019-05-08T16:21:59 | 118,872,481 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 621 | py | import os
from flask import Flask
from rmon.views import api
from rmon.models import db
from rmon.config import DevConfig,ProductConfig
def create_app():
app = Flask('rmon')
env = os.environ.get('RMON_ENV')
if env in ('pro','prod','product'):
app.config.from_object(ProductConfig)
else:
app.config.from_object(DevConfig)
app.config.from_envvar('RMON_SETTINGS',silent=True)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.register_blueprint(api)
db.init_app(app)
if app.debug:
with app.app_context():
db.create_all()
return app | [
"[email protected]"
] | |
d544b9616da5429c24d2a54e72571196885fbcbf | 288884c9a28cda5c78ccc5dc4e1d3f54f584689d | /__init__.py | 75dcfd3b408436e5fc3135085b866af369542964 | [] | no_license | sharpevo/mplayer_resumer | 9f2bfd6640645226c783606e0a8d193f1e0907d9 | f5673618bc706261d1b18b95cb4281292ae34e3e | refs/heads/master | 2021-01-01T20:35:58.786854 | 2014-09-22T13:04:37 | 2014-09-22T13:04:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 92 | py |
from mplayer_resumer.src.main import Player, History
__all__ = [
Player,
History]
| [
"[email protected]"
] | |
fbe9e116e1b96900fc518493e979891f1cdf33b3 | f6641c552622e1446d913d50f561ff14c524e885 | /base_model.py | 1fa403e26db69d5d5f78ebd8a53b47155706e000 | [] | no_license | yangyi02/video_motion_synthetic3 | 939d1ddd3a4caada87e0e2ef3ed430dae9b2447e | e732d3641c555422b977648211683cb21186bcdb | refs/heads/master | 2021-01-01T06:46:55.553125 | 2017-08-04T00:19:28 | 2017-08-04T00:19:28 | 97,509,008 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,715 | py | import math
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import torch.nn.functional as F
class BaseNet(nn.Module):
def __init__(self, im_height, im_width, im_channel, n_inputs, n_class, m_range, m_kernel):
super(BaseNet, self).__init__()
num_hidden = 64
self.conv0 = nn.Conv2d(n_inputs*im_channel, num_hidden, 3, 1, 1)
self.bn0 = nn.BatchNorm2d(num_hidden)
self.conv1 = nn.Conv2d(num_hidden, num_hidden, 3, 1, 1)
self.bn1 = nn.BatchNorm2d(num_hidden)
self.conv2 = nn.Conv2d(num_hidden, num_hidden, 3, 1, 1)
self.bn2 = nn.BatchNorm2d(num_hidden)
self.conv3 = nn.Conv2d(num_hidden, num_hidden, 3, 1, 1)
self.bn3 = nn.BatchNorm2d(num_hidden)
self.conv4 = nn.Conv2d(num_hidden, num_hidden, 3, 1, 1)
self.bn4 = nn.BatchNorm2d(num_hidden)
self.conv5 = nn.Conv2d(num_hidden, num_hidden, 3, 1, 1)
self.bn5 = nn.BatchNorm2d(num_hidden)
self.conv6 = nn.Conv2d(num_hidden, num_hidden, 3, 1, 1)
self.bn6 = nn.BatchNorm2d(num_hidden)
self.conv7 = nn.Conv2d(num_hidden*2, num_hidden, 3, 1, 1)
self.bn7 = nn.BatchNorm2d(num_hidden)
self.conv8 = nn.Conv2d(num_hidden*2, num_hidden, 3, 1, 1)
self.bn8 = nn.BatchNorm2d(num_hidden)
self.conv9 = nn.Conv2d(num_hidden*2, num_hidden, 3, 1, 1)
self.bn9 = nn.BatchNorm2d(num_hidden)
self.conv10 = nn.Conv2d(num_hidden*2, num_hidden, 3, 1, 1)
self.bn10 = nn.BatchNorm2d(num_hidden)
self.conv11 = nn.Conv2d(num_hidden*2, num_hidden, 3, 1, 1)
self.bn11 = nn.BatchNorm2d(num_hidden)
self.conv = nn.Conv2d(num_hidden, n_class, 3, 1, 1)
self.maxpool = nn.MaxPool2d(2, stride=2, return_indices=False, ceil_mode=False)
self.upsample = nn.UpsamplingBilinear2d(scale_factor=2)
self.im_height = im_height
self.im_width = im_width
self.im_channel = im_channel
self.n_inputs = n_inputs
self.n_class = n_class
self.m_range = m_range
m_kernel = m_kernel.swapaxes(0, 1)
self.m_kernel = Variable(torch.from_numpy(m_kernel).float())
if torch.cuda.is_available():
self.m_kernel = self.m_kernel.cuda()
def forward(self, im_input):
x = self.bn0(self.conv0(im_input))
x1 = F.relu(self.bn1(self.conv1(x)))
x2 = self.maxpool(x1)
x2 = F.relu(self.bn2(self.conv2(x2)))
x3 = self.maxpool(x2)
x3 = F.relu(self.bn3(self.conv3(x3)))
x4 = self.maxpool(x3)
x4 = F.relu(self.bn4(self.conv4(x4)))
x5 = self.maxpool(x4)
x5 = F.relu(self.bn5(self.conv5(x5)))
x6 = self.maxpool(x5)
x6 = F.relu(self.bn6(self.conv6(x6)))
x6 = self.upsample(x6)
x7 = torch.cat((x6, x5), 1)
x7 = F.relu(self.bn7(self.conv7(x7)))
x7 = self.upsample(x7)
x8 = torch.cat((x7, x4), 1)
x8 = F.relu(self.bn8(self.conv8(x8)))
x8 = self.upsample(x8)
x9 = torch.cat((x8, x3), 1)
x9 = F.relu(self.bn9(self.conv9(x9)))
x9 = self.upsample(x9)
x10 = torch.cat((x9, x2), 1)
x10 = F.relu(self.bn10(self.conv10(x10)))
x10 = self.upsample(x10)
x11 = torch.cat((x10, x1), 1)
x11 = F.relu(self.bn11(self.conv11(x11)))
m_mask = F.softmax(self.conv(x11))
out_mask = F.conv2d(m_mask, self.m_kernel, None, 1, self.m_range, 1, self.m_kernel.size(0))
seg = construct_seg(out_mask, self.m_kernel, self.m_range)
appear = F.relu(1 - seg)
disappear = F.relu(seg - 1)
pred = construct_image(im_input[:, -self.im_channel:, :, :], out_mask, disappear, self.m_kernel, self.m_range)
return pred, m_mask, disappear, appear
class BaseGtNet(nn.Module):
def __init__(self, im_height, im_width, im_channel, n_inputs, n_class, m_range, m_kernel):
super(BaseGtNet, self).__init__()
self.im_height = im_height
self.im_width = im_width
self.im_channel = im_channel
self.n_class = n_class
self.m_range = m_range
m_kernel = m_kernel.swapaxes(0, 1)
self.m_kernel = Variable(torch.from_numpy(m_kernel).float())
if torch.cuda.is_available():
self.m_kernel = self.m_kernel.cuda()
def forward(self, im_input, gt_motion):
m_mask = self.motion2mask(gt_motion, self.n_class, self.m_range)
out_mask = F.conv2d(m_mask, self.m_kernel, None, 1, self.m_range, 1, self.m_kernel.size(0))
seg = construct_seg(out_mask, self.m_kernel, self.m_range)
appear = F.relu(1 - seg)
disappear = F.relu(seg - 1)
pred = construct_image(im_input[:, -self.im_channel:, :, :], out_mask, disappear, self.m_kernel, self.m_range)
return pred, m_mask, disappear, appear
def motion2mask(self, motion, n_class, m_range):
m_mask = Variable(torch.Tensor(motion.size(0), n_class, motion.size(2), motion.size(3)))
if torch.cuda.is_available():
m_mask = m_mask.cuda()
motion_floor = torch.floor(motion.cpu().data).long()
for i in range(motion.size(0)):
for j in range(motion.size(2)):
for k in range(motion.size(3)):
a = Variable(torch.zeros(int(math.sqrt(n_class))))
b = Variable(torch.zeros(int(math.sqrt(n_class))))
idx = motion_floor[i, 0, j, k] + m_range
a[idx] = 1 - (motion[i, 0, j, k] - motion_floor[i, 0, j, k])
a[idx + 1] = 1 - a[idx]
idx = motion_floor[i, 1, j, k] + m_range
b[idx] = 1 - (motion[i, 1, j, k] - motion_floor[i, 1, j, k])
b[idx + 1] = 1 - b[idx]
tmp = torch.ger(b, a)
m_mask[i, :, j, k] = tmp.view(-1)
return m_mask
def construct_seg(out_mask, m_kernel, m_range):
seg_expand = Variable(torch.ones(out_mask.size()))
if torch.cuda.is_available():
seg_expand = seg_expand.cuda()
nearby_seg = F.conv2d(seg_expand, m_kernel, None, 1, m_range, 1, m_kernel.size(0))
seg = (nearby_seg * out_mask).sum(1)
return seg
def construct_image(im, out_mask, disappear, m_kernel, m_range):
im = im * (1 - disappear).expand_as(im)
pred = Variable(torch.Tensor(im.size()))
if torch.cuda.is_available():
pred = pred.cuda()
for i in range(im.size(1)):
im_expand = im[:, i, :, :].unsqueeze(1).expand_as(out_mask)
nearby_im = F.conv2d(im_expand, m_kernel, None, 1, m_range, 1, m_kernel.size(0))
pred[:, i, :, :] = (nearby_im * out_mask).sum(1)
return pred
| [
"[email protected]"
] | |
b580ad8db2a386d642351069114b1a743e4e0673 | 5badb035ec0a60527859349314da313392425879 | /testing/scripts/run_gtest_perf_test.py | f2923c483bd62c953bbe3defe08b93e56741d90f | [] | no_license | youminxue/gndemo | c3b1697e78bb6d1fa14675a4657267490138c22e | d3b7d6c7e67a0146fad125da5662fa7821d33453 | refs/heads/master | 2020-03-18T19:32:31.234857 | 2018-06-05T03:47:36 | 2018-06-05T03:47:36 | 135,160,324 | 1 | 2 | null | null | null | null | UTF-8 | Python | false | false | 5,255 | py | #!/usr/bin/env python
# Copyright 2015 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.
"""Runs an isolated non-Telemetry perf test .
The main contract is that the caller passes the arguments:
--isolated-script-test-output=[FILENAME]
json is written to that file in the format produced by
common.parse_common_test_results.
--isolated-script-test-chartjson-output=[FILE]
stdout is written to this file containing chart results for the perf dashboard
Optional argument:
--isolated-script-test-filter=[TEST_NAMES]
is a double-colon-separated ("::") list of test names, to run just that subset
of tests. This list is parsed by this harness and sent down via the
--gtest_filter argument.
This script is intended to be the base command invoked by the isolate,
followed by a subsequent non-python executable. It is modeled after
run_gpu_integration_test_as_gtest.py
"""
import argparse
import json
import os
import shutil
import sys
import tempfile
import traceback
import common
def GetChromiumSrcDir():
return os.path.abspath(
os.path.join(os.path.abspath(__file__), '..', '..', '..'))
def GetPerfDir():
return os.path.join(GetChromiumSrcDir(), 'tools', 'perf')
# Add src/tools/perf where generate_legacy_perf_dashboard_json.py lives
sys.path.append(GetPerfDir())
import generate_legacy_perf_dashboard_json
# Add src/testing/ into sys.path for importing xvfb and test_env.
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import xvfb
import test_env
# Unfortunately we need to copy these variables from ../test_env.py.
# Importing it and using its get_sandbox_env breaks test runs on Linux
# (it seems to unset DISPLAY).
CHROME_SANDBOX_ENV = 'CHROME_DEVEL_SANDBOX'
CHROME_SANDBOX_PATH = '/opt/chromium/chrome_sandbox'
def IsWindows():
return sys.platform == 'cygwin' or sys.platform.startswith('win')
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--isolated-script-test-output', type=str,
required=True)
parser.add_argument(
'--isolated-script-test-chartjson-output', type=str,
required=False)
parser.add_argument(
'--isolated-script-test-perf-output', type=str,
required=False)
parser.add_argument(
'--isolated-script-test-filter', type=str, required=False)
parser.add_argument('--xvfb', help='Start xvfb.', action='store_true')
args, rest_args = parser.parse_known_args()
env = os.environ.copy()
# Assume we want to set up the sandbox environment variables all the
# time; doing so is harmless on non-Linux platforms and is needed
# all the time on Linux.
env[CHROME_SANDBOX_ENV] = CHROME_SANDBOX_PATH
rc = 0
try:
executable = rest_args[0]
extra_flags = []
if len(rest_args) > 1:
extra_flags = rest_args[1:]
# These flags are to make sure that test output perf metrics in the log.
if not '--verbose' in extra_flags:
extra_flags.append('--verbose')
if not '--test-launcher-print-test-stdio=always' in extra_flags:
extra_flags.append('--test-launcher-print-test-stdio=always')
if args.isolated_script_test_filter:
filter_list = common.extract_filter_list(
args.isolated_script_test_filter)
extra_flags.append('--gtest_filter=' + ':'.join(filter_list))
if IsWindows():
executable = '.\%s.exe' % executable
else:
executable = './%s' % executable
with common.temporary_file() as tempfile_path:
env['CHROME_HEADLESS'] = '1'
cmd = [executable] + extra_flags
if args.xvfb:
rc = xvfb.run_executable(cmd, env, stdoutfile=tempfile_path)
else:
rc = test_env.run_command_with_output(cmd, env=env,
stdoutfile=tempfile_path)
# Now get the correct json format from the stdout to write to the perf
# results file
results_processor = (
generate_legacy_perf_dashboard_json.LegacyResultsProcessor())
charts = results_processor.GenerateJsonResults(tempfile_path)
# TODO(eakuefner): Make isolated_script_test_perf_output mandatory after
# flipping flag in swarming.
if args.isolated_script_test_perf_output:
filename = args.isolated_script_test_perf_output
else:
filename = args.isolated_script_test_chartjson_output
# Write the returned encoded json to a the charts output file
with open(filename, 'w') as f:
f.write(charts)
except Exception:
traceback.print_exc()
rc = 1
valid = (rc == 0)
failures = [] if valid else ['(entire test suite)']
with open(args.isolated_script_test_output, 'w') as fp:
json.dump({
'valid': valid,
'failures': failures,
}, fp)
return rc
# This is not really a "script test" so does not need to manually add
# any additional compile targets.
def main_compile_targets(args):
json.dump([], args.output)
if __name__ == '__main__':
# Conform minimally to the protocol defined by ScriptTest.
if 'compile_targets' in sys.argv:
funcs = {
'run': None,
'compile_targets': main_compile_targets,
}
sys.exit(common.run_script(sys.argv[1:], funcs))
sys.exit(main())
| [
"[email protected]"
] | |
aa644a0faa6511052d7ad76b16dca0e1c9a8f2b9 | be11f055ded8ca3338163288b691c589a3ec07b3 | /faceRecognition.py | 53bfa0ea409ddadf800856a28fbc778c978392fe | [] | no_license | Nursefa-Elias/Project | 50c70e08c104585ba99c91a0126756976c818a09 | 13ec18ab5e9925770cc40fd9f6de5c8c3b68a7f2 | refs/heads/master | 2022-09-09T03:09:41.750795 | 2020-01-06T18:27:49 | 2020-01-06T18:27:49 | 228,553,158 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,532 | py | import cv2
import os
import numpy as np
def faceDetection(test_img):
gray_img=cv2.cvtColor(test_img,cv2.COLOR_BGR2GRAY)
face_haar_cascade=cv2.CascadeClassifier('LOCATE HARR ALGORITHM PATH')
faces=face_haar_cascade.detectMultiScale(gray_img,scaleFactor=1.2,minNeighbors=3)
return faces,gray_img
def labels_for_training_data(directory):
faces=[]
faceID=[]
for path,subdirnames,filenames in os.walk(directory):
for filename in filenames:
if filename.startswith("."):
print("Skipping The System File")
continue
id=os.path.basename(path)
img_path=os.path.join(path,filename)
print("img_path:",img_path)
print("id:",id)
test_img=cv2.imread(img_path)
if test_img is None:
print("Image not loaded properly")
continue
faces_rect,gray_img=faceDetection(test_img)
if len(faces_rect)!=1:
continue #Since image asummtion work only for single image
(x,y,w,h)=faces_rect[0]
roi_gray=gray_img[y:y+w,x:x+h]
faces.append(roi_gray)
faceID.append(int(id))
return faces,faceID
def train_classifier(faces,faceID):
face_recognizer=cv2.face.createLBPHFaceRecognizer()
face_recognizer.train(faces,np.array(faceID))
return face_recognizer
def draw_rect(test_img,face):
(x,y,w,h)=face
cv2.rectangle(test_img,(x,y),(x+w,y+h),(255,0,0),thickness=1)
def put_text(test_img,text,x,y):
cv2.putText(test_img,text,(x,y),cv2.FONT_HERSHEY_DUPLEX,1,(255,0,0),1)
| [
"[email protected]"
] | |
54ba5a28a9b4692239c4d13c910faa451911be4b | 705a5e28d15752cd26cfcf8e7abeab429994b0a1 | /process_farmer_data.py | 5647de26a3bcb76580ab12165e55ca6ce50c703e | [
"MIT"
] | permissive | Abhi001vj/mlops | 4bdcec2b8f3e57406faed0a967a90cad120a6ca4 | 22ac9b861fc43b2d0885e3018997a987e7a4b44b | refs/heads/main | 2023-04-30T14:57:54.229589 | 2021-05-21T06:27:46 | 2021-05-21T06:27:46 | 368,819,108 | 0 | 0 | MIT | 2021-05-21T06:32:34 | 2021-05-19T09:46:33 | Python | UTF-8 | Python | false | false | 898 | py | import pandas as pd
df = pd.read_csv("data_raw.csv")
all_features = df.columns
# Let's drop some features
names = [feat for feat in all_features if "net_name" in feat] # excluded for privacy reasons
useless = ["info_gew","info_resul","interviewtime","id","date"] # features that we expect are uninformative
drop_list = names + useless
# Remove the questionnaire about agricultural practices until I can better understand it
practice_list = ["legum","conc","add","lact","breed","covman","comp","drag","cov","plow","solar","biog","ecodr"]
for feat in all_features:
if any(x in feat for x in practice_list):
drop_list.append(feat)
df = df.drop(columns=drop_list)
# Convert non-numeric features to numeric
non_numeric = list(df.select_dtypes(include=['O']).columns)
for col in non_numeric:
codes,uniques=pd.factorize(df[col])
df[col] = codes
df.to_csv("data_processed.csv") | [
"[email protected]"
] | |
137fb8ba913ac5c15bb699924a122ceeaf4817bd | 10a1647d6ca3922e2f6f9657c52695a0d406a17b | /NYC_Algos/Berserker_Rush/gamelib/game_state.py | 5207e8f3e90b2a730994f6f5ffde76f61fcbe40e | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | apetri/C1GamesStarterKit | ee4dcd039990dd1daa7abae9dc16dfbf760db19f | cf6d6a297c3a6acc81e3c5c1cd31cebafd5cb83c | refs/heads/master | 2020-06-29T02:13:03.995889 | 2019-08-07T01:19:37 | 2019-08-07T01:19:37 | 200,407,908 | 0 | 0 | NOASSERTION | 2019-08-03T18:22:50 | 2019-08-03T18:22:50 | null | UTF-8 | Python | false | false | 16,555 | py | import math
import json
from .navigation import ShortestPathFinder
from .util import send_command, debug_write
from .unit import GameUnit
from .game_map import GameMap
def is_stationary(unit_type):
return unit_type in FIREWALL_TYPES
class GameState:
"""Represents the entire gamestate for a given turn
Provides methods related to resources and unit deployment
Attributes:
* UNIT_TYPE_TO_INDEX (dict): Maps a unit to a corresponding index
* FILTER (str): A constant representing the filter unit
* ENCRYPTOR (str): A constant representing the encryptor unit
* DESTRUCTOR (str): A constant representing the destructor unit
* PING (str): A constant representing the ping unit
* EMP (str): A constant representing the emp unit
* SCRAMBLER (str): A constant representing the scrambler unit
* FIREWALL_TYPES (list): A list of the firewall units
* ARENA_SIZE (int): The size of the arena
* HALF_ARENA (int): Half the size of the arena
* BITS (int): A constant representing the bits resource
* CORES (int): A constant representing the cores resource
* game_map (:obj: GameMap): The current GameMap. To retrieve a list of GameUnits at a location, use game_map[x, y]
* turn_number (int): The current turn number. Starts at 0.
* my_health (int): Your current remaining health
* my_time (int): The time you took to submit your previous turn
* enemy_health (int): Your opponents current remaining health
* enemy_time (int): Your opponents current remaining time
"""
def __init__(self, config, serialized_string):
""" Setup a turns variables using arguments passed
Args:
* config (JSON): A json object containing information about the game
* serialized_string (string): A string containing information about the game state at the start of this turn
"""
self.serialized_string = serialized_string
self.config = config
self.enable_warnings = True
global FILTER, ENCRYPTOR, DESTRUCTOR, PING, EMP, SCRAMBLER, REMOVE, FIREWALL_TYPES, ALL_UNITS, UNIT_TYPE_TO_INDEX
UNIT_TYPE_TO_INDEX = {}
FILTER = config["unitInformation"][0]["shorthand"]
UNIT_TYPE_TO_INDEX[FILTER] = 0
ENCRYPTOR = config["unitInformation"][1]["shorthand"]
UNIT_TYPE_TO_INDEX[ENCRYPTOR] = 1
DESTRUCTOR = config["unitInformation"][2]["shorthand"]
UNIT_TYPE_TO_INDEX[DESTRUCTOR] = 2
PING = config["unitInformation"][3]["shorthand"]
UNIT_TYPE_TO_INDEX[PING] = 3
EMP = config["unitInformation"][4]["shorthand"]
UNIT_TYPE_TO_INDEX[EMP] = 4
SCRAMBLER = config["unitInformation"][5]["shorthand"]
UNIT_TYPE_TO_INDEX[SCRAMBLER] = 5
REMOVE = config["unitInformation"][6]["shorthand"]
UNIT_TYPE_TO_INDEX[REMOVE] = 6
ALL_UNITS = [PING, EMP, SCRAMBLER, FILTER, ENCRYPTOR, DESTRUCTOR]
FIREWALL_TYPES = [FILTER, ENCRYPTOR, DESTRUCTOR]
self.ARENA_SIZE = 28
self.HALF_ARENA = int(self.ARENA_SIZE / 2)
self.BITS = 0
self.CORES = 1
self.game_map = GameMap(self.config)
self._shortest_path_finder = ShortestPathFinder()
self._build_stack = []
self._deploy_stack = []
self._player_resources = [
{'cores': 0, 'bits': 0}, # player 0, which is you
{'cores': 0, 'bits': 0}] # player 1, which is the opponent
self.__parse_state(serialized_string)
def __parse_state(self, state_line):
"""
Fills in map based on the serialized game state so that self.game_map[x,y] is a list of GameUnits at that location.
state_line is the game state as a json string.
"""
state = json.loads(state_line)
turn_info = state["turnInfo"]
self.turn_number = int(turn_info[1])
p1_health, p1_cores, p1_bits, p1_time = map(float, state["p1Stats"][:4])
p2_health, p2_cores, p2_bits, p2_time = map(float, state["p2Stats"][:4])
self.my_health = p1_health
self.my_time = p1_time
self.enemy_health = p2_health
self.enemy_time = p2_time
self._player_resources = [
{'cores': p1_cores, 'bits': p1_bits},
{'cores': p2_cores, 'bits': p2_bits}]
p1units = state["p1Units"]
p2units = state["p2Units"]
self.__create_parsed_units(p1units, 0)
self.__create_parsed_units(p2units, 1)
def __create_parsed_units(self, units, player_number):
"""
Helper function for __parse_state to add units to the map.
"""
typedef = self.config.get("unitInformation")
for i, unit_types in enumerate(units):
for uinfo in unit_types:
unit_type = typedef[i].get("shorthand")
sx, sy, shp = uinfo[:3]
x, y = map(int, [sx, sy])
hp = float(shp)
# This depends on RM always being the last type to be processed
if unit_type == REMOVE:
# Quick fix will deploy engine fix soon
if self.contains_stationary_unit([x,y]):
self.game_map[x,y][0].pending_removal = True
else:
unit = GameUnit(unit_type, self.config, player_number, hp, x, y)
self.game_map[x,y].append(unit)
def __resource_required(self, unit_type):
return self.CORES if is_stationary(unit_type) else self.BITS
def __set_resource(self, resource_type, amount, player_index=0):
"""
Sets the resources for the given player_index and resource_type.
Is automatically called by other provided functions.
"""
if resource_type == self.BITS:
resource_key = 'bits'
elif resource_type == self.CORES:
resource_key = 'cores'
held_resource = self.get_resource(resource_type, player_index)
self._player_resources[player_index][resource_key] = held_resource + amount
def _invalid_player_index(self, index):
self.warn("Invalid player index {} passed, player index should always be 0 (yourself) or 1 (your opponent)".format(index))
def _invalid_unit(self, unit):
self.warn("Invalid unit {}".format(unit))
def submit_turn(self):
"""Submit and end your turn.
Must be called at the end of your turn or the algo will hang.
"""
build_string = json.dumps(self._build_stack)
deploy_string = json.dumps(self._deploy_stack)
send_command(build_string)
send_command(deploy_string)
def get_resource(self, resource_type, player_index = 0):
"""Gets a players resources
Args:
* resource_type: self.CORES or self.BITS
* player_index: The index corresponding to the player whos resources you are querying, 0 for you 1 for the enemy
Returns:
The number of the given resource the given player controls
"""
if not player_index == 1 and not player_index == 0:
self._invalid_player_index(player_index)
return
if not resource_type == self.BITS and not resource_type == self.CORES:
self.warn("Invalid resource_type '{}'. Please use game_state.BITS or game_state.CORES".format(resource_type))
return
if resource_type == self.BITS:
resource_key = 'bits'
elif resource_type == self.CORES:
resource_key = 'cores'
resources = self._player_resources[player_index]
return resources.get(resource_key, None)
def number_affordable(self, unit_type):
"""The number of units of a given type we can afford
Args:
* unit_type: A unit type, PING, FILTER, etc.
Returns:
The number of units affordable of the given unit_type.
"""
if unit_type not in ALL_UNITS:
self._invalid_unit(unit_type)
return
cost = self.type_cost(unit_type)
resource_type = self.__resource_required(unit_type)
player_held = self.get_resource(resource_type)
return math.floor(player_held / cost)
def project_future_bits(self, turns_in_future=1, player_index=0, current_bits=None):
"""Predicts the number of bits we will have on a future turn
Args:
* turns_in_future: The number of turns in the future we want to look forward to predict
* player_index: The player whose bits we are tracking
* current_bits: If we pass a value here, we will use that value instead of the current bits of the given player.
Returns:
The number of bits the given player will have after the given number of turns
"""
if turns_in_future < 1 or turns_in_future > 99:
self.warn("Invalid turns in future used ({}). Turns in future should be between 1 and 99".format(turns_in_future))
if not player_index == 1 and not player_index == 0:
self._invalid_player_index(player_index)
if type(current_bits) == int and current_type_costbits < 0:
self.warn("Invalid current bits ({}). Current bits cannot be negative.".format(current_bits))
bits = self.get_resource(self.BITS, player_index) if not current_bits else current_bits
for increment in range(1, turns_in_future + 1):
current_turn = self.turn_number + increment
bits *= (1 - self.config["resources"]["bitDecayPerRound"])
bits_gained = self.config["resources"]["bitsPerRound"] + (current_turn // self.config["resources"]["turnIntervalForBitSchedule"])
bits += bits_gained
bits = round(bits, 1)
return bits
def type_cost(self, unit_type):
"""Gets the cost of a unit based on its type
Args:
* unit_type: The units type
Returns:
The units cost
"""
if unit_type not in ALL_UNITS:
self._invalid_unit(unit_type)
return
unit_def = self.config["unitInformation"][UNIT_TYPE_TO_INDEX[unit_type]]
return unit_def.get('cost')
def can_spawn(self, unit_type, location, num=1):
"""Check if we can spawn a unit at a location.
To units, we need to be able to afford them, and the location must be
in bounds, unblocked, on our side of the map, not on top of a unit we can't stack with,
and on an edge if the unit is information.
Args:
* unit_type: The type of the unit
* location: The location we want to spawn the unit
* num: The number of units we want to spawn
Returns:
True if we can spawn the unit(s)
"""
if unit_type not in ALL_UNITS:
self._invalid_unit(unit_type)
return
if not self.game_map.in_arena_bounds(location):
if self.enable_warnings:
self.warn("Could not spawn {} at location {}. Location invalid.".format(unit_type, location))
return False
affordable = self.number_affordable(unit_type) >= num
stationary = is_stationary(unit_type)
blocked = self.contains_stationary_unit(location) or (stationary and len(self.game_map[location[0],location[1]]) > 0)
correct_territory = location[1] < self.HALF_ARENA
on_edge = location in (self.game_map.get_edge_locations(self.game_map.BOTTOM_LEFT) + self.game_map.get_edge_locations(self.game_map.BOTTOM_RIGHT))
if self.enable_warnings:
fail_reason = ""
if not affordable:
fail_reason = fail_reason + " Not enough resources."
if blocked:
fail_reason = fail_reason + " Location is blocked."
if not correct_territory:
fail_reason = fail_reason + " Location in enemy territory."
if not (stationary or on_edge):
fail_reason = fail_reason + " Information units must be deployed on the edge."
if len(fail_reason) > 0:
self.warn("Could not spawn {} at location {}.{}".format(unit_type, location, fail_reason))
return (affordable and correct_territory and not blocked and
(stationary or on_edge) and
(not stationary or num == 1))
def attempt_spawn(self, unit_type, locations, num=1):
"""Attempts to spawn new units with the type given in the given locations.
Args:
* unit_type: The type of unit we want to spawn
* locations: A single location or list of locations to spawn units at
* num: The number of units of unit_type to deploy at the given location(s)
Returns:
The number of units successfully spawned
"""
if unit_type not in ALL_UNITS:
self._invalid_unit(unit_type)
return
if num < 1:
self.warn("Attempted to spawn fewer than one units! ({})".format(num))
return
if type(locations[0]) == int:
locations = [locations]
spawned_units = 0
for location in locations:
for i in range(num):
if self.can_spawn(unit_type, location, 1):
x, y = map(int, location)
cost = self.type_cost(unit_type)
resource_type = self.__resource_required(unit_type)
self.__set_resource(resource_type, 0 - cost)
self.game_map.add_unit(unit_type, location, 0)
if is_stationary(unit_type):
self._build_stack.append((unit_type, x, y))
else:
self._deploy_stack.append((unit_type, x, y))
spawned_units += 1
return spawned_units
def attempt_remove(self, locations):
"""Attempts to remove existing friendly firewalls in the given locations.
Args:
* locations: A location or list of locations we want to remove firewalls from
Returns:
The number of firewalls successfully flagged for removal
"""
if type(locations[0]) == int:
locations = [locations]
removed_units = 0
for location in locations:
if location[1] < self.HALF_ARENA and self.contains_stationary_unit(location):
x, y = map(int, location)
self._build_stack.append((REMOVE, x, y))
removed_units += 1
else:
self.warn("Could not remove a unit from {}. Location has no firewall or is enemy territory.".format(location))
return removed_units
def find_path_to_edge(self, start_location, target_edge):
"""Gets the path a unit at a given location would take
Args:
* start_location: The location of a hypothetical unit
* target_edge: The edge the unit wants to reach. game_map.TOP_LEFT, game_map.BOTTOM_RIGHT, etc.
Returns:
A list of locations corresponding to the path the unit would take
to get from it's starting location to the best available end location
"""
if self.contains_stationary_unit(start_location):
self.warn("Attempted to perform pathing from blocked starting location {}".format(start_location))
return
end_points = self.game_map.get_edge_locations(target_edge)
return self._shortest_path_finder.navigate_multiple_endpoints(start_location, end_points, self)
def contains_stationary_unit(self, location):
"""Check if a location is blocked
Args:
* location: The location to check
Returns:
True if there is a stationary unit at the location, False otherwise
"""
x, y = map(int, location)
for unit in self.game_map[x,y]:
if unit.stationary:
return unit
return False
def warn(self, message):
if(self.enable_warnings):
debug_write(message)
def suppress_warnings(self, suppress):
"""Suppress all warnings
Args:
* suppress: If true, disable warnings. If false, enable warnings.
"""
self.enable_warnings = not suppress
self.game_map.enable_warnings = not suppress
| [
"[email protected]"
] | |
05d488ac281d514b6c5752247da245e798281c00 | c7586cda99c1b9853b828ae98aa39314957a4fc1 | /HW05/main.py | 6105cd7b3798e4c77699ea6e9270febe4c3d23e9 | [] | no_license | RenjieWei/Deep-Learning | 60d9a9c7644f8d20166662676c2d5b4a7aa7c12b | 906fd90b2c6f67d73e6b8d79eabeea551ec9a0b8 | refs/heads/master | 2021-08-07T08:58:19.675742 | 2019-01-03T03:21:46 | 2019-01-03T03:21:46 | 148,950,667 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,810 | py | import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
from torch.utils import *
import os
import argparse
import numpy as np
import pickle as pkl
from tripletImageNetDataset import TripletImageNetDataset
from imageNetDataset import ImageNetDataset
parser = argparse.ArgumentParser(description='PyTorch Training')
parser.add_argument('--blue', action='store_true', help='use bluewater')
args = parser.parse_args()
device = 'cuda' if torch.cuda.is_available() else 'cpu'
start_epoch = 0
train_loss_ep = []
train_acc_ep = []
test_acc_ep = []
print('==> Preparing data..')
transform_train = transforms.Compose([
transforms.RandomCrop(64, padding=8),
transforms.RandomHorizontalFlip(),
transforms.Resize(224, interpolation=2),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
transform_test = transforms.Compose([
transforms.Resize(224, interpolation=2),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
model_dir = "model"
n_triplets_per_sample = 1
batch_size = 64
TOP30 = 30
train_root = "./tiny-imagenet-200/train"
test_root = "./tiny-imagenet-200/val"
if args.blue:
train_root = "/projects/training/bauh/tiny-imagenet-200/train"
test_root = "/projects/training/bauh/tiny-imagenet-200/val"
triplet_trainset = TripletImageNetDataset(root=train_root, n_triplets_per_sample=n_triplets_per_sample, transform=transform_train)
triplet_trainloader = torch.utils.data.DataLoader(triplet_trainset, batch_size=batch_size, shuffle=True, num_workers=4)
class_to_idx = triplet_trainset.get_class_to_idx()
print(class_to_idx)
testset = ImageNetDataset(root=test_root, annotations="val_annotations.txt", class_to_idx=class_to_idx, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=2)
print("==> Finished loading data")
net = torchvision.models.resnet101(pretrained=True)
net = net.to(device)
if device == 'cuda':
net = torch.nn.DataParallel(net)
cudnn.benchmark = True
lossFunction = nn.TripletMarginLoss()
optimizer = optim.Adam(net.parameters(), lr=0.001, weight_decay=5e-4)
def train(epoch):
print('\nTraining Epoch: %d' % epoch)
net.train()
train_loss = 0
for batch_idx, (anchor, pos, neg, _, _, _) in enumerate(triplet_trainloader):
anchor, pos, neg = anchor.to(device), pos.to(device), neg.to(device)
optimizer.zero_grad()
out_achnor = net(anchor)
out_pos = net(pos)
out_neg = net(neg)
loss = lossFunction(out_achnor, out_pos, out_neg)
loss.backward()
if epoch > 2:
for group in optimizer.param_groups:
for p in group['params']:
state = optimizer.state[p]
if(state['step']>=1024):
state['step'] = 1000
optimizer.step()
train_loss += loss.item()
print(batch_idx, len(triplet_trainloader), "Loss: %.3f" % (train_loss/(batch_idx+1)))
train_loss_ep.append(train_loss/len(triplet_trainloader))
def get_codebook(epoch):
n_code = n_triplets_per_sample * len(triplet_trainset)
codebook = np.zeros([n_code, 1000])
classbook = np.zeros(n_code)
imagebook = [""] * n_code
net.eval()
with torch.no_grad():
for batch_idx, (img, _, _, pos_class, _, img_path) in enumerate(triplet_trainloader):
img = img.to(device)
out_img = net(img)
codebook[batch_idx*batch_size:(batch_idx+1)*batch_size, :] = out_img
classbook[batch_idx*batch_size:(batch_idx+1)*batch_size] = pos_class
imagebook[batch_idx*batch_size:(batch_idx+1)*batch_size] = img_path
np.savetxt("{}/codebook_{}.np".format(model_dir, epoch), codebook)
np.savetxt("{}/classbook_{}.np".format(model_dir, epoch), classbook)
with open("{}/imagebook_{}.pkl".format(model_dir, epoch), "wb") as fout:
pkl.dump(imagebook, fout)
return codebook, classbook, imagebook
from datetime import datetime
def get_test_acc(epoch, codebook, classbook):
print('\nTesting Epoch: %d' % epoch)
def get_correct(output, target):
top_idx = np.argsort(np.sum(np.abs(codebook-output)**2, axis=1))[:TOP30]
top_prd = classbook[top_idx]
correct = np.sum([top_prd == target])
return correct
overall_correct, overall_total = 0, 0
net.eval()
with torch.no_grad():
for batch_idx, (inputs, targets, _) in enumerate(testloader):
inputs = inputs.to(device)
outputs = net(inputs)
outputs = outputs.cpu().numpy()
targets = targets.cpu().numpy()
print("Finished inference")
correct, total = 0, len(inputs)*TOP30
for i in range(len(outputs)):
correct += get_correct(outputs[i], targets[i])
overall_correct += correct
overall_total += total
print(batch_idx, len(testloader), 'Acc: %.3f (%d/%d)' % (correct/total, correct, total))
print('Overall Acc: %.3f (%d/%d)' % (overall_correct/overall_total, overall_correct, overall_total))
test_acc_ep.append((epoch, overall_correct/overall_total))
test_epoch = [1, 10, 30, 60, 90]
for epoch in range(start_epoch, start_epoch+91):
train(epoch)
if epoch in test_epoch:
torch.save(net.state_dict(), "{}/checkpoint_{}.pth".format(model_dir, epoch))
print("==> getting code")
codebook, classbook, imagebook = get_codebook(epoch)
print("==> finished getting code")
get_test_acc(epoch, codebook, classbook)
print(train_loss_ep)
print(test_acc_ep)
| [
"[email protected]"
] | |
20af6a6869eac42cf2d3986818dac68af1589c26 | 4820b92d4c437721914a8fe5d600ad92c058caf0 | /src/hack_sols/dexTapSol.py | e33ef52e64a6db186668dbc952ed0ba792fdd92b | [] | no_license | MRzNone/SAPIEN-dexterous-bench-env | 1619b335fa78b03eead933c09e292253282f576d | 38e1128874a0f9f843526e45e61ddcae744d635d | refs/heads/master | 2022-12-20T07:39:49.906586 | 2020-10-05T09:04:04 | 2020-10-05T09:04:04 | 261,099,309 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,035 | py | import enum
from sapien.core import Pose
from transforms3d import euler
import numpy as np
from agent import PandaArm, Box
from env.dexEnv import DexEnv, ARM_NAME, BOX_NAME
from hack_sols import DexHackySolution
from sapien_interfaces import Task
from task.dexTapTask import DexTapTask
class Phase(enum.Enum):
rotate_toward_box = -1
move_above_box = 0
tap_down = 1
tap_up = 2
evaluate = 3
done = 4
class DexTapSolution(DexHackySolution):
def __init__(self):
super().__init__()
self.phase = Phase.rotate_toward_box
self.init_control = True
self.tg_pose = None
self.up_right_q = euler.euler2quat(np.pi, 0, 0)
def init(self, env: DexEnv, task: Task):
super().init(env, task)
self.phase = Phase.rotate_toward_box
self.init_control = True
self.tg_pose = None
robot = env.agents[ARM_NAME]
self.prep_drive(robot)
def prep_drive(self, robot):
super().prep_arm_drive(robot)
self.init_control = True
self.tg_pose = None
def before_step(self, env, task):
robot: PandaArm = env.agents[ARM_NAME]
box: Box = env.agents[BOX_NAME]
if self.phase is Phase.rotate_toward_box:
if self.init_control is True:
box2base = robot.observation['poses'][0].inv() * box.observation['pose']
p = box2base.p
theta = np.arctan(p[1] / p[0])
if p[0] < 0 and p[1] < 0:
theta -= np.pi
elif p[0] < 0 and p[1] > 0:
theta += np.pi
self.init_control = False
self.tg_pose = Pose(robot.observation['poses'][0].p, euler.euler2quat(0, 0, theta))
self.drive_to_pose(robot, self.tg_pose, joint_index=1, theta_thresh=1e-4, theta_abs_thresh=1e-5)
if self.drive[robot] is False:
self.phase = Phase.move_above_box
self.prep_drive(robot)
elif self.phase is Phase.move_above_box:
if self.init_control is True:
self.tg_pose = robot.observation['poses'][-1]
self.tg_pose.set_p(box.observation['pose'].p)
self.tg_pose = Pose([0, 0, 0.2 + box.box_size]) * self.tg_pose
self.init_control = False
self.drive_to_pose(robot, self.tg_pose, override=([-1, -2], [0, 0.6], [0, 0]))
if self.drive[robot] is False:
self.phase = Phase.tap_down
self.prep_drive(robot)
elif self.phase is Phase.tap_down:
if self.init_control is True:
self.tg_pose = robot.observation['poses'][-1]
self.tg_pose.set_p(box.observation['pose'].p)
self.tg_pose = Pose([0, 0, 0.1 + box.box_size]) * self.tg_pose
self.init_control = False
self.drive_to_pose(robot, self.tg_pose, override=([-1, -2], [0, 0.6], [0, 0]), max_v=5e-2)
if task.get_trajectory_status()['touched'] is True:
self.phase = Phase.tap_up
self.prep_drive(robot)
elif self.phase is Phase.tap_up:
if self.init_control is True:
self.tg_pose = robot.observation['poses'][-1]
self.tg_pose.set_p(box.observation['pose'].p)
self.tg_pose = Pose([0, 0, 0.2 + box.box_size]) * self.tg_pose
self.init_control = False
self.drive_to_pose(robot, self.tg_pose, override=([-1, -2], [0, 0.6], [0, 0]))
if self.drive[robot] is False:
self.phase = Phase.evaluate
self.prep_drive(robot)
elif self.phase is Phase.evaluate:
print(task.get_trajectory_status())
self.phase = Phase.done
if __name__ == '__main__':
env = DexEnv()
task = DexTapTask()
env.add_task(task)
sol = DexTapSolution()
task.register_slotion(sol)
sol.init(env, task)
while not env.should_quit:
env.step()
| [
"[email protected]"
] | |
31b4a5e0c1dd49a8f66081d6748f580551d702a7 | 172428d6aa567dddf190d2c49d1c868dd9fbc81e | /utils/html_utils.py | 7a85def1e2576afa7d502dac7b5045343229423a | [
"MIT"
] | permissive | Densol92/denton | a7049a93aaee5d9ef46d795cf4d34312fe9da876 | 4842389cd96aa42f32c04dd70e9baa37855470f0 | refs/heads/master | 2020-03-25T21:18:28.875137 | 2018-08-09T17:14:59 | 2018-08-09T17:14:59 | 144,169,806 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,046 | py | from io import TextIOWrapper
from random import randint
from zipfile import ZipFile
import requests
from requests.auth import HTTPBasicAuth
def download_file_from_url(file_url, credentials=None):
local_file_path = 'report_%s_%s' % (randint(100000, 1000000), file_url.split('/')[-1])
local_file_path = local_file_path.replace(' ', '_')
auth = None
if credentials:
auth = HTTPBasicAuth(*credentials)
r = requests.get(file_url, stream=True, auth=auth)
# todo use temp file
with open(local_file_path, 'wb+') as downloaded_storage_file:
downloaded_storage_file.write(r.content)
downloaded_storage_file.flush()
return local_file_path
def extract_file_from_zip(file_path):
report = ZipFile(file_path)
extracted_report_file = report.open(report.namelist()[0], 'r')
# csv dictReader doesn't support default zip encoding so we need to convert it in right format
extracted_report_file = TextIOWrapper(extracted_report_file, encoding='utf_8_sig')
return extracted_report_file
| [
"[email protected]"
] | |
3610dd0bc1f7916d6c185ebc48d433d6e0015bde | d125d84481016fa92cb7384edc7b92ac9a1b06e8 | /myproject/libreria/admin.py | f38de41e8880dc0567a870de9bf76f62fe8951d6 | [] | no_license | JEnriquePS/Poll_tutorial_django | c15680b3c8df8ba472dfa58b5090c5893e6fdd94 | a850123535985b5924740008952fc225b68510ed | refs/heads/master | 2021-01-01T20:35:07.232448 | 2014-08-16T04:06:14 | 2014-08-16T04:06:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 165 | py | from django.contrib import admin
from models import Publisher, Author, Book
admin.site.register(Publisher)
admin.site.register(Author)
admin.site.register(Book)
| [
"[email protected]"
] | |
b02d7064564e7b569a0eac9e509a3da5856679fa | 63928bbe0f65b57c94e12517ba82bd43cf41570b | /source/webapp/views/__init__.py | d0d5999dc23ae2e306ffce8c0be4c86f6e95e616 | [] | no_license | York5/Issue-Tracker-2 | 041c20874d2e7549fc1706a2293bb3a89fb93c52 | 20c080bfe6d48af22bf564a3e943c573210054dc | refs/heads/master | 2022-12-16T08:17:22.107345 | 2019-12-09T10:53:58 | 2019-12-09T10:53:58 | 219,488,695 | 0 | 0 | null | 2022-11-22T04:47:51 | 2019-11-04T11:46:11 | HTML | UTF-8 | Python | false | false | 481 | py | from .issue_views import IndexView, IssueView, IssueCreateView, IssueUpdateView, IssueDeleteView, IssueForProjectCreateView
from .type_views import TypeIndexView, TypeView, TypeCreateView, TypeUpdateView, TypeDeleteView
from .status_views import StatusIndexView, StatusView, StatusCreateView, StatusUpdateView, StatusDeleteView
from .project_views import ProjectIndexView, ProjectView, ProjectCreateView, ProjectUpdateView, ProjectDeleteView
from .team_views import TeamUpdateView
| [
"[email protected]"
] | |
44601a2978b50b5c542de3c2f08dfd75df766a6f | 1f8a82ec1d738dc50d2002e32d06a9827aa4a260 | /pnlscripts/makeRigidMask.py | 504c28c6035f59049d2a0bd405a4d9a8f951ffed | [] | no_license | reckbo/pnlpipe | a4c52d621aa41e90ab6c5b9f28998f720b5b920b | b585fc2980357f74acf33b26fde4e862f1f4ec17 | refs/heads/master | 2021-09-26T16:31:46.532052 | 2017-09-09T19:24:22 | 2017-09-09T19:24:22 | 83,028,976 | 2 | 3 | null | null | null | null | UTF-8 | Python | false | false | 1,495 | py | #!/usr/bin/env python
from __future__ import print_function
from util import logfmt, TemporaryDirectory
import util
from plumbum import local, cli, FG
from util.antspath import antsRegistrationSyN_sh, antsApplyTransforms
import sys
import logging
logger = logging.getLogger()
logging.basicConfig(level=logging.DEBUG, format=logfmt(__file__))
class App(cli.Application):
"""Rigidly align a labelmap (usually a mask)."""
infile = cli.SwitchAttr(['-i','--infile'], cli.ExistingFile, help='structural',mandatory=True)
labelmap = cli.SwitchAttr(['-l','--labelmap'], cli.ExistingFile, help='structural labelmap, usually a mask',mandatory=True)
target = cli.SwitchAttr(['-t','--target'], cli.ExistingFile, help='target image',mandatory=True)
out = cli.SwitchAttr(['-o', '--out'], help='output labelmap', mandatory=True)
def main(self):
with TemporaryDirectory() as tmpdir:
tmpdir = local.path(tmpdir)
pre = tmpdir / 'ants'
rigidxfm = pre + '0GenericAffine.mat'
antsRegistrationSyN_sh['-t', 'r', '-m', self.infile, '-f', self.target, '-o', pre, '-n', 32] & FG
antsApplyTransforms('-d', '3'
,'-i', self.labelmap
,'-t', rigidxfm
,'-r', self.target
,'-o', self.out
,'--interpolation', 'NearestNeighbor')
if __name__ == '__main__':
App.run()
| [
"[email protected]"
] | |
388b58106827d5e413873c9668ddd32ff9493c75 | 97a00f723f5457d4dd3cf0d2474159076f79f5ca | /geotrek/zoning/management/commands/loaddistricts.py | f0f38f15e88c3de601800fccf43f073e9f971924 | [
"BSD-2-Clause"
] | permissive | Cynthia-Borot-PNE/Geotrek-admin | dd720c168ca792af06bb9f7d33c38fe274fb7b80 | abd9ca8569a7e35ef7473f5b52731b1c78668754 | refs/heads/master | 2020-06-03T23:40:53.946379 | 2019-06-04T14:25:11 | 2019-06-04T14:25:11 | 191,779,849 | 0 | 0 | BSD-2-Clause | 2019-06-13T14:35:42 | 2019-06-13T14:35:41 | null | UTF-8 | Python | false | false | 3,479 | py | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from django.contrib.gis.gdal import DataSource, GDALException, OGRIndexError
from geotrek.zoning.models import District
from django.contrib.gis.geos.polygon import Polygon
from django.contrib.gis.geos.collections import MultiPolygon
from django.conf import settings
class Command(BaseCommand):
help = 'Load Districts from a file within the spatial extent\n'
def add_arguments(self, parser):
parser.add_argument('file_path', help="File's path of the districts")
parser.add_argument('--name-attribute', '-n', action='store', dest='name', default='nom',
help="Name of the name's attribute inside the file")
parser.add_argument('--encoding', '-e', action='store', dest='encoding', default='utf-8',
help='File encoding, default utf-8')
parser.add_argument('--srid', '-s', action='store', dest='srid', default=4326, type=int,
help="File's SRID")
parser.add_argument('--intersect', '-i', action='store_true', dest='intersect', default=False,
help="Check features intersect spatial extent and not only within")
def handle(self, *args, **options):
verbosity = options.get('verbosity')
file_path = options.get('file_path')
name_column = options.get('name')
encoding = options.get('encoding')
srid = options.get('srid')
do_intersect = options.get('intersect')
bbox = Polygon.from_bbox(settings.SPATIAL_EXTENT)
bbox.srid = settings.SRID
ds = DataSource(file_path, encoding=encoding)
count_error = 0
for layer in ds:
for feat in layer:
try:
geom = feat.geom.geos
if not isinstance(geom, Polygon) and not isinstance(geom, MultiPolygon):
if verbosity > 0:
self.stdout.write("%s's geometry is not a polygon" % feat.get(name_column))
break
elif isinstance(geom, Polygon):
geom = MultiPolygon(geom)
self.check_srid(srid, geom)
geom.dim = 2
if do_intersect and bbox.intersects(geom) or not do_intersect and geom.within(bbox):
instance, created = District.objects.update_or_create(name=feat.get(name_column),
defaults={'geom': geom})
if verbosity > 0:
self.stdout.write("%s %s" % ('Created' if created else 'Updated', feat.get(name_column)))
except OGRIndexError:
if count_error == 0:
self.stdout.write(
"Name's attribute do not correspond with options\n"
"Please, use --name to fix it.\n"
"Fields in your file are : %s" % ', '.join(feat.fields))
count_error += 1
def check_srid(self, srid, geom):
if not geom.srid:
geom.srid = srid
if geom.srid != settings.SRID:
try:
geom.transform(settings.SRID)
except GDALException:
raise CommandError("SRID is not well configurate, change/add option srid")
| [
"[email protected]"
] | |
b5bae295d3a0646d16e76a7d1304ced474182760 | 3c1fd6cc5214c005b010ecde147ce596fc500464 | /Utility/urls.py | 5a452e3e4b92e433b98b2a7518f279256c1cafdd | [] | no_license | rjking20/currency-convertor | a607fd8a56bacb47fd6201a45b8bfac28cbab704 | 476a95055b2a3fa03938845537c1638ba2df093d | refs/heads/master | 2023-03-10T07:41:11.683455 | 2021-02-18T15:25:28 | 2021-02-18T15:25:28 | 340,009,681 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 170 | py |
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('',include('Curconvertor.urls')),
path('admin/', admin.site.urls),
]
| [
"[email protected]"
] | |
ca4c784e77d9ceb9dfb4705c24768931dd51fe50 | 766ebd84886c9d86a56d95cf529976eb0f7d0b1d | /accounts/forms.py | ab809db03d481865270af4e65a185c8793b10a77 | [] | no_license | EdinburghFreeCodeCamp/todo_list_with_api | ceb654d69d876941d036f594a9abd47c9bf9f44a | 037be49761e8582072228c3d6299f5d3479e46af | refs/heads/master | 2021-01-23T04:09:11.591459 | 2017-05-11T22:35:22 | 2017-05-11T22:35:22 | 86,160,003 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 276 | py | from django import forms
from django.contrib.auth.models import User
class EditUserForm(forms.ModelForm):
class Meta:
model = User
exclude = ["password", "user_permissions", "groups", "last_login", "is_superuser", "user_permissions", "is_staff", "date_joined"]
| [
"[email protected]"
] | |
8d09e15c59f85008ef777e555e895a491c05ed49 | cbf1d90a16a46f7072005652177be788deb552c5 | /fluent_comments/templatetags/fluent_comments_tags.py | 8251ea8eff37b3148008f30c8ab6e36cfe9c8f2c | [
"Apache-2.0"
] | permissive | rchrd2/django-fluent-comments | a4181703ccb7ed7192068de160b8e47239e3d5f0 | f799247d2ce311691e9033f613f1fac8cbf288bb | refs/heads/master | 2021-01-18T10:55:26.929178 | 2015-01-28T01:06:11 | 2015-01-28T01:06:11 | 10,698,795 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,993 | py | from django.conf import settings
from django.template import Library
from django.core import context_processors
from django.template.loader import get_template
from fluent_comments import appsettings
from fluent_comments.models import get_comments_for_model
from fluent_comments.moderation import comments_are_open, comments_are_moderated
register = Library()
@register.inclusion_tag("fluent_comments/templatetags/ajax_comment_tags.html", takes_context=True)
def ajax_comment_tags(context):
"""
Display the required ``<div>`` elements to let the Ajax comment functionality work with your form.
"""
new_context = {
'STATIC_URL': context.get('STATIC_URL', None),
'USE_THREADEDCOMMENTS': appsettings.USE_THREADEDCOMMENTS,
}
# Be configuration independent:
if new_context['STATIC_URL'] is None:
try:
request = context['request']
except KeyError:
new_context.update({'STATIC_URL': settings.STATIC_URL})
else:
new_context.update(context_processors.static(request))
return new_context
register.filter('comments_are_open', comments_are_open)
register.filter('comments_are_moderated', comments_are_moderated)
@register.filter
def comments_count(content_object):
"""
Return the number of comments posted at a target object.
You can use this instead of the ``{% get_comment_count for [object] as [varname] %}`` tag.
"""
return get_comments_for_model(content_object).count()
@register.simple_tag(takes_context=True)
def fluent_comments_list(context):
"""
A simple tag to select the proper template for the current comments app.
"""
if appsettings.USE_THREADEDCOMMENTS:
template = get_template("fluent_comments/templatetags/threaded_list.html")
else:
template = get_template("fluent_comments/templatetags/flat_list.html")
context['USE_THREADEDCOMMENTS'] = appsettings.USE_THREADEDCOMMENTS
return template.render(context)
| [
"[email protected]"
] | |
613b792680347f686d4688247cd143081358fb26 | ff8ec937d9e5bef6d527f91ec4c8a2248063e9f8 | /Flask_Projects/zlbbs/utils/restful.py | 7cabea78ca738a6154bfe13ca084a59c208ab756 | [] | no_license | zyxyuanxiao/Python-Framework-Study-Resources | 3c7743946b828dbd4c0a5b530363d36e54319e9c | cff0f9cefa36afa9fb43f0af5478b7428795d718 | refs/heads/master | 2020-09-04T15:00:06.987122 | 2019-08-19T10:07:29 | 2019-08-19T10:07:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 743 | py | # encoding: utf-8
from flask import jsonify
class HttpCode(object):
ok = 200
unautherror = 401
paramserror = 400
servererror = 500
def restful_result(code, message, data):
return jsonify({"code": code, "message": message, "data": data or {}})
def success(message="", data=None):
return restful_result(code=HttpCode.ok, message=message, data=data)
def unauth_error(message=""):
return restful_result(code=HttpCode.unautherror, message=message, data=None)
def params_error(message=""):
return restful_result(code=HttpCode.paramserror, message=message, data=None)
def server_error(message=""):
return restful_result(code=HttpCode.servererror, message=message or '服务器内部错误', data=None)
| [
"[email protected]"
] | |
a92df2bb4c3e8253898a9cf3a14a0b8cef4d47e8 | 322c282ff00244b95383ac7bc39d102c9a955529 | /dialog_bot_sdk/groups.py | 4a15b481679fcfa6ff0a396277b49804aea62a3c | [] | no_license | artrslpnv/Supporting_polls_FTL | 1dadacf0759e3ec2aa1e16d44f85d8b545af80e5 | 48ac645dfd731748b1bbc37cd0a06dcbfd81ac0d | refs/heads/master | 2020-08-29T20:27:09.339215 | 2019-10-31T12:17:52 | 2019-10-31T12:17:52 | 218,166,040 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,409 | py | from google.protobuf import wrappers_pb2
from .service import ManagedService
from dialog_api import search_pb2, groups_pb2
class Groups(ManagedService):
"""Class for handling groups
"""
def create_group(self, title, username, users=None):
"""Create group
:param title: title of group
:param username: group name
:param users: list of UserOutPeer's objects
"""
if users is None:
users = []
self.internal.groups.CreateGroup(groups_pb2.RequestCreateGroup(
title=title,
username=wrappers_pb2.StringValue(value=username),
users=users,
group_type=groups_pb2.GROUPTYPE_GROUP
))
def find_group_by_shortname(self, query):
"""Find a groups by shortname (substring name)
:param query: shortname of group
:return: groups list
"""
return self.internal.search.PeerSearch(
search_pb2.RequestPeerSearch(
query=[
search_pb2.SearchCondition(
searchPeerTypeCondition=search_pb2.SearchPeerTypeCondition(peer_type=search_pb2.SEARCHPEERTYPE_GROUPS)
),
search_pb2.SearchCondition(
searchPieceText=search_pb2.SearchPieceText(query=query)
)
]
)
).groups
| [
"ArTuRsl2000"
] | ArTuRsl2000 |
b83d5bf357cac905fe80e2ab646221b2a5ed16d7 | 39e7041ed36f87a1a8c23df9d2c607726fcf0a1a | /data/data_column.py | 6dff515ea2e1681704403aa13480b4eae7215ad9 | [
"MIT"
] | permissive | willbelucky/FleetSalesPricingAtFjordMotor | fad2b65cddcca79c881d7290bcf5d7dd3ff5ba78 | 5899b75363cf6b8a3ae598e88069374cfb35bc3e | refs/heads/master | 2021-09-07T06:48:39.092756 | 2018-02-19T02:12:51 | 2018-02-19T02:12:51 | 119,624,541 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 315 | py | # -*- coding: utf-8 -*-
"""
:Author: Jaekyoung Kim
:Date: 2018. 1. 31.
"""
UNIT_NUMBER = 'unit_number'
UNIT_PRICE = 'unit_price'
TOTAL_PRICE = 'total_price'
WIN = 'win'
DISCOUNT_RATE = 'discount_rate'
UNIT_MARGIN = 'unit_margin'
UNIT_SOLD_NUMBER = 'unit_sold_number'
TOTAL_MARGIN = 'total_margin'
POLICE = 'police'
| [
"[email protected]"
] | |
6a80f09d9da6b0b26b722d9e5a0f62a26142920a | c34d8a2ae4d5d34ec64f59047101f5adc04ab458 | /data/generate_train_samples.py | a1f3844ee7d6ab1be22994a36995e7e512300011 | [] | no_license | hermit0/gradualDetector | b5ac1d6b24b0a4f6ec3be3fca41dc57c91fece26 | 78928541874b1488320a79cf0e063cdc9f068aee | refs/heads/master | 2020-04-27T06:53:17.069148 | 2019-03-27T01:40:52 | 2019-03-27T01:40:52 | 174,120,858 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,124 | py | #-*- coding:utf-8 -*-
'''
根据train.json中的渐变标注生成渐变用训练集
'''
import json
from numpy import random
import pdb
'''
主函数,
输入:
gts_json_path -- str, groundtruth json 文件
samples_in -- int, 单个渐变过程中的采样帧数
rate -- float, 渐变过程前后的采样帧数和m的比值。即渐变过程前(后)采样rate*samples_in帧
skip_frames -- int, 跳过紧贴着渐变过程的skip_frames帧进行采样
out_file_path -- 生成的最终样本的文件的路径
'''
def main(gts_json_path,samples_in,rate,skip_frames,out_file_path):
gts = json.load(open(gts_json_path))
all_samples = []
for video_name, annotation in gts.items():
samples_in_the_video = core_process(annotation,samples_in,rate,skip_frames,out_file_path)
for frame_no,prob_s,prob_mid,prob_e in samples_in_the_video:
all_samples.append((video_name,frame_no,prob_s,prob_mid,prob_e))
save_samples(all_samples,out_file_path)
'''
保存样本文件
'''
def save_samples(samples_list,out_file_path):
fd = open(out_file_path,'w')
for video_name,frame_no,prob_s,prob_mid,prob_e in samples_list:
line = '{} {} {} {} {}\n'.format(video_name,frame_no,prob_s,prob_mid,prob_e)
fd.write(line)
fd.close()
'''
为单个视频生成训练用渐变样本集
返回的样本集中的样本表示为(frame_no,prob_s,prob_mid,prob_e)
'''
def core_process(annotation,samples_in,rate,skip_frames,out_file_path):
total_frames = int(annotation['frame_num'])
prob_s = [] #每一帧是渐变开始帧的概率
prob_e = [] #每一帧是渐变结束帧的概率
prob_mid = [] #每一帧是渐变过程的中间帧的概率
for i in range(total_frames):
prob_s.append(0)
prob_e.append(0)
prob_mid.append(0)
#pdb.set_trace()
all_shots = []
shot_begin = 0 #镜头的开始帧
shot_end = -1 #镜头的结束帧
for begin,end in annotation['transitions']:
if end - begin < 1:
continue
shot_end = begin
all_shots.append((shot_begin,shot_end))
shot_begin = end
shot_end = total_frames - 1
all_shots.append((shot_begin,shot_end))
all_graduals = []
trans_index = 0
for begin, end in annotation['transitions']:
if end - begin < 1:
continue
trans_index += 1
if end - begin == 1:
continue #跳过切变
if end - begin == 2:
continue #跳过长度为1的渐变
gradual = (all_shots[trans_index-1][0],all_shots[trans_index-1][1],
all_shots[trans_index][0],all_shots[trans_index][1]) #(前一镜头,后一镜头)
all_graduals.append(gradual)
for (begin,end) in annotation['transitions']:
if end - begin <= 2:
continue #跳过切变,并忽略掉长度为1的渐变
#整个渐变过程的区间为[begin+1,end-1]
for frame_no in range(begin+1,end):
if frame_no == begin + 1:
#渐变开始帧
prob_s[frame_no] = 1
if frame_no == end - 1:
prob_e[frame_no] = 1
if frame_no > begin + 1 and frame_no + 1 < end:
#渐变过程的中间帧
prob_mid[frame_no] = 1
#这儿可以添加对prob_s,prob_e,prob_mid进行平滑的操作
samples_out = int(samples_in * rate)
results = []#采样的样本集
if len(all_graduals) == 0:
#如果视频不含渐变
for frame_no in sample_from_interval(0,total_frames-1,samples_out):
results.append((frame_no,prob_s[frame_no],prob_mid[frame_no],prob_e[frame_no]))
else:
for (s1,e1,s2,e2) in all_graduals:
#采样渐变过程中的帧
for frame_no in sample_from_gradual(e1+1,s2-1,samples_in):
results.append((frame_no,prob_s[frame_no],prob_mid[frame_no],prob_e[frame_no]))
#采样渐变前的帧
interval_len = 20 #采样的区间长度为21帧
#渐变的前一镜头为[s1,e1],从[e1-skip_frames-20,e1-skip_frames]中随机采样sample_out帧
interval_end = e1 - skip_frames
interval_begin = interval_end - interval_len
if interval_begin < s1:
interval_begin = s1
for frame_no in sample_from_interval(interval_begin,interval_end,samples_out):
results.append((frame_no,prob_s[frame_no],prob_mid[frame_no],prob_e[frame_no]))
#采样渐变后的帧
#渐变的后一镜头为[s2,e2],从[s2+skip_frames,s2+skip_frames+20]中随机采样samples_out帧
interval_begin = s2 + skip_frames
interval_end = s2 + skip_frames + interval_len
if interval_end > e2:
interval_end = e2
for frame_no in sample_from_interval(interval_begin,interval_end,samples_out):
results.append((frame_no,prob_s[frame_no],prob_mid[frame_no],prob_e[frame_no]))
#移除掉重复的采样帧
results = list(set(results))
results.sort()
return results
'''
从渐变[s,e]中采样m帧,必须采样s,e,mid=(s+e)/2这三帧,剩下的帧随机采样
'''
def sample_from_gradual(s,e,total_sample):
has_sampled = []
frame_nos = []
prob = []
for x in range(s,e+1):
frame_nos.append(x)
prob.append(0)
gradual_len = e - s + 1 #渐变的长度
#设置采样的总帧数
if gradual_len < 2:
return has_sampled #跳过长度为1的渐变
if gradual_len < total_sample:
total_sample = gradual_len
has_sampled.append(s)
has_sampled.append(e)
mid = int((s + e) / 2)
if total_sample >= 3:
has_sampled.append(mid)
if total_sample > 3:
remain = total_sample - 3
for i in range(s+1,e):
if i != mid:
prob[i-s] = 1.0 / (gradual_len - 3)
for frame in random.choice(frame_nos,size=remain,p=prob,replace=False):
has_sampled.append(frame)
return has_sampled
'''
从区间[s,e]中随机抽样k帧
'''
def sample_from_interval(s,e,k):
if k > e - s + 1:
k = e - s + 1
all_values = []
if k <= 0:
return all_values
for value in range(s,e+1):
all_values.append(value)
return random.choice(all_values,size=k,replace=False)
if __name__ == '__main__':
gts_json_path = input('Enter the groundtruth json file: ')
samples_in = input('the number you need sample in one gradual transition: ')
samples_in = int(samples_in)
rate = input('Enter the rate of samples out of gradual with respect to samples_in\n'
'ie.samples_out = rate * samples_in: ')
rate = float(rate)
skip_frames = input('Enter the skip_frames to skip near the gradual: ')
skip_frames = int(skip_frames)
out_file_path = input('Enter the path of result sample file: ')
main(gts_json_path,samples_in,rate,skip_frames,out_file_path) | [
"[email protected]"
] | |
85a60a7ffb26a2e4eefac730a32b0916e982a7e4 | c6b9e8cba0c91a03184fef2171f0df131f66ee25 | /setup.py | b08cec8fffe1f3d7e4839ef9270d724b25bc06f9 | [
"BSD-3-Clause"
] | permissive | waltherg/data-structures-algorithms | 41af71ed20a83d17aba6633471970ee43fd58208 | 09e106b84da5879b255ecfb83d25a3e8b40eb777 | refs/heads/master | 2021-01-02T08:19:52.800912 | 2014-02-15T21:56:39 | 2014-02-15T21:56:39 | 16,871,052 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 115 | py | from setuptools import setup
setup(name='dsa',
packages=['dsa', 'dsa.tests'],
test_suite='dsa.tests')
| [
"[email protected]"
] | |
26d93a5357ff0b72b49b771ac58cfeda86ba6b2d | 5692e8a3357f7afe6284b43c4a9770d81957a511 | /accounts/signals.py | ac98bea95d81fb783c4a9b66b5703e53f64bf59c | [] | no_license | OmarFateh/student-management-system | 49bcfbdf15a631cf7f64ff200d530a44a44409ac | 2c53f81a55fe631406b642365a68de19501c0f17 | refs/heads/master | 2023-07-16T00:02:54.796428 | 2021-08-25T01:54:02 | 2021-08-25T01:54:02 | 355,033,774 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 725 | py | from django.dispatch import receiver
from django.db.models.signals import post_save
from .models import User
from student.models import Student
from staff.models import Staff
from adminhod.models import AdminHOD
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
"""
Create an empty profile for each user type once the user is added.
"""
if created:
if instance.user_type == 'HOD':
AdminHOD.objects.create(user=instance)
elif instance.user_type == 'STAFF':
Staff.objects.create(user=instance)
elif instance.user_type == 'STUDENT':
Student.objects.create(user=instance) | [
"[email protected]"
] | |
aaffa49e059f35db72dcc20e75717a416a19f9aa | 9b979d872e1fa81dfc32420272cb7e1676c38bb5 | /Moves/King.py | 0f96157e8bece14a92edf471381354c8fef507c2 | [] | no_license | SusyVenta/Chess | d4b293bc7ce26f21538088290bf3b318b4507b37 | 960351b4f756d8b176d536a56876dad947bbfe86 | refs/heads/master | 2021-06-02T00:41:27.698562 | 2020-07-06T17:32:34 | 2020-07-06T17:32:34 | 148,921,146 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,570 | py | from Chess.Utils import Utils
class King:
def __init__(self, piece_moving):
self.utils = Utils()
self.piece_moving = piece_moving
def move_is_possible(self, start_tag, end_tag, all_turns_pieces_position, max_turn):
return end_tag in self.get_all_allowed_moves(start_tag=start_tag, max_turn=max_turn,
all_turns_pieces_position=all_turns_pieces_position)
def get_all_allowed_moves(self, start_tag, all_turns_pieces_position, max_turn, piece=None):
current_coordinate_number = int(self.utils.get_current_number(start_tag))
print(f"current_coordinate_number: {current_coordinate_number}")
current_coordinate_letter = self.utils.get_current_letter(start_tag)
print(f"current_coordinate_letter: {current_coordinate_letter}")
all_moves = self.horizontal_moves(current_coordinate_number, current_coordinate_letter,
all_turns_pieces_position[max_turn]) + \
self.vertical_moves(current_coordinate_number, current_coordinate_letter,
all_turns_pieces_position[max_turn]) + \
self.diagonal_moves(current_coordinate_number, current_coordinate_letter,
all_turns_pieces_position[max_turn])
print(all_moves)
return all_moves
def horizontal_moves(self, number, letter, pieces_position):
moves = []
current_letter_number = self.utils.letter_to_number(letter)
if current_letter_number + 1 in range(1, 9):
move = f"{self.utils.number_to_letter(current_letter_number + 1)}{number}"
if (self.utils.end_position_is_free(move, pieces_position)) or (
self.utils.end_position_contains_opponent_piece(self.piece_moving, move,
pieces_position)):
moves.append(move)
if current_letter_number - 1 in range(1, 9):
move = f"{self.utils.number_to_letter(current_letter_number - 1)}{number}"
if (self.utils.end_position_is_free(move, pieces_position)) or (
self.utils.end_position_contains_opponent_piece(self.piece_moving, move,
pieces_position)):
moves.append(move)
return moves
def vertical_moves(self, number, letter, pieces_position):
moves = []
if number + 1 in range(1, 9):
move = f"{letter}{number + 1}"
if (self.utils.end_position_is_free(move, pieces_position)) or (
self.utils.end_position_contains_opponent_piece(self.piece_moving, move,
pieces_position)):
moves.append(move)
if number - 1 in range(1, 9):
move = f"{letter}{number - 1}"
if (self.utils.end_position_is_free(move, pieces_position)) or (
self.utils.end_position_contains_opponent_piece(self.piece_moving, move,
pieces_position)):
moves.append(move)
return moves
def diagonal_moves(self, number, letter, pieces_position):
moves = []
current_letter_number = self.utils.letter_to_number(letter)
""" Up - rightwards: letter + 1, number + 1 """
if current_letter_number + 1 in range(1, 9) and number + 1 in range(1, 9):
move = f"{self.utils.number_to_letter(current_letter_number + 1)}{number + 1}"
if (self.utils.end_position_is_free(move, pieces_position)) or (
self.utils.end_position_contains_opponent_piece(self.piece_moving, move,
pieces_position)):
moves.append(move)
""" down - leftwards: letter - 1, number - 1 """
if current_letter_number - 1 in range(1, 9) and number - 1 in range(1, 9):
move = f"{self.utils.number_to_letter(current_letter_number - 1)}{number - 1}"
if (self.utils.end_position_is_free(move, pieces_position)) or (
self.utils.end_position_contains_opponent_piece(self.piece_moving, move,
pieces_position)):
moves.append(move)
""" up - leftwards: letter - 1, number + 1 """
if current_letter_number - 1 in range(1, 9) and number + 1 in range(1, 9):
move = f"{self.utils.number_to_letter(current_letter_number - 1)}{number + 1}"
if (self.utils.end_position_is_free(move, pieces_position)) or (
self.utils.end_position_contains_opponent_piece(self.piece_moving, move,
pieces_position)):
moves.append(move)
""" down - rightwards: letter + 1, number - 1 """
if current_letter_number + 1 in range(1, 9) and number - 1 in range(1, 9):
move = f"{self.utils.number_to_letter(current_letter_number + 1)}{number - 1}"
if (self.utils.end_position_is_free(move, pieces_position)) or (
self.utils.end_position_contains_opponent_piece(self.piece_moving, move,
pieces_position)):
moves.append(move)
return moves
| [
"[email protected]"
] | |
4cb2247360ef74f6bd9fbb08214eb5e7f782b7a3 | 465f8c4575a48e2da00605664424de688a2ff582 | /exchange/admin.py | 792ef0af5f06e22525c030662c02612c883c9100 | [] | no_license | Upendrasg/AutomatedJobProcess | c242b6a9018256d8ecb3e1fcf1014e0cdda07dc8 | 8b6823980e580f65ce80ef3b32210a5b4ef24e0e | refs/heads/master | 2020-05-25T12:43:13.704779 | 2019-03-13T11:13:13 | 2019-03-13T11:13:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 252 | py | from django.contrib import admin
from .models import Report
class ReportAdmin(admin.ModelAdmin):
"""
"""
list_display = (
'id',
'user',
'vacancy',
'result',
)
admin.site.register(Report, ReportAdmin)
| [
"[email protected]"
] | |
5a091300753b2a3257045d18ee390647f1cd7eb5 | bece503909072c9e70cfa8d8d88fdfaab50be8b5 | /configure/migrations/0016_auto_20210502_0607.py | 566cb9134b19e9de23269af6de4fbccafc2104a0 | [] | no_license | yra3/configurator | 2c9a6d7bb410f7108a771bc59a80963c4bc856d3 | cc773f2f31936164a69e172917e2647ea58792d8 | refs/heads/master | 2023-06-12T04:44:15.434496 | 2021-07-05T05:02:04 | 2021-07-05T05:02:04 | 362,072,915 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 566 | py | # Generated by Django 3.2 on 2021-05-02 01:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('configure', '0015_auto_20210502_0506'),
]
operations = [
migrations.RenameField(
model_name='hard35',
old_name='eatures_optional',
new_name='features_optional',
),
migrations.AddField(
model_name='hard25',
name='features_optional',
field=models.CharField(max_length=200, null=True),
),
]
| [
"[email protected]"
] | |
15668f5164fee40889b4cea03738350bc4d556c4 | 8449f44991409dac5fa936c9a17fdf9c7d6387a9 | /anyos_clean.py | 1035fc948f31cb7afded7e490bf4e910d6b9d7a8 | [] | no_license | emilio-carrasco/sharkstattack | ba8b67571e0b0ae47b55b15e16bf491eeb6962fd | 81853480b2c402a507e3edf8ab530a902b7a805b | refs/heads/master | 2023-04-11T19:40:36.544870 | 2021-04-05T18:23:49 | 2021-04-05T18:23:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 671 | py | import pandas as pd
import src.limpieza_texto as lt
pd.options.mode.chained_assignment = None # default='warn'
srk = pd.read_csv("./data/attacks.csv",encoding = "ISO-8859-1")
column_years='Years'
srk = lt.year_cleaner(srk,column_years)
pais = 'AUSTRALIA'
srk_country = lt.clean_one_country(srk, pais)
temp = lt.read_temp("./data/temp.csv", column_years)
magnitud='Attacks'
srk_hist = lt.histograma(srk_country,column_years,magnitud)
primero = 1950
ultimo = 2017
temp = lt.filter_years(temp, primero, ultimo)
srk_hist = lt.filter_years(srk_hist, primero, ultimo)
df=lt.unir(temp,srk_hist)
df.to_csv(path_or_buf='./outputs/anyos_out.csv',index=True) | [
"[email protected]"
] | |
426c6fa3b64b44c80c5d6aa54bfe409e0d0adf9b | 960ab2de7274f9ac590ab4d1e68d4e7aaecb28a4 | /lib.py | 632bb3b0581e40bc78d27c9434fe14bb54a75159 | [] | no_license | apollinaria-sleep/MatrixCalculator | cd4ffee31e124da75291a7a3ace15c8f897eac7d | 20577b3aab3c5027a838c2799b9c7ea18db308eb | refs/heads/master | 2022-08-02T22:06:00.503501 | 2020-05-24T10:04:25 | 2020-05-24T10:04:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,814 | py | import numpy as np
def change_type(matrix):
values = list(map(int, matrix.split(' ')))
return values
def check(matrix):
if matrix.first_matrix.rows == matrix.second_matrix.rows and matrix.first_matrix.col == matrix.second_matrix.col:
return True
else:
return False
class Matrix:
def __init__(self, rows=1, col=1, matrix=[1]):
self.rows = int(rows)
self.col = int(col)
self.matrix = np.array(matrix)
self.matrix = np.reshape(self.matrix, (self.rows, self.col))
class LastMatrix:
POSSIBLE_ITEMS = ['first_rows', 'first_col', 'first_matrix', 'second_rows', 'second_col', 'second_matrix', ]
def __init__(self):
self.first_matrix = Matrix()
self.second_matrix = Matrix()
def add_matrix(self, first_rows, first_col, first_matrix, second_rows, second_col, second_matrix):
first_matrix = change_type(first_matrix)
second_matrix = change_type(second_matrix)
self.first_matrix = Matrix(first_rows, first_col, first_matrix)
self.second_matrix = Matrix(second_rows, second_col, second_matrix)
return 'Done'
def amount(self):
if check(self):
amount = str(self.first_matrix.matrix + self.second_matrix.matrix)
else:
amount = 'Incompatible matrices!'
return amount
def difference(self):
if check(self):
difference = str(self.first_matrix.matrix - self.second_matrix.matrix)
else:
difference = 'Incompatible matrices!'
return difference
def multiplication(self):
if check(self):
multiplication = str(self.first_matrix.matrix * self.second_matrix.matrix)
else:
multiplication = 'Incompatible matrices!'
return multiplication
| [
"[email protected]"
] | |
d3cf0950e795914002185f0928273b3fd1359d3a | 0ee975e4c7d595149620f8e3a657e11bb6b103b3 | /dn_api_14/models/__init__.py | 1e3a53d16df494d756a2b0af3e37f7f39655f2ff | [] | no_license | WithHookahOrg/dn_api_14 | c3a43bdf8eef0bfde1592932b1323e4e2d6632ab | 506f3cb673afb84235aaa35c1de7dc8f3da69c89 | refs/heads/master | 2023-01-07T17:39:28.508282 | 2020-11-09T03:54:46 | 2020-11-09T03:54:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 82 | py | # -*- coding: utf-8 -*-
from . import models
from . import access_token, ir_model | [
"[email protected]"
] | |
5cd64f75881986daf487add822ea662152537e7e | d72f59fc301bd0dde25d2486f09fd450b7504705 | /acmicpc/10171.py | 9af4d44a533c2214c1b8e6dadd00c31e1c61c731 | [] | no_license | jinwoo2516/TIL | a743aa2848425e4b7d1bd41e078a0ec240a6948f | f07cd42e628a40fddf7ac0b40ebd1e287049f6c2 | refs/heads/master | 2023-03-27T05:48:19.066249 | 2021-03-29T17:36:47 | 2021-03-29T17:36:47 | 349,032,460 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 89 | py | print("\\ /\\ ")
print(" ) ( ')")
print("( / )")
print("( / )")
print(" \\(__)|") | [
"[email protected]"
] | |
9567c834436dde5f332d3855a2e98b5e4fe95f8b | 0bab87d3d3bc6f790f6d924330acf7ae1c6ebc30 | /kunyi/bfs/course_schedule_iii.py | 405a72df87a3fb540d0091318268d364e6a92a6e | [] | no_license | KunyiLiu/algorithm_problems | 2032b9488cd2f20b23b47c456107475f609b178f | b27a1d4d65429101ef027f5e1e91ba2afd13bd32 | refs/heads/master | 2020-04-26T15:29:43.875656 | 2019-10-21T19:09:01 | 2019-10-21T19:09:01 | 173,648,702 | 0 | 0 | null | 2019-07-21T19:15:23 | 2019-03-04T00:48:02 | Python | UTF-8 | Python | false | false | 967 | py | class Solution:
"""
@param courses: duration and close day of each course
@return: the maximal number of courses that can be taken
"""
def scheduleCourse(self, courses):
"""
贪心法 Greedy
课程按照 deadline 排序,从左到右扫描每个课程,依次学习。如果发现学了之后超过 deadline 的,就从之前学过的课程里扔掉一个耗时最长的。
因为这样可以使得其他的课程往前挪,而往前挪是没影响的。
所以挑最大值这个事情就是 Heap 的事情了
"""
import heapq
cur_time = 0
heap = []
courses = sorted(courses, key=lambda x: x[1])
for duration, ddl in courses:
cur_time += duration
heapq.heappush(heap, -duration)
if cur_time > ddl:
max_duration = - heapq.heappop(heap)
cur_time -= max_duration
return len(heap)
| [
"[email protected]"
] | |
c415424d926d5a9bee303bdee2da12cf084d45d6 | 2bc470936d9648e3937de2a1dd980fe1c2dabea0 | /helpers/playlists.py | 082e428dd6257988580cf38f7f78f29828b9eaa8 | [
"MIT"
] | permissive | navrudh/youtube-music-helper-scripts | 40e026f11e1fac3ff55616bd2488de625d490e34 | 7bae74d698e15e11bac427e42bd0a21e08163f88 | refs/heads/main | 2023-02-02T22:39:20.139562 | 2020-12-22T20:47:17 | 2020-12-22T20:47:17 | 317,985,731 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,000 | py | from ytmusicapi import YTMusic
from dataclazzes.playlist import Playlist
from dataclazzes.track import Track
def get_playlist_info(ytm_client: YTMusic, id: str):
playlist = ytm_client.get_playlist(id)
raw_tracks = playlist["tracks"]
return Playlist(id='id',
title=playlist['title'],
tracks=Track.from_raw_tracks(raw_tracks))
def get_user_playlist_by_title(ytm_client: YTMusic,
title: str,
limit: int = 25):
raw_playlists = ytm_client.get_library_playlists(limit=limit)
playlists = Playlist.from_raw(raw_playlists)
for pl in playlists:
if pl.title == title:
return pl
def create_playlist(ytm_client: YTMusic, title: str, desc: str = ""):
id = ytm_client.create_playlist(title=title, description=desc)
if not isinstance(id, str):
print(id)
raise Exception("Failed creating playlist!")
return Playlist(id=id, title=title)
| [
"[email protected]"
] | |
4c0a87671652fb0e9964fba421c988acf539a937 | e727005dd121706584df613fb471b39fd62c389a | /textBoxes.py | de47c469f36e866bcfc180fc91a7f15680a4121e | [] | no_license | ajaydheeraj/David-Go-Project | 2666d7b5195a2e281c3f8d1198239e64d6309c41 | 3ed6577aba1f5803800b7d7d07a9a120ec73fa20 | refs/heads/master | 2021-08-24T02:55:10.308915 | 2017-12-07T18:59:01 | 2017-12-07T18:59:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,755 | py | ### text boxes that appear when a player is trying to undo a move, pass the turn
### or reset the game
import pygame
from static import *
# object for using text boxes
class TextBox(pygame.sprite.Sprite):
bounds = (50, 200, 500, 200)
def __init__(self, action):
self.action = action
text = "Are you sure you want to %s?" % action
self.text = pygame.font.Font(None, 36).render(text, True, (0, 0, 0))
def draw(self, screen):
pygame.draw.rect(screen, Colors.WHITE, self.bounds)
pygame.draw.rect(screen, Colors.BLACK, self.bounds, 5)
screen.blit(self.text, (75, 225))
BoolBox("Yes").draw(screen)
BoolBox("No").draw(screen)
def __repr__(self):
return self.action
# object for clicking to remove dead stones text box, draws from TextBox super
class DeadStoneBox(TextBox):
def __init__(self, action):
super().__init__(action)
self.text = pygame.font.Font(None, 36).render("Click to remove dead stones", True, (0, 0, 0))
self.text2 = pygame.font.Font(None, 36).render("Press 'D' when done", True, (0, 0, 0))
def draw(self, screen):
pygame.draw.rect(screen, Colors.WHITE, self.bounds)
pygame.draw.rect(screen, Colors.BLACK, self.bounds, 5)
screen.blit(self.text, (75, 225))
screen.blit(self.text2, (75, 275))
BoolBox("OK").draw(screen)
# The box that appears when the game is over
class GameOverBox(pygame.sprite.Sprite):
bounds = (50, 200, 500, 200)
def __init__(self, p1score, p2score):
if p1score > p2score:
gameStats = ("Black", p1score, p2score)
else:
gameStats = ("White", p2score, p1score)
self.text1 = pygame.font.Font(None, 36).render("GAME OVER!", True, (0, 0, 0))
self.text2 = pygame.font.Font(None, 36).render("Winner is %s, %d to %d"%gameStats, True, (0, 0, 0))
self.text3 = pygame.font.Font(None, 28).render("(Click anywhere to close this box)", True, (0, 0, 0))
def draw(self, screen):
pygame.draw.rect(screen, Colors.WHITE, self.bounds)
pygame.draw.rect(screen, Colors.BLACK, self.bounds, 5)
screen.blit(self.text1, (75, 225))
screen.blit(self.text2, (75, 275))
screen.blit(self.text3, (75, 325))
# the "yes" and "no" buttons on one such text box
class BoolBox(pygame.sprite.Sprite):
def __init__(self, boolean):
self.text = pygame.font.Font(None, 36).render(boolean, True, (0, 0, 0))
if boolean == "Yes" or boolean == "OK":
self.bounds = GoConstants.YESBOXBOUNDS
self.textPos = (100, 337)
elif boolean == "No":
self.bounds = GoConstants.NOBOXBOUNDS
self.textPos = (405, 337)
def draw(self, screen):
pygame.draw.rect(screen, Colors.BLACK, self.bounds, 3)
screen.blit(self.text, self.textPos)
# the "play" button on the start screen
class PlayButton(pygame.sprite.Sprite):
bounds = (300, 250, 200, 50)
def __init__(self):
self.text = pygame.font.Font(None, 36).render("PLAY", True, (0, 0, 0))
self.textPos = (370, 263)
def draw(self, screen):
pygame.draw.rect(screen, Colors.WHITE, self.bounds)
pygame.draw.rect(screen, Colors.BLACK, self.bounds, 5)
screen.blit(self.text, self.textPos)
# the "instructions" button on the start screen
class InstructionsButton(pygame.sprite.Sprite):
bounds = (300, 325, 200, 50)
def __init__(self):
self.text = pygame.font.Font(None, 36).render("INSTRUCTIONS", True, (0, 0, 0))
self.textPos = (305, 338)
def draw(self, screen):
pygame.draw.rect(screen, Colors.WHITE, self.bounds)
pygame.draw.rect(screen, Colors.BLACK, self.bounds, 5)
screen.blit(self.text, self.textPos)
# the title box on the start screen
class TitleBox(pygame.sprite.Sprite):
bounds = (200, 50, 400, 75)
def __init__(self):
self.text = pygame.font.Font(None, 50).render("Go Game", True, (0, 0, 0))
self.textPos = (330, 75)
def draw(self, screen):
pygame.draw.rect(screen, Colors.WHITE, self.bounds)
pygame.draw.rect(screen, Colors.BLACK, self.bounds, 5)
screen.blit(self.text, self.textPos)
# text box showing whose turn it is
class PlayerBox(pygame.sprite.Sprite):
bounds = (600, 30, 180, 50)
blackCenter = (690, 200)
whiteCenter = (690, 450)
circleRadius = 90
def __init__(self):
self.player = "BLACK"
self.text = pygame.font.Font(None, 36).render("%s's turn" % self.player, True, (0, 0, 0))
self.textPos = (605, 45)
def draw(self, screen):
pygame.draw.rect(screen, Colors.WHITE, self.bounds)
pygame.draw.rect(screen, Colors.BLACK, self.bounds, 5)
screen.blit(self.text, self.textPos)
pygame.draw.circle(screen, Colors.BLACK, self.blackCenter, self.circleRadius)
pygame.draw.circle(screen, Colors.WHITE, self.whiteCenter, self.circleRadius)
if self.player == "NO ONE":
return
elif self.player == "BLACK":
turn = self.blackCenter
elif self.player == "WHITE":
turn = self.whiteCenter
pygame.draw.circle(screen, Colors.LIGHTBLUE, turn, self.circleRadius, 10)
def update(self, off=False):
if self.player == "BLACK":
self.player = "WHITE"
elif self.player == "WHITE":
self.player = "BLACK"
if off:
self.player = "NO ONE"
self.text = pygame.font.Font(None, 36).render("%s's turn" % self.player, True, (0, 0, 0)) | [
"[email protected]"
] | |
597501eb53ae1bbe66a77ec3ae75ed19c99eeceb | f2ccfabd0f16ae2d799be5c3b7e7717364d5a01a | /ospurge/tests/resources/test_octavia.py | 2cac78093c07c9e44262548d86df47d04d2eff8d | [
"Apache-2.0"
] | permissive | inovex/ospurge | fc3fe6d6ec14d13cf0eb8e61ad01905f9de59a76 | 6f24c90a1d6a0c8470e02abba039c8ac2a28cb54 | refs/heads/master | 2020-06-11T20:57:11.387821 | 2019-06-27T11:49:47 | 2019-06-27T11:49:47 | 194,083,267 | 1 | 0 | null | 2019-06-27T11:30:59 | 2019-06-27T11:30:58 | null | UTF-8 | Python | false | false | 5,230 | py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import unittest
import shade
from ospurge.resources import octavia
from ospurge.tests import mock
class TestLoadBalancers(unittest.TestCase):
def setUp(self):
self.cloud = mock.Mock(spec_set=shade.openstackcloud.OpenStackCloud)
self.creds_manager = mock.Mock(cloud=self.cloud)
self.client = mock.MagicMock()
@mock.patch('ospurge.resources.octavia.getOctaviaClient', mock.Mock())
def test_check_prerequisite(self):
with mock.patch('shade.meta.get_and_munchify', return_value=["LB1"]):
self.assertEqual(
False,
octavia.LoadBalancers(self.creds_manager).check_prerequisite()
)
with mock.patch('shade.meta.get_and_munchify', return_value=[]):
self.assertEqual(
True,
octavia.LoadBalancers(self.creds_manager).check_prerequisite()
)
@mock.patch('ospurge.resources.octavia.getOctaviaClient', mock.Mock())
def test_list(self):
with mock.patch('shade.meta.get_and_munchify', return_value=[{'name': 'LB1'}, {'name': 'LB2'}]):
self.assertIs(shade.meta.get_and_munchify.return_value,
octavia.LoadBalancers(self.creds_manager).list())
def test_delete(self):
sg = mock.MagicMock()
with mock.patch('ospurge.resources.octavia.getOctaviaClient', return_value=self.client) as m:
self.assertIsNone(
octavia.LoadBalancers(self.creds_manager).delete(sg))
self.client.load_balancer_delete.assert_called_once_with(sg['id'])
@mock.patch('ospurge.resources.octavia.getOctaviaClient', mock.Mock())
def test_to_string(self):
sg = mock.MagicMock()
self.assertIn("Load Balancer (",
octavia.LoadBalancers(self.creds_manager).to_str(sg))
class TestListeners(unittest.TestCase):
def setUp(self):
self.cloud = mock.Mock(spec_set=shade.openstackcloud.OpenStackCloud)
self.creds_manager = mock.Mock(cloud=self.cloud)
self.client = mock.MagicMock()
@mock.patch('ospurge.resources.octavia.getOctaviaClient', mock.Mock())
def test_check_prerequisite(self):
with mock.patch('shade.meta.get_and_munchify', return_value=["Listener1"]):
self.assertEqual(
False,
octavia.Listeners(self.creds_manager).check_prerequisite()
)
with mock.patch('shade.meta.get_and_munchify', return_value=[]):
self.assertEqual(
True,
octavia.Listeners(self.creds_manager).check_prerequisite()
)
@mock.patch('ospurge.resources.octavia.getOctaviaClient', mock.Mock())
def test_list(self):
with mock.patch('shade.meta.get_and_munchify', return_value=[{'name': 'Listener1'}, {'name': 'Listener2'}]):
self.assertIs(shade.meta.get_and_munchify.return_value,
octavia.Listeners(self.creds_manager).list())
def test_delete(self):
sg = mock.MagicMock()
with mock.patch('ospurge.resources.octavia.getOctaviaClient', return_value=self.client) as m:
self.assertIsNone(
octavia.Listeners(self.creds_manager).delete(sg))
self.client.listener_delete.assert_called_once()
@mock.patch('ospurge.resources.octavia.getOctaviaClient', mock.Mock())
def test_to_string(self):
sg = mock.MagicMock()
self.assertIn("Listener (",
octavia.Listeners(self.creds_manager).to_str(sg))
class TestPools(unittest.TestCase):
def setUp(self):
self.cloud = mock.Mock(spec_set=shade.openstackcloud.OpenStackCloud)
self.creds_manager = mock.Mock(cloud=self.cloud)
self.client = mock.MagicMock()
@mock.patch('ospurge.resources.octavia.getOctaviaClient', mock.Mock())
def test_list(self):
with mock.patch('shade.meta.get_and_munchify', return_value=[{'name': 'Pool1'}, {'name': 'Pool2'}]):
self.assertIs(shade.meta.get_and_munchify.return_value,
octavia.Pools(self.creds_manager).list())
def test_delete(self):
sg = mock.MagicMock()
with mock.patch('ospurge.resources.octavia.getOctaviaClient', return_value=self.client) as m:
self.assertIsNone(
octavia.Pools(self.creds_manager).delete(sg))
self.client.pool_delete.assert_called_once()
@mock.patch('ospurge.resources.octavia.getOctaviaClient', mock.Mock())
def test_to_string(self):
sg = mock.MagicMock()
self.assertIn("Pool (",
octavia.Pools(self.creds_manager).to_str(sg))
| [
"[email protected]"
] | |
1ee8b842df61cffe0f5d60740c8942db1efb422b | d5ad13232e3f1ced55f6956bc4cbda87925c8085 | /cc_mcc_seq/20sSV/jumpy/5-format.py | b65a5ce28d9392de067c64373184c4ea98e47851 | [] | no_license | arvin580/SIBS | c0ba9a8a41f59cb333517c286f7d80300b9501a2 | 0cc2378bf62359ec068336ea4de16d081d0f58a4 | refs/heads/master | 2021-01-23T21:57:35.658443 | 2015-04-09T23:11:34 | 2015-04-09T23:11:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 980 | py | import re
def reads(inF):
D = {}
inFile = open(inF)
for line in inFile:
line = line.strip()
if line.find('>')==0:
head = line.lstrip('>')
D.setdefault(head,[])
else:
D[head].append(line)
inFile.close()
D2 = {}
for k in D:
if k.split(':')[2].find('B')==-1:
flag = 0
for item in D[k]:
s = re.split(r'\s+',item)
if len(s)>=2:
if len(s[0])>30 and len(s[-1])>30:
D2[k]= ''.join(s)
flag = 1
break
if flag == 0:
print('warning: '+ k)
ouFile = open(inF+'.formated', 'w')
d = D2.items()
d.sort(cmp = lambda x,y :cmp(x[0],y[0]))
for item in d:
ouFile.write(item[0]+ '\t' +item[1]+ '\n')
ouFile.close()
reads('20s.translocation.exon.reads')
reads('20s.translocation.gene.reads')
| [
"[email protected]"
] | |
a60935f4cf48e25e5bd527a6e85976d93d2910f2 | a9e3f3ad54ade49c19973707d2beb49f64490efd | /Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/grades/scores.py | 9c4da6a8b786e2cedb7472d1c05c310c57c5f6d4 | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | permissive | luque/better-ways-of-thinking-about-software | 8c3dda94e119f0f96edbfe5ba60ca6ec3f5f625d | 5809eaca7079a15ee56b0b7fcfea425337046c97 | refs/heads/master | 2021-11-24T15:10:09.785252 | 2021-11-22T12:14:34 | 2021-11-22T12:14:34 | 163,850,454 | 3 | 1 | MIT | 2021-11-22T12:12:31 | 2019-01-02T14:21:30 | JavaScript | UTF-8 | Python | false | false | 12,149 | py | """
Functionality for problem scores.
"""
from logging import getLogger
from numpy import around
from xblock.core import XBlock
from openedx.core.lib.cache_utils import process_cached
from xmodule.graders import ProblemScore
from .transformer import GradesTransformer
log = getLogger(__name__)
def possibly_scored(usage_key):
"""
Returns whether the given block could impact grading (i.e.
has_score or has_children).
"""
return usage_key.block_type in _block_types_possibly_scored()
def get_score(submissions_scores, csm_scores, persisted_block, block):
"""
Returns the score for a problem, as a ProblemScore object. It is
assumed that the provided storages have already been filtered for
a single user in question and have user-specific values.
The score is retrieved from the provided storages in the following
order of precedence. If no value for the block is found in a
given storage, the next storage is checked.
submissions_scores (dict of {unicode(usage_key): (earned, possible)}):
A python dictionary of serialized UsageKeys to (earned, possible)
tuples. These values, retrieved using the Submissions API by the
caller (already filtered for the user and course), take precedence
above all other score storages.
When the score is found in this storage, it implies the user's score
for the block was persisted via the submissions API. Typically, this API
is used by ORA.
The returned score includes valid values for:
weighted_earned
weighted_possible
graded - retrieved from the persisted block, if found, else from
the latest block content.
Note: raw_earned and raw_possible are not required when submitting scores
via the submissions API, so those values (along with the unused weight)
are invalid and irrelevant.
csm_scores (ScoresClient):
The ScoresClient object (already filtered for the user and course),
from which a courseware.models.StudentModule object can be retrieved for
the block.
When the score is found from this storage, it implies the user's score
for the block was persisted in the Courseware Student Module. Typically,
this storage is used for all CAPA problems, including scores calculated
by external graders.
The returned score includes valid values for:
raw_earned, raw_possible - retrieved from CSM
weighted_earned, weighted_possible - calculated from the raw scores and weight
weight, graded - retrieved from the persisted block, if found,
else from the latest block content
persisted_block (.models.BlockRecord):
The block values as found in the grades persistence layer. These values
are used only if not found from an earlier storage, and take precedence
over values stored within the latest content-version of the block.
When the score is found from this storage, it implies the user has not
yet attempted this problem, but the user's grade _was_ persisted.
The returned score includes valid values for:
raw_earned - will equal 0.0 since the user's score was not found from
earlier storages
raw_possible - retrieved from the persisted block
weighted_earned, weighted_possible - calculated from the raw scores and weight
weight, graded - retrieved from the persisted block
block (block_structure.BlockData):
Values from the latest content-version of the block are used only if
they were not available from a prior storage.
When the score is found from this storage, it implies the user has not
yet attempted this problem and the user's grade was _not_ yet persisted.
The returned score includes valid values for:
raw_earned - will equal 0.0 since the user's score was not found from
earlier storages
raw_possible - retrieved from the latest block content
weighted_earned, weighted_possible - calculated from the raw scores and weight
weight, graded - retrieved from the latest block content
"""
weight = _get_weight_from_block(persisted_block, block)
# TODO: Remove as part of EDUCATOR-4602.
if str(block.location.course_key) == 'course-v1:UQx+BUSLEAD5x+2T2019':
log.info('Weight for block: ***{}*** is {}'
.format(str(block.location), weight))
# Priority order for retrieving the scores:
# submissions API -> CSM -> grades persisted block -> latest block content
raw_earned, raw_possible, weighted_earned, weighted_possible, first_attempted = (
_get_score_from_submissions(submissions_scores, block) or
_get_score_from_csm(csm_scores, block, weight) or
_get_score_from_persisted_or_latest_block(persisted_block, block, weight)
)
# TODO: Remove as part of EDUCATOR-4602.
if str(block.location.course_key) == 'course-v1:UQx+BUSLEAD5x+2T2019':
log.info('Calculated raw-earned: {}, raw_possible: {}, weighted_earned: '
'{}, weighted_possible: {}, first_attempted: {} for block: ***{}***.'
.format(raw_earned, raw_possible, weighted_earned,
weighted_possible, first_attempted, str(block.location)))
if weighted_possible is None or weighted_earned is None:
return None
else:
has_valid_denominator = weighted_possible > 0.0
graded = _get_graded_from_block(persisted_block, block) if has_valid_denominator else False
return ProblemScore(
raw_earned,
raw_possible,
weighted_earned,
weighted_possible,
weight,
graded,
first_attempted=first_attempted,
)
def weighted_score(raw_earned, raw_possible, weight):
"""
Returns a tuple that represents the weighted (earned, possible) score.
If weight is None or raw_possible is 0, returns the original values.
When weight is used, it defines the weighted_possible. This allows
course authors to specify the exact maximum value for a problem when
they provide a weight.
"""
assert raw_possible is not None
cannot_compute_with_weight = weight is None or raw_possible == 0
if cannot_compute_with_weight:
return raw_earned, raw_possible
else:
return float(raw_earned) * weight / raw_possible, float(weight)
def compute_percent(earned, possible):
"""
Returns the percentage of the given earned and possible values.
"""
if possible > 0:
# Rounds to two decimal places.
return around(earned / possible, decimals=2)
else:
return 0.0
def _get_score_from_submissions(submissions_scores, block):
"""
Returns the score values from the submissions API if found.
"""
if submissions_scores:
submission_value = submissions_scores.get(str(block.location))
if submission_value:
first_attempted = submission_value['created_at']
weighted_earned = submission_value['points_earned']
weighted_possible = submission_value['points_possible']
assert weighted_earned >= 0.0 and weighted_possible > 0.0 # per contract from submissions API
return (None, None) + (weighted_earned, weighted_possible) + (first_attempted,)
def _get_score_from_csm(csm_scores, block, weight):
"""
Returns the score values from the courseware student module, via
ScoresClient, if found.
"""
# If an entry exists and has raw_possible (total) associated with it, we trust
# that value. This is important for cases where a student might have seen an
# older version of the problem -- they're still graded on what was possible
# when they tried the problem, not what it's worth now.
#
# Note: Storing raw_possible in CSM predates the implementation of the grades
# own persistence layer. Hence, we have duplicate storage locations for
# raw_possible, with potentially conflicting values, when a problem is
# attempted. Even though the CSM persistence for this value is now
# superfluous, for backward compatibility, we continue to use its value for
# raw_possible, giving it precedence over the one in the grades data model.
score = csm_scores.get(block.location)
has_valid_score = score and score.total is not None
if has_valid_score:
if score.correct is not None:
first_attempted = score.created
raw_earned = score.correct
else:
first_attempted = None
raw_earned = 0.0
raw_possible = score.total
return (raw_earned, raw_possible) + weighted_score(raw_earned, raw_possible, weight) + (first_attempted,)
def _get_score_from_persisted_or_latest_block(persisted_block, block, weight):
"""
Returns the score values, now assuming the earned score is 0.0 - since a
score was not found in an earlier storage.
Uses the raw_possible value from the persisted_block if found, else from
the latest block content.
"""
# TODO: Remove as part of EDUCATOR-4602.
if str(block.location.course_key) == 'course-v1:UQx+BUSLEAD5x+2T2019':
log.info('Using _get_score_from_persisted_or_latest_block to calculate score for block: ***{}***.'.format(
str(block.location)
))
raw_earned = 0.0
first_attempted = None
if persisted_block:
raw_possible = persisted_block.raw_possible
else:
raw_possible = block.transformer_data[GradesTransformer].max_score
# TODO: Remove as part of EDUCATOR-4602.
if str(block.location.course_key) == 'course-v1:UQx+BUSLEAD5x+2T2019':
log.info('Using latest block content to calculate score for block: ***{}***.')
log.info(f'weight for block: ***{str(block.location)}*** is {raw_possible}.')
# TODO TNL-5982 remove defensive code for scorables without max_score
if raw_possible is None:
weighted_scores = (None, None)
else:
weighted_scores = weighted_score(raw_earned, raw_possible, weight)
return (raw_earned, raw_possible) + weighted_scores + (first_attempted,)
def _get_weight_from_block(persisted_block, block):
"""
Returns the weighted value from the persisted_block if found, else from
the latest block content.
"""
if persisted_block:
return persisted_block.weight
else:
return getattr(block, 'weight', None)
def _get_graded_from_block(persisted_block, block):
"""
Returns the graded value from the persisted_block if found, else from
the latest block content.
"""
if persisted_block:
return persisted_block.graded
else:
return _get_explicit_graded(block)
def _get_explicit_graded(block):
"""
Returns the explicit graded field value for the given block.
"""
field_value = getattr(
block.transformer_data[GradesTransformer],
GradesTransformer.EXPLICIT_GRADED_FIELD_NAME,
None,
)
# Set to True if grading is not explicitly disabled for
# this block. This allows us to include the block's score
# in the aggregated self.graded_total, regardless of the
# inherited graded value from the subsection. (TNL-5560)
return True if field_value is None else field_value
@process_cached
def _block_types_possibly_scored():
"""
Returns the block types that could have a score.
Something might be a scored item if it is capable of storing a score
(has_score=True). We also have to include anything that can have children,
since those children might have scores. We can avoid things like Videos,
which have state but cannot ever impact someone's grade.
"""
return frozenset(
category for (category, xblock_class) in XBlock.load_classes() if (
getattr(xblock_class, 'has_score', False) or getattr(xblock_class, 'has_children', False)
)
)
| [
"[email protected]"
] | |
d0ece7f20306187b9863262eb39d15656ad4555d | 52c7ad17f4be984038ab387448e459eabbda49ea | /authApp/models/user.py | c02c994ade6794e906868b31e400351b545d5bdd | [] | no_license | DavidCastro88/ProyectoG3MinTicLamarca | 0f1c755352a364b8ebaf69ae526d3b921a8c32da | e18d734c0fe9719f21866b730ac7c97e76ba6518 | refs/heads/main | 2023-08-26T15:21:37.521615 | 2021-11-08T15:18:37 | 2021-11-08T15:18:37 | 414,810,529 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,565 | py | from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.contrib.auth.hashers import make_password
class UserManager(BaseUserManager):
def create_user(self, username, password=None):
"""
Creates and saves a user with the given username and password.
"""
if not username:
raise ValueError('Users must have an username')
user = self.model(username=username)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, password):
"""
Creates and saves a superuser with the given username and password.
"""
user = self.create_user(
username=username,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
id = models.BigAutoField(primary_key=True)
username = models.CharField('Username', max_length = 15, unique=True)
password = models.CharField('Password', max_length = 256)
name = models.CharField('Name', max_length = 30)
email = models.EmailField('Email', max_length = 100)
cellphone = models.CharField('Cellphone', max_length =15, default="NONE")
def save(self, **kwargs):
some_salt = 'mMUj0DrIK6vgtdIYepkIxN'
self.password = make_password(self.password, some_salt)
super().save(**kwargs)
objects = UserManager()
USERNAME_FIELD = 'username' | [
"[email protected]"
] | |
d72f89aa4b1d9d12ecb32034365378c5cf8a0232 | 9c22ec3666da0d84b51a40d1ad0167ea485647c3 | /models/tf_mlp.py | 6d567ab89a7091e84c4148a203aac7a78a2e593a | [
"Apache-2.0"
] | permissive | ihaeyong/tf-example-models | 9bca0da58330b24903f4b0d643dbfe79d9621c6e | 40b32991a76cb8d7201f9a5851789847db310b79 | refs/heads/master | 2020-04-08T14:38:30.100115 | 2018-05-31T12:39:26 | 2018-05-31T12:39:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,148 | py | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
LOCAL_FOLDER = "MNIST_data/"
IMAGE_PIXELS = 784
NUM_CLASSES = 10
HIDDEN1_UNITS = 500
HIDDEN2_UNITS = 300
LEARNING_RATE = 1e-4
TRAINING_STEPS = 2000
BATCH_SIZE = 100
def dense_layer(x, in_dim, out_dim, layer_name, act):
"""Creates a single densely connected layer of a NN"""
with tf.name_scope(layer_name):
# layer weights corresponding to the input / output dimensions
weights = tf.Variable(
tf.truncated_normal(
[in_dim, out_dim],
stddev=1.0 / tf.sqrt(float(out_dim))
), name="weights"
)
# layer biases corresponding to output dimension
biases = tf.Variable(tf.zeros([out_dim]), name="biases")
# layer activations applied to Wx+b
layer = act(tf.matmul(x, weights) + biases, name="activations")
return layer
# PREPARING DATA
# downloading (on first run) and extracting MNIST data
data = input_data.read_data_sets(LOCAL_FOLDER, one_hot=True, validation_size=0)
# BUILDING COMPUTATIONAL GRAPH
# model inputs: input pixels and targets
input = tf.placeholder(tf.float32, [None, IMAGE_PIXELS], name="input")
targets = tf.placeholder(tf.float32, [None, NUM_CLASSES], name="targets")
# network layers: two hidden and one output
hidden1 = dense_layer(input, IMAGE_PIXELS, HIDDEN1_UNITS, "hidden1", act=tf.nn.relu)
hidden2 = dense_layer(hidden1, HIDDEN1_UNITS, HIDDEN2_UNITS, "hidden2", act=tf.nn.relu)
output = dense_layer(hidden2, HIDDEN2_UNITS, NUM_CLASSES, "output", act=tf.identity)
# loss function: cross-entropy with built-in
# (stable) computation of softmax from logits
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(
labels=targets, logits=output
)
)
# training algorithm: Adam with configurable learning rate
train_step = tf.train.AdamOptimizer(LEARNING_RATE).minimize(cross_entropy)
# evaluation operation: ratio of correct predictions
correct_prediction = tf.equal(tf.argmax(output, 1), tf.argmax(targets, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# RUNNING COMPUTATIONAL GRAPH
# creating session
sess = tf.InteractiveSession()
# initializing trainable variables
sess.run(tf.global_variables_initializer())
# training loop
for step in range(TRAINING_STEPS):
# fetching next batch of training data
batch_xs, batch_ys = data.train.next_batch(BATCH_SIZE)
if step % 100 == 0:
# reporting current accuracy of the model on every 100th batch
batch_accuracy = sess.run(accuracy, feed_dict={input: batch_xs, targets: batch_ys})
print("{0}:\tbatch accuracy {1:.2f}".format(step, batch_accuracy))
# running the training step with the fetched batch
sess.run(train_step, feed_dict={input: batch_xs, targets: batch_ys})
# evaluating model prediction accuracy of the model on the test set
test_accuracy = sess.run(accuracy, feed_dict={input: data.test.images, targets: data.test.labels})
print("-------------------------------------------------")
print("Test set accuracy: {0:.4f}".format(test_accuracy))
| [
"[email protected]"
] | |
1fb01961e84f5053db377ba87858c99906099bdd | 2481cde6506743565dff2b405a2396daf208ab3e | /src/notification/migrations/0022_auto_20220110_0112.py | 336ca943dcffebbbf325cf2160bde50efe6cce2d | [
"Apache-2.0"
] | permissive | aropan/clist | 4819a3036d179595e4df8c646aff2ed593b9dad3 | 5c805b2af71acee97f993f19d8d4e229f7f5b411 | refs/heads/master | 2023-08-31T11:15:17.987776 | 2023-08-27T21:51:14 | 2023-08-27T21:52:16 | 187,111,853 | 276 | 35 | Apache-2.0 | 2023-09-06T18:42:53 | 2019-05-16T22:57:03 | Python | UTF-8 | Python | false | false | 1,360 | py | # Generated by Django 3.1.14 on 2022-01-10 01:12
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('true_coders', '0047_coder_is_virtual'),
('notification', '0021_auto_20220110_0109'),
]
operations = [
migrations.CreateModel(
name='NotificationMessage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True, db_index=True)),
('modified', models.DateTimeField(auto_now=True, db_index=True)),
('message', models.TextField()),
('level', models.TextField(null=True)),
('is_read', models.BooleanField(default=False)),
('read_at', models.DateTimeField(blank=True, null=True)),
('to', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages_set', to='true_coders.coder')),
],
),
migrations.DeleteModel(
name='Message',
),
migrations.AddIndex(
model_name='notificationmessage',
index=models.Index(fields=['to', 'is_read'], name='notificatio_to_id_f43ab7_idx'),
),
]
| [
"[email protected]"
] | |
7a2f26c9fa94c65e34fe91f092289ad81c01b001 | 0cd93652202e105f8aed68092510482c28977358 | /base/kml.py | f1a1d812b30c0d862cdf76fe5376a0d92b1a7569 | [] | no_license | xuejiekun/sky | b9cddb3775a17d757078b52f1194e1f3b4195d93 | 6d69eeb9ba3994f25a9c5c4b2c16bc0a9483e3ee | refs/heads/master | 2020-03-23T20:02:31.124053 | 2018-08-20T10:07:49 | 2018-08-20T10:07:49 | 142,017,448 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,280 | py | # -*- coding: utf-8 -*-
from lxml import etree
from pykml.factory import KML_ElementMaker as KML
class KmlMaker:
def __init__(self):
self.pm_list = []
self.fld = None
# 创建 <Placemark> 节点, 并追加到pm_list
def bulid_pm(self, address_name, lng, lat):
coor = '{},{}'.format(lng, lat)
pm = KML.Placemark(
KML.name(address_name),
KML.Point(
KML.coordinates(coor)
)
)
self.pm_list.append(pm)
return pm
# 获取list(<Placemark>)
def get_pm_list(self):
return self.pm_list
# 创建 <Folder> 节点
def get_fld(self):
if not self.pm_list:
return None
self.fld = KML.Folder(self.pm_list[0])
for pm in self.pm_list[1:]:
self.fld.append(pm)
return self.fld
# 生成kml文件
def build_kml(self, filename):
if self.get_fld() is None:
return
content = etree.tostring(self.fld, pretty_print=True)
with open(filename, 'wb') as fp:
fp.write(content)
if __name__ == '__main__':
p = KmlMaker()
p.bulid_pm('地址1', 113.45678, 22.34567)
p.bulid_pm('地址2', -113.45678, -22.34567)
p.build_kml('1.kml')
| [
"[email protected]"
] | |
a2de05b6487902033f547e9704b8d3061cd021a5 | 995514f414eee6bbe9083ec39ecd3027cf9fd7d8 | /2.4/19/percplot.py | ab33f0b3ed89a43616b8303be70d80b33e966bd2 | [] | no_license | j16949/Programming-in-Python-princeton | e02376ebb714264a1329aacad30347e4ae79f909 | 392391b98815cc1ae2b49e1057a10bc5b37e801f | refs/heads/master | 2023-08-08T11:52:04.362780 | 2023-08-01T13:02:41 | 2023-08-01T13:02:41 | 313,943,770 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,381 | py | #-----------------------------------------------------------------------
# percplot.py
#-----------------------------------------------------------------------
import sys
import stddraw
import estimate
#-----------------------------------------------------------------------
# Plot to standard draw a graph within the interval [x0, x1] from
# (x0, y0) to (x1, y1) that relates site vacancy probabilities to
# percolation probabilities.
def curve(n, x0, y0, x1, y1, trials=1000, gap=.05, err=.0025):
xm = (x0 + x1) / 2.0
ym = (y0 + y1) / 2.0
fxm = estimate.evaluate(n, xm, trials)
if (x1 - x0 < gap) or (abs(ym - fxm) < err):
stddraw.line(x0, y0, x1, y1)
stddraw.show(0.0)
return
curve(n, x0, y0, xm, fxm)
stddraw.filledCircle(xm, fxm, .005)
stddraw.show(0.0)
curve(n, xm, fxm, x1, y1)
#-----------------------------------------------------------------------
# Accept integer n as a command-line argument. Plot to standard draw
# a graph that relates site vacancy probability (control variable) to
# percolation probability (experimental observations) for a
# n-by-n system.
n = int(sys.argv[1])
stddraw.setPenRadius(0.0)
curve(n, 0.0, 0.0, 1.0, 1.0)
stddraw.line(.5,0,.5,1)
stddraw.show()
#-----------------------------------------------------------------------
# python percplot.py 20
# python percplot.py 100
| [
"[email protected]"
] | |
e9ba3889c0184468de51e855a62ad899ac1f3615 | fbbe424559f64e9a94116a07eaaa555a01b0a7bb | /Shapely_numpy/source/numpy/core/tests/test_half.py | 56b574ae8183e697ee30e9afee723f9f919664a9 | [
"MIT"
] | permissive | ryfeus/lambda-packs | 6544adb4dec19b8e71d75c24d8ed789b785b0369 | cabf6e4f1970dc14302f87414f170de19944bac2 | refs/heads/master | 2022-12-07T16:18:52.475504 | 2022-11-29T13:35:35 | 2022-11-29T13:35:35 | 71,386,735 | 1,283 | 263 | MIT | 2022-11-26T05:02:14 | 2016-10-19T18:22:39 | Python | UTF-8 | Python | false | false | 18,534 | py | from __future__ import division, absolute_import, print_function
import platform
import numpy as np
from numpy import uint16, float16, float32, float64
from numpy.testing import TestCase, run_module_suite, assert_, assert_equal, \
dec
def assert_raises_fpe(strmatch, callable, *args, **kwargs):
try:
callable(*args, **kwargs)
except FloatingPointError as exc:
assert_(str(exc).find(strmatch) >= 0,
"Did not raise floating point %s error" % strmatch)
else:
assert_(False,
"Did not raise floating point %s error" % strmatch)
class TestHalf(TestCase):
def setUp(self):
# An array of all possible float16 values
self.all_f16 = np.arange(0x10000, dtype=uint16)
self.all_f16.dtype = float16
self.all_f32 = np.array(self.all_f16, dtype=float32)
self.all_f64 = np.array(self.all_f16, dtype=float64)
# An array of all non-NaN float16 values, in sorted order
self.nonan_f16 = np.concatenate(
(np.arange(0xfc00, 0x7fff, -1, dtype=uint16),
np.arange(0x0000, 0x7c01, 1, dtype=uint16)))
self.nonan_f16.dtype = float16
self.nonan_f32 = np.array(self.nonan_f16, dtype=float32)
self.nonan_f64 = np.array(self.nonan_f16, dtype=float64)
# An array of all finite float16 values, in sorted order
self.finite_f16 = self.nonan_f16[1:-1]
self.finite_f32 = self.nonan_f32[1:-1]
self.finite_f64 = self.nonan_f64[1:-1]
def test_half_conversions(self):
"""Checks that all 16-bit values survive conversion
to/from 32-bit and 64-bit float"""
# Because the underlying routines preserve the NaN bits, every
# value is preserved when converting to/from other floats.
# Convert from float32 back to float16
b = np.array(self.all_f32, dtype=float16)
assert_equal(self.all_f16.view(dtype=uint16),
b.view(dtype=uint16))
# Convert from float64 back to float16
b = np.array(self.all_f64, dtype=float16)
assert_equal(self.all_f16.view(dtype=uint16),
b.view(dtype=uint16))
# Convert float16 to longdouble and back
# This doesn't necessarily preserve the extra NaN bits,
# so exclude NaNs.
a_ld = np.array(self.nonan_f16, dtype=np.longdouble)
b = np.array(a_ld, dtype=float16)
assert_equal(self.nonan_f16.view(dtype=uint16),
b.view(dtype=uint16))
# Check the range for which all integers can be represented
i_int = np.arange(-2048, 2049)
i_f16 = np.array(i_int, dtype=float16)
j = np.array(i_f16, dtype=np.int)
assert_equal(i_int, j)
def test_nans_infs(self):
with np.errstate(all='ignore'):
# Check some of the ufuncs
assert_equal(np.isnan(self.all_f16), np.isnan(self.all_f32))
assert_equal(np.isinf(self.all_f16), np.isinf(self.all_f32))
assert_equal(np.isfinite(self.all_f16), np.isfinite(self.all_f32))
assert_equal(np.signbit(self.all_f16), np.signbit(self.all_f32))
assert_equal(np.spacing(float16(65504)), np.inf)
# Check comparisons of all values with NaN
nan = float16(np.nan)
assert_(not (self.all_f16 == nan).any())
assert_(not (nan == self.all_f16).any())
assert_((self.all_f16 != nan).all())
assert_((nan != self.all_f16).all())
assert_(not (self.all_f16 < nan).any())
assert_(not (nan < self.all_f16).any())
assert_(not (self.all_f16 <= nan).any())
assert_(not (nan <= self.all_f16).any())
assert_(not (self.all_f16 > nan).any())
assert_(not (nan > self.all_f16).any())
assert_(not (self.all_f16 >= nan).any())
assert_(not (nan >= self.all_f16).any())
def test_half_values(self):
"""Confirms a small number of known half values"""
a = np.array([1.0, -1.0,
2.0, -2.0,
0.0999755859375, 0.333251953125, # 1/10, 1/3
65504, -65504, # Maximum magnitude
2.0**(-14), -2.0**(-14), # Minimum normal
2.0**(-24), -2.0**(-24), # Minimum subnormal
0, -1/1e1000, # Signed zeros
np.inf, -np.inf])
b = np.array([0x3c00, 0xbc00,
0x4000, 0xc000,
0x2e66, 0x3555,
0x7bff, 0xfbff,
0x0400, 0x8400,
0x0001, 0x8001,
0x0000, 0x8000,
0x7c00, 0xfc00], dtype=uint16)
b.dtype = float16
assert_equal(a, b)
def test_half_rounding(self):
"""Checks that rounding when converting to half is correct"""
a = np.array([2.0**-25 + 2.0**-35, # Rounds to minimum subnormal
2.0**-25, # Underflows to zero (nearest even mode)
2.0**-26, # Underflows to zero
1.0+2.0**-11 + 2.0**-16, # rounds to 1.0+2**(-10)
1.0+2.0**-11, # rounds to 1.0 (nearest even mode)
1.0+2.0**-12, # rounds to 1.0
65519, # rounds to 65504
65520], # rounds to inf
dtype=float64)
rounded = [2.0**-24,
0.0,
0.0,
1.0+2.0**(-10),
1.0,
1.0,
65504,
np.inf]
# Check float64->float16 rounding
b = np.array(a, dtype=float16)
assert_equal(b, rounded)
# Check float32->float16 rounding
a = np.array(a, dtype=float32)
b = np.array(a, dtype=float16)
assert_equal(b, rounded)
def test_half_correctness(self):
"""Take every finite float16, and check the casting functions with
a manual conversion."""
# Create an array of all finite float16s
a_bits = self.finite_f16.view(dtype=uint16)
# Convert to 64-bit float manually
a_sgn = (-1.0)**((a_bits & 0x8000) >> 15)
a_exp = np.array((a_bits & 0x7c00) >> 10, dtype=np.int32) - 15
a_man = (a_bits & 0x03ff) * 2.0**(-10)
# Implicit bit of normalized floats
a_man[a_exp != -15] += 1
# Denormalized exponent is -14
a_exp[a_exp == -15] = -14
a_manual = a_sgn * a_man * 2.0**a_exp
a32_fail = np.nonzero(self.finite_f32 != a_manual)[0]
if len(a32_fail) != 0:
bad_index = a32_fail[0]
assert_equal(self.finite_f32, a_manual,
"First non-equal is half value %x -> %g != %g" %
(self.finite_f16[bad_index],
self.finite_f32[bad_index],
a_manual[bad_index]))
a64_fail = np.nonzero(self.finite_f64 != a_manual)[0]
if len(a64_fail) != 0:
bad_index = a64_fail[0]
assert_equal(self.finite_f64, a_manual,
"First non-equal is half value %x -> %g != %g" %
(self.finite_f16[bad_index],
self.finite_f64[bad_index],
a_manual[bad_index]))
def test_half_ordering(self):
"""Make sure comparisons are working right"""
# All non-NaN float16 values in reverse order
a = self.nonan_f16[::-1].copy()
# 32-bit float copy
b = np.array(a, dtype=float32)
# Should sort the same
a.sort()
b.sort()
assert_equal(a, b)
# Comparisons should work
assert_((a[:-1] <= a[1:]).all())
assert_(not (a[:-1] > a[1:]).any())
assert_((a[1:] >= a[:-1]).all())
assert_(not (a[1:] < a[:-1]).any())
# All != except for +/-0
assert_equal(np.nonzero(a[:-1] < a[1:])[0].size, a.size-2)
assert_equal(np.nonzero(a[1:] > a[:-1])[0].size, a.size-2)
def test_half_funcs(self):
"""Test the various ArrFuncs"""
# fill
assert_equal(np.arange(10, dtype=float16),
np.arange(10, dtype=float32))
# fillwithscalar
a = np.zeros((5,), dtype=float16)
a.fill(1)
assert_equal(a, np.ones((5,), dtype=float16))
# nonzero and copyswap
a = np.array([0, 0, -1, -1/1e20, 0, 2.0**-24, 7.629e-6], dtype=float16)
assert_equal(a.nonzero()[0],
[2, 5, 6])
a = a.byteswap().newbyteorder()
assert_equal(a.nonzero()[0],
[2, 5, 6])
# dot
a = np.arange(0, 10, 0.5, dtype=float16)
b = np.ones((20,), dtype=float16)
assert_equal(np.dot(a, b),
95)
# argmax
a = np.array([0, -np.inf, -2, 0.5, 12.55, 7.3, 2.1, 12.4], dtype=float16)
assert_equal(a.argmax(),
4)
a = np.array([0, -np.inf, -2, np.inf, 12.55, np.nan, 2.1, 12.4], dtype=float16)
assert_equal(a.argmax(),
5)
# getitem
a = np.arange(10, dtype=float16)
for i in range(10):
assert_equal(a.item(i), i)
def test_spacing_nextafter(self):
"""Test np.spacing and np.nextafter"""
# All non-negative finite #'s
a = np.arange(0x7c00, dtype=uint16)
hinf = np.array((np.inf,), dtype=float16)
a_f16 = a.view(dtype=float16)
assert_equal(np.spacing(a_f16[:-1]), a_f16[1:]-a_f16[:-1])
assert_equal(np.nextafter(a_f16[:-1], hinf), a_f16[1:])
assert_equal(np.nextafter(a_f16[0], -hinf), -a_f16[1])
assert_equal(np.nextafter(a_f16[1:], -hinf), a_f16[:-1])
# switch to negatives
a |= 0x8000
assert_equal(np.spacing(a_f16[0]), np.spacing(a_f16[1]))
assert_equal(np.spacing(a_f16[1:]), a_f16[:-1]-a_f16[1:])
assert_equal(np.nextafter(a_f16[0], hinf), -a_f16[1])
assert_equal(np.nextafter(a_f16[1:], hinf), a_f16[:-1])
assert_equal(np.nextafter(a_f16[:-1], -hinf), a_f16[1:])
def test_half_ufuncs(self):
"""Test the various ufuncs"""
a = np.array([0, 1, 2, 4, 2], dtype=float16)
b = np.array([-2, 5, 1, 4, 3], dtype=float16)
c = np.array([0, -1, -np.inf, np.nan, 6], dtype=float16)
assert_equal(np.add(a, b), [-2, 6, 3, 8, 5])
assert_equal(np.subtract(a, b), [2, -4, 1, 0, -1])
assert_equal(np.multiply(a, b), [0, 5, 2, 16, 6])
assert_equal(np.divide(a, b), [0, 0.199951171875, 2, 1, 0.66650390625])
assert_equal(np.equal(a, b), [False, False, False, True, False])
assert_equal(np.not_equal(a, b), [True, True, True, False, True])
assert_equal(np.less(a, b), [False, True, False, False, True])
assert_equal(np.less_equal(a, b), [False, True, False, True, True])
assert_equal(np.greater(a, b), [True, False, True, False, False])
assert_equal(np.greater_equal(a, b), [True, False, True, True, False])
assert_equal(np.logical_and(a, b), [False, True, True, True, True])
assert_equal(np.logical_or(a, b), [True, True, True, True, True])
assert_equal(np.logical_xor(a, b), [True, False, False, False, False])
assert_equal(np.logical_not(a), [True, False, False, False, False])
assert_equal(np.isnan(c), [False, False, False, True, False])
assert_equal(np.isinf(c), [False, False, True, False, False])
assert_equal(np.isfinite(c), [True, True, False, False, True])
assert_equal(np.signbit(b), [True, False, False, False, False])
assert_equal(np.copysign(b, a), [2, 5, 1, 4, 3])
assert_equal(np.maximum(a, b), [0, 5, 2, 4, 3])
x = np.maximum(b, c)
assert_(np.isnan(x[3]))
x[3] = 0
assert_equal(x, [0, 5, 1, 0, 6])
assert_equal(np.minimum(a, b), [-2, 1, 1, 4, 2])
x = np.minimum(b, c)
assert_(np.isnan(x[3]))
x[3] = 0
assert_equal(x, [-2, -1, -np.inf, 0, 3])
assert_equal(np.fmax(a, b), [0, 5, 2, 4, 3])
assert_equal(np.fmax(b, c), [0, 5, 1, 4, 6])
assert_equal(np.fmin(a, b), [-2, 1, 1, 4, 2])
assert_equal(np.fmin(b, c), [-2, -1, -np.inf, 4, 3])
assert_equal(np.floor_divide(a, b), [0, 0, 2, 1, 0])
assert_equal(np.remainder(a, b), [0, 1, 0, 0, 2])
assert_equal(np.square(b), [4, 25, 1, 16, 9])
assert_equal(np.reciprocal(b), [-0.5, 0.199951171875, 1, 0.25, 0.333251953125])
assert_equal(np.ones_like(b), [1, 1, 1, 1, 1])
assert_equal(np.conjugate(b), b)
assert_equal(np.absolute(b), [2, 5, 1, 4, 3])
assert_equal(np.negative(b), [2, -5, -1, -4, -3])
assert_equal(np.sign(b), [-1, 1, 1, 1, 1])
assert_equal(np.modf(b), ([0, 0, 0, 0, 0], b))
assert_equal(np.frexp(b), ([-0.5, 0.625, 0.5, 0.5, 0.75], [2, 3, 1, 3, 2]))
assert_equal(np.ldexp(b, [0, 1, 2, 4, 2]), [-2, 10, 4, 64, 12])
def test_half_coercion(self):
"""Test that half gets coerced properly with the other types"""
a16 = np.array((1,), dtype=float16)
a32 = np.array((1,), dtype=float32)
b16 = float16(1)
b32 = float32(1)
assert_equal(np.power(a16, 2).dtype, float16)
assert_equal(np.power(a16, 2.0).dtype, float16)
assert_equal(np.power(a16, b16).dtype, float16)
assert_equal(np.power(a16, b32).dtype, float16)
assert_equal(np.power(a16, a16).dtype, float16)
assert_equal(np.power(a16, a32).dtype, float32)
assert_equal(np.power(b16, 2).dtype, float64)
assert_equal(np.power(b16, 2.0).dtype, float64)
assert_equal(np.power(b16, b16).dtype, float16)
assert_equal(np.power(b16, b32).dtype, float32)
assert_equal(np.power(b16, a16).dtype, float16)
assert_equal(np.power(b16, a32).dtype, float32)
assert_equal(np.power(a32, a16).dtype, float32)
assert_equal(np.power(a32, b16).dtype, float32)
assert_equal(np.power(b32, a16).dtype, float16)
assert_equal(np.power(b32, b16).dtype, float32)
@dec.skipif(platform.machine() == "armv5tel", "See gh-413.")
def test_half_fpe(self):
with np.errstate(all='raise'):
sx16 = np.array((1e-4,), dtype=float16)
bx16 = np.array((1e4,), dtype=float16)
sy16 = float16(1e-4)
by16 = float16(1e4)
# Underflow errors
assert_raises_fpe('underflow', lambda a, b:a*b, sx16, sx16)
assert_raises_fpe('underflow', lambda a, b:a*b, sx16, sy16)
assert_raises_fpe('underflow', lambda a, b:a*b, sy16, sx16)
assert_raises_fpe('underflow', lambda a, b:a*b, sy16, sy16)
assert_raises_fpe('underflow', lambda a, b:a/b, sx16, bx16)
assert_raises_fpe('underflow', lambda a, b:a/b, sx16, by16)
assert_raises_fpe('underflow', lambda a, b:a/b, sy16, bx16)
assert_raises_fpe('underflow', lambda a, b:a/b, sy16, by16)
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(2.**-14), float16(2**11))
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(-2.**-14), float16(2**11))
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(2.**-14+2**-24), float16(2))
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(-2.**-14-2**-24), float16(2))
assert_raises_fpe('underflow', lambda a, b:a/b,
float16(2.**-14+2**-23), float16(4))
# Overflow errors
assert_raises_fpe('overflow', lambda a, b:a*b, bx16, bx16)
assert_raises_fpe('overflow', lambda a, b:a*b, bx16, by16)
assert_raises_fpe('overflow', lambda a, b:a*b, by16, bx16)
assert_raises_fpe('overflow', lambda a, b:a*b, by16, by16)
assert_raises_fpe('overflow', lambda a, b:a/b, bx16, sx16)
assert_raises_fpe('overflow', lambda a, b:a/b, bx16, sy16)
assert_raises_fpe('overflow', lambda a, b:a/b, by16, sx16)
assert_raises_fpe('overflow', lambda a, b:a/b, by16, sy16)
assert_raises_fpe('overflow', lambda a, b:a+b,
float16(65504), float16(17))
assert_raises_fpe('overflow', lambda a, b:a-b,
float16(-65504), float16(17))
assert_raises_fpe('overflow', np.nextafter, float16(65504), float16(np.inf))
assert_raises_fpe('overflow', np.nextafter, float16(-65504), float16(-np.inf))
assert_raises_fpe('overflow', np.spacing, float16(65504))
# Invalid value errors
assert_raises_fpe('invalid', np.divide, float16(np.inf), float16(np.inf))
assert_raises_fpe('invalid', np.spacing, float16(np.inf))
assert_raises_fpe('invalid', np.spacing, float16(np.nan))
assert_raises_fpe('invalid', np.nextafter, float16(np.inf), float16(0))
assert_raises_fpe('invalid', np.nextafter, float16(-np.inf), float16(0))
assert_raises_fpe('invalid', np.nextafter, float16(0), float16(np.nan))
# These should not raise
float16(65472)+float16(32)
float16(2**-13)/float16(2)
float16(2**-14)/float16(2**10)
np.spacing(float16(-65504))
np.nextafter(float16(65504), float16(-np.inf))
np.nextafter(float16(-65504), float16(np.inf))
float16(2**-14)/float16(2**10)
float16(-2**-14)/float16(2**10)
float16(2**-14+2**-23)/float16(2)
float16(-2**-14-2**-23)/float16(2)
def test_half_array_interface(self):
"""Test that half is compatible with __array_interface__"""
class Dummy:
pass
a = np.ones((1,), dtype=float16)
b = Dummy()
b.__array_interface__ = a.__array_interface__
c = np.array(b)
assert_(c.dtype == float16)
assert_equal(a, c)
if __name__ == "__main__":
run_module_suite()
| [
"[email protected]"
] | |
20fa77aace3853f5c71e23e3c6be7508ad320949 | 6efc2eb23678741263da7ac6bd868a9f3a37d38b | /01.stock_investment/01.corporate_analysis/test_financial_info.py | dce0c5420177e4b76fd50d68f704692953f44398 | [] | no_license | predora005/business-research | c6272b129353a302673cf8a13c1629b5ade4a50e | 96743cc6a0b592c87e6d0f2de341fc3bbb3ef3b1 | refs/heads/main | 2023-06-18T08:08:24.537951 | 2021-07-22T04:19:09 | 2021-07-22T04:19:09 | 314,985,045 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,600 | py | # coding: utf-8
from stinfo import *
##################################################
# メイン
##################################################
if __name__ == '__main__':
# matplotlibの日本語フォント設定
plt_font_init()
codes = {
'JR東日本' : 9020,
'JR東海' : 9022,
'JR西日本' : 9021,
'東急' : 9005,
'近鉄' : 9041,
}
# 指定した複数銘柄の基本情報を取得する。
df = get_financial_infos(codes)
# ROAとROEを求める
df['ROA'] = df['純利益'] / df['総資産'] * 100
df['ROE'] = df['純利益'] / df['純資産'] * 100
# 複数銘柄の決算情報を整形する
df = reshape_financial_info(df)
print(df)
# ROEとROAを可視化する
visualize_financial_info_in_bar(df, 'ROE', 'roe.png')
visualize_financial_info_in_bar(df, 'ROA', 'roa.png')
# ROEとROAをセットで可視化する
visualize_roe_roa(df, 'roe_roa.png')
# 決算情報のうち指定した複数データを可視化する
visualize_financial_infos_in_line(df, ['自己資本率'], 'test1.png', from_zero=True)
visualize_financial_infos_in_line(df, ['ROA', 'ROE'], 'test2.png', from_zero=True)
visualize_financial_infos_in_line(df, ['純利益(十億円)', '総資産(十億円)', '純資産(十億円)'], 'test3.png', from_zero=True)
visualize_financial_infos_in_line(df, ['売上高(十億円)', '営業利益(十億円)', '経常利益(十億円)', '純利益(十億円)'], 'test4.png', from_zero=True)
visualize_financial_infos_in_line(df, ['営業CF(十億円)', '投資CF(十億円)', '財務CF(十億円)', '現金期末残高(十億円)'], 'test5.png', from_zero=False)
# 決算情報のうち指定した1銘柄の指定データを可視化する
##############################
# JR東日本
visualize_financial_info_for_specified_brand(
df, 'JR東日本', bar_datas=['営業利益(十億円)', '経常利益(十億円)', '純利益(十億円)'],
line_datas=['売上高(十億円)'], filepath='jr_east_pl.png')
visualize_financial_info_for_specified_brand(
df, 'JR東日本', bar_datas=['総資産(十億円)', '純資産(十億円)'],
line_datas=['ROA'], filepath='jr_east_bs.png')
visualize_financial_info_for_specified_brand(
df, 'JR東日本', bar_datas=['営業CF(十億円)', '投資CF(十億円)', '財務CF(十億円)'],
line_datas=['現金期末残高(十億円)'], filepath='jr_east_cf.png')
##############################
# JR東海
visualize_financial_info_for_specified_brand(
df, 'JR東海', bar_datas=['営業利益(十億円)', '経常利益(十億円)', '純利益(十億円)'],
line_datas=['売上高(十億円)'], filepath='jr_central_pl.png')
visualize_financial_info_for_specified_brand(
df, 'JR東海', bar_datas=['総資産(十億円)', '純資産(十億円)'],
line_datas=['ROA'], filepath='jr_central_bs.png')
visualize_financial_info_for_specified_brand(
df, 'JR東海', bar_datas=['営業CF(十億円)', '投資CF(十億円)', '財務CF(十億円)'],
line_datas=['現金期末残高(十億円)'], filepath='jr_central_cf.png')
#code = 9020
#
## 指定した証券コードの決算情報を取得する。
#df = get_financial_info(code)
#print(df)
#
## 決算情報から不要データを削る。
#df2 = trim_unnecessary_from_dataframe(df)
#print(df2)
| [
"[email protected]"
] | |
6054b7c0a200370ed5aaef9854cf3554aa123b53 | 9dac88cf52f688d7c6730f379a1eb9d607bd9d51 | /PCC8_2.py | 25bc9018de9c3a9d5022d3114b464d0c457e2907 | [] | no_license | nurack/eric-pcc-solutions | adcf5f127ea1a7d07b904558edec7a6e8c73209b | 2bc5386b2e7422645f5df9ec758777827a473786 | refs/heads/main | 2023-08-21T08:37:17.853433 | 2021-11-01T18:19:59 | 2021-11-01T18:19:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 112 | py | def favourite_book(title):
print(f"My favourite book is {title.title()}")
favourite_book('the rat eaters') | [
"[email protected]"
] | |
f5e755293a4515477c5281d9da4ce88995cdd6e7 | 6b37deabac3116e65bc869035cf8cfa50f22590c | /abc/abc197/a_rotate/main.py | 7258af0629e32643f188709c3782ab05b7c79b75 | [] | no_license | hiromichinomata/atcoder | 92122a2a2a8b9327f4c8dc0e40889e8dc0321079 | 82216622d9040e95239b4a21e973cb12e59d7f6e | refs/heads/master | 2022-10-05T04:00:44.509719 | 2022-08-14T04:46:49 | 2022-08-14T04:46:49 | 176,891,471 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 152 | py | #!/bin/python3
import sys
input = sys.stdin.readline
def main():
s = list(map(str, input().strip().split()))[0]
print(s[1] + s[2] + s[0])
main()
| [
"[email protected]"
] | |
ea2564cdc374876529e98701b0a447feb6ff2403 | 7704dfa69e81c8a2f22b4bdd2b41a1bdad86ac4a | /nailgun/nailgun/db/sqlalchemy/models/base.py | e2f797464e5e381181bfd006fd7451bde3579e9f | [
"Apache-2.0"
] | permissive | andrei4ka/fuel-web-redhat | 8614af4567d2617a8420869c068d6b1f33ddf30c | 01609fcbbae5cefcd015b6d7a0dbb181e9011c14 | refs/heads/master | 2022-10-16T01:53:59.889901 | 2015-01-23T11:00:22 | 2015-01-23T11:00:22 | 29,728,913 | 0 | 0 | Apache-2.0 | 2022-09-16T17:48:26 | 2015-01-23T10:56:45 | Python | UTF-8 | Python | false | false | 1,173 | py | # -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from datetime import datetime
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import Integer
from sqlalchemy.ext.declarative import declarative_base
from nailgun.db.sqlalchemy.models.fields import JSON
from nailgun.openstack.common.db.sqlalchemy import models
Base = declarative_base(cls=models.ModelBase)
class CapacityLog(Base):
__tablename__ = 'capacity_log'
id = Column(Integer, primary_key=True)
report = Column(JSON)
datetime = Column(DateTime, default=lambda: datetime.now())
| [
"[email protected]"
] | |
66bb050d598ed9c6d34aac08f8a02ad47aa5e985 | f659347de6f37b023b780586461886de60950a3d | /final/temp/config.py | 0e27b2b8850a4b52636303e3ee24a4b4fafd5dbd | [] | no_license | cubarco/SDN-2015 | 3acf72e09d29c087fa852e6e9c20fbc2e7332432 | e2f36cb1133cfaa60b18a658109d3854ce2440eb | refs/heads/master | 2020-12-11T06:05:30.770694 | 2015-08-26T06:25:24 | 2015-08-26T06:25:24 | 34,156,783 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 129 | py | #!/usr/bin/env python
# coding=utf8
modules_path = '/home/cubelin/Documents/sdn/2015/problems/final/modules/'
enable = ['test']
| [
"[email protected]"
] | |
7426f3c1ffb131aff189892e9dbc8c7632ac9f91 | cb0cb69914a6f9789c1c431882eb7d4911791803 | /src/motor.py | 59d7063b91f591e480e47e2d08548a4abaa83445 | [] | no_license | Nicolasgr22/venus | 4cb0acb5ff7812cc11272092bfb440131d5419c4 | 37fb473bdea0509f4fea9e8b88af31c6853ef4d2 | refs/heads/master | 2020-05-25T08:26:11.450888 | 2019-05-19T22:23:19 | 2019-05-19T22:23:19 | 187,710,164 | 0 | 0 | null | 2019-05-20T20:39:52 | 2019-05-20T20:39:52 | null | UTF-8 | Python | false | false | 509 | py | #!/usr/bin/python
import sys
import time
import RPi.GPIO as GPIO
GPIO.cleanup()
Forward=26
Backward=20
sleeptime=1
GPIO.setmode(GPIO.BCM)
GPIO.setup(Forward, GPIO.OUT)
GPIO.setup(Backward, GPIO.OUT)
def forward(x):
GPIO.output(Forward, GPIO.TRUE)
print("Moving Forward")
time.sleep(x)
GPIO.output(Forward, GPIO.FALSE)
def reverse(x):
GPIO.output(Backward, GPIO.TRUE)
print("Moving Backward")
time.sleep(x)
GPIO.output(Backward, GPIO.FALSE)
while (1):
forward(5)
reverse(5)
GPIO.cleanup()
| [
"[email protected]"
] | |
083533dc83abff57679089d9aeb640325a3e250f | 159fe0a86dbff5b16951ded77c5ad796e14b7a7b | /src/main/conf/res/scripts/showAdvice.py | 249fb1d4f5c58c7db10b2bdeed5b610694e31520 | [
"Apache-2.0"
] | permissive | juniper-project/modelling-environment | 9b023c05c2f5b3dadc40bf24bc9b92caf6387a02 | 34fa002e1beb1da25ba9de15e694cf49c2ea8d23 | refs/heads/master | 2021-01-10T09:30:53.765665 | 2015-12-03T16:17:30 | 2015-12-03T16:17:30 | 45,916,377 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,610 | py | #
# Copyright 2014 Modeliosoft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import xml.etree.ElementTree as ET
from tempfile import NamedTemporaryFile
from java.awt import Desktop
from java.io import File
def getTagValues(el, tagName):
lists = [y.getActual() for y in el.getTag() if y.getDefinition().getName() == tagName ]
values = [x.getValue() for list in lists for x in list]
return values
def getTagValue(el, tagName, default=None):
list = getTagValues(el, tagName)
if len(list)>0:
return list[0]
else:
return default
def findReferredObj(advice, attId, objId):
return [ dep.getDependsOn() for dep in advice.getDependsOnDependency() if getTagValue(dep, 'objAttId') == attId and getTagValue(dep, 'objId') == objId]
def findReferredAttachment(advice, attId):
return [attachment for attachment in advice.getOwner().getOwnedElement() if getTagValue(attachment, 'id') == attId]
# #[ dep.getDependsOn() for dep in advice.getDependsOnDependency() if getTagValue(dep, 'attId') == attId]
advice = selectedElements.get(0)
originalXML = str(advice.getDescriptor()[0].getContent())
tree = ET.fromstring(originalXML)
output = NamedTemporaryFile(suffix='.html', delete=False)
print output.name
output.write('<html>\n')
output.write('<head><title>' + advice.getName() +'</title></head>\n')
output.write('<body style="background-color: #ffffe1; font-family: verdana; font-size:12px;">\n')
def interpretElement(advice, element):
if element.tag == '{http://www.fit.vutbr.cz/homes/rychly/juniper/scheduling-advisor}objectRef':
attId = element.get('attId')
objId = element.get('objId')
refObj = findReferredObj(advice, attId, objId)
print attId, objId, refObj
if refObj:
output.write('<b>' + refObj[0].getName() + '</b>')
else:
output.write('<b>object ' + objId + ' from attachment ' + attId + '</b>')
elif element.tag == '{http://www.fit.vutbr.cz/homes/rychly/juniper/scheduling-advisor}attachmentRef':
attId = element.get('attId')
refAtt = findReferredAttachment(advice, attId)
print refAtt, attId
#output.write('<a href="')
#if refAtt:
#output.write(getTagValue(refAtt[0], 'filename', getTagValue(refAtt[0], 'id')) )
#else:
#output.write(attId)
#output.write('">')
if element.text:
output.write('<b>' + element.text + '</b>')
else:
if refAtt:
output.write(refAtt[0].getName())
else:
output.write(attId)
output.write(' (attachment)')
#output.write('</a>')
elif element.tag == '{http://www.fit.vutbr.cz/homes/rychly/juniper/scheduling-advisor}link':
output.write('<a href="'+element.get('{http://www.w3.org/1999/xlink}href')+'">' + element.text + '</a>')
for tag in tree:
if tag.tag == '{http://www.fit.vutbr.cz/homes/rychly/juniper/scheduling-advisor}problem':
output.write('<h3>Problem</h3>\n')
if tag.tag == '{http://www.fit.vutbr.cz/homes/rychly/juniper/scheduling-advisor}solution':
output.write('<h3>Solution</h3>\n')
if tag.tag == '{http://www.fit.vutbr.cz/homes/rychly/juniper/scheduling-advisor}note':
output.write('<h3>Note</h3>\n')
if tag.tag == '{http://www.fit.vutbr.cz/homes/rychly/juniper/scheduling-advisor}sources':
output.write('<h3>Sources</h3>\n')
if tag.text:
output.write(str(tag.text))
for element in tag:
interpretElement(advice, element)
if element.tail:
output.write(str(element.tail))
output.write('</body>\n')
output.write('</html>')
output.close()
from org.eclipse.jface.dialogs import PopupDialog
from org.eclipse.swt.widgets import Shell, Display
from org.eclipse.swt.browser import Browser
from org.eclipse.swt.layout import GridLayout, GridData
from org.eclipse.swt import SWT
from java.lang import Runnable
class AlertDialog(PopupDialog):
def __init__(self, advice):
PopupDialog.__init__(self,
Shell(),
PopupDialog.INFOPOPUPRESIZE_SHELLSTYLE,
True, False, True, False,
'Details about \'' + advice.getName() + '\'', 'Juniper IDE')
def createDialogArea(self, parent):
composite = self.super__createDialogArea(parent)
glayout = GridLayout(1, False)
composite.setLayout(glayout)
data = GridData(SWT.FILL, SWT.FILL, True, True);
data.widthHint = 800;
data.heightHint = 350;
composite.setLayoutData(data);
browser = Browser(composite, SWT.NONE)
browser.setUrl(File(output.name).toURI().toString())
browser.setLayoutData(GridData(SWT.FILL, SWT.FILL, True, True));
return composite
class ShowDialog(Runnable):
def __init__(self, advice):
self.advice = advice
def run(self):
AlertDialog(self.advice).open()
Display.getDefault().syncExec(ShowDialog(advice)) | [
"[email protected]"
] | |
b67377362af4d569f225ef9a8f12aa72e8327e8c | 51f887286aa3bd2c3dbe4c616ad306ce08976441 | /pybind/slxos/v17r_2_00/policy_map/class_/scheduler/strict_priority/__init__.py | c8a5ab6f9041a09b0eaf1860331977bd6d378423 | [
"Apache-2.0"
] | permissive | b2220333/pybind | a8c06460fd66a97a78c243bf144488eb88d7732a | 44c467e71b2b425be63867aba6e6fa28b2cfe7fb | refs/heads/master | 2020-03-18T09:09:29.574226 | 2018-04-03T20:09:50 | 2018-04-03T20:09:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 65,476 | py |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from decimal import Decimal
from bitarray import bitarray
import __builtin__
class strict_priority(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-qos-mqc - based on the path /policy-map/class/scheduler/strict-priority. Each member element of
the container is represented as a class variable - with a specific
YANG type.
"""
__slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__priority_number','__scheduler_type','__dwrr_traffic_class0','__dwrr_traffic_class1','__dwrr_traffic_class2','__dwrr_traffic_class3','__dwrr_traffic_class4','__dwrr_traffic_class5','__dwrr_traffic_class6','__dwrr_traffic_class_last','__TC1','__TC2','__TC3','__TC4','__TC5','__TC6','__TC7',)
_yang_name = 'strict-priority'
_rest_name = 'strict-priority'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
path_helper_ = kwargs.pop("path_helper", None)
if path_helper_ is False:
self._path_helper = False
elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper):
self._path_helper = path_helper_
elif hasattr(self, "_parent"):
path_helper_ = getattr(self._parent, "_path_helper", False)
self._path_helper = path_helper_
else:
self._path_helper = False
extmethods = kwargs.pop("extmethods", None)
if extmethods is False:
self._extmethods = False
elif extmethods is not None and isinstance(extmethods, dict):
self._extmethods = extmethods
elif hasattr(self, "_parent"):
extmethods = getattr(self._parent, "_extmethods", None)
self._extmethods = extmethods
else:
self._extmethods = False
self.__dwrr_traffic_class3 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class3", rest_name="dwrr-traffic-class3", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 4', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
self.__dwrr_traffic_class2 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class2", rest_name="dwrr-traffic-class2", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 5', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
self.__dwrr_traffic_class1 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class1", rest_name="dwrr-traffic-class1", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 6', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
self.__dwrr_traffic_class0 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class0", rest_name="dwrr-traffic-class0", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number < 7', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
self.__dwrr_traffic_class6 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class6", rest_name="dwrr-traffic-class6", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 1', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
self.__dwrr_traffic_class5 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class5", rest_name="dwrr-traffic-class5", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 2', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
self.__dwrr_traffic_class4 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class4", rest_name="dwrr-traffic-class4", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 3', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
self.__TC6 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC6", rest_name="TC6", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 1'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
self.__TC2 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC2", rest_name="TC2", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 5'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
self.__TC4 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC4", rest_name="TC4", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 3'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
self.__TC5 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC5", rest_name="TC5", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 2'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
self.__dwrr_traffic_class_last = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class-last", rest_name="dwrr-traffic-class-last", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
self.__TC3 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC3", rest_name="TC3", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 4'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
self.__TC1 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC1", rest_name="TC1", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 6'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
self.__TC7 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC7", rest_name="TC7", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 0'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
self.__scheduler_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'dwrr': {'value': 1}},), is_leaf=True, yang_name="scheduler-type", rest_name="scheduler-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='enumeration', is_config=True)
self.__priority_number = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), restriction_dict={'range': [u'0 .. 7']}), is_leaf=True, yang_name="priority-number", rest_name="priority-number", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint8', is_config=True)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path()+[self._yang_name]
else:
return [u'policy-map', u'class', u'scheduler', u'strict-priority']
def _rest_path(self):
if hasattr(self, "_parent"):
if self._rest_name:
return self._parent._rest_path()+[self._rest_name]
else:
return self._parent._rest_path()
else:
return [u'policy-map', u'class', u'scheduler', u'strict-priority']
def _get_priority_number(self):
"""
Getter method for priority_number, mapped from YANG variable /policy_map/class/scheduler/strict_priority/priority_number (uint8)
"""
return self.__priority_number
def _set_priority_number(self, v, load=False):
"""
Setter method for priority_number, mapped from YANG variable /policy_map/class/scheduler/strict_priority/priority_number (uint8)
If this variable is read-only (config: false) in the
source YANG file, then _set_priority_number is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_priority_number() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), restriction_dict={'range': [u'0 .. 7']}), is_leaf=True, yang_name="priority-number", rest_name="priority-number", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint8', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """priority_number must be of a type compatible with uint8""",
'defined-type': "uint8",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), restriction_dict={'range': [u'0 .. 7']}), is_leaf=True, yang_name="priority-number", rest_name="priority-number", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint8', is_config=True)""",
})
self.__priority_number = t
if hasattr(self, '_set'):
self._set()
def _unset_priority_number(self):
self.__priority_number = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), restriction_dict={'range': [u'0 .. 7']}), is_leaf=True, yang_name="priority-number", rest_name="priority-number", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint8', is_config=True)
def _get_scheduler_type(self):
"""
Getter method for scheduler_type, mapped from YANG variable /policy_map/class/scheduler/strict_priority/scheduler_type (enumeration)
"""
return self.__scheduler_type
def _set_scheduler_type(self, v, load=False):
"""
Setter method for scheduler_type, mapped from YANG variable /policy_map/class/scheduler/strict_priority/scheduler_type (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_scheduler_type is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_scheduler_type() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'dwrr': {'value': 1}},), is_leaf=True, yang_name="scheduler-type", rest_name="scheduler-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='enumeration', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """scheduler_type must be of a type compatible with enumeration""",
'defined-type': "brocade-qos-mqc:enumeration",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'dwrr': {'value': 1}},), is_leaf=True, yang_name="scheduler-type", rest_name="scheduler-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='enumeration', is_config=True)""",
})
self.__scheduler_type = t
if hasattr(self, '_set'):
self._set()
def _unset_scheduler_type(self):
self.__scheduler_type = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'dwrr': {'value': 1}},), is_leaf=True, yang_name="scheduler-type", rest_name="scheduler-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='enumeration', is_config=True)
def _get_dwrr_traffic_class0(self):
"""
Getter method for dwrr_traffic_class0, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class0 (uint32)
"""
return self.__dwrr_traffic_class0
def _set_dwrr_traffic_class0(self, v, load=False):
"""
Setter method for dwrr_traffic_class0, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class0 (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_dwrr_traffic_class0 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_dwrr_traffic_class0() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class0", rest_name="dwrr-traffic-class0", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number < 7', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """dwrr_traffic_class0 must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class0", rest_name="dwrr-traffic-class0", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number < 7', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)""",
})
self.__dwrr_traffic_class0 = t
if hasattr(self, '_set'):
self._set()
def _unset_dwrr_traffic_class0(self):
self.__dwrr_traffic_class0 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class0", rest_name="dwrr-traffic-class0", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number < 7', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
def _get_dwrr_traffic_class1(self):
"""
Getter method for dwrr_traffic_class1, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class1 (uint32)
"""
return self.__dwrr_traffic_class1
def _set_dwrr_traffic_class1(self, v, load=False):
"""
Setter method for dwrr_traffic_class1, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class1 (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_dwrr_traffic_class1 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_dwrr_traffic_class1() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class1", rest_name="dwrr-traffic-class1", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 6', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """dwrr_traffic_class1 must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class1", rest_name="dwrr-traffic-class1", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 6', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)""",
})
self.__dwrr_traffic_class1 = t
if hasattr(self, '_set'):
self._set()
def _unset_dwrr_traffic_class1(self):
self.__dwrr_traffic_class1 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class1", rest_name="dwrr-traffic-class1", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 6', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
def _get_dwrr_traffic_class2(self):
"""
Getter method for dwrr_traffic_class2, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class2 (uint32)
"""
return self.__dwrr_traffic_class2
def _set_dwrr_traffic_class2(self, v, load=False):
"""
Setter method for dwrr_traffic_class2, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class2 (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_dwrr_traffic_class2 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_dwrr_traffic_class2() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class2", rest_name="dwrr-traffic-class2", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 5', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """dwrr_traffic_class2 must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class2", rest_name="dwrr-traffic-class2", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 5', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)""",
})
self.__dwrr_traffic_class2 = t
if hasattr(self, '_set'):
self._set()
def _unset_dwrr_traffic_class2(self):
self.__dwrr_traffic_class2 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class2", rest_name="dwrr-traffic-class2", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 5', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
def _get_dwrr_traffic_class3(self):
"""
Getter method for dwrr_traffic_class3, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class3 (uint32)
"""
return self.__dwrr_traffic_class3
def _set_dwrr_traffic_class3(self, v, load=False):
"""
Setter method for dwrr_traffic_class3, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class3 (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_dwrr_traffic_class3 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_dwrr_traffic_class3() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class3", rest_name="dwrr-traffic-class3", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 4', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """dwrr_traffic_class3 must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class3", rest_name="dwrr-traffic-class3", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 4', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)""",
})
self.__dwrr_traffic_class3 = t
if hasattr(self, '_set'):
self._set()
def _unset_dwrr_traffic_class3(self):
self.__dwrr_traffic_class3 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class3", rest_name="dwrr-traffic-class3", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 4', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
def _get_dwrr_traffic_class4(self):
"""
Getter method for dwrr_traffic_class4, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class4 (uint32)
"""
return self.__dwrr_traffic_class4
def _set_dwrr_traffic_class4(self, v, load=False):
"""
Setter method for dwrr_traffic_class4, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class4 (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_dwrr_traffic_class4 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_dwrr_traffic_class4() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class4", rest_name="dwrr-traffic-class4", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 3', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """dwrr_traffic_class4 must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class4", rest_name="dwrr-traffic-class4", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 3', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)""",
})
self.__dwrr_traffic_class4 = t
if hasattr(self, '_set'):
self._set()
def _unset_dwrr_traffic_class4(self):
self.__dwrr_traffic_class4 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class4", rest_name="dwrr-traffic-class4", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 3', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
def _get_dwrr_traffic_class5(self):
"""
Getter method for dwrr_traffic_class5, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class5 (uint32)
"""
return self.__dwrr_traffic_class5
def _set_dwrr_traffic_class5(self, v, load=False):
"""
Setter method for dwrr_traffic_class5, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class5 (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_dwrr_traffic_class5 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_dwrr_traffic_class5() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class5", rest_name="dwrr-traffic-class5", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 2', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """dwrr_traffic_class5 must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class5", rest_name="dwrr-traffic-class5", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 2', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)""",
})
self.__dwrr_traffic_class5 = t
if hasattr(self, '_set'):
self._set()
def _unset_dwrr_traffic_class5(self):
self.__dwrr_traffic_class5 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class5", rest_name="dwrr-traffic-class5", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 2', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
def _get_dwrr_traffic_class6(self):
"""
Getter method for dwrr_traffic_class6, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class6 (uint32)
"""
return self.__dwrr_traffic_class6
def _set_dwrr_traffic_class6(self, v, load=False):
"""
Setter method for dwrr_traffic_class6, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class6 (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_dwrr_traffic_class6 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_dwrr_traffic_class6() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class6", rest_name="dwrr-traffic-class6", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 1', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """dwrr_traffic_class6 must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class6", rest_name="dwrr-traffic-class6", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 1', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)""",
})
self.__dwrr_traffic_class6 = t
if hasattr(self, '_set'):
self._set()
def _unset_dwrr_traffic_class6(self):
self.__dwrr_traffic_class6 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class6", rest_name="dwrr-traffic-class6", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'display-when': u'../priority-number< 1', u'cli-incomplete-command': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
def _get_dwrr_traffic_class_last(self):
"""
Getter method for dwrr_traffic_class_last, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class_last (uint32)
"""
return self.__dwrr_traffic_class_last
def _set_dwrr_traffic_class_last(self, v, load=False):
"""
Setter method for dwrr_traffic_class_last, mapped from YANG variable /policy_map/class/scheduler/strict_priority/dwrr_traffic_class_last (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_dwrr_traffic_class_last is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_dwrr_traffic_class_last() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class-last", rest_name="dwrr-traffic-class-last", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """dwrr_traffic_class_last must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class-last", rest_name="dwrr-traffic-class-last", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)""",
})
self.__dwrr_traffic_class_last = t
if hasattr(self, '_set'):
self._set()
def _unset_dwrr_traffic_class_last(self):
self.__dwrr_traffic_class_last = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'0 .. 100']}), is_leaf=True, yang_name="dwrr-traffic-class-last", rest_name="dwrr-traffic-class-last", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='uint32', is_config=True)
def _get_TC1(self):
"""
Getter method for TC1, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC1 (shaping-rate-limit)
"""
return self.__TC1
def _set_TC1(self, v, load=False):
"""
Setter method for TC1, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC1 (shaping-rate-limit)
If this variable is read-only (config: false) in the
source YANG file, then _set_TC1 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_TC1() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC1", rest_name="TC1", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 6'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """TC1 must be of a type compatible with shaping-rate-limit""",
'defined-type': "brocade-qos-mqc:shaping-rate-limit",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC1", rest_name="TC1", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 6'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)""",
})
self.__TC1 = t
if hasattr(self, '_set'):
self._set()
def _unset_TC1(self):
self.__TC1 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC1", rest_name="TC1", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 6'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
def _get_TC2(self):
"""
Getter method for TC2, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC2 (shaping-rate-limit)
"""
return self.__TC2
def _set_TC2(self, v, load=False):
"""
Setter method for TC2, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC2 (shaping-rate-limit)
If this variable is read-only (config: false) in the
source YANG file, then _set_TC2 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_TC2() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC2", rest_name="TC2", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 5'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """TC2 must be of a type compatible with shaping-rate-limit""",
'defined-type': "brocade-qos-mqc:shaping-rate-limit",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC2", rest_name="TC2", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 5'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)""",
})
self.__TC2 = t
if hasattr(self, '_set'):
self._set()
def _unset_TC2(self):
self.__TC2 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC2", rest_name="TC2", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 5'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
def _get_TC3(self):
"""
Getter method for TC3, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC3 (shaping-rate-limit)
"""
return self.__TC3
def _set_TC3(self, v, load=False):
"""
Setter method for TC3, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC3 (shaping-rate-limit)
If this variable is read-only (config: false) in the
source YANG file, then _set_TC3 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_TC3() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC3", rest_name="TC3", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 4'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """TC3 must be of a type compatible with shaping-rate-limit""",
'defined-type': "brocade-qos-mqc:shaping-rate-limit",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC3", rest_name="TC3", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 4'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)""",
})
self.__TC3 = t
if hasattr(self, '_set'):
self._set()
def _unset_TC3(self):
self.__TC3 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC3", rest_name="TC3", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 4'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
def _get_TC4(self):
"""
Getter method for TC4, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC4 (shaping-rate-limit)
"""
return self.__TC4
def _set_TC4(self, v, load=False):
"""
Setter method for TC4, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC4 (shaping-rate-limit)
If this variable is read-only (config: false) in the
source YANG file, then _set_TC4 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_TC4() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC4", rest_name="TC4", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 3'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """TC4 must be of a type compatible with shaping-rate-limit""",
'defined-type': "brocade-qos-mqc:shaping-rate-limit",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC4", rest_name="TC4", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 3'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)""",
})
self.__TC4 = t
if hasattr(self, '_set'):
self._set()
def _unset_TC4(self):
self.__TC4 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC4", rest_name="TC4", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 3'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
def _get_TC5(self):
"""
Getter method for TC5, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC5 (shaping-rate-limit)
"""
return self.__TC5
def _set_TC5(self, v, load=False):
"""
Setter method for TC5, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC5 (shaping-rate-limit)
If this variable is read-only (config: false) in the
source YANG file, then _set_TC5 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_TC5() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC5", rest_name="TC5", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 2'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """TC5 must be of a type compatible with shaping-rate-limit""",
'defined-type': "brocade-qos-mqc:shaping-rate-limit",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC5", rest_name="TC5", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 2'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)""",
})
self.__TC5 = t
if hasattr(self, '_set'):
self._set()
def _unset_TC5(self):
self.__TC5 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC5", rest_name="TC5", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 2'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
def _get_TC6(self):
"""
Getter method for TC6, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC6 (shaping-rate-limit)
"""
return self.__TC6
def _set_TC6(self, v, load=False):
"""
Setter method for TC6, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC6 (shaping-rate-limit)
If this variable is read-only (config: false) in the
source YANG file, then _set_TC6 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_TC6() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC6", rest_name="TC6", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 1'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """TC6 must be of a type compatible with shaping-rate-limit""",
'defined-type': "brocade-qos-mqc:shaping-rate-limit",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC6", rest_name="TC6", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 1'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)""",
})
self.__TC6 = t
if hasattr(self, '_set'):
self._set()
def _unset_TC6(self):
self.__TC6 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC6", rest_name="TC6", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 1'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
def _get_TC7(self):
"""
Getter method for TC7, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC7 (shaping-rate-limit)
"""
return self.__TC7
def _set_TC7(self, v, load=False):
"""
Setter method for TC7, mapped from YANG variable /policy_map/class/scheduler/strict_priority/TC7 (shaping-rate-limit)
If this variable is read-only (config: false) in the
source YANG file, then _set_TC7 is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_TC7() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC7", rest_name="TC7", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 0'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """TC7 must be of a type compatible with shaping-rate-limit""",
'defined-type': "brocade-qos-mqc:shaping-rate-limit",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC7", rest_name="TC7", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 0'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)""",
})
self.__TC7 = t
if hasattr(self, '_set'):
self._set()
def _unset_TC7(self):
self.__TC7 = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), restriction_dict={'range': [u'28000 .. 100000000']}), is_leaf=True, yang_name="TC7", rest_name="TC7", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-optional-in-sequence': None, u'display-when': u'../priority-number> 0'}}, namespace='urn:brocade.com:mgmt:brocade-qos-mqc', defining_module='brocade-qos-mqc', yang_type='shaping-rate-limit', is_config=True)
priority_number = __builtin__.property(_get_priority_number, _set_priority_number)
scheduler_type = __builtin__.property(_get_scheduler_type, _set_scheduler_type)
dwrr_traffic_class0 = __builtin__.property(_get_dwrr_traffic_class0, _set_dwrr_traffic_class0)
dwrr_traffic_class1 = __builtin__.property(_get_dwrr_traffic_class1, _set_dwrr_traffic_class1)
dwrr_traffic_class2 = __builtin__.property(_get_dwrr_traffic_class2, _set_dwrr_traffic_class2)
dwrr_traffic_class3 = __builtin__.property(_get_dwrr_traffic_class3, _set_dwrr_traffic_class3)
dwrr_traffic_class4 = __builtin__.property(_get_dwrr_traffic_class4, _set_dwrr_traffic_class4)
dwrr_traffic_class5 = __builtin__.property(_get_dwrr_traffic_class5, _set_dwrr_traffic_class5)
dwrr_traffic_class6 = __builtin__.property(_get_dwrr_traffic_class6, _set_dwrr_traffic_class6)
dwrr_traffic_class_last = __builtin__.property(_get_dwrr_traffic_class_last, _set_dwrr_traffic_class_last)
TC1 = __builtin__.property(_get_TC1, _set_TC1)
TC2 = __builtin__.property(_get_TC2, _set_TC2)
TC3 = __builtin__.property(_get_TC3, _set_TC3)
TC4 = __builtin__.property(_get_TC4, _set_TC4)
TC5 = __builtin__.property(_get_TC5, _set_TC5)
TC6 = __builtin__.property(_get_TC6, _set_TC6)
TC7 = __builtin__.property(_get_TC7, _set_TC7)
_pyangbind_elements = {'priority_number': priority_number, 'scheduler_type': scheduler_type, 'dwrr_traffic_class0': dwrr_traffic_class0, 'dwrr_traffic_class1': dwrr_traffic_class1, 'dwrr_traffic_class2': dwrr_traffic_class2, 'dwrr_traffic_class3': dwrr_traffic_class3, 'dwrr_traffic_class4': dwrr_traffic_class4, 'dwrr_traffic_class5': dwrr_traffic_class5, 'dwrr_traffic_class6': dwrr_traffic_class6, 'dwrr_traffic_class_last': dwrr_traffic_class_last, 'TC1': TC1, 'TC2': TC2, 'TC3': TC3, 'TC4': TC4, 'TC5': TC5, 'TC6': TC6, 'TC7': TC7, }
| [
"[email protected]"
] | |
d8903c407c47754f512bd6fb9124f70132544489 | 02d26f67c233288b26408797d239e0127d229a67 | /fire.py | 301eae1e3ffeaf315174c19ff5e5ecc3a3f1212a | [] | no_license | sd-james/fire-demo | 27b16ed0c6911c9fab1eaa7c0817143f57415b15 | 7355221cb1abb195785927ce893b13f109a5d191 | refs/heads/master | 2021-03-05T06:24:19.496393 | 2020-03-09T17:45:46 | 2020-03-09T17:45:46 | 246,102,382 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,794 | py | import pygame
from pygame.constants import DOUBLEBUF, K_q
import random
width = 300
height = 100
zoom = 3
screen = pygame.Surface((width, height))
# set the pixel value at a particular location. This is a special set to make things look more fire-like
def draw_pixel(x, y, value):
red = value
green = value * 2 // 3
if green > 70:
green = green * 2 // 3
blue = green
if blue > 60:
blue = blue // 3
pixel = (red, green, blue)
screen.set_at((x, y), pixel)
# gets the intensity of the pixel at position x,y on the screen. In particular returns the RED components
def get_pixel(x, y):
if x < 0 or x >= width or y < 0 or y >= height:
return 0
pixel = tuple(screen.get_at((x, y)))
return pixel[0]
# Draw the fire.
def draw_fire():
for x in range(width):
draw_pixel(x, height - 1, random.randint(0, 255))
for x in range(width):
for y in range(height - 1):
value = (get_pixel(x, y) + get_pixel(x + 1, y + 1) + get_pixel(x, y + 1) + get_pixel(x - 1, y + 1)) // 4 - 1
if value < 0:
value = 0
draw_pixel(x, y, value)
if __name__ == '__main__':
pygame.init()
clock = pygame.time.Clock()
pygame.key.set_repeat()
display = pygame.display.set_mode((width * zoom, height * zoom + 40), DOUBLEBUF)
while True:
clock.tick(50)
display.fill((0, 0, 0))
# draw the fire
draw_fire()
# draw the screen
pygame.transform.scale(screen, (display.get_width(), display.get_height()), display)
pygame.display.flip()
# check if user quit by pressing Q
inpt = pygame.key.get_pressed()
if inpt[K_q]:
break
pygame.event.clear()
pygame.display.quit()
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.