blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
220 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
257 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
f8b32217c9daae58faab52a87b96758125de8793
4fe52c6f01afb05ac787a361a239466ceac69964
/pyjournal2/build_util.py
9acc2f6977346f32e542ec3806689de1074d6201
[ "BSD-3-Clause" ]
permissive
cmsquared/pyjournal2
85beec6e3a0423d0ee873d189c3a879dd9a7db7c
cfa67529033c5fd7bcd5c60b87c8122ef8c22425
refs/heads/master
2020-04-03T18:30:15.119923
2018-10-31T00:41:07
2018-10-31T00:41:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,934
py
"""This module controls building the journal from the entry sources""" import os import webbrowser import pyjournal2.shell_util as shell_util def get_source_dir(defs): """return the directory where we put the sources""" return "{}/journal-{}/source/".format(defs["working_path"], defs["nickname"]) def get_topics(defs): """return a list of the currently known topics""" source_dir = get_source_dir(defs) topics = [] # get the list of directories in source/ -- these are the topics for d in os.listdir(source_dir): if os.path.isdir(os.path.join(source_dir, d)) and not d.startswith("_"): topics.append(d) return topics def create_topic(topic, defs): """create a new topic directory""" source_dir = get_source_dir(defs) try: os.mkdir(os.path.join(source_dir, topic)) except: sys.error("unable to create a new topic") def build(defs, show=0): """build the journal. This entails writing the TOC files that link to the individual entries and then running the Sphinx make command """ source_dir = get_source_dir(defs) topics = get_topics(defs) # for each topic, we want to create a "topic.rst" that then has # things subdivided by year-month, and that a # "topic-year-month.rst" that includes the individual entries for topic in topics: tdir = os.path.join(source_dir, topic) os.chdir(tdir) # look over the directories here, they will be in the form YYYY-MM-DD years = [] entries = [] for d in os.listdir(tdir): if os.path.isdir(os.path.join(tdir, d)): y, _, _ = d.split("-") if y not in years: years.append(y) entries.append(d) years.sort() entries.sort() # we need to create ReST files of the form YYYY.rst. These # will each then contain the links to the entries for that # year for y in years: y_entries = [q for q in entries if q.startswith(y)] with open("{}.rst".format(y), "w") as yf: yf.write("****\n") yf.write("{}\n".format(y)) yf.write("****\n\n") yf.write(".. toctree::\n") yf.write(" :maxdepth: 2\n") yf.write(" :caption: Contents:\n\n") for entry in y_entries: yf.write(" {}/{}.rst\n".format(entry, entry)) # now write the topic.rst with open("{}.rst".format(topic), "w") as tf: tf.write(len(topic)*"*" + "\n") tf.write("{}\n".format(topic)) tf.write(len(topic)*"*" + "\n") tf.write(".. toctree::\n") tf.write(" :maxdepth: 2\n") tf.write(" :caption: Contents:\n\n") for y in years: tf.write(" {}.rst\n".format(y)) # now write the index.rst os.chdir(source_dir) with open("index.rst", "w") as mf: mf.write("Research Journal\n") mf.write("================\n\n") mf.write(".. toctree::\n") mf.write(" :maxdepth: 2\n") mf.write(" :caption: Contents:\n\n") for topic in sorted(topics): mf.write(" {}/{}\n".format(topic, topic)) mf.write("\n") mf.write("Indices and tables\n") mf.write("==================\n\n") mf.write("* :ref:`genindex`\n") mf.write("* :ref:`modindex`\n") mf.write("* :ref:`search`\n") # now do the building build_dir = "{}/journal-{}/".format(defs["working_path"], defs["nickname"]) os.chdir(build_dir) _, _, rc = shell_util.run("make html") if rc != 0: print("build may have been unsuccessful") index = os.path.join(build_dir, "build/html/index.html") # use webbrowser module if show == 1: webbrowser.open_new_tab(index)
[ "michael.zingale@stonybrook.edu" ]
michael.zingale@stonybrook.edu
20ae7bcc5afe279441ec8d3b9c315a60d9785feb
0a3ef6195220f510ba962c25280b1848b63b858b
/Django_bbs/asgi.py
62b376d760ffba23b0b66e2dc5e4b76f004fe1b6
[]
no_license
wykuro/django_bbs
4584659f42190b933fa26b5eea281b19a31a7885
01605676d6f79567c00f7e4aaadcc681014cf06e
refs/heads/master
2022-11-19T06:48:26.081021
2020-07-28T08:56:21
2020-07-28T08:56:21
283,153,068
0
0
null
null
null
null
UTF-8
Python
false
false
397
py
""" ASGI config for Django_bbs 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.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Django_bbs.settings') application = get_asgi_application()
[ "2350199078@qq.com" ]
2350199078@qq.com
30a77a5b2a326c40c06e455066908091bac0870a
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_113/ch44_2020_09_30_10_47_17_987015.py
f078ba9a9524ee5b166c21af69a4c0e35a23748f
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
207
py
#x=True lista = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'] #while x==True: mes = input('Qual o mês? ') print(lista[mes])
[ "you@example.com" ]
you@example.com
735b63875c4d13122c07d03e6bcdc3db602a5dc5
0282d9b7f865b74b5c7e8db1980ffec9b41b1a74
/virtual/bin/epylint
4b3605e0ce3a1ab03838bf5caac28f8798ff50b4
[ "MIT" ]
permissive
aluoch-sheila/GALLERY
3599ded0220144cfdcac403652e89593f2dcd5b4
3a910dc272ce5c731d5780749daeecec66bf2313
refs/heads/master
2020-04-10T03:32:47.755612
2018-12-13T06:52:00
2018-12-13T06:52:00
160,773,028
0
0
null
null
null
null
UTF-8
Python
false
false
263
#!/home/moringaschool/Django/my-gallery/virtual/bin/python # -*- coding: utf-8 -*- import re import sys from pylint import run_epylint if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(run_epylint())
[ "aluochsheila1999@gmail.com" ]
aluochsheila1999@gmail.com
cefccb4e18a42354913c1b1a7008faa1c4c580dc
50219c54e1e1ae1afb3844fe26bb24779c8939aa
/app/clients/email_send_client.py
7ebf66266a323f76ba3bb0c56f173b9abede6db3
[]
no_license
rajsshah23/brightwheel-interview-email-send
aac0de9a55ce95f45b280f9ac1c0bcbdfdbdaa71
86165ab65e976955bb9da4ee05ff2a653b2e3e4a
refs/heads/main
2023-07-18T06:41:09.391399
2021-09-08T03:12:21
2021-09-08T03:12:21
403,364,540
0
0
null
null
null
null
UTF-8
Python
false
false
673
py
from fastapi import Depends from app.dependencies import get_settings from app.models.get_email_status_models import ( GetEmailStatusRequest, GetEmailStatusResponse, ) from app.models.send_email_models import SendEmailRequest, SendEmailResponse from app.setup.settings import Settings class EmailSendClient: def __init__(self, settings: Settings = Depends(get_settings)): self._settings: Settings = settings def send_email(self, request: SendEmailRequest) -> SendEmailResponse: raise NotImplemented() def get_email_status( self, request: GetEmailStatusRequest ) -> GetEmailStatusResponse: raise NotImplemented()
[ "rajsshah23@gmail.com" ]
rajsshah23@gmail.com
0de0fd9a7e56f15a58adbac9a8208ed4548f3d5d
988003149dd3cc82a554d38b2948b7a6dab7f0c5
/161278031/3/3.py
607d0268c8e7b1cc696cfc3d107849286369f7ec
[]
no_license
HomeworkNJU/Final
894cb0a17349f39677dd6ede29781d98484a887a
08906263f5c78e2d0a1828007bf15d6cd28e16d8
refs/heads/master
2020-03-20T01:00:33.201335
2018-06-20T04:04:41
2018-06-20T04:04:41
137,064,142
0
15
null
2018-06-20T04:04:42
2018-06-12T11:49:46
Python
UTF-8
Python
false
false
1,172
py
# -*- coding: utf-8 -*- """ Created on Wed Jun 20 10:15:36 2018 @author: lenovo """ def expense(price,count): money=price*0.002 if(money<5): money=5 money+=(count//1000) money+=1 return money m=int(input("please input the number of action:")) action=[] for i in range(0,m): s=input().split() action.append([int(s[0]),int(s[1]),int(s[2])]) n=int(input("input the change number:")) change=[] for i in range(0,n): s=input().split() change.append([int(s[0]),int(s[1])]) output=0 revenue=0 for i in range(0,len(action)): for j in range(0,len(change)-1): if(action[i][0]>=change[j][0] and action[i][0]<change[j+1][0]): price=change[j][1] break if(action[i][0]>=change[len(change)-1][0]): price=change[len(change)-1][1] if(action[i][2]==1): output+=price*action[i][1]*100 output+=expense(price*action[i][1]*100,action[i][1]*100) else: revenue+=price*action[i][1]*100 output+=expense(price*action[i][1]*100,action[i][1]*100)+price*action[i][1]*100*0.001 print("the allowance is: %.2f" %(revenue-output))
[ "noreply@github.com" ]
HomeworkNJU.noreply@github.com
39d0a5fa54916c6b31eed02202ea9ba9fa284bf2
ad67b49b83d23ba2b0ade3da4db90d9b86d98650
/kafka/archived_scripts/kafka_rss.py
a92f06572dfc8dfb949ad37341f01ac88aace4eb
[ "MIT" ]
permissive
peterhogan/python
f58d08a67991e2822795ee9689544d43cb8fecad
bc6764f7794a862ff0d138bad80f1d6313984dcd
refs/heads/master
2021-01-01T18:41:50.338599
2017-05-13T07:51:54
2017-05-13T07:51:54
34,813,592
0
0
null
null
null
null
UTF-8
Python
false
false
2,215
py
####################################### ############### Imports ############### ####################################### from lxml import etree import os ############################################ ############### Inital setup ############### ############################################ # specify the directory to pull feeds from (default from get_rss_feeds.py) root_dir = 'newsfeeds/' # verbose output or brief (True => Verbose, False => short output) verbose = True # descriptions flag desc_on = True #################################################### ############### Defining the outputs ############### #################################################### def simple_output(rss_file): return def full_output(root_title, root_builddate, item_titles, item_descs, item_pubdates, item_guids): print(item_titles[i].text,"|",item_descs[i].text.split("<")[0],"|",rss_item_pubdates[i].text,"|",rss_item_guids[i].text,"|",rss_root_title[0].text)#,"|",rss_root_builddate[0].text) return # Function to print all the sources picked up in root_dir def print_sources(): return ################################################## ############### Scraping XML files ############### ################################################## for filerss in os.listdir(root_dir): rss_file = etree.parse(root_dir + filerss) rss_root_title = rss_file.xpath('//channel/title') rss_root_builddate = rss_file.xpath('//channel/lastBuildDate') rss_item_titles = rss_file.xpath('//channel/item/title') rss_item_descs = rss_file.xpath('//channel/item/description') rss_item_pubdates = rss_file.xpath('//channel/item/pubDate') rss_item_guids = rss_file.xpath('//channel/item/guid') for i in range(len(rss_item_titles)): #print(rss_root_title[0].text) print(rss_item_titles[i].text,"|",rss_item_descs[i].text,"|",rss_item_pubdates[i].text,"|",rss_item_guids[i].text,"|",rss_root_title[0].text)#,"|",rss_root_builddate[0].text) ''' for i in range(len(rss_item_titles)): print(rss_item_titles[i].text,"|",rss_item_descs[i].text,"|",rss_item_pubdates[i].text,"|",rss_item_guids[i].text,"|",rss_root_title[0].text)#,"|",rss_root_builddate[0].text) '''
[ "peterjameshogan@gmail.com" ]
peterjameshogan@gmail.com
224efd07081d700cef2f4bff2f9f658dcccc15e2
256efb0e9ff8b7420b412c260e6c05cd7c52c5ce
/B/resolve.py
5e0f2bb0fd1bde1c3ffc1f155dfc45171749a311
[ "MIT" ]
permissive
staguchi0703/ABC176
37a85f6d83570967696712a98dd39e1f1a08b04b
16f2f188ef5c73f85d08b028f14cd963b33d55af
refs/heads/master
2022-12-07T18:15:02.659948
2020-08-24T15:00:29
2020-08-24T15:00:29
289,476,704
0
0
null
null
null
null
UTF-8
Python
false
false
204
py
def resolve(): ''' code here ''' N = input() sum_num = 0 for item in N: sum_num += int(item) if sum_num % 9 == 0: print('Yes') else: print('No')
[ "s.taguchi0703@gmail.com" ]
s.taguchi0703@gmail.com
3a61fda2b382065093425824bfebb1070e29668e
e5d8a863c55bda022f9b21561d8594ce55c237b5
/datamodel/tests.py
ad459397b4e90a1426a2e1d7b55f95385f15d5de
[]
no_license
artiimor/GatoRaton
637fad7c883d084a9e433d76e22812cc8ff92963
84233e7102c319816f5d382b89788d3fec50ddc3
refs/heads/master
2020-08-29T17:14:12.764387
2019-12-14T11:14:03
2019-12-14T11:14:03
218,106,585
1
1
null
2019-12-14T11:04:48
2019-10-28T17:29:25
Python
UTF-8
Python
false
false
976
py
""" @author: rlatorre """ from django.contrib.auth.models import User from django.test import TestCase MSG_ERROR_INVALID_CELL = "Invalid cell for a cat or the mouse|Gato o ratón en posición no válida" MSG_ERROR_GAMESTATUS = "Game status not valid|Estado no válido" MSG_ERROR_MOVE = "Move not allowed|Movimiento no permitido" MSG_ERROR_NEW_COUNTER = "Insert not allowed|Inseción no permitida" class BaseModelTest(TestCase): def setUp(self): self.users = [] for name in ['cat_user_test', 'mouse_user_test']: self.users.append(self.get_or_create_user(name)) @classmethod def get_or_create_user(cls, name): try: user = User.objects.get(username=name) except User.DoesNotExist: user = User.objects.create_user(username=name, password=name) return user @classmethod def get_array_positions(cls, game): return [game.cat1, game.cat2, game.cat3, game.cat4, game.mouse]
[ "amorcillop@gmail.com" ]
amorcillop@gmail.com
ad4c71b1ccd1ad4b4495365ed76a0380fc1bfe1b
9539a9704b14545f81b5c60b9f3087b0bdb9661d
/bin/dadl
afb0bf9ba307761bee028311ea20d143d68c5da9
[ "MIT" ]
permissive
Galadirith/my-project-2
b0ef9de6caf2ac65dead527835d03284a901ee4b
5a2d71fc4c1c63d9479c7f57b0e5b335e2f664a3
refs/heads/master
2021-01-09T20:27:34.548747
2016-05-31T10:25:38
2016-05-31T10:25:38
60,062,635
1
0
null
null
null
null
UTF-8
Python
false
false
1,276
#! /usr/bin/env python import sys from dadownloader.auth import Auth from dadownloader.favourites import Favourites from getopt import getopt try: opts, args = getopt(sys.argv[1:], 'adfh', ['help']) except: print('Invalid options passed to dadl') sys.exit() download = {} def usage(): print\ ''' dadl [options] <username> Arguments: <username> The username of the DeviantArt user whos favourites you want to download. Options: -a Download the avatar of the creator of each deviations -d Download the description of each deviation -f Download the file (eg img file) associated with each deviation -h --help Show dadl help menu (this screen) ''' # Unpack command line options for opt, value in opts: # Download avatars? if opt == '-a': download['avatars'] = True # Download descriptions? if opt == '-d': download['descriptions'] = True # Download files? if opt == '-f': download['files'] = True # Show help if opt in ('-h', '--help'): usage() sys.exit() if len(args) == 1: session = Auth().auth() favourites = Favourites(args[0], session, **download) else: print('Wrong number of arguments: %i' % (len(sys.argv)-1))
[ "edward.fauchon.jones@gmail.com" ]
edward.fauchon.jones@gmail.com
611a492f714cd96b2ba9c94b3644617e50c8c6ce
86294539ffa65b34a862b200c84ee068187dc743
/do2things/manage.py
78b2063220ba03afa6e0bd0a501b0280f45ed107
[ "MIT" ]
permissive
tlake/do2things
6acb4f43990b0d0e4a9b80090e21246c1d39398a
4e83bea1fc579006200e9ca3a627c1bc04a6a53b
refs/heads/master
2021-01-21T04:24:57.108087
2016-08-22T08:56:11
2016-08-22T08:56:11
39,576,039
0
0
null
2015-08-27T01:28:15
2015-07-23T15:40:53
JavaScript
UTF-8
Python
false
false
252
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "do2things.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ "tanner.lake@gmail.com" ]
tanner.lake@gmail.com
292069701c70dfc1310c0ae3d406323bae424447
41679cbf83a1339e26513ce1aee09eef9f9b7629
/tests/dependency-classic/setup.py
2fb80d725a7ccc6993867726b137062c62503e12
[ "MIT" ]
permissive
mtkennerly/poetry-dynamic-versioning
db68eb7a3487e042c12820e65844335b62ba9bd4
322fe62f5a5270d324ca8a12b42224f67e822d2e
refs/heads/master
2023-07-20T10:30:17.257360
2023-07-11T15:50:51
2023-07-11T15:50:51
190,498,619
486
31
MIT
2023-09-05T01:33:23
2019-06-06T02:13:29
Python
UTF-8
Python
false
false
117
py
from setuptools import setup setup(name="dependency-classic", version="0.0.666", py_modules=["dependency_classic"])
[ "mtkennerly@gmail.com" ]
mtkennerly@gmail.com
dde187738c41353c5e9b347c6b755e131134564e
05fbf2dd9512528675867d1bf525b4bfb947816b
/main.py
4291e4bbfb32bbf6393874f49faa690cebad8523
[]
no_license
kimmobrunfeldt/kauko
efb46eea1a1ab9c1bdfd92436a88d5daba4f3e38
cbc0af6ec6b3aa1d9f717172d984c89f2a9eded2
refs/heads/master
2023-09-05T23:14:32.547518
2013-01-20T11:55:36
2013-01-20T11:55:36
7,545,552
1
1
null
2013-01-16T22:23:42
2013-01-10T17:41:25
JavaScript
UTF-8
Python
false
false
3,814
py
#!/usr/bin/env python """ Kauko server. Must be run as super user. Usage: sudo python main.py -v -d sudo python main.py -p 8080 Options: -h --help Prints this help. -v --verbose Used commands are printed to console. -d --debug Debug information is printed to console. -p --port=<port> Web server's listening port. """ import logging import socket import sys from gevent import pywsgi import kauko.wsgiserver as wsgiserver def setup_logging(root_logger, level=logging.DEBUG): if root_logger.handlers: for handler in root_logger.handlers: root_logger.removeHandler(handler) if level == logging.DEBUG: format = '%(asctime)-15s %(name)-15s %(levelname)-8s %(message)s' else: format = '%(message)s' formatter = logging.Formatter(format) root_logger.setLevel(level) console_handler = logging.StreamHandler(sys.stdout) console_handler.setFormatter(formatter) console_handler.setLevel(level) root_logger.addHandler(console_handler) def get_ip_address(): """Tries to find the ip address of the interface currently used.""" try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip_address = s.getsockname()[0] s.close() except socket.error: ip_address = socket.gethostbyname(socket.gethostname()) return ip_address class NullLog(object): """gevent writes directly to stdout, give instance of this class to gevent and it will shut up. Errors are still written to stderr though. """ def write(self, *args, **kwargs): pass def main(): argv = sys.argv[1:] if '-h' in argv or '--help' in argv: print(__doc__.strip()) sys.exit(0) port = 80 # Parse port from arguments success = True for param in ['-p', '--port']: if param in argv: # Find the index of -p or --port from argv list try: i = argv.index(param) except ValueError: success = False break # Try to convert the following argument to port number. try: port = int(argv[i + 1]) if not 1 <= port <= 65535: raise ValueError # Invalid port number except (ValueError, IndexError): success = False break if not success: print('Error: Invalid port number.\nUse number between 1-65535.') sys.exit(1) verbose_flag = '-v' in argv or '--verbose' in argv debug_flag = '-d' in argv or '--debug' in argv logging_level = logging.WARNING if verbose_flag: logging_level = logging.INFO # If debug is specified, it overrides the verbose flag. if debug_flag: logging_level = logging.DEBUG setup_logging(logging.getLogger(''), level=logging_level) print('\nKauko is now started, quit the program by pressing Ctrl - C') ip_address = get_ip_address() if not ip_address.startswith('127'): print('\nOpen the following address in your browser:') address = 'http://%s' % ip_address if port != 80: address += ':%s' % port print(address) else: print('\nCouldn\'t resolve your ip address.') # Serve static files and routes with wsgi app if logging_level > logging.DEBUG: log = NullLog() else: log = 'default' # Uses gevent's default logging -> stdout http_server = pywsgi.WSGIServer(('0.0.0.0', port), wsgiserver.main_app, log=log) http_server.serve_forever() if __name__ == '__main__': try: main() except KeyboardInterrupt: print('Quit.\n')
[ "kimmobrunfeldt@gmail.com" ]
kimmobrunfeldt@gmail.com
aabf23c2151534f4a361ed928fa3088942a201fb
cc7e0827e14f37331c6bd7f821a3e062e2fc7e9d
/houses/migrations/0006_auto_20211004_2059.py
8052304ef74e91c4354fcf6de4383bf8e909c6fc
[]
no_license
kudawoo2002/Ayelevi-estat
f8b7e43170d04ce3f64ca78269118f6df2248928
46fa19883aa360782f35e1c2b0d07233839350f4
refs/heads/main
2023-09-04T08:43:04.387373
2021-10-12T18:18:29
2021-10-12T18:18:29
416,324,409
0
0
null
null
null
null
UTF-8
Python
false
false
661
py
# Generated by Django 3.2.7 on 2021-10-04 20:59 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('houses', '0005_rename_sale_type_seller_seller_type'), ] operations = [ migrations.AddField( model_name='house', name='garage', field=models.IntegerField(default=0), preserve_default=False, ), migrations.AddField( model_name='seller', name='email', field=models.CharField(default=0, max_length=200), preserve_default=False, ), ]
[ "kudawoo2002@gmail.com" ]
kudawoo2002@gmail.com
9958bee7ab67e7e9f94c168f40fd987b1ed06256
33ff78109f47d6efe1f3fd334733b8404472277c
/sketch_191203a.pyde
e2b3368b2b203a216e96563ca7a9fb8930c24d55
[ "MIT" ]
permissive
jadejieheng/processing.py-learning
ef29ad5d8f704461e2fb3486b8437a6467094738
aef8b990f4eec4a39def7c6444f7bea4753831a2
refs/heads/master
2020-09-23T11:44:24.663341
2019-12-16T23:46:47
2019-12-16T23:46:47
225,493,387
0
0
null
null
null
null
UTF-8
Python
false
false
2,570
pyde
""" pusedocode c = color(0) x = 0.0 y = 100.0 speed = 1.0 def setup(): size(500, 500) def draw(): background(255) move() display() def move(): global x x = x + speed if x > width: x = 0 def display(): fill(c) rect(x, y, 150, 50) """ """ rewrite the structure, object oriented class Car(object):#class name, data(global variables) def __init__(self): #initializing data self.c = color(255) self.x = 100 self.y = 100 self.xspeed = 1 def display(self): #functionality rectMode(CENTER) fill(self.c) rect(self.x, self.y, 100, 50) def drive(self): #functionality self.x += self.xspeed if self.x > width: self.x = 0 Note that the code for a class exists as its own block and can be placed anywhere outside of setup() and draw(), as long as it's defined before you use it. myCar = Car() #drive() must be called with Car instance as first argument #Car is a class, myCar = Car() is an instance #Car.drive() is not an argument def setup(): size(1000,1000) def draw(): background(255) myCar.drive() myCar.display() result is one """ """using the object""" class Car(object):#class name def __init__(self, c, x, y, xspeed, yspeed): #initializing data self.c = c self.x = x self.y = y self.xspeed = xspeed self.yspeed = yspeed def display(self): #functionality noStroke() rectMode(CENTER) fill(self.c) rect(self.x, self.y, 200, 100) def drive(self): #functionality self.x += self.xspeed if self.x > width: #this loop runs for +speed self.x = 0 if self.x < 0: #this loop runs for -speed self.x = width self.y += self.yspeed# this has no loop #myCar = Car() #initializing an object/object instantiation #object instantiation myCar1 = Car(color(204,14,66), 1000, 650, -5, 0) myCar2 = Car(color(33,45,201), 0, 350, 2, 0) myCar3 = Car(color(234,164,0), 500, 0, 0, 2) def setup(): size(1000,1000) def draw(): background(255) myCar1.drive() # Functions are called with the "dot syntax". myCar1.display() myCar2.drive() myCar2.display() myCar3.drive() myCar3.display()
[ "noreply@github.com" ]
jadejieheng.noreply@github.com
b422f8f7fab0c031a2544141bf37274393b39d00
24192756f1275986078c083412ee0b209bae649f
/donghee_project/donghee_project/urls.py
2de9d8f673a9a270dad68cc545cab23c2460ba4e
[]
no_license
penpen-dongE/django_todolist_project
0128498a7a9973d4fffefbf320d77044b6916530
ceeb5d249d7988677b55a690ee92fb74257e311c
refs/heads/master
2022-05-10T03:24:18.132484
2020-04-23T12:13:48
2020-04-23T12:13:48
255,940,607
0
0
null
null
null
null
UTF-8
Python
false
false
1,432
py
"""donghee_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/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 home.views import home_view from home.views import quote_view from home.views import var_view from home.views import nums_view from todo.views import todo_view from todo.views import todo_progress_view from todo.views import delete_todo from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', home_view), path('quote/', quote_view), path('var/', var_view), path('num/', nums_view), path('todos/', todo_view, name="todos"), path('todos/in_progress', todo_progress_view, name="todos_in_progress"), path('todos/<pk>/delete', delete_todo, name="todo_del"), ] # urlpatterns += \ # static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
[ "dongheepark.dev@gmail.com" ]
dongheepark.dev@gmail.com
3d2281ceea099e3636a2d5593f4e69d3ab66ddbf
c7846ee0828539c2a2019928c1cbf3abd35665bf
/1226.py
e40445bed21211b32f058a29fb64d1cef368c25a
[]
no_license
whiteblue0/sw_problems
10476601c8d6d68d42e2f30af87fcde1e5dbbcc5
1cefc6236cccc20477bf4eadb458a0fd06b09126
refs/heads/master
2020-06-20T10:44:57.463275
2020-05-03T07:27:57
2020-05-03T07:27:57
197,098,448
0
0
null
null
null
null
UTF-8
Python
false
false
881
py
import sys sys.stdin = open('1226.txt') def ispass(y,x): if 0<=y<L and 0<=x<L and data[y][x] != 1 and visited[y][x] == 0: return True else: return False def DFS(sy,sx): global end visited[sy][sx] = 1 if data[sy][sx] == 3: end = 1 for i in range(4): ny = sy + dy[i] nx = sx + dx[i] if ispass(ny, nx): visited[ny][nx] = 1 DFS(ny,nx) # 우하좌상 dy = [0,1,0,-1] dx = [1,0,-1,0] T = 10 for tc in range(1,T+1): N = int(input()) L = 16 data = [list(map(int, input())) for _ in range(L)] visited = [[0]*L for _ in range(L)] for i in range(L): for j in range(L): if data[i][j] == 2: start = (i,j) end = 0 DFS(start[0],start[1]) # for i in range(L): # print(visited[i]) print('#{} {}'.format(tc,end))
[ "21port@naver.com" ]
21port@naver.com
0296d247cff0d46ffe781196db159f2dc53ad9a7
0dc3e9b70da8ccd056e0a0fab2b1d8f850c3d470
/lantern/django/django_celery/src/apps/dealers/models.py
bc779127742bd20a2e9942ebdd4779103f3156e4
[]
no_license
ArturYefriemov/green_lantern
28e7150af7b9d2281a107ad80026828ad77af62a
2841b647e1bfae4a7505e91e8a8695d03f35a3a2
refs/heads/master
2021-03-01T16:54:58.881835
2020-11-17T19:42:23
2020-11-17T19:42:23
245,799,969
0
0
null
2020-07-14T18:51:13
2020-03-08T11:13:32
Python
UTF-8
Python
false
false
735
py
from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class Country(models.Model): name = models.CharField(max_length=32, unique=True) class City(models.Model): name = models.CharField(max_length=32, db_index=True) country = models.ForeignKey(to='Country', on_delete=models.CASCADE, null=True) class Address(models.Model): address1 = models.CharField(max_length=128) address2 = models.CharField(max_length=128, blank=True) zip_code = models.PositiveSmallIntegerField() city = models.ForeignKey(to='City', on_delete=models.CASCADE) class Dealer(AbstractUser): address = models.ForeignKey(to='Address', on_delete=models.CASCADE, null=True)
[ "odarchenko@ex.ua" ]
odarchenko@ex.ua
bddfab9694013cb5361590adc0e4269290af1cec
b82ebabc2568e34ba1db516abd5bb978fda69f2c
/Forming/urls.py
e0ed48947301b255a855f3ffcb08fce25ff8ab42
[]
no_license
msreenathreddy67/farming
3996f19f16a0e689e890687a661ffed46f63d58d
9d727f0297b0fa444da8b7383d84ba3f43decded
refs/heads/main
2023-06-17T07:29:07.520940
2021-07-09T11:04:17
2021-07-09T11:04:17
384,410,129
0
0
null
null
null
null
UTF-8
Python
false
false
863
py
"""Forming URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path('admin/', admin.site.urls), path('index/',views.index,name='index'), path('about/',views.about,name='about') ]
[ "msreenathreddy67@gmail.com" ]
msreenathreddy67@gmail.com
e1a1de36048d93300f9e84f3959504ed9e7d628d
35a2268f7f004ecd4c834eed7a68b54980a2a157
/action sequence generation.py
3658289acb07e626f917a29fea0775543bdae9db
[]
no_license
akagrecha/action-sequence-generation
cefa768b6250dd9968ad7e2068b991d94d7379bf
46ff1a7019d015709832e24c2244106d2dfb9fc7
refs/heads/master
2021-01-20T17:33:52.601183
2016-06-23T05:13:54
2016-06-23T05:13:54
61,200,018
0
0
null
null
null
null
UTF-8
Python
false
false
4,314
py
import cv2 import argparse def action_sequence_generator(video, gblur_ksize_width=21, gblur_ksize_height=21, gblur_sigmaX=0, fg_mask_lower_threshold=50, fg_mask_upper_threshold=255, required_frames=8): """ Action Sequence Generator converts a video containing an action sequence to an image that has the action sequence in it. Algorithm _________ 1. Foreground Extraction: A foreground mask is generated by thresholding a delta image of the first frame and the current frame. The foreground mask is applied to the frame to get foreground frames. Similarly, a background frames are also generated. 2. Recombination: The foreground frames and background frames are saved in an array. Selected foreground and background frames undergo bitwise operations for recombination. Finally, they are combined to get the result. Note ____ The algorithm for foreground extraction works properly when the first frame contains the background only i.e. the foreground object is not visible in the first frame. Function Signature __________________ : param video: the video file with an action sequence in it. : param gblur_ksize_width: kernel size width for the gaussian blur applied on the frame : param gblur_ksize_height: kernel size height for the gaussian blur applied on the frame : param gblur_ksize_sigmaX: Gaussian kernel standard deviation in X direction : param fg_mask_lower_threshold: Lower threshold applied to the delta image to generate foreground mask : param fg_mask_upper_threshold: Upper threshold applied to the delta image to generate foreground mask : param required_frames: Number of frames to be considered while generating the result : return: image having the action sequence of the given video Authors _______ Anmol Kagrecha Ranveer Aggarwal """ cap = cv2.VideoCapture(video) first_frame = None img_foreground_frames = [] img_background_frames = [] number_of_frames = int(cap.get(7)) while 1: ret, frame = cap.read() if ret == 0: break gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (gblur_ksize_width, gblur_ksize_height), gblur_sigmaX) if first_frame is None: first_frame = gray continue # difference of current frame and the first frame frame_delta = cv2.absdiff(first_frame, gray) # foreground mask and background mask foreground_mask = cv2.threshold(frame_delta, fg_mask_lower_threshold, fg_mask_upper_threshold, cv2.THRESH_BINARY)[1] background_mask = cv2.bitwise_not(foreground_mask) # foreground and background foreground = cv2.bitwise_and(frame, frame, mask=foreground_mask) background = cv2.bitwise_and(frame, frame, mask=background_mask) # appending foreground and background to the arrays img_foreground_frames.append(foreground) img_background_frames.append(background) cap.release() # frame numbers generated for the result frame_numbers = [i for i in range(0, number_of_frames + 1, int(number_of_frames/required_frames))] foreground_combined = img_foreground_frames[0] background_combined = img_background_frames[0] # recombination operations to generate the result for i in frame_numbers: foreground_combined = cv2.bitwise_or(img_foreground_frames[i], foreground_combined) background_combined = cv2.bitwise_and(img_background_frames[i], background_combined) result = cv2.bitwise_or(foreground_combined, background_combined) # uncomment to view the result """ cv2.namedWindow('result', 0) cv2.imshow('result', result) cv2.waitKey(0) & 0xFF cv2.destroyAllWindows() """ return result ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", help="path to the video file") args = vars(ap.parse_args()) if args.get("video") is None: print("file not found") else: action_sequence_generator(args["video"])
[ "akagrecha@gmail.com" ]
akagrecha@gmail.com
a0a0950be83e34b71b9196a40ad2399172c4477c
9636c75094a251fc931774c967df135b31012101
/school_mgnt/wsgi.py
a09c0a72615f55cd2c45d10991c74db785214fe0
[]
no_license
bimal125/school_mgnt
9e33bb7f9ae580292eb687dc4955bc54c07a8bd8
01fd33cb2547494cda2213061af443e706dc92d9
refs/heads/master
2022-12-10T00:53:13.106358
2020-08-27T15:07:05
2020-08-27T15:07:05
205,401,910
0
0
null
null
null
null
UTF-8
Python
false
false
399
py
""" WSGI config for school_mgnt 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', 'school_mgnt.settings') application = get_wsgi_application()
[ "pandeybi125@gmail.com" ]
pandeybi125@gmail.com
0f12e75f326736ce1da7a7a6b1fb5297088bafd5
5bfbf31332a5c4750ab57d305f400aa5e20bf6bd
/contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_utah_zip.py
5c11f0c756f7c389107ebd4a9b7e6f5e7f2270a7
[ "Apache-2.0" ]
permissive
alexsherstinsky/great_expectations
9d4ae4c06546c5ab2ee0d04fb7840e3515c25677
2fc4bb36a5b3791c8ada97c5364531cd7510d4ed
refs/heads/develop
2023-08-04T13:13:38.978967
2023-07-24T18:29:46
2023-07-24T18:29:46
203,888,556
1
0
Apache-2.0
2020-07-27T09:12:21
2019-08-22T23:31:19
Python
UTF-8
Python
false
false
5,481
py
from typing import Optional import zipcodes from great_expectations.core.expectation_configuration import ExpectationConfiguration from great_expectations.execution_engine import PandasExecutionEngine from great_expectations.expectations.expectation import ColumnMapExpectation from great_expectations.expectations.metrics import ( ColumnMapMetricProvider, column_condition_partial, ) def is_valid_utah_zip(zip: str): list_of_dicts_of_utah_zips = zipcodes.filter_by(state="UT") list_of_utah_zips = [d["zip_code"] for d in list_of_dicts_of_utah_zips] if len(zip) > 10: return False elif type(zip) != str: return False elif zip in list_of_utah_zips: return True else: return False # This class defines a Metric to support your Expectation. # For most ColumnMapExpectations, the main business logic for calculation will live in this class. class ColumnValuesToBeValidUtahZip(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_utah_zip" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, column, **kwargs): return column.apply(lambda x: is_valid_utah_zip(x)) # This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine # @column_condition_partial(engine=SqlAlchemyExecutionEngine) # def _sqlalchemy(cls, column, _dialect, **kwargs): # raise NotImplementedError # This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine # @column_condition_partial(engine=SparkDFExecutionEngine) # def _spark(cls, column, **kwargs): # raise NotImplementedError # This class defines the Expectation itself class ExpectColumnValuesToBeValidUtahZip(ColumnMapExpectation): """Expect values in this column to be valid Utah zipcodes. See https://pypi.org/project/zipcodes/ for more information. """ # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "valid_utah_zip": ["84001", "84320", "84713", "84791"], "invalid_utah_zip": ["-10000", "1234", "99999", "25487"], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "valid_utah_zip"}, "out": {"success": True}, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "invalid_utah_zip"}, "out": {"success": False}, }, ], } ] # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.valid_utah_zip" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False success_keys = ("mostly",) # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} def validate_configuration( self, configuration: Optional[ExpectationConfiguration] = None ) -> None: """ Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that necessary configuration arguments have been provided for the validation of the expectation. Args: configuration (OPTIONAL[ExpectationConfiguration]): \ An optional Expectation Configuration entry that will be used to configure the expectation Returns: None. Raises InvalidExpectationConfigurationError if the config is not validated successfully """ super().validate_configuration(configuration) configuration = configuration or self.configuration # # Check other things in configuration.kwargs and raise Exceptions if needed # try: # assert ( # ... # ), "message" # assert ( # ... # ), "message" # except AssertionError as e: # raise InvalidExpectationConfigurationError(str(e)) # This object contains metadata for display in the public Gallery library_metadata = { "maturity": "experimental", # "experimental", "beta", or "production" "tags": [ "hackathon", "typed-entities", ], # Tags for this Expectation in the Gallery "contributors": [ # Github handles for all contributors to this Expectation. "@luismdiaz01", "@derekma73", # Don't forget to add your github handle here! ], "requirements": ["zipcodes"], } if __name__ == "__main__": ExpectColumnValuesToBeValidUtahZip().print_diagnostic_checklist()
[ "noreply@github.com" ]
alexsherstinsky.noreply@github.com
de172a8f044e0de1b739d483985f14cd2fb74c27
2d7d5673d78d6ef682e88845eab99dddd8fc0927
/pybaseball/pybaseball/league_pitching_stats.py
cc3eb29485ad7ce43526b1c031e88f3b522029c8
[ "MIT" ]
permissive
BunkyFeats/MLBpy
764026d42afcdd979084b28d851a7d536a0ac70d
d035f904bea08fb73545b333d6f3448b1cb20ab0
refs/heads/master
2021-04-26T23:40:06.190324
2018-03-04T22:35:48
2018-03-04T22:35:48
123,835,303
1
0
null
null
null
null
UTF-8
Python
false
false
5,262
py
import requests import pandas as pd import numpy as np import io from bs4 import BeautifulSoup import datetime def validate_datestring(date_text): try: datetime.datetime.strptime(date_text, '%Y-%m-%d') except ValueError: raise ValueError("Incorrect data format, should be YYYY-MM-DD") def sanitize_input(start_dt, end_dt): # if no dates are supplied, assume they want yesterday's data # send a warning in case they wanted to specify if start_dt is None and end_dt is None: today = datetime.datetime.today() start_dt = (today - datetime.timedelta(1)).strftime("%Y-%m-%d") end_dt = today.strftime("%Y-%m-%d") print("Warning: no date range supplied. Returning yesterday's data. For a different date range, try pitching_stats_range(start_dt, end_dt) or pitching_stats(season).") #if only one date is supplied, assume they only want that day's stats #query in this case is from date 1 to date 1 if start_dt is None: start_dt = end_dt if end_dt is None: end_dt = start_dt #if end date occurs before start date, swap them if end_dt < start_dt: temp = start_dt start_dt = end_dt end_dt = temp # now that both dates are not None, make sure they are valid date strings validate_datestring(start_dt) validate_datestring(end_dt) return start_dt, end_dt def get_soup(start_dt, end_dt): # get most recent standings if date not specified if((start_dt is None) or (end_dt is None)): print('Error: a date range needs to be specified') return None url = "http://www.baseball-reference.com/leagues/daily.cgi?user_team=&bust_cache=&type=p&lastndays=7&dates=fromandto&fromandto={}.{}&level=mlb&franch=&stat=&stat_value=0".format(start_dt, end_dt) s = requests.get(url).content return BeautifulSoup(s, "html.parser") def get_table(soup): table = soup.find_all('table')[0] data = [] headings = [th.get_text() for th in table.find("tr").find_all("th")][1:] data.append(headings) table_body = table.find('tbody') rows = table_body.find_all('tr') for row in rows: cols = row.find_all('td') cols = [ele.text.strip() for ele in cols] data.append([ele for ele in cols]) data = pd.DataFrame(data) data = data.rename(columns=data.iloc[0]) data = data.reindex(data.index.drop(0)) return data def pitching_stats_range(start_dt=None, end_dt=None): """ Get all pitching stats for a set time range. This can be the past week, the month of August, anything. Just supply the start and end date in YYYY-MM-DD format. """ # ensure valid date strings, perform necessary processing for query start_dt, end_dt = sanitize_input(start_dt, end_dt) if datetime.datetime.strptime(start_dt, "%Y-%m-%d").year < 2008: raise ValueError("Year must be 2008 or later") if datetime.datetime.strptime(end_dt, "%Y-%m-%d").year < 2008: raise ValueError("Year must be 2008 or later") # retrieve html from baseball reference soup = get_soup(start_dt, end_dt) table = get_table(soup) table = table.dropna(how='all') # drop if all columns are NA #fix some strange formatting for percentage columns table = table.replace('---%', np.nan) #make sure these are all numeric for column in ['Age', '#days', 'G', 'GS', 'W', 'L', 'SV', 'IP', 'H', 'R', 'ER', 'BB', 'SO', 'HR', 'HBP', 'ERA', 'AB', '2B', '3B', 'IBB', 'GDP', 'SF', 'SB', 'CS', 'PO', 'BF', 'Pit', 'WHIP', 'BAbip', 'SO9', 'SO/W']: table[column] = pd.to_numeric(table[column]) #convert str(xx%) values to float(0.XX) decimal values for column in ['Str', 'StL', 'StS', 'GB/FB', 'LD', 'PU']: table[column] = table[column].replace('%','',regex=True).astype('float')/100 table = table.drop('',1) return table def pitching_stats_bref(season=None): """ Get all pitching stats for a set season. If no argument is supplied, gives stats for current season to date. """ if season is None: season = datetime.datetime.today().strftime("%Y") season = str(season) start_dt = season + '-03-01' #opening day is always late march or early april end_dt = season + '-11-01' #season is definitely over by November return(pitching_stats_range(start_dt, end_dt)) def bwar_pitch(return_all=False): """ Get data from war_daily_pitch table. Returns WAR, its components, and a few other useful stats. To get all fields from this table, supply argument return_all=True. """ url = "http://www.baseball-reference.com/data/war_daily_pitch.txt" s = requests.get(url).content c=pd.read_csv(io.StringIO(s.decode('utf-8'))) if return_all: return c else: cols_to_keep = ['name_common', 'mlb_ID', 'player_ID', 'year_ID', 'team_ID', 'stint_ID', 'lg_ID', 'G', 'GS', 'RA','xRA', 'BIP', 'BIP_perc','salary', 'ERA_plus', 'WAR_rep', 'WAA', 'WAA_adj','WAR'] return c[cols_to_keep]
[ "noreply@github.com" ]
BunkyFeats.noreply@github.com
f9d9118938a3ba4499fe9302991d70005635b133
b88dbcf3619dd3af4896b4b15432ae2b2d390665
/main.py
59c59c21694156ed16b7333845e17b06d0bfdf16
[]
no_license
msubzero2000/bayesian-optimisation-metaflow-optuna
a43ccdb0150fde6ae7571798549210113826c0ea
00bda310bbe7ce42470acfc5d90198f27ad9c5d2
refs/heads/main
2023-08-06T03:27:55.980813
2021-10-06T07:22:19
2021-10-06T07:22:19
413,768,301
10
1
null
null
null
null
UTF-8
Python
false
false
4,302
py
""" Optuna example that optimizes a classifier configuration for cancer dataset using Catboost. In this example, we optimize the validation accuracy of cancer detection using Catboost. We optimize both the choice of booster model and their hyperparameters. """ import logging from datetime import datetime, timedelta from metaflow import FlowSpec, step, S3, current, resources, conda_base, Parameter, batch, project logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) @conda_base(libraries={'catboost': '0.26.1', 'optuna': '2.9.1', 'scikit-learn': '1.0', 'sqlalchemy': '1.4.22', 'psycopg2-binary':'2.9.1'}) class Optimisation(FlowSpec): def objective(self, trial): import optuna import numpy as np import catboost as cb from sklearn.datasets import load_breast_cancer from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split data, target = load_breast_cancer(return_X_y=True) train_x, valid_x, train_y, valid_y = train_test_split(data, target, test_size=0.3) param = { "objective": trial.suggest_categorical("objective", ["Logloss", "CrossEntropy"]), "colsample_bylevel": trial.suggest_float("colsample_bylevel", 0.01, 0.1), "depth": trial.suggest_int("depth", 1, 12), "boosting_type": trial.suggest_categorical("boosting_type", ["Ordered", "Plain"]), "bootstrap_type": trial.suggest_categorical( "bootstrap_type", ["Bayesian", "Bernoulli", "MVS"] ), "used_ram_limit": "3gb", } if param["bootstrap_type"] == "Bayesian": param["bagging_temperature"] = trial.suggest_float("bagging_temperature", 0, 10) elif param["bootstrap_type"] == "Bernoulli": param["subsample"] = trial.suggest_float("subsample", 0.1, 1) gbm = cb.CatBoostClassifier(**param) gbm.fit(train_x, train_y, eval_set=[(valid_x, valid_y)], verbose=0, early_stopping_rounds=100) preds = gbm.predict(valid_x) pred_labels = np.rint(preds) accuracy = accuracy_score(valid_y, pred_labels) return accuracy @batch(cpu=4) @step def start(self): import optuna from distributed_optuna import DistributedOptuna, DistributedOptunaInfo, DistributedOptunaWorkerInfo info = DistributedOptuna.create(num_workers=10, num_trials=10, timeout=600, study_name_prefix="catboost") print(f"Creating study {info.study_name} with {len(info.workers_info)} workers") study = optuna.create_study(direction="maximize", study_name=info.study_name, storage=info.storage) self.optimisation_params = info.workers_info self.next(self.optimise, foreach="optimisation_params") @batch(cpu=4) @step def optimise(self): import optuna from distributed_optuna import DistributedOptuna, DistributedOptunaInfo, DistributedOptunaWorkerInfo study = optuna.load_study(study_name=self.input.study_name, storage=self.input.storage) study.optimize(self.objective, n_trials=self.input.num_trials, timeout=self.input.timeout) print("Number of finished trials: {}".format(len(study.trials))) print("Record Best trial:") # Record this worker's best trial self.trial = study.best_trial self.next(self.join) @step def join(self, inputs): # Find the global best trial amongst worker's best trial best_trial = None best_trial_value = 0 for input in inputs: cur_best_trial = input.trial print(f"Best trial for this worker {cur_best_trial.value}") if best_trial is None or cur_best_trial.value > best_trial_value: best_trial = cur_best_trial best_trial_value = cur_best_trial.value print("Value: {}".format(best_trial.value)) print("Params: ") for key, value in best_trial.params.items(): print(" {}: {}".format(key, value)) self.next(self.end) @step def end(self): print("Completed") opt = Optimisation()
[ "msubzero2000@gmail.com" ]
msubzero2000@gmail.com
127026945e89da6d871b6e151af9d6241f3867e5
200a7fb2a75151a8b83274ef53d661099da61047
/django1_workspace/test4(get)/blues/ddobaki/models.py
d6d5a45b52187cd3bb993d21ac6fa65d5fbb1010
[]
no_license
Minzard/Correctable-Pronunciation
9e967e428f38b2a142e81d1d181caba9bc56305a
4b94d6e07c0c682086595c202fc5fa41106a9df5
refs/heads/master
2021-06-21T03:13:44.751861
2020-12-29T02:05:22
2020-12-29T02:05:22
157,420,423
13
6
null
null
null
null
UTF-8
Python
false
false
353
py
from django.db import models class get_ddobaki(models.Model): user = models.CharField(max_length=100) label = models.CharField(max_length=50) stt = models.CharField(max_length=50) class post_ddobaki(models.Model): divided_stt = models.CharField(max_length=100) color = models.BooleanField(default=True) # Create your models here.
[ "eh@EHui-MacBook-Pro.local" ]
eh@EHui-MacBook-Pro.local
6f73725146e0aa41a0092ee3c4592b5a5dd9124d
b6282963725f1b44e29a11e4ea2479e0667c3b1a
/src/chapter04/demo01.py
f803bdb96f4e21d92e98b40c31dfdb70d8cb6bcd
[]
no_license
geekori/numpy
d2859f56e80a3ab0ea4a33bcb4bc8494dedbb879
e3b18aa6868c1f98963f01875f9afa7ee86f1bf2
refs/heads/master
2020-04-09T07:44:22.074173
2018-12-03T10:01:59
2018-12-03T10:01:59
160,168,662
0
1
null
null
null
null
UTF-8
Python
false
false
203
py
# NumPy高级函数:计算协方差矩阵 from numpy import * a = array([1,3,4,5]) b = array([2,6,2,2]) x = vstack((a,b)) print(x) print(cov(x)) # cov函数会将正常的结果缩小到原来的1/3
[ "282662996@qq.com" ]
282662996@qq.com
ec61f2c11c142888f2e43279e15779776f084d75
b75b3bb6a2c6dd8b4a5b89718eb83d6451000cd4
/hackbright.py
715553d9b927069928d6bfc85808ce5824d2e0b2
[]
no_license
CodeHotPink/project-tracking-flask
22efebeaddf83d2746ba9137f1b478da8c34b1a9
bdd58b17034406f28d5ceaa0c834eb0d6ad06be3
refs/heads/master
2020-04-03T18:46:04.010020
2018-10-31T04:02:38
2018-10-31T04:02:38
155,496,735
0
0
null
null
null
null
UTF-8
Python
false
false
5,034
py
"""Hackbright Project Tracker. A front-end for a database that allows users to work with students, class projects, and the grades students receive in class projects. """ from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) db = SQLAlchemy() def connect_to_db(app): """Connect the database to our Flask app.""" app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///hackbright' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.app = app db.init_app(app) def get_student_by_github(github): """Given a GitHub account name, print info about the matching student.""" QUERY = """ SELECT first_name, last_name, github FROM students WHERE github = :github """ db_cursor = db.session.execute(QUERY, {'github': github}) row = db_cursor.fetchone() print(row) print("Student: {} {}\nGitHub account: {}".format(row[0], row[1], row[2])) return row def make_new_student(first_name, last_name, github): """Add a new student and print confirmation. Given a first name, last name, and GitHub account, add student to the database and print a confirmation message. """ QUERY = """ INSERT INTO students (first_name, last_name, github) VALUES (:first_name, :last_name, :github) """ db.session.execute(QUERY, {'first_name': first_name, 'last_name': last_name, 'github': github,}) db.session.commit() print(f"Successully added student: {first_name} {last_name}") def get_project_by_title(title): """Given a project title, print information about the project.""" QUERY = """ SELECT title, description, max_grade FROM projects WHERE title = :title """ db_cursor = db.session.execute(QUERY, {'title': title}) row = db_cursor.fetchone() print(f"Title: {row[0]}\nDescription: {row[1]}\nMaximum Grade: {row[2]}") def get_grade_by_github_title(github, title): """Print grade student received for a project.""" QUERY = """ SELECT student_github, project_title, grade FROM grades WHERE student_github = :github AND project_title = :title """ db_cursor = db.session.execute(QUERY, {'github': github, 'title': title}) row = db_cursor.fetchone() print(f"Github: {row[0]}\nProject Title: {row[1]}\nGrade: {row[2]}") def assign_grade(github, title, grade): """Assign a student a grade on an assignment and print a confirmation.""" QUERY = """ INSERT INTO grades (student_github, project_title, grade) VALUES (:github, :title, :grade) """ db.session.execute(QUERY,{'github': github, 'title': title, 'grade': grade}) db.session.commit() print(f"Successfully added {github}'s grade for {title}") def add_project(title, description, max_grade): """Creates new project in projects table in Hackbright database. Will print confirmation.""" QUERY = """ INSERT INTO projects (title, description, max_grade) VALUES (:title,:description, :max_grade) """ db.session.execute(QUERY,{'title': title, 'description': description, 'max_grade': max_grade}) print(f"Successfully added {title}.") def handle_input(): """Main loop. Repeatedly prompt for commands, performing them, until 'quit' is received as a command. """ command = None while command != "quit": input_string = input("HBA Database> ") tokens = input_string.split() command = tokens[0] args = tokens[1:] print(args) if command == "student": github = args[0] get_student_by_github(github) elif command == "new_student": first_name, last_name, github = args # unpack! make_new_student(first_name, last_name, github) elif command == "project": title = args[0] get_project_by_title(title) elif command == "github_grade": github, title = args # unpack! get_grade_by_github_title(github, title) elif command == "assign_grade": github, title, grade = args # unpack! assign_grade(github, title, grade) elif command == "add_project": title = args[0] project_desc = args[1:-1] print(type(project_desc)) grade_max = args[-1] add_project(title, project_desc, grade_max) else: if command != "quit": print("Invalid Entry. Try again.") if __name__ == "__main__": connect_to_db(app) handle_input() # To be tidy, we close our database connection -- though, # since this is where our program ends, we'd quit anyway. db.session.close()
[ "no-reply@hackbrightacademy.com" ]
no-reply@hackbrightacademy.com
23c2de5fd645c39cbadd4ecdb4a8572487884ba8
069c2295076c482afadfe6351da5ae02be8e18e6
/tests/urlpatterns/path_same_name_urls.py
d7ea5431b1e2e70e97338b78591e99ba67df435e
[ "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "GPL-1.0-or-later", "Python-2.0.1", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-other-permissive", "Python-2.0" ]
permissive
django/django
5eb557f57053631cd4f566f451e43197309dbeeb
c74a6fad5475495756a5bdb18b2cab2b68d429bc
refs/heads/main
2023-09-01T03:43:44.033530
2023-08-31T08:27:32
2023-08-31T08:27:32
4,164,482
73,530
38,187
BSD-3-Clause
2023-09-14T20:03:48
2012-04-28T02:47:18
Python
UTF-8
Python
false
false
1,483
py
from django.urls import path, re_path, register_converter from . import converters, views register_converter(converters.DynamicConverter, "to_url_value_error") urlpatterns = [ # Different number of arguments. path("number_of_args/0/", views.empty_view, name="number_of_args"), path("number_of_args/1/<value>/", views.empty_view, name="number_of_args"), # Different names of the keyword arguments. path("kwargs_names/a/<a>/", views.empty_view, name="kwargs_names"), path("kwargs_names/b/<b>/", views.empty_view, name="kwargs_names"), # Different path converters. path("converter/path/<path:value>/", views.empty_view, name="converter"), path("converter/str/<str:value>/", views.empty_view, name="converter"), path("converter/slug/<slug:value>/", views.empty_view, name="converter"), path("converter/int/<int:value>/", views.empty_view, name="converter"), path("converter/uuid/<uuid:value>/", views.empty_view, name="converter"), # Different regular expressions. re_path(r"^regex/uppercase/([A-Z]+)/", views.empty_view, name="regex"), re_path(r"^regex/lowercase/([a-z]+)/", views.empty_view, name="regex"), # converter.to_url() raises ValueError (no match). path( "converter_to_url/int/<value>/", views.empty_view, name="converter_to_url", ), path( "converter_to_url/tiny_int/<to_url_value_error:value>/", views.empty_view, name="converter_to_url", ), ]
[ "felisiak.mariusz@gmail.com" ]
felisiak.mariusz@gmail.com
c92030d52698c79b7c903ded6e22f72bf6b89f32
3c176f8c73b157f6aba150d869cefe64b7f0a4d7
/app.py
a3686b206616eecff5056f175889e91a251507e1
[]
no_license
ddev790/image_recommender_selectivesearch
5be5a9659bb98b2f75bfd12ed7582e290d30522d
374904c7be88abfeba2b00df735fd26c519081ad
refs/heads/master
2021-08-11T21:00:59.213932
2017-11-14T04:50:52
2017-11-14T04:50:52
110,641,235
0
0
null
null
null
null
UTF-8
Python
false
false
2,653
py
import os import random import time import requests import sys import simplejson from flask import Flask, request, render_template, session, flash, redirect from celery import Celery import json from psycopg2.extensions import AsIs import psycopg2 from image_process import populate_db app = Flask(__name__) # Initialize Celery celery = Celery(app.name, broker='redis://localhost:6379/0') celery.conf.update(app.config) @celery.task(name="segmentation") def segmentation(image_url, enterprise_id, model_name, model_id): val = populate_db(image_url, enterprise_id, model_name, model_id) print(val) r = requests.post("/callback_url/", data=json.dumps(val)) dataJSON = json.dumps({"image_url": image_url, "callback_url": "/callback_url/"}) return dataJSON @app.route('/segment/<enterprise_id>/<model_name>/<model_id>', methods=['POST']) def insert_data(enterprise_id, model_name, model_id): if request.method == 'POST': content = request.json print(content) image_url = content["image_url"] # segmentation(image_url, enterprise_id, model_name, model_id) segmentation.delay(image_url, enterprise_id, model_name, model_id) return json.dumps({"image_url": image_url, "callback_url": "http://127.0.0.1:5000/callback_url/"}) # // celery process - insert into database - (url will be provided) @app.route('/callback_url', methods=["POST"]) def callback_response(image_name): if request.method == 'POST': content = request.json print(content) # return dataJSON @app.route('/features/<enterprise_id>/<model_name>/<model_id>/<segment_id>', methods=["GET"]) def features(enterprise_id, model_name, model_id, segment_id): dataJSON = {} con = None try: # connect to the PostgreSQL server con = psycopg2.connect("host='localhost' dbname='image_recommender' user='postgres' password='admin'") cur = con.cursor() query_select = "Select enterprise_id,model_name,segment_id,model_id,features from k where segment_id='" + segment_id + "'" cur.execute(query_select) columns = cur.description d = {} for value in cur.fetchall(): for index, column in enumerate(value): k = columns[index][0] if k == 'segment_id': d[k] = str(column) else: d[k] = column except (Exception, psycopg2.DatabaseError) as error: print(error) sys.exit(1) finally: if con is not None: con.close() return json.dumps(d) if __name__ == "__main__": app.run(debug=True)
[ "admin_yosemite_mac" ]
admin_yosemite_mac
bde4160a1d045a92ee19fdc4d0e30366397bb41d
2ade3d231fe1fcc8a4e698845a98fa025197c06b
/dealproperty/dealproperty/wsgi.py
f4be6bfd492254876a4b5741075bafaac4c57faf
[]
no_license
anandraj8756/property_deal_web
d3d7012968ac6c7e0931c9207db61163c518f086
1dc220734b00e651b891741db82469d28079f442
refs/heads/main
2023-06-08T04:30:12.439249
2021-07-05T06:20:33
2021-07-05T06:20:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
401
py
""" WSGI config for dealproperty project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dealproperty.settings') application = get_wsgi_application()
[ "anandallen95@gmail.com" ]
anandallen95@gmail.com
529b1a3a2c7b1d1ca36401ac499afa8ce5891042
d602149c0bf94a178e9972b74f113d7412db0eca
/google-cloud-sdk/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/third_party/apis/tpu/v1alpha1/tpu_v1alpha1_messages.py
46cde70eed13e0fc8a3c6175ab6450f73783066d
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
sarahdactyl71/gneiss-rocks
ffe19df02e77d8afdb2b96ae810e0e31490f2d77
45a4900a89638c1b6bc50d9ff4a83ae631a22c7a
refs/heads/development
2021-07-04T05:36:12.037156
2017-10-06T22:14:27
2017-10-06T22:14:27
102,655,986
0
1
null
2020-07-25T07:44:54
2017-09-06T20:38:11
Python
UTF-8
Python
false
false
25,050
py
"""Generated message classes for tpu version v1alpha1. TPU API provides customers with access to Google TPU technology. """ # NOTE: This file is autogenerated and should not be edited by hand. from apitools.base.protorpclite import messages as _messages from apitools.base.py import encoding from apitools.base.py import extra_types package = 'tpu' class Empty(_messages.Message): """A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`. """ class ListLocationsResponse(_messages.Message): """The response message for Locations.ListLocations. Fields: locations: A list of locations that matches the specified filter in the request. nextPageToken: The standard List next-page token. """ locations = _messages.MessageField('Location', 1, repeated=True) nextPageToken = _messages.StringField(2) class ListNodesResponse(_messages.Message): """Response for ListNodes. Fields: nextPageToken: The next page token or empty if none. nodes: The listed nodes. """ nextPageToken = _messages.StringField(1) nodes = _messages.MessageField('Node', 2, repeated=True) class ListOperationsResponse(_messages.Message): """The response message for Operations.ListOperations. Fields: nextPageToken: The standard List next-page token. operations: A list of operations that matches the specified filter in the request. """ nextPageToken = _messages.StringField(1) operations = _messages.MessageField('Operation', 2, repeated=True) class Location(_messages.Message): """A resource that represents Google Cloud Platform location. Messages: LabelsValue: Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"} MetadataValue: Service-specific metadata. For example the available capacity at the given location. Fields: labels: Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"} locationId: The canonical id for this location. For example: `"us-east1"`. metadata: Service-specific metadata. For example the available capacity at the given location. name: Resource name for the location, which may vary between implementations. For example: `"projects/example-project/locations/us- east1"` """ @encoding.MapUnrecognizedFields('additionalProperties') class LabelsValue(_messages.Message): """Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"} Messages: AdditionalProperty: An additional property for a LabelsValue object. Fields: additionalProperties: Additional properties of type LabelsValue """ class AdditionalProperty(_messages.Message): """An additional property for a LabelsValue object. Fields: key: Name of the additional property. value: A string attribute. """ key = _messages.StringField(1) value = _messages.StringField(2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) @encoding.MapUnrecognizedFields('additionalProperties') class MetadataValue(_messages.Message): """Service-specific metadata. For example the available capacity at the given location. Messages: AdditionalProperty: An additional property for a MetadataValue object. Fields: additionalProperties: Properties of the object. Contains field @type with type URL. """ class AdditionalProperty(_messages.Message): """An additional property for a MetadataValue object. Fields: key: Name of the additional property. value: A extra_types.JsonValue attribute. """ key = _messages.StringField(1) value = _messages.MessageField('extra_types.JsonValue', 2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) labels = _messages.MessageField('LabelsValue', 1) locationId = _messages.StringField(2) metadata = _messages.MessageField('MetadataValue', 3) name = _messages.StringField(4) class Node(_messages.Message): """An instance. Enums: StateValueValuesEnum: This contains a current state for the accelerator. Output only. Fields: acceleratorType: The type of hardware accelerators associated with this node. cidrBlock: The user must supply a CIDR block that the TPU node will use when selecting an IP address. This CIDR block must be a /29 block; the GCE networks API forbids a smaller block, and using a larger block would be wasteful (a node can only consume one IP address). Errors will occur if the CIDR block has already been used for a currently existing TPU node, the CIDR block conflicts with any subnetworks in the user's provided network, or the provided network is peered with another network that is using that CIDR block. createTime: The time when the node was created. Output only. description: User-supplied description of the TPU. Maximum of 512 characters. healthDescription: Human readable description of why the service is unhealthy. Output only. ipAddress: The network address for the TPU as visible to other GCE instances. Output only. machineType: A string attribute. name: Immutable name of the TPU network: The user specifies the name of a network they wish to peer the TPU node to. It must be a preexisting GCE network inside of the project on which this API has been activated. If none is provided, "default" will be used. port: The network port for the TPU as visible to other GCE instances. Output only. serviceAccount: The service account used to run the tensor flow services within the node. To share resources, including Google Cloud Storage data, with the Tensorflow job running in the Node, this account must have permissions to that data. Output only. state: This contains a current state for the accelerator. Output only. tensorflowVersion: The version of Tensorflow running in the Node. """ class StateValueValuesEnum(_messages.Enum): """This contains a current state for the accelerator. Output only. Values: STATE_UNSPECIFIED: TPU node state is not known/set. CREATING: TPU node is being created. READY: TPU node has been created and is fully usable. RESTARTING: TPU node is restarting. REIMAGING: TPU node is undergoing reimaging. DELETING: TPU node is being deleted. REPAIRING: TPU node is being repaired and may be unusable. Details can be found in the `help_description` field. """ STATE_UNSPECIFIED = 0 CREATING = 1 READY = 2 RESTARTING = 3 REIMAGING = 4 DELETING = 5 REPAIRING = 6 acceleratorType = _messages.StringField(1) cidrBlock = _messages.StringField(2) createTime = _messages.StringField(3) description = _messages.StringField(4) healthDescription = _messages.StringField(5) ipAddress = _messages.StringField(6) machineType = _messages.StringField(7) name = _messages.StringField(8) network = _messages.StringField(9) port = _messages.StringField(10) serviceAccount = _messages.StringField(11) state = _messages.EnumField('StateValueValuesEnum', 12) tensorflowVersion = _messages.StringField(13) class Operation(_messages.Message): """This resource represents a long-running operation that is the result of a network API call. Messages: MetadataValue: Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. ResponseValue: The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. Fields: done: If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. error: The error result of the operation in case of failure or cancellation. metadata: Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. name: The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should have the format of `operations/some/unique/name`. response: The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. """ @encoding.MapUnrecognizedFields('additionalProperties') class MetadataValue(_messages.Message): """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. Messages: AdditionalProperty: An additional property for a MetadataValue object. Fields: additionalProperties: Properties of the object. Contains field @type with type URL. """ class AdditionalProperty(_messages.Message): """An additional property for a MetadataValue object. Fields: key: Name of the additional property. value: A extra_types.JsonValue attribute. """ key = _messages.StringField(1) value = _messages.MessageField('extra_types.JsonValue', 2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) @encoding.MapUnrecognizedFields('additionalProperties') class ResponseValue(_messages.Message): """The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. Messages: AdditionalProperty: An additional property for a ResponseValue object. Fields: additionalProperties: Properties of the object. Contains field @type with type URL. """ class AdditionalProperty(_messages.Message): """An additional property for a ResponseValue object. Fields: key: Name of the additional property. value: A extra_types.JsonValue attribute. """ key = _messages.StringField(1) value = _messages.MessageField('extra_types.JsonValue', 2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) done = _messages.BooleanField(1) error = _messages.MessageField('Status', 2) metadata = _messages.MessageField('MetadataValue', 3) name = _messages.StringField(4) response = _messages.MessageField('ResponseValue', 5) class OperationMetadata(_messages.Message): """Represents the metadata of the long-running operation. Fields: apiVersion: [Output only] API version used to start the operation. cancelRequested: [Output only] Identifies whether the user has requested cancellation of the operation. Operations that have successfully been cancelled have Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`. createTime: [Output only] The time the operation was created. endTime: [Output only] The time the operation finished running. statusDetail: [Output only] Human-readable status of the operation, if any. target: [Output only] Server-defined resource path for the target of the operation. verb: [Output only] Name of the verb executed by the operation. """ apiVersion = _messages.StringField(1) cancelRequested = _messages.BooleanField(2) createTime = _messages.StringField(3) endTime = _messages.StringField(4) statusDetail = _messages.StringField(5) target = _messages.StringField(6) verb = _messages.StringField(7) class StandardQueryParameters(_messages.Message): """Query parameters accepted by all methods. Enums: FXgafvValueValuesEnum: V1 error format. AltValueValuesEnum: Data format for response. Fields: f__xgafv: V1 error format. access_token: OAuth access token. alt: Data format for response. bearer_token: OAuth bearer token. callback: JSONP fields: Selector specifying which fields to include in a partial response. key: API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. oauth_token: OAuth 2.0 token for the current user. pp: Pretty-print response. prettyPrint: Returns response with indentations and line breaks. quotaUser: Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. trace: A tracing token of the form "token:<tokenid>" to include in api requests. uploadType: Legacy upload protocol for media (e.g. "media", "multipart"). upload_protocol: Upload protocol for media (e.g. "raw", "multipart"). """ class AltValueValuesEnum(_messages.Enum): """Data format for response. Values: json: Responses with Content-Type of application/json media: Media download with context-dependent Content-Type proto: Responses with Content-Type of application/x-protobuf """ json = 0 media = 1 proto = 2 class FXgafvValueValuesEnum(_messages.Enum): """V1 error format. Values: _1: v1 error format _2: v2 error format """ _1 = 0 _2 = 1 f__xgafv = _messages.EnumField('FXgafvValueValuesEnum', 1) access_token = _messages.StringField(2) alt = _messages.EnumField('AltValueValuesEnum', 3, default=u'json') bearer_token = _messages.StringField(4) callback = _messages.StringField(5) fields = _messages.StringField(6) key = _messages.StringField(7) oauth_token = _messages.StringField(8) pp = _messages.BooleanField(9, default=True) prettyPrint = _messages.BooleanField(10, default=True) quotaUser = _messages.StringField(11) trace = _messages.StringField(12) uploadType = _messages.StringField(13) upload_protocol = _messages.StringField(14) class Status(_messages.Message): """The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model is designed to be: - Simple to use and understand for most users - Flexible enough to meet unexpected needs # Overview The `Status` message contains three pieces of data: error code, error message, and error details. The error code should be an enum value of google.rpc.Code, but it may accept additional error codes if needed. The error message should be a developer-facing English message that helps developers *understand* and *resolve* the error. If a localized user-facing error message is needed, put the localized message in the error details or localize it in the client. The optional error details may contain arbitrary information about the error. There is a predefined set of error detail types in the package `google.rpc` that can be used for common error conditions. # Language mapping The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire format. When the `Status` message is exposed in different client libraries and different wire protocols, it can be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped to some error codes in C. # Other uses The error model and the `Status` message can be used in a variety of environments, either with or without APIs, to provide a consistent developer experience across different environments. Example uses of this error model include: - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the normal response to indicate the partial errors. - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error reporting. - Batch operations. If a client uses batch request and batch response, the `Status` message should be used directly inside batch response, one for each error sub- response. - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of those operations should be represented directly using the `Status` message. - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any stripping needed for security/privacy reasons. Messages: DetailsValueListEntry: A DetailsValueListEntry object. Fields: code: The status code, which should be an enum value of google.rpc.Code. details: A list of messages that carry the error details. There is a common set of message types for APIs to use. message: A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. """ @encoding.MapUnrecognizedFields('additionalProperties') class DetailsValueListEntry(_messages.Message): """A DetailsValueListEntry object. Messages: AdditionalProperty: An additional property for a DetailsValueListEntry object. Fields: additionalProperties: Properties of the object. Contains field @type with type URL. """ class AdditionalProperty(_messages.Message): """An additional property for a DetailsValueListEntry object. Fields: key: Name of the additional property. value: A extra_types.JsonValue attribute. """ key = _messages.StringField(1) value = _messages.MessageField('extra_types.JsonValue', 2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) code = _messages.IntegerField(1, variant=_messages.Variant.INT32) details = _messages.MessageField('DetailsValueListEntry', 2, repeated=True) message = _messages.StringField(3) class TpuProjectsLocationsGetRequest(_messages.Message): """A TpuProjectsLocationsGetRequest object. Fields: name: Resource name for the location. """ name = _messages.StringField(1, required=True) class TpuProjectsLocationsListRequest(_messages.Message): """A TpuProjectsLocationsListRequest object. Fields: filter: The standard list filter. name: The resource that owns the locations collection, if applicable. pageSize: The standard list page size. pageToken: The standard list page token. """ filter = _messages.StringField(1) name = _messages.StringField(2, required=True) pageSize = _messages.IntegerField(3, variant=_messages.Variant.INT32) pageToken = _messages.StringField(4) class TpuProjectsLocationsNodesCreateRequest(_messages.Message): """A TpuProjectsLocationsNodesCreateRequest object. Fields: node: A Node resource to be passed as the request body. nodeId: The unqualified resource name. parent: The parent resource name. serviceAccount: Allows user to set the service account running on the TPU node's workers. """ node = _messages.MessageField('Node', 1) nodeId = _messages.StringField(2) parent = _messages.StringField(3, required=True) serviceAccount = _messages.StringField(4) class TpuProjectsLocationsNodesDeleteRequest(_messages.Message): """A TpuProjectsLocationsNodesDeleteRequest object. Fields: name: The resource name. """ name = _messages.StringField(1, required=True) class TpuProjectsLocationsNodesGetRequest(_messages.Message): """A TpuProjectsLocationsNodesGetRequest object. Fields: name: The resource name. """ name = _messages.StringField(1, required=True) class TpuProjectsLocationsNodesListRequest(_messages.Message): """A TpuProjectsLocationsNodesListRequest object. Fields: pageSize: The maximum number of items to return. pageToken: The next_page_token value returned from a previous List request, if any. parent: The parent resource name. """ pageSize = _messages.IntegerField(1, variant=_messages.Variant.INT32) pageToken = _messages.StringField(2) parent = _messages.StringField(3, required=True) class TpuProjectsLocationsNodesReimageRequest(_messages.Message): """A TpuProjectsLocationsNodesReimageRequest object. Fields: name: The resource name. tensorflowVersion: The version for reimage to create. """ name = _messages.StringField(1, required=True) tensorflowVersion = _messages.StringField(2) class TpuProjectsLocationsNodesResetRequest(_messages.Message): """A TpuProjectsLocationsNodesResetRequest object. Fields: name: The resource name. """ name = _messages.StringField(1, required=True) class TpuProjectsLocationsNodesUpdateStateRequest(_messages.Message): """A TpuProjectsLocationsNodesUpdateStateRequest object. Enums: StateValueValuesEnum: The state the node should be in after update. Fields: name: The resource name. state: The state the node should be in after update. """ class StateValueValuesEnum(_messages.Enum): """The state the node should be in after update. Values: STATE_UNSPECIFIED: <no description> CREATING: <no description> READY: <no description> RESTARTING: <no description> REIMAGING: <no description> DELETING: <no description> REPAIRING: <no description> """ STATE_UNSPECIFIED = 0 CREATING = 1 READY = 2 RESTARTING = 3 REIMAGING = 4 DELETING = 5 REPAIRING = 6 name = _messages.StringField(1, required=True) state = _messages.EnumField('StateValueValuesEnum', 2) class TpuProjectsLocationsOperationsDeleteRequest(_messages.Message): """A TpuProjectsLocationsOperationsDeleteRequest object. Fields: name: The name of the operation resource to be deleted. """ name = _messages.StringField(1, required=True) class TpuProjectsLocationsOperationsGetRequest(_messages.Message): """A TpuProjectsLocationsOperationsGetRequest object. Fields: name: The name of the operation resource. """ name = _messages.StringField(1, required=True) class TpuProjectsLocationsOperationsListRequest(_messages.Message): """A TpuProjectsLocationsOperationsListRequest object. Fields: filter: The standard list filter. name: The name of the operation's parent resource. pageSize: The standard list page size. pageToken: The standard list page token. """ filter = _messages.StringField(1) name = _messages.StringField(2, required=True) pageSize = _messages.IntegerField(3, variant=_messages.Variant.INT32) pageToken = _messages.StringField(4) encoding.AddCustomJsonFieldMapping( StandardQueryParameters, 'f__xgafv', '$.xgafv') encoding.AddCustomJsonEnumMapping( StandardQueryParameters.FXgafvValueValuesEnum, '_1', '1') encoding.AddCustomJsonEnumMapping( StandardQueryParameters.FXgafvValueValuesEnum, '_2', '2')
[ "kirkse710@gmail.com" ]
kirkse710@gmail.com
99102bee439d4e4060ed9c0a44aa1bfe3bb55191
29cc8671d2b4cfb3551bf822751130e769e2651d
/5multipless.py
9bfcc567ee6656d325b20c4dee4507fc11eb7655
[]
no_license
raghava430/Raghava-reddy
67360cf955e8c77e7fc7732eb70feb72fb19b3fe
5e952e0d129427705ad540052757b895ffb38542
refs/heads/master
2020-06-14T10:05:13.429124
2019-07-17T04:35:11
2019-07-17T04:35:11
194,976,566
0
1
null
null
null
null
UTF-8
Python
false
false
78
py
e=int(input()) f=1 while(f<6): g=e*f f=f+1 print(g,end=" ")
[ "noreply@github.com" ]
raghava430.noreply@github.com
f86a2ef5c5fa10d7f88154c33b7e6bf8420fc39d
cac58755bacb8cf144e05d86ddf0f590c1626aa7
/myPdf/pay_slip.py
111c94721de04117f1cf32a6b8815c0d92792ec5
[]
no_license
alaniomotosho2/automate
95d853bda06dc5279cdff894550b399a6ad5bec9
1bb7ee70941029c6092b329184c65935b6355d4c
refs/heads/master
2021-08-07T08:23:22.344109
2017-11-07T21:58:30
2017-11-07T21:58:30
108,914,450
0
0
null
null
null
null
UTF-8
Python
false
false
1,680
py
from datetime import datetime employee_data = [ { 'id': 123, 'name': 'Usman', 'payment': 10000, 'tax': 3000, 'total': 7000 }, { 'id': 245, 'name': 'Sophia', 'payment': 12000, 'tax': 4000, 'total': 8000 }, ] from fpdf import FPDF, HTMLMixin class PaySlip(FPDF, HTMLMixin): def footer(self): self.set_y(-15) self.set_font('Arial', 'I', 8) self.cell(0, 10, 'Page %s' % self.page_no(), 0, 0, 'C') def header(self): self.set_font('Arial', 'B', 15) self.cell(80) self.cell(30, 10, 'Google', 1, 0, 'C') self.ln(20) def generate_payslip(data): month = datetime.now().strftime("%B") year = datetime.now().strftime("%Y") pdf = PaySlip(format='letter') pdf.add_page() pdf.set_font("Times", size=12) pdf.cell(200, 10, txt="Pay Slip for %s, %s" %(month, year), ln=3, align="C") pdf.cell(50) pdf.cell(100, 10, txt="Employeed Id: %s" % employee_data[0]['id'],ln=1, align='L') pdf.cell(50) pdf.cell(100, 10, txt="Employeed Name: %s" % employee_data[0]['name'], ln=3, align='L') html = """ <table border="0" align="center" width="50%"> <thead><tr><th align="left" width="50%"> Pay Slip Details</th><th align="right" width="50%"> Amount in USD</th></tr></thead> <tbody> <tr><td>Payments</td><td align="right"> """ + str(employee_data[0]['payment']) + """ </td></tr> <tr><td>Tax</td><td align="right"> """ + str(employee_data[0]['tax']) + """ </td></tr> <tr><td>Total</td><td align="right"> """ + str(employee_data[0]['total']) + """</td></tr> </tbody> </table> """ pdf.write_html(html) pdf.output('payslip_%s.pdf' % employee_data[0]['id']) # this make sense,, slip is appeneded by the date for emp in employee_data: generate_payslip(emp)
[ "alaniomotosho2@gmail.com" ]
alaniomotosho2@gmail.com
c49351323bd5706e1c5df7eba562dd7673b7e486
78fda83a9cd033d84e3ff47c8f9731b8ab3ff26d
/Scripts/part2.py
9cff5153f59ef3e22aa7bc8b87b3ecc37cb50871
[]
no_license
soham-shah/fireViz
61bea14cfb97bfb51a85c49b4a0740b4f57d1161
3e00a2ec68585be443a7a6eb859870a4f1898360
refs/heads/master
2021-01-19T15:50:30.886862
2017-08-21T16:59:25
2017-08-21T16:59:25
100,973,269
0
0
null
null
null
null
UTF-8
Python
false
false
10,549
py
#!/usr/bin/python import numpy as np import pandas as pd import os import sys sys.path.append("/curc/tools/x86_64/rh6/software/visit/2.10.0/2.10.0/linux-x86_64/lib/site-packages") from visit import * import time def closeDatabases(indexString): CloseDatabase("localhost:/projects/joki9146/week_13/Data_part2/wrfout_" + indexString + ".nc") CloseDatabase("localhost:/projects/joki9146/week_13/Data_part1/katrinaTerrain.png") #open db def openDB(indexString): filename = "localhost:/projects/joki9146/week_13/Data_part2/wrfout_" + indexString + ".nc" OpenDatabase(filename, 0, "NETCDF") ActivateDatabase(filename) #load bg image def loadBGImage(lat, lon): OpenDatabase("localhost:/projects/joki9146/week_13/Data_part1/katrinaTerrain.png", 0, "Image") ActivateDatabase("localhost:/projects/joki9146/week_13/Data_part1/katrinaTerrain.png") AddPlot("Truecolor", "color", 1, 0) TruecolorAtts = TruecolorAttributes() TruecolorAtts.opacity = 1 TruecolorAtts.lightingFlag = 0 SetPlotOptions(TruecolorAtts) #add elevate SetActivePlots(1) AddOperator("Elevate", 0) ElevateAtts = ElevateAttributes() ElevateAtts.zeroFlag = 1 SetOperatorOptions(ElevateAtts, 0) #add transform AddOperator("Transform", 0) TransformAtts = TransformAttributes() TransformAtts.doScale = 1 TransformAtts.scaleX = 0.43 TransformAtts.scaleY = 0.68 TransformAtts.scaleZ = 1 SetOperatorOptions(TransformAtts, 1) #add transform AddOperator("Transform", 0) TransformAtts = TransformAttributes() TransformAtts.doTranslate = 1 TransformAtts.translateX = -lon TransformAtts.translateY = -lat TransformAtts.translateZ = 0 SetOperatorOptions(TransformAtts, 2) def plotWind(): DefineVectorExpression("wind", "{U, V, W}") DefineScalarExpression("windMag", "magnitude(wind)") AddPlot("Vector", "wind") #add slice AddOperator("Slice", 0) SliceAtts = SliceAttributes() SliceAtts.originType = SliceAtts.Intercept # Point, Intercept, Percent, Zone, Node SliceAtts.originIntercept = 5 SliceAtts.normal = (0, 0, 1) SliceAtts.axisType = SliceAtts.ZAxis # XAxis, YAxis, ZAxis, Arbitrary, ThetaPhi SliceAtts.upAxis = (0, 1, 0) SliceAtts.project2d = 0 SliceAtts.meshName = "as_zonal/mesh315x309" SetOperatorOptions(SliceAtts, 0) #wind vec attrs VectorAtts = VectorAttributes() VectorAtts.nVectors = 4000 VectorAtts.lineStyle = VectorAtts.SOLID # SOLID, DASH, DOT, DOTDASH VectorAtts.scale = 0.08 VectorAtts.scaleByMagnitude = 1 VectorAtts.autoScale = 0 VectorAtts.headSize = 0.3 VectorAtts.headOn = 1 VectorAtts.colorByMag = 1 VectorAtts.lineStem = VectorAtts.Cylinder # Cylinder, Line VectorAtts.stemWidth = 0.1 VectorAtts.glyphType = VectorAtts.Arrow # Arrow, Ellipsoid VectorAtts.vectorOrigin = VectorAtts.Middle # Head, Middle, Tail VectorAtts.geometryQuality = VectorAtts.High # Fast, High VectorAtts.useLegend = 0 SetPlotOptions(VectorAtts) def plotStreamtline(): AddPlot("Streamline", "wind") StreamlineAtts = StreamlineAttributes() StreamlineAtts.sourceType = StreamlineAtts.SpecifiedCircle # SpecifiedPoint, SpecifiedPointList, SpecifiedLine, SpecifiedCircle, SpecifiedPlane, SpecifiedSphere, SpecifiedBox, Selection StreamlineAtts.planeOrigin = (155, 155, 5) StreamlineAtts.planeNormal = (0, 0, 1) StreamlineAtts.planeUpAxis = (0, 1, 0) StreamlineAtts.radius = 100 StreamlineAtts.sampleDensity0 = 9 StreamlineAtts.sampleDensity1 = 4 StreamlineAtts.integrationDirection = StreamlineAtts.Both # Forward, Backward, Both StreamlineAtts.maxSteps = 1000 StreamlineAtts.limitMaximumTimestep = 1 StreamlineAtts.maxTimeStep = 0.01 StreamlineAtts.displayMethod = StreamlineAtts.Tubes # Lines, Tubes, Ribbons StreamlineAtts.varyTubeRadius = StreamlineAtts.Scalar # None, Scalar StreamlineAtts.varyTubeRadiusFactor = 10 StreamlineAtts.colorTableName = "hot" StreamlineAtts.coloringMethod = StreamlineAtts.ColorByVariable # Solid, ColorBySpeed, ColorByVorticity, ColorByLength, ColorByTime, ColorBySeedPointID, ColorByVariable, ColorByCorrelationDistance, ColorByNumberDomainsVisited StreamlineAtts.coloringVariable = "windMag" StreamlineAtts.tubeRadiusAbsolute = 0.125 StreamlineAtts.tubeRadiusBBox = 0.0025 StreamlineAtts.showSeeds = 0 StreamlineAtts.varyTubeRadius = StreamlineAtts.Scalar # None, Scalar StreamlineAtts.varyTubeRadiusFactor = 6 StreamlineAtts.varyTubeRadiusVariable = "windMag" StreamlineAtts.legendFlag = 0 SetPlotOptions(StreamlineAtts) #SetActivePlots(3) #RemoveOperator(0, 0) #add clouds def addClouds(): AddPlot("Volume", "QCLOUD", 1, 0) SetActivePlots(4) AddOperator("Transform", 0) TransformAtts = TransformAttributes() TransformAtts.doScale = 1 TransformAtts.scaleOrigin = (0, 0, 0) TransformAtts.scaleX = 1 TransformAtts.scaleY = 1 TransformAtts.scaleZ = 3 SetOperatorOptions(TransformAtts, 0) VolumeAtts = VolumeAttributes() VolumeAtts.legendFlag = 0 VolumeAtts.colorControlPoints.GetControlPoints(0).colors = (220, 220, 220, 0) VolumeAtts.colorControlPoints.GetControlPoints(0).position = 0 VolumeAtts.colorControlPoints.GetControlPoints(1).colors = (240, 240, 240, 255) VolumeAtts.colorControlPoints.GetControlPoints(1).position = 0.34106 VolumeAtts.colorControlPoints.GetControlPoints(2).colors = (255, 255, 255, 255) VolumeAtts.colorControlPoints.GetControlPoints(2).position = 1 VolumeAtts.colorControlPoints.smoothing = VolumeAtts.colorControlPoints.Linear # None, Linear, CubicSpline VolumeAtts.colorControlPoints.equalSpacingFlag = 0 VolumeAtts.colorControlPoints.discreteFlag = 0 VolumeAtts.opacityAttenuation = 1 VolumeAtts.opacityMode = VolumeAtts.ColorTableMode # FreeformMode, GaussianMode, ColorTableMode VolumeAtts.resampleFlag = 1 VolumeAtts.resampleTarget = 10000000 VolumeAtts.rendererType = VolumeAtts.Splatting # Splatting, Texture3D, RayCasting, RayCastingIntegration, SLIVR, RayCastingSLIVR, Tuvok VolumeAtts.gradientType = VolumeAtts.SobelOperator # CenteredDifferences, SobelOperator VolumeAtts.transferFunctionDim = 1 SetPlotOptions(VolumeAtts) #add hot towers def addHotTowers(): AddPlot("Pseudocolor", "QCLOUD", 1, 0) SetActivePlots(5) AddOperator("Transform", 0) TransformAtts = TransformAttributes() TransformAtts.doScale = 1 TransformAtts.scaleOrigin = (0, 0, 0) TransformAtts.scaleX = 1 TransformAtts.scaleY = 1 TransformAtts.scaleZ = 3 SetOperatorOptions(TransformAtts, 0) AddOperator("Isovolume", 0) IsovolumeAtts = IsovolumeAttributes() IsovolumeAtts.lbound = 0.0005 IsovolumeAtts.ubound = 1e+37 IsovolumeAtts.variable = "default" SetOperatorOptions(IsovolumeAtts, 0) PseudocolorAtts = PseudocolorAttributes() PseudocolorAtts.maxFlag = 1 PseudocolorAtts.max = 0.0015 PseudocolorAtts.centering = PseudocolorAtts.Zonal # Natural, Nodal, Zonal PseudocolorAtts.colorTableName = "Reds" PseudocolorAtts.legendFlag = 0 PseudocolorAtts.smoothingLevel = 2 SetPlotOptions(PseudocolorAtts) #add rainfall def addRainfall(): AddPlot("Pseudocolor", "RAINNC", 1, 0) SetActivePlots(6) PseudocolorAtts = PseudocolorAttributes() PseudocolorAtts.colorTableName = "RAINNC" PseudocolorAtts.opacityType = PseudocolorAtts.ColorTable # ColorTable, FullyOpaque, Constant, Ramp, VariableRange PseudocolorAtts.lightingFlag = 0 PseudocolorAtts.legendFlag = 0 SetPlotOptions(PseudocolorAtts) AddOperator("Elevate", 0) ElevateAtts = ElevateAttributes() ElevateAtts.zeroFlag = 1 SetOperatorOptions(ElevateAtts, 0) AddOperator("Transform", 0) TransformAtts = TransformAttributes() TransformAtts.doTranslate = 1 TransformAtts.translateX = 0 TransformAtts.translateY = 0 TransformAtts.translateZ = 0.05 SetOperatorOptions(TransformAtts, 0) #add light def addLight(): light1 = LightAttributes() light1.enabledFlag = 1 light1.type = light1.Object # Ambient, Object, Camera light1.direction = (0, 0, -1) light1.color = (255, 255, 255, 255) light1.brightness = 0.5 SetLight(1, light1) def annotation(): AnnotationAtts = AnnotationAttributes() AnnotationAtts.axes2D.visible = 0 AnnotationAtts.axes3D.visible = 0 AnnotationAtts.axes3D.triadFlag = 0 AnnotationAtts.axes3D.bboxFlag = 0 AnnotationAtts.userInfoFlag = 0 AnnotationAtts.databaseInfoFlag = 0 AnnotationAtts.legendInfoFlag = 0 AnnotationAtts.axesArray.visible = 0 AnnotationAtts.backgroundColor = (0, 0, 0, 255) SetAnnotationAttributes(AnnotationAtts) #set view angle def setView(): View3DAtts = View3DAttributes() View3DAtts.viewNormal = (-0.745356, -0.596285, 0.298142) View3DAtts.focus = (153.99998, 156.99997, 0) View3DAtts.viewUp = (0, 0, 1) View3DAtts.imagePan = (0, .03) View3DAtts.imageZoom = 4 SetView3D(View3DAtts) def saveFile(fileIndex): SaveWindowAtts = SaveWindowAttributes() SaveWindowAtts.outputToCurrentDirectory = 0 SaveWindowAtts.outputDirectory = "/projects/joki9146/week_13/output/" SaveWindowAtts.fileName = "katrina"+fileIndex SaveWindowAtts.family = 0 SaveWindowAtts.format = SaveWindowAtts.PNG # BMP, CURVE, JPEG, OBJ, PNG, POSTSCRIPT, POVRAY, PPM, RGB, STL, TIFF, ULTRA, VTK, PLY SaveWindowAtts.width = 1024 SaveWindowAtts.height = 1024 SaveWindowAtts.compression = SaveWindowAtts.PackBits # None, PackBits, Jpeg, Deflate SaveWindowAtts.forceMerge = 0 SetSaveWindowAttributes(SaveWindowAtts) SaveWindow() def readLatsLons(file): fPath = os.path.join(cwDir, file) df = pd.read_csv(fPath) lats = df['Lat'].values lons = df['Lon'].values lat=[] lon=[] for i in range(0,lats.size): lat.append(lats[i]-lats[0]) for i in range(0,lons.size): lon.append(lons[i]-lons[0]) lat=np.asarray(lat) lon=np.asarray(lon) return lat, lon def readTimes(file): fPath = os.path.join(cwDir, file) df = pd.read_csv(fPath) time = df['Times'].values return time def convertLat(lat): print lat factor = 27.43435 coord = (lat) * factor print coord return coord def convertLon(lon): print lon factor = -24.07495 coord = (lon) * factor print coord return coord #main print "started" i = int(sys.argv[1]) print i cwDir = "/projects/joki9146/week_13/Data_part2/" lats, lons = readLatsLons("latslons.csv") times = readTimes("Times.csv") Launch() loadBGImage(convertLat(lats[i]), convertLon(lons[i])) openDB(str(i).zfill(3)) plotWind() plotStreamtline() addClouds() addHotTowers() addRainfall() addLight() annotation() setView() DrawPlots() saveFile(str(i).zfill(3)) DeleteAllPlots() closeDatabases(str(i).zfill(3)) Close()
[ "sohamshah225@gmail.com" ]
sohamshah225@gmail.com
ce9556d7e5b4f79026943d6b28014f74995039fa
bc38678b79fee6d92c5fe73ce6a56854421f5b70
/github_unit_1/Mod_5/sierra_python_module04-master orig/my_d_nesting.py
071f108ecf481fca1ba89863f26d8c846301b9c2
[]
no_license
JOYFLOWERS/joyflowers.github.io
8a6f757595e4a0cdca621fa4210ac021a87de679
c8417cd06489e04009a773c56f334ea629ff3905
refs/heads/master
2020-07-21T15:49:37.448128
2019-12-14T03:37:31
2019-12-14T03:37:31
206,913,024
0
0
null
null
null
null
UTF-8
Python
false
false
2,536
py
# List Nesting # Since a list can contain any type of object as an element, and a list is itself an object, a list can contain another list as an element. # Such embedding of a list inside another list is known as list nesting.Ex: The code my_list = [[5, 13], [50, 75, 100]] creates a list with two elements # that are each another list. my_list = [[10, 20], [30, 40]] print('First nested list:', my_list[0]) print('Second nested list:', my_list[1]) print('Element 0 of first nested list:', my_list[0][0]) # A list is a single-dimensional sequence of items, like a series of times, data samples, daily temperatures, etc. # List nesting allows for a programmer to also create a multi-dimensional data structure, the simplest being a two-dimensional table, # like a spreadsheet or tic-tac-toe board. The following code defines a two-dimensional table using nested lists: tic_tac_toe = [ ['X', 'O', 'X'], [' ', 'X', ' '], ['O', 'O', 'X'] ] print(tic_tac_toe[0][0], tic_tac_toe[0][1], tic_tac_toe[0][2]) print(tic_tac_toe[1][0], tic_tac_toe[1][1], tic_tac_toe[1][2]) print(tic_tac_toe[2][0], tic_tac_toe[2][1], tic_tac_toe[2][2]) # The example above creates a variable tic_tac_toe that represents a 2-dimensional table with 3 rows and 3 columns, for 3*3=9 total table entries. # Each row in the table is a nested list. Table entries can be accessed by specifying the desired row and column: tic_tac_toe [1][1] accesses the middle square # in row 1, column 1 (starting from 0), which has a value of 'X'. The following code illustrates: currency = [ [1.00, 5.00, 10.0], # US Dollars [0.75, 3.77, 7.53], # Euros [0.65, 3.25, 6.50] # British pounds ] for row in currency: for cell in row: print(cell, end=' ') print() ###Challenge 1### # Print the two-dimensional list mult_table by row and column. Hint: Use nested loops. # Sample output with input: '1 2 3,2 4 6,3 6 9': # 1 | 2 | 3 # 2 | 4 | 6 # 3 | 6 | 9 user_input= input('Enter nine numbers in the following format 1 2 3,2 4 6,3 6 9 ') lines = user_input.split(',') # # This line uses a construct called a list comprehension, introduced elsewhere, # # to convert the input string into a two-dimensional list. # # Ex: 1 2, 2 4 is converted to [ [1, 2], [2, 4] ] mult_table = [[int(num) for num in line.split()] for line in lines] for i in range(len(mult_table)): for j in range(len(mult_table)): print(mult_table[i][j],'|',end=' ') print('')
[ "noreply@github.com" ]
JOYFLOWERS.noreply@github.com
09cace0bf73c69539cf1e99a98b7a6f3ed08f833
5328f77114a898f1c75bf82176306a9ab83a3473
/models/clients.py
1ab3394ff6e1a3a584d126ddfc7b641f30095cee
[]
no_license
prabakaran04/prabakaran
2e207e0dc17cb0c39340b05683fda750eae45eaa
b6f8268192dcffcd095486527777d4edeaafdf68
refs/heads/master
2023-03-11T14:10:38.576472
2019-07-18T13:29:04
2019-07-18T13:29:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,325
py
from odoo import models,fields,api from odoo.exceptions import ValidationError class ClientDetails(models.Model): _name = 'client.details' _rec_name='client_name' client_id = fields.Char(default ='new') client_name = fields.Char(string ='Client name') address = fields.Char(string ='Address') client_email = fields.Char(string = 'Email') mobile = fields.Char(string = 'Mobile') status = fields.Selection(string = 'status' , selection=[('gold', 'Gold'),('silver','Silver'),('bronze','bronze')]) client_sex = fields.Selection(string = "Sex", selection=[('male','Male'),('female','Female')]) date =fields.Datetime(string = "created on" , default=fields.Datetime.now) @api.model def create(self , vals): if vals.get('client_id','new') =='new': vals['client_id'] = self.env['ir.sequence']. next_by_code('client.details') or '/' return super(ClientDetails , self). create(vals) @api.constrains('client_name') def _check_name(self): for val in self: if val['client_name']: if len(val["client_name"])<6: raise ValidationError("name is too short, must be more than 6 character") _sql_constraints =[('client_name_unique','unique(client_name)','name already exists')]
[ "prabakaran@sodexis.com" ]
prabakaran@sodexis.com
fbc7694ea37606dbb8b3d679815129d939c33700
ee7cde00d334cf625e309a7157e331e450a7056d
/scripts/json_toolpath_analyzer.py
205d254edb0b33031dba04f9af66c048882ae369
[]
no_license
makerbot/TestFiles
29a73a135b53ce2c447501c4788c8cceaa1075e4
ba16bccad29646e0ce4379adb33632fb9799b852
refs/heads/master
2021-01-19T02:15:42.711380
2016-07-29T17:45:20
2016-07-29T17:45:20
2,892,052
4
2
null
null
null
null
UTF-8
Python
false
false
15,145
py
import os import sys import re import math import argparse import copy import json layer_begin = re.compile('^(\(|;)(<layer>|Slice) [\d.]+.*(\)|:)?$') paramcodes = 'XYZFABE' g1re = re.compile('^G1\s+(?P<param>(['+paramcodes+']-?\d+(\.\d*)?\s*)+)(?P<comment>.*)$') paramre = re.compile('(?P<code>['+paramcodes+'])(?P<value>-?\d+(\.\d*)?)') def formatParamDict(params, category = ''): '''Convert a dict into an xml-like format''' return reduce(lambda a,b: '%s %s=\"%s\"' % ((a,) + b), params.iteritems(), category) def writeSvg(output, elements): '''Write elements (an iterable) to output (a file-like thing)''' output.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>\n") output.write("<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n") for element in elements: if element: output.write(element + '\n') output.write("</svg>\n") def decodeCommand(command): '''Decode a G1 command or layer change into a dict.''' params = dict() params['line']=filter(lambda a: a!='\n',command) if layer_begin.match(command): params['layer']=True g1match = g1re.match(command) if None is not g1match: params['G1']=True data = paramre.finditer(g1match.group('param')) for match in data: params[match.group('code')] = float(match.group('value')) if 'layer' in params: sys.stdout.write('.') sys.stdout.flush() return params def encodeCommand(command): '''Reconstruct a decoded command.''' if 'G1' in command: foo = lambda a,b: ('%s%s')%(a,((' '+b+str(command[b])) if b in command else ''),) if 'old' in command: return reduce(foo, paramcodes, 'OLD: %s\nNEW: G1' % (encodeCommand(command['old']))) else: return reduce(foo, paramcodes, 'G1') else: try: return command['line'] except KeyError as ke: return '' def interpretCommand(command, md = None): '''Get a style string from a preprocessed command.''' def speedConvert(s): if None is md: s = (s / 5000.0) * 256.0 ** 2 c = [256.0 ** 2, 256.0, 256.0] sc = [math.fmod(s, p) * 256.0/p for p in c] ret = [int(sci) for sci in sc] else: clamp = 2.0 split = 0.5 if md[1] != 0: v = (s - md[0]) / md[1] else: v = 0.0 v = max(v, -clamp) v = min(v, clamp) v = (v + clamp) / (2.0 * clamp) b = 0.0 if v < split: a = v / split #a = math.sqrt(a) c = b else: a = b c = (v - split) / (1.0 - split) #c = math.sqrt(c) ret = [int(255 * j) for j in (a,b,c)] #print s, sc return ret def paramConvert(sc): return (sc[0], sc[1], sc[2], 2.0) speedParam = lambda s: paramConvert(speedConvert(s)) if 'G1' in command: for axis in 'ABE': if axis in command and axis in command['old']: volume = command[axis] - command['old'][axis] break if volume == 0: #travel move params = (0,255,0,1) else: params = speedParam(command['F']) return 'stroke:rgb(%s,%s,%s);stroke-width:%s' % params elif 'type' in command and command['type'] == 'movement': volume = command['volume'] if volume == 0: #travel move params = params = (0,255,0,1) else: params = speedParam(command['speed']) return 'stroke:rgb(%s,%s,%s);stroke-width:%s' % params else: return None def parseCommands(commands): '''Get a list of decoded commands from the commands iterable''' sys.stdout.write('\nReading Commands\n') sys.stdout.flush() return [decodeCommand(command) for command in commands] def dropInitCommands(commands): ''' Drop all things before the first layer label in decoded commands. Returns a list containing only commands from the first layer label ''' for index in range(len(commands)): if 'layer' in commands[index]: return commands[index:] def offsetCommands(commands, offset = (0.0,0.0), scale=10.0): ''' Make all X,Y coordinates in commands positive plus offset. commands is an iterable of decoded commands. offset is a coordinate pair. All commands will be moved such that no command is below offset. scale will increase the size of things ''' minimums = dict({'x':999.0, 'y':999.0}) maximums = dict({'x':-999.0, 'y':-999.0}) offset = dict({'x':offset[0], 'y':offset[1]}) sys.stdout.write('\nDetecting Extents\n') sys.stdout.flush() for command in commands: for axis in 'xy': if axis in command["command"]["parameters"]: minimums[axis] = min(minimums[axis],command["command"]["parameters"][axis]) maximums[axis] = max(maximums[axis],command["command"]["parameters"][axis]) print '\nMinimums:', '%s\t%s' % tuple([minimums[a] for a in 'xy']) print 'Maximums:', '%s\t%s' % tuple([maximums[a] for a in 'xy']) sys.stdout.write('\nTransforming Coordinates\n') sys.stdout.flush() for command in commands: for axis in 'xy': if axis in command["command"]["parameters"]: if 'x' == axis: command["command"]["parameters"][axis] = (command["command"]["parameters"][axis] - minimums[axis]) * scale + offset[axis] else: command["command"]["parameters"][axis] = (maximums[axis] - command["command"]["parameters"][axis]) * scale + offset[axis] def preprocessCommands(commands): '''Add relative information to each command for use in drawing svgs''' oldCommand = dict() currentCommand = dict() sys.stdout.write('\nParsing Command Transitions\n') sys.stdout.flush() for command in commands: currentCommand.update(command) currentCommand['old'] = copy.deepcopy(oldCommand) oldCommand.update(currentCommand) command.update(currentCommand) del oldCommand['old'] def postprocessCommands(commands): '''Convert preprocessed commands into a json-ready dict''' layers = [] movements = [] last_z = 0 for command in commands: if last_z != command["command"]["parameters"]["z"]: if len(movements) > 0: layers.append(movements) movements = [] if command["command"]["function"] == "move" and "command" in command["old"]: #try: movement = dict({'type': 'movement'}) oldPos = dict() newPos = dict() oldPos['x'] = command['old']["command"]["parameters"]['x'] oldPos['y'] = command['old']["command"]["parameters"]['y'] newPos['x'] = command["command"]["parameters"]['x'] newPos['y'] = command["command"]["parameters"]['y'] movement['from'] = oldPos movement['to'] = newPos movement['speed'] = command["command"]["parameters"]['feedrate'] movement['relative'] = dict() for axis in 'xy': movement['relative'][axis] = movement['to'][axis] - movement['from'][axis] movement['distance'] = math.sqrt(movement['relative']['x']**2 + movement['relative']['y']**2) tool = 'a' if 'a' in command["command"]["parameters"]: movement['volume'] = command["command"]["parameters"]['a'] - command['old']["command"]["parameters"]['a'] last_z = command["command"]["parameters"]["z"] movements.append(movement) #except KeyError as ke: # print("Key Error") # pass outDict = dict() outDict['layers'] = [] for layer in layers: curLayer = dict({'movements' : layer}) outDict['layers'].append(curLayer) return outDict def distribution(values): '''From list of numeric types get (mean, std deviation, min, max)''' E = 0.0 E2 = 0.0 counter = 0 M = None m = None for value in values: E += value E2 += value ** 2 counter += 1 if None is M: M = value else: M = max(M, value) if None is m: m = value else: m = min(m, value) E /= counter E2 /= counter return (E, math.sqrt(E2 - E ** 2), m, M) def processedDistribution(commands): ''' From a list of processed commands, get (mean, std deviation) ''' try: largest = max(c['speed'] for c in commands if c['volume'] != 0 and c['distance'] != 0) except ValueError as ve: largest = 0 try: d = distribution(c['speed'] for c in commands if c['volume'] != 0 and c['distance'] != 0) except ZeroDivisionError as zde: d = 0 return d def parseArgs(argv): parser=argparse.ArgumentParser( description="Generate customizable analysis of GCode in svg form.") #MONKEY PATCH BEGIN def argparse_error_override(message): parser.print_help() parser.exit(2) parser.error=argparse_error_override #MONKEY PATCH END parser.add_argument( 'json_path', help='path of json to analyze') parser.add_argument( 'OUTPUT_PATH', type=os.path.abspath, nargs='?', help='top folder where to place generated files', default=None) return parser.parse_args(argv) def commandToSvg(command, arg = None): '''Convert a single processed movement to an svg line''' if 'old' in command: #work on a preprocessed command relative = dict() for param in paramcodes: if param in command and param in command['old']: relative[param] = command[param] - command['old'][param] lineparams = dict() try: lineparams['x1'] = command['old']["command"]["parameters"]['x'] lineparams['y1'] = command['old']["command"]["parameters"]['y'] lineparams['x2'] = command["command"]["parameters"]['x'] lineparams['y2'] = command["command"]["parameters"]['y'] lineparams['style'] = interpretCommand(command, arg) return '<%s />' % (formatParamDict(lineparams, 'line'), ) except KeyError as ke: pass elif 'type' in command and command['type'] == 'movement': #work on a postprocessed command try: if command ['distance'] > 0: #line lineparams = dict({ 'x1': command['from']['x'], 'y1': command['from']['y'], 'x2': command['to']['x'], 'y2': command['to']['y'], 'style': interpretCommand(command, arg) }) return '<%s />' % (formatParamDict(lineparams, 'line'), ) else: #reversal? if command['volume'] < 0: #reverse color = 'blue' elif command['volume'] > 0: #restart color = 'red' else: color = 'rgb(0,255,0)' roundparams = dict({ 'cx': command['to']['x'], 'cy': command['to']['y'], 'r': 4.0, 'stroke': 'none', 'fill': color }) return '<%s />' % (formatParamDict(roundparams, 'circle'), ) except KeyError as ke: pass return None def monolithicPre(commands, out_dir): ''' Cause svg files to appear in out_dir/svg. Return a list of file names written ''' layer_num = 0 layer_name = None oldCommands = [] outFiles = [] sys.stdout.write('\nRendering SVG files\n') sys.stdout.flush() for command in commands: if 'layer' in command: sys.stdout.write('.') sys.stdout.flush() if None is not layer_name: ofilename = os.path.join(out_dir, 'svg', 'layer_%s.svg' % (layer_num)) with open(ofilename, 'w') as ofile: writeSvg(ofile, [commandToSvg(c) for c in oldCommands]) outFiles.append(ofilename) layer_name = command['layer'] layer_num += 1 oldCommands = [] else: oldCommands.append(command) return outFiles def monolithicPost(commands, out_dir): layer_num = 0 outFiles = [] sys.stdout.write('\nRendering SVG files\n') sys.stdout.flush() for layer in commands['layers']: sys.stdout.write('.') sys.stdout.flush() ofilename = os.path.join(out_dir, 'svg', 'layer_%s.svg' % (layer_num)) outFiles.append(ofilename) with open(ofilename, 'w') as ofile: md = processedDistribution(layer['movements']) lines = [commandToSvg(c, md) for c in layer['movements']] #circles = ['<%s />' % formatParamDict(c, 'circle') # for c in computeCurvature(layer['movements'])] writeSvg(ofile, lines) layer_num += 1 return outFiles def monolithicFunc(commands, out_dir): if isinstance(commands, dict) and 'layers' in commands: return monolithicPost(commands, out_dir) else: return monolithicPre(commands, out_dir) def renderIndex(listOfFiles, infile, output): output.write('<html><head><title>%s</title></head><body>\n' % (infile)) output.write('<table>\n') for file in listOfFiles: output.write('\t<tr>\n') output.write('\t\t<td>\n') output.write('\t\t\t<a href=\"%s\">%s</a>\n' % (file, os.path.basename(file))) output.write('\t\t</td>\n') output.write('\t</tr>\n') output.write('</table>\n') output.write('</body></html>') def main(argv = None): if None is argv: argv = sys.argv args = parseArgs(argv[1:]) if None is args.OUTPUT_PATH: args.OUTPUT_PATH = os.path.dirname(args.json_path) OUTPUT_SVG = os.path.join(args.OUTPUT_PATH, 'svg') if not os.path.exists(OUTPUT_SVG): os.makedirs(OUTPUT_SVG) f = open(args.json_path) json_file = json.load(f) offsetCommands(json_file, (32.0,32.0), 10) preprocessCommands(json_file) commandsDict = postprocessCommands(json_file) outFiles = monolithicFunc(commandsDict, args.OUTPUT_PATH) with open(os.path.join(args.OUTPUT_PATH, 'index.html'), 'w') as outIndex: renderIndex(outFiles, os.path.basename(args.json_path), outIndex) if __name__ == '__main__': main()
[ "alison.nj.leonard@gmail.com" ]
alison.nj.leonard@gmail.com
6c77b0407a9a802d567bc0923cd32c4be391bf5a
6c47652bc93ceef2b054fa9759481e70a22de2f1
/225_Fig2g_diableN_y.py
4cca2a370829a583b5c2fbe0d662617cc0710a97
[]
no_license
peakqi/RaI
4c174840ce5affa4dde3990892fb48903b9766a2
6528cc100506e3a491d665d09d620ac9be3013a3
refs/heads/master
2020-05-25T10:47:43.976805
2019-05-22T05:08:09
2019-05-22T05:08:09
187,766,577
0
0
null
null
null
null
UTF-8
Python
false
false
15,991
py
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import matplotlib.pyplot as plt import numpy as np from imgaug import augmenters as iaa import os import scipy as sp from sklearn import linear_model from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error LearningRate = 0.001 # shrink to 0.60 def affine_transform_60(b_x): xx = np.random.uniform(low=0, high=0, size=1) # (-0.5,0.5) yy = np.random.uniform(low=0, high=0, size=1) sx = np.random.uniform(low=0.60, high=0.60, size=1) # (.5,1.2) sy = np.random.uniform(low=0.60, high=0.60, size=1) rr = np.random.uniform(low=0, high=0, size=1) # (-0.5,0.5) sz1, sz2 = b_x.shape images = b_x.reshape([sz1, 28, 28, 1]) seq = iaa.Sequential( [iaa.Affine(translate_percent={"x": xx, "y": yy}, scale={"x": sx, "y": sy}, rotate=rr * 180, )]) images_aug = seq.augment_images(images) b_x = np.reshape(images_aug, [sz1, sz2]) return b_x, np.concatenate((xx, yy, rr), axis=0) # mv x def affine_transform_rand_x(b_x): xx = np.random.uniform(low=-0.2, high=0.2, size=1) # (-0.5,0.5) yy = 0 sx = 1 # (.5,1.2) sy = 1 rr = 0 # (-0.5,0.5) sz1, sz2 = b_x.shape images = b_x.reshape([sz1, 28, 28, 1]) seq = iaa.Sequential( [iaa.Affine(translate_percent={"x": xx, "y": yy}, scale={"x": sx, "y": sy}, rotate=rr * 180, )]) images_aug = seq.augment_images(images) b_x = np.reshape(images_aug, [sz1, sz2]) return b_x # mv y def affine_transform_rand_y(b_x): xx = 0 # (-0.5,0.5) yy = np.random.uniform(low=-0.2, high=0.2, size=1) sx = 1 # (.5,1.2) sy = 1 rr = 0 # (-0.5,0.5) sz1, sz2 = b_x.shape images = b_x.reshape([sz1, 28, 28, 1]) seq = iaa.Sequential( [iaa.Affine(translate_percent={"x": xx, "y": yy}, scale={"x": sx, "y": sy}, rotate=rr * 180, )]) images_aug = seq.augment_images(images) b_x = np.reshape(images_aug, [sz1, sz2]) return b_x, np.concatenate((xx, yy, rr), axis=0) # rtt def affine_transform_rand_r(b_x): xx = 0 # (-0.5,0.5) yy = 0 sx = 1 # (.5,1.2) sy = 1 rr = np.random.uniform(low=-0.2, high=0.2, size=1) # (-0.5,0.5) sz1, sz2 = b_x.shape images = b_x.reshape([sz1, 28, 28, 1]) seq = iaa.Sequential( [iaa.Affine(translate_percent={"x": xx, "y": yy}, scale={"x": sx, "y": sy}, rotate=rr * 180, )]) images_aug = seq.augment_images(images) b_x = np.reshape(images_aug, [sz1, sz2]) return b_x #mv x=deltaX def affine_transform_delta_x(b_x,deltaX): xx = deltaX # (-0.5,0.5) yy = 0 sx = 1 # (.5,1.2) sy = 1 rr = 0 # (-0.5,0.5) sz1, sz2 = b_x.shape images = b_x.reshape([sz1, 28, 28, 1]) seq = iaa.Sequential( [iaa.Affine(translate_percent={"x": xx, "y": yy}, scale={"x": sx, "y": sy}, rotate=rr * 180, )]) images_aug = seq.augment_images(images) b_x = np.reshape(images_aug, [sz1, sz2]) return b_x def affine_transform_delta_y(b_x,deltaY): xx = 0 # (-0.5,0.5) yy = deltaY sx = 1 # (.5,1.2) sy = 1 rr = 0 # (-0.5,0.5) sz1, sz2 = b_x.shape images = b_x.reshape([sz1, 28, 28, 1]) seq = iaa.Sequential( [iaa.Affine(translate_percent={"x": xx, "y": yy}, scale={"x": sx, "y": sy}, rotate=rr * 180, )]) images_aug = seq.augment_images(images) b_x = np.reshape(images_aug, [sz1, sz2]) return b_x XX = 0.2 SX1 = .5 SX2 = 0.7 RX = 0.2 # total mv def affine_transform1(b_x): xx = np.random.uniform(low=-XX, high=XX, size=1) # (-0.5,0.5) yy = np.random.uniform(low=-XX, high=XX, size=1) sx = np.random.uniform(low=SX1, high=SX2, size=1) # (.5,1.2) sy = np.random.uniform(low=SX1, high=SX2, size=1) rr = np.random.uniform(low=-RX, high=RX, size=1) # (-0.5,0.5) sz1, sz2 = b_x.shape images = b_x.reshape([sz1, 28, 28, 1]) seq = iaa.Sequential( [iaa.Affine(translate_percent={"x": xx, "y": yy}, scale={"x": sx, "y": sy}, rotate=rr * 180, )]) images_aug = seq.augment_images(images) b_x = np.reshape(images_aug, [sz1, sz2]) return b_x, np.concatenate((xx, yy, rr), axis=0) def cal_w_stats(we, wep): wed = we - wep; wed_max = np.amax(wed); wed_min = np.amin(wed); wed_avg = np.average(wed); wed_abs_avg = np.average(np.abs(wed)); we_std = np.std(we); we_avg = np.average(we) we_absavg = np.average(np.abs(we)) return np.concatenate((wed_max.reshape([1]), wed_min.reshape([1]), wed_avg.reshape([1]), wed_abs_avg.reshape([1]), we_std.reshape([1]), we_avg.reshape([1]),we_absavg.reshape([1]))) tf.set_random_seed(1) BATCH_SIZE = 128 N_TEST_IMG = 10 x_step=100;x_step2=x_step/2; x=(np.arange(x_step)-x_step2)/x_step2*0.2 mnist = input_data.read_data_sets('./mnist', one_hot=False) # use not one-hotted target data test_x = mnist.test.images[:BATCH_SIZE] test_x, para = affine_transform_60(test_x) #(128, 784) All chg to 0.60 size for i in range(BATCH_SIZE): test_x[i, :] = affine_transform_rand_r(np.reshape(test_x[i], [1, 784])) #rtt test_x[i, :] = affine_transform_rand_x(np.reshape(test_x[i], [1, 784])) #mv y test_x_=np.zeros([x_step,BATCH_SIZE,784]) for i in range(x_step): test_x_[i,:,:]=affine_transform_delta_y(test_x,x[i]) #mv x=deltaX (deltx,Batch,784) v_step=10;v_step2=v_step/2;VIEW_SIZE=3 v=(np.arange(v_step)-v_step2)/v_step2*0.2 view_x = mnist.test.images[BATCH_SIZE+1:BATCH_SIZE+1+VIEW_SIZE] view_x, para = affine_transform_60(view_x) for i in range(VIEW_SIZE): view_x[i, :] = affine_transform_rand_r(np.reshape(view_x[i], [1, 784])) #rtt view_x[i, :] = affine_transform_rand_x(np.reshape(view_x[i], [1, 784])) #mv y view_x_=np.zeros([v_step,VIEW_SIZE,784]) for i in range(v_step): view_x_[i,:,:]=affine_transform_delta_y(view_x,v[i]) #mv x=deltaX (deltx,Batch,784) scale1 = 4 n_l0 = 64 * scale1; n_l1 = 32 * scale1; n_l2 = 16 * scale1; n_l3 = 8 * scale1; n_encoded = 32 # 4*scale1#pow(4,ii) n_d0 = 8 * scale1; n_d1 = 16 * scale1; n_d2 = 32 * scale1; n_d3 = 64 * scale1; n_decoded = 784 print(n_encoded) type = '_n_' + str(n_encoded) + '-batch' + str(BATCH_SIZE) + '-lr' + str(LearningRate) + '-' + str(XX) + '-' + str( SX1) + '-' + str(SX2) + '-' + str(RX) + '-' # tf placeholder tf_x = tf.placeholder(tf.float32, [None, 28 * 28]) # value in the range of (0, 1) ph_encoded = tf.placeholder(tf.float32, [None, n_encoded]) ph_switch = tf.placeholder(tf.float32, [1]) ph_lr = tf.placeholder(tf.float32, []) ph_dis_e = tf.placeholder(tf.float32, [None, n_encoded]) # encoder en0 = tf.layers.dense(tf_x, n_l0, tf.nn.sigmoid) en1 = tf.layers.dense(en0, n_l1, tf.nn.sigmoid) en2 = tf.layers.dense(en1, n_l2, tf.nn.sigmoid) en3 = tf.layers.dense(en2, n_l3, tf.nn.sigmoid) ff_encoded = tf.layers.dense(en3, n_encoded, tf.nn.sigmoid) enc = ff_encoded * ph_switch + ph_encoded * (1 - ph_switch) encoded = tf.multiply(enc, ph_dis_e) # decoder de0 = tf.layers.dense(encoded, n_d0, tf.nn.sigmoid) de1 = tf.layers.dense(de0, n_d1, tf.nn.sigmoid) de2 = tf.layers.dense(de1, n_d2, tf.nn.sigmoid) de3 = tf.layers.dense(de2, n_d3, tf.nn.sigmoid) decoded = tf.layers.dense(de3, n_decoded, tf.nn.sigmoid) loss = tf.losses.mean_squared_error(labels=tf_x, predictions=decoded) train = tf.train.AdamOptimizer(ph_lr).minimize(loss) weights_en0 = tf.get_default_graph().get_tensor_by_name(os.path.split(en0.name)[0] + '/kernel:0') weights_en1 = tf.get_default_graph().get_tensor_by_name(os.path.split(en1.name)[0] + '/kernel:0') weights_en2 = tf.get_default_graph().get_tensor_by_name(os.path.split(en2.name)[0] + '/kernel:0') weights_en3 = tf.get_default_graph().get_tensor_by_name(os.path.split(en3.name)[0] + '/kernel:0') weights_mid = tf.get_default_graph().get_tensor_by_name(os.path.split(ff_encoded.name)[0] + '/kernel:0') weights_de0 = tf.get_default_graph().get_tensor_by_name(os.path.split(de0.name)[0] + '/kernel:0') weights_de1 = tf.get_default_graph().get_tensor_by_name(os.path.split(de1.name)[0] + '/kernel:0') weights_de2 = tf.get_default_graph().get_tensor_by_name(os.path.split(de2.name)[0] + '/kernel:0') weights_de3 = tf.get_default_graph().get_tensor_by_name(os.path.split(de3.name)[0] + '/kernel:0') weights_ddr = tf.get_default_graph().get_tensor_by_name(os.path.split(decoded.name)[0] + '/kernel:0') sess = tf.Session() sess.run(tf.global_variables_initializer()) ph_encoded_ = np.zeros(shape=[BATCH_SIZE, n_encoded]) ph_switch_ = np.ones(shape=[1]) ph_dis_e_ = np.ones(shape=[BATCH_SIZE, n_encoded]) saver = tf.train.Saver() nx = 0 type = '_n_32-batch128-lr0.001-0.2-0.5-0.7-0.2-nx0' saver.restore(sess, '/Users/fengqi/Pycharm_py36/QF/4900000/' + type) rows = ['{}'.format(row) for row in ['x1', 'x1_', 'a', 'a1_', 'd_a', '|d_a|','e_chg-e']] LearningRate = 0.001 ph_lr_ = np.ones(shape=[]) * LearningRate col = np.ones([1, n_l0]); col = np.concatenate([col, np.ones([1, n_l1]) * 0.8, np.ones([1, n_l2]) * 0.6, np.ones([1, n_l3]) * 0.4, np.ones([1, n_encoded]) * 0.2, np.ones([1, n_d0]) * 0.4, np.ones([1, n_d1]) * 0.6, np.ones([1, n_d2]) * 0.8, np.ones([1, n_d3]) * 1.0], axis=1) ####### compute corr ####### #test_x_ (100,128,784) count = 0 cc=np.zeros([BATCH_SIZE,992]) pp=np.zeros([BATCH_SIZE,992]) for i in range(x_step): xdata=np.reshape(test_x_[i,:,:],(BATCH_SIZE,784)) view_decoded_data, we0, we1, we2, we3, wem, wd0, wd1, wd2, wd3, wdd, en0_, en1_, en2_, en3_, ff_encoded_, de0_, de1_, de2_, de3_, ddr_ = sess.run( [decoded, weights_en0, weights_en1, weights_en2, weights_en3, weights_mid, weights_de0, weights_de1, weights_de2, weights_de3, weights_ddr, en0, en1, en2, en3, ff_encoded, de0, de1, de2, de3, decoded], {tf_x: xdata, ph_encoded: ph_encoded_, ph_switch: ph_switch_, ph_dis_e: ph_dis_e_}) act = np.concatenate([en0_, en1_, en2_, en3_, ff_encoded_, de0_, de1_, de2_, de3_], axis=1) if i ==0: sz_act = act.shape; sz_act_length = sz_act[1]; act_mat=np.zeros([x_step,BATCH_SIZE,sz_act_length]) #(100, 128, 992) act_mat[i,:,:] = act for i in range(BATCH_SIZE): print(str(i)) for j in range(992): #corrcoeff=np.corrcoef(act_mat[:,i,j],x) [corrcoeff,pval]=sp.stats.pearsonr(act_mat[:,i,j],x) cc[i,j]=corrcoeff#(128, 992) pp[i,j]=pval # # cc_avg=np.average(cc,axis=0) # pp_avg=np.average(pp,axis=0) # ind=np.where(pp_avg<0.01) # nx_e = cc_avg[480:512] # ind_e = np.argsort(nx_e) # # # # for k in range(32): # print(k) # f, a = plt.subplots(12, v_step) # for i in range(v_step): #left-right # print(str(i)) # # for l in range(11): #up-down # if l==0: # a[0][i].clear() # a[0][i].imshow(np.reshape(view_x_[i,0 ], (28, 28)), cmap='gray') # a[0][i].set_xticks(()) # a[0][i].set_yticks(()) # # view_ph_encoded_ = np.zeros(shape=[VIEW_SIZE, n_encoded]) # view_ph_switch_ = np.ones(shape=[1]) # view_ph_dis_e_ = np.ones(shape=[VIEW_SIZE, n_encoded]) # view_decoded_data1, we0, we1, we2, we3, wem, wd0, wd1, wd2, wd3, wdd, en0_, en1_, en2_, en3_, ff_encoded_, encoded_1, de0_, de1_, de2_, de3_, ddr_ = sess.run( # [decoded, weights_en0, weights_en1, weights_en2, weights_en3, weights_mid, # weights_de0, weights_de1, weights_de2, weights_de3, weights_ddr, en0, en1, en2, en3, ff_encoded, # encoded, de0, de1, # de2, de3, decoded], # {tf_x: view_x_[i], # ph_encoded: view_ph_encoded_, # ph_switch: view_ph_switch_, # ph_dis_e: view_ph_dis_e_}) # if l==0: # flag_1=np.round(ff_encoded_[0,k]*10) # # view_ph_encoded_ = ff_encoded_ # view_ph_switch_ = np.zeros(shape=[1]) # view_ph_dis_e_ = np.ones(shape=[VIEW_SIZE, n_encoded]) # view_ph_encoded_[:,k]=1- l / 10 # view_decoded_data1, we0, we1, we2, we3, wem, wd0, wd1, wd2, wd3, wdd, en0_, en1_, en2_, en3_, ff_encoded_, encoded_1, de0_, de1_, de2_, de3_, ddr_ = sess.run( # [decoded, weights_en0, weights_en1, weights_en2, weights_en3, weights_mid, # weights_de0, weights_de1, weights_de2, weights_de3, weights_ddr, en0, en1, en2, en3, ff_encoded, # encoded, de0, de1, # de2, de3, decoded], # {tf_x: view_x_[i], # ph_encoded: view_ph_encoded_, # ph_switch: view_ph_switch_, # ph_dis_e: view_ph_dis_e_}) # # # a[l+1][i].clear() # a[l+1][i].imshow(np.reshape(view_decoded_data1[0], (28, 28)), cmap='gray') # a[l+1][i].set_xticks(()) # a[l+1][i].set_yticks(()) # if flag_1==10-l: # im=np.reshape(view_decoded_data1[0], (28, 28)) # im[25:27,:]=0.5; # a[l + 1][i].imshow(im, cmap='gray') # # plt.subplots_adjust(left=0.2, right=0.8, bottom=0, top=1, wspace=0.05, hspace=0.05) # plt.savefig('./test/5test_chg_ny_' + str(k) + '.png') # # # # aaaa = 1 # # # # cc_avg=np.average(cc,axis=0) pp_avg=np.average(pp,axis=0) ind=np.where(pp_avg<0.01) nx_e = cc_avg[480:512] ind_e = np.argsort(nx_e) for k in range(32): print(k) f, a = plt.subplots(12, v_step) for i in range(v_step): #left-right print(str(i)) for l in range(11): #up-down if l==0: a[0][i].clear() a[0][i].imshow(np.reshape(view_x_[i,1], (28, 28)), cmap='gray') a[0][i].set_xticks(()) a[0][i].set_yticks(()) view_ph_encoded_ = np.zeros(shape=[VIEW_SIZE, n_encoded]) view_ph_switch_ = np.ones(shape=[1]) view_ph_dis_e_ = np.ones(shape=[VIEW_SIZE, n_encoded]) view_decoded_data1, we0, we1, we2, we3, wem, wd0, wd1, wd2, wd3, wdd, en0_, en1_, en2_, en3_, ff_encoded_, encoded_1, de0_, de1_, de2_, de3_, ddr_ = sess.run( [decoded, weights_en0, weights_en1, weights_en2, weights_en3, weights_mid, weights_de0, weights_de1, weights_de2, weights_de3, weights_ddr, en0, en1, en2, en3, ff_encoded, encoded, de0, de1, de2, de3, decoded], {tf_x: view_x_[i], ph_encoded: view_ph_encoded_, ph_switch: view_ph_switch_, ph_dis_e: view_ph_dis_e_}) if l==0: flag_1=np.round(ff_encoded_[1,k]*10) view_ph_encoded_ = ff_encoded_ view_ph_switch_ = np.zeros(shape=[1]) view_ph_dis_e_ = np.ones(shape=[VIEW_SIZE, n_encoded]) view_ph_encoded_[:,k]=1- l / 10 view_decoded_data1, we0, we1, we2, we3, wem, wd0, wd1, wd2, wd3, wdd, en0_, en1_, en2_, en3_, ff_encoded_, encoded_1, de0_, de1_, de2_, de3_, ddr_ = sess.run( [decoded, weights_en0, weights_en1, weights_en2, weights_en3, weights_mid, weights_de0, weights_de1, weights_de2, weights_de3, weights_ddr, en0, en1, en2, en3, ff_encoded, encoded, de0, de1, de2, de3, decoded], {tf_x: view_x_[i], ph_encoded: view_ph_encoded_, ph_switch: view_ph_switch_, ph_dis_e: view_ph_dis_e_}) a[l+1][i].clear() a[l+1][i].imshow(np.reshape(view_decoded_data1[1], (28, 28)), cmap='gray') a[l+1][i].set_xticks(()) a[l+1][i].set_yticks(()) if flag_1==10-l: im=np.reshape(view_decoded_data1[1], (28, 28)) im[25:27,:]=0.5; a[l + 1][i].imshow(im, cmap='gray') plt.subplots_adjust(left=0.2, right=0.8, bottom=0, top=1, wspace=0.05, hspace=0.05) plt.savefig('./test/6test_chg_ny_' + str(k) + '.png') aaaa = 1
[ "noreply@github.com" ]
peakqi.noreply@github.com
cb221e365a5489dbd72b5c99e681b6870802a23a
70ae772afdabea4213c64ac1e8b824a2dd258611
/FaceRecognition/recognize_specific_face_def.py
e5de6cd5d2c65262dd9fe9894366d3690ead13da
[]
no_license
IdoSeri/DavidsonProject
aa54dc3f07e09ac2a0a9c844a52f6ee5a4ff225c
87dbd48628ece0d55eed4c76d82b63100ce51ca4
refs/heads/master
2022-04-16T22:33:11.923149
2020-04-16T09:47:40
2020-04-16T09:47:40
250,328,967
1
1
null
null
null
null
UTF-8
Python
false
false
2,025
py
# import the necessary packages from imutils.video import VideoStream import face_recognition import imutils import pickle import time import cv2 def recognize_face(): # load the known faces and embeddings data = pickle.loads(open("FaceRecognition/encodings.pickle", "rb").read()) # initialize the video stream vs = VideoStream(src=0).start() time.sleep(2.0) name ="" # loop over frames from the video file stream while name=="": # grab the frame from the threaded video stream frame = vs.read() # convert the input frame from BGR to RGB then resize it to have # a width of 750px (to speedup processing) rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) rgb = imutils.resize(frame, width=750) r = frame.shape[1] / float(rgb.shape[1]) # detect the (x, y)-coordinates of the bounding boxes corresponding to each face in the frame boxes= face_recognition.face_locations(rgb, model="cnn") # compute the facial embeddings for each face encodings = face_recognition.face_encodings(rgb, boxes) # loop over the facial embeddings for encoding in encodings: # attempt to match each face in the input image to our known encodings matches = face_recognition.compare_faces(data["encodings"], encoding) # check to see if we have found a match if True in matches: # find the indexes of all matched faces then initialize a # dictionary to count the total number of times each face # was matched matchedIdxs = [i for (i, b) in enumerate(matches) if b] counts = {} # loop over the matched indexes and maintain a count for # each recognized face face for i in matchedIdxs: name = data["names"][i] counts[name] = counts.get(name, 0) + 1 # determine the recognized face with the largest number # of votes (note: in the event of an unlikely tie Python # will select first entry in the dictionary) name = max(counts, key=counts.get) # cleanup cv2.destroyAllWindows() vs.stop() # send the recognized name return name
[ "noreply@github.com" ]
IdoSeri.noreply@github.com
c5673a94f94f72233370c9935ad7b182c58ba065
47a98fed42dc2e0b589e3f08ff9342a3d924c7ac
/pyblog/XDG_CACHE_HOME/Microsoft/Python Language Server/stubs.v1/epXVRECNA2MadRw60lZ38aCPhTXzoduilN38-UtKc2M=/python.sys.pyi
cb99aafec30445a55c1b4a04ac86042755257854
[]
no_license
mehedi432/python
bd1c592edd622ae435c9f81c0771684048290e0a
725236e1b700ef41612ccf4f2aaccdf9bc1586d4
refs/heads/master
2020-06-06T22:31:44.548167
2019-06-28T07:15:27
2019-06-28T07:15:27
145,439,734
0
0
null
null
null
null
UTF-8
Python
false
false
36,814
pyi
import _io as _mod__io import builtins as _mod_builtins import types as _mod_types def __displayhook__(): 'displayhook(object) -> None\n\nPrint an object to sys.stdout and also save it in builtins._\n' pass __doc__ = "This module provides access to some objects used or maintained by the\ninterpreter and to functions that interact strongly with the interpreter.\n\nDynamic objects:\n\nargv -- command line arguments; argv[0] is the script pathname if known\npath -- module search path; path[0] is the script directory, else ''\nmodules -- dictionary of loaded modules\n\ndisplayhook -- called to show results in an interactive session\nexcepthook -- called to handle any uncaught exception other than SystemExit\n To customize printing in an interactive session or to install a custom\n top-level exception handler, assign other functions to replace these.\n\nstdin -- standard input file object; used by input()\nstdout -- standard output file object; used by print()\nstderr -- standard error object; used for error messages\n By assigning other file objects (or objects that behave like files)\n to these, it is possible to redirect all of the interpreter's I/O.\n\nlast_type -- type of last uncaught exception\nlast_value -- value of last uncaught exception\nlast_traceback -- traceback of last uncaught exception\n These three are only available in an interactive session after a\n traceback has been printed.\n\nStatic objects:\n\nbuiltin_module_names -- tuple of module names built into this interpreter\ncopyright -- copyright notice pertaining to this interpreter\nexec_prefix -- prefix used to find the machine-specific Python library\nexecutable -- absolute path of the executable binary of the Python interpreter\nfloat_info -- a struct sequence with information about the float implementation.\nfloat_repr_style -- string indicating the style of repr() output for floats\nhash_info -- a struct sequence with information about the hash algorithm.\nhexversion -- version information encoded as a single integer\nimplementation -- Python implementation information.\nint_info -- a struct sequence with information about the int implementation.\nmaxsize -- the largest supported length of containers.\nmaxunicode -- the value of the largest Unicode code point\nplatform -- platform identifier\nprefix -- prefix used to find the Python library\nthread_info -- a struct sequence with information about the thread implementation.\nversion -- the version of this interpreter as a string\nversion_info -- version information as a named tuple\n__stdin__ -- the original stdin; don't touch!\n__stdout__ -- the original stdout; don't touch!\n__stderr__ -- the original stderr; don't touch!\n__displayhook__ -- the original displayhook; don't touch!\n__excepthook__ -- the original excepthook; don't touch!\n\nFunctions:\n\ndisplayhook() -- print an object to the screen, and save it in builtins._\nexcepthook() -- print an exception and its traceback to sys.stderr\nexc_info() -- return thread-safe information about the current exception\nexit() -- exit the interpreter by raising SystemExit\ngetdlopenflags() -- returns flags to be used for dlopen() calls\ngetprofile() -- get the global profiling function\ngetrefcount() -- return the reference count for an object (plus one :-)\ngetrecursionlimit() -- return the max recursion depth for the interpreter\ngetsizeof() -- return the size of an object in bytes\ngettrace() -- get the global debug tracing function\nsetcheckinterval() -- control how often the interpreter checks for events\nsetdlopenflags() -- set the flags to be used for dlopen() calls\nsetprofile() -- set the global profiling function\nsetrecursionlimit() -- set the max recursion depth for the interpreter\nsettrace() -- set the global debug tracing function\n" def __excepthook__(): 'excepthook(exctype, value, traceback) -> None\n\nHandle an exception by displaying it with a traceback on sys.stderr.\n' pass def __interactivehook__(): pass __name__ = 'sys' __package__ = '' __stderr__ = _mod__io.TextIOWrapper() __stdin__ = _mod__io.TextIOWrapper() __stdout__ = _mod__io.TextIOWrapper() def _clear_type_cache(): '_clear_type_cache() -> None\nClear the internal type lookup cache.' pass def _current_frames(): "_current_frames() -> dictionary\n\nReturn a dictionary mapping each current thread T's thread id to T's\ncurrent stack frame.\n\nThis function should be used for specialized purposes only." return dict() def _debugmallocstats(): "_debugmallocstats()\n\nPrint summary info to stderr about the state of\npymalloc's structures.\n\nIn Py_DEBUG mode, also perform some expensive internal consistency\nchecks.\n" pass def _getframe(depth=None): '_getframe([depth]) -> frameobject\n\nReturn a frame object from the call stack. If optional integer depth is\ngiven, return the frame object that many calls below the top of the stack.\nIf that is deeper than the call stack, ValueError is raised. The default\nfor depth is zero, returning the frame at the top of the call stack.\n\nThis function should be used for internal and specialized\npurposes only.' pass _git = _mod_builtins.tuple() _home = '/usr/bin' _xoptions = _mod_builtins.dict() abiflags = 'm' api_version = 1013 argv = _mod_builtins.list() base_exec_prefix = '/usr' base_prefix = '/usr' builtin_module_names = _mod_builtins.tuple() byteorder = 'little' def call_tracing(func, args): 'call_tracing(func, args) -> object\n\nCall func(*args), while tracing is enabled. The tracing state is\nsaved, and restored afterwards. This is intended to be called from\na debugger from a checkpoint, to recursively debug some other code.' pass def callstats(): 'callstats() -> tuple of integers\n\nReturn a tuple of function call statistics, if CALL_PROFILE was defined\nwhen Python was built. Otherwise, return None.\n\nWhen enabled, this function returns detailed, implementation-specific\ndetails about the number of function calls executed. The return value is\na 11-tuple where the entries in the tuple are counts of:\n0. all function calls\n1. calls to PyFunction_Type objects\n2. PyFunction calls that do not create an argument tuple\n3. PyFunction calls that do not create an argument tuple\n and bypass PyEval_EvalCodeEx()\n4. PyMethod calls\n5. PyMethod calls on bound methods\n6. PyType calls\n7. PyCFunction calls\n8. generator calls\n9. All other calls\n10. Number of stack pops performed by call_function()' pass copyright = 'Copyright (c) 2001-2018 Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 BeOpen.com.\nAll Rights Reserved.\n\nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.' def displayhook(object): 'displayhook(object) -> None\n\nPrint an object to sys.stdout and also save it in builtins._\n' pass dont_write_bytecode = True def exc_info(): 'exc_info() -> (type, value, traceback)\n\nReturn information about the most recent exception caught by an except\nclause in the current stack frame or in an older stack frame.' return tuple() def excepthook(exctype, value, traceback): 'excepthook(exctype, value, traceback) -> None\n\nHandle an exception by displaying it with a traceback on sys.stderr.\n' pass exec_prefix = '/home/mehedi/python/blog/venv' executable = '/home/mehedi/python/blog/venv/bin/python' def exit(status=None): 'exit([status])\n\nExit the interpreter by raising SystemExit(status).\nIf the status is omitted or None, it defaults to zero (i.e., success).\nIf the status is an integer, it will be used as the system exit status.\nIf it is another kind of object, it will be printed and the system\nexit status will be one (i.e., failure).' pass class flags(_mod_builtins.tuple): 'sys.flags\n\nFlags provided through command line arguments or environment vars.' @staticmethod def __add__(self, value): 'Return self+value.' return __T__() __class__ = flags @staticmethod def __contains__(self, key): 'Return key in self.' return False @staticmethod def __delattr__(self, name): 'Implement delattr(self, name).' return None @staticmethod def __dir__(self): '__dir__() -> list\ndefault dir() implementation' return [''] @staticmethod def __eq__(self, value): 'Return self==value.' return False @staticmethod def __format__(self, format_spec): 'default object formatter' return '' @staticmethod def __ge__(self, value): 'Return self>=value.' return False @staticmethod def __getattribute__(self, name): 'Return getattr(self, name).' pass @staticmethod def __getitem__(self, key): 'Return self[key].' pass @staticmethod def __getnewargs__(self): return () @staticmethod def __gt__(self, value): 'Return self>value.' return False @staticmethod def __hash__(self): 'Return hash(self).' return 0 @staticmethod def __init__(self, *args, **kwargs): 'sys.flags\n\nFlags provided through command line arguments or environment vars.' pass @staticmethod def __init_subclass__(cls): 'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n' return None @staticmethod def __iter__(self): 'Implement iter(self).' return __T__() @staticmethod def __le__(self, value): 'Return self<=value.' return False @staticmethod def __len__(self): 'Return len(self).' return 0 @staticmethod def __lt__(self, value): 'Return self<value.' return False @staticmethod def __mul__(self, value): 'Return self*value.' return __T__() @staticmethod def __ne__(self, value): 'Return self!=value.' return False @staticmethod def __reduce__(self): return ''; return () @staticmethod def __reduce_ex__(self, protocol): 'helper for pickle' return ''; return () @staticmethod def __repr__(self): 'Return repr(self).' return '' @staticmethod def __rmul__(self, value): 'Return value*self.' return __T__() @staticmethod def __setattr__(self, name, value): 'Implement setattr(self, name, value).' return None @staticmethod def __sizeof__(self): '__sizeof__() -> int\nsize of object in memory, in bytes' return 0 @staticmethod def __str__(self): 'Return str(self).' return '' @staticmethod def __subclasshook__(cls, subclass): 'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n' return False bytes_warning = 0 @staticmethod def count(): 'T.count(value) -> integer -- return number of occurrences of value' return 1 debug = 0 dont_write_bytecode = 1 hash_randomization = 1 ignore_environment = 1 @staticmethod def index(): 'T.index(value, [start, [stop]]) -> integer -- return first index of value.\nRaises ValueError if the value is not present.' return 1 inspect = 0 interactive = 0 isolated = 0 n_fields = 13 n_sequence_fields = 13 n_unnamed_fields = 0 no_site = 0 no_user_site = 0 optimize = 0 quiet = 0 verbose = 0 class __float_info(_mod_builtins.tuple): "sys.float_info\n\nA structseq holding information about the float type. It contains low level\ninformation about the precision and internal representation. Please study\nyour system's :file:`float.h` for more information." def __add__(self, value): 'Return self+value.' return __float_info() __class__ = __float_info def __contains__(self, key): 'Return key in self.' return False def __delattr__(self, name): 'Implement delattr(self, name).' return None @classmethod def __dir__(self): '__dir__() -> list\ndefault dir() implementation' return [''] def __eq__(self, value): 'Return self==value.' return False @classmethod def __format__(self, format_spec): 'default object formatter' return '' def __ge__(self, value): 'Return self>=value.' return False def __getattribute__(self, name): 'Return getattr(self, name).' pass def __getitem__(self, key): 'Return self[key].' pass @classmethod def __getnewargs__(self): return () def __gt__(self, value): 'Return self>value.' return False def __hash__(self): 'Return hash(self).' return 0 def __init__(self, *args, **kwargs): "sys.float_info\n\nA structseq holding information about the float type. It contains low level\ninformation about the precision and internal representation. Please study\nyour system's :file:`float.h` for more information." pass @classmethod def __init_subclass__(cls): 'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n' return None def __iter__(self): 'Implement iter(self).' return __float_info() def __le__(self, value): 'Return self<=value.' return False def __len__(self): 'Return len(self).' return 0 def __lt__(self, value): 'Return self<value.' return False def __mul__(self, value): 'Return self*value.' return __float_info() def __ne__(self, value): 'Return self!=value.' return False @classmethod def __reduce__(self): return ''; return () @classmethod def __reduce_ex__(self, protocol): 'helper for pickle' return ''; return () def __repr__(self): 'Return repr(self).' return '' def __rmul__(self, value): 'Return value*self.' return __float_info() def __setattr__(self, name, value): 'Implement setattr(self, name, value).' return None @classmethod def __sizeof__(self): '__sizeof__() -> int\nsize of object in memory, in bytes' return 0 def __str__(self): 'Return str(self).' return '' @classmethod def __subclasshook__(cls, subclass): 'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n' return False @classmethod def count(cls): 'T.count(value) -> integer -- return number of occurrences of value' return 1 dig = 15 epsilon = 2.220446049250313e-16 @classmethod def index(cls): 'T.index(value, [start, [stop]]) -> integer -- return first index of value.\nRaises ValueError if the value is not present.' return 1 mant_dig = 53 max = 1.7976931348623157e+308 max_10_exp = 308 max_exp = 1024 min = 2.2250738585072014e-308 min_10_exp = -307 min_exp = -1021 n_fields = 11 n_sequence_fields = 11 n_unnamed_fields = 0 radix = 2 rounds = 1 float_repr_style = 'short' def get_asyncgen_hooks(): 'get_asyncgen_hooks()\n\nReturn a namedtuple of installed asynchronous generators hooks (firstiter, finalizer).' pass def get_coroutine_wrapper(): 'get_coroutine_wrapper()\n\nReturn the wrapper for coroutine objects set by sys.set_coroutine_wrapper.' pass def getallocatedblocks(): 'getallocatedblocks() -> integer\n\nReturn the number of memory blocks currently allocated, regardless of their\nsize.' return 1 def getcheckinterval(): 'getcheckinterval() -> current check interval; see setcheckinterval().' pass def getdefaultencoding(): 'getdefaultencoding() -> string\n\nReturn the current default string encoding used by the Unicode \nimplementation.' return '' def getdlopenflags(): 'getdlopenflags() -> int\n\nReturn the current value of the flags that are used for dlopen calls.\nThe flag constants are defined in the os module.' return 1 def getfilesystemencodeerrors(): 'getfilesystemencodeerrors() -> string\n\nReturn the error mode used to convert Unicode filenames in\noperating system filenames.' return '' def getfilesystemencoding(): 'getfilesystemencoding() -> string\n\nReturn the encoding used to convert Unicode filenames in\noperating system filenames.' return '' def getprofile(): 'getprofile()\n\nReturn the profiling function set with sys.setprofile.\nSee the profiler chapter in the library manual.' pass def getrecursionlimit(): 'getrecursionlimit()\n\nReturn the current value of the recursion limit, the maximum depth\nof the Python interpreter stack. This limit prevents infinite\nrecursion from causing an overflow of the C stack and crashing Python.' pass def getrefcount(object): 'getrefcount(object) -> integer\n\nReturn the reference count of object. The count returned is generally\none higher than you might expect, because it includes the (temporary)\nreference as an argument to getrefcount().' return 1 def getsizeof(object, default): 'getsizeof(object, default) -> int\n\nReturn the size of object in bytes.' return 1 def getswitchinterval(): 'getswitchinterval() -> current thread switch interval; see setswitchinterval().' pass def gettrace(): 'gettrace()\n\nReturn the global debug tracing function set with sys.settrace.\nSee the debugger chapter in the library manual.' pass class __hash_info(_mod_builtins.tuple): 'hash_info\n\nA struct sequence providing parameters used for computing\nhashes. The attributes are read only.' def __add__(self, value): 'Return self+value.' return __hash_info() __class__ = __hash_info def __contains__(self, key): 'Return key in self.' return False def __delattr__(self, name): 'Implement delattr(self, name).' return None @classmethod def __dir__(self): '__dir__() -> list\ndefault dir() implementation' return [''] def __eq__(self, value): 'Return self==value.' return False @classmethod def __format__(self, format_spec): 'default object formatter' return '' def __ge__(self, value): 'Return self>=value.' return False def __getattribute__(self, name): 'Return getattr(self, name).' pass def __getitem__(self, key): 'Return self[key].' pass @classmethod def __getnewargs__(self): return () def __gt__(self, value): 'Return self>value.' return False def __hash__(self): 'Return hash(self).' return 0 def __init__(self, *args, **kwargs): 'hash_info\n\nA struct sequence providing parameters used for computing\nhashes. The attributes are read only.' pass @classmethod def __init_subclass__(cls): 'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n' return None def __iter__(self): 'Implement iter(self).' return __hash_info() def __le__(self, value): 'Return self<=value.' return False def __len__(self): 'Return len(self).' return 0 def __lt__(self, value): 'Return self<value.' return False def __mul__(self, value): 'Return self*value.' return __hash_info() def __ne__(self, value): 'Return self!=value.' return False @classmethod def __reduce__(self): return ''; return () @classmethod def __reduce_ex__(self, protocol): 'helper for pickle' return ''; return () def __repr__(self): 'Return repr(self).' return '' def __rmul__(self, value): 'Return value*self.' return __hash_info() def __setattr__(self, name, value): 'Implement setattr(self, name, value).' return None @classmethod def __sizeof__(self): '__sizeof__() -> int\nsize of object in memory, in bytes' return 0 def __str__(self): 'Return str(self).' return '' @classmethod def __subclasshook__(cls, subclass): 'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n' return False algorithm = 'siphash24' @classmethod def count(cls): 'T.count(value) -> integer -- return number of occurrences of value' return 1 cutoff = 0 hash_bits = 64 imag = 1000003 @classmethod def index(cls): 'T.index(value, [start, [stop]]) -> integer -- return first index of value.\nRaises ValueError if the value is not present.' return 1 inf = 314159 modulus = 2305843009213693951 n_fields = 9 n_sequence_fields = 9 n_unnamed_fields = 0 nan = 0 seed_bits = 128 width = 64 hexversion = 50727152 implementation = _mod_types.SimpleNamespace() class __int_info(_mod_builtins.tuple): "sys.int_info\n\nA struct sequence that holds information about Python's\ninternal representation of integers. The attributes are read only." def __add__(self, value): 'Return self+value.' return __int_info() __class__ = __int_info def __contains__(self, key): 'Return key in self.' return False def __delattr__(self, name): 'Implement delattr(self, name).' return None @classmethod def __dir__(self): '__dir__() -> list\ndefault dir() implementation' return [''] def __eq__(self, value): 'Return self==value.' return False @classmethod def __format__(self, format_spec): 'default object formatter' return '' def __ge__(self, value): 'Return self>=value.' return False def __getattribute__(self, name): 'Return getattr(self, name).' pass def __getitem__(self, key): 'Return self[key].' pass @classmethod def __getnewargs__(self): return () def __gt__(self, value): 'Return self>value.' return False def __hash__(self): 'Return hash(self).' return 0 def __init__(self, *args, **kwargs): "sys.int_info\n\nA struct sequence that holds information about Python's\ninternal representation of integers. The attributes are read only." pass @classmethod def __init_subclass__(cls): 'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n' return None def __iter__(self): 'Implement iter(self).' return __int_info() def __le__(self, value): 'Return self<=value.' return False def __len__(self): 'Return len(self).' return 0 def __lt__(self, value): 'Return self<value.' return False def __mul__(self, value): 'Return self*value.' return __int_info() def __ne__(self, value): 'Return self!=value.' return False @classmethod def __reduce__(self): return ''; return () @classmethod def __reduce_ex__(self, protocol): 'helper for pickle' return ''; return () def __repr__(self): 'Return repr(self).' return '' def __rmul__(self, value): 'Return value*self.' return __int_info() def __setattr__(self, name, value): 'Implement setattr(self, name, value).' return None @classmethod def __sizeof__(self): '__sizeof__() -> int\nsize of object in memory, in bytes' return 0 def __str__(self): 'Return str(self).' return '' @classmethod def __subclasshook__(cls, subclass): 'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n' return False bits_per_digit = 30 @classmethod def count(cls): 'T.count(value) -> integer -- return number of occurrences of value' return 1 @classmethod def index(cls): 'T.index(value, [start, [stop]]) -> integer -- return first index of value.\nRaises ValueError if the value is not present.' return 1 n_fields = 2 n_sequence_fields = 2 n_unnamed_fields = 0 sizeof_digit = 4 def intern(string): "intern(string) -> string\n\n``Intern'' the given string. This enters the string in the (global)\ntable of interned strings whose purpose is to speed up dictionary lookups.\nReturn the string itself or the previously interned string object with the\nsame value." return '' def is_finalizing(): 'is_finalizing()\nReturn True if Python is exiting.' pass maxsize = 9223372036854775807 maxunicode = 1114111 meta_path = _mod_builtins.list() modules = _mod_builtins.dict() path = _mod_builtins.list() path_hooks = _mod_builtins.list() path_importer_cache = _mod_builtins.dict() platform = 'linux' prefix = '/home/mehedi/python/blog/venv' def set_asyncgen_hooks(*, firstiter=None, finalizer=None): 'set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\nSet a finalizer for async generators objects.' pass def set_coroutine_wrapper(wrapper): 'set_coroutine_wrapper(wrapper)\n\nSet a wrapper for coroutine objects.' pass def setcheckinterval(n): 'setcheckinterval(n)\n\nTell the Python interpreter to check for asynchronous events every\nn instructions. This also affects how often thread switches occur.' pass def setdlopenflags(n): 'setdlopenflags(n) -> None\n\nSet the flags used by the interpreter for dlopen calls, such as when the\ninterpreter loads extension modules. Among other things, this will enable\na lazy resolving of symbols when importing a module, if called as\nsys.setdlopenflags(0). To share symbols across extension modules, call as\nsys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\ncan be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).' pass def setprofile(function): 'setprofile(function)\n\nSet the profiling function. It will be called on each function call\nand return. See the profiler chapter in the library manual.' pass def setrecursionlimit(n): 'setrecursionlimit(n)\n\nSet the maximum depth of the Python interpreter stack to n. This\nlimit prevents infinite recursion from causing an overflow of the C\nstack and crashing Python. The highest possible limit is platform-\ndependent.' pass def setswitchinterval(n): 'setswitchinterval(n)\n\nSet the ideal thread switching delay inside the Python interpreter\nThe actual frequency of switching threads can be lower if the\ninterpreter executes long sequences of uninterruptible code\n(this is implementation-specific and workload-dependent).\n\nThe parameter must represent the desired switching delay in seconds\nA typical value is 0.005 (5 milliseconds).' pass def settrace(function): 'settrace(function)\n\nSet the global debug tracing function. It will be called on each\nfunction call. See the debugger chapter in the library manual.' pass stderr = _mod__io.TextIOWrapper() stdin = _mod__io.TextIOWrapper() stdout = _mod__io.TextIOWrapper() class __thread_info(_mod_builtins.tuple): 'sys.thread_info\n\nA struct sequence holding information about the thread implementation.' def __add__(self, value): 'Return self+value.' return __thread_info() __class__ = __thread_info def __contains__(self, key): 'Return key in self.' return False def __delattr__(self, name): 'Implement delattr(self, name).' return None @classmethod def __dir__(self): '__dir__() -> list\ndefault dir() implementation' return [''] def __eq__(self, value): 'Return self==value.' return False @classmethod def __format__(self, format_spec): 'default object formatter' return '' def __ge__(self, value): 'Return self>=value.' return False def __getattribute__(self, name): 'Return getattr(self, name).' pass def __getitem__(self, key): 'Return self[key].' pass @classmethod def __getnewargs__(self): return () def __gt__(self, value): 'Return self>value.' return False def __hash__(self): 'Return hash(self).' return 0 def __init__(self, *args, **kwargs): 'sys.thread_info\n\nA struct sequence holding information about the thread implementation.' pass @classmethod def __init_subclass__(cls): 'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n' return None def __iter__(self): 'Implement iter(self).' return __thread_info() def __le__(self, value): 'Return self<=value.' return False def __len__(self): 'Return len(self).' return 0 def __lt__(self, value): 'Return self<value.' return False def __mul__(self, value): 'Return self*value.' return __thread_info() def __ne__(self, value): 'Return self!=value.' return False @classmethod def __reduce__(self): return ''; return () @classmethod def __reduce_ex__(self, protocol): 'helper for pickle' return ''; return () def __repr__(self): 'Return repr(self).' return '' def __rmul__(self, value): 'Return value*self.' return __thread_info() def __setattr__(self, name, value): 'Implement setattr(self, name, value).' return None @classmethod def __sizeof__(self): '__sizeof__() -> int\nsize of object in memory, in bytes' return 0 def __str__(self): 'Return str(self).' return '' @classmethod def __subclasshook__(cls, subclass): 'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n' return False @classmethod def count(cls): 'T.count(value) -> integer -- return number of occurrences of value' return 1 @classmethod def index(cls): 'T.index(value, [start, [stop]]) -> integer -- return first index of value.\nRaises ValueError if the value is not present.' return 1 lock = 'semaphore' n_fields = 3 n_sequence_fields = 3 n_unnamed_fields = 0 name = 'pthread' version = 'NPTL 2.28' version = '3.6.8 (default, Apr 9 2019, 04:59:38) \n[GCC 8.3.0]' class __version_info(_mod_builtins.tuple): 'sys.version_info\n\nVersion information as a named tuple.' def __add__(self, value): 'Return self+value.' return __version_info() __class__ = __version_info def __contains__(self, key): 'Return key in self.' return False def __delattr__(self, name): 'Implement delattr(self, name).' return None @classmethod def __dir__(self): '__dir__() -> list\ndefault dir() implementation' return [''] def __eq__(self, value): 'Return self==value.' return False @classmethod def __format__(self, format_spec): 'default object formatter' return '' def __ge__(self, value): 'Return self>=value.' return False def __getattribute__(self, name): 'Return getattr(self, name).' pass def __getitem__(self, key): 'Return self[key].' pass @classmethod def __getnewargs__(self): return () def __gt__(self, value): 'Return self>value.' return False def __hash__(self): 'Return hash(self).' return 0 def __init__(self, *args, **kwargs): 'sys.version_info\n\nVersion information as a named tuple.' pass @classmethod def __init_subclass__(cls): 'This method is called when a class is subclassed.\n\nThe default implementation does nothing. It may be\noverridden to extend subclasses.\n' return None def __iter__(self): 'Implement iter(self).' return __version_info() def __le__(self, value): 'Return self<=value.' return False def __len__(self): 'Return len(self).' return 0 def __lt__(self, value): 'Return self<value.' return False def __mul__(self, value): 'Return self*value.' return __version_info() def __ne__(self, value): 'Return self!=value.' return False @classmethod def __reduce__(self): return ''; return () @classmethod def __reduce_ex__(self, protocol): 'helper for pickle' return ''; return () def __repr__(self): 'Return repr(self).' return '' def __rmul__(self, value): 'Return value*self.' return __version_info() def __setattr__(self, name, value): 'Implement setattr(self, name, value).' return None @classmethod def __sizeof__(self): '__sizeof__() -> int\nsize of object in memory, in bytes' return 0 def __str__(self): 'Return str(self).' return '' @classmethod def __subclasshook__(cls, subclass): 'Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n' return False @classmethod def count(cls): 'T.count(value) -> integer -- return number of occurrences of value' return 1 @classmethod def index(cls): 'T.index(value, [start, [stop]]) -> integer -- return first index of value.\nRaises ValueError if the value is not present.' return 1 major = 3 micro = 8 minor = 6 n_fields = 5 n_sequence_fields = 5 n_unnamed_fields = 0 releaselevel = 'final' serial = 0 warnoptions = _mod_builtins.list() float_info = __float_info() hash_info = __hash_info() int_info = __int_info() thread_info = __thread_info() version_info = __version_info()
[ "aamehedi93@gmail.com" ]
aamehedi93@gmail.com
1c03b9aee293d47ae2cf1cba8865ea237699d603
b838762713aa551690532a7cdc8f2d4556766d2c
/sales/db/init_db.py
b8e0edfab3ff55a9fa9b11a2f0b07c7813ea6df7
[]
no_license
dmitriyignatiev/api_peewee
647ad98f9e3fda76e08f28eb4c2481f5a919db20
3d1a4a6830169a01302e37b7214ed0a1fad08ac1
refs/heads/master
2022-12-10T11:21:05.561156
2020-09-20T16:56:28
2020-09-20T16:56:28
297,037,032
0
0
null
null
null
null
UTF-8
Python
false
false
655
py
from sqlalchemy import create_engine, MetaData from sales.db.db import question from dynaconf import settings DSN = f"postgresql://{settings.DB_USER}:{settings.DB_PASSWORD}@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NASE}" def create_tables(engine): meta = MetaData() meta.create_all(bind=engine, tables=[question]) def sample_data(engine): conn = engine.connect() conn.execute(question.insert(), [ {'question_text': 'What\'s new?', 'pub_date': '2015-12-15 17:17:49.629+02'} ]) conn.close() if __name__ == '__main__': engine = create_engine(DSN) create_tables(engine) sample_data(engine)
[ "dmitriy.ignatiev83@gmail.com" ]
dmitriy.ignatiev83@gmail.com
cb4b16dd237ab801af0b21ca00cf08970de29bf8
e8c82271070e33bb6b181616a0a518d8f8fc6158
/fce/numpy/distutils/tests/f2py_ext/tests/PaxHeader/test_fib2.py
a56021af7be6b185d62870db000c6c9d53082297
[]
no_license
DataRozhlas/profil-volice-share
aafa0a93b26de0773fa6bf2b7d513a5ec856ce38
b4424527fe36e0cd613f7bde8033feeecb7e2e94
refs/heads/master
2020-03-18T01:44:26.136999
2018-05-20T12:19:24
2018-05-20T12:19:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
136
py
17 gid=713727123 15 uid=3629613 20 ctime=1458667064 20 atime=1458667064 23 SCHILY.dev=16777220 23 SCHILY.ino=31296593 18 SCHILY.nlink=1
[ "honza@datastory.cz" ]
honza@datastory.cz
6c1be986fca786a6854705ef2349ec7574a2437b
36b6384001de57775b908234952d7f410402e715
/main.py
6260a322ce1f34873400488ad9182cb24be8b18e
[ "BSD-3-Clause" ]
permissive
furkankykc/AutomatedDocumentMailer
d3140660d3235ebe145f6a73abf4536f1cce920c
f5216e788f9570ed148652f83eb58d1f9a8ef5e8
refs/heads/master
2021-06-30T05:54:30.304651
2020-09-13T17:23:46
2020-09-13T17:23:46
130,085,577
0
0
null
null
null
null
UTF-8
Python
false
false
126
py
from Mailer.loginform import LoginGui from Mailer.gui import Gui if __name__ == '__main__': LoginGui() # Gui('xbet')
[ "furkankykc@gmail.com" ]
furkankykc@gmail.com
75058d90ba45ab474f758745b9903f613016ee98
3fc107a60ecf2144333b23401716020f8c2c6b2c
/apps/mantenimiento_equipo/models.py
88986d87fbd2fa651657ae39cef29373f9b84631
[]
no_license
TulioRafaelCuadradoHoyos/tcuadrado_parcialbase
8d00099f234bcb6f991ae0389a0792bead602e11
5818ffce00e6cb2322d0eb60ce2aca4200169214
refs/heads/master
2023-08-29T05:08:06.929208
2021-10-22T13:51:12
2021-10-22T13:51:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
538
py
from django.db import models from apps import mantenimiento from apps.equipo.models import Equipo from apps.mantenimiento.models import Mantenimiento # Create your models here. class Mantenimiento_equipo(models.Model): mantenimiento = models.ForeignKey(Mantenimiento, on_delete= models.CASCADE) equipo =models.ForeignKey(Equipo, on_delete= models.CASCADE) Descripcion =models.CharField(max_length= 50) Resultado =models.BooleanField() def __str__(self): return self.Descripcion
[ "tcuadrado@uniguajira.edu.co" ]
tcuadrado@uniguajira.edu.co
9e226cf7f1b347db514b5a6f6c603957fe867e63
c3eff34237f19885ee09c81f2eb869a53a66e76b
/app/generate_token.py
0b2dabf9bdc5880404676f02d9b10c6a15b73f1d
[]
no_license
victorvarza/hermes
e9f4bf3fe76b3f6949bfd9e8e23bab7951692f05
62d9c5ba0cb0851ae56bc33e8ac337cecd205f82
refs/heads/master
2021-11-05T13:40:02.298153
2021-01-10T21:51:11
2021-01-10T21:51:11
135,069,301
0
0
null
2021-03-25T22:53:52
2018-05-27T17:56:11
Python
UTF-8
Python
false
false
434
py
from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive cred_path = "app/conf/gdrive_cred.json" gauth = GoogleAuth() gauth.LoadCredentialsFile(cred_path) if gauth.credentials is None: gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() print("Writing credentials to {0}".format(cred_path)) gauth.SaveCredentialsFile(cred_path) drive = GoogleDrive(gauth)
[ "victor.varza@gmail.com" ]
victor.varza@gmail.com
16bc013e99ded0fe9f6941199abd40f35eefdcd6
b3ae6dc41b1930856ad70ff8a7a618112ba6c256
/nncf/definitions.py
5ca5eb73b46fad0321415b2bbec131a428039c5e
[ "Apache-2.0" ]
permissive
RikAllen/nncf_pytorch
05411fb9eb819971c5797524e6c09996b7a46aaa
db8c09d8a1f9efb6c22150ba285ce65bc879d88c
refs/heads/develop
2023-01-14T01:55:04.938358
2020-09-16T15:00:14
2020-09-16T15:00:14
289,278,649
0
0
Apache-2.0
2020-09-24T13:46:45
2020-08-21T13:39:04
Python
UTF-8
Python
false
false
1,057
py
""" Copyright (c) 2020 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import pkg_resources import os NNCF_PACKAGE_ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) HW_CONFIG_RELATIVE_DIR = "hw_configs" def get_install_type(): try: _ = pkg_resources.get_distribution('nncf') install_type = pkg_resources.resource_string(__name__, 'install_type').decode("ASCII") except pkg_resources.DistributionNotFound: # Working with NNCF while not installed as a package install_type = "GPU" return install_type
[ "noreply@github.com" ]
RikAllen.noreply@github.com
439a6cef4d180ab24ddfab790d339f28dba304de
e0def6cfcef03922758940ee1d5ec7a891fafaf0
/files/10_create_altered_rides_table.py
6cb774324fdab5252ebc9c6141eaf892a3b221e4
[]
no_license
DataLiftoff/Analysis_Of_The_Movement_Of_Rental_Bikes
8705845379c20c12267429cd2fc0448e32133423
f5656f247616ca84e2e9925a3437b3d86d7252a2
refs/heads/master
2023-01-05T08:54:17.745088
2020-10-01T21:46:20
2020-10-01T21:46:20
300,298,588
0
0
null
null
null
null
UTF-8
Python
false
false
3,270
py
##### Import Libraries # To load OpenStreetMap-data import osmnx as ox # To work with networks import networkx as nx # To connect to databases from helperFunctions import Graph from helperFunctions import alterRoute from helperFunctions import connectZEO from helperFunctions import connectMySQL from helperFunctions import connectMongo from helperFunctions import containerWait from helperFunctions import managementUpdate ##### Run Program # Wait for the MySQL server to start containerWait() try: # Connect to ZODB root = connectZEO() # Connect to MongoDb cluster, db_mongo, collection_altered = connectMongo(collection='altered') collection_shortest = db_mongo['shortest'] # Connect to MySQL and get cursor db_mysql, cur = connectMySQL() ##### Iterate Over All Cities And Alter The Path # Iterate over all cities while True: # SQL query sql_query = 'SELECT cluster_id FROM city_clusters WHERE city_analyse=1 AND last_osm_graph>last_rides_altered ORDER BY RAND() LIMIT 1' # Execute the query cur.execute(sql_query) cluster_id = cur.fetchall() # Check if clusters are left if not cluster_id: break # Extract data cluster_id = cluster_id[0][0] # Update timestamp for city managementUpdate('last_rides_altered', cur, db_mysql, table='city_clusters', row='cluster_id', id=cluster_id) # Load the graph from the ZODB graph = root[cluster_id].graph # Iterate over all shortest rides for item in collection_shortest.find({'Cluster_Id':cluster_id}): # Create key for dictionary key = item['_id'] # Get precomputed altered paths precomputed_altered = collection_altered.find_one({'_id':key}) # Stop to much computation if precomputed_altered and item['Count']==precomputed_altered['Count']: continue # Check if ride has to be recomputed if precomputed_altered: # Copy precomputed ride to rides rides = precomputed_altered['Rides'] lengths = precomputed_altered['Lengths'] count = precomputed_altered['Count'] else: # Set default values rides = [] lengths = [] count = 0 # Compute the number of missing rides n_missing_rides = item['Count'] - count # Create an altered ride for each count for _ in range(n_missing_rides): # Alter and save each ride ride_altered = alterRoute(item['Ride'], graph, p=0.2) # Compute ride length ride_length = sum(ox.utils_graph.get_route_edge_attributes(graph, ride_altered, attribute='length')) # Store the altered rides rides.append(list(map(int, ride_altered))) lengths.append(ride_length) count += 1 # Update the altered rides in the database collection_altered.update_one({'_id':key}, {'$set':{'_id':key, 'Rides':rides, 'Count':count, 'Lengths':lengths, 'Cluster_Id':cluster_id}}, upsert=True) except mysql.connector.Error as error: print(error) finally: if (db_mysql.is_connected()): db_mysql.close() print('Database has been closed.')
[ "noreply@github.com" ]
DataLiftoff.noreply@github.com
c63effbac0ae9a65a8e037ea99875dcf94ae1746
44e26d6e5ada8bc5fb9d000e86e4694615262bcd
/download_latest_build.py
0a1c243fbbd71a64c4fc2ce7e7a65fd9d9fe1c28
[]
no_license
symlib/clitest
18c9d0475179b035a466d604a60fca52d5c63d84
524bd59f64d4754a760d483c9b7038647f442240
refs/heads/master
2021-06-21T21:20:53.031850
2017-08-22T01:04:19
2017-08-22T01:04:19
81,310,193
0
1
null
null
null
null
UTF-8
Python
false
false
10,847
py
# initial version # March 20, 2017 buildserverurl="http://192.168.208.5/release/hyperion_ds/daily/" fcsserverurl="http://192.168.208.5/release/hyperion_ds/fcs/" tftpserver="root@10.84.2.99:/work/tftpboot/" serv = "MjExLjE1MC42NS44MQ==" u = "amFja3kubGlAY24ucHJvbWlzZS5jb20=" p = "NzcwMjE0WHA=" import requests from bs4 import BeautifulSoup import os import glob import time def getnewbuild(): download=False # get the current build folder files=glob.glob("/work/tftpboot/d5k-multi*.ptif") tftpbuildnumber120=0 tftpbuildnumber121=0 tftpbuildnumber122 = 0 tftpbuildnumber13 = 0 tmp120=tmp121=tmp122=tmp13=0 for file in files: try: if int(file[25:27])==12 and int(file[28])==2: tmp122=int(file[-7:-5]) elif int(file[25:27])==12 and int(file[28])==1: tmp121=int(file[-7:-5]) elif int(file[25:27])==12 and int(file[28])==0: tmp120 = int(file[-7:-5]) elif int(file[25:27]) == 13: tmp13 = int(file[-7:-5]) except: tmp120=0 tmp121 = 0 tmp122 = 0 tmp13=0 if tmp120>tftpbuildnumber120: tftpbuildnumber120=tmp120 if tmp121>tftpbuildnumber121: tftpbuildnumber121=tmp121 if tmp122>tftpbuildnumber122: tftpbuildnumber122=tmp122 if tmp13>tftpbuildnumber13: tftpbuildnumber13=tmp13 # print "current build is %d" %tftpbuildnumber # to get the full directory list soup = BeautifulSoup(requests.get(buildserverurl).text) fcssoup=BeautifulSoup(requests.get(fcsserverurl).text) buildnumber120 = list() buildnumber121 = list() buildnumber122 = list() buildnumber13 = list() for link in soup.find_all('a'): tmp = link.get('href') if "13." in tmp: buildnumber13.append(tmp) if "12.00" in tmp: buildnumber120.append(tmp) if "12.01" in tmp: buildnumber121.append(tmp) if "12.02" in tmp: buildnumber122.append(tmp) for link in fcssoup.find_all('a'): print link tmp = link.get('href') print tmp if "13_" in tmp: buildnumber13.append(tmp) try: webupdatedbuild120=int((buildnumber120[-1].replace("/","").split(".")[-1])) webupdatedbuild121 = int((buildnumber121[-1].replace("/", "").split(".")[-1])) webupdatedbuild122 = int((buildnumber122[-1].replace("/", "").split(".")[-1])) webupdatedbuild13 = int((buildnumber13[-1].replace("/", "").split("_")[-1])) except: webupdatedbuild120=0 webupdatedbuild121=0 webupdatedbuild122 = 0 webupdatedbuild13 = 0 #print "webupdatedbuildnumbers are %d,%d" %(webupdatedbuild12,webupdatedbuild13) # if the webupdated build is newer than the installed one, download the new build # file list contains the filename to be updated on the host filelist=list() print "webupdatebuild120,webupdatedbuild121,tftpbuildnumber120,tftpbuildnumber121,tftpbuildnumber122",webupdatedbuild120,webupdatedbuild121,tftpbuildnumber120,tftpbuildnumber121,webupdatedbuild122 print "webupdatebuild13,tptpbuildnumber13", webupdatedbuild13, tftpbuildnumber13 if webupdatedbuild13 >tftpbuildnumber13: download=True Pfile = open('downloadedfiles', 'w') Pfile.close() #for filetype in ("conf", "multi"): for filetype in ("conf", "multi", "bios", "fw", "lib", "oem", "sw", "usr", "base"): if filetype=="base": filename="d5k-"+filetype+"-"+(buildnumber13[-1].replace("/","")).replace(".","_").replace("13_00","13_0")+".raw.gz" else: filename="d5k-"+filetype+"-"+(buildnumber13[-1].replace("/","")).replace(".","_").replace("13_00","13_0")+".ptif" os.system("wget "+fcsserverurl+buildnumber13[-1]+filename) # os.system("scp "+ filename +" "+tftpserver) # filename="d5k-"+filetype+"-"+webupdatedbuild.replace(".","_").replace("00","0")+".ptif" # #os.system("wget " + buildserverurl + buildnumber[-1] + "/" + filename) timestr=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) os.system("echo " + timestr +" downloaded %s" % filename +" >> downloadedfiles") os.system("mv /root/d5k* /work/tftpboot/") os.system("mv ./d5k* /work/tftpboot/") if webupdatedbuild120 > tftpbuildnumber120: download = True Pfile = open('downloadedfiles', 'w') Pfile.close() # for filetype in ("conf", "multi"): for filetype in ("conf", "multi", "bios", "fw", "lib", "oem", "sw", "usr", "base"): if filetype == "base": filename = "d5k-" + filetype + "-" + (buildnumber120[-1].replace("/", "")).replace(".", "_").replace( "12_00", "12_0") + ".raw.gz" else: filename = "d5k-" + filetype + "-" + (buildnumber120[-1].replace("/", "")).replace(".", "_").replace( "12_00", "12_0") + ".ptif" os.system("wget " + buildserverurl + buildnumber120[-1] + filename) # os.system("scp "+ filename +" "+tftpserver) # filename="d5k-"+filetype+"-"+webupdatedbuild.replace(".","_").replace("00","0")+".ptif" # # os.system("wget " + buildserverurl + buildnumber[-1] + "/" + filename) timestr = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) os.system("echo " + timestr + " downloaded %s" % filename + " >> downloadedfiles") os.system("mv /root/d5k* /work/tftpboot/") os.system("mv ./d5k* /work/tftpboot/") if webupdatedbuild121 > tftpbuildnumber121: download = True Pfile = open('downloadedfiles', 'w') Pfile.close() # for filetype in ("conf", "multi"): for filetype in ("conf", "multi", "bios", "fw", "lib", "oem", "sw", "usr", "base"): if filetype == "base": filename = "d5k-" + filetype + "-" + (buildnumber121[-1].replace("/", "")).replace(".", "_").replace( "12_01", "12_1") + ".raw.gz" else: filename = "d5k-" + filetype + "-" + (buildnumber121[-1].replace("/", "")).replace(".", "_").replace( "12_01", "12_1") + ".ptif" os.system("wget " + buildserverurl + buildnumber121[-1] + filename) # os.system("scp "+ filename +" "+tftpserver) # filename="d5k-"+filetype+"-"+webupdatedbuild.replace(".","_").replace("00","0")+".ptif" # # os.system("wget " + buildserverurl + buildnumber[-1] + "/" + filename) timestr = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) os.system("echo " + timestr + " downloaded %s" % filename + " >> downloadedfiles") os.system("mv /root/d5k* /work/tftpboot/") os.system("mv ./d5k* /work/tftpboot/") if webupdatedbuild122 > tftpbuildnumber122: download = True Pfile = open('downloadedfiles', 'w') Pfile.close() # for filetype in ("conf", "multi"): for filetype in ("conf", "multi", "bios", "fw", "lib", "oem", "sw", "usr", "base"): if filetype == "base": filename = "d5k-" + filetype + "-" + (buildnumber122[-1].replace("/", "")).replace(".", "_").replace( "12_02", "12_2") + ".raw.gz" else: filename = "d5k-" + filetype + "-" + (buildnumber122[-1].replace("/", "")).replace(".", "_").replace( "12_02", "12_2") + ".ptif" os.system("wget " + buildserverurl + buildnumber122[-1] + filename) # os.system("scp "+ filename +" "+tftpserver) # filename="d5k-"+filetype+"-"+webupdatedbuild.replace(".","_").replace("00","0")+".ptif" # # os.system("wget " + buildserverurl + buildnumber[-1] + "/" + filename) timestr = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) os.system("echo " + timestr + " downloaded %s" % filename + " >> downloadedfiles") os.system("mv /root/d5k* /work/tftpboot/") os.system("mv ./d5k* /work/tftpboot/") return download if __name__ == "__main__": timestr=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) os.system("echo %s \" Trying to download files\" >> downloadedfiles" %timestr ) download=getnewbuild() if download==True: import smtplib # Import the email modules we'll need from email.mime.text import MIMEText # Open a plain text file for reading. For this example, assume that # the text file contains only ASCII characters. textfile="downloadedfiles" fp = open(textfile, 'rb') buildversion=fp.readline()[-18:-6] tofile=open("buildnum","w") tofile.write(buildversion.replace("_",".")) tofile.close() os.system("scp /root/buildnum root@192.168.252.106:/opt/testlink-1.9.16-0/apache2/htdocs/srvpool/") # os.system("scp /work/jackyl/buildnum root@192.168.252.106:/opt/testlink-1.9.16-0/apache2/htdocs/srvpool/") time.sleep(1) os.system("scp /root/buildnum root@10.84.2.66:/home/work/jackyl/Scripts/clitest/") # os.system("scp /work/jackyl/buildnum root@10.84.2.66:/home/work/jackyl/Scripts/clitest/") time.sleep(1) # Create a text/plain message msg = MIMEText(fp.read()) fp.close() # me == the sender's email address # you == the recipient's email address msg['Subject'] = 'New build is available at 10.84.2.99:/work/tftpboot/, please see the %s for detail' % textfile msg['From'] = 'jacky.li@cn.promise.com' msg['To'] = 'jacky.li@cn.promise.com' # Send the message via our own SMTP server, but don't include the rec = ['ken.hou@cn.promise.com','tracy.you@cn.promise.com','travis.tang@cn.promise.com','xin.wang@cn.promise.com','lily.zhao@cn.promise.com','lisa.xu@cn.promise.com','jacky.li@cn.promise.com','zach.feng@cn.promise.com','socrates.su@cn.promise.com','paul.diao@cn.promise.com','hulda.zhao@cn.promise.com'] #rec = ['zach.feng@cn.promise.com','jacky.li@cn.promise.com','hulda.zhao@cn.promise.com'] # Send the message via our own SMTP server, but don't include the # Send the message via our own SMTP server, but don't include the # envelope header. u=u.decode('base64') serv=serv.decode('base64') p=p.decode('base64') s = smtplib.SMTP(serv) s.login(u,p) s.sendmail(msg['From'], rec, msg.as_string()) s.quit()
[ "jacky.li@cn.promise.com" ]
jacky.li@cn.promise.com
675458e68451063981849d73115b4a2e5e1566b7
c48f3bb73f3ddda53619174fa1f81d42cd7bd0ca
/agent.py
ea6c262202157c3895d46d98c8186177a946266f
[]
no_license
hanhsienhuang/Gomoku
8f04f0b897feb33ff233d370978bf27c1b36f97f
d7f2cb1f042c92675ca877472e7c4376da600992
refs/heads/master
2022-12-31T02:36:01.310759
2020-10-25T05:51:49
2020-10-25T05:51:49
307,036,549
0
0
null
null
null
null
UTF-8
Python
false
false
9,392
py
import networks import torch import torch.nn as nn import torch.optim as optim import numpy as np from utils import is_in_range, list_add, print_board import random def choice2d(p): i = np.random.choice(np.prod(p.shape), p = p.flatten()) return np.unravel_index(i, p.shape) class Agent: def __init__(self, num_mcts, board_size): self.num_mcts = num_mcts self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self.network = networks.NN(in_channels = 3, feature_size = 50, num_residual = 1, board_size = board_size, value_hidden_size = 256).to(self.device) #self.network = networks.ConvNN(in_channels = 3, # feature_size = 64, # num_layer = 2, # value_hidden_size = 64).to(self.device) self.optim = optim.Adam(self.network.parameters(), 1e-4, weight_decay=1e-4) self.temperature = 1 # TODO self.UCBConstant = 1 self.batchSize = 100 def get_action(self, treeNode): while treeNode.n < self.num_mcts: self._dfs(treeNode) policy = self.get_mcts_policy(treeNode, 0.1) return choice2d(policy) def _dfs(self, treeNode): if treeNode.state.isEnd: return -abs(treeNode.state.endResult) if treeNode.P is None: p, v = self.get_network_policy_and_value(treeNode) treeNode.P = p return v ucb = self.get_mcts_ucb_value(treeNode) move = np.unravel_index(np.argmax(ucb), ucb.shape) v = -self._dfs(treeNode.next(move)) treeNode.update(move, v) return v def get_network_policy_and_value(self, treeNode): inp = self._construct_tensors((treeNode.state, )) policy_logit, value = self.network(inp) policy_logit = policy_logit.cpu().detach().numpy()[0] policy_logit = np.where(treeNode.state.validMoves, policy_logit, float("-inf")) exp_logit = np.exp(policy_logit - policy_logit.max()) policy = exp_logit / exp_logit.sum() value = value.item() return policy, value def get_mcts_ucb_value(self, treeNode): # Q + U # U = c P \sqrt{n} / (1+N) # For invalid move, value = -inf U = np.where(treeNode.state.validMoves, \ self.UCBConstant * np.sqrt(treeNode.n + 1) * treeNode.P / (treeNode.N+1), \ float("-inf")) return treeNode.Q + U def get_mcts_policy(self, treeNode, temperature = None): if temperature is None: temperature = self.temperature poweredN = (treeNode.N / np.max(treeNode.N)) ** (1/temperature if temperature > 0 else float("inf")) return poweredN / poweredN.sum() def update(self, experience): #random.shuffle(experience) states, policies, zs = list(zip(*experience)) inputs = self._construct_tensors(states) valids = torch.stack([torch.as_tensor(s.validMoves, dtype=int, device=self.device) for s in states]) policies = torch.stack([torch.as_tensor(p, dtype=torch.float, device=self.device) for p in policies]) zs = torch.tensor(zs, dtype=torch.float, device=self.device).unsqueeze(-1) neginf = torch.tensor(-1e8, dtype=torch.float, device=self.device) # Rotate and flip inputs = torch.cat([inputs, torch.flip(inputs, [1])]) inputs = torch.cat([torch.rot90(inputs, i, (2,3)) for i in range(4)]) valids = torch.cat([valids, torch.flip(valids, [1])]) valids = torch.cat([torch.rot90(valids, i, (1,2)) for i in range(4)]) policies = torch.cat([policies, torch.flip(policies, [1])]) policies = torch.cat([torch.rot90(policies, i, (1,2)) for i in range(4)]) zs = zs.repeat(8,1) # shuffle index = torch.randperm(valids.shape[0]) inputs = inputs[index] valids = valids.to(dtype=bool)[index] policies = policies[index] zs = zs[index] total_loss = 0 num_it = 0 for i in range(inputs.shape[0] //self.batchSize ): beg, end = i*self.batchSize, (i+1)*self.batchSize inp = inputs[beg:end] val = valids[beg:end] pol = policies[beg:end] z = zs[beg:end] policy_logit, value = self.network(inp) policy_logit = torch.where(val, policy_logit, neginf) loss = - torch.mean(torch.sum(pol * policy_logit, dim=(1,2))) \ + torch.mean(torch.logsumexp(policy_logit, dim=(1,2))) \ + torch.mean((value - z)**2) self.optim.zero_grad() loss.backward() self.optim.step() total_loss += loss.item() num_it += 1 print(f"num iter: {num_it}, mean loss: {total_loss/num_it:.2f}") def copy(self, other): if self is not other: self.network.load_state_dict(other.network.state_dict()) def _construct_tensors(self, states): tensors = [self._construct_tensor(state) for state in states] return torch.stack(tensors) def _construct_tensor(self, state): board = torch.as_tensor(state.board, dtype=torch.float, device=self.device) isBlack = torch.full((1,) + state.shape, int(state.isNextBlack), dtype=torch.float, device=self.device) tensor = torch.cat((board, isBlack)) return tensor.to(self.device) class BaselineAgent0: def __init__(self): pass def get_action(self, treeNode): state = treeNode.state if not np.any(state.board[0]): action = tuple(s//2 for s in state.shape) treeNode.update(action, 1) return action i = int(state.isNextBlack) myBoard = state.board[i] oppoBoard = state.board[(i+1)%2] scores = np.zeros(state.shape, dtype=int) # 1,2,4,100 mapScores = [0, 1, 4, 8, 1000, 0] for i in range(state.shape[0]): for j in range(state.shape[1]): for d in [(1,0), (0,1), (1,1), (1, -1)]: hasFive, n = self._check_five(myBoard, oppoBoard, (i,j), d) if hasFive: score = mapScores[n] for step in range(5): pos = list_add((i,j), d, step) if state.validMoves[pos]: scores[pos] += score hasFive, n = self._check_five(oppoBoard, myBoard, (i,j), d) if hasFive: score = mapScores[n] for step in range(5): pos = list_add((i,j), d, step) if state.validMoves[pos]: scores[pos] += score maxScore = np.max(scores) indices = list(zip(*np.where(np.logical_and(scores == maxScore, state.validMoves)))) action = random.choice(indices) treeNode.update(action, 1) return action def end(self, state): pass def _check_five(self, board, oppoboard, start, direction): num = 0 for step in range(5): pos = list_add(start, direction, step) if not is_in_range(pos, board.shape): return False, None if oppoboard[pos]: return False, None if board[pos]: num += 1 return True, num def get_mcts_policy(self, treeNode): return treeNode.N / np.sum(treeNode.N) class InputAgent: def __init__(self): pass def get_action(self, treeNode): state = treeNode.state print_board(state) while True: inp = input("Input position: ") try: lst = inp.split(",") assert(len(lst)==2) pos = tuple(int(l) for l in lst) break except: print() return pos def get_mcts_policy(self, treeNode): return None def end(self, state): pass import asyncio import json class WebsocketAgent: def __init__(self, ws): self.ws = ws def state_to_json(self, state): shape = state.shape board = [[0]*shape[1] for _ in range(shape[0])] validMoves = [[0]*shape[1] for _ in range(shape[0])] for i in range(shape[0]): for j in range(shape[1]): if state.board[0, i, j]: board[i][j] = 1 elif state.board[1, i, j]: board[i][j] = -1 validMoves[i][j] = 1 if state.validMoves[i, j] else 0 s = dict( shape = shape, board = board, isNextBlack = state.isNextBlack, validMoves = validMoves, isEnd = state.isEnd, endResult = state.endResult, ) return json.dumps(s) async def get_action(self, treeNode): await self.ws.send(self.state_to_json(treeNode.state)) rec = await self.ws.recv() action = tuple(json.loads(rec)) print(action) return action def get_mcts_policy(self, treeNode): return None async def end(self, state): await self.ws.send(self.state_to_json(state)) await self.ws.close()
[ "hu8108@gmail.com" ]
hu8108@gmail.com
e0d3ddf444f96456a667218432e68df52fe04514
3c515d48bba2bd4dc2ecd797aaf66aa5a1ebf596
/app.py
0e59b8ca4a0597b9a814d00fc0a6345534e30c3f
[]
no_license
jason2133/flask_ai_translator
0696797644aec7a3eb9926efbba3deac9e820eaa
f3b3c1a934e2f8a1a4a551dd199c2ca5521835ac
refs/heads/master
2023-07-17T06:16:59.938651
2021-08-25T17:29:51
2021-08-25T17:29:51
399,882,270
1
0
null
null
null
null
UTF-8
Python
false
false
1,905
py
import requests, os, uuid, json from dotenv import load_dotenv load_dotenv() from flask import Flask, render_template from flask import request app = Flask(__name__) @app.route('/', methods=['GET']) def index(): return render_template('index.html') # 서비스를 호출하는 코드 @app.route('/', methods=['POST']) def index_post(): # Read the values from the form original_text = request.form['text'] target_language = request.form['language'] # Load the values from .env key = os.environ['KEY'] endpoint = os.environ['ENDPOINT'] location = os.environ['LOCATION'] # Indicate that we want to translate and the API version (3.0) and the target language path = '/translate?api-version=3.0' # Add the target language parameter target_language_parameter = '&to=' + target_language # Create the full URL constructed_url = endpoint + path + target_language_parameter # Set up the header information, which includes our subscription key headers = { 'Ocp-Apim-Subscription-Key': key, 'Ocp-Apim-Subscription-Region': location, 'Content-type': 'application/json', 'X-ClientTraceId': str(uuid.uuid4()) } # Create the body of the request with the text to be translated body = [{ 'text': original_text }] # Make the call using post translator_request = requests.post(constructed_url, headers=headers, json=body) # Retrieve the JSON response translator_response = translator_request.json() # Retrieve the translation translated_text = translator_response[0]['translations'][0]['text'] # Call render template, passing the translated text, # original text, and target language to the template return render_template( 'results.html', translated_text=translated_text, original_text=original_text, target_language=target_language )
[ "jason2133@likelion.org" ]
jason2133@likelion.org
80d9fb03a91fc8eae47a8e9b11cc9d472ab29f0b
48285275958aba8f8f14ce505f03acf117870584
/src/handlers/HandlerFactory.py
f961b917d06c235f64305e5deaa2a39e94088b0e
[]
no_license
rchuso/Python-Web-Server
095609586c8fb403380752cd99408800d760d8e8
1fe8fdfc77d220923b8ebfafbc759bae1be4074c
refs/heads/master
2021-05-17T18:54:09.141504
2020-04-02T06:23:16
2020-04-02T06:23:16
250,927,592
0
0
null
null
null
null
UTF-8
Python
false
false
2,283
py
''' Created on 15/03/2020 @author: rand huso ''' import os from handlers.HandlerImage import HandlerImage from handlers.HandlerText import HandlerText from handlers.HandlerBad import HandlerBad class HandlerFactory(): handlerTypes = { 'html': {'handler': HandlerText, 'type':'html', 'contentType':'text/html', 'bytes': False }, 'css': {'handler': HandlerText, 'type':'css', 'contentType':'text/css', 'bytes': False }, 'js': {'handler': HandlerText, 'type':'js', 'contentType':'text/javascript', 'bytes': False }, 'json': {'handler': HandlerText, 'type':'json', 'contentType':'application/json', 'bytes': False }, 'ico': {'handler': HandlerImage, 'type':'ico', 'contentType':'image/vnd.microsoft.icon', 'bytes': True }, 'jpg': {'handler': HandlerImage, 'type':'jpg', 'contentType':'image/jpeg', 'bytes': True }, 'png': {'handler': HandlerImage, 'type':'png', 'contentType':'image/png', 'bytes': True }, } def __new__( self, host, URI, headers, postVars=None ): hostQueryFragment = URI.split( '#' ) # will be len=1 if none if 1 == len(hostQueryFragment): fragment = None else: fragment = hostQueryFragment[1] hostQuery = hostQueryFragment[0].split( '?' ) requestPath = hostQuery[0] if '/' == requestPath: requestPath = '/index.html' hostSuffix = os.path.splitext( requestPath ) query = {} if 1 < len(hostQuery): querySplit = hostQuery[1].split( '&' ) # cheap and dirty for qs in querySplit: qss = qs.split( '=' ) query[qss[0]] = qss[1] if postVars is not None: for postVar in postVars: pv = postVar.decode( 'utf-8' ) val = [ v.decode( 'utf-8' ) for v in postVars[postVar]] # it's an array, for some reason query[pv] = val[0] # lose the other information. TODO: could check to see if _is list_ suffix = hostSuffix[1][1:] try: if '..' in requestPath: response = HandlerBad( host, requestPath, query, fragment, headers, HandlerFactory.handlerTypes['html'] ) else: handlerInfo = HandlerFactory.handlerTypes[suffix] response = handlerInfo['handler']( host, requestPath, query, fragment, headers, handlerInfo ) except KeyError: response = HandlerBad( host, requestPath, query, fragment, headers, HandlerFactory.handlerTypes['html'] ) return response
[ "rchuso@gmail.com" ]
rchuso@gmail.com
00b42fcbfbde767ac076c1bdd0d7fb34c5b3382c
67b0379a12a60e9f26232b81047de3470c4a9ff9
/comments/models.py
27fec916d93089637204f146a37c7c27c5e70df4
[]
no_license
vintkor/whitemandarin
8ea9022b889fac718e0858873a07c586cf8da729
5afcfc5eef1bb1cc2febf519b04a4819a7b9648f
refs/heads/master
2021-05-06T03:35:09.367375
2017-12-20T15:43:08
2017-12-20T15:43:08
114,904,110
0
0
null
null
null
null
UTF-8
Python
false
false
3,969
py
# -*- coding: utf-8 -*- from django.db import models from mptt.models import MPTTModel, TreeForeignKey from tinymce import models as tinymce_model import datetime class Comments(MPTTModel): prod_name = models.CharField(max_length=250, blank=True, db_index=True, verbose_name="Название") paket = models.CharField(max_length=250, db_index=True, verbose_name="Пакет") item_model = models.CharField(max_length=250, db_index=True, verbose_name="Модель") item_id = models.IntegerField(db_index=True, null=True, verbose_name="id") published_in_category = models.BooleanField(default=False, verbose_name='Показывать в категории') parent = TreeForeignKey('self', null=True, blank=True, related_name='children', verbose_name=u"Родитель") name = models.CharField(max_length=250, verbose_name="Название") text = tinymce_model.HTMLField(blank=True, verbose_name="Полное описание") published = models.BooleanField(verbose_name="Опубликован") date_add = models.DateTimeField(default=datetime.datetime.today ,verbose_name="Дата публикации") vote = models.DecimalField(max_digits=2, decimal_places=1,db_index=True, null=True, verbose_name="Оценка") positive = models.IntegerField(null=True, blank=True, default=0, verbose_name="Позитивных") negative = models.IntegerField(null=True, blank=True, default=0, verbose_name="Негативных") def save(self): super(Comments, self).save() try: paket = self.paket item_model = self.item_model id = self.item_id count_comments = Comments.objects.filter(paket=paket, item_model=item_model, item_id=int(id), published = True).count() # assert False, count_comments exec "from %s.models import %s" % (paket, item_model) p = eval("%s.objects.get(pk=%d)" % (item_model, int(id))) p.comments_count = count_comments min_vote = 5 max_vote = 0 all_reit = 0.0 prod_votes = Comments.objects.filter(paket=paket, item_model=item_model, item_id=int(id), published = True).values('vote') for item in prod_votes: if min_vote > item['vote']: min_vote = item['vote'] if max_vote < item['vote']: max_vote = item['vote'] all_reit = all_reit + float(item['vote']) # assert False, min_vote p.min_reit = min_vote p.max_reit = max_vote p.reit = all_reit / count_comments p.save() self.prod_name = p.name except: pass super(Comments, self).save() if not self.date_add: self.date_add = datetime.datetime.today() super(Comments, self).save() def get_name(self): paket = self.paket item_model = self.item_model id = self.item_id # count_comments = Comments.objects.filter(paket=paket, item_model=item_model, item_id=int(id), published = True).count() # assert False, count_comments exec "from %s.models import %s" % (paket, item_model) p = eval("%s.objects.get(pk=%d)" % (item_model, int(id))) return p.name def __unicode__(self): return self.name class Meta: verbose_name_plural = "Коментарии " verbose_name = "Коментарий" ordering = ['-id'] class MPTTMeta: order_insertion_by = ['name'] class Utility(models.Model): comment = models.ForeignKey(Comments, blank=True, null=True, verbose_name="Коммент") positive = models.BooleanField(verbose_name="Позитивная оценка") def __unicode__(self): return self.comment.name class Meta: verbose_name_plural = "Оценки" verbose_name = "Оценка"
[ "alkv84@yandex.ru" ]
alkv84@yandex.ru
372ffb8f05abddeea2704b81e3dfd8ba8d5fa88e
236332a967f8f02291b58cab7addfeabdfe7b9a2
/experiments/tests/testing_2_3.py
207477ec55fb3dd07e0cb74d22864d4061c012cc
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ConsumerAffairs/django-experiments
2dbf04b7f0e7ebdff6d5e7879afeb26f7fdb5150
4f1591c9b40390f7302f3777df231ffe3629f00d
refs/heads/master
2021-01-20T11:10:30.199586
2018-04-20T21:26:18
2018-04-20T21:26:18
101,666,220
0
10
MIT
2018-04-20T21:26:19
2017-08-28T16:56:16
Python
UTF-8
Python
false
false
218
py
# coding=utf-8 try: from unittest import mock, skip except ImportError: import mock class DummyLockTests(object): @classmethod def new(cls): test_class = cls return skip(test_class)
[ "fran.hrzenjak@gmail.com" ]
fran.hrzenjak@gmail.com
e2274c4b1495ca6b6d568d9fbaeb1af253a5788c
13e2726a6e25fd4020713c111fc7eb2f3018fc3d
/Product_recommendation/wsgi.py
c231d1b341a002954b6c6cd20d5a424ba336b998
[]
no_license
Abishek-Balasubramaniam/Product-recommendation
e6d9bbf9e5c32cacda0bbb87d4a518fa26b36400
e307d6e0eaa7ee1a070fff3ecbb41034f67d78ea
refs/heads/main
2023-01-31T07:26:40.674404
2020-12-15T12:29:22
2020-12-15T12:29:22
321,660,980
0
0
null
null
null
null
UTF-8
Python
false
false
421
py
""" WSGI config for Product_recommendation project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Product_recommendation.settings') application = get_wsgi_application()
[ "2903abi@gmail.com" ]
2903abi@gmail.com
7b04a97c368a3b4a75712cea5bdf04c07cc5ca00
e833c155f1bbc446dbf83fe9d09eb2eeaf676cf6
/Year1/CSCA48/Assignments/a1/a1_design.py
83177c2b87e4902065241d535781d23bf53a8964
[]
no_license
vincentt117/UTSC.CS
116ebb41caaafbfaea8172d72c7fd507cfa771cb
ffa1a5bea2b85f3afe75b01830786bc584d2da06
refs/heads/master
2020-09-22T12:48:09.539263
2017-01-30T15:58:39
2017-01-30T15:58:39
67,225,189
0
0
null
null
null
null
UTF-8
Python
false
false
8,249
py
class Matrix(): ''' A class which represents a mathematical matrix ''' def __init__(self, content): '''(Matrix, list of obj) -> None Creates a matrix where a dictionary with keys as two element lists containing the row (element zero) and column (element one) position of the object (stored as value). For example: {[1, 7]: 43}, 43 would be the object in the 1st row 7th column in the matrix. The values passed into init in the form of a list of objects. The list of integers, dimension, will dictate the dimensions of the matrix. Dimension exist in the form of [n, m] where n and m are positve integers that can be equal to one anther. The method will take n objects from content and form the first column, it will continue to do this until there are m columns. REQ: content must contain elements such that the matrix is a valid matrix; there are an appropriate number of elements given the number of rows and columns. ''' pass def add_sub(self, target, add_or_sub): '''(Matrix, Matrix, bool) -> None Given another Matrix, perform either matrix addition or subtraction based on the value of add_or_sub. If add_or_sub is True perform addition, else (it being False) perform subtraction. REQ: Elements which reside in the same coordinate of either matrices must be of the same object type and must be able to added/subtracted from one another by some context ''' pass def transpose(self): '''(Matrix) -> None Perform a matrix tranposition on the matrix calling the method. The operation will invert the coordinates of all objects contained in the matrix: row values become column values and vice versa ''' pass def multi(self, target): '''(Matrix, Matrix) -> None Given another Matrix, perform matrix multiplication with the calling matrix on the left hand side of the operation and the target matrix on the right. Method will perform multiplication as described by standard matrix operation. REQ: number of column of the calling matrix must be equal to the number of rows of the targe matrix REQ: All elements within the calling matrix and the matrix being called must be integers or floats ''' pass def switch(self, row_or_col, switched): '''(Matrix, bool, list of ints) -> None Switch two columns or two rows of a calling matrix. If row_or_col is True, switch the two rows contained in switched. For example, if row_or_col is True and switched is [1,3] switch the first and third rows of the matrix. If row_or_col is False, perform the same action, but switch columns instead. REQ: Matrix must possess the rows or columns contained in switch REQ: switched contains exactly two integers ''' pass def get_by_row_or_col(self, coordinate, row_or_col): '''(Matrix, list of ints) -> obj Return a particular object in the matrix by a certain column or row and a position in the row or column. row_or_col dictates whether or not the object is referenced by row or column. If row_or_col is True, it is referencing by row, else it is referencing by row. Coordinate contains two integers, where the first is the coordinate[0]-th row or column and the second is the coordinate[1]-th item in that row/column For example if coordinate is [3, 4], and row_or_col is True return the 4th item in the third column. REQ: Designate coordinate must exist within the matrix ''' pass def set_by_row_or_col(self, replace, coordinate, row_or_col): '''(Matrix, obj, list of ints, bool) -> None Replace a particular object in the matrix by a certain column or row and a position in the row or column. row_or_col dictates whether or not the object is referenced by row or column. If row_or_col is True, it is referencing by row, else it is referencing by row. Coordinate contains two integers, where the first is the coordinate[0]-th row or column and the second is the coordinate[1]-th item in that row/column For example if coordinate is [3, 4], and row_or_col is True return the 4th item in the third column. REQ: Designate coordinate must exist within the matrix REQ: Cannot be called upon by symmetric or identity matrix in a way that would compromise their property of being symmetric or an identity ''' pass def get_determinant(self): '''(Matrix) -> int Returns the determinant of the matrix. The determinant being the difference of the product of the item in the first row first column and item in the second row second column and the product of the item in the first row second column and the second row first column. REQ: Matrix must be 2 by 2 and contain only ints ''' pass def set_content(self, content): '''(Matrix, list of obj) -> None Sets the content of a given Matrix; replacing all elements. REQ: content must be appropriate to dimensions of calling matrix ''' pass class SquareMatrix(Matrix): '''A class which represents a n by n matrix ''' def get_by_daig(self, duel_coor): ''' (Matrix, int) -> obj Return the object at a diagonal position in the calling matrix. For example, if duel_coor is 6, return the item at the 6th column in the 6th row. REQ: Matrix must contain at least as many diagonals as illustraded by duel_coor ''' pass def set_by_diag(self, replace, duel_coor): ''' (Matrix, obj, int) -> None Replace the object at the diagonal specified by duel_coor with the object replace.For example, if duel_coor is 6, replace the item at the 6th column in the 6th row. REQ: Matrix must contain at least as many diagonals as illustraded by duel_coor ''' pass class SymmetricMatrix(SquareMatrix): '''A class which represents a n by n symmetrix matrix ''' def set_by_row_or_col(self, replace, coordinate, treat_as_sym): '''(Matrix, obj, list of ints, bool, bool) -> None Replace a particular object in the matrix by a certain column or row and a position in the row or column. row_or_col dictates whether or not the object is referenced by row or column. If row_or_col is True, it is referencing by row, else it is referencing by row. Coordinate contains two integers, where the first is the coordinate[0]-th row or column and the second is the coordinate[1]-th item in that row/column For example if coordinate is [3, 4], and row_or_col is True return the 4th item in the third column. REQ: Designate coordinate must exist within the matrix ''' pass class IdentityMatrix(SymmetricMatrix): ''' A class which represents an identity matrix ''' def __init__(self, value=1, dimension): ''' (Matrix, obj, int) -> None Create an indentity matrix with the object 'value' populating the diaglonal of the matrix and square dimensions as illustrated by dimension. By difault, the diagonals will be populated with integer 1. ''' pass class OneDMatrix(Matrix): ''' A class which represents a one dimentional matrix ''' def get_val(self, target_val): ''' (Matrix, int) -> obj Return the object held in the target_val-th position of the matrix. REQ: Matrix must have as many positions as illustrated by target_val ''' pass def set_val(self, target_val, replace): ''' (Matrix, int, obj) -> None Replace the object at the target_val-th position of the matrix with the replace value. REQ: Matrix must have as many positions as illustrated by target_val ''' pass
[ "vincentteng@wifihost-82-190.wireless.utsc.utoronto.ca" ]
vincentteng@wifihost-82-190.wireless.utsc.utoronto.ca
7d6af601707ee714c69284f9139215e5417fc341
895700e89119ef4140befdc38588e51af48793cf
/Hongik_Class/Circular_List.py
94a0053cfded54f194a6a56ee8db88555974e7b9
[]
no_license
yoonsangmin/Coding_Test
d17096c5f867c21c05ddcbd854b2a0f32367611c
122bccd2c584f4f2babad835ea22c12352f690c1
refs/heads/master
2023-01-08T06:47:53.276862
2020-11-13T01:42:36
2020-11-13T01:42:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,368
py
#원형 리스트 #https://blex.me/@baealex/%ED%8C%8C%EC%9D%B4%EC%8D%AC%EC%9C%BC%EB%A1%9C-%EA%B5%AC%ED%98%84%ED%95%9C-%EC%9E%90%EB%A3%8C%EA%B5%AC%EC%A1%B0-%EC%97%B0%EA%B2%B0-%EB%A6%AC%EC%8A%A4%ED%8A%B8 #위의 코드 중 오류 수정 버전 #Node는 [ Data | Next ] # <Head> <Tail> # CircleLinkedList는 [ Data | Next ] --> [ Data | Next ] --> [ Data | Next ] # | | # ----------------------------------------------- class Node: def __init__(self, data): self.data = data self.next = None class CircleLinkedList: def __init__(self, data): new_node = Node(data) self.head = new_node self.tail = None self.list_size = 1 def __str__(self): print_list = '[ ' node = self.head while True: if node: print_list += str(node.data) if node == self.tail: # 단순 연결 리스트와 달리 # 노드가 테일 노드면 끝난다 break node = node.next print_list += ', ' print_list += ' ]' return print_list #헤드 추가 함수 def insertFirst(self, data): new_node = Node(data) if self.tail == None: #테일 추가 self.tail = self.head temp_node = self.head self.head = new_node self.head.next = temp_node self.tail.next = new_node #테일 추가 self.list_size += 1 #중간에 넣는 함수는 동일 def insertMiddle(self, num, data): node = self.selectNode(num) new_node = Node(data) temp_next = node.next node.next = new_node new_node.next = temp_next self.list_size += 1 #맨 마지막에 넘느 함수는 tail 처리 필요 def insertLast(self, data): new_node = Node(data) if self.tail == None: self.tail = new_node self.head.next = self.tail else: self.tail.next = new_node self.tail = new_node self.tail.next = self.head self.list_size += 1 def selectNode(self, num): if self.list_size < num: print("Overflow") return node = self.head count = 0 while count < num: node = node.next count += 1 return node def deleteNode(self, num): if self.list_size < 1: return # Underflow elif self.list_size < num: return # Overflow if num == 0: self.deleteHead() return node = self.selectNode(num - 1) node.next = node.next.next del_node = node.next del del_node def deleteHead(self): node = self.head self.head = node.next del node def size(self): return str(self.list_size) def get_head_tail(self): return self.head.data, self.tail.data #메인 함수 if __name__ == "__main__": a = CircleLinkedList(100) print(a.size()) a.insertFirst(999) a.insertFirst(9990) a.insertLast(77) a.insertMiddle(2, 500) b, c = a.get_head_tail() print("head:{} tail:{}".format(b, c)) print(a)
[ "kacias@daum.net" ]
kacias@daum.net
a63f0922e59cac5a62214ffbe9d6b901f45c2afc
844ac3a61068c6d60fbf2add52d927f29d3453c9
/main.py
afde28c6164b8aff73edf7f88f59530d4b9e121b
[]
no_license
ilacombe2022/Rock-Paper-Scissors
21cffa80802361b329d94358f528928a82089485
efd0597ec8614070f7738ffaa0a0caf850bcca62
refs/heads/main
2023-03-22T10:42:37.247944
2021-03-11T17:38:50
2021-03-11T17:38:50
346,786,042
0
0
null
null
null
null
UTF-8
Python
false
false
5,867
py
import random def choose(): choice = input("Shall we get started? [yes/no]: ").lower().strip() if choice == "yes": return choice elif choice == "no": print("We understand, thanks anyways.") exit() else: print("That's not the answer we're looking for.") choose() def difficulty(): print("Choose your difficulty:") print("Best of 1") print("Best of 3") print("Best of 5") diff = int(input("\n[1/3/5]: ")) if diff == 1: bestOfOne(1) elif diff == 3: bestOfThree(2) elif diff == 5: bestOfFive(3) else: print("We do not provide that difficulty.\n") return difficulty() def winner(u,c): print("\nYou beat Al!") print("Final Score: %d - %d" % (u, c)) print("Number of Rounds: %d" % (round - 1)) def loser(u, c): print("You lost to Al.") print("Final Score: %d - %d" % (u, c)) print("Number of Rounds: %d" % (round - 1)) def bestOfOne(num): print("Rule: \tOne round of Rock-Paper-Scissors.") print("\t\tFirst person to score 1 point win!") startGame() introCPU() playGame(num) def bestOfThree(num): print("Rule: \tThree rounds of Rock-Paper-Scissors.") print("\t\tFirst person to score 2 points win!") startGame() introCPU() playGame(num) def bestOfFive(num): print("Rule: \tFive rounds of Rock-Paper-Scissors.") print("\t\tFirst person to score 3 points win!") startGame() introCPU() playGame(num) def playGame(match): userPoint = 0 computerPoint = 0 round = 1 while userPoint < match and computerPoint < match: user = input("\nRound #%d, what will you choose? [rock/paper/scissors]: " % round) computer = random.randrange(1, 4, 1) if user == "rock" or user == "paper" or user == "scissors": if user == "rock" and computer == 1: print("You chose rock and Al chose rock! Tie!") print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "rock" and computer == 2: print("You chose rock and Al chose paper! Al gets a point!") computerPoint = computerPoint + 1 print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "rock" and computer == 3: print("You chose rock and Al chose scissors! You get a point!") userPoint = userPoint + 1 print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "paper" and computer == 1: print("You chose paper and Al chose rock! You gets a point!") userPoint = userPoint + 1 print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "paper" and computer == 2: print("You chose paper and Al chose paper! Tie!") print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "paper" and computer == 3: print("You chose paper and Al chose scissors! Al gets a point!") computerPoint = computerPoint + 1 print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "scissors" and computer == 1: print("You chose scissors and Al chose rock! Al gets a point!") computerPoint = computerPoint + 1 print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "scissors" and computer == 2: print("You chose scissors and Al chose paper! You get a point!") userPoint = userPoint + 1 print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 elif user == "scissors" and computer == 3: print("You chose scissors and Al chose scissors! Tie!") print("Score: %d - %d" % (userPoint, computerPoint)) round = round + 1 else: print("Not an option, time to start over.\n") playGame(match) if userPoint == match: print("\nYou beat Al!") print("Final Score: %d - %d" % (userPoint, computerPoint)) print("Number of Rounds: %d" % (round - 1)) playAgain() elif computerPoint == match: print("You lost to Al.") print("Final Score: %d - %d" % (userPoint, computerPoint)) print("Number of Rounds: %d" % (round - 1)) playAgain() def playAgain(): again = input("\nWould you like to play again?[yes/no]: ").lower().strip() if again == "yes": difficulty() elif again == "no": print("Thanks for playing!") exit() else: print("We are trying to ask if you would like to play again?") playAgain() def startGame(): start = input("\nAre you ready to play against the CPU? [yes/no]: ").lower().strip() if start == "yes": return start elif start == "no": print("Oh! You've changed your mind? That's fine.") exit() else: print("That choice isn't available.\n") startGame() def introCPU(): print("Say hello to Al! He will be you opponent!") print("NOTE: Make sure you spell each word correctly, otherwise, rounds and scores will be reset!") print("HAVE FUN!") if __name__ == '__main__': print("Let's play Rock-Paper-Scissors!") print("Created by Isaac Lacombe\n") choose() difficulty()
[ "noreply@github.com" ]
ilacombe2022.noreply@github.com
8596d664d4d312c1676cc07523a9763a6db80efd
50364def388dfcf4015109cc634dc10fc205edb5
/FaceVerify.py
8d8e14c1a9a7324c471b99b5b31b72e26ae522d7
[]
no_license
malhotraguy/traspod
73bb18221226362035188cb6eade71d9de8ccc16
5d9fd5c9ea266bc6660f532a360cb7f538a50796
refs/heads/master
2021-01-24T01:13:51.033523
2018-03-01T21:57:23
2018-03-01T21:57:23
122,801,097
2
0
null
null
null
null
UTF-8
Python
false
false
3,594
py
import requests from io import BytesIO from PIL import Image, ImageDraw import cognitive_face as CF import urllib import urllib.request as ur import cv2 import numpy as np import matplotlib.pyplot as plt KEY = '6a294681f0f640f3a8b60b1c7de8ea85' # Replace with a valid subscription key (keeping the quotes in place). CF.Key.set(KEY) # If you need to, you can change your base API url with: # CF.BaseUrl.set('https://westus.api.cognitive.microsoft.com/face/v1.0/detect') BASE_URL = 'https://eastus.api.cognitive.microsoft.com/face/v1.0/' # Replace with your regional Base URL CF.BaseUrl.set(BASE_URL) # You can use this example JPG or replace the URL below with your own URL to a JPEG image. img_url = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/1.jpg' result = CF.face.detect(img_url) print(result) #Convert width height to a point in a rectangle def getRectangle(faceDictionary): rect = faceDictionary['faceRectangle'] left = rect['left'] top = rect['top'] bottom = left + rect['height'] right = top + rect['width'] return ((left, top), (bottom, right)) #Download the image from the url response = requests.get(img_url) img = Image.open(BytesIO(response.content)) #For each face returned use the face rectangle and draw a red box. draw = ImageDraw.Draw(img) for face in result: draw.rectangle(getRectangle(face), outline='red') #Display the image in the users default image browser. img.show() def url_to_image(url): """ a helper function that downloads the image, converts it to a NumPy array, and then reads it into OpenCV format """ resp = ur.urlopen(url) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) # return the image return image img = url_to_image(img_url) plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.axis('off') height = result[0]['faceRectangle']['height'] left = result[0]['faceRectangle']['left'] top = result[0]['faceRectangle']['top'] width = result[0]['faceRectangle']['width'] plt.imshow(cv2.cvtColor(img[top:top+height, left:left+width], cv2.COLOR_BGR2RGB)) plt.axis('off') url1 = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/10.jpg' url2 = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/5.jpg' url3 = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/4.jpg' url4 = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/3.jpg' urls = [url1, url2, url3, url4] for url in urls: plt.imshow(cv2.cvtColor(url_to_image(url), cv2.COLOR_BGR2RGB)) plt.axis('off') plt.show() results = [] for url in urls: r = CF.face.detect(url) results += r, all_faceid = [f['faceId'] for image in results for f in image] test_url = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/2.jpg' plt.imshow(cv2.cvtColor(url_to_image(test_url), cv2.COLOR_BGR2RGB)) test_result = CF.face.detect(test_url) test_faceId = test_result[0]['faceId'] for f in all_faceid: r = CF.face.verify(f, test_faceId) print(r) identical_face_id = [f for f in all_faceid if CF.face.verify(f, test_faceId)['isIdentical'] == True] for i in range(len(results)): for face in results[i]: if face['faceId'] in identical_face_id: height = face['faceRectangle']['height'] left = face['faceRectangle']['left'] top = face['faceRectangle']['top'] width = face['faceRectangle']['width'] plt.imshow(cv2.cvtColor(url_to_image(urls[i])[top:top+height, left:left+width], cv2.COLOR_BGR2RGB)) plt.axis('off') plt.show()
[ "noreply@github.com" ]
malhotraguy.noreply@github.com
f6bb5a74f05f10651cae3ee6b1e226e5f896c8de
65e0c11d690b32c832b943fb43a4206739ddf733
/bsdradius/tags/release20060404_v_0_4_0/bsdradius/Typecast.py
436a5e6ae0899419c20edf50298dd09eb597dcaf
[ "BSD-3-Clause" ]
permissive
Cloudxtreme/bsdradius
b5100062ed75c3201d179e190fd89770d8934aee
69dba67e27215dce49875e94a7eedbbdf77bc784
refs/heads/master
2021-05-28T16:50:14.711056
2015-04-30T11:54:17
2015-04-30T11:54:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,761
py
## BSDRadius is released under BSD license. ## Copyright (c) 2006, DATA TECH LABS ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## * Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## * Neither the name of the DATA TECH LABS nor the names of its contributors ## may be used to endorse or promote products derived from this software without ## specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ## ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ## WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ## DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ## (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ## LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ## ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ## SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Functions and methods for casting types from string to other types. Contains functions and class for inheritance in other classes. Supported types: 'str', 'string', 'int', 'hex', 'oct', 'dec', 'bool', 'Template' """ # HeadURL $HeadURL: file:///Z:/backup/svn/bsdradius/tags/release20060404_v_0_4_0/bsdradius/Typecast.py $ # Author: $Author: valts $ # File version: $Revision: 201 $ # Last changes: $Date: 2006-04-04 17:22:11 +0300 (Ot, 04 Apr 2006) $ # for typecasting to Template from string import Template ### functions ### def getstr (input): return str(input) def getstring (input): return getstr(input) def getint (input): return int(str(input)) def gethex (input): return int(str(input), 16) def getoct (input): return int(str(input), 8) def getdec (input): return int(str(input), 10) _booleanStates = {'1': True, 'yes': True, 'y': True, 'true': True, 'on': True, '0': False, 'no': False, 'n': False, 'false': False, 'off': False} def getbool (input): inp = str(input) if inp.lower() not in _booleanStates: raise ValueError, 'Not a boolean: %s' % inp return _booleanStates[inp.lower()] def getTemplate (input): return Template(str(input)) class Typecast: """Use this class as base class in your classes to add typecasting functionality. This class defines methods which are wrappers to functions in module namespace. You can override attribute "data" in derived classes. Since self.data is dictionary (with multiple levels) you can pass any number of keys to typecasting methods. They all use method _getItem() which searches recursively in self.data for rightmost key value. """ _booleanStates = _booleanStates def __init__(self): self.data = {} def _getItem(self, keys): """Search recursively for item by given keys Input: (str) keys Example: t._getItem('key1', 'key2', 'key3') Output: (mixed) value """ if not keys: raise KeyError, 'No key specified' tmp = None for key in keys: if tmp is None: tmp = self.data[key] else: tmp = tmp[key] return tmp def getstr (self, *keys): return getstr(self._getItem(keys)) def getstring (self, *keys): return getstring(self._getItem(keys)) def getint (self, *keys): return getint(self._getItem(keys)) def gethex (self, *keys): return gethex(self._getItem(keys)) def getoct (self, *keys): return getoct(self._getItem(keys)) def getdec (self, *keys): return getdec(self._getItem(keys)) def getbool (self, *keys): return getbool(self._getItem(keys)) def getTemplate (self, *keys): return getTemplate(self._getItem(keys)) # holds references to all supported typecast methods typecastMethods = { 'str' : getstr, 'string' : getstring, 'int' : getint, 'hex' : gethex, 'oct' : getoct, 'dec' : getdec, 'bool' : getbool, 'Template' : getTemplate, } # holds references to all supported typecast methods Typecast.typecastMethods = { 'str' : Typecast.getstr, 'string' : Typecast.getstring, 'int' : Typecast.getint, 'hex' : Typecast.gethex, 'oct' : Typecast.getoct, 'dec' : Typecast.getdec, 'bool' : Typecast.getbool, 'Template' : Typecast.getTemplate, }
[ "valdiic@72071c86-a5be-11dd-a5cd-697bfd0a0cef" ]
valdiic@72071c86-a5be-11dd-a5cd-697bfd0a0cef
76eac8484a0e0f4385ec8d7a7a8100f4be7cd089
d6fa7b19190e83447ac7456ccce5e0d8ae7de4f0
/move.py
dd11292061947f3145cb005a2f669d9ce85a0b32
[]
no_license
VariousMilkshakes/GRID-py
ffcabd35bd421ca56d1486f7b75c875d073940bc
d243be07016742ab129cb0e48ae64c0f5e0733fa
refs/heads/master
2016-08-08T04:03:47.105610
2013-07-04T21:32:37
2013-07-04T21:32:37
11,161,532
0
0
null
null
null
null
ISO-8859-4
Python
false
false
3,402
py
# -*- coding: cp1252 -*- from random import randint import sys print "Welcome to the this Test" print "This is test 2: Sam like Woffles!" print gY = input("How tall do you want your grid?") gX = input("How wide do you want your grid?") oY = gY oX = gX - 2 Xinput = input("Where do you want to start? (X)") Yinput = input("Where do you want to start (Y)?") print c = 0 while (c == 0): foodX = randint(0,oX) foodY = randint(0,oY) if Xinput == foodX and foodY == Yinput: c = 0 else: c = 1 fX = foodX fY = foodY item = '#' mX = Xinput mY = Yinput game = 0 ship='A' jump = False while(game == 0): o = 0 x = 0 y = 0 rowXdef = { 0 : [o] } while (y <= oY): while (x <= oX): rowXdef[y].append(o) x = x + 1 x = 0 y = y + 1 rowXdef[y] = [o] mark = rowXdef[mY] mark[mX] = ship spawn = rowXdef[fY] spawn[fX] = item del rowXdef[(oY + 1)] del rowXdef[oY] if mY == fY and mX == fX: print 'WIN' raw_input() sys.exit() for line in rowXdef: x = rowXdef[line] cCell = 0 while (cCell <= oX): for cell in x: print cell, cCell = cCell + 1 print clean = 0 while (clean == 0): move = raw_input() if move == 'w': if jump == True: mY = (gY - 1) jump = False else: mY = mY - 1 if mY == 0: jump = True ship = 'A' clean = 1 elif move == 'a': if jump == True: mX = (gX - 1) jump = False else: mX = mX - 1 if mX == 0: jump = True ship = '<' clean = 1 elif move == 'd': if jump == True: mX = 0 jump = False else: mX = mX + 1 if mX == (gX - 1): jump = True ship = '>' clean = 1 elif move == 's': if jump == True: mY = 0 jump = False else: mY = mY + 1 if mY == (gY - 1): jump = True ship = 'V' clean = 1 else: print "Īnvalid Movement Key"
[ "bn.gladstone@gmail.com" ]
bn.gladstone@gmail.com
77fdcf1dbfc3a529545552210737968c88bf404b
ffaeaf54e891c3dcca735347f27f1980f66b7a41
/python/1.POP/1.base/01.helloworld.py
015e87763fe1f07c2320ce7fe71f056ea13d317c
[ "Apache-2.0" ]
permissive
dunitian/BaseCode
9804e3d8ff1cb6d4d8cca96978b20d168072e8bf
4855ef4c6dd7c95d7239d2048832d8acfe26e084
refs/heads/master
2020-04-13T09:51:02.465773
2018-12-24T13:26:32
2018-12-24T13:26:32
137,184,193
0
0
Apache-2.0
2018-06-13T08:13:38
2018-06-13T08:13:38
null
UTF-8
Python
false
false
970
py
'''三个单引号多行注释: print("Hello World!") print("Hello World!") print("Hello World!")''' """三个双引号多行注释: print("Hello World!") print("Hello World!") print("Hello World!")""" # 单行注释 输出 print("Hello World!") # 定义一个变量并输出 name = "小明" print(name) print("x" * 10) print("dnt.dkill.net/now", end='') print("带你走进中医经络") print("dnt.dkill.net/now", end="") print("带你走进中医经络") # 如果字符串内部既包含'又包含"怎么办?可以用转义字符\来标识 print("I\'m \"OK\"!") # 如果字符串里面有很多字符都需要转义,就需要加很多\,为了简化,Python还允许用r''表示''内部的字符串默认不转义 print(r'\\\t\\') # 如果字符串内部有很多换行,用\n写在一行里不好阅读,为了简化,Python允许用'''...'''的格式表示多行内容 print('''我请你吃饭吧~ 晚上吃啥? 去厕所,你说呢?''')
[ "39723758+lotapp@users.noreply.github.com" ]
39723758+lotapp@users.noreply.github.com
b6191a17aaf91109773e1e4d016a0f29112fe0f6
d46bae120d44ccec2ac00aa6f7bf2bde744dde73
/venv/bin/python-config
570bc983cb0570a1347c2d2bb79d4ba0f54f6602
[]
no_license
Link-yu/FlaskProject
9f5bbe4596e2a6212cc8764b36348d9326e5b014
e3d560067a5ca6d7e4cccc626ea56b9179b0340d
refs/heads/master
2020-12-02T09:59:53.753105
2017-07-11T12:24:45
2017-07-11T12:24:45
96,673,152
0
0
null
null
null
null
UTF-8
Python
false
false
2,353
#!/home/yupaopao/myPythonProject/venv/bin/python import sys import getopt import sysconfig valid_opts = ['prefix', 'exec-prefix', 'includes', 'libs', 'cflags', 'ldflags', 'help'] if sys.version_info >= (3, 2): valid_opts.insert(-1, 'extension-suffix') valid_opts.append('abiflags') if sys.version_info >= (3, 3): valid_opts.append('configdir') def exit_with_usage(code=1): sys.stderr.write("Usage: {0} [{1}]\n".format( sys.argv[0], '|'.join('--'+opt for opt in valid_opts))) sys.exit(code) try: opts, args = getopt.getopt(sys.argv[1:], '', valid_opts) except getopt.error: exit_with_usage() if not opts: exit_with_usage() pyver = sysconfig.get_config_var('VERSION') getvar = sysconfig.get_config_var opt_flags = [flag for (flag, val) in opts] if '--help' in opt_flags: exit_with_usage(code=0) for opt in opt_flags: if opt == '--prefix': print(sysconfig.get_config_var('prefix')) elif opt == '--exec-prefix': print(sysconfig.get_config_var('exec_prefix')) elif opt in ('--includes', '--cflags'): flags = ['-I' + sysconfig.get_path('include'), '-I' + sysconfig.get_path('platinclude')] if opt == '--cflags': flags.extend(getvar('CFLAGS').split()) print(' '.join(flags)) elif opt in ('--libs', '--ldflags'): abiflags = getattr(sys, 'abiflags', '') libs = ['-lpython' + pyver + abiflags] libs += getvar('LIBS').split() libs += getvar('SYSLIBS').split() # add the prefix/lib/pythonX.Y/config dir, but only if there is no # shared library in prefix/lib/. if opt == '--ldflags': if not getvar('Py_ENABLE_SHARED'): libs.insert(0, '-L' + getvar('LIBPL')) if not getvar('PYTHONFRAMEWORK'): libs.extend(getvar('LINKFORSHARED').split()) print(' '.join(libs)) elif opt == '--extension-suffix': ext_suffix = sysconfig.get_config_var('EXT_SUFFIX') if ext_suffix is None: ext_suffix = sysconfig.get_config_var('SO') print(ext_suffix) elif opt == '--abiflags': if not getattr(sys, 'abiflags', None): exit_with_usage() print(sys.abiflags) elif opt == '--configdir': print(sysconfig.get_config_var('LIBPL'))
[ "kevinyulk@163.com" ]
kevinyulk@163.com
af891e3712afa7d736c6effa451ec60674ec01ed
8504d656fa7badf8aba07ee4930c4d6b7b886e3c
/news_portal_api/wsgi.py
b6a9ff44f93ecdff4d45e8d9d0ac81e58d81b71a
[]
no_license
SarojRajTiwari/web_api_final
a35a8cb4f55b22cf661901ad12b31c878b7db0a6
2ed85ce6566b59e25f554c5a976202954317ca76
refs/heads/master
2022-12-12T06:44:13.643069
2019-12-02T07:50:07
2019-12-02T07:50:07
225,308,743
0
0
null
null
null
null
UTF-8
Python
false
false
407
py
""" WSGI config for news_portal_api 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', 'news_portal_api.settings') application = get_wsgi_application()
[ "sarojrajtiwari5@gmail.com" ]
sarojrajtiwari5@gmail.com
8de1127722d96b24e0ea4a854844cb853d233569
7193be8e52b2095d8b6472f3ef2104843dca339e
/Project5-Capstone/the_dummy_variables/josh/testing/test_relative_path.py
1f24c6af184d5ae1c59feb6189e85136b5bb7ee5
[]
no_license
vuchau/bootcamp007_project
4b0f37f49a1163ea6d8ee4143a5dcfdef0d352dd
ffbd0f961b18510fc72fd49770187ec1b4b013ae
refs/heads/master
2020-03-20T13:19:58.812791
2017-06-08T05:13:24
2017-06-08T05:13:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
140
py
import os file_dir = os.path.dirname(__file__) print file_dir dirname = os.path.dirname print dirname(dirname(os.path.abspath(__file__)))
[ "jlitven@gmail.com" ]
jlitven@gmail.com
a81b7b040209bbe9e4e5f1677ea8da5097ef6593
906297c4f691b03e65b454bf9c12ab0331e53589
/cron/tasks.py
b05b58e0b7ff3f2b13ed3fe898d4431d67695957
[]
no_license
unamatasanatarai/django-movie-theater
5798a54044a889c71f937865fe3adfbe477eb6ab
7d0cd27738b330bfe67eef1a35d2827c2137a222
refs/heads/master
2021-01-23T15:07:47.382052
2017-09-07T06:33:13
2017-09-07T06:33:13
102,700,159
1
1
null
null
null
null
UTF-8
Python
false
false
956
py
from celery import task from theater.models import SeatTentative, SeatBooked from datetime import datetime, timedelta from rest.communicate import Communicate @task() def trim_tentative(): elements = SeatTentative.objects.filter(created_at__lte=(datetime.now() - timedelta(minutes=3))) movie_ids = elements.values_list('repertoire_id', flat=True).distinct() elements.delete() for movie_id in movie_ids: Communicate.tentative_push(str(movie_id)) @task() def confirm_payments(): toconfirm = SeatBooked.objects.filter(created_at__lte=(datetime.now() - timedelta(minutes=2)), confirmed=False) movie_ids = toconfirm.values_list('repertoire_id', flat=True).distinct() for seat in toconfirm: seat.confirmed = True seat.save() SeatTentative.objects.filter(repertoire_id=seat.repertoire_id, seat_id=seat.id).delete() for movie_id in movie_ids: Communicate.tentative_push(str(movie_id))
[ "piotr.grabowski@interak.pl" ]
piotr.grabowski@interak.pl
0c3d4e6d095391de301cf46bf58d774a8b2830a2
3a12b346c87b05dac63951b3bc9cdd882d5ec9ed
/com/huai/learning/customLoss.py
5fe805bc9a0714a658b8ffb5710a0f4cfedfc37e
[]
no_license
namebxl/my_tensorflow
96005d656d33cdb5a8c4a54380adbff5ba697d6f
43e7ccdc94125b125476747b1897795171ad4358
refs/heads/master
2021-06-30T02:51:26.574885
2021-01-20T08:05:51
2021-01-20T08:05:51
213,275,207
0
0
null
2019-10-07T01:52:24
2019-10-07T01:52:24
null
UTF-8
Python
false
false
1,002
py
import tensorflow as tf from numpy.random import RandomState batch_size = 8; x = tf.placeholder(tf.float32, shape=(None, 2), name="x-input") y_ = tf.placeholder(tf.float32, shape=(None, 1), name="y-input") w1 = tf.Variable(tf.random_normal([2, 1], stddev=1, seed=1)); y = tf.matmul(x, w1); loss_less = 10; loss_more = 1; loss = tf.reduce_sum(tf.where(tf.greater(y, y_), (y - y_)*loss_more, (y_-y)*loss_less)); train_step = tf.train.AdamOptimizer(0.001).minimize(loss); rdm = RandomState(1); dataset_size = 128; X = rdm.rand(dataset_size, 2); Y = [[x1 + x2 + rdm.rand()/10.0 - 0.05] for (x1, x2) in X]; with tf.Session() as sess: init_op = tf.initialize_all_variables(); sess.run(init_op); STEPS = 5000; for i in range(STEPS): start = (i * batch_size)%dataset_size; end = min(start + batch_size, dataset_size); sess.run(train_step, feed_dict={x: X[start: end], y_:Y[start: end]}) print(sess.run(w1));
[ "1757153156@qq.com" ]
1757153156@qq.com
bfce90df81d846a317456efccf614e1b2558a113
495fbb4b87586186480826273abf55b947d9c366
/Adivinar_el_numero.py
989c64be349a9c164f29fa88863b8a2871297b8a
[]
no_license
GitBis/-FP-_Labo06_-00370819-
d7b777a76096e7936e5114b10516876f11f360b0
074166f4caefc9a3e4cbd214e40df6556f4dfd24
refs/heads/master
2020-08-13T04:06:13.414501
2019-10-16T05:53:26
2019-10-16T05:53:26
214,902,229
0
0
null
null
null
null
UTF-8
Python
false
false
842
py
import random print("ADIVINA EL NUMERO") comprobar = True contador = 1 while comprobar == True: n = int(input("Ingrese un numero del 1 al 10: ")) if n > 0 and n < 11: all = random.randrange(1,10) if n == all: print(all) print(f"numero de intentos: {contador}") else: while n != all: if n > all: n = int(input("¡Te pasastes! vuelve a intentar: ")) contador += 1 elif n < all: n = int(input("¡Prueba un numero mayor! : ")) contador += 1 print(f"El numero aleatorio era: {all}") print(f"numero de intentos: {contador}") comprobar = False else: print("Ese no es un numero del 1 al 10 vuelve a intentar")
[ "00370819@uca.edu.sv" ]
00370819@uca.edu.sv
a135ba849e3b4b36122c67ab34cbc6fde8d2f519
702c7b618951339f31b4161f55bbbd8f3ffd7811
/hw1/hw1.py
94d3f51e7f777b1727c9f5569e4fa7bc34d19109
[]
no_license
erhla/machine-learning
839f581676cb003d304a2f6efc0528885fce993c
6e9bb6fa377a91039695a717f932f14e5f2214d9
refs/heads/master
2020-05-04T23:31:05.531591
2019-05-29T20:12:28
2019-05-29T20:12:28
179,546,114
0
0
null
null
null
null
UTF-8
Python
false
false
3,773
py
''' Homework 1 Eric Langowski ''' import pandas as pd from sodapy import Socrata import geopandas import shapely #Problem 1 CRIMES_18 = '3i3m-jwuy' CRIMES_17 = 'd62x-nvdr' CENSUS_TRACTS = '74p9-q2aq' def get_crime_data(cid): ''' gets crime data from City of Chicago API ''' client = Socrata('data.cityofchicago.org', None) current = 0 results = client.get(cid, limit=2000, offset=current) while len(results) > 0: current += 2000 new = client.get(cid, limit=2000, offset=current) if new: results.append(new) else: break print(current) return pd.DataFrame.from_records(results) def download_17_18(): ''' Downloads '17 and '18 Crime data ''' crime_17 = get_crime_data(CRIMES_17) crime_18 = get_crime_data(CRIMES_18) return pd.concat(crime_17, crime_18) CSV_URL = 'https://data.cityofchicago.org/api/views/' CSV_FRAG = '/rows.csv?accessType=DOWNLOAD' URLS = {'17': CSV_URL + CRIMES_17 + CSV_FRAG, '18': CSV_URL + CRIMES_18 + CSV_FRAG} def download_17_18_alt(): ''' Alternate method to download '17 and '18 crime data ''' crime_17 = pd.read_csv(URLS['17']) crime_18 = pd.read_csv(URLS['18']) df = pd.concat([crime_17, crime_18]) df['Date'] = pd.to_datetime(df['Date']) return df CENSUS_VARIABLES = {"S0101_C01_001E": "Population", "S1701_C02_001E": "Population in Poverty", "S1901_C01_012E": "Median income", "S1501_C02_015E": "Percent Population with Bachelors", "S2303_C02_033E": "Percent Population working full-time", "S1601_C02_003E": "Percent speaking not English"} CENSUS_URL = "https://api.census.gov/data/2017/acs/acs5/subject?get=" CENSUS_FRAG = "&for=tract:*&in=state:17&in=county:031" def get_census_data(): ''' gets census data for Census tracts in Chicago. Modify dictionary census_variables to change which variables are retrieved ''' url = CENSUS_URL + ",".join(CENSUS_VARIABLES.keys()) + CENSUS_FRAG df = pd.read_json(url, orient='records') new_cols = list(CENSUS_VARIABLES.values()) + ['state', 'county', 'tract'] df.columns = new_cols df = df.drop(df.index[0]) df = df.drop(['state', 'county'], axis=1) return df def geomerge(crime_data): ''' Note: Some of this code is from my group's 122 project which made a spatial join on Chicago's neighborhoods. This takes the crime data and performs a spatial join on Chicago's census tracts. Returns: (geodf) the crime df ''' client = Socrata('data.cityofchicago.org', None) files = client.get(CENSUS_TRACTS) df = pd.DataFrame(files) df['the_geom'] = df['the_geom'].apply(shapely.geometry.shape) df = geopandas.GeoDataFrame(df, geometry='the_geom') df.crs = {'init': 'espg:4326'} df = df[['the_geom', 'tractce10']] crime_data = crime_data[crime_data['Longitude'].notna()] crime_data['Location'] = crime_data['Location'].str.strip('()').str.split(',') crime_data['Location'] = crime_data['Location'].apply(lambda x: (float(x[1]), float(x[0]))) crime_data.loc[:, 'Location'] = crime_data['Location'].apply(shapely.geometry.Point) geodf = geopandas.GeoDataFrame(crime_data, geometry='Location') geodf.crs = {'init': 'espg:4326'} #Memory performance hack ls = [] step = 4000 num_steps = geodf.shape[0] % step - 2 counter = 0 while num_steps > 0: if (counter + 1) * step > geodf.shape[0]: break ls.append(geopandas.sjoin(geodf[step*counter:(counter+1)*step], df, how='left', op='within')) counter = counter + 1 num_steps = num_steps - 1 return pd.concat(ls)
[ "langowski@cs.uchicago.edu" ]
langowski@cs.uchicago.edu
4e72b71582b2240f32ecf38474428072ef1b7413
9e7b9e91b8425061a5ad36e0dd630a799ec79f6f
/opencv_cookbook.py
49d0d5b8c67cdd2753d61353ec3e42ef9014ce83
[]
no_license
OlgaBelitskaya/colab_notebooks
c27fad60f7e4ca35287e2561487b5d9d82efde43
d568149c8bcfb0025f7b09120ca44f639ac40efe
refs/heads/master
2023-07-07T23:02:49.289280
2021-08-14T08:16:38
2021-08-14T08:16:38
158,067,383
1
1
null
null
null
null
UTF-8
Python
false
false
8,397
py
# -*- coding: utf-8 -*- """opencv_cookbook.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1GD7Oi1LtFaEi8VOjiBM5cj5ayWpaejaf # OpenCV Cookbook ## Libraries & Color Tools """ import warnings; warnings.filterwarnings('ignore') import urllib,cv2 from skimage import io,transform import numpy as np,pylab as pl import seaborn as sb,scipy as sp fpath='https://olgabelitskaya.github.io/' pl.style.use('seaborn-whitegrid') pl.rcParams['figure.figsize']=(7,7) ColorFlags=[flag for flag in dir(cv2) if flag.startswith('COLOR')] print (np.array(ColorFlags[:30])) def get_image(original,flag,fpath=fpath): input_file=urllib.request.urlopen(fpath+original) output_file=open(original,'wb'); output_file.write(input_file.read()) output_file.close(); input_file.close() img=cv2.imread(original) return cv2.cvtColor(img,flag) """## Data""" plist=[get_image('pattern0%s.jpeg'%(i+1),flag=cv2.COLOR_BGR2RGB) for i in range(7)] flower_img=get_image('flower.png',flag=cv2.COLOR_BGR2RGB) cat_img=get_image('cat.png',flag=cv2.COLOR_BGR2RGB) img=plist[2] st='Image parameters: size - %s; shape - %s; type - %s' print (st%(img.size,img.shape,img.dtype)) pl.imshow(img); pl.show() """## Simple Manipulations""" img_inv=cv2.bitwise_not(img) pl.imshow(img_inv); pl.show() img_w2b=img.copy() img_w2b[np.where((img_w2b==[255,255,255]).all(axis=2))]=[0,0,0] pl.imshow(img_w2b); pl.show() pl.rcParams['figure.figsize']=(14,7) pl.figure(1); pl.subplot(121) img_gray1=cv2.cvtColor(img,cv2.COLOR_RGB2GRAY) pl.imshow(img_gray1) pl.subplot(122) img_gray2=cv2.cvtColor(img_w2b,cv2.COLOR_RGB2GRAY) pl.imshow(img_gray2); pl.show() pl.rcParams['figure.figsize']=(8,8); N=50 # skimage & opencv - grayscale, resize, invert img_skgray=io.imread('pattern03.jpeg',as_gray=True) img_skgray_resized=transform.resize(img_skgray,(N,N)) img_skgray_resized2=cv2.bitwise_not(img_skgray_resized) img_cvgray_resized=cv2.resize(img_gray1,(N,N), interpolation=cv2.INTER_CUBIC) img_cvgray_resized2=cv2.bitwise_not(img_cvgray_resized) pl.figure(1); pl.subplot(221) pl.imshow(img_skgray_resized,cmap=pl.cm.Greys) pl.subplot(222) pl.imshow(img_skgray_resized2) pl.subplot(223) pl.imshow(img_cvgray_resized,cmap=pl.cm.Greys) pl.subplot(224) pl.imshow(img_cvgray_resized); pl.show() pl.rcParams['figure.figsize']=(8,8) # split color channels img0=plist[0]; b,g,r=cv2.split(img0) # merge channels img_merged=cv2.merge([b,g,r]) # display one of the channels pl.figure(1); pl.subplot(231); pl.imshow(r,cmap=pl.cm.Reds_r) pl.subplot(232); pl.imshow(g,cmap=pl.cm.Greens_r) pl.subplot(233); pl.imshow(b,cmap=pl.cm.Blues_r) # display merged image pl.subplot(234); pl.imshow(img_merged); pl.show() hsv_img=cv2.cvtColor(img0,cv2.COLOR_RGB2HSV_FULL) lab_img=cv2.cvtColor(img0,cv2.COLOR_RGB2LAB) pl.figure(1); pl.subplot(121); pl.imshow(hsv_img) pl.subplot(122); pl.imshow(lab_img); pl.show() pl.rcParams['figure.figsize']=(12,4) # flip images img_vertical_flipped=cv2.flip(img,0) img_horizontal_flipped=cv2.flip(img,1) img_transposed=cv2.transpose(img) pl.figure(1); pl.subplot(131); pl.imshow(img_vertical_flipped) pl.subplot(132); pl.imshow(img_horizontal_flipped) pl.subplot(133); pl.imshow(img_transposed); pl.show() """## Advanced Transformations""" # repeat the fragment img_twice=img.copy() img_fragment=img_twice[15:60,15:60] img_twice[105:105+img_fragment.shape[0],105:105+\ img_fragment.shape[1]]=img_fragment pl.imshow(img_twice); pl.show() pl.rcParams['figure.figsize']=(8,4) # perspective transformation rows,cols,ch=img.shape pts1=np.float32([[10,10],[140,40],[10,140],[140,100]]) pts2=np.float32([[0,0],[150,0],[0,150],[150,150]]) m=cv2.getPerspectiveTransform(pts1,pts2) dst=cv2.warpPerspective(img,m,(150,150)) pl.subplot(121),pl.imshow(img),pl.title('Input') pl.scatter(pts1[:,0],pts1[:,1],c='g') pl.subplot(122),pl.imshow(dst),pl.title('Output') pl.xlim(-5,155); pl.ylim(155,-5) pl.scatter(pts2[:,0],pts2[:,1],c='g'); pl.show() pl.rcParams['figure.figsize']=(16,8) # gradient filters img2=img0.copy() img2_gray=cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) laplacian=cv2.Laplacian(img2_gray,cv2.CV_64F,ksize=5) sobel=cv2.Sobel(img2_gray,cv2.CV_64F,1,0,ksize=3) scharr=cv2.Scharr(img2_gray,cv2.CV_64F,1,0) pl.subplot(1,4,1),pl.imshow(img2) pl.title('Original'),pl.xticks([]),pl.yticks([]) pl.subplot(1,4,2),pl.imshow(laplacian,cmap=pl.cm.bone) pl.title('Laplacian'),pl.xticks([]),pl.yticks([]) pl.subplot(1,4,3),pl.imshow(sobel,cmap=pl.cm.bone) pl.title('Sobel'),pl.xticks([]),pl.yticks([]) pl.subplot(1,4,4),pl.imshow(scharr,cmap=pl.cm.bone) pl.title('Scharr'),pl.xticks([]),pl.yticks([]); pl.show() pl.rcParams['figure.figsize']=(12,12) # erosion kernel=np.ones((3,3),np.uint8) erosion=cv2.erode(img_gray1,kernel,iterations=1) pl.subplot(2,2,1),pl.imshow(img_gray1) pl.title('Original Gray'),pl.xticks([]),pl.yticks([]) pl.subplot(2,2,2),pl.imshow(erosion,cmap=pl.cm.bone) pl.title('Erosion'),pl.xticks([]),pl.yticks([]) img_gray1_inv=cv2.bitwise_not(img_gray1) erosion_inv=cv2.erode(img_gray1_inv,kernel,iterations=1) pl.subplot(2,2,3),pl.imshow(img_gray1_inv) pl.title('Inverted Gray'),pl.xticks([]),pl.yticks([]) pl.subplot(2,2,4),pl.imshow(erosion_inv,cmap=pl.cm.bone) pl.title('Erosion for Inverted') pl.xticks([]),pl.yticks([]); pl.show() # morphological gradient gradient=cv2.morphologyEx(img,cv2.MORPH_GRADIENT,kernel) pl.subplot(1,2,1),pl.imshow(img) pl.title('Original Gray'),pl.xticks([]),pl.yticks([]) pl.subplot(1,2,2),pl.imshow(gradient,cmap=pl.cm.bone) pl.title('Morphological Gradient') pl.xticks([]),pl.yticks([]); pl.show() """## Edges' Detection""" pl.rcParams['figure.figsize']=(12,6) img_gray0=cv2.cvtColor(img0,cv2.COLOR_RGB2GRAY) edge_img=img.copy(); edge_img0=img0.copy() edge=cv2.Canny(img_gray1,90,240) edge_img[edge!=0]=(0,255,0) edge0=cv2.Canny(img_gray0,90,240) edge_img0[edge0!=0]=(0,255,0) pl.figure(1); pl.subplot(121); pl.imshow(edge_img) pl.subplot(122); pl.imshow(edge_img0); pl.show() """## Key Points""" pl.rcParams['figure.figsize']=(16,6) orb_img=flower_img.copy() orb=cv2.ORB_create() keypoints=orb.detect(orb_img,None) keypoints,descriptors=orb.compute(orb_img,keypoints) cv2.drawKeypoints(orb_img,keypoints,orb_img) match_img=np.zeros(flower_img.shape,np.uint8) center_img=flower_img[60:140,90:180] match_img[60:140,100:180]=[0,0,0] center_img=cv2.flip(center_img,0) match_img[100:100+center_img.shape[0], 150:150+center_img.shape[1]]=center_img pl.figure(1); pl.subplot(121); pl.imshow(orb_img) pl.subplot(122); pl.imshow(match_img); pl.show() pl.rcParams['figure.figsize']=(16,6) match_keypoints=orb.detect(match_img,None) match_keypoints,match_descriptors=\ orb.compute(match_img,match_keypoints) brute_force=cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck=True) matches=brute_force.match(descriptors,match_descriptors) matches=sorted(matches,key=lambda x:x.distance) draw_matches=cv2.drawMatches(orb_img,keypoints, match_img,match_keypoints, matches[:9],orb_img) pl.imshow(draw_matches); pl.show() """## Object Detection""" pl.rcParams['figure.figsize']=(8,8) url='haarcascade_frontalcatface.xml' input_file=urllib.request.urlopen(fpath+url) output_file=open(url,'wb') output_file.write(input_file.read()) output_file.close(); input_file.close() gray_cat_img=cv2.cvtColor(cat_img,cv2.COLOR_RGB2GRAY) catface_img=cat_img.copy() catface_cascade=cv2.CascadeClassifier(url) catfaces=catface_cascade.detectMultiScale(gray_cat_img,1.095,6) for (x,y,w,h) in catfaces: cv2.rectangle(catface_img,(x,y),(x+w,y+h),(0,255,0),3) pl.figure(1); pl.subplot(121); pl.imshow(cat_img) pl.subplot(122); pl.imshow(catface_img); pl.show() pl.rcParams['figure.figsize']=(12,12) sport_img=get_image('sport.jpg',flag=cv2.COLOR_BGR2RGB) gray_sport_img=cv2.cvtColor(sport_img,cv2.COLOR_RGB2GRAY) face_img=sport_img.copy() url='haarcascade_frontalface_default.xml' input_file=urllib.request.urlopen(fpath+url) output_file=open(url,'wb') output_file.write(input_file.read()) output_file.close(); input_file.close() face_cascade=cv2.CascadeClassifier(url) faces=face_cascade.detectMultiScale(gray_sport_img,1.095,4) for (x,y,w,h) in faces: cv2.rectangle(face_img,(x,y),(x+w,y+h),(0,255,0),3) pl.figure(1); pl.subplot(211); pl.imshow(sport_img) pl.subplot(212); pl.imshow(face_img); pl.show()
[ "safuolga@gmail.com" ]
safuolga@gmail.com
88ea9f503fbe4878090275c2480106a7648b48f2
f94e4955f9d16b61b7c9bff130b9d9ee43436bea
/labs/lab06/lab06.py
1c1dac20000f742c21337b538d3d8ac3b9563bc4
[]
no_license
j2chu/dsc80-sp19
bd1dade66c19b920a54b0f8551fd999185449f86
dd48210a7cbadfb6470104b275f34085437e4766
refs/heads/master
2020-06-01T23:22:32.727488
2019-06-07T01:46:11
2019-06-07T01:46:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,275
py
import os import pandas as pd import numpy as np import requests import bs4 import json # --------------------------------------------------------------------- # Question # 1 # --------------------------------------------------------------------- def question1(): """ NOTE: You do NOT need to do anything with this function. The function for this question makes sure you have a correctly named HTML file in the right place. Note: This does NOT check if the supplementary files needed for your page are there! >>> os.path.exists('lab06_1.html') True """ # Don't change this function body! # No python required; create the HTML file. return # --------------------------------------------------------------------- # Question # 2 # --------------------------------------------------------------------- def extract_book_links(text): """ :Example: >>> fp = os.path.join('data', 'products.html') >>> out = extract_book_links(open(fp, encoding='utf-8').read()) >>> url = 'scarlet-the-lunar-chronicles-2_218/index.html' >>> out[0] == url True """ return ... def get_product_info(text): """ :Example: >>> fp = os.path.join('data', 'Frankenstein.html') >>> out = get_product_info(open(fp, encoding='utf-8').read()) >>> isinstance(out, dict) True >>> 'UPC' in out.keys() True >>> out['Rating'] 'Two' """ return ... def scrape_books(k): """ :param k: number of book-listing pages to scrape. :returns: a dataframe of information on (certain) books on the k pages (as described in the question). :Example: >>> out = scrape_books(1) >>> out.shape (1, 10) >>> out['Rating'][0] == 'Five' True >>> out['UPC'][0] == 'ce6396b0f23f6ecc' True """ return ... # --------------------------------------------------------------------- # Question 3 # --------------------------------------------------------------------- def send_requests(apiKey, *args): """ :param apiKey: apiKey from newsapi website :param args: number of languages as strings :return: a list of dictionaries, where keys correspond to languages and values correspond to Response objects >>> responses = send_requests(os.environ['API_KEY'], "ru", "fr") >>> isinstance(responses[0], dict) True >>> isinstance(responses[1], dict) True """ return ... def gather_info(resp): """ Finds some basic information from the obtained responses :param resp: a list of dictionaries :return: a list with the following items: language that has the most number of news most common base url for every language >>> responses = send_requests(os.environ['API_KEY'], "ru", "fr") >>> result = gather_info(responses) >>> isinstance(result[0], str) True >>> len(result) == len(responses) + 1 True """ return ... # --------------------------------------------------------------------- # Question # 4 # --------------------------------------------------------------------- def depth(comments): """ :Example: >>> fp = os.path.join('data', 'comments.csv') >>> comments = pd.read_csv(fp, sep='|') >>> depth(comments).max() == 5 True """ return ... # --------------------------------------------------------------------- # DO NOT TOUCH BELOW THIS LINE # IT'S FOR YOUR OWN BENEFIT! # --------------------------------------------------------------------- # Graded functions names! DO NOT CHANGE! # This dictionary provides your doctests with # a check that all of the questions being graded # exist in your code! GRADED_FUNCTIONS = { 'q01': ['question1'], 'q02': ['extract_book_links', 'get_product_info', 'scrape_books'], 'q03': ['send_requests', 'gather_info'], 'q04': ['depth'] } def check_for_graded_elements(): """ >>> check_for_graded_elements() True """ for q, elts in GRADED_FUNCTIONS.items(): for elt in elts: if elt not in globals(): stmt = "YOU CHANGED A QUESTION THAT SHOULDN'T CHANGE! \ In %s, part %s is missing" % (q, elt) raise Exception(stmt) return True
[ "aaron.fraenkel@gmail.com" ]
aaron.fraenkel@gmail.com
24966601f3f870f304dc6d67df48fa497d89c512
46d04bd3a1f8d53b147133b4b7a8c0c4fa58d9cd
/app/views.py
2b2d2323ce93f7cddcf6e68625ba576e2bd2e6e0
[]
no_license
RitikaSethiya/TB-strategic-planning-Web-App
f2c63d97413d1c384b591948cf812ac8dcf071c1
be1b9b3f5d510696cd8a76160426977032d27ed1
refs/heads/master
2022-08-13T19:10:01.334557
2020-05-11T11:59:40
2020-05-11T11:59:40
263,017,987
2
0
null
null
null
null
UTF-8
Python
false
false
28,346
py
# -*- encoding: utf-8 -*- """ License: MIT Copyright (c) 2019 - present AppSeed.us """ # Python modules import os, logging import pandas as pd import numpy as np import requests import base64 import pickle import json import tablib # Flask modules from flask import render_template, request, url_for, redirect, send_from_directory from flask_login import login_user, logout_user, current_user, login_required from werkzeug.exceptions import HTTPException, NotFound, abort from flask import jsonify # App modules from app import app, lm, db, bc from app.models import User from app.forms import LoginForm, RegisterForm # dataset = tablib.Dataset() # with open(os.path.join(os.path.dirname(__file__),'rotated_prediction.csv')) as f: # dataset.csv = f.read() @app.route("/table.html") def table(): data = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\rotated_prediction.csv") # data = "/dataset.html" #return dataset.html return render_template('pages/table.html', dataa=data) #provide login manager with load_user callback @lm.user_loader def load_user(user_id): return User.query.get(int(user_id)) # Logout user @app.route('/logout.html') def logout(): logout_user() return redirect(url_for('index')) # Register a new user @app.route('/register.html', methods=['GET', 'POST']) def register(): # declare the Registration Form form = RegisterForm(request.form) msg = None if request.method == 'GET': return render_template( 'pages/register.html', form=form, msg=msg ) # check if both http method is POST and form is valid on submit if form.validate_on_submit(): # assign form data to variables username = request.form.get('username', '', type=str) password = request.form.get('password', '', type=str) email = request.form.get('email' , '', type=str) # filter User out of database through username user = User.query.filter_by(user=username).first() # filter User out of database through username user_by_email = User.query.filter_by(email=email).first() if user or user_by_email: msg = 'Error: User exists!' else: pw_hash = password #bc.generate_password_hash(password) user = User(username, email, pw_hash) user.save() msg = 'User created, please <a href="' + url_for('login') + '">login</a>' else: msg = 'Input error' return render_template( 'pages/register.html', form=form, msg=msg ) # Authenticate user @app.route('/login.html', methods=['GET', 'POST']) def login(): # Declare the login form form = LoginForm(request.form) # Flask message injected into the page, in case of any errors msg = None # check if both http method is POST and form is valid on submit if form.validate_on_submit(): # assign form data to variables username = request.form.get('username', '', type=str) password = request.form.get('password', '', type=str) # filter User out of database through username user = User.query.filter_by(user=username).first() if user: #if bc.check_password_hash(user.password, password): if user.password == password: login_user(user) return redirect(url_for('index')) else: msg = "Wrong password. Please try again." else: msg = "Unknown user" return render_template( 'pages/login.html', form=form, msg=msg ) # App main route + generic routing @app.route('/', defaults={'path': 'index.html'}) @app.route('/<path>') def index(path): if not current_user.is_authenticated: return redirect(url_for('login')) content = None try: # @WIP to fix this # Temporary solution to solve the dependencies if path.endswith(('.png', '.svg' '.ttf', '.xml', '.ico', '.woff', '.woff2')): return send_from_directory(os.path.join(app.root_path, 'static'), path) # try to match the pages defined in -> pages/<input file> return render_template( 'pages/'+path ) except: return render_template('layouts/auth-default.html', content=render_template( 'pages/404.html' ) ) @app.route('/charts', methods=['GET']) def map(): district = request.args.get('name') df = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\tb_full.csv") xold=df[df["Location"]==district] x_axis = xold['Year'] y_axis= xold['total_cases'] name=df['Location'].unique() rate=y_axis.pct_change() rate=round(rate.fillna(value=0),4) rate=rate.replace(np.inf, 0) line_labelsold=round(x_axis,2) line_valuesold=round(y_axis,2) smear=xold["smear"] data_points_0 = zip(line_labelsold,line_valuesold,smear,rate) df1=pd.concat([x_axis,rate],axis=1) df1.columns=['Year','Total Cases Spread rate'] df1.reset_index(drop=True, inplace=True) path=r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\templates\pages\\"+district+".csv" df1.to_csv(path) return render_template('pages/charts.html', title=district,my_list=data_points_0) @app.route('/graphs', methods=['GET','POST']) def value(): district = request.args.get('name') if request.method == 'POST': so = request.form.get('so') no = request.form.get('no') rspmm = request.form.get('rspm') rainfall = request.form.get('rainfall') temperature = request.form.get('temperature') humidity = request.form.get('humidity') loc=district no2=no so2=so rspm=rspmm print(loc,no2,so2,rspm,rainfall,temperature,humidity) data={'loc':loc,'rspm':int(rspm),'no2':int(no2),'so2':int(so2),'rainfall':int(rainfall),'temperature':int(temperature),'humidity':int(humidity)} response = requests.post('https://beprojectdm.pythonanywhere.com/dm',data=json.dumps(data)).json() df1=pickle.loads(base64.b64decode(response['prediction'].encode())) df2=pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\tb_yearly.csv") dff=df2.append(df1) dff.to_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\prediction2.csv") x=dff[dff["Location"]==loc] x_axis = x['Year'] y_axis= x['total_cases'] smearnew=x["smear"] ratenew=y_axis.pct_change() ratenew=round(ratenew.fillna(value=0),4) ratenew=ratenew.replace(np.inf, 0) name=dff['Location'].unique() line_labelsnew=round(x_axis,2) line_valuesnew=round(y_axis,2) data_points_1 = zip(line_labelsnew,line_valuesnew,smearnew,ratenew) df3=pd.concat([x_axis,ratenew],axis=1) df3.columns=['Year','Total Cases Spread rate'] df3.reset_index(drop=True, inplace=True) path=r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\templates\pages\\"+district+"_retrain.csv" df3.to_csv(path) # df1 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\predicted.csv") df = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\tb_full.csv") xold=df[df["Location"]==district] x_axis = xold['Year'] y_axis= xold['total_cases'] rateold=y_axis.pct_change() rateold=round(rateold.fillna(value=0),4) rateold=rateold.replace(np.inf, 0) name=df['Location'].unique() line_labelsold=round(x_axis,2) line_valuesold=round(y_axis,2) smearold=xold["smear"] data_points_0 = zip(line_labelsold,line_valuesold,smearold,rateold) return render_template('pages/graphs.html', title=district,my_list=data_points_0,my_list_1=data_points_1,rainfall=rainfall,temperature=temperature,humidity=humidity) @app.route('/triple', methods=['POST']) def triple(): district = request.args.get('name') if request.method == 'POST': so = request.values.get('so') no = request.values.get('no') rspmm = request.values.get('rspm') rainfall = request.values.get('rainfall') temperature = request.values.get('temperature') humidity = request.values.get('humidity') loc=district no2=no so2=so rspm=rspmm data={'loc':loc,'rspm':int(rspm),'no2':int(no2),'so2':int(so2),'rainfall':int(rainfall),'temperature':int(temperature),'humidity':int(humidity)} response = requests.post('https://beprojectdm.pythonanywhere.com/dm',data=json.dumps(data)).json() df1=pickle.loads(base64.b64decode(response['prediction'].encode())) df2=pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\tb_yearly.csv") dff=df2.append(df1) x=dff[dff["Location"]==loc] x_axis = x['Year'] y_axis= x['total_cases'] smearnew=x["smear"] ratenew=y_axis.pct_change() ratenew=round(ratenew.fillna(value=0),4) ratenew=ratenew.replace(np.inf, 0) name=dff['Location'].unique() line_labelsnew=round(x_axis,2) line_valuesnew=round(y_axis,2) data_points_2 = zip(line_labelsnew,line_valuesnew,smearnew,ratenew) df3=pd.concat([x_axis,ratenew],axis=1) df3.columns=['Year','Total Cases Spread rate'] df3.reset_index(drop=True, inplace=True) path=r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\templates\pages\\"+district+"_retrain.csv" df3.to_csv(path) # df1 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\predicted.csv") df = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\tb_full.csv") xold=df[df["Location"]==district] x_axis = xold['Year'] y_axis= xold['total_cases'] rateold=y_axis.pct_change() rateold=round(rateold.fillna(value=0),4) rateold=rateold.replace(np.inf, 0) name=df['Location'].unique() line_labelsold=round(x_axis,2) line_valuesold=round(y_axis,2) smearold=xold["smear"] data_points_0 = zip(line_labelsold,line_valuesold,smearold,rateold) dff=pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\prediction2.csv") x=dff[dff["Location"]==loc] x_axis = x['Year'] y_axis= x['total_cases'] smearneww=x["smear"] rateneww=y_axis.pct_change() rateneww=round(rateneww.fillna(value=0),4) rateneww=rateneww.replace(np.inf, 0) name=dff['Location'].unique() line_labelsneww=round(x_axis,2) line_valuesneww=round(y_axis,2) data_points_1 = zip(line_labelsneww,line_valuesneww,smearneww,rateneww) return render_template('pages/triple.html', title=district,my_list=data_points_0,my_list_1=data_points_1,my_list_2=data_points_2) @app.route('/bar', methods=['GET']) def bar(): df = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\india_all_sum.csv") x_axis = df['Year'] y_axis= df['total_cases'] z_axis= df['smear'] data_points = zip(x_axis,y_axis) data_points_smear = zip(x_axis,z_axis) #,smear,ratey,ratez return render_template('pages/bar.html', list=list(data_points),lists=list(data_points_smear)) @app.route('/india_line', methods=['GET']) def line(): df = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\india_all_sum.csv") x_axis = df['Year'] y_axis= df['total_cases'] rate=y_axis.pct_change() rate=round(rate.fillna(value=0),4) line_labelsold=round(x_axis,2) line_valuesold=round(y_axis,2) smear=round(df["smear"],2) data_points_0 = zip(line_labelsold,line_valuesold,smear,rate) return render_template('pages/india_linechart.html',my_list=data_points_0) @app.route('/stats.html', methods=['GET']) def stats(): df1 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_totalcases.csv") df2 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_smearpositivecases.csv") df3 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_totalcases.csv") df4 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_smearpositivecases.csv") gbr_1=df3['gbr'] gbr_2=df1['gbr'] gbr_3=df4['gbr'] gbr_4=df2['gbr'] #,smear,ratey,ratez return render_template('pages/stats.html',train_total=gbr_1,test_total=gbr_2,train_smear=gbr_3,test_smear=gbr_4 ) @app.route('/model2.html', methods=['GET']) def model2(): df1 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_totalcases.csv") df2 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_smearpositivecases.csv") df3 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_totalcases.csv") df4 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_smearpositivecases.csv") rfr_1=df3['rfr'] rfr_2=df1['rfr'] rfr_3=df4['rfr'] rfr_4=df2['rfr'] #,smear,ratey,ratez return render_template('pages/model2.html',train_total=rfr_1,test_total=rfr_2,train_smear=rfr_3,test_smear=rfr_4 ) @app.route('/model3.html', methods=['GET']) def model3(): df1 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_totalcases.csv") df2 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_smearpositivecases.csv") df3 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_totalcases.csv") df4 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_smearpositivecases.csv") dtr_1=df3['dtr'] dtr_2=df1['dtr'] dtr_3=df4['dtr'] dtr_4=df2['dtr'] #,smear,ratey,ratez return render_template('pages/model3.html',train_total=dtr_1,test_total=dtr_2,train_smear=dtr_3,test_smear=dtr_4 ) @app.route('/model4.html', methods=['GET']) def model4(): df1 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_totalcases.csv") df2 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_smearpositivecases.csv") df3 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_totalcases.csv") df4 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_smearpositivecases.csv") xgbr_1=df3['xgbr'] xgbr_2=df1['xgbr'] xgbr_3=df4['xgbr'] xgbr_4=df2['xgbr'] #,smear,ratey,ratez return render_template('pages/model4.html',train_total=xgbr_1,test_total=xgbr_2,train_smear=xgbr_3,test_smear=xgbr_4 ) @app.route('/model5.html', methods=['GET']) def model5(): df1 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_totalcases.csv") df2 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_test_smearpositivecases.csv") df3 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_totalcases.csv") df4 = pd.read_csv(r"C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\plot_train_smearpositivecases.csv") nn_1=df3['nn'] nn_2=df1['nn'] nn_3=df4['nn'] nn_4=df2['nn'] #,smear,ratey,ratez return render_template('pages/model5.html',train_total=nn_1,test_total=nn_2,train_smear=nn_3,test_smear=nn_4 ) @app.route('/correlation.html', methods=['POST']) def corr1(): if request.method =='POST': if request.args.get('list')!=None: value=request.args.get('value_change') col_head=request.args.get('id') selected_list=request.args.get('list') print('value',value,'col_head',col_head,'selected_list',selected_list) df=pd.read_csv(r'C:/Users/Ritika/AppData/Local/Programs/Python/Python37/DMWebapp/app/combinations.csv') df=df.iloc[:,[0,1,2,3,4,5,6,7]] if(col_head=='year' or col_head=='quarter'): value=int(value) df1=df[df[col_head]==value] rspmmm=df1['rspm'].unique().tolist() nooo2=df1['no2'].unique().tolist() sooo2=df1['so2'].unique().tolist() rainfallll=df1['rainfall'].unique().tolist() humidityyy=df1['humidity'].unique().tolist() temperaturee=df1['temperature'].unique().tolist() yearrr=df1['year'].unique().tolist() quarterrr=df1['quarter'].unique().tolist() yearrr.sort() quarterrr.sort() print(rspmmm) # return render_template('pages/correlation.html',rspmmm=rspmmm,nooo2=nooo2,sooo2=sooo2,rainfallll=rainfallll,humidityyy=humidityyy,temperaturee=temperaturee,yearrr=yearrr,quarterrr=quarterrr,selected_list=selected_list) final_list={'rspm':rspmmm,'no2':nooo2,'so2':sooo2,'rainfall':rainfallll,'humidity':humidityyy,'temperature':temperaturee,'year':yearrr,'quarter':quarterrr,'selected_list':selected_list} return jsonify(final_list) elif request.values.get('rspm')!=None: print("hello") rspm = request.values.get('rspm') no2 = request.values.get('no2') so2 = request.values.get('so2') year = request.values.get('year') rainfall = request.values.get('rainfall') temperature = request.values.get('temperature') humidity = request.values.get('humidity') quarter = request.values.get('quarter') year=int(year) quarter=int(quarter) print(rspm,so2,no2,year,rainfall,temperature,humidity,quarter) df=pd.read_csv(r'C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\correlation.csv') df.columns=['Location','Year','Quarter','totalcases','smearpositivecases','rainfall','humidity','temperature','so2','no2','rspm'] table=[] table.append(['rainfall_low','x','750']) table.append(['rainfall_moderate','751','2350']) table.append(['rainfall_high','2351','x']) table.append(['temperature_low','x','20']) table.append(['temperature_moderate','21','30']) table.append(['temperature_high','31','x']) table.append(['humidity_low','x','50']) table.append(['humidity_high','51','x']) table.append(['rspm_good','x','50']) table.append(['rspm_satisfactory','51','100']) table.append(['rspm_moderate','101','200']) table.append(['rspm_poor','201','300']) table.append(['rspm_severe','301','x']) table.append(['no2_safe','x','25']) table.append(['no2_potential','26','50']) table.append(['no2_curtailing','51','100']) table.append(['no2_hazardous','101','x']) table.append(['so2_safe','x','25']) table.append(['so2_potential','26','50']) table.append(['so2_curtailing','51','100']) ranges=pd.DataFrame(table,columns=['category','low','high']) try: df1=df[df['Year']==year] df2=df1[df1['Quarter']==quarter] rspm1=ranges[ranges['category']==rspm].iloc[0,:] if(str(rspm1['low'])=='x'): df3=df2[df2['rspm']<=int(rspm1['high'])] elif(str(rspm1['high'])=='x'): df3=df2[df2['rspm']>=int(rspm1['low'])] else: df3=df2[df2['rspm'].between(int(rspm1['low']),int(rspm1['high']),inclusive=True)] # In[71]: so21=ranges[ranges['category']==so2].iloc[0,:] if(str(so21['low'])=='x'): df4=df3[df3['so2']<=int(so21['high'])] elif(str(so21['high'])=='x'): df4=df3[df3['so2']>=int(so21['low'])] else: df4=df3[df3['so2'].between(int(so21['low']),int(so21['high']),inclusive=True)] # In[72]: no21=ranges[ranges['category']==no2].iloc[0,:] if(str(no21['low'])=='x'): df5=df4[df4['no2']<=int(no21['high'])] elif(str(no21['high'])=='x'): df5=df4[df4['no2']>=int(no21['low'])] else: df5=df4[df4['no2'].between(int(no21['low']),int(no21['high']),inclusive=True)] # In[73]: humidity1=ranges[ranges['category']==humidity].iloc[0,:] if(str(humidity1['low'])=='x'): df6=df5[df5['humidity']<=int(humidity1['high'])] elif(str(humidity1['high'])=='x'): df6=df5[df5['humidity']>=int(humidity1['low'])] else: df6=df5[df5['humidity'].between(int(humidity1['low']),int(humidity1['high']),inclusive=True)] # In[74]: rainfall1=ranges[ranges['category']==rainfall].iloc[0,:] if(str(rainfall1['low'])=='x'): df7=df6[df6['rainfall']<=int(rainfall1['high'])] elif(str(rainfall1['high'])=='x'): df7=df6[df6['rainfall']>=int(rainfall1['low'])] else: df7=df6[df6['rainfall'].between(int(rainfall1['low']),int(rainfall1['high']),inclusive=True)] # In[75]: temperature1=ranges[ranges['category']==temperature].iloc[0,:] if(str(temperature1['low'])=='x'): df8=df7[df7['temperature']<=int(temperature1['high'])] elif(str(temperature1['high'])=='x'): df8=df7[df7['temperature']>=int(temperature1['low'])] else: df8=df7[df7['temperature'].between(int(temperature1['low']),int(temperature1['high']),inclusive=True)] df9=df8.iloc[:,[0,3,4]] l=[x for x in df9["Location"]] print(l) if not l: l=['-1'] return render_template('pages/correlation.html',list1=l,year=year,quarter=quarter,rainfall=rainfall,temperature=temperature,humidity=humidity,rspm=rspm,so2=so2,no2=no2) except: return ['-1'] # return Error return render_template('pages/correlation.html') # @app.route('/correlation', methods=['POST']) # def corr2(): # if request.method == 'POST' and # return render_template('pages/correlation.html') @app.route('/pie', methods=['GET']) def pie(): year=request.args.get('year') quarter=request.args.get('quarter') rspm=request.args.get('rspm') so2=request.args.get('so2') no2=request.args.get('no2') rainfall=request.args.get('rainfall') temperature=request.args.get('temperature') humidity=request.args.get('humidity') year=int(year) quarter=int(quarter) print(rspm,so2,no2,year,rainfall,temperature,humidity,quarter) df=pd.read_csv(r'C:\Users\Ritika\AppData\Local\Programs\Python\Python37\DMWebapp\app\correlation.csv') df.columns=['Location','Year','Quarter','totalcases','smearpositivecases','rainfall','humidity','temperature','so2','no2','rspm'] table=[] table.append(['rainfall_low','x','750']) table.append(['rainfall_moderate','751','2350']) table.append(['rainfall_high','2351','x']) table.append(['temperature_low','x','20']) table.append(['temperature_moderate','21','30']) table.append(['temperature_high','31','x']) table.append(['humidity_low','x','50']) table.append(['humidity_high','51','x']) table.append(['rspm_good','x','50']) table.append(['rspm_satisfactory','51','100']) table.append(['rspm_moderate','101','200']) table.append(['rspm_poor','201','300']) table.append(['rspm_severe','301','x']) table.append(['no2_safe','x','25']) table.append(['no2_potential','26','50']) table.append(['no2_curtailing','51','100']) table.append(['no2_hazardous','101','x']) table.append(['so2_safe','x','25']) table.append(['so2_potential','26','50']) table.append(['so2_curtailing','51','100']) ranges=pd.DataFrame(table,columns=['category','low','high']) df1=df[df['Year']==year] df2=df1[df1['Quarter']==quarter] rspm1=ranges[ranges['category']==rspm].iloc[0,:] if(str(rspm1['low'])=='x'): df3=df2[df2['rspm']<=int(rspm1['high'])] elif(str(rspm1['high'])=='x'): df3=df2[df2['rspm']>=int(rspm1['low'])] else: df3=df2[df2['rspm'].between(int(rspm1['low']),int(rspm1['high']),inclusive=True)] # In[71]: so21=ranges[ranges['category']==so2].iloc[0,:] if(str(so21['low'])=='x'): df4=df3[df3['so2']<=int(so21['high'])] elif(str(so21['high'])=='x'): df4=df3[df3['so2']>=int(so21['low'])] else: df4=df3[df3['so2'].between(int(so21['low']),int(so21['high']),inclusive=True)] # In[72]: no21=ranges[ranges['category']==no2].iloc[0,:] if(str(no21['low'])=='x'): df5=df4[df4['no2']<=int(no21['high'])] elif(str(no21['high'])=='x'): df5=df4[df4['no2']>=int(no21['low'])] else: df5=df4[df4['no2'].between(int(no21['low']),int(no21['high']),inclusive=True)] # In[73]: humidity1=ranges[ranges['category']==humidity].iloc[0,:] if(str(humidity1['low'])=='x'): df6=df5[df5['humidity']<=int(humidity1['high'])] elif(str(humidity1['high'])=='x'): df6=df5[df5['humidity']>=int(humidity1['low'])] else: df6=df5[df5['humidity'].between(int(humidity1['low']),int(humidity1['high']),inclusive=True)] # In[74]: rainfall1=ranges[ranges['category']==rainfall].iloc[0,:] if(str(rainfall1['low'])=='x'): df7=df6[df6['rainfall']<=int(rainfall1['high'])] elif(str(rainfall1['high'])=='x'): df7=df6[df6['rainfall']>=int(rainfall1['low'])] else: df7=df6[df6['rainfall'].between(int(rainfall1['low']),int(rainfall1['high']),inclusive=True)] # In[75]: temperature1=ranges[ranges['category']==temperature].iloc[0,:] if(str(temperature1['low'])=='x'): df8=df7[df7['temperature']<=int(temperature1['high'])] elif(str(temperature1['high'])=='x'): df8=df7[df7['temperature']>=int(temperature1['low'])] else: df8=df7[df7['temperature'].between(int(temperature1['low']),int(temperature1['high']),inclusive=True)] dfff=df8.iloc[:,[0,3,4]] dft=[x for x in dfff["totalcases"]] dfl=[x for x in dfff["Location"]] dfs=[x for x in dfff["smearpositivecases"]] df9=list(zip(dft,dfl,dfs)) print(df9) return render_template('pages/pie.html',df=df9,rspm=rspm,so2=so2,no2=no2,rainfall=rainfall,temperature=temperature,humidity=humidity) @app.route('/pass_val', methods=['POST']) def pass_val(): value=request.args.get('value_change') col_head=request.args.get('id') selected_list=request.args.get('list') print('value',value,'col_head',col_head,'selected_list',selected_list) df=pd.read_csv(r'C:/Users/Ritika/AppData/Local/Programs/Python/Python37/DMWebapp/app/combinations.csv') df=df.iloc[:,[0,1,2,3,4,5,6,7]] if(col_head=='year' or col_head=='quarter'): value=int(value) df1=df[df[col_head]==value] rspmmm=df1['rspm'].unique().tolist() nooo2=df1['no2'].unique().tolist() sooo2=df1['so2'].unique().tolist() rainfallll=df1['rainfall'].unique().tolist() humidityyy=df1['humidity'].unique().tolist() temperaturee=df1['temperature'].unique().tolist() yearrr=df1['year'].unique().tolist() quarterrr=df1['quarter'].unique().tolist() yearrr.sort() quarterrr.sort() return jsonify({'reply':'success'})
[ "ritikasethiya99.rs@gmail.com" ]
ritikasethiya99.rs@gmail.com
5bec3ae23b68e6c2e0be46181e3e6e1f669fcd98
7518d339026e523ca99e77b7b49edfe71b7da5c5
/main.py
8b72a3d7569f8ca47bb5852ececdb44cac03e96b
[]
no_license
SP185221/FileAgent_Client
475c76ed2ab3a705b8643708f3e24f629661b57b
188d4d509c2d127afed8736d26b74805284e4b70
refs/heads/main
2023-07-25T08:03:22.780456
2021-09-02T16:18:01
2021-09-02T16:18:01
402,486,328
0
0
null
null
null
null
UTF-8
Python
false
false
6,751
py
import socket, tqdm from tkinter import* from threading import Thread from tkinter import filedialog import requests import wget, os from PIL import Image from time import sleep from zipfile import ZipFile #import pm_app_fxn as pm output1 = ['']*1 list_of_sent_files = [] class main_App(Thread): def __init__(self): Thread.__init__(self) def browse_button(self): filename = filedialog.askdirectory() #self.filename1[0]=filename #print(filename) temp = self.entry_path.get() #print(temp) self.entry_path.delete('0', 'end') self.entry_path.insert(0,filename) return filename def output(self, value): #value = sample_text.get(1.0, "end-1c") self.output_data.insert(END, value) def output_screen(self): #value = sample_text.get(1.0, "end-1c") value = output1[0] self.output(value) #self.entry_2.insert(1.0, value+'\n') def connect(self): filename = self.filename1[0] to_be_excute = "jpg_to_pdf" #ch = ConvertHandler( filename, to_be_excute ) #ch.start() def execute_handler(self): path = self.entry_path.get() server_ip = self.server_ip.get() server_port = self.server_port.get() interval = self.entry_interval.get() fh = file_handler(path,server_ip, server_port,interval ) fh.start() def run(self): self.filename1 = ['']*1 self.data1 = ['']*1 self.root = Tk() #self.entry_0 = Text(self.root, height = 10, width = 250) self.entry_path = Entry(self.root, width=55) #self.entry_2 = Text(self.root, height = 10, width = 250) #self.root = Tk() self.root.geometry('900x500') self.root.title("File Agent - Send your files to specified server") # Server IP Label(self.root, text = "Server IP:").place(x = 100, y = 50) self.server_ip = Entry(self.root, width=20) self.server_ip.place(x=170,y=50) self.server_ip.insert(0, "192.168.1.109") # Port Number Label(self.root, text = "Port No: ").place(x = 100, y = 100) self.server_port = Entry(self.root, width=20) self.server_port.place(x=170,y=100) self.server_port.insert(0, "5003") #Connect Button Button(self.root, text='Connect',command = self.connect, height = 4, width=64,bg='Green',fg='white').place(x=350,y=50) # File path selector #Button(self.root, text='Choose path of folder where file available',command = self.browse_button, width=35,bg='brown',fg='white').place(x=90,y=150) self.entry_path = Entry(self.root, width=55) self.entry_path.place(x=350,y=150) #Default self.entry_path.insert(0, "Select Folder path") Label(self.root, text = "Interval: ").place(x=690,y=150) self.entry_interval = Entry(self.root, width=10 ) #Default value self.entry_interval.insert(0, " 5") self.entry_interval.place(x=740,y=150) Button(self.root, text='Choose path of folder where file available',command = self.browse_button, width=35,bg='brown',fg='white').place(x=90,y=150) # Action using button Button(self.root, text='Execute',command = self.execute_handler, height = 3, width=47,bg='blue',fg='white').place(x=90,y=200) #Button(self.root, text='Merge PDF',command = self.merge_pdf, width=20,bg='green',fg='white').place(x=280,y=290) #Button(self.root, text='SPLIT PDF',command = self.split_pdf, width=20,bg='green',fg='white').place(x=470,y=290) Button(self.root, text='EXIT ',command = self.root.quit, height = 3, width=47,bg='red',fg='white').place(x=470,y=200) # Display Logs # Action to download self.output_data = Text(self.root, height = 8, width = 90) self.output_data.place(x=90,y=280) self.root.mainloop() print("\nProgram Exit") class file_handler(Thread): def __init__(self, path, server_ip, server_port, interval ): Thread.__init__(self) self.path = path self.server_ip = server_ip self.server_port = int(server_port) self.interval = int(interval) def run(self): list_of_current_files = os.listdir(self.path) #print(list_of_current_files) #print(self.server_ip) #print(self.server_port) #print(self.interval) remaining_files = list(set(list_of_current_files) - set(list_of_sent_files)) for file in remaining_files: file_path = self.path+'/'+file #print(file_path) list_of_sent_files.append(file) ft = FileTransfer(file_path,self.server_ip, self.server_port ) ft.start() ft.join() sleep(10) #self.run() class FileTransfer(Thread): def __init__(self, path, server_ip, server_port): Thread.__init__(self) self.host = server_ip self.port = server_port self.filename = path def run(self): SEPARATOR = "<SEPARATOR>" BUFFER_SIZE = 4096 # send 4096 bytes each time step host = self.host port = int(self.port) filename = self.filename fl = filename.split('/') sp = '\\' filename = sp.join(fl) #print(filename,'\n') #host = "192.168.1.109" # Server address #port = 5003 # Server port #filename = "Wall-Paper.jpeg" # File to be send filesize = os.path.getsize(filename) s = socket.socket() print(f"[+] Connecting to {host}:{port}") s.connect((host, port)) print("[+] Connected.") # send the filename and filesize s.send(f"{filename}{SEPARATOR}{filesize}".encode()) # start sending the file progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024) output1[0] = f"Sending {filename}" main_App.output(client,f"Sending {filename}") with open(filename, "rb") as f: for _ in progress: # read the bytes from the file bytes_read = f.read(BUFFER_SIZE) if not bytes_read: # file transmitting is done break # we use sendall to assure transimission in # busy networks s.sendall(bytes_read) # update the progress bar progress.update(len(bytes_read)) s.close() sleep(3) #output1[0] = f"Sending {filename}" main_App.output(client," - completed\n") client = main_App() client.start()
[ "noreply@github.com" ]
SP185221.noreply@github.com
79115cc0889d1e2a25aaab0b5bb5644d6b83c037
a4b621ef4230c27ddec5a4c1290f2e0c57e40019
/AK_RPversion.py
29bbcef2ed0e84d3c5f66352b6551262107c1064
[]
no_license
EliReid/4Button-Expert
54479297f168fe534a9e5866ba267968337c0011
f5971182a467fc0ff507d7a4ec4904d03803a56e
refs/heads/master
2020-04-28T12:08:03.942819
2019-02-21T22:15:56
2019-02-21T22:15:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
16,752
py
## uses only RP and AK planning units and unit tasks, so far ## perception of the game is hacked, so far import sys sys.path.append('/Users/robertwest/CCMSuite') #sys.path.append('C:/Users/Robert/Documents/Development/SGOMS/CCMSuite') import ccm from random import randrange, uniform log = ccm.log() # log=ccm.log(html=True) from ccm.lib.actr import * class MyEnvironment(ccm.Model): warning_light = ccm.Model(isa='warning_light', state='off') response = ccm.Model(isa='response', state='none') code = ccm.Model(isa='code', state='SU') # model assumes it starts at AK and doen't look until it has to motor_finst = ccm.Model(isa='motor_finst', state='re_set') class MotorModule(ccm.Model): ## def maybe_change_light(self): ## irand = randrange(0, 30) # adjust warning light probability here ## if irand < 1: ## print ' light on ++++++++++++++++++++++++++++++++++++++++++++++++++++' ## print irand ## self.parent.parent.warning_light.state='on' ## ## def turn_off_light(self): ## self.parent.parent.warning_light.state='off' ## print 'light off ------------------------------------------------------' ## # change_state is a generic action that changes the state slot of any object # disadvantages (1) yield #time is always the same (2) cannot use for parallel actions def change_state_fast(self, env_object, slot_value): yield 3 x = eval('self.parent.parent.' + env_object) x.state = slot_value print env_object print slot_value self.parent.parent.motor_finst.state = 'change_state_fast' def vision_slow(self): yield 5 print 'target identified' self.parent.parent.motor_finst.state = 'vision_slow' self.parent.b_vision.set('YP') def motor_finst_reset(self): self.parent.parent.motor_finst.state = 're_set' class EmotionalModule(ccm.ProductionSystem): production_time = 0.043 ## def warning_light(b_emotion='threat:ok',warning_light='state:on'): ## print "warning light is on!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" ## b_emotion.set('threat:high') class Environment_Manager(ACTR): # this agent triggers the warning light b_focus = Buffer() motor = MotorModule() ## def init(): ## b_focus.set('set_warning') ## def environment(b_focus='set_warning'): ## motor.maybe_change_light() class MyAgent(ACTR): # this is the agent that does the task # module buffers b_DM = Buffer() b_motor = Buffer() b_focus = Buffer() b_vision = Buffer() # goal buffers b_context = Buffer() b_plan_unit = Buffer() b_unit_task = Buffer() b_method = Buffer() b_operator = Buffer() b_emotion = Buffer() DM = Memory(b_DM) motor = MotorModule(b_motor) Emotion = EmotionalModule(b_emotion) def init(): ## DM.add('planning_unit:XY cuelag:none cue:start unit_task:X') ## DM.add('planning_unit:XY cuelag:start cue:X unit_task:Y') ## DM.add('planning_unit:XY cuelag:X cue:Y unit_task:finished') DM.add('planning_unit:AK cuelag:none cue:start unit_task:AK') DM.add('planning_unit:AK cuelag:start cue:AK unit_task:RP') DM.add('planning_unit:AK cuelag:AK cue:RP unit_task:finished') DM.add('planning_unit:RP cuelag:none cue:start unit_task:RP') DM.add('planning_unit:RP cuelag:start cue:RP unit_task:AK') DM.add('planning_unit:RP cuelag:RP cue:AK unit_task:finished') b_context.set('finshed:nothing status:unoccupied warning_light:off') b_emotion.set('threat:ok') b_focus.set('none') b_vision.set('AK') # assume this has happened ########################### begin the planning unit # these productions are the highest level of SGOMS and fire off the context buffer # the decision process can be as complex as needed # the simplest way is to have a production for each planning unit (as in this case) # the first unit task in the planning unit is directly triggered from here def run_PU_AK(b_context='finshed:nothing status:unoccupied', b_vision='AK'): b_unit_task.set('unit_task:AK state:running typee:ordered') b_plan_unit.set('planning_unit:AK cuelag:none cue:start unit_task:AK state:running') b_context.set('finished:nothing status:occupied') print 'PU_AK ordered planning unit is chosen OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' def run_PU_RP(b_context='finshed:AK status:unoccupied'): b_unit_task.set('unit_task:RP state:running typee:ordered') b_plan_unit.set('planning_unit:RP cuelag:none cue:start unit_task:RP state:running') b_context.set('finished:nothing status:occupied') print 'PU_RP ordered planning unit is chosen OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' def end(b_context='finshed:RP status:unoccupied'): b_context.set('end') print 'end program' def false_alarm(b_context='finshed:?finished status:interupted'): motor.turn_off_light() b_emotion.set('threat:ok') b_unit_task.set('unit_task:X state:running typee:ordered') b_plan_unit.set('planning_unit:XY cuelag:none cue:start unit_task:X state:running') b_context.set('finished:nothing status:occupied') print 'ordered planning unit is chosen OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' ######################### planning unit management loop # these are generic productions for managing the execution of planning units ######## get next unit task and save a memory of the completed unit task # the first unit task in a planning unit is triggered when the planning unit is chosen # these porductions fire within planning units to get the next unit task # to trigger the next unit task the unit_task state slot value is switched from 'end' to 'begin' # this is also where the successful completion of the last unit task is saved to memory ## the memory save is often not needed in simple models and is not implemented here ### although, in theory, the memory save always happens so this step should always be included # ordered planning units ## retrieve next unit task def request_next_unit_task(b_plan_unit='planning_unit:?planning_unit cuelag:?cuelag cue:?cue unit_task:?unit_task state:running', b_unit_task='unit_task:?unit_task state:end typee:ordered', b_emotion='threat:ok'): DM.request('planning_unit:?planning_unit cue:?unit_task unit_task:? cuelag:?cue') b_plan_unit.set('planning_unit:?planning_unit cuelag:?cuelag cue:?cue unit_task:?unit_task state:retrieve') # next unit task print 'finished unit task = ', unit_task # save completed unit task here def retrieved_next_unit_task(b_plan_unit='state:retrieve', b_DM='planning_unit:?planning_unit cuelag:?cuelag cue:?cue unit_task:?unit_task!finished'): b_plan_unit.set('planning_unit:?planning_unit cuelag:?cuelag cue:?cue unit_task:?unit_task state:running') b_unit_task.set('unit_task:?unit_task state:running typee:ordered') print 'next unit_task = ', unit_task print 'ordered' # situated planning units ## allow the next unit task to fire def next_situated_unit_task(b_unit_task='unit_task:?unit_task state:end typee:situated', b_emotion='threat:ok'): b_unit_task.modify(state='find_match') print 'next situated unit task' print 'situated' # save unit task here ########### end the planning unit and save a memory of it # a planning unit can be thought of as a loop # these are the exit conditions # in these the planning unit should be saved # although, to keep the code simple, this is not done here ## finished ordered planning unit def retrieved_last_unit_task(b_plan_unit='planning_unit:?planning_unit state:retrieve', b_unit_task='unit_task:?unit_task state:end typee:ordered', b_DM='planning_unit:?planning_unit cuelag:?cuelag cue:?cue unit_task:finished'): # not, the memory retrieval indicates the plan is finished print 'stopped planning unit=',planning_unit print 'finished' b_unit_task.modify(state='stopped') b_context.set('finshed:?planning_unit status:unoccupied') # save completed planning unit here def interupted_planning_unit(b_plan_unit='planning_unit:?planning_unit', b_unit_task='unit_task:?unit_task state:end typee:?typee', b_emotion='threat:high'): print 'stopped planning unit=' print 'interupted IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII' b_unit_task.modify(state='stopped') b_context.set('finshed:?planning_unit status:interupted') # save completed planning unit here ####################################### unit tasks # AK unit task AK-WM-SU-ZB-FJ ## situated matching productions def AK_start_unit_task_situated(b_unit_task='state:find_match typee:situated'): b_unit_task.set('unit_task:AK state:running typee:situated') print 'start unit task AK' ## body of the unit task def AK_known_response_AK(b_unit_task='unit_task:AK state:running', b_focus='none'): b_focus.set('AK') b_method.set('method:known_response target:response content:1234 state:start') print 'AK unit task AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' print 'doing AK' def AK_known_response_WM(b_unit_task='unit_task:AK state:running', b_focus='AK', b_method='state:finished'): b_focus.set('WM') b_method.set('method:known_response target:response content:1432 state:start') print 'doing WM' def AK_known_response_SU(b_unit_task='unit_task:AK state:running', b_focus='WM', b_method='state:finished'): b_focus.set('SU') b_method.set('method:known_response target:response content:4123 state:start') print 'doing SU' def AK_known_response_ZB(b_unit_task='unit_task:AK state:running', b_focus='SU', b_method='state:finished'): b_focus.set('ZB') b_method.set('method:known_response target:response content:2143 state:start') print 'doing ZB' def AK_known_response_FJ(b_unit_task='unit_task:AK state:running', b_focus='ZB', b_method='state:finished'): b_focus.set('FJ') b_method.set('method:known_response target:response content:3214 state:start') print 'doing FJ' def AK_finished(b_unit_task='unit_task:AK state:running', b_focus='FJ', b_method='state:finished'): b_focus.set('none') b_unit_task.modify(state='end') ## this line ends the unit task print ' - finished unit task' # YP-FJ # RP unit task RP-SU< # ZB-WM ## situated matching productions def RP_start_unit_task_situated(b_unit_task='state:find_match typee:situated'): b_unit_task.set('unit_task:Y state:running typee:situated') print 'start unit task Y' ## body of the unit task def RP_known_response_RP(b_unit_task='unit_task:RP state:running', b_focus='none'): b_focus.set('RP') b_method.set('method:known_response target:response content:4321 state:start') print 'doing RP_UT RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR' print 'doing RP' def RP_known_response_SU(b_unit_task='unit_task:RP state:running', b_focus='RP', b_method='state:finished'): b_focus.set('SU') b_method.set('method:known_response target:response content:4123 state:start') print 'doing SU' def RP_unknown_code(b_unit_task='unit_task:RP state:running', b_focus='SU', b_method='state:finished'): b_focus.set('unkown_code') b_method.set('method:get_code target:response content:1432 state:start') print 'getting code' def RP_got_code1(b_unit_task='unit_task:RP state:running', b_focus='unkown_code', b_method='state:finished', b_vision='YP'): b_focus.set('YP') b_method.set('method:known_response target:response content:1432 state:start') print 'doing YP' def RP_known_response_FJ(b_unit_task='unit_task:RP state:running', b_focus='YP', b_method='state:finished'): b_focus.set('FJ') b_method.set('method:known_response target:response content:3214 state:start') print 'doing FJ' def RP_finished1(b_unit_task='unit_task:RP state:running', b_focus='FJ', b_method='state:finished'): b_focus.set('none') b_unit_task.modify(state='end') ## this line ends the unit task print ' - finished unit task' def RP_got_code2(b_unit_task='unit_task:RP state:running', b_focus='unkown_code', b_method='state:finished', b_vision='ZB'): b_focus.set('ZB') b_method.set('method:known_response target:response content:1432 state:start') print 'doing ZB' def RP_known_response_WM(b_unit_task='unit_task:RP state:running', b_focus='ZB', b_method='state:finished'): b_focus.set('WM') b_method.set('method:known_response target:response content:2143 state:start') print 'doing WM' def RP_finished2(b_unit_task='unit_task:Y state:running', b_focus='WM', b_method='state:finished'): b_focus.set('none') b_unit_task.modify(state='end') ## this line ends the unit task b_unit_task.modify(state='stop') ## this line ends the unit task print ' - finished unit task' ###################################################### methods ################################################################### ################################################################################################################################## # known response method ######################### # the response is passed down by the production that called this method def known_response_vision(b_method='method:known_response target:?target content:?content state:start'): # target is the chunk to be altered motor.change_state_fast(target, content) b_method.modify(state='running') print 'entering response' print 'target object = ', target def response_entered(b_method='method:?method target:?target state:running', motor_finst='state:change_state_fast'): b_method.modify(state='finished') motor.motor_finst_reset() print 'I have altered - ', target # get_code method ################################ # in the case where the next response depends on the code the agent must first read the code def get_code(b_method='method:get_code target:?target content:?content state:start'): # target is the chunk to be altered motor.vision_slow() b_method.modify(state='running') print 'getting code' def get_code_finished(motor_finst='state:vision_slow', b_vision='?code'): motor.motor_finst_reset() b_method.modify(state='finished') print 'I have spotted the target, I have the new code' print code ############## run model ############# jim = Environment_Manager() tim = MyAgent() # name the agent subway = MyEnvironment() # name the environment subway.agent = tim # put the agent in the environment subway.agent = jim # put the agent in the environment ccm.log_everything(subway) # print out what happens in the environment subway.run() # run the environment ccm.finished() # stop the environment
[ "noreply@github.com" ]
EliReid.noreply@github.com
78bdca14128518d133ddf2e80c557c7d2e26fd7f
933493356546a769dda5c67f0a89eed9c970afa8
/ch6/q57.py
e42bbe6997419cc37dcd0703bfc6f51610b9fcca
[]
no_license
irtfrm/NLP100
233aa3b76d14dd89fe1d8f6d2e204ca3566bd5f5
ee0acedf7d2b00fe23f457120313d621fd1f098f
refs/heads/master
2021-08-06T09:47:38.238306
2020-06-05T08:18:08
2020-06-05T08:18:08
184,555,295
0
0
null
null
null
null
UTF-8
Python
false
false
925
py
import xml.etree.ElementTree as ET def gets_dot(tokens, deps): ans = 'digraph {\n' ans += ' token%s [label="%s"];\n' % (0, 'ROOT') for token in tokens: ans += ' token%s [shape=box, label="%s"];\n' % (token['id'], token['word']) for dep in deps: ans += ' token%s -> token%s;\n' % (dep['governor'], dep['dependent']) ans += '}\n' return ans with open('nlp.txt.xml', 'r') as f: lines = ''.join(f.readlines()) root = ET.fromstring(lines) tokens = [] deps = [] for sentence in root.findall('./document/sentences/sentence'): lst = [] for token in sentence[0]: lst.append({ 'id' : int(token.attrib['id']), 'word' : token[0].text }) tokens.append(lst) lst = [] for dep in sentence[2]: lst.append({ 'governor' : int(dep[0].attrib['idx']), 'dependent' : int(dep[1].attrib['idx']), }) deps.append(lst) i = 0 print(gets_dot(tokens[i], deps[i]))
[ "furukawa.tomoya@g.mbox.nagoya-u.ac.jp" ]
furukawa.tomoya@g.mbox.nagoya-u.ac.jp
e9eef0ae487bb90ae983c14902b33bc6d26c7a4f
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/429/usersdata/313/105928/submittedfiles/jogoDaVelha.py
6702e638a0b195b5ad2f3fe0c84a675088f19cc5
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
1,102
py
print (" BEM-VINDO AO JOGO DA VELHA ") print("O primeiro jogador será o (X) e o segundo o (O) ") posicao = """ posicoes do jogo 1 | 2 | 3 ----------- 4 | 5 | 6 ----------- 7 | 8 | 9 """ print (posicao) posicoes = [ (5,7), (5,5), (5,3), (9,7), (9,5), (9,3), (7,7), (7,5), (7,3), ] ganhador = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7], ] jogo = [] for vertical in posicao.splitlines(): jogo.append(list(vertical)) jogador = "X" jogando = True jogadas = 0 while True: if jogadas == 9: print (" DEU VELHA!") break jogada = int(input(" digite a posicao de 1 à 9 (jogador %s): " % jogador )) if jogada<1 or jogada>9: print ("posicao fora das posicoes do jogo") continue if jogo[posicoes[jogada][0]][posicoes[jogada][1]] != " ": print ("Essa posicao já foi ocupada") continue
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
bc95461ad6fdc0ef95c4d671c174b643f840fd99
3354e6bdd4aeb2ddec84e6a8036c90cd24b6577a
/(구)자료구조와 알고리즘/(구)Quizes/backjoon/back_1002.py
b90ab7cd42413d530cb002dd703cd4c028e3c9d1
[]
no_license
hchayan/Data-Structure-and-Algorithms
1125d7073b099d8c6aae4b14fbdb5e557dcb9412
be060447e42235e94f93a0b2f94f84d2fd560ffe
refs/heads/master
2023-01-05T10:15:02.862700
2020-11-04T08:16:56
2020-11-04T08:16:56
209,513,516
1
0
null
null
null
null
UTF-8
Python
false
false
466
py
import sys import math n = int(sys.stdin.readline().rstrip()) def getAns(): x1, y1, r1, x2, y2, r2 = map(int, sys.stdin.readline().rstrip().split()) leng = math.sqrt((x2-x1)**2+(y2-y1)**2) if r1 == r2 and x1 == x2 and y1 == y2: return -1 if r1 > r2: r1, r2 = r2, r1 if leng > r1+r2: return 0 elif leng == r1+r2: return 1 else: if leng+r1 == r2: return 1 elif leng+r1 < r2: return 0 return 2 for nn in range(n): print(getAns())
[ "k852012@naver.com" ]
k852012@naver.com
4b8450ca316cbf700f09c76a6c374e71ef1ce7c9
62b78ad6d3ec041ad20e4328d1730d815c9e35f1
/Twosteps.py
8c659c092569737b987696cb0d9e96f753e7dd19
[]
no_license
Jamshid93/ForLoops2
7fe5b3240370d88a888f2d4609fb6d7787965a4d
296de0ccc51872001e45e20926b91a4528abd7a5
refs/heads/master
2022-01-26T05:22:18.206075
2019-07-20T04:12:37
2019-07-20T04:12:37
197,874,396
0
0
null
null
null
null
UTF-8
Python
false
false
105
py
for item in range(3, 14, 2): # this is code result 3,5,...13. Because after 14 writin 2 print(item)
[ "hamzayevjf@gmail.com" ]
hamzayevjf@gmail.com
090b3c526b14fc85e5ddfe57bd932deff3860bf7
9d4bf5f90cd0a8eb97e7e48a0545f349c3b17b45
/1-100/Letter_Combinations_of_a_Phone_Number.py
f86071b4c06a57181e25e64c02981526a3a4edc6
[]
no_license
Ys-Zhou/leetcode-medi-p2
8201a6d1ee7e4cb6fe8bc9516530a8b8b3e26e8c
df3495d0bc504237305b11974906f27f8fd124e9
refs/heads/master
2021-10-07T09:07:28.974814
2018-12-04T09:23:21
2018-12-04T09:23:21
111,872,195
0
0
null
null
null
null
UTF-8
Python
false
false
813
py
# 25 / 25 test cases passed. # Runtime: 36 ms class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if digits == '': return [] letters = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']} length = len(digits) def getletter(index): if index == length: return [''] return [x + y for x in letters[digits[index]] for y in getletter(index + 1)] return getletter(0)
[ "zhouyan1993ys@gmail.com" ]
zhouyan1993ys@gmail.com
e36bbc0c4240de429927358094f5d3cd4c54a838
f7e4ba62191d39b050eab6cbf196c9000751a779
/examples/function_param.py
b285fc9ff46f8f155c969867b438a10ade9d1976
[]
no_license
heimo-tiihonen/hello-world
04bdc59f7806b9c851adf43dfa6312ed219bac79
b1d513242a0511f1866874cec9b410484b186038
refs/heads/master
2021-01-09T06:16:34.729181
2017-02-04T19:41:57
2017-02-04T19:41:57
80,949,066
0
0
null
null
null
null
UTF-8
Python
false
false
278
py
def print_max(a, b): if a > b: print(a, 'is maximum') elif a == b: print(a, 'is equal to', b) else: print(b, 'is maximum') # directly pass literal values print_max(3, 4) x = 5 y = 7 z = 'Testi' # pass variables as arguments print_max(z, y)
[ "heimo@dsl-espbrasgw1-50dfb2-69.dhcp.inet.fi" ]
heimo@dsl-espbrasgw1-50dfb2-69.dhcp.inet.fi
1cdb9ccb8eb20c40eb3ca82b06c082532bc3b005
db2e1604cdd45df402b93cd72b36e1995f0ded57
/baidu_baike/baidu_baike/middlewares.py
69c61f1ce3dc83c9f549186ad6a2fc5baa47e026
[]
no_license
JimyFengqi/baidubaike
9bd558bea58d728ef1d256aa9746978b058a138f
6bf6114494db485107f8869ed79ec70200ed26c2
refs/heads/master
2020-04-07T10:46:12.906874
2018-04-26T07:52:49
2018-04-26T07:52:49
124,205,144
2
0
null
null
null
null
UTF-8
Python
false
false
3,605
py
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # https://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals class BaiduBaikeSpiderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_spider_input(self, response, spider): # Called for each response that goes through the spider # middleware and into the spider. # Should return None or raise an exception. return None def process_spider_output(self, response, result, spider): # Called with the results returned from the Spider, after # it has processed the response. # Must return an iterable of Request, dict or Item objects. for i in result: yield i def process_spider_exception(self, response, exception, spider): # Called when a spider or process_spider_input() method # (from other spider middleware) raises an exception. # Should return either None or an iterable of Response, dict # or Item objects. pass def process_start_requests(self, start_requests, spider): # Called with the start requests of the spider, and works # similarly to the process_spider_output() method, except # that it doesn’t have a response associated. # Must return only requests (not items). for r in start_requests: yield r def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name) class BaiduBaikeDownloaderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_request(self, request, spider): # Called for each request that goes through the downloader # middleware. # Must either: # - return None: continue processing this request # - or return a Response object # - or return a Request object # - or raise IgnoreRequest: process_exception() methods of # installed downloader middleware will be called return None def process_response(self, request, response, spider): # Called with the response returned from the downloader. # Must either; # - return a Response object # - return a Request object # - or raise IgnoreRequest return response def process_exception(self, request, exception, spider): # Called when a download handler or a process_request() # (from other downloader middleware) raises an exception. # Must either: # - return None: continue processing this exception # - return a Response object: stops process_exception() chain # - return a Request object: stops process_exception() chain pass def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name)
[ "jmps515@163.com" ]
jmps515@163.com
67f1386cbcd7aa7765debd357ae2e31c5ecdad81
8ab2c341b570e26c8a06e7c5e9e95e3e2a108aba
/build/tasks/catkin_generated/pkg.installspace.context.pc.py
1a3ac85d66d27b61334ac967aed258bf919d3a93
[]
no_license
Aquavaders/Vader3-Control
c6429d58d208f303d5ed309c488d06f140ab08b5
8523e7ddda78b747106586bacfac14e99201741b
refs/heads/master
2020-07-29T04:01:25.852450
2020-02-27T20:04:36
2020-02-27T20:04:36
209,660,745
0
0
null
null
null
null
UTF-8
Python
false
false
366
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "tasks" PROJECT_SPACE_DIR = "/home/alaa/rov19_ws/install" PROJECT_VERSION = "0.0.0"
[ "AlaaAnani" ]
AlaaAnani
c243ec1a490acd1d8b165d7a7ddef83cc8088bf6
2c09e0fa8b9c84af6686962a8d8569af298573d7
/client/GUI.py
8c42ec4ee18b6ba646fd58bec03a55c3b0f80fd8
[]
no_license
eldraco/Adeept_RaspClaws
62e3dd4259e909c7eb5b9809e0815cf616277975
2d7c56016091678803410131ad328c2cae1b8256
refs/heads/master
2022-04-25T21:22:12.775696
2020-04-26T19:25:49
2020-04-26T19:25:49
256,761,979
1
0
null
2020-04-18T13:35:03
2020-04-18T13:35:03
null
UTF-8
Python
false
false
25,732
py
#!/usr/bin/python # -*- coding: UTF-8 -*- # File name : client.py # Description : client # Website : www.adeept.com # E-mail : support@adeept.com # Author : William # Date : 2018/08/22 from socket import * import sys import time import threading as thread import tkinter as tk try:#1 import cv2 import zmq import base64 import numpy as np except: print("Couldn't import OpenCV, you need to install it first.") ip_stu=1 #Shows connection status c_f_stu = 0 c_b_stu = 0 c_l_stu = 0 c_r_stu = 0 c_ls_stu= 0 c_rs_stu= 0 funcMode= 0 tcpClicSock = '' root = '' stat = 0 Switch_3 = 0 Switch_2 = 0 Switch_1 = 0 SmoothMode = 0 ########>>>>>VIDEO<<<<<######## def video_thread(): global footage_socket, font, frame_num, fps context = zmq.Context() footage_socket = context.socket(zmq.SUB) footage_socket.bind('tcp://*:5555') footage_socket.setsockopt_string(zmq.SUBSCRIBE, np.unicode('')) font = cv2.FONT_HERSHEY_SIMPLEX frame_num = 0 fps = 0 def get_FPS(): global frame_num, fps while 1: try: time.sleep(1) fps = frame_num frame_num = 0 except: time.sleep(1) def opencv_r(): global frame_num while True: try: frame = footage_socket.recv_string() img = base64.b64decode(frame) npimg = np.frombuffer(img, dtype=np.uint8) source = cv2.imdecode(npimg, 1) cv2.putText(source,('PC FPS: %s'%fps),(40,20), font, 0.5,(255,255,255),1,cv2.LINE_AA) try: cv2.putText(source,('CPU Temperature: %s'%CPU_TEP),(370,350), font, 0.5,(128,255,128),1,cv2.LINE_AA) cv2.putText(source,('CPU Usage: %s'%CPU_USE),(370,380), font, 0.5,(128,255,128),1,cv2.LINE_AA) cv2.putText(source,('RAM Usage: %s'%RAM_USE),(370,410), font, 0.5,(128,255,128),1,cv2.LINE_AA) #cv2.line(source,(320,240),(260,300),(255,255,255),1) #cv2.line(source,(210,300),(260,300),(255,255,255),1) #cv2.putText(source,('%sm'%ultra_data),(210,290), font, 0.5,(255,255,255),1,cv2.LINE_AA) except: pass #cv2.putText(source,('%sm'%ultra_data),(210,290), font, 0.5,(255,255,255),1,cv2.LINE_AA) cv2.imshow("Stream", source) frame_num += 1 cv2.waitKey(1) except: time.sleep(0.5) break fps_threading=thread.Thread(target=get_FPS) #Define a thread for FPV and OpenCV fps_threading.setDaemon(True) #'True' means it is a front thread,it would close when the mainloop() closes fps_threading.start() #Thread starts video_threading=thread.Thread(target=video_thread) #Define a thread for FPV and OpenCV video_threading.setDaemon(True) #'True' means it is a front thread,it would close when the mainloop() closes video_threading.start() #Thread starts ########>>>>>VIDEO<<<<<######## def replace_num(initial,new_num): #Call this function to replace data in '.txt' file newline="" str_num=str(new_num) with open("ip.txt","r") as f: for line in f.readlines(): if(line.find(initial) == 0): line = initial+"%s" %(str_num) newline += line with open("ip.txt","w") as f: f.writelines(newline) #Call this function to replace data in '.txt' file def num_import(initial): #Call this function to import data from '.txt' file with open("ip.txt") as f: for line in f.readlines(): if(line.find(initial) == 0): r=line begin=len(list(initial)) snum=r[begin:] n=snum return n def call_forward(event): #When this function is called,client commands the car to move forward global c_f_stu if c_f_stu == 0: tcpClicSock.send(('forward').encode()) c_f_stu=1 def call_back(event): #When this function is called,client commands the car to move backward global c_b_stu if c_b_stu == 0: tcpClicSock.send(('backward').encode()) c_b_stu=1 def call_FB_stop(event): #When this function is called,client commands the car to stop moving global c_f_stu,c_b_stu,c_l_stu,c_r_stu,c_ls_stu,c_rs_stu c_f_stu=0 c_b_stu=0 tcpClicSock.send(('DS').encode()) def call_Turn_stop(event): #When this function is called,client commands the car to stop moving global c_f_stu,c_b_stu,c_l_stu,c_r_stu,c_ls_stu,c_rs_stu c_l_stu=0 c_r_stu=0 c_ls_stu=0 c_rs_stu=0 tcpClicSock.send(('TS').encode()) def call_Left(event): #When this function is called,client commands the car to turn left global c_l_stu if c_l_stu == 0: tcpClicSock.send(('left').encode()) c_l_stu=1 def call_Right(event): #When this function is called,client commands the car to turn right global c_r_stu if c_r_stu == 0: tcpClicSock.send(('right').encode()) c_r_stu=1 def call_LeftSide(event): global c_ls_stu if c_ls_stu == 0: tcpClicSock.send(('leftside').encode()) c_ls_stu=1 def call_RightSide(event): global c_rs_stu if c_rs_stu == 0: tcpClicSock.send(('rightside').encode()) c_rs_stu=1 def call_headup(event): tcpClicSock.send(('headup').encode()) def call_headdown(event): tcpClicSock.send(('headdown').encode()) def call_headleft(event): tcpClicSock.send(('headleft').encode()) def call_headright(event): tcpClicSock.send(('headright').encode()) def call_headhome(event): tcpClicSock.send(('headhome').encode()) def call_steady(event): if funcMode == 0: tcpClicSock.send(('steady').encode()) else: tcpClicSock.send(('funEnd').encode()) def call_FindColor(event): if funcMode == 0: tcpClicSock.send(('FindColor').encode()) else: tcpClicSock.send(('funEnd').encode()) def call_WatchDog(event): if funcMode == 0: tcpClicSock.send(('WatchDog').encode()) else: tcpClicSock.send(('funEnd').encode()) def call_Smooth(event): if SmoothMode == 0: tcpClicSock.send(('Smooth_on').encode()) else: tcpClicSock.send(('Smooth_off').encode()) def call_Switch_1(event): if Switch_1 == 0: tcpClicSock.send(('Switch_1_on').encode()) else: tcpClicSock.send(('Switch_1_off').encode()) def call_Switch_2(event): if Switch_2 == 0: tcpClicSock.send(('Switch_2_on').encode()) else: tcpClicSock.send(('Switch_2_off').encode()) def call_Switch_3(event): if Switch_3 == 0: tcpClicSock.send(('Switch_3_on').encode()) else: tcpClicSock.send(('Switch_3_off').encode()) def all_btn_red(): Btn_Steady.config(bg='#FF6D00', fg='#000000') Btn_FindColor.config(bg='#FF6D00', fg='#000000') Btn_WatchDog.config(bg='#FF6D00', fg='#000000') Btn_Fun4.config(bg='#FF6D00', fg='#000000') Btn_Fun5.config(bg='#FF6D00', fg='#000000') Btn_Fun6.config(bg='#FF6D00', fg='#000000') def all_btn_normal(): Btn_Steady.config(bg=color_btn, fg=color_text) Btn_FindColor.config(bg=color_btn, fg=color_text) Btn_WatchDog.config(bg=color_btn, fg=color_text) Btn_Fun4.config(bg=color_btn, fg=color_text) Btn_Fun5.config(bg=color_btn, fg=color_text) Btn_Fun6.config(bg=color_btn, fg=color_text) def connection_thread(): global funcMode, Switch_3, Switch_2, Switch_1, SmoothMode while 1: car_info = (tcpClicSock.recv(BUFSIZ)).decode() if not car_info: continue elif 'FindColor' in car_info: funcMode = 1 all_btn_red() Btn_FindColor.config(bg='#00E676') elif 'steady' in car_info: funcMode = 1 all_btn_red() Btn_Steady.config(bg='#00E676') elif 'WatchDog' in car_info: funcMode = 1 all_btn_red() Btn_WatchDog.config(bg='#00E676') elif 'Smooth_on' in car_info: SmoothMode = 1 Btn_Smooth.config(bg='#4CAF50') elif 'Smooth_off' in car_info: SmoothMode = 0 Btn_Smooth.config(bg=color_btn) elif 'Switch_3_on' in car_info: Switch_3 = 1 Btn_Switch_3.config(bg='#4CAF50') elif 'Switch_2_on' in car_info: Switch_2 = 1 Btn_Switch_2.config(bg='#4CAF50') elif 'Switch_1_on' in car_info: Switch_1 = 1 Btn_Switch_1.config(bg='#4CAF50') elif 'Switch_3_off' in car_info: Switch_3 = 0 Btn_Switch_3.config(bg=color_btn) elif 'Switch_2_off' in car_info: Switch_2 = 0 Btn_Switch_2.config(bg=color_btn) elif 'Switch_1_off' in car_info: Switch_1 = 0 Btn_Switch_1.config(bg=color_btn) elif 'CVFL_on' in car_info: function_stu = 1 Btn_CVFL.config(bg='#4CAF50') elif 'CVFL_off' in car_info: function_stu = 0 Btn_CVFL.config(bg='#212121') elif 'FunEnd' in car_info: funcMode = 0 all_btn_normal() print(car_info) def Info_receive(): global CPU_TEP,CPU_USE,RAM_USE HOST = '' INFO_PORT = 2256 #Define port serial ADDR = (HOST, INFO_PORT) InfoSock = socket(AF_INET, SOCK_STREAM) InfoSock.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) InfoSock.bind(ADDR) InfoSock.listen(5) #Start server,waiting for client InfoSock, addr = InfoSock.accept() print('Info connected') while 1: try: info_data = '' info_data = str(InfoSock.recv(BUFSIZ).decode()) info_get = info_data.split() CPU_TEP,CPU_USE,RAM_USE= info_get #print('cpu_tem:%s\ncpu_use:%s\nram_use:%s'%(CPU_TEP,CPU_USE,RAM_USE)) CPU_TEP_lab.config(text='CPU Temp: %s℃'%CPU_TEP) CPU_USE_lab.config(text='CPU Usage: %s'%CPU_USE) RAM_lab.config(text='RAM Usage: %s'%RAM_USE) except: pass def socket_connect(): #Call this function to connect with the server global ADDR,tcpClicSock,BUFSIZ,ip_stu,ipaddr ip_adr=E1.get() #Get the IP address from Entry if ip_adr == '': #If no input IP address in Entry,import a default IP ip_adr=num_import('IP:') l_ip_4.config(text='Connecting') l_ip_4.config(bg='#FF8F00') l_ip_5.config(text='Default:%s'%ip_adr) pass SERVER_IP = ip_adr SERVER_PORT = 10223 #Define port serial BUFSIZ = 1024 #Define buffer size ADDR = (SERVER_IP, SERVER_PORT) tcpClicSock = socket(AF_INET, SOCK_STREAM) #Set connection value for socket for i in range (1,6): #Try 5 times if disconnected #try: if ip_stu == 1: print("Connecting to server @ %s:%d..." %(SERVER_IP, SERVER_PORT)) print("Connecting") tcpClicSock.connect(ADDR) #Connection with the server print("Connected") l_ip_5.config(text='IP:%s'%ip_adr) l_ip_4.config(text='Connected') l_ip_4.config(bg='#558B2F') replace_num('IP:',ip_adr) E1.config(state='disabled') #Disable the Entry Btn14.config(state='disabled') #Disable the Entry ip_stu=0 #'0' means connected connection_threading=thread.Thread(target=connection_thread) #Define a thread for FPV and OpenCV connection_threading.setDaemon(True) #'True' means it is a front thread,it would close when the mainloop() closes connection_threading.start() #Thread starts info_threading=thread.Thread(target=Info_receive) #Define a thread for FPV and OpenCV info_threading.setDaemon(True) #'True' means it is a front thread,it would close when the mainloop() closes info_threading.start() #Thread starts video_threading=thread.Thread(target=opencv_r) #Define a thread for FPV and OpenCV video_threading.setDaemon(True) #'True' means it is a front thread,it would close when the mainloop() closes video_threading.start() #Thread starts break else: print("Cannot connecting to server,try it latter!") l_ip_4.config(text='Try %d/5 time(s)'%i) l_ip_4.config(bg='#EF6C00') print('Try %d/5 time(s)'%i) ip_stu=1 time.sleep(1) continue if ip_stu == 1: l_ip_4.config(text='Disconnected') l_ip_4.config(bg='#F44336') def connect(event): #Call this function to connect with the server if ip_stu == 1: sc=thread.Thread(target=socket_connect) #Define a thread for connection sc.setDaemon(True) #'True' means it is a front thread,it would close when the mainloop() closes sc.start() #Thread starts def connect_click(): #Call this function to connect with the server if ip_stu == 1: sc=thread.Thread(target=socket_connect) #Define a thread for connection sc.setDaemon(True) #'True' means it is a front thread,it would close when the mainloop() closes sc.start() #Thread starts def set_R(event): time.sleep(0.03) tcpClicSock.send(('wsR %s'%var_R.get()).encode()) def set_G(event): time.sleep(0.03) tcpClicSock.send(('wsG %s'%var_G.get()).encode()) def set_B(event): time.sleep(0.03) tcpClicSock.send(('wsB %s'%var_B.get()).encode()) def EC_send(event):#z tcpClicSock.send(('setEC %s'%var_ec.get()).encode()) time.sleep(0.03) def EC_default(event):#z var_ec.set(0) tcpClicSock.send(('defEC').encode()) def scale_FL(x,y,w):#1 global Btn_CVFL def lip1_send(event): time.sleep(0.03) tcpClicSock.send(('lip1 %s'%var_lip1.get()).encode()) def lip2_send(event): time.sleep(0.03) tcpClicSock.send(('lip2 %s'%var_lip2.get()).encode()) def err_send(event): time.sleep(0.03) tcpClicSock.send(('err %s'%var_err.get()).encode()) def call_Render(event): tcpClicSock.send(('Render').encode()) def call_CVFL(event): tcpClicSock.send(('CVFL').encode()) def call_WB(event): tcpClicSock.send(('WBswitch').encode()) Scale_lip1 = tk.Scale(root,label=None, from_=0,to=480,orient=tk.HORIZONTAL,length=w, showvalue=1,tickinterval=None,resolution=1,variable=var_lip1,troughcolor='#212121',command=lip1_send,fg=color_text,bg=color_bg,highlightthickness=0) Scale_lip1.place(x=x,y=y) #Define a Scale and put it in position Scale_lip2 = tk.Scale(root,label=None, from_=0,to=480,orient=tk.HORIZONTAL,length=w, showvalue=1,tickinterval=None,resolution=1,variable=var_lip2,troughcolor='#212121',command=lip2_send,fg=color_text,bg=color_bg,highlightthickness=0) Scale_lip2.place(x=x,y=y+30) #Define a Scale and put it in position Scale_err = tk.Scale(root,label=None, from_=0,to=200,orient=tk.HORIZONTAL,length=w, showvalue=1,tickinterval=None,resolution=1,variable=var_err,troughcolor='#212121',command=err_send,fg=color_text,bg=color_bg,highlightthickness=0) Scale_err.place(x=x,y=y+60) #Define a Scale and put it in position canvas_cover=tk.Canvas(root,bg=color_bg,height=30,width=510,highlightthickness=0) canvas_cover.place(x=x,y=y+90) Btn_Render = tk.Button(root, width=10, text='Render',fg=color_text,bg='#212121',relief='ridge') Btn_Render.place(x=x+w+111,y=y+20) Btn_Render.bind('<ButtonPress-1>', call_Render) Btn_CVFL = tk.Button(root, width=10, text='CV FL',fg=color_text,bg='#212121',relief='ridge') Btn_CVFL.place(x=x+w+21,y=y+20) Btn_CVFL.bind('<ButtonPress-1>', call_CVFL) Btn_WB = tk.Button(root, width=23, text='LineColorSwitch',fg=color_text,bg='#212121',relief='ridge') Btn_WB.place(x=x+w+21,y=y+60) Btn_WB.bind('<ButtonPress-1>', call_WB) def loop(): #GUI global tcpClicSock,root,E1,connect,l_ip_4,l_ip_5,color_btn,color_text,Btn14,CPU_TEP_lab,CPU_USE_lab,RAM_lab,canvas_ultra,color_text,var_lip1,var_lip2,var_err,var_R,var_B,var_G,var_ec,Btn_Steady,Btn_FindColor,Btn_WatchDog,Btn_Fun4,Btn_Fun5,Btn_Fun6,Btn_Switch_1,Btn_Switch_2,Btn_Switch_3,Btn_Smooth,color_bg #1 The value of tcpClicSock changes in the function loop(),would also changes in global so the other functions could use it. while True: color_bg='#000000' #Set background color color_text='#E1F5FE' #Set text color color_btn='#0277BD' #Set button color color_line='#01579B' #Set line color color_can='#212121' #Set canvas color color_oval='#2196F3' #Set oval color target_color='#FF6D00' root = tk.Tk() #Define a window named root root.title('Adeept RaspClaws') #Main window title root.geometry('565x680') #1 Main window size, middle of the English letter x. root.config(bg=color_bg) #Set the background color of root window try: logo =tk.PhotoImage(file = 'logo.png') #Define the picture of logo,but only supports '.png' and '.gif' l_logo=tk.Label(root,image = logo,bg=color_bg) #Set a label to show the logo picture l_logo.place(x=30,y=13) #Place the Label in a right position except: pass CPU_TEP_lab=tk.Label(root,width=18,text='CPU Temp:',fg=color_text,bg='#212121') CPU_TEP_lab.place(x=400,y=15) #Define a Label and put it in position CPU_USE_lab=tk.Label(root,width=18,text='CPU Usage:',fg=color_text,bg='#212121') CPU_USE_lab.place(x=400,y=45) #Define a Label and put it in position RAM_lab=tk.Label(root,width=18,text='RAM Usage:',fg=color_text,bg='#212121') RAM_lab.place(x=400,y=75) #Define a Label and put it in position l_ip=tk.Label(root,width=18,text='Status',fg=color_text,bg=color_btn) l_ip.place(x=30,y=110) #Define a Label and put it in position l_ip_4=tk.Label(root,width=18,text='Disconnected',fg=color_text,bg='#F44336') l_ip_4.place(x=400,y=110) #Define a Label and put it in position l_ip_5=tk.Label(root,width=18,text='Use default IP',fg=color_text,bg=color_btn) l_ip_5.place(x=400,y=145) #Define a Label and put it in position E1 = tk.Entry(root,show=None,width=16,bg="#37474F",fg='#eceff1') E1.place(x=180,y=40) #Define a Entry and put it in position l_ip_3=tk.Label(root,width=10,text='IP Address:',fg=color_text,bg='#000000') l_ip_3.place(x=175,y=15) #Define a Label and put it in position label_openCV=tk.Label(root,width=28,text='OpenCV Status',fg=color_text,bg=color_btn) label_openCV.place(x=180,y=110) #Define a Label and put it in position ################################ #canvas_rec=canvas_ultra.create_rectangle(0,0,340,30,fill = '#FFFFFF',width=0) #canvas_text=canvas_ultra.create_text((90,11),text='Ultrasonic Output: 0.75m',fill=color_text) ################################ Btn_Smooth = tk.Button(root, width=8, text='Smooth',fg=color_text,bg=color_btn,relief='ridge') Btn_Smooth.place(x=240,y=230) Btn_Smooth.bind('<ButtonPress-1>', call_Smooth) root.bind('<KeyPress-f>', call_Smooth) Btn_Switch_1 = tk.Button(root, width=8, text='Port 1',fg=color_text,bg=color_btn,relief='ridge') Btn_Switch_2 = tk.Button(root, width=8, text='Port 2',fg=color_text,bg=color_btn,relief='ridge') Btn_Switch_3 = tk.Button(root, width=8, text='Port 3',fg=color_text,bg=color_btn,relief='ridge') Btn_Switch_1.place(x=30,y=265) Btn_Switch_2.place(x=100,y=265) Btn_Switch_3.place(x=170,y=265) Btn_Switch_1.bind('<ButtonPress-1>', call_Switch_1) Btn_Switch_2.bind('<ButtonPress-1>', call_Switch_2) Btn_Switch_3.bind('<ButtonPress-1>', call_Switch_3) Btn0 = tk.Button(root, width=8, text='Forward',fg=color_text,bg=color_btn,relief='ridge') Btn1 = tk.Button(root, width=8, text='Backward',fg=color_text,bg=color_btn,relief='ridge') Btn2 = tk.Button(root, width=8, text='Left',fg=color_text,bg=color_btn,relief='ridge') Btn3 = tk.Button(root, width=8, text='Right',fg=color_text,bg=color_btn,relief='ridge') Btn_LeftSide = tk.Button(root, width=8, text='<--',fg=color_text,bg=color_btn,relief='ridge') Btn_LeftSide.place(x=30,y=195) Btn_LeftSide.bind('<ButtonPress-1>', call_LeftSide) Btn_LeftSide.bind('<ButtonRelease-1>', call_Turn_stop) Btn_RightSide = tk.Button(root, width=8, text='-->',fg=color_text,bg=color_btn,relief='ridge') Btn_RightSide.place(x=170,y=195) Btn_RightSide.bind('<ButtonPress-1>', call_RightSide) Btn_RightSide.bind('<ButtonRelease-1>', call_Turn_stop) Btn0.place(x=100,y=195) Btn1.place(x=100,y=230) Btn2.place(x=30,y=230) Btn3.place(x=170,y=230) Btn0.bind('<ButtonPress-1>', call_forward) Btn1.bind('<ButtonPress-1>', call_back) Btn2.bind('<ButtonPress-1>', call_Left) Btn3.bind('<ButtonPress-1>', call_Right) Btn0.bind('<ButtonRelease-1>', call_FB_stop) Btn1.bind('<ButtonRelease-1>', call_FB_stop) Btn2.bind('<ButtonRelease-1>', call_Turn_stop) Btn3.bind('<ButtonRelease-1>', call_Turn_stop) root.bind('<KeyPress-w>', call_forward) root.bind('<KeyPress-a>', call_Left) root.bind('<KeyPress-d>', call_Right) root.bind('<KeyPress-s>', call_back) root.bind('<KeyPress-q>', call_LeftSide) root.bind('<KeyPress-e>', call_RightSide) root.bind('<KeyRelease-q>', call_Turn_stop) root.bind('<KeyRelease-e>', call_Turn_stop) root.bind('<KeyRelease-w>', call_FB_stop) root.bind('<KeyRelease-a>', call_Turn_stop) root.bind('<KeyRelease-d>', call_Turn_stop) root.bind('<KeyRelease-s>', call_FB_stop) Btn_up = tk.Button(root, width=8, text='Up',fg=color_text,bg=color_btn,relief='ridge') Btn_down = tk.Button(root, width=8, text='Down',fg=color_text,bg=color_btn,relief='ridge') Btn_left = tk.Button(root, width=8, text='Left',fg=color_text,bg=color_btn,relief='ridge') Btn_right = tk.Button(root, width=8, text='Right',fg=color_text,bg=color_btn,relief='ridge') Btn_home = tk.Button(root, width=8, text='Home',fg=color_text,bg=color_btn,relief='ridge') Btn_up.place(x=400,y=195) Btn_down.place(x=400,y=265) Btn_left.place(x=330,y=230) Btn_right.place(x=470,y=230) Btn_home.place(x=400,y=230) root.bind('<KeyPress-i>', call_headup) root.bind('<KeyPress-k>', call_headdown) root.bind('<KeyPress-j>', call_headleft) root.bind('<KeyPress-l>', call_headright) root.bind('<KeyPress-h>', call_headhome) Btn_up.bind('<ButtonPress-1>', call_headup) Btn_down.bind('<ButtonPress-1>', call_headdown) Btn_left.bind('<ButtonPress-1>', call_headleft) Btn_right.bind('<ButtonPress-1>', call_headright) Btn_home.bind('<ButtonPress-1>', call_headhome) Btn14= tk.Button(root, width=8,height=2, text='Connect',fg=color_text,bg=color_btn,command=connect_click,relief='ridge') Btn14.place(x=315,y=15) #Define a Button and put it in position root.bind('<Return>', connect) var_lip1 = tk.StringVar()#1 var_lip1.set(440) var_lip2 = tk.StringVar() var_lip2.set(380) var_err = tk.StringVar() var_err.set(20) var_R = tk.StringVar() var_R.set(0) Scale_R = tk.Scale(root,label=None, from_=0,to=255,orient=tk.HORIZONTAL,length=505, showvalue=1,tickinterval=None,resolution=1,variable=var_R,troughcolor='#F44336',command=set_R,fg=color_text,bg=color_bg,highlightthickness=0) Scale_R.place(x=30,y=330) #Define a Scale and put it in position var_G = tk.StringVar() var_G.set(0) Scale_G = tk.Scale(root,label=None, from_=0,to=255,orient=tk.HORIZONTAL,length=505, showvalue=1,tickinterval=None,resolution=1,variable=var_G,troughcolor='#00E676',command=set_G,fg=color_text,bg=color_bg,highlightthickness=0) Scale_G.place(x=30,y=360) #Define a Scale and put it in position var_B = tk.StringVar() var_B.set(0) Scale_B = tk.Scale(root,label=None, from_=0,to=255,orient=tk.HORIZONTAL,length=505, showvalue=1,tickinterval=None,resolution=1,variable=var_B,troughcolor='#448AFF',command=set_B,fg=color_text,bg=color_bg,highlightthickness=0) Scale_B.place(x=30,y=390) #Define a Scale and put it in position var_ec = tk.StringVar() #Z start var_ec.set(0) Scale_ExpCom = tk.Scale(root,label='Exposure Compensation Level', from_=-25,to=25,orient=tk.HORIZONTAL,length=315, showvalue=1,tickinterval=None,resolution=1,variable=var_ec,troughcolor='#212121',command=EC_send,fg=color_text,bg=color_bg,highlightthickness=0) Scale_ExpCom.place(x=30,y=610) #Define a Scale and put it in position canvas_cover_exp=tk.Canvas(root,bg=color_bg,height=30,width=510,highlightthickness=0) canvas_cover_exp.place(x=30,y=610+50) Btn_dEC = tk.Button(root, width=23,height=2, text='Set Default Exposure\nCompensation Level',fg=color_text,bg='#212121',relief='ridge') Btn_dEC.place(x=30+315+21,y=610+3) Btn_dEC.bind('<ButtonPress-1>', EC_default) #Z end canvas_cover=tk.Canvas(root,bg=color_bg,height=30,width=510,highlightthickness=0) canvas_cover.place(x=30,y=420) Btn_Steady = tk.Button(root, width=10, text='Steady',fg=color_text,bg=color_btn,relief='ridge') Btn_Steady.place(x=30,y=445) root.bind('<KeyPress-z>', call_steady) Btn_Steady.bind('<ButtonPress-1>', call_steady) Btn_FindColor = tk.Button(root, width=10, text='FindColor',fg=color_text,bg=color_btn,relief='ridge') Btn_FindColor.place(x=115,y=445) root.bind('<KeyPress-z>', call_FindColor) Btn_FindColor.bind('<ButtonPress-1>', call_FindColor) Btn_WatchDog = tk.Button(root, width=10, text='WatchDog',fg=color_text,bg=color_btn,relief='ridge') Btn_WatchDog.place(x=200,y=445) root.bind('<KeyPress-z>', call_WatchDog) Btn_WatchDog.bind('<ButtonPress-1>', call_WatchDog) Btn_Fun4 = tk.Button(root, width=10, text='Function 4',fg=color_text,bg=color_btn,relief='ridge') Btn_Fun4.place(x=285,y=445) root.bind('<KeyPress-z>', call_WatchDog) Btn_Fun4.bind('<ButtonPress-1>', call_WatchDog) Btn_Fun5 = tk.Button(root, width=10, text='Function 5',fg=color_text,bg=color_btn,relief='ridge') Btn_Fun5.place(x=370,y=445) root.bind('<KeyPress-z>', call_WatchDog) Btn_Fun5.bind('<ButtonPress-1>', call_WatchDog) Btn_Fun6 = tk.Button(root, width=10, text='Function 6',fg=color_text,bg=color_btn,relief='ridge') Btn_Fun6.place(x=455,y=445) root.bind('<KeyPress-z>', call_WatchDog) Btn_Fun6.bind('<ButtonPress-1>', call_WatchDog) scale_FL(30,490,315)#1 global stat if stat==0: # Ensure the mainloop runs only once root.mainloop() # Run the mainloop() stat=1 # Change the value to '1' so the mainloop() would not run again. if __name__ == '__main__': try: loop() # Load GUI except: tcpClicSock.close() # Close socket or it may not connect with the server again footage_socket.close() cv2.destroyAllWindows() pass
[ "noreply@github.com" ]
eldraco.noreply@github.com
b91cd725562befb469c66d4ce9802baecaa2cf54
e999577db526bdc87ab83d30d393e06f921c2326
/multiagent/multiAgents.py
2dab318ae711f77bae0c426c49a25673c4ad1a2c
[]
no_license
anant-k-singh/Pacman-AI
e4a630de420ad942fef8b0c5ab0d6799859c0737
503730f7baa5fac690cedcd6f65cc592bb7758c3
refs/heads/master
2022-01-22T18:23:32.347366
2019-07-31T17:24:26
2019-07-31T17:24:26
115,016,037
2
0
null
null
null
null
UTF-8
Python
false
false
14,272
py
# multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel (pabbeel@cs.berkeley.edu). from util import manhattanDistance from game import Directions import random, util, sys from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() legalMoves.remove('Stop') # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) # bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] # chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" for i in range(0,len(scores)): if(scores[i] == bestScore): return legalMoves[i] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" # for ghostState in newGhostStates: # print manhattanDistance(newPos, ghostState.getPosition()) # return successorGameState.getScore() foodlist = currentGameState.getFood().asList() distanceToClosestFood = min(map(lambda x: util.manhattanDistance(newPos, x), foodlist)) distanceToClosestGhost = manhattanDistance(newPos, newGhostStates[0].getPosition()) if distanceToClosestGhost == 0: return -50 # print int(-8/distanceToClosestGhost) return -(8/distanceToClosestGhost)-distanceToClosestFood def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gamestate): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" def pacman(gameState, curDepth): if gameState.isWin() or gameState.isLose(): return self.evaluationFunction(gameState) legalMoves = gameState.getLegalActions(0) score = [] for move in legalMoves: nextState = gameState.generateSuccessor(0, move) if nextState.isWin(): return self.evaluationFunction(nextState) score.append( ghost(nextState,curDepth,total_ghosts) ) # print score,"score for pacman @",curDepth return max(score) def ghost(gameState, curDepth, ghost_idx): if curDepth == self.depth or gameState.isWin() or gameState.isLose(): return self.evaluationFunction(gameState) legalMoves = gameState.getLegalActions(ghost_idx) score = [] # Pacman's turn if ghost_idx == 1: for move in legalMoves: nextState = gameState.generateSuccessor(ghost_idx, move) if nextState.isLose(): return self.evaluationFunction(nextState) score.append( pacman(nextState,curDepth+1) ) # next ghost's turn else: for move in legalMoves: nextState = gameState.generateSuccessor(ghost_idx, move) if nextState.isLose(): return self.evaluationFunction(nextState) score.append( ghost(nextState, curDepth, ghost_idx-1) ) # print score,"score for ghost",ghost_idx,"@",curDepth return min(score) bestScore = -9999 bestMove = 'Fail' total_ghosts = gamestate.getNumAgents()-1 legalMoves = gamestate.getLegalActions(0) for move in legalMoves: nextState = gamestate.generateSuccessor(0, move) # if it can win immediately if nextState.isWin(): return move tempScore = ghost(nextState, 1, total_ghosts) if tempScore > bestScore: bestScore = tempScore bestMove = move return bestMove class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gamestate): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" def pacman(gameState, curDepth,A,B): if gameState.isWin() or gameState.isLose(): return self.evaluationFunction(gameState) legalMoves = [action for action in gameState.getLegalActions(0) if action!='Stop'] score = -9999999 for move in legalMoves: nextState = gameState.generateSuccessor(0, move) if nextState.isWin(): return self.evaluationFunction(nextState) score = max(score, ghost(nextState,curDepth,total_ghosts,A,B)) if score > B: return score A = max(A,score) # print score,"score for pacman @",curDepth return score def ghost(gameState, curDepth, ghost_idx,A,B): if curDepth == self.depth or gameState.isWin() or gameState.isLose(): return self.evaluationFunction(gameState) legalMoves = gameState.getLegalActions(ghost_idx) score = 9999999 # Pacman's turn if ghost_idx == 1: for move in legalMoves: nextState = gameState.generateSuccessor(ghost_idx, move) if nextState.isLose(): return self.evaluationFunction(nextState) # score.append( pacman(nextState,curDepth+1) ) score = min(score, pacman(nextState,curDepth+1,A,B)) if score < A: return score B = min(B,score) # next ghost's turn else: for move in legalMoves: nextState = gameState.generateSuccessor(ghost_idx, move) if nextState.isLose(): return self.evaluationFunction(nextState) # score.append( ghost(nextState, curDepth, ghost_idx-1) ) score = min(score, ghost(nextState, curDepth, ghost_idx-1,A,B)) # print score,"score for ghost",ghost_idx,"@",curDepth return score bestScore = -99999999 bestMove = 'Fail' total_ghosts = gamestate.getNumAgents()-1 legalMoves = gamestate.getLegalActions(0) for move in legalMoves: nextState = gamestate.generateSuccessor(0, move) # if it can win immediately if nextState.isWin(): return move tempScore = ghost(nextState, 1, total_ghosts,-9999999,9999999) if tempScore > bestScore: bestScore = tempScore bestMove = move return bestMove class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gamestate): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" def pacman(gameState, curDepth): if gameState.isWin() or gameState.isLose(): return self.evaluationFunction(gameState) legalMoves = [action for action in gameState.getLegalActions(0) if action!='Stop'] score = [] for move in legalMoves: nextState = gameState.generateSuccessor(0, move) if nextState.isWin(): return self.evaluationFunction(nextState) score.append( ghost(nextState,curDepth,total_ghosts) ) # print score,"score for pacman @",curDepth return max(score) def ghost(gameState, curDepth, ghost_idx): if curDepth == self.depth or gameState.isWin() or gameState.isLose(): return self.evaluationFunction(gameState) legalMoves = gameState.getLegalActions(ghost_idx) score = 0 # Pacman's turn if ghost_idx == 1: for move in legalMoves: nextState = gameState.generateSuccessor(ghost_idx, move) if nextState.isLose(): return self.evaluationFunction(nextState) score += pacman(nextState,curDepth+1) # next ghost's turn else: for move in legalMoves: nextState = gameState.generateSuccessor(ghost_idx, move) if nextState.isLose(): return self.evaluationFunction(nextState) score += ghost(nextState, curDepth, ghost_idx-1) # print score,"score for ghost",ghost_idx,"@",curDepth return (score*1.0)/len(legalMoves) bestScore = -999999 bestMove = 'Fail' total_ghosts = gamestate.getNumAgents()-1 legalMoves = gamestate.getLegalActions(0) for move in legalMoves: nextState = gamestate.generateSuccessor(0, move) # if it can win immediately if nextState.isWin(): return move tempScore = ghost(nextState, 1, total_ghosts) if tempScore > bestScore: bestScore = tempScore bestMove = move return bestMove def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: Farther the nearest food higher the score """ "*** YOUR CODE HERE ***" pacmanPos = currentGameState.getPacmanPosition() foodlist = currentGameState.getFood().asList() distanceToClosestFood = min(map(lambda x: util.manhattanDistance(pacmanPos, x), foodlist)) return currentGameState.getScore()+distanceToClosestFood # Abbreviation better = betterEvaluationFunction
[ "anant02sep@gmail.com" ]
anant02sep@gmail.com
c6d6c965204756070013e9e873147cede25d1b53
70fd9545d8f273db2126ac8bb0715c90838fe98b
/polls/serializers.py
42ab6011a5fffa46a4744713a8cd70ab5d82ac49
[]
no_license
Gohstreck/Backend
6fd99e0c304054d6b60e44111b56b3453c78109b
6052e6ffecf3c297d1256f51a695d55b89b3b883
refs/heads/master
2020-04-04T12:52:39.966936
2018-11-12T04:13:20
2018-11-12T04:13:20
155,940,576
0
0
null
2018-11-03T01:58:44
2018-11-03T01:58:44
null
UTF-8
Python
false
false
2,459
py
from rest_framework import serializers from . import models class PersonSerializer(serializers.HyperlinkedModelSerializer): groups = serializers.HyperlinkedRelatedField( many = True, read_only = True, view_name = 'group-detail' ) articles = serializers.HyperlinkedRelatedField( many = True, read_only = True, view_name = 'article-detail' ) class Meta: model = models.Person fields = ('id_person', 'name', 'birthdate', 'mail', 'phone_number', 'articles', 'groups') class InstitutionSerializer(serializers.HyperlinkedModelSerializer): branches = serializers.HyperlinkedRelatedField( many = True, read_only = True, view_name = 'branch-detail' ) class Meta: model = models.Institution fields = ('id_institution', 'name', 'branches') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Group fields = ('id_group', 'name', 'members', 'leader') class BranchSerializer(serializers.HyperlinkedModelSerializer): departments = serializers.HyperlinkedRelatedField( many = True, read_only = True, view_name = 'department-detail' ) class Meta: model = models.Branch fields = ('id_branch', 'institution', 'name', 'departments') class ArticleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Article fields = ('id_article', 'title', 'authors') class DepartmentSerializer(serializers.HyperlinkedModelSerializer): researchers = serializers.HyperlinkedRelatedField( many = True, read_only = True, view_name = 'researcher-detail' ) class Meta: model = models.Department fields = ('id_department', 'name', 'phone_number', 'adress', 'branch', 'researchers') class ResearcherSerializer(serializers.HyperlinkedModelSerializer): students = serializers.HyperlinkedRelatedField( many = True, read_only = True, view_name = 'student-detail' ) leader = serializers.HyperlinkedRelatedField( many = True, read_only = True, view_name = 'researcher-detail' ) class Meta: model = models.Researcher fields = ('id_researcher', 'person', 'department', 'students', 'leader') class StudentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Student fields = ('id_student', 'person', 'supervisor')
[ "equiroz@ciencias.unam.mx" ]
equiroz@ciencias.unam.mx
43ded90cced3f1255adfe6cd098a2966f73fb180
42705b3049418c3dc2815a0262aa814c6a2e3d9e
/feat_eng/funcs.py
dcc248c03ab3520bd17e5e378f3b4fea24b3f0f4
[]
no_license
ppiont/cnn-soc-wagga
617f4a0fecd6ac0b7d6fac2cb7171df9bfbf74a2
5152faf59c38c4b168a1dc9639fa8d13c16a91cd
refs/heads/master
2023-07-11T09:01:08.786970
2021-08-14T12:17:09
2021-08-14T12:17:09
257,276,955
0
0
null
null
null
null
UTF-8
Python
false
false
2,506
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 30 18:32:01 2020. @author: peter """ import numpy as np def min_max(array, axis=(0, 1, 2), rm_no_variance=True): """Min-max scale an array and optionally remove features with no variance. Parameters ---------- array : ndarray Array to be scaled. axis : int or tuple of int, optional The axis or axes along which to scale. The default is (0, 1, 2). Returns ------- ndarray The scaled array. zero_channels_idx : ndarray, depending on `rm_no_variance` The idx of zero variance features/channels that were removed. """ # Compute the mins along the axis x_mins = array.min(axis=axis) # Compute the maxs along hte axis x_maxs = array.max(axis=axis) # Get the difference diff = x_maxs-x_mins if rm_no_variance is True: # Get index of features with no variance (max == min) zero_channels_idx = np.where(diff == 0)[0] # Remove features with no variance array = np.delete(array, zero_channels_idx, -1) diff = np.delete(diff, zero_channels_idx) x_maxs = np.delete(x_maxs, zero_channels_idx) x_mins = np.delete(x_mins, zero_channels_idx) print(f'Removed from axis: {zero_channels_idx}') # Compute and return the array normalized to 0-1 range and # optionally return zero variance indexes return (array-x_mins)/diff, zero_channels_idx else: return (array-x_mins)/diff def crop_center(arr, crop_x, crop_y): """Crop an array, maintaining center.""" if len(arr.shape) == 4 and arr.shape[0] == 1: arr = np.squeeze(arr) y, x, _ = arr.shape start_x = x//2 - crop_x//2 start_y = y//2 - crop_y//2 return arr[start_y:start_y + crop_y, start_x:start_x + crop_x, :] def get_corr_feats(X, min_corr=0.8): """Get indices of correlated features of an array.""" correlated_features = set() correlation_matrix = np.corrcoef(X, rowvar=False) for i in range(correlation_matrix.shape[-1]): for j in range(i): if abs(correlation_matrix[i, j]) > min_corr: correlated_features.add(i) return np.array(list(correlated_features)) def add_min(a): """Add abs(minimum) along whole 1-D array.""" return a + abs(a.min()) if a.min() < 0 else a def safe_log(x): """Apply log transform on all values except x <= 0s.""" x = np.ma.log(x) return x.filled(0)
[ "piontek0@gmail.com" ]
piontek0@gmail.com
4b9670f8ab0b81af5668d3c702c93f533e2797c4
48581671e6fe9f59633aa9527c07d2724783a45c
/backend/Sunshine/api/urls.py
13f6022e5be3c9148cab22057ca78eec281224c2
[]
no_license
suma2001/SeniorSunshine
14fdcf22877c30d3f81d0f159c3b91df91e5bc44
54274d3b2f1a87fcb8926313a32bc4234fe48572
refs/heads/master
2023-02-03T03:24:26.871423
2020-12-11T14:08:02
2020-12-11T14:08:02
320,590,319
0
0
null
null
null
null
UTF-8
Python
false
false
1,661
py
from django.urls import path from .views import * from rest_framework.urlpatterns import format_suffix_patterns from rest_framework.authtoken import views from knox import views as knox_views urlpatterns = [ path('register/', RegisterAPI.as_view(), name='register'), path('login/', LoginAPI.as_view(), name='login'), path('logout/', LogoutAPI.as_view(), name='logout'), path('logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'), path('elderregister/', RegisterElderAPI.as_view(), name='elderregister'), path('elderlogin/', LoginElderAPI.as_view(), name='elderlogin'), path('currentuser/', current_user, name='current_user'), path('token/', views.obtain_auth_token, name='token'), path('services/', ServicesAPIView.as_view(), name ='get_post_services'), path('service/<int:id>/', ServicesDetailsView.as_view(), name='get_delete_update_service'), # path('profiles/', ProfileAPIView.as_view()), # path('profile/<int:id>/', ProfileDetailsView.as_view()), path('elders/',ElderListView.as_view(),name ='get_post_elder_profiles'), path('elder/<int:id>/',ElderDetailView.as_view(),name ='get_delete_update_elder_profile'), path('requestservice/',RequestServiceAPIView.as_view(),name ='get_post_service'), path('feedback/',FeedbackSubmitAPIView.as_view(),name ='get_post_feedback'), path('test_volunteers/',TestVolunteerView.as_view(), name ='get_post_profiles'), path('test_volunteer/<int:id>/',TestVolunteerDetailView.as_view(),name='get_delete_update_profile'), path('custom_users/',UsersAPIView.as_view()), path('volunteers/<int:id>/',GetVolunteers.as_view()) ]
[ "sumashreya.t18@iiits.in" ]
sumashreya.t18@iiits.in
4345a2c669d02154dade74de723eb3affdd3c2a8
07252bc9ce0ba693e8c3cd0ad969ab7e9f336083
/apps/posts/forms.py
d2e808cc4daa9f7550ad748f64978972f26c3e4b
[]
no_license
Bakal1990/project
9f038ae2f821e737ae3cd39e3c4d1efcf8db90e1
3673c621383f8366572b083be203f49074eba55e
refs/heads/master
2020-12-25T19:26:10.888707
2015-02-16T19:31:09
2015-02-16T19:31:09
30,318,392
0
0
null
null
null
null
UTF-8
Python
false
false
455
py
from django import forms from .models import Post from profiles.models import User class LikePostForm(forms.Form): post_id = forms.CharField() user_id = forms.CharField() def clean_post_id(self): post_id = self.cleaned_data.get('post_id') return Post.objects.filter(id=post_id).exists() def clean_user_id(self): user_id = self.cleaned_data.get('user_id') return User.objects.filter(id=user_id).exists()
[ "molotovxiii@gmail.com" ]
molotovxiii@gmail.com
3a79af3088336b15e677b0d3a821806575a98c86
2a466b71eb9f24c58ca6ba52a379870485d19140
/src/cert_scanner/report/progress_graph_generator.py
ff14fd2a750106e8b5427dfc8ef64f1e2832767a
[ "MIT" ]
permissive
kgarwood/digital_certificate_scanner
5df0fb47193f838353a0cadb696d49b8acbf8351
ede1344144fa62349c0076d5618eccfc4131f98f
refs/heads/master
2020-03-30T07:42:53.860968
2018-10-02T16:12:47
2018-10-02T16:12:47
150,961,231
0
0
null
null
null
null
UTF-8
Python
false
false
11,102
py
import cert_scanner.util.file_name_utility as file_name_utility import cert_scanner.util.certificate_scanner_utility as \ certificate_scanner_utility import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.ticker import MultipleLocator import os def generate(original_df, output_directory, expiry_type, expiry_period_field_name, expiry_period_phrase, start_date, end_date, xtick_rotation_angle, show_every_ith_x_label): title_date_phrase = \ "from {} to {}\n({} {} to Week {})".format( start_date.strftime("%d %b %Y"), end_date.strftime("%d %b %Y"), expiry_period_phrase, start_date.strftime("%W %Y"), expiry_period_phrase, end_date.strftime("%W %Y")) # print("generate 11111111111111111111111") # print(original_df.columns.values) # print("generate 22222222222222222222222") __generate_num_certs_graph(original_df, output_directory, expiry_type, expiry_period_field_name, expiry_period_phrase, start_date, end_date, xtick_rotation_angle, show_every_ith_x_label) __generate_num_releases_graph(original_df, output_directory, expiry_type, expiry_period_field_name, expiry_period_phrase, start_date, end_date, xtick_rotation_angle, show_every_ith_x_label) __generate_num_locations_graph(original_df, output_directory, expiry_type, expiry_period_field_name, expiry_period_phrase, start_date, end_date, xtick_rotation_angle, show_every_ith_x_label) def __generate_num_locations_graph(original_df, output_directory, expiry_type, expiry_period_field_name, expiry_period_phrase, start_date, end_date, xtick_rotation_angle, show_every_ith_x_label): title_date_phrase = \ __generate_title_phrase(start_date, end_date, expiry_period_phrase) num_locations_title = \ "Number of Files Containing Expiring Certs\n{}".format( title_date_phrase) period_to_period_phrase = \ __generate_period_to_period_phrase(expiry_type, start_date, end_date, expiry_period_phrase) num_locations_title = \ "Expiring Cert Files {}".format(period_to_period_phrase) date_to_date_phrase = \ certificate_scanner_utility.generate_date_range_phrase(start_date, end_date) ax = original_df.plot.bar(x=expiry_period_field_name, y='total_locations', width=1.0, rot=0) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) ax.tick_params(labelsize=6) legend = ax.legend() legend.remove() plt.xlabel('xlabel', fontsize=10) plt.ylabel('ylabel', fontsize=10) plt.suptitle(num_locations_title, fontsize=14) plt.title(date_to_date_phrase, fontsize=10) ith_label = 0 for label in ax.xaxis.get_ticklabels(): label.set_visible(False) for label in ax.xaxis.get_ticklabels()[::show_every_ith_x_label]: label.set_visible(True) plt.setp(ax.get_xticklabels(), rotation=xtick_rotation_angle, horizontalalignment='center') plt.xlabel('Expiry {}'.format(expiry_period_phrase)) plt.ylabel('Total Files') base_file_name = "total_{}_locations".format(expiry_type) file_name = \ file_name_utility.get_time_range_file_name(base_file_name, None, start_date, end_date, "png") output_file_path = os.path.join(output_directory, file_name) plt.savefig(output_file_path) def __generate_num_certs_graph(original_df, output_directory, expiry_type, expiry_period_field_name, expiry_period_phrase, start_date, end_date, xtick_rotation_angle, show_every_ith_x_label): period_to_period_phrase = \ __generate_period_to_period_phrase(expiry_type, start_date, end_date, expiry_period_phrase) num_certs_title = \ "Expiring Cert Records {}".format(period_to_period_phrase) date_to_date_phrase = \ certificate_scanner_utility.generate_date_range_phrase(start_date, end_date) ax = original_df.plot.bar(x=expiry_period_field_name, y='total_expiring_certs', width=1.0, rot=0) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) legend = ax.legend() legend.remove() ax.tick_params(labelsize=6) plt.xlabel('xlabel', fontsize=12) plt.ylabel('ylabel', fontsize=12) plt.suptitle(num_certs_title, fontsize=14) plt.title(date_to_date_phrase, fontsize=10) ith_label = 0 for label in ax.xaxis.get_ticklabels(): label.set_visible(False) for label in ax.xaxis.get_ticklabels()[::show_every_ith_x_label]: label.set_visible(True) plt.setp(ax.get_xticklabels(), rotation=xtick_rotation_angle, horizontalalignment='center') plt.xlabel('Expiry {}'.format(expiry_period_phrase)) plt.ylabel('Total Certificates') base_file_name = "total_{}_certs".format(expiry_type) file_name = \ file_name_utility.get_time_range_file_name(base_file_name, None, start_date, end_date, "png") output_file_path = os.path.join(output_directory, file_name) plt.savefig(output_file_path) def __generate_num_releases_graph(original_df, output_directory, expiry_type, expiry_period_field_name, expiry_period_phrase, start_date, end_date, xtick_rotation_angle, show_every_ith_x_label): period_to_period_phrase = \ __generate_period_to_period_phrase(expiry_type, start_date, end_date, expiry_period_phrase) num_releases_title = \ "Expiring Cert Releases {}".format(period_to_period_phrase) date_to_date_phrase = \ certificate_scanner_utility.generate_date_range_phrase(start_date, end_date) ax = \ original_df.plot.bar(x=expiry_period_field_name, y='total_releases', width=1.0, rot=0) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) ax.tick_params(labelsize=6) legend = ax.legend() legend.remove() plt.xlabel('xlabel', fontsize=12) plt.ylabel('ylabel', fontsize=12) plt.suptitle(num_releases_title, fontsize=14) plt.title(date_to_date_phrase, fontsize=10) ith_label = 0 for label in ax.xaxis.get_ticklabels(): label.set_visible(False) for label in ax.xaxis.get_ticklabels()[::show_every_ith_x_label]: label.set_visible(True) plt.setp(ax.get_xticklabels(), rotation=xtick_rotation_angle, horizontalalignment='center') plt.xlabel('Expiry {}'.format(expiry_period_phrase)) plt.ylabel('Total Releases') base_file_name = "total_{}_releases".format(expiry_type) file_name = \ file_name_utility.get_time_range_file_name(base_file_name, None, start_date, end_date, "png") output_file_path = os.path.join(output_directory, file_name) plt.savefig(output_file_path) def __generate_title_phrase(start_date, end_date, expiry_period_phrase): title_date_phrase = \ "from {} to {}\n({} {} to Week {})".format( start_date.strftime("%d %b %Y"), end_date.strftime("%d %b %Y"), expiry_period_phrase, start_date.strftime("%W %Y"), expiry_period_phrase, end_date.strftime("%W %Y")) return title_date_phrase def __generate_period_to_period_phrase(expiry_type, start_date, end_date, expiry_period_phrase): if expiry_type == 'monthly': return "({} to {})".format( start_date.strftime("%b %Y"), end_date.strftime("%b %Y")) else: return "(Week {} to Week {})".format( start_date.strftime("%W %Y"), end_date.strftime("%W %Y")) def __generate_date_range_phrase(period_phrase, start_date, end_date): return "from {} to {}\n({} {} to {} {})".format( start_date.strftime("%d %b %Y"), end_date.strftime("%d %b %Y"), period_phrase, start_date.strftime("%W %Y"), period_phrase, end_date.strftime("%W %Y"))
[ "kevin.garwood@digital.cabinet-office.gov.uk" ]
kevin.garwood@digital.cabinet-office.gov.uk
d23876d3a93f905357e7be2a1449341ef64f86a7
f4718efa9d34fabad15f1b4ef856c4639eb6e718
/Test.py
0f3fceb541fd26b23c09661bee50a64c921d957e
[]
no_license
wilee1224/Data_wrangling
98faa7428da2ec28dba5ad524d811bfadaf2db2b
ba4d88a987a38a4c1850f2954073d423300f1652
refs/heads/master
2020-03-12T04:14:49.194795
2018-08-06T12:24:57
2018-08-06T12:24:57
130,441,245
0
0
null
null
null
null
UTF-8
Python
false
false
127
py
import xlrd book = xlrd.open_workbook("SOWC 2014 Stat Tables_Table 9.xlsx") for sheet in book.sheets(): print sheet.name
[ "wilee1224@gmail.com" ]
wilee1224@gmail.com
2ca4b0788bfc54be10e712eabe0884ac23c7bf0a
ba9d6e33133709eb8ef9c643e50646596f8ab98b
/homeworks/hole_detection.py
79f5583093614b7b290b86aac89e248e3a1b6e74
[]
no_license
otniel/computer-vision
2eb5588d7662ada0999001083e5562e3c3e69fd1
82430fd60c21d3f6c6609b429b051b25526b0102
refs/heads/master
2021-01-25T07:07:51.592712
2015-05-18T17:29:10
2015-05-18T17:29:10
29,542,857
1
0
null
null
null
null
UTF-8
Python
false
false
2,639
py
import Image import numpy as np import matplotlib.pyplot as plt from scipy.signal import argrelextrema from utils.tools import normalize_rgb_image, normalize_grayscale_image from utils.detect_peaks import detect_peaks class HoleDetection: def __init__(self, image): self.image = normalize_rgb_image(image) self.pixels = self.image.load() self.width, self.height = self.image.size def smooth_list(self, the_list, width): smoothed_list = [] for index, value in enumerate(the_list): window = the_list[max(0, index-1):min(index+width, len(the_list))] new_value = int(sum(window) / len(window)) smoothed_list.append(new_value) return smoothed_list def detect_holes(self): horizontal_histogram = self.get_horizontal_histogram() vertical_histogram = self.get_vertical_histogram() smoothed_horizontal = self.smooth_list(horizontal_histogram, 5) smoothed_horizontal = self.smooth_list(smoothed_horizontal, 5) smoothed_horizontal = self.smooth_list(smoothed_horizontal, 5) smoothed_vertical = self.smooth_list(vertical_histogram, 5) smoothed_vertical = self.smooth_list(smoothed_vertical, 5) smoothed_vertical = self.smooth_list(smoothed_vertical, 5) horizontal_candidates = (np.gradient(np.sign(np.gradient(np.array(smoothed_horizontal)))) > 0).nonzero()[0] vertical_candidates = (np.gradient(np.sign(np.gradient(np.array(smoothed_vertical)))) > 0).nonzero()[0] # Drawing candidates for y in xrange(self.height): for x in horizontal_candidates: self.pixels[x, y] = (255, 0, 0) for x in xrange(self.width): for y in vertical_candidates: self.pixels[x, y] = (0, 0, 255) self.image.save('../test-images/holes_intersection.png') def get_horizontal_histogram(self): horizontal_histogram = [] for x in range(self.width): total_row = 0 for y in range(self.height): total_row += self.pixels[x, y][0] horizontal_histogram.append(total_row / self.height) return horizontal_histogram def get_vertical_histogram(self): vertical_histogram = [] for y in range(self.height): total_column = 0 for x in range(self.width): total_column += self.pixels[x, y][0] vertical_histogram.append(total_column / self.width) return vertical_histogram image = Image.open('../test-images/holes.png') hd = HoleDetection(image) hd.detect_holes()
[ "otnieel.aguilar@gmail.com" ]
otnieel.aguilar@gmail.com
f024098d382063eb23c1aa5ac661a60dd1e56307
0556e11758ec9a632d4b1406be1597c6900aa93d
/tutorials/tutorial05/05_SPDE_on_fenics_solver.py
99cad0868dac1a4b573f149230b8cc61853a6a92
[ "MIT" ]
permissive
mtezzele/ATHENA
85b5f1dd44180314ab9548a7cac054ca8a77b9df
d8f48680e035a4d51d51c1883932b46fd0bd8da8
refs/heads/master
2023-05-30T10:53:27.722329
2023-04-27T22:05:40
2023-04-27T22:05:40
226,117,142
0
0
null
2019-12-05T14:10:57
2019-12-05T14:10:56
null
UTF-8
Python
false
false
5,930
py
from dolfin import * import matplotlib.pyplot as plt import numpy as np import sys import os from pathlib import Path import warnings warnings.filterwarnings('ignore') def compute_mesh_map(mesh, dim): m_map = np.zeros((dim, 2)) for j, cell in enumerate(cells(mesh)): m_map[j, :] = cell.midpoint().array()[:2] # print(m_map.shape) return m_map def compute_cov(mesh, beta, dim, mesh_map): print("start covariance assemble") cov = np.zeros((dim, dim)) for i in range(dim): for j in range(i, dim): cov[j, i] = cov[i, j] = np.exp( -(np.linalg.norm(mesh_map[i, :] - mesh_map[j, :], 1)) / (beta)) print("end covariance assemble") evals, evecs = np.linalg.eig(cov) E = (evals[:m] * evecs[:, :m]).T return cov, E def set_conductivity(sim_index, mesh, c): # print("set conductivity") D = FunctionSpace(mesh, "DG", 0) kappa = Function(D) dm = D.dofmap() for i, cell in enumerate(cells(mesh)): kappa.vector()[dm.cell_dofs(cell.index())] = np.exp(c[sim_index, i]) return kappa def boundary(x): return x[1] < DOLFIN_EPS or x[1] > 1.0 - DOLFIN_EPS def boundary0(x): return x[0] < DOLFIN_EPS def compute_solution(sim_index, mesh, kappa, pl=False): # print("compute solution") V = FunctionSpace(mesh, "Lagrange", 1) u0 = Expression("10*x[1]*(1-x[1])", degree=0) bc = DirichletBC(V, Constant(0.0), boundary) bc0 = DirichletBC(V, u0, boundary0) u = TrialFunction(V) v = TestFunction(V) f = Constant( 1.0 ) #Expression("exp( - 2*pow(x[0]-0.5, 2) - 2*pow(x[1]-0.5, 2) )", element=V.ufl_element()) a = kappa * inner(grad(u), grad(v)) * dx L = f * v * dx u = Function(V) solve(a == L, u, [bc, bc0]) if pl: u_pl = plot(u, title='u') plt.colorbar(u_pl) plt.show() return u def restrict(mesh, v): # print("restrict on outflow right side") Right = AutoSubDomain(lambda x, on_bnd: near(x[0], 1) and on_bnd) V = FunctionSpace(mesh, 'CG', 1) bc0 = DirichletBC(V, 1, Right) u = Function(V) bc0.apply(u.vector()) v_restriction = v.vector()[u.vector() == 1] return v_restriction.mean() def compute_gradients(component_index, mesh, kappa, E, boundary, cache, solution, pl=False): # print("compute gradient") V = FunctionSpace(mesh, "Lagrange", 1) bc = DirichletBC(V, Constant(0.0), boundary) w = TrialFunction(V) v = TestFunction(V) a = kappa * inner(grad(w), grad(v)) * dx D = FunctionSpace(mesh, "DG", 0) dkappa = Function(D) dm = D.dofmap() for i, cell in enumerate(cells(mesh)): dkappa.vector()[dm.cell_dofs( cell.index())] = kappa.vector()[dm.cell_dofs( cell.index())] * E[component_index, i] rhs = dkappa * inner(grad(solution), grad(v)) * dx w = Function(V) solve(a == rhs, w, bc) if pl: w_pl = plot(w, title='w') plt.colorbar(w_pl) plt.show() return w def show_mode(mode, mesh): c = MeshFunction("double", mesh, 2) # value = mode.dot(E) # Iterate over mesh and set values for i, cell in enumerate(cells(mesh)): c[cell] = mode[i] #np.exp(value[i]) plot(c) plt.show() # Read mesh from file and create function space mesh = Mesh("data/mesh.xml") #dim = 6668 #mesh_2 dim = 3194 m = 10 M = 500 d = 1668 cache = np.zeros((d, m)) cache_res = np.zeros(m) #choose lengthscale beta = 0.015 #beta=0.03 inputs = np.random.multivariate_normal(np.zeros(m), np.eye(m), M) #samples np.save("data/inputs", inputs) #covariance modes assemble m_map = compute_mesh_map(mesh, dim) cov, E = compute_cov(mesh, beta, dim, m_map) c = inputs.dot(E) np.save("data/covariance", cov) np.save("data/cov_modes", E) print("Karhunen-Loève mode shape", E.shape) n = 2 print("Mode number {} of Karhunen-Loève decomposition".format(n)) show_mode(E[n, :], mesh) # cov = np.load("data/covariance.npy", allow_pickle=True) # E = np.load("data/cov_modes.npy", allow_pickle=True) V = FunctionSpace(mesh, "Lagrange", 1) dofs = V.dofmap().dofs() # Get coordinates as len(dofs) x gdim array dim = V.dim() N = mesh.geometry().dim() dofs_x = V.tabulate_dof_coordinates() n_dof = 300 print("Coordinates of degree of freedom number {0} are {1}".format( n_dof, dofs_x[n_dof])) mesh = Mesh("data/mesh.xml") V = FunctionSpace(mesh, "Lagrange", 1) u = Function(V) print(np.array(u.vector()[:]).shape) for j in range(16): for i in range(1668): if i == (j + 1) * 100: u.vector()[i] = 1 else: u.vector()[i] = 0 plot(u, title='dof {}'.format((1 + j) * 100)) plt.savefig('data/component_{}.png'.format((1 + j) * 100)) for it in range(M): print("Solution number :", it) #set conductivity kappa = set_conductivity(it, mesh, c) #plot(kappa) #plt.show() #compute solution u = compute_solution(it, mesh, kappa, pl=False) #pl=True to plot u_res = restrict(mesh, u) #print("mean of the solution restricted on the outflow (right side)", u_res) #compute gradients for j in range(m): #print("Evaluating gradient component number :", j) du = compute_gradients(j, mesh, kappa, E, boundary, cache, u) du_res = restrict(mesh, du) cache[:, j] = du.vector()[:] cache_res[j] = du_res file = Path("data/outputs.npy") with file.open('ab') as f: np.save(f, u.vector()[:]) file = Path("data/outputs_res.npy") with file.open('ab') as f: np.save(f, u_res) file = Path("data/gradients.npy") with file.open('ab') as f: np.save(f, cache) file = Path("data/gradients_res.npy") with file.open('ab') as f: np.save(f, cache_res)
[ "francesco.romor@gmail.com" ]
francesco.romor@gmail.com
4acf925d2f474e88d0b195933e8e7df31a2aa765
9446feb2a94486ac16c585f712dbcbea7d112a9d
/src/taskmaster/cli/master.py
b78926059cf4a36ee7d184b223ba2326de9179e4
[ "Apache-2.0" ]
permissive
jdunck/taskmaster
c16c879a546dd2ac383f804788e2d8ae2606abd1
04a03bf0853facf318ce98192db6389cdaaefe3c
refs/heads/master
2023-08-23T19:29:22.605052
2012-05-16T00:52:24
2012-05-16T00:52:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
958
py
""" taskmaster.cli.master ~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 DISQUS. :license: Apache License 2.0, see LICENSE for more details. """ def run(target, reset=False, size=10000, address='tcp://0.0.0.0:3050'): from taskmaster.server import Server, Controller server = Server(address, size=size) controller = Controller(server, target) if reset: controller.reset() controller.start() def main(): import optparse import sys parser = optparse.OptionParser() parser.add_option("--address", dest="address", default='tcp://127.0.0.1:3050') parser.add_option("--size", dest="size", default='10000', type=int) parser.add_option("--reset", dest="reset", default=False, action='store_true') (options, args) = parser.parse_args() if len(args) != 1: print 'Usage: tm-master <callback>' sys.exit(1) sys.exit(run(args[0], **options.__dict__)) if __name__ == '__main__': main()
[ "dcramer@gmail.com" ]
dcramer@gmail.com
dac71081393db6a981bf3c583d5697793ad0de22
24ce8e56cd54c93c5a285089acb1825132e9e2eb
/495.TeemoAttacking/teemoattacking.py
ebdaf083b15431291215be7042244143c3ef7706
[]
no_license
mayuripatil07/LeetCode
6c7d2148e05fe2c086412d38a7cb71e6e74eee87
4617b11d9487385522ba665ca34b378659afe02c
refs/heads/master
2023-01-13T11:03:49.805792
2020-11-01T21:41:59
2020-11-01T21:41:59
261,207,306
0
0
null
null
null
null
UTF-8
Python
false
false
729
py
class Solution: def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int: if not timeSeries: return 0 poison_time = timeSeries[0] + duration poison_condition = duration for i in range(1,len(timeSeries)): if poison_time <= timeSeries[i]: poison_condition += duration poison_time = timeSeries[i] + duration elif poison_time > timeSeries[i]: diff = poison_time - timeSeries[i] add_time = duration - diff if diff <= duration: poison_condition += add_time poison_time = timeSeries[i] + duration return poison_condition
[ "mpatil7@binghamton.edu" ]
mpatil7@binghamton.edu
2d399e7009cc07f480db636304e56d03c3aa52d9
32d4cbfce0edf448e5c6518a3dc5fb7a27d74b88
/build/lib/malaria/study_sites/SugungumAgeSeasonCalibSiteBabies.py
d572d77d05d0948e88dbcdb4bceecce749917500
[]
no_license
bertozzivill/dtk-tools-malaria-old
7458164f35452d3ede99d03d709197a7108366ba
9aef758261b67c0b06520d8b74b7a9da537448fc
refs/heads/master
2020-03-24T19:24:02.338717
2018-12-17T21:53:21
2018-12-17T21:53:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,717
py
import logging import os import numpy as np from calibtool.analyzers.Helpers import season_channel_age_density_csv_to_pandas from calibtool.study_sites.site_setup_functions import \ config_setup_fn, summary_report_fn, add_treatment_fn, site_input_eir_fn from calibtool.study_sites.DensityCalibSite import DensityCalibSite logger = logging.getLogger(__name__) class SugungumAgeSeasonCalibSiteBabies(DensityCalibSite): metadata = { 'parasitemia_bins': [0.0, 16.0, 70.0, 409.0, np.inf], # (, 0] (0, 16] ... (409, inf] 'age_bins': [0, 1, 4, 8, 18, 28, 43, np.inf], # (, 1] (1, 4] ... (43, inf], 'seasons': ['DC2', 'DH2', 'W2'], 'seasons_by_month': { 'May': 'DH2', 'September': 'W2', 'January': 'DC2' }, 'village': 'Matsari' } def get_reference_data(self, reference_type): super(SugungumAgeSeasonCalibSiteBabies, self).get_reference_data(reference_type) # Load the Parasitology CSV dir_path = os.path.dirname(os.path.realpath(__file__)) reference_csv = os.path.join(dir_path, 'inputs', 'GarkiDB_data', 'GarkiDBparasitology.csv') reference_data = season_channel_age_density_csv_to_pandas(reference_csv, self.metadata).reset_index() reference_data = (reference_data[reference_data['Age Bin'] == 1.0]).set_index( ['Channel', 'Season', 'Age Bin', 'PfPR Bin']) return reference_data def get_setup_functions(self): setup_fns = super(SugungumAgeSeasonCalibSiteBabies, self).get_setup_functions() setup_fns.append(config_setup_fn(duration=365 * 2)) # 60 years (with leap years) setup_fns.append(summary_report_fn(start=365, interval=365.0 / 12, description='Monthly_Report', parasitemia_bins=[0.0, 16.0, 70.0, 409.0, 4000000.0], age_bins=[1.0, 4.0, 8.0, 18.0, 28.0, 43.0, 400000.0])) setup_fns.append(site_input_eir_fn(self.name, birth_cohort=True)) setup_fns.append(lambda cb: cb.update_params( {'Demographics_Filenames': ['Calibration\\birth_cohort_demographics_babies.json'], 'Age_Initialization_Distribution_Type': 'DISTRIBUTION_SIMPLE', 'Base_Population_Scale_Factor': 10, 'Birth_Rate_Dependence': 'FIXED_BIRTH_RATE', "Death_Rate_Dependence": "NONDISEASE_MORTALITY_OFF", 'Enable_Birth': 1, 'Enable_Vital_Dynamics': 1, 'Maternal_Antibodies_Type': 'SIMPLE_WANING', })) return setup_fns def __init__(self): super(SugungumAgeSeasonCalibSiteBabies, self).__init__('Sugungum_babies')
[ "jsuresh@idmod.org" ]
jsuresh@idmod.org
2e9f65cb125310604066c976eeca51526b77e980
4b226dfa9c17da6bab4c2e1831de057b049a7919
/monitoring/availability.py
17860d236749fd6a9fab47a417a837db94250c16
[]
no_license
eea/inspire.harvest.feasibility.tools
616070cff9608c09bb3543be711e7d66152c17a5
b4994db8bd02ccfc2c5d5bf9fe5c8efbfda55bc3
refs/heads/master
2023-08-01T06:27:52.888886
2018-11-15T16:09:17
2018-11-15T16:09:17
142,995,171
1
0
null
null
null
null
UTF-8
Python
false
false
3,446
py
import logging import csv from datetime import datetime import pytz import requests from monitoring.common import HTTPCheckResult, Monitor, get_service_urls logger = logging.getLogger("availability_check") info, debug, error = logger.info, logger.debug, logger.error def check_availability(url, url_id, output_path, csv_write_lock, timeout): """ Checks the availability of a URL, and appends the result to a CSV file. URL's are verified using a streaming GET request - the connection is severed once the headers are received, to avoid impacting services with a sizeable response content size. Parameters: url(str) : The URL to check url_id(int) : The is written to file instead of the URL, for correlation. output_path(str): The path of the CSV file to append the results to. csv_write_lock (threading.Lock): Lock for writing to CSV. timeout(float): The timeout in seconds for the GET requests - if `None`, defaults to `DEFAULT_CHECK_INTERVAL`. """ info(f"Checking {url}") try: with requests.get(url, timeout=timeout, stream=True) as r: try: content_length = int(r.headers["Content-Length"]) except (KeyError, ValueError): content_length = None result = HTTPCheckResult( status_code=r.status_code, content_length=content_length, content_type=r.headers.get("Content-Type"), duration=r.elapsed.total_seconds(), last_modified=r.headers.get("Last-Modified"), ) except requests.exceptions.Timeout: result = HTTPCheckResult(timeout=True) except requests.exceptions.ConnectionError: result = HTTPCheckResult(connection_error=True) with csv_write_lock: with open(output_path, "a") as f: w = csv.writer(f, delimiter="\t") w.writerow( [ datetime.now(pytz.UTC).isoformat(), url_id, result.status_code, result.content_length, result.content_type, result.duration, result.last_modified, 1 if result.timeout else 0, 1 if result.connection_error else 0, ] ) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser( description="Run the INSPIRE endpoints availability monitor" ) parser.add_argument("--endpoints-csv", help="Path to CSV with endpoint URL's") parser.add_argument("--output", help="Path to monitoring output file") parser.add_argument( "--urls-col-no", default=0, type=int, help="URL's column number in the CSV file" ) parser.add_argument( "--check-interval", default=300, type=int, help="Interval to check every endpoint at, in seconds. Defaults to 5 min.", ) args = parser.parse_args() logging.basicConfig(level=logging.INFO, format="%(message)s") logging.getLogger("schedule").setLevel(logging.WARNING) urls = get_service_urls(args.endpoints_csv, col_no=args.urls_col_no) monitor = Monitor( service_urls=urls, check_func=check_availability, output_path=args.output, check_interval=args.check_interval, ) monitor.run()
[ "andrei@duhnea.net" ]
andrei@duhnea.net
2917ef2371964c06a2bedd3acf1b8cd301c7a4b7
216fe95ca1d92c6071155cf59c36789edcb27123
/languageBot/messengerBot/urls.py
f6e9f82f5d5d8ff77f08b523aed294744dc7ad97
[ "MIT" ]
permissive
singhvisha/LanguageBot
16b5b153e55b432bfa108a7add5a087b38af7722
9cef316bceb2f6951863af2fa869398fb5242519
refs/heads/master
2023-05-31T11:26:41.773724
2020-07-12T17:49:15
2020-07-12T17:49:15
279,117,273
0
0
MIT
2021-06-10T23:09:31
2020-07-12T17:46:28
Python
UTF-8
Python
false
false
192
py
from django.conf.urls import include, url from .views import messengerBotView urlpatterns = [ url(r'^21975e0a3c7ab17aa37124158bbda569af363d15eacb576e06/?$', messengerBotView.as_view()), ]
[ "vishalsingh600700@gmail.com" ]
vishalsingh600700@gmail.com
40115813710fb922b4615d58c11ab7d51905be62
9de9beaf657bf3d5967997b301753c3d1cd03d51
/2. SLAE/errors/errors.py
925669e7fe86341252a64bbc1bc78c60a59c5b8c
[]
no_license
karmapolice-0/Numerical-things
e87116b86c52b63424137f72ae079c3a48a7154b
41852fb84fed71a0a5673eaa977a476b95733e59
refs/heads/master
2021-05-18T19:35:04.576327
2020-04-04T19:59:14
2020-04-04T19:59:14
251,380,982
0
0
null
null
null
null
UTF-8
Python
false
false
1,462
py
class MatrixError(Exception): def __init__(self, msg=""): self.message = msg def __str__(self): return self.message class DimensionError(MatrixError): def __init__(self, err, *args): self.message = err class NotListOrTuple(MatrixError): def __init__(self, err, *args): self.message = f"Given value should be a list or a tuple, not '{type(err).__name__}'"+". ".join(args) class EmptyMatrix(MatrixError): def __init__(self, err, *args): self.message = str(err).join(args) class InvalidIndex(MatrixError): def __init__(self, err, *args): self.message = f"'{type(err).__name__}' type index '{err}' can't be used as a row index. "+". ".join(args) class InvalidColumn(MatrixError): def __init__(self, err, *args): self.message = f"'{type(err).__name__}' type index '{err}' can't be used as a column index. "+". ".join(args) class FillError(MatrixError): def __init__(self, err, *args): self.message = f"'{type(err).__name__}' type '{err}' can't be used to fill matrices. "+". ".join(args) class OutOfRangeList(MatrixError): def __init__(self, lis, r, *args): self.message = f"Given {lis} should have values in range {r} \n"+". ".join(args) class ParameterError(MatrixError): def __init__(self, err, params, *args): self.message = f"'{err}' isn't a valid parameter name. \nAvailable parameter names:\n\t{params}. "+". ".join(args)
[ "akselivj@gmail.com" ]
akselivj@gmail.com
fdf8d0c74a52e8f39d8f597575a9abaa39184b7d
31996e49289655f60b71ed176cc94e32648ffe40
/criterion.py
3354fd91fc4305af5fdb94aa158db4645a80560f
[]
no_license
Will3577/MultitaskOCTA
064fe7d437fe4a234653f4e5ba50faccc6f4bfb6
b6719e10318421bc841daf66468c52066bec0f7a
refs/heads/master
2023-06-24T06:59:05.763417
2021-07-13T09:05:55
2021-07-13T09:05:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
17,651
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 14 10:40:54 2019 @author: wujon """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import surface_distance # import nibabel as ni import scipy.io import scipy.spatial import xlwt import os import cv2 from skimage import morphology from skimage.morphology import thin from sklearn.metrics import confusion_matrix, jaccard_score, f1_score os.chdir('./') predictName = 'cotrain_192_pad' predictPath = './smp/' + predictName + '/' labelPath = "./smp/mask_ori_f1/" name_experiment = 'exp_test' path_experiment = './' + name_experiment + '/' # labelPath = "./gt/" # outpredictPath = "./gt_poor_o_thin/" # outlabelPath = "./gt_o_thin/" def getDSC(testImage, resultImage): """Compute the Dice Similarity Coefficient.""" testArray = testImage.flatten() resultArray = resultImage.flatten() return 1.0 - scipy.spatial.distance.dice(testArray, resultArray) def getJaccard(testImage, resultImage): """Compute the Dice Similarity Coefficient.""" testArray = testImage.flatten() resultArray = resultImage.flatten() return 1.0 - scipy.spatial.distance.jaccard(testArray, resultArray) def getPrecisionAndRecall(testImage, resultImage): testArray = testImage.flatten() resultArray = resultImage.flatten() TP = np.sum(testArray*resultArray) FP = np.sum((1-testArray)*resultArray) FN = np.sum(testArray*(1-resultArray)) precision = TP/(TP+FP) recall = TP/(TP+FN) return precision, recall def intersection(testImage, resultImage): testSkel = morphology.skeletonize(testImage) testSkel = testSkel.astype(int) resultSkel = morphology.skeletonize(resultImage) resultSkel = resultSkel.astype(int) testArray = testImage.flatten() resultArray = resultImage.flatten() testSkel = testSkel.flatten() resultSkel = resultSkel.flatten() recall = np.sum(resultSkel * testArray) / (np.sum(testSkel)) precision = np.sum(resultArray * testSkel) / (np.sum(testSkel)) intersection = 2 * precision * recall / (precision + recall) return intersection if __name__ == "__main__": labelList = os.listdir(labelPath) # labelList.sort(key = lambda x: int(x[:-4])) img_nums = len(labelList) Q1 = [] Q2 = [] Q3 = [] Q4 = [] Q5 = [] Q6 = [] Q7 = [] Q8 = [] Q9 = [] Q10 = [] Q11 = [] Q12 = [] Q13 = [] Q14 = [] Q15 = [] Q16 = [] Q17 = [] book = xlwt.Workbook(encoding='utf-8', style_compression=0) sheet = book.add_sheet('mysheet', cell_overwrite_ok=True) row_num = 0 sheet.write(row_num, 0, 'CaseName') sheet.write(row_num, 1, 'DSC') sheet.write(row_num, 2, 'Pre') sheet.write(row_num, 3, 'Recall') sheet.write(row_num, 4, 'HD') sheet.write(row_num, 5, 'ASSD') sheet.write(row_num, 6, 'surface_dice_0') sheet.write(row_num, 7, 'rel_overlap_gt') sheet.write(row_num, 8, 'rel_overlap_pred') sheet.write(row_num, 9, 'intersec') sheet.write(row_num, 10, 'HD_thin') sheet.write(row_num, 11, 'ASSD_thin') sheet.write(row_num, 12, 'surface_dice_1') sheet.write(row_num, 13, 'surface_dice_2') sheet.write(row_num, 14, 'Jaccard') sheet.write(row_num, 15, 'acc') sheet.write(row_num, 16, 'spe') sheet.write(row_num, 17, 'sen') for idx, filename in enumerate(labelList): label = cv2.imread(labelPath + filename, 0) # print (label.dtype) # label = cv2.imread(labelPath + filename) label[label < 50] = 0 label[label >= 50] = 1 thinned_label = thin(label) # cv2.imwrite(outlabelPath+filename,(thinned_label*255).astype(np.uint8)) # ret,label = cv2.threshold(label,127,255,cv2.THRESH_BINARY) predict = cv2.imread(predictPath + filename.replace('_manual.png', '_expert.png'), 0) # print(predictPath + filename) # print (predict.dtype) # ret,predict = cv2.threshold(predict,127,255,cv2.THRESH_BINARY) # predict = cv2.imread(predictPath + filename) # predict = predict / 255 predict[predict < 127] = 0 predict[predict >= 127] = 1 # ============================================================================================================================================================================== y_scores = cv2.imread(predictPath + filename.replace('_manual.png', '_expert.png'), 0) # ##################################################################### y_scores = np.asarray(y_scores.flatten())/255. y_scores = y_scores[:, np.newaxis] # print(y_scores.shape) y_true = cv2.imread(labelPath + filename, 0) y_true = np.asarray(y_true.flatten())/255. # fpr, tpr, thresholds = roc_curve((y_true), y_scores) # AUC_ROC = roc_auc_score(y_true, y_scores) # # test_integral = np.trapz(tpr,fpr) #trapz is numpy integration # print ("\nArea under the ROC curve: " +str(AUC_ROC)) # roc_curve =plt.figure() # plt.plot(fpr,tpr,'-',label='Area Under the Curve (AUC = %0.4f)' % AUC_ROC) # plt.title('ROC curve') # plt.xlabel("FPR (False Positive Rate)") # plt.ylabel("TPR (True Positive Rate)") # plt.legend(loc="lower right") # plt.savefig(path_experiment+"ROC.png") # precision, recall, thresholds = precision_recall_curve(y_true, y_scores) # precision = np.fliplr([precision])[0] #so the array is increasing (you won't get negative AUC) # recall = np.fliplr([recall])[0] #so the array is increasing (you won't get negative AUC) # AUC_prec_rec = np.trapz(precision,recall) # print ("\nArea under Precision-Recall curve: " +str(AUC_prec_rec)) # prec_rec_curve = plt.figure() # plt.plot(recall,precision,'-',label='Area Under the Curve (AUC = %0.4f)' % AUC_prec_rec) # plt.title('Precision - Recall curve') # plt.xlabel("Recall") # plt.ylabel("Precision") # plt.legend(loc="lower right") # plt.savefig(path_experiment+"Precision_recall.png") # def best_f1_threshold(precision, recall, thresholds): # best_f1=-1 # for index in range(len(precision)): # curr_f1=2.*precision[index]*recall[index]/(precision[index]+recall[index]) # if best_f1<curr_f1: # best_f1=curr_f1 # best_threshold=thresholds[index] # return best_f1, best_threshold # best_f1, best_threshold = best_f1_threshold(precision, recall, thresholds) # print("\nthresholds: " + str(thresholds)) # print("\nbest_f1: " + str(best_f1)) # print("\nbest_threshold: " + str(best_threshold)) # Confusion matrix threshold_confusion = 0.5 # print ("\nConfusion matrix: Custom threshold (for positive) of " +str(threshold_confusion)) y_pred = np.empty((y_scores.shape[0])) # print(y_scores.shape[0]) # print(np.unique(y_pred)) for i in range(y_scores.shape[0]): if y_scores[i] >= threshold_confusion: y_pred[i] = 1 else: y_pred[i] = 0 # print(np.unique(y_pred)) # print(np.unique(y_true)) confusion = confusion_matrix(y_true, y_pred) # print (confusion) accuracy = 0 if float(np.sum(confusion)) != 0: accuracy = float(confusion[0, 0]+confusion[1, 1])/float(np.sum(confusion)) # print ("Global Accuracy: " +str(accuracy)) specificity = 0 if float(confusion[0, 0]+confusion[0, 1]) != 0: # 00 tn 11 tp 10 fn 01 fp specificity = float(confusion[0, 0])/float(confusion[0, 0]+confusion[0, 1]) # print ("Specificity: " +str(specificity)) sensitivity = 0 if float(confusion[1, 1]+confusion[1, 0]) != 0: sensitivity = float(confusion[1, 1])/float(confusion[1, 1]+confusion[1, 0]) # print ("Sensitivity: " +str(sensitivity)) precision = 0 if float(confusion[1, 1]+confusion[0, 1]) != 0: precision = float(confusion[1, 1])/float(confusion[1, 1]+confusion[0, 1]) # print ("Precision: " +str(precision)) if float(confusion[1, 1]+confusion[0, 1]) != 0: PPV = float(confusion[1, 1])/float(confusion[1, 1]+confusion[0, 1]) # print ("PPV: " +str(PPV)) # Jaccard similarity index jaccard_index = jaccard_score(y_true, y_pred) print("\nJaccard similarity score: " + str(jaccard_index)) # F1 score F1_score = f1_score(y_true, y_pred, labels=None, average='binary', sample_weight=None) # print ("\nF1 score (F-measure): " +str(F1_score)) # Save the results # file_perf = open(path_experiment+'performances.txt', 'w') # # file_perf.write("Area under the ROC curve: "+str(AUC_ROC) # # + "\nArea under Precision-Recall curve: " +str(AUC_prec_rec) # # + "\nJaccard similarity score: " +str(jaccard_index) # # + "\nF1 score (F-measure): " +str(F1_score) # # +"\n\nConfusion matrix:" # # +str(confusion) # # +"\nACCURACY: " +str(accuracy) # # +"\nSENSITIVITY: " +str(sensitivity) # # +"\nSPECIFICITY: " +str(specificity) # # +"\nPRECISION: " +str(precision) # # +"\nRECALL: " +str(sensitivity) # # +"\nPPV: " +str(PPV) # # +"\nbest_th: " +str(best_threshold) # # +"\nbest_f1: " +str(best_f1) # # ) # file_perf.write( # "\nJaccard similarity score: " +str(jaccard_index) # + "\nF1 score (F-measure): " +str(F1_score) # +"\n\nConfusion matrix:" # +str(confusion) # +"\nACCURACY: " +str(accuracy) # +"\nSENSITIVITY: " +str(sensitivity) # +"\nSPECIFICITY: " +str(specificity) # +"\nPRECISION: " +str(precision) # +"\nRECALL: " +str(sensitivity) # +"\nPPV: " +str(PPV) # ) # file_perf.close() # #============================================================================================================================================================================== thinned_predict = thin(predict) # cv2.imwrite(outpredictPath+filename,(thinned_predict*255).astype(np.uint8)) # predict[predict>=1] = 1 # dice = getDSC(predict, label) # print("filename:" , filename , "dice:" , dice) # dice_res = "the " + filename[:-4] + " image's DSC : " + str(round(dice,4)) + "\n" DSC = getDSC(label, predict) # surface_distances = surface_distance.compute_surface_distances(label, predict, spacing_mm=(1, 1, 1)) # HD = surface_distance.compute_robust_hausdorff(surface_distances, 95) # distances_gt_to_pred = surface_distances["distances_gt_to_pred"] # distances_pred_to_gt = surface_distances["distances_pred_to_gt"] # surfel_areas_gt = surface_distances["surfel_areas_gt"] # surfel_areas_pred = surface_distances["surfel_areas_pred"] # ASSD = (np.sum(distances_pred_to_gt * surfel_areas_pred) +np.sum(distances_gt_to_pred * surfel_areas_gt))/(np.sum(surfel_areas_gt)+np.sum(surfel_areas_pred)) Jaccard = getJaccard(label, predict) precision, recall = getPrecisionAndRecall(label, predict) intersec = intersection(label, predict) label = np.array(label, dtype=bool) predict = np.array(predict, dtype=bool) surface_distances = surface_distance.compute_surface_distances(label, predict, spacing_mm=(1, 1)) surface_distances_thin = surface_distance.compute_surface_distances(thinned_label, thinned_predict, spacing_mm=(1, 1)) HD = surface_distance.compute_robust_hausdorff(surface_distances, 95) HD_thin = surface_distance.compute_robust_hausdorff(surface_distances_thin, 95) surface_dice_2 = surface_distance.compute_surface_dice_at_tolerance(surface_distances, 2) rel_overlap_gt, rel_overlap_pred = surface_distance.compute_surface_overlap_at_tolerance(surface_distances, 2) surface_dice_1 = surface_distance.compute_surface_dice_at_tolerance(surface_distances, 1) surface_dice_0 = surface_distance.compute_surface_dice_at_tolerance(surface_distances, 0) surface_dice_3 = surface_distance.compute_surface_dice_at_tolerance(surface_distances, 3) distances_gt_to_pred = surface_distances["distances_gt_to_pred"] distances_pred_to_gt = surface_distances["distances_pred_to_gt"] surfel_areas_gt = surface_distances["surfel_areas_gt"] surfel_areas_pred = surface_distances["surfel_areas_pred"] ASSD = (np.sum(distances_pred_to_gt * surfel_areas_pred) + np.sum(distances_gt_to_pred * surfel_areas_gt))/(np.sum(surfel_areas_gt)+np.sum(surfel_areas_pred)) distances_gt_to_pred_t = surface_distances_thin["distances_gt_to_pred"] distances_pred_to_gt_t = surface_distances_thin["distances_pred_to_gt"] surfel_areas_gt_t = surface_distances_thin["surfel_areas_gt"] surfel_areas_pred_t = surface_distances_thin["surfel_areas_pred"] ASSD_thin = (np.sum(distances_pred_to_gt_t * surfel_areas_pred_t) + np.sum(distances_gt_to_pred_t * surfel_areas_gt_t))/(np.sum(surfel_areas_gt_t)+np.sum(surfel_areas_pred_t)) # print(surface_overlap) row_num += 1 sheet.write(row_num, 0, filename) sheet.write(row_num, 1, DSC) sheet.write(row_num, 2, precision) sheet.write(row_num, 3, recall) sheet.write(row_num, 4, HD) sheet.write(row_num, 5, ASSD) sheet.write(row_num, 6, surface_dice_0) sheet.write(row_num, 7, rel_overlap_gt) sheet.write(row_num, 8, rel_overlap_pred) sheet.write(row_num, 9, intersec) sheet.write(row_num, 10, HD_thin) sheet.write(row_num, 11, ASSD_thin) sheet.write(row_num, 12, surface_dice_1) sheet.write(row_num, 13, surface_dice_2) # sheet.write(row_num, 14, surface_dice_3) sheet.write(row_num, 14, Jaccard) sheet.write(row_num, 15, accuracy) sheet.write(row_num, 16, specificity) sheet.write(row_num, 17, sensitivity) Q1.append(DSC) Q2.append(precision) Q3.append(recall) Q4.append(HD) Q5.append(ASSD) Q6.append(surface_dice_0) Q7.append(rel_overlap_gt) Q8.append(rel_overlap_pred) Q9.append(intersec) Q10.append(HD_thin) Q11.append(ASSD_thin) Q12.append(surface_dice_1) Q13.append(surface_dice_2) # Q14.append(surface_dice_3) Q14.append(Jaccard) Q15.append(accuracy) Q16.append(specificity) Q17.append(sensitivity) Q1 = np.array(Q1) Q2 = np.array(Q2) Q3 = np.array(Q3) Q4 = np.array(Q4) Q5 = np.array(Q5) Q6 = np.array(Q6) Q7 = np.array(Q7) Q8 = np.array(Q8) Q9 = np.array(Q9) Q10 = np.array(Q10) Q11 = np.array(Q11) Q12 = np.array(Q12) Q13 = np.array(Q13) Q14 = np.array(Q14) Q15 = np.array(Q15) Q16 = np.array(Q16) Q17 = np.array(Q17) row_num += 2 sheet.write(row_num, 0, 'CaseName') sheet.write(row_num, 1, 'DSC') sheet.write(row_num, 2, 'Pre') sheet.write(row_num, 3, 'Recall') sheet.write(row_num, 4, 'HD') sheet.write(row_num, 5, 'ASSD') sheet.write(row_num, 6, 'surface_dice_0') sheet.write(row_num, 7, 'rel_overlap_gt') sheet.write(row_num, 8, 'rel_overlap_pred') sheet.write(row_num, 9, 'intersec') sheet.write(row_num, 10, 'HD_thin') sheet.write(row_num, 11, 'ASSD_thin') sheet.write(row_num, 12, 'surface_dice_1') sheet.write(row_num, 13, 'surface_dice_2') sheet.write(row_num, 14, 'Jaccard') sheet.write(row_num, 15, 'accuracy') sheet.write(row_num, 16, 'specificity') sheet.write(row_num, 17, 'sensitivity') row_num += 1 sheet.write(row_num, 0, predictName) sheet.write(row_num, 1, Q1.mean()) sheet.write(row_num, 2, Q2.mean()) sheet.write(row_num, 3, Q3.mean()) sheet.write(row_num, 4, Q4.mean()) sheet.write(row_num, 5, Q5.mean()) sheet.write(row_num, 6, Q6.mean()) sheet.write(row_num, 7, Q7.mean()) sheet.write(row_num, 8, Q8.mean()) sheet.write(row_num, 9, Q9.mean()) sheet.write(row_num, 10, Q10.mean()) sheet.write(row_num, 11, Q11.mean()) sheet.write(row_num, 12, Q12.mean()) sheet.write(row_num, 13, Q13.mean()) sheet.write(row_num, 14, Q14.mean()) sheet.write(row_num, 15, Q15.mean()) sheet.write(row_num, 16, Q16.mean()) sheet.write(row_num, 17, Q17.mean()) book.save('./smp/' + predictName + '.xls')
[ "11712616@mail.sustech.edu.cn" ]
11712616@mail.sustech.edu.cn
817f463578dec04dd4c4938523da72404795d281
f5b31994dfbe4effa7868557f223952d1a2dc0f6
/src/mic.py
e648fca6167cfaad255f044ac0b3bb511beb4322
[]
no_license
jacobsny/hackathon_checkin
96f39a4f4b55599e214617c439bbc63159a0fcf6
ff588c8511f4cf496bdf53dee1e534977a6e5a8a
refs/heads/master
2020-07-29T21:06:08.345970
2019-09-22T13:14:05
2019-09-22T13:14:05
209,959,335
0
0
null
null
null
null
UTF-8
Python
false
false
5,423
py
from __future__ import division import re import sys from google.cloud import speech from google.cloud.speech import enums from google.cloud.speech import types import pyaudio from six.moves import queue # Audio recording parameters RATE = 16000 CHUNK = int(RATE / 10) # 100ms class MicrophoneStream(object): """Opens a recording stream as a generator yielding the audio chunks.""" def __init__(self, rate, chunk): self._rate = rate self._chunk = chunk # Create a thread-safe buffer of audio data self._buff = queue.Queue() self.closed = True def __enter__(self): self._audio_interface = pyaudio.PyAudio() self._audio_stream = self._audio_interface.open( format=pyaudio.paInt16, # The API currently only supports 1-channel (mono) audio # https://goo.gl/z757pE channels=1, rate=self._rate, input=True, frames_per_buffer=self._chunk, # Run the audio stream asynchronously to fill the buffer object. # This is necessary so that the input device's buffer doesn't # overflow while the calling thread makes network requests, etc. stream_callback=self._fill_buffer, ) self.closed = False return self def __exit__(self, type, value, traceback): self._audio_stream.stop_stream() self._audio_stream.close() self.closed = True # Signal the generator to terminate so that the client's # streaming_recognize method will not block the process termination. self._buff.put(None) self._audio_interface.terminate() def _fill_buffer(self, in_data, frame_count, time_info, status_flags): """Continuously collect data from the audio stream, into the buffer.""" self._buff.put(in_data) return None, pyaudio.paContinue def generator(self): while not self.closed: # Use a blocking get() to ensure there's at least one chunk of # data, and stop iteration if the chunk is None, indicating the # end of the audio stream. chunk = self._buff.get() if chunk is None: return data = [chunk] # Now consume whatever other data's still buffered. while True: try: chunk = self._buff.get(block=False) if chunk is None: return data.append(chunk) except queue.Empty: break yield b''.join(data) def listen_print_loop(responses): """Iterates through server responses and prints them. The responses passed is a generator that will block until a response is provided by the server. Each response may contain multiple results, and each result may contain multiple alternatives; for details, see https://goo.gl/tjCPAU. Here we print only the transcription for the top alternative of the top result. In this case, responses are provided for interim results as well. If the response is an interim one, print a line feed at the end of it, to allow the next result to overwrite it, until the response is a final one. For the final one, print a newline to preserve the finalized transcription. """ num_chars_printed = 0 for response in responses: if not response.results: continue # The `results` list is consecutive. For streaming, we only care about # the first result being considered, since once it's `is_final`, it # moves on to considering the next utterance. result = response.results[0] if not result.alternatives: continue # Display the transcription of the top alternative. transcript = result.alternatives[0].transcript # Display interim results, but with a carriage return at the end of the # line, so subsequent lines will overwrite them. # # If the previous result was longer than this one, we need to print # some extra spaces to overwrite the previous result overwrite_chars = ' ' * (num_chars_printed - len(transcript)) if not result.is_final: sys.stdout.write(transcript + overwrite_chars + '\r') sys.stdout.flush() num_chars_printed = len(transcript) else: return transcript + overwrite_chars def main(lang): # See http://g.co/cloud/speech/docs/languages # for a list of supported languages. language_code = lang # a BCP-47 language tag client = speech.SpeechClient() config = types.RecognitionConfig( encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16, sample_rate_hertz=RATE, language_code=language_code) streaming_config = types.StreamingRecognitionConfig( config=config, interim_results=True) with MicrophoneStream(RATE, CHUNK) as stream: audio_generator = stream.generator() requests = (types.StreamingRecognizeRequest(audio_content=content) for content in audio_generator) responses = client.streaming_recognize(streaming_config, requests) # Now, put the transcription responses to use. return listen_print_loop(responses) if __name__ == '__main__': main('en-US')
[ "jacob.snyderman@gmail.com" ]
jacob.snyderman@gmail.com
9090a6049a51ef8672151f75d28c7f01c75a1436
fc3deae46d7104924d9b982638f38eb42eadbb9f
/yrnetwork/setting.py
0fd31990a155271ff3f6b9b4c0a28ee4958148c9
[]
no_license
THRILLERLEMON/YR_Greening_Network
6fc578d4a94bf240b954181d9ea8d1cf18fb172d
8745679d58c3e459d88524e0afae18e072b18e0a
refs/heads/main
2023-03-19T00:08:28.187235
2021-03-05T13:21:53
2021-03-05T13:21:53
303,892,090
0
0
null
null
null
null
UTF-8
Python
false
false
637
py
class BaseConfig(object): RESULT_PATH = '' LUC_NET_DATA_PATH = 'D://OneDrive//JustDo//The_Greening_of_YR_from_the_Perspective_of_Network//Data//LUCNetData//' LUC_NET_DATA_HEAD = 'InfoForLUCNet' LUC_NET_DATA_TAIL = '.csv' GEO_AGENT_PATH = 'E://MY PROGRAM//YR_Greening_Network//data//GeoAgent//ForCartopy//' COUPLED_NET_DATA_PATH = 'E://MY PROGRAM//YR_Greening_Network//data//Data_for_LAI_Causal//' COUPLED_NET_DATA_HEAD = 'YR_GA_Info_' COUPLED_NET_DATA_TAIL = '.csv' OUT_PATH = 'D://OneDrive//JustDo//The_Greening_of_YR_from_the_Perspective_of_Network//OutPutforLAICausal//' BACKGROUND_VALUE = -999
[ "thrillerlemon@outlook.com" ]
thrillerlemon@outlook.com