blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
288
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 684
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 147
values | src_encoding
stringclasses 25
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 128
12.7k
| extension
stringclasses 142
values | content
stringlengths 128
8.19k
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b532663dbe99cf46e6de9766168e7521419f9b32
|
c59194e1908bac7fc0dd4d80bef49c6afd9f91fb
|
/CodeSignal/Python/SlitheringInStrings/ConvertTabs.py
|
5e77e7af1f1acf2c9b3f435b15c1daae37a49f38
|
[] |
no_license
|
Bharadwaja92/CompetitiveCoding
|
26e9ae81f5b62f4992ce8171b2a46597353f0c82
|
d0505f28fd6e93b2f4ef23ad02c671777a3caeda
|
refs/heads/master
| 2023-01-23T03:47:54.075433
| 2023-01-19T12:28:07
| 2023-01-19T12:28:07
| 208,804,519
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 819
|
py
|
"""
You found an awesome customizable Python IDE that has almost everything you'd like to see in your working environment.
However, after a couple days of coding you discover that there is one important feature that this IDE lacks:
it cannot convert tabs to spaces. Luckily, the IDE is easily customizable, so you decide to write a plugin that would
convert all tabs in the code into the given number of whitespace characters.
Implement a function that, given a piece of code and a positive integer x will turn each tabulation character in code
into x whitespace characters.
Example
For code = "\treturn False" and x = 4, the output should be
convertTabs(code, x) = " return False".
"""
def convertTabs(code, x):
return code.replace('\t', ' '*x)
code = "\treturn False"
x = 4
print(convertTabs(code, x))
|
[
"saibharadwaja92@gmail.com"
] |
saibharadwaja92@gmail.com
|
1dad86a2398f0ba35ec7eae771277fb34b70e513
|
196d32dbe3d212974f90fec3fcf58ffbaf6fe654
|
/reward/utils/batch.py
|
34808a77074f4e623ee0de6058d2c4a6c213cd5f
|
[
"MIT"
] |
permissive
|
lgvaz/reward
|
a4f1f418f39102225d7ee00a70fed33f1137051a
|
cfff8acaf70d1fec72169162b95ab5ad3547d17a
|
refs/heads/master
| 2021-10-10T08:16:29.151557
| 2019-01-08T10:08:57
| 2019-01-08T10:08:57
| 115,865,905
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 843
|
py
|
import numpy as np
import torch
from torch.utils.data import DataLoader, TensorDataset
from reward.utils.memories import SimpleMemory
from reward.utils import to_tensor, join_first_dims, to_np
from reward.utils.device import get
class Batch(SimpleMemory):
def __len__(self):
return len(self["s"])
def apply_to_all(self, func): return Batch((k, func(v)) for k, v in self.items())
def apply_to_keys(self, func, keys): return Batch((k, func(self[k])) for k in keys)
def concat_batch(self):
func = (
lambda x: join_first_dims(x, num_dims=2)
if (isinstance(x, (np.ndarray, torch.Tensor)))
else x
)
return self.apply_to_all(func)
def to_tensor(self, ignore=["idx"]):
return Batch({k: v if k in ignore else to_tensor(v) for k, v in self.items()})
|
[
"lucasgouvaz@gmail.com"
] |
lucasgouvaz@gmail.com
|
adc0b9f134e3152c574524e73f31f45144d81956
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/verbs/_savours.py
|
a906acbbfc694c29d8980efe7376d9c99028bb49
|
[
"MIT"
] |
permissive
|
cash2one/xai
|
de7adad1758f50dd6786bf0111e71a903f039b64
|
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
|
refs/heads/master
| 2021-01-19T12:33:54.964379
| 2017-01-28T02:00:50
| 2017-01-28T02:00:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 238
|
py
|
from xai.brain.wordbase.verbs._savour import _SAVOUR
#calss header
class _SAVOURS(_SAVOUR, ):
def __init__(self,):
_SAVOUR.__init__(self)
self.name = "SAVOURS"
self.specie = 'verbs'
self.basic = "savour"
self.jsondata = {}
|
[
"xingwang1991@gmail.com"
] |
xingwang1991@gmail.com
|
008c3ed1df59cba2c6bce0b737ac840ef68508c2
|
c7f43c4cc0ee84a5fe246b67f51e30b8d726ebd5
|
/keras2/keras78_03_cifar10_ResNet50.py
|
3b90c7a4949262c3b1014362398e7aae04f63536
|
[] |
no_license
|
89Mansions/AI_STUDY
|
d9f8bdf206f14ba41845a082e731ea844d3d9007
|
d87c93355c949c462f96e85e8d0e186b0ce49c76
|
refs/heads/master
| 2023-07-21T19:11:23.539693
| 2021-08-30T08:18:59
| 2021-08-30T08:18:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,214
|
py
|
# ResNet50
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.datasets import cifar10
import numpy as np
import pandas as pd
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.models import Sequential
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint
#1. DATA
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = x_train.reshape(x_train.shape[0], x_train.shape[1], x_train.shape[2], x_train.shape[3])/255.
x_test = x_test.reshape(x_test.shape[0], x_test.shape[1], x_test.shape[2], x_test.shape[3])/255.
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
print(x_train.shape, y_train.shape)
print(x_test.shape, y_test.shape)
# (50000, 32, 32, 3) (50000, 10)
# (10000, 32, 32, 3) (10000, 10)
#2. Modeling
rn50 = ResNet50(weights='imagenet', include_top=False, input_shape=(32,32,3))
rn50.trainable = False
model = Sequential()
model.add(rn50)
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(10, activation='softmax'))
# model.summary()
#3. Compile, Train
lr = ReduceLROnPlateau(monitor='val_loss', factor=0.4, patience=10, verbose=1, mode='min')
es = EarlyStopping(monitor='val_loss', patience=20, mode='min')
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc'])
model.fit(x_train, y_train, epochs=100, batch_size=32, validation_split=0.2, verbose=1, callbacks=[lr, es])
loss, acc = model.evaluate(x_test, y_test, batch_size=32)
print("loss : ", loss)
print("acc : ", acc)
## CNN
# loss : 1.7849451303482056
# acc : 0.5971999764442444
###### 전이학습 ######
# VGG16
# loss : 1.9435967206954956
# acc : 0.604200005531311
# VGG19
# loss : 1.9104373455047607
# acc : 0.5917999744415283
# Xception
# ValueError: Input size must be at least 71x71; got `input_shape=(32, 32, 3)`
# >> UpSampling2D & input_shape = (96, 96,3)으로 바꿔줌
# loss : 2.4691503047943115
# acc : 0.7441999912261963
# ResNet50
# loss : 2.302600860595703
# acc : 0.10000000149011612
|
[
"hwangkei0212@gmail.com"
] |
hwangkei0212@gmail.com
|
47cf1a099f9594ba41114c905f4b027f41b1fb7a
|
930a868ae9bbf85df151b3f54d04df3a56bcb840
|
/benchmark/paper_weighted_union_find_on_XZZX/debug_code_capacity_noise_model/plot_weight_change/weight_change_neighbor.py
|
2eb2c091cdab7939f2048f5ca5ca59293dfc50aa
|
[
"MIT"
] |
permissive
|
yuewuo/QEC-Playground
|
1148f3c5f4035c069986d8b4103acf7f1e34f9d4
|
462208458cdf9dc8a33d4553a560f8a16c00e559
|
refs/heads/main
| 2023-08-10T13:05:36.617858
| 2023-07-22T23:48:49
| 2023-07-22T23:48:49
| 312,809,760
| 16
| 1
|
MIT
| 2023-07-22T23:48:51
| 2020-11-14T12:10:38
|
Python
|
UTF-8
|
Python
| false
| false
| 3,171
|
py
|
import os, sys
import subprocess, sys
qec_playground_root_dir = subprocess.run("git rev-parse --show-toplevel", cwd=os.path.dirname(os.path.abspath(__file__)), shell=True, check=True, capture_output=True).stdout.decode(sys.stdout.encoding).strip(" \r\n")
rust_dir = os.path.join(qec_playground_root_dir, "backend", "rust")
fault_toleran_MWPM_dir = os.path.join(qec_playground_root_dir, "benchmark", "fault_tolerant_MWPM")
sys.path.insert(0, fault_toleran_MWPM_dir)
from automated_threshold_evaluation import qec_playground_fault_tolerant_MWPM_simulator_runner_vec_command
from automated_threshold_evaluation import run_qec_playground_command_get_stdout, compile_code_if_necessary
import numpy as np
import matplotlib.pyplot as plt
di = 11
p = 0.07
divide = 10
bias_eta_vec = [str(0.5 * (10 ** (i / divide))) for i in range(4 * divide)]
# print(bias_eta_vec)
parameters = f"-p1 --time_budget 3600 --use_xzzx_code --shallow_error_on_bottom --debug_print_only --debug_print_direct_connections".split(" ")
# only plot one node because otherwise it's too mesy
interested_node = "[12][10][9]" # in the middle
# interested_node = "[12][20][19]" # on the boundary
results = []
for bias_eta in bias_eta_vec:
command = qec_playground_fault_tolerant_MWPM_simulator_runner_vec_command([p], [di], [di], [0], parameters + ["--bias_eta", f"{bias_eta}"])
# run experiment
stdout, returncode = run_qec_playground_command_get_stdout(command, use_tmp_out=True)
# print("\n" + stdout)
assert returncode == 0, "command fails..."
boundary = None
edges = []
is_interested = False
for line in stdout.strip(" \r\n").split("\n"):
if line[0] == "[":
addr = line.split(":")[0]
is_interested = (addr == interested_node)
elif is_interested:
head, value = line.split(": ")
if head == "boundary":
if value[:4] == "p = ":
boundary = float(value[4:])
if head[:5] == "edge ":
assert value[:4] == "p = "
t,i,j = [int(e) for e in head[5:][1:-1].split("][")]
edges.append(((t,i,j), float(value[4:])))
results.append((boundary, edges))
print(bias_eta, boundary, edges)
fig = plt.figure(f"weight change")
fig.clear()
ax0 = fig.add_subplot(111)
plt.xscale("log")
plt.yscale("log")
ax0.set_title(f"direct neighbors of {interested_node}")
ax0.set_xlabel("bias eta")
ax0.set_xticks([0.5, 5, 50, 500, 5000])
ax0.set_xticklabels([0.5, 5, 50, 500, 5000])
ax0.set_ylabel("probability")
float_bias_eta_vec = [float(e) for e in bias_eta_vec]
if results[0][0] is not None:
boundaries = [results[i][0] for i in range(len(results))]
ax0.plot(float_bias_eta_vec, boundaries, label="boundary")
for ni in range(len(results[0][1])):
addr = results[0][1][ni][0]
for i in range(len(results)):
if addr != results[i][1][ni][0]:
print(addr, results[i][1][ni][0])
assert addr == results[i][1][ni][0]
values = [results[i][1][ni][1] for i in range(len(results))]
ax0.plot(float_bias_eta_vec, values, label=f"[{addr[0]}][{addr[1]}][{addr[2]}]")
ax0.legend()
plt.show()
|
[
"yue.wu@yale.edu"
] |
yue.wu@yale.edu
|
c023c176ead2dccd07efeef6792dfdb196aae49c
|
0eb6c70503c680ebec415016ff1b0cfac92486ca
|
/lincdm/blog/managers.py
|
4467fa3b95367eb9e9040e51170ef10107db77b1
|
[] |
no_license
|
alexliyu/lincdm
|
c8b473946f59aca9145b3291890635474f144583
|
eab93285f0b03217ea041a7910edae7e00095cd8
|
refs/heads/master
| 2020-12-30T10:50:05.248988
| 2011-08-09T15:52:38
| 2011-08-09T15:52:38
| 1,464,255
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,684
|
py
|
"""Managers of blog"""
from datetime import datetime
from django.db import models
from django.contrib.sites.models import Site
DRAFT = 0
HIDDEN = 1
PUBLISHED = 2
def tags_published():
"""Return the published tags"""
from tagging.models import Tag
from lincdm.blog.models import Entry
tags_entry_published = Tag.objects.usage_for_queryset(
Entry.published.all())
# Need to do that until the issue #44 of django-tagging is fixed
return Tag.objects.filter(name__in=[t.name for t in tags_entry_published])
class AuthorPublishedManager(models.Manager):
"""Manager to retrieve published authors"""
def get_query_set(self):
"""Return published authors"""
now = datetime.now()
return super(AuthorPublishedManager, self).get_query_set().filter(
entries__status=PUBLISHED,
entries__start_publication__lte=now,
entries__end_publication__gt=now,
entries__sites=Site.objects.get_current()
).distinct()
def entries_published(queryset):
"""Return only the entries published"""
now = datetime.now()
return queryset.filter(status=PUBLISHED,
start_publication__lte=now,
end_publication__gt=now,
sites=Site.objects.get_current())
class EntryPublishedManager(models.Manager):
"""Manager to retrieve published entries"""
def get_query_set(self):
"""Return published entries"""
return entries_published(
super(EntryPublishedManager, self).get_query_set())
def on_site(self):
"""Return entries published on current site"""
return super(EntryPublishedManager, self).get_query_set(
).filter(sites=Site.objects.get_current())
def search(self, pattern):
"""Top level search method on entries"""
try:
return self.advanced_search(pattern)
except:
return self.basic_search(pattern)
def advanced_search(self, pattern):
"""Advanced search on entries"""
from lincdm.blog.search import advanced_search
return advanced_search(pattern)
def basic_search(self, pattern):
"""Basic search on entries"""
lookup = None
for pattern in pattern.split():
query_part = models.Q(content__icontains=pattern) | \
models.Q(excerpt__icontains=pattern) | \
models.Q(title__icontains=pattern)
if lookup is None:
lookup = query_part
else:
lookup |= query_part
return self.get_query_set().filter(lookup)
|
[
"alexliyu2012@gmail.com"
] |
alexliyu2012@gmail.com
|
523050cba42f58cd7ac14e6992ad3f7708a17e55
|
ba2ad1187e447dc948e32ff1629935d2f05b7d59
|
/New folder/08 Accepting User Input In Tkinter Form.py
|
2bdfa914adfd1ad27b6475cf0c318faf44ff9aea
|
[] |
no_license
|
kkgarai/Tkinter
|
14fce2e0bbbe013a439f0f7fff8a3e88d3a5370e
|
4ce77c22b1229484cdae5f8926011ca32fe0d9ba
|
refs/heads/master
| 2023-02-27T11:10:51.678239
| 2021-02-02T21:08:38
| 2021-02-02T21:08:38
| 295,819,467
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,989
|
py
|
from tkinter import *
root = Tk()
def getvals():
print("Submitting form")
print(
f"{namevalue.get(), phonevalue.get(), gendervalue.get(), emergencyvalue.get(), paymentmodevalue.get(), foodservicevalue.get()} ")
with open("records.txt", "a") as f:
f.write(
f"{namevalue.get(), phonevalue.get(), gendervalue.get(), emergencyvalue.get(), paymentmodevalue.get(), foodservicevalue.get()}\n")
root.geometry("644x344")
# Heading
Label(root, text="Welcome to Harry Travels", font="comicsansms 13 bold",
pady=15).grid(row=0, column=3)
# Text for our form
name = Label(root, text="Name")
phone = Label(root, text="Phone")
gender = Label(root, text="Gender")
emergency = Label(root, text="Emergency Contact")
paymentmode = Label(root, text="Payment Mode")
# Pack text for our form
name.grid(row=1, column=2)
phone.grid(row=2, column=2)
gender.grid(row=3, column=2)
emergency.grid(row=4, column=2)
paymentmode.grid(row=5, column=2)
# Tkinter variable for storing entries
namevalue = StringVar()
phonevalue = StringVar()
gendervalue = StringVar()
emergencyvalue = StringVar()
paymentmodevalue = StringVar()
foodservicevalue = IntVar()
# Entries for our form
nameentry = Entry(root, textvariable=namevalue)
phoneentry = Entry(root, textvariable=phonevalue)
genderentry = Entry(root, textvariable=gendervalue)
emergencyentry = Entry(root, textvariable=emergencyvalue)
paymentmodeentry = Entry(root, textvariable=paymentmodevalue)
# Packing the Entries
nameentry.grid(row=1, column=3)
phoneentry.grid(row=2, column=3)
genderentry.grid(row=3, column=3)
emergencyentry.grid(row=4, column=3)
paymentmodeentry.grid(row=5, column=3)
# Checkbox & Packing it
foodservice = Checkbutton(text="Want to prebook your meals?",
variable=foodservicevalue)
foodservice.grid(row=6, column=3)
# Button & packing it and assigning it a command
Button(text="Submit to Harry Travels", command=getvals).grid(row=7, column=3)
root.mainloop()
|
[
"you@example.com"
] |
you@example.com
|
582c4ad65e1b6f2bff267c7119594dd2d2af4f26
|
30d360f965253167c99f9b4cd41001491aed08af
|
/PTFE_code/Old/rdf_ptfe.py
|
12cde9224cf10d6a131600e280ca7a988aaaa356
|
[] |
no_license
|
petervanya/PhDcode
|
d2d9f7170f201d6175fec9c3d4094617a5427fb5
|
891e6812a2699025d26b901c95d0c46a706b0c96
|
refs/heads/master
| 2020-05-22T06:43:47.293134
| 2018-01-29T12:59:42
| 2018-01-29T12:59:42
| 64,495,043
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,431
|
py
|
#!/usr/bin/env python
"""Usage:
rdf_ptfe.py (--bead <b> | water) <fnames>
[--L <L> --bins <nbins> --binalg <b>]
Read xyz files and compute radial distribution function
for any DPD beads or water beads (water is in both beads C and W):
* C: 3 molecules (SO3+3H2O, bead 3)
* W: 6 molecules (bead 4)
Arguments:
--beadtype <b> Number from 1 to num. bead types, typically 4
<fnames> Regex for all the xyz files to read
Options:
--bins <nbins> Number of bins
--binalg <b> 'numpy' or 'fortran' [Default: fortran]
--L <L> Box size [default: 40.0]
pv278@cam.ac.uk, 09/01/16
"""
import numpy as np
from math import *
import glob, sys
from docopt import docopt
import lmp_lib as ll
from Fcore.f_rdf import f_rdf # Fortran module
def set_num_bins(N, method="sqrt"):
"""Set number of histogram bins, various recipes.
Available methods: rice, sturges, sqrt (default)"""
if method == "rice":
return int(2*N**(1./3)) + 1 # Rice rule
elif method == "sturges":
return int(log(N, 2)+1) + 1 # Sturges' formula
else:
return int(sqrt(N)) + 1 # most primitive
def read_outfile(outfile):
"""Read one xyz outfile into a numpy matrix"""
A = open(outfile, "r").readlines()[2:]
A = [line.split() for line in A]
A = np.array(A, order="F").astype(float)
return A
def save_data(outfile, *args):
"""Save two vectors into file"""
m, n = len(args), len(args[0]) # cols, rows
args = zip(*args)
with open(outfile, "w") as f:
for i in range(n):
line = ""
for j in range(m):
line += str(args[i][j]) + "\t"
line += "\n"
f.write(line)
def compute_rdf_water_np(outfile, L, nbins=30):
"""Compute radial dist'n fcn from the xyz frame using
Fortran routine for pair distances and numpy binning
"""
A = read_outfile(outfile)
xyz_C = A[A[:, 0] == 3][:, 1:]
xyz_W = A[A[:, 0] == 4][:, 1:]
cell = L * np.eye((3, 3))
d_C = f_rdf.dist_vec(xyz_C, cell) # rdf for beads C
# print " Distance matrix for C beads done."
rdf_raw_C, r = np.histogram(d_C, nbins)
# print " Binning for C beads done."
del d_C
d_W = f_rdf.dist_vec(xyz_W, cell) # rdf for beads W
# print " Distance matrix for W beads done."
rdf_raw_W, r = np.histogram(d_W, nbins)
# print " Binning for W beads done."
del d_W
d_CW = f_rdf.dist_vec_2mat(xyz_C, xyz_W, cell) # rdf for combined beads C and W
# print " Distance matrix for CW beads done."
rdf_raw_CW, r = np.histogram(d_CW, nbins)
# print " Binning for CW beads done."
del d_CW
rdf_raw = rdf_raw_C * 3**2 + rdf_raw_W * 6**2 + rdf_raw_CW * 3*6
r = r[:-1] + np.diff(r)/2.0
dr = r[1] - r[0]
rdf = rdf_raw/(4*pi*r**2 * dr)
return r, rdf
def compute_rdf_water(outfile, L, nbins=30):
"""Compute radial dist'n fcn from the xyz frame
using Fortran routine, both distance matrix and binning"""
A = read_outfile(outfile)
xyz_C = A[A[:, 0] == 3][:, 1:]
xyz_W = A[A[:, 0] == 4][:, 1:]
cell = L * np.eye((3, 3))
rdf_raw_C, r = f_rdf.pair_dist_hist(xyz_C, nbins, cell)
# print " Bead C pair dist and binning beads done"
rdf_raw_W, r = f_rdf.pair_dist_hist(xyz_W, nbins, cell)
# print " Bead W pair dist and binning beads done"
rdf_raw_CW, r = f_rdf.pair_dist_hist2(xyz_C, xyz_W, nbins, cell)
# print " Beads C and W pair dist and binning beads done"
rdf_raw = rdf_raw_C * 3**2 + rdf_raw_W * 6**2 + rdf_raw_CW * 3*6
r = r[:-1] + np.diff(r)/2.0
dr = r[1] - r[0]
rdf = rdf_raw/(4*pi*r**2 * dr)
return r, rdf
def master_rdf_water(outfiles, L, nbins=30, method="fortran"):
"""Construct an rdf for water beads
from all the available xyz files"""
rdf_mat = []
if method == "fortran":
for outfile in outfiles:
r, rdf_i = compute_rdf_water(outfile, L, nbins)
rdf_mat.append(rdf_i)
print(outfile, "done.")
if method == "numpy":
for outfile in outfiles:
r, rdf_i = compute_rdf_water_np(outfile, L, nbins)
rdf_mat.append(rdf_i)
print(outfile, "done.")
rdf_mat = np.array(rdf_mat).T
np.savetxt("rdf_mat.out", rdf_mat)
print("rdf matrix saved in rdf_mat.out")
rdf = np.array(np.sum(rdf_mat, 1) / len(outfiles))
return r, rdf
def compute_rdf(outfile, L, beadtype, nbins=30):
"""Compute RDF from the xyz frame uusing Fortran routine, distance matrix and binning"""
A = read_outfile(outfile)
cell = L * np.eye((3, 3))
xyz = A[A[:, 0] == beadtype][:, 1:]
rdf_raw, r = f_rdf.pair_dist_hist(xyz, nbins, cell) # key routine
r = r[:-1] + np.diff(r)/2.0
dr = r[1] - r[0]
rdf = rdf_raw/(4*pi*r**2 * dr)
return r, rdf
def master_rdf(outfiles, L, beadtype, nbins=30):
"""Construct an rdf for given bead type
from all the available xyz files"""
rdf_mat = []
for outfile in outfiles:
r, rdf_i = compute_rdf(outfile, L, beadtype, nbins)
rdf_mat.append(rdf_i)
print(outfile, "done.")
rdf_mat = np.array(rdf_mat).T
np.savetxt("rdf_mat.out", rdf_mat)
print("rdf matrix saved in rdf_mat.out")
rdf = np.array(np.sum(rdf_mat, 1) / len(outfiles))
return r, rdf
if __name__ == "__main__":
args = docopt(__doc__)
outfiles = glob.glob(args["<fnames>"])
beadtype = "water" if args["water"] else args["<b>"]
if len(outfiles) == 0:
raise ValueError("No xyz files captured, aborting.")
print(outfiles)
Nfiles = len(outfiles)
N = int(open(outfiles[0], "r").readline())
L = float(args["--L"])
if args["--bins"]:
Nbins = int(args["--bins"])
else:
Nbins = set_num_bins(N, method="sturges")
method = args["--binalg"]
A = ll.read_xyzfile(outfiles[0])
Nbt = len(set(A[:, 0]))
Nb = len(A[A[:, 0] == int(beadtype)])
print("Total beads: %i | Num. beadtypes: %i | Bins: %i" % (N, Nbt, Nbins))
print("Bead type: %s | Beads of this type: %i" % (beadtype, Nb))
if beadtype == "water":
r, vals = master_rdf_water(outfiles, L, Nbins, method)
fname = "rdf_water.out"
else:
r, vals = master_rdf(outfiles, L, int(beadtype), Nbins)
fname = "rdf.out"
save_data(fname, r, vals)
print("rdf saved in", fname)
|
[
"peter.vanya@gmail.com"
] |
peter.vanya@gmail.com
|
c66bd3c2ab4b0774d6d5247124b5b57b6b452835
|
b2716c78a38fcc0acee852c3e33bf110fa35f4f6
|
/Rem_pro/yes_no_app/migrations/0001_initial.py
|
adac69f943774781d801b67b55ffe04899f1a85d
|
[] |
no_license
|
RajeshKumar-1998/Reminder-App
|
f381e8728af5694d5e0e627ed261886a20b45318
|
985a1ee548b8a5b1a9970a9421cac4c98d6fc3b4
|
refs/heads/master
| 2022-11-07T00:27:30.348065
| 2020-06-19T11:28:35
| 2020-06-19T11:28:35
| 259,647,627
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 554
|
py
|
# Generated by Django 2.2.7 on 2019-12-03 23:54
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Todorem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('list', models.CharField(max_length=200)),
('completes', models.BooleanField(default=False)),
],
),
]
|
[
"57509232+Rajeshkumar-dev-cloud@users.noreply.github.com"
] |
57509232+Rajeshkumar-dev-cloud@users.noreply.github.com
|
bae8017147a594e2103ce78cf22b3560ebbb921d
|
68c37d6a87113fb992126e9806a78896d1727c43
|
/examples/wrap_protos/python/wrap_protos_test.py
|
dd8e3e8c73c9fec00c9ebd62bbdad2337b427a09
|
[
"Apache-2.0"
] |
permissive
|
Pandinosaurus/clif
|
1b8be31a0b1b45b11d93fe2d7b3f359f69d9075f
|
87eed3999dba9f8d160c6b735e1803640d019289
|
refs/heads/master
| 2021-04-09T13:53:23.744431
| 2020-09-11T01:53:03
| 2020-09-11T01:53:03
| 125,673,546
| 1
| 0
|
Apache-2.0
| 2020-09-11T04:35:26
| 2018-03-17T22:20:42
|
C++
|
UTF-8
|
Python
| false
| false
| 2,310
|
py
|
# Copyright 2017 Google 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.
"""Tests for clif.examples.wrap_protos.python.wrap_protos."""
import unittest
import wrap_protos
import sample_pb2
class WrapProtosTest(unittest.TestCase):
def testProtos(self):
s = sample_pb2.MyMessage()
# Even though DefaultInitSample on the C++ side takes a pointer to the
# proto, |s| is serialized and deserialized in to a copy of the C++ proto.
# Hence, changes made to the proto on the C++ side do not reflect in Python.
wrap_protos.DefaultInitMyMessage(s)
self.assertNotEqual(s.name, 'default')
# |s| is a normal Python proto with all its normal Python proto API.
s.name = 'my_python_name'
s.msg.id.append(123)
s.msg.id.append(345)
self.assertEqual(len(s.msg.id), 2)
pman = wrap_protos.ProtoManager()
# The GetSample method returns a copy of the proto even though the C++
# method returns a pointer. The C++ proto is serialized and then
# deserialized into a Python proto.
s = pman.GetMyMessage()
self.assertEqual(s.name, 'default')
# Changing the proto in Python does not have any effect on the C++ side.
s.name = 'new_name'
s = pman.GetMyMessage()
self.assertEqual(s.name, 'default')
# Create instances of nested proto messages using the '.' notation as usual.
nested = sample_pb2.MyMessage.Nested()
nested.value = sample_pb2.MyMessage.Nested.DEFAULT
# And pass them to a wrapped functions as usual.
msg = wrap_protos.MakeMyMessageFromNested(nested)
self.assertEquals(msg.name, 'from_nested')
enum_val = sample_pb2.MyMessage.Nested.EXPLICIT
msg = wrap_protos.MakeMyMessageFromNestedEnum(enum_val)
self.assertEquals(msg.name, 'from_nested_enum')
if __name__ == '__main__':
unittest.main()
|
[
"mrovner@google.com"
] |
mrovner@google.com
|
318b1eb3d3c2cefce03b58798d8e9617e20f6b8b
|
2a4bb0307d903678c3b51d1e2c8b7a53ee4ae26e
|
/backend/chat/api/v1/urls.py
|
99a41c839549f4bde6227190e323d88b69862120
|
[] |
no_license
|
crowdbotics-apps/came2mind-20661
|
37835754c6b3fae6920b3f43bd5e9e1b824548f6
|
5eaed44b4b116ab89f9ae5f5ce4e2f314ae33172
|
refs/heads/master
| 2022-12-24T08:45:31.081668
| 2020-09-25T03:15:03
| 2020-09-25T03:15:03
| 298,455,069
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 644
|
py
|
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .viewsets import (
MessageViewSet,
ThreadMemberViewSet,
MessageActionViewSet,
ThreadActionViewSet,
ForwardedMessageViewSet,
ThreadViewSet,
)
router = DefaultRouter()
router.register("forwardedmessage", ForwardedMessageViewSet)
router.register("thread", ThreadViewSet)
router.register("threadaction", ThreadActionViewSet)
router.register("messageaction", MessageActionViewSet)
router.register("message", MessageViewSet)
router.register("threadmember", ThreadMemberViewSet)
urlpatterns = [
path("", include(router.urls)),
]
|
[
"team@crowdbotics.com"
] |
team@crowdbotics.com
|
ec9e9967a9d35ecb9c137b87d2b0304e54b3bf9f
|
eefb06b0d8c8c98c1e9cfc4c3852d5c453eb5429
|
/data/input/anchor/make-magic/core/store.py
|
6c8c1ab79e867d22aa00a08806097d60a5d46324
|
[] |
no_license
|
bopopescu/pythonanalyzer
|
db839453bde13bf9157b76e54735f11c2262593a
|
8390a0139137574ab237b3ff5fe8ea61e8a0b76b
|
refs/heads/master
| 2022-11-22T02:13:52.949119
| 2019-05-07T18:42:52
| 2019-05-07T18:42:52
| 282,079,884
| 0
| 0
| null | 2020-07-23T23:46:09
| 2020-07-23T23:46:08
| null |
UTF-8
|
Python
| false
| false
| 2,808
|
py
|
#! /usr/bin/env python
'''persistant storage of state data
We need some way to keep track of Tasks that are being worked on,
the state of items etc. It would be even cooler if that data was
to hang around when the process was gone.
'''
try: import pymongo
except: pass # allow import where noone is using the MongoStore
import config
import random
class MongoStore(object):
'''persistant mongodb store'''
def __init__(self):
self.connection = pymongo.Connection(config.mongodb_server,config.mongodb_port)
self.db = self.connection[config.mongodb_database]
def get_tasks(self):
return [name for name in self.db.collection_names() if 'system.' not in name]
def new_task(self, uuid, items, metadata=None):
if metadata == None: metadata = {}
metadata['uuid'] = uuid
metadata['metadata'] = True
self.db[uuid].create_index('name')
self.db[uuid].create_index('metadata')
self.db[uuid].insert(items)
self.db[uuid].insert(metadata)
def _noid(self, item):
if item is None or '_id' not in item: return item
del item['_id']
return item
def item(self, uuid, name):
'''get a specific item for a task'''
return self._noid( self.db[uuid].find_one({'name': name}) )
def items(self, uuid):
'''get all the items for a task'''
# ALL THE THINGS!
return [self._noid(item) for item in self.db[uuid].find({'name': {'$exists': True},'metadata': {'$exists': False}})]
def metadata(self, uuid):
'''get metadata for a task'''
metadata = self.db[uuid].find_one({'metadata': {'$exists': True}})
return self._noid(metadata)
def update_item(self, uuid, name, updatedict, existingstate={}):
'''updates an item similar to dict.update()
if 'existingdict' is supplied, the update will only succeed if
the items in existingdict match what is in the item already
returns the contents of the item after the attempt is made.
It is up to the caller to check if the update worked or failed.
'''
matchon = dict(existingstate)
matchon['name'] = name
self.db[uuid].update(matchon, {'$set': updatedict})
return self.item(uuid, name)
def update_metadata(self, uuid, updatedict, existingstate={}):
'''updates a metadata similar to dict.update()
if 'existingdict' is supplied, the update will only succeed if
the items in existingdict match what is in the metadata already
returns the contents of the metadata after the attempt is made.
It is up to the caller to check if the update worked or failed.
'''
matchon = dict(existingstate)
matchon['metadata'] = {'$exists': True}
self.db[uuid].update(matchon, {'$set': updatedict})
return self.metadata(uuid)
def delete_task(self, uuid):
'''delete a task, all it's items, and all it's metadata
This is not recoverable.
'''
self.db[uuid].drop()
# Define the default Store here
Store = MongoStore
|
[
"rares.begu@gmail.com"
] |
rares.begu@gmail.com
|
4ca0d26c31143eecceec45ee9e2ea01a0526ef94
|
19da8356b07108c640ca107729a183670829a694
|
/tests/storage/test_observable.py
|
6fc02760b8a477088fb6b63a3e5b6bb7a9068638
|
[
"Apache-2.0"
] |
permissive
|
kolotaev/vakt
|
2ebbc59f7ece8a3ad27ee9e77b3a9cb62509df6b
|
3a669d058b64c9c0aa75aa72745049d25635d292
|
refs/heads/master
| 2023-05-25T13:11:12.988351
| 2023-04-12T11:16:03
| 2023-04-12T11:16:03
| 115,222,029
| 154
| 27
|
Apache-2.0
| 2023-05-22T21:37:17
| 2017-12-23T21:10:41
|
Python
|
UTF-8
|
Python
| false
| false
| 3,548
|
py
|
import pytest
from vakt.storage.memory import MemoryStorage
from vakt.storage.observable import ObservableMutationStorage
from ..helper import CountObserver
from vakt import Policy, Inquiry
class TestObservableMutationStorage:
@pytest.fixture()
def factory(self):
def objects_factory():
mem = MemoryStorage()
st = ObservableMutationStorage(mem)
observer = CountObserver()
st.add_listener(observer)
return st, mem, observer
return objects_factory
def test_add(self, factory):
st, mem, observer = factory()
p1 = Policy(1)
p2 = Policy(2)
p3 = Policy(3)
st.add(p1)
st.add(p2)
assert 2 == observer.count
assert 2 == len(list(mem.retrieve_all()))
assert 2 == len(list(st.retrieve_all()))
st.add(p3)
assert 3 == observer.count
def test_get(self, factory):
st, mem, observer = factory()
p1 = Policy('a')
st.add(p1)
assert 'a' == st.get('a').uid
assert 'a' == mem.get('a').uid
assert 1 == observer.count
assert None is st.get('b')
assert None is mem.get('b')
assert 1 == observer.count
def test_update(self, factory):
st, mem, observer = factory()
p1 = Policy('a')
st.add(p1)
p1.uid = 'b'
st.update(p1)
assert 'b' == list(mem.retrieve_all())[0].uid
assert 'b' == list(st.retrieve_all())[0].uid
assert 2 == observer.count
p1.uid = 'c'
st.update(p1)
assert 3 == observer.count
def test_delete(self, factory):
st, mem, observer = factory()
p1 = Policy('a')
st.add(p1)
st.delete('a')
assert [] == list(mem.retrieve_all())
assert [] == list(st.retrieve_all())
assert 2 == observer.count
st.delete('a')
assert [] == list(mem.retrieve_all())
assert [] == list(st.retrieve_all())
assert 3 == observer.count
def test_retrieve_all(self, factory):
st, mem, observer = factory()
p1 = Policy('a')
st.add(p1)
assert 'a' == list(mem.retrieve_all())[0].uid
assert 'a' == list(st.retrieve_all())[0].uid
assert 1 == observer.count
assert 'a' == list(mem.retrieve_all(batch=2))[0].uid
assert 'a' == list(st.retrieve_all(batch=2))[0].uid
assert 1 == observer.count
assert 'a' == list(mem.retrieve_all(5))[0].uid
assert 'a' == list(st.retrieve_all(5))[0].uid
assert 1 == observer.count
def test_get_all(self, factory):
st, mem, observer = factory()
p1 = Policy('a')
st.add(p1)
assert 'a' == list(mem.get_all(5, 0))[0].uid
assert 'a' == list(st.get_all(5, 0))[0].uid
assert 1 == observer.count
st.get_all(9, 0)
st.get_all(888, 0)
assert 1 == observer.count
def test_find_for_inquiry(self, factory):
st, mem, observer = factory()
inq = Inquiry(action='get', subject='foo', resource='bar')
p1 = Policy('a')
p2 = Policy('b')
st.add(p1)
st.add(p2)
mem_found = list(mem.find_for_inquiry(inq))
assert [p1, p2] == mem_found or [p2, p1] == mem_found
st_found = list(st.find_for_inquiry(inq))
assert [p1, p2] == st_found or [p2, p1] == st_found
assert 2 == observer.count
st.find_for_inquiry(inq)
st.find_for_inquiry(inq)
assert 2 == observer.count
|
[
"kolotaev@tut.by"
] |
kolotaev@tut.by
|
2eda2a6491ee50990066f2822c92a82bbc2bf67d
|
1fe8d4133981e53e88abf633046060b56fae883e
|
/venv/lib/python3.8/site-packages/keras/api/_v2/keras/applications/efficientnet/__init__.py
|
a1937c921b8c52bf1875287a5e3e4aecfbfc8217
|
[] |
no_license
|
Akira331/flask-cifar10
|
6c49db8485038731ce67d23f0972b9574746c7a7
|
283e7a2867c77d4b6aba7aea9013bf241d35d76c
|
refs/heads/master
| 2023-06-14T16:35:06.384755
| 2021-07-05T14:09:15
| 2021-07-05T14:09:15
| 382,864,970
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 128
|
py
|
version https://git-lfs.github.com/spec/v1
oid sha256:31d32b42c854a00b62bce6763a16a669094ee5a52103e00e97a238c43ef7234c
size 894
|
[
"business030301@gmail.com"
] |
business030301@gmail.com
|
fb14339c19c7c98a958d8c1a2f148ae76f946893
|
6268a19db5d7806b3a91d6350ec2777b3e13cee6
|
/old_stuff/code/mlcv-exp_01/src/utils/fpha.py
|
e9b04c766cd61753ea10d92891cc0009d77a9fe8
|
[] |
no_license
|
aaronlws95/phd_2019
|
3ae48b4936f039f369be3a40404292182768cf3f
|
22ab0f5029b7d67d32421d06caaf3e8097a57772
|
refs/heads/master
| 2023-03-22T14:38:18.275184
| 2021-03-21T11:39:29
| 2021-03-21T11:39:29
| 186,387,381
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,871
|
py
|
from pathlib import Path
import numpy as np
from src import ROOT
# ========================================================
# CONSTANTS
# ========================================================
ORI_WIDTH = 1920
ORI_HEIGHT = 1080
REORDER_IDX = [0, 1, 6, 7, 8, 2, 9,
10, 11, 3, 12, 13, 14, 4,
15, 16, 17, 5, 18, 19, 20]
CAM_EXTR = [[0.999988496304, -0.00468848412856,
0.000982563360594, 25.7],
[0.00469115935266, 0.999985218048,
-0.00273845880292, 1.22],
[-0.000969709653873, 0.00274303671904,
0.99999576807, 3.902],
[0, 0, 0, 1]]
FOCAL_LENGTH_X_COLOR = 1395.749023
FOCAL_LENGTH_Y_COLOR = 1395.749268
X0_COLOR = 935.732544
Y0_COLOR = 540.681030
CAM_INTR_COLOR = [[FOCAL_LENGTH_X_COLOR, 0, X0_COLOR],
[0, FOCAL_LENGTH_Y_COLOR, Y0_COLOR],
[0, 0, 1]]
FOCAL_LENGTH_X_DEPTH = 475.065948
FOCAL_LENGTH_Y_DEPTH = 475.065857
X0_DEPTH = 315.944855
Y0_DEPTH = 245.287079
CAM_INTR_DEPTH = [[FOCAL_LENGTH_X_DEPTH, 0, X0_DEPTH],
[0, FOCAL_LENGTH_Y_DEPTH, Y0_DEPTH],
[0, 0, 1]]
BBOX_NORMUVD = [397, 361, 1004.3588]
BBSIZE = 260
INV_CAM_EXTR = [[0.99998855624950122256, 0.0046911597684540387191,
-0.00096970967236367877683, -25.701645303388132272],
[-0.0046884842637616731197, 0.99998527559956268165,
0.0027430368219501163773, -1.1101913203320408265],
[0.00098256339938933108913, -0.0027384588555197885184,
0.99999576732453258074, -3.9238944436608977969]]
# ========================================================
# XYZ UVD CONVERSION
# ========================================================
def uvd2xyz_depth(skel_uvd):
""" UVD space to XYZ space for depth """
skel_xyz = np.empty_like(skel_uvd).astype("float32")
fx0 = FOCAL_LENGTH_X_DEPTH
fy0 = FOCAL_LENGTH_Y_DEPTH
skel_xyz[...,0] = (skel_uvd[..., 0]-X0_DEPTH)/fx0*skel_uvd[..., 2]
skel_xyz[...,1] = (skel_uvd[..., 1]-Y0_DEPTH)/fy0*skel_uvd[..., 2]
skel_xyz[...,2] = skel_uvd[...,2]
return skel_xyz
def xyz2uvd_depth(skel_xyz):
""" XYZ space to UVD space for depth """
skel_uvd = np.empty_like(skel_xyz).astype("float32")
skel_uvd[..., 0] = X0_DEPTH + \
FOCAL_LENGTH_X_DEPTH*(skel_xyz[..., 0]/skel_xyz[..., 2])
skel_uvd[..., 1] = Y0_DEPTH + \
FOCAL_LENGTH_Y_DEPTH*(skel_xyz[..., 1]/skel_xyz[..., 2])
skel_uvd[..., 2] = skel_xyz[..., 2]
return skel_uvd
def xyz2uvd_color(skel_xyz):
""" XYZ space to UVD space for color """
skel_uvd = np.empty_like(skel_xyz).astype("float32")
ccs_x = CAM_EXTR[0][0]*skel_xyz[..., 0] + \
CAM_EXTR[0][1]*skel_xyz[..., 1] + \
CAM_EXTR[0][2]*skel_xyz[..., 2] + CAM_EXTR[0][3]
ccs_y = CAM_EXTR[1][0]*skel_xyz[..., 0] + \
CAM_EXTR[1][1]*skel_xyz[..., 1] + \
CAM_EXTR[1][2]*skel_xyz[..., 2] + CAM_EXTR[1][3]
ccs_z = CAM_EXTR[2][0]*skel_xyz[..., 0] + \
CAM_EXTR[2][1]*skel_xyz[..., 1] + \
CAM_EXTR[2][2]*skel_xyz[..., 2] + CAM_EXTR[2][3]
skel_uvd[..., 0] = X0_COLOR+FOCAL_LENGTH_X_COLOR*(ccs_x/ccs_z)
skel_uvd[..., 1] = Y0_COLOR+FOCAL_LENGTH_Y_COLOR*(ccs_y/ccs_z)
skel_uvd[..., 2] = ccs_z
return skel_uvd
def uvd2xyz_color(skel_uvd):
""" UVD space to XYZ space for color """
ccs_z = skel_uvd[..., 2]
ccs_x = ((skel_uvd[..., 0]-X0_COLOR)/FOCAL_LENGTH_X_COLOR)*ccs_z
ccs_y = ((skel_uvd[..., 1]-Y0_COLOR)/FOCAL_LENGTH_Y_COLOR)*ccs_z
skel_xyz = np.empty_like(skel_uvd).astype("float32")
skel_xyz[..., 0] = INV_CAM_EXTR[0][0]*ccs_x + \
INV_CAM_EXTR[0][1]*ccs_y + \
INV_CAM_EXTR[0][2]*ccs_z + INV_CAM_EXTR[0][3]
skel_xyz[..., 1] = INV_CAM_EXTR[1][0]*ccs_x + \
INV_CAM_EXTR[1][1]*ccs_y + \
INV_CAM_EXTR[1][2]*ccs_z + INV_CAM_EXTR[1][3]
skel_xyz[..., 2] = INV_CAM_EXTR[2][0]*ccs_x + \
INV_CAM_EXTR[2][1]*ccs_y + \
INV_CAM_EXTR[2][2]*ccs_z + INV_CAM_EXTR[2][3]
return skel_xyz
def xyz2ccs_color(skel_xyz):
""" XYZ space to camera coordinate space for color """
skel_ccs = np.empty_like(skel_xyz).astype("float32")
skel_ccs[..., 0] = CAM_EXTR[0][0]*skel_xyz[..., 0] + \
CAM_EXTR[0][1]*skel_xyz[..., 1] + \
CAM_EXTR[0][2]*skel_xyz[..., 2] + CAM_EXTR[0][3]
skel_ccs[..., 1] = CAM_EXTR[1][0]*skel_xyz[..., 0] + \
CAM_EXTR[1][1]*skel_xyz[..., 1] + \
CAM_EXTR[1][2]*skel_xyz[..., 2] + CAM_EXTR[1][3]
skel_ccs[..., 2] = CAM_EXTR[2][0]*skel_xyz[..., 0] + \
CAM_EXTR[2][1]*skel_xyz[..., 1] + \
CAM_EXTR[2][2]*skel_xyz[..., 2] + CAM_EXTR[2][3]
return skel_ccs
def ccs2uvd_color(skel_ccs):
""" Camera coordinate space to UVD for color """
skel_uvd = np.empty_like(skel_ccs).astype("float32")
skel_uvd[..., 0] = X0_COLOR + \
FOCAL_LENGTH_X_COLOR*(skel_ccs[..., 0]/skel_ccs[..., 2])
skel_uvd[..., 1] = Y0_COLOR + \
FOCAL_LENGTH_Y_COLOR*(skel_ccs[..., 1]/skel_ccs[..., 2])
skel_uvd[..., 2] = skel_ccs[..., 2]
return skel_uvd
def uvd2ccs_color(skel_uvd):
""" UVD space to camera coordinate space for color """
skel_ccs = np.empty_like(skel_uvd).astype("float32")
fx0 = FOCAL_LENGTH_X_COLOR
fy0 = FOCAL_LENGTH_Y_COLOR
skel_ccs[..., 2] = skel_uvd[..., 2]
skel_ccs[..., 0] = ((skel_uvd[..., 0] - X0_COLOR)/fx0)*skel_uvd[..., 2]
skel_ccs[..., 1] = ((skel_uvd[..., 1]- Y0_COLOR)/fy0)*skel_uvd[..., 2]
return skel_ccs
def ccs2xyz_color(skel_ccs):
""" Camera coordinate space to XYZ for color """
skel_xyz = np.empty_like(skel_ccs).astype("float32")
skel_xyz[..., 0] = INV_CAM_EXTR[0][0]*skel_ccs[..., 0] + \
INV_CAM_EXTR[0][1]*skel_ccs[..., 1] + \
INV_CAM_EXTR[0][2]*skel_ccs[..., 2] + INV_CAM_EXTR[0][3]
skel_xyz[..., 1] = INV_CAM_EXTR[1][0]*skel_ccs[..., 0] + \
INV_CAM_EXTR[1][1]*skel_ccs[..., 1] + \
INV_CAM_EXTR[1][2]*skel_ccs[..., 2] + INV_CAM_EXTR[1][3]
skel_xyz[..., 2] = INV_CAM_EXTR[2][0]*skel_ccs[..., 0] + \
INV_CAM_EXTR[2][1]*skel_ccs[..., 1] + \
INV_CAM_EXTR[2][2]*skel_ccs[..., 2] + INV_CAM_EXTR[2][3]
return skel_xyz
# ========================================================
# GET LABELS
# ========================================================
def get_action_dict():
action_dict = {}
action_list_dir = 'First_Person_Action_Benchmark/action_object_info.txt'
with open(Path(ROOT)/action_list_dir, 'r') as f:
lines = f.readlines()[1:]
for l in lines:
l = l.split(' ')
action_dict[int(l[0]) - 1] = l[1]
return action_dict
def get_obj_dict():
obj_dict = []
action_list_dir = 'First_Person_Action_Benchmark/action_object_info.txt'
with open(Path(ROOT)/action_list_dir, 'r') as f:
lines = f.readlines()[1:]
for l in lines:
l = l.split(' ')
obj_dict.append(l[2])
obj_dict = np.unique(obj_dict)
obj_dict = {v: k for v, k in enumerate(obj_dict)}
return obj_dict
|
[
"aaronlws95@gmail.com"
] |
aaronlws95@gmail.com
|
e10826db48bc30e47dd014c15a1662c7c79db3f1
|
27696870511ac02b75e4389fa4b54afa0f3978d0
|
/mysite/apps/users/forms.py
|
ed7cf48fadccff4eab2da9a21a8251c423c7a5d2
|
[] |
no_license
|
tminlun/OnlineEducation
|
ef4f7f6a3742b10dcaf4d263a9366fa1446d73fe
|
5008aeaa14a15b799d37fadd44c1c17b9ade7a68
|
refs/heads/master
| 2020-04-09T19:01:22.747193
| 2019-02-05T03:15:56
| 2019-02-05T03:15:56
| 160,531,635
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,687
|
py
|
from captcha.fields import CaptchaField
from django import forms
from .models import UserProfile
class LoginForm(forms.Form):
"""登录验证表单"""
username = forms.CharField(required=True)
password = forms.CharField(required=True, min_length=6)
class RegisterForm(forms.Form):
"""注册验证表单"""
username = forms.CharField(required=True, min_length=2,max_length=10)
email = forms.EmailField(required=True)
password = forms.CharField(required=True, min_length=6,max_length=20)
password_again = forms.CharField(required=True, min_length=6, max_length=20)
captcha = CaptchaField(error_messages={"invalid": "验证码输入错误"})#验证码,可以自定义错误。key(invalid是固定的),value自己可以随意写
class ForgetPwdForm(forms.Form):
"""找回密码表单"""
email = forms.EmailField(required=True)
captcha = CaptchaField(error_messages={"invalid": "验证码输入错误"})
class ModifyPwdForm(forms.Form):
"""找回密码表单"""
password1 = forms.CharField(required=True, min_length=6, max_length=15)
password2 = forms.CharField(required=True, min_length=6, max_length=15)
class ModifyImageForm(forms.ModelForm):
"""修改头像"""
class Meta:
model = UserProfile
fields = ['image']
class UpdatePwdForm(forms.Form):
password1 = forms.CharField(required=True, min_length=6, max_length=15)
password2 = forms.CharField(required=True, min_length=6, max_length=15)
class UpdateUserForm(forms.ModelForm):
"""修改个人信息"""
class Meta:
model = UserProfile
fields = ['nick_name', 'brithday', 'gander', 'adress', 'mobile']
|
[
"you@example.com"
] |
you@example.com
|
6871dbe97578fe8557bb9d770b9e99836a77fab7
|
ebf7427c8605d8654c67e3386b8adb2bd7503b44
|
/LeetCode Pattern/3. Backtracking/78_med_subsets.py
|
531b1f975ffeb5fe748d8104138d4181755a7f74
|
[] |
no_license
|
ryoman81/Leetcode-challenge
|
78e5bc4800a440052f8515c75829e669484fed40
|
fac3a49c49d2f62eafffb201a9d9cfac988ad30a
|
refs/heads/master
| 2023-09-04T05:21:54.569459
| 2021-10-26T14:14:08
| 2021-10-26T14:14:08
| 291,615,959
| 7
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,345
|
py
|
'''
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
All the numbers of nums are unique.
'''
class Solution:
'''
MY CODE VERSION
Thought:
Template:
- Almost the same as question to 77. combination
- We need to update result ANYTIME when we enter this recursion
Complexity:
Time: O(n * 2^n) - comparing to 46 and 77, this time complexity is more of a mathematical question. I copied it from official solution.
Space: O(n)
'''
def subsets(self, nums):
result = []
path = []
def backtracking (start):
# the subset requires anytime when recursion, it is one of the result
result.append(path[:])
# base case
if start == len(nums):
return
# search solution space
for i in range(start, len(nums)):
path.append(nums[i])
backtracking(i+1)
path.pop()
backtracking(0)
return result
## Run code after defining input and solver
input1 = [1,2,3]
solver = Solution().subsets
print(solver(input1))
|
[
"sqygg1002@gmail.com"
] |
sqygg1002@gmail.com
|
0d51133b3bdbcb43ffd745eeb543c357ff5a4faa
|
6443a587e16658a58b884a2e5c6dbbab1be50674
|
/Design_Patterns/MVC.py
|
41527a426a427ef6d6f168cc407aa49bd64086ef
|
[] |
no_license
|
xiaochenchen-PITT/CC150_Python
|
a6cbe213946851639a827068961934920b6c3e57
|
e96394265d8a41a1b4558d5d2b34aa34af99662f
|
refs/heads/master
| 2020-12-24T17:18:14.606804
| 2014-11-08T21:48:20
| 2014-11-08T21:48:20
| 25,654,100
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,175
|
py
|
import Tkinter as tk
class Observable:
"""class Observable defines the infrastructure of
model/view register and notification"""
def __init__(self, InitialValue = 0):
self.data = InitialValue
self.observer_list = []
def RegisterObserver(self, observer):
self.observer_list.append(observer)
def ObserverNotify(self):
for ov in self.observer_list:
ov.update(self.data)
def get(self):
return self.data
class Model(Observable):
"""Model extends its super class Observable and purely just functions"""
def __init__(self):
Observable.__init__(self)
def AddMoney(self, value):
self.data = self.get() + value
Observable.ObserverNotify(self)
def SubMoney(self, value):
self.data = self.get() - value
Observable.ObserverNotify(self)
class View(tk.Toplevel):
"""viewis the visual presentation of data"""
def __init__(self, master):
tk.Toplevel.__init__(self, master)
self.up_frame = tk.Frame(self)
self.up_frame.pack()
self.bottom_frame = tk.Frame(self)
self.bottom_frame.pack(side = 'bottom')
self.label = tk.Label(self.up_frame, text = 'My Money')
self.label.pack(side = 'left')
self.moneyDisplay = tk.Entry(self.up_frame, width = 8)
self.moneyDisplay.pack(side = 'left')
self.addButton = tk.Button(self.bottom_frame, text = 'Add', width = 8)
self.addButton.pack(side = 'left')
self.subButton = tk.Button(self.bottom_frame, text = 'Sub', width = 8)
self.subButton.pack(side = 'left')
def update(self, money):
self.moneyDisplay.delete(0, 'end')
self.moneyDisplay.insert('end', str(money))
class Controller:
"""Controller is the interconnection of model and view"""
def __init__(self, root):
self.model = Model()
self.view = View(root)
self.model.RegisterObserver(self.view)
self.view.addButton.config(command = self.AddMoney)
self.view.subButton.config(command = self.SubMoney)
self.MoneyChanged(self.model.get())
def AddMoney(self):
self.model.AddMoney(10)
def SubMoney(self):
self.model.SubMoney(10)
def MoneyChanged(self, money):
self.view.update(money)
if __name__ == '__main__':
root = tk.Tk()
root.withdraw()
whatever = Controller(root)
root.mainloop()
|
[
"cxc0520@hotmail.com"
] |
cxc0520@hotmail.com
|
587a5111f581fa6a8b63ab0fe2cce3dccbb8d97c
|
cb1d59b57510d222efcfcd37e7e4e919b6746d6e
|
/python/fizz_buzz.py
|
56c3fdeaade6e0122efa3841053aa624a1f63b6c
|
[] |
no_license
|
pzmrzy/LeetCode
|
416adb7c1066bc7b6870c6616de02bca161ef532
|
ef8c9422c481aa3c482933318c785ad28dd7703e
|
refs/heads/master
| 2021-06-05T14:32:33.178558
| 2021-05-17T03:35:49
| 2021-05-17T03:35:49
| 49,551,365
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 254
|
py
|
class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
return ["FizzBuzz" if n % 15 == 0 else "Fizz" if n % 3 == 0 else "Buzz" if n % 5 == 0 else str(n) for n in range(1, n + 1)]
|
[
"pzmrzy@gmail.com"
] |
pzmrzy@gmail.com
|
dff2d7ca09d52a201ba58b3ce5d4779e7271cb95
|
0c8214d0d7827a42225b629b7ebcb5d2b57904b0
|
/practice/P001_Matrix/main.py
|
e52128512ba48dafcdf746dde3478eb9df8fa36b
|
[] |
no_license
|
mertturkmenoglu/python-examples
|
831b54314410762c73fe2b9e77aee76fe32e24da
|
394072e1ca3e62b882d0d793394c135e9eb7a56e
|
refs/heads/master
| 2020-05-04T15:42:03.816771
| 2020-01-06T19:37:05
| 2020-01-06T19:37:05
| 179,252,826
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 175
|
py
|
# Practice 001: Read and print matrix
row = int(input('Row number: '))
col = int(input('Col number: '))
matrix = [[0 for _ in range(col)] for _ in range(row)]
print(matrix)
|
[
"mertturkmenoglu99@gmail.com"
] |
mertturkmenoglu99@gmail.com
|
3af938f6309801fbf139369b23994e67acc3176f
|
7949f96ee7feeaa163608dbd256b0b76d1b89258
|
/toontown/safezone/DistributedDDTreasure.py
|
97aff6809e6d0c59e21d67a112ed9c6dee2141f7
|
[] |
no_license
|
xxdecryptionxx/ToontownOnline
|
414619744b4c40588f9a86c8e01cb951ffe53e2d
|
e6c20e6ce56f2320217f2ddde8f632a63848bd6b
|
refs/heads/master
| 2021-01-11T03:08:59.934044
| 2018-07-27T01:26:21
| 2018-07-27T01:26:21
| 71,086,644
| 8
| 10
| null | 2018-06-01T00:13:34
| 2016-10-17T00:39:41
|
Python
|
UTF-8
|
Python
| false
| false
| 368
|
py
|
# File: t (Python 2.4)
import DistributedSZTreasure
class DistributedDDTreasure(DistributedSZTreasure.DistributedSZTreasure):
def __init__(self, cr):
DistributedSZTreasure.DistributedSZTreasure.__init__(self, cr)
self.modelPath = 'phase_6/models/props/starfish_treasure'
self.grabSoundPath = 'phase_4/audio/sfx/SZ_DD_treasure.mp3'
|
[
"fr1tzanatore@aol.com"
] |
fr1tzanatore@aol.com
|
6675c1f8bde9a8b0c7cdeeb0041b9769069edcca
|
d308fffe3db53b034132fb1ea6242a509f966630
|
/pirates/effects/LureGlow.py
|
e9c4eaabe605d5c76b88c0746c2a90f554148add
|
[
"BSD-3-Clause"
] |
permissive
|
rasheelprogrammer/pirates
|
83caac204965b77a1b9c630426588faa01a13391
|
6ca1e7d571c670b0d976f65e608235707b5737e3
|
refs/heads/master
| 2020-03-18T20:03:28.687123
| 2018-05-28T18:05:25
| 2018-05-28T18:05:25
| 135,193,362
| 3
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,824
|
py
|
# uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: pirates.effects.LureGlow
from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from EffectController import EffectController
from PooledEffect import PooledEffect
class LureGlow(PooledEffect, EffectController):
__module__ = __name__
def __init__(self):
PooledEffect.__init__(self)
EffectController.__init__(self)
model = loader.loadModel('models/effects/particleCards')
self.effectModel = model.find('**/particleSparkle')
self.effectModel.reparentTo(self)
self.effectColor = Vec4(1, 1, 1, 1)
self.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOne))
self.setTransparency(True)
self.setColorScaleOff()
self.setBillboardPointEye()
self.setDepthWrite(0)
self.setLightOff()
self.setFogOff()
self.effectModel.hide()
def createTrack(self):
self.effectModel.hide()
self.effectModel.setColorScale(self.effectColor)
pulseIval = Sequence(LerpScaleInterval(self.effectModel, duration=0.15, scale=3.5), LerpScaleInterval(self.effectModel, duration=0.15, scale=1.0))
self.startEffect = Sequence(Func(self.effectModel.show), Func(pulseIval.loop))
self.endEffect = Sequence(Func(pulseIval.finish), Func(self.cleanUpEffect))
self.track = Sequence(self.startEffect, Wait(1.0), self.endEffect)
def cleanUpEffect(self):
EffectController.cleanUpEffect(self)
self.checkInEffect(self)
def destroy(self):
EffectController.destroy(self)
PooledEffect.destroy(self)
|
[
"33942724+itsyaboyrocket@users.noreply.github.com"
] |
33942724+itsyaboyrocket@users.noreply.github.com
|
0b393c99acb69e2e47500842eda4d0fff53b69a6
|
4adc1d1b8f9badefcd8c25c6e0e87c6545ccde2c
|
/OrcApi/Driver/Web/WindowDefMod.py
|
81ea8efdc597472a2d1aed384e743b1cac1c6b9e
|
[] |
no_license
|
orange21cn/OrcTestToolsKit
|
eb7b67e87a608fb52d7bdcb2b859fa588263c136
|
69b6a3c382a7043872db1282df4be9e413d297d6
|
refs/heads/master
| 2020-04-15T07:30:35.485214
| 2017-09-30T06:16:17
| 2017-09-30T06:16:17
| 68,078,991
| 5
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,884
|
py
|
# -*- coding: utf-8 -*-
from datetime import datetime
from OrcLib.LibCommon import is_null
from OrcLib.LibException import OrcDatabaseException
from OrcLib.LibDatabase import WebWindowDef
from OrcLib.LibDatabase import orc_db
from OrcLib.LibLog import OrcLog
class WindowDefMod:
"""
Test data management
"""
__session = orc_db.session
__logger = OrcLog("api.driver.web.window_def")
def __init__(self):
pass
def usr_search(self, p_cond=None):
"""
查询符合条件的控件
:param p_cond:
:return:
"""
# 判断输入参数是否为空
cond = p_cond if p_cond else dict()
# 查询条件 like
_like = lambda p_flag: "%%%s%%" % cond[p_flag]
# db session
result = self.__session.query(WebWindowDef)
if 'id' in cond:
# 查询支持多 id
if isinstance(cond["id"], list):
result = result.filter(WebWindowDef.id.in_(cond['id']))
else:
result = result.filter(WebWindowDef.id == cond['id'])
if 'window_mark' in cond:
result = result.filter(WebWindowDef.window_mark.ilike(_like('window_mark')))
if 'window_desc' in cond:
result = result.filter(WebWindowDef.window_desc.ilike(_like('window_desc')))
if 'comment' in cond:
result = result.filter(WebWindowDef.comment.ilike(_like('comment')))
return result.all()
def usr_add(self, p_data):
"""
:param p_data:
:return:
"""
_node = WebWindowDef()
# Create id
_node.id = p_data['id']
# window_mark
_node.window_mark = p_data['window_mark'] if 'window_mark' in p_data else ""
# window_desc
_node.window_desc = p_data['window_desc'] if 'window_desc' in p_data else ""
# batch_desc, comment
_node.comment = p_data['comment'] if 'comment' in p_data else ""
# create_time, modify_time
_node.create_time = datetime.now()
_node.modify_time = datetime.now()
try:
self.__session.add(_node)
self.__session.commit()
except:
self.__logger.error("")
raise OrcDatabaseException
return _node
def usr_update(self, p_cond):
for t_id in p_cond:
if "id" == t_id:
continue
_data = None if is_null(p_cond[t_id]) else p_cond[t_id]
_item = self.__session.query(WebWindowDef).filter(WebWindowDef.id == p_cond['id'])
_item.update({t_id: _data})
self.__session.commit()
def usr_delete(self, p_id):
"""
Delete
:param p_id:
:return:
"""
self.__session.query(WebWindowDef).filter(WebWindowDef.id == p_id).delete()
self.__session.commit()
|
[
"orange21cn@126.com"
] |
orange21cn@126.com
|
3da8cd2718bcab6e44d110b99aeb4836a002db47
|
eae6dddca9285702c4c7ed6ba6bdaceef9631df2
|
/CCC-2019/Junior/Junior-2/J2.py
|
ead798d878460926221d2b7467237cbe4a4a29f4
|
[] |
no_license
|
simrit1/CCC-Solutions-2
|
7823ce14801c4219f6f1dd4c42fb013c2dfc45dd
|
ee2883aa38f933e526ce187d50ca68763876cb58
|
refs/heads/master
| 2023-07-04T02:19:37.320261
| 2021-08-07T22:12:36
| 2021-08-07T22:12:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 377
|
py
|
# CCC 2019 Junior 2: Time to Decompress
#
# Author: Charles Chen
#
# Strings and loops
num_lines = int(input())
num_symbols = []
symbol_type = []
for i in range(num_lines):
input_data = input().split()
num_symbols.append(int(input_data[0]))
symbol_type.append(input_data[1])
for i in range(num_lines):
print(symbol_type[i] * num_symbols[i])
|
[
"noreply@github.com"
] |
simrit1.noreply@github.com
|
d155f15f7ad2a469627d668066a70e11fe83b0b2
|
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
|
/Y4gwcGfcGb3SKz6Tu_0.py
|
e71f5bc1628a8c29847b14606c19007da771aeb7
|
[] |
no_license
|
daniel-reich/ubiquitous-fiesta
|
26e80f0082f8589e51d359ce7953117a3da7d38c
|
9af2700dbe59284f5697e612491499841a6c126f
|
refs/heads/master
| 2023-04-05T06:40:37.328213
| 2021-04-06T20:17:44
| 2021-04-06T20:17:44
| 355,318,759
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 203
|
py
|
def max_separator(s):
substrings = [(s.find(i, idx+1) - idx, i) for idx, i in enumerate(s) if s.find(i, idx+1) != -1]
return sorted([c for size, c in substrings if size == max(substrings)[0]])
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
37913c6ecbbbda6ad28bc4dac8635652653d5abb
|
23611933f0faba84fc82a1bc0a85d97cf45aba99
|
/google-cloud-sdk/.install/.backup/lib/surface/compute/instance_groups/managed/get_named_ports.py
|
adf1818f3b56f360348f6678bf9cbb31f379ccb2
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
KaranToor/MA450
|
1f112d1caccebdc04702a77d5a6cee867c15f75c
|
c98b58aeb0994e011df960163541e9379ae7ea06
|
refs/heads/master
| 2021-06-21T06:17:42.585908
| 2020-12-24T00:36:28
| 2020-12-24T00:36:28
| 79,285,433
| 1
| 1
|
Apache-2.0
| 2020-12-24T00:38:09
| 2017-01-18T00:05:44
|
Python
|
UTF-8
|
Python
| false
| false
| 2,035
|
py
|
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for listing named ports in instance groups."""
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import instance_groups_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.instance_groups import flags as instance_groups_flags
from googlecloudsdk.core import properties
class GetNamedPorts(base.ListCommand):
"""Implements get-named-ports command, alpha, and beta versions."""
def Format(self, unused_args):
return 'table(name, port)'
@staticmethod
def Args(parser):
instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_ARG.AddArgument(parser)
def Run(self, args):
"""Retrieves response with named ports."""
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
project = properties.VALUES.core.project.Get(required=True)
group_ref = (
instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_ARG.ResolveAsResource(
args, holder.resources,
default_scope=compute_scope.ScopeEnum.ZONE,
scope_lister=flags.GetDefaultScopeLister(
holder.client, project)))
return instance_groups_utils.OutputNamedPortsForGroup(
group_ref, holder.client)
detailed_help = (
instance_groups_utils.INSTANCE_GROUP_GET_NAMED_PORT_DETAILED_HELP)
|
[
"toork@uw.edu"
] |
toork@uw.edu
|
511d5d391655996dc02f37c3a43187003bad7158
|
17fe10b0f0f85765767ad0eceaf3d7118694ae80
|
/backend/event/api/v1/serializers.py
|
e4a19836dcba1b8de8bb160cfd2e4b1d0c1f056f
|
[] |
no_license
|
crowdbotics-apps/cotter-trout-dock-23862
|
5f2de4b3c820f49926d7b43ead203c8f3c8593b2
|
1e956b9b4572d324902af73b6ff4fdde1776f5b2
|
refs/heads/master
| 2023-02-12T21:13:52.324832
| 2021-01-15T16:17:01
| 2021-01-15T16:17:01
| 329,955,009
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,458
|
py
|
from rest_framework import serializers
from event.models import (
Vendor,
Location,
Favorites,
VendorDetail,
Category,
Faq,
Presenter,
Schedule,
MySchedule,
Sponsor,
)
class FaqSerializer(serializers.ModelSerializer):
class Meta:
model = Faq
fields = "__all__"
class SponsorSerializer(serializers.ModelSerializer):
class Meta:
model = Sponsor
fields = "__all__"
class FavoritesSerializer(serializers.ModelSerializer):
class Meta:
model = Favorites
fields = "__all__"
class ScheduleSerializer(serializers.ModelSerializer):
class Meta:
model = Schedule
fields = "__all__"
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = "__all__"
class VendorSerializer(serializers.ModelSerializer):
class Meta:
model = Vendor
fields = "__all__"
class VendorDetailSerializer(serializers.ModelSerializer):
class Meta:
model = VendorDetail
fields = "__all__"
class PresenterSerializer(serializers.ModelSerializer):
class Meta:
model = Presenter
fields = "__all__"
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = "__all__"
class MyScheduleSerializer(serializers.ModelSerializer):
class Meta:
model = MySchedule
fields = "__all__"
|
[
"team@crowdbotics.com"
] |
team@crowdbotics.com
|
dc573298a746f7d19680c66c688ceaaf5c15b85f
|
081b33ead95b323e77bdce3717af0a5790e34a1e
|
/backend/apps/settings/models.py
|
3692f2d192f0341b23781b392ab4a7de1f431656
|
[] |
no_license
|
alexmon1989/afliga
|
81ea3b32b18040bb8baa4e8af14a73003fb9a89f
|
661da30c0a5aa6b9975eb7dea9c9a031529d2dbb
|
refs/heads/master
| 2023-02-23T11:12:45.608118
| 2023-02-11T12:12:41
| 2023-02-11T12:12:41
| 105,630,198
| 0
| 0
| null | 2023-02-15T20:50:12
| 2017-10-03T08:36:15
|
Python
|
UTF-8
|
Python
| false
| false
| 2,744
|
py
|
from django.db import models
from apps.league.models import Player
class FooterSettings(models.Model):
"""Настройки футера."""
information_block_title = models.CharField('Заголовок текстового блока', max_length=100, null=True, blank=True)
information_block_text = models.TextField('Текст блока (html)', null=True, blank=True)
contacts_block_html = models.TextField(
'Текст блока "Контактная информация" (html)',
null=True,
blank=True
)
facebook_link = models.CharField('Ссылка Facebook', max_length=255, null=True, blank=True)
vk_link = models.CharField('Ссылка VK', max_length=255, null=True, blank=True)
twitter_link = models.CharField('Ссылка Twitter', max_length=255, null=True, blank=True)
google_link = models.CharField('Ссылка Google', max_length=255, null=True, blank=True)
copyrights_block_html = models.TextField(
'Текст блока копирайта (html)',
null=True,
blank=True
)
class Meta:
verbose_name = 'Footer'
verbose_name_plural = 'Footer'
class Banner(models.Model):
"""Модель баннера."""
title = models.CharField('Заголовок', max_length=255, blank=False)
is_visible = models.BooleanField('Включено', default=True)
link = models.CharField('Ссылка', max_length=255, null=True, blank=True)
image = models.ImageField('Изображение', upload_to='banners', null=True, blank=True)
created_at = models.DateTimeField('Создано', auto_now_add=True)
updated_at = models.DateTimeField('Обновлено', auto_now=True)
class Meta:
verbose_name = 'Баннер'
verbose_name_plural = 'Баннеры'
class PersonWidget(models.Model):
"""Настройки виджета персоны."""
title = models.CharField('Заголовок', max_length=255, default='Персона')
player = models.ForeignKey(Player, verbose_name='Игрок', on_delete=models.CASCADE)
is_visible = models.BooleanField('Включено', default=True)
class Meta:
verbose_name = 'Виджет "Персона"'
verbose_name_plural = 'Виджет "Персона"'
class Analytics(models.Model):
"""Модель HTML-кода аналитики."""
code = models.TextField('HTML-код')
created_at = models.DateTimeField('Создано', auto_now_add=True)
updated_at = models.DateTimeField('Обновлено', auto_now=True)
class Meta:
verbose_name = 'HTML-код аналитики'
verbose_name_plural = 'HTML-код аналитики'
|
[
"alex.mon1989@gmail.com"
] |
alex.mon1989@gmail.com
|
15715eaf8822905a4c32b90071642f1351caf2ba
|
2f54c561e13df5f0f4479e73a47103b8413a235a
|
/python codes/recursion.py
|
a4aa83e9d1dd41e409479f1902abf580bc1a520f
|
[] |
no_license
|
suvimanikandan/PYTHON_CODES
|
7123e2898d8c363e018477d2b60f26c7287d4e72
|
2a8eaae317a773b7236529021a333e9e2a40e51f
|
refs/heads/main
| 2023-04-03T19:45:06.009539
| 2021-04-20T05:26:44
| 2021-04-20T05:26:44
| 359,693,270
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 160
|
py
|
import sys
sys.setrecursionlimit(2000)
print(sys.getrecursionlimit())
i=0
def greet():
global i
i+=1
print("hello",i)
greet()
greet()
|
[
"noreply@github.com"
] |
suvimanikandan.noreply@github.com
|
5c0172e12c8046dfc13f3f6538b0c802f7623194
|
781e2692049e87a4256320c76e82a19be257a05d
|
/all_data/exercism_data/python/word-count/e606d579317c48f6b8b3ea5ff8b93984.py
|
42692983767720aa1ef6632e7378b60086e0a348
|
[] |
no_license
|
itsolutionscorp/AutoStyle-Clustering
|
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
|
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
|
refs/heads/master
| 2020-12-11T07:27:19.291038
| 2016-03-16T03:18:00
| 2016-03-16T03:18:42
| 59,454,921
| 4
| 0
| null | 2016-05-23T05:40:56
| 2016-05-23T05:40:56
| null |
UTF-8
|
Python
| false
| false
| 151
|
py
|
def word_count(phrase):
count = dict()
for word in phrase.split():
count.setdefault(word, 0)
count[word] += 1
return count
|
[
"rrc@berkeley.edu"
] |
rrc@berkeley.edu
|
eb8cfced5d54b2f954d35b0c31564dbadc38423d
|
91d1a6968b90d9d461e9a2ece12b465486e3ccc2
|
/codestar-notifications_write_1/notification-rule_update.py
|
a01451f4c062a17c803d10c7d64f8e5e744998b5
|
[] |
no_license
|
lxtxl/aws_cli
|
c31fc994c9a4296d6bac851e680d5adbf7e93481
|
aaf35df1b7509abf5601d3f09ff1fece482facda
|
refs/heads/master
| 2023-02-06T09:00:33.088379
| 2020-12-27T13:38:45
| 2020-12-27T13:38:45
| 318,686,394
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,466
|
py
|
#!/usr/bin/python
# -*- codding: utf-8 -*-
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from common.execute_command import write_one_parameter
# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/update-notification-rule.html
if __name__ == '__main__':
"""
create-notification-rule : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/create-notification-rule.html
delete-notification-rule : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/delete-notification-rule.html
describe-notification-rule : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/describe-notification-rule.html
list-notification-rules : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/list-notification-rules.html
"""
parameter_display_string = """
# arn : The Amazon Resource Name (ARN) of the notification rule.
"""
add_option_dict = {}
#######################################################################
# parameter display string
add_option_dict["parameter_display_string"] = parameter_display_string
# ex: add_option_dict["no_value_parameter_list"] = "--single-parameter"
write_one_parameter("codestar-notifications", "update-notification-rule", "arn", add_option_dict)
|
[
"hcseo77@gmail.com"
] |
hcseo77@gmail.com
|
0d1c6e2ddb041ef981f6b1c916b97199a9ef93b8
|
bd55b7fefa99156aeb3c28a4abfa407fc03c6bb1
|
/vstructui/scripts/vstructui_bin.py
|
66119705e9eec7b30622b45971dec5769cecb73d
|
[
"Apache-2.0"
] |
permissive
|
williballenthin/python-pyqt5-vstructui
|
175419738549f9a8ba97ced004c88561356ddcdc
|
2e06f5fed8aa362e07ad5f677fb42d5cd15163e1
|
refs/heads/master
| 2021-01-10T02:18:34.326960
| 2015-12-10T04:55:19
| 2015-12-10T04:55:19
| 36,752,901
| 10
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,669
|
py
|
import os
import sys
import imp
import mmap
import contextlib
from PyQt5.QtWidgets import QApplication
from vstruct import VStruct
from vstruct import VArray
from vstruct.primitives import v_prim
from vstruct.primitives import v_number
from vstruct.primitives import v_bytes
from vstruct.primitives import v_uint8
from vstruct.primitives import v_uint16
from vstruct.primitives import v_uint32
from vstructui.vstruct_parser import ComposedParser
from vstructui.vstruct_parser import VstructInstance
import vstructui
# TODO: use pkg_resources
defspath = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "defs")
def get_parsers(defspath=defspath):
parsers = ComposedParser()
for filename in os.listdir(defspath):
if not filename.endswith(".py"):
continue
deffilepath = os.path.join(defspath, filename)
mod = imp.load_source("vstruct_parser", deffilepath)
if not hasattr(mod, "vsEntryVstructParser"):
continue
parser = mod.vsEntryVstructParser()
parsers.add_parser(parser)
return parsers
_HEX_ALPHA_CHARS = set(list("abcdefABCDEF"))
def is_probably_hex(s):
if s.startswith("0x"):
return True
for c in s:
if c in _HEX_ALPHA_CHARS:
return True
return False
def _main(*args):
parsers = get_parsers()
buf = ""
structs = ()
filename = None
if len(args) == 0:
print("error: at least one argument required (path to binary file)")
return -1
# vstructui.py /path/to/binary/file "0x0:uint32:first dword" "0x4:uint_2:first word"
structs = []
args = list(args) # we want a list that we can modify
filename = args.pop(0)
with open(filename, "rb") as f:
with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as buf:
for d in args:
if ":" not in d:
raise RuntimeError("invalid structure declaration: {:s}".format(d))
soffset, _, parser_name = d.partition(":")
parser_name, _, name = parser_name.partition(":")
offset = None
if is_probably_hex(soffset):
offset = int(soffset, 0x10)
else:
offset = int(soffset)
structs.extend(parsers.parse(parser_name, buf, offset, name=name))
app = QApplication(sys.argv)
screen = vstructui.VstructViewWidget(parsers, structs, buf)
screen.show()
sys.exit(app.exec_())
def main():
sys.exit(_main(*sys.argv[1:]))
if __name__ == "__main__":
main()
|
[
"willi.ballenthin@gmail.com"
] |
willi.ballenthin@gmail.com
|
ae6d37bf310be7ced448efde5f9029f8a50c2e93
|
3da574f57da42ef745c59b121c70f0d89b98242d
|
/mandrill/mayhem_1.py
|
21868aebc9ee247f16ef4607f788a9bc5099a05d
|
[
"MIT"
] |
permissive
|
yijxiang/mayhem
|
5a93e184f4f0081d86e9651b815e01712297218a
|
521b1e4540d37395ca47908520183245b167e2b0
|
refs/heads/master
| 2021-09-20T03:28:13.509396
| 2018-08-02T17:22:02
| 2018-08-02T17:22:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,269
|
py
|
#!/usr/bin/env python3.7
# Copyright (c) 2018 Lynn Root
"""
Initial setup - starting point based off of
http://asyncio.readthedocs.io/en/latest/producer_consumer.html
Notice! This requires:
- attrs==18.1.0
"""
import asyncio
import logging
import random
import string
import attr
# NB: Using f-strings with log messages may not be ideal since no matter
# what the log level is set at, f-strings will always be evaluated
# whereas the old form ('foo %s' % 'bar') is lazily-evaluated.
# But I just love f-strings.
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s,%(msecs)d %(levelname)s: %(message)s',
datefmt='%H:%M:%S',
)
@attr.s
class PubSubMessage:
instance_name = attr.ib()
message_id = attr.ib(repr=False)
hostname = attr.ib(repr=False, init=False)
def __attrs_post_init__(self):
self.hostname = f'{self.instance_name}.example.net'
async def publish(queue, n):
"""Simulates an external publisher of messages.
Args:
queue (asyncio.Queue): Queue to publish messages to.
n (int): Number of messages to publish.
"""
choices = string.ascii_lowercase + string.digits
for x in range(1, n + 1):
host_id = ''.join(random.choices(choices, k=4))
instance_name = f'cattle-{host_id}'
msg = PubSubMessage(message_id=x, instance_name=instance_name)
# publish an item
await queue.put(msg)
logging.info(f'Published {x} of {n} messages')
# indicate the publisher is done
await queue.put(None)
async def consume(queue):
"""Consumer client to simulate subscribing to a publisher.
Args:
queue (asyncio.Queue): Queue from which to consume messages.
"""
while True:
# wait for an item from the publisher
msg = await queue.get()
# the publisher emits None to indicate that it is done
if msg is None:
break
# process the msg
logging.info(f'Consumed {msg}')
# unhelpful simulation of i/o work
await asyncio.sleep(random.random())
if __name__ == '__main__':
queue = asyncio.Queue()
publisher_coro = publish(queue, 5)
consumer_coro = consume(queue)
asyncio.run(publisher_coro)
asyncio.run(consumer_coro)
|
[
"lynn@lynnroot.com"
] |
lynn@lynnroot.com
|
052e64eed1a7060c8189bf73a146399bddecfa95
|
53784d3746eccb6d8fca540be9087a12f3713d1c
|
/res/packages/scripts/scripts/client/gui/prb_control/entities/base/pre_queue/listener.py
|
4911d5bab483ee2b93e16664718ddd92927ec370
|
[] |
no_license
|
webiumsk/WOT-0.9.17.1-CT
|
736666d53cbd0da6745b970e90a8bac6ea80813d
|
d7c3cf340ae40318933e7205bf9a17c7e53bac52
|
refs/heads/master
| 2021-01-09T06:00:33.898009
| 2017-02-03T21:40:17
| 2017-02-03T21:40:17
| 80,870,824
| 0
| 0
| null | null | null | null |
WINDOWS-1250
|
Python
| false
| false
| 2,051
|
py
|
# 2017.02.03 21:48:33 Střední Evropa (běžný čas)
# Embedded file name: scripts/client/gui/prb_control/entities/base/pre_queue/listener.py
from gui.prb_control.entities.base.listener import IPrbListener
class IPreQueueListener(IPrbListener):
"""
Interface of prequeue listener.
"""
def onEnqueued(self, queueType, *args):
"""
Event that is called when player goes into queue.
Args:
queueType: joined queue type
"""
pass
def onDequeued(self, queueType, *args):
"""
Event that is called when player leaves queue.
Args:
queueType: left queue type
"""
pass
def onEnqueueError(self, queueType, *args):
"""
Event that is called when player receives enqueue error.
Args:
queueType: queue type that we're trying to join
"""
pass
def onKickedFromQueue(self, queueType, *args):
"""
Event that is called when player was kicked from queue.
Args:
queueType: queue type that we're kicked from
"""
pass
def onKickedFromArena(self, queueType, *args):
"""
Event that is called when player was kicked from arena.
Args:
queueType: queue type that we're kicked from
"""
pass
def onArenaJoinFailure(self, queueType, *args):
"""
Event that is called when player was kicked during arena join.
Args:
queueType: queue type that we're kicked from
"""
pass
def onPreQueueSettingsChanged(self, diff):
"""
Event that is called when player receives settings updates.
Args:
diff: settings changes
"""
pass
# okay decompyling c:\Users\PC\wotsources\files\originals\res\packages\scripts\scripts\client\gui\prb_control\entities\base\pre_queue\listener.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2017.02.03 21:48:33 Střední Evropa (běžný čas)
|
[
"info@webium.sk"
] |
info@webium.sk
|
8fd3d7573ef2a7f903f530d6c758f8bdd40b49f9
|
bd498cbbb28e33370298a84b693f93a3058d3138
|
/NVIDIA/benchmarks/transformer/implementations/pytorch/fairseq/data/token_block_dataset.py
|
8c9239ff4ca7fef2bb06e97ece279c95a3aecae6
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
piyushghai/training_results_v0.7
|
afb303446e75e3e9789b0f6c40ce330b6b83a70c
|
e017c9359f66e2d814c6990d1ffa56654a73f5b0
|
refs/heads/master
| 2022-12-19T16:50:17.372320
| 2020-09-24T01:02:00
| 2020-09-24T18:01:01
| 298,127,245
| 0
| 1
|
Apache-2.0
| 2020-09-24T00:27:21
| 2020-09-24T00:27:21
| null |
UTF-8
|
Python
| false
| false
| 3,681
|
py
|
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import math
import numpy as np
import torch
class TokenBlockDataset(torch.utils.data.Dataset):
"""Break a 1d tensor of tokens into blocks.
The blocks are fetched from the original tensor so no additional memory is allocated.
Args:
tokens: 1d tensor of tokens to break into blocks
sizes: sentence lengths (required for 'complete' and 'eos')
block_size: maximum block size (ignored in 'eos' break mode)
break_mode: Mode used for breaking tokens. Values can be one of:
- 'none': break tokens into equally sized blocks (up to block_size)
- 'complete': break tokens into blocks (up to block_size) such that
blocks contains complete sentences, although block_size may be
exceeded if some sentences exceed block_size
- 'eos': each block contains one sentence (block_size is ignored)
include_targets: return next tokens as targets
"""
def __init__(self, tokens, sizes, block_size, break_mode=None, include_targets=False):
super().__init__()
self.tokens = tokens
self.total_size = len(tokens)
self.include_targets = include_targets
self.slice_indices = []
if break_mode is None or break_mode == 'none':
length = math.ceil(len(tokens) / block_size)
def block_at(i):
start = i * block_size
end = min(start + block_size, len(tokens))
return (start, end)
self.slice_indices = [block_at(i) for i in range(length)]
elif break_mode == 'complete':
assert sizes is not None and sum(sizes) == len(tokens), '{} != {}'.format(sum(sizes), len(tokens))
tok_idx = 0
sz_idx = 0
curr_size = 0
while sz_idx < len(sizes):
if curr_size + sizes[sz_idx] <= block_size or curr_size == 0:
curr_size += sizes[sz_idx]
sz_idx += 1
else:
self.slice_indices.append((tok_idx, tok_idx + curr_size))
tok_idx += curr_size
curr_size = 0
if curr_size > 0:
self.slice_indices.append((tok_idx, tok_idx + curr_size))
elif break_mode == 'eos':
assert sizes is not None and sum(sizes) == len(tokens), '{} != {}'.format(sum(sizes), len(tokens))
curr = 0
for sz in sizes:
# skip samples with just 1 example (which would be just the eos token)
if sz > 1:
self.slice_indices.append((curr, curr + sz))
curr += sz
else:
raise ValueError('Invalid break_mode: ' + break_mode)
self.sizes = np.array([e - s for s, e in self.slice_indices])
def __getitem__(self, index):
s, e = self.slice_indices[index]
item = torch.LongTensor(self.tokens[s:e])
if self.include_targets:
# target is the sentence, for source, rotate item one token to the left (would start with eos)
if s == 0:
source = np.concatenate([self.tokens[-1:], self.tokens[0:e - 1]])
else:
source = self.tokens[s - 1:e - 1]
return torch.LongTensor(source), item
return item
def __len__(self):
return len(self.slice_indices)
|
[
"vbittorf@google.com"
] |
vbittorf@google.com
|
68868e6f1a4c75f460454a8f20542df8dbbe4308
|
c2ddadd3cf14dfc56ec1e4b8d52b8c1a23ea1e61
|
/quiz/models.py
|
9e3fbcc7e92e0ec967ef6edc13c06711e68a42e2
|
[] |
no_license
|
ashimmitra/Varsity-Final-Project-by-Django
|
09f944a9f1aae7be4212f0c09cfe5d2c596bd848
|
6274d966f09d9ead2344542b56576a77e0758d5a
|
refs/heads/main
| 2023-07-17T15:50:04.414565
| 2021-08-20T12:31:24
| 2021-08-20T12:31:24
| 342,790,345
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,590
|
py
|
from django.db import models
# Create your models here.
class Quiz(models.Model):
question = models.CharField(max_length = 500)
option1 = models.CharField(max_length = 20)
option2 = models.CharField(max_length = 20)
option3 = models.CharField(max_length = 20)
option4 = models.CharField(max_length = 20)
answer = models.CharField(max_length = 20)
class Ban(models.Model):
question = models.CharField(max_length = 500)
option1 = models.CharField(max_length = 20)
option2 = models.CharField(max_length = 20)
option3 = models.CharField(max_length = 20)
option4 = models.CharField(max_length = 20)
answer = models.CharField(max_length = 20)
#class ICT(models.Model):
#question = models.CharField(max_length = 500)
#option1 = models.CharField(max_length = 20)
#option2 = models.CharField(max_length = 20)
#option3 = models.CharField(max_length = 20)
#option4 = models.CharField(max_length = 20)
#answer = models.CharField(max_length = 20)
class Science(models.Model):
question = models.CharField(max_length = 500)
option1 = models.CharField(max_length = 20)
option2 = models.CharField(max_length = 20)
option3 = models.CharField(max_length = 20)
option4 = models.CharField(max_length = 20)
answer = models.CharField(max_length = 20)
class Math(models.Model):
question = models.CharField(max_length = 500)
option1 = models.CharField(max_length = 20)
option2 = models.CharField(max_length = 20)
option3 = models.CharField(max_length = 20)
option4 = models.CharField(max_length = 20)
answer = models.CharField(max_length = 20)
class GK(models.Model):
question = models.CharField(max_length = 500)
option1 = models.CharField(max_length = 20)
option2 = models.CharField(max_length = 20)
option3 = models.CharField(max_length = 20)
option4 = models.CharField(max_length = 20)
answer = models.CharField(max_length = 20)
class MA(models.Model):
question = models.CharField(max_length = 500)
option1 = models.CharField(max_length = 20)
option2 = models.CharField(max_length = 20)
option3 = models.CharField(max_length = 20)
option4 = models.CharField(max_length = 20)
answer = models.CharField(max_length = 20)
class IC(models.Model):
question = models.CharField(max_length = 500)
option1 = models.CharField(max_length = 20)
option2 = models.CharField(max_length = 20)
option3 = models.CharField(max_length = 20)
option4 = models.CharField(max_length = 20)
answer = models.CharField(max_length = 20)
|
[
"34328617+ashimmitra@users.noreply.github.com"
] |
34328617+ashimmitra@users.noreply.github.com
|
2db4dae997653d84e0371a2931389dd011acab93
|
30a2f77f5427a3fe89e8d7980a4b67fe7526de2c
|
/gen/RSGravitonToBBbar_M_650_TuneZ2star_8TeV_pythia6_cfg.py
|
58a5a616d4582034f7a015e59624302553db3e82
|
[] |
no_license
|
DryRun/QCDAnalysis
|
7fb145ce05e1a7862ee2185220112a00cb8feb72
|
adf97713956d7a017189901e858e5c2b4b8339b6
|
refs/heads/master
| 2020-04-06T04:23:44.112686
| 2018-01-08T19:47:01
| 2018-01-08T19:47:01
| 55,909,998
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,080
|
py
|
# Auto generated configuration file
# using:
# Revision: 1.381.2.28
# Source: /local/reps/CMSSW/CMSSW/Configuration/PyReleaseValidation/python/ConfigBuilder.py,v
# with command line options: CMSDIJET/QCDAnalysis/python/RSGravitonToBBbar_M_650_TuneZ2star_8TeV_pythia6_cff.py --python_filename /uscms/home/dryu/Dijets/CMSSW_5_3_32_patch3/src/CMSDIJET/QCDAnalysis/gen/RSGravitonToBBbar_M_650_TuneZ2star_8TeV_pythia6_cfg.py --fileout file:RSGravitonToBBbar_M_650_TuneZ2star_8TeV_pythia6_FastSim_RECOSIM.root --step GEN,FASTSIM,HLT:7E33v2 --mc --eventcontent RECOSIM --datatier GEN-SIM-DIGI-RECO --pileup 2012_Startup_inTimeOnly --geometry DB --conditions auto:mc --beamspot Realistic8TeVCollision --no_exec -n 1000
import FWCore.ParameterSet.Config as cms
process = cms.Process('HLT')
# import of standard configurations
process.load('Configuration.StandardSequences.Services_cff')
process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')
process.load('FWCore.MessageService.MessageLogger_cfi')
process.load('FastSimulation.Configuration.EventContent_cff')
process.load('FastSimulation.PileUpProducer.PileUpSimulator_2012_Startup_inTimeOnly_cff')
process.load('FastSimulation.Configuration.Geometries_MC_cff')
process.load('Configuration.StandardSequences.MagneticField_38T_cff')
process.load('Configuration.StandardSequences.Generator_cff')
process.load('GeneratorInterface.Core.genFilterSummary_cff')
process.load('FastSimulation.Configuration.FamosSequences_cff')
process.load('IOMC.EventVertexGenerators.VtxSmearedParameters_cfi')
process.load('HLTrigger.Configuration.HLT_7E33v2_Famos_cff')
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1000)
)
# Input source
process.source = cms.Source("EmptySource")
process.options = cms.untracked.PSet(
)
# Production Info
process.configurationMetadata = cms.untracked.PSet(
version = cms.untracked.string('$Revision: 1.381.2.28 $'),
annotation = cms.untracked.string('CMSDIJET/QCDAnalysis/python/RSGravitonToBBbar_M_650_TuneZ2star_8TeV_pythia6_cff.py nevts:1000'),
name = cms.untracked.string('PyReleaseValidation')
)
# Output definition
process.RECOSIMoutput = cms.OutputModule("PoolOutputModule",
splitLevel = cms.untracked.int32(0),
eventAutoFlushCompressedSize = cms.untracked.int32(5242880),
outputCommands = process.RECOSIMEventContent.outputCommands,
fileName = cms.untracked.string('file:RSGravitonToBBbar_M_650_TuneZ2star_8TeV_pythia6_FastSim_RECOSIM.root'),
dataset = cms.untracked.PSet(
filterName = cms.untracked.string(''),
dataTier = cms.untracked.string('GEN-SIM-DIGI-RECO')
),
SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('generation_step')
)
)
# Additional output definition
# Other statements
process.genstepfilter.triggerConditions=cms.vstring("generation_step")
process.famosSimHits.SimulateCalorimetry = True
process.famosSimHits.SimulateTracking = True
process.simulation = cms.Sequence(process.simulationWithFamos)
process.HLTEndSequence = cms.Sequence(process.reconstructionWithFamos)
process.Realistic8TeVCollisionVtxSmearingParameters.type = cms.string("BetaFunc")
process.famosSimHits.VertexGenerator = process.Realistic8TeVCollisionVtxSmearingParameters
process.famosPileUp.VertexGenerator = process.Realistic8TeVCollisionVtxSmearingParameters
from Configuration.AlCa.GlobalTag import GlobalTag
process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:mc', '')
process.generator = cms.EDFilter("Pythia6GeneratorFilter",
pythiaPylistVerbosity = cms.untracked.int32(1),
filterEfficiency = cms.untracked.double(1.0),
pythiaHepMCVerbosity = cms.untracked.bool(False),
comEnergy = cms.double(8000.0),
crossSection = cms.untracked.double(13.12),
maxEventsToPrint = cms.untracked.int32(0),
PythiaParameters = cms.PSet(
pythiaUESettings = cms.vstring('MSTU(21)=1 ! Check on possible errors during program execution',
'MSTJ(22)=2 ! Decay those unstable particles',
'PARJ(71)=10 . ! for which ctau 10 mm',
'MSTP(33)=0 ! no K factors in hard cross sections',
'MSTP(2)=1 ! which order running alphaS',
'MSTP(51)=10042 ! structure function chosen (external PDF CTEQ6L1)',
'MSTP(52)=2 ! work with LHAPDF',
'PARP(82)=1.921 ! pt cutoff for multiparton interactions',
'PARP(89)=1800. ! sqrts for which PARP82 is set',
'PARP(90)=0.227 ! Multiple interactions: rescaling power',
'MSTP(95)=6 ! CR (color reconnection parameters)',
'PARP(77)=1.016 ! CR',
'PARP(78)=0.538 ! CR',
'PARP(80)=0.1 ! Prob. colored parton from BBR',
'PARP(83)=0.356 ! Multiple interactions: matter distribution parameter',
'PARP(84)=0.651 ! Multiple interactions: matter distribution parameter',
'PARP(62)=1.025 ! ISR cutoff',
'MSTP(91)=1 ! Gaussian primordial kT',
'PARP(93)=10.0 ! primordial kT-max',
'MSTP(81)=21 ! multiple parton interactions 1 is Pythia default',
'MSTP(82)=4 ! Defines the multi-parton model'),
processParameters = cms.vstring('PMAS(347,1)= 650 ! mass of RS Graviton',
'PARP(50) = 0.54 ! 0.54 == c=0.1 (k/M_PL=0.1)',
'MSEL=0 ! (D=1) to select between full user control (0, then use MSUB) and some preprogrammed alternative',
'MSUB(391)=1 ! q qbar -> G* ',
'MSUB(392)=1 ! g g -> G*',
'5000039:ALLOFF ! Turn off all decays of G*',
'5000039:ONIFANY 5 ! Turn on the decay b bbar'),
parameterSets = cms.vstring('pythiaUESettings',
'processParameters')
)
)
process.ProductionFilterSequence = cms.Sequence(process.generator)
# Path and EndPath definitions
process.generation_step = cms.Path(process.pgen_genonly)
process.reconstruction = cms.Path(process.reconstructionWithFamos)
process.genfiltersummary_step = cms.EndPath(process.genFilterSummary)
process.RECOSIMoutput_step = cms.EndPath(process.RECOSIMoutput)
# Schedule definition
process.schedule = cms.Schedule(process.generation_step,process.genfiltersummary_step)
process.schedule.extend(process.HLTSchedule)
process.schedule.extend([process.reconstruction,process.RECOSIMoutput_step])
# filter all path with the production filter sequence
for path in process.paths:
getattr(process,path)._seq = process.ProductionFilterSequence * getattr(process,path)._seq
# customisation of the process.
# Automatic addition of the customisation function from HLTrigger.Configuration.customizeHLTforMC
from HLTrigger.Configuration.customizeHLTforMC import customizeHLTforMC
#call to customisation function customizeHLTforMC imported from HLTrigger.Configuration.customizeHLTforMC
process = customizeHLTforMC(process)
# End of customisation functions
|
[
"david.renhwa.yu@gmail.com"
] |
david.renhwa.yu@gmail.com
|
48cd1bdae7a1166b75c4968c0fb1f53f4f29376d
|
235bf57e37733cf265913ba2d6e7e95f915dad06
|
/pricealert.py
|
4e0e80488f9c421adb80ddd7ee79747cf8f801c9
|
[] |
no_license
|
dbrgn/avarulo
|
47c3e3ea129a6d80afe55b81e3a62e513f526f47
|
bf48d2f6a19bb2f0af0ccecb83c70b9bef3affa2
|
refs/heads/master
| 2021-05-22T18:13:33.359090
| 2020-04-04T15:56:58
| 2020-04-04T15:56:58
| 253,034,903
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,065
|
py
|
"""
Price Alert
Monitor products for price reductions.
Usage:
pricealert.py [-c <configfile>]
Options:
-c <configfile> [default: config.yml]
"""
import re
import sys
from typing import Optional, Tuple
from bs4 import BeautifulSoup
from docopt import docopt
import requests
import yaml
USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64; rv:74.0) Gecko/20100101 Firefox/74.0'
def fetch(url: str, raw: bool = False) -> BeautifulSoup:
response = requests.get(url, headers={'User-Agent': USER_AGENT})
response.raise_for_status()
if raw:
return response.text
return BeautifulSoup(response.text, 'html.parser')
def check_galaxus(url: str) -> Tuple[float, Optional[float]]:
"""
Check the price on galaxus.ch.
Current price:
<meta content="49" property="product:price:amount"/>
Regular price:
<meta content="72.4" property="og:price:standard_amount"/>
"""
soup = fetch(url)
current = float(soup.find('meta', property='product:price:amount').get('content'))
standard_amount_meta = soup.find('meta', property='og:price:standard_amount')
if standard_amount_meta:
regular = float(standard_amount_meta.get('content')) # type: Optional[float]
else:
regular = None
return (current, regular)
def check_baechli(url: str) -> Tuple[float, Optional[float]]:
"""
Check the price on baechli-bergsport.ch.
Current price:
<meta content="49" property="product:price:amount"/>
Regular price: ??
"""
soup = fetch(url)
current = float(soup.find('meta', property='product:price:amount').get('content'))
return (current, None)
def check_intersport(url: str) -> Tuple[float, Optional[float]]:
"""
Check the price on achermannsport.ch.
Raw data:
<div class="summary entry-summary">
<h1 class="product_title entry-title">Ligtning Ascent 22 Women raspberry und Gunmetal</h1>
<p class="price">
<del><span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">CHF</span> 379.00</span></del>
<ins><span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">CHF</span> 299.90</span></ins>
</p>
...
Raw data (no rebate):
<div class="summary entry-summary">
<h1 class="product_title entry-title">Ligtning Ascent 22 Women raspberry und Gunmetal</h1>
<p class="price">
<span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">CHF</span> 29.00</span>
</p>
...
"""
soup = fetch(url)
summary = soup.find('div', class_='entry-summary')
prices = summary.find(class_='price')
regular = prices.find('del', recursive=False)
current = prices.find('ins', recursive=False)
def _get_price(element) -> float:
parts = element.find(class_='amount').text.split('\xa0')
assert parts[0] == 'CHF'
return float(parts[1])
if regular and current:
return (_get_price(current), _get_price(regular))
else:
return (_get_price(prices), None)
def check_primal(url: str) -> Tuple[float, Optional[float]]:
"""
Check the price on primal.ch.
Current price:
<meta itemprop="price" content="284.90">
Regular price:
<span class="price--line-through">CHF 469.00 *</span>
"""
soup = fetch(url)
current = float(soup.find('meta', itemprop='price').get('content'))
regular_element = soup.find('span', class_='price--line-through')
if regular_element:
regular = float(re.findall(r'[\d\.]+', regular_element.text)[0])
return (current, regular)
else:
return (current, None)
def check_transa(url: str) -> Tuple[float, Optional[float]]:
"""
Check the price on transa.ch.
Non-promo:
price: {
base: '',
promo: 'CHF 379.90',
savings: 'CHF 0.00',
reducedPriceInfoText: 'Streichpreis entspricht dem zuletzt angezeigten Preis im Onlineshop.',
basicPrice: ''
},
Promo:
price: {
base: 'CHF 899.90',
promo: 'CHF 629.90',
savings: 'CHF 270.00',
reducedPriceInfoText: 'Streichpreis entspricht dem zuletzt angezeigten Preis im Onlineshop.',
basicPrice: ''
},
"""
text = fetch(url, raw=True)
prices = {}
matches = filter(
None,
[re.match(r"^\s*(base|promo): 'CHF ([^']*)',$", line) for line in text.splitlines()],
)
for match in matches:
prices[match.group(1)] = float(match.group(2))
return (prices['promo'], prices.get('base'))
def _load_check_fn(shop: dict) -> dict:
"""
Load a check function by name.
"""
func = globals().get(shop['check_func'])
if func is None:
raise ValueError('Check func not found: {}'.format(shop['check_func']))
shop['check_func'] = func
return shop
def main(config: dict):
# Load shops
shops = {
k: _load_check_fn(v)
for k, v
in config['shops'].items()
}
for product in config['products']:
print('Checking {}:'.format(product['name']))
for shop_id, url in product['shops'].items():
shop = shops[shop_id]
prices = shop['check_func'](url)
print(' {}: {:.2f} CHF'.format(shop['name'], prices[0]), end='')
if prices[1] is None:
print()
else:
assert prices[1] > prices[0], prices
print(' (statt {:.2f} CHF)'.format(prices[1]))
print()
if __name__ == '__main__':
args = docopt(__doc__, version='Price Alert 0.1')
configfile = args['-c'] or 'config.yml'
with open(configfile, 'r') as f:
try:
config = yaml.safe_load(f)
except yaml.YAMLError as e:
print('Could not load config file: {}'.format(e))
sys.exit(1)
main(config)
|
[
"mail@dbrgn.ch"
] |
mail@dbrgn.ch
|
8416beada435e65a21c8e0124f100302ee9f9bf5
|
71501709864eff17c873abbb97ffabbeba4cb5e3
|
/llvm14.0.4/lldb/test/API/functionalities/data-formatter/type_summary_list_arg/TestTypeSummaryListArg.py
|
a47d91434822e44e560cc297352404f11b7429aa
|
[
"NCSA",
"Apache-2.0",
"LLVM-exception"
] |
permissive
|
LEA0317/LLVM-VideoCore4
|
d08ba6e6f26f7893709d3285bdbd67442b3e1651
|
7ae2304339760685e8b5556aacc7e9eee91de05c
|
refs/heads/master
| 2022-06-22T15:15:52.112867
| 2022-06-09T08:45:24
| 2022-06-09T08:45:24
| 189,765,789
| 1
| 0
|
NOASSERTION
| 2019-06-01T18:31:29
| 2019-06-01T18:31:29
| null |
UTF-8
|
Python
| false
| false
| 1,235
|
py
|
"""
Test lldb data formatter subsystem.
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TypeSummaryListArgumentTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
@no_debug_info_test
def test_type_summary_list_with_arg(self):
"""Test that the 'type summary list' command handles command line arguments properly"""
self.expect(
'type summary list Foo',
substrs=[
'Category: default',
'Category: system'])
self.expect(
'type summary list char',
substrs=[
'char ?(\*|\[\])',
'char ?\[[0-9]+\]'])
self.expect(
'type summary list -w default',
substrs=['system'],
matching=False)
self.expect(
'type summary list -w system unsigned',
substrs=[
'default',
'0-9'],
matching=False)
self.expect(
'type summary list -w system char',
substrs=[
'char ?(\*|\[\])',
'char ?\[[0-9]+\]'],
matching=True)
|
[
"kontoshi0317@gmail.com"
] |
kontoshi0317@gmail.com
|
16ac290fc3f25f1b9ba3e8307728a0f77ff6b606
|
d90daf0b839349d49439037f6bffe37830e165aa
|
/settings.py
|
c9ae21702e837243477afde60e6e602c6faf4b9f
|
[] |
no_license
|
m2o/fitlog
|
2d49ecff12069769c88617f07c600512ef2a0c97
|
e8736a3bc677d1d160cf7f3b6201ffa1b0de2760
|
refs/heads/master
| 2020-05-20T08:54:27.169217
| 2013-12-12T21:24:42
| 2013-12-12T21:24:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,858
|
py
|
# Django settings for fitlog project.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ROOT_PATH = os.path.dirname(__file__)
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.postgresql_psycopg2',
#'NAME' : 'fitlog_db',
#'HOST' : 'localhost',
#'PORT' : '',
#'USER' : 'fitloguser',
#'PASSWORD' : 'fitlogpass'
}
}
DATABASES['default'] = {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ROOT_PATH,'fitlogdb'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = None
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(ROOT_PATH, 'site_media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '#i+-%8t=-79_pzu7q5yy367h_x5662w!_e9(@z4h9ns5s7i!0x'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'fitlog.urls'
TEMPLATE_DIRS = (
os.path.join(ROOT_PATH,'fitlogapp/templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'fitlogapp',
'fitlogmodel',
'tagging',
'django.contrib.admin',
'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
|
[
"t.pivcevic@gmail.com"
] |
t.pivcevic@gmail.com
|
ff59ca30001dc596066bc271b4203a45b303fe6e
|
52e8841ac9603e994fc487ecb52f232e55a50e07
|
/Bio/GA/Selection/RouletteWheel.py
|
0dc44d9302247f22c95f690600dd792906fdb1dd
|
[] |
no_license
|
rored/RozszerzenieBio.PDB
|
aff434fddfe57199a7465f79126eba62b1c789ae
|
7c9d696faacabff912b1263fe19291d6a198c3c2
|
refs/heads/master
| 2021-01-21T04:50:37.903227
| 2016-06-23T19:15:42
| 2016-06-23T19:15:42
| 55,064,794
| 0
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,863
|
py
|
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
#
"""Implement Roulette Wheel selection on a population.
This implements Roulette Wheel selection in which individuals are
selected from a population randomly, with their proportion of selection
based on their relative fitness in the population.
"""
# standard modules
import random
import copy
# local modules
from .Abstract import AbstractSelection
__docformat__ = "restructuredtext en"
class RouletteWheelSelection(AbstractSelection):
"""Roulette wheel selection proportional to individuals fitness.
The implements a roulette wheel selector that selects individuals
from the population, and performs mutation and crossover on
the selected individuals.
"""
def __init__(self, mutator, crossover, repairer=None):
"""Initialize the selector.
Arguments:
o mutator -- A Mutation object which will perform mutation
on an individual.
o crossover -- A Crossover object which will take two
individuals and produce two new individuals which may
have had crossover occur.
o repairer -- A class which can do repair on rearranged genomes
to eliminate infeasible individuals. If set at None, so repair
will be done.
"""
AbstractSelection.__init__(self, mutator, crossover, repairer)
def select(self, population):
"""Perform selection on the population based using a Roulette model.
Arguments:
o population -- A population of organisms on which we will perform
selection. The individuals are assumed to have fitness values which
are due to their current genome.
"""
# set up the current probabilities for selecting organisms
# from the population
prob_wheel = self._set_up_wheel(population)
probs = sorted(prob_wheel)
# now create the new population with the same size as the original
new_population = []
for pair_spin in range(len(population) // 2):
# select two individuals using roulette wheel selection
choice_num_1 = random.random()
choice_num_2 = random.random()
# now grab the two organisms from the probabilities
chosen_org_1 = None
chosen_org_2 = None
prev_prob = 0
for cur_prob in probs:
if choice_num_1 > prev_prob and choice_num_1 <= cur_prob:
chosen_org_1 = prob_wheel[cur_prob]
if choice_num_2 > prev_prob and choice_num_2 <= cur_prob:
chosen_org_2 = prob_wheel[cur_prob]
prev_prob = cur_prob
assert chosen_org_1 is not None, "Didn't select organism one"
assert chosen_org_2 is not None, "Didn't select organism two"
# do mutation and crossover to get the new organisms
new_org_1, new_org_2 = self.mutate_and_crossover(chosen_org_1,
chosen_org_2)
new_population.extend([new_org_1, new_org_2])
return new_population
def _set_up_wheel(self, population):
"""Set up the roulette wheel based on the fitnesses.
This creates a fitness proportional 'wheel' that will be used for
selecting based on random numbers.
Returns:
o A dictionary where the keys are the 'high' value that an
individual will be selected. The low value is determined by
the previous key in a sorted list of keys. For instance, if we
have a sorted list of keys like:
[.1, .3, .7, 1]
Then the individual whose key is .1 will be selected if a number
between 0 and .1 is chosen, the individual whose key is .3 will
be selected if the number is between .1 and .3, and so on.
The values of the dictionary are the organism instances.
"""
# first sum up the total fitness in the population
total_fitness = 0
for org in population:
total_fitness += org.fitness
# now create the wheel dictionary for all of the individuals
wheel_dict = {}
total_percentage = 0
for org in population:
org_percentage = float(org.fitness) / float(total_fitness)
# the organisms chance of being picked goes from the previous
# percentage (total_percentage) to the previous percentage
# plus the organisms specific fitness percentage
wheel_dict[total_percentage + org_percentage] = copy.copy(org)
# keep a running total of where we are at in the percentages
total_percentage += org_percentage
return wheel_dict
|
[
"Viktoria@MacBook-Pro-Viktoria.local"
] |
Viktoria@MacBook-Pro-Viktoria.local
|
4b20434b8674ccfded74054b0a37ae33caa44811
|
4fbd844113ec9d8c526d5f186274b40ad5502aa3
|
/algorithms/python3/perfect_rectangle.py
|
adda3b9866b4f36c19ea7e24a53d4cded0ddd0ba
|
[] |
no_license
|
capric8416/leetcode
|
51f9bdc3fa26b010e8a1e8203a7e1bcd70ace9e1
|
503b2e303b10a455be9596c31975ee7973819a3c
|
refs/heads/master
| 2022-07-16T21:41:07.492706
| 2020-04-22T06:18:16
| 2020-04-22T06:18:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,302
|
py
|
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region.
Each rectangle is represented as a bottom-left point and a top-right point.
For example, a unit square is represented as [1,1,2,2].
(coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)).
Example 1:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[3,2,4,4],
[1,3,2,4],
[2,3,3,4]
]
Return true.
All 5 rectangles together form an exact cover of a rectangular region.
Example 2:
rectangles = [
[1,1,2,3],
[1,3,2,4],
[3,1,4,2],
[3,2,4,4]
]
Return false.
Because there is a gap between the two rectangular regions.
Example 3:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[3,2,4,4]
]
Return false.
Because there is a gap in the top center.
Example 4:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[2,2,4,4]
]
Return false.
Because two of the rectangles overlap with each other.
"""
""" ==================== body ==================== """
class Solution:
def isRectangleCover(self, rectangles):
"""
:type rectangles: List[List[int]]
:rtype: bool
"""
""" ==================== body ==================== """
|
[
"capric8416@gmail.com"
] |
capric8416@gmail.com
|
56afaf83d0bb5a2323b007f43c24edf5e93f4b66
|
3e381dc0a265afd955e23c85dce1e79e2b1c5549
|
/hi-A5/kacayyasadin.py
|
67e22449145123ac051f0a67ea72997107d722c8
|
[] |
no_license
|
serkancam/byfp2-2020-2021
|
3addeb92a3ff5616cd6dbd3ae7b2673e1a1a1a5e
|
c67206bf5506239d967c3b1ba75f9e08fdbad162
|
refs/heads/master
| 2023-05-05T04:36:21.525621
| 2021-05-29T11:56:27
| 2021-05-29T11:56:27
| 322,643,962
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 149
|
py
|
d_yil=int(input("hangi yıl doğdun:"))
d_ay=int(input("kaçın ay doğdun:"))
y_ay = (2020-d_yil)*12+(11-d_ay)
print(y_ay," ay yaşadın.")
|
[
"sekocam@gmail.com"
] |
sekocam@gmail.com
|
682de6a4f15064d60f1678610e503b2d3074a33e
|
ab704c85613bc430dfbb4e5d8ed139ba0a1da584
|
/manage.py
|
d1fd55b64f4c533ec2620e28f4a0de4f7f967bb9
|
[] |
no_license
|
arthuroe/shopperholics
|
eb4b1257a32354bb2b71607719f61a3a098b7fcb
|
6f941bf370a11d697c1577ca1e92bc1ba8ec4d3b
|
refs/heads/develop
| 2022-12-09T23:16:17.235490
| 2018-08-14T20:39:21
| 2019-02-20T00:01:18
| 139,479,448
| 0
| 0
| null | 2022-12-08T02:21:51
| 2018-07-02T18:25:22
|
Python
|
UTF-8
|
Python
| false
| false
| 283
|
py
|
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from api import app
from api.models.model_mixin import db
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
|
[
"arthur.orache@gmail.com"
] |
arthur.orache@gmail.com
|
bfe54bf4a84bae770d8568d0e5d8d98a85bd6046
|
f03e771eb4c1f300ae819179090efc388bcc6d32
|
/src/pymine/metadata/MetadataValue.py
|
c155a8834298482b1fd2fe55b4228d4f4dd64f3c
|
[] |
no_license
|
lacthan28/PyMine
|
d8d2365b0aabefcb056754260f67095dbcbe62ff
|
e7d4778f01181d45551c02fa0cef151327fa240a
|
refs/heads/master
| 2021-01-21T19:50:48.417635
| 2017-06-30T05:38:46
| 2017-06-30T05:38:46
| 92,161,042
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 570
|
py
|
# -*- coding: utf-8 -*-
from ..plugin.Plugin import *
class MetadataValue(metaclass = ABCMeta):
"""
:param Plugin owningPlugin:
"""
owningPlugin = None
def __init__(self, owningPlugin: Plugin):
self.owningPlugin = owningPlugin
def getOwningPlugin(self):
""" :return: Plugin """
return self.owningPlugin
@abstractmethod
def value(self):
"""
Fetches the value of this metadata item.
:return: mixed
"""
@abstractmethod
def invalidate(self):
"""
Invalidates this metadata item, forcing it to recompute when next accessed.
:return:
"""
|
[
"lacthan28@gmail.com"
] |
lacthan28@gmail.com
|
cb609dc44f22d8dceb8c61401be4c62ca445e9d6
|
573d470c9fcb3799e8822e6953e1259b74e0672c
|
/Course/syntax/example_12.py
|
ba29a4c138e0d6a7ace344e04386e2ac5c48f214
|
[
"Apache-2.0"
] |
permissive
|
zevgenia/Python_shultais
|
e6f35773e54a72477ea5ee83520dbecfbee7ff48
|
e51c31de221c5e7f36ede857a960138009ec8a05
|
refs/heads/master
| 2020-03-31T21:46:25.061571
| 2018-10-11T13:43:47
| 2018-10-11T13:43:47
| 152,593,211
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 409
|
py
|
age = 12
male = "f"
location = "Russia"
locations = ["Russia", "Ukraine", "Belarus"]
is_programmer = True
is_admin = False
if (age >= 12
and male == "f"
and location in locations
and (is_programmer or is_admin)):
print("Доступ открыт")
if age >= 12 \
and male == "m" \
and location in locations \
and (is_programmer or is_admin):
print("Доступ открыт")
|
[
"zatonskaya@yandex.ru"
] |
zatonskaya@yandex.ru
|
dbaf7c583e82742b17220b3b45bbabb630c64530
|
697fb11686110f569e7f4284045049d008688221
|
/windows/nsist/tests/test_commands.py
|
077ef0e8505a5a9f5e8aad17d9ce5190dcfc8f72
|
[
"Apache-2.0",
"MIT",
"BSD-3-Clause",
"CC-BY-3.0"
] |
permissive
|
andredoumad/p3env
|
433c9174899f0909b149f51c3243b6fe04e076bf
|
a8850d06755d53eb6fedd9995091dad34f1f9ccd
|
refs/heads/master
| 2023-02-03T20:50:07.357255
| 2020-12-23T09:15:55
| 2020-12-23T09:15:55
| 317,041,015
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,591
|
py
|
import io
from testpath import assert_isfile, assert_not_path_exists
from zipfile import ZipFile
from nsist import commands, _assemble_launchers
def test_prepare_bin_dir(tmpdir):
cmds = {
'acommand': {
'entry_point': 'somemod:somefunc',
'extra_preamble': io.StringIO(u'import extra')
}
}
commands.prepare_bin_directory(tmpdir, cmds)
launcher_file = str(tmpdir / 'launcher_exe.dat')
launcher_noconsole_file = str(tmpdir / 'launcher_noconsole_exe.dat')
zip_file = str(tmpdir / 'acommand-append.zip')
zip_file_invalid = str(tmpdir / 'acommand-append-noconsole.zip')
exe_file = str(tmpdir / 'acommand.exe')
assert_isfile(launcher_file)
assert_isfile(launcher_noconsole_file)
assert_isfile(zip_file)
assert_not_path_exists(zip_file_invalid)
assert_not_path_exists(exe_file)
with open(launcher_file, 'rb') as lf:
b_launcher = lf.read()
assert b_launcher[:2] == b'MZ'
with open(launcher_noconsole_file, 'rb') as lf:
assert lf.read(2) == b'MZ'
with ZipFile(zip_file) as zf:
assert zf.testzip() is None
script_contents = zf.read('__main__.py').decode('utf-8')
assert 'import extra' in script_contents
assert 'somefunc()' in script_contents
_assemble_launchers.main(['_assemble_launchers.py', 'C:\\path\\to\\python', str(tmpdir)])
assert_isfile(exe_file)
with open(exe_file, 'rb') as ef, open(zip_file, 'rb') as zf:
b_exe = ef.read()
b_zip = zf.read()
assert b_exe[:len(b_launcher)] == b_launcher
assert b_exe[len(b_launcher):-len(b_zip)].decode('utf-8') == '#!"C:\\path\\to\\python.exe"\r\n'
assert b_exe[-len(b_zip):] == b_zip
with ZipFile(exe_file) as zf:
assert zf.testzip() is None
assert zf.read('__main__.py').decode('utf-8') == script_contents
def test_prepare_bin_dir_noconsole(tmpdir):
cmds = {
'acommand': {
'entry_point': 'somemod:somefunc',
'console': False
}
}
commands.prepare_bin_directory(tmpdir, cmds)
launcher_file = str(tmpdir / 'launcher_exe.dat')
launcher_noconsole_file = str(tmpdir / 'launcher_noconsole_exe.dat')
zip_file = str(tmpdir / 'acommand-append-noconsole.zip')
zip_file_invalid = str(tmpdir / 'acommand-append.zip')
exe_file = str(tmpdir / 'acommand.exe')
assert_isfile(launcher_file)
assert_isfile(launcher_noconsole_file)
assert_isfile(zip_file)
assert_not_path_exists(zip_file_invalid)
assert_not_path_exists(exe_file)
with open(launcher_file, 'rb') as lf:
assert lf.read(2) == b'MZ'
with open(launcher_noconsole_file, 'rb') as lf:
b_launcher = lf.read()
assert b_launcher[:2] == b'MZ'
with ZipFile(zip_file) as zf:
assert zf.testzip() is None
script_contents = zf.read('__main__.py').decode('utf-8')
assert 'import extra' not in script_contents
assert 'somefunc()' in script_contents
_assemble_launchers.main(['_assemble_launchers.py', 'C:\\custom\\python.exe', str(tmpdir)])
assert_isfile(exe_file)
with open(exe_file, 'rb') as ef, open(zip_file, 'rb') as zf:
b_exe = ef.read()
b_zip = zf.read()
assert b_exe[:len(b_launcher)] == b_launcher
assert b_exe[len(b_launcher):-len(b_zip)].decode('utf-8') == '#!"C:\\custom\\pythonw.exe"\r\n'
assert b_exe[-len(b_zip):] == b_zip
with ZipFile(exe_file) as zf:
assert zf.testzip() is None
assert zf.read('__main__.py').decode('utf-8') == script_contents
|
[
"andre@stringkeeper.com"
] |
andre@stringkeeper.com
|
c87d5afa14f70ed9c35d2b5894f71311df928142
|
a904e99110721719d9ca493fdb91679d09577b8d
|
/month05/spider/day01_course/day01_code/10_novelSpiderMysql.py
|
f0fca531e47d09485d510041f8e19a4946197908
|
[
"Apache-2.0"
] |
permissive
|
chaofan-zheng/tedu-python-demo
|
7c7c64a355e5380d1f8b6464affeddfde0d27be7
|
abe983ddc52690f4726cf42cc6390cba815026d8
|
refs/heads/main
| 2023-03-12T05:17:34.596664
| 2021-02-27T08:33:31
| 2021-02-27T08:33:31
| 323,350,480
| 4
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,194
|
py
|
"""
笔趣阁小说爬虫,所抓数据:href、title、author、comment
思路步骤:
1、确认数据来源(右键->查看网页源代码->搜索关键字)
2、确认静态:观察URL地址规律
3、写正则表达式
"""
import requests
import re
import time
import random
import pymysql
class NovelSpider:
def __init__(self):
self.url = 'https://www.biqukan.cc/fenlei1/{}.html'
self.headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'}
# 连接数据库、创建游标对象
self.db = pymysql.connect(
'localhost','root','123456','noveldb',charset='utf8'
)
self.cur = self.db.cursor()
def get_html(self, url):
"""请求,发请求获取响应内容html"""
html = requests.get(url=url, headers=self.headers).text
# 直接调用解析函数
self.parse_html(html)
def parse_html(self, html):
"""解析提取数据"""
regex = '<div class="caption">.*?href="(.*?)" title="(.*?)">.*?<small class="text-muted fs-12">(.*?)</small>.*?>(.*?)</p>'
# r_list: [(href,title,author,comment), (), ...]
r_list = re.findall(regex, html, re.S)
# 直接调用数据处理函数
self.save_html(r_list)
def save_html(self, r_list):
"""数据处理函数"""
ins = 'insert into novel_tab values(%s,%s,%s,%s)'
for r in r_list:
# execute():第二个参数可为列表、也可为元组
self.cur.execute(ins, r)
self.db.commit()
print(r)
def crawl(self):
"""爬虫逻辑函数"""
for page in range(1, 3):
page_url = self.url.format(page)
self.get_html(url=page_url)
# 控制数据抓取频率
time.sleep(random.randint(1, 3))
# 所有数据抓取完成后,断开数据库连接
self.cur.close()
self.db.close()
if __name__ == '__main__':
spider = NovelSpider()
spider.crawl()
|
[
"417355570@qq.com"
] |
417355570@qq.com
|
ecb1f88de692273696479a78d63266fb28e7ab08
|
128548b223a941c1570aba99c679a698dedb3e72
|
/rename.py
|
0b1a95e3d55d759c39a67fb810c8a247760c7484
|
[] |
no_license
|
hhk86/Barra
|
de3e8d715f6ead1b425e5b639538df370a4eb11f
|
ddcf50766bcbdecb602213cccc65cab01146f88b
|
refs/heads/master
| 2020-07-26T18:04:44.006126
| 2019-09-26T07:36:48
| 2019-09-26T07:36:48
| 208,727,872
| 1
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,005
|
py
|
import sys
from pymongo import MongoClient
from basicFunction import *
import sys
class MongoDB():
'''
Connect to local MongoDB
'''
def __init__(self):
self.host = "18.210.68.192"
self.port = 27017
self.db = "basicdb"
self.username = "user"
self.password = "user"
def __enter__(self):
self.conn = MongoClient(self.host, self.port, username=self.username, password=self.password)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.conn.close()
def connect(self):
return self
if __name__ == "__main__":
confirm = input("Please input confirm:\n>>>")
if confirm != "confirm":
sys.exit()
with MongoDB() as mongo:
connection = mongo.connect()
db = connection.conn["basicdb"]
collection = db["basic_balance_new"]
db.basic_balance_new.rename("basic_balance")
# a = db.universe_new2.find()
# for b in a:
# print(b)
|
[
"hhk0@outlook.com"
] |
hhk0@outlook.com
|
24ae940898e40cd452fccf9a14a65f0d30687132
|
c4b7399a10b7f963f625d8d15e0a8215ea35ef7d
|
/239.滑动窗口最大值.py
|
28a32c944148c249efaaa64c9393453ee7122d3f
|
[] |
no_license
|
kangkang59812/LeetCode-python
|
a29a9788aa36689d1f3ed0e8b668f79d9ca43d42
|
276d2137a929e41120c2e8a3a8e4d09023a2abd5
|
refs/heads/master
| 2022-12-05T02:49:14.554893
| 2020-08-30T08:22:16
| 2020-08-30T08:22:16
| 266,042,478
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,027
|
py
|
#
# @lc app=leetcode.cn id=239 lang=python3
#
# [239] 滑动窗口最大值
#
# https://leetcode-cn.com/problems/sliding-window-maximum/description/
#
# algorithms
# Hard (44.47%)
# Likes: 262
# Dislikes: 0
# Total Accepted: 33.6K
# Total Submissions: 75.5K
# Testcase Example: '[1,3,-1,-3,5,3,6,7]\n3'
#
# 给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k
# 个数字。滑动窗口每次只向右移动一位。
#
# 返回滑动窗口中的最大值。
#
#
#
# 示例:
#
# 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
# 输出: [3,3,5,5,6,7]
# 解释:
#
# 滑动窗口的位置 最大值
# --------------- -----
# [1 3 -1] -3 5 3 6 7 3
# 1 [3 -1 -3] 5 3 6 7 3
# 1 3 [-1 -3 5] 3 6 7 5
# 1 3 -1 [-3 5 3] 6 7 5
# 1 3 -1 -3 [5 3 6] 7 6
# 1 3 -1 -3 5 [3 6 7] 7
#
#
#
# 提示:
#
# 你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。
#
#
#
# 进阶:
#
# 你能在线性时间复杂度内解决此题吗?
#
#
# @lc code=start
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
from collections import deque
n = len(nums)
if n == 0 or k < 1:
return []
if k == 1:
return nums
if n <= k:
return [max(nums)]
window = deque()
res = []
for i in range(k):
while window and nums[window[-1]] <= nums[i]:
window.pop()
window.append(i)
for i in range(k, n):
res.append(nums[window[0]])
if i-window[0] >= k:
window.popleft()
while window and nums[window[-1]] <= nums[i]:
window.pop()
window.append(i)
res.append(nums[window[0]])
return res
# @lc code=end
|
[
"596286458@qq.com"
] |
596286458@qq.com
|
e5aafc8df7b44ff0c83d49b3d4cab9e3ea94de56
|
240e7cbb46bf2a94b3fd337267c71c1db42e7ce1
|
/examples/ad_manager/v202002/adjustment_service/get_all_traffic_adjustments.py
|
7754fa8a3e02792791e992f180562cb4b0e174bc
|
[
"Apache-2.0"
] |
permissive
|
andreferraro/googleads-python-lib
|
2624fa84ca7064c3b15a7d9d48fc0f023316524d
|
a9ddeae56c5b9769f50c4e9d37eb32fd1eebe534
|
refs/heads/master
| 2022-11-13T03:38:38.300845
| 2020-07-03T13:17:59
| 2020-07-03T13:17:59
| 276,904,111
| 0
| 0
|
Apache-2.0
| 2020-07-03T13:16:21
| 2020-07-03T13:16:20
| null |
UTF-8
|
Python
| false
| false
| 1,945
|
py
|
#!/usr/bin/env python
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all traffic adjustments."""
from __future__ import print_function
# Import appropriate modules from the client library.
from googleads import ad_manager
def main(client):
# Initialize the adjustment service.
adjustment_service = client.GetService('AdjustmentService', version='v202002')
# Create a statement to get all forecast traffic adjustments.
statement = ad_manager.StatementBuilder(version='v202002')
# Retrieve a small number of traffic adjustments at a time, paging
# through until all traffic adjustments have been retrieved.
while True:
response = adjustment_service.getTrafficAdjustmentsByStatement(
statement.ToStatement())
if 'results' in response and len(response['results']):
for adjustment in response['results']:
# Print out some information for each traffic adjustment.
print('Traffic forecast adjustment with id %d and %d segments was '
'found.' % (adjustment['id'],
len(adjustment['forecastAdjustmentSegments'])))
statement.offset += statement.limit
else:
break
print('\nNumber of results found: %s' % response['totalResultSetSize'])
if __name__ == '__main__':
# Initialize client object.
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client)
|
[
"davidwihl@users.noreply.github.com"
] |
davidwihl@users.noreply.github.com
|
61109f2520040675af6b0001cb0b033d7f46f74f
|
68728961294d360d26e8149e7e0a4816adf20842
|
/src/build_seq2seq_transformer/train_helper.py
|
847c17f886a834c2ab5cd5579e7cba3bd6108705
|
[] |
no_license
|
Dawn-Flying/text_summarization
|
d334fe884aa3a6341dd7bc381b03c1ab3e2c057e
|
ab68555c6f455c4f14fead5fc1c49420cdef8dc4
|
refs/heads/master
| 2023-07-17T07:49:21.995004
| 2021-08-26T15:46:19
| 2021-08-26T15:46:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,842
|
py
|
import time
import tensorflow as tf
from src.build_seq2seq_transformer.schedules.lr_schedules import CustomSchedule
from src.build_seq2seq_transformer.layers.transformer import create_masks
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False, reduction='none')
def loss_function(real, pred):
mask = tf.math.logical_not(tf.math.equal(real, 0))
loss_ = loss_object(real, pred)
mask = tf.cast(mask, dtype=loss_.dtype)
loss_ *= mask
loss_ = tf.reduce_sum(loss_, axis=1) / tf.reduce_sum(mask, axis=1)
return tf.reduce_mean(loss_)
def train_model(model, dataset, params, ckpt_manager):
learning_rate = CustomSchedule(params["d_model"])
optimizer = tf.keras.optimizers.Adam(learning_rate)
def train_step(enc_inp, enc_extended_inp, dec_inp, dec_tar, batch_oov_len, decoder_pad_mask):
enc_padding_mask, combined_mask, dec_padding_mask = create_masks(enc_inp, dec_inp)
with tf.GradientTape() as tape:
outputs = model(enc_inp,
enc_extended_inp,
batch_oov_len,
dec_inp,
params['training'],
enc_padding_mask,
combined_mask,
dec_padding_mask)
pred = outputs["logits"]
batch_loss = loss_function(dec_tar, pred)
log_loss, cov_loss = 0., 0.
variables = model.trainable_variables
gradients = tape.gradient(batch_loss, variables)
optimizer.apply_gradients(zip(gradients, variables))
return batch_loss, log_loss, cov_loss
best_loss = 20
epochs = params['epochs']
for epoch in range(epochs):
t0 = time.time()
step = 0
total_loss = 0
total_log_loss = 0
total_cov_loss = 0
# for step, batch in enumerate(dataset.take(params['steps_per_epoch'])):
for encoder_batch_data, decoder_batch_data in dataset:
batch_loss, log_loss, cov_loss = train_step(encoder_batch_data["enc_input"], # shape=(16, 200)
encoder_batch_data["extended_enc_input"], # shape=(16, 200)
decoder_batch_data["dec_input"], # shape=(16, 50)
decoder_batch_data["dec_target"], # shape=(16, 50)
encoder_batch_data["max_oov_len"],
decoder_batch_data['decoder_pad_mask'])
step += 1
total_loss += batch_loss
total_log_loss += log_loss
total_cov_loss += cov_loss
if step % 10 == 0:
print('Epoch {} Batch {} avg_loss {:.4f} log_loss {:.4f} cov_loss {:.4f}'.format(epoch + 1,
step,
total_loss / step,
total_log_loss / step,
total_cov_loss / step))
if epoch % 1 == 0:
if total_loss / step < best_loss:
best_loss = total_loss / step
ckpt_save_path = ckpt_manager.save()
print('Saving checkpoint for epoch {} at {} ,best loss {}'.format(epoch + 1, ckpt_save_path, best_loss))
print('Epoch {} Loss {:.4f}'.format(epoch + 1, total_loss / step))
print('Time taken for 1 epoch {} sec\n'.format(time.time() - t0))
|
[
"184419810@qq.com"
] |
184419810@qq.com
|
becf43a0b4dfb0ea436cf8140e0e35e4cfda4e6a
|
6527b66fd08d9e7f833973adf421faccd8b765f5
|
/yuancloud/plugin/account_extend/__yuancloud__.py
|
8db29a38062cd53a33ecab90e168d9cf7f69b8a1
|
[] |
no_license
|
cash2one/yuancloud
|
9a41933514e57167afb70cb5daba7f352673fb4d
|
5a4fd72991c846d5cb7c5082f6bdfef5b2bca572
|
refs/heads/master
| 2021-06-19T22:11:08.260079
| 2017-06-29T06:26:15
| 2017-06-29T06:26:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 873
|
py
|
# -*- coding: utf-8 -*-
{
'name': "财务模块扩展",
'summary': """
""",
'description': """
Long description of module's purpose
""",
'author': "zhangzs@sswyuan.com",
'website': "http://www.sswyuan.net/yuancloud",
# Categories can be used to filter modules in modules listing
# Check https://github.com/yuancloud/yuancloud/blob/master/yuancloud/addons/base/module/module_data.xml
# for the full list
'category' : 'Finance Management',
'version':'0.3',
# any module necessary for this one to work correctly
'depends': ['base','account_accountant'],
# always loaded
'data': [
# 'security/ir.model.access.csv',
'views/account_move_view.xml',
# 'views/templates.xml',
],
# only loaded in demonstration mode
# 'demo': [
# 'demo/demo.xml',
# ],
}
|
[
"liuganghao@lztogether.com"
] |
liuganghao@lztogether.com
|
07fccf67a1e8f157cd3475218604638fde43eeab
|
0931b32140ba932b3ba02f5109a087c6c70a244d
|
/frappe/utils/background_jobs.py
|
f6f35f3c8239acf3302486d691b210bc54e537ca
|
[
"MIT"
] |
permissive
|
cstkyrilos/frappe
|
b60ed4e95ce929c74c2fc46000080d10b343190e
|
27d9306bc5924c11c2749503454cc6d11a8cc654
|
refs/heads/main
| 2023-03-23T10:35:42.732385
| 2021-03-22T21:55:58
| 2021-03-22T21:55:58
| 350,292,784
| 0
| 0
|
MIT
| 2021-03-22T10:01:08
| 2021-03-22T10:01:07
| null |
UTF-8
|
Python
| false
| false
| 5,097
|
py
|
from __future__ import unicode_literals, print_function
import redis
from rq import Connection, Queue, Worker
from frappe.utils import cstr
from collections import defaultdict
import frappe
import MySQLdb
import os, socket, time
default_timeout = 300
queue_timeout = {
'long': 1500,
'default': 300,
'short': 300
}
def enqueue(method, queue='default', timeout=300, event=None,
async=True, job_name=None, now=False, **kwargs):
'''
Enqueue method to be executed using a background worker
:param method: method string or method object
:param queue: should be either long, default or short
:param timeout: should be set according to the functions
:param event: this is passed to enable clearing of jobs from queues
:param async: if async=False, the method is executed immediately, else via a worker
:param job_name: can be used to name an enqueue call, which can be used to prevent duplicate calls
:param now: if now=True, the method is executed via frappe.call
:param kwargs: keyword arguments to be passed to the method
'''
if now or frappe.flags.in_migrate:
return frappe.call(method, **kwargs)
q = get_queue(queue, async=async)
if not timeout:
timeout = queue_timeout.get(queue) or 300
return q.enqueue_call(execute_job, timeout=timeout,
kwargs={
"site": frappe.local.site,
"user": frappe.session.user,
"method": method,
"event": event,
"job_name": job_name or cstr(method),
"async": async,
"kwargs": kwargs
})
def execute_job(site, method, event, job_name, kwargs, user=None, async=True, retry=0):
'''Executes job in a worker, performs commit/rollback and logs if there is any error'''
from frappe.utils.scheduler import log
if async:
frappe.connect(site)
if user:
frappe.set_user(user)
if isinstance(method, basestring):
method_name = method
method = frappe.get_attr(method)
else:
method_name = cstr(method.__name__)
try:
method(**kwargs)
except (MySQLdb.OperationalError, frappe.RetryBackgroundJobError), e:
frappe.db.rollback()
if (retry < 5 and
(isinstance(e, frappe.RetryBackgroundJobError) or e.args[0] in (1213, 1205))):
# retry the job if
# 1213 = deadlock
# 1205 = lock wait timeout
# or RetryBackgroundJobError is explicitly raised
frappe.destroy()
time.sleep(retry+1)
return execute_job(site, method, event, job_name, kwargs,
async=async, retry=retry+1)
else:
log(method_name, message=repr(locals()))
raise
except:
frappe.db.rollback()
log(method_name, message=repr(locals()))
raise
else:
frappe.db.commit()
finally:
if async:
frappe.destroy()
def start_worker(queue=None):
'''Wrapper to start rq worker. Connects to redis and monitors these queues.'''
with frappe.init_site():
# empty init is required to get redis_queue from common_site_config.json
redis_connection = get_redis_conn()
with Connection(redis_connection):
queues = get_queue_list(queue)
Worker(queues, name=get_worker_name(queue)).work()
def get_worker_name(queue):
'''When limiting worker to a specific queue, also append queue name to default worker name'''
name = None
if queue:
# hostname.pid is the default worker name
name = '{hostname}.{pid}.{queue}'.format(
hostname=socket.gethostname(),
pid=os.getpid(),
queue=queue)
return name
def get_jobs(site=None, queue=None, key='method'):
'''Gets jobs per queue or per site or both'''
jobs_per_site = defaultdict(list)
for queue in get_queue_list(queue):
q = get_queue(queue)
for job in q.jobs:
if job.kwargs.get('site'):
if site is None:
# get jobs for all sites
jobs_per_site[job.kwargs['site']].append(job.kwargs[key])
elif job.kwargs['site'] == site:
# get jobs only for given site
jobs_per_site[site].append(job.kwargs[key])
else:
print('No site found in job', job.__dict__)
return jobs_per_site
def get_queue_list(queue_list=None):
'''Defines possible queues. Also wraps a given queue in a list after validating.'''
default_queue_list = queue_timeout.keys()
if queue_list:
if isinstance(queue_list, basestring):
queue_list = [queue_list]
for queue in queue_list:
validate_queue(queue, default_queue_list)
return queue_list
else:
return default_queue_list
def get_queue(queue, async=True):
'''Returns a Queue object tied to a redis connection'''
validate_queue(queue)
return Queue(queue, connection=get_redis_conn(), async=async)
def validate_queue(queue, default_queue_list=None):
if not default_queue_list:
default_queue_list = queue_timeout.keys()
if queue not in default_queue_list:
frappe.throw("Queue should be one of {0}".format(', '.join(default_queue_list)))
def get_redis_conn():
if not hasattr(frappe.local, 'conf'):
raise Exception('You need to call frappe.init')
elif not frappe.local.conf.redis_queue:
raise Exception('redis_queue missing in common_site_config.json')
return redis.from_url(frappe.local.conf.redis_queue)
def enqueue_test_job():
enqueue('frappe.utils.background_jobs.test_job', s=100)
def test_job(s):
import time
print('sleeping...')
time.sleep(s)
|
[
"cst.kyrilos@gmail.com"
] |
cst.kyrilos@gmail.com
|
cffac3e938b8f72f426447724e96e8a625dca2f2
|
54f352a242a8ad6ff5516703e91da61e08d9a9e6
|
/Source Codes/AtCoder/abc027/D/4117422.py
|
388be0989c70f290b2cd9f0347c18a27adb75478
|
[] |
no_license
|
Kawser-nerd/CLCDSA
|
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
|
aee32551795763b54acb26856ab239370cac4e75
|
refs/heads/master
| 2022-02-09T11:08:56.588303
| 2022-01-26T18:53:40
| 2022-01-26T18:53:40
| 211,783,197
| 23
| 9
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 412
|
py
|
from itertools import accumulate
S = input()
N = len(S)
M_cnt = S.count('M')
cnt_plus = list(accumulate([(1 if s == '+' else 0) for s in S[::-1]]))[::-1]
cnt_minus = list(accumulate([(1 if s == '-' else 0) for s in S[::-1]]))[::-1]
p = []
for i, s in enumerate(S):
if s == 'M':
p.append(cnt_plus[i] - cnt_minus[i])
p.sort()
ans = sum(p[M_cnt // 2:]) - sum(p[:M_cnt // 2])
print(ans)
|
[
"kwnafi@yahoo.com"
] |
kwnafi@yahoo.com
|
b2a3deaae28ce2efbd89fe01d8a2d2145f9946ff
|
c8ed5baad6ce8527f4b75a73d0f15b1207aa660e
|
/app/discourse/config.py
|
41c134bf5724c4ec50aaeec6afe12e15213f4a81
|
[] |
no_license
|
GovLab/noi2
|
f12aed284c11c743fff0286df4fe59bb8b894050
|
7fce89f0c4c437718916fc95ca4c6c4372cdf464
|
refs/heads/master
| 2021-04-15T15:10:20.713982
| 2016-10-06T23:27:05
| 2016-10-06T23:27:05
| 40,134,662
| 5
| 9
| null | 2016-06-30T06:37:33
| 2015-08-03T16:10:41
|
Python
|
UTF-8
|
Python
| false
| false
| 593
|
py
|
from werkzeug.local import LocalProxy
from flask import current_app
class DiscourseConfig(object):
def __init__(self, config):
self.api_key = config['api_key']
self.origin = config['origin']
self.sso_secret = config['sso_secret']
self.admin_username = 'system'
def url(self, path):
return self.origin + path
@classmethod
def from_app(cls, app):
return cls(app.config['DISCOURSE'])
@classmethod
def from_current_app(cls):
return cls.from_app(current_app)
config = LocalProxy(DiscourseConfig.from_current_app)
|
[
"varmaa@gmail.com"
] |
varmaa@gmail.com
|
12ab0540bafb80390bcb2af09737bf5eb8328fae
|
b2ba670818623f8ab18162382f7394baed97b7cb
|
/test-data/AndroidSlicer/Bites/DD/4.py
|
b62029f34f1e3997c9a8c10994ecffaead769d2e
|
[
"MIT"
] |
permissive
|
hsumyatwin/ESDroid-artifact
|
012c26c40537a79b255da033e7b36d78086b743a
|
bff082c4daeeed62ceda3d715c07643203a0b44b
|
refs/heads/main
| 2023-04-11T19:17:33.711133
| 2022-09-30T13:40:23
| 2022-09-30T13:40:23
| 303,378,286
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,621
|
py
|
#start monkey test seedNo 0
import os;
from subprocess import Popen
from subprocess import PIPE
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
from com.android.monkeyrunner.MonkeyDevice import takeSnapshot
from com.android.monkeyrunner.easy import EasyMonkeyDevice
from com.android.monkeyrunner.easy import By
from com.android.chimpchat.hierarchyviewer import HierarchyViewer
from com.android.monkeyrunner import MonkeyView
import random
import sys
import subprocess
from sys import exit
from random import randint
device = MonkeyRunner.waitForConnection()
package = 'caldwell.ben.bites'
activity ='caldwell.ben.bites.Bites'
runComponent = package+'/'+activity
device.startActivity(component=runComponent)
MonkeyRunner.sleep(0.2)
MonkeyRunner.sleep(0.2)
device.touch(4,1371, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(582,784, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(431,846, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(881,1691, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(1052,1239, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(946,447, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(1000,1859, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(792,1652, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(998,1849, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(247,1894, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(279,1642, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(1032,1841, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(1015,1873, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(1008,1850, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(969,1919, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(1059,1914, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(949,1829, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(926,1818, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(998,1917, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(918,1881, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(974,1897, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(1079,1867, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(584,1014, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(870,270, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(1070,1850, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(1000,1862, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(678,1645, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(437,988, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(338,1337, 'DOWN_AND_UP')
MonkeyRunner.sleep(0.2)
device.touch(443,798, 'DOWN_AND_UP')
|
[
"hsumyatwin@gmail.com"
] |
hsumyatwin@gmail.com
|
3de583f2f00f4914d1aa86d9d991dd8cc02811f0
|
909afe0216a37bdc19683d81e533fa6c094329c1
|
/python/leetcode/53-maximum-subarray.py
|
a2af229326ee18c0e058516c510b22433c0acfdd
|
[] |
no_license
|
wxnacy/study
|
af7fdcd9915d668be73c6db81bdc961247e24c73
|
7bca9dc8ec211be15c12f89bffbb680d639f87bf
|
refs/heads/master
| 2023-04-08T17:57:40.801687
| 2023-03-29T08:02:20
| 2023-03-29T08:02:20
| 118,090,886
| 18
| 22
| null | 2022-12-16T03:11:43
| 2018-01-19T07:14:02
|
HTML
|
UTF-8
|
Python
| false
| false
| 4,928
|
py
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)
# Description: 最大子序和 为完成动态规划算法
'''
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:
如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
'''
from constants import NUMS_FOR53
class Solution:
def maxSubArray1(self, nums) -> int:
'''
暴力解法,时间超限,详见
https://leetcode-cn.com/submissions/detail/18022319/
'''
if not nums:
return 0
if len(nums) == 1:
return nums[0]
max_sum = -2 ** 23
sums = []
for i in range(len(nums)):
sums.append(nums[i])
if nums[i] > max_sum:
max_sum = nums[i]
for j in range(len(nums)):
k = i + j + 1
if k >= len(nums):
break
s = sums[-1] + nums[k]
sums.append(s)
if s > max_sum:
max_sum = s
return max_sum
def maxSubArray2(self, nums) -> int:
'''
时间复杂度 : O(n)
执行用时 : 64 ms, 在Maximum Subarray的Python3提交中击败了72.70% 的用户
内存消耗 : 13.4 MB, 在Maximum Subarray的Python3提交中击败了96.67% 的用户
'''
if not nums:
return 0
if len(nums) == 1:
return nums[0]
max_index = 0
max_val = -2 ** 23
s = max_val
max_s = s
b = -1
i = 0
l = len(nums)
for i in range(l):
if nums[i] > max_val:
max_val = nums[i]
max_index = i
if b == -1 and nums[i] > 0 and i < l - 1:
bv = nums[i] + nums[i + 1]
if bv > 0:
b = i
s = nums[i]
if s > max_s:
max_s = s
else:
s+=nums[i]
if s <=0:
b = -1
if s > max_s:
max_s = s
return max_s if max_s > max_val else max_val
def maxSubArray3(self, nums) -> int:
'''
时间复杂度 : O(n)
执行用时 : 64 ms, 在Maximum Subarray的Python3提交中击败了72.70% 的用户
内存消耗 : 13.4 MB, 在Maximum Subarray的Python3提交中击败了96.67% 的用户
'''
if not nums:
return 0
s = 0
max_sum = nums[0]
for n in nums:
s += n
if s > max_sum:
max_sum = s
if s < 0:
s = 0
return max_sum
def maxSubArray4(self, nums) -> int:
'''
时间复杂度 : O(n)
执行用时 : 64 ms, 在Maximum Subarray的Python3提交中击败了72.70% 的用户
内存消耗 : 13.4 MB, 在Maximum Subarray的Python3提交中击败了96.67% 的用户
'''
if not nums:
return 0
s = nums[0]
for i in range(1, len(nums)):
if nums[i-1] > 0:
nums[i] += nums[i-1]
if nums[i] > s:
s = nums[i]
return s
import unittest
import utils
s = Solution()
class TestMain(unittest.TestCase):
def setUp(self):
'''before each test function'''
pass
def tearDown(self):
'''after each test function'''
pass
def do(self, func):
nums = [-2,1,-3,4,-1,2,1,-5,4]
self.assertEqual(func(nums), 6)
nums = [-2, 1]
self.assertEqual(func(nums), 1)
nums = [-2, -1]
self.assertEqual(func(nums), -1)
nums = [1, 2]
self.assertEqual(func(nums), 3)
nums = [1, 1, -2]
self.assertEqual(func(nums), 2)
nums = [3,1,-3,-3,2,-1]
self.assertEqual(func(nums), 4)
nums = [8,-19,5,-4,20]
self.assertEqual(func(nums), 21)
nums = [2,0,-3,2,1,0,1,-2]
self.assertEqual(func(nums), 4)
# for nums in TEST_LISTS:
# self.assertEqual(s.maxSubArray2(nums), func(nums))
def test_func(self):
s = Solution()
self.do(s.maxSubArray4)
self.do(s.maxSubArray3)
self.do(s.maxSubArray2)
self.do(s.maxSubArray1)
if __name__ == "__main__":
count = 100
tm = TestMain()
utils.print_func_run_time(count, s.maxSubArray2, nums = NUMS_FOR53)
utils.print_func_run_time(count, s.maxSubArray3, nums = NUMS_FOR53)
utils.print_func_run_time(count, s.maxSubArray4, nums = NUMS_FOR53)
# utils.print_func_run_time1(count, tm.do, s.maxSubArray3)
unittest.main()
|
[
"371032668@qq.com"
] |
371032668@qq.com
|
3787e3fd933ddd148fab18af2ec10a45fdbe09e4
|
caf5807c331ff22b1e7d48f59b626a8869bd418d
|
/quotes/models.py
|
d5d4b80e67599700f8a2ceddb5a9ece5e1f0e9a7
|
[] |
no_license
|
tahirawan4/cserver
|
d7cd2953f75485b8f061e0301d2ce4d77605e8fa
|
fcb7e0e22e3e2bac6e0278aa41709f84f93c9da2
|
refs/heads/master
| 2021-01-10T02:50:12.879964
| 2015-06-03T19:58:59
| 2015-06-03T19:58:59
| 36,827,447
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,171
|
py
|
from django.db import models
# Create your models here.
from django.db import models
# Create your models here.
class Author(models.Model):
name = models.CharField(max_length=30)
author_discription = models.CharField(max_length=150)
author_url = models.CharField(max_length=150)
author_image = models.ImageField(upload_to="media/", null=True, blank=True)
def __str__(self): # __unicode__ on Python 2
return self.name
list_display = ('name', 'author_discription', 'author_url')
class Categories(models.Model):
name = models.CharField(max_length=30)
cat_id = models.IntegerField(default=0)
def __str__(self): # __unicode__ on Python 2
return self.name
list_display = ('cat_id', 'name')
class Quote(models.Model):
author = models.ForeignKey(Author)
category = models.ForeignKey(Categories)
quote_id = models.IntegerField(default=0)
quote_discription = models.CharField(max_length=1000)
def __str__(self): # __unicode__ on Python 2
return self.quote_discription
list_display = ('author', 'category','quote_id','quote_discription')
|
[
"tahirawan4@gmail.com"
] |
tahirawan4@gmail.com
|
497a9fbcff26fdec2bfd886a40ed6cae1bc0b5fc
|
72765c1736a10b86be8583dbd694906aff467068
|
/tkinter/tkinter_pack/tkinter_font.py
|
86bf8bb16121622c1a8e3b449bc37793646e9847
|
[] |
no_license
|
taison2000/Python
|
05e3f3834501a4f5ef7a6260d8bf3d4ce41930f3
|
44079700c3db289f92792ea3ec5add6a523f8eae
|
refs/heads/master
| 2021-10-16T07:43:55.202012
| 2019-02-09T02:22:44
| 2019-02-09T02:22:44
| 103,322,062
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,169
|
py
|
#!/usr/bin/python
# Comment start with #
import sys
import tkinter as tk
#from tkinter import messagebox as msgBox
## tkMessageBox (v2.x) ==> messagebox (v3.x)
top = tk.Tk()
lbl1 = tk.Label(None, text='This is a label #1')
lbl2 = tk.Label(None, text=' label #2', bg="light green")
lbl3 = tk.Label(None, text='ABCDEFHJIJKLMNOPQRSTUVWXYZ', bg="gray", height=3, width=30, \
font=("Harlow", 35), fg="green", cursor='cross', underline=(15))
lbl1.pack()
lbl2.pack()
lbl3.pack()
top.mainloop()
# -----------------------------------------------------------------------------
# Resources
# http://www.tutorialspoint.com/python/python_gui_programming.htm
#
# https://docs.python.org/3.4/tutorial/modules.html
# http://www.tutorialspoint.com/python/tk_label.htm <-- Label
# http://www.tutorialspoint.com/python/tk_cursors.htm <-- cursor names
# http://effbot.org/tkinterbook/label.htm <-- Label
#
# Windows - Font
# - "Control Panel" -> "Appearance and Personalization" -> "Fonts"
# - "Control Panel" -> "Fonts"
#
# * Arial
# * Forte
# * Forte
# * Gungsuh
# * Harrington
#
|
[
"noreply@github.com"
] |
taison2000.noreply@github.com
|
eb35046e2b6c4f11866a15ec83a1b6d45ec5dcb7
|
6580ba5d135c4f33f1a0996953ba2a65f7458a14
|
/applications/ji178/models/fd404.py
|
1e76f1088602024a7d98867bbe6b8c5253fb2792
|
[
"LicenseRef-scancode-public-domain",
"MIT"
] |
permissive
|
ali96343/facew2p
|
02b038d3853691264a49de3409de21c8a33544b8
|
a3881b149045e9caac344402c8fc4e62edadb42f
|
refs/heads/master
| 2021-06-10T17:52:22.200508
| 2021-05-10T23:11:30
| 2021-05-10T23:11:30
| 185,795,614
| 7
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,643
|
py
|
#
# table for controller: X404
#
from gluon.contrib.populate import populate
db.define_table('d404',
Field('f0', label='key', writable = True , length= 1000),
Field('f1', 'text', label='data string', length= 1000),
Field('f2', 'text', label='save data string', length= 1000, default='' ),
)
#
if not db(db.d404.id ).count():
db.d404.insert( f0= 'sp983', f1= '(983)Dashboard')
db.d404.insert( f0= 'sp984', f1= '(984)Components')
db.d404.insert( f0= 'hf985', f1= '(985)Custom Components:')
db.d404.insert( f0= 'aa987', f1= '(987)Buttons')
db.d404.insert( f0= 'aa989', f1= '(989)Cards')
db.d404.insert( f0= 'sp990', f1= '(990)Utilities')
db.d404.insert( f0= 'hf991', f1= '(991)Custom Utilities:')
db.d404.insert( f0= 'aa993', f1= '(993)Colors')
db.d404.insert( f0= 'aa995', f1= '(995)Borders')
db.d404.insert( f0= 'aa997', f1= '(997)Animations')
db.d404.insert( f0= 'aa999', f1= '(999)Other')
db.d404.insert( f0= 'sp1000', f1= '(1000)Pages')
db.d404.insert( f0= 'hf1001', f1= '(1001)Login Screens:')
db.d404.insert( f0= 'aa1003', f1= '(1003)Login')
db.d404.insert( f0= 'aa1005', f1= '(1005)Register')
db.d404.insert( f0= 'aa1007', f1= '(1007)Forgot Password')
db.d404.insert( f0= 'hf1008', f1= '(1008)Other Pages:')
db.d404.insert( f0= 'aa1010', f1= '(1010)404 Page')
db.d404.insert( f0= 'aa1012', f1= '(1012)Blank Page')
db.d404.insert( f0= 'sp1014', f1= '(1014)Charts')
db.d404.insert( f0= 'sp1016', f1= '(1016)Tables')
db.d404.insert( f0= 'pb1017', f1= '(1017)Search for...')
db.d404.insert( f0= 'pb1018', f1= '(1018)Search for...')
db.d404.insert( f0= 'sx1019', f1= '(1019)3+')
db.d404.insert( f0= 'di1020', f1= '(1020)December 12, 2019')
db.d404.insert( f0= 'sx1021', f1= '(1021)A new monthly report is ready to download!')
db.d404.insert( f0= 'di1022', f1= '(1022)December 7, 2019')
db.d404.insert( f0= 'di1023', f1= '(1023)December 2, 2019')
db.d404.insert( f0= 'aa1024', f1= '(1024)Show All Alerts')
db.d404.insert( f0= 'di1025', f1= '(1025)Hi there! I am wondering if you can help me with a problem I ve been having.')
db.d404.insert( f0= 'di1026', f1= '(1026)Emily Fowler 58m')
db.d404.insert( f0= 'di1027', f1= '(1027)I have the photos that you ordered last month, how would you like them sent to you?')
db.d404.insert( f0= 'di1028', f1= '(1028)Jae Chun 1d')
db.d404.insert( f0= 'di1029', f1= '(1029)Last month s report looks great, I am very happy with the progress so far, keep up the good work!')
db.d404.insert( f0= 'di1030', f1= '(1030)Morgan Alvarez 2d')
db.d404.insert( f0= 'di1031', f1= '(1031)Am I a good boy? The reason I ask is because someone told me that people say this to all dogs, even if they aren t good...')
db.d404.insert( f0= 'di1032', f1= '(1032)Chicken the Dog 2w')
db.d404.insert( f0= 'aa1033', f1= '(1033)Read More Messages')
db.d404.insert( f0= 'sx1034', f1= '(1034)Valerie Luna')
db.d404.insert( f0= 'di1035', f1= '(1035)404')
db.d404.insert( f0= 'pc1036', f1= '(1036)Page Not Found')
db.d404.insert( f0= 'pc1037', f1= '(1037)It looks like you found a glitch in the matrix...')
db.d404.insert( f0= 'sp1039', f1= '(1039)Copyright © Your Website 2019')
db.d404.insert( f0= 'he1040', f1= '(1040)Ready to Leave?')
db.d404.insert( f0= 'sx1041', f1= '(1041)')
db.d404.insert( f0= 'di1042', f1= '(1042)Select Logout below if you are ready to end your current session.')
db.d404.insert( f0= 'bu1043', f1= '(1043)Cancel')
db.d404.insert( f0= 'aa1045', f1= '(1045)Logout')
db.commit()
#
|
[
"ab96343@gmail.com"
] |
ab96343@gmail.com
|
287ea9e6f95498d1cc39def3a007c223b9d638fb
|
99a472a443ed55652de88dc82451fdcc22d601f9
|
/label_maker.py
|
1cc3d5b5bff9ef693b587a327bb524bf5bd29a8e
|
[] |
no_license
|
JeremyGibson/gvision
|
c954144c8c8648619fb0e34cec855a6d72d23cb3
|
b218e0255d076c7bdb5f5c0c694264399fa4419d
|
refs/heads/main
| 2023-03-07T02:44:53.521075
| 2021-02-15T21:18:57
| 2021-02-15T21:39:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,510
|
py
|
#!/usr/bin/python
import os
from pathlib import Path
from datetime import datetime
from google.cloud import vision
LOG_PATH = Path("logs")
PATH_TO_IMAGES = Path(os.environ["PHOTOS_DIR"])
client = vision.ImageAnnotatorClient()
POTENTIAL_DOCUMENT = ['font', 'material property', 'parallel', 'stationery', 'recipe', 'paper', 'paper product',
'letter', 'document', 'post-it note', 'screenshot', '']
def is_paper(labels: list):
test = [x for x in labels if x in POTENTIAL_DOCUMENT]
match_per = len(test) / len(POTENTIAL_DOCUMENT)
if len(test) > 0:
return True, match_per
return False, match_per
def get_file():
images = [".jpg", ".png"]
for p in PATH_TO_IMAGES.glob("**/*.*"):
if p.suffix.lower() in images:
yield p
def label_maker():
log = LOG_PATH / f"potential_documents_{datetime.now()}.log"
with log.open('w') as logfh:
for f in get_file():
print(f"Examining: {f}")
with f.open('rb') as fh:
content = fh.read()
image = vision.Image(content=content)
response = client.label_detection(image=image)
labels = response.label_annotations
labels = [x.description.lower() for x in labels]
potential, percentage = is_paper(labels)
if potential:
print(f"{f} is probably a document.")
logfh.write(f"{f}: {percentage} {labels}\n")
if __name__ == "__main__":
label_maker()
|
[
"vinod@kurup.com"
] |
vinod@kurup.com
|
1f4fc6c7eee5b82ea686875e7a379a7e1f509552
|
e311664619d469addd2c77566ec97d24affcbfd9
|
/src/apps/alumno_profesor/migrations/0007_alumno_last_login.py
|
bf2c5409384950bcfb799164bb23bacfe9e2d549
|
[] |
no_license
|
danielhuamani/Proyecto-taller-base-datos
|
361dc8c915dff36a9ce96a7147c11f0af9d51227
|
5d791383f77f8042a2890db4cfd31079c6d1dc7b
|
refs/heads/master
| 2016-08-11T13:47:03.169317
| 2015-12-22T04:28:52
| 2015-12-22T04:28:52
| 46,673,349
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 461
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('alumno_profesor', '0006_auto_20151220_1948'),
]
operations = [
migrations.AddField(
model_name='alumno',
name='last_login',
field=models.DateTimeField(null=True, verbose_name=b'\xc3\x9altimo Login', blank=True),
),
]
|
[
"danielhuamani15@gmail.com"
] |
danielhuamani15@gmail.com
|
e81481b04fb1f65a6e1d9d47e39919236d78028e
|
81a62053841c03d9621fd31f8e7984c712c7aed2
|
/zoo/BEVFormer/attacks/attacker/pgd.py
|
f0b9a265b5f49216b58f49230fbcad46f430c69e
|
[
"Apache-2.0"
] |
permissive
|
Daniel-xsy/BEV-Attack
|
d0eb3a476875f9578c53df9bcb21564dea18ce0c
|
7970b27396c1af450c80b12eb312e76a8ab52a0a
|
refs/heads/master
| 2023-05-23T01:13:44.121533
| 2023-02-22T05:48:14
| 2023-02-22T05:48:14
| 540,328,937
| 7
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,428
|
py
|
import torch
import torch.nn as nn
import numpy as np
import random
import mmcv
from attacks.attacker.base import BaseAttacker
from attacks.attacker.builder import ATTACKER
@ATTACKER.register_module()
class PGD(BaseAttacker):
def __init__(self,
epsilon,
step_size,
num_steps,
loss_fn,
assigner,
category="Madry",
rand_init=False,
single_camera=False,
*args,
**kwargs):
""" PGD pixel attack
Args:
epsilon (float): L_infty norm bound for visual percep
step_size (float): step size of one attack iteration
num_steps (int): attack iteration number
loss_fn (class): adversarial objective function
category (str): `trades` or `Madry`, which type of initialization of attack
rand_init (bool): random initialize adversarial noise or zero initialize
assigner (class): assign prediction bbox to ground truth bbox
single_camera (bool): only attack random choose single camera
"""
super().__init__(*args, **kwargs)
self.epsilon = epsilon
self.step_size = step_size
self.num_steps = num_steps
self.loss_fn = loss_fn
self.category = category
self.single_camera = single_camera
self.rand_init = rand_init
self.assigner = assigner
def run(self, model, img, img_metas, gt_bboxes_3d, gt_labels_3d):
"""Run PGD attack optimization
Args:
model (nn.Module): model to be attacked
img (DataContainer): [B, M, C, H, W]
img_metas (DataContainer): img_meta information
gt_bboxes_3d: ground truth of bboxes
gt_labels_3d: ground truth of labels
Return:
inputs: (dict) {'img': img, 'img_metas': img_metas}
"""
model.eval()
camera = random.randint(0, 5)
img_ = img[0].data[0].clone()
B, M, C, H, W = img_.size()
assert B == 1, f"Batchsize should set to 1 in attack, but now is {B}"
# only calculate grad of single camera image
if self.single_camera:
camera_mask = torch.zeros((B, M, C, H, W))
camera_mask[:, camera] = 1
if self.category == "trades":
if self.single_camera:
x_adv = img_.detach() + camera_mask * 0.001 * torch.randn(img_.shape).to(img_.device).detach() if self.rand_init else img_.detach()
else:
x_adv = img_.detach() + 0.001 * torch.randn(img_.shape).to(img_.device).detach() if self.rand_init else img_.detach()
if self.category == "Madry":
if self.single_camera:
x_adv = img_.detach() + camera_mask * torch.from_numpy(np.random.uniform(-self.epsilon, self.epsilon, img_.shape)).float().to(img_.device) if self.rand_init else img_.detach()
else:
x_adv = img_.detach() + torch.from_numpy(np.random.uniform(-self.epsilon, self.epsilon, img_.shape)).float().to(img_.device) if self.rand_init else img_.detach()
x_adv = torch.clamp(x_adv, self.lower.view(1, 1, C, 1, 1), self.upper.view(1, 1, C, 1, 1))
for k in range(self.num_steps):
x_adv.requires_grad_()
img[0].data[0] = x_adv
inputs = {'img': img, 'img_metas': img_metas}
# with torch.no_grad():
outputs = model(return_loss=False, rescale=True, adv_mode=True, **inputs)
# assign pred bbox to ground truth
assign_results = self.assigner.assign(outputs, gt_bboxes_3d, gt_labels_3d)
# no prediction are assign to ground truth, stop attack
if assign_results is None:
break
loss_adv = self.loss_fn(**assign_results)
loss_adv.backward()
eta = self.step_size * x_adv.grad.sign()
if self.single_camera:
eta = eta * camera_mask
x_adv = x_adv.detach() + eta
x_adv = torch.min(torch.max(x_adv, img_ - self.epsilon), img_ + self.epsilon)
x_adv = torch.clamp(x_adv, self.lower.view(1, 1, C, 1, 1), self.upper.view(1, 1, C, 1, 1))
img[0].data[0] = x_adv.detach()
torch.cuda.empty_cache()
return {'img': img, 'img_metas':img_metas}
|
[
"1491387884@qq.com"
] |
1491387884@qq.com
|
9012f3d446c9811c846cbdf005bfb6e188fa54c8
|
52b5773617a1b972a905de4d692540d26ff74926
|
/.history/rottenOranges_20200810193226.py
|
9ad8d01ffd15107d6776d9a79b8fb4622742316f
|
[] |
no_license
|
MaryanneNjeri/pythonModules
|
56f54bf098ae58ea069bf33f11ae94fa8eedcabc
|
f4e56b1e4dda2349267af634a46f6b9df6686020
|
refs/heads/master
| 2022-12-16T02:59:19.896129
| 2020-09-11T12:05:22
| 2020-09-11T12:05:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,038
|
py
|
def markrotten(i,j,row,column,grid):
if (i < 0 or i >= row or j < 0 or j >= column) or grid[i][j] !=1:
return
else:
grid[i][j] == 2
print('grid',grid)
# checking its neighbours
markrotten(i+1,j,row,column,grid)
markrotten(i,j+1,row,column,grid)
markrotten(i,j-1,row,column,grid)
markrotten(i-1,j,row,column,grid)
def oranges(grid):
if len(grid) == 0:
return 0
# loop through the grid
# if there is no fresh orange just return 0
# if there is a two check all its four neighbours
# recursive call
# count when a one becomes a two
row = len(grid)
column = len(grid[0])
minutes = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 2:
markrotten(i,j,row,column,grid)
minutes +=1
print(minutes)
print(grid)
oranges( [[2,1,1],[0,1,1],[1,0,1]])
|
[
"mary.jereh@gmail.com"
] |
mary.jereh@gmail.com
|
9f7ab36b72ea976d64ec31fe193a1ffd67c51b33
|
3ced55b04ec82df5257f0e3b500fba89ddf73a8a
|
/src/stk/molecular/functional_groups/factories/bromo_factory.py
|
efd349b3d0830c3e38e99827798093df7e4a8813
|
[
"MIT"
] |
permissive
|
rdguerrerom/stk
|
317282d22f5c4c99a1a8452023c490fd2f711357
|
1ac2ecbb5c9940fe49ce04cbf5603fd7538c475a
|
refs/heads/master
| 2023-08-23T21:04:46.854062
| 2021-10-16T14:01:38
| 2021-10-16T14:01:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,018
|
py
|
"""
Bromo Factory
=============
"""
from __future__ import annotations
import typing
from collections import abc
from .functional_group_factory import FunctionalGroupFactory
from .utilities import get_atom_ids
from ..functional_groups import Bromo
from ...molecule import Molecule
from ...elements import Br
__all__ = (
'BromoFactory',
)
_ValidIndex = typing.Literal[0, 1]
class BromoFactory(FunctionalGroupFactory):
"""
Creates :class:`.Bromo` instances.
Creates functional groups from substructures, which match the
``[*][Br]`` functional group string.
Examples:
*Creating Functional Groups with the Factory*
You want to create a building block which has :class:`.Bromo`
functional groups. You want the atom bonded to the bromine to
be the *bonder* atom, and the bromine atom to be the *deleter*
atom.
.. testcode:: creating-functional-groups-with-the-factory
import stk
building_block = stk.BuildingBlock(
smiles='BrCCCBr',
functional_groups=(stk.BromoFactory(), ),
)
.. testcode:: creating-functional-groups-with-the-factory
:hide:
assert all(
isinstance(functional_group, stk.Bromo)
for functional_group
in building_block.get_functional_groups()
)
assert building_block.get_num_functional_groups() == 2
See Also:
:class:`.GenericFunctionalGroup`
Defines *bonders* and *deleters*.
"""
def __init__(
self,
bonders: tuple[_ValidIndex, ...] = (0, ),
deleters: tuple[_ValidIndex, ...] = (1, ),
placers: typing.Optional[tuple[_ValidIndex, ...]] = None,
) -> None:
"""
Initialize a :class:`.BromoFactory` instance.
Parameters:
bonders:
The indices of atoms in the functional group string,
which are *bonder* atoms.
deleters:
The indices of atoms in the functional group string,
which are *deleter* atoms.
placers:
The indices of atoms in the functional group string,
which are *placer* atoms. If ``None``, `bonders` will
be used.
"""
self._bonders = bonders
self._deleters = deleters
self._placers = bonders if placers is None else placers
def get_functional_groups(
self,
molecule: Molecule,
) -> abc.Iterable[Bromo]:
for atom_ids in get_atom_ids('[*][Br]', molecule):
atoms = tuple(molecule.get_atoms(atom_ids))
yield Bromo(
bromine=typing.cast(Br, atoms[1]),
atom=atoms[0],
bonders=tuple(atoms[i] for i in self._bonders),
deleters=tuple(atoms[i] for i in self._deleters),
placers=tuple(atoms[i] for i in self._placers),
)
|
[
"noreply@github.com"
] |
rdguerrerom.noreply@github.com
|
a9b66bfafdae81a479bdb341cbce153b8d8dec62
|
0fe394b10b39864915fcc4073a5fa050aa02502e
|
/SoloLearn_Project/skip.py
|
15ca46a183e4985396b92c323c1ecce9196dcecc
|
[] |
no_license
|
JohnAssebe/Python
|
9997d47bba4a056fdcd74c6e5207fc52b002cbfd
|
b88a7c2472f245dc6a0e8900bbea490cb0e0beda
|
refs/heads/master
| 2022-05-14T10:08:37.311345
| 2022-05-09T19:48:53
| 2022-05-09T19:48:53
| 212,562,910
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 613
|
py
|
def skip_elements(elements):
# Initialize variables
new_list = []
i = 0
if len(elements)==0:
return []
# Iterate through the list
for i in range(0,len(elements),2):
# Does this element belong in the resulting list?
if elements[i] not in new_list:
# Add this element to the resulting list
new_list.append(elements[i])
return new_list
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []
|
[
"noreply@github.com"
] |
JohnAssebe.noreply@github.com
|
736d83f69f045da85f0dcc4f44f46644a627a50f
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03472/s538005754.py
|
db417a8a26fe90ea010a6da9d14aba392ac1ffdb
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 442
|
py
|
n,h = map(int,input().split())
katana_a = []
katana_b = []
for i in range(n):
a,b = map(int,input().split())
katana_a.append(a)
katana_b.append(b)
amax = max(katana_a)
katana_b.sort(reverse=True)
ans = 0
k = 0
while h > 0:
if k == n:
break
if katana_b[k] > amax:
h -= katana_b[k]
ans += 1
k += 1
else:
break
if h <= 0:
print(ans)
else:
print(ans + (h+amax-1)//amax)
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
db431d9e93dd7b65b8dad33e2dccb31adb4e6276
|
6c137e70bb6b1b618fbbceddaeb74416d387520f
|
/pyqtgraph/examples/contextMenu.py
|
c2c5918dbf2642bbf316f24c4f9143c973f8d93c
|
[
"BSD-2-Clause",
"MIT"
] |
permissive
|
zhong-lab/code
|
fe497c75662f8c3b7ab3c01e7e351bff6d5e8d15
|
b810362e06b44387f0768353c602ec5d29b551a2
|
refs/heads/master
| 2023-01-28T09:46:01.448833
| 2022-06-12T22:53:47
| 2022-06-12T22:53:47
| 184,670,765
| 2
| 7
|
BSD-2-Clause
| 2022-12-08T21:46:15
| 2019-05-02T23:37:39
|
Python
|
UTF-8
|
Python
| false
| false
| 4,497
|
py
|
# -*- coding: utf-8 -*-
"""
Demonstrates adding a custom context menu to a GraphicsItem
and extending the context menu of a ViewBox.
PyQtGraph implements a system that allows each item in a scene to implement its
own context menu, and for the menus of its parent items to be automatically
displayed as well.
"""
import initExample ## Add path to library (just for examples; you do not need this)
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
win = pg.GraphicsWindow()
win.setWindowTitle('pyqtgraph example: context menu')
view = win.addViewBox()
# add two new actions to the ViewBox context menu:
zoom1 = view.menu.addAction('Zoom to box 1')
zoom2 = view.menu.addAction('Zoom to box 2')
# define callbacks for these actions
def zoomTo1():
# note that box1 is defined below
view.autoRange(items=[box1])
zoom1.triggered.connect(zoomTo1)
def zoomTo2():
# note that box1 is defined below
view.autoRange(items=[box2])
zoom2.triggered.connect(zoomTo2)
class MenuBox(pg.GraphicsObject):
"""
This class draws a rectangular area. Right-clicking inside the area will
raise a custom context menu which also includes the context menus of
its parents.
"""
def __init__(self, name):
self.name = name
self.pen = pg.mkPen('r')
# menu creation is deferred because it is expensive and often
# the user will never see the menu anyway.
self.menu = None
# note that the use of super() is often avoided because Qt does not
# allow to inherit from multiple QObject subclasses.
pg.GraphicsObject.__init__(self)
# All graphics items must have paint() and boundingRect() defined.
def boundingRect(self):
return QtCore.QRectF(0, 0, 10, 10)
def paint(self, p, *args):
p.setPen(self.pen)
p.drawRect(self.boundingRect())
# On right-click, raise the context menu
def mouseClickEvent(self, ev):
if ev.button() == QtCore.Qt.RightButton:
if self.raiseContextMenu(ev):
ev.accept()
def raiseContextMenu(self, ev):
menu = self.getContextMenus()
# Let the scene add on to the end of our context menu
# (this is optional)
menu = self.scene().addParentContextMenus(self, menu, ev)
pos = ev.screenPos()
menu.popup(QtCore.QPoint(pos.x(), pos.y()))
return True
# This method will be called when this item's _children_ want to raise
# a context menu that includes their parents' menus.
def getContextMenus(self, event=None):
if self.menu is None:
self.menu = QtGui.QMenu()
self.menu.setTitle(self.name+ " options..")
green = QtGui.QAction("Turn green", self.menu)
green.triggered.connect(self.setGreen)
self.menu.addAction(green)
self.menu.green = green
blue = QtGui.QAction("Turn blue", self.menu)
blue.triggered.connect(self.setBlue)
self.menu.addAction(blue)
self.menu.green = blue
alpha = QtGui.QWidgetAction(self.menu)
alphaSlider = QtGui.QSlider()
alphaSlider.setOrientation(QtCore.Qt.Horizontal)
alphaSlider.setMaximum(255)
alphaSlider.setValue(255)
alphaSlider.valueChanged.connect(self.setAlpha)
alpha.setDefaultWidget(alphaSlider)
self.menu.addAction(alpha)
self.menu.alpha = alpha
self.menu.alphaSlider = alphaSlider
return self.menu
# Define context menu callbacks
def setGreen(self):
self.pen = pg.mkPen('g')
# inform Qt that this item must be redrawn.
self.update()
def setBlue(self):
self.pen = pg.mkPen('b')
self.update()
def setAlpha(self, a):
self.setOpacity(a/255.)
# This box's context menu will include the ViewBox's menu
box1 = MenuBox("Menu Box #1")
view.addItem(box1)
# This box's context menu will include both the ViewBox's menu and box1's menu
box2 = MenuBox("Menu Box #2")
box2.setParentItem(box1)
box2.setPos(5, 5)
box2.scale(0.2, 0.2)
## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
|
[
"none"
] |
none
|
83c644506d964c736a4d5cae65f08195d41dc016
|
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
|
/7yo5FJX4xFbNxim5q_22.py
|
9783436a95859a2a95ce2cbc4b159661968c0f8b
|
[] |
no_license
|
daniel-reich/ubiquitous-fiesta
|
26e80f0082f8589e51d359ce7953117a3da7d38c
|
9af2700dbe59284f5697e612491499841a6c126f
|
refs/heads/master
| 2023-04-05T06:40:37.328213
| 2021-04-06T20:17:44
| 2021-04-06T20:17:44
| 355,318,759
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 217
|
py
|
def harry(po):
if len(po[0])==0:
return -1
downright = sum(po[-1])+sum(po[i][0] for i in range(len(po)-1))
rightdown = sum(po[0])+sum(po[i][-1] for i in range(len(po)-1))
return max(downright,rightdown)
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
1974a71145eabc83d069ae9eb89f4b22ccb733e3
|
6044266e775c87afed99397c8bb88366fbbca0e7
|
/scrapy_projt/xpath_tutorial_1/xpath_normalize-space_span.py
|
a61ab6ea4dc655eeab231d5be07451831d6f7fc6
|
[] |
no_license
|
ranafge/all-documnent-projects
|
e4434b821354076f486639419598fd54039fb5bd
|
c9d65ddea291c53b8e101357547ac63a36406ed9
|
refs/heads/main
| 2023-05-08T20:01:20.343856
| 2021-05-30T10:44:28
| 2021-05-30T10:44:28
| 372,186,355
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,181
|
py
|
import scrapy
html="""<form class="variants" action="/cart">
<a class="thumb fancybox image_outer" href="products/apple-iphone-5s-16gb-black--space-gray-chernyj" data-fancybox-group="gallery5">
<img src="http://first-store.ru/files/products/iphone%205S%20black_1.100x112.jpg?16ef5c4132fc88594851f92ccc2f3437" alt="Apple iPhone 5s 16GB Black & Space Gray (Чёрный)" title="Apple iPhone 5s 16GB Black & Space Gray (Чёрный)">
</a>
<h1>
<a class="name_mark" data-product="1075" href="products/apple-iphone-5s-16gb-black--space-gray-chernyj">Apple iPhone 5s 16GB Black & Space Gray (Чёрный)</a>
</h1>
<span class="price price_mark price_value">26 990 <span class="currency">руб</span>
<input id="variants_2927" name="variant" value="2927" type="radio" class="variant_radiobutton" checked="" style="display:none;">
<input class="button buy buy_button buy_button_catalog" type="submit" value="Купить" data-result-text="Добавлено">
</span>
</form>"""
data = scrapy.Selector(text=html)
print(data.xpath("span[contains(concat(' ', normalize-space(@class), ' '), ' price ')]"))
|
[
"ranafge@gmail.com"
] |
ranafge@gmail.com
|
c55d7e21b155df85decbb4db71b4bff34ba005ab
|
c80b3cc6a8a144e9858f993c10a0e11e633cb348
|
/components/ally-core-http/__setup__/ally_core_http/definition_time_zone.py
|
c7622168d8027cd0b24ee99b10fc4017a9d64a68
|
[] |
no_license
|
cristidomsa/Ally-Py
|
e08d80b67ea5b39b5504f4ac048108f23445f850
|
e0b3466b34d31548996d57be4a9dac134d904380
|
refs/heads/master
| 2021-01-18T08:41:13.140590
| 2013-11-06T09:51:56
| 2013-11-06T09:51:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,179
|
py
|
'''
Created on Jul 17, 2013
@package: ally core http
@copyright: 2012 Sourcefabric o.p.s.
@license: http://www.gnu.org/licenses/gpl-3.0.txt
@author: Gabriel Nistor
Provides the time zone header definitions.
'''
from ..ally_core.definition import definitions, defin, errors, error, desc
from .definition_header import CATEGORY_HEADER, VERIFY_CATEGORY, \
updateDescriptionsForHeaders
from ally.container import ioc
from ally.core.http.spec.codes import TIME_ZONE_ERROR
from ally.core.impl.definition import Name
# --------------------------------------------------------------------
try: import pytz # @UnusedImport
except ImportError: pass
else:
from pytz import all_timezones
from ally.core.http.impl.processor.time_zone import TIME_ZONE, CONTENT_TIME_ZONE
from .processor_time_zone import default_time_zone
# --------------------------------------------------------------------
VERIFY_TIME_ZONE = Name(TIME_ZONE.name) & VERIFY_CATEGORY
VERIFY_CONTENT_TIME_ZONE = Name(CONTENT_TIME_ZONE.name) & VERIFY_CATEGORY
# --------------------------------------------------------------------
@ioc.before(definitions)
def updateDefinitionsForTimeZone():
defin(category=CATEGORY_HEADER, name=TIME_ZONE.name)
defin(category=CATEGORY_HEADER, name=CONTENT_TIME_ZONE.name)
@ioc.before(errors)
def updateDefinitionErrorForTimeZone():
error(TIME_ZONE_ERROR.code, VERIFY_TIME_ZONE | VERIFY_CONTENT_TIME_ZONE, 'The time zone headers')
@ioc.before(updateDescriptionsForHeaders)
def updateDescriptionsForTimeZone():
sample, curr = [], None
for tz in all_timezones:
if curr != tz[:1]:
sample.append(tz)
curr = tz[:1]
# This is based on @see: updateDefinitionsForTimeZone().
desc(Name(TIME_ZONE.name),
'the time zone to render the time stamps in, as an example:\n%(sample)s',
'the default time zone is %(default)s', sample=sample, default=default_time_zone())
desc(Name(CONTENT_TIME_ZONE.name),
'same as \'%(name)s\' but for parsed content', name=TIME_ZONE.name)
|
[
"gabriel.nistor@sourcefabric.org"
] |
gabriel.nistor@sourcefabric.org
|
d0c4d0d97f9a1c42d2bc97257e59f28c94e033e4
|
6f56dbc188abcc8156eb7dae625243192516675b
|
/python/jittor/test/test_lazy_execution.py
|
ce276b4798848f4d6ea6f3e482b3ff93859baa1f
|
[
"Apache-2.0"
] |
permissive
|
linker666/jittor
|
80e03d2e8dec91bb69d4d6f7b0d222bfbf6c750f
|
96545765eca7364ec4938e1fa756bce4cb84dfb8
|
refs/heads/master
| 2023-02-09T21:28:48.706061
| 2021-01-05T15:08:33
| 2021-01-05T15:08:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,315
|
py
|
# ***************************************************************
# Copyright (c) 2020 Jittor. All Rights Reserved.
# Maintainers:
# Meng-Hao Guo <guomenghao1997@gmail.com>
# Dun Liang <randonlang@gmail.com>.
#
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this source code package.
# ***************************************************************
import jittor as jt
import unittest
import sys, os
from subprocess import getoutput
class TestLazyExecution(unittest.TestCase):
@unittest.skipIf(not jt.has_cuda, "No cuda found")
def test_lazy_execution(self):
code = """
import jittor as jt
jt.flags.use_cuda = 1
a = jt.zeros(1)
b = jt.code([1], a.dtype, [a],
cuda_header='''
#include <assert.h>
''',
cuda_src='''
__global__ void kernel(float32* a, float32* b) {
b[0] = a[0];
assert(a[0] == 1);
}
kernel<<<1,1>>>(in0_p, out0_p);
''')
c = a+b
print(c)
"""
fpath = os.path.join(jt.flags.cache_path, "lazy_error.py")
with open(fpath, 'w') as f:
f.write(code)
res = getoutput(f"{sys.executable} {fpath}")
assert 'print(c)' in res
res = getoutput(f"lazy_execution=0 {sys.executable} {fpath}")
assert "''')" in res
if __name__ == "__main__":
unittest.main()
|
[
"randonlang@gmail.com"
] |
randonlang@gmail.com
|
a42e0f404a06eceeff048e1750ca7e2890973dfc
|
7da3fe4ea12be962b574c8be63c35014df0d2faf
|
/facade.py
|
7f78edabd4455cfb95a3de2bfdde477d571562e5
|
[] |
no_license
|
hanmiton/patronesDise-o
|
2a4b581fc90a512bf7db26f728a17ce0f48eef83
|
523d993dfc60318e4af4a4dbc7fa236b9ae0bc94
|
refs/heads/master
| 2020-04-18T16:54:08.084782
| 2016-09-01T06:16:29
| 2016-09-01T06:16:29
| 66,985,551
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 471
|
py
|
class Scanner:
def __init__(self):
self.name = "Scanner"
class Parser:
def __init__(self):
self.name = "Parser"
class Compiler:
def __init__(self):
self.name = "Compiler"
self.scanner = Scanner()
self.parser = Parser()
def compile(self):
print("Compiling ...")
print("Scanning %s" % self.scanner.name)
print("Parsing %s" % self.parser.name)
if __name__ == "__main__":
compiler = Compiler()
compiler.compile()
|
[
"hanmilton_12@outlook.com"
] |
hanmilton_12@outlook.com
|
c0474becc0c7f964e582da615406555736dbaf11
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/17/usersdata/132/6773/submittedfiles/lecker.py
|
4b0c09bdee76966f8925264740fabe32156d6d34
|
[] |
no_license
|
rafaelperazzo/programacao-web
|
95643423a35c44613b0f64bed05bd34780fe2436
|
170dd5440afb9ee68a973f3de13a99aa4c735d79
|
refs/heads/master
| 2021-01-12T14:06:25.773146
| 2017-12-22T16:05:45
| 2017-12-22T16:05:45
| 69,566,344
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 403
|
py
|
# -*- coding: utf-8 -*-
from __future__ import division
import math
a= input(' digite um valor:')
b= input(' digite um valor:')
c= input(' digite um valor:')
d= input(' digite um valor:')
if a>b>c>d:
print('S')
if a>b>c<d:
print('N')
if a>b<c>d:
print('N')
if a>b<c<d:
print('N')
if a<b>c>d:
print('S')
if a<b>c<d:
print('N')
if a<b<c>d:
print('S')
if a<b<c<d:
print('S')
|
[
"rafael.mota@ufca.edu.br"
] |
rafael.mota@ufca.edu.br
|
570b3e7425911bb1015aa72da24b6775e9a9cf9f
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03030/s750969702.py
|
3af20d6d293086c39ad8ce1585af7340da080628
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 159
|
py
|
n = int(input())
lst = []
for i in range(n):
s, p = input().split()
lst.append([s, -(int(p)), i+1])
lst.sort()
for i in range(n):
print(lst[i][2])
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
050b92002ed36ae06083ba938f6d02ed2827a17f
|
5ecaded45e28c1041c1986c13db446806a28b3ee
|
/function-arguments/learn-python-function-arguments/positional-argument-unpacking.py
|
15f83e9c8a7c4b9fe6c11866c9e470762c69f06a
|
[] |
no_license
|
109658067/Python3_Codecademy
|
12206ec74e8dc95cc1200491b4ed75b856bfb25e
|
8480912c6dd15649b3c51f4c205afdd253ea462b
|
refs/heads/master
| 2022-09-15T18:21:26.742741
| 2020-06-04T05:48:58
| 2020-06-04T05:48:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 423
|
py
|
from os.path import join
path_segment_1 = "/Home/User"
path_segment_2 = "Codecademy/videos"
path_segment_3 = "cat_videos/surprised_cat.mp4"
# join all three of the paths here!
print(join(path_segment_1, path_segment_2, path_segment_3))
def myjoin(*args):
joined_string = args[0]
for arg in args[1:]:
joined_string += '/' + arg
return joined_string
print(myjoin(path_segment_1, path_segment_2, path_segment_3))
|
[
"9368802+NiteshMistry@users.noreply.github.com"
] |
9368802+NiteshMistry@users.noreply.github.com
|
a506c46467e4562eaec2431f7bc7348fc991d68b
|
a4e41b84931ba69d7d8548a7df0ca4fe68ed02b5
|
/view/customer_test.py
|
6ab1159cf42343e130a8f828604dc27e840080ab
|
[] |
no_license
|
LittleDeveloper-CSharp/typography_rmp
|
b05869b735df1c72c6d0c11addb6b1c68fda62f3
|
6a0e50f7ffbdc51b609761be3bf23920721682b3
|
refs/heads/master
| 2023-04-13T21:36:22.589576
| 2021-04-25T20:05:52
| 2021-04-25T20:05:52
| 361,526,716
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,927
|
py
|
import models.customer
from tkinter import Entry, END, Button, Label, Frame, VERTICAL
from tkinter.ttk import Treeview, Scrollbar
class CustomerWindow:
def fill_tree_view(self):
self.list_customer = models.customer.select_customer()
for item in self.list_customer:
self.tree_view_customer.insert("", "end", values=item)
def filter_by_name(self, event, name):
self.final_filter()
def filter_by_patronymic(self, event, patronymic):
self.final_filter()
def filter_by_last_name(self, event, last_name):
self.final_filter()
@staticmethod
def final_filter():
global list_customer
a = 23
def accept_action(self):
action = self.bt_accept['text']
if action == "Добавить":
models.customer.insert_customer(list())
else:
models.customer.update_customer(self.index_customer, list())
self.fill_tree_view()
def delete_action(self):
models.customer.delete_customer(self.index_customer)
self.fill_tree_view()
def __init__(self, master):
self.master = master
self.frame = Frame(self.master)
self.index_customer = 0
self.list_customer = ()
self.frame_output_info = Frame()
self.frame_first_name_search = Frame(self.frame_output_info)
self.first_name_search_entry = Entry(self.frame_output_info)
self.first_name_search_entry.grid(row=0, column=0)
self.columns = ("1", "2", "3", "4", "5", "6")
self.tree_view_customer = Treeview(self.frame_output_info, show="headings", columns=self.columns,
displaycolumns=("2", "3", "4", "5", "6"))
self.tree_view_customer.heading("2", text="Фамилия")
self.tree_view_customer.heading("3", text="Имя")
self.tree_view_customer.heading("4", text="Отчество")
self.tree_view_customer.heading("5", text="Адрес")
self.tree_view_customer.heading("6", text="Телефон")
self.ysb = Scrollbar(orient=VERTICAL, command=self.tree_view_customer.yview)
self.tree_view_customer.config(yscroll=self.ysb.set)
self.tree_view_customer.grid(column=0)
self.frame_output_info.grid(row=0, column=0)
self.frame_for_add = Frame()
self.frame_last_name = Frame(self.frame_for_add)
Label(self.frame_last_name, text="Фамилия").grid(row=0)
self.last_name_entry = Entry(self.frame_last_name)
self.last_name_entry.grid(row=1)
self.frame_last_name.grid(row=0)
self.frame_first_name = Frame(self.frame_for_add)
Label(self.frame_first_name, text="Имя").grid(row=0)
self.first_name_entry = Entry(self.frame_first_name)
self.first_name_entry.grid(row=1)
self.frame_first_name.grid(row=1)
self.frame_patronymic = Frame(self.frame_for_add)
Label(self.frame_patronymic, text="Отчество").grid(row=0)
self.patronymic_entry = Entry(self.frame_patronymic)
self.patronymic_entry.grid(row=1)
self.frame_patronymic.grid(row=2)
self.frame_address = Frame(self.frame_for_add)
Label(self.frame_address, text="Адрес").grid(row=0)
self.address_entry = Entry(self.frame_address)
self.address_entry.grid(row=1)
self.frame_address.grid(row=3)
self.frame_phone = Frame(self.frame_for_add)
Label(self.frame_phone, text="Телефон").grid(row=0)
self.phone_entry = Entry(self.frame_phone)
self.phone_entry.grid(row=1)
self.frame_phone.grid(row=4)
self.bt_accept = Button(self.frame_for_add, text="Добавить")
self.bt_accept.grid(row=5)
Button(self.frame_for_add, text="Удалить").grid(row=6)
self.frame_for_add.grid(row=0, column=1)
self.fill_tree_view()
|
[
"test"
] |
test
|
c0f9dbecd67de39faf7a200cd391cce07c3eb470
|
c80e4dea4548de89d32f2abd6ca58812670ecc7b
|
/scripts/regal/RegalDispatch.py
|
49aa3451931469377a6fd4c1f560c3bfcb014de4
|
[
"Unlicense",
"MIT",
"LicenseRef-scancode-glut",
"BSD-3-Clause",
"SGI-B-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] |
permissive
|
chinmaygarde/regal
|
971699cc8d991633b7257ce9ced2b4d65dd6d9b2
|
db0832075bd78241afe003b9c1b8f6ac0051370b
|
refs/heads/master
| 2021-01-17T04:42:10.354459
| 2012-10-10T09:08:13
| 2012-10-10T09:08:13
| 6,150,566
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,311
|
py
|
#!/usr/bin/python -B
from string import Template, upper, replace
from ApiUtil import outputCode
from ApiUtil import typeIsVoid
from ApiCodeGen import *
from RegalDispatchLog import apiDispatchFuncInitCode
from RegalDispatchEmu import dispatchSourceTemplate
from RegalContextInfo import cond
##############################################################################################
def apiGlobalDispatchTableDefineCode(apis, args):
categoryPrev = None
code = ''
code += 'struct DispatchTableGlobal {\n'
code += '\n'
code += ' DispatchTableGlobal();\n'
code += ' ~DispatchTableGlobal();\n'
for api in apis:
code += '\n'
if api.name in cond:
code += '#if %s\n' % cond[api.name]
for function in api.functions:
if function.needsContext:
continue
if getattr(function,'regalOnly',False)==True:
continue
name = function.name
params = paramsDefaultCode(function.parameters, True)
rType = typeCode(function.ret.type)
category = getattr(function, 'category', None)
version = getattr(function, 'version', None)
if category:
category = category.replace('_DEPRECATED', '')
elif version:
category = version.replace('.', '_')
category = 'GL_VERSION_' + category
# Close prev if block.
if categoryPrev and not (category == categoryPrev):
code += '\n'
# Begin new if block.
if category and not (category == categoryPrev):
code += ' // %s\n\n' % category
code += ' %s(REGAL_CALL *%s)(%s);\n' % (rType, name, params)
categoryPrev = category
if api.name in cond:
code += '#endif // %s\n' % cond[api.name]
code += '\n'
# Close pending if block.
if categoryPrev:
code += '\n'
code += '};\n'
return code
def apiDispatchTableDefineCode(apis, args):
categoryPrev = None
code = ''
code += 'struct DispatchTable {\n'
code += '\n'
code += ' bool _enabled;\n'
code += ' DispatchTable *_prev;\n'
code += ' DispatchTable *_next;\n'
code += '''
// Lookup a function pointer from the table,
// or deeper in the stack as necessary.
template<typename T>
T call(T *func)
{
RegalAssert(func);
if (_enabled && *func)
return *func;
DispatchTable *i = this;
RegalAssert(i);
RegalAssert(reinterpret_cast<void *>(func)>=reinterpret_cast<void *>(i));
RegalAssert(reinterpret_cast<void *>(func)< reinterpret_cast<void *>(i+1));
std::size_t offset = reinterpret_cast<char *>(func) - reinterpret_cast<char *>(i);
T f = *func;
// Step down the stack for the first available function in an enabled table
while (!f || !i->_enabled)
{
// Find the next enabled dispatch table
for (i = i->_next; !i->_enabled; i = i->_next) { RegalAssert(i); }
// Get the function pointer
RegalAssert(i);
RegalAssert(i->_enabled);
f = *reinterpret_cast<T *>(reinterpret_cast<char *>(i)+offset);
}
return f;
}
'''
for api in apis:
code += '\n'
if api.name in cond:
code += '#if %s\n' % cond[api.name]
for function in api.functions:
if not function.needsContext:
continue
if getattr(function,'regalOnly',False)==True:
continue
name = function.name
params = paramsDefaultCode(function.parameters, True)
rType = typeCode(function.ret.type)
category = getattr(function, 'category', None)
version = getattr(function, 'version', None)
if category:
category = category.replace('_DEPRECATED', '')
elif version:
category = version.replace('.', '_')
category = 'GL_VERSION_' + category
# Close prev if block.
if categoryPrev and not (category == categoryPrev):
code += '\n'
# Begin new if block.
if category and not (category == categoryPrev):
code += ' // %s\n\n' % category
code += ' %s(REGAL_CALL *%s)(%s);\n' % (rType, name, params)
categoryPrev = category
if api.name in cond:
code += '#endif // %s\n' % cond[api.name]
code += '\n'
# Close pending if block.
if categoryPrev:
code += '\n'
code += '};\n'
return code
dispatchHeaderTemplate = Template( '''${AUTOGENERATED}
${LICENSE}
#ifndef __${HEADER_NAME}_H__
#define __${HEADER_NAME}_H__
#include "RegalUtil.h"
REGAL_GLOBAL_BEGIN
#include <GL/Regal.h>
REGAL_GLOBAL_END
REGAL_NAMESPACE_BEGIN
${API_GLOBAL_DISPATCH_TABLE_DEFINE}
extern DispatchTableGlobal dispatchTableGlobal;
${API_DISPATCH_TABLE_DEFINE}
REGAL_NAMESPACE_END
#endif // __${HEADER_NAME}_H__
''')
def generateDispatchHeader(apis, args):
globalDispatchTableDefine = apiGlobalDispatchTableDefineCode( apis, args )
dispatchTableDefine = apiDispatchTableDefineCode(apis, args)
# Output
substitute = {}
substitute['LICENSE'] = args.license
substitute['AUTOGENERATED'] = args.generated
substitute['COPYRIGHT'] = args.copyright
substitute['HEADER_NAME'] = 'REGAL_DISPATCH'
substitute['API_GLOBAL_DISPATCH_TABLE_DEFINE'] = globalDispatchTableDefine
substitute['API_DISPATCH_TABLE_DEFINE'] = dispatchTableDefine
outputCode( '%s/RegalDispatch.h' % args.outdir, dispatchHeaderTemplate.substitute(substitute))
|
[
"nigels@users.sourceforge.net"
] |
nigels@users.sourceforge.net
|
dc55651adbffad521879c30bf2544d1f19ac7c98
|
472370808bd279442f25b1bb96c20e8a164d3b06
|
/train_k7.py
|
772ef38767cbcb6b81ba9125cae686aaaed5a87c
|
[] |
no_license
|
Qidian213/Emotion_challenge
|
d2983a078aa6c0ff76d052d0120acc9f387ecb6d
|
b214c532a4b079d6654507d2865ec65336ead65e
|
refs/heads/master
| 2021-08-28T20:58:45.547325
| 2021-08-18T11:10:46
| 2021-08-18T11:10:46
| 246,117,379
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,430
|
py
|
import os
import logging
import torch
import torch.optim
import numpy as np
from torch.optim import lr_scheduler
from datasets import make_dataloader,RandomSampler,train_collate
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.nn.parallel.data_parallel import data_parallel
from model import Baseline
import pandas as pd
from collections import defaultdict
os.environ['CUDA_VISIBLE_DEVICES'] = '7'
kd_id = 7
kd_num = 10
batch_size = 64
instance_num = 2
tr_w = 0.5
#device = torch.device("cuda:1,2" if torch.cuda.is_available() else "cpu")
ind2label = [ 'N_N', '1_1', '1_2', '1_3', '1_4', '1_5', '1_6', '1_7',
'2_1', '2_2', '2_3', '2_4', '2_5', '2_6', '2_7',
'3_1', '3_2', '3_3', '3_4', '3_5', '3_6', '3_7',
'4_1', '4_2', '4_3', '4_4', '4_5', '4_6', '4_7',
'5_1', '5_2', '5_3', '5_4', '5_5', '5_6', '5_7',
'6_1', '6_2', '6_3', '6_4', '6_5', '6_6', '6_7',
'7_1', '7_2', '7_3', '7_4', '7_5', '7_6', '7_7' ]
def adjust_lr(optimizer, epoch):
for param_group in optimizer.param_groups:
if epoch < 2:
param_group['lr'] = 0.00001
elif epoch < 20:
param_group['lr'] = 0.0001
else:
param_group['lr'] = param_group['lr'] * 0.95
print('Adjust learning rate: {}'.format(param_group['lr']))
def train_fuc(model, epoch):
model = model.train()
step_loss = 0
correct = 0
num_all = 0
for step, (images,lms,labels)in enumerate(train_loader):
images = images.cuda()
labels = labels.cuda()
lms = lms.cuda()
prds,feat = model(images, lms)
# loss = model.criterion(prds, labels) + tr_w*model.triplet(feat, labels)
loss = model.xent(prds, labels) + tr_w*model.triplet(feat, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
prediction = torch.argmax(prds.detach(), 1)
correct += (prediction == labels).sum().float()
num_all += len(labels)
step_loss += loss
if(step%20 == 0):
print('[{}/{}/{}], Loss:{}, Acc: {}'.format(step, train_length, epoch,
'%.5f' % (step_loss/20), '%.5f' % (correct/num_all)))
step_loss = 0
correct = 0
num_all = 0
print('--------------------------------------------------------------------')
def val_fuc(model, epoch):
model = model.eval()
correct = 0
num_all = 0
with torch.no_grad():
result = defaultdict(list)
for step, (images,lms,labels)in enumerate(val_loader):
images = images.cuda()
labels = labels.cuda()
lms = lms.cuda()
prds,_ = model(images, lms)
prediction = torch.argmax(prds.detach(), 1)
correct += (prediction == labels).sum().float()
num_all += len(labels)
prds = F.softmax(prds)
prds = prds.cpu().numpy()
for pred, label in zip(prds, labels):
pred = list(pred)
for ind, prd in enumerate(pred):
result[ind2label[ind]].append(prd)
result['gt'].append(ind2label[label])
dataframe = pd.DataFrame(result)
dataframe.to_csv("models/val_" + str(kd_id) + '_' + model_name + '_' + '%.5f' % (correct/num_all) +".csv",index=False,sep=',')
print('Epoch: {}, Val_Acc: {}'.format(epoch, '%.5f' % (correct/num_all)))
print('--------------------------------------------------------------------')
return correct/num_all
# model_name = 'mobilfacenet'
# model_path='model_mobilefacenet.pth'
# model_name = 'model_ir_se50'
# model_path='model_ir_se50.pth'
# model_name = 'resnet50_ibn_a'
# model_path = 'resnet50_ibn_a.pth.tar'
# model_name = 'se_resnet50'
# model_path = 'se_resnet50-ce0d4300.pth'
model_name = 'AlexNet'
model_path='model_mobilefacenet.pth'
# model_name = 'MiniXception'
# model_path = ' '
# model_name = 'ConvNet'
# model_path = ' '
# model_name = 'MixNet'
# model_path = ' '
model = Baseline(model='train',model_name = model_name, model_path=model_path)
#model.load_param('models/model_1_180000.pth')
model = model.cuda()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
#exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.1)
# kd_id = 0
# kd_num = 7
# batch_size = 48
# instance_num = 1
train_data, val_data, trains, vals = make_dataloader(kd_id,kd_num)
train_loader = DataLoader(dataset=train_data, batch_size=batch_size, sampler=RandomSampler(trains, batch_size, instance_num), shuffle=False, num_workers=2, collate_fn=train_collate)
#train_loader = DataLoader(dataset=train_data, batch_size=48, shuffle=False, num_workers=2, collate_fn=train_collate)
val_loader = DataLoader(dataset=val_data, batch_size=64, shuffle=False, num_workers=2, collate_fn=train_collate )
train_length = len(train_loader)
val_length = len(val_loader)
if __name__ == '__main__':
max_epoch = 50
max_val_acc = 0
for epoch in range(0,max_epoch):
adjust_lr(optimizer, epoch)
train_fuc(model, epoch)
val_acc = val_fuc(model, epoch)
torch.save(model.state_dict(), 'models/'+ str(kd_id)+'_'+ model_name + '_'+ '%.5f'%(val_acc) +'_'+ str(epoch) +'.pth')
|
[
"xhx1247786632@gmail.com"
] |
xhx1247786632@gmail.com
|
5b7cc4476300d195ed7f2a305a7db60edd92fcc5
|
dc40794d0d17f4ee552d58621c4340e60a998d68
|
/leetcode/python/remove-all-adjacent-duplicates-in-string.py
|
c6153b82c0e4c1b7c2a2b2f055323d3690212110
|
[] |
no_license
|
lsom11/coding-challenges
|
26e67e440bea4c42a0f28051653290f2cb08d0e7
|
4c127fdeb2ccbbdcdee0c8cd5d5ba47631508479
|
refs/heads/master
| 2021-11-23T11:40:37.516896
| 2021-10-27T15:50:35
| 2021-10-27T15:50:35
| 193,889,529
| 1
| 3
| null | 2020-10-27T12:59:54
| 2019-06-26T11:15:27
|
Python
|
UTF-8
|
Python
| false
| false
| 238
|
py
|
class Solution:
def removeDuplicates(self, S):
stack = []
for s in S:
if not stack or s != stack[-1]:
stack += [s]
else:
stack.pop()
return ''.join(stack)
|
[
"lucwsomers@gmail.com"
] |
lucwsomers@gmail.com
|
5a1531e3ab03bca5ad92b86fd67eda6eaa285b9a
|
13acfcb4a300d6c9f40c79f56175c74b0f673c3f
|
/ILI9341/examples/01_basic/05a_println.py
|
9be665576366149f3decadc57fbec3e13c34cad2
|
[] |
no_license
|
mchobby/pyboard_drive
|
821d7fce0f6791877397159cdf3c0636916628ae
|
8e32dc68b131d31aba38087588883fac26534d0f
|
refs/heads/master
| 2021-01-18T16:13:50.127858
| 2016-04-10T19:43:21
| 2016-04-10T19:43:21
| 55,912,768
| 1
| 0
| null | 2016-04-10T17:25:57
| 2016-04-10T17:25:56
|
Python
|
UTF-8
|
Python
| false
| false
| 1,103
|
py
|
# The driver allows you to draw text (string) on the screen.
# Text drawing has the following feature:
# * Support of various font
# * Support for text color (and background color)
# * Cursor blinking
# * Draw from position (x,y)
#
from lcd import *
from fonts.arial_14 import Arial_14
import pyb
l = LCD( rate=21000000 ) # step down the SPI bus speed to 21 MHz may be opportune when using 150+ mm wires
l.fillMonocolor( CYAN )
# Create an object that can print string on the screen
# * initCh() create a BaseChars object which retains graphical properties about the printed string
# * bgcolor, color: defines the background color and the text color
# * font : Arial_14 by default allows you to define the font to use
# * scale: scale the font (1, 2, 3)
# * bctimes: number of time to blink the cursor (when requested)
#
c = l.initCh(font=Arial_14, color=RED, bgcolor=CYAN)
# Print the string at position x=10, y=10
# bc: False by default, allows to show the blinking cursor when the string is printed
# scale: scale the font (1, 2, 3)
#
c.printLn( "Hello PyBoard", 10, 10 )
|
[
"info@mchobby.be"
] |
info@mchobby.be
|
8257e2e8157015ef95f33c5f7785f5aef2c3375c
|
170026ff5b435027ce6e4eceea7fff5fd0b02973
|
/glycan_profiling/serialize/base.py
|
b71b0e0048d9fda6a2af63717a16b06d6e733fa8
|
[
"Apache-2.0"
] |
permissive
|
mstim/glycresoft
|
78f64ae8ea2896b3c4f4c185e069387824e6c9f5
|
1d305c42c7e6cba60326d8246e4a485596a53513
|
refs/heads/master
| 2022-12-24T23:44:53.957079
| 2020-09-29T13:38:20
| 2020-09-29T13:38:20
| 276,471,357
| 0
| 0
|
NOASSERTION
| 2020-07-01T20:04:43
| 2020-07-01T20:04:42
| null |
UTF-8
|
Python
| false
| false
| 1,397
|
py
|
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (
Column, Numeric, Integer, String, ForeignKey, PickleType,
Boolean)
from sqlalchemy.orm import validates
from sqlalchemy.orm.session import object_session
Base = declarative_base()
def Mass(index=True):
return Column(Numeric(14, 6, asdecimal=False), index=index)
def find_by_name(session, model_class, name):
return session.query(model_class).filter(model_class.name == name).first()
def make_unique_name(session, model_class, name):
marked_name = name
i = 1
while find_by_name(session, model_class, marked_name) is not None:
marked_name = "%s (%d)" % (name, i)
i += 1
return marked_name
class HasUniqueName(object):
name = Column(String(128), default=u"", unique=True)
uuid = Column(String(64), index=True, unique=True)
@classmethod
def make_unique_name(cls, session, name):
return make_unique_name(session, cls, name)
@classmethod
def find_by_name(cls, session, name):
return find_by_name(session, cls, name)
@validates("name")
def ensure_unique_name(self, key, name):
session = object_session(self)
if session is not None:
model_class = self.__class__
name = make_unique_name(session, model_class, name)
return name
else:
return name
|
[
"mobiusklein@gmail.com"
] |
mobiusklein@gmail.com
|
d5b88f8629f9f6924631d18a30e861b74631cacc
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_354/ch118_2020_10_05_20_26_56_452982.py
|
e6c9398b5afb5dea7dc4d9be024f67529850913e
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 169
|
py
|
import math
def reflexao_total_interna(n1,n2,o2):
y=(n2*math.sin(math.radians(o2)))/n1
if y > 1:
return True
else:
return False
|
[
"you@example.com"
] |
you@example.com
|
31cc256c5c48f8f108aebbc668b02473408ab0fc
|
0f9f8e8478017da7c8d408058f78853d69ac0171
|
/python3/l0203_remove_linked_list_elements.py
|
11775486cd12a337eda8f3139c2959e183cdbebc
|
[] |
no_license
|
sprax/1337
|
dc38f1776959ec7965c33f060f4d43d939f19302
|
33b6b68a8136109d2aaa26bb8bf9e873f995d5ab
|
refs/heads/master
| 2022-09-06T18:43:54.850467
| 2020-06-04T17:19:51
| 2020-06-04T17:19:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 344
|
py
|
from common import ListNode
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
p = dummy = ListNode(0)
dummy.next = head
while p.next:
if p.next.val == val:
p.next = p.next.next
else:
p = p.next
return dummy.next
|
[
"zhoulv82@gmail.com"
] |
zhoulv82@gmail.com
|
a1730b0036d7737aea484625171644187585d455
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_5630113748090880_0/Python/Dog/mainB.py
|
8ad199a6e9d658b1e59232341d93ba4eca935dc0
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 793
|
py
|
#! /usr/bin/env python3
import sys
def solve(numbers):
counts = dict((n, 0) for n in set(numbers))
for n in numbers:
counts[n] += 1
row = list()
for (n, c) in counts.items():
if c % 2 == 1:
row.append(n)
return ' '.join(map(str, sorted(row)))
#################################################################
if __name__ == '__main__':
filename = sys.argv[1]
with open(filename) as f:
content = f.read().strip()
numbers = list(map(int, content.split()))
T = numbers[0]
numbers = numbers[1:]
for c in range(T):
N = numbers[0]
numbers = numbers[1:]
ns = (2*N - 1)*N
lists = numbers[:ns]
numbers = numbers[ns:]
print('Case #', c+1, ': ', solve(lists), sep='')
|
[
"alexandra1.back@gmail.com"
] |
alexandra1.back@gmail.com
|
a85936ec234127243476ed150e317b33f2431a3c
|
8f0aa0b8b8a9c9a8884fa6cb769ee34639e2f355
|
/lending_library/lender_profile/models.py
|
ea35d7bdcd283a51b6d3d6541fb9033377044c57
|
[] |
no_license
|
datatalking/django-lender-401d7
|
3f9e2b46e73a0efd17c082b87edf4705ad7ddded
|
64eae040c4c778cb96e2dedbdb2de5dc2bc1223b
|
refs/heads/master
| 2020-03-11T17:16:31.631481
| 2017-11-30T23:11:14
| 2017-11-30T23:11:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 271
|
py
|
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class LenderProfile(models.Model):
location = models.CharField(max_length=200, blank=True, null=True)
user = models.OneToOneField(User, related_name='profile')
|
[
"nhuntwalker@gmail.com"
] |
nhuntwalker@gmail.com
|
0480de31fa8374c05cecf776dc5f07449d15f22e
|
15f321878face2af9317363c5f6de1e5ddd9b749
|
/solutions_python/Problem_95/2141.py
|
e328217501accf9709c862aaf76b4cc5c0f26338
|
[] |
no_license
|
dr-dos-ok/Code_Jam_Webscraper
|
c06fd59870842664cd79c41eb460a09553e1c80a
|
26a35bf114a3aa30fc4c677ef069d95f41665cc0
|
refs/heads/master
| 2020-04-06T08:17:40.938460
| 2018-10-14T10:12:47
| 2018-10-14T10:12:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 455
|
py
|
from string import maketrans
import sys
def trans(input):
alpha = "abcdefghijklmnopqrstuvwxyz"
trans = "yhesocvxduiglbkrztnwjpfmaq"
transtab = maketrans(alpha,trans)
return input.translate(transtab)
if __name__ == "__main__":
f = sys.stdin
if len(sys.argv) >= 2:
fn = sys.argv[1]
if fn != '-':
f = open(fn)
t = int(f.readline())
for s in xrange(t):
inp = f.readline()
print "Case #%d: %s" %(s+1,trans(inp).strip())
|
[
"miliar1732@gmail.com"
] |
miliar1732@gmail.com
|
dd9ac21ba1fb5bced046fac8d050cf79d2b20897
|
fb28a622b21f5127c83c7fe6193b6312294b2dbe
|
/apps/order/migrations/0010_auto_20190729_0947.py
|
911a373cc6830572f340789dd65c5e59e26d2a0d
|
[] |
no_license
|
laoyouqing/video
|
0cd608b1f9d3a94da4a537867fafce6f7dcd1297
|
9aa7ecf17f0145437408a8c979f819bb61617294
|
refs/heads/master
| 2022-12-19T11:02:01.343892
| 2019-08-21T04:00:13
| 2019-08-21T04:00:13
| 203,500,521
| 0
| 0
| null | 2022-12-08T06:03:17
| 2019-08-21T03:40:13
|
Python
|
UTF-8
|
Python
| false
| false
| 536
|
py
|
# Generated by Django 2.1.1 on 2019-07-29 01:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('order', '0009_auto_20190729_0941'),
]
operations = [
migrations.AlterField(
model_name='ordergoods',
name='video',
field=models.ForeignKey(help_text='订单商品', null=True, on_delete=django.db.models.deletion.CASCADE, to='videos.Video', verbose_name='订单商品'),
),
]
|
[
"lingo.lin@foxmail.com"
] |
lingo.lin@foxmail.com
|
5326a03c579aa60eca70ccc490e2ce6b66223d77
|
15f0514701a78e12750f68ba09d68095172493ee
|
/Python3/488.py
|
2fe4101ca082c932b0960dd56c0a27563aed247f
|
[
"MIT"
] |
permissive
|
strengthen/LeetCode
|
5e38c8c9d3e8f27109b9124ae17ef8a4139a1518
|
3ffa6dcbeb787a6128641402081a4ff70093bb61
|
refs/heads/master
| 2022-12-04T21:35:17.872212
| 2022-11-30T06:23:24
| 2022-11-30T06:23:24
| 155,958,163
| 936
| 365
|
MIT
| 2021-11-15T04:02:45
| 2018-11-03T06:47:38
| null |
UTF-8
|
Python
| false
| false
| 3,473
|
py
|
__________________________________________________________________________________________________
sample 28 ms submission
class Solution:
def findMinStep(self, board: str, hand: str) -> int:
from collections import Counter
balls_count = Counter(hand)
return self.dfs(board, balls_count)
def dfs(self, board, balls_count):
if not board:
return 0
answer = float('inf')
i = 0
while i < len(board):
j = i + 1
while j < len(board) and board[j] == board[i]:
j += 1
gap = 3 - (j - i)
if balls_count[board[i]] >= gap:
if (j - i) > 3:
gap = 0
balls_count[board[i]] -= gap
a = self.dfs(board[:i] + board[j:], balls_count)
if a >= 0:
answer = min(answer, a + gap)
balls_count[board[i]] += gap
i = j
return answer if answer != float('inf') else -1
__________________________________________________________________________________________________
sample 32 ms submission
class Solution:
def findMinStep(self, board: str, hand: str) -> int:
if not board or len(board) == 0:
return -1
hand_map = {}
for b in hand:
hand_map[b] = hand_map.get(b, 0) + 1
min_res = [len(hand) + 1]
self.dfs(board, hand_map, 0, min_res)
return min_res[0] if min_res[0] != len(hand) + 1 else -1
def dfs(self, board, hand_map, used, min_res):
l = len(board)
if l == 0:
if min_res[0] > used:
min_res[0] = used
return
if len(hand_map) == 0:
return
for i in range(l):
ch = board[i]
if ch not in hand_map:
continue
count = hand_map[ch]
if i < l-1 and board[i+1] == ch:
new_count = count - 1
if new_count == 0:
del hand_map[ch]
else:
hand_map[ch] = new_count
new_board = self.create_board(board, i-1, i+2)
self.dfs(new_board, hand_map, used+1, min_res)
hand_map[ch] = count
elif count >= 2:
new_count = count - 2
if new_count == 0:
del hand_map[ch]
else:
hand_map[ch] = new_count
new_board = self.create_board(board, i-1, i+1)
self.dfs(new_board, hand_map, used+2, min_res)
hand_map[ch] = count
def create_board(self, board, left, right):
l = len(board)
while left >= 0 and right < l:
ch = board[left]
count = 0
i, j = left, right
while i >= 0 and board[i] == ch:
i -= 1
count += 1
while j < l and board[j] == ch:
j += 1
count += 1
if count < 3:
break
else:
left, right = i, j
return board[:left+1] + board[right:]
__________________________________________________________________________________________________
|
[
"strengthen@users.noreply.github.com"
] |
strengthen@users.noreply.github.com
|
c4a6e8d1854c60e586f254827e4f58e654aec6df
|
910d1c6f0531982ac85cfbfcfd96f694d77d53d9
|
/tornado-restfulapi/celery_app/celeryconfig.py
|
b54ff2f18fb2036a8084450817b73fe78a3fcf5c
|
[
"MIT"
] |
permissive
|
zhangyong7887/tornado
|
d00ed173a542c187a2272fd9d250679894cc3263
|
2a89ce36380c7f322acbcd7cf5b035b3e8d99619
|
refs/heads/main
| 2023-03-27T07:26:11.600519
| 2021-03-11T22:08:18
| 2021-03-11T22:08:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,812
|
py
|
from celery.schedules import crontab
from datetime import timedelta
from kombu import Queue
from kombu import Exchange
# 设置任务接受的类型,默认是{'json'}
accept_content = ['json']
# 请任务接受后存储时的类型
result_accept_content = ['json']
# 时间格式化为中国的标准
timezone = "Asia/Shanghai"
# 结果序列化为json格式 默认值json从4.0开始(之前为pickle)。
result_serializer = 'json'
# 指定borker为redis 如果指定rabbitmq broker_url = 'amqp://guest:guest@localhost:5672//'
broker_url = "redis://127.0.0.1/0"
# 指定存储结果的地方,支持使用rpc、数据库、redis等等,具体可参考文档 # result_backend = 'db+mysql://scott:tiger@localhost/foo' # mysql 作为后端数据库
result_backend = "redis://127.0.0.1/1"
# 设置任务过期时间 默认是一天,为None或0 表示永不过期
result_expires = 60 * 60 * 24
# 设置worker并发数,默认是cpu核心数
worker_concurrency = 12
# 设置每个worker最大任务数
worker_max_tasks_per_child = 100
# 指定任务队列,使不同的任务在不同的队列中被执行 如果配置,在启动celery时需要增加 -Q add 多个示例 -Q add,mul
# 示例:celery -A celery_app worker -Q add -l info -P eventlet(在Windows下启动worker,它将只消费add队列中的消息,也就是只执行add任务)
# 示例:celery -A celery_app worker -Q add,mul -l info(在Linux下启动worker,它将只消费add和mul队列中的消息,也就是只执行add和mul任务)
# task_routes = {
# 'celery_app.tasks.add': {'queue': 'add'},
# 'celery_app.tasks.mul': {'queue': 'mul'},
# 'celery_app.tasks.xsum': {'queue': 'xsum'},
# }
# 指定任务的位置
imports = (
'celery_app.tasks',
'apps.users.tasks',
)
# 后台运行worker示例:
|
[
"wishkind@126.com"
] |
wishkind@126.com
|
7f9cf2c3ee18d83cacfa58b96162d62ed0d51a03
|
52cb25dca22292fce4d3907cc370098d7a57fcc2
|
/BAEKJOON/다이나믹 프로그래밍/9461_파도반 수열.py
|
9696a17c3a5037916b2f467d9cac06307a38b7ef
|
[] |
no_license
|
shjang1013/Algorithm
|
c4fc4c52cbbd3b7ecf063c716f600d1dbfc40d1a
|
33f2caa6339afc6fc53ea872691145effbce0309
|
refs/heads/master
| 2022-09-16T12:02:53.146884
| 2022-08-31T16:29:04
| 2022-08-31T16:29:04
| 227,843,135
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 295
|
py
|
# 동적 계획법(다이나믹 프로그래밍)을 이용
# 4번째부터 규칙 존재
def triangle(N):
f = [0, 1, 1, 1]
for i in range(4, N+1):
f.append(f[i-3]+f[i-2])
return f[N]
T = int(input())
for _ in range(T):
N = int(input())
print(triangle(N))
|
[
"shjang113@gmail.com"
] |
shjang113@gmail.com
|
2189c521d643b8c9feae447145f8e67196cd1384
|
ea727658bb22df6dd0a4d8aaff5d13beec8ec8b5
|
/examples/大數據資料分析/範例程式/第11章/program11-2.py
|
ee59c8722f865802cb46b9adc72cedd22431edec
|
[] |
no_license
|
kelvinchoiwc/DataScience_1082
|
f8e31c230776f45d70f6b96ef81d16881118e453
|
199f915540afe6c9a9ec7055aac5911420d783be
|
refs/heads/master
| 2023-07-24T04:29:01.763893
| 2021-09-01T12:33:21
| 2021-09-01T12:33:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 235
|
py
|
import random
s2 = tuple([random.randint(1, 49) for i in range(1,100)])
print(s2)
lottoNums = 50*[0]
for i in range(len(s2)):
k = s2[i]
lottoNums[k] += 1
for j in range(1, len(lottoNums)):
print('%d: %d'%(j, lottoNums[j]))
|
[
"jumbokh@gmail.com"
] |
jumbokh@gmail.com
|
e03e4f0d8e5feaf4628a344d6adcdffa5bdb7312
|
0adb19e463ec27dda57b7f551b2d49e229053b8c
|
/film_editing/film_edit_skill.py
|
16cc540b54225aae15ee09161b532391f16a7bf9
|
[] |
no_license
|
alam-mahtab/FastapiCD
|
c8d36852a674583bba088eee8b1cb98a24acbea1
|
7206179408a9ae67ba485a4620d14b470009153d
|
refs/heads/main
| 2023-02-25T05:56:35.685081
| 2021-02-03T16:16:26
| 2021-02-03T16:16:26
| 335,682,061
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,741
|
py
|
from typing import List
from fastapi import Depends,File, UploadFile, APIRouter
from sqlalchemy.orm import Session
from film_editing import crud, models
from writer.database import SessionLocal, engine
from film_editing.schemas import FilmeditBase, FilmeditList
from film_editing.models import Filmedit
# Pagination
from fastapi_pagination import Page, pagination_params
from fastapi_pagination.paginator import paginate
router = APIRouter()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
models.Base.metadata.create_all(bind=engine)
import uuid
from pathlib import Path
import time
#from fastapi.staticfiles import StaticFiles
from starlette.staticfiles import StaticFiles
import os
from os.path import dirname, abspath, join
import shutil
router.mount("/static", StaticFiles(directory="static"), name="static")
dirname = dirname(dirname(abspath(__file__)))
images_path = join(dirname, '/static')
@router.post("/film_editing/")
def create_film_edit(
desc:str,name:str,file_pro: UploadFile= File(...), file_cover: UploadFile= File(...), db: Session = Depends(get_db)
):
extension_pro = file_pro.filename.split(".")[-1] in ("jpg", "jpeg", "png")
if not extension_pro:
return "Image must be jpg or png format!"
suffix_pro = Path(file_pro.filename).suffix
filename_pro = time.strftime( str(uuid.uuid4().hex) + "%Y%m%d-%H%M%S" + suffix_pro )
with open("static/"+filename_pro, "wb") as image:
shutil.copyfileobj(file_pro.file, image)
url_profile = os.path.join(images_path, filename_pro)
extension_cover = file_cover.filename.split(".")[-1] in ("jpg", "jpeg", "png")
if not extension_cover:
return "Image must be jpg or png format!"
suffix_cover =Path(file_cover.filename).suffix
filename_cover = time.strftime( str(uuid.uuid4().hex) + "%Y%m%d-%H%M%S" + suffix_cover )
with open("static/"+filename_cover, "wb") as image:
shutil.copyfileobj(file_cover.file, image)
url_cover = os.path.join(images_path, filename_cover)
return crud.create_film_edit(db=db,name=name,desc=desc,url_profile=url_profile,url_cover=url_cover)
@router.get("/film_editings/" ,dependencies=[Depends(pagination_params)])
def film_edit_list(db: Session = Depends(get_db)):
film_edit_all =crud.film_edit_list(db=db)
return paginate(film_edit_all)
@router.get("/film_editings/{film_editing_id}")
def film_edit_detail(film_edit_id:int,db: Session = Depends(get_db)):
return crud.get_film_edit(db=db, id=film_edit_id)
@router.delete("film_editings/{film_editings_id}")
async def delete(film_edit_id: int, db: Session = Depends(get_db)):
deleted = await crud.delete(db, film_edit_id)
return {"deleted": deleted}
|
[
"67095487+alam-mahtab@users.noreply.github.com"
] |
67095487+alam-mahtab@users.noreply.github.com
|
f0806efc13466846b13387d88cdb1bf970b40434
|
5254c3a7e94666264120f26c87734ad053c54541
|
/4. Aleatoridad/4.2 Random/ejercicio_4.9.py
|
dfd5b986fc932ed4cef71f7090ca15df0345c9d0
|
[] |
no_license
|
ccollado7/UNSAM---Python
|
425eb29a2df8777e9f892b08cc250bce9b2b0b8c
|
f2d0e7b3f64efa8d03f9aa4707c90e992683672d
|
refs/heads/master
| 2023-03-21T17:42:27.210599
| 2021-03-09T13:06:45
| 2021-03-09T13:06:45
| 286,613,172
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 220
|
py
|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 27 09:13:45 2020
@author: User
"""
#Ejercicio 4.9
import random
def genear_punto():
x = random.random()
y = random.random()
return(x,y)
print(genear_punto())
|
[
"46108725+ccollado7@users.noreply.github.com"
] |
46108725+ccollado7@users.noreply.github.com
|
aff205bbbf740f5431d56b6de1825f1a154142f0
|
04b1803adb6653ecb7cb827c4f4aa616afacf629
|
/components/timers/DEPS
|
413f57b96cae54eaae8224d794ee782a7eca92c5
|
[
"BSD-3-Clause"
] |
permissive
|
Samsung/Castanets
|
240d9338e097b75b3f669604315b06f7cf129d64
|
4896f732fc747dfdcfcbac3d442f2d2d42df264a
|
refs/heads/castanets_76_dev
| 2023-08-31T09:01:04.744346
| 2021-07-30T04:56:25
| 2021-08-11T05:45:21
| 125,484,161
| 58
| 49
|
BSD-3-Clause
| 2022-10-16T19:31:26
| 2018-03-16T08:07:37
| null |
UTF-8
|
Python
| false
| false
| 237
|
include_rules = [
# This directory is shared with Chrome OS, which only links against
# base/. We don't want any other dependencies to creep in.
"-build",
"-content",
"-library_loaders",
"-net",
"-third_party",
"-url",
]
|
[
"sunny.nam@samsung.com"
] |
sunny.nam@samsung.com
|
|
bdd400d86f704fe57d59d284b35088dda056e839
|
a7058080e41af37eb77c146fc09a5e4db57f7ec6
|
/Solved/11723/11723_set.py
|
7a52dc728f80e451173148d39006f3a366c611eb
|
[] |
no_license
|
Jinmin-Goh/BOJ_PS
|
bec0922c01fbf6e440589cc684d0cd736e775066
|
09a285bd1369bd0d73f86386b343d271dc08a67d
|
refs/heads/master
| 2022-09-24T02:24:50.823834
| 2022-09-21T02:16:22
| 2022-09-21T02:16:22
| 223,768,547
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 994
|
py
|
# Problem No.: 11723
# Solver: Jinmin Goh
# Date: 20200410
# URL: https://www.acmicpc.net/problem/11723
import sys
def main():
n = int(input())
numSet = set()
for _ in range(n):
order = list(sys.stdin.readline().split())
if len(order) == 2:
num = int(order[1])
order = order[0]
if order == "add":
if num not in numSet:
numSet.add(num)
elif order == "check":
if num in numSet:
print(1)
else:
print(0)
elif order == "remove":
if num in numSet:
numSet.remove(num)
elif order == "toggle":
if num in numSet:
numSet.remove(num)
else:
numSet.add(num)
elif order == "all":
numSet = set([_ for _ in range(1, 21)])
elif order == "empty":
numSet = set()
return
if __name__ == "__main__":
main()
|
[
"eric970901@gmail.com"
] |
eric970901@gmail.com
|
f0f23530fb3cbc50111cfe4a488934543ebda0da
|
c7d7dfa5ac23b940e852a67155364439d9069486
|
/widget_image_tools/tests/test_data_get.py
|
e4b4e188f3230a7c9c77643e2405c1d4efe1f91c
|
[] |
no_license
|
shurshilov/odoo
|
d163f6c939bcbfb36bdf83eeeeffca368f0a4722
|
8099e62254b7f1e113be7b522585dbc352aea5a8
|
refs/heads/16.0
| 2023-09-04T03:02:31.427240
| 2023-09-03T16:25:28
| 2023-09-03T16:25:28
| 89,852,559
| 20
| 43
| null | 2023-09-03T06:30:22
| 2017-04-30T13:32:08
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 625
|
py
|
import logging
from openerp.tests.common import HttpCase
_logger = logging.getLogger(__name__)
class TestDataGet(HttpCase):
at_install = False
post_install = True
def test_data_get(self):
test_attachment = self.env.ref("ir_attachment_url.test_url_attachment")
self.env["ir.attachment"].search_read(
[("id", "=", test_attachment.id)], ["id", "datas"]
)
def test_open_url(self):
user_demo = self.env.ref("base.user_demo")
url = "/web/image?model=res.users&id={}&field=image_medium".format(
user_demo.id
)
self.url_open(url)
|
[
"shurshilov.a@yandex.ru"
] |
shurshilov.a@yandex.ru
|
92f627735e41204e95c82484985badde9791b02d
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02271/s655155562.py
|
70e2e74705b0aa77c4c0f55bb17c1e3a42de475a
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 198
|
py
|
n = int(input())
SET1 = {0}
for a in map(int, input().split()):
for b in tuple(SET1):
SET1.add(a + b)
input()
for m in map(int, input().split()):
print('yes' if m in SET1 else 'no')
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
b9168ca4256f538357f56f9175e1e1b507d98538
|
56f5b2ea36a2258b8ca21e2a3af9a5c7a9df3c6e
|
/CMGTools/H2TauTau/prod/25aug_corrMC/up/mc/VBF_HToTauTau_M-120_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0_1377467448/HTT_24Jul_newTES_manzoni_Up_Jobs/Job_80/run_cfg.py
|
c87bf367bb3c41826a53f12310721f39747c57ee
|
[] |
no_license
|
rmanzoni/HTT
|
18e6b583f04c0a6ca10142d9da3dd4c850cddabc
|
a03b227073b2d4d8a2abe95367c014694588bf98
|
refs/heads/master
| 2016-09-06T05:55:52.602604
| 2014-02-20T16:35:34
| 2014-02-20T16:35:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,477
|
py
|
import FWCore.ParameterSet.Config as cms
import os,sys
sys.path.append('/afs/cern.ch/user/m/manzoni/summer13/CMGTools/CMSSW_5_3_9/src/CMGTools/H2TauTau/prod/25aug_corrMC/up/mc/VBF_HToTauTau_M-120_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0_1377467448/HTT_24Jul_newTES_manzoni_Up_Jobs')
from base_cfg import *
process.source = cms.Source("PoolSource",
noEventSort = cms.untracked.bool(True),
inputCommands = cms.untracked.vstring('keep *',
'drop cmgStructuredPFJets_cmgStructuredPFJetSel__PAT'),
duplicateCheckMode = cms.untracked.string('noDuplicateCheck'),
fileNames = cms.untracked.vstring('/store/cmst3/user/cmgtools/CMG/VBF_HToTauTau_M-120_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_5.root',
'/store/cmst3/user/cmgtools/CMG/VBF_HToTauTau_M-120_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_50.root',
'/store/cmst3/user/cmgtools/CMG/VBF_HToTauTau_M-120_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_51.root',
'/store/cmst3/user/cmgtools/CMG/VBF_HToTauTau_M-120_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_52.root',
'/store/cmst3/user/cmgtools/CMG/VBF_HToTauTau_M-120_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_53.root')
)
|
[
"riccardo.manzoni@cern.ch"
] |
riccardo.manzoni@cern.ch
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.