blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
283
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
41
| license_type
stringclasses 2
values | repo_name
stringlengths 7
96
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 58
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 12.7k
662M
⌀ | star_events_count
int64 0
35.5k
| fork_events_count
int64 0
20.6k
| gha_license_id
stringclasses 11
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 43
values | src_encoding
stringclasses 9
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 7
5.88M
| extension
stringclasses 30
values | content
stringlengths 7
5.88M
| authors
sequencelengths 1
1
| author
stringlengths 0
73
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5ae2ba41318e5cf923f6e71130b05474ea22e368 | d3791c06d7a9434781330883aed6780283bd2e75 | /fastgreedy.py | 80355bdfa69608cb7ed9c91c3b179ea545feb979 | [] | no_license | saisrirammortha/Text-Document-Processing-For-Classification | 43f45a406c1dd7fe63bc82dfafb159ba135fff3a | 99ad04b61d7939ca975282bcc1db455a92cb44b1 | refs/heads/master | 2022-11-28T20:11:54.386201 | 2020-08-07T13:49:57 | 2020-08-07T13:49:57 | 181,516,626 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,006 | py |
def dist(a,b):
import math
n=len(a)
k=0
for i in range(0,n):
k=k+((a[i]-b[i])**2)
return math.sqrt(k)
def db(X,clusters):
n=len(X)
cno=0
temp=[]
for i in clusters:
if i not in temp:
cno=cno+1
temp.append(i)
index=0
centroid=[]
for i in range(0,cno):
cc=[]
count=0
k=0
for j in range(0,n):
if (clusters[j]==i):
cc=X[j]
k=j
count=count+1
break
for j in range(0,n):
if (clusters[j]==i) and (k!=j):
cc=cc+X[j]
count=count+1
cc=cc/count
centroid.append(cc)
cluster=[]
for i in range(0,cno):
cluster.append([])
for i in range(0,cno):
for j in range(0,n):
if (clusters[j]==i):
cluster[i].append(j)
selfcluster=[]
for i in range(0,cno):
k=0
for j in cluster[i]:
k=k+dist(X[j],centroid[i])
k=k/len(cluster[i])
selfcluster.append(k)
diff=[]
for i in range(0,cno):
a=[]
for j in range(0,cno):
a.append(dist(centroid[i],centroid[j]))
diff.append(a)
index=[]
for i in range(0,cno):
a=[]
for j in range(0,cno):
if (i==j):
a.append(0)
else:
k=(selfcluster[i]+selfcluster[j])/diff[i][j]
a.append(k)
index.append(a)
value=[0,0]
for i in range(0,cno):
value[0]=value[0]+max(index[i])
value[0]=value[0]/cno
den=max(selfcluster)
new=[]
for i in range(0,cno):
for j in diff[i]:
if (j!=0):
new.append(j)
num=min(new)
value[1]=num/den
print(value)
return value
f=open("finalvectors.txt","r")
a=[]
a=[[float(num) for num in line.split(",")] for line in f]
import numpy as np
myarray = np.asarray(a)
from igraph import *
g=Graph.Read("Finaldata.gml")
d=g.community_fastgreedy()
print("Fast Greedy Clustering ALgorithm\n")
print(d.as_clustering())
p=d.as_clustering()
assigned=[]
for i in range(0,100):
for j in range(0,2):
if i in p[j]:
assigned.append(j)
break
print(assigned)
value=db(myarray,assigned)
| [
"[email protected]"
] | |
42b3884ac70b7a2e76ae5bcede46e819ad0e8578 | a36a320fe0124da12c94f93756f38c716874e534 | /tst/tst_chk_srt.py | 15840e5d19a6a7b0982e53ca00657719b7356ece | [
"BSD-3-Clause"
] | permissive | geoallen/rrr | 76376431c30a9cf7369c1ea8e31f004cf9994c2d | a1b3f273b30d7fc034af63074ad6a6d6c19ba4eb | refs/heads/master | 2021-05-05T01:53:34.058607 | 2018-04-16T21:01:06 | 2018-04-16T21:01:06 | 119,757,564 | 0 | 0 | null | 2018-01-31T23:39:56 | 2018-01-31T23:39:55 | null | UTF-8 | Python | false | false | 5,362 | py | #!/usr/bin/env python2
#*******************************************************************************
#tst_chk_srt.py
#*******************************************************************************
#Purpose:
#Given a river connectivity file and a river ID file, this program checks that
#the river ID file is sorted from upstream to downstream. The river ID file
#can contain all the rivers of the domain, or only a subset of it.
#Author:
#Cedric H. David, 2007-2017
#*******************************************************************************
#Import Python modules
#*******************************************************************************
import sys
import csv
#*******************************************************************************
#Declaration of variables (given as command line arguments)
#*******************************************************************************
# 1 - rrr_con_file
# 2 - rrr_riv_file
#*******************************************************************************
#Get command line arguments
#*******************************************************************************
IS_arg=len(sys.argv)
if IS_arg < 3 or IS_arg > 3:
print('ERROR - 2 and only 2 arguments can be used')
raise SystemExit(22)
rrr_con_file=sys.argv[1]
rrr_riv_file=sys.argv[2]
#*******************************************************************************
#Print input information
#*******************************************************************************
print('Command line inputs')
print('- '+rrr_con_file)
print('- '+rrr_riv_file)
#*******************************************************************************
#Check if files exist
#*******************************************************************************
try:
with open(rrr_con_file) as file:
pass
except IOError as e:
print('ERROR - Unable to open '+rrr_con_file)
raise SystemExit(22)
try:
with open(rrr_riv_file) as file:
pass
except IOError as e:
print('ERROR - Unable to open '+rrr_riv_file)
raise SystemExit(22)
#*******************************************************************************
#Read files
#*******************************************************************************
print('Reading input files')
#-------------------------------------------------------------------------------
#rrr_con_file
#-------------------------------------------------------------------------------
IV_riv_tot_id=[]
IV_down_id=[]
with open(rrr_con_file,'rb') as csvfile:
csvreader=csv.reader(csvfile)
for row in csvreader:
IV_riv_tot_id.append(int(row[0]))
IV_down_id.append(int(row[1]))
IS_riv_tot=len(IV_riv_tot_id)
print('- Number of river reaches in rrr_con_file: '+str(IS_riv_tot))
#-------------------------------------------------------------------------------
#rrr_riv_file
#-------------------------------------------------------------------------------
IV_riv_bas_id=[]
with open(rrr_riv_file,'rb') as csvfile:
csvreader=csv.reader(csvfile)
for row in csvreader:
IV_riv_bas_id.append(int(row[0]))
IS_riv_bas=len(IV_riv_bas_id)
print('- Number of river reaches in rrr_riv_file: '+str(IS_riv_bas))
#*******************************************************************************
#Checking upstream to downstream sorting
#*******************************************************************************
print('Checking upstream to downstream sorting')
#-------------------------------------------------------------------------------
#Create hash table
#-------------------------------------------------------------------------------
IM_hsh={}
for JS_riv_bas in range(IS_riv_bas):
IM_hsh[IV_riv_bas_id[JS_riv_bas]]=JS_riv_bas
#This hash table contains the index of each reach ID in rrr_riv_file
#-------------------------------------------------------------------------------
#Check sorting
#-------------------------------------------------------------------------------
for JS_riv_tot in range(IS_riv_tot):
#Looping through all reach IDs in rrr_con_file
if IV_riv_tot_id[JS_riv_tot] in IM_hsh:
#Checking that the reach ID in rrr_con_file is in rrr_riv_file
JS_riv_bas1=IM_hsh[IV_riv_tot_id[JS_riv_tot]]
#JS_riv_bas1 is the index of reach ID in rrr_riv_file
if IV_down_id[JS_riv_tot] in IM_hsh:
#checking that the ID downstream of JS_riv_bas1 is in rrr_riv_file
JS_riv_bas2=IM_hsh[IV_down_id[JS_riv_tot]]
#JS_riv_bas2 is the index of the downstream ID in rrr_riv_file
else:
JS_riv_bas2=IS_riv_bas
#Largest value if downstream ID not in rrr_riv_file (also
#applies to ID=0.
if JS_riv_bas1 > JS_riv_bas2:
#checking that ID downstream is not earlier in rrr_riv_file
print('ERROR - rrr_riv_file not sorted from upstream to ' \
'downstream')
print('Reach ID '+str(IV_riv_tot_id[JS_riv_bas1])+ \
' is located above of '+str(IV_down_id[JS_riv_bas1]))
raise SystemExit(22)
print('Success!!!')
#*******************************************************************************
#End
#*******************************************************************************
| [
"[email protected]"
] | |
9e29b73e6b373690d991733fa6fcf7dc2ccec79c | 4334fc4e5e500c5c97fef73a31add1b726abbe5e | /03.FindGroup/downloadzebodata.py | 293e133e10a3f230f084533ca27ad2af29aad152 | [] | no_license | tkrs/collective.intelligence | 5a68d9774fa775d698a0419cd0522f79df8d946f | 7180e03182be7f7f4050863523c2b7147aa6af74 | refs/heads/master | 2016-09-11T04:09:20.688577 | 2014-06-25T17:51:23 | 2014-06-25T17:51:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 929 | py | from BeautifulSoup import BeautifulSoup
import urllib2
import re
chare = re.compile(r'[!-\.&]')
itemowners = {}
# ignore patterns
dropwrds = ['a', 'new', 'some', 'more', 'my', 'own', 'the', 'many', 'other', 'another']
currentuser = 0
for i in range(1, 51):
c = urllib2.urlopen(
'http://member.zebo.com/Main?event_key=USERSEARCH&wiowiw=wiw&keyword=car&page=%d' % (i))
soup = BeautifulSoup(c)
for td in soup('td'):
if ('class' in dict(td.attrs) and td['class'] == 'bgverdanasmall'):
items = [re.sub(chare, '', str(a.countents[0]).lower()).strip() for a in td('a')]
for item in items:
# 余計な単語を除去
txt = ' '.join([t for t in item.split(' ') if not t in dropwrds])
if len(txt) < 2: continue
itemowners.setdefault(txt, {})
itemowners[txt][currentuser] = 1
currentuser += 1
| [
"[email protected]"
] | |
8815c48bbe620eaecd88f26cf0fccb55bd3142a6 | 9a1791bca8787b5e789e5017219b7dafe145ac89 | /nnutil2/layers/debug.py | 418ccee4bd94c0df87cbd8e85dcac3192ad44548 | [
"BSD-3-Clause"
] | permissive | aroig/nnutil2 | 7f6086c0d555ec3820447ca64a948c29496a79a6 | 1fc77df351d4eee1166688e25a94287a5cfa27c4 | refs/heads/master | 2023-04-11T14:07:17.649496 | 2020-08-01T18:03:57 | 2020-08-01T18:03:57 | 196,260,872 | 0 | 0 | BSD-3-Clause | 2023-03-25T00:50:57 | 2019-07-10T19:04:00 | Python | UTF-8 | Python | false | false | 673 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# nnutil2 - Tensorflow utilities for training neural networks
# Copyright (c) 2019, Abdó Roig-Maranges <[email protected]>
#
# This file is part of 'nnutil2'.
#
# This file may be modified and distributed under the terms of the 3-clause BSD
# license. See the LICENSE file for details.
import tensorflow as tf
from .layer import Layer
class Debug(Layer):
def __init__(self, **kwargs):
super(Debug, self).__init__(**kwargs)
def compute_output_shape(self, input_shape):
return input_shape
def call(self, inputs):
print("Debug: shape = {}".format(inputs.shape))
return inputs
| [
"[email protected]"
] | |
3df0debeaf2e1dc76b3f8d82907893aba2e5e5b0 | fa455c127b669386a1b353554e1ecf14a13f173f | /FC_DenseNet_Tiramisu_org.py | 2724e2e3dacc33d831133dbbc7cff01fa1de9a96 | [] | no_license | gyeongchan-yun/computer-vision-project | f93340471baf132d8d5cdfa9d92d24722edd5b29 | 290d7ac7d57344d7b2482d13a9444e5ac19f97d5 | refs/heads/master | 2022-12-11T14:34:18.563367 | 2020-01-31T08:57:35 | 2020-01-31T08:57:35 | 237,391,713 | 0 | 0 | null | 2022-12-08T03:31:58 | 2020-01-31T08:46:32 | Python | UTF-8 | Python | false | false | 6,074 | py | from __future__ import division
import os,time,cv2
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
def preact_conv(inputs, n_filters, filter_size=[3, 3], dropout_p=0.2):
"""
Basic pre-activation layer for DenseNets
Apply successivly BatchNormalization, ReLU nonlinearity, Convolution and
Dropout (if dropout_p > 0) on the inputs
"""
preact = tf.nn.relu(slim.batch_norm(inputs))
conv = slim.conv2d(preact, n_filters, filter_size, activation_fn=None, normalizer_fn=None)
if dropout_p != 0.0:
conv = slim.dropout(conv, keep_prob=(1.0-dropout_p))
return conv
def DenseBlock(stack, n_layers, growth_rate, dropout_p, scope=None):
"""
DenseBlock for DenseNet and FC-DenseNet
Args:
stack: input 4D tensor
n_layers: number of internal layers
growth_rate: number of feature maps per internal layer
Returns:
stack: current stack of feature maps (4D tensor)
new_features: 4D tensor containing only the new feature maps generated
in this block
"""
with tf.name_scope(scope) as sc:
new_features = []
for j in range(n_layers):
# Compute new feature maps
layer = preact_conv(stack, growth_rate, dropout_p=dropout_p)
new_features.append(layer)
# stack new layer
stack = tf.concat([stack, layer], axis=-1)
new_features = tf.concat(new_features, axis=-1)
return stack, new_features
def TransitionLayer(inputs, n_filters, dropout_p=0.2, compression=1.0, scope=None):
"""
Transition layer for DenseNet
Apply 1x1 BN + conv then 2x2 max pooling
"""
with tf.name_scope(scope) as sc:
if compression < 1.0:
n_filters = tf.to_int32(tf.floor(n_filters*compression))
l = preact_conv(inputs, n_filters, filter_size=[1, 1], dropout_p=dropout_p)
l = slim.pool(l, [2, 2], stride=[2, 2], pooling_type='AVG')
return l
def TransitionDown(inputs, n_filters, dropout_p=0.2, scope=None):
"""
Transition Down (TD) for FC-DenseNet
Apply 1x1 BN + ReLU + conv then 2x2 max pooling
"""
with tf.name_scope(scope) as sc:
l = preact_conv(inputs, n_filters, filter_size=[1, 1], dropout_p=dropout_p)
l = slim.pool(l, [2, 2], stride=[2, 2], pooling_type='MAX')
return l
def TransitionUp(block_to_upsample, skip_connection, n_filters_keep, scope=None):
"""
Transition Up for FC-DenseNet
Performs upsampling on block_to_upsample by a factor 2 and concatenates it with the skip_connection
"""
with tf.name_scope(scope) as sc:
# Upsample
l = slim.conv2d_transpose(block_to_upsample, n_filters_keep, kernel_size=[3, 3], stride=[2, 2])
# Concatenate with skip connection
l = tf.concat([l, skip_connection], axis=-1)
return l
def build_fc_densenet(inputs, preset_model='FC-DenseNet56', num_classes=12, n_filters_first_conv=48, n_pool=5, growth_rate=12, n_layers_per_block=4, dropout_p=0.2, scope=None):
"""
Args:
n_classes: number of classes
n_filters_first_conv: number of filters for the first convolution applied
n_pool: number of pooling layers = number of transition down = number of transition up
growth_rate: number of new feature maps created by each layer in a dense block
n_layers_per_block: number of layers per block. Can be an int or a list of size 2 * n_pool + 1
dropout_p: dropout rate applied after each convolution (0. for not using)
"""
if preset_model == 'FC-DenseNet56':
n_pool=5
growth_rate=12
n_layers_per_block=4
elif preset_model == 'FC-DenseNet67':
n_pool=5
growth_rate=16
n_layers_per_block=5
elif preset_model == 'FC-DenseNet103':
n_pool=5
growth_rate=16
n_layers_per_block=[4, 5, 7, 10, 12, 15, 12, 10, 7, 5, 4]
if type(n_layers_per_block) == list:
assert (len(n_layers_per_block) == 2 * n_pool + 1)
elif type(n_layers_per_block) == int:
n_layers_per_block = [n_layers_per_block] * (2 * n_pool + 1)
else:
raise ValueError
with tf.variable_scope(scope, preset_model, [inputs]) as sc:
#####################
# First Convolution #
#####################
# We perform a first convolution.
stack = slim.conv2d(inputs, n_filters_first_conv, [3, 3], scope='first_conv')
n_filters = n_filters_first_conv
#####################
# Downsampling path #
#####################
skip_connection_list = []
for i in range(n_pool):
# Dense Block
stack, _ = DenseBlock(stack, n_layers_per_block[i], growth_rate, dropout_p, scope='denseblock%d' % (i+1))
n_filters += growth_rate * n_layers_per_block[i]
# At the end of the dense block, the current stack is stored in the skip_connections list
skip_connection_list.append(stack)
# Transition Down
stack = TransitionDown(stack, n_filters, dropout_p, scope='transitiondown%d'%(i+1))
skip_connection_list = skip_connection_list[::-1]
#####################
# Bottleneck #
#####################
# Dense Block
# We will only upsample the new feature maps
stack, block_to_upsample = DenseBlock(stack, n_layers_per_block[n_pool], growth_rate, dropout_p, scope='denseblock%d' % (n_pool + 1))
#######################
# Upsampling path #
#######################
for i in range(n_pool):
# Transition Up ( Upsampling + concatenation with the skip connection)
n_filters_keep = growth_rate * n_layers_per_block[n_pool + i]
stack = TransitionUp(block_to_upsample, skip_connection_list[i], n_filters_keep, scope='transitionup%d' % (n_pool + i + 1))
# Dense Block
# We will only upsample the new feature maps
stack, block_to_upsample = DenseBlock(stack, n_layers_per_block[n_pool + i + 1], growth_rate, dropout_p, scope='denseblock%d' % (n_pool + i + 2))
#####################
# Softmax #
#####################
net = slim.conv2d(stack, num_classes, [1, 1], scope='logits')
return net | [
"[email protected]"
] | |
d55a3164fd73e3a5fcbacf91e9d1ded395dafa83 | 366f6414e7ee6f5f032fb0ce395184aae1c24014 | /projectAwwards/serializer.py | c77674711754190d3eef3d72e8026864064f13c8 | [] | no_license | praize-laurine/Awwards | 271910bce5d31e0cabe6e65ba3660e49871f30c3 | 4c6a10abe17b2f08e06c27967ea8d044d0630964 | refs/heads/master | 2023-02-22T15:05:33.301611 | 2021-01-29T07:00:48 | 2021-01-29T07:00:48 | 331,952,987 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 356 | py | from rest_framework import serializers
from .models import Profile,Project
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('user','bio')
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ('title','description','url_link','user') | [
"[email protected]"
] | |
a95c69a39de74191a2cf07f7bbe52fda833d9226 | 58ee6d6e86a026cebcd51e146f37d30061f95e91 | /tutorial/quickstart/views.py | 99bc313def55a655d0ac568ab106cc8141d16847 | [] | no_license | SFSeiei/tutorial | fa7e28dbba0bd0e7a43630c882d52b123a78fe8d | dcda7533d80b9c89975884a2676243058f38d944 | refs/heads/master | 2020-08-31T10:47:55.636779 | 2019-10-31T06:19:26 | 2019-10-31T06:19:26 | 218,673,324 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 936 | py | from django.shortcuts import render
# Create your views here.
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
from django.shortcuts import redirect, HttpResponse, reverse
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
# 不知道为什么不行
class Test(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
print("this is test_class.")
def test_func():
return HttpResponse("this is test_func.")
| [
"[email protected]"
] | |
1cdb295c7d4c5f4d444031d64b2eaf82620aa1e4 | 058749c63b46987c371edb227669332f297316cc | /2_AddTwoNumbers.py | 1256ea6dfb9a6709d9b324466b705a0d4bc0e29a | [] | no_license | gaosheng19920801/leetcode | 764b6e5c1e8ee449f23b6999fb2820c0088e0921 | f6752ba1010ed44e69f29274865f1788f0b31600 | refs/heads/master | 2021-06-21T18:43:36.838786 | 2021-05-10T13:43:02 | 2021-05-10T13:43:02 | 219,732,754 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,348 | py | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def printList(self):
while self:
print(self.val)
self = self.next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
dummyHead = ListNode(0)
currNode = dummyHead
carry = 0
while l1 or l2:
if l1:
x = l1.val
else:
x = 0
if l2:
y = l2.val
else:
y = 0
sum = x + y + carry
carry = sum // 10
currNode.next = ListNode(sum % 10)
currNode = currNode.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
if carry > 0:
currNode.next = ListNode(carry)
return dummyHead.next
'''
def main():
num1 = ListNode(2)
num1.next = ListNode(4)
num1.next.next = ListNode(3)
num2 = ListNode(5)
num2.next = ListNode(6)
num2.next.next = ListNode(4)
solution = Solution()
result = solution.addTwoNumbers(num1,num2)
result.printList()
print('end')
if __name__ == '__main__':
main()
'''
| [
"[email protected]"
] | |
a4aaf4f6008b047c676dfce3d862c91abf2f8237 | d53dd5d21588e210e00b6d765179aff934e2f24a | /instrumentation/instrumentation.py | 79657d9440b7e06a745e171c90d79dc820d828f9 | [
"Apache-2.0"
] | permissive | iobeam/samples-python | 8ad8a93b3fbd6478a0b5552a72b2545d9c261520 | b275e9515785ae346478f3a69e01463cc19d5354 | refs/heads/master | 2020-05-17T06:06:46.365775 | 2016-01-28T22:21:49 | 2016-01-28T22:21:49 | 41,765,693 | 2 | 0 | null | 2015-12-19T00:09:36 | 2015-09-01T22:02:09 | Python | UTF-8 | Python | false | false | 2,351 | py | from iobeam import iobeam
import datetime
import time
###########################
# Template for a basic instrumentation app.
#
# This template outlines a script that periodically transmits device instrumentation
# data (e.g., temperature, humidity, gps, etc.) to iobeam.
#
# Instructions:
#
# 0. Add your project info below and name this device
#
# 1. Run with placeholder data from command line:
# python instrumentation.py
#
# 2. Replace placeholder data with device specific code below in each of the
# template functions
#
# 3. Run again with your real data!
#
#
###########################
###########################
# Your project info
###########################
PROJECT_ID = # YOUR PROJECT ID HERE (int)
PROJECT_TOKEN = # YOUR PROJECT TOKEN HERE (String)
DEVICE_ID = # ID FOR THIS DEVICE (String)
DEVICE_NAME = # NAME FOR THIS DEVICE (String, can be the same as DEVICE_ID)
###########################
# Template functions
# NOTE: Fill your own code here
###########################
def get_temperature():
return 72 # placeholder
def get_humidity():
return 0.6 # placeholder
def get_gps():
return (42.359155,-71.0952463) # placeholder
###########################
# Data collection / transmission
###########################
def main():
# Build iobeam client
builder = iobeam.ClientBuilder(PROJECT_ID, PROJECT_TOKEN).saveToDisk().registerOrSetId(DEVICE_ID, deviceName=DEVICE_NAME)
client = builder.build()
# Create data store with schema for transmitted data
# Note: Update this schema with any new instrumentation data types
measurements = client.createDataStore(["temperature", "humidity", "lat", "long"])
# Loop
while True:
# Collect data
now = int(time.time()*1000)
temperature = get_temperature()
humidity = get_humidity()
gps_lat, gps_long = get_gps()
# Add data points to data store
measurements.add(now, {"temperature": temperature, "humidity": humidity, "lat": gps_lat, "long": gps_long})
# Send data to iobeam
client.send()
# Print out data for debugging
dt = datetime.datetime.fromtimestamp(now/1000.0)
print('Sent: (Temperature: {:.2f}, Humidity: {:.2f}, (Lat, Long): ({:.6f}, {:.6f}) at {}'.format(temperature, humidity*100, gps_lat, gps_long, dt))
# Sleep for a bit (30 sec)
time.sleep(30)
if __name__ == "__main__":
main()
| [
"[email protected]"
] | |
745610ac743cdea2d4adb68730d67d5a100c65b7 | e50d7e173f76d4e0c9f297a1dca2ecff898daf7f | /config.py | f20bd8400b18a5dabee48365417d75b7d77f46a0 | [] | no_license | joshandrews/emilymcintyre.ca | 242d9f9bb5aa3b8ef40c718ca47968a3e6ae27ec | b22077896a90f7b77972bdd851329e3d0d030ceb | refs/heads/master | 2021-01-18T12:54:56.776590 | 2015-01-16T00:35:33 | 2015-01-16T00:35:33 | 28,666,992 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,721 | py | #!/usr/bin/env python
import ConfigParser
import os.path
class Config:
def __init__(self):
self.config = ConfigParser.ConfigParser()
if not os.path.isfile("americano.ini"):
cfgfile = open("americano.ini",'w')
self.config.add_section('MySQL')
self.config.add_section("Preferences")
self.config.add_section("Info")
self.config.set("Preferences", "ExtraHeaderEnabled", "False")
self.config.set("Preferences", "Colors", "Default")
self.config.set('Preferences', 'indexbackgroundurl', "http://photos-c.ak.instagram.com/hphotos-ak-xpa1/t51.2885-15/10369418_255518024631354_1092534291_n.jpg")
self.config.set("Info", "Installed", "1")
self.config.write(cfgfile)
cfgfile.close()
else:
self.config.read("americano.ini")
def setMySQLUsername(self, username):
cfgfile = open("americano.ini",'w')
self.config.set('MySQL','username',username)
self.config.write(cfgfile)
cfgfile.close()
def setMySQLPassword(self, password):
cfgfile = open("americano.ini",'w')
self.config.set('MySQL','password',password)
self.config.write(cfgfile)
cfgfile.close()
def setMySQLDatabase(self, database):
cfgfile = open("americano.ini",'w')
self.config.set('MySQL','database',database)
self.config.write(cfgfile)
cfgfile.close()
def setName(self, name):
cfgfile = open("americano.ini",'w')
self.config.set('Info','name',name)
self.config.write(cfgfile)
cfgfile.close()
def setInstalled(self, val):
cfgfile = open("americano.ini",'w')
self.config.set('Info','installed',val)
self.config.write(cfgfile)
cfgfile.close()
def setIndexBackgroundUrl(self, val):
cfgfile = open("americano.ini",'w')
self.config.set('Preferences','indexbackgroundurl',val)
self.config.write(cfgfile)
cfgfile.close()
def ConfigSectionMap(self, section):
dict1 = {}
self.config.read('americano.ini')
options = self.config.options(section)
for option in options:
try:
dict1[option] = self.config.get(section, option)
if dict1[option] == -1:
print "skip: %s" % option
except:
print("exception on %s!" % option)
dict1[option] = None
return dict1
if __name__ == '__main__':
con = Config()
con.setMySQLUsername("admin")
con.setMySQLPassword("andre")
con.setMySQLDatabase("blog")
print con.ConfigSectionMap("MySQL")["database"]
| [
"[email protected]"
] | |
b626ae56932dee05bae3412201691ec260ae1044 | a8182e9ddf3229dc50c752bd3526fac1ae5862e6 | /app/cabotapp/calendar.py | 6759d13fb0b76e29667a70889b3974f3cfd53def | [
"MIT"
] | permissive | kowsik/heroku-cabot | bb2159cf24398060551e55e10d0d893c2a10f405 | faa6b24606c7c30e8fdeb857d3ad0bf1347cb490 | refs/heads/master | 2021-01-17T18:05:26.269311 | 2014-04-28T18:04:41 | 2014-04-28T18:04:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 583 | py |
from django.conf import settings
from icalendar import Calendar, Event
import requests
def get_calendar_data():
feed_url = settings.CALENDAR_ICAL_URL
resp = requests.get(feed_url)
cal = Calendar.from_ical(resp.content)
return cal
def get_events():
events = []
for component in get_calendar_data().walk():
if component.name == 'VEVENT':
events.append({
'start': component.decoded('dtstart'),
'end': component.decoded('dtend'),
'summary': component.decoded('summary'),
'uid': component.decoded('uid'),
})
return events | [
"[email protected]"
] | |
5aa055671b51307ce7e5d87a5287cc6d5064c1a9 | d1b1cd3710d0f5f248ace0d1230fc2a2170f7dc9 | /sc2/agent/DRLAgentWithNaiveDQN_phil.py | a73861718d2fb825ed55d6ce84b6896ecdda9658 | [] | no_license | prokokok/starcraft2_rl | a7e7a1d20972d232af83457a952cfbe9c52394fc | ade3b1cc3537f990a4581da132f40b2766518962 | refs/heads/master | 2022-12-28T01:12:16.085932 | 2020-09-22T01:36:26 | 2020-09-22T01:36:26 | 296,833,774 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 17,690 | py | import random
import time
import math
import os.path
import numpy as np
import pandas as pd
from pysc2.agents import base_agent
from pysc2.env import sc2_env, run_loop
from pysc2.lib import actions, features, units
from absl import app
import torch
from torch.utils.tensorboard import SummaryWriter
from skdrl.pytorch.model.mlp import NaiveMultiLayerPerceptron
from skdrl.pytorch.model.naivedqn import NaiveDQN
from skdrl.pytorch.util.train_util import EMAMeter
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
writer = SummaryWriter()
class ProtossAgentWithRawActsAndRawObs(base_agent.BaseAgent):
actions = ("do_nothing",
"harvest_minerals",
"build_pylons",
"build_gateways",
"train_zealot",
"attack")
def get_my_units_by_type(self, obs, unit_type):
return [unit for unit in obs.observation.raw_units
if unit.unit_type == unit_type
and unit.alliance == features.PlayerRelative.SELF]
def get_enemy_units_by_type(self, obs, unit_type):
return [unit for unit in obs.observation.raw_units
if unit.unit_type == unit_type
and unit.alliance == features.PlayerRelative.ENEMY]
def get_my_completed_units_by_type(self, obs, unit_type):
return [unit for unit in obs.observation.raw_units
if unit.unit_type == unit_type
and unit.build_progress == 100
and unit.alliance == features.PlayerRelative.SELF]
def get_enemy_completed_units_by_type(self, obs, unit_type):
return [unit for unit in obs.observation.raw_units
if unit.unit_type == unit_type
and unit.build_progress == 100
and unit.alliance == features.PlayerRelative.ENEMY]
def get_distances(self, obs, units, xy):
units_xy = [(unit.x, unit.y) for unit in units]
return np.linalg.norm(np.array(units_xy) - np.array(xy), axis=1)
def getMeanLocation(self, unitList):
sum_x = 0
sum_y = 0
for unit in unitList:
sum_x += unit.x
sum_y += unit.y
mean_x = sum_x / len(unitList)
mean_y = sum_y / len(unitList)
return [mean_x, mean_y]
def transformDistance(self, x, x_distance, y, y_distance):
if not self.base_top_left:
return [x - x_distance, y - y_distance]
return [x + x_distance, y + y_distance]
def step(self, obs):
super(ProtossAgentWithRawActsAndRawObs, self).step(obs)
if obs.first():
nexus = self.get_my_units_by_type(
obs, units.Protoss.Nexus)[0]
self.base_top_left = (nexus.x < 32)
def do_nothing(self, obs):
return actions.RAW_FUNCTIONS.no_op()
def harvest_minerals(self, obs):
probes = self.get_my_units_by_type(obs, units.Protoss.Probe)
idle_probes = [probe for probe in probes if probe.order_length == 0]
if len(idle_probes) > 0:
mineral_patches = [unit for unit in obs.observation.raw_units
if unit.unit_type in [
units.Neutral.BattleStationMineralField,
units.Neutral.BattleStationMineralField750,
units.Neutral.LabMineralField,
units.Neutral.LabMineralField750,
units.Neutral.MineralField,
units.Neutral.MineralField750,
units.Neutral.PurifierMineralField,
units.Neutral.PurifierMineralField750,
units.Neutral.PurifierRichMineralField,
units.Neutral.PurifierRichMineralField750,
units.Neutral.RichMineralField,
units.Neutral.RichMineralField750
]]
probe = random.choice(idle_probes)
distances = self.get_distances(obs, mineral_patches, (probe.x, probe.y))
mineral_patch = mineral_patches[np.argmin(distances)]
return actions.RAW_FUNCTIONS.Harvest_Gather_unit(
"now", probe.tag, mineral_patch.tag)
return actions.RAW_FUNCTIONS.no_op()
def build_pylons(self, obs):
nexus = self.get_my_units_by_type(obs, units.Protoss.Nexus)
pylons = self.get_my_units_by_type(obs, units.Protoss.Pylon)
probes = self.get_my_units_by_type(obs, units.Protoss.Probe)
if len(nexus) == 1 and len(pylons) == 0 and obs.observation.player.minerals >= 100:
mean_x, mean_y = self.getMeanLocation(nexus)
pylon_xy = self.transformDistance(int(mean_x), -20, int(mean_y), 30)
distances = self.get_distances(obs, probes, pylon_xy)
probe = probes[np.argmin(distances)]
return actions.RAW_FUNCTIONS.Build_Pylon_pt(
"now", probe.tag, pylon_xy)
elif len(pylons) > 0:
pylon_coordinate = []
for pylon in pylons:
pylon_coordinate.append((pylon.x, pylon.y))
x_coordinate, y_coordinate = max(pylon_coordinate, key=lambda t: t[1])
pylon_xy = self.transformDistance(int(x_coordinate), 10, int(y_coordinate), 0)
distances = self.get_distances(obs, probes, pylon_xy)
probe = probes[np.argmin(distances)]
return actions.RAW_FUNCTIONS.FUNCTIONS.Build_Pylon_pt("now", probe.tag, pylon_xy)
return actions.RAW_FUNCTIONS.no_op()
def build_gateways(self, obs):
completed_pylons = self.get_my_completed_units_by_type(obs, units.Protoss.Pylon)
gateways = self.get_my_units_by_type(obs, units.Protoss.Gateway)
probes = self.get_my_units_by_type(obs, units.Protoss.Probe)
if (len(completed_pylons) > 0 and len(gateways) == 0 and
obs.observation.player.minerals >= 150 and len(probes) > 0):
target_pylon = random.choice(completed_pylons)
gateway_xy = self.transformDistance(int(target_pylon.x), 0, int(target_pylon.y), -10)
distances = self.get_distances(obs, probes, gateway_xy)
probe = probes[np.argmin(distances)]
return actions.RAW_FUNCTIONS.Build_Gateway_pt("now", probe.tag, gateway_xy)
return actions.RAW_FUNCTIONS.no_op()
def train_marine(self, obs):
completed_gateways = self.get_my_completed_units_by_type(
obs, units.Protoss.Gateway)
free_supply = (obs.observation.player.food_cap -
obs.observation.player.food_used)
if (len(completed_gateways) > 0 and obs.observation.player.minerals >= 100
and free_supply > 1):
gateways = self.get_my_units_by_type(obs, units.Protoss.Gateway)
gateway = random.choice(gateways)
if gateway.order_length < 5:
return actions.RAW_FUNCTIONS.Train_Zealot_quick("now", gateway.tag)
return actions.RAW_FUNCTIONS.no_op()
def attack(self, obs):
zealots = self.get_my_units_by_type(obs, units.Protoss.Zealot)
if len(zealots) > 0:
attack_xy = (38, 44) if self.base_top_left else (19, 23)
x_offset = random.randint(-4, 4)
y_offset = random.randint(-4, 4)
zealots_tags = [zealot.tag for zealot in zealots]
return actions.RAW_FUNCTIONS.Attack_pt(
"now", zealots_tags, (attack_xy[0] + x_offset, attack_xy[1] + y_offset))
return actions.RAW_FUNCTIONS.no_op()
class ProtossRandomAgent(ProtossAgentWithRawActsAndRawObs):
def step(self, obs):
super(ProtossRandomAgent, self).step(obs)
action = random.choice(self.actions)
return getattr(self, action)(obs)
class ProtossRLAgentWithRawActsAndRawObs(ProtossAgentWithRawActsAndRawObs):
def __init__(self):
super(ProtossRLAgentWithRawActsAndRawObs, self).__init__()
self.s_dim = 21
self.a_dim = 6
self.lr = 1e-4
self.gamma = 1.0
self.epsilon = 1.0
self.qnetwork = NaiveMultiLayerPerceptron(input_dim=self.s_dim,
output_dim=self.a_dim,
num_neurons=[128],
hidden_act_func='ReLU',
out_act_func='Identity').to(device)
self.data_file = 'rlagent_with_naive_dqn'
if os.path.isfile(self.data_file + '.pt'):
self.qnetwork.load_state_dict(torch.load(self.data_file + '.pt'))
self.dqn = NaiveDQN(state_dim=self.s_dim,
action_dim=self.a_dim,
qnet=self.qnetwork,
lr=self.lr,
gamma=self.gamma,
epsilon=self.epsilon).to(device)
self.print_every = 50
self.ema_factor = 0.5
self.ema = EMAMeter(self.ema_factor)
self.cum_reward = 0
self.cum_loss = 0
self.episode_count = 0
self.new_game()
def reset(self):
super(TerranRLAgentWithRawActsAndRawObs, self).reset()
self.new_game()
def new_game(self):
self.base_top_left = None
self.previous_state = None
self.previous_action = None
self.cum_reward = 0
self.cum_loss = 0
def get_state(self, obs):
scvs = self.get_my_units_by_type(obs, units.Terran.SCV)
idle_scvs = [scv for scv in scvs if scv.order_length == 0]
command_centers = self.get_my_units_by_type(obs, units.Terran.CommandCenter)
supply_depots = self.get_my_units_by_type(obs, units.Terran.SupplyDepot)
completed_supply_depots = self.get_my_completed_units_by_type(
obs, units.Terran.SupplyDepot)
barrackses = self.get_my_units_by_type(obs, units.Terran.Barracks)
completed_barrackses = self.get_my_completed_units_by_type(
obs, units.Terran.Barracks)
marines = self.get_my_units_by_type(obs, units.Terran.Marine)
queued_marines = (completed_barrackses[0].order_length
if len(completed_barrackses) > 0 else 0)
free_supply = (obs.observation.player.food_cap -
obs.observation.player.food_used)
can_afford_supply_depot = obs.observation.player.minerals >= 100
can_afford_barracks = obs.observation.player.minerals >= 150
can_afford_marine = obs.observation.player.minerals >= 100
enemy_scvs = self.get_enemy_units_by_type(obs, units.Terran.SCV)
enemy_idle_scvs = [scv for scv in enemy_scvs if scv.order_length == 0]
enemy_command_centers = self.get_enemy_units_by_type(
obs, units.Terran.CommandCenter)
enemy_supply_depots = self.get_enemy_units_by_type(
obs, units.Terran.SupplyDepot)
enemy_completed_supply_depots = self.get_enemy_completed_units_by_type(
obs, units.Terran.SupplyDepot)
enemy_barrackses = self.get_enemy_units_by_type(obs, units.Terran.Barracks)
enemy_completed_barrackses = self.get_enemy_completed_units_by_type(
obs, units.Terran.Barracks)
enemy_marines = self.get_enemy_units_by_type(obs, units.Terran.Marine)
return (len(command_centers),
len(scvs),
len(idle_scvs),
len(supply_depots),
len(completed_supply_depots),
len(barrackses),
len(completed_barrackses),
len(marines),
queued_marines,
free_supply,
can_afford_supply_depot,
can_afford_barracks,
can_afford_marine,
len(enemy_command_centers),
len(enemy_scvs),
len(enemy_idle_scvs),
len(enemy_supply_depots),
len(enemy_completed_supply_depots),
len(enemy_barrackses),
len(enemy_completed_barrackses),
len(enemy_marines))
def step(self, obs):
super(TerranRLAgentWithRawActsAndRawObs, self).step(obs)
#time.sleep(0.5)
state = self.get_state(obs)
state = torch.tensor(state).float().view(1, self.s_dim).to(device)
action_idx = self.dqn.choose_action(state)
action = self.actions[action_idx]
done = True if obs.last() else False
if self.previous_action is not None:
loss = self.dqn.learn(self.previous_state.to(device),
torch.tensor(self.previous_action).view(1, 1).to(device),
torch.tensor(obs.reward).view(1, 1).to(device),
state.to(device),
torch.tensor(done).float().view(1, 1).to(device)
)
self.cum_loss += loss.detach().numpy()
self.cum_reward += obs.reward
self.previous_state = state
self.previous_action = action_idx
if obs.last():
self.episode_count = self.episode_count + 1
torch.save(self.dqn.qnet.state_dict(), self.data_file + '.pt')
self.ema.update(self.cum_reward)
writer.add_scalar("Loss/online", self.cum_loss/obs.observation.game_loop, self.episode_count)
writer.add_scalar("Score", self.ema.s, self.episode_count)
if self.episode_count % self.print_every == 0:
print("Episode {} || EMA: {} || EPS : {}".format(self.episode_count, self.ema.s, self.dqn.epsilon))
if self.episode_count >= 150:
self.dqn.epsilon *= 0.999
return getattr(self, action)(obs)
# def main(unused_argv):
# agent1 = TerranRLAgentWithRawActsAndRawObs()
# agent2 = TerranRandomAgent()
# try:
# with sc2_env.SC2Env(
# map_name="Simple64",
# players=[sc2_env.Agent(sc2_env.Race.terran),
# sc2_env.Agent(sc2_env.Race.terran)],
# agent_interface_format=features.AgentInterfaceFormat(
# action_space=actions.ActionSpace.RAW,
# use_raw_units=True,
# raw_resolution=64,
# ),
# step_mul=8,
# disable_fog=True,
# ) as env:
# run_loop.run_loop([agent1, agent2], env, max_episodes=1000)
# except KeyboardInterrupt:
# pass
# def main(unused_argv):
# agent = TerranRLAgentWithRawActsAndRawObs()
# try:
# with sc2_env.SC2Env(
# map_name="Simple64",
# players=[sc2_env.Agent(sc2_env.Race.terran),
# sc2_env.Bot(sc2_env.Race.terran,
# sc2_env.Difficulty.very_easy)],
# agent_interface_format=features.AgentInterfaceFormat(
# action_space=actions.ActionSpace.RAW,
# use_raw_units=True,
# raw_resolution=64,
# ),
# step_mul=8,
# disable_fog=True,
# ) as env:
# agent.setup(env.observation_spec(), env.action_spec())
#
# timesteps = env.reset()
# agent.reset()
#
# while True:
# step_actions = [agent.step(timesteps[0])]
# if timesteps[0].last():
# break
# timesteps = env.step(step_actions)
# except KeyboardInterrupt:
# pass
# def main(unused_argv):
# agent = TerranRLAgentWithRawActsAndRawObs()
# try:
# while True:
# with sc2_env.SC2Env(
# map_name="Simple64",
# players=[sc2_env.Agent(sc2_env.Race.terran),
# sc2_env.Bot(sc2_env.Race.terran,
# sc2_env.Difficulty.very_easy)],
# agent_interface_format=features.AgentInterfaceFormat(
# action_space=actions.ActionSpace.RAW,
# use_raw_units=True,
# raw_resolution=64,
# ),
# step_mul=8,
# disable_fog=True,
# game_steps_per_episode=0,
# visualize=False) as env:
#
# agent.setup(env.observation_spec(), env.action_spec())
#
# timesteps = env.reset()
# agent.reset()
#
# while True:
# step_actions = [agent.step(timesteps[0])]
# if timesteps[0].last():
# break
# timesteps = env.step(step_actions)
#
# except KeyboardInterrupt:
# pass
def main(unused_argv):
agent1 = TerranRLAgentWithRawActsAndRawObs()
try:
with sc2_env.SC2Env(
map_name="Simple64",
players=[sc2_env.Agent(sc2_env.Race.terran),
sc2_env.Bot(sc2_env.Race.terran,
sc2_env.Difficulty.very_easy)],
agent_interface_format=features.AgentInterfaceFormat(
action_space=actions.ActionSpace.RAW,
use_raw_units=True,
raw_resolution=64,
),
step_mul=8,
disable_fog=True,
visualize=False
) as env:
run_loop.run_loop([agent1], env, max_episodes=1000)
except KeyboardInterrupt:
pass
if __name__ == "__main__":
app.run(main)
| [
"[email protected]"
] | |
3f18c535d464c3fa0364386235cbbb1f472cbbf5 | 8a433500d1e66df60fdfe3ee7104e3591e2489d3 | /homework3/31.py | 344012ef0c5d9e8701910e7643a32b0dc126faef | [] | no_license | ratmirdudin/numerical | 091c4f1810f2225bc2dff741a04e500a9bf272bb | 2d16f4a5419d441b25016879fb838596e73a3979 | refs/heads/master | 2022-10-11T13:51:53.129953 | 2020-06-10T19:10:21 | 2020-06-10T19:10:21 | 264,369,663 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,171 | py | import numpy as np
import matplotlib.pyplot as plt
train_x = open('data1/train.dat', 'r')
train_y = open('data1/train.ans', 'r')
test_x = open('data1/test.dat', 'r')
test_y = open('data1/test.ans', 'w')
x = [float(i) for i in train_x.readline().split()]
y = [float(i) for i in train_y.readline().split()]
z = [float(i) for i in test_x.readline().split()]
n = len(x)
m = len(z)
A = np.zeros(n)
B = np.zeros(n)
f = np.zeros(m)
for i in range(n - 1):
A[i] = (y[i + 1] - y[i]) / (x[i + 1] - x[i])
B[i] = y[i]
for j in range(m):
for i in range(n - 1):
if z[j] < x[0]:
f[j] = A[0] * (z[j] - x[0]) + B[0]
if z[j] >= x[n - 1]:
f[j] = A[n - 2] * (z[j] - x[n - 2]) + B[n - 2]
if x[i] < z[j] <= x[i + 1]:
f[j] = A[i] * (z[j] - x[i]) + B[i]
test_y.write(str(f[j]) + ' ')
print('Count train = ', n)
print('x = ', x)
print('y = ', y)
print('Count of test = ', m)
print('z = ', z)
print('f = ', f)
train_x.close()
train_y.close()
test_x.close()
test_y.close()
plt.plot(x, y, 'b', label = 'interpolation')
plt.plot(x, y, 'o', label = 'train')
plt.plot(z, f, 'r*', label = 'test')
plt.ylabel('y(x), f(z)')
plt.xlabel('x, z')
plt.legend()
plt.grid()
plt.show() | [
"[email protected]"
] | |
ce26fc7a6b6d61f812f05ba974c34ce227688d94 | 9e328530c7e96b9229cc7a7a06e433fd3e8a5b34 | /python/project2.py | 8c476f54aec71bb9c91045c738605e4609c76c6a | [] | no_license | anirudhRowjee/Class11 | e5bdc5b4dd2895fe278cf7caa0a12b36e58d2188 | dc90a5efd33ca71cfffa3e2f154621f064a1e2c1 | refs/heads/master | 2021-06-26T14:28:56.700587 | 2018-08-09T17:53:51 | 2018-08-09T17:53:51 | 143,626,058 | 2 | 2 | null | 2020-10-07T09:15:26 | 2018-08-05T15:42:49 | Python | UTF-8 | Python | false | false | 232 | py | a = float(input("please input a"))
b = float(input("please input b"))
c = float(input("please input c"))
x = float(input("please input x"))
answer = (((a*x*x*x) - (3*x*x))/(2*x)) + (((b*x*x) - (4*x)) / (c*x))
print answer
| [
"[email protected]"
] | |
4cfa849ee0707d7f4584967ead32663365e3e83a | e86f88bd05d2dfc3197191245a28734e0a94306c | /scripts/manage_donors_db.py | 3c4a29bd2ebd82ae9f17f1414497b0935e76ab61 | [] | no_license | transreductionist/API-Project-1 | b83e008a8dcf19f690109d89b298111062f760c0 | d5ffcc5d276692d1578cea704125b1b3952beb1c | refs/heads/master | 2022-01-16T06:31:06.951095 | 2019-05-09T15:22:44 | 2019-05-09T15:22:44 | 185,820,751 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,882 | py | """The following script will DROP ALL tables and then CREATE ALL.
Use with caution! It will remove all existing data, and then reconstruct the tables with no entries. Other functions
can be added to manage other database tasks. To run a function navigate to the project root and, for example, on the
command line type:
python -c "import scripts.manage_donors_db;scripts.manage_donors_db.drop_all_and_create()"
python -c "import scripts.manage_donors_db;scripts.manage_donors_db.create_database_tables()"
"""
import uuid
from application.app import create_app
from application.flask_essentials import database
from application.schemas.agent import AgentSchema
from application.schemas.caged_donor import CagedDonorSchema
from application.schemas.queued_donor import QueuedDonorSchema
from tests.helpers.default_dictionaries import get_caged_donor_dict
app = create_app( 'DEV' ) # pylint: disable=C0103
def drop_all_and_create():
"""A function to drop and then recreate the database tables."""
with app.app_context():
database.reflect()
database.drop_all()
database.create_all()
def create_database_tables():
"""Function to create the DONATE database tables, specifically the CagedDonorModel and QueuedDonorModel with UUID.
All that is said here for the CagedDonorModel also holds for the QueuedDonorModel. The CagedDonorModel is built
using Marshmallow schema CagedDonorSchema, which deserializes a dictionary to the model. The searchable_id in the
donor_json is:
donor_json[ 'searchable_id' ] = uuid.uuid4()
This gets passed to the CagedDonorSchema where:
searchable_id = fields.UUID()
And so the validation step is passed.
MySql does not have a UUID type though and there we have ( CagedDonorModel ):
searchable_id = database.Column( database.BINARY( 16 ), nullable=False, default=uuid.uuid4().bytes )
The helper model class BinaryUUID in binary_uuid.py handles the serialization in and out.
"""
with app.app_context():
drop_all_and_create()
caged_donors = []
queued_donors = []
# Create 100 caged donors.
for i in range( 0, 100 ):
donor_json = get_caged_donor_dict( { 'gift_searchable_id': uuid.uuid4() } )
donor_json[ 'gift_id' ] = i + 1
donor_json[ 'customer_id' ] = str( ( i + 1 ) + 1000 )
del donor_json[ 'id' ]
caged_donor = CagedDonorSchema().load( donor_json ).data
queued_donor = QueuedDonorSchema().load( donor_json ).data
caged_donors.append( caged_donor )
queued_donors.append( queued_donor )
# Create the agents.
agent_jsons = [
{ 'name': 'Donate API', 'user_id': None, 'staff_id': None, 'type': 'Automated' },
{ 'name': 'Braintree', 'user_id': None, 'staff_id': None, 'type': 'Organization' },
{ 'name': 'PayPal', 'user_id': None, 'staff_id': None, 'type': 'Organization' },
{ 'name': 'Credit Card Issuer', 'user_id': None, 'staf_id': None, 'type': 'Organization' },
{ 'name': 'Unspecified NumbersUSA Staff', 'user_id': None, 'staff_id': None, 'type': 'Staff Member' },
{ 'name': 'Dan Marsh', 'user_id': 1234, 'staff_id': 4321, 'type': 'Staff Member' },
{ 'name': 'Joshua Turcotte', 'user_id': 7041, 'staff_id': 1407, 'type': 'Staff Member' },
{ 'name': 'Donate API', 'user_id': None, 'staff_id': None, 'type': 'Automated' }
]
agents = []
for agent_json in agent_jsons:
agent_model = AgentSchema().load( agent_json ).data
agents.append( agent_model )
database.session.bulk_save_objects( caged_donors )
database.session.bulk_save_objects( queued_donors )
database.session.bulk_save_objects( agents )
database.session.commit()
| [
"[email protected]"
] | |
76165af58121e1b0a60e11a06bbd03a474677c14 | 248e9951f171425a21d30f4f9789b4780aef83a7 | /test/functional/rpc_scantxoutset.py | 84f69aff87facfef64e6d6695718a5fb529559c2 | [
"MIT"
] | permissive | bitcoinrtx/BitcoinRTX-V0.1 | 8dd4f2b79e40d1eba39a1dc8e27bffe5c34785d4 | defcb5024837d0a17152d1304e6de3fb338436f5 | refs/heads/master | 2023-03-12T11:16:08.751490 | 2021-03-06T20:05:56 | 2021-03-06T20:05:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,467 | py | #!/usr/bin/env python3
#
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the scantxoutset rpc call."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_rpc_error
from decimal import Decimal
import shutil
import os
def descriptors(out):
return sorted(u['desc'] for u in out['unspents'])
class ScantxoutsetTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
def run_test(self):
self.log.info("Mining blocks...")
self.nodes[0].generate(110)
addr_P2SH_SEGWIT = self.nodes[0].getnewaddress("", "p2sh-segwit")
pubk1 = self.nodes[0].getaddressinfo(addr_P2SH_SEGWIT)['pubkey']
addr_LEGACY = self.nodes[0].getnewaddress("", "legacy")
pubk2 = self.nodes[0].getaddressinfo(addr_LEGACY)['pubkey']
addr_BECH32 = self.nodes[0].getnewaddress("", "bech32")
pubk3 = self.nodes[0].getaddressinfo(addr_BECH32)['pubkey']
self.nodes[0].sendtoaddress(addr_P2SH_SEGWIT, 0.001)
self.nodes[0].sendtoaddress(addr_LEGACY, 0.002)
self.nodes[0].sendtoaddress(addr_BECH32, 0.004)
#send to child keys of tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK
self.nodes[0].sendtoaddress("mkHV1C6JLheLoUSSZYk7x3FH5tnx9bu7yc", 0.008) # (m/0'/0'/0')
self.nodes[0].sendtoaddress("mipUSRmJAj2KrjSvsPQtnP8ynUon7FhpCR", 0.016) # (m/0'/0'/1')
self.nodes[0].sendtoaddress("n37dAGe6Mq1HGM9t4b6rFEEsDGq7Fcgfqg", 0.032) # (m/0'/0'/1500')
self.nodes[0].sendtoaddress("mqS9Rpg8nNLAzxFExsgFLCnzHBsoQ3PRM6", 0.064) # (m/0'/0'/0)
self.nodes[0].sendtoaddress("mnTg5gVWr3rbhHaKjJv7EEEc76ZqHgSj4S", 0.128) # (m/0'/0'/1)
self.nodes[0].sendtoaddress("mketCd6B9U9Uee1iCsppDJJBHfvi6U6ukC", 0.256) # (m/0'/0'/1500)
self.nodes[0].sendtoaddress("mj8zFzrbBcdaWXowCQ1oPZ4qioBVzLzAp7", 0.512) # (m/1/1/0')
self.nodes[0].sendtoaddress("mfnKpKQEftniaoE1iXuMMePQU3PUpcNisA", 1.024) # (m/1/1/1')
self.nodes[0].sendtoaddress("mou6cB1kaP1nNJM1sryW6YRwnd4shTbXYQ", 2.048) # (m/1/1/1500')
self.nodes[0].sendtoaddress("mtfUoUax9L4tzXARpw1oTGxWyoogp52KhJ", 4.096) # (m/1/1/0)
self.nodes[0].sendtoaddress("mxp7w7j8S1Aq6L8StS2PqVvtt4HGxXEvdy", 8.192) # (m/1/1/1)
self.nodes[0].sendtoaddress("mpQ8rokAhp1TAtJQR6F6TaUmjAWkAWYYBq", 16.384) # (m/1/1/1500)
self.nodes[0].generate(1)
self.log.info("Stop node, remove wallet, mine again some blocks...")
self.stop_node(0)
shutil.rmtree(os.path.join(self.nodes[0].datadir, "regtest", 'wallets'))
self.start_node(0)
self.nodes[0].generate(110)
scan = self.nodes[0].scantxoutset("start", [])
info = self.nodes[0].gettxoutsetinfo()
assert_equal(scan['success'], True)
assert_equal(scan['height'], info['height'])
assert_equal(scan['txouts'], info['txouts'])
assert_equal(scan['bestblock'], info['bestblock'])
self.restart_node(0, ['-nowallet'])
self.log.info("Test if we have found the non HD unspent outputs.")
assert_equal(self.nodes[0].scantxoutset("start", [ "pkh(" + pubk1 + ")", "pkh(" + pubk2 + ")", "pkh(" + pubk3 + ")"])['total_amount'], Decimal("0.002"))
assert_equal(self.nodes[0].scantxoutset("start", [ "wpkh(" + pubk1 + ")", "wpkh(" + pubk2 + ")", "wpkh(" + pubk3 + ")"])['total_amount'], Decimal("0.004"))
assert_equal(self.nodes[0].scantxoutset("start", [ "sh(wpkh(" + pubk1 + "))", "sh(wpkh(" + pubk2 + "))", "sh(wpkh(" + pubk3 + "))"])['total_amount'], Decimal("0.001"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(" + pubk1 + ")", "combo(" + pubk2 + ")", "combo(" + pubk3 + ")"])['total_amount'], Decimal("0.007"))
assert_equal(self.nodes[0].scantxoutset("start", [ "addr(" + addr_P2SH_SEGWIT + ")", "addr(" + addr_LEGACY + ")", "addr(" + addr_BECH32 + ")"])['total_amount'], Decimal("0.007"))
assert_equal(self.nodes[0].scantxoutset("start", [ "addr(" + addr_P2SH_SEGWIT + ")", "addr(" + addr_LEGACY + ")", "combo(" + pubk3 + ")"])['total_amount'], Decimal("0.007"))
self.log.info("Test range validation.")
assert_raises_rpc_error(-8, "End of range is too high", self.nodes[0].scantxoutset, "start", [ {"desc": "desc", "range": -1}])
assert_raises_rpc_error(-8, "Range should be greater or equal than 0", self.nodes[0].scantxoutset, "start", [ {"desc": "desc", "range": [-1, 10]}])
assert_raises_rpc_error(-8, "End of range is too high", self.nodes[0].scantxoutset, "start", [ {"desc": "desc", "range": [(2 << 31 + 1) - 1000000, (2 << 31 + 1)]}])
assert_raises_rpc_error(-8, "Range specified as [begin,end] must not have begin after end", self.nodes[0].scantxoutset, "start", [ {"desc": "desc", "range": [2, 1]}])
assert_raises_rpc_error(-8, "Range is too large", self.nodes[0].scantxoutset, "start", [ {"desc": "desc", "range": [0, 1000001]}])
self.log.info("Test extended key derivation.")
# Run various scans, and verify that the sum of the amounts of the matches corresponds to the expected subset.
# Note that all amounts in the UTXO set are powers of 2 multiplied by 0.001 BTC, so each amounts uniquely identifies a subset.
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0'/0h/0h)"])['total_amount'], Decimal("0.008"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0'/0'/1h)"])['total_amount'], Decimal("0.016"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0h/0'/1500')"])['total_amount'], Decimal("0.032"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0h/0h/0)"])['total_amount'], Decimal("0.064"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0'/0h/1)"])['total_amount'], Decimal("0.128"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0h/0'/1500)"])['total_amount'], Decimal("0.256"))
assert_equal(self.nodes[0].scantxoutset("start", [ {"desc": "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0'/0h/*h)", "range": 1499}])['total_amount'], Decimal("0.024"))
assert_equal(self.nodes[0].scantxoutset("start", [ {"desc": "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0'/0'/*h)", "range": 1500}])['total_amount'], Decimal("0.056"))
assert_equal(self.nodes[0].scantxoutset("start", [ {"desc": "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0h/0'/*)", "range": 1499}])['total_amount'], Decimal("0.192"))
assert_equal(self.nodes[0].scantxoutset("start", [ {"desc": "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0'/0h/*)", "range": 1500}])['total_amount'], Decimal("0.448"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0')"])['total_amount'], Decimal("0.512"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/1')"])['total_amount'], Decimal("1.024"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/1500h)"])['total_amount'], Decimal("2.048"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)"])['total_amount'], Decimal("4.096"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/1)"])['total_amount'], Decimal("8.192"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/1500)"])['total_amount'], Decimal("16.384"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/0)"])['total_amount'], Decimal("4.096"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo([abcdef88/1/2'/3/4h]tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/1)"])['total_amount'], Decimal("8.192"))
assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/1500)"])['total_amount'], Decimal("16.384"))
assert_equal(self.nodes[0].scantxoutset("start", [ {"desc": "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*')", "range": 1499}])['total_amount'], Decimal("1.536"))
assert_equal(self.nodes[0].scantxoutset("start", [ {"desc": "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*')", "range": 1500}])['total_amount'], Decimal("3.584"))
assert_equal(self.nodes[0].scantxoutset("start", [ {"desc": "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)", "range": 1499}])['total_amount'], Decimal("12.288"))
assert_equal(self.nodes[0].scantxoutset("start", [ {"desc": "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)", "range": 1500}])['total_amount'], Decimal("28.672"))
assert_equal(self.nodes[0].scantxoutset("start", [ {"desc": "combo(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/*)", "range": 1499}])['total_amount'], Decimal("12.288"))
assert_equal(self.nodes[0].scantxoutset("start", [ {"desc": "combo(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/*)", "range": 1500}])['total_amount'], Decimal("28.672"))
assert_equal(self.nodes[0].scantxoutset("start", [ {"desc": "combo(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/*)", "range": [1500,1500]}])['total_amount'], Decimal("16.384"))
# Test the reported descriptors for a few matches
assert_equal(descriptors(self.nodes[0].scantxoutset("start", [ {"desc": "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0h/0'/*)", "range": 1499}])), ["pkh([0c5f9a1e/0'/0'/0]026dbd8b2315f296d36e6b6920b1579ca75569464875c7ebe869b536a7d9503c8c)#dzxw429x", "pkh([0c5f9a1e/0'/0'/1]033e6f25d76c00bedb3a8993c7d5739ee806397f0529b1b31dda31ef890f19a60c)#43rvceed"])
assert_equal(descriptors(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)"])), ["pkh([0c5f9a1e/1/1/0]03e1c5b6e650966971d7e71ef2674f80222752740fc1dfd63bbbd220d2da9bd0fb)#cxmct4w8"])
assert_equal(descriptors(self.nodes[0].scantxoutset("start", [ {"desc": "combo(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/*)", "range": 1500}])), ['pkh([0c5f9a1e/1/1/0]03e1c5b6e650966971d7e71ef2674f80222752740fc1dfd63bbbd220d2da9bd0fb)#cxmct4w8', 'pkh([0c5f9a1e/1/1/1500]03832901c250025da2aebae2bfb38d5c703a57ab66ad477f9c578bfbcd78abca6f)#vchwd07g', 'pkh([0c5f9a1e/1/1/1]030d820fc9e8211c4169be8530efbc632775d8286167afd178caaf1089b77daba7)#z2t3ypsa'])
# Check that status and abort don't need second arg
assert_equal(self.nodes[0].scantxoutset("status"), None)
assert_equal(self.nodes[0].scantxoutset("abort"), False)
# Check that second arg is needed for start
assert_raises_rpc_error(-1, "scanobjects argument is required for the start action", self.nodes[0].scantxoutset, "start")
if __name__ == '__main__':
ScantxoutsetTest().main()
| [
"[email protected]"
] | |
6a6ffca20c1c9cc02781e1c479389521f4e3e993 | 0be6823ef69ce50f35063aad98cba913abfca3d4 | /deepr/hooks/num_params.py | f7808e1823f80c1ab60b65387bdf8db04ea1edda | [
"Apache-2.0"
] | permissive | Mbompr/deepr | 944e827c114be60f73ad5882130a531bb2332559 | 1fb28e15aeeac6ef2d8e5b678feb380f2b1951f2 | refs/heads/master | 2022-11-11T10:02:01.929598 | 2020-05-20T16:29:38 | 2020-05-25T10:36:52 | 266,785,156 | 0 | 0 | Apache-2.0 | 2020-05-25T13:23:03 | 2020-05-25T13:23:02 | null | UTF-8 | Python | false | false | 1,408 | py | """Log Number of Parameters after session creation"""
from typing import Tuple, List
import logging
import tensorflow as tf
from deepr.utils import mlflow
LOGGER = logging.getLogger(__name__)
class NumParamsHook(tf.train.SessionRunHook):
"""Log Number of Parameters after session creation"""
def __init__(self, use_mlflow: bool):
self.use_mlflow = use_mlflow
def after_create_session(self, session, coord):
super().after_create_session(session, coord)
num_global, num_trainable = get_num_params()
LOGGER.info(f"Number of parameters (global) = {num_global}")
LOGGER.info(f"Number of parameters (trainable) = {num_trainable}")
if self.use_mlflow:
mlflow.log_metrics({"num_params_global": num_global, "num_params_trainable": num_trainable})
def get_num_params() -> Tuple[int, int]:
"""Get number of global and trainable parameters
Returns
-------
Tuple[int, int]
num_global, num_trainable
"""
def _count(variables: List):
total = 0
for var in variables:
shape = var.get_shape()
var_params = 1
for dim in shape:
var_params *= dim.value
total += var_params
return total
num_global = _count(tf.global_variables())
num_trainable = _count(tf.trainable_variables())
return num_global, num_trainable
| [
"[email protected]"
] | |
c0964f7a176be551ea3d34649e8c502828aa6ad1 | ecd3051e5baed08d2b987a36820a764223ceb7fd | /algo/leetcode/dp/perfect_square-279.py | 5afe06502d2b1a80d98a04de7d71aa57688dd3e3 | [
"CC0-1.0"
] | permissive | Hasaber8/cheatsheets | 5493cfbd178d01a1ab9cf6e216263299c9425776 | 94b44424e8661a74e2ded8445455d00b122f167f | refs/heads/master | 2021-04-16T20:09:17.095374 | 2018-07-08T04:34:26 | 2018-07-08T04:34:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,033 | py |
import math
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
>>> s = Solution()
>>> s.numSquares(1)
1
>>> s.numSquares(2)
2
>>> s.numSquares(3)
3
>>> s.numSquares(4)
1
>>> s.numSquares(5)
2
>>> s.numSquares(6)
3
>>> s.numSquares(7)
4
>>> s.numSquares(8)
2
>>> s.numSquares(9)
1
>>> s.numSquares(10)
2
"""
if math.floor(math.sqrt(n)) ** 2 == n:
return 1
d = [0 for i in range(n)]
for i in range(n):
if math.floor(math.sqrt(n)) ** 2 == i + 1:
d[i] = 1
else:
d[i] = 1 + d[0] + d[i-1]
for j in range(i-1):
if d[i] > 1 + d[j] + d[i- 1 - j]:
d[i] = 1 + d[j] + d[i - 1 - j]
return d[n-1]
if __name__ == '__main__':
import doctest
doctest.testmod() | [
"[email protected]"
] | |
e2502517508c67dd94bb252188d8778ab806099e | 2fa075e320c1331dbef73d36f3697f29b72aa42a | /linkedin/11.binarytreeordertraversal.py | 383d0309216b00abc4a57079e1bde2ba6fc96ac8 | [] | no_license | ashushekar/python-advance-samples | c35313940a8c03eeef2446485fd2101a581f2c1b | a9acf02a1ac96eee0020284babc1102ebaab6b07 | refs/heads/master | 2020-09-11T09:47:30.126094 | 2019-11-25T13:29:26 | 2019-11-25T13:29:26 | 222,026,874 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 726 | py | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
result = []
if not root:
return result
current_level = [root]
while len(current_level): # sort of bfs
next_level = []
for x in current_level:
if x and x.left:
next_level.append(x.left)
if x and x.right:
next_level.append(x.right)
result.append([x.val for x in current_level if x])
current_level = next_level
return result
| [
"[email protected]"
] | |
8143a6a3909f400bc57671bbfe5c265e553dee59 | dc9bd4397878980f708ee10b978a55880bcfcc4f | /posts/migrations/0001_initial.py | 6e351f5c4b67abb839d9e122baac1cd7507fd765 | [] | no_license | eslam2002/Socialsite- | e2dcdb01a622b39cd6a71ccf44a95410bf5cd3d7 | c97d97b1c0be24f9acf667b8e55bf9ae6ea1df63 | refs/heads/master | 2020-03-28T20:40:29.088657 | 2018-09-17T08:24:39 | 2018-09-17T08:24:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,216 | py | # Generated by Django 2.0.5 on 2018-06-09 15:25
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('groups', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now=True)),
('massage', models.TextField()),
('group', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='posts', to='groups.Group')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='posts', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['-created_at'],
},
),
migrations.AlterUniqueTogether(
name='post',
unique_together={('user', 'massage')},
),
]
| [
"[email protected]"
] | |
0bda8a3cbb74408a4b46cea22f14d231b62063c4 | 218007ee08f382d5cebcf79b8bafb9d98d78b85a | /FugModel/MIM.py | fc920171842186666f9e207fac2b52bc526096df | [
"MIT"
] | permissive | DiamondModels/FugModel | 30222eff446787f6a5db03e61d3e902d673218f2 | d0247fe784439c97aa3c3d34934edf85e301059c | refs/heads/master | 2020-03-25T02:43:41.542865 | 2019-03-15T15:44:25 | 2019-03-15T15:44:25 | 143,304,689 | 0 | 1 | MIT | 2019-03-15T15:44:26 | 2018-08-02T14:20:28 | Python | UTF-8 | Python | false | false | 1,408 | py | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 3 11:22:09 2018
@author: Tim Rodgers
"""
import numpy as np
import pandas as pd
from HelperFuncs import vant_conv, arr_conv
from FugModel import FugModel
class MIM(FugModel):
"""Multimedia Indoor Model fugacity model object. Implementation of the model by
?? as updated by Adjei-Kyereme (2018) and Kvasnicka (in prep)
Attributes:
----------
ic input_calc (df): Dataframe describing the system up to the point
of matrix solution, which includes D values DTi and D_IJ
"""
def __init__(self,locsumm,chemsumm,params,num_compartments = 6,name = None):
FugModel. __init__(self,locsumm,chemsumm,params,num_compartments,name)
self.ic = self.input_calc(self.locsumm,self.chemsumm,self.params)
def input_calc(self,locsumm,chemsumm,params,pp):
""" Perform the initial calulations to set up the fugacity matrix. A steady state
MIM object is an n compartment fugacity model solved at steady
state using the compartment parameters from locsumm and the chemical
parameters from chemsumm, other parameters from params
"""
#Declare constants
R = 8.314 #Ideal gas constant, J/mol/K
#Initialize results by copying the chemsumm dataframe
res = pd.DataFrame.copy(chemsumm,deep=True)
return res
| [
"[email protected]"
] | |
4b74be3a151dab7cac6d990d8d186b1b84de6013 | 92fa526d5ca2e31f5908f17bb95c529b09ac9995 | /fun_models/game_2/gif2frame.py | 9270f8d5aded0cf8b274c0041422a5da62ac243d | [] | no_license | KevinLongkk/IFit | 55e1f7f872dbdd28e23066c9b96465315061ca2a | 438fbdbd63d7cf4059038623e2739fc0a860c26b | refs/heads/master | 2020-03-21T02:08:49.538064 | 2018-06-20T04:53:56 | 2018-06-20T04:53:56 | 137,982,728 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 325 | py | from PIL import Image, ImageSequence
import cv2
import numpy as np
pit_path = r'/home/kevin/IFit/fun_models/game_2/picture/p2motion_1.gif'
ii = Image.open(pit_path)
ite = ImageSequence.Iterator(ii)
index = 0
for i in ite:
i.save("/home/kevin/IFit/fun_models/game_2/picture/p2motion_1/frame%d.png" % index)
index+=1 | [
"[email protected]"
] | |
513b4655b7e6f455c974cd3837e7f4a99a34df90 | d8b5aba2a1f53fbf3fcfc388c26e547afa76b13f | /modules/DEFA/plugin_text.py | e479b7a07afd519822d75554439bc5126dafbe03 | [
"Apache-2.0"
] | permissive | dfrc-korea/carpe | e88b4e3bcb536355e2a64d00e807bccd631f8c93 | f9299b8ad0cb2a6bbbd5e65f01d2ba06406c70ac | refs/heads/master | 2023-04-28T01:12:49.138443 | 2023-04-18T07:37:39 | 2023-04-18T07:37:39 | 169,518,336 | 75 | 38 | Apache-2.0 | 2023-02-08T00:42:41 | 2019-02-07T04:21:23 | Python | UTF-8 | Python | false | false | 1,172 | py | # -*- coding: utf-8 -*-
import os
import datetime
from modules import defa_connector
from modules.DEFA import interface
from modules.DEFA.MappingDocuments import MappingDocuments
from modules import logger
class TextPlugin(interface.DEFAPlugin):
NAME = "TEXT"
DESCRIPTION = "text(txt/log) plugin"
def Process(self, **kwargs): # fp: file_path, meta: document_info
super(TextPlugin, self).Process(**kwargs)
file_path = kwargs['fp']
meta = kwargs['meta']
data = MappingDocuments()
data.date = None
data.version = None
data.category = None
try:
with open(file_path, 'r', encoding='utf-8') as f:
data.content = f.read()
f.close()
except UnicodeDecodeError:
with open(file_path, 'r', encoding='utf-16-le') as f:
data.content = f.read()
f.close()
else:
log_msg = 'UnicodeDecodeError error occurred when read {}'.format(file_path)
logger.error(log_msg)
#raise Exception(log_msg)
return data
defa_connector.DEFAConnector.RegisterPlugin(TextPlugin) | [
"[email protected]"
] | |
1e538e961da6d1f2cac2ea265c1da47f058b9c51 | 165d117a5c969c76f193adc477e53e7290ca7cdb | /ch_10/alice.py | 58eaaba0bef9184e450bd7dc010b57059e48beeb | [] | no_license | shubhammuramkar/pythonwork | b8beaf203bcb98718f0afcfa489bc3b96d5da406 | b43845a8fceec1bc05d257922b2c952e2e3b9462 | refs/heads/master | 2021-01-20T21:44:45.366588 | 2017-08-29T16:54:26 | 2017-08-29T16:54:26 | 101,785,026 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 242 | py | file = "alice.txt"
try:
with open(file) as f:
data = f.read()
except FileNotFoundError:
msg = "Sorry, the file " + file + " does not exist."
print(msg)
else:
data.split()
l = len(data)
print(file + " file have " + str(l) + " words ") | [
"[email protected]"
] | |
642d8566dd86655cd61f51f62c96be0d14eb0791 | 823ce1bb953187f59a2569ae8f5fdac0372e109f | /app1/admin.py | a9b718982e3943cb17b2e908f2da96d9cccab105 | [] | no_license | Devdeepsinh0591/Enhanced-Product-Management-System | 7c4984c47b03b90fa49490748e6e5315f7bf4340 | 460fe1498d8eaf558aaa566de688bac58154380f | refs/heads/main | 2023-07-07T16:24:20.043115 | 2021-08-18T10:22:34 | 2021-08-18T10:22:34 | 394,928,524 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 299 | py | from django.contrib import admin
from .models import Company_Details, Customer_Order,Company_Customers,Company_Product
# Register your models here.
admin.site.register(Company_Details)
admin.site.register(Company_Customers)
admin.site.register(Company_Product)
admin.site.register(Customer_Order)
| [
"[email protected]"
] | |
8598a1df14804656d5d40abba2e7cc1ff46f7e9b | 8063bf621b0f7e54b9c31bbb4c0b27557c08978b | /src/model/_Model.py | b6bb34a2454ddc3c83de1119f32699907d921ba6 | [
"MIT"
] | permissive | hukuda222/Chat-Yojo-Bot | 8c703a8bfccc3d55a4df87a83a3bd77161d13ee6 | b431506ae85335f1b6fe7fe35074594dcd8fa6ca | refs/heads/master | 2020-03-26T21:26:37.745204 | 2019-01-21T08:21:39 | 2019-01-21T08:21:39 | 145,388,579 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,499 | py | import os
import sys
import copy
import time
import math
import random
import numpy as np
import functools as ft
import chainer
from chainer import cuda
from chainer import optimizers, serializers
from chainer import Chain
import chainer.functions as F
import chainer.links as L
yaju = 810
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# for decoder
class NLayerLSTM(chainer.ChainList):
def __init__(self, eDim, hDim):
layers = [0] * 1 # get place holder for each layer
layers[0] = L.LSTM(eDim, hDim)
super(NLayerLSTM, self).__init__(*layers)
# process a lstm for every layer
def __call__(self, hin):
hout = self[0](hin)
return hout
# initialize all layer's lstm's state
def reset_state(self):
self[0].reset_state()
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# for passing cell and hidden state from encoder to decoder and
# beam search where multiple lstm apply is not able
# [0c, 0h,
# 1c, 1h,
# 2c, 2h,
# ...
# nc, nh]
# ic, ih: np.array
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
def getAllLSTMStates(self):
h = self[0].h
c = self[0].c
return (h, c)
def setAllLSTMStates(self, states): # states: (h, c)
self[0].h = states[0]
self[0].c = states[1]
class EncoderDecoder:
def __init__(self, encoderVocab, decoderVocab, trainData, setting):
self.encw2i = encoderVocab # dict
self.decw2i = decoderVocab # dict
self.encVocabSize = len(encoderVocab)
self.decVocabSize = len(decoderVocab)
# dictionary for get vocabulary from index
self.enci2w = {v: k for k, v in self.encw2i.items()}
self.deci2w = {v: k for k, v in self.decw2i.items()}
self.eDim_enc = setting.eDim_enc
self.eDim_dec = setting.eDim_dec
self.hDim = setting.hDim
self.n_layers = setting.n_layers
self.dropout_rate = setting.dropout_rate
self.gpu = setting.gpu
# encoder-docoder network
def initModel(self):
self.model = chainer.Chain(
encoderEmbed=L.EmbedID(self.encVocabSize, self.eDim_enc), # encoder embedding layer
decoderEmbed=L.EmbedID(self.decVocabSize, self.eDim_dec), # decoder embedding layer
decOutputL=L.Linear(self.hDim, self.decVocabSize), # output layer
encoder_bak=L.NStepLSTM(n_layers=self.n_layers, in_size=self.eDim_enc, out_size=self.hDim, dropout=self.dropout_rate), # encoder backward
encoder_fwd=L.NStepLSTM(n_layers=self.n_layers, in_size=self.eDim_enc, out_size=self.hDim, dropout=self.dropout_rate), # encoder forward
decoder_=NLayerLSTM(eDim=self.eDim_dec, hDim=self.hDim), # decoder
attnIn=L.Linear(self.hDim, self.hDim, nobias=True), # attn
attnOut=L.Linear(self.hDim + self.hDim, self.hDim, nobias=True) # attn
)
def getLastSavedIndex(self, dirname):
for dirpath, dirnames, filenames in os.walk(dirname): # model_0.npz
norm_filenames = [fn for fn in filenames if not(fn == ".DS_Store")]
ansind = 0 if (len(norm_filenames) == 0) else max([int(fn.split(".")[0].split("_")[1])
for fn in list(norm_filenames)])
return ansind
def saveModel(self, dirname, diffepoch):
ind = self.getLastSavedIndex(dirname)
fname = dirname + "model_{}".format(int(ind) + int(diffepoch))
copied_model = copy.deepcopy(self.model)
copied_model.to_cpu()
sys.stdout.write("# Saved model: {}\n".format(fname))
serializers.save_npz(fname, copied_model)
def loadModel(self, dirname):
ind = self.getLastSavedIndex(dirname)
if ind > 0:
fname = dirname + "model_{}".format(int(ind))
sys.stdout.write("# Loaded model: {}\n".format(fname))
serializers.load_npz(fname, self.model)
else:
sys.stdout.write("# No model loaded\n")
def setToGPUs(self):
if self.gpu >= 0:
sys.stderr.write("# Working on GPU [gpu=%d]\n" % (self.gpu))
self.model.encoderEmbed.to_gpu(self.gpu)
self.model.decoderEmbed.to_gpu(self.gpu)
self.model.decOutputL.to_gpu(self.gpu)
self.model.encoder_bak.to_gpu(self.gpu)
self.model.encoder_fwd.to_gpu(self.gpu)
self.model.decoder_.to_gpu(self.gpu)
self.model.attnIn.to_gpu(self.gpu)
self.model.attnOut.to_gpu(self.gpu)
else:
sys.stderr.write("# Working on CPU [cpu=%d]\n" % (self.gpu))
# get embedding for encoder
def getEncoderInputEmbeddings(self, xs): # xs: [arr(l1), ...], still on cpu
x_len = [len(x) for x in xs]
x_section = np.cumsum(x_len[:-1])
vxs = [F.copy(chainer.Variable(x), self.gpu) for x in xs] # to gpu
ex = self.model.encoderEmbed(F.concat(tuple(vxs), axis=0))
exs = F.split_axis(ex, x_section, 0)
return list(exs)
# get embedding for decoder
def getDecoderInputEmbeddings(self, xs): # xs: [arr(l1), ...], still on cpu
x_len = [len(x) for x in xs]
x_section = np.cumsum(x_len[:-1])
vxs = [F.copy(chainer.Variable(x), self.gpu) for x in xs] # to gpu
ex = self.model.decoderEmbed(F.concat(tuple(vxs), axis=0))
exs = F.split_axis(ex, x_section, 0)
return list(exs)
def outputMerging(self, bak, fwd): # bak, fwd: [(encLen, hDim)]
ys = [b + f for b, f in zip(bak, fwd)]
return ys
def statesMerging(self, sb, sf): # sb, sf: (layer, batch, hDim)
s_added = sb + sf;
s = F.stack([s_added[-1]]) # use last encoder's layer's hidden state for decoder's state
return s
def calcAttention(self, h1, encList, encLen, batchsize): # attention, h1: (batch, hDim)
target1 = self.model.attnIn(h1) # convert
# (batchsize, self.hDim) => (batchsize, self.hDim)
target2 = F.expand_dims(target1, axis=1)
# (batchsize, self.hDim) => (batchsize, 1, self.hDim)
target3 = F.broadcast_to(target2, (batchsize, encLen, self.hDim))
# (batchsize, 1, self.hDim) => (batchsize, encLen, self.hDim)
# bilinear
# target3: (batchsize, encLen, self.hDim) tensor
# encList: (batchsize, encLen, self.hDim) tensor
# [[[...], [...], [...], ...]]
# * * *
# [[[...], [...], [...], ...]]
# [[ a0, a1, a2, ...]]
aval = F.sum(target3 * encList, axis=2) # shape: (batchsize, encLen)
"""
# MLP
# convert for attnSum
t1 = F.reshape(target3, (batchsize * encLen, self.hDim))
# (batchsize * encLen, self.hDim) => (batchsize * encLen, 1)
t2 = self.model.attnSum(F.tanh(t1 + aList))
# shape: (batchsize, encLen)
aval = F.reshape(t2, (batchsize, encLen))
"""
# 3, calc softmax
cAttn1 = F.softmax(aval) # (batchsize, encLen) => (batchsize, encLen)
# 4, make context vector using attention
cAttn2 = F.expand_dims(cAttn1, axis=1) # (batchsize, encLen) => (batchsize, 1, encLen)
cAttn3 = F.batch_matmul(cAttn2, encList)
# (1, encLen) x (encLen, hDim) matmul for batchsize times => (batchsize, 1, hDim)
context = F.reshape(cAttn3, (batchsize, self.hDim)) # (batchsize, hDim)
# 6, attention時の最終隠れ層の計算
c1 = F.concat((h1, context))
c2 = self.model.attnOut(c1)
finalH = F.tanh(c2)
return finalH # context
def encodingInput(self, encarrs):
xs_bak = [x[::-1] for x in encarrs] # for backward
xs_fwd = [x for x in encarrs] # for forward
exs_bak = self.getEncoderInputEmbeddings(xs_bak) # for backward
exs_fwd = self.getEncoderInputEmbeddings(xs_fwd) # for forward
hx_bak, cx_bak, xs_bak = self.model.encoder_bak(None, None, exs_bak) # for backward
hx_fwd, cx_fwd, xs_fwd = self.model.encoder_fwd(None, None, exs_fwd) # for forward
xs = self.outputMerging(xs_bak, xs_fwd)
hx = self.statesMerging(hx_bak, hx_fwd) # (1, batch, hDim)
cx = self.statesMerging(cx_bak, cx_fwd) # (1, batch, hDim)
return hx, cx, xs
def train(self, optimizer, trainData, epoch):
xp = cuda.get_array_module(self.model.decOutputL.W.data)
total_loss_val = 0
for enu, (enc, dec) in enumerate(trainData):
begin = time.time()
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
hy, cy, ys = self.encodingInput(enc) # encoding
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# data preparing and embedding
dec_ind_dom = [y[:-1] for y in dec] # for pred
dec_ind_cod = [F.copy(chainer.Variable(y[1:]), self.gpu) for y in dec] # for true
cword = sum([len(y) for y in dec_ind_cod])
decoder_dom = self.getDecoderInputEmbeddings(dec_ind_dom)
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# decoding
self.model.decoder_.reset_state()
self.model.decoder_.setAllLSTMStates((hy[0], cy[0]))
zs_ = [] # [(batch, hDim)]
decoder_dom_ = F.swapaxes(F.stack(decoder_dom), 0, 1) # (decLen, batch, hDim)
dec_ind_cod_ = F.swapaxes(F.stack(dec_ind_cod), 0, 1) # (decLen, batch)
for i in range(len(decoder_dom_)):
hout_ = self.model.decoder_(decoder_dom_[i])
hout_att = self.calcAttention(h1=hout_, encList=F.stack(ys), encLen=len(ys[0]), batchsize=len(ys))
zs_.append(hout_att)
concat_zs_pred_ = F.concat(tuple(zs_), axis=0)
concat_zs_true_ = F.concat(tuple(dec_ind_cod_), axis=0)
closs_ = F.sum(F.softmax_cross_entropy(self.model.decOutputL(concat_zs_pred_),
concat_zs_true_,
reduce="no")) / cword
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
if (xp.isnan(closs_.data)):
sys.stderr.write("Nan occured! skip :(\n")
continue
total_loss_val += closs_.data
optimizer.target.cleargrads()
closs_.backward()
optimizer.update()
end = time.time()
sys.stdout.write("epoch: {:3d}, enu: {:3d}, X-entropy: {:5.6f}, total_word: {:5d}, time: {:2.5f}\n".format(
int(epoch), int(enu), float(closs_.data), int(cword), float(end - begin)))
if enu == 1200: break
next_test_index = random.randint(0, len(trainData) - 1)
arr_list = trainData[next_test_index][0]
for arr in arr_list[:5]:
fuck = self.translate([arr])
sys.stdout.write("# Test: {}, utter: [{}], rep: [{}]\n".format(
int(epoch), "".join([self.enci2w[x] for x in arr]), fuck[0][3:-4]))
sys.stderr.write("total_loss: {:4.5f}\n".format(float(total_loss_val)))
def translate(self, encarrs, max_length=10, beam_width=5): # len(xs) = 1
xp = cuda.get_array_module(self.model.decOutputL.W.data)
assert (len(encarrs) == 1), "Batch size is too match!"
with chainer.no_backprop_mode(), chainer.using_config("train", False):
hx, cx, xs = self.encodingInput(encarrs)
# [(log (p1 * p2 * ...), (h, c), [word1, worc2, ...])]
# result = [(0, (hx, cx), ["<s>"])] # priority queue for beam search
# [(log (p1 * p2 * ...), ((1, batch, hDim), (batch, hDim)), [word1, worc2, ...])]
result_ = [(0.0, (hx[0], cx[0]), ["<s>"])] # priority queue for beam search
# [(log (p1 * p2 * ...), ((batch, hDim), (batch, hDim)), [word1, worc2, ...])]
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
i_ = 0
#beam search
while True:
c_result_ = []
for (logp, (h, c), stkwords) in result_:
lastword_ = stkwords[-1]
y_ = xp.full(1, self.decw2i[lastword_], 'i')
ey_ = self.model.decoderEmbed(y_)
self.model.decoder_.reset_state()
self.model.decoder_.setAllLSTMStates((h, c))
dy_ = self.model.decoder_(ey_)
dy_att = self.calcAttention(h1=dy_, encList=F.stack(xs), encLen=len(xs[0]), batchsize=len(xs))
(nh_, nc_) = self.model.decoder_.getAllLSTMStates()
wy_ = F.softmax(self.model.decOutputL(dy_att))
yind_ = xp.argmax(wy_.data, axis=1).astype('i')
probs_list_ = cuda.to_cpu(wy_.data)[0].tolist()
index_prob_list_ = list(zip(list(range(len(probs_list_))), probs_list_))
for idx, prob in index_prob_list_:
if self.deci2w[idx] == "<\s>":
c_result_.append((logp + 0,
(nh_, nc_),
stkwords + [self.deci2w[idx]]))
sys.stdout.write("{}\n", c_result_)
else:
c_result_.append((logp + math.log(prob + 1e-100),
(nh_, nc_),
stkwords + [self.deci2w[idx]]))
sorted_c_result_ = sorted(c_result_, key=lambda x: x[0], reverse=True)
result_ = sorted_c_result_[:beam_width]
end = ft.reduce(lambda a, b: a or b,
["<\s>" in x[2] for x in result_]) # check output "</s>" or not
i_ += 1
if end or i_ == max_length: break
outs_ = [x[2] for x in result_]
outs_ = ["".join(x).split("</s>")[0] + "</s>" if ("</s>" in x) else "".join(x) + "</s>" for x in outs_]
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
return outs_
| [
"[email protected]"
] | |
a17ee63004936c7173f0f09cc22d22f71b8bff3a | dc612714dbde7fc1d6060599035333d9cd182a53 | /databasemysql.py | 3ed29735f48a511986b6604cbd96eee6d6d975b6 | [] | no_license | ratsi-boy/blood-donation | b88e4d6b07a1540396f9ee887d2cc4a263574473 | b5d2d8a96bfac48f43e79f9c99de7994f639bc89 | refs/heads/main | 2023-03-31T12:14:30.988621 | 2021-03-29T07:48:18 | 2021-03-29T07:48:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 22,790 | py | from tkinter import *
from tkinter import messagebox
from tkinter import ttk
from tkinter import colorchooser
import mysql.connector
import datetime
from PIL import ImageTk, Image
root= Tk()
root.title("Blood Bank System")
root.geometry("1024x686+-8+-8")
root.configure(background='white')
root.bind("<Return>")
my_menu= Menu(root)
root.config(menu=my_menu)
root.iconbitmap("blood.ico")
now= datetime.datetime.now()
conn= mysql.connector.connect(
host="localhost",
user="username",
passwd="password",
database="blood")
c=conn.cursor()
def color():
global my_color
global buttn_edit
global buttn_delete
my_color= colorchooser.askcolor()
root.config(menu=my_menu,background=my_color[1])
buttn_submit.config(bg=my_color[1], activebackground=my_color[1])
search_buttn.config(bg=my_color[1], activebackground=my_color[1])
buttn_show.config(bg=my_color[1])
buttn_delete.config(bg=my_color[1])
buttn_edit.config(bg=my_color[1])
def admin_login():
global command1
global command2
global entry1
global entry2
global top
global bttn1
top= Toplevel()
top.title("Login Screen")
top.geometry("500x500")
top.bind("<Return>")
top.configure(background="white")
global admin_img
admin_img= PhotoImage(file="12.png")
label3= Label(top, image=admin_img, bg="white")
label3.pack()
global entry1
global entry2
label1= Label(top, text="Username", font=('Halvetica',25),bg='white')
label1.pack()
entry1= Entry(top, bd=5)
entry1.pack()
label2= Label(top, text="Password", font=('Halvetica',25),bg='white')
label2.pack()
entry2= Entry(top, show="*")
entry2.pack()
entry2.bind("<Return>", command1)
global bttn_login
bttn_login= PhotoImage(file="login.png")
bttn1= Button(top, text="Login", image=bttn_login, command= lambda: command1(1), bd=0, bg="white")
bttn1.pack()
bttn1.bind("<Return>", command1)
global bttn_close
bttn_close= PhotoImage(file="close.png")
bttn2= Button(top, text="Close", image=bttn_close, command=open_admin_panel, bd=0, bg="white")
bttn2.pack()
root.withdraw()
def logout():
global buttn_edit
global edit
global buttn_delete
global delete
global select_id_label
global buttn_show
buttn_edit.destroy()
buttn_delete.destroy()
buttn_show.destroy()
select_id_label.destroy()
select_id.destroy()
global tools_menu
tools_menu.entryconfig("Admin Login", state=NORMAL)
tools_menu.delete("Logout")
def edit_root_window():
#Creating buttons
global buttn_edit
global edit
global buttn_delete
global delete
global select_id_label
select_id_label= Label(root,text="Select Id ",font=('Halvetica',10), bg="white")
select_id_label.grid(row=10,column=0, stick=W,pady=2)
global select_id
select_id = Entry(root,bd=5,bg="white",font=('Halvetica',10))
select_id.grid(row=10,column=1, stick=W+E+N+S,pady=2, padx=3)
global bttn_edit_img
bttn_edit_img= PhotoImage(file='3.png')
global buttn_edit
buttn_edit= Button(root, text="Update Record",image=bttn_edit_img,command=lambda: edit(1), pady=5, bd=0, bg="white",font=('Halvetica',10))
buttn_edit.grid(row=11,column=0,columnspan=2, stick=W+E+N+S, padx=3)
buttn_edit.bind("<Return>", edit)
global bttn_delete_img
bttn_delete_img= PhotoImage(file='2.png')
global buttn_delete
buttn_delete= Button(root, text="Delete Record",image=bttn_delete_img,command=lambda: delete(1), pady=5, bd=0, bg="white",font=('Halvetica',10))
buttn_delete.grid(row=12,column=0,columnspan=2, stick=W+E+N+S, padx=3)
buttn_delete.bind("<Return>", delete)
global sort
sortby=["Sort By..",
"Name",
"Gender",
"Blood Group",
"Date Update"
]
sort= ttk.Combobox(root, value=sortby)
sort.set("Sort By..")
sort.grid(row=13,column=1, stick=W+E+N+S,pady=2)
global sort_label
sort_label= Label(root,text="Sort By ",font=('Halvetica',10), bg="white")
sort_label.grid(row=13,column=0, stick=W,pady=2, padx=3)
global enter_name
enter_name = Entry(root, bd=5, bg="white",font=('Halvetica',10))
enter_name.grid(row=14, column=0, columnspan=2, stick=W+E+N+S, pady=2, padx=3)
global bttn_show
bttn_show= PhotoImage(file='5.png')
global buttn_show
buttn_show= Button(root, text="Show All", image=bttn_show, command=lambda:show(1), pady=5, bd=0, bg="white",font=('Halvetica',10))
buttn_show.grid(row=15,column=0,columnspan=2, stick=W+E+N+S, padx=3)
buttn_show.bind("<Return>", show)
global tools_menu
tools_menu.entryconfig("Admin Login", state=DISABLED)
tools_menu.add_cascade(label='Logout', command=logout)
if my_color:
buttn_show.config(bg=my_color[1])
buttn_delete.config(bg=my_color[1])
buttn_edit.config(bg=my_color[1])
def command1(e):
if entry1.get()=="admin" and entry2.get()== "admin" or entry1.get()=="root" and entry2.get()== "root":
root.deiconify()
top.destroy()
edit_root_window()
else:
messagebox.showerror("Error", "Please Enter Valid Username or Password")
entry1.delete(0, END)
entry2.delete(0, END)
def open_admin_panel():
root.deiconify()
top.destroy()
def new_file():
pass
def find():
pass
def find_next():
pass
def next_file():
pass
def previous_file():
pass
def contact_us():
pass
def read_tnc():
pass
def submit(e):
# Label(root,text=full_name.get() +gender.get()+address.get()+city.get()+state.get()+zip_code.get()).grid(row=7,column=0)
if full_name.get() =="" or drop.get() == "Select gender" or drop_blood.get()== "Select Blood Group" or address.get() =="" or contact.get()== "" or city.get() =="" or state.get()== "Select State" or zip_code.get() =="":
messagebox.showinfo("Error", "Enter Valid Details !!!! ")
else:
try:
conn= mysql.connector.connect(
host="localhost",
user="username",
passwd="password",
database="blood"
)
decide=messagebox.askyesno("Confirmation","You Want To Save These Details")
if decide == 1:
c=conn.cursor()
c.execute("INSERT INTO donors(name, gender, blood_group, address, contact, city, state, zip_code, date_updated) VALUES ('"+full_name.get().title()+"','"+drop.get()+"','"+drop_blood.get()+"','"+address.get().title()+"','"+contact.get()+"','"+city.get().title()+"','"+state.get()+"','"+zip_code.get()+"', '"+now.strftime("%Y/%m/%d")+"')")
messagebox.showinfo("Success", "Record Submitted Successfully")
full_name.delete(0, END)
drop.set("Select gender")
drop_blood.set("Select Blood Group")
address.delete(0, END)
contact.delete(0, END)
city.delete(0, END)
state.set("Select State")
zip_code.delete(0, END)
conn.commit()
conn.close()
except Exception as e:
print(e)
messagebox.showinfo("Error", "Enter Correct zip Code or contact no. !!! ")
def exit(e):
root.destroy()
def show(e):
try:
conn= mysql.connector.connect(
host="localhost",
user="username",
passwd="password",
database="blood"
)
c=conn.cursor()
global result
if sort.get()=="Sort By..":
c.execute("SELECT * FROM donors")
result=c.fetchall()
elif sort.get()=="Name":
if enter_name.get()=="":
c.execute("SELECT * FROM donors order by name")
result=c.fetchall()
else:
c.execute("SELECT * FROM donors WHERE name=('"+enter_name.get().title()+"')")
result=c.fetchall()
elif sort.get()=="Date Update":
c.execute("SELECT * FROM donors order by date_updated desc")
result=c.fetchall()
elif sort.get()=="Gender":
c.execute("SELECT * FROM donors order by gender")
result=c.fetchall()
elif sort.get()=="Blood Group":
c.execute("SELECT * FROM donors order by blood_group")
result=c.fetchall()
conn.commit()
conn.close()
sort.set("Sort By..")
enter_name.delete(0,END)
if len(result) ==0:
messagebox.showerror("Error", "No Record Found")
else:
show_windows()
except Exception as e:
messagebox.showerror("Error", "Error Occured")
def show_windows():
global show_window
show_window= Toplevel()
show_window.title("Show records")
show_window.geometry("1024x686+-8+-8")
show_window.config(bg='white')
main_frame= Frame(show_window)
main_frame.pack(fill=BOTH, expand=1)
my_canvas= Canvas(main_frame,bg='white')
my_canvas.pack(side=LEFT, fill=BOTH, expand=1)
my_scrollbar= ttk.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>' , lambda e: my_canvas.configure(scrollregion= my_canvas.bbox("all")))
second_frame = Frame(my_canvas,bg='white')
my_canvas.create_window((0,0), window=second_frame, anchor="nw")
global label_show
label_list=[
"Id",
"Name",
"Gender",
"Blood Group",
"Address",
"Contact",
"City",
"State",
"Zip Code",
"Date Updated"
]
for ind, k in enumerate(label_list):
top_label= Label(second_frame,text=k,bg="white")
top_label.grid(row=0,column=ind,stick=W, padx=5)
for index, i in enumerate(result):
num=0
for j in i:
label_show=Label(second_frame,text=j,bg="white")
label_show.grid(row=index+1,column=num, stick=W, padx=5)
num+=1
def delete(e):
if select_id.get()== "":
messagebox.showinfo("Caution", "Enter Valid Id")
select_id.delete(0, END)
else:
try:
conn= mysql.connector.connect(
host="localhost",
user="username",
passwd="password",
database="blood"
)
c=conn.cursor()
c.execute("SELECT * FROM donors WHERE iddonors=('"+select_id.get()+"')")
global res
res=c.fetchall()
conn.commit()
conn.close()
if len(res) == 0:
messagebox.showinfo("Error","Record Not Found")
select_id.delete(0, END)
else:
conn= mysql.connector.connect(
host="localhost",
user="username",
passwd="password",
database="blood"
)
c=conn.cursor()
c.execute("DELETE FROM donors WHERE iddonors=('"+select_id.get()+"')")
conn.commit()
conn.close()
show()
messagebox.showinfo("Success","Successfully Deleted Record")
select_id.delete(0, END)
except Exception as e:
messagebox.showinfo("Error", "Enter Valid Id")
select_id.delete(0, END)
def update(e):
if full_name_editor.get() =="" or dro.get() == "Select gender" or dro_blood.get()== "Select Blood Group" or address_editor.get() =="" or contact_editor.get()== "" or city_editor.get() =="" or dro_state.get()== "Select State" or zip_code_editor.get() =="":
messagebox.showinfo("Error", "Enter Valid Details !!!! ")
else:
try:
conn= mysql.connector.connect(
host="localhost",
user="username",
passwd="password",
database="blood")
c=conn.cursor()
c.execute("UPDATE donors SET name=('"+full_name_editor.get().title()+"'), gender=('"+dro.get()+"'), blood_group=('"+dro_blood.get()+"'), address=('"+address_editor.get().title()+"'), contact=('"+contact_editor.get()+"'), city=('"+city_editor.get().title()+"'), state=('"+dro_state.get()+"'), zip_code=('"+zip_code_editor.get()+"'), date_updated=('"+now.strftime("%Y/%m/%d")+"') WHERE iddonors=('"+select_id.get()+"')")
conn.commit()
conn.close()
messagebox.showinfo("Success!", "Successfully Updated Record !")
editor.destroy()
select_id.delete(0, END)
show(e)
except Exception as e:
print(e)
messagebox.showinfo("Error", "Error Occured...")
def edit(e):
if select_id.get()=="":
messagebox.showinfo("Caution", "Enter Valid Id")
select_id.delete(0, END)
else:
try:
global editor
editor= Toplevel()
editor.title("Edit Record")
global full_name_editor
global gender_editor
global blood_group_editor
global address_editor
global contact_editor
global city_editor
global state_editor
global zip_code_editor
global dro
global dro_blood
global dro_state
dro= StringVar()
dro_state= StringVar()
dro_blood= StringVar()
full_name_editor= Entry(editor,bd=5)
full_name_editor.grid(row=0,column=1, stick=W+E)
gender_editor=OptionMenu(editor,dro, "Select gender", "Male", "Female", "Other")
gender_editor.grid(row=1,column=1, stick=W+E)
blood_group_editor= OptionMenu(editor,dro_blood, *bloodgroups)
blood_group_editor.grid(row=2,column=1, stick=W+E)
address_editor= Entry(editor,bd=5)
address_editor.grid(row=3,column=1, stick=W+E)
contact_editor= Entry(editor,bd=5)
contact_editor.grid(row=4,column=1, stick=W+E)
city_editor= Entry(editor,bd=5)
city_editor.grid(row=5,column=1, stick=W+E)
state_editor= OptionMenu(editor,dro_state, *states)
state_editor.grid(row=6,column=1, stick=W+E)
zip_code_editor= Entry(editor,bd=5)
zip_code_editor.grid(row=7,column=1, stick=W+E)
full_name_label_editor= Label(editor,text="Full Name")
full_name_label_editor.grid(row=0,column=0, stick=W+E)
gender_label_editor=Label(editor,text="Gender")
gender_label_editor.grid(row=1,column=0, stick=W+E)
blood_group_label_editor= Label(editor,text="Enter Blood Group")
blood_group_label_editor.grid(row=2,column=0, stick=W+E)
address_label_editor= Label(editor,text="Address")
address_label_editor.grid(row=3,column=0, stick=W+E)
contact_label_editor= Label(editor, text="Contact No.")
contact_label_editor.grid(row=4,column=0, stick=W+E)
city_label_editor= Label(editor,text="City")
city_label_editor.grid(row=5,column=0, stick=W+E)
state_label_editor= Label(editor,text="State")
state_label_editor.grid(row=6,column=0, stick=W+E)
zip_code_label_editor= Label(editor,text="Zip Code")
zip_code_label_editor.grid(row=7,column=0, stick=W+E)
buttn_save= Button(editor, text="Save",command=lambda: update(1), pady=5,bg="green")
buttn_save.grid(row=8,column=0,columnspan=2, stick=W+E, pady=5)
buttn_save.bind("<Return>", update)
conn= mysql.connector.connect(
host="localhost",
user="username",
passwd="password",
database="blood"
)
c=conn.cursor()
c.execute("SELECT * FROM donors WHERE iddonors=('"+select_id.get()+"')")
result= c.fetchall()
for rslt in result:
full_name_editor.insert(0, rslt[1])
dro.set(rslt[2])
dro_blood.set(rslt[3])
address_editor.insert(0, rslt[4])
contact_editor.insert(0, rslt[5])
city_editor.insert(0, rslt[6])
dro_state.set(rslt[7])
zip_code_editor.insert(0, rslt[8])
conn.commit()
conn.close()
editor.mainloop()
except Exception as e:
messagebox.showinfo("Error","Please Enter Valid Id")
def search(e):
global select_blood
if select_blood.get() == "Select Blood Group":
messagebox.showinfo("Caution", "Enter Valid Blood Group")
select_blood.delete(0, END)
else:
conn= mysql.connector.connect(
host="localhost",
user="username",
passwd="password",
database="blood")
c= conn.cursor()
c.execute("SELECT name, gender,blood_group,contact,city,state,date_updated FROM donors WHERE blood_group=('"+select_blood.get()+"') order by date_updated desc")
re=c.fetchall()
conn.commit()
conn.close()
if len(re) ==0:
messagebox.showinfo("Error", "NO Record Found")
else:
search_window= Toplevel()
search_window.title("Search Result")
search_window.config(bg="white")
search_window.geometry("1024x686+-8+-8")
main_frame= Frame(search_window)
main_frame.pack(fill=BOTH, expand=1)
my_canvas= Canvas(main_frame,bg='white')
my_canvas.pack(side=LEFT, fill=BOTH, expand=1)
my_scrollbar= ttk.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>' , lambda e: my_canvas.configure(scrollregion= my_canvas.bbox("all")))
second_frame = Frame(my_canvas,bg='white')
my_canvas.create_window((0,0), window=second_frame, anchor="nw")
global label_show
label_list=[
"Name",
"Gender",
"Blood Group",
"Contact",
"City",
"State",
"Date Updated"
]
for ind, k in enumerate(label_list):
top_label= Label(second_frame,text=k,bg="white")
top_label.grid(row=0,column=ind,stick=W, padx=5)
for index, i in enumerate(re):
num=0
for j in i:
label_show=Label(second_frame,text=j,bg="white")
label_show.grid(row=index+1,column=num, stick=W, padx=5)
num+=1
select_blood.set("Select Blood Group")
def menus():
# Creating menus
global file_menu
global my_menu
global edit_menu
global tools_menu
global help_menu
file_menu= Menu(my_menu, tearoff=False)
my_menu.add_cascade(label='File', menu=file_menu)
file_menu.add_cascade(label='New...', command=new_file)
file_menu.add_separator()
file_menu.add_cascade(label='Exit', command=root.quit)
edit_menu= Menu(my_menu, tearoff=False)
my_menu.add_cascade(label='Edit', menu=edit_menu)
edit_menu.add_cascade(label='Find', command=find)
edit_menu.add_cascade(label='Find next', command=find_next)
tools_menu= Menu(my_menu, tearoff=False)
my_menu.add_cascade(label='Tools', menu=tools_menu)
tools_menu.add_cascade(label='Next', command=next_file)
tools_menu.add_cascade(label='Previous', command=previous_file)
tools_menu.add_cascade(label='Background Color', command=color)
tools_menu.add_cascade(label='Admin Login', command=admin_login)
help_menu= Menu(my_menu, tearoff=False)
my_menu.add_cascade(label='Help', menu=help_menu)
help_menu.add_cascade(label='Contact Us', command=contact_us)
help_menu.add_cascade(label='Read T&C..', command=read_tnc)
def button_label():
# Creating main heading label
global head
head= Label(root,text= "Blood Donation Portal", font=('Halvetica',25),bg='white')
head.grid(row=0,column=0,columnspan=2)
global states
global bloodgroups
# States Lists
states = [
"Select State",
"Andhra Pradesh",
"Arunachal Pradesh ",
"Assam",
"Bihar",
"Chhattisgarh",
"Goa",
"Gujarat",
"Haryana",
"Himachal Pradesh",
"Jammu and Kashmir",
"Jharkhand",
"Karnataka",
"Kerala",
"Madhya Pradesh",
"Maharashtra",
"Manipur",
"Meghalaya",
"Mizoram",
"Nagaland",
"Odisha",
"Punjab",
"Rajasthan",
"Sikkim",
"Tamil Nadu",
"Telangana",
"Tripura",
"Uttar Pradesh",
"Uttarakhand",
"West Bengal",
"Andaman and Nicobar Islands",
"Chandigarh",
"Dadra and Nagar Haveli",
"Daman and Diu",
"Lakshadweep",
"National Capital Territory of Delhi",
"Puducherry"
]
# Blood Groups Lists
bloodgroups=[
"Select Blood Group",
"A+",
"A-",
"B+",
"B-",
"O+",
"O-",
"AB+",
"AB-"
]
# Creating entry widgets
global full_name
global drop
global gender
global drop_blood
global blood_group
global address
global contact
global city
global state
global zip_code
full_name= Entry(root,bd=5,bg="white",font=('Halvetica',10))
full_name.grid(row=1,column=1, stick=W+E+N+S,pady=2)
drop= StringVar()
gender=OptionMenu(root,drop, "Select gender", "Male", "Female", "Other")
drop.set("Select gender")
gender.grid(row=2,column=1, stick=W+E+N+S,pady=2)
drop_blood= StringVar()
blood_group= OptionMenu(root,drop_blood, *bloodgroups)
drop_blood.set("Select Blood Group")
blood_group.grid(row=3,column=1, stick=W+E+N+S,pady=2)
address= Entry(root,bd=5,bg="white",font=('Halvetica',10))
address.grid(row=4,column=1, stick=W+E+N+S,pady=2)
contact= Entry(root,bd=5,bg="white",font=('Halvetica',10))
contact.grid(row=5,column=1, stick=W+E+N+S,pady=2)
city= Entry(root,bd=5,bg="white",font=('Halvetica',10))
city.grid(row=6,column=1, stick=W+E+N+S,pady=2)
state= ttk.Combobox(root, value=states)
state.set("Select State")
state.grid(row=7,column=1, stick=W+E+N+S,pady=2)
zip_code= Entry(root,bd=5,bg="white",font=('Halvetica',10))
zip_code.grid(row=8,column=1, stick=W+E+N+S,pady=2)
# Creating submit and show buttons
global bttn_submit
bttn_submit= PhotoImage(file='1.png')
global buttn_submit
buttn_submit= Button(root, text="Submit", image=bttn_submit, command=lambda: submit(1), bd=0, pady=5, bg="white",font=('Halvetica',10))
buttn_submit.grid(row=9,column=0,columnspan=2, stick=W+E+N+S, pady=(5,0), padx=3)
buttn_submit.bind("<Return>", submit)
# creating labels
global full_name_label
global gender_label
global blood_group_label
global address_label
global contact_label
global city_label
global state_label
global zip_code_label
full_name_label= Label(root,text="Full Name ",font=('Halvetica',10), bg="white")
full_name_label.grid(row=1,column=0, stick=W,pady=2, padx=3)
gender_label=Label(root,text="Gender ",font=('Halvetica',10), bg="white")
gender_label.grid(row=2,column=0, stick=W,pady=2, padx=3)
blood_group_label= Label(root,text="Enter Blood Group ",font=('Halvetica',10), bg="white")
blood_group_label.grid(row=3,column=0, stick=W,pady=2, padx=3)
address_label= Label(root,text="Address ",font=('Halvetica',10), bg="white")
address_label.grid(row=4,column=0, stick=W,pady=2, padx=3)
contact_label= Label(root, text="Contact No. ",font=('Halvetica',10), bg="white")
contact_label.grid(row=5,column=0, stick=W,pady=2, padx=3)
city_label= Label(root,text="City ",font=('Halvetica',10), bg="white")
city_label.grid(row=6,column=0, stick=W,pady=2, padx=3)
state_label= Label(root,text="State ",font=('Halvetica',10), bg="white")
state_label.grid(row=7,column=0, stick=W,pady=2, padx=3)
zip_code_label= Label(root,text="Zip Code ",font=('Halvetica',10), bg="white")
zip_code_label.grid(row=8,column=0, stick=W,pady=2, padx=3)
# global bttn_exit
# bttn_exit= PhotoImage(file='exit.png')
# buttn_exit= Button(root, text="Exit",image=bttn_exit, command=lambda: exit(1), pady=5, bd=5, bg="red",font=('Halvetica',10))
# buttn_exit.grid(row=14,column=0,columnspan=2, stick=W+E+N+S)
# buttn_exit.bind("<Return>", exit)
# Creating Labels for search
global head_1
head_1 = Label(root,text= "Search For Donor", font=('Halvetica',25),bg='white')
head_1.grid(row=0, column=2,columnspan=2,stick=W+E+N+S, padx=50)
global label_blood
label_blood= Label(root,text="Select Blood Group ",font=('Halvetica',10), bg="white")
label_blood.grid(row=1, column=2, stick=W, pady=2, padx=50)
global select_blood
select_blood= ttk.Combobox(root, value=bloodgroups)
select_blood.set("Select Blood Group")
select_blood.grid(row=1, column=3, stick=W, pady=2, padx=50)
# Creating Search Button to search donors
global bttn_search
bttn_search= PhotoImage(file='4.png')
global search_buttn
search_buttn= Button(root, text="Search For Donors",image=bttn_search, command=lambda: search(1), bg="white", pady=2, bd=0, font=('Halvetica',10))
search_buttn.grid(row=2, column=2, columnspan=2, stick=W+E+N+S, padx=50)
search_buttn.bind("<Return>", search)
menus()
button_label()
conn.commit()
conn.close()
root.mainloop() | [
"[email protected]"
] | |
f1e94113114ac69c0633da7f51734a3613a42aa1 | 45ec599e17e8b848f694f9d091b2fdd05efdb4e9 | /2.1-databases/work_with_database/phones/models.py | e904ab93191dc8bba335b39769ac54fa7f034252 | [] | no_license | TVP-18/hw_Django | 042ffc45a45c248fcdc7c7a4c65c1dd64e515649 | 4b4eade4fe7feb364adad63bf32e8fc634264dd0 | refs/heads/master | 2023-08-25T13:47:13.037055 | 2021-10-10T08:37:44 | 2021-10-10T08:37:44 | 392,289,184 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 370 | py | from django.db import models
class Phone(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=10, decimal_places=2)
image = models.TextField()
release_date = models.DateField()
lte_exists = models.BooleanField()
slug = models.SlugField()
def __str__(self):
return f"{self.id}: {self.name}"
| [
"[email protected]"
] | |
672e718a1caa49c808935d85d027e983ba5e9a4c | 044da5aa2acc9e92888dd40b06a8d2f50cccfca0 | /blog/migrations/0003_post_tags.py | ea622c3bdd266741783036ae4a4bf24209a76490 | [] | no_license | KunalKP4042/KPs-Resto-Bar | b189f591eb42827a9813a14e40b569312281bac8 | 8ccc73d1425965fe65a31c4345538de00715becb | refs/heads/master | 2023-04-09T13:56:25.573775 | 2021-04-18T07:16:27 | 2021-04-18T07:16:27 | 337,150,644 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 572 | py | # Generated by Django 3.1.3 on 2021-01-11 15:23
from django.db import migrations
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('taggit', '0003_taggeditem_add_unique_index'),
('blog', '0002_auto_20210111_1959'),
]
operations = [
migrations.AddField(
model_name='post',
name='tags',
field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'),
),
]
| [
"[email protected]"
] | |
e5f14a4bfe366c2341e18edf43b7120c578dd466 | 487f4987f7ade541c673f2c6571545c09d345a84 | /main.py | 001a420a8bdf948d8a8694bc729f149c64fd3bf9 | [] | no_license | tolulope-od/Diagonal-FileTraverse-Python3 | 9afb7e13b179b98fa4bcf32d859e36c8a79d7932 | 42c431578e37ed05f7fd7ff98eaad14fa297d5b6 | refs/heads/master | 2020-04-02T00:24:13.297318 | 2018-10-19T15:22:33 | 2018-10-19T15:22:33 | 153,802,843 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,128 | py | #import the xlrd module for working with xlsx extension files
import xlrd
traverseresult = list() #create an empty list to hold results of the data gotten from the file
#create a class that can make instances of xlsx file objects
class ReadXlsx(object):
#Create a method to open the file and traverse it
def traversefile(self, filepath):
#Open the spreadsheet file
workbook = xlrd.open_workbook(filepath)
#Open the first sheet in the file
worksheet = workbook.sheet_by_index(0)
#Create a for loop to iterate through all the colums in the file diagonally
#store them into an Array/List for further actions
total_cols = worksheet.ncols
for i in range(total_cols):
traverseresult.append(worksheet.cell(i, i).value)
return traverseresult
#Add a method to display the values stored in the list dynamically printed on one line
def displayTraverseValues(self):
print(" ".join(str(x) for x in traverseresult))
'''
for i in traverseresult:
print(i, end = " ")
'''
def main():
test = ReadXlsx()
test.traversefile("qzAjJo.xlsx")
test.displayTraverseValues()
if __name__ == '__main__':
main() | [
"[email protected]"
] | |
e0eade989224a93aace44ec5a8e10d22abaee72e | 646d4d2e4457f30c602610e36afc81b461ff31ca | /taskproject/auth_backends.py | c340c90a32346f53da0f5b4afc6e85813e429e75 | [] | no_license | rupeshdeoria/customuser | f25d7c4e14f0c0a521020d2770e1d0e6b53c7daa | 24e7cd6c70d94ad9b338284998a0a7e4b1674282 | refs/heads/master | 2021-03-12T20:09:28.652690 | 2014-10-21T07:19:41 | 2014-10-21T07:19:41 | 25,507,924 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,156 | py | # import the User object
from django.contrib.auth.models import User
# Name my backend 'MyCustomBackend'
class MyCustomBackend:
# Create an authentication method
# This is called by the standard Django login procedure
def authenticate(self, username=None, password=None):
try:
# Try to find a user matching your username
user = User.objects.get(email=username)
# Check the password is the reverse of the username
'''if password == username[::-1]:
# Yes? return the Django user object
return user'''
if user.check_password(password):
return user
else:
# No? return None - triggers default login failed
return None
except User.DoesNotExist:
# No user was found, return None - triggers default login failed
return None
# Required for your backend to work properly - unchanged in most scenarios
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None | [
"[email protected]"
] | |
1ff6304e4f44581cb3db2507410b0bcf616e211c | 896c304b4b44945b7c00753dc929c404ba220e05 | /ChatServer.py | 2e41e9a5b1bac62f9d8c660c9c6490ebb537e3a9 | [] | no_license | essigs13/Chat-room-Server-and-Client | 97d22ac2c88bc8e4af850e897409a73729a884fc | b7b326a3b7643178b5621fbbb7042477eb3e70c5 | refs/heads/master | 2020-04-17T01:21:43.536168 | 2019-01-16T18:28:26 | 2019-01-16T18:28:26 | 166,088,907 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,603 | py | #assn1 server program written by Steven Essig
import socket
# Create a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 12222)
sock.bind(server_address)
print("listening on: %s and port: %s" % server_address)
#Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
connection, client_address = sock.accept()
print("Client Found! \n")
print("Users take turns sending messages back and forth")
print("The session will be closed if either user sends the message: Good bye my friend")
print("The client goes first \n")
print("Session is starting\n")
try:
# Receive the data and retransmit it back
while True:
data = connection.recv(256)
decoded = data.decode()
if 'Good bye my friend' in decoded:
print("receiving: %s" % decoded)
print("\nSession is closing")
break
# Echos back any data received that was not "Echo" or "Exit"
else:
print("receiving: %s" % decoded)
data = input("sending: ")
if 'Good bye my friend' in data:
connection.sendall(data.encode())
print("\nSession is closing")
break
else:
connection.sendall(data.encode())
finally:
# Close up the connection and exit the server
connection.close()
exit() | [
"[email protected]"
] | |
4f4c63844906ccc546fe71211dcb411fb127f080 | 0e37e0f2427b05cc1f583327c9e9b31a1dd4ebf8 | /melon-production/shipping_procedure.py | fb24a9463c32add8965f0fb953f8c8963799e75a | [] | no_license | EmmaOnThursday/hackbright-homework | c271c5c2e4bec53eef85d17a105cec7cc940a01b | e9831afd297a1256648622b62c21f9ddad73ca64 | refs/heads/master | 2016-08-12T23:46:57.955461 | 2016-02-02T04:59:14 | 2016-02-02T04:59:14 | 50,083,478 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,846 | py | """Shipping procedures for Ubermelon."""
import robots
import sys
MELON_LIMIT = 200
class Melon(object):
"""Melon."""
def __init__(self, melon_type):
"""Initialize melon.
melon_type: type of melon being built.
"""
self.melon_type = melon_type
self.weight = 0.0
self.color = None
self.stickers = []
def prep(self):
"""Prepare the melon."""
robots.cleanerbot.clean(self)
robots.stickerbot.apply_logo(self)
def __str__(self):
"""Print out information about melon."""
if self.weight <= 0:
return self.melon_type
else:
return "{} {:.2f} lbs {}".format(self.color,
self.weight,
self.melon_type)
# FIXME: Add Squash Class definition here.
class Squash(Melon):
"""Winter Squash"""
def prep(self):
"""Prepare the melon."""
robots.cleanerbot.clean(self)
robots.stickerbot.apply_logo(self)
robots.painterbot.paint(self)
def show_help():
print """
shipping_procedure.py
Master Control Program for Automated Melon Order Fullfillment
This program processes order from an order log file and controls the
robots used to fulfill the orders.
Usage:
python shipping_procedure.py [logfile]
Where:
[logfile]
The name of the log file you would like to process.
Hint: There are two files included in this project folder.
"""
def main():
"""Assesses and packs order objects.
Distinguishes between melons/squashes."""
# Check to make sure we've been passed an argument on the
# command line. If not, display instructions.
if len(sys.argv) < 2:
show_help()
sys.exit()
# Get the name of the log file to open from the command line
logfilename = sys.argv[1]
# Open the log file
f = open(logfilename)
# Read each line from the log file and process it
for line in f:
# Each line should be in the format:
# <melon name>: <quantity>
# Unpacks each line into variables
melon_type, quantity = line.rstrip().split(':')
quantity = int(quantity)
print "\n-----"
print "Fullfilling order of {} {}".format(quantity, melon_type)
print "-----\n"
count = 0
melons = []
# Pick melons until we reach the requested quantity
while len(melons) < quantity:
# Make sure we haven't reached our limit for the total
# number of melons we're allowed to pick
if count > MELON_LIMIT:
print "\n------------------------------"
print "ALL MELONS HAVE BEEN PICKED"
print "ORDERS FAILED TO BE FULFILLED!"
print "------------------------------\n"
sys.exit()
# Have the robot pick a 'melon' -- check to
# see if it is a Winter Squash or not.
if melon_type != "Winter Squash":
m = Melon(melon_type)
else:
m = Squash(melon_type)
robots.pickerbot.pick(m)
count += 1
# Prepare the melon
m.prep()
# Evaluate the melon
presentable = robots.inspectorbot.evaluate(m)
if presentable:
melons.append(m)
else:
robots.trashbot.trash(m)
continue
print "------"
print "Robots Picked {} {} for order of {}".format(count, melon_type, quantity)
# Pack the melons for shipping
boxes = robots.packerbot.pack(melons)
# Ship the boxes
robots.shipperbot.ship(boxes)
print "------\n"
main()
| [
"[email protected]"
] | |
6d28be97f2afbd88a2e1dc0864ef9d921ab270b3 | f70b87f3f5e690c149a5034528f2e1dd10b5096e | /python/strings.py | af964df1b00c4d254d10d6c25e34ba38236044eb | [] | no_license | kriti-ixix/ml-230 | 02ebfb0a85a73f52683e59bf513e25e949b163da | d7dac60034677b82de51c9197c4f9d38938322b6 | refs/heads/main | 2023-07-09T07:09:19.134665 | 2021-08-18T07:05:11 | 2021-08-18T07:05:11 | 386,823,869 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 669 | py | myString = "Hello world!"
myString2 = "How are you?"
#String Indexing
print(myString[2])
print(myString[7])
print(myString[-1]) #Negative Indexing
#String slicing
#string[start=0 : stop=len(exclusive) : step=1]
print(myString[2:8])
print(myString[2:8:2])
print(myString[::-1]) #Reverse a string
#Length of a string
print(len(myString))
#String concatenation
print(myString + " " + myString2)
#String casing
print(myString.upper())
print(myString.lower())
#String splitting
print(myString.split())
print(myString2.split())
tweet = "Good morning #niceweather #feelinggood #sunny"
print(tweet.split("#"))
print(tweet.split("#", 1))
for x in myString:
print(x) | [
"[email protected]"
] | |
1de6e990459f2886842476ffbf3f9018c7bb01db | 72c732f0e7e8bae3a14700368b3a4ec54f8958b7 | /scripts/parse_wiki.py | 7b645f7e3d8e5b64bee3410e8fd95e37a0744e0f | [] | no_license | colinsongf/medical_lexical_simplification | 7b0db42993fe985e4beca3b8817f5118475abac7 | 4bfe189265bc64c095a8ec0889cf8f3137194dbf | refs/heads/master | 2020-08-29T06:04:03.295970 | 2019-10-09T10:10:26 | 2019-10-09T10:10:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,190 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 17 12:29:09 2018
@author: Samuele Garda
"""
import argparse
import logging
import multiprocessing
import bz2
import functools
from collections import defaultdict
import smart_open
from gensim.corpora import wikicorpus
from gensim.utils import to_unicode,to_utf8,chunkize
from gensim.parsing import preprocessing as pp
from io_utils import IOManager as iom
logger = logging.getLogger(__name__)
logging.basicConfig(format = '%(asctime)s : %(levelname)s : %(module)s: %(message)s', level = 'INFO')
def parse_args():
"""
Parse command line arguments
"""
parser = argparse.ArgumentParser(description='Parse Wikipedia dump')
parser.add_argument('--input',required = True, type = str, help = "File containing wikipedia dump : XML.BZ2 format")
parser.add_argument('--out', required = True, type = str, help = "Output directory where store files")
parser.add_argument('--limit',default = 1000, type = int, help = "Parse only this many examples")
parser.add_argument('--cores',default = 4, type = int, help = "How many cores to use")
return parser.parse_args()
# gensim preprocessing functions
FILTERS = [lambda x : x.lower(), pp.strip_tags,
pp.strip_punctuation,
pp.strip_multiple_whitespaces, pp.remove_stopwords]
def preprocess_fn(text):
"""
Preprocess string.
Args:
text (str) : input text
Return:
out (list) : list of tokens
"""
out = pp.preprocess_string(text, filters = FILTERS)
return out
def process_wikipedia_article(wiki_page,preprocess_fn):
"""
Parse single wikipedia article.
Args:
wiki_page (tuple) : tuple of (str or None, str, str)
preprocess_fn (function) : preprocessing function
Return:
title,text (str) : tuple containing title and text of wiki page
"""
title, text, page_id = wiki_page
title = to_unicode(title.replace('\t', ' '))
text = wikicorpus.filter_wiki(text)
text = preprocess_fn(text)
return title,text
def parse_wiki_dump(infile, min_words, process_function, processes=multiprocessing.cpu_count()-2):
"""
Yield articles from a bz2 Wikipedia dump `infile` as (title, tokens) 2-tuples.
Only articles of sufficient length are returned (short articles & redirects
etc are ignored).
Uses multiple processes to speed up the parsing in parallel.
Args:
infile (str) : path to bz2 Wikipedia dump
min_words (int) : skip article if it has less than this many words
process_function (function) : preprocessing function
processes (int) : number of cores to be used
"""
logger.info("Start processing Wikipedia dump `{}`".format(infile))
articles, articles_all = 0, 0
pool = multiprocessing.Pool(processes)
# process the corpus in smaller chunks of docs, because multiprocessing.Pool
# is dumb and would try to load the entire dump into RAM...
texts = wikicorpus._extract_pages(bz2.BZ2File(infile)) # generator
ignore_namespaces = 'Wikipedia Category File Portal Template MediaWiki User Help Book Draft'.split()
for group in chunkize(texts, chunksize=10 * processes):
for title,tokens in pool.imap(process_function, group):
if articles_all % 10000 == 0:
logger.info("PROGRESS: at article #{} accepted {} articles".format(articles_all, articles))
articles_all += 1
# article redirects and short stubs are pruned here
if any(title.startswith(ignore + ':') for ignore in ignore_namespaces) or len(tokens) < min_words:
continue
# all good: use this article
articles += 1
yield title,tokens
pool.terminate()
logger.info("finished iterating over Wikipedia corpus of {} documents with total {} articles".format(articles, articles_all))
if __name__ == "__main__":
args = parse_args()
infile = args.input
out_dir = args.out
limit = args.limit
cores = args.cores
min_words = 50
iom.make_dir(out_dir)
out_name = iom.base_name(out_dir)
out_path = iom.join_paths([out_dir,out_name+".txt.gz"])
counts_path = iom.join_paths([out_dir,out_name+".freqs"])
wiki_counts = defaultdict(int)
process_article = functools.partial(process_wikipedia_article, preprocess_fn = preprocess_fn)
with smart_open.open(out_path ,'wb') as fout:
for docno,(title,tokens) in enumerate(parse_wiki_dump(infile = infile,
min_words = min_words,
process_function = process_article,
processes = cores)):
if limit is not None and docno > limit:
break
for tok in tokens:
wiki_counts[tok] += 1
bytes_line = to_utf8(' '.join(tokens)) # make sure we're storing proper utf8
fout.write(bytes_line)
if limit and docno > limit:
break
logger.info("Completed processing wikipedia dump")
logger.info("Saving english wiki word frequencies at : `{}`".format(counts_path))
iom.save_pickle(wiki_counts,counts_path)
| [
"[email protected]"
] | |
34ae655ceb66bb79bd0c2a65c932b65b98108990 | ce680c45968e7f7c6c6906b24fab90487d860f69 | /ml_gym/environments/attention_allocation_test.py | d70b9658cd652ff238503121a4deaedfb2a0555b | [
"Apache-2.0"
] | permissive | olliethomas/ml-fairness-gym | 884420d058301be342ae68b72a2dcf2d2651525b | adaa878596d3ce7dc0ee821f53f99cdf0cd2ef5f | refs/heads/master | 2021-03-30T05:40:39.356381 | 2020-03-17T16:48:35 | 2020-03-17T16:48:35 | 248,021,897 | 0 | 0 | Apache-2.0 | 2020-03-17T16:41:11 | 2020-03-17T16:41:10 | null | UTF-8 | Python | false | false | 5,508 | py | # coding=utf-8
# Copyright 2020 The ML Fairness Gym Authors.
#
# 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.
# Lint as: python2, python3
"""Tests for attention_allocation environment."""
from __future__ import absolute_import, division, print_function
import numpy as np
from absl.testing import absltest
from six.moves import range
import test_util
from ml_gym.agents import random_agents
from ml_gym.environments import attention_allocation
class LocationAllocationTest(absltest.TestCase):
def test_sample_incidents_centered_on_incident_rates(self):
"""Check sample_incidents return follows expected distribution.
This test verifies the incident rates across locations returned by
_sample_incidents are centered on the underling incident_rates.
"""
n_trials = 100
rng = np.random.RandomState()
rng.seed(0)
params = attention_allocation.Params()
# _sample_incidents returns occurred incidents and reported incidents.
# They are generated identically so we are testing on ocurred incidents,
# which is at index 0.
samples = [attention_allocation._sample_incidents(rng, params)[0] for _ in range(n_trials)]
means = np.mean(samples, axis=0)
std = np.std(samples, axis=0)
errors_in_tolerance = [
(np.abs(means[i] - params.incident_rates[i]) < (std[i] / 3.0))
for i in range(params.n_locations)
]
self.assertTrue(np.all(errors_in_tolerance))
def test_update_state(self):
"""Check that state is correctly updated with incidents_seen.
This tests checks that numbers of incidents_seen are no more than the
incidents generated and the attention deployed as specified in the action,
if allocating without attention replacement.
"""
env = attention_allocation.LocationAllocationEnv()
env.seed(0)
agent = random_agents.RandomAgent(env.action_space, None, env.observation_space)
observation = env.reset()
action = agent.act(observation, False)
crimes, reported_incidents = attention_allocation._sample_incidents(
env.state.rng, env.state.params
)
attention_allocation._update_state(env.state, crimes, reported_incidents, action)
incidents_seen = env.state.incidents_seen
self.assertTrue((incidents_seen <= crimes).all())
if not env.state.params.attention_replacement:
self.assertTrue((incidents_seen <= action).all())
def test_parties_can_interact(self):
test_util.run_test_simulation(env=attention_allocation.LocationAllocationEnv())
def test_dynamic_rate_change(self):
params = attention_allocation.Params()
params.dynamic_rate = 0.1
params.incident_rates = [4.0, 2.0]
params.n_attention_units = 2
env = attention_allocation.LocationAllocationEnv(params=params)
env.seed(0)
env.step(action=np.array([2, 0]))
new_rates = env.state.params.incident_rates
expected_rates = [3.8, 2.1]
self.assertEqual(expected_rates, new_rates)
def test_features_centered_correctly_no_noise(self):
params = attention_allocation.Params()
params.n_locations = 3
params.prior_incident_counts = (500, 500, 500)
params.incident_rates = [1.0, 1.0, 1.0]
params.miss_incident_prob = (0.2, 0.2, 0.2)
params.extra_incident_prob = (0.0, 0.0, 0.0)
params.feature_covariances = [[0, 0], [0, 0]]
rng = np.random.RandomState()
rng.seed(0)
expected_features_shape = (params.n_locations, len(params.feature_means))
features = attention_allocation._get_location_features(params, rng, [1, 1, 1])
self.assertEqual(features.shape, expected_features_shape)
expected_feautres = np.array([[1.0, 2.0], [1.0, 2.0], [1.0, 2.0]])
self.assertTrue(np.array_equal(expected_feautres, features))
def test_features_centered_correctly(self):
params = attention_allocation.Params()
params.n_locations = 3
params.prior_incident_counts = (500, 500, 500)
params.incident_rates = [1.0, 1.0, 1.0]
params.miss_incident_prob = (0.2, 0.2, 0.2)
params.extra_incident_prob = (0.0, 0.0, 0.0)
rng = np.random.RandomState()
rng.seed(0)
n_samples = 200
expected_features_shape = (params.n_locations, len(params.feature_means))
features = np.zeros(expected_features_shape)
for _ in range(n_samples):
new_features = attention_allocation._get_location_features(params, rng, [1, 1, 1])
self.assertEqual(new_features.shape, expected_features_shape)
features = features + new_features
expected_feature_average = np.array([[1.0, 2.0], [1.0, 2.0], [1.0, 2.0]])
self.assertTrue(
np.all(np.isclose(features / n_samples, expected_feature_average, atol=0.1))
)
if __name__ == "__main__":
absltest.main()
| [
"[email protected]"
] | |
0e8a3cb11dc43c1866ed7af41b88fab6d7a8deaf | 81c280d8a6187615b9a80b7c8870523d531d5edb | /policy_eval_recurrenct.py | a564d15a49bdc4dc098ba4c801e80bc77cc37ccb | [] | no_license | haoranyuan/MasterThesis | 02ab80ca775051822bee175272bcbcf5a402d619 | f12501b6cf4ecde7d04e738697d04dde3cbc4e7f | refs/heads/master | 2022-12-19T12:11:14.844840 | 2020-09-10T07:44:59 | 2020-09-10T07:44:59 | 294,337,807 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,641 | py | from matplotlib import pyplot as plt
import numpy as np
from rl_policy_dir import RL_Multi
from rewardconstruct import FeatureExpectation
from demo_discrete import Discretize
import os
def policy_eval(DIR, iter, PLOT=False, force_evaluate=False):
# import mixed policies
dis = Discretize(data=None)
fe = FeatureExpectation()
Feature_expectation = []
# if not os.path.isfile(DIR + 'mixed_feature_expectations.csv') and force_evaluate:
if True:
print('Evaluating un-fuzzy policy')
for i in range(iter):
RL_Multi(QUAD_DYNAMICS_UPDATE=0.2, render=False, validation=1,
episode=231, file_dir=DIR + 'iter' + str(i) + '/',
policy_dir=DIR + 'iter' + str(i) + '/mixed_policy.csv')
dis.data = np.genfromtxt(DIR + 'iter' + str(i) + '/agentdata_mp.csv', delimiter=',')
traj = dis.discretize_data()
feat, _ = fe.featureexpectations(trajectories=traj, header_exist=True)
Feature_expectation.append(feat)
np.savetxt(DIR + 'mixed_feature_expectations.csv', Feature_expectation, delimiter=',')
Feature_expectation = []
# if not os.path.isfile(DIR + 'mixedfuzzy_feature_expectations.csv') and force_evaluate:
if True:
print('Evaluating fuzzy policy')
for i in range(iter):
RL_Multi(QUAD_DYNAMICS_UPDATE=0.2, render=False, validation=1,
episode=231, file_dir=DIR + 'iter' + str(i) + '/',
policy_dir=DIR + 'iter' + str(i) + '/mixedfuzzy_policy.csv', fuzzy=True)
dis.data = np.genfromtxt(DIR + 'iter' + str(i) + '/agentdata_fuzzymp.csv', delimiter=',')
traj = dis.discretize_data()
feat, _ = fe.featureexpectations(trajectories=traj, header_exist=True)
Feature_expectation.append(feat)
np.savetxt(DIR + 'mixedfuzzy_feature_expectations.csv', Feature_expectation, delimiter=',')
mixed_fea = np.genfromtxt(DIR + 'mixed_feature_expectations.csv', delimiter=',')
mixedfuzzy_fea = np.genfromtxt(DIR + 'mixedfuzzy_feature_expectations.csv', delimiter=',')
fea__ = np.genfromtxt(DIR + 'feature_expectation_AL.csv', delimiter=',')
fea_e = np.genfromtxt(DIR + 'feature_expectations.csv', delimiter=',')[0, :-1]
fea = np.genfromtxt(DIR + 'feature_expectations.csv', delimiter=',')[1:, :-1]
print([np.linalg.norm(f - fea_e) for f in fea])
print([np.linalg.norm(f - fea_e) for f in fea__])
print([np.linalg.norm(f - fea_e) for f in mixed_fea])
print([np.linalg.norm(f - fea_e) for f in mixedfuzzy_fea])
Lambda = np.genfromtxt(DIR + 'Lambda.csv', delimiter=',')
'''
#print([l for l in Lambda])
lam = [l for l in Lambda]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_ylabel('distance to $\mu_e$')
ax1.set_xlabel('iterations')
ax1.plot([np.linalg.norm(f - fea_e) for f in fea], label='$\mu$ using reward functions')
ax1.plot([np.linalg.norm(f - fea_e) for f in fea__], label=r"$\bar \mu$")
ax1.plot([np.linalg.norm(f - fea_e) for f in mixedfuzzy_fea], label= 'mixed non-deterministic'+r'$\hat\mu$')
ax1.plot([np.linalg.norm(f - fea_e) for f in mixed_fea], label= 'mixed deterministic'+r'$\hat\mu$')
ax2 = ax1.twinx()
ax2.plot(np.arange(len(lam))+1, lam, 'o--', label='$\lambda$')
ax2.set_ylabel('$\lambda$')
ax1.set_xticks(np.arange(0, 20))
#ax2.set_yticks(lam)
ax1.grid()
fig.legend()
'''
if PLOT:
plt.show()
if __name__ == '__main__':
DIR = 'AL_results/projection_good/projection_good6/'
iter = 20
policy_eval(DIR, iter, PLOT=True) | [
"[email protected]"
] | |
80ba13b0f9ecdfd7d0b9ad1d2b306231339bd5f4 | 05a9ebf253d821cf8a5d408b20fbbb73797edb9e | /python/tvm/driver/tvmc/composite_target.py | ba7862378557c905811c6293c23e9c5bc6a8fd0d | [
"Apache-2.0",
"Zlib",
"MIT",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense"
] | permissive | axistek/tvm | af881afcd336cdc370ea19c000c0443f2df55b09 | c559855c2738f98cb5d925fb9924acbe50e91278 | refs/heads/main | 2023-08-21T03:33:22.671864 | 2021-10-27T01:02:30 | 2021-10-27T01:02:30 | 344,383,241 | 0 | 2 | Apache-2.0 | 2021-03-04T07:12:26 | 2021-03-04T07:12:26 | null | UTF-8 | Python | false | false | 3,088 | py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""
Provides support to composite target on TVMC.
"""
import logging
# Make sure Vitis AI codegen is registered
import tvm.contrib.target.vitis_ai # pylint: disable=unused-import
from tvm.relay.op.contrib.arm_compute_lib import partition_for_arm_compute_lib
from tvm.relay.op.contrib.ethosn import partition_for_ethosn
from tvm.relay.op.contrib.cmsisnn import partition_for_cmsisnn
from tvm.relay.op.contrib.ethosu import partition_for_ethosu
from tvm.relay.op.contrib.bnns import partition_for_bnns
from tvm.relay.op.contrib.vitis_ai import partition_for_vitis_ai
from .common import TVMCException
# pylint: disable=invalid-name
logger = logging.getLogger("TVMC")
# Global dictionary to map targets
#
# Options
# -------
# config_key : str
# The configuration key to be used in the PassContext (if any).
# pass_pipeline : Callable
# A function to transform a Module before compilation, mainly used
# for partitioning for the target currently.
REGISTERED_CODEGEN = {
"compute-library": {
"config_key": None,
"pass_pipeline": partition_for_arm_compute_lib,
},
"cmsis-nn": {
"config_key": None,
"pass_pipeline": partition_for_cmsisnn,
},
"ethos-n77": {
"config_key": "relay.ext.ethos-n.options",
"pass_pipeline": partition_for_ethosn,
},
"ethos-u": {
"config_key": "relay.ext.ethosu.options",
"pass_pipeline": partition_for_ethosu,
},
"bnns": {
"config_key": None,
"pass_pipeline": partition_for_bnns,
},
"vitis-ai": {
"config_key": "relay.ext.vitis_ai.options",
"pass_pipeline": partition_for_vitis_ai,
},
}
def get_codegen_names():
"""Return a list of all registered codegens.
Returns
-------
list of str
all registered targets
"""
return list(REGISTERED_CODEGEN.keys())
def get_codegen_by_target(name):
"""Return a codegen entry by name.
Parameters
----------
name : str
The name of the target for which the codegen info should be retrieved.
Returns
-------
dict
requested target codegen information
"""
try:
return REGISTERED_CODEGEN[name]
except KeyError:
raise TVMCException("Composite target %s is not defined in TVMC." % name)
| [
"[email protected]"
] | |
e89af17f04f427784e2cae3449287fb1f36f07e6 | fea1810e5e08687bd631d7d824429a32a748b606 | /moving_rectangles.py | f2d1c10edd2165d8654540316b107f921d412e38 | [] | no_license | digipodium/sophomore_python_1230_oct_21 | a72938a3e7db09e8f0d7a29bcfdac7c27875e258 | e723cbac406114f6b88675491245a540a21a57ac | refs/heads/main | 2023-08-28T03:07:37.939849 | 2021-10-25T08:30:59 | 2021-10-25T08:30:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 359 | py | # Write your code here :-)
WIDTH = 500
HEIGHT = 500
box = Rect((20,20), (60,60))
box2 = Rect((400,350),(60,60))
def draw():
screen.clear()
screen.draw.rect(box,'yellow')
screen.draw.filled_rect(box2,'orange')
def update():
box.x = box.x + 10
if box.x > WIDTH:
box.x = 0
box2.x +=2
if box2.x > WIDTH:
box2.x = 0
| [
"[email protected]"
] | |
81c456913d2484e9f7bda48bacf4d1eb2c6b9a04 | e9bbf3133c91c3323cb4750bcaaad288ac830f24 | /reports/report.py | 57e752cf4b15b8897cbd6fa263fcbe56afbe25b5 | [] | no_license | ricardocr18/igo_vereador | ff89942fbb874f5ec8f6ccf8c46c9449e013218d | 95bb0c17ff0ed4e0b7878a772e0354dda31dcf8a | refs/heads/main | 2023-07-12T04:20:37.371384 | 2021-08-17T06:11:35 | 2021-08-17T06:11:35 | 383,234,224 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,530 | py | # -*- coding: utf-8 -*-
from odoo import models, fields, api,tools,exceptions, _, SUPERUSER_ID
class RelatorioSolicitacao(models.TransientModel):
_name = 'report_solicitacao'
#Campos para o usuario selecionar
status = fields.Selection([('andamento', 'Em andamento'),
('pendente', 'Pendente'),
('concluido', 'Concluído')], string="Status")
cpf = fields.Char("CPF")
def get_report(self):
#Funcao que retorna o campo solucionado
data = {
'ids': self.ids,
'model': self._name,
'form': {
'status': self.status,
'cpf': self.cpf,
},
}
#Retorno para a view pdf_report com o ID recap_report
return self.env.ref('igo_vereador.recap_report').report_action(self, data=data)
class ReportRelatorioSolicitacao(models.AbstractModel):
#Model de construcao do relatorio o nome da model deve sempre começar com report
_name = 'report.igo_vereador.solicitacao_report_view'
@api.model
def _get_report_values(self, docids, data=None):
status = data['form']['status']
cpf = data['form']['cpf']
docs = []
print (status,cpf)
if status != False and cpf == False:
solicitacoes = self.env['cadastro.cidadao'].search([('status', '=', status),], order='data_solicitacao asc')
if cpf != False and status == False:
solicitacoes = self.env['cadastro.cidadao'].search([('cpf', '=', cpf), ], order='data_solicitacao asc')
if cpf != False and status != False:
solicitacoes = self.env['cadastro.cidadao'].search([('status', '=', status),('cpf', '=', cpf), ], order='data_solicitacao asc')
for solicitacao in solicitacoes:
docs.append({
'name': solicitacao.name,
'cpf': solicitacao.cpf,
'email': solicitacao.email,
'telefone': solicitacao.telefone,
'celular': solicitacao.celular,
'descricao_pedido': solicitacao.descricao_pedido,
'categoria': solicitacao.categoria,
'data_solicitacao': solicitacao.data_solicitacao,
'data_entrega': solicitacao.data_entrega,
'status': solicitacao.status,
})
return {
'doc_ids': data['ids'],
'doc_model': data['model'],
'status': status,
'docs': docs,
}
| [
"[email protected]"
] | |
a3a925b906dc6944d5f8c7f307fb6c90fddcbefa | e33eb3bd25f4e7f0612a32cbee94b3f0c61e1c76 | /tests/mealpy_test.py | 6938fc4d75cc4079cbb432ed0ad047aeb460a6fc | [
"MIT"
] | permissive | pmbranco/mealpy | 107e8178b05d21fe16ec66f939422ac160af620d | 5d2eef36d1003b85d048ebab7c16d9987332571e | refs/heads/master | 2022-01-19T01:05:45.382003 | 2019-05-14T02:02:49 | 2019-05-14T02:02:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 20,328 | py | from collections import namedtuple
from unittest import mock
import pytest
import requests
import responses
from mealpy import mealpy
City = namedtuple('City', 'name objectId')
@pytest.fixture(autouse=True)
def mock_responses():
with responses.RequestsMock() as _responses:
yield _responses
class TestCity:
@staticmethod
def test_get_cities(mock_responses):
response = {
'result': [
{
'id': 'mock_id1',
'objectId': 'mock_objectId1',
'state': 'CA',
'name': 'San Francisco',
'city_code': 'SFO',
'latitude': 'mock_latitude',
'longitude': 'mock_longitude',
'timezone': -7,
'countryCode': 'usa',
'countryCodeAlphaTwo': 'us',
'defaultLocale': 'en-US',
'dinner': False,
'neighborhoods': [
{
'id': 'mock_fidi_id',
'name': 'Financial District',
},
{
'id': 'mock_soma_id',
'name': 'SoMa',
},
],
},
{
'id': 'mock_id2',
'objectId': 'mock_objectId2',
'state': 'WA',
'name': 'Seattle',
'city_code': 'SEA',
'latitude': 'mock_latitude',
'longitude': 'mock_longitude',
'timezone': -7,
'countryCode': 'usa',
'countryCodeAlphaTwo': 'us',
'defaultLocale': 'en-US',
'dinner': False,
'neighborhoods': [
{
'id': 'mock_belltown_id',
'name': 'Belltown',
},
],
},
],
}
mock_responses.add(
responses.RequestsMock.POST,
mealpy.CITIES_URL,
json=response,
)
cities = mealpy.MealPal.get_cities()
city = [i for i in cities if i['name'] == 'San Francisco'][0]
assert city.items() >= {
'id': 'mock_id1',
'state': 'CA',
'name': 'San Francisco',
}.items()
@staticmethod
def test_get_cities_bad_response(mock_responses):
mock_responses.add(
responses.RequestsMock.POST,
mealpy.CITIES_URL,
status=400,
)
with pytest.raises(requests.exceptions.HTTPError):
mealpy.MealPal.get_cities()
class TestLogin:
@staticmethod
def test_login(mock_responses):
mock_responses.add(
responses.RequestsMock.POST,
mealpy.LOGIN_URL,
status=200,
json={
'id': 'GUID',
'email': 'email',
'status': 3,
'firstName': 'first_name',
'lastName': 'last_name',
'sessionToken': 'r:GUID',
'city': {
'id': 'GUID',
'name': 'San Francisco',
'city_code': 'SFO',
'countryCode': 'usa',
'__type': 'Pointer',
'className': 'City',
'objectId': 'GUID',
},
},
)
mealpal = mealpy.MealPal()
assert mealpal.login('username', 'password') == 200
@staticmethod
def test_login_fail(mock_responses):
mock_responses.add(
method=responses.RequestsMock.POST,
url=mealpy.LOGIN_URL,
status=404,
json={
'code': 101,
'error': 'An error occurred while blah blah, try agian.',
},
)
mealpal = mealpy.MealPal()
with pytest.raises(requests.HTTPError):
mealpal.login('username', 'password')
class TestSchedule:
@staticmethod
@pytest.fixture
def mock_city():
yield City('mock_city', 'mock_city_object_id')
@staticmethod
@pytest.fixture
def success_response():
"""A complete response example for MENU_URL endpoint."""
yield {
'city': {
'id': 'GUID',
'name': 'San Francisco',
'state': 'CA',
'time_zone_name': 'America/Los_Angeles',
},
'generated_at': '2019-04-01T00:00:00Z',
'schedules': [{
'id': 'GUID',
'priority': 9,
'is_featured': True,
'date': '20190401',
'meal': {
'id': 'GUID',
'name': 'Spam and Eggs',
'description': 'Soemthign sometlhing python',
'cuisine': 'asian',
'image': 'https://example.com/image.jpg',
'portion': 2,
'veg': False,
},
'restaurant': {
'id': 'GUID',
'name': 'RestaurantName',
'address': 'RestaurantAddress',
'state': 'CA',
'latitude': '111.111',
'longitude': '-111.111',
'neighborhood': {
'name': 'Financial District',
'id': 'GUID',
},
'city': {
'name': 'San Francisco',
'id': 'GUID',
'timezone_offset_hours': -7,
},
'open': '2019-04-01T00:00:00Z',
'close': '2019-04-01T00:00:00Z',
'mpn_open': '2019-04-01T00:00:00Z',
'mpn_close': '2019-04-01T00:00:00Z',
},
}],
}
@staticmethod
@pytest.fixture
def menu_url_response(mock_responses, success_response, mock_city):
mock_responses.add(
responses.RequestsMock.GET,
mealpy.MENU_URL.format(mock_city.objectId),
status=200,
json=success_response,
)
yield mock_responses
@staticmethod
@pytest.fixture
def mock_get_city(mock_responses, mock_city):
mock_responses.add(
method=responses.RequestsMock.POST,
url=mealpy.CITIES_URL,
json={
'result': [{
'id': 'mock_id1',
'objectId': mock_city.objectId,
'name': mock_city.name,
}],
},
)
yield
@staticmethod
@pytest.mark.usefixtures('mock_get_city', 'menu_url_response')
def test_get_schedule_by_restaurant_name(mock_city):
schedule = mealpy.MealPal.get_schedule_by_restaurant_name('RestaurantName', mock_city.name)
meal = schedule['meal']
restaurant = schedule['restaurant']
assert meal.items() >= {
'id': 'GUID',
'name': 'Spam and Eggs',
}.items()
assert restaurant.items() >= {
'id': 'GUID',
'name': 'RestaurantName',
'address': 'RestaurantAddress',
}.items()
@staticmethod
@pytest.mark.usefixtures('mock_get_city', 'menu_url_response')
@pytest.mark.xfail(
raises=StopIteration,
reason='#24 Invalid restaurant input not handled',
)
def test_get_schedule_by_restaurant_name_not_found(mock_city):
mealpy.MealPal.get_schedule_by_restaurant_name('NotFound', mock_city.name)
@staticmethod
@pytest.mark.usefixtures('mock_get_city', 'menu_url_response')
@pytest.mark.xfail(
raises=StopIteration,
reason='#24 Invalid meal name not handled',
)
def test_get_schedule_by_meal_name_not_found(mock_city):
mealpy.MealPal.get_schedule_by_meal_name('NotFound', mock_city.name)
@staticmethod
@pytest.mark.usefixtures('mock_get_city', 'menu_url_response')
def test_get_schedule_by_meal_name(mock_city):
schedule = mealpy.MealPal.get_schedule_by_meal_name('Spam and Eggs', mock_city.name)
meal = schedule['meal']
restaurant = schedule['restaurant']
assert meal.items() >= {
'id': 'GUID',
'name': 'Spam and Eggs',
}.items()
assert restaurant.items() >= {
'id': 'GUID',
'name': 'RestaurantName',
'address': 'RestaurantAddress',
}.items()
@staticmethod
@pytest.mark.usefixtures('mock_get_city')
def test_get_schedules_fail(mock_responses, mock_city):
mock_responses.add(
method=responses.RequestsMock.GET,
url=mealpy.MENU_URL.format(mock_city.objectId),
status=400,
)
with pytest.raises(requests.HTTPError):
mealpy.MealPal.get_schedules(mock_city.name)
class TestCurrentMeal:
@staticmethod
@pytest.fixture
def current_meal():
yield {
'id': 'GUID',
'createdAt': '2019-03-20T02:53:28.908Z',
'date': 'March 20, 2019',
'pickupTime': '12:30-12:45',
'pickupTimeIso': ['12:30', '12:45'],
'googleCalendarLink': (
'https://www.google.com/calendar/render?action=TEMPLATE&text=Pick Up Lunch from MealPal&'
'details=Pick up lunch from MealPal: MEALNAME from RESTAURANTNAME\nPickup instructions: BLAHBLAH&'
'location=ADDRESS, CITY, STATE&dates=20190320T193000Z/20190320T194500Z&sf=true&output=xml'
),
'mealpalNow': False,
'orderNumber': '1111',
'emojiWord': None,
'emojiCharacter': None,
'emojiUrl': None,
'meal': {
'id': 'GUID',
'image': 'https://example.com/image.jpg',
'description': 'spam, eggs, and bacon. Served on avocado toast. With no toast.',
'name': 'Spam Eggs',
},
'restaurant': {
'id': 'GUID',
'name': 'RESTURANTNAME',
'address': 'ADDRESS',
'city': {
'__type': 'Object',
'className': 'cities',
'createdAt': '2016-06-22T14:33:23.000Z',
'latitude': '111.111',
'longitude': '-111.111',
'name': 'San Francisco',
'city_code': 'SFO',
'objectId': 'GUID',
'state': 'CA',
'timezone': -7,
'updatedAt': '2019-03-18T16:08:22.577Z',
},
'latitude': '111.1111',
'longitude': '-111.1111',
'lunchOpen': '11:30am',
'lunchClose': '2:30pm',
'pickupInstructions': 'BLAH BLAH',
'state': 'CA',
'timezoneOffset': -7,
'neighborhood': {
'id': 'GUID',
'name': 'SoMa',
},
},
'schedule': {
'__type': 'Object',
'objectId': 'GUID',
'className': 'schedules',
'date': {
'__type': 'Date',
'iso': '2019-03-20T00:00:00.000Z',
},
},
}
@staticmethod
@pytest.fixture
def success_response_no_reservation():
yield {
'result': {
'status': 'OPEN',
'kitchenMode': 'classic',
'time': '19:59',
'reserveUntil': '2019-03-20T10:30:00-07:00',
'cancelUntil': '2019-03-20T15:00:00-07:00',
'kitchenTimes': {
'openTime': '5pm',
'openTimeMilitary': 1700,
'openHourMilitary': 17,
'openMinutesMilitary': 0,
'openHour': '5',
'openMinutes': '00',
'openPeriod': 'pm',
'closeTime': '10:30am',
'closeTimeMilitary': 1030,
'closeHourMilitary': 10,
'closeMinutesMilitary': 30,
'closeHour': '10',
'closeMinutes': '30',
'closePeriod': 'am',
'lateCancelHour': 15,
'lateCancelMinutes': 0,
},
'today': {
'__type': 'Date',
'iso': '2019-03-20T02:59:42.000Z',
},
},
}
@staticmethod
@pytest.fixture
def kitchen_url_response(mock_responses, success_response_no_reservation):
mock_responses.add(
responses.RequestsMock.POST,
mealpy.KITCHEN_URL,
status=200,
json=success_response_no_reservation,
)
yield mock_responses
@staticmethod
@pytest.fixture
def kitchen_url_response_with_reservation(mock_responses, success_response_no_reservation, current_meal):
success_response_no_reservation['reservation'] = current_meal
mock_responses.add(
responses.RequestsMock.POST,
mealpy.KITCHEN_URL,
status=200,
json=success_response_no_reservation,
)
yield mock_responses
@staticmethod
@pytest.mark.usefixtures('kitchen_url_response')
def test_get_current_meal_no_meal():
mealpal = mealpy.MealPal()
current_meal = mealpal.get_current_meal()
assert 'reservation' not in current_meal
@staticmethod
@pytest.mark.usefixtures('kitchen_url_response_with_reservation')
def test_get_current_meal():
mealpal = mealpy.MealPal()
current_meal = mealpal.get_current_meal()
assert current_meal['reservation'].keys() >= {
'id',
'pickupTime',
'orderNumber',
'meal',
'restaurant',
'schedule',
}
@staticmethod
@pytest.mark.xfail(raises=NotImplementedError)
def test_cancel_current_meal():
mealpal = mealpy.MealPal()
mealpal.cancel_current_meal()
class TestReserve:
@staticmethod
@pytest.fixture()
def reserve_response(mock_responses): # pragma: no cover
# Current unused
response = {
'result': {
'date': 'March 20, 2019',
'user_id': 'GUID',
'google_calendar_link': (
'https://www.google.com/calendar/render?'
'action=TEMPLATE&'
'text=Pick Up Lunch from MealPal&'
'details=Pick up lunch from MealPal: BLAH BLAH BLAH&'
'location=LOCATION&'
'dates=20190320T194500Z/20190320T200000Z&'
'sf=true&'
'output=xml'
),
'encoded_google_calendar_link': 'URI_ENCODED',
'schedule': {
'schedule_id': 'GUID',
'ordered_quantity': 1,
'late_canceled_quantity': 0,
'pickup_window_start': '2019-03-20T12:45:00-07:00',
'pickup_window_end': '2019-03-20T13:00:00-07:00',
'google_calendar_link': 'LOL_WHAT_THIS_IS_DUPLICATE',
'encoded_google_calendar_link': 'ENCODED_URI',
'order_number': '1111',
'mealpal_now': False,
'emoji_word': None,
'emoji_character': None,
'emoji_url': None,
'reserve_until': '2019-03-20T10:30:00-07:00',
'cancel_until': '2019-03-20T15:00:00-07:00',
'meal': {
'name': 'MEAL_NAME',
'image_url': 'https://example.com/image.jpg',
'ingredients': 'INGREDIENT_DESCRIPTION',
},
'restaurant': {
'lunch_open_at': '2019-03-20T11:30:00-07:00',
'lunch_close_at': '2019-03-20T14:30:00-07:00',
'name': 'RESTAURANT_NAME',
'address': 'ADDRESS',
'latitude': '111.111',
'longitude': '-111.111',
'pickup_strategy': 'qr_codes',
'pickup_strategy_set': 'online',
'pickup_instructions': 'INSTRUCTIONS',
'city_name': 'San Francisco',
'city_state': 'CA',
},
},
},
}
mock_responses.add(
responses.RequestsMock.POST,
mealpy.KITCHEN_URL,
status=200,
json=response,
)
yield mock_responses
@staticmethod
@pytest.fixture()
def reserve_response_failed(mock_responses): # pragma: no cover
# Current unused
response = {'error': 'ERROR_RESERVATION_LIMIT'}
mock_responses.add(
responses.RequestsMock.POST,
mealpy.KITCHEN_URL,
status=400,
json=response,
)
yield mock_responses
@staticmethod
def test_reserve_meal_by_meal_name():
mealpal = mealpy.MealPal()
schedule_id = 1
timing = 'mock_timing'
with mock.patch.object(
mealpy.MealPal,
'get_schedule_by_meal_name',
return_value={'id': schedule_id},
) as mock_get_schedule_by_meal, \
mock.patch.object(mealpal, 'session') as mock_requests:
mealpal.reserve_meal(
timing,
'mock_city',
meal_name='meal_name',
)
assert mock_get_schedule_by_meal.called
assert mock_requests.post.called_with(
mealpy.RESERVATION_URL,
{
'quantity': 1,
'schedule_id': schedule_id,
'pickup_time': timing,
'source': 'Web',
},
)
@staticmethod
def test_reserve_meal_by_restaurant_name():
mealpal = mealpy.MealPal()
schedule_id = 1
timing = 'mock_timing'
with mock.patch.object(
mealpy.MealPal,
'get_schedule_by_restaurant_name',
return_value={'id': schedule_id},
) as mock_get_schedule_by_restaurant, \
mock.patch.object(mealpal, 'session') as mock_requests:
mealpal.reserve_meal(
timing,
'mock_city',
restaurant_name='restaurant_name',
)
assert mock_get_schedule_by_restaurant.called
assert mock_requests.post.called_with(
mealpy.RESERVATION_URL,
{
'quantity': 1,
'schedule_id': schedule_id,
'pickup_time': timing,
'source': 'Web',
},
)
@staticmethod
def test_reserve_meal_missing_params():
"""Need to set restaurant_name or meal_name."""
mealpal = mealpy.MealPal()
with pytest.raises(AssertionError):
mealpal.reserve_meal(mock.sentinel.timing, mock.sentinel.city)
@staticmethod
@pytest.mark.xfail(raises=NotImplementedError)
def test_reserve_meal_cancel_meal():
"""Test that meal can be canceled before reserving.
This test is a little redundant atm. But it'll probably make more sense if cancellation is moved to an cli arg.
At least this gives test coverage.
"""
mealpal = mealpy.MealPal()
mealpal.reserve_meal(
'mock_timing',
'mock_city',
restaurant_name='restaurant_name',
cancel_current_meal=True,
)
| [
"[email protected]"
] | |
066dff68cd6fc3bdfb737f2e654f0e3701cfb805 | 9b568abb1d2ecb56b8f5f68c6291fb3dac46a53e | /squares.py | df70233e73e96c32742c08395b5ee043364afa1d | [] | no_license | lnc31/PythonX | e15da81f8bb0c7fd809a7ab51ec652909be0c5d4 | a327748d24272dce80de5de00e5d7ef8421ab0a6 | refs/heads/master | 2023-04-15T04:34:39.234851 | 2021-04-24T18:33:34 | 2021-04-24T18:33:34 | 361,239,262 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 94 | py | from Functions import square
for i in range(10):
print(f"The square of {i} is {square(i)}") | [
"[email protected]"
] | |
8ac8bab9bee70c5b61b4c9bf716b822881de78e0 | 19595705c8dfe4d21d672ba344a4bbfd2dd9b56d | /fantasyStocks/fantasyStocks/settings.py | 2ecd914356bad70f80806593acc3d986f7d38055 | [
"Apache-2.0"
] | permissive | Newzald/FantasyStocks | f80ea70bc4b04ee5bf695d67a7681bf5393238f4 | 65671bec2d65da0bade27d19e4bbd29da3bbddb9 | refs/heads/master | 2021-01-15T09:02:56.183594 | 2016-06-20T01:17:02 | 2016-06-20T01:17:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,429 | py | """
Django settings for fantasyStocks project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from django.core.urlresolvers import reverse_lazy
import dj_database_url
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
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/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# One of these days, I should get a way to keep this safer while still having
# in source control. Someday...
SECRET_KEY = '*imh(^2l3_!uoxr$z#((vovmj4xmqp*@p2&phrlqt7xyau*aqw'
# 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',
'stocks',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'fantasyStocks.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',
],
},
},
]
LOGIN_URL = reverse_lazy("home")
WSGI_APPLICATION = 'fantasyStocks.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
if os.environ.get("DATABASE_URL", None):
DATABASES["default"] = dj_database_url.config()
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
MEDIA_ROOT = BASE_DIR + "/res/"
MEDIA_URL = "/images/"
FIXTURE_DIRS = [os.path.join(BASE_DIR, "/stocks/fixtures/")]
EMAIL_HOST = "aspmx.l.google.com"
EMAIL_PORT = 25
| [
"[email protected]"
] | |
52e7d93a3be694d33c6f756375b712af5059afe2 | 91053fd1765a1ea747f7b01537badf21c574c577 | /src/baseline/features.py | f58db342f3c834907283a1449087eba3927d5ca6 | [] | no_license | yaya-sy/mwe-extraction | 2812b0531ef21ccfa8f54db0be9472bf508b173d | 30a259a9a6cefd22db6fb46b9a76115d949a5631 | refs/heads/main | 2023-06-07T00:04:35.907068 | 2021-06-24T20:47:13 | 2021-06-24T20:47:13 | 372,106,500 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,524 | py | """Ce module module contient des fonction d'extraction de caractéristiques pour la baseline
"""
from itertools import chain
def features(phrase, tags, span_w, span_s, position) :
"""
Fonction qui extrait les features en créant un dictionnaire : pour chaque mot (par exemeple 'désinfection'), on regarde
- pref1 (son préfixe de longueur 1) : 'd'
- pref2 (son préfixe de longueur 2) : 'dé'
- etc
- suff1 (son suffixe de longueur 1) : 'n'
- suff2 (son suffixe de longueur 2) : 'on'
- suff3 (son suffixe de longueur 3) : 'ion'
- etc.
"""
beg, end = list(zip(*((f"@BEG{i}@", f"@END{i}@") for i in range(span_s))))
beg, end = list(beg), list(end)
span_s += 1
l = len(phrase)
p = beg + phrase + end
t = beg + tags + beg
features = []
if p[position] not in beg + end : #and mot in mc and mot not in mots :
for spann in chain.from_iterable([(-i, i) for i in range(1, span_s)]) :
features.append("w_" + str(spann) + " = " + p[position + spann])
if spann < 0 : features.append("t_" + str(spann) + " = " + t[position + spann])
for span in chain.from_iterable([(-i, i) for i in range(1, span_w + 1)]):
if span < 0 :
if len(p[position]) >= abs(span) :
features.append("pref" + str(abs(span)) + "=" + p[position][:-span])
else :
features.append("pref" + str(abs(span)) + "=" + "HayDara")
else :
if len(p[position]) >= abs(span) :
features.append("suff" + str(span) + "=" + p[position][-span:])
else :
features.append("suff" + str(abs(span)) + "=HayDara")
features.append("maj" + "=" + str(p[position][0].isupper()))
features.append("mot" + "=" + p[position])
features.append("Maj" + "=" + str(p[position].isupper()))
if bool(features) :
return features, t[position]
def get_features(corpus) :
"""
fonction qui parcourt les phrase pour extraire les caractéristiques
Returns
-------
- tuple :
les caractéristiques et les classes
"""
fts = []
golds = []
for phrase, labels in corpus :
if len(phrase) <= 1:continue
for i in range(len(phrase)) :
f = features(list(phrase), list(labels), 4, 1, i)
if f != None :
f,g = f
fts.append(f)
golds.append(g)
return fts, golds
| [
"[email protected]"
] | |
f5819bc1758f11c02fccbff2b04871087efe5580 | e70ae13dfd1db072941b24b51a452de9b42e838e | /xorKeras/test.py | b67efdb96f0b149222ce0c19bd05941008201d9f | [] | no_license | mohanmanju/tensorFlow | 136670c28e1afe95e35767f171e24c5172bcfbd9 | 38db20420a2ff40875ff532cdbc9c5a7c77a6e06 | refs/heads/master | 2021-01-02T08:35:41.483827 | 2018-07-30T18:26:59 | 2018-07-30T18:26:59 | 99,025,346 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 654 | py | from keras.models import Sequential
from keras.layers import Dense
from keras.models import model_from_json
import numpy as np
import os
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
loaded_model.load_weights("model.h5")
loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
dataTest = np.random.binomial(1,0.5,(1000,2))
result = np.transpose(dataTest)
labelsTest = result[0]^result[1]
score = loaded_model.evaluate(dataTest, labelsTest, verbose=0)
print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))
| [
"[email protected]"
] | |
d5f9b10607579fcf1a3df619faa2d5218ff61628 | ee4c4c2cc6c663d4233d8145b01ae9eb4fdeb6c0 | /tools/r3det_kl/train.py | 68a4bf224bda39eb73ffa6aa70f6eb0d96e4a9d9 | [
"Apache-2.0"
] | permissive | yangcyz/RotationDetection | c86f40f0be1142c30671d4fed91446aa01ee31c1 | 82706f4c4297c39a6824b9b53a55226998fcd2b2 | refs/heads/main | 2023-09-01T23:25:31.956004 | 2021-11-23T13:57:31 | 2021-11-23T13:57:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,816 | py | # -*- coding:utf-8 -*-
# Author: Xue Yang <[email protected]>, <[email protected]>
# License: Apache-2.0 license
# Copyright (c) SJTU. ALL Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
sys.path.append("../../")
from tools.train_base import Train
from configs import cfgs
from alpharotate.libs.models.detectors.r3det_kl import build_whole_network
from alpharotate.libs.utils.coordinate_convert import backward_convert, get_horizen_minAreaRectangle
from alpharotate.utils.pretrain_zoo import PretrainModelZoo
os.environ["CUDA_VISIBLE_DEVICES"] = cfgs.GPU_GROUP
class TrainR3DetKL(Train):
def get_gtboxes_and_label(self, gtboxes_and_label_h, gtboxes_and_label_r, num_objects):
return gtboxes_and_label_h[:int(num_objects), :].astype(np.float32), \
gtboxes_and_label_r[:int(num_objects), :].astype(np.float32)
def main(self):
with tf.Graph().as_default() as graph, tf.device('/cpu:0'):
num_gpu = len(cfgs.GPU_GROUP.strip().split(','))
global_step = slim.get_or_create_global_step()
lr = self.warmup_lr(cfgs.LR, global_step, cfgs.WARM_SETP, num_gpu)
tf.summary.scalar('lr', lr)
optimizer = tf.train.MomentumOptimizer(lr, momentum=cfgs.MOMENTUM)
r3det_kl = build_whole_network.DetectionNetworkR3DetKL(cfgs=self.cfgs,
is_training=True)
with tf.name_scope('get_batch'):
if cfgs.IMAGE_PYRAMID:
shortside_len_list = tf.constant(cfgs.IMG_SHORT_SIDE_LEN)
shortside_len = tf.random_shuffle(shortside_len_list)[0]
else:
shortside_len = cfgs.IMG_SHORT_SIDE_LEN
img_name_batch, img_batch, gtboxes_and_label_batch, num_objects_batch, img_h_batch, img_w_batch = \
self.reader.next_batch(dataset_name=cfgs.DATASET_NAME,
batch_size=cfgs.BATCH_SIZE * num_gpu,
shortside_len=shortside_len,
is_training=True)
# data processing
inputs_list = []
for i in range(num_gpu):
img = tf.expand_dims(img_batch[i], axis=0)
pretrain_zoo = PretrainModelZoo()
if self.cfgs.NET_NAME in pretrain_zoo.pth_zoo or self.cfgs.NET_NAME in pretrain_zoo.mxnet_zoo:
img = img / tf.constant([cfgs.PIXEL_STD])
gtboxes_and_label_r = tf.py_func(backward_convert,
inp=[gtboxes_and_label_batch[i]],
Tout=tf.float32)
gtboxes_and_label_r = tf.reshape(gtboxes_and_label_r, [-1, 6])
gtboxes_and_label_h = get_horizen_minAreaRectangle(gtboxes_and_label_batch[i])
gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [-1, 5])
num_objects = num_objects_batch[i]
num_objects = tf.cast(tf.reshape(num_objects, [-1, ]), tf.float32)
img_h = img_h_batch[i]
img_w = img_w_batch[i]
inputs_list.append([img, gtboxes_and_label_h, gtboxes_and_label_r, num_objects, img_h, img_w])
tower_grads = []
biases_regularizer = tf.no_regularizer
weights_regularizer = tf.contrib.layers.l2_regularizer(cfgs.WEIGHT_DECAY)
with tf.variable_scope(tf.get_variable_scope()):
for i in range(num_gpu):
with tf.device('/gpu:%d' % i):
with tf.name_scope('tower_%d' % i):
with slim.arg_scope(
[slim.model_variable, slim.variable],
device='/device:CPU:0'):
with slim.arg_scope([slim.conv2d, slim.conv2d_in_plane,
slim.conv2d_transpose, slim.separable_conv2d,
slim.fully_connected],
weights_regularizer=weights_regularizer,
biases_regularizer=biases_regularizer,
biases_initializer=tf.constant_initializer(0.0)):
gtboxes_and_label_h, gtboxes_and_label_r = tf.py_func(self.get_gtboxes_and_label,
inp=[inputs_list[i][1],
inputs_list[i][2],
inputs_list[i][3]],
Tout=[tf.float32, tf.float32])
gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [-1, 5])
gtboxes_and_label_r = tf.reshape(gtboxes_and_label_r, [-1, 6])
img = inputs_list[i][0]
img_shape = inputs_list[i][-2:]
img = tf.image.crop_to_bounding_box(image=img,
offset_height=0,
offset_width=0,
target_height=tf.cast(img_shape[0], tf.int32),
target_width=tf.cast(img_shape[1], tf.int32))
outputs = r3det_kl.build_whole_detection_network(input_img_batch=img,
gtboxes_batch_h=gtboxes_and_label_h,
gtboxes_batch_r=gtboxes_and_label_r,
gpu_id=i)
gtboxes_in_img_h = self.drawer.draw_boxes_with_categories(img_batch=img,
boxes=gtboxes_and_label_h[
:, :-1],
labels=gtboxes_and_label_h[
:, -1],
method=0)
gtboxes_in_img_r = self.drawer.draw_boxes_with_categories(img_batch=img,
boxes=gtboxes_and_label_r[
:, :-1],
labels=gtboxes_and_label_r[
:, -1],
method=1)
tf.summary.image('Compare/gtboxes_h_gpu:%d' % i, gtboxes_in_img_h)
tf.summary.image('Compare/gtboxes_r_gpu:%d' % i, gtboxes_in_img_r)
if cfgs.ADD_BOX_IN_TENSORBOARD:
detections_in_img = self.drawer.draw_boxes_with_categories_and_scores(
img_batch=img,
boxes=outputs[0],
scores=outputs[1],
labels=outputs[2],
method=1)
tf.summary.image('Compare/final_detection_gpu:%d' % i, detections_in_img)
loss_dict = outputs[-1]
total_loss_dict, total_losses = self.loss_dict(loss_dict, num_gpu)
if i == num_gpu - 1:
regularization_losses = tf.get_collection(
tf.GraphKeys.REGULARIZATION_LOSSES)
# weight_decay_loss = tf.add_n(slim.losses.get_regularization_losses())
total_losses = total_losses + tf.add_n(regularization_losses)
tf.get_variable_scope().reuse_variables()
grads = optimizer.compute_gradients(total_losses)
if cfgs.GRADIENT_CLIPPING_BY_NORM is not None:
grads = slim.learning.clip_gradient_norms(grads, cfgs.GRADIENT_CLIPPING_BY_NORM)
tower_grads.append(grads)
self.log_printer(r3det_kl, optimizer, global_step, tower_grads, total_loss_dict, num_gpu, graph)
if __name__ == '__main__':
trainer = TrainR3DetKL(cfgs)
trainer.main() | [
"[email protected]"
] | |
f54baea6e40dbc71d63547b07f97abfce23a5921 | 5a61cd84b3ef2d154258b72c6594c61779d02e24 | /robeep/core/exceptions.py | cd696fba766a82c6fb691d7141f4839f76ae1e4e | [
"MIT"
] | permissive | k-nii0211/rbp_agent | c925a6c6815e9dbee349858c7145f3ea0cba916a | 53724797ee7b579fc98d63809b9551867929476e | refs/heads/master | 2021-01-10T09:32:54.873043 | 2016-04-01T09:09:15 | 2016-04-01T09:09:15 | 55,218,803 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 96 | py | class ConfigurationError(Exception):
pass
class DiscardDataException(Exception):
pass
| [
"[email protected]"
] | |
14334a24ea2719d723061d0662ccc472d18deae4 | df350a0d14afdc30b38194104f5e3e3d927ec95f | /origin/main_03_visualize_and_generate_video.py | 022ee365c6aecc2439d5c8742e34c6802f4a4b2d | [] | no_license | sugartom/fromXiaochen | 80945e97fe36aaba399ad6d87124933572212999 | 16aa4052406b1ead135cfbb42b26981798ee57a0 | refs/heads/master | 2020-03-19T22:54:56.356696 | 2018-08-20T05:28:49 | 2018-08-20T05:28:49 | 136,986,052 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,936 | py | import numpy as np
import os
import json
import cv2
import argparse
from time import time
VIDEO_OUT_FOLDER = './output_videos/'
TUBE_COLORS = np.random.rand(300,3) * 255
TUBE_COLORS = TUBE_COLORS.astype(int)
with open('label_conversion.json') as fp:
LABEL_CONV = json.load(fp)
# "training2real": {"0": [15, "answer_phone"], ...
# "real2training": {"15": [0, "answer_phone"], ...
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input_video', type=str, required=True)
parser.add_argument('-v', '--visualize_video', type=int, required=False, default=1)
parser.add_argument('-s', '--save_video', type=int, required=False, default=1)
args = parser.parse_args()
video_path = args.input_video
visualize_flag = bool(args.visualize_video)
save_video = bool(args.save_video)
visualize_generate_result(video_path, visualize_flag, save_video)
def visualize_generate_result(video_path, visualize_flag, save_video):
if save_video: print('\nGenerating output video!\n')
video_name = video_path.split('/')[-1].split('.')[0]
print('Visualization: %s' % ('yes' if visualize_flag else 'no'))
print('Saving output video: %s' % ('yes' if save_video else 'no'))
tubes_json = './jsons/%s_tubes.json' % video_name
actions_json = './jsons/%s_actions.json' % video_name
if os.path.exists(tubes_json):
with open(tubes_json) as fp:
tubelet_infos = json.load(fp)
else:
print('Error: Tubes json not found! Run extract tubes first')
raise IOError
if os.path.exists(actions_json):
with open(actions_json) as fp:
actions_info = json.load(fp)
else:
print('Error: Actions json not found! Run detect actions first')
raise IOError
tubelet_ids = actions_info.keys()
# combine annotations
tubelets_w_actions = []
for tubelet_info in tubelet_infos:
tubelet_id = tubelet_info['tube_id']
tubelet_key = 'person_%.3i' % tubelet_id
action_probs = actions_info[tubelet_key]
tubelet_length = len(tubelet_info['avg_box_list'])
action_length = len(action_probs)
slope = action_length / float(tubelet_length)
# if tubelet_id == 3: import pdb;pdb.set_trace()
# TODO add some filtering/smoothing here
actions_for_each_frame = []
for ii in range(tubelet_length):
cur_action = action_probs[int(ii * slope)]
actions_for_each_frame.append(cur_action)
tubelet_info['frame_actions'] = actions_for_each_frame
tubelet_info['tube_key'] = tubelet_key
vcap = cv2.VideoCapture(video_path)
## Video Properties
vidfps = vcap.get(cv2.CAP_PROP_FPS)
# sometimes opencv fails at getting the fps
if vidfps == 0: vidfps = 20
W = vcap.get(cv2.CAP_PROP_FRAME_WIDTH) # float
H = vcap.get(cv2.CAP_PROP_FRAME_HEIGHT) # float
H, W = int(H), int(W)
if save_video:
out_path = VIDEO_OUT_FOLDER + '%s_results.avi' % video_name
fourcc = cv2.VideoWriter_fourcc(*'XVID')
# fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter(out_path,fourcc, vidfps, (5*W//4,H))
frame_no = 0
cur_time = time()
while vcap.isOpened():
ret, frame = vcap.read()
if not ret: break
trackers = []
lost_trackers = []
for tubelet_info in tubelet_infos:
start_frame = tubelet_info['starting_frame']
end_frame = tubelet_info['lost_since_frame']
if frame_no >= start_frame and frame_no < end_frame:
relative_frame = frame_no - start_frame
current_box = tubelet_info['avg_box_list'][relative_frame]
current_detections = [tubelet_info['detections'][0]]
tubelet_id = tubelet_info['tube_id']
tube_key = tubelet_info['tube_key']
current_actions = tubelet_info['frame_actions'][relative_frame]
new_tracker = {'box': current_box,
'detections': current_detections,
'tube_id': tubelet_id,
'tube_key': tube_key,
'action_probs': current_actions}
trackers.append(new_tracker)
elif frame_no > start_frame and frame_no <= end_frame + 30:
# relative_frame = frame_no - start_frame
current_box = tubelet_info['avg_box_list'][-1]
current_detections = [tubelet_info['detections'][0]]
tubelet_id = tubelet_info['tube_id']
current_actions = tubelet_info['frame_actions'][-1]
new_tracker = {'box': current_box,
'detections': current_detections,
'tube_id': tubelet_id,
'tube_key': tube_key,
'action_probs': current_actions}
lost_trackers.append(new_tracker)
else:
continue
img_with_objects = visualize(frame, trackers, lost_trackers, visualize_flag)
sidebar = add_action_sidebars(frame, trackers, H, W)
img_with_actions = np.concatenate([sidebar, img_with_objects], axis=1)
if visualize_flag:
cv2.imshow('Results', img_with_actions)
k = cv2.waitKey(0)
if k == ord('q'):
break
if save_video:
out.write(img_with_actions)
frame_no += 1
print('To result: %0.2f' % ((time() - cur_time)/frame_no))
vcap.release()
if save_video:
out.release()
print('Video %s is saved!' % out_path)
def visualize(frame, trackers, lost_trackers, visualize_flag):
imgcv = np.copy(frame)
colors = np.load('object_detector/colors.npy')
for tracker in trackers:
box = tracker['box']
detection_info = tracker['detections'][-1]
top, left, bottom, right = box
# conf = detection_info['score']
label = detection_info['class_str']
label_indx = min(detection_info['class_no'] - 1, 79)
tube_id = tracker['tube_id']
# message = '%.3i_%s: %.2f' % (tube_id, label , conf)
message = '%.3i_%s' % (tube_id, label)
if visualize_flag: print(message)
thick = 3
label_indx = int(label_indx)
# color = colors[label_indx]
color = TUBE_COLORS[tube_id]
cv2.rectangle(imgcv, (left,top), (right,bottom), color, thick)
font_size = max(0.5,(right - left)/50.0/float(len(message)))
# font_size = (right - left)/float(len(message))/10.0
cv2.rectangle(imgcv, (left, top-int(font_size*40)), (right,top), color, -1)
cv2.putText(imgcv, message, (left, top-12), 0, font_size, (255,255,255)-color, thick//2)
for lost_tracker in lost_trackers:
box = lost_tracker['box']
top, left, bottom, right = box
cv2.rectangle(imgcv, (left,top), (right,bottom), (0,0,255), 1)
if visualize_flag:print('\n\n')
return imgcv
def add_action_sidebars(frame, trackers, H, W):
black_bar_left = np.zeros([H,W//4,3], np.uint8)
# black_bar_right = np.zeros([H,W//4,C], np.uint8)
if trackers:
for ii, tracker in enumerate(trackers):
box = tracker['box']
top, left, bottom, right = box
bb_label = tracker['tube_key']
bb_frame = extract_box_frame(frame, box)
bb_frame = np.copy(bb_frame)
bbH, bbW = H//8, int(bb_frame.shape[1] / float(bb_frame.shape[0]) * H // 8)
bb_frame = cv2.resize(bb_frame, (bbW, bbH))
current_action_probs = tracker['action_probs']
bb_acts = get_act_strs(current_action_probs, 5)
# bbH, bbW, bbC = bb_frame.shape
starting_index = H//24 + ii * H//8 + ii * 10
if starting_index + bbH < H:
black_bar_left[starting_index: starting_index+bbH, 20:20+bbW, :] = bb_frame
cur_HH = starting_index + 10
# label
font_size = 0.5
tube_color = TUBE_COLORS[tracker['tube_id']]
cv2.putText(black_bar_left, bb_label, (40+bbW, cur_HH), 0, font_size, tube_color, 1)
# Actions
for act in bb_acts:
cur_HH += 13
cv2.putText(black_bar_left, act, (40+bbW, cur_HH+13), 0, font_size, (255,255,255), 1)
return black_bar_left
# try:
# black_bar_left[cur_H:cur_H+bbH, 20:20+bbW, :] = bb_frame
# # label
# cv2.putText(black_bar, bb_label, (40+bbW, cur_H + 20), 0, font_size, (255,255,255), thick//2)
# # Actions
# cur_HH = cur_H + 30
# for act in bb_acts:
# cur_HH += 13
# cv2.putText(black_bar, act, (40+bbW, cur_HH), 0, font_size, (255,255,255), thick//2)
# except ValueError:
# break
def get_act_strs(action_probs, topk):
class_probs = np.array(action_probs)
class_order = np.argsort(class_probs) [::-1]
probs_order = class_probs[class_order]
class_strs = [LABEL_CONV['training2real'][str(class_no)][1] for class_no in class_order]
printable = [ '%s : %.3f' % (class_str, prob) for class_str, prob in zip(class_strs,probs_order)]
return printable[0:topk]
# print(printable)
# no_print = 5
# pixel_distance = 25
# black_bar = np.zeros([(no_print+2) * pixel_distance, T * W,C], np.uint8)
# for ii in range(no_print):
# cur_printable = printable[ii]
# cv2.putText(black_bar, cur_printable, (T * W // 2, (ii+2) * pixel_distance), 0, 1, (255,255,255), 1)
def extract_box_frame(frame, box):
# extracts the box from the full frame
# takes into account if the box coords are outside of frame boundaries and fills with zeros
H, W, C = frame. shape
top, left, bottom, right = box
# initialize with zeros so out of boundary areas are black
extracted_box = np.zeros((bottom - top, right - left, 3), np.uint8)
# sometimes tracker get confused and gives a box completely outside img boundaries
if left >= W or top >= H:
# then just return a black frame
print('Tracker box completely out of range')
return extracted_box
if left >= 0: # bounding box coords are within frame boundary
frame_left = left
ebox_left = 0
else: # bounding box coords are outside frame boundary
frame_left = 0
ebox_left = 0 - left
if top >= 0: # bounding box coords are within frame boundary
frame_top = top
ebox_top = 0
else: # bounding box coords are outside frame boundary
frame_top = 0
ebox_top = 0 - top
if right <= W: # bounding box coords are within frame boundary
frame_right = right
ebox_right = extracted_box.shape[1]
else: # bounding box coords are outside frame boundary
frame_right = W
ebox_right = extracted_box.shape[1] + (W - right)
if bottom <= H: # bounding box coords are within frame boundary
frame_bottom = bottom
ebox_bottom = extracted_box.shape[0]
else: # bounding box coords are outside frame boundary
frame_bottom = H
ebox_bottom = extracted_box.shape[0] + (H - bottom)
extracted_box[ebox_top:ebox_bottom, ebox_left:ebox_right, :] = \
frame[frame_top:frame_bottom, frame_left:frame_right, :]
# try:
# extracted_box[ebox_top:ebox_bottom, ebox_left:ebox_right, :] = \
# frame[frame_top:frame_bottom, frame_left:frame_right, :]
# except ValueError:
# import pdb;pdb.set_trace()
return extracted_box
if __name__ == '__main__':
main() | [
"[email protected]"
] | |
f4f44e30aaa47a84790961c15312ca28b5d5b394 | 8a5ab3d33e3b653c4c64305d81a85f6a4582d7ac | /PySide/QtGui/QStringListModel.py | 73f8b4abdbcfac2c25221147365010e9ac073514 | [
"Apache-2.0"
] | permissive | sonictk/python-skeletons | be09526bf490856bb644fed6bf4e801194089f0d | 49bc3fa51aacbc2c7f0c7ab86dfb61eefe02781d | refs/heads/master | 2020-04-06T04:38:01.918589 | 2016-06-09T20:37:43 | 2016-06-09T20:37:43 | 56,334,503 | 0 | 0 | null | 2016-04-15T16:30:42 | 2016-04-15T16:30:42 | null | UTF-8 | Python | false | false | 1,377 | py | # encoding: utf-8
# module PySide.QtGui
# from /corp.blizzard.net/BFD/Deploy/Packages/Published/ThirdParty/Qt4.8.4/2015-05-15.163857/prebuilt/linux_x64_gcc41_python2.7_ucs4/PySide/QtGui.so
# by generator 1.138
# no doc
# imports
import PySide.QtCore as __PySide_QtCore
class QStringListModel(__PySide_QtCore.QAbstractListModel):
# no doc
def data(self, *args, **kwargs): # real signature unknown
pass
def flags(self, *args, **kwargs): # real signature unknown
pass
def insertRows(self, *args, **kwargs): # real signature unknown
pass
def removeRows(self, *args, **kwargs): # real signature unknown
pass
def rowCount(self, *args, **kwargs): # real signature unknown
pass
def setData(self, *args, **kwargs): # real signature unknown
pass
def setStringList(self, *args, **kwargs): # real signature unknown
pass
def sort(self, *args, **kwargs): # real signature unknown
pass
def stringList(self, *args, **kwargs): # real signature unknown
pass
def supportedDropActions(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *more): # real signature unknown; restored from __doc__
""" x.__init__(...) initializes x; see help(type(x)) for signature """
pass
staticMetaObject = None
__new__ = None
| [
"[email protected]"
] | |
f6f7f79e264f3dc7c08372cc1a93769028e1ca8a | ea515ab67b832dad3a9b69bef723bd9d918395e7 | /03_Implementacao/DataBase/true_or_false_question_frequent_nums_rotate_and_roman_nums/question/version_2/program2.py | 782a9221cbec6629fd468a1175446f7f77203c96 | [] | no_license | projeto-exercicios/Exercicios-Python-de-correccao-automatica | b52be3211e75d97cb55b6cdccdaa1d9f9d84f65b | a7c80ea2bec33296a3c2fbe4901ca509df4b1be6 | refs/heads/master | 2022-12-13T15:53:59.283232 | 2020-09-20T21:25:57 | 2020-09-20T21:25:57 | 295,470,320 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 234 | py | from random import randint
from random import seed
seed(1486166)
def int_to_roman(num):
def most_frequent(List):
def least_frequent(List):
def rotate_list(nums, h):
e = []
for j in range(19222):
e.append(randint(30, 570))
| [
"[email protected]"
] | |
ea4d718083ea5fed390d5f996879d6489332aded | 6a965a7e9a3691c77c1e0e9980de8d17baa8e3d2 | /todo/migrations/0001_initial.py | 91e40c017b8a92b86699fe3f68a207eb3ba91dff | [] | no_license | laurence100795/Django-First-Look | 10fd40b2491b09a72e07ccc8a20dcd63f01458f0 | 80c1293e3dc1ce87438bcc894ef3d611c2aa177f | refs/heads/master | 2023-08-04T01:40:23.179937 | 2020-06-20T16:47:01 | 2020-06-20T16:47:01 | 270,749,532 | 0 | 0 | null | 2021-09-22T19:11:29 | 2020-06-08T16:53:53 | HTML | UTF-8 | Python | false | false | 545 | py | # Generated by Django 3.0.7 on 2020-06-09 17:04
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Item',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('done', models.BooleanField(default=False)),
],
),
]
| [
"[email protected]"
] | |
97cf1fadf12602012e1aa3ec11e2b6f0aeff22ae | 72dc7d124cdac8f2dcab3f72e95e9a646154a6a0 | /scripts/create_database_tables.py | a1e12ba385835734338ff86ff143500afb84177c | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | m-ober/byceps | e6569802ee76e8d81b892f1f547881010359e416 | 4d0d43446f3f86a7888ed55395bc2aba58eb52d5 | refs/heads/master | 2020-11-30T23:31:33.944870 | 2020-02-12T23:53:55 | 2020-02-12T23:56:04 | 40,315,983 | 0 | 0 | null | 2015-08-06T16:41:36 | 2015-08-06T16:41:36 | null | UTF-8 | Python | false | false | 679 | py | #!/usr/bin/env python
"""Create the initial database structure.
Existing tables will be ignored, and those not existing will be created.
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.database import db
from byceps.util.system import get_config_filename_from_env_or_exit
from _util import app_context
@click.command()
def execute():
click.echo('Creating database tables ... ', nl=False)
db.create_all()
click.secho('done.', fg='green')
if __name__ == '__main__':
config_filename = get_config_filename_from_env_or_exit()
with app_context(config_filename):
execute()
| [
"[email protected]"
] | |
ce69df129364894f433ebc76cdfc03d2a08f13a5 | 7029dcf95ef133431e376a121b720b810d2b7e39 | /backend/mobile_app_dev_1693/settings.py | ab679299c67e25c38465c3a376854417ed2e3e39 | [] | no_license | crowdbotics-apps/mobile-app-dev-1693 | 880a3a9fe3466578573743b208237a25b0ae79e5 | 0a84178ba92f857525857dcebcecc79d9c126695 | refs/heads/master | 2022-04-04T20:30:14.633621 | 2020-02-21T07:36:37 | 2020-02-21T07:36:37 | 241,854,741 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,741 | py | """
Django settings for mobile_app_dev_1693 project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
import environ
env = environ.Env()
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool("DEBUG", default=False)
# 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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env.str("SECRET_KEY")
ALLOWED_HOSTS = env.list("HOST", default=["*"])
SITE_ID = 1
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = env.bool("SECURE_REDIRECT", default=False)
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django.contrib.sites",
]
LOCAL_APPS = [
"home",
"users.apps.UsersConfig",
]
THIRD_PARTY_APPS = [
"rest_framework",
"rest_framework.authtoken",
"rest_auth",
"rest_auth.registration",
"bootstrap4",
"allauth",
"allauth.account",
"allauth.socialaccount",
"allauth.socialaccount.providers.google",
"django_extensions",
"drf_yasg",
# start fcm_django push notifications
"fcm_django",
# end fcm_django push notifications
]
INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS
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 = "mobile_app_dev_1693.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 = "mobile_app_dev_1693.wsgi.application"
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
}
}
if env.str("DATABASE_URL", default=None):
DATABASES = {"default": env.db()}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.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/2.2/howto/static-files/
STATIC_URL = "/static/"
MIDDLEWARE += ["whitenoise.middleware.WhiteNoiseMiddleware"]
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
# allauth / users
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
ACCOUNT_UNIQUE_EMAIL = True
LOGIN_REDIRECT_URL = "users:redirect"
ACCOUNT_ADAPTER = "users.adapters.AccountAdapter"
SOCIALACCOUNT_ADAPTER = "users.adapters.SocialAccountAdapter"
ACCOUNT_ALLOW_REGISTRATION = env.bool("ACCOUNT_ALLOW_REGISTRATION", True)
SOCIALACCOUNT_ALLOW_REGISTRATION = env.bool("SOCIALACCOUNT_ALLOW_REGISTRATION", True)
REST_AUTH_SERIALIZERS = {
# Replace password reset serializer to fix 500 error
"PASSWORD_RESET_SERIALIZER": "home.api.v1.serializers.PasswordSerializer",
}
REST_AUTH_REGISTER_SERIALIZERS = {
# Use custom serializer that has no username and matches web signup
"REGISTER_SERIALIZER": "home.api.v1.serializers.SignupSerializer",
}
# Custom user model
AUTH_USER_MODEL = "users.User"
EMAIL_HOST = env.str("EMAIL_HOST", "smtp.sendgrid.net")
EMAIL_HOST_USER = env.str("SENDGRID_USERNAME", "")
EMAIL_HOST_PASSWORD = env.str("SENDGRID_PASSWORD", "")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# start fcm_django push notifications
FCM_DJANGO_SETTINGS = {"FCM_SERVER_KEY": env.str("FCM_SERVER_KEY", "")}
# end fcm_django push notifications
if DEBUG:
# output email to console instead of sending
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
| [
"[email protected]"
] | |
fc574674773d487563c29aaf36bef49acd284013 | 65b2c16b3e04cf9f0c5f341718a5c8ab9e74c268 | /blog_cookiecutter/blog-cookiecutter/docs/conf.py | 8cf6fe0a60ceb83d32f85ebf2924cffd1deddef7 | [
"MIT",
"BSD-3-Clause"
] | permissive | Jaleleddine/blog-projects | bbe5407daa6cf4c9796781db5a0936c78d406a59 | 5f71ec9d5558f354856373adac12406ee345bb1c | refs/heads/master | 2022-12-14T20:13:09.323100 | 2020-06-08T06:28:06 | 2020-06-08T06:28:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,914 | py | # -*- coding: utf-8 -*-
#
# blog_cookiecutter documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
import sys
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'blog_cookiecutter'
copyright = u"2016, Krzysztof Żuraw"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'blog-cookiecutterdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index',
'blog-cookiecutter.tex',
u'blog_cookiecutter Documentation',
u"Krzysztof Żuraw", 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'blog-cookiecutter', u'blog_cookiecutter Documentation',
[u"Krzysztof Żuraw"], 1)
]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'blog-cookiecutter', u'blog_cookiecutter Documentation',
u"Krzysztof Żuraw", 'blog_cookiecutter',
'This is example of cookiecutter django usage', 'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
| [
"[email protected]"
] | |
87be869d242f2572f7ccf70c6c233552612f5b9b | 957387796af9ea12af26bc17dc2c0ce75bebffd0 | /dj_medical_reminder/asgi.py | a8f5bce4f5a853ba847d078b8c7b96ad0e08737f | [] | no_license | iamgaddiel/typmeAPI | e152871b3b72f268518f5c5aee109943dc5eb637 | bff3aa10c505dca7b1265c2a693dcb6334aa9993 | refs/heads/main | 2023-02-19T17:28:57.730511 | 2021-01-22T00:30:49 | 2021-01-22T00:30:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 415 | py | """
ASGI config for dj_medical_reminder project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dj_medical_reminder.settings')
application = get_asgi_application()
| [
"[email protected]"
] | |
fb9ddbb0e53ee6a524821b91c6f3d4bad3b8bb85 | 5da3c9ff915dd4ee53d0db57babbe2bcd832bfd0 | /pago/models.py | 8e7e096a783467da3d86516cecf25c400d84f6f3 | [] | no_license | LopsanAMO/ejemplo-django-conekta | 3f90def1f4116483a023b1b0a8d2996abc3959d1 | 9f4e92066e47fb95855b2c2f53a90ca9988b6d78 | refs/heads/master | 2021-01-11T06:06:52.802869 | 2016-10-23T08:06:44 | 2016-10-23T08:06:44 | 71,689,745 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,780 | py |
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
import conekta
import json
class Sale(models.Model):
def __init__(self, *args, **kwargs):
super(Sale, self).__init__(*args, **kwargs)
conekta.api_key = settings.CONEKTA_PRIVATE_KEY
def charge(self, price_in_cents, token_id):
try:
charge = conekta.Charge.create({
"description":"Stogies",
"amount": price_in_cents,
"currency":"MXN",
"reference_id":"9839-wolf_pack",
"card": token_id,
"details": {
"name": "Arnulfo Quimare",
"phone": "403-342-0642",
"email": "[email protected]",
"line_items": [{
"name": "Box of Cohiba S1s",
"description": "Imported From Mex.",
"unit_price": price_in_cents,
"quantity": 1,
"sku": "cohb_s1",
"category": "food"
}],
"shipment": {
"carrier":"estafeta",
"service":"international",
"price": price_in_cents,
"address": {
"street1": "250 Alexis St",
"street2": "Interior 303",
"street3": "Col. Condesa",
"city":"Red Deer",
"state":"Alberta",
"zip":"T4N 0B8",
"country":"Canada"
}
}
}
})
return json.dumps(charge.__dict__)
except conekta.ConektaError as e:
return e.error_json['message']
| [
"[email protected]"
] | |
f981c59ed5948e48e7b95680c69b2d4ed02de4c9 | 78ae6050590464bcfe37eed2dcfcc62c46f40c45 | /TF4_Overfitting.py | ffa1653f2dcec2452fa87b4cf3bdb9574b858b56 | [] | no_license | JesusUrtasun/MachineLearningRep | 3c7c6c38f3fca172763006f175aa6a341e0f6a56 | 83a603df2845fce5883b087623b107f1d447f978 | refs/heads/master | 2020-04-20T01:53:40.513058 | 2019-03-21T12:01:00 | 2019-03-21T12:01:00 | 168,557,489 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,556 | py | # TensorFlow Chapter 4. Overfitting and underfitting
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
# Check the version of TensorFlow
print("TensorFlow version: {}".format(tf.__version__))
print("TensorFlow Chapter 4: Overfitting and underfitting")
# As seen in previous chapters, accuracy on the validation set peaks at a particular number of epochs, and the starts decreasing
# Overfitting has happened. The network learns patterns on the train set that do not generalize to the test data
# Prevent overfitting by use more training data. When not possible, use regularization techniques
# Download the Internet Movie Database IMDB. Multi-hot encode the sentences (turning them into vectors of 0s and 1s)
# Example, the sequence [3, 5] will be a 10000-dim vector with all zeros except for the indices 3 and 5, being there ones
NUM_WORDS = 10000
(train_data, train_labels), (test_data, test_labels) = keras.datasets.imdb.load_data(num_words = NUM_WORDS)
def multi_hot_sequences(sequences, dimension = NUM_WORDS):
# Create an zero matrix of shape (len(sequences), dimension)
results = np.zeros((len(sequences), dimension))
for i, word_indices in enumerate(sequences):
# Set specific indices of results[i] to be 1
results[i, word_indices] = 1.0
return results
train_data = multi_hot_sequences(train_data)
test_data = multi_hot_sequences(test_data)
# Look at the multi-hot encoded vectors. Word indices are sorted by frequency, so there are more one-values near index zero
print("Example. 1st element of the training set:")
plt.plot(train_data[0])
plt.show()
# Demonstrate overfitting.
# Simplest way to avoid it is by reducing the model. Then, there are less parameters to learn. Number of parameters to learn, "capacity"
# Recall, deep learning models are good at fitting to the training data, but real goal is generalization, not fitting
# Start by building a simple model with only Dense layers
print("\n1. Build baseline model")
baseline_model = keras.Sequential([
# input shape is required only required so that .summary() works
keras.layers.Dense(16, activation = tf.nn.relu, input_shape = (NUM_WORDS,)),
keras.layers.Dense(16, activation = tf.nn.relu),
keras.layers.Dense(1, activation = tf.nn.sigmoid)
])
baseline_model.compile(optimizer = "adam", loss = "binary_crossentropy", metrics = ["accuracy", "binary_crossentropy"])
baseline_model.summary()
print("\nTrain the baseline model")
baseline_history = baseline_model.fit(train_data, train_labels,
epochs = 20, batch_size = 512, validation_data = (test_data, test_labels), verbose = 1)
# Build a bigger model
print("\n2. Build bigger model")
bigger_model = keras.Sequential([
# input shape is required only required so that .summary() works
keras.layers.Dense(256, activation = tf.nn.relu, input_shape = (NUM_WORDS,)),
keras.layers.Dense(256, activation = tf.nn.relu),
keras.layers.Dense(1, activation = tf.nn.sigmoid)
])
bigger_model.compile(optimizer = "adam", loss = "binary_crossentropy", metrics = ["accuracy", "binary_crossentropy"])
bigger_model.summary()
print("\n Train the bigger model")
bigger_history = bigger_model.fit(train_data, train_labels,
epochs = 20, batch_size = 512, validation_data = (test_data, test_labels), verbose = 1)
# Plot the training and validation loss
def plot_history(histories, key = "binary_crossentropy"):
plt.figure(figsize = (16, 10))
for name, history in histories:
val = plt.plot(history.epoch, history.history["val_"+key], "--", label = name.title() + "Val")
plt.plot(history.epoch, history.history[key], color = val[0].get_color(), label = name.title() + "Train")
plt.xlabel("Epochs")
plt.ylabel(key.replace("_", " ").title())
plt.legend()
plt.xlim([0, max(history.epoch)])
print("\n3. Plot the training and validation loss for every model")
plot_history([("baseline", baseline_history), ("bigger", bigger_history)])
plt.show()
# The larger network begins overfitting almost right away, after just one epoch and overfits much more severely
# The more capacity a network has, the quicker it will be able to model the training data (low training loss)
# Strategies.
# Weight regularization
print("\n5. Add weight regularization")
# Occam's priciple. There are multiple sets of weights that can fit the data, and simple models are less likely to overfit
# Simple model, where the distribution of parameter values has less entropy.
# Force the weights to take small values, making the distribution more "regular"
# Add to the loss function a cost associated with having large weights. L1 and L2 regularization
L2_model = keras.models.Sequential([
keras.layers.Dense(16, kernel_regularizer = keras.regularizers.l2(0.001),
activation = tf.nn.relu, input_shape = (NUM_WORDS,)),
keras.layers.Dense(16, kernel_regularizer = keras.regularizers.l2(0.001),
activation = tf.nn.relu),
keras.layers.Dense(1, activation = tf.nn.sigmoid)
])
L2_model.compile(optimizer = "adam", loss = "binary_crossentropy", metrics = ["accuracy", "binary_crossentropy"])
L2_history = L2_model.fit(train_data, train_labels,
epochs = 20, batch_size = 512, validation_data = (test_data, test_labels), verbose = 1)
print("\nPlot loss after weight regularization")
plot_history([("baseline", baseline_history), ("L2", L2_history)])
plt.show()
# Dropout
print("\n6. Add dropout")
# Applied to a layer, randomly "dropping out" a number of output features of the layer during training
# [0.2, 0.5, 1.3, 8, 1, 1] will become [0, 0.5, 1.3, 0, 1, 1]. Dropout rate usually from 0.2 to 0.5
# At test time no values are dropped out. Instead, the output values are scaled down by a factor equal to the dropout rate
# This balances the fact that now more units are active that during the training
Dpt_model = keras.models.Sequential([
keras.layers.Dense(16, activation = tf.nn.relu, input_shape = (NUM_WORDS,)),
keras.layers.Dropout(0.5),
keras.layers.Dense(16, activation = tf.nn.relu),
keras.layers.Dropout(0.5),
keras.layers.Dense(1, activation = tf.nn.sigmoid)
])
Dpt_model.compile(optimizer = "adam", loss = "binary_crossentropy", metrics = ["accuracy", "binary_crossentropy"])
Dpt_history = L2_model.fit(train_data, train_labels,
epochs = 20, batch_size = 512, validation_data = (test_data, test_labels), verbose = 1)
print("\nPlot loss after weight regularization")
plot_history([("baseline", baseline_history), ("Dropout", Dpt_history)])
plt.show()
| [
"[email protected]"
] | |
4254377a5d2940c8d357014eda1cb62590da6ef7 | 4f946107165c8be6380f7399fc1170f64d4e1a61 | /Projectionable/urls.py | 82ad876fddbb3728b3bde18112bb8840ed90544f | [] | no_license | vail130/projectionable | 744a74afbe16354f937c5a2f6f0f4916a581299a | a7c749f616e57895847d6583e9e522c5452152b7 | refs/heads/master | 2021-01-20T04:33:26.459509 | 2013-11-02T18:04:32 | 2013-11-02T18:04:32 | 14,071,601 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,655 | py | from django.conf.urls import patterns, url
from django.conf import settings
from app.views import *
from project_api.views import *
from account_api.views import *
urlpatterns = patterns('',
url(r'^$', App.as_view(), name='app'),
url(r'^home/?$', Home.as_view(), name='home'),
url(r'^signup/?$', Signup.as_view(), name='signup'),
url(r'^signin/?(?:\?.*)?$', Signin.as_view(), name='signin'),
url(r'^verify_email/?(?:\?.*)?$', VerifyEmail.as_view(), name='verifyemail'),
url(r'^reset_password/?(?:\?.*)?$', ResetPassword.as_view(), name='resetpassword'),
url(r'^verify_invitation/?(?:\?.*)?$', VerifyInvitation.as_view(), name='verifyinvitation'),
url(r'^contact/?$', ContactUs.as_view(), name='contact'),
url(r'^terms/?$', Terms.as_view(), name='terms'),
url(r'^privacy/?$', Privacy.as_view(), name='privacy'),
url(r'^api/permissions/(?P<permission_id>[^/\?]+)/?(?:\?.*)?$', PermissionEditor.as_view(), name='permissioneditor'),
url(r'^api/permissions/?(?:\?.*)?$', PermissionManager.as_view(), name='permissionmanager'),
url(r'^api/projects/(?P<project_id>[^/\?]+)/?(?:\?.*)?$', ProjectEditor.as_view(), name='projecteditor'),
url(r'^api/projects/?(?:\?.*)?$', ProjectManager.as_view(), name='projectmanager'),
url(r'^api/groups/(?P<group_id>[^/\?]+)/?(?:\?.*)?$', GroupEditor.as_view(), name='groupeditor'),
url(r'^api/groups/?(?:\?.*)?$', GroupManager.as_view(), name='groupmanager'),
url(r'^api/requirements/(?P<req_id>[^/\?]+)/?(?:\?.*)?$', RequirementEditor.as_view(), name='requirementeditor'),
url(r'^api/requirements/?(?:\?.*)?$', RequirementManager.as_view(), name='requirementmanager'),
url(r'^api/sessions/(?P<session_id>[^/\?]+)/?(?:\?.*)?$', SessionEditor.as_view(), name='sessioneditor'),
url(r'^api/sessions/?(?:\?.*)?$', SessionManager.as_view(), name='sessionmanager'),
url(r'^api/accounts/?(?:\?.*)?$', AccountManager.as_view(), name='accountmanager'),
url(r'^api/accounts(?:/(?P<account_id>[0-9]+)/?)?(?:\?.*)?$', AccountEditor.as_view(), name='accounteditor'),
url(r'^api/contacts/(?P<contact_id>[^/\?]+)/?(?:\?.*)?$', ContactEditor.as_view(), name='contacteditor'),
url(r'^api/contacts/?(?:\?.*)?$', ContactManager.as_view(), name='contactmanager'),
#url(r'^api/payments/?(?:\?.*)?$', PaymentManager.as_view(), name='paymentmanager'),
#url(r'^api/payments(?:/(?P<payment_id>[0-9]+)/?)?(?:\?.*)?$', PaymentEditor.as_view(), name='paymenteditor'),
)
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
) | [
"[email protected]"
] | |
d6628e565916deb25682028f7bc00649b17deace | c06efd90533c51c2b29b7e92cd13723388de25ee | /actions/patchCoreV1NamespacedPod.py | e554a7d6a49f7318cebf1d3759cd8ba3c64fc0e8 | [] | no_license | ajohnstone/stackstorm-kubernetes | 490e4a73daad3713d7c5b5b639d5f30ff1ab3e58 | 99ffad27f5947583a2ab1b56e80c06003d014c47 | refs/heads/master | 2021-01-11T23:29:49.642435 | 2016-12-07T13:20:34 | 2016-12-07T13:20:34 | 78,588,572 | 0 | 0 | null | 2017-01-11T00:48:59 | 2017-01-11T00:48:59 | null | UTF-8 | Python | false | false | 892 | py | from lib import k8s
from st2actions.runners.pythonrunner import Action
class patchCoreV1NamespacedPod(Action):
def run(self,body,name,namespace,config_override=None,pretty=None):
myk8s = k8s.K8sClient(self.config)
args = {}
if body is not None:
args['body'] = body
else:
return (False, "body is a required parameter")
if name is not None:
args['name'] = name
else:
return (False, "name is a required parameter")
if namespace is not None:
args['namespace'] = namespace
else:
return (False, "namespace is a required parameter")
if config_override is not None:
args['config_override'] = config_override
if pretty is not None:
args['pretty'] = pretty
return (True, myk8s.runAction('patchCoreV1NamespacedPod', **args))
| [
"[email protected]"
] | |
caaefd1f715b30c6abb83cedb29f149cf97de3d9 | 58263e881e677a76ace8d4c0587d34db893dba97 | /ExtractionManager.py | 5aacc9a60ffaefa904adb45d77dc4d3eb1a47bab | [
"MIT"
] | permissive | AndresRestrepoRodriguez/NLPTweets | 9874d6a5e29de6077e1c66ce0710f220d2941acc | a3222c543cf73905639d104c9a975b464f93923b | refs/heads/main | 2023-01-24T06:22:25.857865 | 2020-12-10T12:31:20 | 2020-12-10T12:31:20 | 315,610,420 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,857 | py | from datetime import datetime, timedelta
import json
from APIConnection import APIConnection
from Extraction import Extraction
class ExtractionManager:
def __init__(self):
self._dates = list()
self._credentials = dict()
self._dataExtracted = list()
def setCredentials(self, pathfile):
with open(pathfile, "r") as read_file:
self._credentials = json.load(read_file)
def getCredentials(self):
return self._credentials
def setDates(self):
today = datetime.today()
dateFormat = "%Y-%m-%d"
self._dates = [str((today-timedelta(days=val)).strftime(dateFormat)) for val in range(7)]
def getDates(self):
return self._dates
@staticmethod
def generateConnection(credentials, connection):
apiconnection = APIConnection(credentials["costumer_key"], credentials["consumer_secret"],
credentials["access_token"], credentials["access_token_secret"], connection)
apiconnection.setConnection(apiconnection.getAccessToken(), apiconnection.getAccessTokenSecret(),
apiconnection.getCustomerKey(), apiconnection.getCustomerSecret(), connection)
return apiconnection.getConnection()
def setDataExtracted(self, parameters, connection):
extractor = Extraction(parameters["phrases"], parameters["account"], parameters["words"], parameters["hashtags"])
extractor.setQuery(extractor.getPhrases(), extractor.getWords(), extractor.getHashtags(),
extractor.getAccount(), parameters["logicaloption"])
self.setDates()
extractor.setTweets(connection, extractor.getQuery(), self.getDates())
self._dataExtracted = extractor.getTweets()
def getDataExtracted(self):
return self._dataExtracted
| [
"[email protected]"
] | |
b4b9d6422487b26d0713f3b750b3210f9a67418c | 6d11d48fb6d6ce45d2f9866f05310ae873a727dc | /code/deeplab/datasets/data_generator.py | a5802794f4f5bd487117cb6823901cf0d85ba4ca | [
"MIT"
] | permissive | BasemElbarashy/image-compression-and-semantic-segmentation | 634b107154377d4ac1a41fba5777d21d6f8ad075 | 760d7f779e97659f3f8f59f68eaa4268ec08618b | refs/heads/master | 2020-12-19T02:05:02.249473 | 2020-01-22T15:08:14 | 2020-01-22T15:08:14 | 235,588,116 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,276 | py | # Copyright 2018 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.
# ==============================================================================
"""Wrapper for providing semantic segmentaion data.
The SegmentationDataset class provides both images and annotations (semantic
segmentation and/or instance segmentation) for TensorFlow. Currently, we
support the following datasets:
1. PASCAL VOC 2012 (http://host.robots.ox.ac.uk/pascal/VOC/voc2012/).
PASCAL VOC 2012 semantic segmentation dataset annotates 20 foreground objects
(e.g., bike, person, and so on) and leaves all the other semantic classes as
one background class. The dataset contains 1464, 1449, and 1456 annotated
images for the training, validation and test respectively.
2. Cityscapes dataset (https://www.cityscapes-dataset.com)
The Cityscapes dataset contains 19 semantic labels (such as road, person, car,
and so on) for urban street scenes.
3. ADE20K dataset (http://groups.csail.mit.edu/vision/datasets/ADE20K)
The ADE20K dataset contains 150 semantic labels both urban street scenes and
indoor scenes.
References:
M. Everingham, S. M. A. Eslami, L. V. Gool, C. K. I. Williams, J. Winn,
and A. Zisserman, The pascal visual object classes challenge a retrospective.
IJCV, 2014.
M. Cordts, M. Omran, S. Ramos, T. Rehfeld, M. Enzweiler, R. Benenson,
U. Franke, S. Roth, and B. Schiele, "The cityscapes dataset for semantic urban
scene understanding," In Proc. of CVPR, 2016.
B. Zhou, H. Zhao, X. Puig, S. Fidler, A. Barriuso, A. Torralba, "Scene Parsing
through ADE20K dataset", In Proc. of CVPR, 2017.
"""
import collections
import os
import tensorflow as tf
from deeplab import common
from deeplab import input_preprocess
# Named tuple to describe the dataset properties.
DatasetDescriptor = collections.namedtuple(
'DatasetDescriptor',
[
'splits_to_sizes', # Splits of the dataset into training, val and test.
'num_classes', # Number of semantic classes, including the
# background class (if exists). For example, there
# are 20 foreground classes + 1 background class in
# the PASCAL VOC 2012 dataset. Thus, we set
# num_classes=21.
'ignore_label', # Ignore label value.
])
_CITYSCAPES_INFORMATION = DatasetDescriptor(
splits_to_sizes={
'train': 2975,
'val': 500,
},
num_classes=19,
ignore_label=255,
)
_PASCAL_VOC_SEG_INFORMATION = DatasetDescriptor(
splits_to_sizes={
'train': 1464,
'train_aug': 10582,
'trainval': 2913,
'val': 1449,
},
num_classes=21,
ignore_label=255,
)
_ADE20K_INFORMATION = DatasetDescriptor(
splits_to_sizes={
'train': 20210, # num of samples in images/training
'val': 2000, # num of samples in images/validation
},
num_classes=151,
ignore_label=0,
)
_DATASETS_INFORMATION = {
'cityscapes': _CITYSCAPES_INFORMATION,
'pascal_voc_seg': _PASCAL_VOC_SEG_INFORMATION,
'ade20k': _ADE20K_INFORMATION,
}
# Default file pattern of TFRecord of TensorFlow Example.
_FILE_PATTERN = '%s-*'
def get_cityscapes_dataset_name():
return 'cityscapes'
class Dataset(object):
"""Represents input dataset for deeplab model."""
def __init__(self,
dataset_name,
split_name,
dataset_dir,
batch_size,
crop_size,
min_resize_value=None,
max_resize_value=None,
resize_factor=None,
min_scale_factor=1.,
max_scale_factor=1.,
scale_factor_step_size=0,
model_variant=None,
num_readers=1,
is_training=False,
should_shuffle=False,
should_repeat=False):
"""Initializes the dataset.
Args:
dataset_name: Dataset name.
split_name: A train/val Split name.
dataset_dir: The directory of the dataset sources.
batch_size: Batch size.
crop_size: The size used to crop the image and label.
min_resize_value: Desired size of the smaller image side.
max_resize_value: Maximum allowed size of the larger image side.
resize_factor: Resized dimensions are multiple of factor plus one.
min_scale_factor: Minimum scale factor value.
max_scale_factor: Maximum scale factor value.
scale_factor_step_size: The step size from min scale factor to max scale
factor. The input is randomly scaled based on the value of
(min_scale_factor, max_scale_factor, scale_factor_step_size).
model_variant: Model variant (string) for choosing how to mean-subtract
the images. See feature_extractor.network_map for supported model
variants.
num_readers: Number of readers for data provider.
is_training: Boolean, if dataset is for training or not.
should_shuffle: Boolean, if should shuffle the input data.
should_repeat: Boolean, if should repeat the input data.
Raises:
ValueError: Dataset name and split name are not supported.
"""
if dataset_name not in _DATASETS_INFORMATION:
raise ValueError('The specified dataset is not supported yet.')
self.dataset_name = dataset_name
splits_to_sizes = _DATASETS_INFORMATION[dataset_name].splits_to_sizes
if split_name not in splits_to_sizes:
raise ValueError('data split name %s not recognized' % split_name)
if model_variant is None:
tf.logging.warning('Please specify a model_variant. See '
'feature_extractor.network_map for supported model '
'variants.')
self.split_name = split_name
self.dataset_dir = dataset_dir
self.batch_size = batch_size
self.crop_size = crop_size
self.min_resize_value = min_resize_value
self.max_resize_value = max_resize_value
self.resize_factor = resize_factor
self.min_scale_factor = min_scale_factor
self.max_scale_factor = max_scale_factor
self.scale_factor_step_size = scale_factor_step_size
self.model_variant = model_variant
self.num_readers = num_readers
self.is_training = is_training
self.should_shuffle = should_shuffle
self.should_repeat = should_repeat
self.num_of_classes = _DATASETS_INFORMATION[self.dataset_name].num_classes
self.ignore_label = _DATASETS_INFORMATION[self.dataset_name].ignore_label
def _parse_function(self, example_proto):
"""Function to parse the example proto.
Args:
example_proto: Proto in the format of tf.Example.
Returns:
A dictionary with parsed image, label, height, width and image name.
Raises:
ValueError: Label is of wrong shape.
"""
# Currently only supports jpeg and png.
# Need to use this logic because the shape is not known for
# tf.image.decode_image and we rely on this info to
# extend label if necessary.
def _decode_image(content, channels):
return tf.cond(
tf.image.is_jpeg(content),
lambda: tf.image.decode_jpeg(content, channels),
lambda: tf.image.decode_png(content, channels))
features = {
'image/encoded':
tf.FixedLenFeature((), tf.string, default_value=''),
'image/filename':
tf.FixedLenFeature((), tf.string, default_value=''),
'image/format':
tf.FixedLenFeature((), tf.string, default_value='jpeg'),
'image/height':
tf.FixedLenFeature((), tf.int64, default_value=0),
'image/width':
tf.FixedLenFeature((), tf.int64, default_value=0),
'image/segmentation/class/encoded':
tf.FixedLenFeature((), tf.string, default_value=''),
'image/depth/filled/encoded':
tf.FixedLenFeature((), tf.string, default_value=''),
'image/segmentation/class/format':
tf.FixedLenFeature((), tf.string, default_value='png'),
}
parsed_features = tf.parse_single_example(example_proto, features)
image = _decode_image(parsed_features['image/encoded'], channels=3)
depth = _decode_image(parsed_features['image/depth/filled/encoded'], channels=1)
label = None
if self.split_name != common.TEST_SET:
label = _decode_image(
parsed_features['image/segmentation/class/encoded'], channels=1)
image_name = parsed_features['image/filename']
if image_name is None:
image_name = tf.constant('')
sample = {
common.IMAGE: image,
common.IMAGE_NAME: image_name,
common.HEIGHT: parsed_features['image/height'],
common.WIDTH: parsed_features['image/width'],
'depth':depth
}
if label is not None:
if label.get_shape().ndims == 2:
label = tf.expand_dims(label, 2)
elif label.get_shape().ndims == 3 and label.shape.dims[2] == 1:
pass
else:
raise ValueError('Input label shape must be [height, width], or '
'[height, width, 1].')
label.set_shape([None, None, 1])
sample[common.LABELS_CLASS] = label
return sample
def _preprocess_image(self, sample):
"""Preprocesses the image and label.
Args:
sample: A sample containing image and label.
Returns:
sample: Sample with preprocessed image and label.
Raises:
ValueError: Ground truth label not provided during training.
"""
image = sample[common.IMAGE]
label = sample[common.LABELS_CLASS]
depth = sample['depth']
original_image, image, label, depth = input_preprocess.preprocess_image_and_label(
image=image,
label=label,
depth=depth,
crop_height=self.crop_size[0],
crop_width=self.crop_size[1],
min_resize_value=self.min_resize_value,
max_resize_value=self.max_resize_value,
resize_factor=self.resize_factor,
min_scale_factor=self.min_scale_factor,
max_scale_factor=self.max_scale_factor,
scale_factor_step_size=self.scale_factor_step_size,
ignore_label=self.ignore_label,
is_training=self.is_training,
model_variant=self.model_variant)
sample[common.IMAGE] = image
sample['depth'] = depth
if not self.is_training:
# Original image is only used during visualization.
sample[common.ORIGINAL_IMAGE] = original_image
if label is not None:
sample[common.LABEL] = label
# Remove common.LABEL_CLASS key in the sample since it is only used to
# derive label and not used in training and evaluation.
sample.pop(common.LABELS_CLASS, None)
return sample
def get_one_shot_iterator(self):
"""Gets an iterator that iterates across the dataset once.
Returns:
An iterator of type tf.data.Iterator.
"""
files = self._get_all_files()
dataset = (
tf.data.TFRecordDataset(files, num_parallel_reads=self.num_readers)
.map(self._parse_function, num_parallel_calls=self.num_readers)
.map(self._preprocess_image, num_parallel_calls=self.num_readers))
if self.should_shuffle:
dataset = dataset.shuffle(buffer_size=100)
if self.should_repeat:
dataset = dataset.repeat() # Repeat forever for training.
else:
dataset = dataset.repeat(1)
dataset = dataset.batch(self.batch_size).prefetch(self.batch_size)
return dataset.make_one_shot_iterator()
def _get_all_files(self):
"""Gets all the files to read data from.
Returns:
A list of input files.
"""
file_pattern = _FILE_PATTERN
file_pattern = os.path.join(self.dataset_dir,
file_pattern % self.split_name)
return tf.gfile.Glob(file_pattern)
| [
"[email protected]"
] | |
5e66ca3f880c62a693021918fb5172b2376c63ff | 8cdaf9c49ae75bcc24d0c01860bb12bd5f7b5cfb | /svs_only_tsr.py | f72e37daaa03d88e4e3d42d5351f668332f41b37 | [] | no_license | TheSimpleRobotics/tsr_carla_scripts | e9cad8a3163956ce20313b198e1c96ad1b1ec118 | e7ec995d54eb2895a5574b542373098408abd229 | refs/heads/master | 2020-04-29T07:09:30.339650 | 2019-03-17T13:49:06 | 2019-03-17T13:49:06 | 175,941,876 | 0 | 0 | null | 2019-03-17T14:14:48 | 2019-03-16T07:43:48 | Python | UTF-8 | Python | false | false | 18,061 | py | #!/usr/bin/env python
# Copyright (c) 2018 The simple robotics
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
# Allows controlling a vehicle with a keyboard. For a simpler and more
# documented example, please take a look at tutorial.py.
"""
Welcome to TSR manual control.
Use ARROWS or WASD keys for control.
W : throttle
S : brake
AD : steer
Q : toggle reverse
Space : hand-brake
P : toggle autopilot
C : change weather (Shift+C reverse)
ESC : quit
"""
from __future__ import print_function
import glob
import os
import sys
# ==============================================================================
# -- imports -------------------------------------------------------------------
# ==============================================================================
import carla
from carla import ColorConverter as cc
import argparse
import collections
import datetime
import logging
import math
import random
import re
import weakref
try:
import pygame
from pygame.locals import KMOD_CTRL
from pygame.locals import KMOD_SHIFT
from pygame.locals import K_0
from pygame.locals import K_9
from pygame.locals import K_BACKQUOTE
from pygame.locals import K_BACKSPACE
from pygame.locals import K_COMMA
from pygame.locals import K_DOWN
from pygame.locals import K_ESCAPE
from pygame.locals import K_F1
from pygame.locals import K_LEFT
from pygame.locals import K_PERIOD
from pygame.locals import K_RIGHT
from pygame.locals import K_SLASH
from pygame.locals import K_SPACE
from pygame.locals import K_TAB
from pygame.locals import K_UP
from pygame.locals import K_a
from pygame.locals import K_c
from pygame.locals import K_d
from pygame.locals import K_h
from pygame.locals import K_m
from pygame.locals import K_p
from pygame.locals import K_q
from pygame.locals import K_r
from pygame.locals import K_s
from pygame.locals import K_w
from pygame.locals import K_MINUS
from pygame.locals import K_EQUALS
except ImportError:
raise RuntimeError(
'cannot import pygame, make sure pygame package is installed')
try:
import numpy as np
except ImportError:
raise RuntimeError(
'cannot import numpy, make sure numpy package is installed')
svs_resolution = ['1280', '800']
# ==============================================================================
# -- TSR functions ----------------------------------------------------------
# ==============================================================================
class CameraTsr(object):
def __init__(self, vehicle, width, height, fov='90', tick='0.0', pygame_disp=False):
self.vehicle = vehicle
self.width = width
self.height = height
self.fov = fov
self.tick = tick
self._pygame_disp = pygame_disp # display for pygame
self._surface = None # image to render fom array for pygame display
self.camera = None
def add_camera(self, x=-6.5, y=0.0, z=2.7,
roll=0, pitch=0, yaw=0,
camera_type='sensor.camera.rgb',
):
''' The camera type can be also:
'sensor.camera.semantic_segmentation'
'sensor.camera.depth'
'''
if self.camera is None:
# Find the blueprint of the sensor.
blueprint = self.vehicle.get_world().get_blueprint_library().find(camera_type)
# Modify the attributes of the blueprint to set image resolution and field of view.
blueprint.set_attribute('image_size_x', self.width)
blueprint.set_attribute('image_size_y', self.height)
blueprint.set_attribute('fov', self.fov)
# Set the time in seconds between sensor captures
blueprint.set_attribute('sensor_tick', self.tick)
# Provide the position of the sensor relative to the vehicle.
transform = carla.Transform(carla.Location(
x=x, y=y, z=z), carla.Rotation(roll=roll, pitch=pitch, yaw=yaw))
# Tell the world to spawn the sensor, don't forget to attach it to your vehicle actor.
self.camera = self.vehicle.get_world().spawn_actor(
blueprint, transform, attach_to=self.vehicle)
# Subscribe to the sensor stream by providing a callback function, this function is
# called each time a new image is generated by the sensor.
self.camera.listen(lambda data: self._process_image(data))
else:
Print("The camera sensor is already initialized")
def _process_image(self, image):
''' The callback function which gets raw image
and convert it to array '''
array = np.frombuffer(image.raw_data, dtype=np.dtype("uint8"))
array = np.reshape(array, (image.height, image.width, 4))
array = array[:, :, :3]
array = array[:, :, ::-1]
if self._pygame_disp:
self._surface = pygame.surfarray.make_surface(array.swapaxes(0, 1))
def render(self, display):
''' The function gets display class from pygame window
and render the image from the current camera. '''
if self._surface is not None:
display.blit(self._surface, (0, 0))
# ==============================================================================
# -- Global functions ----------------------------------------------------------
# ==============================================================================
def find_weather_presets():
rgx = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)')
def name(x): return ' '.join(m.group(0) for m in rgx.finditer(x))
presets = [x for x in dir(carla.WeatherParameters)
if re.match('[A-Z].+', x)]
return [(getattr(carla.WeatherParameters, x), name(x)) for x in presets]
def get_actor_display_name(actor, truncate=250):
name = ' '.join(actor.type_id.replace('_', '.').title().split('.')[1:])
return (name[:truncate-1] + u'\u2026') if len(name) > truncate else name
# ==============================================================================
# -- World ---------------------------------------------------------------------
# ==============================================================================
class World(object):
def __init__(self, carla_world, actor_filter):
self.world = carla_world
self.map = self.world.get_map()
self.player = None
self._weather_presets = find_weather_presets()
self._weather_index = 0
self._actor_filter = actor_filter
# Camera view
self.camera_view = None
self.restart()
# SVS cameras
self.cam1_svs_front = None
self.cam2_svs_rigtht = None
self.cam3_svs_back = None
self.cam4_svs_rear = None
# SVS semseg cameras
self.sem_cam1_svs_front = None
self.sem_cam2_svs_rigtht = None
self.sem_cam3_svs_back = None
self.sem_cam4_svs_rear = None
def restart(self):
# Get a vehicle mercedes.
blueprint_library = self.world.get_blueprint_library()
vehicle_bp = blueprint_library.find('vehicle.mercedes-benz.coupe')
vehicle_bp.set_attribute('role_name', 'hero')
vehicle_bp.set_attribute('color', '255,0,0')
# Spawn the player.
if self.player is not None:
spawn_point = self.player.get_transform()
spawn_point.location.z += 2.0
spawn_point.rotation.roll = 0.0
spawn_point.rotation.pitch = 0.0
self.destroy()
self.player = self.world.try_spawn_actor(vehicle_bp, spawn_point)
while self.player is None:
spawn_points = self.map.get_spawn_points()
spawn_point = random.choice(
spawn_points) if spawn_points else carla.Transform()
self.player = self.world.try_spawn_actor(vehicle_bp, spawn_point)
# Svs front camera
self.cam1_svs_front = CameraTsr(
vehicle=self.player, width=svs_resolution[0], height=svs_resolution[1], fov="90", pygame_disp=True)
self.cam1_svs_front.add_camera(
x=0.8, y=0.0, z=1.7, roll=0, pitch=-15, yaw=0)
self.camera_view = self.cam1_svs_front
# Svs semseg gt camera
self.sem_cam1_svs_front = CameraTsr(
vehicle=self.player, width=svs_resolution[0], height=svs_resolution[1], fov="90")
self.sem_cam1_svs_front.add_camera(
x=0.8, y=0.0, z=1.7, roll=0, pitch=-15, yaw=0, camera_type='sensor.camera.semantic_segmentation')
# Svs right camera
self.cam2_svs_right = CameraTsr(
vehicle=self.player, width=svs_resolution[0], height=svs_resolution[1], fov="90")
self.cam2_svs_right.add_camera(
x=0.0, y=0.5, z=1.7, roll=0, pitch=-15, yaw=90)
# Svs semseg gt camera
self.sem_cam2_svs_rigtht = CameraTsr(
vehicle=self.player, width=svs_resolution[0], height=svs_resolution[1], fov="90")
self.sem_cam2_svs_rigtht.add_camera(
x=0.0, y=0.5, z=1.7, roll=0, pitch=-15, yaw=90, camera_type='sensor.camera.semantic_segmentation')
# Svs back camera
self.cam3_svs_back = CameraTsr(
vehicle=self.player, width=svs_resolution[0], height=svs_resolution[1], fov="90")
self.cam3_svs_back.add_camera(
x=-0.8, y=0.0, z=1.7, roll=0, pitch=-15, yaw=180)
# Svs semseg gt camera
self.sem_cam3_svs_back = CameraTsr(
vehicle=self.player, width=svs_resolution[0], height=svs_resolution[1], fov="90")
self.sem_cam3_svs_back.add_camera(
x=-0.8, y=0.0, z=1.7, roll=0, pitch=-15, yaw=180, camera_type='sensor.camera.semantic_segmentation')
# Svs left camera
self.cam4_svs_left = CameraTsr(
vehicle=self.player, width=svs_resolution[0], height=svs_resolution[1], fov="90")
self.cam4_svs_left.add_camera(
x=0.0, y=-0.5, z=1.7, roll=0, pitch=-15, yaw=270)
# Svs semseg gt camera
self.sem_cam4_svs_rear = CameraTsr(
vehicle=self.player, width=svs_resolution[0], height=svs_resolution[1], fov="90")
self.sem_cam4_svs_rear.add_camera(
x=0.0, y=-0.5, z=1.7, roll=0, pitch=-15, yaw=270, camera_type='sensor.camera.semantic_segmentation')
def next_weather(self, reverse=False):
self._weather_index += -1 if reverse else 1
self._weather_index %= len(self._weather_presets)
preset = self._weather_presets[self._weather_index]
self.player.get_world().set_weather(preset[0])
def render(self, display):
self.camera_view.render(display)
def destroy(self):
actors = [
self.player,
self.camera_view.camera,
self.cam1_svs_front.camera,
self.cam2_svs_rigtht.camera,
self.cam3_svs_back.camera,
self.cam4_svs_rear.camera,
self.sem_cam1_svs_front.camera,
self.sem_cam2_svs_rigtht.camera,
self.sem_cam3_svs_back.camera,
self.sem_cam4_svs_rear.camera
]
for actor in actors:
if actor is not None:
actor.destroy()
# ==============================================================================
# -- KeyboardControl -----------------------------------------------------------
# ==============================================================================
class KeyboardControl(object):
def __init__(self, world, start_in_autopilot):
self._autopilot_enabled = start_in_autopilot
if isinstance(world.player, carla.Vehicle):
self._control = carla.VehicleControl()
world.player.set_autopilot(self._autopilot_enabled)
elif isinstance(world.player, carla.Walker):
self._control = carla.WalkerControl()
self._autopilot_enabled = False
self._rotation = world.player.get_transform().rotation
else:
raise NotImplementedError("Actor type not supported")
self._steer_cache = 0.0
def parse_events(self, client, world, clock):
for event in pygame.event.get():
if event.type == pygame.QUIT:
return True
elif event.type == pygame.KEYUP:
if self._is_quit_shortcut(event.key):
return True
elif event.key == K_c and pygame.key.get_mods() & KMOD_SHIFT:
world.next_weather(reverse=True)
elif event.key == K_c:
world.next_weather()
if isinstance(self._control, carla.VehicleControl):
if event.key == K_q:
self._control.gear = 1 if self._control.reverse else -1
elif event.key == K_p and not (pygame.key.get_mods() & KMOD_CTRL):
self._autopilot_enabled = not self._autopilot_enabled
world.player.set_autopilot(self._autopilot_enabled)
if not self._autopilot_enabled:
if isinstance(self._control, carla.VehicleControl):
self._parse_vehicle_keys(
pygame.key.get_pressed(), clock.get_time())
self._control.reverse = self._control.gear < 0
elif isinstance(self._control, carla.WalkerControl):
self._parse_walker_keys(
pygame.key.get_pressed(), clock.get_time())
world.player.apply_control(self._control)
def _parse_vehicle_keys(self, keys, milliseconds):
self._control.throttle = 1.0 if keys[K_UP] or keys[K_w] else 0.0
steer_increment = 5e-4 * milliseconds
if keys[K_LEFT] or keys[K_a]:
self._steer_cache -= steer_increment
elif keys[K_RIGHT] or keys[K_d]:
self._steer_cache += steer_increment
else:
self._steer_cache = 0.0
self._steer_cache = min(0.7, max(-0.7, self._steer_cache))
self._control.steer = round(self._steer_cache, 1)
self._control.brake = 1.0 if keys[K_DOWN] or keys[K_s] else 0.0
self._control.hand_brake = keys[K_SPACE]
def _parse_walker_keys(self, keys, milliseconds):
self._control.speed = 0.0
if keys[K_DOWN] or keys[K_s]:
self._control.speed = 0.0
if keys[K_LEFT] or keys[K_a]:
self._control.speed = .01
self._rotation.yaw -= 0.08 * milliseconds
if keys[K_RIGHT] or keys[K_d]:
self._control.speed = .01
self._rotation.yaw += 0.08 * milliseconds
if keys[K_UP] or keys[K_w]:
self._control.speed = 5.556 if pygame.key.get_mods() & KMOD_SHIFT else 2.778
self._control.jump = keys[K_SPACE]
self._rotation.yaw = round(self._rotation.yaw, 1)
self._control.direction = self._rotation.get_forward_vector()
@staticmethod
def _is_quit_shortcut(key):
return (key == K_ESCAPE) or (key == K_q and pygame.key.get_mods() & KMOD_CTRL)
# ==============================================================================
# -- game_loop() ---------------------------------------------------------------
# ==============================================================================
def game_loop(args):
pygame.init()
pygame.font.init()
world = None
try:
client = carla.Client(args.host, args.port)
client.set_timeout(2.0)
display = pygame.display.set_mode(
(args.width, args.height),
pygame.HWSURFACE | pygame.DOUBLEBUF)
world = World(client.get_world(), args.filter)
controller = KeyboardControl(world, args.autopilot)
clock = pygame.time.Clock()
while True:
clock.tick_busy_loop(60)
if controller.parse_events(client, world, clock):
return
world.render(display)
pygame.display.flip()
finally:
if world is not None:
world.destroy()
pygame.quit()
# ==============================================================================
# -- main() --------------------------------------------------------------------
# ==============================================================================
def main():
argparser = argparse.ArgumentParser(
description='CARLA Manual Control Client')
argparser.add_argument(
'-v', '--verbose',
action='store_true',
dest='debug',
help='print debug information')
argparser.add_argument(
'--host',
metavar='H',
default='127.0.0.1',
help='IP of the host server (default: 127.0.0.1)')
argparser.add_argument(
'-p', '--port',
metavar='P',
default=2000,
type=int,
help='TCP port to listen to (default: 2000)')
argparser.add_argument(
'-a', '--autopilot',
action='store_true',
help='enable autopilot')
argparser.add_argument(
'--res',
metavar='WIDTHxHEIGHT',
default='1280x800',
help='window resolution (default: 1280x800)')
argparser.add_argument(
'--filter',
metavar='PATTERN',
default='vehicle.*',
help='actor filter (default: "vehicle.*")')
args = argparser.parse_args()
args.width, args.height = [int(x) for x in args.res.split('x')]
log_level = logging.DEBUG if args.debug else logging.INFO
logging.basicConfig(format='%(levelname)s: %(message)s', level=log_level)
logging.info('listening to server %s:%s', args.host, args.port)
print(__doc__)
try:
game_loop(args)
except KeyboardInterrupt:
print('\nCancelled by user. Bye!')
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
e4e921e27952df4763b04936511b286bd092123e | 4bcd94d568aee06e638d6f451ec4a2136714d9e1 | /HW_1_1.py | 90c7106bc37ca101f236dba19efdc8f92bfb2321 | [] | no_license | kuchabska/python_cource | 82a582071361163446d9e63be9d54058416244eb | 72ef68b9c55af18f41467e3d07ef7926a9ecdab8 | refs/heads/master | 2020-07-11T07:23:26.573974 | 2019-08-26T13:10:29 | 2019-08-26T13:10:29 | 204,477,471 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 123 | py | a = float (input ( 'input a \n'))
b = float (input ( 'input b \n'))
print (a + b)
print (a - b)
print (a * b)
print (a / b) | [
"[email protected]"
] | |
2540b0d2ce8d3f80b974b15498b4478fcfb42135 | 32535cc2c4a2ec52a0031d34e3125cbc7751a3e4 | /project_name/project_name/configuracion/base.py | 32fcfb9b1c327eaee4f110d735be7bbcaed109b9 | [] | no_license | lizceth/prueba2 | 0bd5024abfb0d8095f421bb49d2d354a2929f19e | 4c4c5d68ef3f715adbc18d1b9e7a7b0b55e8f148 | refs/heads/master | 2021-01-20T03:26:00.468046 | 2014-09-19T18:50:06 | 2014-09-19T18:50:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,096 | py | import os
from os.path import dirname, basename, normpath, abspath, join
from sys import path
#muestra la ruta del proyecto django
DJANGO_ROOT=dirname(dirname(abspath(__file__)))
#muestra la ruta del repositorio del proyecto
SITE_ROOT=dirname(DJANGO_ROOT)
#muestra el nombre del projecto dajngo
SITE_NAME=basename(DJANGO_ROOT)
path.append(DJANGO_ROOT)
#configuracion para mostrar los errores que haya en el proyecto
DEBUG = True
#configuracion para mostrar los errores de la plantilla del proyecto
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = []
#configuracion del administrador django
ADMINS=(
('name','[email protected]'),
)
MANAGER=ADMINS
#configuracion de la base de datos, la ruta y y el nombre con que se guardara al generase
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
########## END DATABASE CONFIGURATION
########## GENERAL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone
TIME_ZONE = 'UTC'
# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
LANGUAGE_CODE = 'es-pe'
# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
USE_I18N = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
USE_L10N = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
USE_TZ = True
########## END GENERAL CONFIGURATION
########## MEDIA CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = normpath(join(SITE_ROOT, 'media'))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'
########## END MEDIA CONFIGURATION
########## STATIC FILE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = normpath(join(SITE_ROOT, 'assets'))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = '/static/'
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = (
normpath(join(SITE_ROOT, 'static')),
)
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
########## END STATIC FILE CONFIGURATION
########## SECRET CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Note: This key should only be used for development and testing.
#SECRET_KEY = r"{{ secret_key }}"
########## END SECRET CONFIGURATION
########## SITE CONFIGURATION
# Hosts/domain names that are valid for this site
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
########## END SITE CONFIGURATION
########## FIXTURE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS
FIXTURE_DIRS = (
normpath(join(SITE_ROOT, 'fixtures')),
)
########## END FIXTURE CONFIGURATION
########## TEMPLATE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.request',
)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
TEMPLATE_DIRS = (
normpath(join(SITE_ROOT, 'template')),
)
########## END TEMPLATE CONFIGURATION
########## MIDDLEWARE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#middleware-classes
MIDDLEWARE_CLASSES = (
# Default Django middleware.
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
########## END MIDDLEWARE CONFIGURATION
########## URL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf
ROOT_URLCONF = '%s.urls' % SITE_NAME
########## END URL CONFIGURATION
########## APP CONFIGURATION
DJANGO_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
)
# Apps specific for this project go here.
LOCAL_APPS = (
)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS
########## END APP CONFIGURATION
########## LOGGING CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
########## END LOGGING CONFIGURATION
########## WSGI CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME
########## END WSGI CONFIGURATION
#clave que se genera por cada proyecto realizado, esta debe ser unica.
# SECURITY WARNING: keep the secret key used in production secret!
#SECRET_KEY = 'q*194oc8pwre*$^udru%)#l94o52ug%^o8#hzsge5tp711n42)'
SECRET_KEY=r"{{ secret_key }}"
# SECURITY WARNING: don't run with debug turned on in production!
########## SOUTH CONFIGURATION
# See: http://south.readthedocs.org/en/latest/installation.html#configuring-your-django-installation
INSTALLED_APPS += (
# Database migration helpers:
#'south',
)
# Don't need to use South when setting up a test database.
SOUTH_TESTS_MIGRATE = False
########## END SOUTH CONFIGURATION
| [
"[email protected]"
] | |
da2d4be10dbde9b53d5252fb39575bc48970029f | 9225ad5fb5dd92af547f4c4e04874bc812620d04 | /0.Dev Training/1.Junior/22.绘制并定制化图表/moveax.py | 31e2697b37e24ebbcdd193de787acc00f050b56c | [] | no_license | skynimrod/dt_python | 6fb50d354d3e8cef995edc459ef45fe42b234c48 | bd822140634ae56d1f2331bde9877c871f62507a | refs/heads/master | 2021-05-16T06:55:32.840279 | 2017-09-15T04:11:10 | 2017-09-15T04:11:10 | 103,612,926 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 484 | py | import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( -np.pi, np.pi, 500, endpoint = True )
y = np.sin(x)
plt.plot(x, y)
ax = plt.gca()
# hide two spines
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# move bottom and left spine to 0,0
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position( ('data',0) )
# move ticks positions
ax.xaxis.set_ticks_position( 'bottom' )
ax.yaxis.set_ticks_position( 'left' )
plt.show() | [
"[email protected]"
] | |
43f48b573d2b18f3d9446e41b86481c7d77fef58 | 4b5d0b71b6a1d5615f7678037bca48a45ce1dc22 | /basic_app/views.py | 5f7ea383f42bbd684805bcdf3caea2be99be67a5 | [] | no_license | Gigi1111/django-deployment-example | 71b91e79557d0a2579676582442e647f817fb9f3 | f1b125bb7546d47072a0150fbf2cdfc617b82229 | refs/heads/master | 2020-07-08T23:36:18.461744 | 2019-08-22T15:10:08 | 2019-08-22T15:10:08 | 203,812,325 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,523 | py | from django.shortcuts import render
from basic_app.forms import UserForm, UserProfileInfoForm
# Create your views here.
# login
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
# before django 2.0 from django.core.urlresolvers import reverse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
def index(request):
return render(request, 'basic_app/index.html')
# only logged in user can see it
@login_required
def special(request):
return HttpResponse("You are logged in, Nice!")
@login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
def register(request):
registered = False
if request.method == "POST":
user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
# hashing password with set
user.set_password(user.password)
user.save()
# not saving to db yet, incaseof collision,
# see if there's pic before save
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
print(user_form.errors, profile_form.errors)
# no request yet
else:
user_form = UserForm()
profile_form = UserProfileInfoForm()
return render(request, 'basic_app/register.html', {'registered': registered, 'user_form': user_form, 'profile_form': profile_form})
def user_login(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Account not Active")
else:
print("Someone tried to login and failed")
print("Username: {} and password {}".format(username, password))
return HttpResponse("invalid login details supplied")
else:
return render(request, 'basic_app/login.html', {})
| [
"[email protected]"
] | |
e89a4fa08e2efb9d31175514312fd1b1f0d96881 | b657f54555330af28ef9f22ee935bfed697a91f0 | /Exercicios Loop/exercicio 40 - secao 06.py | 68b3bded1e4b36e98db190cdf57dbd3d25668c08 | [
"MIT"
] | permissive | cristinamais/exercicios_python | cecadd29a5f610b30ee929b94b00a4491d90d116 | 8a09b0b68ffaa62d13afb952998e890a79667c7e | refs/heads/master | 2021-06-12T18:58:35.595609 | 2020-04-09T14:01:43 | 2020-04-09T14:01:43 | 254,380,930 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 421 | py | """
40 - Elabore um programa que faça leitura de vários números inteiros, até que se digite um número
negativo. O programa tem que retornar o maior e o menor número lido.
"""
lista = []
numero = int(input(f'Digite o número: '))
while numero >= 0:
lista.append(numero)
numero = int(input(f'Digite o número: '))
print('O maior valor da lista é:', max(lista), '\nO menor valor da lista é:', min(lista))
| [
"[email protected]"
] | |
e545daf7555bd993e6f754da1bdbdf23ba23b0d4 | b79c76bfba65afb209eff02293e8f73fbeced7fd | /3-11.py | 771fd8e5a9cf7bd6667be998059d625bc0001f11 | [] | no_license | MyeongJun88/homework | c4d910a2802f9675f78f773f8553efb47763438b | c9a13407f726700eea87c0bee3ca03752db9f20c | refs/heads/master | 2020-03-24T16:27:20.910258 | 2018-07-30T04:33:52 | 2018-07-30T04:33:52 | 142,825,325 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 37 | py | def calculate_change(payment, cost):
| [
"[email protected]"
] | |
069841c93b19d8461a30d4b06d90309bc17b5cf9 | a371e9122dacaf433d6fc1619955cf6173ec79fd | /app/my_settings/settings.py | 4b6967026dfd5dbc9bd6fbc7a73d6f017e5733dd | [] | no_license | Jason-Oleana/from-classification-to-web-application | 978768d1b38b44d23ae7b64ca570631232eac899 | a6568172c5f9ee5a754736b63e122ba182c13159 | refs/heads/main | 2023-04-16T08:09:16.170501 | 2021-04-29T15:47:47 | 2021-04-29T15:47:47 | 360,296,904 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,376 | py | """
Django settings for project.
Generated by 'django-admin startproject' using Django 2.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qslmozm3+))#m_p@7b6_u!$7o_z$1ifv2jc6d=@^pd4jm+xhdx'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["*","167.71.6.96"]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'webapp.apps.Config',
]
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 = 'my_settings.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["templates"],
'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 = 'my_settings.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/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.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/2.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/2.2/howto/static-files/
STATIC_URL = '/static/'
#STATIC_ROOT = os.path.join(BASE_DIR, "static/")
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
| [
"[email protected]"
] | |
2adbc4e7e758cf4da8dc63ae807a98e4c7ac40f2 | 6e517b4043d1ed39462621e592c5536b519fae2d | /algorithms/python/datastruct/nchoosek.py | 96af871e0b88a9dd6cee5c0b227b2141ef209baa | [] | no_license | ziXiong/leetcode | c4552d725358ccab33bfd5755add79e34b4c2be4 | 2bedcdb585661cbb5addf0ff8bc1a23343a120ce | refs/heads/master | 2022-04-30T11:13:42.126460 | 2022-04-10T11:27:04 | 2022-04-10T11:27:04 | 25,695,519 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 277 | py | # -*- coding: utf-8 -*-
def nchoosek(nums, k):
if k == 0:
return [[]]
if k == len(nums):
return [nums]
return nchoosek(nums[:-1], k) + [[nums[-1]] + res for res in nchoosek(nums[:-1], k - 1)]
nums = [1, 2, 3, 4, 9] * 10
print(nchoosek(nums, 5))
| [
"[email protected]"
] | |
a6f81a9adc3eb8a103dfdd5fb1363a4b70f26c5e | 586e6c48ac0a29c35882c73d53a8eab59847c53c | /sigteca/settings/active.py | b1f54383e2dafab2b9225c512ab9d746fd97cc0a | [] | no_license | rodolphopivetta/sigteca | cf831bdec997ac002b757cdd5e68dfa81e4a0c01 | 58390c22be5600d21c62639452839ec609c497fc | refs/heads/master | 2020-04-10T00:48:41.253951 | 2016-03-08T22:47:08 | 2016-03-08T22:47:08 | 40,916,167 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 67 | py | # -*- coding: utf-8 -*-
from sigteca.settings.development import *
| [
"[email protected]"
] | |
163c63c277b114424bc9dd73fa5d4a369238a9ab | aeea3a1183773a375190806f6022b78ef6bfebea | /blog/search_indexes.py | a065e105ee8c40566f2dbe43152ed1e1f2306144 | [] | no_license | hnlisf/myblog-0.6 | cb57ae3db779cad6a73cd8f6e9c14693f819554f | b5fae2a27ca9a3a2f81debae0a69ad6641cccd12 | refs/heads/master | 2021-08-30T10:55:26.663980 | 2017-12-17T15:28:10 | 2017-12-17T15:28:10 | 114,540,902 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 428 | py | #!/root/myenv1/bin python3.5
# -*- coding: utf-8 -*-
from haystack import indexes
from .models import Post
# 全文检索模块
class PostIndex(indexes.SearchIndex,indexes.Indexable):
text = indexes.CharField(document=True,use_template=True)
def get_model(self):
return Post
def index_queryset(self, using=None):
print(self.get_model().objects.all())
return self.get_model().objects.all() | [
"[email protected]"
] | |
5d077083bf21613f0ecaf29e149ad0d24d8c2b4b | 443f2d8ef26de8bd17512c64a9c1a7565cdb3f21 | /app/libs/redprint.py | bd3d0c8d73893f3928f7d4706b524d48048f3a43 | [] | no_license | AaronTesting/ginger | fc4040cedb782543440cb527b9206d5122b0f66d | f63bb8c20b1f92c8f4d015d4e330a28ab4acd08a | refs/heads/master | 2021-05-20T00:31:13.420675 | 2020-04-01T16:26:33 | 2020-04-01T16:26:33 | 252,108,175 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 671 | py | # -*- coding: utf-8 -*-
__author__ = 'Aaron'
__date__ = '2020/4/1 0001 17:20'
class Redprint:
def __init__(self, name):
self.name = name
self.mound = []
def route(self, rule, **options):
def decorator(f):
self.mound.append((f, rule, options))
return f
return decorator
def register(self, bp, url_prefix=None):
if url_prefix is None:
url_prefix = '/' + self.name
for f, rule, options in self.mound:
endpoint = self.name + '+' + \
options.pop("endpoint", f.__name__)
bp.add_url_rule(url_prefix + rule, endpoint, f, **options) | [
"[email protected]"
] | |
51dcaf59b1453a68599a83e6cda3997c59335edf | 3c157d4e652be07d867088387bfdd8b1b2b7560d | /example.py | 681b4fa6ac848842d49f21d1ba76a51aff95b5e6 | [
"MIT"
] | permissive | zotsing/WealthEngine-Python-SDK | 6b318ce085cc71a2d08f51d6ceb2534567c70c81 | f59801e0ac07030caca1f0aad5d21fe1937af22c | refs/heads/master | 2020-03-07T07:46:38.014486 | 2015-07-05T20:41:50 | 2015-07-05T20:41:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 974 | py | from wealthengine_python_sdk import WealthEngineClient
#Instantiate the WealtheEngine SDK with API Key and Environment
WeAPI = WealthEngineClient('ddb26e11-9348-4ead-9e2a-5a3b80a01b52', 'prod')
#Look up a WealthEngine Profile by email address
post_fields = {
"email": "[email protected]",
"first_name": "zack",
"last_name": "proser"
}
print WeAPI.getProfileByEmail(post_fields)
#Look up a WealthEngine profile by address
post_fields = {
"first_name": "Hamburt",
"last_name": "Porkington",
"address_line1": "756 Jambon Dr",
"city": "Baton Rouge",
"state": "LA",
"zip": 70801
}
print WeAPI.getProfileByAddress(post_fields)
#Look up a WealthEngine profile by phone number
post_fields = {
"first_name": "Hamburt",
"last_name": "Porkington",
"phone": "1231231234"
}
print WeAPI.getProfileByPhone(post_fields)
#Create a session - passing desired duration in milliseconds
post_fields = {
"duration": 7200
}
print WeAPI.createSession(post_fields)
| [
"[email protected]"
] | |
c48abf9be04d7fb8c779c33c68b4c60769dc4e78 | 2dff30dc6d6fbadf499b61fa0eb4b0b98459f278 | /chapter9/src/dict_comp.py | 5a685cb507c34a6dd7cc1d6b187beabe453c7128 | [] | no_license | Vignesh77/python-learning | 7133549123df24dc6e75114c858f58d38d064ec4 | ed4034aba0d17db1299aa9dcbdcb6f2014240892 | refs/heads/master | 2021-01-19T14:18:41.238465 | 2018-03-20T13:51:02 | 2018-03-20T13:51:02 | 88,144,674 | 0 | 0 | null | 2017-05-26T05:30:11 | 2017-04-13T08:49:47 | Python | UTF-8 | Python | false | false | 317 | py | """
@file :dict_comp.py
@brief :Create the dictionary dict_sample = {1:1, 2:2} using
dictionary comprehension
@author :vignesh
"""
def print_dict():
"""
function for creating dictionary
comprehension
"""
dict1 = {n:n for n in range(1, 11)}
print dict1
print_dict()
| [
"[email protected]"
] | |
3bb065239227e8de41c95b1c3570296e2f87de46 | 39aa8f4c6260b5307f1c427780ef462b7dfc751f | /data/actions/sum.py | 24c7b3713e47259c983426249e091278456898f9 | [] | no_license | ovkhasch/procflow | 51e66c8048292e64a9679da3432003c1a19276e7 | c58dcc538c54cbc876938254fa871cfda200d458 | refs/heads/master | 2022-11-17T00:00:15.814910 | 2020-07-08T07:44:34 | 2020-07-08T07:44:34 | 277,301,816 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 51 | py | res = arg1 + arg2
print(f'{arg1}+{arg2}={res}')
res | [
"[email protected]"
] | |
76820e8e2f4659673c77d3ece8a36ecaa9983766 | 12ceb4b82994048d1aa4561afc7e98b56a9b629d | /Hugo Bohácsek/mx_cif.py | c15f9130684738275789aadcaf7bd76452092b79 | [] | no_license | oguh43/bilicka | c5a3006f82cfcfec0d25bc012f6bdb7cc2877ceb | 8df20f487ad553f66b29004f2009a12819fe9cc6 | refs/heads/master | 2023-02-16T12:40:47.844257 | 2023-02-15T10:46:45 | 2023-02-15T10:46:45 | 220,057,073 | 8 | 1 | null | 2019-11-06T20:09:36 | 2019-11-06T17:52:33 | null | UTF-8 | Python | false | false | 199 | py | inp = list(input("Číselko? > "))
print(f'Najväčšia cifra je {max(inp)}!')
mx = 0
inp = map(int,inp)
for c in inp:
if c > mx:
mx = c
print(f'Najväčšia cifra je {mx}!')
| [
"[email protected]"
] | |
786aba9b3e6665e708a3db46f46a3a40c11ec478 | 224f314304bb3d6ae6c89d9a438233b740116323 | /versioningproj/versioningproj/wsgi.py | fadc28262c35e0e7ae3bff6b7a03fe53ce24d3cb | [] | no_license | thanhgit/backend-contest | 29f2b5a6947b2960759a41f7b7c8f46a244185fb | 4995210fab6d40bd05dd699386274db8dd6427ff | refs/heads/master | 2020-07-11T05:21:55.190418 | 2020-06-21T09:23:06 | 2020-06-21T09:23:06 | 204,455,094 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 405 | py | """
WSGI config for versioningproj 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.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'versioningproj.settings')
application = get_wsgi_application()
| [
"[email protected]"
] | |
e9e8cf762df89cb9437ef0b569dc75287034fb2a | 4c974c8bbb0c0b24db263f0db447fb92d7bc5cbd | /evaluations/evaluation_friends.py | eb63af40a183603c6106c4e3a21df6551aa70648 | [] | no_license | QualityMinds/classroom-reputation-simulator | 62aba472025de214bcab6b1105d442a573d462d0 | 36627c452a0a5d75db00d531e3891ed888e05c4f | refs/heads/master | 2020-03-11T09:21:47.064345 | 2018-05-24T07:54:08 | 2018-05-24T07:54:08 | 129,908,430 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,325 | py | from centrality.eigentrust import EigenTrust
from centrality.indegree import InDegree
from centrality.indegree_positive import InDegreePositive
from centrality.pagerank import PageRank
from evaluations.community.online_discussion_group import OnlineDiscussionGroup
from output.chart import chart
from output.metrics import print_metrics, print_stddev_metrics
from simulation.community import ActionProfile
from simulation.member import Member
if __name__ == '__main__':
"""
In this test, it is evaluated how many friends who are significantly less competent
than their peers are required to trick the system so that they reach top position
in the reputation ranking.
"""
test_name = "Friends"
community = OnlineDiscussionGroup()
ALL_CENTRALITY_SCORES = [
PageRank(),
EigenTrust(),
InDegree(),
InDegreePositive()
]
# Possible Actions
actions: ActionProfile = community.action_profile
# Group unaffiliated
num_unaffiliated = 25
unaffiliated = Member("unaffiliated", [
(0.27, actions.post_good_comment),
(0.03, actions.post_bad_comment),
(0.32, actions.vote_bad_comment_negative),
(0.03, actions.vote_any_comment_negative),
(0.32, actions.vote_good_comment_positive),
(0.03, actions.vote_any_comment_positive),
])
community.create_members_by_prototype(unaffiliated, num_unaffiliated)
# Group friends
friends = Member("f", [
(0.06, actions.post_good_comment),
(0.24, actions.post_bad_comment),
(0.7, actions.vote_good_comment_by_friend_positive),
])
friends.set_friends([num_unaffiliated, num_unaffiliated + 1])
community.create_members_by_prototype(friends, 2)
# Run
groups = ('f', 'unaffiliated')
colors = {'f': 'c', 'unaffiliated': 'b'}
results = community.simulate(ALL_CENTRALITY_SCORES, 100, 100)
for (name, result, intermediate_results) in results:
c = chart(result, groups, colors, test_name + " - " + name)
path = '{}-{}.png'.format(test_name, name)
c.savefig(path, bbox_inches='tight', dpi=400)
print("Saved " + path)
print_metrics(name, result, groups)
print_stddev_metrics(name, intermediate_results, groups) | [
"[email protected]"
] | |
b089325c3b000bf90d4528103da4c099ebdfef77 | 068d271e241d8cdb46dbf4243166e4b8ee7025b2 | /day05/day5/作业.py | 8002d8c0a0cc3a7e25803679291ab1221c2456f4 | [] | no_license | caiqinxiong/python | f6e226e76cb62aac970bcfbcb6c8adfc64858b60 | 9029f6c528d2cb742b600af224e803baa74cbe6a | refs/heads/master | 2023-05-26T19:41:34.911885 | 2020-05-15T09:02:08 | 2020-05-15T09:02:08 | 195,261,757 | 1 | 0 | null | 2021-06-10T23:33:33 | 2019-07-04T15:01:42 | JavaScript | UTF-8 | Python | false | false | 1,011 | py | # 1.注册一个账号,创建一个自己的博客主页
# 你的博客主页贴给我们的
# 每一周-两周 有一篇产出
# 2.递归函数 - 三级菜单
# 递归函数 - 二分查找
# 3.random 实现一个验证码,可以是4位或者6位,可以是纯数字,数字+字母
# 大作业:re模块和正则表达式 循环 不推荐用递归
exp = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
# exp = 2*3
# exp = 2+3
# exp = 2-3
# exp = 2/3
# 2+3*5
# print(eval(exp))
# 通过正则表达式 匹配出"内部不再有小括号的表达式" 9-10/3 + 7 /3*99/4*2998 +10 * 568/14
# 匹配第一个乘法或者除法 '2*5'
# 计算这个表达式的结果
# 循环一直到所有的乘除法都计算完毕
# 处理加减法
# 匹配第一个乘法或者除法 '2*5'
# 计算这个表达式的结果
# 循环一直到加减法也都计算完毕
# 基本需求 :只考虑整数 和 加减乘除四则运算
# 进阶需求 :考虑小数 和 加减乘除+() | [
"[email protected]"
] | |
c17e6e15b7fd656e21bd5cc3fdeef62ebc17e120 | 189a8025592f58dd0f0f90fe6197c0d7b865ea93 | /EulerFuncTester.py | 4b5ba9dc263d912542f971c38dba8f3faa13934f | [] | no_license | stepzhou/Project-Euler | 526c6c5085038f33cb72e444d46a442f6e9a3ab9 | e45db80cbdb87520e2264766b7913018995312c9 | refs/heads/master | 2021-01-19T11:26:16.631291 | 2012-10-16T19:19:37 | 2012-10-16T19:19:37 | 3,293,788 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 784 | py | '''
Created on Jan 8, 2012
@author: Admin
'''
import EulerFuncs
import timeit
def test_sieve_time():
TRIALS = 20
t = timeit.Timer("EulerFuncs.primes_below(1000000)", "import EulerFuncs")
print "Own: %.4f s/pass" % (t.timeit(number=TRIALS)/TRIALS)
t = timeit.Timer("EulerFuncs.primes_under(1000000)", "import EulerFuncs")
print "Old: %.4f s/pass" % (t.timeit(number=TRIALS)/TRIALS)
def test_pandigital():
print EulerFuncs.is_pandigital(12345678)
print EulerFuncs.is_pandigital(123456789)
print EulerFuncs.is_pandigital(1234567890)
print EulerFuncs.is_pandigital(203456789)
print EulerFuncs.is_pandigital(234567189)
if __name__ == "__main__":
print sum(EulerFuncs.primes_below(1000)[3:24])
print EulerFuncs.primes_below(1000)[23] | [
"[email protected]"
] | |
b1b7fad020c7a06528fed6a5731846ed727c0807 | 5bf5baf1bb79affd4756c1a6b40a8701ebef4cdb | /store/urls.py | 7ffc65c5a0376193b8f114567d631ed604ea18a2 | [] | no_license | sgithub99/E-Shop | 42b4144f37b7e3771cf3dbe5cb50ff340cc51477 | 6830bda9484f4964d5f0a0104b2d1c108186e30c | refs/heads/master | 2023-06-10T17:19:54.200585 | 2021-06-23T17:03:51 | 2021-06-23T17:03:51 | 378,679,007 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,267 | py | """Eshop 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
from .views.home import Index
from .views.signup import Signup
from .views.login import Login, logout
from .views.cart import Cart
from .views.checkout import CheckOut
from .views.order import OrderView
urlpatterns = [
path('', Index.as_view(), name='homepage'),
path('signup', Signup.as_view(), name='signup'),
path('login', Login.as_view(), name='login'),
path('logout', logout, name='logout'),
path('cart', Cart.as_view(), name='cart'),
path('check-out', CheckOut.as_view(), name='checkout'),
path('order', OrderView.as_view(), name='order')
]
| [
"[email protected]"
] | |
a406bd698bd55916814911f3075806d30eda981b | e177c23ce7763551ca6c0d0c763e26887e136a4e | /MoreExampleOfMouseEvent.py | d9df12aa31a647df547b18132c06b5ad64530201 | [] | no_license | happyiminjay1/PythonOpenCVPractice | 8786e46d9d3ef3b9acc08d878535e2e91159e99b | 2c4930b990ed5b9531f0b70e91bf3e3c0ad25cc5 | refs/heads/master | 2020-07-05T15:08:46.508950 | 2019-08-19T07:51:47 | 2019-08-19T07:51:47 | 202,681,274 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 536 | py | import numpy as np
import cv2
#events = [i for i in dir(cv2)]
#print(events)
def click_event(event,x,y,flags,param) :
if event == cv2.EVENT_LBUTTONDOWN:
cv2.circle(img,(x,y),3,(0,0,255),-1)
points.append((x,y))
if len(points) >= 2 :
cv2.line(img
cv2.imshow('image', img)
#img = np.zeros((512,512,3),np.uint8)
img = cv2.imread('lena.jpg')
cv2.imshow('image',img)
points = []
cv2.setMouseCallback('image',click_event) #windwo name should be same
cv2.waitKey(0)
cv2.destroyAllWindows()
| [
"[email protected]"
] | |
b6c7bba737c9ddcc917d06d094c7fb376bf00b31 | dcdeb1935f73fd5090a1f5146c0e0cd52b9803c5 | /main.py | 17815c158456469eb423f0bb73bcb9163d2aedb8 | [] | no_license | RetroDude128/EpicBot-Discord | d6a18f95217f5d7100fb8dc95d61c4a00fac292f | 5b763264d99c22f39df0ffa1abb75704058248ec | refs/heads/main | 2023-06-25T06:37:08.180569 | 2021-07-31T13:45:52 | 2021-07-31T13:45:52 | 391,253,960 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 299 | py | from discord.ext import commands
import discord
print("token?")
TOKEN = input()
I = 1
di = 1
prefix = "!"
bot = commands.Bot(prefix)
print("Bot is ready!")
@bot.command()
async def die(ctx):
await ctx.send("So you have chosen death")
print("Someone used the command [!die]")
bot.run(TOKEN)
| [
"[email protected]"
] | |
3efd5fde40d40b037e28cde351d3d54173d164f9 | 3cdd026cb269ca0c009016500cd2ba09655a6de6 | /server/instapic/tests/test_user.py | 4517ca9dd2a83a74a4facd275dd6c9aa3d1e5882 | [] | no_license | mileswong/instapic | 3034e7c768426dc4973dd65a0c7fde7695cfaf85 | 335229200e70e21d76495f36998b56deee6fc55c | refs/heads/master | 2022-03-02T23:32:01.314901 | 2019-05-28T14:54:42 | 2019-05-29T06:03:17 | 188,964,347 | 0 | 0 | null | 2022-02-10T17:50:42 | 2019-05-28T06:05:22 | JavaScript | UTF-8 | Python | false | false | 2,950 | py | import pytest
import logging
import json
from instapic.models import db, User
from instapic.config import Config
from flask_jwt_extended import (
create_access_token,
create_refresh_token,
)
def get_test_client(app):
return app.test_client()
def post_client(client, url, data=None, headers=None):
return client.post(url,
data=json.dumps(data),
content_type='application/json',
headers=headers)
def signup_user(client, username, password):
return post_client(client=client,
url='/v1/users/signup',
data=dict(username=username,
password=password))
def login_user(client, username, password):
return post_client(client=client,
url='/v1/users/login',
data=dict(username=username,
password=password))
def refresh_user(client, headers):
return post_client(client=client,
url='v1/users/refresh',
headers=headers)
def test_user(app):
client = get_test_client(app)
username = 'Edwin'
password = '123456'
# First signup
res = signup_user(client, username, password)
user = json.loads(res.data)['user']
user_id = user['id']
assert user['username'] == username
# Attempt to signup with the same username
res = signup_user(client, username, password)
message = json.loads(res.data)['message']
assert message == 'ERR_USERNAME_IS_USED'
# Attempt to signup with invalid type
res = signup_user(client, username, 500)
message = json.loads(res.data)['message']
assert message == 'INVALID_PAYLOAD'
# Successfully login with the same credentials
res = login_user(client, username, password)
user = json.loads(res.data)['user']
assert user['id'] == user_id
assert user['username'] == username
# Attempt to login with incorrect password
res = login_user(client, username, 'i_am_a_wrong_password')
message = json.loads(res.data)['message']
assert message == 'ERR_INVALID_USERNAME_OR_PASSWORD'
# Successfully refresh user token
identity = { "id": user_id, "username": "Edwin" }
refresh_token = create_refresh_token(identity=identity)
access_token = create_access_token(identity=identity)
headers = {
'Authorization': 'Bearer {}'.format(refresh_token)
}
res = refresh_user(client, headers)
assert user_id == json.loads(res.data)['id']
assert username == json.loads(res.data)['username']
# Successfully get user post of empty list
res = client.get('v1/users/{user_id}/posts'.format(user_id=user_id))
posts = json.loads(res.data)['posts']
assert len(posts) == 0
# No posts in db
res = app.test_client().get('/v1/posts')
posts = json.loads(res.data)['posts']
assert len(posts) == 0
| [
"[email protected]"
] | |
6911200ffb465a9a5709a7ade0f83c5c5ac558b3 | f880f230f90241dbfd2e729c02cf329ad27ca082 | /lab1/graph_results.py | a6230876d1d8161c40f161892010a08c76d1086e | [] | no_license | c-brenn/conc_sys_labs | bc666ec1870e8fea07557af785b58f9e24c0fbd7 | 24b21dd780b9a17b32a8125895f06c6d8af32549 | refs/heads/master | 2016-09-08T02:38:01.893716 | 2015-03-04T23:12:06 | 2015-03-04T23:12:06 | 30,213,969 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 788 | py | import matplotlib.pyplot as pyplot
import json
import sys
#get the name of the file containing
#the results to be plotted
file_name = sys.argv[1]
#open the file and load the contents as JSON
data = open(file_name, 'r')
data = data.read()
results = json.loads(data)
#extract the x and y values to plot
x = results['x']
y = results['y']
#get the number of cores
cpu_count = results['cpu_count']
#plot the x values against the y values
pyplot.plot(x,y)
#label the axes
pyplot.ylabel('time (sec)')
pyplot.xlabel('threads used')
#set the scale on the axes
pyplot.axis([1, len(x), 0, max(y) + min(y)], 'o')
#add a vertical line at 'cpu_count'
pyplot.axvline(cpu_count, color='r')
#add a title and display the plot
pyplot.title('A plot of time vs threads used to calculate pi')
pyplot.show() | [
"[email protected]"
] | |
1e2311f171807948b3c2b3e2d22c964acf347270 | aa52f688fc9203d4dc78c8a80b6938ef385780b5 | /week6/Lecture_6/printing_to_binary.py | 8e123059e9deb4ab2312189b818c42647d964bb3 | [] | no_license | mohitKhanna1411/COMP9021-Principles-of-Programming-1 | 9ec91753de914b1ed3abb72468a66ce0cac9224a | f04dec815e0c8a29a86e7ab2bdd2d6d0f5d0558f | refs/heads/master | 2020-08-31T20:32:38.336752 | 2018-09-11T10:36:11 | 2018-09-11T10:36:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,367 | py | # Prints out the representation of a nonnegative number in base 2,
# using two recursive procedures, one of which is tail-recursive.
#
# Written by Eric Martin for COMP9021
def print_binary_representation_1(n):
'''
>>> print_binary_representation_1(0)
0
>>> print_binary_representation_1(1)
1
>>> print_binary_representation_1(2)
10
>>> print_binary_representation_1(5)
101
>>> print_binary_representation_1(23)
10111
'''
_print_binary_representation_1(n)
print()
def _print_binary_representation_1(n):
if n >= 2:
_print_binary_representation_1(n // 2)
print(n % 2, end = '')
def print_binary_representation_2(n):
'''
>>> print_binary_representation_1(0)
0
>>> print_binary_representation_1(1)
1
>>> print_binary_representation_1(2)
10
>>> print_binary_representation_1(5)
101
>>> print_binary_representation_1(23)
10111
'''
_print_binary_representation_2(n, n.bit_length() - 1)
def _print_binary_representation_2(n, exp):
if exp < 0:
print()
if 2 ** exp <= n:
print(1, end = '')
_print_binary_representation_2(n - 2 ** exp, exp - 1)
else:
print(0, end = '')
_print_binary_representation_2(n, exp - 1)
if __name__ == '__main__':
import doctest
doctest.testmod()
| [
"[email protected]"
] | |
d05a52b546234ab73ee386e23bc8b67c8fd8b956 | fdf946b10a1478ea490e96d22bb4b04be30d0f39 | /flask_demo/1_get_hello_world.py | 34af100f93a44156b5fa044af6fb850e88a94ab2 | [] | no_license | ermakovpetr/rsoi | b27ae054bb7a6f0ea2fda74893025ce0f3accfd2 | 23f680d0090a8353621151b2872a22466fa82e92 | refs/heads/master | 2021-01-22T22:53:07.938139 | 2015-10-05T16:38:16 | 2015-10-05T16:38:16 | 35,239,405 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 186 | py | # coding=utf-8
from flask import Flask
app = Flask(__name__)
@app.route('/hello_world')
def hello_world():
return 'hello world'
if __name__ == '__main__':
app.run(debug=True)
| [
"[email protected]"
] | |
b9e27aec2cd9a9e2fa16db440f40306ebc490801 | 2db9b4efc9a5f62213e18d0241f3179916b8a5de | /using-python-to-access-web-data/extensible_markup_language(XML)_chapter13/parsing_XML.py | 1d59bba777cc88cc443846f21d3b9170a1837f71 | [] | no_license | Pratimathulung/python-tutorial | 52ced7b40087e1791a94cc5d52eee2a1f2505dd9 | 4d0136d849c6bd784181fb85ca4943a86d5b1d8d | refs/heads/master | 2020-03-20T22:59:09.199034 | 2019-01-25T18:48:55 | 2019-01-25T18:48:55 | 137,824,110 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 759 | py | import xml.etree.ElementTree as ET
# data = '''<person>
# <name>Pratima</name>
# <phone type="intl">
# +17039609603
# </phone>
# <email hide="yes"/>
# </person>'''
#
# tree = ET.fromstring(data)
# print('Name:', tree.find('name').text)
# print('Attr:', tree.find('email').get('hide'))
input = '''<stuff>
<users>
<user x='2'>
<id>001</id>
<name>Pratima</name>
</user>
<user x='3'>
<id>007</id>
<name>Yogen</name>
</user>
</users>
</stuff>'''
stuff = ET.fromstring(input)
lst = stuff.findall('users/user')
print('User count:',len(lst))
for item in lst:
print('Name:',item.find('name').text)
print('Id:',item.find('id').text)
print('Attribute:',item.get('x')) | [
"[email protected]"
] | |
4559d843f122d32a32c92fec1111354c7de91b94 | 24046530f58ecb5f90cdf65e8fb65a3135e4615f | /src/server_test.py | 911bad81fc2366d8b78225c0371a840577e56449 | [] | no_license | HappyYusuke/door_open_ver2 | d73d1c89e910fbb3877a3d053fe7c73674a85820 | 600f5cbf1e0016848c73e31bea637d38dca028a3 | refs/heads/main | 2023-06-30T18:05:09.290460 | 2021-08-04T11:07:12 | 2021-08-04T11:07:12 | 392,164,640 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,728 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#----------------------------------------------------------------------
#Title: door_open_ver2のサービスサーバ
#Author: Kanazawa Yusuke
#Data: 2021/7/2
#memo: サービスサーバーから進行速度、入室してからの進行距離を指定できる
#----------------------------------------------------------------------
import rospy
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist
from door_open_ver2.srv import door_open_ver2
from door_open_ver2.srv import door_open_ver2Response
MAX_LINER_VELOCITY = 0.23
MIN_LINER_VELOCITY = 0.0
MAX_PROCRESS_DISTANCE = 10.0
MIN_PROGRESS_DISTANCE = 0.0
def value_set(request):
vel = Twist()
is_set_success = True
if request.linear_vel <= MAX_LINER_VELOCITY and (request.linear_vel >= MIN_LINER_VELOCITY):
vel.linear.x = request.linear_vel
else:
is_set_success = False
if request.target_dist <= MAX_PROCRESS_DISTANCE and (request.target_dist >= MIN_PROGRESS_DISTANCE):
target_dist = request.target_dist
else:
is_set_success = False
if is_set_success:
time = request.target_dist / request.linear_vel
start_time = rospy.get_time()
while not rospy.is_shutdown() and (rospy.get_time() - start_time) <= time:
print('now_time = ', rospy.get_time() - start_time)
pub.publish(vel)
return door_open_ver2Response(result = is_set_success)
if __name__ == '__main__':
rospy.init_node('door_open_server_test')
pub = rospy.Publisher('/mobile_base/commands/velocity',Twist, queue_size = 10)
service_server = rospy.Service('door_open_ver2', door_open_ver2, value_set)
rospy.spin()
| [
"[email protected]"
] | |
9cf1e8ef1a108dc58dd252619ae16129a83d49ed | ca58f8e1696e6275116dfb3eea68ff17eec3bbe1 | /PyQt5开发与实战(网易云课堂)/src/dialogs/QFileDialogDemo.py | d43697b37326b45d10d3714df30cc967736fd162 | [] | no_license | piperpi/python_book_code | 9b8f99d08ed9840d34389aa008fd9ff5fd15e1ae | 19d35e33624923a764711469bed9006549a59d52 | refs/heads/master | 2022-07-15T05:34:53.226952 | 2020-06-30T10:20:40 | 2020-06-30T10:20:40 | 217,888,567 | 3 | 2 | null | 2022-07-06T20:42:49 | 2019-10-27T17:10:00 | Python | UTF-8 | Python | false | false | 1,525 | py | '''
文件对话框:QFileDialog
'''
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class QFileDialogDemo(QWidget):
def __init__(self):
super(QFileDialogDemo,self).__init__()
self.initUI()
def initUI(self):
layout = QVBoxLayout()
self.button1 = QPushButton('加载图片')
self.button1.clicked.connect(self.loadImage)
layout.addWidget(self.button1)
self.imageLabel = QLabel()
layout.addWidget(self.imageLabel)
self.button2 = QPushButton('加载文本文件')
self.button2.clicked.connect(self.loadText)
layout.addWidget(self.button2)
self.contents = QTextEdit()
layout.addWidget(self.contents)
self.setLayout(layout)
self.setWindowTitle('文件对话框演示 ')
def loadImage(self):
fname,_ = QFileDialog.getOpenFileName(self,'打开文件','.','图像文件(*.jpg *.png)')
self.imageLabel.setPixmap(QPixmap(fname))
def loadText(self):
dialog = QFileDialog()
dialog.setFileMode(QFileDialog.AnyFile)
dialog.setFilter(QDir.Files)
if dialog.exec():
filenames = dialog.selectedFiles()
f = open(filenames[0],encoding='utf-8',mode='r')
with f:
data = f.read()
self.contents.setText(data)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = QFileDialogDemo()
main.show()
sys.exit(app.exec_()) | [
"[email protected]"
] | |
d0628825b606d2a282727436ee6ae01b097cec5d | 11ba1df6ef160aea4459e1f98cd44d3232647ff8 | /game_stats.py | ca15ebfba0c9ca267b4d1d80fcfb2619f5893901 | [] | no_license | frankTheCodeBoy/PYGAME_GAME_DEVELOPMENT | ddd4d79eea94bd3b40d2fa392277491809453662 | 1a58123e39b02ed559fc33583ac71a14a7cfc8d3 | refs/heads/main | 2023-03-21T14:19:03.934349 | 2021-03-12T13:49:11 | 2021-03-12T13:49:11 | 343,720,872 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 639 | py | class GameStats:
"""Track statistics for Alien Invasion."""
def __init__(self,first_play):
"""Initialize statistics."""
self.settings = first_play.settings
self.reset_stats()
# Start game in an inactive state.
self.game_active = False
# High score should never be reset
import json
with open("high_scores.json",'r') as f:
self.high_score = json.load(f)
def reset_stats(self):
"""Initialize statistics that can change during the game"""
self.goku_left = self.settings.goku_lives
self.score = 0
self.level = 1
| [
"[email protected]"
] | |
40ceb780fe2991fec43e0dd14528fcefa02c234d | 82ed7d2c21c5576a193ceafd30e74c1c48c6ad47 | /max2cookie.py | d9fc37a423ef25d599571340fe4e9529f59df740 | [] | no_license | alixedi/Max2Cookie | 4483d45b3588e081334f7a95e4c9cc1866868237 | ab42bb2a9ea9bc8a4109eed645f6051ec6def44e | refs/heads/master | 2016-08-03T18:46:24.365224 | 2014-12-12T13:05:37 | 2014-12-12T13:05:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,746 | py | """
max_to_cookie
=============
Usage
-----
max_to_cookie.py <project_path> <stem_name>
Where:
<project>: Name of the project directory that is generated using the MaxIDE.
<stem_name>: Value of one of the fields in the project creation dialogue. At the moment, for simplicity, we do not support override of naming options.
About
-----
This is a quick and dirty script I have written for automatically creating cokiecutter templates out of regular MaxCompiler project. You can find out more about
cookiecutter [here](https://github.com/audreyr/cookiecutter).
The logic of project creation which has been automated in this script is based on reverse-engineering - I generated a few project by selecting various options,
and diff-ed the project folders to get an idea of what went on behind the scenes. As a result, the correctness of this script is questionable at the moment.
"""
import os, sys
import shutil
project = sys.argv[1]
stem = sys.argv[2]
# try and copy the cpu code template with all the slic interfaces
print 'Copying CpuCode template...'
shutil.copyfile(os.path.join('./templates', 'CpuCode.c'), os.path.join('./' + project, 'CPUCode/' + stem + 'CpuCode.c'))
print 'Done.'
# try and copy the manager code template with standard as well as custom manager
print 'Coping ManagerCode template...'
shutil.copyfile(os.path.join('./templates', 'Manager.maxj'), os.path.join('./' + project, 'EngineCode/src/' + stem.lower() + '/' + stem + 'Manager.maxj'))
print 'Done.'
# try and replace project name with context variable
print 'Replacing project name with {{cookiecutter.project_name}}...'
os.system('grep -rl %s ./ | xargs sed -i "s/%s/{{cookiecutter.project_name}}/g"' % (project, project))
print 'Done.'
#try and replace {{cookiecutter.dfe_model}} with context variable
print 'Replacing {{cookiecutter.dfe_model}} with {{cookiecutter.dfe_model}}...'
os.system('grep -rl {{cookiecutter.dfe_model}} ./ | xargs sed -i "s/{{cookiecutter.dfe_model}}/{{cookiecutter.dfe_model}}/g"')
print 'Done.'
# try and replace stem name with context variable
print 'Replaceing given stem name with {{cookiecutter.stem_name}}'
os.system('grep -rl %s ./ | xargs sed -i "s/%s/{{cookiecutter.stem_name}}/g"' % (stem, stem))
print 'Done.'
# try and replace stem name lower with context variable
print 'Replacing given stem name (lowercase) with {{cookiecutter.stem_name|lower}}...'
os.system('grep -rl %s ./ | xargs sed -i "s/%s/{{cookiecutter.stem_name|lower}}/g"' % (stem.lower(), stem.lower()))
print 'Done.'
# try and replace the mpcx setting with context variable
print 'Replacing enableMPCX setting with template logic...'
os.system('grep -rl "<enableMPCX enabled=\\"false\\"/>" ./ | xargs sed -i "s@<enableMPCX enabled=\\"false\\"/>@<enableMPCX enabled=\\"{% if cookiecutter.optimize_for_mpcx %}true{% else %}false{% endif %}\\"/>@g"')
print 'Done.'
# try and rename all the files now
print 'Replacing files names containing stem name with {{cookiecutter.stem_name}}...'
for root, dirs, files in os.walk("./" + project):
for x in files:
if stem in x:
os.rename(os.path.join(root, x), os.path.join(root, x.replace(stem, '{{cookiecutter.stem_name}}')))
print 'Done.'
# try and rename all the directories
print 'Replacing directory names containint stem name (lowercase) with {{cookiecutter.stem_name|lower}}'
for root, dirs, files in os.walk("./" + project):
for x in dirs:
if stem.lower() in x:
os.rename(os.path.join(root, x), os.path.join(root, x.replace(stem.lower(), '{{cookiecutter.stem_name|lower}}')))
print 'Done.'
# try and rename the whole project folder
print 'Renaming project folder...'
os.rename('./' + project, '{{cookiecutter.project_name}}')
print 'Done.'
| [
"[email protected]"
] | |
15bd7ffc90a297cef5a326704f3d014f642e5396 | 006341ca12525aa0979d6101600e78c4bd9532ab | /CMS/Zope-3.2.1/Dependencies/twisted-Zope-3.2.1/twisted/internet/iocpreactor/ops.py | ab8211afcfdec329364da2053fefe05b753acb86 | [
"ZPL-2.1",
"Python-2.0",
"ICU",
"LicenseRef-scancode-public-domain",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"ZPL-2.0",
"MIT"
] | permissive | germanfriday/code-examples-sandbox | d0f29e20a3eed1f8430d06441ac2d33bac5e4253 | 4c538584703754c956ca66392fdcecf0a0ca2314 | refs/heads/main | 2023-05-30T22:21:57.918503 | 2021-06-15T15:06:47 | 2021-06-15T15:06:47 | 377,200,448 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,752 | py | # Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
import struct, socket, os, errno
#import time
from twisted.internet import error
from twisted.python import failure
from _iocp import have_connectex
SO_UPDATE_ACCEPT_CONTEXT = 0x700B
SO_UPDATE_CONNECT_CONTEXT = 0x7010
ERROR_CONNECTION_REFUSED = 1225
winerrcodeMapping = {ERROR_CONNECTION_REFUSED: errno.WSAECONNREFUSED}
class OverlappedOp:
def __init__(self, transport):
from twisted.internet import reactor
self.reactor = reactor
self.transport = transport
def ovDone(self, ret, bytes, arg):
raise NotImplementedError
def initiateOp(self):
raise NotImplementedError
class ReadFileOp(OverlappedOp):
def ovDone(self, ret, bytes, (handle, buffer)):
if ret or not bytes:
self.transport.readErr(ret, bytes)
else:
self.transport.readDone(bytes)
def initiateOp(self, handle, buffer):
self.reactor.issueReadFile(handle, buffer, self.ovDone, (handle, buffer))
class WriteFileOp(OverlappedOp):
def ovDone(self, ret, bytes, (handle, buffer)):
# log.msg("WriteFileOp.ovDone", time.time())
if ret or not bytes:
self.transport.writeErr(ret, bytes)
else:
self.transport.writeDone(bytes)
def initiateOp(self, handle, buffer):
# log.msg("WriteFileOp.initiateOp", time.time())
self.reactor.issueWriteFile(handle, buffer, self.ovDone, (handle, buffer))
class WSASendToOp(OverlappedOp):
def ovDone(self, ret, bytes, (handle, buffer)):
if ret or not bytes:
self.transport.writeErr(ret, bytes)
else:
self.transport.writeDone(bytes)
def initiateOp(self, handle, buffer, addr):
max_addr, family, type, protocol = self.reactor.getsockinfo(handle)
self.reactor.issueWSASendTo(handle, buffer, family, addr, self.ovDone, (handle, buffer))
class WSARecvFromOp(OverlappedOp):
def ovDone(self, ret, bytes, (handle, buffer, ab)):
if ret or not bytes:
self.transport.readErr(ret, bytes)
else:
self.transport.readDone(bytes, self.reactor.interpretAB(ab))
def initiateOp(self, handle, buffer):
ab = self.reactor.AllocateReadBuffer(1024)
self.reactor.issueWSARecvFrom(handle, buffer, ab, self.ovDone, (handle, buffer, ab))
class AcceptExOp(OverlappedOp):
def ovDone(self, ret, bytes, (handle, buffer, acc_sock)):
if ret == 64: # ERROR_NETNAME_DELETED
# yay, recursion
self.initiateOp(handle)
elif ret:
self.transport.acceptErr(ret, bytes)
else:
try:
acc_sock.setsockopt(socket.SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, struct.pack("I", handle))
except socket.error, se:
self.transport.acceptErr(ret, bytes)
else:
self.transport.acceptDone(acc_sock, acc_sock.getpeername())
def initiateOp(self, handle):
max_addr, family, type, protocol = self.reactor.getsockinfo(handle)
acc_sock = socket.socket(family, type, protocol)
buffer = self.reactor.AllocateReadBuffer(max_addr*2 + 32)
self.reactor.issueAcceptEx(handle, acc_sock.fileno(), self.ovDone, (handle, buffer, acc_sock), buffer)
class ConnectExOp(OverlappedOp):
def ovDone(self, ret, bytes, (handle, sock)):
if ret:
# print "ConnectExOp err", ret
self.transport.connectErr(failure.Failure(error.errnoMapping.get(winerrcodeMapping.get(ret), error.ConnectError)())) # finish the mapping in error.py
else:
if have_connectex:
try:
sock.setsockopt(socket.SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, "")
except socket.error, se:
self.transport.connectErr(failure.Failure(error.ConnectError()))
self.transport.connectDone()
def threadedDone(self, _):
self.transport.connectDone()
def threadedErr(self, err):
self.transport.connectErr(err)
def initiateOp(self, sock, addr):
handle = sock.fileno()
if have_connectex:
max_addr, family, type, protocol = self.reactor.getsockinfo(handle)
self.reactor.issueConnectEx(handle, family, addr, self.ovDone, (handle, sock))
else:
from twisted.internet.threads import deferToThread
d = deferToThread(self.threadedThing, sock, addr)
d.addCallback(self.threadedDone)
d.addErrback(self.threadedErr)
def threadedThing(self, sock, addr):
res = sock.connect_ex(addr)
if res:
raise error.getConnectError((res, os.strerror(res)))
| [
"[email protected]"
] | |
f3d4bbace67d36667abafa32f72fc581eac19388 | 62e53c576274ef8734300c44edb00f857e01b9cc | /utils/coco_utils.py | e51aec46956f1c61893c9dc85b36684688d82d87 | [] | no_license | dmatos2012/torch-object-detection | ca26457df050d35255aca71a0a3fa9b67297442c | de1ff8fe55d40a185ef6a6748485993ca0ce0959 | refs/heads/master | 2023-07-25T11:08:51.627728 | 2021-08-24T11:56:06 | 2021-08-24T11:56:06 | 380,284,151 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,078 | py | # Taken from https://github.com/pytorch/vision/blob/master/references/detection/coco_utils.py
# Modified slightly to fit my needs
import copy
import numpy as np
import torch
import torch.utils.data
import torchvision
from pycocotools import mask as coco_mask
from pycocotools.coco import COCO
class FilterAndRemapCocoCategories(object):
def __init__(self, categories, remap=True):
self.categories = categories
self.remap = remap
def __call__(self, image, target):
anno = target["annotations"]
anno = [obj for obj in anno if obj["category_id"] in self.categories]
if not self.remap:
target["annotations"] = anno
return image, target
anno = copy.deepcopy(anno)
for obj in anno:
obj["category_id"] = self.categories.index(obj["category_id"])
target["annotations"] = anno
return image, target
def convert_coco_poly_to_mask(segmentations, height, width):
masks = []
for polygons in segmentations:
rles = coco_mask.frPyObjects(polygons, height, width)
mask = coco_mask.decode(rles)
if len(mask.shape) < 3:
mask = mask[..., None]
mask = torch.as_tensor(mask, dtype=torch.uint8)
mask = mask.any(dim=2)
masks.append(mask)
if masks:
masks = torch.stack(masks, dim=0)
else:
masks = torch.zeros((0, height, width), dtype=torch.uint8)
return masks
class ConvertCocoPolysToMask(object):
def __call__(self, image, target):
w, h = image.size
image_id = target["image_id"]
image_id = torch.tensor([image_id])
anno = target["annotations"]
anno = [obj for obj in anno if obj["iscrowd"] == 0]
boxes = [obj["bbox"] for obj in anno]
# guard against no boxes via resizing
boxes = torch.as_tensor(boxes, dtype=torch.float32).reshape(-1, 4)
boxes[:, 2:] += boxes[:, :2]
boxes[:, 0::2].clamp_(min=0, max=w)
boxes[:, 1::2].clamp_(min=0, max=h)
classes = [obj["category_id"] for obj in anno]
classes = torch.tensor(classes, dtype=torch.int64)
segmentations = [obj["segmentation"] for obj in anno]
masks = convert_coco_poly_to_mask(segmentations, h, w)
keypoints = None
if anno and "keypoints" in anno[0]:
keypoints = [obj["keypoints"] for obj in anno]
keypoints = torch.as_tensor(keypoints, dtype=torch.float32)
num_keypoints = keypoints.shape[0]
if num_keypoints:
keypoints = keypoints.view(num_keypoints, -1, 3)
keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
boxes = boxes[keep]
classes = classes[keep]
masks = masks[keep]
if keypoints is not None:
keypoints = keypoints[keep]
target = {}
target["boxes"] = boxes
target["labels"] = classes
target["masks"] = masks
target["image_id"] = image_id
if keypoints is not None:
target["keypoints"] = keypoints
# for conversion to coco api
area = torch.tensor([obj["area"] for obj in anno])
iscrowd = torch.tensor([obj["iscrowd"] for obj in anno])
target["area"] = area
target["iscrowd"] = iscrowd
return image, target
def _coco_remove_images_without_annotations(dataset, cat_list=None):
def _has_only_empty_bbox(anno):
return all(any(o <= 1 for o in obj["bbox"][2:]) for obj in anno)
def _count_visible_keypoints(anno):
return sum(sum(1 for v in ann["keypoints"][2::3] if v > 0) for ann in anno)
min_keypoints_per_image = 10
def _has_valid_annotation(anno):
# if it's empty, there is no annotation
if len(anno) == 0:
return False
# if all boxes have close to zero area, there is no annotation
if _has_only_empty_bbox(anno):
return False
# keypoints task have a slight different critera for considering
# if an annotation is valid
if "keypoints" not in anno[0]:
return True
# for keypoint detection tasks, only consider valid images those
# containing at least min_keypoints_per_image
if _count_visible_keypoints(anno) >= min_keypoints_per_image:
return True
return False
assert isinstance(dataset, torchvision.datasets.CocoDetection)
ids = []
for ds_idx, img_id in enumerate(dataset.ids):
ann_ids = dataset.coco.getAnnIds(imgIds=img_id, iscrowd=None)
anno = dataset.coco.loadAnns(ann_ids)
if cat_list:
anno = [obj for obj in anno if obj["category_id"] in cat_list]
if _has_valid_annotation(anno):
ids.append(ds_idx)
dataset = torch.utils.data.Subset(dataset, ids)
return dataset
def convert_to_coco_api(ds):
coco_ds = COCO()
# annotation IDs need to start at 1, not 0, see torchvision issue #1530
ann_id = 1
dataset = {"images": [], "categories": [], "annotations": []}
categories = set()
for img_idx in range(len(ds)):
# find better way to get target
# targets = ds.get_annotations(img_idx)
img, targets = ds[img_idx]
image_id = targets["img_idx"].item()
img_dict = {}
img_dict["id"] = image_id
img_dict["height"] = img.shape[-2]
img_dict["width"] = img.shape[-1]
dataset["images"].append(img_dict)
bboxes = targets["boxes"]
bboxes[:, 2:] -= bboxes[:, :2]
# bboxes = bboxes.tolist()
labels = targets["labels"].tolist()
# areas = np.array((bboxes[:, 2] - bboxes[:, 0]) * (bboxes[:, 3] - bboxes[:, 1]))
areas = bboxes[:, 2] * bboxes[:, 3]
# areas = targets['area'].tolist()
areas = areas.tolist()
bboxes = bboxes.tolist()
iscrowd = np.zeros((len(bboxes))).tolist()
# iscrowd = targets['iscrowd'].tolist()
if "masks" in targets:
masks = targets["masks"]
# make masks Fortran contiguous for coco_mask
masks = masks.permute(0, 2, 1).contiguous().permute(0, 2, 1)
if "keypoints" in targets:
keypoints = targets["keypoints"]
keypoints = keypoints.reshape(keypoints.shape[0], -1).tolist()
num_objs = len(bboxes)
for i in range(num_objs):
ann = {}
ann["image_id"] = image_id
ann["bbox"] = bboxes[i]
ann["category_id"] = labels[i]
categories.add(labels[i])
ann["area"] = areas[i]
ann["iscrowd"] = iscrowd[i]
ann["id"] = ann_id
if "masks" in targets:
ann["segmentation"] = coco_mask.encode(masks[i].numpy())
if "keypoints" in targets:
ann["keypoints"] = keypoints[i]
ann["num_keypoints"] = sum(k != 0 for k in keypoints[i][2::3])
dataset["annotations"].append(ann)
ann_id += 1
dataset["categories"] = [{"id": i} for i in sorted(categories)]
coco_ds.dataset = dataset
coco_ds.createIndex()
return coco_ds
def get_coco_api_from_dataset(dataset):
for _ in range(10):
if isinstance(dataset, torchvision.datasets.CocoDetection):
break
if isinstance(dataset, torch.utils.data.Subset):
dataset = dataset.dataset
if isinstance(dataset, torchvision.datasets.CocoDetection):
return dataset.coco
return convert_to_coco_api(dataset)
class CocoDetection(torchvision.datasets.CocoDetection):
def __init__(self, img_folder, ann_file, transforms):
super(CocoDetection, self).__init__(img_folder, ann_file)
self._transforms = transforms
def __getitem__(self, idx):
img, target = super(CocoDetection, self).__getitem__(idx)
image_id = self.ids[idx]
target = dict(image_id=image_id, annotations=target)
if self._transforms is not None:
img, target = self._transforms(img, target)
return img, target
| [
"[email protected]"
] | |
f4181c7e25478f21c87d670378495933b5304fb8 | f3b233e5053e28fa95c549017bd75a30456eb50c | /CDK2_input/L30/30-26_MD_NVT_rerun/set_4.py | 8cf73f4cd9548453c53991a4c27c186eeea9f7b8 | [] | no_license | AnguseZhang/Input_TI | ddf2ed40ff1c0aa24eea3275b83d4d405b50b820 | 50ada0833890be9e261c967d00948f998313cb60 | refs/heads/master | 2021-05-25T15:02:38.858785 | 2020-02-18T16:57:04 | 2020-02-18T16:57:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 740 | py | import os
dir = '/mnt/scratch/songlin3/run/CDK2/L30/MD_NVT_rerun/ti_one-step/30_26/'
filesdir = dir + 'files/'
temp_prodin = filesdir + 'temp_prod_4.in'
temp_pbs = filesdir + 'temp_4.pbs'
lambd = [ 0.00922, 0.04794, 0.11505, 0.20634, 0.31608, 0.43738, 0.56262, 0.68392, 0.79366, 0.88495, 0.95206, 0.99078]
for j in lambd:
os.chdir("%6.5f" %(j))
workdir = dir + "%6.5f" %(j) + '/'
#prodin
prodin = workdir + "%6.5f_prod_4.in" %(j)
os.system("cp %s %s" %(temp_prodin, prodin))
os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, prodin))
#PBS
pbs = workdir + "%6.5f_4.pbs" %(j)
os.system("cp %s %s" %(temp_pbs, pbs))
os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, pbs))
#submit pbs
#os.system("qsub %s" %(pbs))
os.chdir(dir)
| [
"[email protected]"
] | |
fb8191dad12514eabd745e1a21bf0a4e1f269672 | c1960138a37d9b87bbc6ebd225ec54e09ede4a33 | /adafruit-circuitpython-bundle-py-20210402/lib/adafruit_sgp30.py | 4a58560aa73b763fdcb32ad065a5317380db7802 | [] | no_license | apalileo/ACCD_PHCR_SP21 | 76d0e27c4203a2e90270cb2d84a75169f5db5240 | 37923f70f4c5536b18f0353470bedab200c67bad | refs/heads/main | 2023-04-07T00:01:35.922061 | 2021-04-15T18:02:22 | 2021-04-15T18:02:22 | 332,101,844 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,228 | py | # SPDX-FileCopyrightText: 2017 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_sgp30`
====================================================
I2C driver for SGP30 Sensirion VoC sensor
* Author(s): ladyada
Implementation Notes
--------------------
**Hardware:**
* Adafruit `SGP30 Air Quality Sensor Breakout - VOC and eCO2
<https://www.adafruit.com/product/3709>`_ (Product ID: 3709)
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the ESP8622 and M0-based boards:
https://github.com/adafruit/circuitpython/releases
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
"""
import time
from adafruit_bus_device.i2c_device import I2CDevice
from micropython import const
__version__ = "2.3.4"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_SGP30.git"
_SGP30_DEFAULT_I2C_ADDR = const(0x58)
_SGP30_FEATURESETS = (0x0020, 0x0022)
_SGP30_CRC8_POLYNOMIAL = const(0x31)
_SGP30_CRC8_INIT = const(0xFF)
_SGP30_WORD_LEN = const(2)
class Adafruit_SGP30:
"""
A driver for the SGP30 gas sensor.
"""
def __init__(self, i2c, address=_SGP30_DEFAULT_I2C_ADDR):
"""Initialize the sensor, get the serial # and verify that we found a proper SGP30"""
self._device = I2CDevice(i2c, address)
# get unique serial, its 48 bits so we store in an array
self.serial = self._i2c_read_words_from_cmd([0x36, 0x82], 0.01, 3)
# get featureset
featureset = self._i2c_read_words_from_cmd([0x20, 0x2F], 0.01, 1)
if featureset[0] not in _SGP30_FEATURESETS:
raise RuntimeError("SGP30 Not detected")
self.iaq_init()
@property
# pylint: disable=invalid-name
def TVOC(self):
"""Total Volatile Organic Compound in parts per billion."""
return self.iaq_measure()[1]
@property
# pylint: disable=invalid-name
def baseline_TVOC(self):
"""Total Volatile Organic Compound baseline value"""
return self.get_iaq_baseline()[1]
@property
# pylint: disable=invalid-name
def eCO2(self):
"""Carbon Dioxide Equivalent in parts per million"""
return self.iaq_measure()[0]
@property
# pylint: disable=invalid-name
def baseline_eCO2(self):
"""Carbon Dioxide Equivalent baseline value"""
return self.get_iaq_baseline()[0]
@property
# pylint: disable=invalid-name
def Ethanol(self):
"""Ethanol Raw Signal in ticks"""
return self.raw_measure()[1]
@property
# pylint: disable=invalid-name
def H2(self):
"""H2 Raw Signal in ticks"""
return self.raw_measure()[0]
def iaq_init(self):
"""Initialize the IAQ algorithm"""
# name, command, signals, delay
self._run_profile(["iaq_init", [0x20, 0x03], 0, 0.01])
def iaq_measure(self):
"""Measure the eCO2 and TVOC"""
# name, command, signals, delay
return self._run_profile(["iaq_measure", [0x20, 0x08], 2, 0.05])
def raw_measure(self):
"""Measure H2 and Ethanol (Raw Signals)"""
# name, command, signals, delay
return self._run_profile(["raw_measure", [0x20, 0x50], 2, 0.025])
def get_iaq_baseline(self):
"""Retreive the IAQ algorithm baseline for eCO2 and TVOC"""
# name, command, signals, delay
return self._run_profile(["iaq_get_baseline", [0x20, 0x15], 2, 0.01])
def set_iaq_baseline(self, eCO2, TVOC): # pylint: disable=invalid-name
"""Set the previously recorded IAQ algorithm baseline for eCO2 and TVOC"""
if eCO2 == 0 and TVOC == 0:
raise RuntimeError("Invalid baseline")
buffer = []
for value in [TVOC, eCO2]:
arr = [value >> 8, value & 0xFF]
arr.append(self._generate_crc(arr))
buffer += arr
self._run_profile(["iaq_set_baseline", [0x20, 0x1E] + buffer, 0, 0.01])
def set_iaq_humidity(self, gramsPM3): # pylint: disable=invalid-name
"""Set the humidity in g/m3 for eCO2 and TVOC compensation algorithm"""
tmp = int(gramsPM3 * 256)
buffer = []
for value in [tmp]:
arr = [value >> 8, value & 0xFF]
arr.append(self._generate_crc(arr))
buffer += arr
self._run_profile(["iaq_set_humidity", [0x20, 0x61] + buffer, 0, 0.01])
# Low level command functions
def _run_profile(self, profile):
"""Run an SGP 'profile' which is a named command set"""
# pylint: disable=unused-variable
name, command, signals, delay = profile
# pylint: enable=unused-variable
# print("\trunning profile: %s, command %s, %d, delay %0.02f" %
# (name, ["0x%02x" % i for i in command], signals, delay))
return self._i2c_read_words_from_cmd(command, delay, signals)
def _i2c_read_words_from_cmd(self, command, delay, reply_size):
"""Run an SGP command query, get a reply and CRC results if necessary"""
with self._device:
self._device.write(bytes(command))
time.sleep(delay)
if not reply_size:
return None
crc_result = bytearray(reply_size * (_SGP30_WORD_LEN + 1))
self._device.readinto(crc_result)
# print("\tRaw Read: ", crc_result)
result = []
for i in range(reply_size):
word = [crc_result[3 * i], crc_result[3 * i + 1]]
crc = crc_result[3 * i + 2]
if self._generate_crc(word) != crc:
raise RuntimeError("CRC Error")
result.append(word[0] << 8 | word[1])
# print("\tOK Data: ", [hex(i) for i in result])
return result
# pylint: disable=no-self-use
def _generate_crc(self, data):
"""8-bit CRC algorithm for checking data"""
crc = _SGP30_CRC8_INIT
# calculates 8-Bit checksum with given polynomial
for byte in data:
crc ^= byte
for _ in range(8):
if crc & 0x80:
crc = (crc << 1) ^ _SGP30_CRC8_POLYNOMIAL
else:
crc <<= 1
return crc & 0xFF
| [
"[email protected]"
] | |
c810a8c7f61382cb93aa85d97410ffbc095726b3 | 7baebc3c3e8cb27a0e21ffd118e7ec11ad1dc1d3 | /first_assignement/section4.py | 4587b531fdd628a74359fe747547ba1374cd9dae | [] | no_license | robin-libert/INFO8003-1-OPTIMAL-DECISION-MAKING-FOR-COMPLEX-PROBLEMS | 8e67a869d6cd9072d7bb3133c6c981f3331cd749 | 4374b33b2d660c8fb98a58418434d8d2e5598340 | refs/heads/master | 2021-01-02T03:01:39.420136 | 2020-04-13T11:29:03 | 2020-04-13T11:29:03 | 239,462,283 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,713 | py | from domain import Domain
import random
random.seed(42)#for reproductibility
domain = Domain()
def my_routine(T):
"""
Compute r(x,u) and p(x'|x,u) and a trajectory of size T
"""
p = {}
r = {}
#counters to compute the mean
nr = {}
np = {}
counter = 0
ht = []
for i in domain.state_space:
for state in i:
for j in domain.state_space:
for newState in j:
for action in domain.action_space:
r[(state, action)] = 0.
p[(state, action, newState)] = 0.
nr[(state, action)] = 0.
np[(state, action, newState)] = 0.
state = (3,0)#initial state
ht.append(state)
while counter < T:
action = domain.action_space[random.randint(0,3)]
ht.append(action)
newState = domain.move(state, action) #new state with maybe some disturbance
reward = domain.reward_signal(newState)
ht.append(reward)
ht.append(newState)
newState2 = (min(max(state[0]+action[0],0),domain.n-1), min(max(state[1]+action[1],0),domain.m-1))#new state if there is no disturbances
r[(state, action)] += reward
nr[(state, action)] += 1.
if newState == newState2:
p[(state, action, newState2)] += 1.
np[(state, action, newState2)] += 1.
else:
np[(state, action, newState2)] += 1.
state = newState
counter += 1
for i in domain.state_space:
for state in i:
for action in domain.action_space:
if nr[(state, action)] > 0:
r[(state, action)] = r[(state, action)] / nr[(state, action)]
for i in domain.state_space:
for state in i:
for j in domain.state_space:
for newState in j:
for action in domain.action_space:
if np[(state, action, newState)] != 0:
p[(state, action, newState)] = p[(state, action, newState)] /np[(state, action, newState)]
return (p, r, ht)
def memoize(f):
"""
To optimize the Q function
"""
memo = {}
def helper(a,b,c,d,e):
if (a,b,c) not in memo:
memo[(a,b,c)] = f(a,b,c,d,e)
return memo[(a,b,c)]
return helper
@memoize
def Q(state, action, N, r, p):
"""
Return the value of the state_action value function.
state:
a tuple (n,m) where 0<=n,m<=4
action:
a tuple (a,b) where -1<=a,b<= 1 which belongs to domain.action_space
N:
the nnumber of steps
r:
dictionary containing r(x,u) previously computed for each state, action
p:
dictionary containing p(x'|x,u) previously computed for each state, action, new state
"""
if N == 0:
return 0
else:
mysum = 0
recurse = 0
for i in domain.state_space:
for newState in i:
recurse = max(Q(newState, domain.action_space[0], N-1, r, p),Q(newState, domain.action_space[1], N-1, r, p),Q(newState, domain.action_space[2], N-1, r, p),Q(newState, domain.action_space[3], N-1, r, p))
mysum += p[(state,action,newState)] * recurse
return r[(state,action)] + domain.discount_factor * mysum
def compute_JN_and_optimal_policy(N, rewards, probabilities):
"""
Compute an optimal policy and the value function
"""
optimal_J_mu_N = {}
optimal_policy = {}
for i in domain.state_space:
for state in i:
best_action = domain.action_space[0]
maxi = Q(state, domain.action_space[0],N, rewards, probabilities)
for action in domain.action_space[1:4]:
current = Q(state, action,N, rewards, probabilities)
if current > maxi:
maxi = current
best_action = action
optimal_policy[state] = best_action
optimal_J_mu_N[state] = maxi
return (optimal_J_mu_N, optimal_policy)
def tune_N(gamma=0.99, Br=19, erreur = 0.5):
"""
return the best value of N
"""
N = 1
e = ((2*(gamma**N))/(1-gamma)**2)*Br
while e > erreur:
N += 1
e = ((2*(gamma**N))/(1-gamma)**2)*Br
return N
if __name__ == "__main__":
domain.setting = 0
T = 10000
N = tune_N()#compute N to have an error <= 0.5
probabilities, rewards, trajectory = my_routine(T)
optimal_J_mu_N, optimal_policy = compute_JN_and_optimal_policy(N, rewards, probabilities)
for i in domain.state_space:
for state in i:
print('current state = {} | optimal_JN = {}'.format(state, optimal_J_mu_N[state]))
| [
"[email protected]"
] | |
760bd612f39858593c024b41140e20e18fedf54b | 633be23fe191d1daf6adee05fc455520d6a378bd | /json-to-xml/json_to_xml.py | 91cb119280de173bd0a1cca079366ee36df53078 | [] | no_license | gabrielw33/Xml_Test | 524745c9619289135aabfea278b7714b2f14497b | d79b0f4eee80a673e09fbdd9e7511431bb52db2e | refs/heads/master | 2020-07-05T15:04:04.565633 | 2019-08-19T11:15:36 | 2019-08-19T11:15:36 | 202,680,084 | 0 | 0 | null | 2019-08-16T11:38:41 | 2019-08-16T07:27:33 | Python | UTF-8 | Python | false | false | 748 | py | import xml.etree.ElementTree as ET
import json
import sys
import argparse
import Function as F
parser = argparse.ArgumentParser(description='')
parser.add_argument('json', help='json file with configurations')
parser.add_argument('xml', help='xml base file')
parser.add_argument('-id', help='product id', default="mxb")
args = parser.parse_args()
if len(sys.argv) < 3:
print("error:no params")
tree = ET.parse(str(args.xml))
root = tree.getroot()
with open(str(args.json)) as json_file:
data = json.load(json_file)
json_file.close()
for k, v in data.items():
if v != -2:
element = ET.SubElement(
root.find('nvm'), 'param', F.DictForParamTAG(k, v))
root.set('productID', str(args.id))
tree.write('max4.xml')
| [
"[email protected]"
] | |
1f344a548e0eb08347b4cbbc2725414f705f0872 | 5d89e400ab38309e144a3ff2082fe8500f70d952 | /ProjectStructure/__init__.py | 0e15df4929e7ef46a01ddefc566046afddc7ab84 | [] | no_license | GarageManager/Doc_Converter | f9dbdb2b587a52fbd92b4f4fa046fa1970fbbcb6 | b5655ed747107850b1c832cc48fbbd5c4d8f2f7c | refs/heads/master | 2022-12-20T04:10:49.503929 | 2020-10-07T07:54:58 | 2020-10-07T07:54:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 522 | py | from ProjectStructure.InterfaceInfo import InterfaceInfo
from ProjectStructure.NamespaceInfo import NamespaceInfo
from ProjectStructure.PropertyInfo import PropertyInfo
from ProjectStructure.StructInfo import StructInfo
from ProjectStructure.MethodInfo import MethodInfo, Method
from ProjectStructure.ClassInfo import ClassInfo
from ProjectStructure.FieldInfo import FieldInfo
from ProjectStructure.EnumInfo import EnumInfo
from ProjectStructure.CsFileInfo import FileInfo
from ProjectStructure.EventInfo import EventInfo
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.