blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 281 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 6 116 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 313 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 18.2k 668M ⌀ | star_events_count int64 0 102k | fork_events_count int64 0 38.2k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 107 values | src_encoding stringclasses 20 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 4 6.02M | extension stringclasses 78 values | content stringlengths 2 6.02M | authors listlengths 1 1 | author stringlengths 0 175 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b3955108d2bd467190ee0f8b33b6c7dae412e68a | 7b84f6ace903337a3a5894ea70c564ac6bc324be | /quiz-w7-2-densenet/datasets/download_and_convert_cifar10.py | 9711adc55b485f221751dd287481890fa33cf643 | [] | no_license | zhouzhiqi/Deep-Learning | 8d17359d7f66c46292e89a86f44326310b723052 | 416abd68737cd81e5d8bf15507d59bbd560d1c1a | refs/heads/master | 2021-09-14T16:57:29.203381 | 2018-05-16T08:38:41 | 2018-05-16T08:38:41 | 126,123,994 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 6,588 | py | # Copyright 2016 The TensorFlow Authors. 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.
# ==============================================================================
r"""Downloads and converts cifar10 data to TFRecords of TF-Example protos.
This module downloads the cifar10 data, uncompresses it, reads the files
that make up the cifar10 data and creates two TFRecord datasets: one for train
and one for test. Each TFRecord dataset is comprised of a set of TF-Example
protocol buffers, each of which contain a single image and label.
The script should take several minutes to run.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import tarfile
import numpy as np
from six.moves import cPickle
from six.moves import urllib
import tensorflow as tf
from datasets import dataset_utils
# The URL where the CIFAR data can be downloaded.
# _DATA_URL = 'http://192.168.0.108/D%3A/cifar-10-python.tar.gz'
_DATA_URL = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'
# The number of training files.
_NUM_TRAIN_FILES = 5
# The height and width of each image.
_IMAGE_SIZE = 32
# The names of the classes.
_CLASS_NAMES = [
'airplane',
'automobile',
'bird',
'cat',
'deer',
'dog',
'frog',
'horse',
'ship',
'truck',
]
def _add_to_tfrecord(filename, tfrecord_writer, offset=0):
"""Loads data from the cifar10 pickle files and writes files to a TFRecord.
Args:
filename: The filename of the cifar10 pickle file.
tfrecord_writer: The TFRecord writer to use for writing.
offset: An offset into the absolute number of images previously written.
Returns:
The new offset.
"""
with tf.gfile.Open(filename, 'rb') as f:
if sys.version_info < (3,):
data = cPickle.load(f)
else:
data = cPickle.load(f, encoding='bytes')
images = data[b'data']
num_images = images.shape[0]
images = images.reshape((num_images, 3, 32, 32))
labels = data[b'labels']
with tf.Graph().as_default():
image_placeholder = tf.placeholder(dtype=tf.uint8)
encoded_image = tf.image.encode_png(image_placeholder)
with tf.Session('') as sess:
for j in range(num_images):
sys.stdout.write('\r>> Reading file [%s] image %d/%d' % (
filename, offset + j + 1, offset + num_images))
sys.stdout.flush()
image = np.squeeze(images[j]).transpose((1, 2, 0))
label = labels[j]
png_string = sess.run(encoded_image,
feed_dict={image_placeholder: image})
example = dataset_utils.image_to_tfexample(
png_string, b'png', _IMAGE_SIZE, _IMAGE_SIZE, label)
tfrecord_writer.write(example.SerializeToString())
return offset + num_images
def _get_output_filename(dataset_dir, split_name):
"""Creates the output filename.
Args:
dataset_dir: The dataset directory where the dataset is stored.
split_name: The name of the train/test split.
Returns:
An absolute file path.
"""
return '%s/cifar10_%s.tfrecord' % (dataset_dir, split_name)
def _download_and_uncompress_dataset(dataset_dir):
"""Downloads cifar10 and uncompresses it locally.
Args:
dataset_dir: The directory where the temporary files are stored.
"""
filename = _DATA_URL.split('/')[-1]
filepath = os.path.join(dataset_dir, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> Downloading %s %.1f%%' % (
filename, float(count * block_size) / float(total_size) * 100.0))
sys.stdout.flush()
filepath, _ = urllib.request.urlretrieve(_DATA_URL, filepath, _progress)
print()
statinfo = os.stat(filepath)
print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
tarfile.open(filepath, 'r:gz').extractall(dataset_dir)
def _clean_up_temporary_files(dataset_dir):
"""Removes temporary files used to create the dataset.
Args:
dataset_dir: The directory where the temporary files are stored.
"""
filename = _DATA_URL.split('/')[-1]
filepath = os.path.join(dataset_dir, filename)
tf.gfile.Remove(filepath)
tmp_dir = os.path.join(dataset_dir, 'cifar-10-batches-py')
tf.gfile.DeleteRecursively(tmp_dir)
def run(dataset_dir):
"""Runs the download and conversion operation.
Args:
dataset_dir: The dataset directory where the dataset is stored.
"""
if not tf.gfile.Exists(dataset_dir):
tf.gfile.MakeDirs(dataset_dir)
training_filename = _get_output_filename(dataset_dir, 'train')
testing_filename = _get_output_filename(dataset_dir, 'test')
if tf.gfile.Exists(training_filename) and tf.gfile.Exists(testing_filename):
print('Dataset files already exist. Exiting without re-creating them.')
return
dataset_utils.download_and_uncompress_tarball(_DATA_URL, dataset_dir)
# First, process the training data:
with tf.python_io.TFRecordWriter(training_filename) as tfrecord_writer:
offset = 0
for i in range(_NUM_TRAIN_FILES):
filename = os.path.join(dataset_dir,
'cifar-10-batches-py',
'data_batch_%d' % (i + 1)) # 1-indexed.
offset = _add_to_tfrecord(filename, tfrecord_writer, offset)
# Next, process the testing data:
with tf.python_io.TFRecordWriter(testing_filename) as tfrecord_writer:
filename = os.path.join(dataset_dir,
'cifar-10-batches-py',
'test_batch')
_add_to_tfrecord(filename, tfrecord_writer)
# Finally, write the labels file:
labels_to_class_names = dict(zip(range(len(_CLASS_NAMES)), _CLASS_NAMES))
dataset_utils.write_label_file(labels_to_class_names, dataset_dir)
_clean_up_temporary_files(dataset_dir)
print('\nFinished converting the Cifar10 dataset!')
| [
"zhouzhiqi1234@outlook.com"
] | zhouzhiqi1234@outlook.com |
862ba01f331fad15fbd5638250d0613e8136b898 | 606d56d4dfe3eff3f34caa43091b725db06b885d | /src/productos/views.py | 95fdb6b404d32c98069129b37218835847c74b01 | [
"MIT",
"Apache-2.0"
] | permissive | Sublime441/inventario-api | 8b6a45fdba2e7076750a9d1b06630fbe7e8af93b | e084b18908f65a481fcca0cbd44a9c2e7236e18a | refs/heads/master | 2021-09-05T13:49:18.583407 | 2017-10-20T11:21:46 | 2017-10-20T11:21:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 437 | py | from rest_framework import viewsets
from .models import Producto
from .models import Categoria
from .serializers import CategoriaSerializer
from .serializers import ProductoSerializer
class CategoriaVista(viewsets.ModelViewSet):
queryset = Categoria.objects.all()
serializer_class = CategoriaSerializer
class ProductoVista(viewsets.ModelViewSet):
queryset = Producto.objects.all()
serializer_class = ProductoSerializer | [
"cercadocarlos@gmail.com"
] | cercadocarlos@gmail.com |
1a00af2d94457d9d773df82a3718628355f690e3 | 51c4288732642aa75b173c9efa25c02968aa5406 | /src/book/forms.py | 8ea6d15f3dfed41737d6182ea82ba16aa914c020 | [] | no_license | EvgPol19/Book | ae16276d5d41cf50ab9038b93a308c4be84c8280 | beeffe3c2fd55920239003b28b5b63cd1ad9d924 | refs/heads/main | 2023-07-17T01:29:32.698177 | 2021-08-17T07:13:29 | 2021-08-17T07:13:29 | 369,847,918 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 153 | py | from django import forms
from . import models
class CreateBook(forms.ModelForm):
class Meta:
model = models.Book
fields = '__all__'
| [
"elulbako@list.ru"
] | elulbako@list.ru |
9ca06377d8cd9fbe39082bfb3d7983c1eb7ddd2c | 6b27c39edc10b1353104043b7a523f4981c99ef2 | /pytype/tools/merge_pyi/test_data/stars.pep484.py | 56d6529efedb9cc54e761bdb5952bafc66cde7b3 | [
"Apache-2.0",
"MIT"
] | permissive | google/pytype | ad0ff0b6c1083b4f0a1af1747869d422f2b5f4d8 | bda0b9547af9a084bb2bd1427f58dcde968e48b5 | refs/heads/main | 2023-08-26T17:52:23.546035 | 2023-08-24T22:48:00 | 2023-08-24T22:48:00 | 32,483,713 | 4,595 | 367 | NOASSERTION | 2023-09-13T04:40:45 | 2015-03-18T20:52:08 | Python | UTF-8 | Python | false | false | 288 | py | def f1(*a):
pass
def f2(**a):
pass
def f3(a, *b):
pass
def f4(a, **b):
pass
## arg with default after *args is valid python3, not python2
def f5(*a, b=1):
pass
def f6(*a, b=1, **c):
pass
def f7(x=1, *a, b=1, **c):
pass
def f8(#asd
*a):
pass
| [
"rechen@google.com"
] | rechen@google.com |
f3ae22f885b78d753d9dbc851fea38a065e80d88 | 9fc768c541145c1996f2bdb8a5d62d523f24215f | /code/HomeWork/ch5/H_5_4.py | a92df699ef2667ea9bcb8c973b7297b29db61309 | [] | no_license | jumbokh/pyclass | 3b624101a8e43361458130047b87865852f72734 | bf2d5bcca4fff87cb695c8cec17fa2b1bbdf2ce5 | refs/heads/master | 2022-12-25T12:15:38.262468 | 2020-09-26T09:08:46 | 2020-09-26T09:08:46 | 283,708,159 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 722 | py | # H_5_4.py 功能:輸入數字後判斷是否為11的倍數
num_even = 0 # 儲存偶數位數字暫存
num_odd = 0 # 儲存奇數位數字暫存
number = str(input('請輸入數字 : '))
l = len(number) # 判斷輸入數字之長度
x = int(number) # 轉換成數值型態
for n in range(l,0,-1):
y = x//(10**(n-1)) # 計算奇偶位數字
x = x - (y*(10**(n-1)))
if n%2 == 0: # 判斷若是偶數位數字則儲存在偶數位暫存,反之存奇數位暫存
num_even = num_even + y
else:
num_odd = num_odd + y
# 判斷是否為11的倍數
if abs(num_even - num_odd) == 0 or (abs(num_even - num_odd))%11 == 0:
print('此數為11的倍數')
else:
print('此數不是11的倍數') | [
"jumbokh@gmail.com"
] | jumbokh@gmail.com |
b2fd156cbb5144ba90084307461364a83221c543 | 8feb451342837ba72967d06f339536e9b2dd6213 | /2018/Python/puzzle45_46.py | 17e5d209be95a13826f588c01ddda9b6d4684827 | [] | no_license | csvila/AdventOfCode | bcecfcfd404d10ee36b9f0c6a82561154cc2958d | 807ffba369b7a64167851e76a7edd632c7150e06 | refs/heads/master | 2020-04-16T06:06:17.851824 | 2019-12-10T16:18:15 | 2019-12-10T16:18:15 | 165,333,033 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,876 | py | import re
def get_bots(values):
r = re.compile("pos=<([0-9-]+),([0-9-]+),([0-9-]+)>, r=([0-9]+)")
bots = []
for cur in values:
if cur.startswith("#"):
print("# Note: " + cur)
else:
m = r.search(cur)
if m is None:
print(cur)
bots.append([int(x) for x in m.groups()])
return bots
def calc(values):
bots = get_bots(values)
best_i = None
best_val = None
for i in range(len(bots)):
if best_i is None or bots[i][3] > best_val:
best_val = bots[i][3]
best_i = i
bx, by, bz, bdist = bots[best_i]
ret = 0
for i in range(len(bots)):
x, y, z, _dist = bots[i]
if abs(x - bx) + abs(y - by) + abs(z - bz) <= bdist:
ret += 1
return ret
def find(done, bots, xs, ys, zs, dist, ox, oy, oz, forced_count):
at_target = []
for x in range(min(xs), max(xs)+1, dist):
for y in range(min(ys), max(ys)+1, dist):
for z in range(min(zs), max(zs)+1, dist):
# See how many bots are possible
count = 0
for bx, by, bz, bdist in bots:
if dist == 1:
calc = abs(x - bx) + abs(y - by) + abs(z - bz)
if calc <= bdist:
count += 1
else:
calc = abs((ox+x) - (ox+bx))
calc += abs((oy+y) - (oy+by))
calc += abs((oz+z) - (oz+bz))
# The minus three is to include the current box
# in any bots that are near it
if calc //dist - 3 <= (bdist) // dist:
count += 1
if count >= forced_count:
at_target.append((x, y, z, count, abs(x) + abs(y) + abs(z)))
while len(at_target) > 0:
best = []
best_i = None
# Find the best candidate from the possible boxes
for i in range(len(at_target)):
if best_i is None or at_target[i][4] < best[4]:
best = at_target[i]
best_i = i
if dist == 1:
# At the end, just return the best match
return best[4], best[3]
else:
# Search in the sub boxes, see if we find any matches
xs = [best[0], best[0] + dist//2]
ys = [best[1], best[1] + dist//2]
zs = [best[2], best[2] + dist//2]
a, b = find(done, bots, xs, ys, zs, dist // 2, ox, oy, oz, forced_count)
if a is None:
# This is a false path, remove it from consideration and try any others
at_target.pop(best_i)
else:
# We found something, go ahead and let it bubble up
return a, b
# This means all of the candidates yeild false paths, so let this one
# be treated as a false path by our caller
return None, None
def calc2(values):
bots = get_bots(values)
# Find the range of the bots
xs = [x[0] for x in bots] + [0]
ys = [x[1] for x in bots] + [0]
zs = [x[2] for x in bots] + [0]
# Pick a starting resolution big enough to find all of the bots
dist = 1
while dist < max(xs) - min(xs) or dist < max(ys) - min(ys) or dist < max(zs) - min(zs):
dist *= 2
# And some offset values so there are no strange issues wrapping around zero
ox = -min(xs)
oy = -min(ys)
oz = -min(zs)
# Try to find all of the bots, backing off with a binary search till
# we can find the most bots
span = 1
while span < len(bots):
span *= 2
forced_check = 1
tried = {}
best_val, best_count = None, None
while True:
# We might try the same value multiple times, save some time if we've seen it already
if forced_check not in tried:
tried[forced_check] = find(set(), bots, xs, ys, zs, dist, ox, oy, oz, forced_check)
test_val, test_count = tried[forced_check]
if test_val is None:
# Nothing found at this level, so go back
if span > 1:
span = span // 2
forced_check = max(1, forced_check - span)
else:
# We found something, so go forward
if best_count is None or test_count > best_count:
best_val, best_count = test_val, test_count
if span == 1:
# This means we went back one, and it was empty, so we're done!
break
forced_check += span
print("The max count I found was: " + str(best_count))
return best_val
def run(values):
print("Nearest the big bot: " + str(calc(values)))
print("Best location value: " + str(calc2(values)))
run(open('input23.txt').read().split('\n'))
| [
"cesar.vilarim@hotmail.com"
] | cesar.vilarim@hotmail.com |
a305c45934f4cccda3f2ff9cda3ac07315b86ddb | a1f00428cf522c8e51ff05101ab2a1024cf04248 | /python/matrix/matrix.py | 55438e97e1b764bbae2543bc8f394c06bc7f247d | [] | no_license | siddharthisaiah/exercism | c994132d9f59fa5c6b11cb28c10806aed41a1c30 | b4ce66543fdc70073916028c6bdd6f70ae1cc7a2 | refs/heads/master | 2023-01-05T23:35:48.341670 | 2019-07-09T17:42:52 | 2019-07-09T17:42:52 | 186,884,684 | 1 | 0 | null | 2023-01-05T02:14:45 | 2019-05-15T18:47:35 | Python | UTF-8 | Python | false | false | 298 | py | class Matrix(object):
def __init__(self, matrix_string):
self.matrix = [[int(n) for n in row.split()] for row in matrix_string.split("\n")]
def row(self, index):
return self.matrix[index-1]
def column(self, index):
return [row[index-1] for row in self.matrix]
| [
"siddharthisaiah@gmail.com"
] | siddharthisaiah@gmail.com |
9b1c4cf2eb86462a040f6f3f3d50654cb43b7469 | df0849fb516ae123a8031f5830fe55b5341391df | /test/test_binaryreply.py | abf58df752c5c35f5a6ed4981f49cee6659c3cce | [
"Apache-2.0"
] | permissive | duncanmcbryde/zaber.serial | e5380eafcb0ca7ab8817118a28999edaf06f8265 | 3edeec2703f6266fe13d300b61c46782171e1287 | refs/heads/master | 2016-08-11T09:44:37.235121 | 2015-12-01T13:29:40 | 2015-12-01T13:29:40 | 47,191,136 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,527 | py | import pytest
from zaber.serial import BinaryReply
def test_init():
br = BinaryReply([1, 56, 10502])
assert(br.device_number == 1)
assert(br.command_number == 56)
assert(br.data == 10502)
def test_init_with_message_id():
br = BinaryReply([2, 44, 21231, 12])
assert(br.device_number == 2)
assert(br.command_number == 44)
assert(br.data == 21231)
assert(br.message_id == 12)
def test_message_id_is_None():
br = BinaryReply([3, 32, 0])
assert(br.message_id == None)
def test_parsing():
br = BinaryReply(b"\x01\xFF\x03\x00\x00\x00")
assert(br.device_number == 1)
assert(br.command_number == 0xFF == 255)
assert(br.data == 3)
def test_parsing_with_message_id():
br = BinaryReply(b"\x01\x02\x03\x04\x05\x06", message_id=True)
assert(br.device_number == 1)
assert(br.command_number == 2)
assert(br.data == 3 | (4 << 8) | (5 << 16) == 328707)
assert(br.message_id == 6)
def test_parsing_without_message_id():
br = BinaryReply(b"\x01\x02\x03\x04\x05\x06", message_id=False)
assert(br.device_number == 1)
assert(br.command_number == 2)
assert(br.data == 100992003 == 3 | (4 << 8) | (5 << 16) | (6 << 24) )
assert(br.message_id == None)
def test_dict_will_raise_typeerror():
br = BinaryReply([1, 2, 3])
br = BinaryReply(b"\x01\x02\x03\x04\x05\x06")
with pytest.raises(TypeError):
br = BinaryReply({
'device number': 1,
'command number': 2,
'data': 3}) # This should fail.
| [
"duncan.mcbryde@ttp.com"
] | duncan.mcbryde@ttp.com |
bc65a3921d29d115fa2d05902808f18552cb33e5 | 94efbd46bec43b07f29f8718b378834f28cfa18c | /env/Lib/site-packages/dotenv/__init__.py | 1867868f719e0edd17ad0cc144fa680c9e273bf4 | [
"Apache-2.0"
] | permissive | BiceCold/Citadel_of_Ricks | 2a9d1fc45fe36098dc61f2e00c55cedfd1dd22b7 | 72f1a447accc2c11d1fa1cbf3c3342913913e50e | refs/heads/master | 2021-06-15T17:52:35.999378 | 2019-06-15T18:29:55 | 2019-06-15T18:29:55 | 129,338,382 | 2 | 0 | Apache-2.0 | 2021-02-26T02:29:49 | 2018-04-13T02:45:19 | Python | UTF-8 | Python | false | false | 1,276 | py | from typing import Any, Optional
from .main import load_dotenv, get_key, set_key, unset_key, find_dotenv, dotenv_values
def load_ipython_extension(ipython):
# type: (Any) -> None
from .ipython import load_ipython_extension
load_ipython_extension(ipython)
def get_cli_string(path=None, action=None, key=None, value=None, quote=None):
# type: (Optional[str], Optional[str], Optional[str], Optional[str], Optional[str]) -> str
"""Returns a string suitable for running as a shell script.
Useful for converting a arguments passed to a fabric task
to be passed to a `local` or `run` command.
"""
command = ['dotenv']
if quote:
command.append('-q %s' % quote)
if path:
command.append('-f %s' % path)
if action:
command.append(action)
if key:
command.append(key)
if value:
if ' ' in value:
command.append('"%s"' % value)
else:
command.append(value)
return ' '.join(command).strip()
__all__ = ['get_cli_string',
'load_dotenv',
'dotenv_values',
'get_key',
'set_key',
'unset_key',
'find_dotenv',
'load_ipython_extension']
| [
"bice.jeremy@outlook.com"
] | bice.jeremy@outlook.com |
4e69526e2f22b9e6ead9e0673d893c9460e3b570 | fc1cc515a65e844705cc6262a70cd0a12ce1d1df | /math/0x00-linear_algebra/2-size_me_please.py | f9800d2c3bc375d8df09bd35e4d0cfd25402da82 | [] | no_license | yulyzulu/holbertonschool-machine_learning | 4f379a4d58da201e8125bd8d74e3c9a4dfcf8a57 | d078d9c1c5bd96730a08d52e4520eb380467fb48 | refs/heads/master | 2022-12-26T12:01:25.345332 | 2020-10-03T03:19:05 | 2020-10-03T03:19:05 | 279,392,075 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 301 | py | #!/usr/bin/env python3
""" Module to execute function """
def matrix_shape(matrix):
"""Function that calculates the shape of a matrix"""
shape = []
shape.append(len(matrix))
while type(matrix[0]) == list:
matrix = matrix[0]
shape.append(len(matrix))
return shape
| [
"yulyzulu05@gmail.com"
] | yulyzulu05@gmail.com |
d13484b16678129c6aaeb00750fcd04de43e2ed3 | 0228a6aefd7dcedb16bb6baf2152bb893b0a7c4e | /externalapiproject/settings.py | 6441bbd7eac8a52a31de11e8614fec179ed1ce49 | [] | no_license | balaji2245/django_project_externalapi | 7cf7d950cbdfb7c396f194f5b2df4d7390a58e56 | 4fdecbfd7f2a6863c77ab9c98348d16f5a199f4c | refs/heads/master | 2023-08-30T09:58:25.551883 | 2021-11-15T19:45:21 | 2021-11-15T19:45:21 | 428,282,828 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,019 | py | """
Django settings for externalapiproject project.
Generated by 'django-admin startproject' using Django 3.2.9.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
import django_heroku
from pathlib import Path
# SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
print("im in settings=============================================================================")
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-=9x388zxl3h5a@9599i&gavvfz@fgd+g56*d&2%wnm@nb$3em-'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['iceandfireapi.herokuapp.com']
# ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'iceandfireapi',
'rest_framework'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'externalapiproject.urls'
# print(os.path.join(SETTINGS_PATH, 'templates'))
# print("++++++++++++++++++++++")
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [os.path.join(SETTINGS_PATH, 'templates')],
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'externalapiproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'd7gd2472l8f28r',
'USER': 'scqmagwzpgmmub',
'PASSWORD': '6992e89a514c6899930ee643c07021b6996b704e9fae06fdf9119ea838d25a2e',
'HOST': 'ec2-52-201-195-11.compute-1.amazonaws.com',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
django_heroku.settings(locals())
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
| [
"balajidavangavem@gmail.com"
] | balajidavangavem@gmail.com |
748bd141851012ae41c1d7935ee35c81843e1b35 | 22dc5935a022e23d053cca14357b5b0732d96a63 | /DataScie/tuts/pd_intro.py | 18b715277127112b19a636a33662be70d361bcb7 | [] | no_license | deaninous/playground | 3aa548db543e2e1620793dea15d1c934967c6976 | fe43d0e97a188b3f368114c0a295b34ded396760 | refs/heads/master | 2021-01-02T23:03:46.557197 | 2017-08-09T00:06:05 | 2017-08-09T00:06:05 | 99,456,332 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,261 | py | from pandas import Series, DataFrame
import numpy as np
stock = Series([4, 3, 8, 9])
#stock
#Out[12]:
#0 4
#1 3
#2 8
#3 9
#dtype: int64
# stock.values
# DataFrame, think csv
# pandas, think linear values
# numpy, think spreadsheets
data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
'year': [2000, 2001, 2002, 2001, 2002],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
frame = DataFrame(data)
#Arithmetic methods with fill values
#indexwise arithmetics
df1 = DataFrame(np.arange(25).reshape(5,5), columns=list('abcde'), index=list('abcde'))
df2 = DataFrame(np.arange(25, 50).reshape(5,5), columns=list('abcde'), index=list('abcde'))
#df2
#Out[12]:
# 0 1 2 3 4
#0 0 1 2 3 4
#1 5 6 7 8 9
#2 10 11 12 13 14
#3 15 16 17 18 19
#4 20 21 22 23 24
# =============================================================================
# df2.add(df1)
# Out[24]:
# 0 1 2 3 4 a b c d e
# 0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# 1 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# 2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# 3 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# 4 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# a NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# b NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# c NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# d NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# e NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# =============================================================================
#reason is we got 0 common indexes
# =============================================================================
# df2.add(df1,fill_value=0)
# =============================================================================
# Out[31]:
# a b c d e
# a 25 27 29 31 33
# b 35 37 39 41 43
# c 45 47 49 51 53
# d 55 57 59 61 63
# e 65 67 69 71 73
# =============================================================================
# =============================================================================
#Operations between DataFrame and Series
arr = np.arange(12.).reshape((3, 4))
# =============================================================================
# array([[ 0., 1., 2., 3.],
# [ 4., 5., 6., 7.],
# [ 8., 9., 10., 11.]])
# =============================================================================
#n [34]: arr-arr[0]
#Out[34]:
#array([[ 0., 0., 0., 0.],
# [ 4., 4., 4., 4.],
# [ 8., 8., 8., 8.]])
#<<-- broadcatstig
frame = DataFrame(np.arange(12.).reshape((4,3)), columns=list('bde'),
index=['Fox', 'Cnn', 'Abc', 'Hbo'])
series=frame.ix[0]
series2 = Series(range(3), index=['b', 'e', 'f'])
#frame
#Out[37]:
# b d e
#Fox 0.0 1.0 2.0
#Cnn 3.0 4.0 5.0
#Abc 6.0 7.0 8.0
#Hbo 9.0 10.0 11.0
#
#frame - series
#Out[41]:
# b d e
#Fox 0.0 0.0 0.0
#Cnn 3.0 3.0 3.0
#Abc 6.0 6.0 6.0
#Hbo 9.0 9.0 9.0
#
#n [44]: frame + series2
#Out[44]:
#Fox 0.0 NaN 3.0 NaN
#Cnn 3.0 NaN 6.0 NaN
#Abc 6.0 NaN 9.0 NaN
#Hbo 9.0 NaN 12.0 NaN
# =============================================================================
# To broadcst over columns instead use df methods && specify axis
# =============================================================================
#series3 = frame['d']
#
#series3
#Out[46]:
#Fox 1.0
#Cnn 4.0
#Abc 7.0
#Hbo 10.0
#Name: d, dtype: float64
#
#frame.sub(series3, axis=0)
#Out[47]:
# b d e
#Fox -1.0 0.0 1.0
#Cnn -1.0 0.0 1.0
#Abc -1.0 0.0 1.0
#Hbo -1.0 0.0 1.0
# =============================================================================
# #Function application and mapping
# =============================================================================
frame = DataFrame(np.random.randn(9, 8), columns=list('abcdefgh'),
index= ['New York', 'Indiana', 'Alabama', 'Georgia',
'Washington', 'New Jersey', 'Texsas','Test', 'Lost'])
#frame
#Out[53]:
# a b c d e f \
#New York -0.661570 -0.895319 -1.402747 -1.648802 -0.632552 0.909815
#Indiana -0.453228 -1.697909 -0.765338 0.076564 -0.119203 0.018256
#Alabama -1.453918 0.448392 0.539369 -0.000963 0.444399 -1.099213
#Georgia -0.175848 -0.882784 -0.202698 -2.281018 1.394478 0.647207
#Washington -0.255284 -0.632032 -0.069683 -1.595015 -0.147538 0.984192
#New Jersey 0.117526 0.334670 -1.223019 1.196941 1.395554 0.607997
#Texsas -0.499998 1.974074 1.956290 0.186298 0.386323 1.620411
#Test -0.665570 0.863472 1.754348 0.552725 0.688808 -1.430362
#Lost -0.928069 -0.206633 -1.933997 -0.630691 -1.072648 0.140674
#
# g h
#New York 1.179303 -1.019131
#Indiana -1.758359 -0.720638
#Alabama 1.381439 0.606448
#Georgia -1.144267 -0.398720
#Washington 0.024846 -0.704271
#New Jersey -1.136606 -0.627800
#Texsas -0.733755 0.023039
#Test 1.072744 1.014227
#Lost -0.760507 0.662007
#rule is col x row and col maps to index
#np.abs(frame) --> obvious
#Apply a function to 1D arrays to each column or row with 'apply' keyword
#think reduce
f = lambda x: x.max() - x.min()
def f(x):
return Series([x.min(), x.max()], index=['min', 'max'])
frame.apply(f)
#
#frame.apply(f)
#Out[61]:
#a 2.985977
#b 3.085566
#c 2.187401
#d 3.863492
#e 3.479368
#f 3.815942
#g 3.701089
#h 4.230962
#dtype: float64
#for element wise, use applymap
format = lambda x: '%.2f' % x
frame.applymap(format)
obj = Series(range(4), index=['d', 'a', 'b', 'c'])
# obj.sort_index()
# Out[3]:
# a 1
# b 2
# c 3
# d 0
# dtype: int64
# With a DataFrame, you can sort by index on either axis:
frame = DataFrame(np.arange(8).reshape((2, 4)), index=['three', 'one'],
columns=['d', 'a', 'b', 'c'])
# frame.sort_index()
# Out[5]:
# d a b c
# one 4 5 6 7
# three 0 1 2 3
# frame.sort_index(axis=1)
# Out[8]:
# a b c d
# three 1 2 3 0
# one 5 6MM 7 4
# Summarizing and Computing Descriptive Statistics
# Correlation and Covariance
import pandas_datareader.data as web
f = web.get_quote_google('AAPL')
c = web.get_data_yahoo('AAPL')
| [
"ouedinous20@gmail.com"
] | ouedinous20@gmail.com |
acda56ee78a8132344cc053561886c569a3f64fd | 61fa09e50752022ee57553f1af4dd84b201b4aff | /0x00-python-hello_world/6-concat.py | 7c492b9d7fa2f0c5c7c0cfa14012dcdd748e2c0c | [] | no_license | ellio-hub/holbertonschool-higher_level_programming | 184880bbb99c59d1d64d8f650d4addbec41321db | 96ddcd43889b9df5e8497669e14ef85e9494cbb0 | refs/heads/master | 2023-06-18T20:22:57.871905 | 2021-07-14T14:08:20 | 2021-07-14T14:08:20 | 270,609,342 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 116 | py | #!/usr/bin/python3
str1 = "Holberton"
str2 = "School"
str1 = str1 + ' ' + str2
print('Welcome to {}!'.format(str1))
| [
"1421@holbertonschool.com"
] | 1421@holbertonschool.com |
eacef7a09f8311f33624a9f5acb965d5ec877336 | 7d8022661a756f77f715ee4d099fb17cb9da671a | /engine/data_loader.py | 6e92e9d69aff6df248ddbe721e11db9904459073 | [] | no_license | lxj0276/Quant-Util | a7d70d88fc47eb16a08149faefa7b128c01c670e | 2706ecba72a293ee01105ad22508a8d6b20e1394 | refs/heads/master | 2020-04-25T13:40:36.700892 | 2018-10-15T04:35:54 | 2018-10-15T04:35:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,979 | py | import os
from collections import OrderedDict
import pandas as pd
from engine.cons import *
from engine.utils import get_calendar
from feature.time import TimeRange
from mongoapi.get_data import get_day_trade_data
from redis_cache.rediscache import cache_it_pickle
class pricing_data_loader:
def __init__(self, load_path=PRICING_DATA_PATH):
self.load_path = load_path
def load_data(self, instruments, feature, start_time, end_time):
pass
#
# @cache_it_pickle()
# def load_single_data(self, instrument, start_time, end_time, feature='close'):
# df = pd.read_csv(os.path.join(self.load_path, instrument + '.csv'))[['date', feature, 'rate']]
# df = df.rename(columns={feature: PRICE})
# # df[PRICE]=df[PRICE]/df['rate']
# del df['rate']
# carlender = get_calendar()
#
# df = df.set_index('date')
# df_full = df.reindex(carlender).fillna(method='ffill')
#
# pricing_data = df_full[(df_full.index >= start_time) & (df_full.index <= end_time)].to_dict()[PRICE]
# df = df.reindex(df_full.index)
# on_trading = (~df[(df.index >= start_time) & (df.index <= end_time)].isnull()).astype(int).to_dict()[PRICE]
# return OrderedDict(pricing_data), OrderedDict(on_trading)
@cache_it_pickle()
def load_single_data(self, instrument, start_time, end_time, feature='close'):
trade_calendar = get_calendar(start_time, end_time)
data = get_day_trade_data([instrument],
start_time,
end_time,
[feature],
return_df=True)[['date',feature]].set_index('date')
data=data.reindex(trade_calendar)
pricing_data = data.fillna(method='ffill').to_dict()[feature]
on_trading = (~data.isnull()).astype(int).to_dict()[feature]
return OrderedDict(pricing_data), OrderedDict(on_trading)
| [
"zhangzc@pku.edu.cn"
] | zhangzc@pku.edu.cn |
66c913bf07d18f0b0788b67fdd65aaa861d80416 | 771856a4f24b8a4ff0cb627a316e825f6364db5f | /04_conditional_statements/ifelifelse.py | c977dd4c830f8f79818f21cc6daf6c9f7f6ec492 | [] | no_license | rafaelgramoschi/pythontuts | f3cd8df91cdfda40910c3946f9018cdf29659b4a | b7b3145658e9b38f30d7579b0b031e4abdc916ac | refs/heads/main | 2023-02-06T11:47:36.488737 | 2021-01-02T15:32:42 | 2021-01-02T15:32:42 | 326,212,033 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 461 | py | """
if-elif-else
"""
zero = 0;
one = 1;
if one > zero:
#Indentation is important!
#it makes python understand that if something happens
#it must follow the indented code,
print("one is greater than 0")
elif one == zero:
print("number are the same")
else
print("one is less than 0")
str = 'str'
if str is 'str':
print("str is 'str'")
if 1: # if True: (always executed)
print("This is printed if str is 'str'")
else:
print("str is not 'str'")
| [
"gramoschi.rafael@gmail.com"
] | gramoschi.rafael@gmail.com |
a1f30bad67e95432f8ac7e765fea90b9672f1617 | af314ff8e16565cc826e2cf747605da645c631c9 | /Project/urls.py | e86b975ad118c8a2847ef0a280d5899607ac158d | [] | no_license | cutlerwater/django_blog | 8bbcc7a5b51109650dad80eebb32a4ae7c85c690 | 6c7e71f82af59e9bd28c5315428457d678d62aa5 | refs/heads/main | 2023-08-21T17:57:53.783259 | 2021-09-30T20:51:51 | 2021-09-30T20:51:51 | 411,458,990 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 792 | py | """Project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('App.urls'))
]
| [
"cutlerwater2@live.com"
] | cutlerwater2@live.com |
f4d4ad5fffdbd3200bfabf4936fb900e12376a50 | ec2075fc61f622a0ddf11744d67222d10d7582ea | /pickle.py | f918870478bc477f88030a65c7a293ee31f3a522 | [] | no_license | Aravinthanucep/Python-program | f3b2f4df8b6f53d049db062852af7a5ddb435546 | 3502fdf2755ade6c735f8478e5c31730688f68a7 | refs/heads/master | 2021-05-08T14:56:25.438546 | 2018-02-11T17:08:19 | 2018-02-11T17:08:19 | 120,101,252 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 608 | py | #-------------------------------------------------------------------------------
# Name: module2
# Purpose:
#
# Author: Deepa
#
# Created: 19/01/2018
# Copyright: (c) Deepa 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
try:
import cPickle as pickle
except:
import pickle
import pprint
data = [ { 'a':'A', 'b':2, 'c':3.0 } ]
print ('DATA:',)
pprint.pprint(data)
data_string = pickle.dumps(data)
print ('PICKLE:', data_string)
if __name__ == '__main__':
main()
| [
"noreply@github.com"
] | noreply@github.com |
11a9a10ba5f3266f862981818c7a0334b636af87 | 294dd0d3534d95479348d0fc7c03f1dd0f4c1e42 | /RemitaBillingService/EncryptionConfig.py | 8fd57202a8bcc2dabed8e0b5ed1ce406915628e0 | [] | no_license | RemitaNet/billing-gateway-sdk-python | 7827c9a16fd81ce48ca0206c350aba762c2a5cfe | d051f24cdce99b5f3c4acf96d19fcbd5d3da2aa8 | refs/heads/master | 2023-02-22T23:23:53.064169 | 2023-02-20T20:30:28 | 2023-02-20T20:30:28 | 207,595,239 | 4 | 1 | null | 2023-09-12T13:49:35 | 2019-09-10T15:25:56 | Python | UTF-8 | Python | false | false | 1,320 | py | import hashlib
from Responses.BaseResponse import BaseResponse
class EncryptionConfig(object):
empty_credential_msg: str
empty_credential_code: str
def sha512(input):
hashed_input = hashlib.sha512(input.encode('utf-8'))
hex_dig = hashed_input.hexdigest()
return hex_dig
def credential_available(self, credentials):
if not credentials.public_key:
self.empty_credential_msg = "Public key not provided"
self.empty_credential_data = "No available data"
self.empty_credential_code = "011"
return False
elif not credentials.secret_key:
self.empty_credential_msg = "Secret key not provided"
self.empty_credential_data = "No available data"
self.empty_credential_code = "012"
return False
elif not credentials.environment:
credentials.environment = "DEMO"
return True
else:
return True
def throw_exception(self, code, message):
response_data = []
response = '{"responseCode": "' + code + \
'", "responseData": "' + str(response_data) + \
'", "responseMsg": "' + str(message) + '"}'
base_response = BaseResponse(response)
return base_response
| [
"ilesanmi@Systemspecs.com.ng"
] | ilesanmi@Systemspecs.com.ng |
7903bebf11136419ad1380585a837c763047ba50 | 16f9e5c65d309bb3d3f0da90bd2a3ffa6dfbb922 | /labs/lab3/mysiteS20/myapp/migrations/0004_auto_20200623_1522.py | 293c9fe8f3a20fcc0f30ae5b71d0a787257fff65 | [] | no_license | datqlam/internet-app-distributed-sys | e8ffaa8eeec0a808d07f8f3d3ba9095c0ae63189 | 3e5fe41282023b8678710d7805765b00cecb2b38 | refs/heads/master | 2022-12-10T16:29:45.596137 | 2020-08-20T21:08:22 | 2020-08-20T21:08:22 | 268,125,378 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 494 | py | # Generated by Django 3.0.7 on 2020-06-23 19:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0003_auto_20200619_1833'),
]
operations = [
migrations.RemoveField(
model_name='order',
name='course',
),
migrations.AddField(
model_name='order',
name='courses',
field=models.ManyToManyField(to='myapp.Course'),
),
]
| [
"lqdat2n@gmail.com"
] | lqdat2n@gmail.com |
91c02459d4b5116db0e911aeeb9585e3e2c177d5 | 0a7a2941602ceeb819fad3f222a7b3950452d304 | /zeus/controller/BusinessController.py | 4fbd01d8f9a720253ea74c7b4e089b8257d087fb | [
"Apache-2.0"
] | permissive | flyliufu/PythonDemo | 3b9ed3c74181ad7f46257655bba03c389d870eec | 9f31998a53e94b4036c6e96d80748945845b82b6 | refs/heads/master | 2022-04-26T10:54:42.543061 | 2022-03-11T07:51:29 | 2022-03-11T07:51:29 | 147,266,004 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,861 | py | from zeus.util.MsgUtil import MsgUtil
# 微信服务器推送消息是xml的,根据利用ElementTree来解析出的不同xml内容返回不同的回复信息,就实现了基本的自动回复功能了,也可以按照需求用其他的XML解析方法
import xml.etree.ElementTree as et
import logging
logger = logging.getLogger("django.request")
class BusinessController:
def auto_reply(self, body):
xml_data = et.fromstring(body)
msg_type = xml_data.find('MsgType').text
ToUserName = xml_data.find('ToUserName').text
FromUserName = xml_data.find('FromUserName').text
CreateTime = xml_data.find('CreateTime').text
# MsgId = xml_data.find('MsgId').text
reply_msg = MsgUtil(FromUserName, ToUserName)
content = "您好,欢迎来到Python学习!"
if msg_type == 'event': # 触发事件消息类型
event = xml_data.find('Event').text
eventKey = xml_data.find('EventKey').text
if event == 'subscribe': # 订阅事件
return reply_msg.send_text("终于等到你了!欢迎关注我们,未来我们一起成长!!!")
if event == 'unsubscribe': # 取消订阅事件
pass
if msg_type == 'text':
content = "文本已收到,谢谢"
elif msg_type == 'image':
content = "图片已收到,谢谢"
elif msg_type == 'voice':
content = "语音已收到,谢谢"
elif msg_type == 'video':
content = "视频已收到,谢谢"
elif msg_type == 'shortvideo':
content = "小视频已收到,谢谢"
elif msg_type == 'location':
content = "位置已收到,谢谢"
elif msg_type == 'link':
content = "链接已收到,谢谢"
return reply_msg.send_text(content)
| [
"flyliufu@sina.com"
] | flyliufu@sina.com |
672a4e70022ac965ccb9167e465218b4afb9d018 | 3efc0c578c5136d83eeab69dc3e5fd565de05c31 | /Assignment 3/P1_Baseline/p1/baseline.py | 5e4ea735ca9db4350f25a51ac22f38f53193240e | [] | no_license | Rshcaroline/UCSD-CSE256-Statistical-NLP | 34ccc690ec3e7f1e7e41a176a46350e8bddbeaf6 | 57d3f2081d7aa46d44b096669ca2d6c9e242c5c2 | refs/heads/master | 2023-04-01T14:27:20.390827 | 2019-12-13T06:36:07 | 2019-12-13T06:36:07 | 213,223,407 | 6 | 5 | null | 2023-03-25T00:11:32 | 2019-10-06T18:40:57 | JavaScript | UTF-8 | Python | false | false | 2,212 | py | '''
@Author:
@Date: 2019-11-01 19:48:16
@LastEditors: Shihan Ran
@LastEditTime: 2019-11-01 20:41:28
@Email: rshcaroline@gmail.com
@Software: VSCode
@License: Copyright(C), UCSD
@Description:
'''
import sys
from collections import defaultdict
import math
def read_counts(counts_file, word_tag, word_dict, uni_tag):
for l in counts_file:
line = l.strip().split(' ')
if line[1] == 'WORDTAG':
word_tag[(line[3], line[2])] = int(line[0])
word_dict.append(line[3])
elif line[1] == '1-GRAM':
uni_tag[(line[2])] = int(line[0])
def word_with_max_tagger(word_tag, word_dict, uni_tag, word_tag_max):
for word in word_dict:
max_tag = ''
max_val = 0.0
for tag in uni_tag:
if float(word_tag[(word, tag)]) / float(uni_tag[(tag)]) > max_val:
max_val = float(word_tag[(word, tag)]) / float(uni_tag[(tag)])
max_tag = tag
word_tag_max[(word)] = max_tag
def tag_gene(word_tag_max, out_f, dev_file):
for l in dev_file:
line = l.strip()
if line:
if line in word_tag_max:
out_f.write("%s %s\n" % (line, word_tag_max[(line)]))
else:
out_f.write("%s %s\n" % (line, word_tag_max[('_RARE_')]))
else:
out_f.write("\n")
def usage():
print ("""
python baseline.py [input_train_counts] [input_dev_file] > [output_file]
Read in counts file and dev file, produce tagging results.
""")
if __name__ == "__main__":
if len(sys.argv)!=3: # Expect exactly one argument: the training data file
usage()
sys.exit(2)
try:
counts_file = open(sys.argv[1], "r")
dev_file = open(sys.argv[2], 'r')
except IOError:
sys.stderr.write("ERROR: Cannot read inputfile %s.\n" % arg)
sys.exit(1)
word_tag, uni_tag, word_tag_max = defaultdict(int), defaultdict(int), defaultdict(int)
word_dict = []
read_counts(counts_file, word_tag, word_dict, uni_tag)
counts_file.close()
word_with_max_tagger(word_tag, word_dict, uni_tag, word_tag_max)
tag_gene(word_tag_max, sys.stdout, dev_file)
dev_file.close() | [
"RshCaroline@163.com"
] | RshCaroline@163.com |
7c38dda3f18562b3df7eecb78e86f2712b212369 | b5d72e68c3976766a7adfd1fa33f778a5268c84a | /Regex/ex1.py | 35628e29ded201a4fa05a049420dc39525ee29d4 | [] | no_license | LizinczykKarolina/Python | 4a2fb0e7fb130c86239b2666fb346bf35a8e655b | 7f4a3a9cba15fd2b4c7a104667461b3c49f8b757 | refs/heads/master | 2021-06-18T21:43:52.983557 | 2017-06-17T21:24:01 | 2017-06-17T21:24:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 328 | py | #1. Write a Python program to check that a string contains only a certain set of characters (in this case a-z, A-Z and 0-9).
import re
email_address = 'wieczorek.karolina1@o2.pl'
searchObj = re.search(r'[a-zA-Z0-9.]', email_address, re.M | re.I)
if searchObj:
print True
else:
print False
"sxdupa1" -match '^sx|1$' | [
"wieczorek.karolina1@o2.pl"
] | wieczorek.karolina1@o2.pl |
932a26342f04be288d55af4acb34cfe86fc29623 | 5258f5997ad9d2d75a5a0b950abb41b122c2a2d2 | /source/Mlos.Python/mlos/Optimizers/ExperimentDesigner/UtilityFunctionOptimizers/UtilityFunctionOptimizerFactory.py | 07c4da47b756ec8ca0b90a0a4dc3a21b35801b91 | [
"MIT",
"GPL-2.0-only"
] | permissive | amueller/MLOS | 49c0d361aeaffabce20d5b31ab44ad180d8dd13d | 8f79bfa27a6fd09c3e00187bae8d7177eaf55247 | refs/heads/main | 2023-07-07T23:46:03.028439 | 2021-06-14T20:09:09 | 2021-06-14T20:09:09 | 290,320,526 | 4 | 1 | MIT | 2020-11-06T01:12:17 | 2020-08-25T20:49:13 | Python | UTF-8 | Python | false | false | 2,789 | py | #
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#
from mlos.Optimizers.ExperimentDesigner.UtilityFunctions.UtilityFunction import UtilityFunction
from mlos.Optimizers.ExperimentDesigner.UtilityFunctionOptimizers.GlowWormSwarmOptimizer import GlowWormSwarmOptimizer, glow_worm_swarm_optimizer_config_store
from mlos.Optimizers.ExperimentDesigner.UtilityFunctionOptimizers.RandomNearIncumbentOptimizer import RandomNearIncumbentOptimizer,\
random_near_incumbent_optimizer_config_store
from mlos.Optimizers.ExperimentDesigner.UtilityFunctionOptimizers.RandomSearchOptimizer import RandomSearchOptimizer, random_search_optimizer_config_store
from mlos.Optimizers.OptimizationProblem import OptimizationProblem
from mlos.Optimizers.ParetoFrontier import ParetoFrontier
from mlos.Spaces import Point
class UtilityFunctionOptimizerFactory:
"""Creates specialized instances of the abstract base class UtilityFunctionOptimzier."""
@classmethod
def create_utility_function_optimizer(
cls,
utility_function: UtilityFunction,
optimizer_type_name: str,
optimizer_config: Point,
optimization_problem: OptimizationProblem,
pareto_frontier: ParetoFrontier = None,
logger=None
):
if optimizer_type_name == RandomSearchOptimizer.__name__:
assert optimizer_config in random_search_optimizer_config_store.parameter_space
return RandomSearchOptimizer(
optimizer_config=optimizer_config,
optimization_problem=optimization_problem,
utility_function=utility_function,
logger=logger
)
if optimizer_type_name == GlowWormSwarmOptimizer.__name__:
assert optimizer_config in glow_worm_swarm_optimizer_config_store.parameter_space
return GlowWormSwarmOptimizer(
optimizer_config=optimizer_config,
optimization_problem=optimization_problem,
utility_function=utility_function,
logger=logger
)
if optimizer_type_name == RandomNearIncumbentOptimizer.__name__:
assert optimizer_config in random_near_incumbent_optimizer_config_store.parameter_space
assert pareto_frontier is not None
return RandomNearIncumbentOptimizer(
optimizer_config=optimizer_config,
optimization_problem=optimization_problem,
utility_function=utility_function,
pareto_frontier=pareto_frontier,
logger=logger
)
raise RuntimeError(f"Unsupported UtilityFunctionOptimizerType: {optimizer_type_name}")
| [
"noreply@github.com"
] | noreply@github.com |
6eeb30afedb9faf5956630200d67199cef30815d | 2a4a17a67b9069c19396c0f8eabc8b7c4b6ff703 | /BGP3D/Chapter11/WorldClass_00.py | 2cd366287c64b1790280d87dd425c04951cc0271 | [] | no_license | kaz101/panda-book | 0fa273cc2df5849507ecc949b4dde626241ffa5e | 859a759c769d9c2db0d11140b0d04506611c2b7b | refs/heads/master | 2022-12-19T09:36:05.794731 | 2020-09-16T19:04:10 | 2020-09-16T19:04:10 | 295,784,057 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,569 | py | ''' World Class
This class is the launching point for the game.
This is the file that needs to run to start the game,
and this class creates all the pieces of the game.
'''
import direct.directbase.DirectStart
from direct.filter.CommonFilters import CommonFilters
from HUDClass_00 import HUD
from RaceClass_00 import Race
from InputManagerClass_00 import InputManager
from MenuClass_00 import Menu
class World:
def __init__(self):
base.disableMouse()
# Turns off the default mouse-camera controls in Panda3D.
base.setBackgroundColor(0, 0, 0)
# Sets the background to black.
self.inputManager = InputManager()
# Creates an InputManager to handle all of the user input in the game.
#taskMgr.doMethodLater(10, self.debugTask, "Debug Task")
# Tells the debugTask to run once every ten seconds. The debug task is a good
# place to put various data print outs about the game to help with debugging.
self.filters = CommonFilters(base.win, base.cam)
filterok = self.filters.setBloom(blend=(0,0,0,1),
desat=-0.5, intensity=3.0, size=2)
render.setShaderAuto()
# Turns on Panda3D's automatic shader generation.
self.menuGraphics = loader.loadModel(
"../Models/MenuGraphics.egg")
# Loads the egg that contains all the menu graphics.
self.fonts = {
"silver" : loader.loadFont("../Fonts/LuconSilver.egg"),
"blue" : loader.loadFont("../Fonts/LuconBlue.egg"),
"orange" : loader.loadFont("../Fonts/LuconOrange.egg")}
# Loads the three custom fonts our game will use.
hud = HUD(self.fonts)
# Creates the HUD.
self.race = Race(self.inputManager, hud)
self.race.createDemoRace()
# creates an instance of the race class and tells it to
# start a demo race.
self.createStartMenu()
# creates the start menu.
def createStartMenu(self):
menu = Menu(self.menuGraphics, self.fonts, self.inputManager)
menu.initMenu([0,None,
["New Game", "Quit Game"],
[[self.race.createRace, self.createReadyDialogue],
[base.userExit]],
[[None,None],[None]]])
def createReadyDialogue(self):
menu = Menu(self.menuGraphics, self.fonts, self.inputManager)
menu.initMenu([3,"Are you ready?",
["Yes","Exit"],
[[self.race.startRace],[self.race.createDemoRace]],
[[3],[None]]])
def debugTask(self, task):
print(taskMgr)
# prints all of the tasks in the task manager.
return task.again
# debugTask: Runs once every ten seconds to print out reports on the games status.
w = World()
run() | [
"kaz101130@gmail.com"
] | kaz101130@gmail.com |
6e954ce6187d1273920eca965ab0db30375857bf | 60f88b58500abed3e01b67dd519506b6e0e6e491 | /PasswordKeeper/PasswordKeeper/PasswordKeeper/wsgi.py | d6dbb1e0e6e4378a0fab8d42ab8ac4e44886db9a | [] | no_license | gouravgarg48/PasswordKeeper | 61008339982192a766c50597cdb28f88c41f5d4d | 439770004100ca32e9cb494fb177d5c642906565 | refs/heads/master | 2022-12-09T08:15:38.592805 | 2020-08-25T13:21:28 | 2020-08-25T13:21:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 405 | py | """
WSGI config for PasswordKeeper project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PasswordKeeper.settings')
application = get_wsgi_application()
| [
"gauravgarg4000@gmail.com"
] | gauravgarg4000@gmail.com |
cf2b8cbadeba4fa6168e63817f67c1570428e5b9 | 0ab04927cda34b384044d5d827a0043a5db0105d | /projects/data science/college_admission_poly.py | 0c7b806c3e7c229db7fb0ac731bdd607299acce1 | [] | no_license | anishd513/projects | 49b6a03b5d60db71dde0bdb3a9c99d37e3afa752 | 6c85b7c7e2b9ed6b71e8244204ec355bb26edbd9 | refs/heads/main | 2023-06-08T23:14:32.861369 | 2021-06-29T15:20:28 | 2021-06-29T15:20:28 | 305,082,217 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 803 | py | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 16 20:34:45 2020
@author: Admin
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
dataset=pd.read_csv("Admission_Predict.csv")
x=dataset.iloc[:,1:-1].values
y=dataset.iloc[:,-1:].values
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=1,test_size=0.2)
from sklearn.linear_model import LinearRegression
lin_reg=LinearRegression()
lin_reg.fit(x,y)
from sklearn.preprocessing import PolynomialFeatures
poly=PolynomialFeatures(degree=4)
poly.fit_transform(x_train)
y_pred=lin_reg.predict(x_test)
#print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))
cf_pol=np.sum(abs((y_test-y_pred)))
print(cf_pol)
| [
"noreply@github.com"
] | noreply@github.com |
bb4e4bd748283b521eb43cbfc3512f14cc5a6fd9 | 8d39bfe6bbe1f30077b69d92745eac067d4619c4 | /parserInvoke-Mimikatz.py | f42deb1e197310e3173d734c97d8181d347b75b9 | [] | no_license | Ne0nd0g/scripts | f987f416070dfd60425ce83598cc02ece191bc81 | 5b8f989c88860bbe663a81c489c3baff82b81ee9 | refs/heads/master | 2021-01-17T12:21:56.836062 | 2018-12-07T16:41:01 | 2018-12-07T16:41:01 | 30,088,779 | 20 | 11 | null | null | null | null | UTF-8 | Python | false | false | 5,337 | py | #!/usr/bin/python
#!/usr/bin/env python
"""Parse files generated by piped output from Invoke-Mimikatz.ps1"""
import logging
import argparse
import sys
import os
import readline
#################################################
# Variables #
#################################################
__author__ = "Russel Van Tuyl"
__license__ = "GPL"
__version__ = "0.1"
__maintainer__ = "Russel Van Tuyl"
__email__ = "Russel.VanTuyl@gmail.com"
__status__ = "Development"
logging.basicConfig(stream=sys.stdout, format='%(asctime)s\t%(levelname)s\t%(message)s',
datefmt='%Y-%m-%d %I:%M:%S %p', level=logging.DEBUG) # Log to STDOUT
script_root = os.path.dirname(os.path.realpath(__file__))
readline.parse_and_bind('tab: complete')
readline.set_completer_delims('\t')
#################################################
# COLORS #
#################################################
note = "\033[0;0;33m-\033[0m"
warn = "\033[0;0;31m!\033[0m"
info = "\033[0;0;36mi\033[0m"
question = "\033[0;0;37m?\033[0m"
parser = argparse.ArgumentParser()
parser.add_argument('-F', '--file', type=argparse.FileType('r'), help="Mimikatz output file")
parser.add_argument('-D', '--directory', help="Directory containing Mimikatz output files")
# parser.add_argument('-O', '--output', help="File to save username and password list")
parser.add_argument('-v', '--verbose', action='store_true', default=False, help="Verbose Output")
args = parser.parse_args()
def parse_file(f):
"""Parse a text file for hashes"""
users = {}
# users = {SID{username: <username>, domain: <domain>, LM: <LM>, NTLM:<NTLM>}}
username = None
domain = None
SID = None
print "["+note+"]Parsing " + f
mimikatz_file = open(f, "r")
mimikatz_file_data = mimikatz_file.readlines()
for line in mimikatz_file_data:
# print line
if line.startswith('User Name : '):
# print "["+info+"]Found User: " + line[20:]
if line.endswith("$\r\n") or line.endswith('LOCAL SERVICE\r\n') or line.endswith('(null)\r\n'): # Filter out Machine accounts
username = None
domain = None
SID = None
else:
username = line[20:].rstrip('\r\n')
if line.startswith('Domain : ') and username is not None:
# print "["+info+"]Found Domain: " + line[20:]
if line.endswith('NT AUTHORITY\r\n'):
username = None
domain = None
SID = None
else:
domain = line[20:].rstrip('\r\n')
if line.startswith('SID : ') and username is not None:
# print "["+info+"]Found SID: " + line[20:]
SID = line[20:].rstrip('\r\n')
if SID not in users:
if args.verbose:
print "["+info+"]Found User: " + domain + "\\" + username
users[SID] = {'username': username, 'domain': domain}
if line.startswith(' * LM : ') and username is not None:
if args.verbose and 'LM' not in users[SID].keys():
print "\t["+info+"]LM HASH: " + line[15:]
users[SID]['LM'] = line[15:].rstrip('\r\n')
if line.startswith(' * NTLM : ') and username is not None:
if args.verbose and 'NTLM' not in users[SID].keys():
print "\t["+info+"]NTLM Hash: " + line[15:]
users[SID]['NTLM'] = line[15:].rstrip('\r\n')
if line.startswith(' * Password : ') and username is not None:
if 'password' not in users[SID].keys():
if args.verbose and 'password' not in users[SID].keys():
print "\t["+info+"]Password: " + line[15:]
# print "\t["+note+"]Creds: " + domain + "\\" + username + ":" + line[15:]
users[SID]['password'] = line[15:].rstrip('\r\n')
# raw_input("Press Enter")
if args.file:
print_user_pass(users)
elif args.directory:
return users
def parse_directory():
users = {}
files = None
if os.path.isdir(os.path.expanduser(args.directory)):
files = os.listdir(args.directory)
if files is not None:
for f in files:
temp = parse_file(os.path.join(os.path.expanduser(args.directory), f))
users.update(temp)
print_user_pass(users)
def print_user_pass(users):
"""Print recovered user accounts and credentials to the screen"""
for u in users:
if 'password' in users[u].keys():
if len(users[u]['password']) < 100: # Use this to exclude Kerberos data
print "["+warn+"]" + users[u]['domain'] + "\\" + users[u]['username'] + ":" + users[u]['password']
if __name__ == '__main__':
try:
if args.file:
creds = parse_file(args.file.name)
elif args.directory:
parse_directory()
else:
print "["+warn+"]No arguments provided!"
print "["+warn+"]Try: python " + __file__ + " --help"
except KeyboardInterrupt:
print "\n["+warn+"]User Interrupt! Quitting...."
except:
print "\n["+warn+"]Please report this error to " + __maintainer__ + " by email at: " + __email__
raise | [
"rcvt@sses.net"
] | rcvt@sses.net |
4b90e720e1c60a9af54132d8db1f4f2a10f0e5d0 | 5aa3fd7dbad807c12fdecf9504e9a1580ab24768 | /ctopy.py | e465eb04bba5b9be97183b7fb950969455d7eee9 | [
"BSD-3-Clause"
] | permissive | sunnybesunny/CtoPy_Gillespie_Brute | 3ca2030943c7a1bd58af3a45f67bb9dba8e44e6a | 8d2e59d5893502cf09d8d963d97928ea56c996c0 | refs/heads/master | 2021-01-10T03:12:39.127213 | 2018-05-13T00:26:39 | 2018-05-13T00:26:39 | 55,079,548 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 62,780 | py | #!/usr/bin/env python
"""
ctopy -- a quick and dirty C-to-Python translator.
Libraries not mapped that theoretically could be: curses.panel, dbm,
md5, popen2, pty, resource, sha, subprocess, syslog, time. Some of these
would need more elaborate machinery for method translation.
Python library bindings are as of 2.6a0.
"""
import sys, re
version=0.1
stringify = []
printflike = ["printf", "sprintf", "vfprintf",
"printw", "mvprintw", "wprintw", "mvwprintw"]
shorthands = {
'id' : r"[a-zA-Z_][a-zA-Z0-9._]*",
'exp' : r"[a-zA-Z0-9._\-+\*/]+",
'type' : r"\bvoid\b|\bint\b|\bbool\b|\bchar\b|\bshort\b|\bdouble\b|\blong\b|\bfloat\b|\btime_t\b|\bFILE\b|bWINDOW\b",
'class' : r"\b__dummyclass__\b",
'ind' : r"(\n[ \t]*)", # Whitespace at start of line
'eol' : r"[ \t]*(?=\n|\Z)", # Whitespace to end of line or comment
'arg' : r"([^,]+),\s*", # initial or medial argument
'farg' : r"([^)]+)", # final argument
}
# C functions and constants to be mapped into Python standard library bindings.
funmappings = (
# File object methods (from C stdlib).
(r"\bfclose\(%(farg)s\)", r"\1.close()", None),
(r"\bfflush\(%(farg)s\)", r"\1.flush()", None),
(r"\bfileno\(%(farg)s\)", r"\1.fileno()", None),
(r"\bfprintf\(%(arg)s\)", r"\1.write()", None),
(r"\bfseek\(%(arg)s", r"\1.seek(", None),
(r"\bftell\(%(farg)s\)", r"\1.tell()", None),
(r"\bftruncate\(%(arg)s", r"\1.truncate(", None),
# Python atexit library
(r"\batexit\(", r"atexit.register(", "atexit"),
# Python crypt library
(r"\bcrypt\(", r"crypt.crypt(", "crypt"),
# Curses library. Below are all function calls listed in the
# ncurses(3) version 5.5 manual page in the order they are listed.
# The ones we don't translate have been left in as comments,
# pending future improvements. The largest category of things not
# translated is the wide-character support; it's possible there's
# an easy way to map this, but I don't have a need for it.
# Mappings marked "EXCEPTION" violate the convention that the C names
# of window methods begin with 'w'. Mappings marked "NONTRIVIAL"
# map a C entry point into a Python entry point with a different name,
# usually to throw away a length argument Python doesn't need or vecause
# the Python method handles a position as the first two arguments.
(r"\bCOLOR_PAIR\(", "curses.color_pair(", "curses"),
(r"\bPAIR_NUMBER\(", "curses.pair_number(", "curses"),
#_nc_tracebits curs_trace(3X)*
#_traceattr curs_trace(3X)*
#_traceattr2 curs_trace(3X)*
#_tracechar curs_trace(3X)*
#_tracechtype curs_trace(3X)*
#_tracechtype2 curs_trace(3X)*
#_tracedump curs_trace(3X)*
#_tracef curs_trace(3X)*
#_tracemouse curs_trace(3X)*
#add_wch curs_add_wch(3X)
#add_wchnstr curs_add_wchstr(3X)
#add_wchstr curs_add_wchstr(3X)
(r"\baddch\(", r"stdscr.addch(", "curses"),
#addchnstr curs_addchstr(3X)
#addchstr curs_addchstr(3X)
(r"\baddnstr\(", r"stdscr.addnstr(", "curses"),
#addnwstr curs_addwstr(3X)
(r"\baddstr\(", r"stdscr.addstr(", "curses"),
#addwstr curs_addwstr(3X)
#assume_default_colors default_colors(3X)*
#attr_get curs_attr(3X)
(r"\battr_off\(", r"stdscr.attrof(", r"curses"),
(r"\battr_on\(", r"stdscr.attron(", r"curses"),
(r"\battr_set\(", r"stdscr.attrset(", r"curses"),
(r"\battroff\(", r"stdscr.attrof(", r"curses"),
(r"\battron\(", r"stdscr.attron(", r"curses"),
(r"\battrset\(", r"stdscr.attrset(", r"curses"),
(r"\bbaudrate\(", r"curses.baudrate(", r"curses"),
(r"\bbeep\(", r"curses.beep(", r"curses"),
(r"\bbkgd\(", r"stdscr.bkgd(", r"curses"),
(r"\bbkgdset\(", r"stsdcr.bkgdset(", r"curses"),
#bkgrnd curs_bkgrnd(3X)
#bkgrndset curs_bkgrnd(3X)
(r"\bborder\(", r"stdscr.border(", r"curses"),
#border_set curs_border_set(3X)
(r"\bbox\(%(arg)s", r"\1.box(", r"curses"), # EXCEPTION
#box_set curs_border_set(3X)
(r"\bcan_change_color\(", r"curses.can_change_color(", r"curses"),
(r"\bcbreak\(", r"curses.cbreak(", r"curses"),
#chgat curs_attr(3X)
(r"\bclear\(", r"stdscr.clear(", r"curses"),
(r"\bclearok\(", r"stdscr.clearok(", r"curses"),
(r"\bclrtobot\(", r"stdscr.clrtobot(", r"curses"),
(r"\bclrtoeol\(", r"stdscr.clrtoeol(", r"curses"),
(r"\bcolor_content\(", r"curses.color_content(", r"curses"),
#color_set curs_attr(3X)
#copywin curs_overlay(3X)
(r"\bcurs_set\(", r"curses.curs_set(", r"curses"),
#curses_version curs_extend(3X)*
(r"\bdef_prog_mode\(", r"curses.def_prog_mode(", r"curses"),
(r"\bdef_shell_mode\(", r"curses.def_shell_mode(", r"curses"),
#define_key define_key(3X)*
#del_curterm curs_terminfo(3X)
(r"\bdelay_output\(", r"curses.delay_output(", r"curses"),
(r"\bdelch\(", r"stdscr.delch(", r"curses"),
(r"\bdeleteln\(\)", r"stdscr.deleteln()", r"curses"),
#delscreen curs_initscr(3X)
#delwin curs_window(3X)
(r"\bderwin\(%(arg)s", r"\1.derwin(", "curses"), # EXCEPTION
(r"\bdoupdate\(\)", r"curses.doupdate()", "curses"),
#dupwin curs_window(3X)
(r"\becho\(", r"curses.echo(", "curses"),
#echo_wchar curs_add_wch(3X)
(r"\bechochar\(", r"stdscr.echochar(", "curses"),
(r"\bendwin\(", r"curses.endwin(", "curses"),
(r"\berase\(", r"stdscr.erase(", "curses"),
#erasechar curs_termattrs(3X)
#erasewchar curs_termattrs(3X)
(r"\bfilter\(\)", r"curses.filter()", "curses"),
(r"\bflash\(\)", r"curses.flash()", "curses"),
(r"\bflushinp\(\)", r"curses.flushinp()", "curses"),
#get_wch curs_get_wch(3X)
#get_wstr curs_get_wstr(3X)
(r"\bgetbegyx\(%(arg)s%(arg)s%(farg)s\)", # EXCEPTION
r"(\2, \3) = \1.getbegyx()", "curses"),
(r"\bgetbkgd\(", r"\1.getbkgd(", "curses"), # EXCEPTION
#getbkgrnd curs_bkgrnd(3X)
#getcchar curs_getcchar(3X)
(r"\bgetch\(", r"stdscr.getch(", "curses"),
(r"\bgetmaxyx\(%(arg)s", r"\1.getmaxyx(", "curses"), # EXCEPTION
(r"\bgetmouse\(%(farg)s\)", r"\1 = curses.getmouse()", "curses"),
#getn_wstr curs_get_wstr(3X)
(r"\bgetnstr\(%(arg)s%(farg)s\)", # NONTRIVIAL
r"\1 = stdscr.getstr()", "curses"),
(r"\bgetparyx\(%(arg)s%(arg)s%(farg)s\)", # EXCEPTION
r"(\2, \3) = \1.getparyx()", "curses"),
(r"\bgetsyx\(%(arg)s%(farg)s\)", r"(\1, \2) = curses.getsyx()", "curses"),
(r"\bgetstr\(\)", r"stdscr.getstr()", "curses"),
(r"\bgetyx\(%(arg)s%(arg)s%(farg)s\)", #EXCEPTION
r"(\2, \3) = \1.getyx()", "curses"),
(r"\bgetwin\(", r"curses.getwin(", "curses"),
(r"\bhalfdelay\(", r"curses.halfdelay(", "curses"),
(r"\bhas_colors\(", r"curses.has_colors(", "curses"),
(r"\bhas_ic\(", r"curses.has_ic(", "curses"),
(r"\bhas_il\(", r"curses.has_il(", "curses"),
(r"\bhas_key\(", r"curses.has_key(", "curses"),
(r"\bhline\(", r"stdscr.hline(", "curses"),
#hline_set curs_border_set(3X)
(r"\bidcok\(%(arg)s", r"\1.idcok(", "curses"), # EXCEPTION
(r"\bidlok\(%(arg)s", r"\1.idlok(", "curses"), # EXCEPTION
(r"\bimmedok\(%(arg)s", r"\1.immedok(", "curses"), # EXCEPTION
# in_wch curs_in_wch(3X)
# in_wchnstr curs_in_wchstr(3X)
# in_wchstr curs_in_wchstr(3X)
(r"\binch\(", r"stdscr.inch(", "curses"),
#inchnstr curs_inchstr(3X)
#inchstr curs_inchstr(3X)
(r"\binit_color\(", r"curses.init_color(", "curses"),
(r"\binit_pair\(", r"curses.init_pair(", "curses"),
(r"\binitscr\(", r"curses.initscr(", "curses"),
(r"\binnstr\(%(arg)s", r"\1.instr(", "curses"), # NONTRIVIAL
#innwstr curs_inwstr(3X)
#ins_nwstr curs_ins_wstr(3X)
#ins_wch curs_ins_wch(3X)
#ins_wstr curs_ins_wstr(3X)
(r"\binsch\(", r"stdscr.insch(", "curses"),
(r"\binsdelln\(", r"stdscr.insdelln(", "curses"),
(r"\binsertln\(", r"stdscr.insertln(", "curses"),
(r"\binsnstr\(", r"stdscr.insnstr(", "curses"),
(r"\binsstr\(", r"stdscr.insstr(", "curses"),
(r"\binstr\(%(farg)s\)", r"\1 = stdscr.instr()", "curses"),
(r"\bintrflush\(\)", r"curses.intrflush()", "curses"),
#inwstr curs_inwstr(3X)
(r"\bis_linetouched\(%(arg)s", r"\1.is_linetouched(", "curses"),# EXCEPTION
(r"\bis_wintouched\(%(farg)s\)", r"\1.is_wintouched()", "curses"),# EXCEPTION
(r"\bisendwin\(\)", r"curses.isendwin()", "curses"),
#key_defined key_defined(3X)*
#key_name curs_util(3X)
#keybound keybound(3X)*
(r"\bkeyname\(", r"curses.keyname(", "curses"),
#keyok keyok(3X)*
(r"\bkeypad\(%(arg)s", r"\1.keypad(", "curses"), # EXCEPTION
(r"\bkillchar\(\)", r"curses.killchar()", "curses"),
#killwchar curs_termattrs(3X)
(r"\bleaveok\(%(arg)s", r"\1.leaveok(", "curses"), # EXCEPTION
(r"\blongname\(\)", r"curses.longname()", "curses"),
#mcprint curs_print(3X)*
(r"\bmeta\(", r"curses.meta(", "curses"),
#mouse_trafo curs_mouse(3X)*
(r"\bmouseinterval\(", r"curses.mouseinterval(", "curses"),
(r"\bmousemask\(", r"curses.mousemask(", "curses"),
(r"\bmove\(", r"stdscr.move(", "curses"),
#mvadd_wch curs_add_wch(3X)
#mvadd_wchnstr curs_add_wchstr(3X)
#mvadd_wchstr curs_add_wchstr(3X)
(r"\bmvaddch\(", r"stdscr.addch(", "curses"), # NONTRIVIAL
#mvaddchnstr curs_addchstr(3X)
#mvaddchstr curs_addchstr(3X)
(r"\bmvaddnstr\(", r"stdscr.addnstr(", "curses"), # NONTRIVIAL
#mvaddnwstr curs_addwstr(3X)
(r"\bmvaddstr\(", r"stdscr.addstr(", "curses"), # NONTRIVIAL
#mvaddwstr curs_addwstr(3X)
#mvchgat curs_attr(3X)
#mvcur curs_terminfo(3X)
(r"\bmvdelch\(", r"stdscr.delch(", "curses"), # NONTRIVIAL
(r"\bmvderwin\(%(arg)s", r"\1.derwin(", "curses"), # NONTRIVIAL,EXCEPTION
#mvget_wch curs_get_wch(3X)
#mvget_wstr curs_get_wstr(3X)
(r"\bmvgetch\(%(arg)s", r"stdscr.getch(", "curses"), # NONTRIVIAL
#mvgetn_wstr curs_get_wstr(3X)
(r"\bmvgetnstr\(%(arg)s%(arg)s%(arg)s%(farg)s\)", # NONTRIVIAL
r"\3 = stdscr.getstr(\1, \2)", "curses"),
(r"\bmvgetstr\(%(arg)s%(arg)s%(farg)s\)", # NONTRIVIAL
r"\3 = stdscr.getstr(\1, \2)", "curses"),
(r"\bmvhline\(", r"stdscr.hline(", "curses"), # NONTRIVIAL
#mvhline_set curs_border_set(3X)
#mvin_wch curs_in_wch(3X)
#mvin_wchnstr curs_in_wchstr(3X)
#mvin_wchstr curs_in_wchstr(3X)
(r"\bmvinch\(", r"stdscr.inch(", "curses"), # NONTRIVIAL
(r"\bmvinchnstr\(", r"stdscr.instr(", "curses"), # NONTRIVIAL
(r"\bmvinchstr\(", r"stdscr.instr(", "curses"), # NONTRIVIAL
(r"\bmvinnstr\(", r"stdscr.instr(", "curses"), # NONTRIVIAL
#mvinnwstr curs_inwstr(3X)
#mvins_nwstr curs_ins_wstr(3X)
#mvins_wch curs_ins_wch(3X)
#mvins_wstr curs_ins_wstr(3X)
(r"\bmvinsch\(", r"stdscr.insch(", "curses"), # NONTRIVIAL
(r"\bmvinsnstr\(", r"stdscr.instr(", "curses"), # NONTRIVIAL
(r"\bmvinsstr\(", r"stdscr.instr(", "curses"), # NONTRIVIAL
(r"\bmvinstr\(", r"stdscr.instr(", "curses"), # NONTRIVIAL
#mvwinwstr curs_inwstr(3X)
(r"\bmvprintw\(", r"stdscr.addstr(", "curses"), # NONTRIVIAL
# mvscanw curs_scanw(3X)
(r"\bmvvline\(", r"stdscr.vline(", "curses"), # NONTRIVIAL
#mvvline_set curs_border_set(3X)
#mvwadd_wch curs_add_wch(3X)
#mvwadd_wchnstr curs_add_wchstr(3X)
#mvwadd_wchstr curs_add_wchstr(3X)
(r"\bmvwaddch\(%(arg)s", r"\1.addch(", "curses"), # NONTRIVIAL
#mvwaddchnstr curs_addchstr(3X)
#mvwaddchstr curs_addchstr(3X)
(r"\bmvwaddnstr\(%(arg)s", r"\1.addnstr(", "curses"), # NONTRIVIAL
#mvwaddnwstr curs_addwstr(3X)
(r"\bmvwaddstr\(%(arg)s", r"\1.addstr(", "curses"), # NONTRIVIAL
#mvwaddwstr curs_addwstr(3X)
#mvwchgat curs_attr(3X)
(r"\bmvwdelch\(%(arg)s", r"\1.delch(", "curses"), # NONTRIVIAL
#mvwget_wch curs_get_wch(3X)
#mvwget_wstr curs_get_wstr(3X)
(r"\bmvwgetch\(%(arg)s", r"\1.getch(", "curses"), # NONTRIVIAL
#mvwgetn_wstr curs_get_wstr(3X)
(r"\bmvwgetnstr\(%(arg)s", r"\1.getstr(", "curses"), # NONTRIVIAL
(r"\bmvwgetstr\(%(arg)s", r"\1.getstr(", "curses"), # NONTRIVIAL
(r"\bmvwhline\(%(arg)s", r"\1.hline(", "curses"), # NONTRIVIAL
#mvwhline_set curs_border_set(3X)
(r"\bmvwin\(%(arg)s", r"\1.mvwin(", "curses"), # EXCEPTION
#mvwin_wch curs_in_wch(3X)
#mvwin_wchnstr curs_in_wchstr(3X)
#mvwin_wchstr curs_in_wchstr(3X)
(r"\bmvwinch\(%(arg)s", r"\1.inch(", "curses"), # NONTRIVIAL
#mvwinchnstr curs_inchstr(3X)
#mvwinchstr curs_inchstr(3X)
(r"\bmvwinnstr\(%(arg)s%(arg)s%(arg)s", # NONTRIVIAL
r"\3 = \1.instr(\1, \2", "curses"),
#mvwinnwstr curs_inwstr(3X)
#mvwins_nwstr curs_ins_wstr(3X)
#mvwins_wch curs_ins_wch(3X)
#mvwins_wstr curs_ins_wstr(3X)
(r"\bmvwinsch\(%(arg)s", r"\1.insch(", "curses"), # NONTRIVIAL
(r"\bmvwinsnstr\(%(arg)s", r"\1.insnstr(", "curses"), # NONTRIVIAL
(r"\bmvwinsstr\(%(arg)s", r"\1.insstr(", "curses"), # NONTRIVIAL
(r"\bmvwinstr\(%(arg)s", r"\1.instr(", "curses"), # NONTRIVIAL
#mvwinwstr curs_inwstr(3X)
(r"\bmvwprintw\(%(arg)s", r"\1.addstr(", "curses"), # NONTRIVIAL
#mvwscanw curs_scanw(3X)
(r"\bmvwvline\(%(arg)s", r"\1.vline(", "curses"), # NONTRIVIAL
#mvwvline_set curs_border_set(3X)
(r"\bnapms\(", r"curses.napms(", "curses"),
(r"\bnewpad\(", r"curses.newpad(", "curses"),
#newterm curs_initscr(3X)
(r"\bnewwin\(", r"curses.newwin(", "curses"),
(r"\bnl\(", r"curses.nl(", "curses"),
(r"\bnocbreak\(", r"curses.nocbreak(", "curses"),
(r"\bnodelay\(%(arg)s", r"\1.nodelay(", "curses"), # EXCEPTION
(r"\bnoecho\(", r"curses.noecho(", "curses"),
(r"\bnonl\(", r"curses.nonl(", "curses"),
(r"\bnoqiflush\(", r"curses.noqiflush(", "curses"),
(r"\bnoraw\(", r"curses.noraw(", "curses"),
(r"\bnotimeout\(%(arg)s", r"\1.notimeout(", "curses"),
(r"\boverlay\(%(arg)s", r"\1.overlay(", "curses"),
(r"\boverwrite\(%(arg)s", r"\1.overwrite(", "curses"),
(r"\bpair_content\(", r"curses.pair_content(", "curses"),
#pechochar curs_pad(3X)
#pnoutrefresh curs_pad(3X)
#prefresh curs_pad(3X)
(r"\bprintw\(%(arg)s", r"\1.addstr(", "curses"), # NONTRIVIAL
#putp curs_terminfo(3X)
#putwin curs_util(3X)
(r"\bqiflush\(", r"curses.qiflush(", "curses"),
(r"\braw\(", r"curses.raw(", "curses"),
(r"\bredrawwin\(%(farg)s\)", r"\1.redrawwin()", "curses"), # EXCEPTION
(r"\brefresh\(\)", r"stdscr.refresh()", "curses"),
(r"\breset_prog_mode\(", r"curses.reset_prog_mode(", "curses"),
(r"\breset_shell_mode\(", r"curses.reset_shell_mode(", "curses"),
#resetty curs_kernel(3X)
#resizeterm resizeterm(3X)*
#restartterm curs_terminfo(3X)
#ripoffline curs_kernel(3X)
#savetty curs_kernel(3X)
#scanw curs_scanw(3X)
#scr_dump curs_scr_dump(3X)
#scr_init curs_scr_dump(3X)
#scr_restore curs_scr_dump(3X)
#scr_set curs_scr_dump(3X)
(r"\bscrl\(", r"stdscr.scroll(", "curses"), # NONTRIVIAL
(r"\bscroll\(%(farg)s\)", r"\1.scroll(1)", "curses"), # NONTRIVIAL
(r"\bscrollok\(%(arg)s", r"\1.scrollok(", "curses"), # EXCEPTION
#set_curterm curs_terminfo(3X)
#set_term curs_initscr(3X)
#setcchar curs_getcchar(3X)
(r"\bsetscrreg\(", r"stdscr.setscrreg(", "curses"),
(r"\bsetsyx\(", r"curses.setsyx(", "curses"),
#setterm curs_terminfo(3X)
(r"\bsetupterm\(", r"curses.setupterm(", "curses"),
#slk_attr curs_slk(3X)*
#slk_attr_off curs_slk(3X)
#slk_attr_on curs_slk(3X)
#slk_attr_set curs_slk(3X)
#slk_attroff curs_slk(3X)
#slk_attron curs_slk(3X)
#slk_attrset curs_slk(3X)
#slk_clear curs_slk(3X)
#slk_color curs_slk(3X)
#slk_init curs_slk(3X)
#slk_label curs_slk(3X)
#slk_noutrefresh curs_slk(3X)
#slk_refresh curs_slk(3X)
#slk_restore curs_slk(3X)
#slk_set curs_slk(3X)
#slk_touch curs_slk(3X)
(r"\bstandend\(", r"stdscr.standend(", "curses"),
(r"\bstandout\(", r"stdscr.standout(", "curses"),
(r"\bstart_color\(", r"curses.start_color(", "curses"),
(r"\bsubpad\(%(arg)s", r"\1.subpad(", "curses"), # EXCEPTION
(r"\bsubwin\(%(arg)s", r"\1.subwin(", "curses"), # EXCEPTION
(r"\bsyncok\(%(arg)s", r"\1.syncok(", "curses"), # EXCEPTION
#term_attrs curs_termattrs(3X)
(r"\btermattrs\(", r"curses.termattrs(", "curses"),
(r"\btermname\(", r"curses.termname(", "curses"),
#tgetent curs_termcap(3X)
#tgetflag curs_termcap(3X)
#tgetnum curs_termcap(3X)
#tgetstr curs_termcap(3X)
#tgoto curs_termcap(3X)
(r"\btigetflag\(", r"curses.tigetflag(", "curses"),
(r"\btigetnum\(", r"curses.tigetnum(", "curses"),
(r"\btigetstr\(", r"curses.tigetstr(", "curses"),
(r"\btimeout\(", r"stdscr.timeout(", "curses"),
(r"\btouchline\(%(arg)s", r"\1.touchline(", "curses"), # EXCEPTION
(r"\btouchwin\(%(farg)s\)", r"\1.touchwin()", "curses"), # EXCEPTION
(r"\btparm\(", r"curses.tparm(", "curses"),
#tputs curs_termcap(3X)
#tputs curs_terminfo(3X)
#trace curs_trace(3X)*
(r"\btypeahead\(", r"curses.typeahead(", "curses"),
(r"\bunctrl\(", r"curses.unctrl(", "curses"),
#unget_wch curs_get_wch(3X)
(r"\bungetch\(", r"curses.ungetch(", "curses"),
(r"\bungetmouse\(%(arg)s", r"\1.ungetmouse(", "curses"), # False friend
(r"\buntouchwin\(%(farg)s\)", r"\1.untouchwin()", "curses"),
(r"\buse_default_colors\(", r"curses.use_default_colors(", "curses"),
(r"use_env\(", r"use_env(", "curses"),
#use_extended_names curs_extend(3X)*
#vid_attr curs_terminfo(3X)
#vid_puts curs_terminfo(3X)
#vidattr curs_terminfo(3X)
#vidputs curs_terminfo(3X)
(r"vline\(", "stdscr.vline(", "curses"),
#vline_set curs_border_set(3X)
#vw_printw curs_printw(3X)
#vw_scanw curs_scanw(3X)
#vwprintw curs_printw(3X)
#vwscanw curs_scanw(3X)
#wadd_wch curs_add_wch(3X)
#wadd_wchnstr curs_add_wchstr(3X)
#wadd_wchstr curs_add_wchstr(3X)
(r"\bwaddch\(%(arg)s", "\1.addch(", "curses"), # NONTRIVIAL
#waddchnstr curs_addchstr(3X)
#waddchstr curs_addchstr(3X)
(r"\bwaddnstr\(%(arg)s", "\1.addnstr(", "curses"), # NONTRIVIAL
#waddnwstr curs_addwstr(3X)
(r"\bwaddstr\(%(arg)s", "\1.addstr(", "curses"), # NONTRIVIAL
#waddwstr curs_addwstr(3X)
#wattr_get curs_attr(3X)
#wattr_off curs_attr(3X)
#wattr_on curs_attr(3X)
#wattr_set curs_attr(3X)
(r"\bwattroff\(%(arg)s", "\1.attroff(", "curses"), # NONTRIVIAL
(r"\bwattron\(%(arg)s", "\1.attron(", "curses"), # NONTRIVIAL
(r"\bwattrset\(%(arg)s", "\1.attrset(", "curses"), # NONTRIVIAL
(r"\bwbkgd\(%(arg)s", "\1.bkgd(", "curses"), # NONTRIVIAL
(r"\bwbkgdset\(%(arg)s", "\1.bkgdset(", "curses"), # NONTRIVIAL
#wbkgrnd curs_bkgrnd(3X)
#wbkgrndset curs_bkgrnd(3X)
(r"\bwborder\(%(arg)s", "\1.border(", "curses"), # NONTRIVIAL
#wborder_set curs_border_set(3X)
#wchgat curs_attr(3X)
(r"\bwclear\(%(farg)s\)", "\1.clear()", "curses"), # NONTRIVIAL
(r"\bwclrtobot\(%(farg)s\)", "\1.clrtobot()", "curses"), # NONTRIVIAL
(r"\bwclrtoeol\(%(farg)s\)", "\1.clrtoeol()", "curses"), # NONTRIVIAL
#wcolor_set curs_attr(3X)
#wcursyncup curs_window(3X)
(r"\bwdelch\(%(arg)s", "\1.delch(", "curses"), # NONTRIVIAL
(r"\bwdeleteln\(%(farg)s\)", "\1.deleteln()", "curses"), # NONTRIVIAL
#wecho_wchar curs_add_wch(3X)
(r"\bwechochar\(%(arg)s", "\1.echochar(", "curses"), # NONTRIVIAL
(r"\bwenclose\(%(arg)s", "\1.enclose(", "curses"), # NONTRIVIAL
(r"\bwerase\(%(farg)s\)", "\1.erase()", "curses"), # NONTRIVIAL
#wget_wch curs_get_wch(3X)
#wget_wstr curs_get_wstr(3X)
#wgetbkgrnd curs_bkgrnd(3X)
(r"\bwgetch\(%(farg)s\)", "\1.getch()", "curses"), # NONTRIVIAL
#wgetn_wstr curs_get_wstr(3X)
(r"\bwgetnstr\(%(arg)s", "\1.getstr(", "curses"), # NONTRIVIAL
(r"\bwgetstr\(%(arg)s", "\1.getstr(", "curses"), # NONTRIVIAL
(r"\bwhline\(%(arg)s", "\1.hline(", "curses"), # NONTRIVIAL
#whline_set curs_border_set(3X)
#win_wch curs_in_wch(3X)
#win_wchnstr curs_in_wchstr(3X)
#win_wchstr curs_in_wchstr(3X)
(r"\bwinch\(%(arg)s", "\1.inch(", "curses"), # NONTRIVIAL
#winchnstr curs_inchstr(3X)
#winchstr curs_inchstr(3X)
(r"\bwinnstr\(%(arg)s", "\1.instr(", "curses"), # NONTRIVIAL
#winnwstr curs_inwstr(3X)
#wins_nwstr curs_ins_wstr(3X)
#wins_wch curs_ins_wch(3X)
#wins_wstr curs_ins_wstr(3X)
(r"\bwinsch\(%(arg)s", "\1.insch(", "curses"), # NONTRIVIAL
(r"\bwinsdelln\(%(arg)s", "\1.insdelln(", "curses"), # NONTRIVIAL
(r"\bwinsertln\(%(farg)s\)", "\1.insertln()", "curses"), # NONTRIVIAL
(r"\bwinsnstr\(%(arg)s", "\1.insnstr(", "curses"), # NONTRIVIAL
(r"\binsstr\(%(arg)s", "\1.insstr(", "curses"), # NONTRIVIAL
(r"\bwinstr\(%(arg)s", "\1.instr(", "curses"), # NONTRIVIAL
#winwstr curs_inwstr(3X)
#wmouse_trafo curs_mouse(3X)*
(r"\bwmove\(%(arg)s", "\1.move(", "curses"), # NONTRIVIAL
(r"\bwnoutrefresh\(%(arg)s", "\1.noutrefresh(", "curses"), # NONTRIVIAL
(r"\bwprintw\(%(arg)s", "\1.addstr(", "curses"), # NONTRIVIAL
(r"\bwredrawln\(%(arg)s", "\1.redrawln(", "curses"), # NONTRIVIAL
(r"\bwrefresh\(%(arg)s", "\1.refresh(", "curses"), # NONTRIVIAL
(r"\bwresize\(%(arg)s", "\1.resize(", "curses"), # NONTRIVIAL
#wscanw curs_scanw(3X)
(r"\bwscrl\(%(arg)s", r"\1.scroll(", "curses"), # NINTRIVIAL
(r"\bwsetscrreg\(%(arg)s", "\1.setscrreg(", "curses"), # NONTRIVIAL
(r"\bwstandend\(%(arg)s", "\1.standend(", "curses"), # NONTRIVIAL
(r"\bwstandout\(%(arg)s", "\1.standout(", "curses"), # NONTRIVIAL
(r"\bwsyncdown\(%(farg)s\)", "\1.syncdown()", "curses"), # NONTRIVIAL
(r"\bwsyncup\(%(arg)s", "\1.syncup(", "curses"), # NONTRIVIAL
(r"\bwtimeout\(%(arg)s", "\1.timeout(", "curses"), # NONTRIVIAL
(r"\bwtouchln\(%(arg)s", "\1.touchln(", "curses"), # NONTRIVIAL
(r"\bwunctrl\(%(arg)s", r"\1.unctrl(", "curses"), # NONTRIVIAL
(r"\bwvline\(%(arg)s", r"\1.vline(", "curses"), # NONTRIVIAL
#wvline_set curs_border_set(3X)
# And this does the curses library constants
(r"\bA_ATTRIBUTES\b", r"curses.A_ATTRIBUTES", "curses"),
(r"\bA_NORMAL\b", r"curses.A_NORMAL", "curses"),
(r"\bA_STANDOUT\b", r"curses.A_STANDOUT", "curses"),
(r"\bA_UNDERLINE\b", r"curses.A_UNDERLINE", "curses"),
(r"\bA_REVERSE\b", r"curses.A_REVERSE", "curses"),
(r"\bA_BLINK\b", r"curses.A_BLINK", "curses"),
(r"\bA_DIM\b", r"curses.A_DIM", "curses"),
(r"\bA_BOLDW\b", r"curses.A_BOLDW", "curses"),
(r"\bA_ALTCHARSET\b", r"curses.A_ALTCHARSET", "curses"),
(r"\bA_INVIS\b", r"curses.A_INVIS", "curses"),
(r"\bA_PROTECT\b", r"curses.A_PROTECT", "curses"),
(r"\bA_HORIZONTAL\b", r"curses.A_HORIZONTAL", "curses"),
(r"\bA_LEFT\b", r"curses.A_LEFT", "curses"),
(r"\bA_LOW\b", r"curses.A_LOW", "curses"),
(r"\bA_RIGHT\b", r"curses.A_RIGHT", "curses"),
(r"\bA_TOP\b", r"curses.A_TOP", "curses"),
(r"\bA_VERTICAL\b", r"curses.A_VERTICAL", "curses"),
(r"\bOLOR_BLACK\b", r"curses.OLOR_BLACK", "curses"),
(r"\bOLOR_RED\b", r"curses.OLOR_RED", "curses"),
(r"\bOLOR_GREEN\b", r"curses.OLOR_GREEN", "curses"),
(r"\bOLOR_YELLOW\b", r"curses.OLOR_YELLOW", "curses"),
(r"\bOLOR_BLUE\b", r"curses.OLOR_BLUE", "curses"),
(r"\bOLOR_MAGENTA\b", r"curses.OLOR_MAGENTA", "curses"),
(r"\bOLOR_CYAN\b", r"curses.OLOR_CYAN", "curses"),
(r"\bOLOR_WHITE\b", r"curses.OLOR_WHITE", "curses"),
(r"\bACS_ULCORNER\b", r"curses.ACS_ULCORNER", "curses"),
(r"\bACS_LLCORNER\b", r"curses.ACS_LLCORNER", "curses"),
(r"\bACS_URCORNER\b", r"curses.ACS_URCORNER", "curses"),
(r"\bACS_LRCORNER\b", r"curses.ACS_LRCORNER", "curses"),
(r"\bACS_LTEE\b", r"curses.ACS_LTEE", "curses"),
(r"\bACS_RTEE\b", r"curses.ACS_RTEE", "curses"),
(r"\bACS_BTEE\b", r"curses.ACS_BTEE", "curses"),
(r"\bACS_TTEE\b", r"curses.ACS_TTEE", "curses"),
(r"\bACS_HLINE\b", r"curses.ACS_HLINE", "curses"),
(r"\bACS_VLINE\b", r"curses.ACS_VLINE", "curses"),
(r"\bACS_PLUS\b", r"curses.ACS_PLUS", "curses"),
(r"\bACS_S1\b", r"curses.ACS_S1", "curses"),
(r"\bACS_S9\b", r"curses.ACS_S9", "curses"),
(r"\bACS_DIAMOND\b", r"curses.ACS_DIAMOND", "curses"),
(r"\bACS_CKBOARD\b", r"curses.ACS_CKBOARD", "curses"),
(r"\bACS_DEGREE\b", r"curses.ACS_DEGREE", "curses"),
(r"\bACS_PLMINUS\b", r"curses.ACS_PLMINUS", "curses"),
(r"\bACS_BULLET\b", r"curses.ACS_BULLET", "curses"),
(r"\bACS_LARROW\b", r"curses.ACS_LARROW", "curses"),
(r"\bACS_RARROW\b", r"curses.ACS_RARROW", "curses"),
(r"\bACS_DARROW\b", r"curses.ACS_DARROW", "curses"),
(r"\bACS_UARROW\b", r"curses.ACS_UARROW", "curses"),
(r"\bACS_BOARD\b", r"curses.ACS_BOARD", "curses"),
(r"\bACS_LANTERN\b", r"curses.ACS_LANTERN", "curses"),
(r"\bACS_BLOCK\b", r"curses.ACS_BLOCK", "curses"),
(r"\bBUTTON(\d)_PRESSED\b", r"BUTTON\1_PRESSED", "curses"),
(r"\bBUTTON(\d)_RELEASED\b", r"BUTTON\1_RELEASED", "curses"),
(r"\bBUTTON(\d)_CLICKED\b", r"BUTTON\1_CLICKED", "curses"),
(r"\bBUTTON(\d)_DOUBLE_CLICKED\b", r"BUTTON\1_DOUBLE_CLICKED", "curses"),
(r"\bBUTTON(\d)_TRIPLE_CLICKED\b", r"BUTTON\1_TRIPLE_CLICKED", "curses"),
(r"\bBUTTON_SHIFT\b", r"BUTTON_SHIFT", "curses"),
(r"\bBUTTON_CTRL\b", r"BUTTON_CTRL", "curses"),
(r"\bBUTTON_ALT\b", r"BUTTON_ALT", "curses"),
(r"\bALL_MOUSE_EVENTS\b", r"ALL_MOUSE_EVENTS", "curses"),
(r"\bREPORT_MOUSE_POSITION\b", r"REPORT_MOUSE_POSITION", "curses"),
# Python curses.ascii library
(r"\bisalnum\(", r"curses.ascii.isalnum(", "curses.ascii"),
(r"\bisalpha\(", r"curses.ascii.isalpha(", "curses.ascii"),
(r"\bisascii\(", r"curses.ascii.isascii(", "curses.ascii"),
(r"\bisblank\(", r"curses.ascii.isblank(", "curses.ascii"),
(r"\biscntrl\(", r"curses.ascii.iscntrl(", "curses.ascii"),
(r"\bisdigit\(", r"curses.ascii.isdigit(", "curses.ascii"),
(r"\bisgraph\(", r"curses.ascii.isgraph(", "curses.ascii"),
(r"\bislower\(", r"curses.ascii.islower(", "curses.ascii"),
(r"\bisprint\(", r"curses.ascii.isprint(", "curses.ascii"),
(r"\bispunct\(", r"curses.ascii.ispunct(", "curses.ascii"),
(r"\bisspace\(", r"curses.ascii.isspace(", "curses.ascii"),
(r"\bisupper\(", r"curses.ascii.isupper(", "curses.ascii"),
(r"\bisxdigit\(", r"curses.ascii.isxdigit(", "curses.ascii"),
(r"\bisctrl\(", r"curses.ascii.isctrl(", "curses.ascii"),
(r"\bismeta\(", r"curses.ascii.ismeta(", "curses.ascii"),
# Python errno library
(r"\bEPERM\b", r"errno.EPERM", "errno"),
(r"\bENOENT\b", r"errno.ENOENT", "errno"),
(r"\bESRCH\b", r"errno.ESRCH", "errno"),
(r"\bEINTR\b", r"errno.EINTR", "errno"),
(r"\bEIO\b", r"errno.EIO", "errno"),
(r"\bENXIO\b", r"errno.ENXIO", "errno"),
(r"\bE2BIG\b", r"errno.E2BIG", "errno"),
(r"\bENOEXEC\b", r"errno.ENOEXEC", "errno"),
(r"\bEBADF\b", r"errno.EBADF", "errno"),
(r"\bECHILD\b", r"errno.ECHILD", "errno"),
(r"\bEAGAIN\b", r"errno.EAGAIN", "errno"),
(r"\bENOMEM\b", r"errno.ENOMEM", "errno"),
(r"\bEACCES\b", r"errno.EACCES", "errno"),
(r"\bEFAULT\b", r"errno.EFAULT", "errno"),
(r"\bENOTBLK\b", r"errno.ENOTBLK", "errno"),
(r"\bEBUSY\b", r"errno.EBUSY", "errno"),
(r"\bEEXIST\b", r"errno.EEXIST", "errno"),
(r"\bEXDEV\b", r"errno.EXDEV", "errno"),
(r"\bENODEV\b", r"errno.ENODEV", "errno"),
(r"\bENOTDIR\b", r"errno.ENOTDIR", "errno"),
(r"\bEISDIR\b", r"errno.EISDIR", "errno"),
(r"\bEINVAL\b", r"errno.EINVAL", "errno"),
(r"\bENFILE\b", r"errno.ENFILE", "errno"),
(r"\bEMFILE\b", r"errno.EMFILE", "errno"),
(r"\bENOTTY\b", r"errno.ENOTTY", "errno"),
(r"\bETXTBSY\b", r"errno.ETXTBSY", "errno"),
(r"\bEFBIG\b", r"errno.EFBIG", "errno"),
(r"\bENOSPC\b", r"errno.ENOSPC", "errno"),
(r"\bESPIPE\b", r"errno.ESPIPE", "errno"),
(r"\bEROFS\b", r"errno.EROFS", "errno"),
(r"\bEMLINK\b", r"errno.EMLINK", "errno"),
(r"\bEPIPE\b", r"errno.EPIPE", "errno"),
(r"\bEDOM\b", r"errno.EDOM", "errno"),
(r"\bERANGE\b", r"errno.ERANGE", "errno"),
(r"\bEDEADLK\b", r"errno.EDEADLK", "errno"),
(r"\bENAMETOOLONG\b", r"errno.ENAMETOOLONG", "errno"),
(r"\bENOLCK\b", r"errno.ENOLCK", "errno"),
(r"\bENOSYS\b", r"errno.ENOSYS", "errno"),
(r"\bENOTEMPTY\b", r"errno.ENOTEMPTY", "errno"),
(r"\bELOOP\b", r"errno.ELOOP", "errno"),
(r"\bEWOULDBLOCK\b", r"errno.EWOULDBLOCK", "errno"),
(r"\bENOMSG\b", r"errno.ENOMSG", "errno"),
(r"\bEIDRM\b", r"errno.EIDRM", "errno"),
(r"\bECHRNG\b", r"errno.ECHRNG", "errno"),
(r"\bEL2NSYNC\b", r"errno.EL2NSYNC", "errno"),
(r"\bEL3HLT\b", r"errno.EL3HLT", "errno"),
(r"\bEL3RST\b", r"errno.EL3RST", "errno"),
(r"\bELNRNG\b", r"errno.ELNRNG", "errno"),
(r"\bEUNATCH\b", r"errno.EUNATCH", "errno"),
(r"\bENOCSI\b", r"errno.ENOCSI", "errno"),
(r"\bEL2HLT\b", r"errno.EL2HLT", "errno"),
(r"\bEBADE\b", r"errno.EBADE", "errno"),
(r"\bEBADR\b", r"errno.EBADR", "errno"),
(r"\bEXFULL\b", r"errno.EXFULL", "errno"),
(r"\bENOANO\b", r"errno.ENOANO", "errno"),
(r"\bEBADRQC\b", r"errno.EBADRQC", "errno"),
(r"\bEBADSLT\b", r"errno.EBADSLT", "errno"),
(r"\bEDEADLOCK\b", r"errno.EDEADLOCK", "errno"),
(r"\bEBFONT\b", r"errno.EBFONT", "errno"),
(r"\bENOSTR\b", r"errno.ENOSTR", "errno"),
(r"\bENODATA\b", r"errno.ENODATA", "errno"),
(r"\bETIME\b", r"errno.ETIME", "errno"),
(r"\bENOSR\b", r"errno.ENOSR", "errno"),
(r"\bENONET\b", r"errno.ENONET", "errno"),
(r"\bENOPKG\b", r"errno.ENOPKG", "errno"),
(r"\bEREMOTE\b", r"errno.EREMOTE", "errno"),
(r"\bENOLINK\b", r"errno.ENOLINK", "errno"),
(r"\bEADV\b", r"errno.EADV", "errno"),
(r"\bESRMNT\b", r"errno.ESRMNT", "errno"),
(r"\bECOMM\b", r"errno.ECOMM", "errno"),
(r"\bEPROTO\b", r"errno.EPROTO", "errno"),
(r"\bEMULTIHOP\b", r"errno.EMULTIHOP", "errno"),
(r"\bEDOTDOT\b", r"errno.EDOTDOT", "errno"),
(r"\bEBADMSG\b", r"errno.EBADMSG", "errno"),
(r"\bEOVERFLOW\b", r"errno.EOVERFLOW", "errno"),
(r"\bENOTUNIQ\b", r"errno.ENOTUNIQ", "errno"),
(r"\bEBADFD\b", r"errno.EBADFD", "errno"),
(r"\bEREMCHG\b", r"errno.EREMCHG", "errno"),
(r"\bELIBACC\b", r"errno.ELIBACC", "errno"),
(r"\bELIBBAD\b", r"errno.ELIBBAD", "errno"),
(r"\bELIBSCN\b", r"errno.ELIBSCN", "errno"),
(r"\bELIBMAX\b", r"errno.ELIBMAX", "errno"),
(r"\bELIBEXEC\b", r"errno.ELIBEXEC", "errno"),
(r"\bEILSEQ\b", r"errno.EILSEQ", "errno"),
(r"\bERESTART\b", r"errno.ERESTART", "errno"),
(r"\bESTRPIPE\b", r"errno.ESTRPIPE", "errno"),
(r"\bEUSERS\b", r"errno.EUSERS", "errno"),
(r"\bENOTSOCK\b", r"errno.ENOTSOCK", "errno"),
(r"\bEDESTADDRREQ\b", r"errno.EDESTADDRREQ", "errno"),
(r"\bEMSGSIZE\b", r"errno.EMSGSIZE", "errno"),
(r"\bEPROTOTYPE\b", r"errno.EPROTOTYPE", "errno"),
(r"\bENOPROTOOPT\b", r"errno.ENOPROTOOPT", "errno"),
(r"\bEPROTONOSUPPORT\b", r"errno.EPROTONOSUPPORT", "errno"),
(r"\bESOCKTNOSUPPORT\b", r"errno.ESOCKTNOSUPPORT", "errno"),
(r"\bEOPNOTSUPP\b", r"errno.EOPNOTSUPP", "errno"),
(r"\bEPFNOSUPPORT\b", r"errno.EPFNOSUPPORT", "errno"),
(r"\bEAFNOSUPPORT\b", r"errno.EAFNOSUPPORT", "errno"),
(r"\bEADDRINUSE\b", r"errno.EADDRINUSE", "errno"),
(r"\bEADDRNOTAVAIL\b", r"errno.EADDRNOTAVAIL", "errno"),
(r"\bENETDOWN\b", r"errno.ENETDOWN", "errno"),
(r"\bENETUNREACH\b", r"errno.ENETUNREACH", "errno"),
(r"\bENETRESET\b", r"errno.ENETRESET", "errno"),
(r"\bECONNABORTED\b", r"errno.ECONNABORTED", "errno"),
(r"\bECONNRESET\b", r"errno.ECONNRESET", "errno"),
(r"\bENOBUFS\b", r"errno.ENOBUFS", "errno"),
(r"\bEISCONN\b", r"errno.EISCONN", "errno"),
(r"\bENOTCONN\b", r"errno.ENOTCONN", "errno"),
(r"\bESHUTDOWN\b", r"errno.ESHUTDOWN", "errno"),
(r"\bETOOMANYREFS\b", r"errno.ETOOMANYREFS", "errno"),
(r"\bETIMEDOUT\b", r"errno.ETIMEDOUT", "errno"),
(r"\bECONNREFUSED\b", r"errno.ECONNREFUSED", "errno"),
(r"\bEHOSTDOWN\b", r"errno.EHOSTDOWN", "errno"),
(r"\bEHOSTUNREACH\b", r"errno.EHOSTUNREACH", "errno"),
(r"\bEALREADY\b", r"errno.EALREADY", "errno"),
(r"\bEINPROGRESS\b", r"errno.EINPROGRESS", "errno"),
(r"\bESTALE\b", r"errno.ESTALE", "errno"),
(r"\bEUCLEAN\b", r"errno.EUCLEAN", "errno"),
(r"\bENOTNAM\b", r"errno.ENOTNAM", "errno"),
(r"\bENAVAIL\b", r"errno.ENAVAIL", "errno"),
(r"\bEISNAM\b", r"errno.EISNAM", "errno"),
(r"\bEREMOTEIO\b", r"errno.EREMOTEIO", "errno"),
(r"\bEDQUOT\b", r"errno.EDQUOT", "errno"),
# Python fcntl library
(r"\bfcntl\(", r"fcntl.fcntl(", "fcntl"),
(r"\bflock\(", r"fcntl.lockf(", "fcntl"),
(r"\blockf\(", r"fcntl.lockf(", "fcntl"),
(r"\bLOCK_UN\b", r"fcntl.LOCK_UN", "fcntl"),
(r"\bLOCK_EX\b", r"fcntl.LOCK_EX", "fcntl"),
(r"\bLOCK_SH\b", r"fcntl.LOCK_SH", "fcntl"),
(r"\bLOCK_NB\b", r"fcntl.LOCK_NB", "fcntl"),
# Python getpass library
(r"\bgetpass\(", r"getpass.getpass(", "getpass"),
# Python glob library
(r"\bglob\(", r"glob.glob(", "glob"), # Calling conventions differ
# Python grp library
(r"\bgetgrgid\(", r"grp.getgrgid(", "grp"),
(r"\bgetgrnam\(", r"grp.getgrnam(", "grp"),
# Python math library
(r"\bacos\(", r"math.acos(", "math"),
(r"\basin\(", r"math.asin(", "math"),
(r"\batan\(", r"math.atan(", "math"),
(r"\batan2\(", r"math.atan2(", "math"),
(r"\bceil\(", r"math.ceil(", "math"),
(r"\bcos\(", r"math.cos(", "math"),
(r"\bcosh\(", r"math.cosh(", "math"),
(r"\bexp\(", r"math.exp(", "math"),
(r"\bfabs\(", r"math.fabs(", "math"),
(r"\bfloor\(", r"math.floor(", "math"),
(r"\bfmod\(", r"math.fmod(", "math"),
(r"\bfrexp\(", r"math.frexp(", "math"), # Calling conventions differ
(r"\bldexp\(", r"math.ldexp(", "math"),
(r"\blog10\(", r"math.log10(", "math"),
(r"\blog\(", r"math.log(", "math"),
(r"\bmodf\(", r"math.modf(", "math"), # Calling conventions differ
(r"\bpow\(", r"math.pow(", "math"),
(r"\bsinh\(", r"math.sinh(", "math"),
(r"\bsin\(", r"math.sin(", "math"),
(r"\bsqrt\(", r"math.sqrt(", "math"),
(r"\btan\(", r"math.tan(", "math"),
(r"\btanh\(", r"math.tanh(", "math"),
# Python os library
(r"\babort\(", r"os.abort(", "os"),
(r"\baccess\(", r"os.access(", "os"),
(r"\bchdir\(", r"os.chdir(", "os"),
(r"\bclose\(", r"os.close(", "os"),
(r"\benviron\(", r"os.environ(", "os"),
(r"\bfchdir\(", r"os.fchdir(", "os"),
(r"\bchroot\(", r"os.chroot(", "os"),
(r"\bchmod\(", r"os.chmod(", "os"),
(r"\bchown\(", r"os.chown(", "os"),
(r"\bctermid\(", r"os.ctermid(", "os"),
(r"\bdup\(", r"os.dup(", "os"),
(r"\bdup2\(", r"os.dup2(", "os"),
(r"\bexecl\(", r"os.execl(", "os"),
(r"\bexecle\(", r"os.execle(", "os"),
(r"\bexeclp\(", r"os.execlp(", "os"),
(r"\bexeclpe\(", r"os.execlpe(", "os"),
(r"\bexecv\(", r"os.execv(", "os"),
(r"\bexecve\(", r"os.execve(", "os"),
(r"\bexecvp\(", r"os.execvp(", "os"),
(r"\bexecvpe\(", r"os.execvpe(", "os"),
(r"\b_exit\(", r"os._exit(", "os"),
(r"\bexit\(", r"os.exit(", "os"),
(r"\bfdopen\(", r"os.fdopen(", "os"),
(r"\bfork\(", r"os.fork(", "os"),
(r"\bfsync\(", r"os.fsync(", "os"),
(r"\bftruncate\(", r"os.ftruncate(", "os"),
(r"\bgetcwd\(", r"os.getcwd(", "os"),
(r"\bgetegid\(", r"os.getegid(", "os"),
(r"\bgeteuid\(", r"os.geteuid(", "os"),
(r"\bgetenv\(", r"os.getenv(", "os"),
(r"\bgetgid\(", r"os.getgid(", "os"),
(r"\bgetgroups\(", r"os.getgroups(", "os"),
(r"\bgetlogin\(", r"os.getlogin(", "os"),
(r"\bgetpgid\(", r"os.getpgid(", "os"),
(r"\bgetpgrp\(", r"os.getpgrp(", "os"),
(r"\bgetpid\(", r"os.getpid(", "os"),
(r"\bgetppid\(", r"os.getppid(", "os"),
(r"\bgetuid\(", r"os.getuid(", "os"),
(r"\bkill\(", r"os.kill(", "os"),
(r"\bkillpg\(", r"os.killpg(", "os"),
(r"\bisatty\(", r"os.isatty(", "os"),
(r"\blseek\(", r"os.lseek(", "os"),
(r"\blchown\(", r"os.lchown(", "os"),
(r"\bgetcwd\(", r"os.getcwd(", "os"),
(r"\blstat\(", r"os.lstat(", "os"),
(r"\bmkfifo\(", r"os.mkfifo(", "os"),
(r"\bmknod\(", r"os.mknod(", "os"),
(r"\bmkdir\(", r"os.mkdir(", "os"),
(r"\bnice\(", r"os.nice(", "os"),
(r"\bopen\(", r"os.open(", "os"),
(r"\bpathconf\(", r"os.pathconf(", "os"),
(r"\bpipe\(", r"os.pipe(", "os"),
(r"\bplock\(", r"os.plock(", "os"),
(r"\bputenv\(", r"os.putenv(", "os"),
(r"\bread\(", r"os.read(", "os"),
(r"\brmdir\(", r"os.rmdir(", "os"),
(r"\bsetegid\(", r"os.setegid(", "os"),
(r"\bseteuid\(", r"os.seteuid(", "os"),
(r"\bsetgid\(", r"os.setgid(", "os"),
(r"\bsetgroups\(", r"os.setgroups(", "os"),
(r"\bsetpgrp\(", r"os.setpgrp(", "os"),
(r"\bsetpgid\(", r"os.setpgid(", "os"),
(r"\bsetreuid\(", r"os.setreuid(", "os"),
(r"\bsetregid\(", r"os.setregid(", "os"),
(r"\bsetsid\(", r"os.setsid(", "os"),
(r"\bsetuid\(", r"os.setuid(", "os"),
(r"\bstrerror\(", r"os.strerror(", "os"),
(r"\bumask\(", r"os.umask(", "os"),
(r"\bsymlink\(", r"os.symlink(", "os"),
(r"\bsystem\(", r"os.system(", "os"),
(r"\btcgetpgrp\(", r"os.tcgetpgrp(", "os"),
(r"\btcsetpgrp\(", r"os.tcsetpgrp(", "os"),
(r"\btmpfile\(", r"os.tmpfile(", "os"),
(r"\bttyname\(", r"os.ttyname(", "os"),
(r"\bunlink\(", r"os.unlink(", "os"),
(r"\bwrite\(", r"os.write(", "os"),
(r"\bwait\(", r"os.wait(", "os"),
(r"\bwaitpid\(", r"os.waitpid(", "os"),
(r"\bWNOHANG\b", r"os.WNOHANG", "os"),
(r"\bWCONTINUED\b", r"os.WCONTINUED", "os"),
(r"\bWUNTRACED\b", r"os.WUNTRACED", "os"),
(r"\bWCOREDUMP\b", r"os.WCOREDUMP", "os"),
(r"\bWIFCONTINUED\b", r"os.WIFCONTINUED", "os"),
(r"\bWIFSTOPPED\b", r"os.WIFSTOPPED", "os"),
(r"\bWIFSIGNALED\b", r"os.WIFSIGNALED", "os"),
(r"\bWIFEXITED\b", r"os.WIFEXITED", "os"),
(r"\bWEXITSTATUS\b", r"os.WEXITSTATUS", "os"),
(r"\bWSTOPSIG\b", r"os.WSTOPSIG", "os"),
(r"\bWTERMSIG\b", r"os.WTERMSIG", "os"),
(r"\bO_RDONLY\b", r"os.O_RDONLY", "os"),
(r"\bO_WRONLY\b", r"os.O_WRONLY", "os"),
(r"\bO_RDWR\b", r"os.O_RDWR", "os"),
(r"\bO_NDELAY\b", r"os.O_NDELAY", "os"),
(r"\bO_NONBLOCK\b", r"os.O_NONBLOCK", "os"),
(r"\bO_APPEND\b", r"os.O_APPEND", "os"),
(r"\bO_DSYNC\b", r"os.O_DSYNC", "os"),
(r"\bO_RSYNC\b", r"os.O_RSYNC", "os"),
(r"\bO_SYNC\b", r"os.O_SYNC", "os"),
(r"\bO_NOCTTY\b", r"os.O_NOCTTY", "os"),
(r"\bO_CREAT\b", r"os.O_CREAT", "os"),
(r"\bO_EXCL\b", r"os.O_EXCL", "os"),
(r"\bO_TRUNC\b", r"os.O_TRUNC", "os"),
(r"\bF_OK\b", r"os.F_OK", "os"),
(r"\bR_OK\b", r"os.R_OK", "os"),
(r"\bW_OK\b", r"os.W_OK", "os"),
(r"\bX_OK\b", r"os.X_OK", "os"),
(r"\bS_ISUID\b", r"os.S_ISUID", "os"),
(r"\bS+ISGID\b", r"os.S+ISGID", "os"),
(r"\bS_ENFMT\b", r"os.S_ENFMT", "os"),
(r"\bS_ISVTX\b", r"os.S_ISVTX", "os"),
(r"\bS_IREAD\b", r"os.S_IREAD", "os"),
(r"\bS_IWRITE\b", r"os.S_IWRITE", "os"),
(r"\bS_IEXEC\b", r"os.S_IEXEC", "os"),
(r"\bS_IRWXU\b", r"os.S_IRWXU", "os"),
(r"\bS_IRUSR\b", r"os.S_IRUSR", "os"),
(r"\bS_IXUSR\b", r"os.S_IXUSR", "os"),
(r"\bS_IRWXG\b", r"os.S_IRWXG", "os"),
(r"\bS_IRGRP\b", r"os.S_IRGRP", "os"),
(r"\bS_IWGRP\b", r"os.S_IWGRP", "os"),
(r"\bS_IXGRP\b", r"os.S_IXGRP", "os"),
(r"\bS_IRWXO\b", r"os.S_IRWXO", "os"),
(r"\bS_IROTH\b", r"os.S_IROTH", "os"),
(r"\bS_IWOTH\b", r"os.S_IWOTH", "os"),
(r"\bS_IXOTH\b", r"os.S_IXOTH", "os"),
# Python os.path library
(r"\bbasename\(", r"os.path.basename(", "os.path"),
(r"\bdirname\(", r"os.path.dirname(", "os.path"),
# Python pwd library
(r"\bgetpwuid\(", r"pwd.getpwuid(", "pwd"),
(r"\bgetpwnam\(", r"pwd.getpwnam(", "pwd"),
# Python random library -- alas, C rand() doesn't map cleanly
(r"\bsrand48\(", r"random.seed(", "random"),
(r"\bsrand\(", r"random.seed(", "random"),
# Python string library
(r"\btoupper\(%(farg)s\)", r"\1.upper(", None),
(r"\btolower\(%(farg)s\)", r"\1.lower(", None),
# Python sys library
(r"\bargv\(", r"sys.argv(", "sys"),
(r"\bstdin\(", r"sys.stdin(", "sys"),
(r"\bstdout\(", r"sys.stdout(", "sys"),
(r"\bstderr\(", r"sys.stderr(", "sys"),
# Python termios library
(r"\btcgetattr\(", r"termios.tcgetattr(", "termios"), # Calling conventions differ
(r"\btcsetattr\(", r"termios.tcsetattr(", "termios"), # Calling conventions differ
(r"\btcsendbreak\(", r"termios.tcsendbreak(", "termios"),
(r"\btcflush\(", r"termios.tcflush(", "termios"),
(r"\btcdrain\(", r"termios.tcdrain(", "termios"),
(r"\btcflow\(", r"termios.tcflow(", "termios"),
(r"\bVMIN\b", r"termios.VMIN", "termios"),
(r"\bVMAX\b", r"termios.VMAX", "termios"),
(r"\bTCSANOW\b", r"termios.TCSANOW", "termios"),
(r"\bTCSADRAIN\b", r"termios.TCSADRAIN", "termios"),
(r"\bTCSAFLUSH\b", r"termios.TCSAFLUSH", "termios"),
(r"\bTCIFLUSH\b", r"termios.TCIFLUSH", "termios"),
(r"\bTCOFLUSH\b", r"termios.TCOFLUSH", "termios"),
(r"\bTCOOFF\b", r"termios.TCOOFF", "termios"),
(r"\bTCOON\b", r"termios.TCOON", "termios"),
)
falsefriends = (
r"frexp", r"glob", r"ioctl", r"modf", r"tcgetattr", r"tcsetattr",
r"ungetmouse",
)
# These have to be applied to the entire file without breaking it into regions
file_transformations = (
# Simple initializers to tuples
(r"(?:static)?\s+(?:%(type)s|%(class)s)\s+(%(id)s)\[[a-zA-Z0-9._]*]\s*=\s*{([^}]+)}",
r"\1 = (\2)"),
(r"enum\s+(%(id)s\s*){\s*", r"enum \1{\n"),
(r"enum\s+{\s*", r"enum {\n"),
(r"%(ind)s#\s*\$ctopy.*", r""), # Make hints go away
(r"(?:int )?main\(int\s+argc,\s+char\s+\*argv\)\s*{",
"if __name__ == '__main__':"),
)
# These need to be applied repeatedly within regions.
# They rely on semicolons as statatement end markers.
repeat_transformations = (
(
# Group 1: What we're doing here is stripping out prefix, suffix,
# and wrapper parts of declarations in order to reduce everything
# to base type followed by whitespace followed by id. This is
# significant for simplifying both function formal parameter lists
# and variable declaration lines. We'll get rid of the remaining
# type stuff in a later pass.
(r"(%(type)s|%(class)s)\s*\*", r"\1 "), # Pointer type decls
(r"(%(type)s|%(class)s)(.*), \*", r"\1\2, "), # Pointer type decls
(r"(%(type)s|%(class)s)\s*\((%(id)s)\)\(\)", r"\1 \2"), # Function pointer wrappers
(r"(%(type)s|%(class)s)\s*(%(id)s)\[\]", r"\1 \2"), # Array declarators
),
(
# Group 2: Translate function headers. This needs to happen after
# reduction to base types (just above) but before scalar types
# have been removed entirely.
(r"\n(?:static\s+)?(?:%(type)s|%(class)s) +(.*\)) *\n", r"\ndef \1:\n"),
),
(
# Group 3: What we're doing here is trying to get rid of variable
# declarations that don't have initializer parts.
# Scalar-vars just after the type and before a comma go away.
(r"(\n[ \t]*(?:%(type)s))(\s*%(id)s),", r"\1 "),
# Scalar-vars just after type and before a semi go away, but semi stays.
(r"(\n[ \t]*(?:%(type)s))(\s*%(id)s);", r"\1;"),
# Class-vars after class names and before comma or semi get an initializer.
(r"(\n[ \t]*)(%(class)s)(\s*%(id)s)([;,])", r"\1\2\3 = \2()\4"),
# Scalar-vars between a comma and a trailing semicolon go away.
(r"(\n[ \t]*)((?:%(type)s).*)(,\s*%(id)s\s*);", r"\1\2;"),
# Class-Vars between comma and semicolon get a following initializer
(r"(\n[ \t]*)(%(class)s)(.*,\s)*(%(id)s)(\s*;)", r"\1\2\3\4 = \2()\5"),
# Scalar-vars between commas in a declaration line go away.
(r"(\n[ \t]*(?:%(type)s)\s+.*)(,\s*%(id)s)(,.*);", r"\1\3;"),
# Bare class-vars between commas get an initializer
(r"(\n[ \t]*)(%(class)s)(\s+.*,)(\s*%(id)s),(.*);",r"\1\2\3\4 = \2(),\5;"),
# Any declaration line not containing an initializer goes away.
(r"\n[ \t]*(?:%(type)s|%(class)s)[^=;]*;", r""),
),
(
# Group 4: At this point all declarations left have initializers.
# Replace commas in declaration lines with semis, otherwise Python will
# barf later because it thinks that, e.g., a=4, b=5 is an attempt to
# assign a constant to a tuple.
# FIXME: This will fail messily on GCC structure intializers.
(r"(\n[ \t]*(?:%(type)s|%(class)s).*),(.*);", r"\1;\2"),
),
(
# Group 5: Now rip out all remaining base type information.
# This will strip remaining type declarators out of formal parameter lists.
# It will also remove types from the beginning of declaration lines.
# Won't nuke casts because it looks for at least one following whitespace.
(r"(?:%(type)s|%(class)s)[\s;]\s*", r""),
),
)
# These get applied once within regions, before type info has been stripped
pre_transformations = (
# We used to do function header translation here. We leave
# this in place because we'll probably need to do things here again.
)
# These get applied once within regions, after type info has been stripped
post_transformations = (
# some consequences of having translated function headers
(r"\(void\):\n", r"():\n"),
(r"def(.*):\n\Z", r"def\1:\n "), # indent comment on line after def
# externs can just disappear -- this may discard a following comment
(r"extern[^;]+;.*\n", r""),
# macros
(r"#define\s+(%(id)s)\s+(.*)", r"\1\t= \2"),
(r"#define\s+(%(id)s)\(([^)]*)\)\s+(.*\))", r"def \1(\2):\treturn \3"),
(r"#define\s+(%(id)s)\(([^)]*)\)\s+([^(].*)", r"def \1(\2):\t\3"),
# control structure
(r"\bif *\((.*)\)(\s*{)?", r"if \1:"),
(r"\bwhile *\((.*)\)(\s*{)?", r"while \1:"),
(r"\bwhile 1:", r"while True:"),
(r"\bfor \(;;\)(\s*{)?", r"while True:"),
(r"\bfor \((%(id)s) *= *0; *\1 *<= *([^;]+); *\1\+\+\)(\s*{)?",
r"for \1 in range(\2+1):"),
(r"\bfor \((%(id)s) *= *([^;]+); *\1 *<= *([^;]+); *\1\+\+\)(\s*{)?",
r"for \1 in range(\2, \3+1):"),
(r"\bfor \((%(id)s) *= *0; *\1 *< *([^;]+); *\1\+\+\)\s*{",
r"for \1 in range(\2):"),
(r"\bfor \((%(id)s) *= *([^;]+); *\1 *< *([^;]+); *\1\+\+\)(\s*{)?",
r"for \1 in range(\2, \3):"),
(r"else if", r"elif"),
(r"(?:} )?else\s*{", r"else"),
(r"(?<!#)else", r"else:"),
(r"\bdo\s*{", r"while True:"),
(r"}\s*while\s*(\(.*\));", r"if not \1: break # DO-WHILE TERMINATOR -- INDENTATION IS PROBABLY WRONG"),
(r"switch *\((.*)\)(\s*{)?", r"switch \1:"),# Not Python, but less ugly
# constants
(r"\btrue\b", r"True"), # C99
(r"\bfalse\b", r"False"), # C99
(r"\bTRUE\b", r"True"), # pre-C99
(r"\bFALSE\b", r"False"), # pre-C99
# expression operations
(r" *\&\& *", r" and "),
(r" *\|\| *", r" or "),
(r"-\>", r"."),
(r"!(?!=) *", r"not "),
(r"(and|or) *\n", r"\1 \\\n"),
# most common uses of address operator
(r"return *&", r"return "),
(r"= *&", r"= "),
# increment and decrement statements
(r"(%(id)s)\+\+([;\n])", r"\1 += 1\2"),
(r"(%(id)s)--([;\n])", r"\1 -= 1\2"),
(r"\+\+(%(id)s)([;\n])", r"\1 += 1\2"),
(r"--(%(id)s)([;\n])", r"\1 -= 1\2"),
# no-op voids
(r"\n[ \t]*\(void\)", r"\n"),
# C functions that turn into Python builtins
(r"\batoi\(", r"int("),
(r"\batof\(", r"float("),
(r"\batol\(", r"long("),
(r"\bfopen\(", r"open("),
(r"\bputchar\(", r"stdout.write("),
(r"\bgetchar\(\)", r"stdout.read(1)"),
(r"\bstrlen\(", r"len("),
(r"\bstrcmp\((%(exp)s),\s*(%(exp)s)\)\s*==\s*0", r"\1 == \2"),
(r"\bstrcmp\((%(exp)s),\s*(%(exp)s)\)\s*!=\s*0", r"\1 != \2"),
(r"\bstrcpy\((%(exp)s),\s*(%(exp)s)\)", r"\1 = \2"),
# Python time library
(r"\btime\(NULL\)", r"time.time()"),
# well-known includes
(r"#include \<string.h\>\n", r""),
(r"#include \<stdlib.h\>\n", r""),
(r"#include \<stdbool.h\>\n", r""),
(r"#include \<stdio.h\>\n", r"import sys\n"),
(r"#include \<math.h\>\n", r"import math\n"),
(r"#include \<time.h\>\n", r"import time\n"),
(r"#include \<regex.h\>\n", r"import re\n"),
(r"#include \<curses.h\>\n", r"import curses\n"),
(r"#include \<termios.h\>\n", r"import termios\n"),
)
final_transformations = (
# block delimiters -- do these as late as possible, they're useful
(r";(%(eol)s)", r"\1"),
(r"\n[ \t]*}%(eol)s", r""),
(r"(?<!=\n)\n{\n", r"\n"), # Start-of-line brace that's not an initializer
(r"%% \(,(%(ind)s)", r"%\1("),
)
def single_apply(transforms, text):
"Apply specified set of transformations once."
for (fro, to) in transforms:
oldtext = text
# Prepending \n then stripping it means that \n can reliably
# be used to recognize start of line.
text = re.sub(fro % shorthands, to, "\n" + oldtext)[1:]
if debug >= 2 and text != oldtext:
print "%s transforms '%s' to '%s'" % ((fro, to), `oldtext`, `text`)
return text
def repeat_apply(transforms, text):
"Repeatedly apply specified transformations to text until it's stable."
while True:
transformed = single_apply(transforms, text)
if transformed != text:
text = transformed
else:
break
return text
def ctopy(inputc):
"Transform C to Python."
if debug >= 2:
print "Gathering hints"
hints = re.finditer(r"\$ctopy (.*)", inputc)
for hint in hints:
process_hint(hint.group(1))
if debug >= 2:
print "Processing inline enums"
global stringify
enums = re.finditer(r"enum[ \t]*{(.*)} (%(id)s)" % shorthands, inputc)
for instance in enums:
stringify += instance.group(1).replace(" ", "").split(",")
inputc = inputc[:instance.start(0)] + inputc[instance.start(2):]
if debug:
print "Pre-transformations begin"
inputc = repeat_apply(file_transformations, inputc)
if debug >= 2:
print "After pre-transformations: %s" % `code`
if debug:
print "Region analysis begins"
boundaries = [0]
state = "text"
for i in range(len(inputc)):
if state == "text":
if inputc[i] == '"' and (i == 0 or inputc[i-1] != '\\'):
if debug >= 2:
print "String literal starts at %d" % i
boundaries.append(i)
state = "stringliteral"
elif inputc[i:i+2] == "/*":
if debug >= 2:
print "Closed comment starts at %d" % (i-1)
boundaries.append(i)
state = "closedcomment"
elif inputc[i:i+2] == "//":
if debug >= 2:
print "Open comment starts at %d" % i
boundaries.append(i)
state = "opencomment"
elif inputc[i:].startswith("typedef enum {") or inputc[i:].startswith("enum {"):
if debug >= 2:
print "enumeration starts at %d" % i
if inputc[i-2:i+1] != 'f e':
boundaries.append(i)
boundaries.append(i + inputc[i:].find("enum") + 5)
elif inputc[i:].startswith("\n}"):
if debug >= 2:
print "start-of-line brace at %d" % i
boundaries.append(i)
boundaries.append(i+2)
elif state == "stringliteral":
if inputc[i] == '"' and (i == 0 or inputc[i-1] != '\\'):
if debug >= 2:
print "String ends at %d" % i
boundaries.append(i+1)
state = "text"
elif state == "closedcomment":
if inputc[i:i+2] == "*/":
if debug >= 2:
print "closed comment ends at %d" % (i+1)
boundaries.append(i+2)
state = "text"
elif state == "opencomment":
if inputc[i] == "\n":
if debug >= 2:
print "Open comment ends at %d" % (i+1)
boundaries.append(i+1)
state = "text"
boundaries.append(len(inputc))
if debug >= 2:
print "Boundaries:", boundaries
regions = []
for i in range(len(boundaries)-1):
regions.append(inputc[boundaries[i]:boundaries[i+1]])
regions = filter(lambda x: x != '', regions)
if debug:
print "Regexp transformation begins"
if debug:
import pprint
pp = pprint.PrettyPrinter(indent=4)
print "Regions:"
pp.pprint(regions)
if debug >= 2:
print "Processing printf-like functions"
for (i, here) in enumerate(regions):
if regions[i][0] != '"' or not "%" in here:
continue
else:
for func in printflike:
if re.search(r"\b%s\([^;]*\Z" % func, regions[i]):
break
else:
continue # Didn't find printf-like function
# Found printf-like function. Replace first comma in the
# argument region with " % (". This copes gracefully with the
# case where the format string is wrapped in _( ) for
# initialization.
regions[i+1] = re.sub(r",\s*", r" % (", regions[i+1], 1)
j = regions[i+1].find("%") + 2
parenlevel = 0
while j < len(regions[i+1]):
if regions[i+1][j] == "(":
parenlevel += 1
if regions[i+1][j] == ")":
parenlevel -= 1
if parenlevel == 0:
regions[i+1] = regions[i+1][:j] + ")" + regions[i+1][j:]
break
j += 1
importlist = []
try:
for i in range(len(regions)):
if regions[i][:2] == "/*":
if regions[i].count("\n") <= 1: # winged comment
regions[i] = "#" + regions[i][2:-2]
elif re.search("/\*+\n", regions[i]): # boxed comment
regions[i] = re.sub(r"\n([ \t]*) \* ?", r"\n\1",regions[i])
regions[i] = re.sub(r"\n([ \t]*)\*", r"\n\1", regions[i])
regions[i] = re.sub(r"^([ \t]*)/\*+\n", r"\1#\n", regions[i])
regions[i] = re.sub(r"\n([ \t]*)\**/", r"\n\1", regions[i])
regions[i] = re.sub(r"\n([ \t]*)(?!#)", r"\n\1# ", regions[i])
else:
regions[i] = regions[i].replace("/*", "#")
regions[i] = regions[i].replace("\n*/", "\n#")
regions[i] = regions[i].replace("*/", "")
regions[i] = regions[i].replace("\n *", "\n")
regions[i] = regions[i].replace("\n", "\n#")
elif regions[i][:2] == "//":
regions[i] = "#" + regions[i][2:]
elif regions[i][0] != '"':
if debug >= 2:
print "Doing pre transformations"
regions[i] = single_apply(pre_transformations, regions[i])
if debug >= 2:
print "Doing repeated transformations"
for (j, hack) in enumerate(repeat_transformations):
if debug >= 2:
print "Repeat transformations group %d" % (j+1)
regions[i] = repeat_apply(hack, regions[i])
if debug:
print "Function and method mappings begin"
for (fro, to, module) in funmappings:
if re.search(fro, regions[i]):
regions[i] = re.sub(fro, to, regions[i])
if module not in importlist and module:
importlist.append(module)
for name in falsefriends:
if re.search(r"\b" + name + r"\b\(", regions[i]):
sys.stderr.write("warning: %s calling conventions differ between C and Python." % name)
if debug >= 2:
print "Doing post transformations"
regions[i] = single_apply(post_transformations, regions[i])
for istr in stringify:
regions[i] = re.sub(r"\b" + istr + r"\b",
'"' + istr + '"', regions[i])
except IndexError:
sys.stderr.write("ctopy: pathological string literal at %d.\n" % boundaries[i])
raise SystemExit, 1
if debug:
"Enumeration processing"
state = "plain"
for (i, region) in enumerate(regions):
# first compute a parse state
if region.startswith("typedef enum"):
state = "typedef"
elif region.startswith("enum"):
state = "enum"
elif region == "\n}":
if state in ("typedef", "enum"):
regions[i] = ''
state = "plain"
# now do something useful with it
if debug >= 3:
print "Enumeration processing: state = %s, region = %s" % (state, `regions[i]`)
if state in ("enum", "typedef"):
if regions[i] == "enum ":
m = re.match("(%(id)s) {" % shorthands, regions[i+1])
if m:
shorthands['type'] += "|" + m.group(1)
regions[i] = '# From enumerated type \'%s\'\n' % m.group(1)
regions[i+1] = regions[i+1][m.end(0)+1:]
else:
regions[i] = '# From anonymous enumerated type\n'
elif regions[i] == "typedef enum ":
m = re.match("\s* (%(id)s)\s*;?" % shorthands, regions[i+3])
if m:
shorthands['type'] += "|" + m.group(1)
regions[i] = '# From enumerated type \'%s\'\n' % m.group(1)
regions[i+3] = regions[i+3][:m.start(0)] + "\n\n"
else:
regions[i] = '# From anonymous typedefed enum (?!)\n'
else:
regions[i] = re.sub(",\s*", "\n", regions[i])
val = 0
txt = regions[i].split("\n")
for j in range(len(txt)):
if txt[j] == '' or txt[j].startswith("{"):
pass
elif '=' not in txt[j]:
txt[j] += " = %d" % val
val += 1
regions[i] = "\n".join(txt)
if debug:
"Final transformations begin"
regions = map(lambda r: repeat_apply(final_transformations, r),regions)
text = "".join(regions)
if importlist:
importlist = "import " + ", ".join(importlist) + "\n"
text = importlist + text
# Emit what we got. Preserve imports in case this is a .h file
return text
def process_hint(line):
"Process a translation-hints line."
if line[0] == "#":
pass
else:
global stringify, printflike
if debug >= 2:
print "Hint: %s" % `line`
lst = line.replace(",", " ").split()
if lst[0] == "stringify":
stringify += lst[1:]
elif lst[0] == "type":
for tok in lst[1:]:
shorthands["type"] += r"|\b" + tok + r"\b"
elif lst[0] == "class":
for tok in lst[1:]:
shorthands["class"] += r"|\b" + tok + r"\b"
elif lst[0] == "printflike":
printflike += lst[1:]
if __name__ == "__main__":
import getopt
(options, arguments) = getopt.getopt(sys.argv[1:], "c:h:ds:t:")
debug = 0;
for (switch, val) in options:
if (switch == '-c'):
shorthands["class"] += r"|\b" + val + r"\b"
elif (switch == '-d'):
debug += 1
elif (switch == '-h'):
for line in open(val):
process_hint(line)
elif (switch == '-s'):
stringify.append(val)
elif (switch == '-t'):
shorthands["type"] += r"|\b" + val + r"\b"
try:
code = sys.stdin.read()
if debug >= 2:
print "Input is: %s" % `code`
text = ctopy(code)
if debug:
print "Output:"
sys.stdout.write(text)
except KeyboardInterrupt:
pass
| [
"mskang@mit.edu"
] | mskang@mit.edu |
93770b04b06cc4bee60b772d822f418ad8a272c9 | faca8866b3c8aca30a915d8cb2748766557ed808 | /object_detection_updata/metrics/tf_example_parser.py | 510e6917fa9838e9282ec6f561e50cb77a7b5ff9 | [] | no_license | yongqis/proposal_joint_retireval | 6899d80f8fb94569c7b60764f6e7de74bcfa9cc8 | 97b086c62473ab1a5baf45743535fce70c3f8c20 | refs/heads/master | 2020-05-25T19:07:22.946008 | 2019-06-03T07:09:04 | 2019-06-03T07:09:09 | 187,943,867 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,294 | py | # Copyright 2017 The TensorFlow Authors. 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.
# ==============================================================================
"""Tensorflow Example proto parser for data loading.
A parser to decode data containing serialized tensorflow.Example
protos into materialized tensors (numpy arrays).
"""
import numpy as np
from object_detection_updata.core import data_parser
from object_detection_updata.core import standard_fields as fields
class FloatParser(data_parser.DataToNumpyParser):
"""Tensorflow Example float parser."""
def __init__(self, field_name):
self.field_name = field_name
def parse(self, tf_example):
return np.array(
tf_example.features.feature[self.field_name].float_list.value,
dtype=np.float).transpose() if tf_example.features.feature[
self.field_name].HasField("float_list") else None
class StringParser(data_parser.DataToNumpyParser):
"""Tensorflow Example string parser."""
def __init__(self, field_name):
self.field_name = field_name
def parse(self, tf_example):
return "".join(tf_example.features.feature[self.field_name]
.bytes_list.value) if tf_example.features.feature[
self.field_name].HasField("bytes_list") else None
class Int64Parser(data_parser.DataToNumpyParser):
"""Tensorflow Example int64 parser."""
def __init__(self, field_name):
self.field_name = field_name
def parse(self, tf_example):
return np.array(
tf_example.features.feature[self.field_name].int64_list.value,
dtype=np.int64).transpose() if tf_example.features.feature[
self.field_name].HasField("int64_list") else None
class BoundingBoxParser(data_parser.DataToNumpyParser):
"""Tensorflow Example bounding box parser."""
def __init__(self, xmin_field_name, ymin_field_name, xmax_field_name,
ymax_field_name):
self.field_names = [
ymin_field_name, xmin_field_name, ymax_field_name, xmax_field_name
]
def parse(self, tf_example):
result = []
parsed = True
for field_name in self.field_names:
result.append(tf_example.features.feature[field_name].float_list.value)
parsed &= (
tf_example.features.feature[field_name].HasField("float_list"))
return np.array(result).transpose() if parsed else None
class TfExampleDetectionAndGTParser(data_parser.DataToNumpyParser):
"""Tensorflow Example proto parser."""
def __init__(self):
self.items_to_handlers = {
fields.DetectionResultFields.key:
StringParser(fields.TfExampleFields.source_id),
# Object ground truth boxes and classes.
fields.InputDataFields.groundtruth_boxes: (BoundingBoxParser(
fields.TfExampleFields.object_bbox_xmin,
fields.TfExampleFields.object_bbox_ymin,
fields.TfExampleFields.object_bbox_xmax,
fields.TfExampleFields.object_bbox_ymax)),
fields.InputDataFields.groundtruth_classes: (
Int64Parser(fields.TfExampleFields.object_class_label)),
# Object detections.
fields.DetectionResultFields.detection_boxes: (BoundingBoxParser(
fields.TfExampleFields.detection_bbox_xmin,
fields.TfExampleFields.detection_bbox_ymin,
fields.TfExampleFields.detection_bbox_xmax,
fields.TfExampleFields.detection_bbox_ymax)),
fields.DetectionResultFields.detection_classes: (
Int64Parser(fields.TfExampleFields.detection_class_label)),
fields.DetectionResultFields.detection_scores: (
FloatParser(fields.TfExampleFields.detection_score)),
}
self.optional_items_to_handlers = {
fields.InputDataFields.groundtruth_difficult:
Int64Parser(fields.TfExampleFields.object_difficult),
fields.InputDataFields.groundtruth_group_of:
Int64Parser(fields.TfExampleFields.object_group_of),
fields.InputDataFields.groundtruth_image_classes:
Int64Parser(fields.TfExampleFields.image_class_label),
}
def parse(self, tf_example):
"""Parses tensorflow example and returns a tensor dictionary.
Args:
tf_example: a tf.Example object.
Returns:
A dictionary of the following numpy arrays:
fields.DetectionResultFields.source_id - string containing original image
id.
fields.InputDataFields.groundtruth_boxes - a numpy array containing
groundtruth boxes.
fields.InputDataFields.groundtruth_classes - a numpy array containing
groundtruth classes.
fields.InputDataFields.groundtruth_group_of - a numpy array containing
groundtruth group of flag (optional, None if not specified).
fields.InputDataFields.groundtruth_difficult - a numpy array containing
groundtruth difficult flag (optional, None if not specified).
fields.InputDataFields.groundtruth_image_classes - a numpy array
containing groundtruth image-level labels.
fields.DetectionResultFields.detection_boxes - a numpy array containing
detection boxes.
fields.DetectionResultFields.detection_classes - a numpy array containing
detection class labels.
fields.DetectionResultFields.detection_scores - a numpy array containing
detection scores.
Returns None if tf.Example was not parsed or non-optional fields were not
found.
"""
results_dict = {}
parsed = True
for key, parser in self.items_to_handlers.items():
results_dict[key] = parser.parse(tf_example)
parsed &= (results_dict[key] is not None)
for key, parser in self.optional_items_to_handlers.items():
results_dict[key] = parser.parse(tf_example)
return results_dict if parsed else None
| [
"syq132@live.com"
] | syq132@live.com |
94d174ed0e5896823a43d4869acc725f51bd70f3 | e306eb3fc110dee0e3f5e68eb375c55704b3642f | /personel_portfolio/urls.py | 3a0c2409023554b1730c7ac42d3244152c9166dd | [] | no_license | Yeet2006/personel-potfolio | 446cc22f7a678b64aa6a01267878d9ebff5c41e3 | 9ecbfc58504654cb043aedffddc44e3b13cd6db9 | refs/heads/main | 2023-01-28T11:42:27.880185 | 2020-12-14T13:48:38 | 2020-12-14T13:48:38 | 321,355,428 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,035 | py | """personel_portfolio URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from portfolio import views
urlpatterns = [
path('admin/', admin.site.urls),
path('' , views.home , name='home'),
path('blog/', include('blog.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root =settings.MEDIA_ROOT)
| [
"yeetkamakazi@gmail.com"
] | yeetkamakazi@gmail.com |
cdccf29b8a2c7760740db2afacb752d2876105f2 | f8bc86843e8904404940fb37d1b153e8aa28e180 | /crop_microstructure.py | 0eef73b0e1399d28ec813e90d7913b8e16356ebd | [] | no_license | pkarira/Cascade | 621ad8ee20825ca1cd77bbebd7e9be1917e49ab0 | d32d77f78131e158092225d9df16ef6ef161137d | refs/heads/master | 2020-04-26T09:31:53.286493 | 2019-04-09T11:36:14 | 2019-04-09T11:36:14 | 173,458,734 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,058 | py | import glob
import numpy as np
from skimage.io import imread, imsave
import os
def quad_crop(image, w=224):
""" crop out four panels from the center of the image """
labels = np.array([['UL', 'UR'], ['LL', 'LR']])
center = (np.array(image.shape) / 2).astype(int)
x, y = center
crops = []
for idx in (0,1):
xmin = x - (w * ((1-idx)%2))
xmax = x + (w * (idx%2))
for idy in (0,1):
ymin = y - (w * ((1-idy)%2))
ymax = y + (w * (idy%2))
crop = image[xmin:xmax,ymin:ymax]
crops.append((labels[idx,idy], crop))
return crops
def side_center_crop(image,w=224):
labels = np.array([['UL', 'UR'], ['LL', 'LR']])
size = np.array(image.shape).astype(int)
x, y = size
crops = []
crop = image[0:w,0:w]
crops.append(('UL', crop))
crop = image[x-w:,0:w]
crops.append(('UR',crop))
crop = image[0:w,y-w:]
crops.append(('LL',crop))
crop = image[x-w:,y-w:]
crops.append(('LR',crop))
center = (np.array(image.shape) / 2).astype(int)
x, y = center
crop = image[x-w/2:x+w/2,y-w/2:y+w/2]
crops.append(('CC', crop))
return crops
def single_crop(image, w=224):
center = (np.array(image.shape) / 2).astype(int)
x, y = center
crops = []
print x-w/2
print x+w/2
print y-w/2
print y+w/2
crop = image[x-w/2:x+w/2,y-w/2:y+w/2]
crops.append(('CC', crop))
return crops
def cropper():
paths = glob.glob('data/micrographs_new/*')
#cropping given image into 4 sub -images
for path in paths:
# print('cropping {}'.format(path))
prefix, ext = os.path.splitext(os.path.basename(path))
image = imread(path, as_grey=True)
if image.shape[0]<448 or image.shape[1]<448:
crops = side_center_crop(image)
else:
crops = quad_crop(image)
for label, crop in crops:
dest = '{}-crop{}.tif'.format(prefix, label)
dest = os.path.join('data/crops_new', dest)
imsave(dest, crop) | [
"pulkit5208@gmail.com"
] | pulkit5208@gmail.com |
94a6049bd0b29f745ad759a26578f79218888ef5 | b25f9a671d57616d359ed1885fc7c96009af0984 | /uuv_control/uuv_trajectory_control/src/uuv_control_interfaces/dp_pid_controller_base.py | af563bdb5a244caf02552b74f7d33d880de65750 | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | AbdelazizAssem/VAUV-simulator | 8bb55c6e59307efdf2d27dd8dead348cb354e486 | 1ef4078de239a05fbdb050cc64e735897a31b3b7 | refs/heads/main | 2023-04-03T23:45:36.803280 | 2021-04-11T19:02:27 | 2021-04-11T19:02:27 | 356,694,933 | 0 | 0 | Apache-2.0 | 2021-04-10T21:07:56 | 2021-04-10T21:07:56 | null | UTF-8 | Python | false | false | 5,539 | py | # Copyright (c) 2020 The Plankton Authors.
# All rights reserved.
#
# This source code is derived from UUV Simulator
# (https://github.com/uuvsimulator/uuv_simulator)
# Copyright (c) 2016-2019 The UUV Simulator Authors
# licensed under the Apache license, Version 2.0
# cf. 3rd-party-licenses.txt file in the root directory of this source tree.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import rclpy
from uuv_control_msgs.srv import *
from .dp_controller_base import DPControllerBase
class DPPIDControllerBase(DPControllerBase):
"""Abstract class for PID-based controllers. The base
class method `update_controller` must be overridden
in other for a controller to work.
"""
def __init__(self, node_name, *args, **kwargs):
#super().__init__(node_name)
# Start the super class
DPControllerBase.__init__(self, node_name, *args, **kwargs)
self._logger.info('Initializing: PID controller')
# Proportional gains
self._Kp = np.zeros(shape=(6, 6))
# Derivative gains
self._Kd = np.zeros(shape=(6, 6))
# Integral gains
self._Ki = np.zeros(shape=(6, 6))
# Integrator component
self._int = np.zeros(6)
# Error for the vehicle pose
self._error_pose = np.zeros(6)
if self.has_parameter('Kp'):
# Use 'value' in case int values are specified instead of double
Kp_diag = self.get_parameter('Kp').value
if len(Kp_diag) == 6:
self._Kp = np.diag(Kp_diag)
else:
raise RuntimeError('Kp matrix error: 6 coefficients '
'needed')
self._logger.info('Kp=' + str([self._Kp[i, i] for i in range(6)]))
if self.has_parameter('Kd'):
Kd_diag = self.get_parameter('Kd').value
if len(Kd_diag) == 6:
self._Kd = np.diag(Kd_diag)
else:
raise RuntimeError('Kd matrix error: 6 coefficients '
'needed')
self._logger.info('Kd=' + str([self._Kd[i, i] for i in range(6)]))
if self.has_parameter('Ki'):
Ki_diag = self.get_parameter('Ki').value
if len(Ki_diag) == 6:
self._Ki = np.diag(Ki_diag)
else:
raise RuntimeError('Ki matrix error: 6 coefficients '
'needed')
self._logger.info('Ki=' + str([self._Ki[i, i] for i in range(6)]))
self._services['set_pid_params'] = self.create_service(
SetPIDParams,
'set_pid_params',
self.set_pid_params_callback)
self._services['get_pid_params'] = self.create_service(
GetPIDParams,
'get_pid_params',
self.get_pid_params_callback)
self._logger.info('PID controller ready!')
# =========================================================================
def _reset_controller(self):
"""Reset reference and and error vectors."""
super(DPPIDControllerBase, self)._reset_controller()
self._error_pose = np.zeros(6)
self._int = np.zeros(6)
# =========================================================================
def set_pid_params_callback(self, request, response):
"""Service callback function to set the
PID's parameters
"""
kp = request.kp
kd = request.kd
ki = request.ki
if len(kp) != 6 or len(kd) != 6 or len(ki) != 6:
response.success = False
return response
self._Kp = np.diag(kp)
self._Ki = np.diag(ki)
self._Kd = np.diag(kd)
response.success = True
return response
# =========================================================================
def get_pid_params_callback(self, request, response):
"""Service callback function to return
the PID's parameters
"""
response.kp = [self._Kp[i, i] for i in range(6)]
response.kd = [self._Kd[i, i] for i in range(6)]
response.ki = [self._Ki[i, i] for i in range(6)]
return response
# =========================================================================
def update_pid(self):
"""Return the control signal computed from the PID
algorithm. To implement a PID-based controller that
inherits this class, call this function in the
derived class' `update` method to obtain the control
vector.
> *Returns*
`numpy.array`: Control signal
"""
if not self.odom_is_init:
return
# Update integrator
self._int += 0.5 * (self.error_pose_euler + self._error_pose) * self._dt
# Store current pose error
self._error_pose = self.error_pose_euler
return np.dot(self._Kp, self.error_pose_euler) \
+ np.dot(self._Kd, self._errors['vel']) \
+ np.dot(self._Ki, self._int)
| [
"engibrahimhabib@gmail.com"
] | engibrahimhabib@gmail.com |
36e77a80aeb9667fa8fbfe256dc23efc4a5d068a | 4637dcdfbfa4eeaefaa9c2ffc5e537ab21171fff | /main.py | 9a4f557401b411bd11c83084e9fda8003013177f | [
"MIT"
] | permissive | gabriel-farache/homautomation | 98321a2c6ddc8ead60a6cc89a7917619a5743fdb | c2bd6a18deb2699242d543bc0eeaf386c2b6296a | refs/heads/master | 2020-04-06T07:57:21.459828 | 2018-02-25T17:02:30 | 2018-02-25T17:02:30 | 64,056,793 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 605 | py | # main.py -- put your code here!
import pycom
import time
import sendData
from machine import RTC
pycom.heartbeat(False)
try:
sendData.connectLocalBox('/flash/config.json')
rtc = RTC()
rtc.ntp_sync('fr.pool.ntp.org')
pycom.rgbled(0x00FF00)
time.sleep(0.2)
pycom.rgbled(0)
time.sleep(0.2)
pycom.rgbled(0x00FF00)
time.sleep(0.2)
pycom.rgbled(0)
except Exception as e:
print(e)
pycom.rgbled(0xFF0000)
time.sleep(0.2)
pycom.rgbled(0)
time.sleep(0.2)
pycom.rgbled(0xFF0000)
time.sleep(0.2)
pycom.rgbled(0)
| [
"gabi.matamu@gmail.com"
] | gabi.matamu@gmail.com |
d83ff9d35756aa203096778316d1f1840a266b4c | d9f6f439300d298246c37ccfb881e8e8af4fda22 | /cfp/migrations/0021_profile_name.py | 814cb2ed2021c677ece96c65e1671b44cb2a0824 | [
"MIT"
] | permissive | ajlozier/speakers | e62b8d346a58a034998860d1b42a38b00cbdbd23 | d7d87c99b1cfa5f9df5455f737385115d9d5279c | refs/heads/master | 2021-09-08T19:33:08.894305 | 2018-03-12T00:54:10 | 2018-03-12T00:54:10 | 122,101,157 | 0 | 0 | null | 2018-02-19T18:08:18 | 2018-02-19T18:08:18 | null | UTF-8 | Python | false | false | 444 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('cfp', '0020_auto_20150218_0802'),
]
operations = [
migrations.AddField(
model_name='profile',
name='name',
field=models.CharField(max_length=300, default=''),
preserve_default=False,
),
]
| [
"kyle@kyleconroy.com"
] | kyle@kyleconroy.com |
07956246e6818d61ad5c4214d016aa49af201c8e | 58185d7c1684d4ed78fdf7702578d88f9fe97c0c | /nires/dez.py | 70a5ddfb5ab71797593fc7f25630f46725639734 | [] | no_license | jmel/NIRES | 51a6086e590833fd3d4bf8bb22db9a712891027b | fbd62ac18412595924c537e54e160a8721fd509e | refs/heads/master | 2021-01-21T04:35:14.098096 | 2016-07-08T17:20:12 | 2016-07-08T17:20:12 | 11,027,957 | 0 | 0 | null | 2016-07-08T17:20:13 | 2013-06-28T14:12:46 | Python | UTF-8 | Python | false | false | 2,340 | py | #!/usr/bin/env python
# Take difference between two fits files
import sys
import numpy
import readcol as rc
import pyfits as pf
import string
import ds9
import globals
z = sys.argv[1]
unit = open(globals.calibrationpath + 'z_emission.reg','w')
wsol = pf.open(globals.calibrationpath + 'tspec_wavesol.fits')[0].data
sz=wsol.shape
unit.write('# Region file format: DS9 version 4.1\n')
unit.write('# Filename: zregion.reg\n')
unit.write('global color=black dashlist=8 3 width=3 font="helvetica 14 bold" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\n')
unit.write('physical\n')
try:
id,pd,llist=rc.readcol(globals.calibrationpath + 'emissionLineList.dat',names=False,twod=False,fsep=",")
names,(ord,xx,yy,lam)=rc.readcol(globals.calibrationpath + 'tspec_wavelength_file.dat',names=True,twod=False)
z=float(z)
lam=lam/(1.+z)
id=id.tolist()
lam=lam.tolist()
print id
print lam
m=max(lam)
llist2=[i for i in llist if i < m]
print llist2
r1=range(0,len(llist2))
r2=range(0,len(lam))
jtest=True
for i in r1:
jtest=True
for j in r2:
if (lam[j] > llist2[i] -0.0005) and (lam[j] < llist2[i] +0.0005):
if jtest:
s='line(%d,%d,%d,%d) # line=0 0\n' % (xx[j],yy[j]+90,xx[j],yy[j]+80)
unit.write(s)
s2='# text(%d,%d) text={%s}\n' % (xx[j],yy[j]+110,pd[i])
unit.write(s2)
jtest=False
else:
jtest=True
'''r1=range(0,sz[0])
r1.reverse()
r2=range(0,sz[1])
r2.reverse()
for i in r1:
for j in r2:
c=0
for ll in lam:
if (wsol[i,j] > ll -0.0005) and (wsol[i,j] < ll +0.0005):
print i,j,ll,wsol[i,j]
s='line(%d,%d,%d,%d) # line=0 0\n' % (j,i-80,j,i-60)
print s
unit.write(s)
s2='# text(%d,%d) text={%s}\n' % (j,i-90,id[c])
unit.write(s2)
lam.pop(c)
id.pop(c)
c=c+1'''
except:
print "did not work"
unit.close()
try:
DD=0
DD=ds9.ds9("Spectrograph")
DD.emissiondisp()
except:
print "could not display \n"
| [
"jason.melbourne@gmail.com"
] | jason.melbourne@gmail.com |
cfa3e6dd807a8829414f580e7847edd533b53527 | dfee236b3f4bf66e52d50b0226b7773a745d8d34 | /structure/validator.py | 21f68f8c5d9deec430c12ffe98c0d815eb8bb1ca | [
"MIT"
] | permissive | ayush5harma/ECS-Hiring-Challenge | 43409aadf69d58addd9ffd8818b30adaff4eb20f | ccab72645026c311aee74ac68c69503d187740ff | refs/heads/main | 2023-08-06T06:23:36.939623 | 2021-09-23T20:12:43 | 2021-09-23T20:12:43 | 352,643,716 | 0 | 0 | null | 2021-09-23T20:12:43 | 2021-03-29T12:57:40 | PowerShell | UTF-8 | Python | false | false | 914 | py | from marshmallow import Schema, fields
from marshmallow.validate import Length
class DataModel(Schema):
""" /api/note - POST
Parameters:
- title (str)
- note (str)
- user_id (int)
- time_created (time)
"""
title = fields.Str(required=True, error_messages={
"required": "title is required."},
validate=Length(max=100, min=5))
image_path = fields.Str(required=False, validate=Length(max=100))
description = fields.Str(required=False, validate=Length(max=255))
discount_price = fields.Int(required=True, error_messages={
"required": "discount_price is required."})
price = fields.Int(required=True, error_messages={
"required": "price is required."})
on_discount = fields.Boolean(required=True, error_messages={
"required": "on_discount is required."})
id = fields.Int(required=False)
| [
"47772616+ayush5harma@users.noreply.github.com"
] | 47772616+ayush5harma@users.noreply.github.com |
e5d51b840f9d3e61bbf612efe4cb4e6c26e84ce6 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/nouns/_actor.py | 04e32c50a329bba627e107500de9e8bd1c6b493f | [
"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 | 386 | py |
#calss header
class _ACTOR():
def __init__(self,):
self.name = "ACTOR"
self.definitions = [u'someone who pretends to be someone else while performing in a film, play, or television or radio programme: ']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'nouns'
def run(self, obj1 = [], obj2 = []):
return self.jsondata
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
1a89d48503fba5a5f596dc365fc645417e63c887 | 77311ad9622a7d8b88707d7cee3f44de7c8860cb | /res/scripts/client/gui/scaleform/battle.py | cb3cb78844254b812459a7a4b3f4ed98dac52a20 | [] | no_license | webiumsk/WOT-0.9.14-CT | 9b193191505a4560df4e872e022eebf59308057e | cfe0b03e511d02c36ce185f308eb48f13ecc05ca | refs/heads/master | 2021-01-10T02:14:10.830715 | 2016-02-14T11:59:59 | 2016-02-14T11:59:59 | 51,606,676 | 0 | 0 | null | null | null | null | WINDOWS-1250 | Python | false | false | 39,654 | py | # 2016.02.14 12:38:27 Střední Evropa (běžný čas)
# Embedded file name: scripts/client/gui/Scaleform/Battle.py
import weakref
import BigWorld
import GUI
import Math
import SoundGroups
import VOIP
import constants
import BattleReplay
import CommandMapping
from ConnectionManager import connectionManager
from account_helpers.settings_core.SettingsCore import g_settingsCore
from gui.Scaleform.LogitechMonitor import LogitechMonitor
from gui.Scaleform.daapi.view.battle.damage_info_panel import VehicleDamageInfoPanel
from gui.Scaleform.daapi.view.battle.gas_attack import GasAttackPlugin
from gui.Scaleform.daapi.view.battle.repair_timer import RepairTimerPlugin
from gui.Scaleform.daapi.view.battle.resource_points import ResourcePointsPlugin
from gui.Scaleform.daapi.view.battle.respawn_view import RespawnViewPlugin
from gui.Scaleform.daapi.view.battle.PlayersPanelsSwitcher import PlayersPanelsSwitcher
from gui.Scaleform.daapi.view.battle.RadialMenu import RadialMenu
from gui.Scaleform.daapi.view.battle.flag_notification import FlagNotificationPlugin
from gui.Scaleform.daapi.view.battle.players_panel import playersPanelFactory
from gui.Scaleform.daapi.view.battle.score_panel import scorePanelFactory
from gui.Scaleform.daapi.view.battle.ConsumablesPanel import ConsumablesPanel
from gui.Scaleform.daapi.view.battle.BattleRibbonsPanel import BattleRibbonsPanel
from gui.Scaleform.daapi.view.battle.TimersBar import TimersBar
from gui.Scaleform.daapi.view.battle.damage_panel import DamagePanel
from gui.Scaleform.daapi.view.battle.indicators import IndicatorsCollection
from gui.Scaleform.daapi.view.battle.messages import PlayerMessages, VehicleErrorMessages, VehicleMessages
from gui.Scaleform.daapi.view.battle.stats_form import statsFormFactory
from gui.Scaleform.daapi.view.battle.teams_bases_panel import TeamBasesPanel
from gui.Scaleform.daapi.view.battle.markers import MarkersManager
from gui.Scaleform.daapi.view.lobby.ReportBug import makeHyperLink, reportBugOpenConfirm
from gui.Scaleform.locale.ARENAS import ARENAS
from gui.Scaleform.locale.INGAME_GUI import INGAME_GUI
from gui.Scaleform.locale.MENU import MENU
import gui
from gui.battle_control import g_sessionProvider
from gui.battle_control.DynSquadViewListener import DynSquadViewListener, RecordDynSquadViewListener, ReplayDynSquadViewListener
from gui.battle_control.battle_arena_ctrl import battleArenaControllerFactory
from gui.battle_control.battle_constants import VEHICLE_VIEW_STATE
from gui.prb_control.formatters import getPrebattleFullDescription
from gui.shared import g_eventBus, events, EVENT_BUS_SCOPE
from gui.shared.formatters import text_styles
from gui.shared.utils.TimeInterval import TimeInterval
from gui.shared.utils.plugins import PluginsCollection
from messenger import MessengerEntry
from windows import BattleWindow
from SettingsInterface import SettingsInterface
from debug_utils import LOG_DEBUG, LOG_ERROR
from helpers import i18n, isPlayerAvatar
from gui import DEPTH_OF_Battle, GUI_SETTINGS, g_tankActiveCamouflage, g_guiResetters, g_repeatKeyHandlers, game_control
from gui.LobbyContext import g_lobbyContext
from gui.Scaleform import VoiceChatInterface, ColorSchemeManager, getNecessaryArenaFrameName
from gui.Scaleform.SoundManager import SoundManager
from gui.shared.denunciator import BattleDenunciator
from gui.shared.utils import toUpper
from gui.shared.utils.functions import makeTooltip, getArenaSubTypeName, isBaseExists, getBattleSubTypeWinText
from gui.Scaleform.windows import UIInterface
from gui.Scaleform.MovingText import MovingText
from gui.Scaleform.Minimap import Minimap
from gui.Scaleform.CursorDelegator import g_cursorDelegator
from gui.Scaleform.ingame_help import IngameHelp
from gui.Scaleform import SCALEFORM_SWF_PATH
from gui.battle_control.arena_info import getArenaIcon, hasFlags, hasRespawns, hasResourcePoints, isFalloutMultiTeam, hasRepairPoints, isFalloutBattle, hasGasAttack
from gui.battle_control import avatar_getter
def _isVehicleEntity(entity):
import Vehicle
return isinstance(entity, Vehicle.Vehicle)
def _getQuestsTipData(arena, arenaDP):
pqTipData = [None] * 3
serverSettings = g_lobbyContext.getServerSettings()
isPQEnabled = serverSettings is not None and serverSettings.isPotapovQuestEnabled()
if isPQEnabled and (arena.guiType == constants.ARENA_GUI_TYPE.RANDOM or arena.guiType == constants.ARENA_GUI_TYPE.TRAINING and constants.IS_DEVELOPMENT or isFalloutBattle()):
vehInfo = arenaDP.getVehicleInfo(arenaDP.getPlayerVehicleID(forceUpdate=True))
if isFalloutBattle():
pQuests = vehInfo.player.getFalloutPotapovQuests()
else:
pQuests = vehInfo.player.getRandomPotapovQuests()
if len(pQuests):
quest = pQuests[0]
pqTipData = [quest.getUserName(), _getQuestConditionsMessage(INGAME_GUI.POTAPOVQUESTS_TIP_MAINHEADER, quest.getUserMainCondition()), _getQuestConditionsMessage(INGAME_GUI.POTAPOVQUESTS_TIP_ADDITIONALHEADER, quest.getUserAddCondition())]
else:
pqTipData = [i18n.makeString(INGAME_GUI.POTAPOVQUESTS_TIP_NOQUESTS_BATTLETYPE if isFalloutBattle() else INGAME_GUI.POTAPOVQUESTS_TIP_NOQUESTS_VEHICLETYPE), None, None]
return pqTipData
def _getQuestConditionsMessage(header, text):
return i18n.makeString(text_styles.middleTitle(header) + '\n' + text_styles.main(text))
_CONTOUR_ICONS_MASK = '../maps/icons/vehicle/contour/%(unicName)s.png'
_SMALL_MAP_SOURCE = '../maps/icons/map/battleLoading/%s.png'
_SCOPE = EVENT_BUS_SCOPE.BATTLE
class Battle(BattleWindow):
teamBasesPanel = property(lambda self: self.__teamBasesPanel)
timersBar = property(lambda self: self.__timersBar)
consumablesPanel = property(lambda self: self.__consumablesPanel)
damagePanel = property(lambda self: self.__damagePanel)
markersManager = property(lambda self: self.__markersManager)
vErrorsPanel = property(lambda self: self.__vErrorsPanel)
vMsgsPanel = property(lambda self: self.__vMsgsPanel)
pMsgsPanel = property(lambda self: self.__pMsgsPanel)
minimap = property(lambda self: self.__minimap)
radialMenu = property(lambda self: self.__radialMenu)
damageInfoPanel = property(lambda self: self.__damageInfoPanel)
fragCorrelation = property(lambda self: self.__fragCorrelation)
statsForm = property(lambda self: self.__statsForm)
leftPlayersPanel = property(lambda self: self.__leftPlayersPanel)
rightPlayersPanel = property(lambda self: self.__rightPlayersPanel)
ribbonsPanel = property(lambda self: self.__ribbonsPanel)
ppSwitcher = property(lambda self: self.__ppSwitcher)
indicators = property(lambda self: self.__indicators)
VEHICLE_DESTROY_TIMER = {'ALL': 'all',
constants.VEHICLE_MISC_STATUS.VEHICLE_DROWN_WARNING: 'drown',
constants.VEHICLE_MISC_STATUS.VEHICLE_IS_OVERTURNED: 'overturn'}
VEHICLE_DEATHZONE_TIMER = {'ALL': 'all',
constants.DEATH_ZONES.STATIC: 'death_zone',
constants.DEATH_ZONES.GAS_ATTACK: 'gas_attack'}
VEHICLE_DEATHZONE_TIMER_SOUND = {constants.DEATH_ZONES.GAS_ATTACK: ({'warning': 'fallout_gaz_sphere_warning',
'critical': 'fallout_gaz_sphere_timer'}, {'warning': '/GUI/fallout/fallout_gaz_sphere_warning',
'critical': '/GUI/fallout/fallout_gaz_sphere_timer'})}
__cameraVehicleID = -1
__stateHandlers = {VEHICLE_VIEW_STATE.FIRE: '_setFireInVehicle',
VEHICLE_VIEW_STATE.SHOW_DESTROY_TIMER: '_showVehicleTimer',
VEHICLE_VIEW_STATE.HIDE_DESTROY_TIMER: '_hideVehicleTimer',
VEHICLE_VIEW_STATE.SHOW_DEATHZONE_TIMER: 'showDeathzoneTimer',
VEHICLE_VIEW_STATE.HIDE_DEATHZONE_TIMER: 'hideDeathzoneTimer',
VEHICLE_VIEW_STATE.OBSERVED_BY_ENEMY: '_showSixthSenseIndicator'}
def __init__(self, appNS):
self.__ns = appNS
self.__soundManager = None
self.__arena = BigWorld.player().arena
self.__plugins = PluginsCollection(self)
plugins = {}
if hasFlags():
plugins['flagNotification'] = FlagNotificationPlugin
if hasRepairPoints():
plugins['repairTimer'] = RepairTimerPlugin
if hasRespawns() and (constants.IS_DEVELOPMENT or not BattleReplay.g_replayCtrl.isPlaying):
plugins['respawnView'] = RespawnViewPlugin
if hasResourcePoints():
plugins['resources'] = ResourcePointsPlugin
if hasGasAttack():
plugins['gasAttack'] = GasAttackPlugin
self.__plugins.addPlugins(plugins)
self.__denunciator = BattleDenunciator()
self.__timerSounds = {}
for timer, sounds in self.VEHICLE_DEATHZONE_TIMER_SOUND.iteritems():
self.__timerSounds[timer] = {}
for level, sound in sounds[False].iteritems():
self.__timerSounds[timer][level] = SoundGroups.g_instance.getSound2D(sound)
self.__timerSound = None
BattleWindow.__init__(self, 'battle.swf')
self.__isHelpWindowShown = False
self.__cameraMode = None
self.component.wg_inputKeyMode = 1
self.component.position.z = DEPTH_OF_Battle
self.movie.backgroundAlpha = 0
self.addFsCallbacks({'battle.leave': self.onExitBattle})
self.addExternalCallbacks({'battle.showCursor': self.cursorVisibility,
'battle.tryLeaveRequest': self.tryLeaveRequest,
'battle.populateFragCorrelationBar': self.populateFragCorrelationBar,
'Battle.UsersRoster.Appeal': self.onDenunciationReceived,
'Battle.selectPlayer': self.selectPlayer,
'battle.helpDialogOpenStatus': self.helpDialogOpenStatus,
'battle.initLobbyDialog': self._initLobbyDialog,
'battle.reportBug': self.reportBug})
self.__dynSquadListener = None
BigWorld.wg_setRedefineKeysMode(False)
self.onPostmortemVehicleChanged(BigWorld.player().playerVehicleID)
return
@property
def appNS(self):
return self.__ns
@property
def soundManager(self):
return self.__soundManager
def attachCursor(self):
return g_cursorDelegator.activateCursor()
def detachCursor(self):
return g_cursorDelegator.detachCursor()
def getRoot(self):
return self.__battle_flashObject
def getCameraVehicleID(self):
return self.__cameraVehicleID
def populateFragCorrelationBar(self, _):
if self.__fragCorrelation is not None:
self.__fragCorrelation.populate()
return
def showAll(self, event):
self.call('battle.showAll', [event.ctx['visible']])
def showCursor(self, isShow):
self.cursorVisibility(-1, isShow)
def selectPlayer(self, cid, vehId):
player = BigWorld.player()
if isPlayerAvatar():
player.selectPlayer(int(vehId))
def onDenunciationReceived(self, _, uid, userName, topic):
self.__denunciator.makeAppeal(uid, userName, topic)
self.__arenaCtrl.invalidateGUI()
def onPostmortemVehicleChanged(self, id):
if self.__cameraVehicleID == id:
return
else:
self.__cameraVehicleID = id
self.__arenaCtrl.invalidateGUI(not g_sessionProvider.getCtx().isPlayerObserver())
g_sessionProvider.getVehicleStateCtrl().switchToAnother(id)
self._hideVehicleTimer('ALL')
self.hideDeathzoneTimer('ALL')
self.__vErrorsPanel.clear()
self.__vMsgsPanel.clear()
aim = BigWorld.player().inputHandler.aim
if aim is not None:
aim.updateAmmoState(True)
return
def onCameraChanged(self, cameraMode, curVehID = None):
LOG_DEBUG('onCameraChanged', cameraMode, curVehID)
if self.__cameraMode == 'mapcase':
self.setAimingMode(False)
elif cameraMode == 'mapcase':
self.setAimingMode(True)
self.__cameraMode = cameraMode
def setVisible(cname):
m = self.getMember(cname)
if m is not None:
m.visible = cameraMode != 'video'
return
if self.__isGuiShown():
self.damagePanel.showAll(cameraMode != 'video')
setVisible('vehicleErrorsPanel')
if cameraMode == 'video':
self.__cameraVehicleID = -1
self.__vErrorsPanel.clear()
self.__vMsgsPanel.clear()
self._hideVehicleTimer('ALL')
self.hideDeathzoneTimer('ALL')
aim = BigWorld.player().inputHandler.aim
if aim is not None:
aim.updateAmmoState(True)
aim = BigWorld.player().inputHandler.aim
if aim is not None:
aim.onCameraChange()
return
def __isGuiShown(self):
m = self.getMember('_root')
if m is not None and callable(m.isGuiVisible):
return m.isGuiVisible()
else:
return False
def _showVehicleTimer(self, value):
code, time, warnLvl = value
LOG_DEBUG('show vehicles destroy timer', code, time, warnLvl)
self.call('destroyTimer.show', [self.VEHICLE_DESTROY_TIMER[code], time, warnLvl])
def _hideVehicleTimer(self, code = None):
LOG_DEBUG('hide vehicles destroy timer', code)
if code is None:
code = 'ALL'
self.call('destroyTimer.hide', [self.VEHICLE_DESTROY_TIMER[code]])
return
def showDeathzoneTimer(self, value):
zoneID, time, warnLvl = value
if self.__timerSound is not None:
self.__timerSound.stop()
self.__timerSound = None
sound = self.__timerSounds.get(zoneID, {}).get(warnLvl)
if sound is not None:
self.__timerSound = sound
self.__timerSound.play()
LOG_DEBUG('show vehicles deathzone timer', zoneID, time, warnLvl)
self.call('destroyTimer.show', [self.VEHICLE_DEATHZONE_TIMER[zoneID], time, warnLvl])
return
def hideDeathzoneTimer(self, zoneID = None):
if self.__timerSound is not None:
self.__timerSound.stop()
self.__timerSound = None
if zoneID is None:
zoneID = 'ALL'
LOG_DEBUG('hide vehicles deathzone timer', zoneID)
self.call('destroyTimer.hide', [self.VEHICLE_DEATHZONE_TIMER[zoneID]])
return
def _showSixthSenseIndicator(self, isShow):
self.call('sixthSenseIndicator.show', [isShow])
def setVisible(self, bool):
LOG_DEBUG('[Battle] visible', bool)
self.component.visible = bool
def afterCreate(self):
event = events.AppLifeCycleEvent
g_eventBus.handleEvent(event(self.__ns, event.INITIALIZING))
player = BigWorld.player()
voice = VoiceChatInterface.g_instance
LOG_DEBUG('[Battle] afterCreate')
setattr(self.movie, '_global.wg_isShowLanguageBar', GUI_SETTINGS.isShowLanguageBar)
setattr(self.movie, '_global.wg_isShowServerStats', constants.IS_SHOW_SERVER_STATS)
setattr(self.movie, '_global.wg_isShowVoiceChat', GUI_SETTINGS.voiceChat)
setattr(self.movie, '_global.wg_voiceChatProvider', voice.voiceChatProvider)
setattr(self.movie, '_global.wg_isChina', constants.IS_CHINA)
setattr(self.movie, '_global.wg_isKorea', constants.IS_KOREA)
setattr(self.movie, '_global.wg_isReplayPlaying', BattleReplay.g_replayCtrl.isPlaying)
BattleWindow.afterCreate(self)
addListener = g_eventBus.addListener
addListener(events.GameEvent.HELP, self.toggleHelpWindow, scope=_SCOPE)
addListener(events.GameEvent.GUI_VISIBILITY, self.showAll, scope=_SCOPE)
player.inputHandler.onPostmortemVehicleChanged += self.onPostmortemVehicleChanged
player.inputHandler.onCameraChanged += self.onCameraChanged
g_settingsCore.onSettingsChanged += self.__accs_onSettingsChanged
g_settingsCore.interfaceScale.onScaleChanged += self.__onRecreateDevice
isMutlipleTeams = isFalloutMultiTeam()
isFallout = isFalloutBattle()
self.proxy = weakref.proxy(self)
self.__battle_flashObject = self.proxy.getMember('_level0')
if self.__battle_flashObject:
self.__battle_flashObject.resync()
voice.populateUI(self.proxy)
voice.onPlayerSpeaking += self.setPlayerSpeaking
voice.onVoiceChatInitFailed += self.onVoiceChatInitFailed
self.colorManager = ColorSchemeManager._ColorSchemeManager()
self.colorManager.populateUI(self.proxy)
self.movingText = MovingText()
self.movingText.populateUI(self.proxy)
self.__settingsInterface = SettingsInterface()
self.__settingsInterface.populateUI(self.proxy)
self.__soundManager = SoundManager()
self.__soundManager.populateUI(self.proxy)
self.__timersBar = TimersBar(self.proxy, isFallout)
self.__teamBasesPanel = TeamBasesPanel(self.proxy)
self.__debugPanel = DebugPanel(self.proxy)
self.__consumablesPanel = ConsumablesPanel(self.proxy)
self.__damagePanel = DamagePanel(self.proxy)
self.__markersManager = MarkersManager(self.proxy)
self.__ingameHelp = IngameHelp(self.proxy)
self.__minimap = Minimap(self.proxy)
self.__radialMenu = RadialMenu(self.proxy)
self.__ribbonsPanel = BattleRibbonsPanel(self.proxy)
self.__indicators = IndicatorsCollection()
self.__ppSwitcher = PlayersPanelsSwitcher(self.proxy)
isColorBlind = g_settingsCore.getSetting('isColorBlind')
self.__leftPlayersPanel = playersPanelFactory(self.proxy, True, isColorBlind, isFallout, isMutlipleTeams)
self.__rightPlayersPanel = playersPanelFactory(self.proxy, False, isColorBlind, isFallout, isMutlipleTeams)
self.__damageInfoPanel = VehicleDamageInfoPanel(self.proxy)
self.__damageInfoPanel.start()
self.__fragCorrelation = scorePanelFactory(self.proxy, isFallout, isMutlipleTeams)
self.__statsForm = statsFormFactory(self.proxy, isFallout, isMutlipleTeams)
self.__plugins.init()
self.isVehicleCountersVisible = g_settingsCore.getSetting('showVehiclesCounter')
self.__fragCorrelation.showVehiclesCounter(self.isVehicleCountersVisible)
self.__vErrorsPanel = VehicleErrorMessages(self.proxy)
self.__vMsgsPanel = VehicleMessages(self.proxy)
self.__pMsgsPanel = PlayerMessages(self.proxy)
self.__plugins.start()
self.__debugPanel.start()
self.__consumablesPanel.start()
self.__damagePanel.start()
self.__ingameHelp.start()
self.__vErrorsPanel.start()
self.__vMsgsPanel.start()
self.__pMsgsPanel.start()
self.__markersManager.start()
self.__markersManager.setMarkerDuration(GUI_SETTINGS.markerHitSplashDuration)
markers = {'enemy': g_settingsCore.getSetting('enemy'),
'dead': g_settingsCore.getSetting('dead'),
'ally': g_settingsCore.getSetting('ally')}
self.__markersManager.setMarkerSettings(markers)
MessengerEntry.g_instance.gui.invoke('populateUI', self.proxy)
g_guiResetters.add(self.__onRecreateDevice)
g_repeatKeyHandlers.add(self.component.handleKeyEvent)
self.__onRecreateDevice()
self.__statsForm.populate()
self.__leftPlayersPanel.populateUI(self.proxy)
self.__rightPlayersPanel.populateUI(self.proxy)
if BattleReplay.g_replayCtrl.isPlaying:
BattleReplay.g_replayCtrl.onBattleSwfLoaded()
self.__populateData()
self.__minimap.start()
self.__radialMenu.setSettings(self.__settingsInterface)
self.__radialMenu.populateUI(self.proxy)
self.__ribbonsPanel.start()
g_sessionProvider.setBattleUI(self)
self.__arenaCtrl = battleArenaControllerFactory(self, isFallout, isMutlipleTeams)
g_sessionProvider.addArenaCtrl(self.__arenaCtrl)
self.updateFlagsColor()
self.movie.setFocussed(SCALEFORM_SWF_PATH)
self.call('battle.initDynamicSquad', self.__getDynamicSquadsInitParams(enableButton=not BattleReplay.g_replayCtrl.isPlaying))
self.call('sixthSenseIndicator.setDuration', [GUI_SETTINGS.sixthSenseDuration])
g_tankActiveCamouflage[player.vehicleTypeDescriptor.type.compactDescr] = self.__arena.arenaType.vehicleCamouflageKind
keyCode = CommandMapping.g_instance.get('CMD_VOICECHAT_MUTE')
if not BigWorld.isKeyDown(keyCode):
VOIP.getVOIPManager().setMicMute(True)
ctrl = g_sessionProvider.getVehicleStateCtrl()
ctrl.onVehicleStateUpdated += self.__onVehicleStateUpdated
ctrl.onPostMortemSwitched += self.__onPostMortemSwitched
if BattleReplay.g_replayCtrl.isPlaying:
self.__dynSquadListener = ReplayDynSquadViewListener(self.proxy)
elif BattleReplay.g_replayCtrl.isRecording:
self.__dynSquadListener = RecordDynSquadViewListener(self.proxy)
else:
self.__dynSquadListener = DynSquadViewListener(self.proxy)
g_eventBus.handleEvent(event(self.__ns, event.INITIALIZED))
def beforeDelete(self):
LOG_DEBUG('[Battle] beforeDelete')
removeListener = g_eventBus.removeListener
removeListener(events.GameEvent.HELP, self.toggleHelpWindow, scope=_SCOPE)
removeListener(events.GameEvent.GUI_VISIBILITY, self.showAll, scope=_SCOPE)
ctrl = g_sessionProvider.getVehicleStateCtrl()
if ctrl is not None:
ctrl.onVehicleStateUpdated -= self.__onVehicleStateUpdated
ctrl.onPostMortemSwitched -= self.__onPostMortemSwitched
player = BigWorld.player()
if player and player.inputHandler:
player.inputHandler.onPostmortemVehicleChanged -= self.onPostmortemVehicleChanged
player.inputHandler.onCameraChanged -= self.onCameraChanged
if self.colorManager:
self.colorManager.dispossessUI()
voice = VoiceChatInterface.g_instance
if voice:
voice.dispossessUI(self.proxy)
voice.onPlayerSpeaking -= self.setPlayerSpeaking
voice.onVoiceChatInitFailed -= self.onVoiceChatInitFailed
if self.__plugins is not None:
self.__plugins.stop()
self.__plugins.fini()
self.__plugins = None
if self.movingText is not None:
self.movingText.dispossessUI()
self.movingText = None
if self.__timerSound is not None:
self.__timerSound.stop()
self.__timerSound = None
if self.__soundManager is not None:
self.__soundManager.dispossessUI()
self.__soundManager = None
if self.colorManager is not None:
self.colorManager.dispossessUI()
self.colorManager = None
if self.component:
g_repeatKeyHandlers.discard(self.component.handleKeyEvent)
g_settingsCore.onSettingsChanged -= self.__accs_onSettingsChanged
g_settingsCore.interfaceScale.onScaleChanged -= self.__onRecreateDevice
self.__timersBar.destroy()
self.__teamBasesPanel.destroy()
self.__debugPanel.destroy()
self.__consumablesPanel.destroy()
self.__damagePanel.destroy()
self.__markersManager.destroy()
self.__ingameHelp.destroy()
self.__vErrorsPanel.destroy()
self.__vMsgsPanel.destroy()
self.__pMsgsPanel.destroy()
self.__radialMenu.destroy()
self.__minimap.destroy()
self.__ribbonsPanel.destroy()
self.__fragCorrelation.destroy()
self.__statsForm.destroy()
self.__damageInfoPanel.destroy()
g_sessionProvider.clearBattleUI()
if self.__arenaCtrl is not None:
g_sessionProvider.removeArenaCtrl(self.__arenaCtrl)
self.__arenaCtrl.clear()
self.__arenaCtrl = None
self.__ppSwitcher.destroy()
self.__leftPlayersPanel.dispossessUI()
self.__rightPlayersPanel.dispossessUI()
MessengerEntry.g_instance.gui.invoke('dispossessUI')
self.__arena = None
self.__denunciator = None
g_guiResetters.discard(self.__onRecreateDevice)
self.__settingsInterface.dispossessUI()
self.__settingsInterface = None
if self.__dynSquadListener:
self.__dynSquadListener.destroy()
self.__dynSquadListener = None
BattleWindow.beforeDelete(self)
event = events.AppLifeCycleEvent
g_eventBus.handleEvent(event(self.__ns, event.DESTROYED))
return
def __onVehicleStateUpdated(self, state, value):
if state not in self.__stateHandlers:
return
else:
handler = getattr(self, self.__stateHandlers[state], None)
if handler and callable(handler):
if value is not None:
handler(value)
else:
handler()
return
def _setFireInVehicle(self, bool):
self.call('destroyTimer.onFireInVehicle', [bool])
def onVoiceChatInitFailed(self):
if GUI_SETTINGS.voiceChat:
self.call('VoiceChat.initFailed', [])
def clearCommands(self):
pass
def bindCommands(self):
self.__consumablesPanel.bindCommands()
self.__ingameHelp.buildCmdMapping()
def updateFlagsColor(self):
isColorBlind = g_settingsCore.getSetting('isColorBlind')
colorGreen = self.colorManager.getSubScheme('flag_team_green', isColorBlind=isColorBlind)['rgba']
colorRed = self.colorManager.getSubScheme('flag_team_red', isColorBlind=isColorBlind)['rgba']
arenaDP = g_sessionProvider.getArenaDP()
teamsOnArena = arenaDP.getTeamsOnArena()
for teamIdx in teamsOnArena:
color = colorGreen if arenaDP.isAllyTeam(teamIdx) else colorRed
BigWorld.wg_setFlagColor(teamIdx, color / 255)
for teamIdx in [0] + teamsOnArena:
BigWorld.wg_setFlagEmblem(teamIdx, 'system/maps/wg_emblem.dds', Math.Vector4(0.0, 0.1, 0.5, 0.9))
def setPlayerSpeaking(self, accountDBID, flag):
self.__callEx('setPlayerSpeaking', [accountDBID, flag])
vID = g_sessionProvider.getCtx().getVehIDByAccDBID(accountDBID)
if vID > 0:
self.__markersManager.showDynamic(vID, flag)
def isPlayerSpeaking(self, accountDBID):
return VoiceChatInterface.g_instance.isPlayerSpeaking(accountDBID)
def __onPostMortemSwitched(self):
LogitechMonitor.onScreenChange('postmortem')
if self.radialMenu is not None:
self.radialMenu.forcedHide()
if not g_sessionProvider.getCtx().isPlayerObserver():
self.__callEx('showPostmortemTips', [1.0, 5.0, 1.0])
return
def cursorVisibility(self, callbackId, visible, x = None, y = None, customCall = False, enableAiming = True):
if visible:
g_cursorDelegator.syncMousePosition(self, x, y, customCall)
else:
g_cursorDelegator.restoreMousePosition()
if BigWorld.player() is not None and isPlayerAvatar():
BigWorld.player().setForcedGuiControlMode(visible, False, enableAiming)
return
def tryLeaveRequest(self, _):
resStr = 'quitBattle'
replayCtrl = BattleReplay.g_replayCtrl
player = BigWorld.player()
isVehicleAlive = getattr(player, 'isVehicleAlive', False)
isNotTraining = self.__arena.guiType != constants.ARENA_GUI_TYPE.TRAINING
if not replayCtrl.isPlaying:
if constants.IS_KOREA and gui.GUI_SETTINGS.igrEnabled and self.__arena is not None and isNotTraining:
vehicleID = getattr(player, 'playerVehicleID', -1)
if vehicleID in self.__arena.vehicles:
vehicle = self.__arena.vehicles[vehicleID]
if isVehicleAlive and vehicle.get('igrType') != constants.IGR_TYPE.NONE:
resStr = 'quitBattleIGR'
else:
LOG_ERROR("Player's vehicle not found", vehicleID)
isDeserter = isVehicleAlive and isNotTraining
if isDeserter:
resStr += '/deserter'
else:
isDeserter = False
self.__callEx('tryLeaveResponse', [resStr, isDeserter])
return
def onExitBattle(self, _):
arena = getattr(BigWorld.player(), 'arena', None)
LOG_DEBUG('onExitBattle', arena)
if arena:
BigWorld.player().leaveArena()
return
def toggleHelpWindow(self, _):
self.__callEx('showHideHelp', [not self.__isHelpWindowShown])
def setAimingMode(self, isAiming):
self.__callEx('setAimingMode', [isAiming])
def helpDialogOpenStatus(self, cid, isOpened):
self.__isHelpWindowShown = isOpened
def _initLobbyDialog(self, cid):
if connectionManager.serverUserName:
tooltipBody = i18n.makeString('#tooltips:header/info/players_online_full/body')
tooltipFullData = makeTooltip('#tooltips:header/info/players_online_full/header', tooltipBody % {'servername': connectionManager.serverUserName})
self.__callEx('setServerStatsInfo', [tooltipFullData])
self.__callEx('setServerName', [connectionManager.serverUserName])
if constants.IS_SHOW_SERVER_STATS:
stats = game_control.g_instance.serverStats.getStats()
if 'clusterCCU' in stats and 'regionCCU' in stats:
self.__callEx('setServerStats', [stats['clusterCCU'], stats['regionCCU']])
else:
self.__callEx('setServerStats', [None, None])
else:
self.__callEx('setServerName', ['-'])
links = GUI_SETTINGS.reportBugLinks
if len(links):
reportBugButton = makeHyperLink('ingameMenu', MENU.INGAME_MENU_LINKS_REPORT_BUG)
self.__callEx('setReportBugLink', [reportBugButton])
return
def reportBug(self, _):
reportBugOpenConfirm(g_sessionProvider.getArenaDP().getVehicleInfo().player.accountDBID)
def __getDynamicSquadsInitParams(self, enableAlly = True, enableEnemy = False, enableButton = True):
return [self.__arena.guiType == constants.ARENA_GUI_TYPE.RANDOM and enableAlly, enableEnemy, enableButton]
def __populateData(self):
arena = avatar_getter.getArena()
arenaDP = g_sessionProvider.getArenaDP()
arenaData = ['',
0,
'',
'',
'']
if arena:
arenaData = [toUpper(arena.arenaType.name)]
descExtra = getPrebattleFullDescription(arena.extraData or {})
arenaSubType = getArenaSubTypeName(BigWorld.player().arenaTypeID)
if descExtra:
arenaData.extend([arena.guiType + 1, descExtra])
elif arena.guiType in [constants.ARENA_GUI_TYPE.RANDOM, constants.ARENA_GUI_TYPE.TRAINING]:
arenaTypeName = '#arenas:type/%s/name' % arenaSubType
arenaData.extend([getNecessaryArenaFrameName(arenaSubType, isBaseExists(BigWorld.player().arenaTypeID, BigWorld.player().team)), arenaTypeName])
elif arena.guiType in constants.ARENA_GUI_TYPE.RANGE:
arenaData.append(constants.ARENA_GUI_TYPE_LABEL.LABELS[arena.guiType])
arenaData.append('#menu:loading/battleTypes/%d' % arena.guiType)
else:
arenaData.extend([arena.guiType + 1, '#menu:loading/battleTypes/%d' % arena.guiType])
myTeamNumber = arenaDP.getNumberOfTeam()
getTeamName = g_sessionProvider.getCtx().getTeamName
arenaData.extend([getTeamName(myTeamNumber), getTeamName(arenaDP.getNumberOfTeam(enemy=True))])
teamHasBase = 1 if isBaseExists(BigWorld.player().arenaTypeID, myTeamNumber) else 2
if not isFalloutBattle():
typeEvent = 'normal'
winText = getBattleSubTypeWinText(BigWorld.player().arenaTypeID, teamHasBase)
else:
typeEvent = 'fallout'
if isFalloutMultiTeam():
winText = i18n.makeString(ARENAS.TYPE_FALLOUTMUTLITEAM_DESCRIPTION)
else:
winText = i18n.makeString('#arenas:type/%s/description' % arenaSubType)
arenaData.append(winText)
arenaData.append(typeEvent)
arenaData.extend(_getQuestsTipData(arena, arenaDP))
arenaData.extend([_SMALL_MAP_SOURCE % arena.arenaType.geometryName])
self.__callEx('arenaData', arenaData)
def __onRecreateDevice(self, scale = None):
params = list(GUI.screenResolution())
params.append(g_settingsCore.interfaceScale.get())
self.call('Stage.Update', params)
self.__markersManager.updateMarkersScale()
def invalidateGUI(self):
arenaCtrl = getattr(self, '_Battle__arenaCtrl', None)
if arenaCtrl is not None:
arenaCtrl.invalidateGUI()
return
def __callEx(self, funcName, args = None):
self.call('battle.' + funcName, args)
def __accs_onSettingsChanged(self, diff):
self.colorManager.update()
if 'isColorBlind' in diff:
isColorBlind = diff['isColorBlind']
self.__leftPlayersPanel.defineColorFlags(isColorBlind=isColorBlind)
self.__rightPlayersPanel.defineColorFlags(isColorBlind=isColorBlind)
self.updateFlagsColor()
self.__markersManager.updateMarkers()
self.__minimap.updateEntries()
if 'enemy' in diff or 'dead' in diff or 'ally' in diff:
markers = {'enemy': g_settingsCore.getSetting('enemy'),
'dead': g_settingsCore.getSetting('dead'),
'ally': g_settingsCore.getSetting('ally')}
self.__markersManager.setMarkerSettings(markers)
self.__markersManager.updateMarkerSettings()
if 'showVehiclesCounter' in diff:
self.isVehicleCountersVisible = diff['showVehiclesCounter']
self.__fragCorrelation.showVehiclesCounter(self.isVehicleCountersVisible)
if 'interfaceScale' in diff:
self.__onRecreateDevice()
self.__arenaCtrl.invalidateGUI()
self.__arenaCtrl.invalidateArenaInfo()
def setTeamValuesData(self, data):
if self.__battle_flashObject is not None:
self.__battle_flashObject.setTeamValues(data)
return
def setMultiteamValues(self, data):
if self.__battle_flashObject is not None:
self.__battle_flashObject.setMultiteamValues(data)
return
def getPlayerNameLength(self, isEnemy):
panel = self.rightPlayersPanel if isEnemy else self.leftPlayersPanel
return panel.getPlayerNameLength()
def getVehicleNameLength(self, isEnemy):
panel = self.rightPlayersPanel if isEnemy else self.leftPlayersPanel
return panel.getVehicleNameLength()
def getTeamBasesPanel(self):
return self.__teamBasesPanel
def getBattleTimer(self):
return self.__timersBar
def getPreBattleTimer(self):
return self.__timersBar
def getConsumablesPanel(self):
return self.__consumablesPanel
def getDamagePanel(self):
return self.__damagePanel
def getMarkersManager(self):
return self.__markersManager
def getVErrorsPanel(self):
return self.__vErrorsPanel
def getVMsgsPanel(self):
return self.__vMsgsPanel
def getPMsgsPanel(self):
return self.__pMsgsPanel
def getMinimap(self):
return self.__minimap
def getRadialMenu(self):
return self.__radialMenu
def getDamageInfoPanel(self):
return self.__damageInfoPanel
def getFragCorrelation(self):
return self.__fragCorrelation
def getStatsForm(self):
return self.__statsForm
def getLeftPlayersPanel(self):
return self.__leftPlayersPanel
def getRightPlayersPanel(self):
return self.__rightPlayersPanel
def getRibbonsPanel(self):
return self.__ribbonsPanel
def getPlayersPanelsSwitcher(self):
return self.__ppSwitcher
def getIndicators(self):
return self.__indicators
def getDebugPanel(self):
return self.__debugPanel
class DebugPanel(UIInterface):
__UPDATE_INTERVAL = 0.01
def __init__(self, parentUI):
UIInterface.__init__(self)
self.__ui = parentUI
self.__timeInterval = None
self.__performanceStats = _PerformanceStats()
self.__performanceStats.populateUI(parentUI)
return
def start(self):
self.__timeInterval = TimeInterval(self.__UPDATE_INTERVAL, self, '_DebugPanel__update')
self.__timeInterval.start()
self.__update()
def destroy(self):
self.__performanceStats.disposeUI()
self.__performanceStats = None
self.__timeInterval.stop()
return
def __update(self):
player = BigWorld.player()
if player is None or not hasattr(player, 'playerVehicleID'):
return
else:
fps = 0
recordedFps = -1
ping = 0
isLaggingNow = False
replayCtrl = BattleReplay.g_replayCtrl
if replayCtrl.isPlaying and replayCtrl.fps > 0:
fps = BigWorld.getFPS()[1]
recordedFps = replayCtrl.fps
ping = replayCtrl.ping
isLaggingNow = replayCtrl.isLaggingNow
else:
isLaggingNow = player.filter.isLaggingNow
if not isLaggingNow:
for v in BigWorld.entities.values():
if _isVehicleEntity(v):
if not v.isPlayerVehicle:
if v.isAlive() and isinstance(v.filter, BigWorld.WGVehicleFilter) and v.filter.isLaggingNow:
isLaggingNow = True
break
ping = min(BigWorld.LatencyInfo().value[3] * 1000, 999)
if ping < 999:
ping = max(1, ping - 500.0 * constants.SERVER_TICK_LENGTH)
fpsInfo = BigWorld.getFPS()
from helpers.statistics import g_statistics
g_statistics.update(fpsInfo, ping, isLaggingNow)
fps = fpsInfo[1]
if replayCtrl.isRecording:
replayCtrl.setFpsPingLag(fps, ping, isLaggingNow)
try:
self.__performanceStats.updateDebugInfo(int(fps), int(ping), isLaggingNow, int(recordedFps))
except:
pass
return
class _PerformanceStats(UIInterface):
def __init__(self):
UIInterface.__init__(self)
self.flashObject = None
return
def populateUI(self, proxy):
UIInterface.populateUI(self, proxy)
self.flashObject = self.uiHolder.getMember('_level0.debugPanel')
self.flashObject.script = self
def updateDebugInfo(self, fps, ping, lag, fpsReplay):
if fpsReplay != 0 and fpsReplay != -1:
fps = '{0}({1})'.format(fpsReplay, fps)
else:
fps = str(fps)
ping = str(ping)
self.flashObject.as_updateDebugInfo(fps, ping, lag)
def disposeUI(self):
self.flashObject.script = None
self.flashObject = None
return
# okay decompyling c:\Users\PC\wotsources\files\originals\res\scripts\client\gui\scaleform\battle.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2016.02.14 12:38:28 Střední Evropa (běžný čas)
| [
"info@webium.sk"
] | info@webium.sk |
752c2a30035856ddab6654f7db9b32d5874bd910 | d90200c658360b455092f9124211b5da8f2caf0d | /6.py | 0fb73f44320ff20d6eb8eaa84ae553f34bb72b1f | [] | no_license | Shreemay/FP | 797abdaeea286718ea9caddc2d1040827a15533d | 783542cdb2aa9a59d997c8e038278f0ab2a14bea | refs/heads/master | 2016-09-09T21:22:40.457124 | 2014-12-10T09:58:49 | 2014-12-10T09:58:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 134 | py | def low(li):
li = map(fun,li)
print li
def fun(x):
return x.lower()
lst = ['Hello World','abc','NaMo','INDIA','python']
low(lst)
| [
"shreemay1993@gmail.com"
] | shreemay1993@gmail.com |
1faa06888f69e06de3d838ad15e8f59de008c405 | a2f72e29393a2613bf4c869d6618d256d202e57e | /Tpu/GanV2/Tpu_GanV2.py | 6bcc03a5bacb7cf47ebbbb82ac85c9de8f4716cc | [] | no_license | eladshabi/Acgan | 937b7c01bd5c1b64d4228b831cf82d7ed7b8ecd7 | c8073d275db253b306e097d16442d7a7b0f95a67 | refs/heads/master | 2020-04-17T22:55:14.480906 | 2019-02-24T13:00:51 | 2019-02-24T13:00:51 | 167,007,224 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,889 | py | import numpy as np
import time
from tensorflow.contrib.mixed_precision import FixedLossScaleManager, LossScaleOptimizer
from tensorflow.examples.tutorials.mnist import input_data
from Tpu.GanV2.Generator import Generator
from Tpu.GanV2.Discriminator import Discriminator
from Tpu.GanV2.losses import *
from Tpu.GanV2.dtype_convert import float32_variable_storage_getter
mnist = input_data.read_data_sets("data/", one_hot=True)
#mnist = tf.keras.datasets.mnist
def get_data():
return mnist.load_data()
def create_gan_model():
gen = Generator(letant_size=100, tpu=True)
dis = Discriminator(128, True)
labels = tf.placeholder(tf.int32, shape=[None])
real_images = dis.get_input_tensor()
z = gen.get_input_tensor()
G = gen.get_generator(z, labels)
print("gen :",G)
D_output_real, D_logits_real = dis.get_discriminator(G, labels)
D_output_fake, D_logits_fake = dis.get_discriminator(G,labels,reuse=True)
#############################
# #
# Loss functions #
# #
#############################
D_loss , G_loss= loss(labels, D_output_real, D_logits_real, D_output_fake, D_logits_fake, G)
# Get all the trainable variables
tvars = tf.trainable_variables()
d_vars = [var for var in tvars if 'dis' in var.name]
g_vars = [var for var in tvars if 'gen' in var.name]
# Standard Optimizers
D_trainer = tf.train.AdamOptimizer(0.002, 0.5)
G_trainer = tf.train.AdamOptimizer(0.002, 0.5)
loss_scale_manager_D = FixedLossScaleManager(5000)
loss_scale_manager_G = FixedLossScaleManager(5000)
loss_scale_optimizer_D = LossScaleOptimizer(D_trainer, loss_scale_manager_D)
loss_scale_optimizer_G = LossScaleOptimizer(G_trainer, loss_scale_manager_G)
grads_variables_D = loss_scale_optimizer_D.compute_gradients(D_loss, d_vars)
grads_variables_G = loss_scale_optimizer_G.compute_gradients(G_loss, g_vars)
training_step_op_D = loss_scale_optimizer_D.apply_gradients(grads_variables_D)
training_step_op_G = loss_scale_optimizer_D.apply_gradients(grads_variables_G)
init = tf.global_variables_initializer()
samples = []
batch_size = 128
epochs = 100
saver = tf.train.Saver(var_list=g_vars)
with tf.Session() as sess:
sess.run(init)
start = time.time()
# Recall an epoch is an entire run through the training data
for e in range(epochs):
# // indicates classic division
num_batches = mnist.train.num_examples // batch_size
for i in range(num_batches):
# Grab batch of images
batch = mnist.train.next_batch(batch_size)
# Get images, reshape and rescale to pass to D
batch_images = batch[0].astype(np.float16).reshape((batch_size, 784))
batch_images = batch_images * 2 - 1
# Z (random latent noise data for Models)
# -1 to 1 because of tanh activation
batch_z = np.random.uniform(-1, 1, size=(batch_size, 100))
# Run optimizers, no need to save outputs, we won't use them
_ = sess.run(training_step_op_D, feed_dict={real_images: batch_images, z: batch_z})
_ = sess.run(training_step_op_G, feed_dict={z: batch_z})
print("Currently on Epoch {} of {} total...".format(e + 1, epochs))
# Sample from generator as we're training for viewing afterwards
#sample_z = np.random.uniform(-1, 1, size=(1, 100))
# gen_sample = sess.run(generator(z, reuse=True), feed_dict={z: sample_z})
#
# samples.append(gen_sample)
saver.save(sess, '/models/model.ckpt')
end = time.time()
print(end - start)
if __name__ == "__main__":
create_gan_model() | [
"elad.eladsh@gmail.com"
] | elad.eladsh@gmail.com |
8f7d8ba80dc18fa7a18f4b34c9b016bd9aee0260 | 49f73eaf29d3e9427216b44ed519cb8b0b9c6ef4 | /products/models.py | 32473adb2498dbc4f85c0b5f48f06db99a3341bf | [] | no_license | zauribrahimkhalilov-zz/python-django-shoppinlistapp | dc5797d4d49f07d226b90129322442af6e5ca8b4 | ffd1f1cf84e2ab2f57dbd675271fa96a9e278f5c | refs/heads/master | 2021-09-20T18:16:55.112863 | 2018-08-13T17:18:56 | 2018-08-13T17:18:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 450 | py | from django.db import models
from datetime import datetime
from django.urls import reverse
class Products(models.Model):
name = models.CharField(max_length=200)
created_at = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "Products"
def get_absolute_url(self):
return reverse("products:product-detail", kwargs={"id": self.id}) | [
"zibrahimov95@gmail.com"
] | zibrahimov95@gmail.com |
be907c727984cfab702dce79e342cc787711db91 | f121b8c1ace10068da592fe76607f4f2af62728d | /genspirasi/wsgi.py | 1090cd1a995f0c117b5fb60efd5204df423c0010 | [] | no_license | bajjol/websitetest | f8e289a78d7cc2747841678c8a675e83ae8cf6b7 | a6a82001fe687c94bf7a7215566689f610cb77be | refs/heads/master | 2020-04-30T06:48:03.641942 | 2019-03-30T09:31:38 | 2019-03-30T09:31:38 | 176,663,368 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 413 | py | """
WSGI config for genspirasi project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'genspirasi.settings')
application = get_wsgi_application()
| [
"noreply@github.com"
] | noreply@github.com |
feeedca4690352677357ee4f6a4fd44bdc23359e | 39a1da7d6e302bc22d6dc9053d32c0a8b587b178 | /engine/metrics/tests.py | bf490fecaa927cc4eb0b0780d9bc7ef432c65913 | [] | no_license | jinchuuriki91/whats-the-mosam | f1e3ed8c4e1f2a81e0a776680f3d51060fdbcb64 | 9af79bb2888af227e94877d87f152cb404eae0bf | refs/heads/master | 2020-04-08T00:11:04.115839 | 2018-11-30T11:39:51 | 2018-11-30T11:39:51 | 158,840,857 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,418 | py | # Python imports
import requests
# Django imports
from django.test import TestCase
# Engine imports
from metrics.constants import REGION_INT
class APITestCase(TestCase):
url = "http://localhost:8000/api/v1/metric/"
metric_type = "Rainfall"
location = "England"
def test_post(self):
try:
url = "https://s3.eu-west-2.amazonaws.com/interview-question-data/metoffice/%s-%s.json" % (self.metric_type, self.location)
resp = requests.get(url)
resp.raise_for_status()
data = resp.json()
body = {"type": self.metric_type, "location": self.location, "data": data}
resp = requests.post(self.url, json=body)
self.assertEqual(resp.status_code, 201)
except Exception as exc:
raise exc
def test_get(self):
try:
params = {
"start_date": "1991-06-04",
"end_date": "2015-06-04",
"type": self.metric_type,
"location": self.location
}
resp = requests.get(self.url, params=params)
self.assertEqual(resp.status_code, 200)
resp_json = resp.json()
self.assertIn("count", resp_json.keys())
self.assertIn("results", resp_json.keys())
self.assertIsInstance(resp_json["results"], list)
except Exception as exc:
raise exc | [
"gandhar.pednekar15@gmail.com"
] | gandhar.pednekar15@gmail.com |
e599a060cadc68ae4d18deb51d3ae77921ac74f9 | 11c2e2360666ea02196ff0973ba3340f8f327a17 | /clearlog.py | 7678e00655e1b659083799ca790fca92a7fc3670 | [] | no_license | KingDarkness/clear-old-file | 456a3eeab0e56142320f0ba0fda9cf1d85960cf6 | 50a55684cdd56b39c9e4ce4c2bf61b2447b981a1 | refs/heads/master | 2020-06-03T20:37:13.225193 | 2019-06-13T09:34:54 | 2019-06-13T09:34:54 | 191,722,284 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,166 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
from datetime import datetime
import argparse
def clear_directory_older_than(directory, days):
print "Xoá dữ liệu tạo trước %s ngày thư mục %s " % (days, directory)
now = time.time()
cutoff = now - (days * 86400)
files = os.listdir(directory)
for xfile in files:
t = os.stat(os.path.join(directory, xfile))
c = t.st_mtime
if c < cutoff and not os.path.isdir(os.path.join(directory, xfile)):
print "Xoá: %s | tạo lúc: %s" % (os.path.join(directory, xfile), datetime.fromtimestamp(c).strftime('%d-%m-%Y %H:%M:%S'))
os.remove(os.path.join(directory, xfile))
if __name__ == "__main__":
argparser = argparse.ArgumentParser()
argparser.add_argument('-days', metavar='N', type=int, help='Xoá file tạo trước hiện tại [days] ngày', required=True)
argparser.add_argument('-d', '--directory', action='append', help='Danh sách thư mục cần xoá', required=True)
args = argparser.parse_args()
for directory in args.directory:
clear_directory_older_than(directory, args.days)
| [
"noreply@github.com"
] | noreply@github.com |
6541bd8abead9b63b701593616ed08cc40c2325a | 2ef60bfe78bdc963da9512b98c763ef65b5f033a | /converter.py | 96d5bd5da44610044d91ddb85087b22844497c91 | [] | no_license | moritzschaefer/back-to-earth | 5c264d16535b1acf0f4a288e5fc749c5096ed248 | 6f641c74c5452197507fbaf170ebcc6625e90805 | refs/heads/master | 2021-01-22T10:07:43.289137 | 2014-10-25T19:03:44 | 2014-10-25T19:03:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 881 | py | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
# <codecell>
# <codecell>
import sys
prefix = 'public int[,] level = new int[,]{'
suffix = '};'
f = open ("spaceship.txt" , "r")
tr={'.':'0' , '-':'1' , '#':'2' , 'A':'3' , 'G':'4'}
# <codecell>
# <codecell>
# <codecell>
def translate (line):
line=line.strip('\n')
out="{"
for c in line:
out += tr[c]
out += ','
return out[:-1]+'}'
# <codecell>
def convert(filename):
with open(filename, 'r') as f:
lines = f.readlines()
output = prefix
output += ",\n".join([translate(line) for line in lines])
print output+suffix
# <codecell>
convert("spaceship.txt")
# <codecell>
# <codecell>
if __name__=='__main__':
if len(sys.argv) != 2:
print("Usage: {} <inputfilename>")
sys.exit()
convert(sys.argv[1])
| [
"senexger@gmail.com"
] | senexger@gmail.com |
7d9b13742e9ffbb7203c8dcddb9174cf144b5264 | 617b88b30b82d422f67f0b474a42586c3bc57279 | /solution.py | 0780b674351b62d58d7639099258852296def536 | [] | no_license | gilbertduenas/hackerrank---itertools.product- | 51835068112279b9b36f4584235c0dc724c16111 | 24ba35d36a1a67bdcb481540d209a97cdf25e304 | refs/heads/master | 2022-11-26T03:00:28.119239 | 2020-08-02T22:46:31 | 2020-08-02T22:46:31 | 284,551,933 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 143 | py | # learn to splat
from itertools import product
x = list(map(int, input().split()))
y = list(map(int, input().split()))
print(*product(x, y))
| [
"noreply@github.com"
] | noreply@github.com |
7c121797cad965fbc6295c3de5455d4268684abb | 09f630e6550c067238677879c01724a511d73470 | /awsutils/sqs/queue.py | c5f3696586e2945fed2ed25420cafced6d5eb451 | [
"MIT"
] | permissive | morgothdz/awsutils | 638803c01a986b688cfb1fbc2bc7112e26dfc896 | 3bff36b8c8fb400f6066b4c749ca502e7a04acf7 | refs/heads/master | 2021-01-17T05:51:51.197683 | 2013-02-20T20:54:05 | 2013-02-20T20:54:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,229 | py | # awsutils/sqs/queue.py
# Copyright 2013 Sandor Attila Gerendi (Sanyi)
#
# This module is part of awsutils and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import time, logging
from awsutils.exceptions.aws import UserInputException
from awsutils.sqs.message import SQSMessage
class SQSQueue:
COOLDOWN_BETWEEN_RECEIVEMESSAGES = 1
def __init__(self, qName, sqsclient, loadAttributes=True):
"""
@param qName: the SQS queue name
@type qName: str
@param sqsclient: the s3client to be used for communication
@type sqsclient: SQSClient
"""
self.VisibilityTimeout = 60
self.qName = qName
self.sqsclient = sqsclient
self.logger = logging.getLogger("%s.%s" % (type(self).__module__, type(self).__name__))
self.logger.addHandler(logging.NullHandler())
if loadAttributes:
self.refresh()
def refresh(self):
"""
Refresh the queue attributes
"""
attributes = self.sqsclient.getQueueAttributes(self.qName)
for attribute in attributes:
setattr(self, attribute['Name'], attribute['Value'])
def send(self, message, delaySeconds=None):
"""
@type message: SQSMessage
@type delaySeconds: int
"""
if message.messageBody is None:
raise UserInputException('this message has no body')
self.sqsclient.sendMessage(self.qName, message.messageBody, delaySeconds)
def delete(self, message):
if message.receiptHandle is None:
raise UserInputException('this message does not have receiptHandle set')
if message.queue != self:
raise UserInputException('this message does not belong to this queue')
self.sqsclient.deleteMessage(message.queue.qName, message.receiptHandle)
message.queue = None
message.receiptHandle = None
def receive(self, attributes='All', maxNumberOfMessages=1, visibilityTimeout=None, waitTimeSeconds=None):
"""
@type visibilityTimeout: int
@type waitTimeSeconds: int
@type maxNumberOfMessages: int
"""
messages = []
if waitTimeSeconds is None or waitTimeSeconds <= 20:
messages = self.sqsclient.receiveMessage(self.qName, attributes, maxNumberOfMessages,
visibilityTimeout, waitTimeSeconds)
else:
starttime = int(time.time())
while True:
remainingtime = waitTimeSeconds - (int(time.time()) - starttime)
_waitTimeSeconds = min(remainingtime, 20)
if _waitTimeSeconds <= 0:
return None
print(time.time(), waitTimeSeconds, _waitTimeSeconds)
messages = self.sqsclient.receiveMessage(self.qName, attributes, maxNumberOfMessages,
visibilityTimeout, _waitTimeSeconds)
if messages != []:
break
time.sleep(self.COOLDOWN_BETWEEN_RECEIVEMESSAGES)
if messages == []:
if maxNumberOfMessages == 1: return None
else: return []
result = []
if visibilityTimeout is None:
visibilityTimeout = int(self.VisibilityTimeout)
for item in messages:
message = SQSMessage(item['Body'])
message.id = item['MessageId']
message.receiptHandle = item['ReceiptHandle']
message.queue = self
message.visibilityTimeout = visibilityTimeout
message.receptionTimestamp = time.time()
for attribute in item['Attribute']:
setattr(message, attribute['Name'], attribute['Value'])
if maxNumberOfMessages == 1:
return message
result.append(message)
return result
def messages(self, attributes='All', visibilityTimeout=None, autodelete=True, neverfail=True):
"""
Generator to retrieve infinitely messages from a queue
@param visibilityTimeout:
@type visibilityTimeout: int
@param autodelete: the message deletion will be attempted upon release
@type autodelete: bool
@param neverfail: don't fail on aws exceptions
@type neverfail: bool
@rtype: SQSMessage
"""
while True:
try:
items = self.sqsclient.receiveMessage(self.qName, attributes,
maxNumberOfMessages = 1,
visibilityTimeout = visibilityTimeout,
waitTimeSeconds = 20)
except Exception as e:
if neverfail:
self.logger.warn('receiveMessage error [%s]', e)
time.sleep(self.COOLDOWN_BETWEEN_RECEIVEMESSAGES)
continue
raise
if items == []:
time.sleep(self.COOLDOWN_BETWEEN_RECEIVEMESSAGES)
continue
item = items[0]
message = SQSMessage(item['Body'])
message.id = item['MessageId']
message.receiptHandle = item['ReceiptHandle']
message.queue = self
message.visibilityTimeout = visibilityTimeout
message.receptionTimestamp = time.time()
for attribute in item['Attribute']:
setattr(message, attribute['Name'], attribute['Value'])
yield message
if autodelete:
timeleft = message.visibilityTimeoutLeft()
if timeleft < 0:
self.logger.warn('Missed the message deletion by %s s. %s', -1*timeleft, message)
else:
try:
self.delete(message)
except Exception as e:
if neverfail:
self.logger.warn("Could not delete the message %s [%s]", message, e)
raise
def __repr__(self):
return "SQSQueue: " + repr(self.__dict__)
| [
"sanyi@fake.com"
] | sanyi@fake.com |
bef9c9db13ccd2fe5d3bc2eaad4f4e2d1b933af0 | 8dfa84f10fbcb9e16ff266675bc6c8c5aad48085 | /uebung3/djangoProject/vorlesung3/wsgi.py | 05b181c233da97525a3524277f0c192c5e1ddf69 | [] | no_license | mharidy/python-WS2021 | 3ce5ea3891fe745498fb003995e74fd15b0b42b2 | 0c0316fd51d2236b2fe5429c21983f13c0632f7d | refs/heads/master | 2023-02-27T04:46:29.625128 | 2021-02-07T08:48:54 | 2021-02-07T08:48:54 | 304,264,579 | 0 | 0 | null | 2021-01-25T03:58:56 | 2020-10-15T08:47:49 | Python | UTF-8 | Python | false | false | 397 | py | """
WSGI config for vorlesung3 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'vorlesung3.settings')
application = get_wsgi_application()
| [
"mohamed.haridy@avy.health"
] | mohamed.haridy@avy.health |
230f3f86dd3cbe8b70cccfa1db296bdc5283e8a1 | dcfdc9822308c21824b27c051f221a971864e637 | /desafio2 aula4.py | 7f2a0e50aa677da8a05c309c580a503e9ab5c6d2 | [] | no_license | renato29/python3-mundo-1 | 04d5f23bcf8e0f5558cd6db129896ce09e14cc6f | a7d92d5b620d56efbcaeced8e00ff4a5fb80ae23 | refs/heads/master | 2020-04-23T05:10:21.013030 | 2019-02-15T21:54:29 | 2019-02-15T21:54:29 | 170,931,417 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 229 | py | dia=input(print("digite seu dia de nascimento"))
mes=input(print("digite o mes de nascimento"))
ano=input(print("digite o ano que vc nasceu"))
print('Você nasceu no dia', dia, 'de', mes, 'de', ano, '. Correto?')
wait
| [
"noreply@github.com"
] | noreply@github.com |
f881b852d96988139088e6ec681f7e3666dff200 | 76277abda6d4f5dea18209a2e362a2725c154055 | /bentoml/exceptions.py | 850b95e0289fd86b61c509070e1d143e98090b1b | [
"Apache-2.0"
] | permissive | joychen0103/BentoML | eb77e30d434e05b69e8cb44a6be93b38de537044 | e7d05d5f32adb3cbb90bd165ed2f45871052c192 | refs/heads/master | 2020-08-05T06:12:54.126786 | 2019-10-02T19:23:14 | 2019-10-02T19:23:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,115 | py | # Copyright 2019 Atalaya Tech, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class BentoMLException(Exception):
"""
Base class for all BentoML's errors.
Each custom exception should be derived from this class
"""
status_code = 500
class BentoMLConfigException(BentoMLException):
pass
class BentoMLDeploymentException(BentoMLException):
pass
class BentoMLRepositoryException(BentoMLException):
pass
class BentoMLMissingDepdencyException(BentoMLException):
pass
| [
"noreply@github.com"
] | noreply@github.com |
07573412e81359a8769586309efc67f4597edaa7 | be4fc3aac9d41e52e799cc366376e611fe726f90 | /reading_comprehension/model/base_model.py | a99aeb0dc25f2c9e397569854c5077ed1086596b | [
"Apache-2.0"
] | permissive | Hope247code/reading_comprehension_tf | 235fac5eee98183e021d8c315b8193f4a1a33ba3 | 6cd4ac78c6c93900458ac75c774766b56125891d | refs/heads/master | 2023-06-28T14:50:26.802641 | 2019-07-14T06:30:30 | 2019-07-14T06:30:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,095 | py | import collections
import os.path
import numpy as np
import tensorflow as tf
from util.default_util import *
from util.reading_comprehension_util import *
from util.layer_util import *
__all__ = ["TrainResult", "InferResult", "BaseModel"]
class TrainResult(collections.namedtuple("TrainResult",
("loss", "learning_rate", "global_step", "batch_size", "summary"))):
pass
class InferResult(collections.namedtuple("InferResult",
("predict", "predict_detail", "batch_size", "summary"))):
pass
class BaseModel(object):
"""reading comprehension base model"""
def __init__(self,
logger,
hyperparams,
data_pipeline,
external_data,
mode="train",
scope="base"):
"""initialize mrc base model"""
self.logger = logger
self.hyperparams = hyperparams
self.data_pipeline = data_pipeline
self.mode = mode
self.scope = scope
self.update_op = None
self.train_loss = None
self.learning_rate = None
self.global_step = None
self.train_summary = None
self.infer_answer_start = None
self.infer_answer_start_mask = None
self.infer_answer_end = None
self.infer_answer_end_mask = None
self.infer_summary = None
self.word_embedding = external_data["word_embedding"] if external_data is not None and "word_embedding" in external_data else None
self.batch_size = tf.size(tf.reduce_max(self.data_pipeline.input_answer_mask, axis=-2))
self.num_gpus = self.hyperparams.device_num_gpus
self.default_gpu_id = self.hyperparams.device_default_gpu_id
self.logger.log_print("# {0} gpus are used with default gpu id set as {1}"
.format(self.num_gpus, self.default_gpu_id))
if self.hyperparams.train_regularization_enable == True:
self.regularizer = create_weight_regularizer(self.hyperparams.train_regularization_type,
self.hyperparams.train_regularization_scale)
else:
self.regularizer = None
self.random_seed = self.hyperparams.train_random_seed if self.hyperparams.train_enable_debugging else None
def _create_fusion_layer(self,
input_unit_dim,
output_unit_dim,
fusion_type,
num_layer,
hidden_activation,
dropout,
num_gpus,
default_gpu_id,
regularizer,
random_seed,
trainable):
"""create fusion layer for mrc base model"""
with tf.variable_scope("fusion", reuse=tf.AUTO_REUSE):
if fusion_type == "concate":
fusion_layer_list = []
if input_unit_dim != output_unit_dim:
convert_layer = create_convolution_layer("1d", 1, input_unit_dim,
output_unit_dim, 1, 1, 1, "SAME", None, [0.0], None, False, False, False,
num_gpus, default_gpu_id, regularizer, random_seed, trainable)
fusion_layer_list.append(convert_layer)
elif fusion_type == "dense":
fusion_layer = create_dense_layer("single", num_layer, output_unit_dim, 1, hidden_activation,
[dropout] * num_layer, None, False, False, False, num_gpus, default_gpu_id, regularizer, random_seed, trainable)
fusion_layer_list = [fusion_layer]
elif fusion_type == "highway":
fusion_layer_list = []
if input_unit_dim != output_unit_dim:
convert_layer = create_convolution_layer("1d", 1, input_unit_dim,
output_unit_dim, 1, 1, 1, "SAME", None, [0.0], None, False, False, False,
num_gpus, default_gpu_id, regularizer, random_seed, trainable)
fusion_layer_list.append(convert_layer)
fusion_layer = create_highway_layer(num_layer, output_unit_dim, hidden_activation,
[dropout] * num_layer, num_gpus, default_gpu_id, regularizer, random_seed, trainable)
fusion_layer_list.append(fusion_layer)
elif fusion_type == "conv":
fusion_layer = create_convolution_layer("1d", num_layer, input_unit_dim,
output_unit_dim, 1, 1, 1, "SAME", hidden_activation, [dropout] * num_layer,
None, False, False, False, num_gpus, default_gpu_id, regularizer, random_seed, trainable)
fusion_layer_list = [fusion_layer]
else:
raise ValueError("unsupported fusion type {0}".format(fusion_type))
return fusion_layer_list
def _build_fusion_result(self,
input_data_list,
input_mask_list,
fusion_layer_list):
"""build fusion result for mrc base model"""
input_fusion = tf.concat(input_data_list, axis=-1)
input_fusion_mask = tf.reduce_max(tf.concat(input_mask_list, axis=-1), axis=-1, keepdims=True)
if fusion_layer_list != None:
for fusion_layer in fusion_layer_list:
input_fusion, input_fusion_mask = fusion_layer(input_fusion, input_fusion_mask)
return input_fusion, input_fusion_mask
def _get_exponential_moving_average(self,
num_steps):
decay_rate = self.hyperparams.train_ema_decay_rate
enable_debias = self.hyperparams.train_ema_enable_debias
enable_dynamic_decay = self.hyperparams.train_ema_enable_dynamic_decay
if enable_dynamic_decay == True:
ema = tf.train.ExponentialMovingAverage(decay=decay_rate, num_updates=num_steps, zero_debias=enable_debias)
else:
ema = tf.train.ExponentialMovingAverage(decay=decay_rate, zero_debias=enable_debias)
return ema
def _apply_learning_rate_warmup(self,
learning_rate):
"""apply learning rate warmup"""
warmup_mode = self.hyperparams.train_optimizer_warmup_mode
warmup_rate = self.hyperparams.train_optimizer_warmup_rate
warmup_end_step = self.hyperparams.train_optimizer_warmup_end_step
if warmup_mode == "exponential_warmup":
warmup_factor = warmup_rate ** (1 - tf.to_float(self.global_step) / tf.to_float(warmup_end_step))
warmup_learning_rate = warmup_factor * learning_rate
elif warmup_mode == "inverse_exponential_warmup":
warmup_factor = tf.log(tf.to_float(self.global_step + 1)) / tf.log(tf.to_float(warmup_end_step))
warmup_learning_rate = warmup_factor * learning_rate
else:
raise ValueError("unsupported warm-up mode {0}".format(warmup_mode))
warmup_learning_rate = tf.cond(tf.less(self.global_step, warmup_end_step),
lambda: warmup_learning_rate, lambda: learning_rate)
return warmup_learning_rate
def _apply_learning_rate_decay(self,
learning_rate):
"""apply learning rate decay"""
decay_mode = self.hyperparams.train_optimizer_decay_mode
decay_rate = self.hyperparams.train_optimizer_decay_rate
decay_step = self.hyperparams.train_optimizer_decay_step
decay_start_step = self.hyperparams.train_optimizer_decay_start_step
if decay_mode == "exponential_decay":
decayed_learning_rate = tf.train.exponential_decay(learning_rate=learning_rate,
global_step=(self.global_step - decay_start_step),
decay_steps=decay_step, decay_rate=decay_rate, staircase=True)
elif decay_mode == "inverse_time_decay":
decayed_learning_rate = tf.train.inverse_time_decay(learning_rate=learning_rate,
global_step=(self.global_step - decay_start_step),
decay_steps=decay_step, decay_rate=decay_rate, staircase=True)
else:
raise ValueError("unsupported decay mode {0}".format(decay_mode))
decayed_learning_rate = tf.cond(tf.less(self.global_step, decay_start_step),
lambda: learning_rate, lambda: decayed_learning_rate)
return decayed_learning_rate
def _initialize_optimizer(self,
learning_rate):
"""initialize optimizer"""
optimizer_type = self.hyperparams.train_optimizer_type
if optimizer_type == "sgd":
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
elif optimizer_type == "momentum":
optimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate,
momentum=self.hyperparams.train_optimizer_momentum_beta)
elif optimizer_type == "rmsprop":
optimizer = tf.train.RMSPropOptimizer(learning_rate=learning_rate,
decay=self.hyperparams.train_optimizer_rmsprop_beta,
epsilon=self.hyperparams.train_optimizer_rmsprop_epsilon)
elif optimizer_type == "adadelta":
optimizer = tf.train.AdadeltaOptimizer(learning_rate=learning_rate,
rho=self.hyperparams.train_optimizer_adadelta_rho,
epsilon=self.hyperparams.train_optimizer_adadelta_epsilon)
elif optimizer_type == "adagrad":
optimizer = tf.train.AdagradOptimizer(learning_rate=learning_rate,
initial_accumulator_value=self.hyperparams.train_optimizer_adagrad_init_accumulator)
elif optimizer_type == "adam":
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
beta1=self.hyperparams.train_optimizer_adam_beta_1, beta2=self.hyperparams.train_optimizer_adam_beta_2,
epsilon=self.hyperparams.train_optimizer_adam_epsilon)
else:
raise ValueError("unsupported optimizer type {0}".format(optimizer_type))
return optimizer
def _minimize_loss(self,
loss):
"""minimize optimization loss"""
"""compute gradients"""
if self.num_gpus > 1:
grads_and_vars = self.optimizer.compute_gradients(loss, colocate_gradients_with_ops=True)
else:
grads_and_vars = self.optimizer.compute_gradients(loss, colocate_gradients_with_ops=False)
"""clip gradients"""
gradients = [x[0] for x in grads_and_vars]
variables = [x[1] for x in grads_and_vars]
clipped_gradients, gradient_norm = tf.clip_by_global_norm(gradients, self.hyperparams.train_clip_norm)
grads_and_vars = zip(clipped_gradients, variables)
"""update model based on gradients"""
update_model = self.optimizer.apply_gradients(grads_and_vars, global_step=self.global_step)
return update_model, clipped_gradients, gradient_norm
def train(self,
sess):
"""train model"""
_, loss, learning_rate, global_step, batch_size, summary = sess.run([self.update_op,
self.train_loss, self.decayed_learning_rate, self.global_step, self.batch_size, self.train_summary])
return TrainResult(loss=loss, learning_rate=learning_rate,
global_step=global_step, batch_size=batch_size, summary=summary)
def infer(self,
sess):
"""infer model"""
(answer_start, answer_end, answer_start_mask, answer_end_mask,
batch_size, summary) = sess.run([self.infer_answer_start, self.infer_answer_end,
self.infer_answer_start_mask, self.infer_answer_end_mask, self.batch_size, self.infer_summary])
max_context_length = self.hyperparams.data_max_context_length
max_answer_length = self.hyperparams.data_max_answer_length
predict_start = np.expand_dims(answer_start[:max_context_length], axis=-1)
predict_start_mask = np.expand_dims(answer_start_mask[:max_context_length], axis=-1)
predict_start_start = predict_start * predict_start_mask
predict_end = np.expand_dims(answer_end[:max_context_length], axis=-1)
predict_end_mask = np.expand_dims(answer_end_mask[:max_context_length], axis=-1)
predict_end = predict_end * predict_end_mask
predict_span = np.matmul(predict_start, predict_end.transpose((0,2,1)))
predict_span_mask = np.matmul(predict_start_mask, predict_end_mask.transpose((0,2,1)))
predict_span = predict_span * predict_span_mask
predict = np.full((batch_size, 2), -1)
for k in range(batch_size):
max_prob = float('-inf')
max_prob_start = -1
max_prob_end = -1
for i in range(max_context_length):
for j in range(i, min(max_context_length, i+max_answer_length)):
if predict_span[k, i, j] > max_prob:
max_prob = predict_span[k, i, j]
max_prob_start = i
max_prob_end = j
predict[k, 0] = max_prob_start
predict[k, 1] = max_prob_end
predict_detail = np.concatenate((predict_start, predict_end), axis=-1)
return InferResult(predict=predict, predict_detail=predict_detail, batch_size=batch_size, summary=summary)
def _get_train_summary(self):
"""get train summary"""
return tf.summary.merge([tf.summary.scalar("learning_rate", self.learning_rate),
tf.summary.scalar("train_loss", self.train_loss), tf.summary.scalar("gradient_norm", self.gradient_norm)])
def _get_infer_summary(self):
"""get infer summary"""
return tf.no_op()
| [
"mizheng@microsoft.com"
] | mizheng@microsoft.com |
9bbf035b5e759603277ab311b08da9172cf22559 | cd40fd66338bab16c3cac360ec68d0410daf85dc | /asyncio_study/event_loop/utils.py | 039087d9261d78679ca8a895731fe964988d7754 | [] | no_license | suhjohn/Asyncio-Study | c74a95c37d6ce1d0983b5626a4f68d2b80d7ec79 | d9c5a092924a32f18849787fd30cb322a0ff8b15 | refs/heads/master | 2021-05-12T12:28:15.749447 | 2018-01-14T17:25:22 | 2018-01-14T17:25:22 | 117,414,697 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 585 | py | from functools import wraps
from time import time
def log_execution_time(func):
"""
Decorator function that prints how long it took to execute the function
:param func:
:return:
"""
@wraps(func)
def wrapper(*args, **kwargs):
start = time()
return_value = func(*args, **kwargs)
end = time()
delta = end - start
print(f"Executing {func.__name__} took {delta} seconds.")
return return_value
return wrapper
def fib(n):
return fib(n - 1) + fib(n - 2) if n > 1 else n
timed_fib = log_execution_time(fib) | [
"johnsuh94@gmail.com"
] | johnsuh94@gmail.com |
0ba626c1cb0e67582804291760036684180e9aac | 3faeae950e361eb818830ad210f30a6232e5d7f1 | /wepppy/_scripts/lt_runs_low.py | efdeb5b5aecc5bf4b8561c6458f160bf05309335 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | rogerlew/wepppy | 401e6cee524073209a4445c680b43ea0c6102dfc | 1af4548d725b918b73ee022f2572a63b5194cce0 | refs/heads/master | 2023-07-21T12:56:26.979112 | 2023-07-13T23:26:22 | 2023-07-13T23:26:22 | 125,935,882 | 10 | 6 | NOASSERTION | 2023-03-07T20:42:52 | 2018-03-20T00:01:27 | HTML | UTF-8 | Python | false | false | 46,439 | py |
import os
import shutil
from os.path import exists as _exists
from pprint import pprint
from time import time
from time import sleep
import wepppy
from wepppy.nodb import *
from os.path import join as _join
from wepppy.wepp.out import TotalWatSed
from wepppy.export import arc_export
from osgeo import gdal, osr
gdal.UseExceptions()
if __name__ == '__main__':
projects = [
# dict(wd='CurCond_Watershed_1',
# extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
# map_center=[-120.1348114013672, 39.165471994238374],
# map_zoom=12,
# outlet=[-120.09757304843217, 39.19773527084747],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_2',
# extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
# map_center=[-120.1348114013672, 39.165471994238374],
# map_zoom=12,
# outlet=[-120.11460381632118, 39.18896973503106],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_3',
# extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
# map_center=[-120.1348114013672, 39.165471994238374],
# map_zoom=12,
# outlet=[-120.12165282292143, 39.18644160172608],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_4',
# extent=[-120.20605087280275, 39.15083019711799, -120.08588790893556, 39.243953257043124],
# map_center=[-120.14596939086915, 39.19740715574304],
# map_zoom=13,
# outlet=[-120.12241504431637, 39.181379503672105],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_5',
# extent=[-120.25222778320314, 39.102091011833686, -120.01190185546876, 39.28834275351453],
# map_center=[-120.13206481933595, 39.19527859633793],
# map_zoom=12,
# outlet=[-120.1402884859731, 39.175919130374645],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_6',
# extent=[-120.25222778320314, 39.102091011833686, -120.01190185546876, 39.28834275351453],
# map_center=[-120.13206481933595, 39.19527859633793],
# map_zoom=12,
# outlet=[-120.14460408169862, 39.17224134827233],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_7_Ward',
# extent=[-120.29445648193361, 39.06424830007589, -120.11867523193361, 39.20059987393997],
# map_center=[-120.20656585693361, 39.13245708812353],
# map_zoom=12,
# outlet=[-120.15993239840523, 39.13415744093873],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_8',
# extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
# map_center=[-120.20313262939455, 39.09276546806873],
# map_zoom=12,
# outlet=[-120.16237493339143, 39.12864047715305],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_9_Blackwood',
# extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
# map_center=[-120.20313262939455, 39.09276546806873],
# map_zoom=12,
# outlet=[-120.16359931397338, 39.10677866737716],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_10',
# extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
# map_center=[-120.20313262939455, 39.09276546806873],
# map_zoom=12,
# outlet=[-120.14140904093959, 39.07218260362715],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_11_General',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.12006459240162, 39.05139598278608],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_12_Meeks',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.12452021800915, 39.036407051851995],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_13',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.11884807004954, 39.02163646138702],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_14',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.12066635447759, 39.01951924517021],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_15',
# extent=[-120.15652656555177, 38.98636711600028, -120.09644508361818, 39.033052785617535],
# map_center=[-120.12648582458498, 39.00971380270266],
# map_zoom=14,
# outlet=[-120.10916060023823, 39.004865203316534],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_16',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.10472536830764, 39.002638030718146],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_17',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.10376442165887, 39.00072228304711],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_18',
# extent=[-120.22579193115236, 38.826603057341515, -119.98546600341798, 39.01358193815758],
# map_center=[-120.10562896728517, 38.92015408680781],
# map_zoom=12,
# outlet=[-120.10700793337516, 38.95312733140358],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_19',
# extent=[-120.22579193115236, 38.826603057341515, -119.98546600341798, 39.01358193815758],
# map_center=[-120.10562896728517, 38.92015408680781],
# map_zoom=12,
# outlet=[-120.09942499965612, 38.935371421937056],
# landuse=None,
# cs=12, erod=0.000001),
# dict(wd='CurCond_Watershed_20',
# extent=[-120.14305114746095, 38.877536817489165, -120.02288818359376, 38.97102081360566],
# map_center=[-120.08296966552736, 38.924294213302424],
# map_zoom=13,
# outlet=[-120.07227563388808, 38.940891230590054],
# landuse=None,
# cs=12, erod=0.000001),
#
#
# dict(wd='Thinn_Watershed_1',
# extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
# map_center=[-120.1348114013672, 39.165471994238374],
# map_zoom=12,
# outlet=[-120.09757304843217, 39.19773527084747],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_2',
# extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
# map_center=[-120.1348114013672, 39.165471994238374],
# map_zoom=12,
# outlet=[-120.11460381632118, 39.18896973503106],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_3',
# extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
# map_center=[-120.1348114013672, 39.165471994238374],
# map_zoom=12,
# outlet=[-120.12165282292143, 39.18644160172608],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_4',
# extent=[-120.20605087280275, 39.15083019711799, -120.08588790893556, 39.243953257043124],
# map_center=[-120.14596939086915, 39.19740715574304],
# map_zoom=13,
# outlet=[-120.12241504431637, 39.181379503672105],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_5',
# extent=[-120.25222778320314, 39.102091011833686, -120.01190185546876, 39.28834275351453],
# map_center=[-120.13206481933595, 39.19527859633793],
# map_zoom=12,
# outlet=[-120.1402884859731, 39.175919130374645],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_6',
# extent=[-120.25222778320314, 39.102091011833686, -120.01190185546876, 39.28834275351453],
# map_center=[-120.13206481933595, 39.19527859633793],
# map_zoom=12,
# outlet=[-120.14460408169862, 39.17224134827233],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_7_Ward',
# extent=[-120.29445648193361, 39.06424830007589, -120.11867523193361, 39.20059987393997],
# map_center=[-120.20656585693361, 39.13245708812353],
# map_zoom=12,
# outlet=[-120.15993239840523, 39.13415744093873],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_8',
# extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
# map_center=[-120.20313262939455, 39.09276546806873],
# map_zoom=12,
# outlet=[-120.16237493339143, 39.12864047715305],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_9_Blackwood',
# extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
# map_center=[-120.20313262939455, 39.09276546806873],
# map_zoom=12,
# outlet=[-120.16359931397338, 39.10677866737716],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_10',
# extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
# map_center=[-120.20313262939455, 39.09276546806873],
# map_zoom=12,
# outlet=[-120.14140904093959, 39.07218260362715],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_11_General',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.12006459240162, 39.05139598278608],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_12_Meeks',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.12452021800915, 39.036407051851995],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_13',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.11884807004954, 39.02163646138702],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_14',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.12066635447759, 39.01951924517021],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_15',
# extent=[-120.15652656555177, 38.98636711600028, -120.09644508361818, 39.033052785617535],
# map_center=[-120.12648582458498, 39.00971380270266],
# map_zoom=14,
# outlet=[-120.10916060023823, 39.004865203316534],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_16',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.10472536830764, 39.002638030718146],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_17',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.10376442165887, 39.00072228304711],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_18',
# extent=[-120.22579193115236, 38.826603057341515, -119.98546600341798, 39.01358193815758],
# map_center=[-120.10562896728517, 38.92015408680781],
# map_zoom=12,
# outlet=[-120.10700793337516, 38.95312733140358],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_19',
# extent=[-120.22579193115236, 38.826603057341515, -119.98546600341798, 39.01358193815758],
# map_center=[-120.10562896728517, 38.92015408680781],
# map_zoom=12,
# outlet=[-120.09942499965612, 38.935371421937056],
# landuse=107,
# cs=12, erod=0.000001),
# dict(wd='Thinn_Watershed_20',
# extent=[-120.14305114746095, 38.877536817489165, -120.02288818359376, 38.97102081360566],
# map_center=[-120.08296966552736, 38.924294213302424],
# map_zoom=13,
# outlet=[-120.07227563388808, 38.940891230590054],
# landuse=107,
# cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_1',
extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
map_center=[-120.1348114013672, 39.165471994238374],
map_zoom=12,
outlet=[-120.09757304843217, 39.19773527084747],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_2',
extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
map_center=[-120.1348114013672, 39.165471994238374],
map_zoom=12,
outlet=[-120.11460381632118, 39.18896973503106],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_3',
extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
map_center=[-120.1348114013672, 39.165471994238374],
map_zoom=12,
outlet=[-120.12165282292143, 39.18644160172608],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_4',
extent=[-120.20605087280275, 39.15083019711799, -120.08588790893556, 39.243953257043124],
map_center=[-120.14596939086915, 39.19740715574304],
map_zoom=13,
outlet=[-120.12241504431637, 39.181379503672105],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_5',
extent=[-120.25222778320314, 39.102091011833686, -120.01190185546876, 39.28834275351453],
map_center=[-120.13206481933595, 39.19527859633793],
map_zoom=12,
outlet=[-120.1402884859731, 39.175919130374645],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_6',
extent=[-120.25222778320314, 39.102091011833686, -120.01190185546876, 39.28834275351453],
map_center=[-120.13206481933595, 39.19527859633793],
map_zoom=12,
outlet=[-120.14460408169862, 39.17224134827233],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_7_Ward',
extent=[-120.29445648193361, 39.06424830007589, -120.11867523193361, 39.20059987393997],
map_center=[-120.20656585693361, 39.13245708812353],
map_zoom=12,
outlet=[-120.15993239840523, 39.13415744093873],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_8',
extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
map_center=[-120.20313262939455, 39.09276546806873],
map_zoom=12,
outlet=[-120.16237493339143, 39.12864047715305],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_9_Blackwood',
extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
map_center=[-120.20313262939455, 39.09276546806873],
map_zoom=12,
outlet=[-120.16359931397338, 39.10677866737716],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_10',
extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
map_center=[-120.20313262939455, 39.09276546806873],
map_zoom=12,
outlet=[-120.14140904093959, 39.07218260362715],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_11_General',
extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
map_center=[-120.14408111572267, 39.003177506910475],
map_zoom=12,
outlet=[-120.12006459240162, 39.05139598278608],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_12_Meeks',
extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
map_center=[-120.14408111572267, 39.003177506910475],
map_zoom=12,
outlet=[-120.12452021800915, 39.036407051851995],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_13',
extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
map_center=[-120.14408111572267, 39.003177506910475],
map_zoom=12,
outlet=[-120.11884807004954, 39.02163646138702],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_14',
extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
map_center=[-120.14408111572267, 39.003177506910475],
map_zoom=12,
outlet=[-120.12066635447759, 39.01951924517021],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_15',
extent=[-120.15652656555177, 38.98636711600028, -120.09644508361818, 39.033052785617535],
map_center=[-120.12648582458498, 39.00971380270266],
map_zoom=14,
outlet=[-120.10916060023823, 39.004865203316534],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_16',
extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
map_center=[-120.14408111572267, 39.003177506910475],
map_zoom=12,
outlet=[-120.10472536830764, 39.002638030718146],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_17',
extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
map_center=[-120.14408111572267, 39.003177506910475],
map_zoom=12,
outlet=[-120.10376442165887, 39.00072228304711],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_18',
extent=[-120.22579193115236, 38.826603057341515, -119.98546600341798, 39.01358193815758],
map_center=[-120.10562896728517, 38.92015408680781],
map_zoom=12,
outlet=[-120.10700793337516, 38.95312733140358],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_19',
extent=[-120.22579193115236, 38.826603057341515, -119.98546600341798, 39.01358193815758],
map_center=[-120.10562896728517, 38.92015408680781],
map_zoom=12,
outlet=[-120.09942499965612, 38.935371421937056],
landuse=106,
cs=12, erod=0.000001),
dict(wd='LowSev_Watershed_20',
extent=[-120.14305114746095, 38.877536817489165, -120.02288818359376, 38.97102081360566],
map_center=[-120.08296966552736, 38.924294213302424],
map_zoom=13,
outlet=[-120.07227563388808, 38.940891230590054],
landuse=106,
cs=12, erod=0.000001),
#
# dict(wd='HighSev_Watershed_1',
# extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
# map_center=[-120.1348114013672, 39.165471994238374],
# map_zoom=12,
# outlet=[-120.09757304843217, 39.19773527084747],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_2',
# extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
# map_center=[-120.1348114013672, 39.165471994238374],
# map_zoom=12,
# outlet=[-120.11460381632118, 39.18896973503106],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_3',
# extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
# map_center=[-120.1348114013672, 39.165471994238374],
# map_zoom=12,
# outlet=[-120.12165282292143, 39.18644160172608],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_4',
# extent=[-120.20605087280275, 39.15083019711799, -120.08588790893556, 39.243953257043124],
# map_center=[-120.14596939086915, 39.19740715574304],
# map_zoom=13,
# outlet=[-120.12241504431637, 39.181379503672105],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_5',
# extent=[-120.25222778320314, 39.102091011833686, -120.01190185546876, 39.28834275351453],
# map_center=[-120.13206481933595, 39.19527859633793],
# map_zoom=12,
# outlet=[-120.1402884859731, 39.175919130374645],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_6',
# extent=[-120.25222778320314, 39.102091011833686, -120.01190185546876, 39.28834275351453],
# map_center=[-120.13206481933595, 39.19527859633793],
# map_zoom=12,
# outlet=[-120.14460408169862, 39.17224134827233],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_7_Ward',
# extent=[-120.29445648193361, 39.06424830007589, -120.11867523193361, 39.20059987393997],
# map_center=[-120.20656585693361, 39.13245708812353],
# map_zoom=12,
# outlet=[-120.15993239840523, 39.13415744093873],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_8',
# extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
# map_center=[-120.20313262939455, 39.09276546806873],
# map_zoom=12,
# outlet=[-120.16237493339143, 39.12864047715305],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_9_Blackwood',
# extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
# map_center=[-120.20313262939455, 39.09276546806873],
# map_zoom=12,
# outlet=[-120.16359931397338, 39.10677866737716],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_10',
# extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
# map_center=[-120.20313262939455, 39.09276546806873],
# map_zoom=12,
# outlet=[-120.14140904093959, 39.07218260362715],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_11_General',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.12006459240162, 39.05139598278608],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_12_Meeks',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.12452021800915, 39.036407051851995],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_13',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.11884807004954, 39.02163646138702],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_14',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.12066635447759, 39.01951924517021],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_15',
# extent=[-120.15652656555177, 38.98636711600028, -120.09644508361818, 39.033052785617535],
# map_center=[-120.12648582458498, 39.00971380270266],
# map_zoom=14,
# outlet=[-120.10916060023823, 39.004865203316534],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_16',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.10472536830764, 39.002638030718146],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_17',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.10376442165887, 39.00072228304711],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_18',
# extent=[-120.22579193115236, 38.826603057341515, -119.98546600341798, 39.01358193815758],
# map_center=[-120.10562896728517, 38.92015408680781],
# map_zoom=12,
# outlet=[-120.10700793337516, 38.95312733140358],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_19',
# extent=[-120.22579193115236, 38.826603057341515, -119.98546600341798, 39.01358193815758],
# map_center=[-120.10562896728517, 38.92015408680781],
# map_zoom=12,
# outlet=[-120.09942499965612, 38.935371421937056],
# landuse=105,
# cs=12, erod=0.000001),
# dict(wd='HighSev_Watershed_20',
# extent=[-120.14305114746095, 38.877536817489165, -120.02288818359376, 38.97102081360566],
# map_center=[-120.08296966552736, 38.924294213302424],
# map_zoom=13,
# outlet=[-120.07227563388808, 38.940891230590054],
# landuse=105,
# cs=12, erod=0.000001),
#
#
#
#
# dict(wd='ModSev_Watershed_1',
# extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
# map_center=[-120.1348114013672, 39.165471994238374],
# map_zoom=12,
# outlet=[-120.09757304843217, 39.19773527084747],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_2',
# extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
# map_center=[-120.1348114013672, 39.165471994238374],
# map_zoom=12,
# outlet=[-120.11460381632118, 39.18896973503106],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_3',
# extent=[-120.25497436523439, 39.072244930479926, -120.0146484375, 39.25857565711887],
# map_center=[-120.1348114013672, 39.165471994238374],
# map_zoom=12,
# outlet=[-120.12165282292143, 39.18644160172608],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_4',
# extent=[-120.20605087280275, 39.15083019711799, -120.08588790893556, 39.243953257043124],
# map_center=[-120.14596939086915, 39.19740715574304],
# map_zoom=13,
# outlet=[-120.12241504431637, 39.181379503672105],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_5',
# extent=[-120.25222778320314, 39.102091011833686, -120.01190185546876, 39.28834275351453],
# map_center=[-120.13206481933595, 39.19527859633793],
# map_zoom=12,
# outlet=[-120.1402884859731, 39.175919130374645],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_6',
# extent=[-120.25222778320314, 39.102091011833686, -120.01190185546876, 39.28834275351453],
# map_center=[-120.13206481933595, 39.19527859633793],
# map_zoom=12,
# outlet=[-120.14460408169862, 39.17224134827233],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_7_Ward',
# extent=[-120.29445648193361, 39.06424830007589, -120.11867523193361, 39.20059987393997],
# map_center=[-120.20656585693361, 39.13245708812353],
# map_zoom=12,
# outlet=[-120.15993239840523, 39.13415744093873],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_8',
# extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
# map_center=[-120.20313262939455, 39.09276546806873],
# map_zoom=12,
# outlet=[-120.16237493339143, 39.12864047715305],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_9_Blackwood',
# extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
# map_center=[-120.20313262939455, 39.09276546806873],
# map_zoom=12,
# outlet=[-120.16359931397338, 39.10677866737716],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_10',
# extent=[-120.29102325439453, 39.02451827974919, -120.11524200439455, 39.16094667321639],
# map_center=[-120.20313262939455, 39.09276546806873],
# map_zoom=12,
# outlet=[-120.14140904093959, 39.07218260362715],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_11_General',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.12006459240162, 39.05139598278608],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_12_Meeks',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.12452021800915, 39.036407051851995],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_13',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.11884807004954, 39.02163646138702],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_14',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.12066635447759, 39.01951924517021],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_15',
# extent=[-120.15652656555177, 38.98636711600028, -120.09644508361818, 39.033052785617535],
# map_center=[-120.12648582458498, 39.00971380270266],
# map_zoom=14,
# outlet=[-120.10916060023823, 39.004865203316534],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_16',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.10472536830764, 39.002638030718146],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_17',
# extent=[-120.23197174072267, 38.9348437659246, -120.05619049072267, 39.07144530820888],
# map_center=[-120.14408111572267, 39.003177506910475],
# map_zoom=12,
# outlet=[-120.10376442165887, 39.00072228304711],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_18',
# extent=[-120.22579193115236, 38.826603057341515, -119.98546600341798, 39.01358193815758],
# map_center=[-120.10562896728517, 38.92015408680781],
# map_zoom=12,
# outlet=[-120.10700793337516, 38.95312733140358],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_19',
# extent=[-120.22579193115236, 38.826603057341515, -119.98546600341798, 39.01358193815758],
# map_center=[-120.10562896728517, 38.92015408680781],
# map_zoom=12,
# outlet=[-120.09942499965612, 38.935371421937056],
# landuse=118,
# cs=12, erod=0.000001),
# dict(wd='ModSev_Watershed_20',
# extent=[-120.14305114746095, 38.877536817489165, -120.02288818359376, 38.97102081360566],
# map_center=[-120.08296966552736, 38.924294213302424],
# map_zoom=13,
# outlet=[-120.07227563388808, 38.940891230590054],
# landuse=118,
# cs=12, erod=0.000001)
]
failed = open('failed', 'w')
for proj in projects:
try:
wd = proj['wd']
extent = proj['extent']
map_center = proj['map_center']
map_zoom = proj['map_zoom']
outlet = proj['outlet']
default_landuse = proj['landuse']
print('cleaning dir')
if _exists(wd):
print()
shutil.rmtree(wd)
os.mkdir(wd)
print('initializing project')
#ron = Ron(wd, "lt-fire.cfg")
ron = Ron(wd, "lt.cfg")
#ron = Ron(wd, "0.cfg")
ron.name = wd
ron.set_map(extent, map_center, zoom=map_zoom)
print('fetching dem')
ron.fetch_dem()
print('building channels')
topaz = Topaz.getInstance(wd)
topaz.build_channels(csa=5, mcl=60)
topaz.set_outlet(*outlet)
sleep(0.5)
print('building subcatchments')
topaz.build_subcatchments()
print('abstracting watershed')
wat = Watershed.getInstance(wd)
wat.abstract_watershed()
translator = wat.translator_factory()
topaz_ids = [top.split('_')[1] for top in translator.iter_sub_ids()]
print('building landuse')
landuse = Landuse.getInstance(wd)
landuse.mode = LanduseMode.Gridded
landuse.build()
landuse = Landuse.getInstance(wd)
# 105 - Tahoe High severity fire
# topaz_ids is a list of string ids e.g. ['22', '23']
if default_landuse is not None:
print('setting default landuse')
landuse.modify(topaz_ids, default_landuse)
print('building soils')
soils = Soils.getInstance(wd)
soils.mode = SoilsMode.Gridded
soils.build()
print('building climate')
climate = Climate.getInstance(wd)
stations = climate.find_closest_stations()
climate.input_years = 27
climate.climatestation = stations[0]['id']
climate.climate_mode = ClimateMode.Observed
climate.climate_spatialmode = ClimateSpatialMode.Multiple
climate.set_observed_pars(start_year=1990, end_year=2016)
climate.build(verbose=1)
print('prepping wepp')
wepp = Wepp.getInstance(wd)
wepp.prep_hillslopes()
print('running hillslopes')
wepp.run_hillslopes()
print('prepping watershed')
wepp = Wepp.getInstance(wd)
wepp.prep_watershed(erodibility=proj['erod'], critical_shear=proj['cs'])
print('running watershed')
wepp.run_watershed()
print('generating loss report')
loss_report = wepp.report_loss()
print('generating totalwatsed report')
fn = _join(ron.export_dir, 'totalwatsed.csv')
totwatsed = TotalWatSed(_join(ron.output_dir, 'totalwatsed.txt'),
wepp.baseflow_opts, wepp.phosphorus_opts)
totwatsed.export(fn)
assert _exists(fn)
print('exporting arcmap resources')
arc_export(wd)
except:
failed.write('%s\n' % wd)
| [
"rogerlew@gmail.com"
] | rogerlew@gmail.com |
19c02720487d050d98b087fa4a3eff70b39034f9 | 9c2d4ca98df937fcaa8879e44ef1f3e5fe93876b | /SciGen/__init__.py | 3de4372d820f1f2d98f6b622bbdcc3d25459c300 | [
"MIT"
] | permissive | SamuelSchmidgall/Machine-Learning-from-Scratch | 500b80b1cd4944df2b75c9feb15e220064ae2a1b | d030b71ab87a034f9d59c5a53f501e96411dc0b2 | refs/heads/master | 2021-06-22T15:50:13.457129 | 2021-01-02T23:19:36 | 2021-01-02T23:19:36 | 132,190,537 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 137 | py | #!/usr/bin/env python
__name__ = "SciGen"
__author__ = "Samuel Schmidgall"
__license__ = "MIT"
__email__ = "sschmidg@masonlive.gmu.edu"
| [
"AbstractMobius@gmail.com"
] | AbstractMobius@gmail.com |
c1a6112f2cab90786e3b5cd0ded693d7946074e3 | 14ac1cd2a1e1d5366ef06e26fadc3d34ff5d5fad | /apps/news/forms.py | 3c43fc6e77f7b85acd06118b3639b0741797dfa8 | [] | no_license | wangdawei0515/django_project | 1c5b2384eaab112cf65da032ed3d5fccd7e27c70 | 7834237a8c19b4b854e8450e2d64458a17584d36 | refs/heads/master | 2020-03-24T02:50:46.708396 | 2018-07-29T14:31:21 | 2018-07-29T14:31:21 | 140,164,573 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 398 | py | #encoding: utf-8
from django import forms
from apps.forms import FormMixin
class AddCommentForm(forms.Form,FormMixin):
# 在表单中,CharField和TextField唯一的区别
# 就是在表单渲染成模板的时候会有区别。
# CharField会被渲染成Input标签
# TextField会被渲染成Textarea
content = forms.CharField()
news_id = forms.IntegerField() | [
"wangdawei_@outlook.com"
] | wangdawei_@outlook.com |
44931ba564f7deaf02d0a94267264fb6b8edf874 | 87f4634d4a5a3287871765f77cabd2dcc37284a3 | /setup.py | 7c0f5314842f8a754ee3727381e78c8e3a2a20d6 | [] | no_license | yangyushi/yaggie | 2792a8ca61b4093ff2d80c5493f9f6d9e47ddc50 | 1cb928a014e8393e5852d20a4b8df76f9206f28b | refs/heads/master | 2021-03-24T13:19:37.060445 | 2019-08-28T13:37:07 | 2019-08-28T13:37:07 | 117,542,208 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 335 | py | from distutils.core import setup
setup(name='yaggie',
version='0.1',
packages=['yaggie',
'yaggie.engine',
'yaggie.engine.colloids',
'yaggie.engine.mytrack'],
py_modules=['yaggie.analysis',
'yaggie.render',
'yaggie.utility']
)
| [
"yangyushi1992@icloud.com"
] | yangyushi1992@icloud.com |
8f95dcb9c22025b63932cb30e24ae18203a9dc38 | ce48d74eb28ec153573cd42fe58d39adc784c85c | /jdcloud_sdk/services/xdata/models/DwDatabaseInfo.py | bedf36eee3a80637f1aaf4c87b6493744b5f6c2c | [
"Apache-2.0"
] | permissive | oulinbao/jdcloud-sdk-python | 4c886cb5b851707d98232ca9d76a85d54c8ff8a8 | 660e48ec3bc8125da1dbd576f7868ea61ea21c1d | refs/heads/master | 2020-03-16T22:22:15.922184 | 2018-05-11T10:45:34 | 2018-05-11T10:45:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,049 | py | # coding=utf8
# Copyright 2018-2025 JDCLOUD.COM
#
# 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.
#
# NOTE: This class is auto generated by the jdcloud code generator program.
class DwDatabaseInfo(object):
def __init__(self, owner=None, comments=None, databaseName=None):
"""
:param owner: (Optional) 所有者
:param comments: (Optional) 描述信息
:param databaseName: (Optional) 数据库名称
"""
self.owner = owner
self.comments = comments
self.databaseName = databaseName
| [
"oulinbao@jd.com"
] | oulinbao@jd.com |
087c70a2155e879d896447289bfc2e295a84c7fb | 585f3bd3b846512b058ae1e48a29afc8ab11eae3 | /Week2P3/Week2P3(with wabble).py | f0b25e4e4aab74e8d9841ce8ddda0168ac5f4054 | [] | no_license | johntraben/ENG209-CR | 05bb1584ecbbb0eb8db0359967a60dd1fd9832f8 | d927d264fbe24b86c6a5e11d0affdba412530e4d | refs/heads/main | 2022-12-31T23:53:18.695963 | 2020-10-29T19:33:42 | 2020-10-29T19:33:42 | 306,501,410 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,184 | py | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 20 17:42:44 2020
MDP problem
@author: fishy
"""
class MDP(object):
def __init__(self,Xmax,Vmax,Pw):
self.Xmax = Xmax
self.Vmax = Vmax
self.Pw = Pw
def startState(self):
return [self.X0,self.V0]
def isEdge(self,state):
return (((state[0]+state[1])>self.Xmax )or((state[0]+state[1])<-self.Xmax))
def isEnd(self,state):
return state == [0,0]
def actions(self,state):
# return list of valid actions
results = []
if (self.isEdge(state) or self.isEnd(state)):
results.append('none')
else:
results.append('Do_nothing')
if state[1]+1 <= self.Vmax:
results.append('accelerating')
if state[1]-1 >= -self.Vmax:
results.append('decelerating')
return results
def TransProbAndReward(self,state,action):
results = []
next_state = []
if action == 'Do_nothing':
next_state = [state[0]+state[1],state[1]]
results.append((next_state, 1.- 2*self.Pw ,int(self.isEnd(next_state))))
if (state[1]+1)<= self.Vmax:
next_state = [state[0]+state[1],state[1]+1]
results.append((next_state, self.Pw ,int(self.isEnd(next_state))))
if (state[1]-1)>= -self.Vmax:
next_state = [state[0]+state[1],state[1]-1]
results.append((next_state, self.Pw ,int(self.isEnd(next_state))))
elif action == 'accelerating':
next_state = [state[0]+state[1],state[1]+1]
results.append((next_state, 1- 2*self.Pw ,int(self.isEnd(next_state))))
if (state[1]+2)<= self.Vmax:
next_state = [state[0]+state[1],state[1]+2]
results.append((next_state, self.Pw ,int(self.isEnd(next_state))))
next_state = [state[0]+state[1],state[1]]
results.append((next_state, self.Pw ,int(self.isEnd(next_state))))
elif action == 'decelerating':
next_state = [state[0]+state[1],state[1]]
results.append((next_state, self.Pw ,int(self.isEnd(next_state))))
if (state[1]-2)>= -self.Vmax:
next_state = [state[0]+state[1],state[1]-2]
results.append((next_state, self.Pw ,int(self.isEnd(next_state))))
next_state = [state[0]+state[1],state[1]-1]
results.append((next_state, 1- 2*self.Pw ,int(self.isEnd(next_state))))
return results
def discount(self):
return 0.9
def states(self):
results = []
for i in range(-self.Xmax, self.Xmax+1):
for j in range(-self.Vmax, self.Vmax+1):
results.append([i,j])
return results
def valueIteration(mdp):
V = {}
for state in mdp.states():
V[tuple(state)] = 0.
def Q(state,action):
return sum(prob* (reward + mdp.discount()*V[tuple(newstate)]) \
for newstate, prob, reward in mdp.TransProbAndReward(state,action))
while True:
newV = {}
for state in mdp.states():
if (mdp.isEnd(state) or mdp.isEdge(state)):
newV[tuple(state)] = 0.
else:
newV[tuple(state)] = max(Q(state,action) for action in mdp.actions(state))
if max(abs(V[tuple(state)]-newV[tuple(state)])\
for state in mdp.states() ) < 1e-8:
break
V = newV
pi = {}
for state in mdp.states():
if (mdp.isEnd(state) or mdp.isEdge(state)):
pi[tuple(state)] = 'none'
else:
pi[tuple(state)] = max((Q(state,action),action) for action in mdp.actions(state)) [1]
print('{:20} {:20}| {:15} '.format('s','V(s)','pi(s)'))
for state in mdp.states():
print('{} {:>20} {:>20} '.format(state,V[tuple(state)],pi[tuple(state)]))
mdp = MDP(4,2,0)
valueIteration(mdp)
| [
"noreply@github.com"
] | noreply@github.com |
be63af58864e0d9a3c0117f2cb0652068ab7729d | 7fdef65f58dbe5ce5a0a660e3f7db9a7a215c17e | /ldif/torch/sif_test.py | 0c4f6be9a869f522ade976a6eb9591dab6439862 | [
"Apache-2.0"
] | permissive | hpp340/ldif | e7c73fbc6b6bcbded6192418eff1a5e5b88b545e | ed5bcaa10bf1614f148b94d6b9bdad248b8ccf48 | refs/heads/master | 2022-11-27T19:44:47.923034 | 2020-08-08T01:08:21 | 2020-08-08T01:08:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,814 | py | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
import unittest
# Unit tests need LDIF added to the path, because the scripts aren't
# in the repository top-level directory.
ldif_root = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
sys.path.append(ldif_root)
import numpy as np
import torch
from ldif.torch import sif
TEST_DATA_DIR = './data'
class TestSif(unittest.TestCase):
def _ensure_sifs_equal(self, a, b, ith=0):
end=ith+1
if ith == -1:
self.assertEqual(a.bs, b.bs)
ith = 0
end = b.bs
self.assertTrue(torch.all(a._constants.eq(b._constants[ith:end, ...])))
self.assertTrue(torch.all(a._centers.eq(b._centers[ith:end, ...])))
self.assertTrue(torch.all(a._radii.eq(b._radii[ith:end, ...])))
self.assertTrue(torch.all(a._rotations.eq(b._rotations[ith:end, ...])))
self.assertEqual(a.symmetry_count, b.symmetry_count)
self.assertEqual(a.element_count, b.element_count)
def test_load_sif(self):
sif_path = os.path.join(TEST_DATA_DIR, 'b831f60f211435df5bbc861d0124304c.txt')
constants, centers, radii, rotations, symmetry_count, features = (
sif._load_v1_txt(sif_path))
self.assertEqual(type(symmetry_count), int)
self.assertEqual(constants.shape, (32,))
self.assertEqual(centers.shape, (32, 3))
self.assertEqual(radii.shape, (32, 3))
self.assertEqual(rotations.shape, (32, 3))
self.assertEqual(symmetry_count, 16)
self.assertEqual(features, None)
self.assertEqual(constants.dtype, np.float32)
self.assertEqual(centers.dtype, np.float32)
self.assertEqual(radii.dtype, np.float32)
self.assertEqual(rotations.dtype, np.float32)
self.assertAlmostEqual(constants[4], -0.028, places=3)
self.assertAlmostEqual(radii[4, 1], 0.000352, places=6)
self.assertAlmostEqual(rotations[4, 2], -0.0532, places=4)
def test_build_sif(self):
sif_path = os.path.join(TEST_DATA_DIR, 'b831f60f211435df5bbc861d0124304c.txt')
shape = sif.Sif.from_file(sif_path)
self.assertAlmostEqual(shape._constants[0, 4, 0].cpu().numpy(), -0.028, places=3)
self.assertAlmostEqual(shape._radii[0, 4, 1].cpu().numpy(), 0.000352, places=6)
self.assertAlmostEqual(shape._rotations[0, 4, 2].cpu().numpy(), -0.0532, places=4)
def test_flatten_unflatten(self):
sif_path = os.path.join(TEST_DATA_DIR, 'b831f60f211435df5bbc861d0124304c.txt')
shape = sif.Sif.from_file(sif_path)
flattened, symc = shape.to_flat_tensor()
unflattened = sif.Sif.from_flat_tensor(flattened, symc)
self._ensure_sifs_equal(shape, unflattened)
def test_batching(self):
shapes = []
flattened_shapes = []
test_names = ['b831f60f211435df5bbc861d0124304c',
'b7eefc4c25dd9e49238581dd5a8af82c']
for name in test_names:
path = os.path.join(TEST_DATA_DIR, name + '.txt')
shape = sif.Sif.from_file(path)
flattened_shapes.append(shape.to_flat_tensor())
flats = [x[0] for x in flattened_shapes]
symcs = [x[1] for x in flattened_shapes]
for symc in symcs:
self.assertEqual(symc, symcs[0])
batched_tensor = torch.cat(flats, dim=0)
batched_sif = sif.Sif.from_flat_tensor(batched_tensor, symcs[0])
unbatched = batched_sif
if __name__ == '__main__':
unittest.main()
| [
"kgenova@princeton.edu"
] | kgenova@princeton.edu |
7b758e318532e9262ef0816f41982476f0035b5c | 265a903707573862c5f786dff014c276d2560407 | /exercise54.py | 16c0b6cc017a726cbfbcb2308293522706142d34 | [] | no_license | kailichama/dev-sprint1 | 877a4855dfee8c2eb65e97a859b5139cbef42e7f | 56086d8b96ca44f4bd254b13dc4543e05fd83d4d | refs/heads/master | 2021-01-15T21:43:56.323504 | 2013-05-01T15:54:24 | 2013-05-01T15:54:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 273 | py | # This is where Exercise 5.4 goes
# Name: Kelly Chiang
def is_triangle(a, b, c):
if a + b < c:
print "no"
if a + c < b:
print "no"
if b + c < a:
print "no"
else:
print "yes"
is_triangle(29, 11, 12)
is_triangle(10, 11, 12)
| [
"chiang.kellymimi@gmail.com"
] | chiang.kellymimi@gmail.com |
75af3c206ddd4f8e25574cabd71067f19214176c | 4170ed62059b6898cc8914e7f23744234fc2f637 | /CD zum Buch "Einstieg in Python"/Programmbeispiele/GUI/gui_check.py | 5f2ffb98025c0f74ac7ab1c38d5a0295e3aeec43 | [] | no_license | Kirchenprogrammierer/Cheats | 9633debd31ab1df78dc639d1aef90d3ac4c1f069 | 0b71c150f48ad1f16d7b47a8532b1f94d26e148e | refs/heads/master | 2021-05-08T10:42:39.927811 | 2018-02-01T17:29:11 | 2018-02-01T17:29:11 | 119,858,392 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 817 | py | import tkinter
def ende():
main.destroy()
def anzeigen():
lb["text"] = "Zimmer " + du.get() + " " + mb.get()
main = tkinter.Tk()
# Anzeigelabel
lb = tkinter.Label(main, text = "Zimmer ", width=40)
lb.pack()
# Widget-Variablen
du = tkinter.StringVar()
du.set("ohne Dusche")
mb = tkinter.StringVar()
mb.set("ohne Minibar")
# Zwei Checkbuttons
cb1 = tkinter.Checkbutton(main, text="Dusche",
variable=du, onvalue="mit Dusche",
offvalue="ohne Dusche", command=anzeigen)
cb1.pack()
cb2 = tkinter.Checkbutton(main, text="Minibar",
variable=mb, onvalue="mit Minibar",
offvalue="ohne Minibar", command=anzeigen)
cb2.pack()
bende = tkinter.Button(main, text = "Ende",
command = ende)
bende.pack()
main.mainloop()
| [
"noreply@github.com"
] | noreply@github.com |
d932abbee00bae52a08077fa165348144d5dab19 | 92bce619c4fccc60601ab613b6b87e6eb336c9c8 | /Python/contrast.py | 323b30409248e5a0fb4249d55212c7f3551ab1c2 | [] | no_license | nealbayya/Dehaze | 152373f6b44a099bb4dadb5259050fe96f16af28 | a13ae01a26864e4b944154f2177b1604a644bdba | refs/heads/master | 2020-06-18T11:25:07.677255 | 2019-07-10T22:45:57 | 2019-07-10T22:45:57 | 196,284,750 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 725 | py | import numpy as np
import cv2 as cv
img = cv.imread('rocks0.jpg', 1)
#img = cv.blur(input, (3, 3))
print(img.shape)
nimg = np.zeros((img.shape[0], img.shape[1], 3))
T = 20
a = 7
b = 7
h, w, d = img.shape
for i in range(h):
for j in range(w):
avg = np.mean(img[max(0, i-a):min(h, i+a), max(0, j-b):min(w, j+b)])
temp = img[max(0, i-a):min(h, i+a), max(0, j-b):min(w, j+b)].copy()
temp = temp.reshape(temp.shape[0]*temp.shape[1]*temp.shape[2])
mx = np.mean(temp[np.argsort(temp)[-5:]])
#print(mx)
navg = avg-(mx-avg)
nimg[i,j] = navg + 2*(img[i,j]-avg)
#exit(0)
nimg = nimg.astype(np.uint8)
cv.imshow('Frame', nimg)
cv.imwrite('t0.jpg', nimg)
cv.waitKey(0)
| [
"gtangg12@gmail.com"
] | gtangg12@gmail.com |
37142c60c2f8e5880e54185a549c7cc27bbc1105 | 34fe072f9dc15728f3d8be00a1654499bfbc9c5b | /check_json | ebc96db0236ce43d641bb148fb12e75b9d664e78 | [] | no_license | mmaschenk/docker-nagios-full | 13b5c28cb5a44d8b69c9f86516549251d5626121 | 5f8d8ea54132ebd2cd49ec6ff1255f924694d820 | refs/heads/master | 2023-01-05T11:19:46.511130 | 2020-11-06T14:15:39 | 2020-11-06T14:15:39 | 309,425,110 | 0 | 0 | null | 2020-11-06T14:15:41 | 2020-11-02T16:13:42 | Shell | UTF-8 | Python | false | false | 2,265 | #! /usr/bin/env python
"""
Nagios plugin to check a value returned from a uri in json format.
Copyright (c) 2009 Peter Kropf. All rights reserved.
Example:
Compare the "hostname" field in the json structure returned from
http://store.example.com/hostname.py against a known value.
./check_json hostname buenosaires http://store.example.com/hostname.py
"""
import urllib2
import simplejson
import sys
from optparse import OptionParser
import base64
prefix = 'JSON'
class nagios:
ok = (0, 'OK')
warning = (1, 'WARNING')
critical = (2, 'CRITICAL')
unknown = (3, 'UNKNOWN')
def exit(status, message):
print prefix + ' ' + status[1] + ' - ' + message
sys.exit(status[0])
parser = OptionParser(usage='usage: %prog field_name expected_value uri')
options, args = parser.parse_args()
if len(sys.argv) < 3:
exit(nagios.unknown, 'missing command line arguments')
field = args[0]
value = args[1]
uri = args[2]
try:
#handler=urllib2.HTTPSHandler(debuglevel=1)
#opener = urllib2.build_opener(handler)
#urllib2.install_opener(opener)
request = urllib2.Request(uri)
username = 'mschenk'
password = 'Mark1234!'
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
#request.add_header("Cookie", "sessionId=5jt7mzxmqii7car75y47wvqx0o86eyqy")
request.add_header('Cookie', 'TUD-USE-COOKIES=yes; django_language=en-us; filterChoice=1; fe_typo_user=b84fb6f9b145b768cb5cd62d3b5fb98f; __utma=1.1746657823.1425573094.1433140486.1433846366.11; __utmc=1; __utmz=1.1433140486.10.6.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); sessionid=5jt7mzxmqii7car75y47wvqx0o86eyqy; csrftoken=OdJ5SaH18vRokxHC6PRCsu7ZxdEhG87N; _ga=GA1.3.146260451.1415355044')
result = urllib2.urlopen(request)
#print result.read()
j = simplejson.load(result)
except urllib2.HTTPError, ex:
exit(nagios.unknown, 'invalid uri')
if field not in j:
exit(nagios.unknown, 'field: ' + field + ' not present')
if str(j[field]) != value:
exit(nagios.critical, str(j[field]) + ' != ' + value)
#exit(nagios.ok, str(j[field]) + ' == ' + value)
exit(nagios.ok, field + ' == ' + value)
| [
"m.m.a.schenk@tudelft.nl"
] | m.m.a.schenk@tudelft.nl | |
8db3d4c9d758b5bd397cc8c7c6ed56d2302b981f | d415f387170b564eccc0c01b386c4eff4b709066 | /CalculadoraSimples.py | efb956605969cea22f4c993dd562202bc678f1a9 | [] | no_license | alessandradiamantino/Estudo | ae53130909d9339bac08948b6bfea9637942e9c0 | b3fff6aeeae0e7dbb824593f655d2d87f79c1bfb | refs/heads/master | 2022-12-19T15:00:21.259636 | 2020-09-14T21:54:24 | 2020-09-14T21:54:24 | 295,545,117 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 484 | py | print("1 - soma\n")
print("2 - subtração\n")
print("3 - multiplicação\n")
print("4 - divisão\n\n")
c = int(input(" "))
import os
os.system('clear') or None
a = int(input("Digite o primeiro numero\n"))
b = int(input("Digite o segundo numero\n\n"))
if c == 1:
print(a + b)
elif c == 2:
print(a - b)
elif c == 3:
print( a * b)
else:
try:
print(a / b)
except:
print("Não é possível fazer a divisão\n") | [
"noreply@github.com"
] | noreply@github.com |
0c0edac82221a10cdd16bca3b52020df36b734b2 | c8dea2ed440fd3f937d96a468ec4e5f1f4fd9de4 | /Part Seven/Exp1.py | 02fc04a3cdf3ebc560b99cf80d88e84448da205f | [] | no_license | chnlmy/python | 1def0414d46f447af61219830598cb26fda7dcab | b1981de93dc8a69c4b93eea782412d4415842121 | refs/heads/master | 2023-06-20T02:20:41.760800 | 2020-11-20T08:00:16 | 2020-11-20T08:00:16 | 293,464,684 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 241 | py | linenum = 0
file = open("/Users/liumingyi/github/python/Part Seven/latex.log", 'r')
for line in file.readlines():
if len(line) == 1:
continue
else:
linenum = linenum + 1
file.close()
print("共{:}行".format(linenum)) | [
"chnlmy@gmail.com"
] | chnlmy@gmail.com |
5e190cb9273f15764a6e53b5d5f884e17dd9e3b8 | 9a995cd9312fd343ce9ba44f2d091ff791f76236 | /Solver.py | ffab89eaa321a935688e561d554cad1d62b1a929 | [] | no_license | sytan98/Sudoku-Generator-Solver | 8da9d012b9a3b9e8938b150e1e5bfce66121e7ef | 9472355799ab13f17b5cbe3d47afb6cf8c5c9381 | refs/heads/master | 2021-05-17T13:07:21.107194 | 2020-03-31T06:00:11 | 2020-03-31T06:00:11 | 250,791,052 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,074 | py | def backtrack(sudokuobj):
#base cases
if sudokuobj.check_grid():
print("solved")
return True
#horizontal wise needs to be unique
for idx, i in enumerate(sudokuobj.flatlist):
if i == 0:
for j in range(1,10):
row = idx//9
column = idx%9
subsquare = (idx//9//3)*3+(idx%9//3+1)-1
# print(idx, row, column, subsquare, j)
if (sudokuobj.check_inrow(row, j) and sudokuobj.check_incolumn(column, j) and sudokuobj.check_insubsquare(subsquare,j)):
# print("found an element that might be suitable")
sudokuobj.list[row][column] = j
# print(sudokuobj.rows)
# print("trying for next empty element")
if backtrack(sudokuobj):
return True
break
# print("Previous element not suitable, backtracking..")
sudokuobj.list[idx//9][idx%9] = 0
return False | [
"tan.siyu@dhs.sg"
] | tan.siyu@dhs.sg |
119b52b10b3fa591bba1e1f716e73d8db86a9d0b | 41c0f6d4dac27558138924c3122a3ca790fd2dea | /set1/test_challenge7.py | 409b4bdb27ad783df6f03ff6da8f3d5d47823b51 | [] | no_license | kevinmel2000/cryptopals | 541f1b20e21461586fe45a8467cdd5fd9cdc828e | 0756cd5d2152425b085e81043e3474d6fbb4f0a2 | refs/heads/master | 2020-03-26T21:01:39.744070 | 2016-06-07T09:54:48 | 2016-06-07T09:54:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 491 | py | '''
Challenge 7:
AES in ECB mode
'''
from set1.challenge7 import *
import unittest
class Challenge7TestCase(unittest.TestCase):
def test_aes_ecb_decrypt(self):
from base64 import b64decode
ciphertext = b64decode(file('data/data_7.txt').read().replace('\n', ''))
key = "YELLOW SUBMARINE"
plaintext = aes_ecb_decrypt(ciphertext, key)
self.assertIn("Supercalafragilisticexpialidocious", plaintext)
if __name__ == '__main__':
unittest.main() | [
"muhammad.abrari@gmail.com"
] | muhammad.abrari@gmail.com |
1ac0b215a67ef3e113fd1ccf8e1ac0319a3d6200 | d3e299214d97149bcb2e10393e9c9ec1a63497b7 | /Barnet.py | 7d5f07b0a02e734a9779596a67c18194d1170985 | [] | no_license | M00-M00/BoroughScrape | 68bd9a5729bfaab96a66c89fe9fdee0cf2066c36 | 36f1ff82547bd9afc56d09e6b9adbee55f7af3e7 | refs/heads/master | 2023-05-12T03:02:32.275844 | 2021-06-08T11:25:05 | 2021-06-08T11:25:05 | 291,691,221 | 0 | 0 | null | 2020-09-01T19:02:59 | 2020-08-31T11:01:24 | Python | UTF-8 | Python | false | false | 507 | py | import requests
from bs4 import BeautifulSoup as bs
import csv
from Scraper2 import Scraper
import json
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-S', '--Start_Data', help='delimited list input', type=str)
parser.add_argument('-E', '--End_Data', type=str)
args = parser.parse_args()
a = "b"
print(args)
print(args.End_Data)
if a == "all":
barnet = Scraper("Barnet")
barnet.get_cases_from_all_weeks()
barnet.scrape_all_cases_to_csv()
barnet.csv_to_excel()
| [
"edimchenko@gmail.com"
] | edimchenko@gmail.com |
a414e93bf6a93d7ea9d9d9fafad47934f70567b8 | 271c7959a39f3d7ff63dddf285004fd5badee4d9 | /venv/Lib/site-packages/ncclient/devices/h3c.py | 17e98b5a38712d3469fac56fcd86aaac22fcbffa | [
"MIT"
] | permissive | natemellendorf/configpy | b6b01ea4db1f2b9109fd4ddb860e9977316ed964 | 750da5eaef33cede9f3ef532453d63e507f34a2c | refs/heads/master | 2022-12-11T05:22:54.289720 | 2019-07-22T05:26:09 | 2019-07-22T05:26:09 | 176,197,442 | 4 | 1 | MIT | 2022-12-08T02:48:51 | 2019-03-18T03:24:12 | Python | UTF-8 | Python | false | false | 1,936 | py | """
Handler for Huawei device specific information.
Note that for proper import, the classname has to be:
"<Devicename>DeviceHandler"
...where <Devicename> is something like "Default", "Huawei", etc.
All device-specific handlers derive from the DefaultDeviceHandler, which implements the
generic information needed for interaction with a Netconf server.
"""
from ncclient.xml_ import BASE_NS_1_0
from .default import DefaultDeviceHandler
from ncclient.operations.third_party.h3c.rpc import *
class H3cDeviceHandler(DefaultDeviceHandler):
"""
H3C handler for device specific information.
In the device_params dictionary, which is passed to __init__, you can specify
the parameter "ssh_subsystem_name". That allows you to configure the preferred
SSH subsystem name that should be tried on your H3C switch. If connecting with
that name fails, or you didn't specify that name, the other known subsystem names
will be tried. However, if you specify it then this name will be tried first.
"""
_EXEMPT_ERRORS = []
def __init__(self, device_params):
super(H3cDeviceHandler, self).__init__(device_params)
def add_additional_operations(self):
dict = {}
dict["get_bulk"] = GetBulk
dict["get_bulk_config"] = GetBulkConfig
dict["cli"] = CLI
dict["action"] = Action
dict["save"] = Save
dict["load"] = Load
dict["rollback"] = Rollback
return dict
def get_capabilities(self):
# Just need to replace a single value in the default capabilities
c = super(H3cDeviceHandler, self).get_capabilities()
return c
def get_xml_base_namespace_dict(self):
return {None: BASE_NS_1_0}
def get_xml_extra_prefix_kwargs(self):
d = {}
d.update(self.get_xml_base_namespace_dict())
return {"nsmap": d}
def perform_qualify_check(self):
return False
| [
"nate.mellendorf@gmail.com"
] | nate.mellendorf@gmail.com |
4465a47f36c248e586fd89f8135164aa44745ffb | a2c5591e2c3f362d1cf1cdea0cac492330c43bad | /printre.py | 14241c616e1dd6bcf9a7964c655f43a342de354e | [] | no_license | sowmiyavelu17/geet | 7b62c975e49f2f7c199882de3db33e71f060b1c4 | 9f6aaf35712d6da980d8428af8401b8188bae703 | refs/heads/master | 2020-07-02T04:50:26.525866 | 2019-08-09T10:53:06 | 2019-08-09T10:53:06 | 201,420,814 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 90 | py | counter = test_str.count('e')
print ("Count of e in GeeksforGeeks is : "+ str(counter))
| [
"noreply@github.com"
] | noreply@github.com |
d2ef8b0ff9076684e5a93e502c80273ff56384c2 | c5fe83f61f96a5997a46799005f87a7eb2e75582 | /versione_senza_encoder/system_conf.py | 07e169c398fc69eacd05a4f37afd66fcda8780a0 | [] | no_license | Elena-Umili/RL-Planning-Robots | 0d4c7e43b4b721ce2378a0ecf81c311707a390b0 | 523ac1da5bd7e03048c35053436729be9e92455c | refs/heads/master | 2023-04-06T16:28:45.537739 | 2021-04-01T09:23:11 | 2021-04-01T09:23:11 | 329,588,877 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 271 | py |
##################### ACROBOT
STATE_SIZE = 3
INPUT_SIZE = STATE_SIZE
ACTION_SIZE = 3
CODE_SIZE = 200
DISCRETE_CODES = False
REW_THRE = 2000
WINDOW = 20
MODELS_DIR = "models/acrobot/"
Q_HIDDEN_NODES = 256
BATCH_SIZE = 64
MARGIN = 1 / CODE_SIZE
PREDICT_CERTAINTY = False
| [
"ema.antonioni@gmail.com"
] | ema.antonioni@gmail.com |
124795f3a26f9782d34d258bac83edde79ca6dab | 76c70ae75cef1ec0e97859e52fbae406d9e6c9db | /ESOP/settings.py | 447a2e66883792a24e7eefd677acc81a9368ab06 | [] | no_license | Abhinavjha07/ESOP | 57ff9eca47baff8bd74d73c29dcd9f7d8a1f6ef7 | 1894c07dee0a6abb8570e35037858cebf87eeaef | refs/heads/master | 2022-12-11T01:23:32.176067 | 2020-01-21T05:41:36 | 2020-01-21T05:41:36 | 182,563,392 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,248 | py | """
Django settings for ESOP project.
Generated by 'django-admin startproject' using Django 2.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'uy%)r^2wc!dz@%=(7cl8#)^th_apg+wd#8!-mp6c30@xb9w#i0'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'services.apps.ServicesConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ESOP.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ESOP.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
| [
"jhaabhinav1998@gmail.com"
] | jhaabhinav1998@gmail.com |
ef84877ff5bc598bf1ca12ec0dd579f441b351b3 | 328a69af8c40cad52274edfda118cc8d3926e74f | /tests/conftest.py | 8784801df4b408468d64b1f8422f4cdce7b0f508 | [
"MIT"
] | permissive | hydrogen602/settlersPy | 49c1ed6b41660606bdab7e6c24889ab72fa56c97 | 5a1df6162d35b6ae9eeefd11c9a0a9ba7a19019c | refs/heads/master | 2022-12-01T23:46:17.633117 | 2020-08-15T14:57:17 | 2020-08-15T14:57:17 | 247,985,767 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,224 | py | # content of conftest.py
# https://docs.pytest.org/en/latest/example/simple.html
from typing import Dict, Tuple
import pytest
# store history of failures per test class name and per index in parametrize (if parametrize used)
_test_failed_incremental: Dict[str, Dict[Tuple[int, ...], str]] = {}
def pytest_runtest_makereport(item, call):
if "incremental" in item.keywords:
# incremental marker is used
if call.excinfo is not None:
# the test has failed
# retrieve the class name of the test
cls_name = str(item.cls)
# retrieve the index of the test (if parametrize is used in combination with incremental)
parametrize_index = (
tuple(item.callspec.indices.values())
if hasattr(item, "callspec")
else ()
)
# retrieve the name of the test function
test_name = item.originalname or item.name
# store in _test_failed_incremental the original name of the failed test
_test_failed_incremental.setdefault(cls_name, {}).setdefault(
parametrize_index, test_name
)
def pytest_runtest_setup(item):
if "incremental" in item.keywords:
# retrieve the class name of the test
cls_name = str(item.cls)
# check if a previous test has failed for this class
if cls_name in _test_failed_incremental:
# retrieve the index of the test (if parametrize is used in combination with incremental)
parametrize_index = (
tuple(item.callspec.indices.values())
if hasattr(item, "callspec")
else ()
)
# retrieve the name of the first test function to fail for this class name and index
test_name = _test_failed_incremental[cls_name].get(parametrize_index, None)
# if name found, test has failed for the combination of class name & test name
if test_name is not None:
pytest.xfail("previous test failed ({})".format(test_name))
def pytest_configure(config):
config.addinivalue_line(
"markers", "incremental: run one after the other"
) | [
"32135041+hydrogen602@users.noreply.github.com"
] | 32135041+hydrogen602@users.noreply.github.com |
d780ebeb1d6e59ceaf5520b60be0ebd357fe4938 | 970f3b8a80cb941cb72e7ebfbf2199ac75b0f5dc | /app.py | b6a6f937b53946f9fe75aeefee64ade6e5d46ce1 | [] | no_license | vincenth520/tusou-python | 22c4f00681bf3aed1154dc4e1268c1312a5a567c | c4ab8eedbfa01b3a8b7c83c2b6cc7e3d76085ffd | refs/heads/master | 2021-01-19T13:15:27.640132 | 2017-08-20T04:07:18 | 2017-08-20T04:07:18 | 100,837,163 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,062 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-04-07 16:46:00
# @Author : Vincent H (1091986039@qq.com)
# @Link : http://luvial.cn
# @Version : $Id$
import os,random,json,threading,zipfile,base64,urllib.parse
from flask import Flask
from flask import request,redirect,url_for,send_from_directory,make_response
from flask import render_template
from gather import Gather
import BloomFilter
import db_inc
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
bloomfilter = BloomFilter.BloomFilter()
# 首页
@app.route('/')
def index():
list = getpiclist(20)
return render_template('index_page.html',piclist=json.loads(list),title='图搜 - 一个强大的在线图库搜索',hot=hot(5,'click desc'))
#首页获取推荐图片
@app.route('/api/getpiclist/<num>')
def getpiclist(num):
num = int(num)
piclist = set()
files = os.listdir('./static/tmp/')
random.shuffle(files)
for d in files:
if num == 0:
break
if(file_extension(d) == '.jpg'):
piclist.add(setUrl()+'/static/tmp/'+d)
num = num - 1
return json.dumps(list(piclist))
# API获取search list
@app.route('/api/search/<s>')
def searchlist(s):
t = threading.Thread(target=searchshell, args=(s,))
t.start()
t.join()
print('这里',t)
#old_piclist = set()
piclist = set()
files = os.listdir('./static/tmp/'+s)
#print(old_piclist,'zhege')
#random.shuffle(files)
for d in files:
if(file_extension(d) == '.jpg'):
piclist.add(setUrl()+'/static/tmp/'+s+'/'+d)
#old_piclist.add(setUrl()+'/static/tmp/'+s+'/'+d)
#print('piclist',setUrl()+'/static/tmp/'+s+'/'+d)
return json.dumps(list(piclist))
# def getsearchlist(s):
# pass
# 执行爬取脚本
#@app.route('/shell/api/search/<s>')
def searchshell(s):
gather = Gather(s)
piclist = gather.craw()
return json.dumps(list(piclist))
# 搜索图片界面
@app.route('/search/<s>')
def search(s):
db = db_inc.get_db()
cur = db.cursor()
rs = db_inc.query_db('select * from search where name = \''+s+'\'')
print('长度',len(rs))
if(len(rs) == 0):
cur.execute('insert into search(id,name,click) values(null,\''+s+'\',1)')
else:
cur.execute('update search set click = click+1 where name = \''+s+'\'')
#print(cur.rowcount)
# for user in db_inc.query_db('select * from search'):
# print (user['id'], 'has the id', user['name'])
cur.close()
db.commit()
db.close()
# cur.execute('select * from search')
# value = cur.fetchall()
# print('这是',value)
path = './static/tmp/'+s
# resp = make_response(render_template(...))
# resp.set_cookie('this_path', path)
#print(path)
piclist = set()
if os.path.exists(path):
i = 0
files = os.listdir(path)
for d in files:
if i == 20:
break
if(file_extension(d) == '.jpg'):
piclist.add(path[1:]+'/'+d)
i = i + 1
#piclist = searchlist(s)
piclist=json.dumps(list(piclist))
else:
pass
piclist = searchshell(s)
return render_template('search_page.html',piclist=json.loads(piclist),s=s)
# 单图片页面
@app.route('/pic')
def pic():
pic = urllib.parse.unquote(request.args.get('item'))
if os.path.exists(pic.replace(setUrl(),'./')):
return render_template('pic.html',pic=pic,hot=hot(10,'click desc'),rand=hot(1,'RANDOM()'))
return page_not_found(404)
# 获取最热搜索词
def hot(num,type):
db = db_inc.get_db()
cur = db.cursor()
hotsearch = db_inc.query_db('select * from search order by '+type+' limit '+str(num))
return hotsearch
# 404页面
@app.errorhandler(404)
def page_not_found(error):
return render_template('404.html'), 404
# 设置域名
def setUrl():
return 'http://localhost:5000'
# 获取文件后缀
def file_extension(path):
return os.path.splitext(path)[1]
# @app.route('/baseget/<s>')
# def safe_base64_decode(s):
# a = (-len(s)) % 4
# s=s+'='*a
# return base64.b64decode(urllib.parse.quote(s)).decode()
# @app.route('/base')
# def safe_base64_encode():
# return base64.b64encode(request.args.get(urllib.parse.unquote('s')).encode(encoding="utf-8")).decode().replace('=','')
if __name__ == '__main__':
#app.debug = True
app.run(host='0.0.0.0') | [
"1091986039@qq.com"
] | 1091986039@qq.com |
0021af907a58a0843f7c18e83c58a1abb80bf758 | 83a765b6cfc99b65b4fb317d55f34ce426996fd7 | /chp4/bot_v_bot.py | 57651c8678c57d719f5c834f4f2e6b10172fd325 | [] | no_license | Guyuena/dlgo-deep-learning-and-chess | c9e67ee5ad1675a029fee06cafd64d3cd7ead14f | b051c46d1dda74587000cb228357b175d72f3ee2 | refs/heads/main | 2023-06-09T15:11:03.125581 | 2021-07-02T02:37:43 | 2021-07-02T02:37:43 | 378,629,721 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 937 | py | from __future__ import print_function
# tag::bot_vs_bot[]
from dlgo.agent.navie import RandomBot
from dlgo import goboard as goboard
from dlgo import gotypes
from dlgo.utils import print_board, print_move
import time
"""":argument
机器自对弈脚本
"""
def main():
board_size = 9
game = goboard.GameState.new_game(board_size)
bots = {
gotypes.Player.black: RandomBot(),
gotypes.Player.white: RandomBot(),
# gotypes.Player.black: FastRandomBot(),
# gotypes.Player.white: FastRandomBot(),
}
while not game.is_over():
time.sleep(0.3) # <1> 0.3s休眠
print(chr(27) + "[2J") # <2> 每次落子前都清除屏幕
print_board(game.board)
bot_move = bots[game.next_player].select_move(game)
print_move(game.next_player, bot_move)
game = game.apply_move(bot_move)
print("游戏结束")
if __name__ == '__main__':
main()
| [
"428106418@qq.com"
] | 428106418@qq.com |
71d2dd398ee838fa80d1528cb2d96542fb693907 | 1c596a3d21b0346a46751cbe89cb15cb3cd1177f | /Session1/hw_3.py | 0f37040195171df07055acaca280fa3dac097672 | [] | no_license | minhphuong1804/truongminhphuong-fundamentals-c4e25 | e4449687dd0d6c8484d87100186e1fddf1b877cf | ec630be8ce531308667aa84f35148d11d1d10766 | refs/heads/master | 2020-04-17T07:44:15.647436 | 2019-01-18T12:21:03 | 2019-01-18T12:21:03 | 166,381,885 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 122 | py | n = int(input("Enter the temperature in Celcius?"))
r = float(n)
degree = (r*9/5) + 32
print(n, "(C)", "=", degree, "(F)") | [
"minhphuongtruong1804@gmail.com"
] | minhphuongtruong1804@gmail.com |
165f0ac619c8d4cf21a08ce53f6979e0046631a8 | cb42eef9aba4fc1a0dc808aae00e73cd5b44d7c0 | /webapp/urls.py | d551ca7b6274835ff783a112707d1685d2c7fcf0 | [] | no_license | xintao222/talkcode | 9ad997533699698933a3339e2c644be3d827942f | 28533b00036b6c0931f44aa63988679f601db502 | refs/heads/master | 2021-01-22T00:19:32.823257 | 2011-03-23T22:59:08 | 2011-03-23T22:59:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 654 | py | from django.conf import settings
from django.conf.urls.defaults import *
from django.contrib.auth.views import login, logout
from django.views.generic.simple import direct_to_template
from talkcode.views import register, index
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^add$', 'talkcode.views.add' ),
url(r'^get$', 'talkcode.views.get' ),
url(r'^media/(.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
url(r'^admin/(.*)', admin.site.root, name='admin'),
url(r'^register/$', register, name='register'),
url(r'^.*$', index, name="index"),
)
| [
"disbeat@gmail.com"
] | disbeat@gmail.com |
daa0b55e0254d92e20fabdcca8849457341bf5a5 | c4422e4e0a5ddf0f3f56d47bb898d5aeff400c79 | /miprint.py | 5db1f8985609d47de4d9269ecbfad52a9741dbea | [] | no_license | Antoniorg-12/Curso2021 | e4bda0e2e7c23427529512f6afbe13a1f5df4a9d | 9e68e0b229ddb2eed1e8ea340c7c3c079a94a7a1 | refs/heads/main | 2023-03-09T05:09:33.483630 | 2021-02-27T12:44:52 | 2021-02-27T12:44:52 | 342,662,006 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 52 | py | def hola_mundo():
print("hola desde un modulo")
| [
"antoniorg.uma@gmail.com"
] | antoniorg.uma@gmail.com |
68333b91ab1080bd3102141d3e24622cadc72097 | 858dfa9bcec66eae9fe4a4008b5c7bf575767efc | /src/metrics/divergences.py | 4e0daefa0d69fffab72750702533ffb2b4bea987 | [] | no_license | Danial-Alh/TextGenerationEvaluator | 766f06f687d8ad5f4e5060aca99425f9cc6820ae | fbad8e35859d9252cd22a8cb04bc42304c2560dd | refs/heads/master | 2023-06-24T02:43:58.398691 | 2020-08-20T19:55:18 | 2020-08-20T19:55:18 | 160,636,771 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,786 | py | # from scipy.special import logsumexp
import numpy as np
from scipy.misc import logsumexp
def logmeanexp(inp):
# log(mean(exp(x)))
l = inp.shape[0]
assert inp.shape == (l,)
return logsumexp(inp - np.log(l))
def log1pexp(inp):
# log(1 + exp(x))
return np.logaddexp(0., inp)
def lndiff(nllp_fromp, nllq_fromp, nllp_fromq, nllq_fromq):
# nllp_fromp, nllq_fromp, nllp_fromq, nllq_fromq = map(np.array, [nllp_fromp, nllq_fromp, nllp_fromq, nllq_fromq])
assert nllp_fromp.shape == nllq_fromp.shape
assert nllp_fromq.shape == nllq_fromq.shape
lndiff_p = nllp_fromp - nllq_fromp
lndiff_q = nllp_fromq - nllq_fromq
return lndiff_p, lndiff_q
def Bhattacharyya(nllp_fromp, nllq_fromp, nllp_fromq, nllq_fromq):
lndiff_p, lndiff_q = lndiff(nllp_fromp, nllq_fromp, nllp_fromq, nllq_fromq)
res = -0.5 * (logmeanexp(0.5 * lndiff_q) + logmeanexp(-0.5 * lndiff_p))
# res = np.exp(0.5 * lndiff1) + np.exp(-0.5 * lndiff2)
# res = -1. * np.log(np.mean(res))
return float(res)
def JensenShannon(nllp_fromp, nllq_fromp, nllp_fromq, nllq_fromq):
lndiff_p, lndiff_q = lndiff(nllp_fromp, nllq_fromp, nllp_fromq, nllq_fromq)
# TODO: check numerical error (https://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf)
res = np.mean(log1pexp(lndiff_q)) + np.mean(log1pexp(-1. * lndiff_p))
# res = np.mean(np.log(1. + np.exp(lndiff1)) + np.log(1. + np.exp(-1. * lndiff2)))
# res = np.mean(np.log(1. + np.exp(lndiff1) + np.exp(-1. * lndiff2) + np.exp(lndiff1 - lndiff2)))
return np.log(2.) - 0.5 * res
def Jeffreys(nllp_fromp, nllq_fromp, nllp_fromq, nllq_fromq):
lndiff_p, lndiff_q = lndiff(nllp_fromp, nllq_fromp, nllp_fromq, nllq_fromq)
return np.mean(lndiff_p) - np.mean(lndiff_q)
| [
"danial.alihosseini@gmail.com"
] | danial.alihosseini@gmail.com |
b6e77796d885e1ff2b153035ca5ccf756ae11b66 | c506e2707708f6b1d1c8b6a4761b3952cdf33c12 | /backend/www/test/upload_contacts_test.py | 1abc56c42b13ef091d47cfb8ba1b890375b3c5f1 | [
"Apache-2.0"
] | permissive | xuantan/viewfinder | 69e17d50228dd34fa34d79eea1c841cc80a869ff | 992209086d01be0ef6506f325cf89b84d374f969 | refs/heads/master | 2021-08-26T00:58:18.180445 | 2021-08-10T03:06:48 | 2021-08-10T03:06:48 | 19,481,298 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,824 | py | # Copyright 2013 Viewfinder Inc. All Rights Reserved.
"""Test upload_contacts service method.
"""
__authors__ = ['mike@emailscrubbed.com (Mike Purtell)']
import json
import mock
from copy import deepcopy
from viewfinder.backend.base import util
from viewfinder.backend.www.test import service_base_test
from viewfinder.backend.db.contact import Contact
from viewfinder.backend.db.db_client import DBKey
from viewfinder.backend.db.notification import Notification
from viewfinder.backend.db.operation import Operation
class UploadContactsTestCase(service_base_test.ServiceBaseTestCase):
def testUploadContacts(self):
"""Test successful upload_contacts."""
contacts = [{'identities': [{'identity': 'Email:mikep@non.com', 'description': 'work'}],
'contact_source': Contact.MANUAL,
'name': 'Mike Purtell',
'given_name': 'Mike',
'family_name': 'Purtell'},
{'identities': [{'identity': 'Phone:+13191231111', 'description': 'home'},
{'identity': 'Phone:+13191232222', 'description': 'mobile'},
{'identity': 'Phone:+13191233333', 'description': 'a'},
{'identity': 'Phone:+13195555555'},
{'identity': 'FacebookGraph:1232134234'}],
'contact_source': Contact.IPHONE,
'name': 'Mike Purtell',
'given_name': 'Mike',
'family_name': 'Purtell'}]
result_0 = self._tester.QueryContacts(self._cookie)
upload_result = self._tester.UploadContacts(self._cookie, contacts)
self.assertEqual(len(upload_result['contact_ids']), 2)
result_1 = self._tester.QueryContacts(self._cookie)
# Observe that the number of contacts increased by 2.
self.assertEqual(result_0['num_contacts'] + 2, result_1['num_contacts'])
self.assertEqual(upload_result['contact_ids'][1], result_1['contacts'][0]['contact_id'])
self.assertEqual(upload_result['contact_ids'][0], result_1['contacts'][1]['contact_id'])
# Try to upload the same contacts again and see that there's no error and no changes in contacts on server.
self._tester.UploadContacts(self._cookie, contacts)
result_2 = self._tester.QueryContacts(self._cookie)
self.assertEqual(result_1, result_2)
# Slightly modify one of the contacts and see that a new contact is added.
contacts[1]['name'] = 'John Purtell'
self._tester.UploadContacts(self._cookie, contacts)
# This should result in just one additional contact on the server.
result_3 = self._tester.QueryContacts(self._cookie)
self.assertEqual(result_2['num_contacts'] + 1, result_3['num_contacts'])
def testContactsWithRegisteredUsers(self):
"""Test interaction between user registration, contacts and notifications."""
def _RegisterUser(name, given_name, email):
user, _ = self._tester.RegisterFakeViewfinderUser({'name': name, 'given_name': given_name, 'email': email}, {})
return user
def _ValidateContactUpdate(expected_notification_name, expected_user_ids):
notification_list = self._tester._RunAsync(Notification.RangeQuery,
self._client,
self._user.user_id,
range_desc=None,
limit=1,
col_names=None,
scan_forward=False)
self.assertEqual(notification_list[0].name, expected_notification_name)
invalidation = json.loads(notification_list[0].invalidate)
start_key = invalidation['contacts']['start_key']
query_result = self._tester.QueryContacts(self._cookie, start_key=start_key)
found_user_ids = set()
for contact in query_result['contacts']:
for identity in contact['identities']:
if identity.has_key('user_id'):
found_user_ids.add(identity['user_id'])
self.assertEqual(expected_user_ids, found_user_ids)
contacts = [{'identities': [{'identity': 'Email:mike@boat.com'}],
'contact_source': Contact.MANUAL,
'name': 'Mike Boat'},
{'identities': [{'identity': 'Email:mike@porsche.com'}, {'identity': 'Email:mike@vw.com'}],
'contact_source': Contact.MANUAL,
'name': 'Mike Cars'}]
util._TEST_TIME += 1
user_boat = _RegisterUser('Mike Purtell', 'Mike', 'mike@boat.com')
self._tester.UploadContacts(self._cookie, contacts)
_ValidateContactUpdate('upload_contacts', set([user_boat.user_id]))
util._TEST_TIME += 1
user_vw = _RegisterUser('Mike VW', 'Mike', 'mike@vw.com')
_ValidateContactUpdate('first register contact', set([user_vw.user_id]))
util._TEST_TIME += 1
user_porsche = _RegisterUser('Mike Porsche', 'Mike', 'mike@porsche.com')
_ValidateContactUpdate('first register contact', set([user_vw.user_id, user_porsche.user_id]))
@mock.patch.object(Operation, 'FAILPOINTS_ENABLED', True)
def testIdempotency(self):
"""Force op failure in order to test idempotency."""
self._tester.UploadContacts(self._cookie,
[{'identities': [{'identity': 'Email:mikep@non.com', 'description': 'work'}],
'contact_source': Contact.MANUAL,
'name': 'Mike Purtell',
'given_name': 'Mike',
'family_name': 'Purtell'}])
def testUploadContactsFailures(self):
"""ERROR: Test some failure cases."""
good_contact = {'identities': [{'identity': 'Email:mikep@non.com', 'description': 'work'}],
'contact_source': Contact.MANUAL,
'name': 'Mike Purtell',
'given_name': 'Mike',
'family_name': 'Purtell'}
# ERROR: Empty identities:
bad_contact = deepcopy(good_contact)
bad_contact['identities'] = [{}]
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: Missing identities:
bad_contact = deepcopy(good_contact)
bad_contact.pop('identities')
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: Missing contact_source:
bad_contact = deepcopy(good_contact)
bad_contact.pop('contact_source')
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: Unknown contact source:
bad_contact = deepcopy(good_contact)
bad_contact['contact_source'] = 'x'
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: Attempt to upload a contact as if it's from facebook:
bad_contact = deepcopy(good_contact)
bad_contact['contact_source'] = Contact.FACEBOOK
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: Attempt to upload a contact as if it's from gmail:
bad_contact = deepcopy(good_contact)
bad_contact['contact_source'] = Contact.GMAIL
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: Malformed identities field:
bad_contact = deepcopy(good_contact)
bad_contact['identities'] = ['invalid']
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: Invalid identity properties field:
bad_contact = deepcopy(good_contact)
bad_contact['identities'] = [{'something': 'invalid'}]
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: Unknown identity type:
bad_contact = deepcopy(good_contact)
bad_contact['identities'] = [{'identity': 'Blah:234'}]
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: Invalid additional identity properties field:
bad_contact = deepcopy(good_contact)
bad_contact['identities'] = [{'identity': 'Email:me@my.com', 'bad': 'additional field'}]
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: Extra/unknown field:
bad_contact = deepcopy(good_contact)
bad_contact['unknown'] = 'field'
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: identity not in canonical form (upper case character):
bad_contact = deepcopy(good_contact)
bad_contact['identities'] = [{'identity': 'Email:Me@my.com'}]
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: too many contacts in a single request:
too_many_contacts = [good_contact for i in xrange(51)]
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, too_many_contacts)
# ERROR: too many identities in a single contact:
bad_contact = deepcopy(good_contact)
bad_contact['identities'] = [{'identity': 'Email:me@my.com'} for i in xrange(51)]
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: contact name too long:
bad_contact = deepcopy(good_contact)
bad_contact['name'] = 'a' * 1001
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: contact given_name too long:
bad_contact = deepcopy(good_contact)
bad_contact['given_name'] = 'a' * 1001
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: contact family_name too long:
bad_contact = deepcopy(good_contact)
bad_contact['family_name'] = 'a' * 1001
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: contact identity key too long:
bad_contact = deepcopy(good_contact)
bad_contact['identities'] = [{'identity': 'Email:%s' % ('a' * 1001)}]
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
# ERROR: contact description too long:
bad_contact = deepcopy(good_contact)
bad_contact['identities'] = [{'identity': 'Email:me@my.com', 'description': 'a' * 1001}]
self.assertRaisesHttpError(400, self._tester.UploadContacts, self._cookie, [bad_contact])
@mock.patch.object(Contact, 'MAX_CONTACTS_LIMIT', 2)
def testMaxContactLimit(self):
"""Test exceed limit error."""
# This should increase the total to 1 and succeed.
self._tester.UploadContacts(self._cookie,
[{'identities': [{'identity': 'Email:e1@a.com'}],
'contact_source': Contact.IPHONE}])
# This should fail because it would bring the total above 2.
self.assertRaisesHttpError(403,
self._tester.UploadContacts,
self._cookie,
[{'identities': [{'identity': 'Email:e2@a.com'}],
'contact_source': Contact.IPHONE},
{'identities': [{'identity': 'Email:e3@a.com'}],
'contact_source': Contact.MANUAL}])
# This should increase the total to 2 and succeed.
self._tester.UploadContacts(self._cookie,
[{'identities': [{'identity': 'Email:e2@a.com'}],
'contact_source': Contact.MANUAL}])
def testUploadContactWithNoIdentities(self):
"""Verify that a contact without any identities succeeds."""
contacts = [{'identities': [],
'contact_source': Contact.IPHONE,
'name': 'Mike Purtell',
'given_name': 'Mike',
'family_name': 'Purtell'}]
upload_result = self._tester.UploadContacts(self._cookie, contacts)
self.assertEqual(len(upload_result['contact_ids']), 1)
contact_id = upload_result['contact_ids'][0]
result = self._tester.QueryContacts(self._cookie)
# Observe that query_contacts returns contact with empty identities list.
self.assertEqual(len(result['contacts']), 1)
self.assertEqual(len(result['contacts'][0]['identities']), 0)
# Ensure that we can also remove this contact.
self._tester.RemoveContacts(self._cookie, [contact_id])
result = self._tester.QueryContacts(self._cookie)
self.assertEqual(len(result['contacts']), 1)
self.assertIn('removed', result['contacts'][0]['labels'])
def _TestUploadContacts(tester, user_cookie, request_dict):
"""Called by the ServiceTester in order to test upload_contacts
service API call.
"""
def _ValidateUploadOneContact(contact):
contact = deepcopy(contact)
# Transform into proper form for Contact.CalculateContactId()
identities_properties = [(identity_properties['identity'], identity_properties.get('description', None))
for identity_properties in contact['identities']]
contact.pop('identities')
contact_dict = Contact.CreateContactDict(user_id, identities_properties, op_dict['op_timestamp'], **contact)
predicate = lambda c: c.contact_id == contact_dict['contact_id']
existing_contacts = validator.QueryModelObjects(Contact, predicate=predicate)
# Create contact if it doesn't already exist or it's in a 'removed' state.
if len(existing_contacts) == 0 or existing_contacts[-1].IsRemoved():
if len(existing_contacts) != 0:
# Delete the 'removed' contact.
validator.ValidateDeleteDBObject(Contact, DBKey(user_id, existing_contacts[-1].sort_key))
validator.ValidateCreateContact(**contact_dict)
return contact_dict['contact_id']
validator = tester.validator
user_id, device_id = tester.GetIdsFromCookie(user_cookie)
request_dict = deepcopy(request_dict)
# Send upload_episode request.
actual_dict = tester.SendRequest('upload_contacts', user_cookie, request_dict)
op_dict = tester._DeriveNotificationOpDict(user_id, device_id, request_dict)
result_contact_ids = []
for contact in request_dict['contacts']:
contact_id = _ValidateUploadOneContact(contact)
result_contact_ids.append(contact_id)
# Validate that a notification was created for the upload of contacts.
invalidate = {'contacts': {'start_key': Contact.CreateSortKey(None, op_dict['op_timestamp'])}}
validator.ValidateNotification('upload_contacts', user_id, op_dict, invalidate)
# Increment time so that subsequent contacts will use later time.
util._TEST_TIME += 1
tester._CompareResponseDicts('upload_contacts', user_id, request_dict, {'contact_ids': result_contact_ids}, actual_dict)
return actual_dict
| [
"bdarnell@squareup.com"
] | bdarnell@squareup.com |
6ef0f3542476b9b7cd97d7170c181e4a05c7decb | 000ed48cae44f7191dba018d7fdd3aa2b1317cb2 | /compute/K_clean.py | 8ef724d292c30db2bab3ab97d99e36cf02b5159e | [] | no_license | Jinzewang/cqHouseAnalyze | 7d80c0ed99cd5e1e0eafa047f7b97265250287f3 | d177af6facb6a35bee28a52bd8cb2d420b5edf4d | refs/heads/master | 2023-07-17T07:00:19.410059 | 2021-09-01T08:59:18 | 2021-09-01T08:59:18 | 404,224,430 | 1 | 2 | null | null | null | null | UTF-8 | Python | false | false | 2,312 | py | import pandas as pd
import numpy as np
import pymysql
conn = pymysql.connect(host='10.20.220.203', user='root', passwd='sx2626', port=3306, db='python', charset='utf8')
cursot = conn.cursor()
# 重庆各区二手房装修情况与单价间关系
cursot.execute("select count(a),sum(UnitPrice),area,Decoration from data_K GROUP BY area,Decoration;")
data_5 = cursot.fetchall()
print(data_5)
#重庆各区二手房关注人数
#1.获取关注人数,并转换成列表
# cursot.execute("select area,NumPeople from data_K")
# row1 = cursot.fetchall() #返回多个元组
# area_1 = np.array(row1)
# area_2 = area_1.tolist()
# print(area_2)
# # 2.将读取的列表类型数据转换为dataframe类型
# from pandas.core.frame import DataFrame
# data = DataFrame(area_2) #以行为标准写入的
# # print(data)
# data[1] = data[[1]].astype(int) #将数据转化为int类型
# data_1 = data.groupby(0)[1].sum()
# data_2 = data.groupby(0)[1].mean().round(2)
# print(data_2)
#
# data_1=data_1.to_frame().reset_index() #Series类型转为dataframe
# data_2=data_2.to_frame().reset_index() #Series类型转为dataframe
# data_3=pd.concat([data_1, data_2], axis=1,ignore_index=True) #将两个dataframe拼一起
# data_4=data_3.loc[:,[0,1,3]] #提取需要的列
# print(data_4)
#
# 重庆各区二手房装修情况与单价间关系
cursot.execute("select count(a),sum(UnitPrice),area,Decoration from data_K GROUP BY area,Decoration;")
data_5 = cursot.fetchall()
print(data_5)
#
# from pandas.core.frame import DataFrame
# data_5=DataFrame(data_5)
# data_5[4]=round((data_5[1]/data_5[0]),2) #将data_5第2列单价总量与第一列数量作商并保留2位小数
# print(data_5)
#写入数据库
# sql_1="""insert into ZX(
# sum,sum_price,area,zx,avg) values (%s,%s,%s,%s,%s);""" #向数据库增加数据
# #
#
# sql_2="""insert into attention(
# area,sum_people,avg_people) values (%s,%s,%s);""" #向数据库增加数据
#
# xx=data_4.values.tolist()
# # mc=data_5.values.tolist()
# try:
# # cursot.executemany(sql_1,mc) #一次性全部写入数据
# cursot.executemany(sql_2,xx) #一次性全部写入数据
# conn.commit()
# except Exception as e:
# print(e)
# conn.rollback()
# conn.close()
| [
"1348754914@qq.com"
] | 1348754914@qq.com |
37359538a19f04c13b9e9e200eef0fa7be950791 | fd451cb1a829c72ea51a93168eba81a475f983a1 | /python/class2.py | d6084276f55b907ea10df3e39e7c64d63f4e80e6 | [] | no_license | shapigou123/Programming | e9fd63f509fb2b45ba9792b13092da6aa8abe935 | 64215eb0f333b583690e32cd9fcce02236713603 | refs/heads/master | 2021-06-26T02:33:56.623872 | 2017-09-07T07:12:11 | 2017-09-07T07:12:11 | 94,725,535 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,988 | py | #coding=utf-8
'''
class Person(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
class Student(Person):
def __init__(self, name, gender, score):
super(Student, self).__init__(name, gender)
self.score = score
def __str__(self):
return '(student: %s , %s ,%s)' % (self.name, self.gender, self.score)
__repr__ = __str__
s = Student('Bob', 'male', 88)
print s
'''
#########################################
'''
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return '(%s: %s)' % (self.name, self.score)
__repr__ = __str__
def __cmp__(self, s):
if self.score == s.score:
return cmp(self.name, s.name)
return -cmp(self.score, s.score)
L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
print sorted(L)
p = Student('yuyang', 24)
print p
'''
############################################
'''
class Student(object):
def __init__(self, *args, **kw):
self.names = args
self.others = kw
for k,v in kw.iteritems():
setattr(self, k, v)
def __len__(self):
return len(self.names)
s = Student('Bob', 'Alice', 'Tim', school="一中")
print len(s)
print s.school
'''
################################
class Fib(object):
def __init__(self, num):
a, b, L = 0, 1, []
for n in range(num):
L.append(a)
a, b = b, a + b
self.numbers = L
def __str__(self):
return str(self.numbers)
__repr__ = __str__
def __len__(self):
return len(self.numbers)
f = Fib(10)
print f
print len(f)
class Fib(object):
def __init__(self, nums):
a, b, l = 0, 1, []
for n in range(nums):
l.append(a)
a, b = b, a+b
self.numbers = l
def __str__(self):
return str(self.numbers)
__repr__ = __str__
def __len__(self):
return len(self.numbers)
f = Fib(5)
print f
print len(f)
'''
class Person(object):
__slots__ = ('name', 'gender')
def __init__(self, name, gender):
self.name = name
self.gender = gender
class Student(Person):
__slots__ = ('score',)
def __init__(self, name, gender, score):
super(Student, self).__init__(name, gender)
self.score = score
s = Student('Bob', 'male', 59)
s.name = 'Tim'
s.score = 99
print s.score
class Person(object):
pass
class Student(Person):
pass
class Teacher(Person):
pass
class SkillMixin(object):
pass
class BasketballMixin(SkillMixin):
def skill(self):
return 'basketball'
class FootballMixin(SkillMixin):
def skill(self):
return 'football'
class BStudent(Student, BasketballMixin):
pass
class FTeacher(Teacher, FootballMixin):
pass
s = BStudent()
print s.skill()
t = FTeacher()
print t.skill()
''' | [
"563594467@qq.com"
] | 563594467@qq.com |
2ab3fb3795eb30b0dc859566175874912f1f9e7b | c34559f130c5c9eaa8027f768bfe90ef9521a271 | /tests/supportkit_tests.py | aab82ca0f44998d95e9cc722b8464bbe3b8d230d | [] | no_license | lemieux/supportkit-python | 2675408de6ab7fa79136cf4c63f6d9453cc8120e | 7b4b3d29e6a51a3d1a4be64d03811329f5ab505f | refs/heads/master | 2021-01-10T08:39:44.440765 | 2015-10-07T21:19:53 | 2015-10-07T21:19:53 | 43,841,977 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 159 | py |
from nose.tools import *
import supportkit
def setup():
print "SETUP!"
def teardown():
print "TEAR DOWN!"
def test_basic():
print "I RAN!"
| [
"marc@marcantoinelemieux.com"
] | marc@marcantoinelemieux.com |
f0d53247787de483a8157978732687647973de62 | 09e57dd1374713f06b70d7b37a580130d9bbab0d | /data/cirq_new/cirq_program/startCirq_Class651.py | dd0dd8db9096c5bbae3a183ddb1975f869ce8a2d | [
"BSD-3-Clause"
] | permissive | UCLA-SEAL/QDiff | ad53650034897abb5941e74539e3aee8edb600ab | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | refs/heads/main | 2023-08-05T04:52:24.961998 | 2021-09-19T02:56:16 | 2021-09-19T02:56:16 | 405,159,939 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,289 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=24
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
def make_circuit(n: int, input_qubit):
c = cirq.Circuit() # circuit begin
c.append(cirq.H.on(input_qubit[0])) # number=1
c.append(cirq.H.on(input_qubit[1])) # number=2
c.append(cirq.H.on(input_qubit[1])) # number=7
c.append(cirq.H.on(input_qubit[2])) # number=3
c.append(cirq.H.on(input_qubit[3])) # number=4
c.append(cirq.H.on(input_qubit[0])) # number=18
c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=19
c.append(cirq.H.on(input_qubit[0])) # number=20
c.append(cirq.H.on(input_qubit[0])) # number=10
c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=11
c.append(cirq.H.on(input_qubit[0])) # number=12
c.append(cirq.CNOT.on(input_qubit[2],input_qubit[0])) # number=8
c.append(cirq.H.on(input_qubit[0])) # number=13
c.append(cirq.CZ.on(input_qubit[2],input_qubit[0])) # number=14
c.append(cirq.H.on(input_qubit[0])) # number=15
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=21
c.append(cirq.X.on(input_qubit[2])) # number=22
c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=23
c.append(cirq.X.on(input_qubit[2])) # number=17
# circuit end
return c
def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
if __name__ == '__main__':
qubit_count = 4
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
circuit = make_circuit(qubit_count,input_qubits)
circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')
circuit_sample_count =0
info = cirq.final_state_vector(circuit)
qubits = round(log2(len(info)))
frequencies = {
np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)
for i in range(2 ** qubits)
}
writefile = open("../data/startCirq_Class651.csv","w+")
print(format(frequencies),file=writefile)
print("results end", file=writefile)
print(circuit.__len__(), file=writefile)
print(circuit,file=writefile)
writefile.close() | [
"wangjiyuan123@yeah.net"
] | wangjiyuan123@yeah.net |
f1a703e8a9a0d640da215f4b818d4aa7dc419291 | a424323a34a2fc5700d690829752d3e30032a1e6 | /routelanta/swagger_client/api/running_races_api.py | 36fb88060b123482bbc68d58707be9943f0ffc92 | [] | no_license | jackrager/jackrager.github.io | 884747803fa44063372efdbf46e36e979474d2fe | 50b9b62ca7a7fae6744796c1aa032f16cfad5898 | refs/heads/master | 2023-03-09T22:08:53.059755 | 2023-02-20T22:30:23 | 2023-02-20T22:30:23 | 228,740,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,501 | py | # coding: utf-8
"""
Strava API v3
The [Swagger Playground](https://developers.strava.com/playground) is the easiest way to familiarize yourself with the Strava API by submitting HTTP requests and observing the responses before you write any client code. It will show what a response will look like with different endpoints depending on the authorization scope you receive from your athletes. To use the Playground, go to https://www.strava.com/settings/api and change your “Authorization Callback Domain” to developers.strava.com. Please note, we only support Swagger 2.0. There is a known issue where you can only select one scope at a time. For more information, please check the section “client code” at https://developers.strava.com/docs. # noqa: E501
OpenAPI spec version: 3.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from swagger_client.api_client import ApiClient
class RunningRacesApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def get_running_race_by_id(self, id, **kwargs): # noqa: E501
"""Get Running Race # noqa: E501
Returns a running race for a given identifier. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_running_race_by_id(id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param int id: The identifier of the running race. (required)
:return: RunningRace
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_running_race_by_id_with_http_info(id, **kwargs) # noqa: E501
else:
(data) = self.get_running_race_by_id_with_http_info(id, **kwargs) # noqa: E501
return data
def get_running_race_by_id_with_http_info(self, id, **kwargs): # noqa: E501
"""Get Running Race # noqa: E501
Returns a running race for a given identifier. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_running_race_by_id_with_http_info(id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param int id: The identifier of the running race. (required)
:return: RunningRace
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_running_race_by_id" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params or
params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `get_running_race_by_id`") # noqa: E501
collection_formats = {}
path_params = {}
if 'id' in params:
path_params['id'] = params['id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['strava_oauth'] # noqa: E501
return self.api_client.call_api(
'/running_races/{id}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='RunningRace', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_running_races(self, **kwargs): # noqa: E501
"""List Running Races # noqa: E501
Returns a list running races based on a set of search criteria. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_running_races(async_req=True)
>>> result = thread.get()
:param async_req bool
:param int year: Filters the list by a given year.
:return: list[RunningRace]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_running_races_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.get_running_races_with_http_info(**kwargs) # noqa: E501
return data
def get_running_races_with_http_info(self, **kwargs): # noqa: E501
"""List Running Races # noqa: E501
Returns a list running races based on a set of search criteria. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_running_races_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param int year: Filters the list by a given year.
:return: list[RunningRace]
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['year'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_running_races" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'year' in params:
query_params.append(('year', params['year'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['strava_oauth'] # noqa: E501
return self.api_client.call_api(
'/running_races', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[RunningRace]', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
| [
"noreply@github.com"
] | noreply@github.com |
33280c23ce326b75e21f7c1e6b655ba9c1896cde | 9680ba23fd13b4bc0fc3ce0c9f02bb88c6da73e4 | /Bernd Klein (520) ile Python/p_20404a.py | bc54c21d16cad7c304cceedabad9a88e4a32d34d | [] | no_license | mnihatyavas/Python-uygulamalar | 694091545a24f50a40a2ef63a3d96354a57c8859 | 688e0dbde24b5605e045c8ec2a9c772ab5f0f244 | refs/heads/master | 2020-08-23T19:12:42.897039 | 2020-04-24T22:45:22 | 2020-04-24T22:45:22 | 216,670,169 | 0 | 0 | null | null | null | null | ISO-8859-9 | Python | false | false | 683 | py | # coding:iso-8859-9 Türkçe
# p_20404a.py: İnternet ip adresleriyle iletişim kontrolü örneği.
import os, re # threading/ipsiz kontrol...
alınanPaketler = re.compile (r"(\d) alındı")
durum = ("cevapsız", "canlı fakat kayıp", "canlı")
for sonek in range (20,30):
ip = "192.168.178." + str (sonek)
kontrol = os.popen ("çınlattı -q -c2 " + ip, "r")
print ("...çınlatıyor ", ip)
while True:
satır = kontrol.readsatır()
if not satır: break
alınan = alınanPaketler.findall (satır)
if alınan: print (ip + ": " + durum[int (alınan[0])])
#İnternet açık olmalı ve ilgili ip adresleri kontrol edilmeli... | [
"noreply@github.com"
] | noreply@github.com |
d26b48204806352ba4722be9cf5fc9324a9c0d14 | 54a0b86d4c3f731487ad4470fb365907970472e6 | /P1/studentparameters/Project1_Parameters_ad.py | abd32ecc8b79a7a3387eba925bcaeff4e5091637 | [] | no_license | samiurrahman98/ece458-computer-security | 26aa46e174b0bf77f748e6451dd2e0e4183feebd | cf79430b98e3679ffcd687a0c96b5e979187e1e3 | refs/heads/master | 2022-11-25T01:26:36.874094 | 2020-07-31T21:24:53 | 2020-07-31T21:24:53 | 280,979,038 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,771 | py | # Select the file name that matches your first two letters of your last name on Learn
# Read those parameters as your ECE458 project 1 parameters
# p,q,g are DSA domain parameters, sk_i (secret keys) are used in each signature and verification
p=16158504202402426253991131950366800551482053399193655122805051657629706040252641329369229425927219006956473742476903978788728372679662561267749592756478584653187379668070077471640233053267867940899762269855538496229272646267260199331950754561826958115323964167572312112683234368745583189888499363692808195228055638616335542328241242316003188491076953028978519064222347878724668323621195651283341378845128401263313070932229612943555693076384094095923209888318983438374236756194589851339672873194326246553955090805398391550192769994438594243178242766618883803256121122147083299821412091095166213991439958926015606973543
q=13479974306915323548855049186344013292925286365246579443817723220231
g=9891663101749060596110525648800442312262047621700008710332290803354419734415239400374092972505760368555033978883727090878798786527869106102125568674515087767296064898813563305491697474743999164538645162593480340614583420272697669459439956057957775664653137969485217890077966731174553543597150973233536157598924038645446910353512441488171918287556367865699357854285249284142568915079933750257270947667792192723621634761458070065748588907955333315440434095504696037685941392628366404344728480845324408489345349308782555446303365930909965625721154544418491662738796491732039598162639642305389549083822675597763407558360
sk1=11901278079431521417510182145794663264975691637509742253512537133135
sk2=5169869455587584420217628936034595597270984859924339992857774218592
sk3=270864169201384296687902210880717403152220842818569896183973535059
| [
"S72RAHMA@uwaterloo.ca"
] | S72RAHMA@uwaterloo.ca |
6127db8c4201697208fcbd427c8f2ff605b318ec | ea9aa0e93a7f264511ef10b5ccb90f65d958900f | /3rd_practice/blog/models.py | c0eca233fb31aebd733abc8ef197a867e51945e6 | [] | no_license | wayhome25/django_travel_blog_2 | 01cf4591e0aa69fb5a3144e0739bd43ce4bebc9c | 13e5d7ad2851febafb9a57e1fc93bb29c916c4c7 | refs/heads/master | 2020-06-01T08:58:24.492163 | 2017-08-26T13:19:45 | 2017-08-26T15:04:18 | 94,069,137 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,118 | py | from django.core.urlresolvers import reverse
from django.conf import settings
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
photo = models.ImageField()
is_public = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post_detail', args=[self.pk])
class Comment(models.Model):
post = models.ForeignKey(Post)
author = models.ForeignKey(settings.AUTH_USER_MODEL)
message = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-id']
def __str__(self):
return self.message
def get_edit_url(self):
return reverse('blog:comment_edit', args=[self.post.pk, self.pk])
def get_delete_url(self):
return reverse('blog:comment_delete', args=[self.post.pk, self.pk])
| [
"siwabada@gmail.com"
] | siwabada@gmail.com |
156c46403266268d942b197c55ec383227d63858 | 290d6fd35fd5433ef03bfcc1ec14108a1e8e10ed | /unittest1_task_perf.py | ed6c3d3fbd2180982107da0bcf232d07b551b8e8 | [] | no_license | PlumpMath/pyos | 3103e2c878f579aa10c32f8a3c3430b4d11de209 | c5b6e3fdb8e4d4615a5d098130a6e34c92217c65 | refs/heads/master | 2021-01-20T09:54:24.953803 | 2014-01-29T10:42:58 | 2014-01-29T10:42:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,899 | py | #!/usr/bin/python2
# Perf and Unit tests
#
# Test what happens with large numbers of tasks
# Simon Ryan 2014
from pyos9 import *
import sys,random,time,threading
mode = sys.argv[1:2] and sys.argv[1] or None
num = sys.argv[2:3] and sys.argv[2] or None
if not (mode and num):
print('usage: %s [pyos|threads] numberoftasks' % (sys.argv[0]))
sys.exit(1)
try:
num = int(num)
except:
num = 1000
now = time.time()
def readhellos():
yield SubscribeMessage('hello')
while 1:
# We need to go idle in order to listen for the message
yield Idle()
message = (yield)
if message and message[2] == 'quit':
break
def spawninator():
print('spawninator starting')
for i in xrange(num):
yield NewTask(readhellos())
print('spawninator finishing spawning %d tasks in %2.2f seconds' % (num,time.time() - now))
print('sending quit message')
yield Message('hello','quit')
class globs:
# Poor mans messaging for threads
timetodie = False
def simpletask():
# Something we can launch as a thread
while 1:
time.sleep(1)
if globs.timetodie:
break
if mode == 'pyos':
sched = Scheduler()
sched.new(spawninator())
sched.mainloop()
else:
# Do approximately the same but with threads
threadlist = []
for i in range(num):
try:
testthread = threading.Thread(target=simpletask)
testthread.start()
except:
print('Thread create error at thread number %d' % (i+1))
break
threadlist.append(testthread)
elapsed = time.time() - now
print('spawninator finishing spawning %d tasks in %2.2f seconds' % (num,elapsed))
globs.timetodie = True
for task in threadlist:
task.join()
elapsed = time.time() - now
print('Finished in %2.2f seconds' % (time.time() - now))
| [
"simon@smartblackbox.com"
] | simon@smartblackbox.com |
1ca2692d8354900cb36bdd5e40c951da55534123 | 3b562b977e337d09aa97a6b1289f2b3338aa9a68 | /extras.py | d45e205c5841b876f3e76a53542af8a4213e84ca | [] | no_license | Kolimar/AdivinaPalabra | 0bad2a957da1aa9f2443215f892dad52a93709f7 | 769741d6a183e7981c8b262def75138ba02a45e0 | refs/heads/master | 2020-04-25T08:16:33.521653 | 2019-02-26T05:26:14 | 2019-02-26T05:26:14 | 172,641,940 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,025 | py | import pygame
from pygame.locals import *
from configuracion import *
def ShowDireccion(direccion):
if direccion == [-1,-1]:
return "Abajo - izquierda"
if direccion == [-1,0]:
return "Abajo"
if direccion == [-1,1]:
return "Abajo - derecha"
if direccion == [0,-1]:
return "Izquierda"
if direccion == [0,0]:
return "<con el cursor> (8 dir)"
if direccion == [0,1]:
return "Derecha"
if direccion == [1,-1]:
return "Arriba - izquierda"
if direccion == [1,0]:
return "Arriba"
if direccion == [1,1]:
return "Arriba - derecha"
def LetraApretada(key):
if key == K_a:
return("a")
elif key == K_b:
return("b")
elif key == K_c:
return("c")
elif key == K_d:
return("d")
elif key == K_e:
return("e")
elif key == K_f:
return("f")
elif key == K_g:
return("g")
elif key == K_h:
return("h")
elif key == K_i:
return("i")
elif key == K_j:
return("j")
elif key == K_k:
return("k")
elif key == K_l:
return("l")
elif key == K_m:
return("m")
elif key == K_n:
return("n")
elif key == K_o:
return("o")
elif key == K_p:
return("p")
elif key == K_q:
return("q")
elif key == K_r:
return("r")
elif key == K_s:
return("s")
elif key == K_t:
return("t")
elif key == K_u:
return("u")
elif key == K_v:
return("v")
elif key == K_w:
return("w")
elif key == K_x:
return("x")
elif key == K_y:
return("y")
elif key == K_z:
return("z")
# elif key == K_SPACE:
# return(" ")
else:
return("")
## Esta funcion es opcional, sirve para debugging
def PrintMatriz(M, filas):
for i in range(filas):
print (M[i])
print()
## Es opcional usar esta funcion
def escribirEnPantalla(screen, palabra, posicion, tamano, color):
defaultFont= pygame.font.Font( pygame.font.get_default_font(), tamano)
ren = defaultFont.render(palabra, 1, color)
screen.blit(ren, posicion)
def dibujar(screen, candidata, letras, posiciones, puntos, segundos):
defaultFont= pygame.font.Font( pygame.font.get_default_font(), 20)
#Linea del piso
pygame.draw.line(screen, (255,255,255), (0, ALTO-70) , (ANCHO, ALTO-70), 5)
ren1 = defaultFont.render(candidata, 1, COLOR_TEXTO)
ren2 = defaultFont.render("Puntos: " + puntos, 1, COLOR_TEXTO)
if segundos<15 :
ren3 = defaultFont.render("Tiempo: " + str(int(segundos)), 1, COLOR_TIEMPO_FINAL)
else:
ren3 = defaultFont.render("Tiempo: " + str(int(segundos)), 1, COLOR_TEXTO)
for i in range(len(letras)):
screen.blit(defaultFont.render(letras[i], 1, COLOR_LETRAS), posiciones[i])
screen.blit(ren1, (190, 570))
screen.blit(ren2, (680, 10))
screen.blit(ren3, (10, 10))
def PosicionEnRango(fil, col):
return (0 <= fil) and (fil <= FILAS) and (0 <= col) and (col <= COLUMNAS)
### "Coordenadas gordas"
def dibujarMatriz(screen, MatLetras, puntos, intentos, palabra, fil, col, direccion, ganador, segundos, inputField):
defaultFont= pygame.font.Font(pygame.font.get_default_font(), TAMANNO_LETRA)
#dibuja grilla
bordeDerecha = (COLUMNAS+0.4) * ANCHO_COL
for i in range(FILAS):
coordY = PISO - i * ANCHO_FIL
pygame.draw.line(screen, (0,0,0), (0, coordY), (bordeDerecha, coordY), 3)
coordY -= ANCHO_FIL
pygame.draw.line(screen, (0,0,0), (0, coordY), (bordeDerecha, coordY), 3)
for j in range(COLUMNAS):
coordX = j * ANCHO_COL
pygame.draw.line(screen, (0,0,0), (coordX, coordY), (coordX, PISO), 3)
coordX -= ANCHO_FIL
pygame.draw.line(screen, (0,0,0), (bordeDerecha, coordY), (bordeDerecha, PISO), 3)
ren1a = defaultFont.render("Puntos: " + puntos, 1, COLOR_TEXTO)
ren1b = defaultFont.render("Intentos disponibles: " + str(intentos), 1, COLOR_TEXTO)
ren2 = defaultFont.render(ganador, 1, COLOR_TEXTO)
for i in range(FILAS):
for j in range(COLUMNAS):
if MatLetras[i][j] != 0 :
aux = str(MatLetras[i][j])
else:
aux = " "
screen.blit(defaultFont.render(aux, 1, COLOR_LETRAS),
((j+0.4) * ANCHO_COL, PISO - (i+1) * ANCHO_FIL))
if inputField == -1:
screen.blit(defaultFont.render("Intenta de nuevo!", 1, COLOR_RESALTADO), (bordeDerecha / 2, ALTO / 2 - ANCHO_FIL))
if inputField == 0:
color3a = COLOR_RESALTADO
color3b = COLOR_TEXTO
color3c = COLOR_TEXTO
color3d = COLOR_TEXTO
elif inputField == 1:
color3a = COLOR_TEXTO
color3b = COLOR_RESALTADO
color3c = COLOR_TEXTO
color3d = COLOR_TEXTO
elif inputField == 2:
color3a = COLOR_TEXTO
color3b = COLOR_TEXTO
color3c = COLOR_RESALTADO
color3d = COLOR_TEXTO
elif inputField == 3:
color3a = COLOR_TEXTO
color3b = COLOR_TEXTO
color3c = COLOR_TEXTO
color3d = COLOR_RESALTADO
if(fil!=""):
f = int(fil)
else:
f=-2
if(col!=""):
c = int(col)
else:
c=-2
if PosicionEnRango(f,c):
screen.blit(defaultFont.render(str(MatLetras[f][c]), 1, COLOR_RESALTADO),
((c+0.4) * ANCHO_COL, PISO - (f+1) * ANCHO_FIL))
else:
color3a = COLOR_TEXTO
color3b = COLOR_TEXTO
color3c = COLOR_TEXTO
color3d = COLOR_TEXTO
ren3a = defaultFont.render("Palabra: " + palabra, 1, color3a)
#ren3b = defaultFont.render("Fila: " + fil, 1, color3b)
#ren3c = defaultFont.render("Columna: " + col, 1, color3c)
#ren3d = defaultFont.render("Direccion: " + direccion, 1, color3d)
ren6 = defaultFont.render("Intentos Disponibles: " + str(intentos), 1, COLOR_TEXTO)
if intentos==0 or segundos<=0:
# CAMBIAR POR ALGO MAS LINDO
ren4 = defaultFont.render("Perdiste... Presiona S para salir", 1,(200,10,10))
screen.blit(ren4, (ANCHO_COL, ALTO / 2 + ANCHO_FIL))
if segundos<15:
color9 = COLOR_TIEMPO_FINAL
else:
color9 = COLOR_TEXTO
ren9 = defaultFont.render("Tiempo: " + str(int(segundos)), 1, color9)
screen.blit(ren1a, (ANCHO_COL, 10))
screen.blit(ren1b, (ANCHO_COL, 10 + ANCHO_FIL))
screen.blit(ren2, (ANCHO_COL, PISO + ANCHO_FIL * 5/3))
screen.blit(ren3a, (ANCHO_COL, ALTO / 2))
# screen.blit(ren4, (ANCHO_COL, ALTO / 2 + ANCHO_FIL))
# screen.blit(ren3c, (bordeDerecha + ANCHO_COL, ALTO / 2 + 2* ANCHO_FIL))
# screen.blit(ren3d, (bordeDerecha + ANCHO_COL, ALTO / 2 + 3* ANCHO_FIL))
screen.blit(ren9, (bordeDerecha / 2, 10))
| [
"noreply@github.com"
] | noreply@github.com |
fd6a2813514485429915c41e2b4f71e9b6aaa8a9 | e5217df72e21f2fe75bccd0fdd914432b6cce68e | /ds18b20_2.py | 18e103335f5f05cfeef2150c3c1a800510c5d664 | [] | no_license | tarjanyij/Python | 02411272758eb21be63a4bad07b3fce666718e08 | f3f4dbd961497001a88af00ffc9cb86772237da8 | refs/heads/main | 2023-04-03T20:10:09.577825 | 2021-04-08T19:37:20 | 2021-04-08T19:37:20 | 304,701,453 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 809 | py | import os
import sys
from time import sleep
from w1thermsensor import W1ThermSensor
def ds18b20_read_sensor():
data ={}
for sensor in W1ThermSensor.get_available_sensors():
#print("sor: %s Sensor %s has temperature %.2f" % (i,sensor.id, sensor.get_temperature()))
data.update({sensor.id : sensor.get_temperature()})
return data
if __name__ == '__main__':
try:
print("CTRL+C press to exit")
while True:
#ds18b20_read_sensor()
data = ds18b20_read_sensor()
#print (data)
for sensorid, temp in data.items():
print ("Sensor {} has temperature {}".format(sensorid, temp))
sleep(5)
except KeyboardInterrupt:
print(" ")
print("Bye") | [
"tarjanyi.jozsef@freemail.hu"
] | tarjanyi.jozsef@freemail.hu |
a924d5f770bc699d0607786b29a0763d26011f25 | 333abfacec09f1118c19fd07d340228a314b5ec3 | /ch2/ex_2.1-4_arbitrary_numerical_system_addition.py | 36b6035af17c1923087118d7170a6e5819a5234a | [] | no_license | olehb/ita3 | 18331d4ee298e60b70884bf25b24653e9c959ad4 | 23c412c647de0e89efba049c39f7d38375ff574b | refs/heads/master | 2023-05-29T08:30:13.039062 | 2015-05-08T16:03:03 | 2015-05-08T16:03:03 | 15,146,847 | 0 | 0 | null | 2023-05-17T05:18:52 | 2013-12-12T20:39:51 | Python | UTF-8 | Python | false | false | 250 | py | #!/usr/bin/env python3
base = 10
n = 4
n2 = (2, 2, 2, 2)
n1 = (0, 0, 3, 0)
result = []
r = 0
for i in range(n-1, -1, -1):
v = n1[i] + n2[i] + r
r = v // base
result.append(v % base)
if r>0:
result.append(r)
result.reverse()
print(result)
| [
"oleh.boiko@gmail.com"
] | oleh.boiko@gmail.com |
e2690fdaa4d677a52afa36499234099fce9dcb9f | e3ac7c428aa5b60e021a9440262320ff80f5be88 | /Ui/welcomescreen.py | 12640c6e51d951c0941192071407924a8f52cfc2 | [] | no_license | turamant/PyQt5-PhoneBook | b3423f978d2a368e6a997889095d13c5cb47a875 | 522490439889d91a40a651574339e80af6b6db1d | refs/heads/main | 2023-07-11T00:50:10.109781 | 2021-08-10T14:24:54 | 2021-08-10T14:24:54 | 391,993,150 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,599 | py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'welcomescreen.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(1178, 798)
self.widget = QtWidgets.QWidget(Dialog)
self.widget.setGeometry(QtCore.QRect(0, 0, 1181, 801))
self.widget.setMinimumSize(QtCore.QSize(831, 731))
self.widget.setStyleSheet("background-color: rgb(232, 232, 232);")
self.widget.setObjectName("widget")
self.labelWelcom = QtWidgets.QLabel(self.widget)
self.labelWelcom.setGeometry(QtCore.QRect(370, 110, 551, 131))
self.labelWelcom.setStyleSheet("font: 28pt \"DejaVu Math TeX Gyre\";\n"
"color: black;")
self.labelWelcom.setObjectName("labelWelcom")
self.loginPushButton = QtWidgets.QPushButton(self.widget)
self.loginPushButton.setGeometry(QtCore.QRect(240, 480, 191, 51))
self.loginPushButton.setStyleSheet("\n"
"font: 18pt \"Cantarell\";\n"
"background-color: rgb(232, 232, 232);")
self.loginPushButton.setObjectName("loginPushButton")
self.signupPushButton = QtWidgets.QPushButton(self.widget)
self.signupPushButton.setGeometry(QtCore.QRect(490, 480, 211, 51))
self.signupPushButton.setStyleSheet("\n"
"font: 18pt \"Cantarell\";\n"
"background-color: rgb(232, 232, 232);")
self.signupPushButton.setObjectName("signupPushButton")
self.cancelPushButton = QtWidgets.QPushButton(self.widget)
self.cancelPushButton.setGeometry(QtCore.QRect(760, 480, 211, 51))
self.cancelPushButton.setStyleSheet("background-color: rgb(232, 232, 232);\n"
"\n"
"font: 18pt \"Cantarell\";\n"
"")
self.cancelPushButton.setObjectName("cancelPushButton")
self.nameuserLineEdit = QtWidgets.QLineEdit(self.widget)
self.nameuserLineEdit.setGeometry(QtCore.QRect(370, 260, 461, 71))
self.nameuserLineEdit.setObjectName("nameuserLineEdit")
self.passwordLineEdit = QtWidgets.QLineEdit(self.widget)
self.passwordLineEdit.setGeometry(QtCore.QRect(370, 360, 461, 71))
self.passwordLineEdit.setObjectName("passwordLineEdit")
self.saveMeCheckBox = QtWidgets.QCheckBox(self.widget)
self.saveMeCheckBox.setGeometry(QtCore.QRect(470, 550, 291, 71))
self.saveMeCheckBox.setStyleSheet("font: 18pt \"Cantarell\";")
self.saveMeCheckBox.setObjectName("saveMeCheckBox")
self.echoPasswordCheckBox = QtWidgets.QCheckBox(self.widget)
self.echoPasswordCheckBox.setGeometry(QtCore.QRect(470, 600, 291, 71))
self.echoPasswordCheckBox.setStyleSheet("font: 18pt \"Cantarell\";")
self.echoPasswordCheckBox.setObjectName("echoPasswordCheckBox")
self.forgotPasswordPushButton = QtWidgets.QPushButton(self.widget)
self.forgotPasswordPushButton.setGeometry(QtCore.QRect(490, 690, 231, 36))
self.forgotPasswordPushButton.setStyleSheet("color: blue;\n"
"font: 14pt \"Cantarell\";\n"
"background-color: rgb(235, 235, 235);\n"
"border:0px;")
self.forgotPasswordPushButton.setObjectName("forgotPasswordPushButton")
self.changePasswordPushButton = QtWidgets.QPushButton(self.widget)
self.changePasswordPushButton.setGeometry(QtCore.QRect(490, 740, 231, 36))
self.changePasswordPushButton.setStyleSheet("color: blue;\n"
"font: 14pt \"Cantarell\";\n"
"background-color: rgb(235, 235, 235);\n"
"border:0px;")
self.changePasswordPushButton.setObjectName("changePasswordPushButton")
self.helpPushButton = QtWidgets.QPushButton(self.widget)
self.helpPushButton.setGeometry(QtCore.QRect(1060, 10, 113, 36))
self.helpPushButton.setStyleSheet("background-color: rgb(232, 232, 232);")
self.helpPushButton.setObjectName("helpPushButton")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.labelWelcom.setText(_translate("Dialog", "Окно авторизации"))
self.loginPushButton.setText(_translate("Dialog", "Войти"))
self.signupPushButton.setText(_translate("Dialog", "Регистрация"))
self.cancelPushButton.setText(_translate("Dialog", "Выход"))
self.nameuserLineEdit.setPlaceholderText(_translate("Dialog", " e-mail"))
self.passwordLineEdit.setWhatsThis(_translate("Dialog", "<html><head/><body><p>sdefesrgvesrgvegrvevgre</p><p>vrbge</p></body></html>"))
self.passwordLineEdit.setPlaceholderText(_translate("Dialog", " Пароль"))
self.saveMeCheckBox.setText(_translate("Dialog", "Запомнить меня"))
self.echoPasswordCheckBox.setText(_translate("Dialog", "Показать пароль"))
self.forgotPasswordPushButton.setText(_translate("Dialog", "Забыли пароль?"))
self.changePasswordPushButton.setText(_translate("Dialog", "Сменить пароль"))
self.helpPushButton.setText(_translate("Dialog", "Help"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
| [
"tur1amant@gmail.com"
] | tur1amant@gmail.com |
5db01072a7b1cfb52cc6a3b3c2a3401cc35537e6 | a5103b7d5066138ac1a9aabc273361491a5031cd | /course5/week1/rnn_utils.py | eafeffe54a31969af6913bbe0cbfc4a64948fa29 | [] | no_license | mckjzhangxk/deepAI | 0fa2f261c7899b850a4ec432b5a387e8c5f13e83 | 24e60f24b6e442db22507adddd6bf3e2c343c013 | refs/heads/master | 2022-12-13T18:00:12.839041 | 2021-06-18T03:01:10 | 2021-06-18T03:01:10 | 144,862,423 | 1 | 1 | null | 2022-12-07T23:31:01 | 2018-08-15T14:19:10 | Jupyter Notebook | UTF-8 | Python | false | false | 3,663 | py | import numpy as np
def _initial_parameters(n_x,n_a,n_y):
params={}
params['Waa'] = np.random.randn(n_a,n_a)
params['Wax'] = np.random.randn(n_a,n_x)
params['ba'] = np.random.randn(n_a,1)
params['Wya'] = np.random.randn(n_y,n_a)
params['by'] = np.random.randn(n_y,1)
return params
def _initial_gradients(params):
grads={'d'+key:np.zeros_like(value) for key,value in params.items()}
grads['da_next']=0
return grads
def softmax(x):
'''
x have shape [n,m]
:param x:
:return:
'''
x=x-np.max(x,axis=0,keepdims=True)
expx=np.exp(x)
expsum=np.sum(expx,axis=0,keepdims=True)
return expx/expsum
def _unpack(parameter):
return parameter['Waa'],parameter['Wax'],parameter['Wya'],parameter['ba'],parameter['by']
def _rnn_step_forward(xt,a_prev,parameter):
'''
:param xt:shape [nx,m]
:param a_prev: [na_m]
:param parameter: Waa,Wax,Way,bx,by
:return: cache all input and parameter,and a(i+1)
and a y_predition
'''
Waa, Wax, Wya, ba, by=_unpack(parameter)
a_out=np.tanh(Waa.dot(a_prev)+Wax.dot(xt)+ba)
ypred=softmax(Wya.dot(a_out)+by)
cache=xt,a_prev,a_out,parameter
return a_out,ypred,cache
def _rnn_step_backward(dy,cache,gradients):
'''
:param dy:shape[n_y,m]
:param cache:xt,a_prev,parameter
:param gradients: dWaa,dWy,dWax,dba,dby,da_next
:return:gradients
'''
xt,a_prev,a_out,parameter=cache
Waa, Wax, Wya, ba, by = _unpack(parameter)
#from linear prediction
dWya=dy.dot(a_out.T)
dby=np.sum(dy,axis=1,keepdims=True)
da_next=Wya.T.dot(dy)+gradients['da_next']
#from rnn units
dz=da_next*(1-a_out**2)
dWaa=dz.dot(a_prev.T)
dWax=dz.dot(xt.T)
dba=np.sum(dz,axis=1,keepdims=True)
gradients['da_next']=Waa.T.dot(dz)
gradients['dWaa']+=dWaa
gradients['dWax'] += dWax
gradients['dba'] += dba
gradients['dWya'] += dWya
gradients['dby'] += dby
return gradients
def _rnn_forward(x,a_prev,parameter):
'''
:param x: shape [n_x,m,T]
:param a_prev: shape [n_a,m]
:param parameter: Waa,Wax,Way,ba,by
:return: y_pred shape:[n_y,m,T],
caches:a list of all cache
'''
n_x,m,T=x.shape
n_y,n_a=parameter['Wya'].shape
#the return value
y_pred=np.zeros((n_y,m,T))
a_out=np.zeros((n_a,m,T))
caches=[]
for t in range(T):
a_prev,yhat,cache=_rnn_step_forward(x[:,:,t],a_prev,parameter)
y_pred[:,:,t]=yhat
a_out[:,:,t]=a_prev
caches.append(cache)
return y_pred,a_out,caches
def _rnn_backward(dy,caches,param):
'''
:param dy:shape[n_c,m,T]
:param caches: cahces of rnn_forward
:return: gradients
'''
n_y,m,T=dy.shape
gradients=_initial_gradients(param)
for t in reversed(range(T)):
gradients=_rnn_step_backward(dy[:,:,t],caches[t],gradients)
return gradients
def _computeLoss(yhat,y):
'''
:param yhat:
:param y:[n_y,m,T]
:return:
'''
#shape mxT
prob_of_trueLabel=np.sum(yhat*y,axis=0)
prob_of_trueLabel=prob_of_trueLabel.ravel()
loss=np.mean(-np.log(prob_of_trueLabel))
return loss
from keras.applications.vgg16 import VGG16
from keras.applications.vgg19 import VGG19
from keras.applications.resnet50 import ResNet50
from keras.applications.inception_v3 import InceptionV3
# VGG16()
VGG19()
ResNet50()
InceptionV3()
m,n_x,n_a,n_y,T=100,27,32,10,60
x=np.random.randn(n_x,m,T)
a_prev=np.random.randn(n_a,m)
params=_initial_parameters(n_x,n_a,n_y)
y_pred,a_out,caches=_rnn_forward(x,a_prev,params)
dy=np.random.randn(n_y,m,T)
gradients=_rnn_backward(dy,caches,params) | [
"mckj_zhangxk@163.com"
] | mckj_zhangxk@163.com |
85dfc959dee627d18e987008e72ca57b20a778f5 | ff4ac7422819d18dd8792b2b1dd92354f493bb23 | /assignments/autograder/autograde.py | cf78e62715fd25ea7a2d7cdd3fa2ca0045af3e7b | [
"MIT"
] | permissive | fyjgreatlion/cs-for-psych | 0b40cc0b5736632c2b3375c5092e6d7b74815418 | 647642f364d92bcdbc2320a4f527d2a0eba12ba9 | refs/heads/master | 2023-06-30T13:01:22.555967 | 2021-07-26T02:33:36 | 2021-07-26T02:33:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 513 | py | from grader import autograde, commit_and_push
from glob import glob
import typer
app = typer.Typer()
@app.command()
def run(path: str, summarize: bool=False, commit: bool=False, push: bool=False, root=None, grader=None, public=None, private=None):
grades = autograde(path, plot_it=summarize, root=root, grading_repo=grader, public_checks_dir=public, private_checks_dir=private)
if commit:
commit_and_push(path, grades.index.to_list(), debug=(not push))
if __name__ == "__main__":
app() | [
"jeremy.r.manning@dartmouth.edu"
] | jeremy.r.manning@dartmouth.edu |
e5122630508b4ef675f2ef514d43e70e1a838257 | 47d80dcfdbcea8a8527be73de6e57e1379be2c8b | /Django/quotes/Recipe/urls.py | 6354142d8f67a162ba971a6e187cb7e5da0b1afd | [] | no_license | tleysen/Webtech-4 | a23d1f2094e070a04aca1be4bb4ed38908104d0d | 8eee67e772fce1190b0681e106271c502a99b46a | refs/heads/master | 2021-01-23T16:12:56.765708 | 2017-09-07T12:20:46 | 2017-09-07T12:20:46 | 102,732,058 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 820 | py | """quotes URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^Recipes/', include('Recipes.urls')),
url(r'^admin/', admin.site.urls),
]
| [
"thomasleysen@MacBook-Air-van-Thomas.local"
] | thomasleysen@MacBook-Air-van-Thomas.local |
4df58b827efdb8b9e33d0f96ef24b7287e582d7b | 55668bc4e19fd9aa3caa4395add2fe73741eb844 | /206/main.py | 29930f8e53ae428345565b5f0a0b9b54dc5cbd5c | [
"MIT"
] | permissive | pauvrepetit/leetcode | cb8674e10b0dc6beb29e9b64a49bede857b889fd | 2fda37371f1c5afcab80214580e8e5fd72b48a3b | refs/heads/master | 2023-08-30T07:39:08.982036 | 2023-08-25T08:52:57 | 2023-08-25T08:52:57 | 151,678,677 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 905 | py | #
# @lc app=leetcode.cn id=206 lang=python3
#
# [206] 反转链表
#
from typing import Optional
# @lc code=start
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def rev(self, head: Optional[ListNode], prev: Optional[ListNode]) -> Optional[ListNode]:
if head == None:
return head
next = head.next
head.next = prev
if next == None:
return head
return self.rev(next, head)
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
return self.rev(head, None)
# if head == None or head.next == None:
# return head
# return self.rev(head.next, head)
# @lc code=end
a = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5, None)))))
Solution().reverseList(a) | [
"hu__ao@outlook.com"
] | hu__ao@outlook.com |
6b482961ceb846d151075be3e5574ce30b958fbb | 9c3c83007c5bf0f36635b0045b2aad7f8a11ac11 | /novice/03-02/variablerules.py | 04efe613839917730bde3cf315a1c00a8a16bb91 | [
"MIT"
] | permissive | septiannurtrir/praxis-academy | bc58f9484db36b36c202bf90fdfd359482b72770 | 1ef7f959c372ae991d74ccd373123142c2fbc542 | refs/heads/master | 2021-06-21T17:04:58.379408 | 2019-09-13T16:46:08 | 2019-09-13T16:46:08 | 203,007,994 | 1 | 0 | MIT | 2021-03-20T01:43:24 | 2019-08-18T13:38:23 | Python | UTF-8 | Python | false | false | 481 | py | from flask import Flask
app = Flask(__name__)
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % escape(username)
@app.route('/post/<int:post_id>')
def show_post(post_id):
#show the post with the given id, the id is an integer
return 'Post %d' % post_id
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
#show the subpath after /path/
return 'Subpath %s' % escape(subpath) | [
"septiannurtrir@gmail.com"
] | septiannurtrir@gmail.com |
3996a1c41e99afd8b6eabfd0864dad2c2f4c7187 | 13e1fb78955c03a75cf483725f4811abd1b51ac4 | /compiler/tests/03_wire_test.py | 61e21985e7422f475fa91e656c3f095e1c483963 | [
"BSD-3-Clause"
] | permissive | ucb-cs250/OpenRAM | d7a88695ac6820d03b4b365245a1c4962cdc546d | 3c5e13f95c925a204cabf052525c3de07638168f | refs/heads/master | 2023-01-23T15:09:35.183103 | 2020-10-12T16:05:07 | 2020-10-12T16:05:07 | 318,904,763 | 0 | 0 | BSD-3-Clause | 2020-12-05T22:47:14 | 2020-12-05T22:47:13 | null | UTF-8 | Python | false | false | 2,212 | py | #!/usr/bin/env python3
# See LICENSE for licensing information.
#
# Copyright (c) 2016-2019 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#
import unittest
from testutils import *
import sys
import os
sys.path.append(os.getenv("OPENRAM_HOME"))
import globals
class wire_test(openram_test):
def runTest(self):
config_file = "{}/tests/configs/config".format(os.getenv("OPENRAM_HOME"))
globals.init_openram(config_file)
import wire
import tech
import design
layer_stacks = [tech.poly_stack] + tech.beol_stacks
for reverse in [False, True]:
for stack in layer_stacks:
if reverse:
layer_stack = stack[::-1]
else:
layer_stack = stack
# Just make a conservative spacing. Make it wire pitch instead?
min_space = 2 * (tech.drc["minwidth_{}".format(layer_stack[0])] +
tech.drc["minwidth_{}".format(layer_stack[2])])
position_list = [[0, 0],
[0, 3 * min_space],
[1 * min_space, 3 * min_space],
[4 * min_space, 3 * min_space],
[4 * min_space, 0],
[7 * min_space, 0],
[7 * min_space, 4 * min_space],
[-1 * min_space, 4 * min_space],
[-1 * min_space, 0]]
position_list = [[x - min_space, y - min_space] for x, y in position_list]
w = design.design("wire_test_{}".format("_".join(layer_stack)))
wire.wire(w, layer_stack, position_list)
self.local_drc_check(w)
globals.end_openram()
# run the test from the command line
if __name__ == "__main__":
(OPTS, args) = globals.parse_args()
del sys.argv[1:]
header(__file__, OPTS.tech_name)
unittest.main(testRunner=debugTestRunner())
| [
"mrg@ucsc.edu"
] | mrg@ucsc.edu |
4db2e0c7af5d155f9cb641317fcba67abd59aea2 | fc36930722e170fa80b2f4195a15d686d138dc03 | /files_project/app.py | 58b803277ebe7f4911d9ad5f03b9c4db510932ea | [] | no_license | mayank4519/python_projects | d781ef3f81c1c6b3357351472019b8205c172897 | 4d0a84b9fae98cd194b6b73cbd83f6e2cc8b1ea4 | refs/heads/master | 2022-12-02T23:14:59.972893 | 2020-08-13T18:15:07 | 2020-08-13T18:15:07 | 266,676,174 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 244 | py | my_file = open('data.txt', 'r')
file_content = my_file.read()
my_file.close()
print(file_content)
#write into file
user_name = input("enter name")
my_file_writing = open('data.txt', 'w')
my_file_writing.write(user_name)
my_file_writing.close() | [
"mayankjn.jain1993@gmail.com"
] | mayankjn.jain1993@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.