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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4c57bed9f11e7868280ca359231fa7da943f30c9 | dc6220b4e7187c2b15b964eca89a1fd08b75bb5c | /traits_futures/multiprocessing_context.py | d2c4be8fb6eabf34dde1da5310aa03199906e742 | [
"BSD-3-Clause"
] | permissive | Intertangle-survey/traits-futures | 8d7dfba3926ba487d54e6786ee55992368a267b5 | 6abb8b81538b6a545073df76687a05f8d891c919 | refs/heads/main | 2023-06-18T13:48:40.059977 | 2021-07-06T06:06:11 | 2021-07-06T06:06:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,441 | py | # (C) Copyright 2018-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
"""
Context providing multiprocessing-friendly worker pools, events, and routers.
"""
import concurrent.futures
import multiprocessing
from traits_futures.i_parallel_context import IParallelContext
from traits_futures.multiprocessing_router import MultiprocessingRouter
class MultiprocessingContext(IParallelContext):
"""
Context for multiprocessing, suitable for use with the TraitsExecutor.
"""
def __init__(self):
self._closed = False
self._manager = multiprocessing.Manager()
def worker_pool(self, *, max_workers=None):
"""
Provide a new worker pool suitable for this context.
Parameters
----------
max_workers : int, optional
Maximum number of workers to use. If not given, the choice is
delegated to the ProcessPoolExecutor.
Returns
-------
executor : concurrent.futures.Executor
"""
return concurrent.futures.ProcessPoolExecutor(max_workers=max_workers)
def event(self):
"""
Return a shareable event suitable for this context.
Returns
-------
event : event-like
An event that can be shared safely with workers.
"""
return self._manager.Event()
def message_router(self, event_loop):
"""
Return a message router suitable for use in this context.
Parameters
----------
event_loop : IEventLoop
The event loop to interact with.
Returns
-------
message_router : MultiprocessingRouter
"""
return MultiprocessingRouter(
event_loop=event_loop,
manager=self._manager,
)
def close(self):
"""
Do any cleanup necessary before disposal of the context.
"""
self._manager.shutdown()
self._closed = True
@property
def closed(self):
"""
True if this context is closed, else False.
"""
return self._closed
| [
"noreply@github.com"
] | Intertangle-survey.noreply@github.com |
4677a47dd7cb52ce3b9bd6761890378d031fbf5b | 5015022c98ef1e7cb174974023f10517a45cdb2f | /lib/ClassListener.py | e445e9db0ac53504760601c4043f51e471cdec16 | [] | no_license | tlqaksqhr/Java2UML | 01b7b9eb6a38ff38ffb82aec8ad73675a345931f | 01aaa210d1c2d68c39be7b4300558444cc8b824a | refs/heads/master | 2023-03-25T18:40:53.153111 | 2020-04-03T14:50:18 | 2020-04-03T14:50:18 | 109,405,329 | 22 | 2 | null | 2021-03-20T00:47:11 | 2017-11-03T14:29:39 | Python | UTF-8 | Python | false | false | 3,084 | py | from antlr4 import *
from .JavaLexer import JavaLexer
from .JavaParser import JavaParser
from .JavaListener import JavaListener
from .MethodListener import MethodListener
from .FieldListener import FieldListener
from .InterfaceListener import InterfaceListener
from .ClassNode import ClassNode
class ClassListener(JavaListener):
def __init__(self):
self.ClassNode = ClassNode
# Enter a parse tree produced by JavaParser#classDeclaration.
def enterClassDeclaration(self, ctx:JavaParser.ClassDeclarationContext):
Cnode = ClassNode()
Cnode.ClassName = ctx.Identifier().getText()
#print("Name : ", ctx.Identifier().getText())
extends = ctx.typeType()
if(type(extends) != type(None)):
Cnode.Extends = self.getAllText(extends)
#print("Extends : ", self.getAllText(extends))
# TODO : interface name parsing
implementList = ctx.typeList()
if(type(implementList) != type(None)):
implementList = implementList.typeType()
for implement in implementList:
#print("Implement : ", self.getAllText(implement))
Cnode.ImplementList.append({"Type" : self.getAllText(implement)})
classBodyDeclarations = ctx.classBody().classBodyDeclaration()
MethodContainer = []
FieldContainer = []
for classBodyDeclaration in classBodyDeclarations:
modifier = ""
for mod in classBodyDeclaration.modifier():
modifier = modifier + " " + self.getAllText(mod)
if(type(classBodyDeclaration.memberDeclaration().methodDeclaration()) != type(None)):
MethodContainer.append({"modifier" : modifier,"value" : classBodyDeclaration.memberDeclaration().methodDeclaration()})
elif(type(classBodyDeclaration.memberDeclaration().constructorDeclaration()) != type(None)):
MethodContainer.append({"modifier" : modifier,"value" : classBodyDeclaration.memberDeclaration().constructorDeclaration()})
elif(type(classBodyDeclaration.memberDeclaration().fieldDeclaration()) != type(None)):
FieldContainer.append({"modifier" : modifier,"value" : classBodyDeclaration.memberDeclaration().fieldDeclaration()})
for Method in MethodContainer:
methodListener = MethodListener()
Method["value"].enterRule(methodListener)
methodListener.Method["modifier"] = Method["modifier"]
Cnode.MethodList.append(methodListener.Method)
#print(methodListener.Method)
for Field in FieldContainer:
fieldListener = FieldListener()
Field["value"].enterRule(fieldListener)
for i in range(0,len(fieldListener.FieldList)):
fieldListener.FieldList[i].update({"modifier" : Field["modifier"]})
Cnode.FieldList += fieldListener.FieldList
#print(methodListener.Method)
self.ClassNode = Cnode
#print("Class Name : ", self.ClassNode.ClassName)
#print("Class Extends : ", self.ClassNode.Extends)
#print("Class Methods : ",self.ClassNode.MethodList)
#print("Class Fields : ",self.ClassNode.FieldList)
#print("Class Implements : ",self.ClassNode.ImplementList)
#print(self.ClassNode)
# Exit a parse tree produced by JavaParser#classDeclaration.
def exitClassDeclaration(self, ctx:JavaParser.ClassDeclarationContext):
pass | [
"tlqaksqhr@naver.com"
] | tlqaksqhr@naver.com |
656be5dbcb1eafd87b80b79d3ab98dee77814001 | af5d19ddd86f87df18ecc88dc6139bca9e8c8ee8 | /test/functional/feature_cltv.py | d263ff27561311077bbf29b9aee94656149e8ddb | [
"MIT"
] | permissive | GameLoverZ/MogCoin | 635cc4d749d52292a4224ea207021756df6bd75a | 2aa4d7ea7e81151a4565e2c37416aa1dc487c199 | refs/heads/master | 2023-03-28T20:03:56.181698 | 2021-03-28T14:39:08 | 2021-03-28T14:39:08 | 351,828,530 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 6,508 | py | #!/usr/bin/env python3
# Copyright (c) 2015-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test BIP65 (CHECKLOCKTIMEVERIFY).
Test that the CHECKLOCKTIMEVERIFY soft-fork activates at (regtest) block height
1351.
"""
from test_framework.blocktools import create_coinbase, create_block, create_transaction
from test_framework.messages import CTransaction, msg_block, ToHex
from test_framework.mininode import mininode_lock, P2PInterface
from test_framework.script import CScript, OP_1NEGATE, OP_CHECKLOCKTIMEVERIFY, OP_DROP, CScriptNum
from test_framework.test_framework import MogCoinTestFramework
from test_framework.util import assert_equal, bytes_to_hex_str, hex_str_to_bytes, wait_until
from io import BytesIO
CLTV_HEIGHT = 1351
# Reject codes that we might receive in this test
REJECT_INVALID = 16
REJECT_OBSOLETE = 17
REJECT_NONSTANDARD = 64
def cltv_invalidate(tx):
'''Modify the signature in vin 0 of the tx to fail CLTV
Prepends -1 CLTV DROP in the scriptSig itself.
TODO: test more ways that transactions using CLTV could be invalid (eg
locktime requirements fail, sequence time requirements fail, etc).
'''
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_CHECKLOCKTIMEVERIFY, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
def cltv_validate(node, tx, height):
'''Modify the signature in vin 0 of the tx to pass CLTV
Prepends <height> CLTV DROP in the scriptSig, and sets
the locktime to height'''
tx.vin[0].nSequence = 0
tx.nLockTime = height
# Need to re-sign, since nSequence and nLockTime changed
signed_result = node.signrawtransactionwithwallet(ToHex(tx))
new_tx = CTransaction()
new_tx.deserialize(BytesIO(hex_str_to_bytes(signed_result['hex'])))
new_tx.vin[0].scriptSig = CScript([CScriptNum(height), OP_CHECKLOCKTIMEVERIFY, OP_DROP] +
list(CScript(new_tx.vin[0].scriptSig)))
return new_tx
class BIP65Test(MogCoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.extra_args = [['-whitelist=127.0.0.1']]
self.setup_clean_chain = True
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
def run_test(self):
self.nodes[0].add_p2p_connection(P2PInterface())
self.log.info("Mining %d blocks", CLTV_HEIGHT - 2)
self.coinbase_txids = [self.nodes[0].getblock(b)['tx'][0] for b in self.nodes[0].generate(CLTV_HEIGHT - 2)]
self.nodeaddress = self.nodes[0].getnewaddress()
self.log.info("Test that an invalid-according-to-CLTV transaction can still appear in a block")
spendtx = create_transaction(self.nodes[0], self.coinbase_txids[0],
self.nodeaddress, amount=1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
tip = self.nodes[0].getbestblockhash()
block_time = self.nodes[0].getblockheader(tip)['mediantime'] + 1
block = create_block(int(tip, 16), create_coinbase(CLTV_HEIGHT - 1), block_time)
block.nVersion = 3
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.solve()
self.nodes[0].p2p.send_and_ping(msg_block(block))
assert_equal(self.nodes[0].getbestblockhash(), block.hash)
self.log.info("Test that blocks must now be at least version 4")
tip = block.sha256
block_time += 1
block = create_block(tip, create_coinbase(CLTV_HEIGHT), block_time)
block.nVersion = 3
block.solve()
self.nodes[0].p2p.send_and_ping(msg_block(block))
assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)
wait_until(lambda: "reject" in self.nodes[0].p2p.last_message.keys(), lock=mininode_lock)
with mininode_lock:
assert_equal(self.nodes[0].p2p.last_message["reject"].code, REJECT_OBSOLETE)
assert_equal(self.nodes[0].p2p.last_message["reject"].reason, b'bad-version(0x00000003)')
assert_equal(self.nodes[0].p2p.last_message["reject"].data, block.sha256)
del self.nodes[0].p2p.last_message["reject"]
self.log.info("Test that invalid-according-to-cltv transactions cannot appear in a block")
block.nVersion = 4
spendtx = create_transaction(self.nodes[0], self.coinbase_txids[1],
self.nodeaddress, amount=1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
# First we show that this tx is valid except for CLTV by getting it
# rejected from the mempool for exactly that reason.
assert_equal(
[{'txid': spendtx.hash, 'allowed': False, 'reject-reason': '64: non-mandatory-script-verify-flag (Negative locktime)'}],
self.nodes[0].testmempoolaccept(rawtxs=[bytes_to_hex_str(spendtx.serialize())], allowhighfees=True)
)
# Now we verify that a block with this transaction is also invalid.
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.solve()
self.nodes[0].p2p.send_and_ping(msg_block(block))
assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)
wait_until(lambda: "reject" in self.nodes[0].p2p.last_message.keys(), lock=mininode_lock)
with mininode_lock:
assert self.nodes[0].p2p.last_message["reject"].code in [REJECT_INVALID, REJECT_NONSTANDARD]
assert_equal(self.nodes[0].p2p.last_message["reject"].data, block.sha256)
if self.nodes[0].p2p.last_message["reject"].code == REJECT_INVALID:
# Generic rejection when a block is invalid
assert_equal(self.nodes[0].p2p.last_message["reject"].reason, b'block-validation-failed')
else:
assert b'Negative locktime' in self.nodes[0].p2p.last_message["reject"].reason
self.log.info("Test that a version 4 block with a valid-according-to-CLTV transaction is accepted")
spendtx = cltv_validate(self.nodes[0], spendtx, CLTV_HEIGHT - 1)
spendtx.rehash()
block.vtx.pop(1)
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.solve()
self.nodes[0].p2p.send_and_ping(msg_block(block))
assert_equal(int(self.nodes[0].getbestblockhash(), 16), block.sha256)
if __name__ == '__main__':
BIP65Test().main()
| [
"13012523111@163.com"
] | 13012523111@163.com |
f6ec734ec992124626199e369b018942752a223b | 16c84dcf0cdce20c3b8ec5dc37e95d42385f583e | /resources/user.py | faadd561f082a6360efed3abd2f67cc15a945dc1 | [] | no_license | wadeph/stores-rest-api | b072d8690e013163e6dfa40d9ac696f1f35c4c22 | 7634a427f934812e99417d98083711160d288d14 | refs/heads/master | 2021-05-07T20:01:52.425216 | 2017-10-31T05:03:27 | 2017-10-31T05:03:27 | 108,920,076 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 756 | py | import sqlite3
from flask_restful import Resource, reqparse
from models.user import UserModel
class UserRegister(Resource):
parser = reqparse.RequestParser()
parser.add_argument('username',
type=str,
required=True,
help="This field cannot be left blank!"
)
parser.add_argument('password',
type=str,
required=True,
help="This field cannot be left blank!"
)
def post(self):
data = UserRegister.parser.parse_args()
if UserModel.find_by_username(data['username']):
return {"message": "A user with that username already exists."}, 400
user = UserModel(**data)
user.save_to_db()
return {"message": "User created successfully."}, 201
| [
"zengpei@us.ibm.com"
] | zengpei@us.ibm.com |
cbb3a7efd2d39d7e62ed09496260773532d3e0ad | 8d84eeceb3e3bb6e42c8f76182e202dd0248094f | /Thepigapp/wsgi.py | d00b3597048747ebfa949a210654feb282029980 | [] | no_license | Vaughnkoehn/thepigapp | b38df25b30e77e1d7d4de502ac26e33fbcef222f | 9efeb335d1065c9830942674fbf8ed833b9f0440 | refs/heads/master | 2021-06-25T07:22:51.436619 | 2018-04-11T17:28:43 | 2018-04-11T17:28:43 | 96,172,230 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 396 | py | """
WSGI config for Thepigapp 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/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Thepigapp.settings")
application = get_wsgi_application()
| [
"vkoehn99@gmail.com"
] | vkoehn99@gmail.com |
b135e13d684c6f2fc7bc42e5d6fb2f89544055b9 | bb11731aedcc21c2b7da0112de930cb0719cd1cf | /app.py | fded5f8911f34620f274446b944b21453e559b65 | [] | no_license | stassyn/facebook-bot | 8b2d8f6eff259d672d1d49b968088b984f0293bd | 2e97342601b09bfa064f845ab33d5411f0f7188f | refs/heads/master | 2021-01-14T12:00:50.321219 | 2016-09-19T08:41:40 | 2016-09-19T11:21:05 | 68,581,837 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,873 | py | import os
import json
import requests
from dotenv import load_dotenv, find_dotenv
from flask import Flask, request
app = Flask(__name__)
load_dotenv(find_dotenv())
@app.route("/", methods=['GET'])
def verify():
"""
Echo 'hub.challenge" so we can register app as webhook
"""
if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
if not request.args.get("hub.verify_token") == os.environ["VERIFY_TOKEN"]:
return "Token mismatch", 403
return request.args["hub.challenge"], 200
return "Hello!", 200
@app.route("/", methods=['POST'])
def hook():
"""
Receives all messages from Facebook bot
"""
data = request.get_json()
if data["object"] == "page":
for entry in data["entry"]:
for messaging_event in entry["messaging"]:
handle_messaging_event(messaging_event)
def handle_messaging_event(messaging_event):
"""
Handle all events from bot (messages, delivery, optins, postbacks)
:param messaging_event: event object
"""
if messaging_event.get("postback"):
# Here we handling payload which we setup by sending this request
# curl - X POST - H "Content-Type: application/json" - d '{
# "setting_type":"call_to_actions",
# "thread_state":"new_thread",
# "call_to_actions":[
# {
# "payload": "GET_STARTED"
# }
# ]
# }'
if messaging_event["postback"]["payload"] == 'GET_STARTED':
sender_id = messaging_event["sender"]["id"]
profile = get_profile(sender_id)
send_message(sender_id, "{}, what would you like to do tonight?".format(profile["first_name"]))
def get_profile(user_id):
"""
Get profile of user by id
:param user_id: user id
"""
params = {
'access_token': os.environ["PAGE_ACCESS_TOKEN"]
}
headers = {
'Content-type': 'application/json'
}
r = requests.get("https://graph.facebook.com/v2.7/{}".format(user_id), params=params, headers=headers)
if r.status_code == 200:
return json.loads(r.text)
def send_message(recipient_id, message):
"""
Handle message sending
:param recipient_id: who should receive message
:param message: message text
"""
params = {
'access_token': os.environ["PAGE_ACCESS_TOKEN"]
}
headers = {
'Content-type': 'application/json'
}
data = json.dumps({
"recipient": {
"id": recipient_id,
},
"message": {
"text": message,
}
})
r = requests.post("https://graph.facebook.com/v2.6/me/messages", params=params, headers=headers, data=data)
if r.status_code != 200:
raise Exception(r.text)
if __name__ == "__main__":
app.run()
| [
"stasinyavskiy@gmail.com"
] | stasinyavskiy@gmail.com |
72caf78639809a0b6127295f16c0fa724f14f44f | 1fc14364077cb02ad94e738d8191eb3eb5f7a1c7 | /gui_tools.py | f4794c17da361996cab356fdc1efa1bcd1a1e8bf | [] | no_license | stgl/TopoAnalysis | 1797d8a1652226da8be3a83c308cf6b4f0a6d859 | 5e068ee49287e228f311521558dd630cdc14fa29 | refs/heads/master | 2023-04-16T22:08:35.980133 | 2022-10-15T19:28:41 | 2022-10-15T19:28:41 | 51,605,604 | 4 | 7 | null | 2021-05-03T16:30:31 | 2016-02-12T17:49:26 | Python | UTF-8 | Python | false | false | 2,306 | py | import matplotlib
matplotlib.use('TKAgg')
import dem as d
import matplotlib.pylab as plt
import numpy as np
import pickle as p
import matplotlib.cm as cm
import sys
if sys.version_info[0] >= 3:
raw_input = input
def plot_dem(dem, hs):
plt.close('all')
dem.plot()
hs.plot(alpha = 0.5, cmap = plt.cm.gray)
def select_outlets(dem, fd, prefix, hs = None, outlet_filename = 'outlets.p', color = 'r'):
if hs is None:
hs = d.Hillshade(elevation = dem, azimuth = 320, inclination = 20)
plot_dem(dem, hs)
keep_going = True
while keep_going:
zoom_ok = False
print('\nZoom or pan to view, \npress spacebar when ready to select point upstream of outlet:\n')
while not zoom_ok:
zoom_ok = plt.waitforbuttonpress()
print('\nClick on point upstream of outlet.')
xy = plt.ginput(1)[0]
xy_path = fd.search_down_flow_direction_from_xy_location(xy)
plt.plot(xy)
plt.plot(xy_path)
xy_path_plot = list(zip(*xy_path))
path = plt.plot(xy_path_plot[0],xy_path_plot[1], color+'-')
print('\nClick on the outlet location.')
xy = plt.ginput(1)[0]
min_distance = 1E12
for loc in xy_path:
if (np.sqrt( np.power(loc[0] - xy[0], 2) + np.power(loc[1] - xy[1], 2)) < min_distance) or min_distance == 1E12:
outlet_loc = loc
min_distance = np.sqrt( np.power(loc[0] - xy[0], 2) + np.power(loc[1] - xy[1], 2))
plt.figure(1)
plt.plot(outlet_loc[0], outlet_loc[1], color+'o')
path.pop(0).remove()
outlet_prefix = raw_input('Type a name for this outlet (leaving this blank will prevent outlet from being saved and will complete the selection process: ')
if outlet_prefix != '':
import os.path
if os.path.isfile(outlet_filename):
outlets = p.load(open(outlet_filename, 'rb'))
else:
outlets = dict()
this_tile = outlets.get(prefix, dict())
this_tile[outlet_prefix] = outlet_loc
outlets[prefix] = this_tile
p.dump(outlets, open(outlet_filename, 'wb'))
else:
keep_going = False
| [
"gehilley@gmail.com"
] | gehilley@gmail.com |
fae19db2bb19282cd27d0e76d46e27f9d84b1f05 | 523bce137c2332cf6fac7e859ae56a29e722d88a | /WakeOnLan-server/flask/api/models/Computer.py | 7c04b5bffe8fa14036cfc5853a694cd58b6e6e1f | [] | no_license | DarioGar/WakeOnLan | bc03977cc42371874ad3a3e0989cf0b83a9ecce9 | 72ba34ce64482da23020d84a41819b889dad51f1 | refs/heads/main | 2023-08-25T11:11:48.109594 | 2021-09-25T09:47:41 | 2021-09-25T09:47:41 | 346,698,368 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,618 | py | from datetime import date
from api.v1 import con
from api.reusable import checkMAC
from wakeonlan import send_magic_packet
import schedule
class Computer:
def __init__(self,mac,os,cpu,ssd,ram,gpu):
self.mac = mac
self.cpu = cpu
self.os = os
self.ram = ram
self.gpu = gpu
self.ssd = ssd
@staticmethod
def fetchAll():
cur = con.cursor()
query = "select * from computers"
cur.execute(query,)
computers = cur.fetchall()
return computers
@staticmethod
def fetchComputersUnassigned():
cur = con.cursor()
query = "select ip,mac,cpu,ram,ssd,os,gpu,computers.id,name from computers where room_id IS NULL"
cur.execute(query,)
computers = cur.fetchall()
return computers
@staticmethod
def poweredEachDay():
cur = con.cursor()
query = "select extract(dow from booted_at) as days, count(*) from bootup_log group by days"
cur.execute(query,)
days = cur.fetchall()
return days
@staticmethod
def activeUsers():
cur = con.cursor()
query = "select username,count(*) from bootup_log group by username"
cur.execute(query,)
users = cur.fetchall()
return users
@staticmethod
def insert(mac,ip,ram,cpu,gpu,os,ssd,owner,name):
cur = con.cursor()
try:
query = "select id from public.users where username = %s"
cur.execute(query,(owner,))
user = cur.fetchone()
except:
return -1
try:
query = "INSERT INTO computers (mac,ip,ram,cpu,gpu,ssd,os,owner,name) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
cur.execute(query,(mac,ip,ram,cpu,gpu,ssd,os,user[0],name))
con.commit()
return 0
except Exception as e:
con.rollback()
return -1
@staticmethod
def update(mac,ip,ram,cpu,gpu,os,ssd,name):
cur = con.cursor()
try:
query = "UPDATE computers SET (ip,ram,cpu,gpu,ssd,os,name) = (%s,%s,%s,%s,%s,%s,%s) WHERE mac = %s"
cur.execute(query,(ip,ram,cpu,gpu,ssd,os,name,mac))
con.commit()
return 0
except Exception as e:
con.rollback()
return -1
@staticmethod
def delete(mac):
cur = con.cursor()
try:
query = "DELETE FROM computers WHERE mac = %s"
cur.execute(query,(mac,))
con.commit()
return 0
except Exception as e:
con.rollback()
return -1
@staticmethod
def fetchComputerFor(username):
cur = con.cursor()
computers = []
# Get both role and id from the user
query = "select role,id from public.users where username = %s"
cur.execute(query,(username,))
user = cur.fetchone()
# CASE 1 User is an admin, return everything
if user[0] == 'admin':
query = "SELECT ip,mac,cpu,ram,ssd,os,gpu,computers.id,name FROM computers"
cur.execute(query,)
computersInRoom = cur.fetchall()
computers.append(computersInRoom)
return list(set(computers[0]))
# CASE 2a User belongs to some group, add computers assigned to the group
query = "select group_id from group_member where user_id = %s"
cur.execute(query,(user[1],))
work_groups = cur.fetchall()
if len(work_groups) != 0:
for group_id in work_groups:
query = "SELECT DISTINCT rooms.id FROM rooms where group_id = %s"
cur.execute(query,(group_id[0],))
rooms = cur.fetchall()
# We look for all the computers in every room and append them to the computers array
for room in rooms:
query = "SELECT ip,mac,cpu,ram,ssd,os,gpu,computers.id,name FROM computers INNER JOIN rooms ON computers.room_id = rooms.id where rooms.id = %s"
cur.execute(query,(room[0],))
computersInRoom = cur.fetchall()
computers.append(computersInRoom)
# CASE 3 Check if the user has been given permissions to a specific computer
query = "SELECT ip,mac,cpu,ram,ssd,os,gpu,computers.id,name FROM permissions INNER JOIN computers on computers.id = permissions.computer_id where permissions.user_id = %s"
cur.execute(query,(user[1],))
rows = cur.fetchall()
computers.append(rows)
return list(set(computers[0]))
@staticmethod
def powerOn(MAC,user):
formattedMAC = MAC.replace('-',':')
if(checkMAC(formattedMAC)):
Computer.registerLog(user,MAC)
send_magic_packet(formattedMAC)
return schedule.CancelJob
@staticmethod
def registerLog(user,mac):
cur = con.cursor()
query = "select id from public.computers where mac = %s"
cur.execute(query,(mac,))
id = cur.fetchone()
try:
query = "INSERT INTO bootup_log (username,computer_id) VALUES (%s,%s)"
cur.execute(query,(user,id))
con.commit()
except Exception as e:
con.rollback()
return 0
@staticmethod
def fetch(id):
cur = con.cursor()
query = "select * from public.computers where id = %s"
cur.execute(query,(id,))
computer = cur.fetchone()
return computer
@staticmethod
def computersOf(username):
cur = con.cursor()
query = "select id from public.users where username = %s"
cur.execute(query,(username,))
user = cur.fetchone()
query = "SELECT ip,mac,cpu,ram,ssd,os,gpu,id,name from public.computers where owner = %s"
cur.execute(query,(user[0],))
computer = cur.fetchall()
return computer
@staticmethod
def logsFor(mac):
cur = con.cursor()
query = "select id from public.computers where mac = %s"
cur.execute(query,(mac,))
id = cur.fetchone()
query = "select * from public.bootup_log where computer_id = '%s'"
cur.execute(query,(id[0],))
computer = cur.fetchall()
return computer
@staticmethod
def usersAllowedOn(mac):
cur = con.cursor()
query = "select id from public.computers where mac = %s"
cur.execute(query,(mac,))
user = cur.fetchone()
query = "select user_id from public.permissions where computer_id = %s"
cur.execute(query,(user[0],))
computer = cur.fetchall()
return computer
@staticmethod
def changeAllowed(username,allowed,mac):
cur = con.cursor()
query = "select id from public.users where username = %s"
cur.execute(query,(username,))
user = cur.fetchone()
query = "select id from public.computers where mac = %s"
cur.execute(query,(mac,))
computer = cur.fetchone()
if(allowed):
try:
query = "insert into permissions values (%s,%s)"
cur.execute(query,(user,computer,))
con.commit()
result = "allowed"
except:
con.rollback()
result = "allowed"
else:
query = "delete from permissions where user_id=%s AND computer_id=%s"
cur.execute(query,(user[0],computer[0]))
con.commit()
result = "disallowed"
return result
| [
"Dariogm95@usal.es"
] | Dariogm95@usal.es |
c298e4689e2bd2ab98e112e3c4689b09fb588b46 | 64e139ec86e7ed0afe346c6964a89e87eebf7297 | /Software/SoftwareFunctions/LiuHengJun/BA10ConfiguringCommands/DBExpand.py | 361fe7d11dec8f09b8a23b092922660ca9801e3d | [] | no_license | ChinaAIS/AutomaticInstallation | 0705ec779b9948ce306842b72b060733efdf5cca | 1d56892e42a0d4f077dcf18ced2315800d5cc220 | refs/heads/master | 2021-01-20T14:17:08.919741 | 2018-03-11T13:26:53 | 2018-03-11T13:26:58 | 90,584,167 | 2 | 2 | null | null | null | null | UTF-8 | Python | false | false | 252 | py | import os
import Common
CF = Common.CommonFuction()
centralinkPath = os.path.abspath(".") + "\Source\Centralink.lnk"
scriptPath = os.path.abspath(".") + "\Source\DB_Expand\Import.txt"
CF.centralinkLogin(centralinkPath)
CF.importScriptFile(scriptPath) | [
"lhj_liuhengjun@163.com"
] | lhj_liuhengjun@163.com |
ccaa8331ba45c7e092821f902d34302c3be64a4b | af4abf0a22db1cebae466c56b45da2f36f02f323 | /storage/team10/lib/Hash.py | c028a52b082c52b9030bc406caef42c3faf20994 | [
"MIT"
] | permissive | joorgej/tytus | 0c29408c09a021781bd3087f419420a62194d726 | 004efe1d73b58b4b8168f32e01b17d7d8a333a69 | refs/heads/main | 2023-02-17T14:00:00.571200 | 2021-01-09T00:48:47 | 2021-01-09T00:48:47 | 322,429,634 | 3 | 0 | MIT | 2021-01-09T00:40:50 | 2020-12-17T22:40:05 | Python | UTF-8 | Python | false | false | 12,784 | py | from Node import Node
from graphviz import Digraph
class TablaHash:
def __init__(self, size, name, nCols):
self.id = 0
self.Size = size-1
self.name = name
self.contadorNodo = 0
self.nCols = nCols
self.genericId = -1
self.pk = None
self.values = [None]*self.Size
self.inrehashing = False
def getName(self):
return self.name
def setName(self, name):
self.name = name
def getSize(self):
return self.Size
def setSize(self, n):
self.Size = n
def getNodo(self):
return self.values
#dato sera de tipo nodo
def setNodo(self, nodo):
self.values = nodo
def alterAddPK(self, indices):
for i in indices:
try:
int(i)
except:
return 1
if i not in range(0, self.nCols):
return 5
if len(indices) <= self.nCols:
if not self.pk:
return self.recalculateKey(self.pk, indices)
# return 0
else:
# print("No se puede poner otra PK")
return 4
else:
return 5
def toASCII(self, cadena):
result = ""
aux = 0
comma = 0
for char in cadena:
if char != ",":
result += str(ord(char))
else:
comma += int(ord(char))
aux = int(result) + comma
result = str(aux)
return int(result)
def funcionHash(self, dato, flag = False):
if isinstance(dato, list):
lenDato = 0
res = ""
if flag:
for key in self.pk:
res += str(dato[key]) + ","
else:
for key in dato:
res += str(key) + ","
lenDato = self.toASCII(res)
return (int(lenDato % self.Size),lenDato) #cambie aqui para poder obtener la posicion en el arreglo (posicion hash, posicion en arreglo)
def insertIntoArray(self, dato, posicion_hash, key):
bandera = self.verificarDato(key, posicion_hash)
if self.values[posicion_hash] is not None:
if bandera:
nuevo_dato = self.values[posicion_hash]
nuevo_dato.insert(dato, key)
self.contadorNodo +=1
return 0
else:
return 4
else:
nuevo_dato = Node()
if self.pk:
nuevo_dato.pk = self.pk
else:
nuevo_dato.pk = self.genericId
nuevo_dato.isGeneric = True
nuevo_dato.insert(dato,key)
nuevo_dato.key = posicion_hash
self.values[posicion_hash] = nuevo_dato
self.contadorNodo +=1
return 0
def insert(self, dato):
if not self.inrehashing:
self.rehashing()
if isinstance(dato, list):
if len(dato) == self.nCols:
if self.pk:
# Recorre las anteriores buscando su llave primaria
# for node in self.values:
# if node is not None and node.isGeneric:
# self.recalculateKey(node)
# node.isGeneric = False
posicion_hash = self.funcionHash(dato, True)
return self.insertIntoArray(dato, posicion_hash[0], posicion_hash[1]) #aqui manda las dos llaves
else:
posicion_hash = int(self.genericId % self.Size)
self.genericId += 1
return self.insertIntoArrayCSV(dato, posicion_hash, self.genericId)
else:
return 5
else:
return 1
def insertCSV(self, dato):
if self.inrehashing:
self.rehashing()
if self.pk:
posicion_hash = self.funcionHash(dato, True)
return self.insertIntoArrayCSV(dato, posicion_hash[0], posicion_hash[1]) #aqui manda las dos llaves
else:
posicion_hash = int(self.genericId % self.Size)
self.genericId += 1
return self.insertIntoArrayCSV(dato, posicion_hash, self.genericId)
def insertIntoArrayCSV(self, dato, posicion_hash, key):
bandera = self.verificarDato(key, posicion_hash)
if self.values[posicion_hash] is not None:
if bandera:
nuevo_dato = self.values[posicion_hash]
nuevo_dato.insert(dato, key)
self.contadorNodo +=1
return 0
else:
return 4
else:
nuevo_dato = Node()
if self.pk:
nuevo_dato.pk = self.pk
else:
nuevo_dato.pk = self.genericId
nuevo_dato.isGeneric = True
nuevo_dato.insert(dato,key)
nuevo_dato.key = posicion_hash
self.values[posicion_hash] = nuevo_dato
self.contadorNodo +=1
return 0
def recalculateKey(self, newPk, indices):
listCol = []
data = []
ids = []
for node in self.values:
if node is not None:
for n in node.array:
d = n[1]
data.append(d)
key = ""
# ids = n[1][0]
# for i in n[1]:
for j in indices:
ids = n[1][j]
key += str(ids)
listCol.append(key)
if listCol.count(key) > 1:
return 1
else:
continue
# lista = self.values.copy()
self.values.clear()
self.values = [None]*self.Size
self.pk = indices
for d in data:
self.insert(d)
def truncate(self):
try:
self.values.clear()
return 0
except:
return 1
def editar(self, columna, modificacion, key):
posicion_hash = self.funcionHash(key)
nodo = self.values[posicion_hash[0]]
if nodo:
if columna not in self.pk:
respuesta = nodo.modificar(columna,modificacion,posicion_hash[1])
else:
return 4
if respuesta == 0:
return 0
elif respuesta == 4:
return 4
else:
return 1
else:
return 4
def ElementosEn_tbl(self):
auxiliar = 0
for nodo in self.values:
if nodo is not None:
auxiliar +=1
return auxiliar
def rehashing(self):
factorAgregado = int(self.Size * 0.75)
if self.contadorNodo >= factorAgregado:
estoy_en_rehashing = True
self.setSize( int(self.Size*4))
self.inrehashing =True
arrayAuxiliar = self.values[:]
self.values.clear()
self.values = [None]*self.Size
lista = [tupla for nodo in arrayAuxiliar if nodo is not None for tupla in nodo.array]
for j in lista:
self.insert(j[1])
arrayAuxiliar.clear()
self.inrehashing = False
def verificarDato(self, key, position):
aux_bol = False
if self.values[position] is not None:
if not self.values[position].buscarDato_binary(key):
aux_bol = True
return aux_bol
def eliminarDato(self, dato):
posicion_hash = self.funcionHash(dato)
nodo_hash = self.values[posicion_hash[0]]
if nodo_hash:
if nodo_hash.eliminar(posicion_hash[1]):
return 0
elif nodo_hash.eliminar(posicion_hash[1]) == 0:
return 0
self.values[posicion_hash] = None
else:
return 1
else:
return 4
def printTbl(self):
if self.values:
for i in self.values:
if i and (len(i.array) > 0):
print(str(i.key) + " | " + str(i.array) + "\n")
else:
return "vacio"
def buscar(self, dato):
posicion_hash = self.funcionHash(dato)
nodo = self.values[posicion_hash[0]]
if nodo is not None:
return nodo.busquedaB(posicion_hash[1])
else:
return []
def printlistTbl(self):
listTbl=[]
if self.values:
for i in self.values:
if i :
new = str(i.key) + " | " + str(i.array).replace('[','')
new2 = new.replace(']','')
listTbl.append(new2)
else:
print("vacio")
return listTbl
def imp1(self,columnNumber,lower,upper): ##Modificando este metodo
listCol=[]
for nodo in self.values:
if nodo is not None:
#print(nodo.array)
if len(nodo.array)>1:
for subnodo in nodo.array:
val = nodo.imp_column(subnodo[1],columnNumber,lower,upper) ##
if val != None:
listCol.append(val)
else:
val = nodo.imp_column2(columnNumber,lower,upper) ##
if val != None:
listCol.append(val)
return listCol
# agrega la nueva columna y asigna el valor
def alterAddColumn(self, dato):
if dato == []:
return 1
else:
self.nCols += 1
for i in self.values:
if i :
i.alterAddColumn(dato)
return 0
#19/12/2020
def getNumeroColumnas(self):
return self.nCols
def alterDropColumn(self, columnNumber):
if columnNumber in range(0, self.nCols):
if columnNumber <= self.nCols:
flag = False
if self.pk:
for key in self.pk:
if columnNumber == key:
return 4
pass
for i in self.values:
if i and len(i.array) > 1:
for j in i.array:
flag = True
j[1].pop(columnNumber)
pass
pass
if flag:
newKeys = []
if self.pk:
for key in self.pk:
if (key > columnNumber) and (key != 0):
key -= 1
newKeys.append(key)
self.nCols -= 1
self.pk = None
self.alterAddPK(newKeys)
return 0
else:
return 4
else:
return 4
else:
return 5
def alterDropPK(self):
if not self.pk:
return 4
else:
self.pk = None
for i in self.values:
if i:
i.isGeneric = True
return 0
#output_size = [ 4024,4024]
def genGraph(self, name):
f = Digraph("structs" , filename = name+".gv" , format = "svg",
node_attr={'shape' : 'record', } )
f.attr(rankdir='LR')
f.graph_attr['overlap']= 'false'
f.graph_attr['splines']= 'true'
hashTB = ''
contador = 0
for i in self.values:
if i:
hashTB += '<f' + str(contador) +'>' + str(i.key)+ '|'
contador +=1
hashTB = hashTB[0: len(hashTB)-1]
f.node('hash', hashTB,**{'height':str(50)})
datos = "{<n>"
for j in self.values:
count = 0
if j:
for i in j.array:
for k in i[1]:
datos += str(k) +"|"
datos+="<p>}"
with f.subgraph(name=str(j.key)+","+str(count) ) as a:
a.node("node" +str(j.key)+str(count),datos)
datos="{<n>"
count +=1
n = 0
for j in self.values:
m = 0
if j:
f.edges([("hash:f"+str(n), "node" +str(j.key)+str(0)+":n")])
for i in j.array:
if m+1 < len(j.array):
f.edges([("node" +str(j.key)+str(m)+":p", ("node"+str(j.key)+str(m+1)+":n" ))])
m+=1
n+=1
f.view()
| [
"noreply@github.com"
] | joorgej.noreply@github.com |
bccf9c9c28d20e34697457e1559fa9f6cf847ad5 | 46e070a5f7b2c9e9f3f2ce63482db0c726c401f5 | /dates.py | 0fd3441aac8f1db02f258934f179dcddb60bc20d | [] | no_license | Pawan300/Algorithms-Python | eefb5e56a3ea9de54302b2bfc6cc787c6fc365ff | fb6821a486b69f1130eef20de94500cb71dff72a | refs/heads/main | 2022-12-28T09:54:45.398189 | 2020-10-14T07:42:37 | 2020-10-14T07:42:37 | 303,651,105 | 1 | 0 | null | 2020-10-14T06:51:17 | 2020-10-13T09:22:23 | Python | UTF-8 | Python | false | false | 979 | py | date=[]
d1=[]
d=[]
t={}
l1=[]
month={"01":"Januaury",
"02":"Febuary",
"03":"March",
"04":"April",
"05":"May",
"06":"June",
"07":"July",
"08":"August",
"09":"September",
"10":"October",
"11":"November",
"12":"December"
}
print("\tRULES : \n1.DAY (1-31) \n2.MONTH(1-12) ")
for i in range(0,20):
d=input("Enter date : ") #For enter date
date=date+[d]
date_distinct=set(date)
d1=list(date_distinct)
print("distinct dates are : ") #For distinct date
print(date_distinct)
for j in range(0,len(d1)):
d=d1[j].split("/") #For print date with month name
if((d[1] in month)&(int(d[0]) in range(1,31))):
print(d[0],month[d[1]],d[2],end=" : ")
temp=input("Enter temperature for date : ")
l1=l1+[temp]
else:
l1=l1+["error"]
t=dict(zip(d1,l1))
print(t)
| [
"pawanbisht300@gmail.com"
] | pawanbisht300@gmail.com |
64cfa52924e87e6ae51b00d870885e958d99c04f | 6f679797132139025c3da60abc85ce449fa7241b | /IGclone/asgi.py | a6a8e04f6aa345af3ab24ba98ab0c3dc567a1504 | [] | no_license | kumarSuraj-bit/Django-project | 4aaf72e83cfdbff9e3b6a3b4bd8b808b07285c85 | c11326d744ace997f7e9f32ae6b5be1c5fb69266 | refs/heads/master | 2023-06-03T17:09:39.754343 | 2021-06-21T08:16:37 | 2021-06-21T08:16:37 | 376,090,023 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 391 | py | """
ASGI config for IGclone 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.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'IGclone.settings')
application = get_asgi_application()
| [
"surajk.ug19.ec@nitp.ac.in"
] | surajk.ug19.ec@nitp.ac.in |
97b80931157b4e7addebe8a0f9542f5bc0757cbb | 7d0e8a43700122d0c0aef44e95c0f3216b76607e | /functions/calculator.py | 949f6cf41d27e16de6d26275e32d1fa669a31f2b | [] | no_license | rohanchikorde/pythonChallenges | a4694992f012659045e54c2aa27b422da2a6949b | beff40bc6e27cd3f0578359190089c920ade6bda | refs/heads/main | 2023-03-12T18:42:20.091449 | 2021-03-05T11:37:35 | 2021-03-05T11:37:35 | 344,790,837 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,589 | py | # calculator python
def add(a, b):
"""Add two numbers and return sum"""
summation = round(a + b, 4)
print('summation of ' + str(a) + ' and ' + str(b) + ' is ' + str(summation) + '.')
return str(a) + ' + ' + str(b) + ' = ' + str(summation)
def subtract(a, b):
"""Subtract two numbers and return the difference"""
difference = round(a - b, 4)
print('Difference of ' + str(a) + ' and ' + str(b) + ' is ' + str(difference) + '.')
return str(a) + ' - ' + str(b) + ' = ' + str(difference)
def multiply(a, b):
"""multiply two numbers and return the product"""
product = round(a * b, 4)
print('Product of ' + str(a) + ' and ' + str(b) + ' is ' + str(product) + '.')
return str(a) + ' * ' + str(b) + ' = ' + str(product)
def divide(a , b):
"""divide two numbers and return the quotient"""
if b == 0:
print('You cannot be divided by zero')
return 'Div Error'
else:
quotient = round(a / b, 4)
print('The quotient of ' + str(a) + ' and ' + str(b) + ' is ' + str(quotient) + '.')
return str(a) + ' / ' + str(b) + ' = ' + str(quotient)
def exponent(a, b):
"""take a number to a power and return the result"""
power = round(a ** b, 4)
print('Power of ' + str(a) + ' raised to ' + str(b) + ' is ' + str(power) + '.')
return str(a) + ' ** ' + str(b) + ' = ' + str(power)
# Main function
def main():
print('\n--------- Welcome to the Python Calculator! ---------')
print('\n Enter two numbers and an operation desired')
history = []
running = True
while running:
# get user input
num1 = float(input('\n Enter a number: '))
num2 = float(input(' Enter a number: '))
operator = input('Enter an operation (add, sub, mul, div, exp): ').lower().strip()
if operator == 'add' or operator == 'a':
result = add(num1, num2)
elif operator == 'sub' or operator == 's':
result = subtract(num1, num2)
else:
print('\nThis is not a valid operation ')
result = 'Opp Error'
# append the result to the history
history.append(result)
choice = input('\nWould you like to run again? ').lower().strip()
if choice != 'y':
print('\nCalculation Summary: ')
for cal in history:
print(cal)
print('\nThank you for using python calculator')
running = False
main() | [
"noreply@github.com"
] | rohanchikorde.noreply@github.com |
2a8cf8a5b2a1b35d46343173ca83418793bb1fde | 396f729fd669865578cc5c4a02808a8c93cb5512 | /wangluo-pydicom.py | ba94a8545c48ec7229f865fa2b684ae83dc0400e | [] | no_license | liucz25/python-dicom-yanjiu | cef594805fba58c92c6f50e3169da48adfce4962 | 6a2983f404e99959ad494cceb0685f340c3b954e | refs/heads/master | 2020-05-29T20:16:03.567887 | 2019-12-31T13:15:30 | 2019-12-31T13:15:30 | 37,176,105 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,204 | py | # -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import pydicom
import pydicom.uid
import sys
import PIL.Image as Image
from PyQt5 import QtGui
import os
have_numpy = True
try:
import numpy
except ImportError:
have_numpy = False
raise
sys_is_little_endian = (sys.byteorder == 'little')
NumpySupportedTransferSyntaxes = [
pydicom.uid.ExplicitVRLittleEndian,
pydicom.uid.ImplicitVRLittleEndian,
pydicom.uid.DeflatedExplicitVRLittleEndian,
pydicom.uid.ExplicitVRBigEndian,
]
# ๆฏๆ็ไผ ่พ่ฏญๆณ
def supports_transfer_syntax(dicom_dataset):
"""
Returns
-------
bool
True if this pixel data handler might support this transfer syntax.
False to prevent any attempt to try to use this handler
to decode the given transfer syntax
"""
return (dicom_dataset.file_meta.TransferSyntaxUID in
NumpySupportedTransferSyntaxes)
def needs_to_convert_to_RGB(dicom_dataset):
return False
def should_change_PhotometricInterpretation_to_RGB(dicom_dataset):
return False
# ๅ ่ฝฝDicomๅพๅๆฐๆฎ
def get_pixeldata(dicom_dataset):
"""If NumPy is available, return an ndarray of the Pixel Data.
Raises
------
TypeError
If there is no Pixel Data or not a supported data type.
ImportError
If NumPy isn't found
NotImplementedError
if the transfer syntax is not supported
AttributeError
if the decoded amount of data does not match the expected amount
Returns
-------
numpy.ndarray
The contents of the Pixel Data element (7FE0,0010) as an ndarray.
"""
if (dicom_dataset.file_meta.TransferSyntaxUID not in
NumpySupportedTransferSyntaxes):
raise NotImplementedError("Pixel Data is compressed in a "
"format pydicom does not yet handle. "
"Cannot return array. Pydicom might "
"be able to convert the pixel data "
"using GDCM if it is installed.")
# ่ฎพ็ฝฎ็ชๅฎฝ็ชไฝ
#dicom_dataset.
if not have_numpy:
msg = ("The Numpy package is required to use pixel_array, and "
"numpy could not be imported.")
raise ImportError(msg)
if 'PixelData' not in dicom_dataset:
raise TypeError("No pixel data found in this dataset.")
# Make NumPy format code, e.g. "uint16", "int32" etc
# from two pieces of info:
# dicom_dataset.PixelRepresentation -- 0 for unsigned, 1 for signed;
# dicom_dataset.BitsAllocated -- 8, 16, or 32
if dicom_dataset.BitsAllocated == 1:
# single bits are used for representation of binary data
format_str = 'uint8'
elif dicom_dataset.PixelRepresentation == 0:
format_str = 'uint{}'.format(dicom_dataset.BitsAllocated)
elif dicom_dataset.PixelRepresentation == 1:
format_str = 'int{}'.format(dicom_dataset.BitsAllocated)
else:
format_str = 'bad_pixel_representation'
try:
numpy_dtype = numpy.dtype(format_str)
except TypeError:
msg = ("Data type not understood by NumPy: "
"format='{}', PixelRepresentation={}, "
"BitsAllocated={}".format(
format_str,
dicom_dataset.PixelRepresentation,
dicom_dataset.BitsAllocated))
raise TypeError(msg)
if dicom_dataset.is_little_endian != sys_is_little_endian:
numpy_dtype = numpy_dtype.newbyteorder('S')
pixel_bytearray = dicom_dataset.PixelData
if dicom_dataset.BitsAllocated == 1:
# if single bits are used for binary representation, a uint8 array
# has to be converted to a binary-valued array (that is 8 times bigger)
try:
pixel_array = numpy.unpackbits(
numpy.frombuffer(pixel_bytearray, dtype='uint8'))
except NotImplementedError:
# PyPy2 does not implement numpy.unpackbits
raise NotImplementedError(
'Cannot handle BitsAllocated == 1 on this platform')
else:
pixel_array = numpy.frombuffer(pixel_bytearray, dtype=numpy_dtype)
length_of_pixel_array = pixel_array.nbytes
expected_length = dicom_dataset.Rows * dicom_dataset.Columns
if ('NumberOfFrames' in dicom_dataset and
dicom_dataset.NumberOfFrames > 1):
expected_length *= dicom_dataset.NumberOfFrames
if ('SamplesPerPixel' in dicom_dataset and
dicom_dataset.SamplesPerPixel > 1):
expected_length *= dicom_dataset.SamplesPerPixel
if dicom_dataset.BitsAllocated > 8:
expected_length *= (dicom_dataset.BitsAllocated // 8)
padded_length = expected_length
if expected_length & 1:
padded_length += 1
if length_of_pixel_array != padded_length:
raise AttributeError(
"Amount of pixel data %d does not "
"match the expected data %d" %
(length_of_pixel_array, padded_length))
if expected_length != padded_length:
pixel_array = pixel_array[:expected_length]
if should_change_PhotometricInterpretation_to_RGB(dicom_dataset):
dicom_dataset.PhotometricInterpretation = "RGB"
if dicom_dataset.Modality.lower().find('ct') >= 0: # CTๅพๅ้่ฆๅพๅฐๅ
ถCTๅผๅพๅ
pixel_array = pixel_array * dicom_dataset.RescaleSlope + dicom_dataset.RescaleIntercept # ่ทๅพๅพๅ็CTๅผ
pixel_array = pixel_array.reshape(dicom_dataset.Rows, dicom_dataset.Columns*dicom_dataset.SamplesPerPixel)
return pixel_array, dicom_dataset.Rows, dicom_dataset.Columns
# ่ฐๆดCTๅพๅ็็ชๅฎฝ็ชไฝ
def setDicomWinWidthWinCenter(img_data, winwidth, wincenter, rows, cols):
img_temp = numpy.zeros((rows,cols),dtype=numpy.int16)
img_temp.flags.writeable = True
min = (2 * wincenter - winwidth) / 2.0 + 0.5
max = (2 * wincenter + winwidth) / 2.0 + 0.5
dFactor = 255.0 / (max - min)
for i in numpy.arange(rows):
for j in numpy.arange(cols):
img_temp[i, j] = int((img_data[i, j]-min)*dFactor)
min_index = img_temp < 0
img_temp[min_index] = 0
max_index = img_temp > 255
img_temp[max_index] = 255
return img_temp
# ๅ ่ฝฝDicomๅพ็ไธญ็Tagไฟกๆฏ
def loadFileInformation(filename):
information = {}
ds = pydicom.read_file(filename)
information['PatientID'] = ds.PatientID
information['PatientName'] = ds.PatientName
information['PatientBirthDate'] = ds.PatientBirthDate
information['PatientSex'] = ds.PatientSex
information['StudyID'] = ds.StudyID
information['StudyDate'] = ds.StudyDate
information['StudyTime'] = ds.StudyTime
information['InstitutionName'] = ds.InstitutionName
information['Manufacturer'] = ds.Manufacturer
print(dir(ds))
print(type(information))
return information
if __name__=="__main__":
filename="Image15.dcm"
dcm = pydicom.dcmread(filename) # ๅ ่ฝฝDicomๆฐๆฎ
# infr=loadFileInformation(filename)
img,wight,hight=get_pixeldata(dcm)
img_lung=setDicomWinWidthWinCenter(img,1500,-500,wight,hight)
data_lung=Image.fromarray(img_lung)
data_lung = data_lung.convert('L')
#data_lung.show()
img_abd=setDicomWinWidthWinCenter(img,350,200,wight,hight)
data_abd=Image.fromarray(img_abd)
data_abd = data_abd.convert('L')
#data_abd.show()
img_bone=setDicomWinWidthWinCenter(img,2000,800,wight,hight)
data_bone=Image.fromarray(img_bone)
data_bone = data_bone.convert('L')
#data_bone.show()
imgdata=setDicomWinWidthWinCenter(img,650,250,wight,hight)
dcm_img = Image.fromarray(imgdata) # ๅฐNumpy่ฝฌๆขไธบPIL.Image
dcm_img = dcm_img.convert('L')
#dcm_img.show()
sanse=numpy.array([img_abd,img_bone,img_lung,])
img_data2=sanse.transpose(1,2,0)
# dcm_img2 = Image.fromarray(img_data2) # ๅฐNumpy่ฝฌๆขไธบPIL.Image
# dcm_img2.show()
plt.imshow(img_data2)
# plt.gray()
plt.show()
| [
"noreply@github.com"
] | liucz25.noreply@github.com |
75b2cd516f53f446e65c67a6b9b93280787fb678 | d26bb53d00360bafa9d15890b93d56ef3337a74f | /banking_auth_templ_models/personalbanking/views.py | f96fc4d54530e02d28d9c58c3a01126bc432cafc | [] | no_license | Logeswaran-gnt/Banking-Domain | a79a04ef1a1230ec54868066710d6a81ddf62855 | f2b3dadc479ee50088693214936f1c8d526d6659 | refs/heads/master | 2022-11-24T00:38:35.870722 | 2020-08-01T11:12:12 | 2020-08-01T11:12:12 | 262,955,735 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 172 | py | from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("reached personal banking") | [
"logeswaran.gnt@gmail.com"
] | logeswaran.gnt@gmail.com |
b25d7d16789ce89a7bc2e8f4eb87ee12cf48308b | 7b68262e8cff6aeb402fe37d056366194cc4599a | /fcis/InstanceSegmentation_Sentinel2/utils/mxnet_fcis_predict.py | 30d206d922ac3021c2a4a22d703d551e573122f7 | [
"MIT"
] | permissive | ecohydro/CropMask_RCNN | ee2d5e60a6687e1c3a31718bc912bef41c6e9697 | b7535ed241baa1fe0f055ee0c91e1b2b3ad7f9f3 | refs/heads/master | 2022-02-11T00:36:17.330109 | 2022-02-07T07:31:38 | 2022-02-07T07:31:38 | 168,214,774 | 20 | 3 | MIT | 2021-02-26T07:15:06 | 2019-01-29T19:29:16 | Jupyter Notebook | UTF-8 | Python | false | false | 6,255 | py |
def predict_on_image_names(image_names, config, model_path_id="/home/data/output/resnet_v1_101_coco_fcis_end2end_ohem-nebraska/train-nebraska/e2e",epoch=8):
import argparse
import os
import sys
import logging
import pprint
import cv2
from utils.image import resize, transform
import numpy as np
# get config
os.environ['PYTHONUNBUFFERED'] = '1'
os.environ['MXNET_CUDNN_AUTOTUNE_DEFAULT'] = '0'
os.environ['MXNET_ENABLE_GPU_P2P'] = '0'
cur_path = os.path.abspath(".")
sys.path.insert(0, os.path.join(cur_path, '../external/mxnet', config.MXNET_VERSION))
import mxnet as mx
print("use mxnet at", mx.__file__)
from core.tester import im_detect, Predictor
from symbols import *
from utils.load_model import load_param
from utils.show_masks import show_masks
from utils.tictoc import tic, toc
from nms.nms import py_nms_wrapper
from mask.mask_transform import gpu_mask_voting, cpu_mask_voting
# get symbol
ctx_id = [int(i) for i in config.gpus.split(',')]
sym_instance = eval(config.symbol)()
sym = sym_instance.get_symbol(config, is_train=False)
# set up class names
num_classes = 2
classes = ['cp']
# load demo data
data = []
for im_name in image_names:
assert os.path.exists(im_name), ('%s does not exist'.format(im_name))
im = cv2.imread(im_name, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)
target_size = config.SCALES[0][0]
max_size = config.SCALES[0][1]
im, im_scale = resize(im, target_size, max_size, stride=config.network.IMAGE_STRIDE)
im_tensor = transform(im, config.network.PIXEL_MEANS)
im_info = np.array([[im_tensor.shape[2], im_tensor.shape[3], im_scale]], dtype=np.float32)
data.append({'data': im_tensor, 'im_info': im_info})
# get predictor
data_names = ['data', 'im_info']
label_names = []
data = [[mx.nd.array(data[i][name]) for name in data_names] for i in xrange(len(data))]
max_data_shape = [[('data', (1, 3, max([v[0] for v in config.SCALES]), max([v[1] for v in config.SCALES])))]]
provide_data = [[(k, v.shape) for k, v in zip(data_names, data[i])] for i in xrange(len(data))]
provide_label = [None for i in xrange(len(data))]
# loading the last epoch that was trained, 8
arg_params, aux_params = load_param(model_path_id, epoch, process=True)
predictor = Predictor(sym, data_names, label_names,
context=[mx.gpu(ctx_id[0])], max_data_shapes=max_data_shape,
provide_data=provide_data, provide_label=provide_label,
arg_params=arg_params, aux_params=aux_params)
all_classes = []
all_configs = []
all_masks = []
all_dets = []
all_ims = []
# warm up
for i in xrange(2):
data_batch = mx.io.DataBatch(data=[data[0]], label=[], pad=0, index=0,
provide_data=[[(k, v.shape) for k, v in zip(data_names, data[0])]],
provide_label=[None])
scales = [data_batch.data[i][1].asnumpy()[0, 2] for i in xrange(len(data_batch.data))]
_, _, _, _ = im_detect(predictor, data_batch, data_names, scales, config)
# test
for idx, im_name in enumerate(image_names):
data_batch = mx.io.DataBatch(data=[data[idx]], label=[], pad=0, index=idx,
provide_data=[[(k, v.shape) for k, v in zip(data_names, data[idx])]],
provide_label=[None])
scales = [data_batch.data[i][1].asnumpy()[0, 2] for i in xrange(len(data_batch.data))]
tic()
scores, boxes, masks, data_dict = im_detect(predictor, data_batch, data_names, scales, config)
im_shapes = [data_batch.data[i][0].shape[2:4] for i in xrange(len(data_batch.data))]
if not config.TEST.USE_MASK_MERGE:
all_boxes = [[] for _ in xrange(num_classes)]
all_masks = [[] for _ in xrange(num_classes)]
nms = py_nms_wrapper(config.TEST.NMS)
for j in range(1, num_classes):
indexes = np.where(scores[0][:, j] > 0.7)[0]
cls_scores = scores[0][indexes, j, np.newaxis]
cls_masks = masks[0][indexes, 1, :, :]
try:
if config.CLASS_AGNOSTIC:
cls_boxes = boxes[0][indexes, :]
else:
raise Exception()
except:
cls_boxes = boxes[0][indexes, j * 4:(j + 1) * 4]
cls_dets = np.hstack((cls_boxes, cls_scores))
keep = nms(cls_dets)
all_boxes[j] = cls_dets[keep, :]
all_masks[j] = cls_masks[keep, :]
dets = [all_boxes[j] for j in range(1, num_classes)]
masks = [all_masks[j] for j in range(1, num_classes)]
else:
masks = masks[0][:, 1:, :, :]
im_height = np.round(im_shapes[0][0] / scales[0]).astype('int')
im_width = np.round(im_shapes[0][1] / scales[0]).astype('int')
print (im_height, im_width)
boxes = clip_boxes(boxes[0], (im_height, im_width))
result_masks, result_dets = gpu_mask_voting(masks, boxes, scores[0], num_classes,
100, im_width, im_height,
config.TEST.NMS, config.TEST.MASK_MERGE_THRESH,
config.BINARY_THRESH, ctx_id[0])
dets = [result_dets[j] for j in range(1, num_classes)]
masks = [result_masks[j][:, 0, :, :] for j in range(1, num_classes)]
print ('testing {} {:.4f}s'.format(im_name, toc()))
# visualize
for i in xrange(len(dets)):
keep = np.where(dets[i][:,-1]>0.7)
dets[i] = dets[i][keep]
masks[i] = masks[i][keep]
all_classes.append(classes)
all_configs.append(config)
all_masks.append(masks)
all_dets.append(dets)
im = cv2.imread(im_name)
all_ims.append(im)
return all_ims, all_dets, all_masks, all_configs, all_classes | [
"ravery@ucsb.edu"
] | ravery@ucsb.edu |
efd6665975ffe1ab4121c32f379cd14cb8273d76 | e0e66fe2dc2ba39502c95da924bb3330a2b5102e | /get_geotagged_posts.py | 429c035fcc52c80ebec6c626da6e9e49f479e398 | [] | no_license | DigitalGeographyLab/maphel-finlang | d1835b1398cdd1bf79eddb353b3e3e78f2fe550b | d756e284ab2956d12058d8171a58f1d73b956aac | refs/heads/master | 2023-03-03T10:00:36.947159 | 2021-02-04T12:59:42 | 2021-02-04T12:59:42 | 249,674,371 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,329 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 5 15:19:55 2020
INFO
####
This script reads geotagged tweets from a PostgreSQL database table to a pandas
dataframe and saves it locally to disk as a pickled dataframe.
USAGE
#####
Run the script with the following command:
python get_geotagged_posts.py -ho your.host.com -db databasename -u username
-pw password -tb table -o path/to/tweets.pkl
NOTE
####
This script saves both a GeoDataFrame and a normal DataFrame. GeoDataFrame file
is indicated by the '.gpkg' ending in the filename.
@author: Tuomas Vรคisรคnen
"""
import pandas as pd
import psycopg2
import geopandas as gpd
from sqlalchemy.engine.url import URL
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy.orm import sessionmaker
import argparse
# Set up the argument parser
ap = argparse.ArgumentParser()
# Define the path to input database
ap.add_argument("-ho", "--host", required=True,
help="Address of your database server")
# Name of the database to connect to on host server
ap.add_argument("-db", "--database", required=True,
help="Database name")
# User name for the database on the host server
ap.add_argument("-u", "--user", required=True,
help="Your username in the database")
# Password for user
ap.add_argument("-pw", "--password", required=True,
help="Your password in the database")
# Table in database
ap.add_argument("-tb", "--table", required=True,
help="Table your data is in")
# Output file
ap.add_argument("-o", "--output", required=True,
help="Path to output file")
# Parse arguments
args = vars(ap.parse_args())
# Assign arguments to variables
database = args['datanase']
host = args['host']
user = args['user']
pw = args['password']
tablename = args['table']
geoutput = args['output']
geoutput = geoutput[:-4] + '.gpkg'
# Database info
print("[INFO] - Setting up database URL...")
db_url = URL(drivername='postgresql+psycopg2', host=host, database=database,
username=user, port=5432, password=pw)
# Create engine
print("[INFO] - Creating database engine...")
engine = create_engine(db_url, use_batch_mode=True)
# set up database connection
con = psycopg2.connect(database=database, user=user, password=pw,
host=host)
print('[INFO] - Connected to ' + str(database) + ' at ' + str(host))
# Init Metadata
meta = MetaData()
# Create session
print("[INFO] - Launching database session...")
Session = sessionmaker(bind=engine)
session = Session()
# sql to get geotagged posts with language detections
sql = "SELECT id, user_id, created_at, string_agg(language::character varying,';') as langs, latitude, longitude"\
" FROM " + tablename + " WHERE prob >= 0.7 AND lat IS NOT NULL "\
" GROUP BY id, user_id, created_at, latitude, longitude;"
# retrieve data
print("[INFO] - Querying to dataframe...")
df = pd.read_sql(sql, con=con)
# convert to geodataframe with WGS-84 crs
gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df['longitude'], df['latitude']),
crs='EPSG:4326')
# save to output file
print("[INFO] - Saving to disk...")
df.to_pickle(args['output'])
gdf.to_file(geoutput, driver='GPKG')
print("[INFO] - ... done!") | [
"tuomvais@dx8-500-039.science.helsinki.fi"
] | tuomvais@dx8-500-039.science.helsinki.fi |
fc8246245e72888781cf600c09d2aae16ba4208b | 21c4efd4d4a657fe1d3b3903729846f56f961f34 | /jaipur.py | 8980192002832cc664707dacc00b677b0f91a45d | [] | no_license | chrislopez28/jaipur-simulation | 0ad007f1761d87250d4a387b340ba515c4368b40 | 9f1827dbfcf091e50bbb418f536c8089ae53d009 | refs/heads/master | 2022-11-25T10:14:12.792613 | 2020-08-05T06:53:56 | 2020-08-05T06:53:56 | 285,190,637 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,516 | py | """Python implementation of a trading game based on Jaipur"""
import random
NUM_DIAMOND = 6
NUM_GOLD = 6
NUM_SILVER = 6
NUM_CLOTH = 8
NUM_SPICES = 8
NUM_LEATHER = 10
NUM_CAMEL = 8
INITIAL_HAND_LENGTH = 5
CARD_TYPES = {
"Diamond": NUM_DIAMOND,
"Gold": NUM_GOLD,
"Silver": NUM_SILVER,
"Cloth": NUM_CLOTH,
"Spices": NUM_SPICES,
"Leather": NUM_LEATHER,
"Camel": NUM_CAMEL
}
CHIP_VALUES = {
"Diamond": [5, 5, 5, 7, 7],
"Gold": [5, 5, 5, 6, 6],
"Silver": [5, 5, 5, 5, 5],
"Cloth": [1, 1, 2, 2, 3, 3, 3],
"Spices": [1, 1, 2, 2, 3, 3, 5],
"Leather": [1, 1, 1, 1, 1, 1, 2, 3, 4]
}
BONUS_THREE = [1, 1, 2, 2, 2, 3, 3]
BONUS_FOUR = [4, 4, 5, 5, 6, 6]
BONUS_FIVE = [8, 8, 9, 10, 10]
class Card:
"""Representation of Playing Cards"""
def __init__(self, card_type: str) -> None:
self.card_type = card_type
def __repr__(self) -> None:
return f"{self.card_type}"
class Chip:
"""Representation of Playing Chips"""
def __init__(self, chip_type: str, value: int) -> None:
self.chip_type = chip_type
self.value = value
class ChipStack():
"""Representation of a Stack of Available Chips"""
def __init__(self, chip_type: str) -> None:
self.chips = CHIP_VALUES[chip_type]
def __repr__(self) -> str:
return f"{self.chips}"
class ChipMarket():
"""Representation of all available chips"""
def __init__(self) -> None:
self.diamond = ChipStack("Diamond")
self.gold = ChipStack("Gold")
self.silver = ChipStack("Silver")
self.cloth = ChipStack("Cloth")
self.spices = ChipStack("Spices")
self.leather = ChipStack("Leather")
def __repr__(self) -> str:
return f"""
Diamond: {self.diamond}
Gold: {self.gold}
Silver: {self.silver}
Cloth: {self.cloth}
Spices: {self.spices}
Leather: {self.leather}"""
class Hand:
"""Player Hand"""
def __init__(self) -> None:
self.cards = []
self.herd = []
def has_three_of_a_good(self) -> bool:
"""Check if the hand has 3 of any type of good"""
return self.__has_n_of_a_good(3)
def has_four_of_a_good(self) -> bool:
"""Check if the hand has 4 of any type of good"""
return self.__has_n_of_a_good(4)
def has_five_of_a_good(self) -> bool:
"""Check if the hand has 5 of any type of good"""
return self.__has_n_of_a_good(5)
def has_good(self, good: str, n: int = 1) -> bool:
"""Check if the hand has some number n of a particular good"""
assert n >= 1 & n <= 7
count = 0
for card in self.cards:
if card.card_type == good:
count += 1
if count >= n:
return True
return False
def summarize(self) -> dict:
summary = {key:0 for key in CARD_TYPES}
for card in self.cards:
summary[card.card_type] += 1
summary["Camel"] += len(self.herd)
return summary
def __has_n_of_a_good(self, n: int) -> bool:
for good in CARD_TYPES:
if good == "Camel":
next
if self.has_good(good, n):
return True
return False
def __repr__(self) -> str:
return f"""Goods: {self.cards}, Camels: {len(self.herd)}"""
class Deck:
"""Representation of Deck"""
def __init__(self, shuffle: bool = True) -> None:
self.cards = []
for card_type in CARD_TYPES:
for _ in range(CARD_TYPES[card_type]):
self.cards.append(Card(card_type))
if shuffle:
self.shuffle()
def shuffle(self) -> None:
"""Shuffles the deck"""
length = len(self.cards)
for i in range(length):
selected = random.randint(i, length - 1)
temp = self.cards[i]
self.cards[i] = self.cards[selected]
self.cards[selected] = temp
def deal_hand(self, hand: Hand) -> None:
"""Deals cards from Deck to a specified hand object"""
for _ in range(INITIAL_HAND_LENGTH):
temp = self.cards.pop()
if temp.card_type == "Camel":
hand.herd.append(temp)
else:
hand.cards.append(temp)
class Market:
"""Representation of Market"""
def __init__(self) -> None:
self.cards = []
class Discard:
"""Representation of Discard Pile"""
def __init__(self) -> None:
self.cards = [] | [
"chrislopez28@gmail.com"
] | chrislopez28@gmail.com |
628f4ac22f2789cdbb844383f72b1cf54801034b | 4f5c062ce52c1653d092431517a671e979612104 | /rest_server/resource.py | 74f3faef68ffd84167cce31efbe3299e278b5d61 | [] | no_license | Kjwanm/SOA_CLASS | adc9cb4668d63414f8f0f9fe72c0fbf0db699940 | f1065841773a5fc7241a2105c7ce1c3596ce845c | refs/heads/master | 2020-09-29T10:50:15.397130 | 2019-12-17T07:53:32 | 2019-12-17T07:53:32 | 227,022,104 | 0 | 0 | null | null | null | null | UHC | Python | false | false | 5,554 | py | #-*- coding:cp949 -*-
import json
from flask import make_response, render_template, jsonify, Response
from flask.json import dumps
from flask_restful import Resource, abort, reqparse
from database.resource_db_access import EducationResourceDatabase
class EducationResource(Resource):
def __init__(self):
self.education_resource_db = EducationResourceDatabase()
self.parser = reqparse.RequestParser()
self.parser.add_argument('sigun')
self.parser.add_argument('emd')
self.parser.add_argument('types')
self.parser.add_argument('named')
self.parser.add_argument('daepyo')
self.parser.add_argument('telno')
self.parser.add_argument('address')
self.parser.add_argument('lat')
self.parser.add_argument('loat')
def get(self, named):
education = self.education_resource_db.readByNamed(named=named)
print(education)
if education is None:
return Response("์ด๋ฆ : {0} ๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค.".format(named), status=404, mimetype='application/json; charset=utf-8')
else:
return Response(dumps(education, ensure_ascii=False), content_type='application/json; charset=utf-8')
def put(self, named):
args = self.parser.parse_args()
education = self.education_resource_db.readByNamed(named=named)
if education is None:
return Response("์ด๋ฆ : {0} ๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค.".format(named), status=404, mimetype='application/json; charset=utf-8')
else:
self.education_resource_db.update(
sigun=args['sigun'],
emd=args['emd'],
types=args['types'],
daepyo=args['daepyo'],
telno=args['telno'],
address=args['address'],
lat=args['lat'],
loat=args['loat']
)
return Response("์ด๋ฆ : {0},".format(named), status=200, mimetype='application/json; charset=utf-8')
def delete(self, named):
education = self.education_resource_db.readByNamed(named=named)
if education is None:
return Response("์ด๋ฆ : {0},".format(named), status=204, mimetype='application/json; charset=utf-8')
else:
self.education_resource_db.delete(named=named)
return Response("์ด๋ฆ : {0},".format(named), status=204, mimetype='application/json; charset=utf-8')
class EducationCreationResource(Resource):
def __init__(self):
self.education_resource_db = EducationResourceDatabase()
self.parser = reqparse.RequestParser()
self.parser.add_argument('sigun')
self.parser.add_argument('emd')
self.parser.add_argument('types')
self.parser.add_argument('named')
self.parser.add_argument('daepyo')
self.parser.add_argument('telno')
self.parser.add_argument('address')
self.parser.add_argument('lat')
self.parser.add_argument('loat')
def post(self):
args = self.parser.parse_args()
named = args['named']
education = self.education_resource_db.readByNamed(named=named)
if education is not None:
return Response("์ด๋ฆ : {0}๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค!!,".format(named), status=409, mimetype='application/json; charset=utf-8')
else:
self.education_resource_db.crate(
sigun=args['sigun'],
emd=args['emd'],
types=args['types'],
named=named,
daepyo=args['daepyo'],
telno=args['telno'],
address=args['address'],
lat=args['lat'],
loat=args['loat']
)
return Response("์ด๋ฆ : {0},".format(named), status=201, mimetype='application/json; charset=utf-8')
class EducationByLocationResource(Resource):
def __init__(self):
self.education_resource_db = EducationResourceDatabase()
def get(self, sigun):
education = self.education_resource_db.readByLocation(sigun=sigun)
if education is None:
# abort(404, message="sigun {0} doesn't exist".format(sigun))
return Response("์๊ตฐ์ ๋ณด : {0} ๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค.".format(sigun), status=404, mimetype='application/json; charset=utf-8')
else:
return Response(dumps(education, ensure_ascii=False), content_type='application/json; charset=utf-8')
class EducationByEMDResource(Resource):
def __init__(self):
self.education_resource_db = EducationResourceDatabase()
def get(self, emd):
education = self.education_resource_db.readByEMD(emd=emd)
if education is None:
return Response("์๋ฉด๋ : {0} ๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค.".format(emd), status=404, mimetype='application/json; charset=utf-8')
else:
return Response(dumps(education, ensure_ascii=False), content_type='application/json; charset=utf-8')
class EducationByDistance(Resource):
def __init__(self):
self.education_resource_db = EducationResourceDatabase()
def get(self, named):
education = self.education_resource_db.readByDistance(named=named)
if education is None:
return Response("ํด๋นํ๋ ํ์ : {0} ๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค.".format(named), status=404, mimetype='application/json; charset=utf-8')
else:
return Response(dumps(education, ensure_ascii=False), content_type='application/json; charset=utf-8') | [
"kjwanm@naver.com"
] | kjwanm@naver.com |
572a956c2808994ebfbbc2d4099b2d77b4d1188e | 62ca0c921eb07b489a9d00cdfc40d12f06ac9bb1 | /win_schedule.py | e54258e16aa48920ec426acd9e9869bfdee9f59a | [
"MIT"
] | permissive | gauravengine/Cowin-Slots-Notifier | 57248c7f574a3a1164f81dd9f63bbaa00daea641 | 5720481d25bfb74832d207c4dc6367f92ee822c8 | refs/heads/main | 2023-09-01T00:34:45.047042 | 2021-10-24T14:29:07 | 2021-10-24T14:29:07 | 375,738,339 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,081 | py | import requests
import time
from datetime import datetime
import winsound
fileName= open('log.txt','a')
today = datetime.today()
d1 = today.strftime("%d-%m-%Y")
#implement search
pinCode = 110043 #hardcoded for Najafgarh
date = d1
district_id = 150 #hardcoded for South West Delhi
URL = 'https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByPin?pincode={}&date={}'.format(
pinCode, date)
# URL='https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict?district_id={}&date={}'.format(district_id,date)
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
# 1 for availaibility play shape of you and sleep for 30seconds
# 2 for not availaibility sleep for 10 seconds
try:
result = requests.get(URL, headers=header)
except requests.exceptions.RequestException as e: # This is the correct syntax
raise SystemExit(e)
response_json = result.json()
data = response_json["sessions"]
#print(data)
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
# print log as time and centres in log file
print("---------------------finder has begun-------------------------------",file=fileName)
print("Current Time = {}".format(current_time),file=fileName)
flag = False
#playsound(r'C:\Users\gengi\Desktop\Cowin_Bot\ding-sound.mp3') #remove it just for testing
for each in data:
if((each["available_capacity_dose1"] > 0) & (each["min_age_limit"] == 18) & (each["fee"] == "0")):
#print("Hello there")
print("Name of Center : {}".format(each["name"]),file=fileName)
print("Pincode of the Center : {}".format(each["pincode"]),file=fileName)
print("Type of Vaccine : {}".format(each["vaccine"]),file=fileName)
print("No of Vaccines Available : {}".format(each["available_capacity"]),file=fileName)
flag = True
#playsound(r'ding-sound.wav') #just check it
#print the center details in a file
if(flag):
winsound.PlaySound('notification_sound.wav', winsound.SND_FILENAME)
| [
"gengine232@gmail.com"
] | gengine232@gmail.com |
829bc2de78bd6e898108a4307b33c8632d7cc472 | 0331dc54aebe833da24028892404e49b3d644601 | /pettingzoo/sisl/pursuit/pursuit_base.py | 1fe06e6e02444bf392643dc79fd48ad5653cb843 | [] | no_license | aecgames-paper/aecgames | 56a70288d20cbd56c23420cb7e5b79578246bcb0 | 3e9c8e0b7a522676c0e17004790fa966556a211a | refs/heads/master | 2023-02-21T23:25:02.391817 | 2021-01-20T21:23:14 | 2021-01-20T21:23:14 | 331,433,744 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 18,264 | py | import glob
import os
from os.path import join
from subprocess import call
import numpy as np
from gym import spaces
from gym.utils import seeding
import pygame
from .utils import agent_utils
from .utils.agent_layer import AgentLayer
from .utils.controllers import RandomPolicy, SingleActionPolicy
from .utils import two_d_maps
class Pursuit():
def __init__(self, **kwargs):
"""
In evade purusit a set of pursuers must 'tag' a set of evaders
Required arguments:
x_size, y_size: World size
local_ratio: proportion of reward allocated locally vs distributed among all agents
n_evaders
n_pursuers
obs_range: how far each agent can see
Optional arguments:
pursuer controller: stationary policy of ally pursuers
evader controller: stationary policy of opponent evaders
tag_reward: reward for 'tagging' a single evader
max_cycles: after how many frames should the game end
n_catch: how surrounded evader needs to be, before removal
freeze_evaders: toggle evaders move or not
catch_reward: reward for pursuer who catches an evader
urgency_reward: reward added in each step
surround: toggles surround condition for evader removal
constraint_window: window in which agents can randomly spawn
"""
self.x_size = kwargs.pop('x_size', 16)
self.y_size = kwargs.pop('y_size', 16)
x_size = self.x_size
y_size = self.y_size
self.map_matrix = two_d_maps.rectangle_map(self.x_size, self.y_size)
self.max_cycles = kwargs.pop("max_cycles", 500)
self.seed()
self.local_ratio = kwargs.pop('local_ratio', 1.0)
self.n_evaders = kwargs.pop('n_evaders', 30)
self.n_pursuers = kwargs.pop('n_pursuers', 8)
self.num_agents = self.n_pursuers
self.latest_reward_state = [0 for _ in range(self.num_agents)]
self.latest_done_state = [False for _ in range(self.num_agents)]
self.latest_obs = [None for _ in range(self.num_agents)]
# can see 7 grids around them by default
self.obs_range = kwargs.pop('obs_range', 7)
# assert self.obs_range % 2 != 0, "obs_range should be odd"
self.obs_offset = int((self.obs_range - 1) / 2)
self.pursuers = agent_utils.create_agents(
self.n_pursuers, self.map_matrix, self.obs_range, self.np_random)
self.evaders = agent_utils.create_agents(
self.n_evaders, self.map_matrix, self.obs_range, self.np_random)
self.pursuer_layer = AgentLayer(x_size, y_size, self.pursuers)
self.evader_layer = AgentLayer(x_size, y_size, self.evaders)
self.n_catch = kwargs.pop('n_catch', 2)
n_act_purs = self.pursuer_layer.get_nactions(0)
n_act_ev = self.evader_layer.get_nactions(0)
self.freeze_evaders = kwargs.pop('freeze_evaders', False)
if self.freeze_evaders:
self.evader_controller = kwargs.pop(
'evader_controller', SingleActionPolicy(4))
self.pursuer_controller = kwargs.pop(
'pursuer_controller', SingleActionPolicy(4))
else:
self.evader_controller = kwargs.pop(
'evader_controller', RandomPolicy(n_act_purs, self.np_random))
self.pursuer_controller = kwargs.pop(
'pursuer_controller', RandomPolicy(n_act_ev, self.np_random))
self.current_agent_layer = np.zeros((x_size, y_size), dtype=np.int32)
self.tag_reward = kwargs.pop('tag_reward', 0.01)
self.catch_reward = kwargs.pop('catch_reward', 5.0)
self.urgency_reward = kwargs.pop('urgency_reward', 0.0)
self.ally_actions = np.zeros(n_act_purs, dtype=np.int32)
self.opponent_actions = np.zeros(n_act_ev, dtype=np.int32)
max_agents_overlap = max(self.n_pursuers, self.n_evaders)
obs_space = spaces.Box(low=0, high=max_agents_overlap, shape=(
self.obs_range, self.obs_range, 3), dtype=np.float32)
act_space = spaces.Discrete(n_act_purs)
self.action_space = [act_space for _ in range(self.n_pursuers)]
self.observation_space = [obs_space for _ in range(self.n_pursuers)]
self.act_dims = [n_act_purs for i in range(self.n_pursuers)]
self.evaders_gone = np.array([False for i in range(self.n_evaders)])
self.surround = kwargs.pop('surround', True)
self.constraint_window = kwargs.pop('constraint_window', 1.0)
self.surround_mask = np.array([[-1, 0], [1, 0], [0, 1], [0, -1]])
self.model_state = np.zeros(
(4,) + self.map_matrix.shape, dtype=np.float32)
self.renderOn = False
self.pixel_scale = 30
self.frames = 0
self.reset()
assert not kwargs, f"gave arguments {list(kwargs.keys())} that are not valid pursuit arguments"
def close(self):
if self.renderOn:
pygame.event.pump()
pygame.display.quit()
pygame.quit()
#################################################################
# The functions below are the interface with MultiAgentSiulator #
#################################################################
@property
def agents(self):
return self.pursuers
def seed(self, seed=None):
self.np_random, seed_ = seeding.np_random(seed)
try:
policies = [self.evader_controller, self.pursuer_controller]
for policy in policies:
try:
policy.set_rng(self.np_random)
except AttributeError:
pass
except AttributeError:
pass
return [seed_]
def get_param_values(self):
return self.__dict__
def reset(self):
self.evaders_gone.fill(False)
x_window_start = self.np_random.uniform(0.0, 1.0 - self.constraint_window)
y_window_start = self.np_random.uniform(0.0, 1.0 - self.constraint_window)
xlb, xub = int(self.x_size * x_window_start), int(self.x_size * (x_window_start + self.constraint_window))
ylb, yub = int(self.y_size * y_window_start), int(self.y_size * (y_window_start + self.constraint_window))
constraints = [[xlb, xub], [ylb, yub]]
self.pursuers = agent_utils.create_agents(self.n_pursuers, self.map_matrix, self.obs_range, self.np_random,
randinit=True, constraints=constraints)
self.pursuer_layer = AgentLayer(self.x_size, self.y_size, self.pursuers)
self.evaders = agent_utils.create_agents(self.n_evaders, self.map_matrix, self.obs_range, self.np_random,
randinit=True, constraints=constraints)
self.evader_layer = AgentLayer(self.x_size, self.y_size, self.evaders)
self.latest_reward_state = [0 for _ in range(self.num_agents)]
self.latest_done_state = [False for _ in range(self.num_agents)]
self.latest_obs = [None for _ in range(self.num_agents)]
self.model_state[0] = self.map_matrix
self.model_state[1] = self.pursuer_layer.get_state_matrix()
self.model_state[2] = self.evader_layer.get_state_matrix()
self.frames = 0
self.renderOn = False
return self.safely_observe(0)
def step(self, action, agent_id, is_last):
agent_layer = self.pursuer_layer
opponent_layer = self.evader_layer
opponent_controller = self.evader_controller
# actual action application
agent_layer.move_agent(agent_id, action)
self.latest_reward_state = self.reward() / self.num_agents
if is_last:
ev_remove, pr_remove, pursuers_who_remove = self.remove_agents()
for i in range(opponent_layer.n_agents()):
# controller input should be an observation, but doesn't matter right now
a = opponent_controller.act(self.model_state)
opponent_layer.move_agent(i, a)
self.latest_reward_state += self.catch_reward * pursuers_who_remove
self.latest_reward_state += self.urgency_reward
self.model_state[0] = self.map_matrix
self.model_state[1] = self.pursuer_layer.get_state_matrix()
self.model_state[2] = self.evader_layer.get_state_matrix()
if is_last:
global_val = self.latest_reward_state.mean()
local_val = self.latest_reward_state
self.latest_reward_state = self.local_ratio * local_val + (1 - self.local_ratio) * global_val
self.frames = self.frames + 1
def draw_model_state(self):
# -1 is building pixel flag
x_len, y_len = self.model_state[0].shape
for x in range(x_len):
for y in range(y_len):
pos = pygame.Rect(
self.pixel_scale * x, self.pixel_scale * y, self.pixel_scale, self.pixel_scale)
col = (0, 0, 0)
if self.model_state[0][x][y] == -1:
col = (255, 255, 255)
pygame.draw.rect(self.screen, col, pos)
def draw_pursuers_observations(self):
for i in range(self.pursuer_layer.n_agents()):
x, y = self.pursuer_layer.get_position(i)
patch = pygame.Surface(
(self.pixel_scale * self.obs_range, self.pixel_scale * self.obs_range))
patch.set_alpha(128)
patch.fill((255, 152, 72))
ofst = self.obs_range / 2.0
self.screen.blit(
patch, (self.pixel_scale * (x - ofst + 1 / 2), self.pixel_scale * (y - ofst + 1 / 2)))
def draw_pursuers(self):
for i in range(self.pursuer_layer.n_agents()):
x, y = self.pursuer_layer.get_position(i)
center = (int(self.pixel_scale * x + self.pixel_scale / 2),
int(self.pixel_scale * y + self.pixel_scale / 2))
col = (255, 0, 0)
pygame.draw.circle(self.screen, col, center, int(self.pixel_scale / 3))
def draw_evaders(self):
for i in range(self.evader_layer.n_agents()):
x, y = self.evader_layer.get_position(i)
center = (int(self.pixel_scale * x + self.pixel_scale / 2),
int(self.pixel_scale * y + self.pixel_scale / 2))
col = (0, 0, 255)
pygame.draw.circle(self.screen, col, center, int(self.pixel_scale / 3))
def render(self, mode="human"):
if not self.renderOn and mode == "human":
pygame.display.init()
self.screen = pygame.display.set_mode(
(self.pixel_scale * self.x_size, self.pixel_scale * self.y_size))
self.renderOn = True
self.draw_model_state()
self.draw_pursuers_observations()
self.draw_evaders()
self.draw_pursuers()
observation = pygame.surfarray.pixels3d(self.screen)
new_observation = np.copy(observation)
del observation
pygame.display.flip()
return np.transpose(new_observation, axes=(1, 0, 2)) if mode == "rgb_array" else None
def animate(self, act_fn, nsteps, file_name, rate=1.5, verbose=False):
"""
Save an animation to an mp4 file.
"""
# run sim loop
o = self.reset()
file_path = "/".join(file_name.split("/")[0:-1])
temp_name = join(file_path, "temp_0.png")
# generate .pngs
self.save_image(temp_name)
removed = 0
for i in range(nsteps):
a = act_fn(o)
o, r, done, info = self.step(a)
temp_name = join(file_path, "temp_" + str(i + 1) + ".png")
self.save_image(temp_name)
removed += info['removed']
if done:
break
# use ffmpeg to create .pngs to .mp4 movie
ffmpeg_cmd = "ffmpeg -framerate " + str(rate) + " -i " + join(
file_path, "temp_%d.png") + " -c:v libx264 -pix_fmt yuv420p " + file_name
call(ffmpeg_cmd.split())
# clean-up by removing .pngs
map(os.remove, glob.glob(join(file_path, "temp_*.png")))
def save_image(self, file_name):
self.render()
capture = pygame.surfarray.array3d(self.screen)
xl, xh = -self.obs_offset - 1, self.x_size + self.obs_offset + 1
yl, yh = -self.obs_offset - 1, self.y_size + self.obs_offset + 1
window = pygame.Rect(xl, yl, xh, yh)
subcapture = capture.subsurface(window)
pygame.image.save(subcapture, file_name)
def reward(self):
es = self.evader_layer.get_state_matrix() # evader positions
rewards = [
self.tag_reward * np.sum(es[np.clip(
self.pursuer_layer.get_position(
i)[0] + self.surround_mask[:, 0], 0, self.x_size - 1
), np.clip(
self.pursuer_layer.get_position(i)[1] + self.surround_mask[:, 1], 0, self.y_size - 1)])
for i in range(self.n_pursuers)
]
return np.array(rewards)
@property
def is_terminal(self):
# ev = self.evader_layer.get_state_matrix() # evader positions
# if np.sum(ev) == 0.0:
if self.evader_layer.n_agents() == 0:
return True
return False
def update_ally_controller(self, controller):
self.ally_controller = controller
def update_opponent_controller(self, controller):
self.opponent_controller = controller
def n_agents(self):
return self.pursuer_layer.n_agents()
def safely_observe(self, i):
agent_layer = self.pursuer_layer
obs = self.collect_obs(agent_layer, i)
return obs
def collect_obs(self, agent_layer, i):
for j in range(self.n_agents()):
if i == j:
return self.collect_obs_by_idx(agent_layer, i)
assert False, "bad index"
def collect_obs_by_idx(self, agent_layer, agent_idx):
# returns a flattened array of all the observations
obs = np.zeros((3, self.obs_range, self.obs_range), dtype=np.float32)
obs[0].fill(1.0) # border walls set to -0.1?
xp, yp = agent_layer.get_position(agent_idx)
xlo, xhi, ylo, yhi, xolo, xohi, yolo, yohi = self.obs_clip(xp, yp)
obs[0:3, xolo:xohi, yolo:yohi] = np.abs(self.model_state[0:3, xlo:xhi, ylo:yhi])
return obs
def obs_clip(self, x, y):
xld = x - self.obs_offset
xhd = x + self.obs_offset
yld = y - self.obs_offset
yhd = y + self.obs_offset
xlo, xhi, ylo, yhi = (np.clip(xld, 0, self.x_size - 1), np.clip(xhd, 0, self.x_size - 1),
np.clip(yld, 0, self.y_size - 1), np.clip(yhd, 0, self.y_size - 1))
xolo, yolo = abs(np.clip(xld, -self.obs_offset, 0)
), abs(np.clip(yld, -self.obs_offset, 0))
xohi, yohi = xolo + (xhi - xlo), yolo + (yhi - ylo)
return xlo, xhi + 1, ylo, yhi + 1, xolo, xohi + 1, yolo, yohi + 1
def remove_agents(self):
"""
Remove agents that are caught. Return tuple (n_evader_removed, n_pursuer_removed, purs_sur)
purs_sur: bool array, which pursuers surrounded an evader
"""
n_pursuer_removed = 0
n_evader_removed = 0
removed_evade = []
removed_pursuit = []
ai = 0
rems = 0
xpur, ypur = np.nonzero(self.model_state[1])
purs_sur = np.zeros(self.n_pursuers, dtype=np.bool)
for i in range(self.n_evaders):
if self.evaders_gone[i]:
continue
x, y = self.evader_layer.get_position(ai)
if self.surround:
pos_that_catch = self.surround_mask + \
self.evader_layer.get_position(ai)
truths = np.array(
[np.equal([xi, yi], pos_that_catch).all(axis=1) for xi, yi in zip(xpur, ypur)])
if np.sum(truths.any(axis=0)) == self.need_to_surround(x, y):
removed_evade.append(ai - rems)
self.evaders_gone[i] = True
rems += 1
tt = truths.any(axis=1)
for j in range(self.n_pursuers):
xpp, ypp = self.pursuer_layer.get_position(j)
tes = np.concatenate(
(xpur[tt], ypur[tt])).reshape(2, len(xpur[tt]))
tem = tes.T == np.array([xpp, ypp])
if np.any(np.all(tem, axis=1)):
purs_sur[j] = True
ai += 1
else:
if self.model_state[1, x, y] >= self.n_catch:
# add prob remove?
removed_evade.append(ai - rems)
self.evaders_gone[i] = True
rems += 1
for j in range(self.n_pursuers):
xpp, ypp = self.pursuer_layer.get_position(j)
if xpp == x and ypp == y:
purs_sur[j] = True
ai += 1
ai = 0
for i in range(self.pursuer_layer.n_agents()):
x, y = self.pursuer_layer.get_position(i)
# can remove pursuers probabilitcally here?
for ridx in removed_evade:
self.evader_layer.remove_agent(ridx)
n_evader_removed += 1
for ridx in removed_pursuit:
self.pursuer_layer.remove_agent(ridx)
n_pursuer_removed += 1
return n_evader_removed, n_pursuer_removed, purs_sur
def need_to_surround(self, x, y):
"""
Compute the number of surrounding grid cells in x,y position that are open
(no wall or obstacle)
"""
tosur = 4
if x == 0 or x == (self.x_size - 1):
tosur -= 1
if y == 0 or y == (self.y_size - 1):
tosur -= 1
neighbors = self.surround_mask + np.array([x, y])
for n in neighbors:
xn, yn = n
if not 0 < xn < self.x_size or not 0 < yn < self.y_size:
continue
if self.model_state[0][xn, yn] == -1:
tosur -= 1
return tosur
| [
"aecgames.paper@gmail.com"
] | aecgames.paper@gmail.com |
f72b255f1a70060f3fae7db94812b435d5bb8b2d | 818e5e78f84596a7c086b218fd4aa9e8ea912afe | /hackatons/materials/algo/source/T5_LinearStructure/P2_Queue/counter_game_deq.py | d78087eb4b0f2a733e40cb405b86b2885f5e47e4 | [] | no_license | davendiy/forpythonanywhere | 44fbc63651309598b58391667f0fead40e8fad91 | 1b9292ca33b06b17cd516e4e9913479edb6d35cd | refs/heads/master | 2020-08-10T04:24:02.665635 | 2019-10-25T07:05:46 | 2019-10-25T07:05:46 | 214,255,096 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,193 | py | #ะััะธะปะบะฐ ะท ะฒะธะบะพัะธััะฐะฝะฝัะผ ะดะตะบั
from source.T5_LinearStructure.P2_Queue.counter_game import Player
from source.T5_LinearStructure.P2_Queue.Deque import Deque
def count_counter():
""" ะคัะฝะบััั ัะพะทะฒ'ัะทัั ะทะฐะดะฐัั "ะปััะธะปะบะฐ" """
d = Deque() # ััะฒะพัะธัะธ ะดะตะบ d
n = int(input('ะัะปัะบัััั ะณัะฐะฒััะฒ: '))
m = int(input('ะัะปัะบัััั ัะปัะฒ: '))
for i in range(n):
pl = Player(i+1) # ััะฒะพัะธัะธ ะณัะฐะฒัั ะท ะฝะพะผะตัะพะผ ะฝะฐ 1 ะฑัะปััะต i
d.append(pl) # ะดะพะดะฐัะธ ะณัะฐะฒัั ั ะบัะฝะตัั ะดะตะบั
print('\nะะพัะปัะดะพะฒะฝัััั ะฝะพะผะตััะฒ, ัะพ ะฒะธะฑัะฒะฐััั')
while not d.empty():
for i in range(m-1): # m-1 ัะฐะท ะฟะตัะตะบะปะฐััะธ ะณัะฐะฒัั ะท ะฟะพัะฐัะบั ะดะพ ะบัะฝัั ะดะตะบั
d.append(d.popleft())
pl = d.popleft() # ัะทััะธ m-ะณะพ ะณัะฐะฒัั ะท ะฟะพัะฐัะบั ะดะตะบั
print(pl) # ัะฐ ะฟะพะบะฐะทะฐัะธ ะนะพะณะพ ะฝะพะผะตั
count_counter()
| [
"davendiy@gmail.com"
] | davendiy@gmail.com |
e54e82dd782cfdb2f10b0bfe75e0c9d0f784242e | 108a33707a8d5e165761c6a9fb861b939c30ee5b | /quest/keras/applications/inception_resnet_v2.py | 23625cfbca5a7564c56b9f5f4c20cdde38db87c1 | [
"BSD-3-Clause"
] | permissive | sheffieldnlp/deepQuest | 2c7d01b731641954a269950e7c7d7c41493cc0bc | 75a8d00009b4c5c63c7554a07c5340c15d67ae1c | refs/heads/master | 2021-06-26T09:05:50.297201 | 2020-09-23T21:37:04 | 2020-09-23T21:37:04 | 133,787,310 | 40 | 16 | BSD-3-Clause | 2019-10-08T17:02:51 | 2018-05-17T09:02:12 | Python | UTF-8 | Python | false | false | 15,478 | py | # -*- coding: utf-8 -*-
"""Inception-ResNet V2 model for Keras.
Model naming and structure follows TF-slim implementation (which has some additional
layers and different number of filters from the original arXiv paper):
https://github.com/tensorflow/models/blob/master/slim/nets/inception_resnet_v2.py
Pre-trained ImageNet weights are also converted from TF-slim, which can be found in:
https://github.com/tensorflow/models/tree/master/slim#pre-trained-models
# Reference
- [Inception-v4, Inception-ResNet and the Impact of
Residual Connections on Learning](https://arxiv.org/abs/1602.07261)
"""
from __future__ import print_function
from __future__ import absolute_import
import warnings
from ..models import Model
from ..layers import Activation
from ..layers import AveragePooling2D
from ..layers import BatchNormalization
from ..layers import Concatenate
from ..layers import Conv2D
from ..layers import Dense
from ..layers import GlobalAveragePooling2D
from ..layers import GlobalMaxPooling2D
from ..layers import Input
from ..layers import Lambda
from ..layers import MaxPooling2D
from ..utils.data_utils import get_file
from ..engine.topology import get_source_inputs
from . import imagenet_utils
from .imagenet_utils import _obtain_input_shape
from .imagenet_utils import decode_predictions
from .. import backend as K
BASE_WEIGHT_URL = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.7/'
def preprocess_input(x):
"""Preprocesses a numpy array encoding a batch of images.
# Arguments
x: a 4D numpy array consists of RGB values within [0, 255].
# Returns
Preprocessed array.
"""
return imagenet_utils.preprocess_input(x, mode='tf')
def conv2d_bn(x,
filters,
kernel_size,
strides=1,
padding='same',
activation='relu',
use_bias=False,
name=None):
"""Utility function to apply conv + BN.
# Arguments
x: input tensor.
filters: filters in `Conv2D`.
kernel_size: kernel size as in `Conv2D`.
padding: padding mode in `Conv2D`.
activation: activation in `Conv2D`.
strides: strides in `Conv2D`.
name: name of the ops; will become `name + '_ac'` for the activation
and `name + '_bn'` for the batch norm layer.
# Returns
Output tensor after applying `Conv2D` and `BatchNormalization`.
"""
x = Conv2D(filters,
kernel_size,
strides=strides,
padding=padding,
use_bias=use_bias,
name=name)(x)
if not use_bias:
bn_axis = 1 if K.image_data_format() == 'channels_first' else 3
bn_name = None if name is None else name + '_bn'
x = BatchNormalization(axis=bn_axis, scale=False, name=bn_name)(x)
if activation is not None:
ac_name = None if name is None else name + '_ac'
x = Activation(activation, name=ac_name)(x)
return x
def inception_resnet_block(x, scale, block_type, block_idx, activation='relu'):
"""Adds a Inception-ResNet block.
This function builds 3 types of Inception-ResNet blocks mentioned
in the paper, controlled by the `block_type` argument (which is the
block name used in the official TF-slim implementation):
- Inception-ResNet-A: `block_type='block35'`
- Inception-ResNet-B: `block_type='block17'`
- Inception-ResNet-C: `block_type='block8'`
# Arguments
x: input tensor.
scale: scaling factor to scale the residuals (i.e., the output of
passing `x` through an inception module) before adding them
to the shortcut branch. Let `r` be the output from the residual branch,
the output of this block will be `x + scale * r`.
block_type: `'block35'`, `'block17'` or `'block8'`, determines
the network structure in the residual branch.
block_idx: an `int` used for generating layer names. The Inception-ResNet blocks
are repeated many times in this network. We use `block_idx` to identify
each of the repetitions. For example, the first Inception-ResNet-A block
will have `block_type='block35', block_idx=0`, ane the layer names will have
a common prefix `'block35_0'`.
activation: activation function to use at the end of the block
(see [activations](../activations.md)).
When `activation=None`, no activation is applied
(i.e., "linear" activation: `a(x) = x`).
# Returns
Output tensor for the block.
# Raises
ValueError: if `block_type` is not one of `'block35'`,
`'block17'` or `'block8'`.
"""
if block_type == 'block35':
branch_0 = conv2d_bn(x, 32, 1)
branch_1 = conv2d_bn(x, 32, 1)
branch_1 = conv2d_bn(branch_1, 32, 3)
branch_2 = conv2d_bn(x, 32, 1)
branch_2 = conv2d_bn(branch_2, 48, 3)
branch_2 = conv2d_bn(branch_2, 64, 3)
branches = [branch_0, branch_1, branch_2]
elif block_type == 'block17':
branch_0 = conv2d_bn(x, 192, 1)
branch_1 = conv2d_bn(x, 128, 1)
branch_1 = conv2d_bn(branch_1, 160, [1, 7])
branch_1 = conv2d_bn(branch_1, 192, [7, 1])
branches = [branch_0, branch_1]
elif block_type == 'block8':
branch_0 = conv2d_bn(x, 192, 1)
branch_1 = conv2d_bn(x, 192, 1)
branch_1 = conv2d_bn(branch_1, 224, [1, 3])
branch_1 = conv2d_bn(branch_1, 256, [3, 1])
branches = [branch_0, branch_1]
else:
raise ValueError('Unknown Inception-ResNet block type. '
'Expects "block35", "block17" or "block8", '
'but got: ' + str(block_type))
block_name = block_type + '_' + str(block_idx)
channel_axis = 1 if K.image_data_format() == 'channels_first' else 3
mixed = Concatenate(axis=channel_axis, name=block_name + '_mixed')(branches)
up = conv2d_bn(mixed,
K.int_shape(x)[channel_axis],
1,
activation=None,
use_bias=True,
name=block_name + '_conv')
x = Lambda(lambda inputs, scale: inputs[0] + inputs[1] * scale,
output_shape=K.int_shape(x)[1:],
arguments={'scale': scale},
name=block_name)([x, up])
if activation is not None:
x = Activation(activation, name=block_name + '_ac')(x)
return x
def InceptionResNetV2(include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000):
"""Instantiates the Inception-ResNet v2 architecture.
Optionally loads weights pre-trained on ImageNet.
Note that when using TensorFlow, for best performance you should
set `"image_data_format": "channels_last"` in your Keras config
at `~/.keras/keras.json`.
The model and the weights are compatible with TensorFlow, Theano and
CNTK backends. The data format convention used by the model is
the one specified in your Keras config file.
Note that the default input image size for this model is 299x299, instead
of 224x224 as in the VGG16 and ResNet models. Also, the input preprocessing
function is different (i.e., do not use `imagenet_utils.preprocess_input()`
with this model. Use `preprocess_input()` defined in this module instead).
# Arguments
include_top: whether to include the fully-connected
layer at the top of the network.
weights: one of `None` (random initialization)
or `'imagenet'` (pre-training on ImageNet).
input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
to use as image input for the model.
input_shape: optional shape tuple, only to be specified
if `include_top` is `False` (otherwise the input shape
has to be `(299, 299, 3)` (with `'channels_last'` data format)
or `(3, 299, 299)` (with `'channels_first'` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 139.
E.g. `(150, 150, 3)` would be one valid value.
pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the last convolutional layer.
- `'avg'` means that global average pooling
will be applied to the output of the
last convolutional layer, and thus
the output of the model will be a 2D tensor.
- `'max'` means that global max pooling will be applied.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is `True`, and
if no `weights` argument is specified.
# Returns
A Keras `Model` instance.
# Raises
ValueError: in case of invalid argument for `weights`,
or invalid input shape.
"""
if weights not in {'imagenet', None}:
raise ValueError('The `weights` argument should be either '
'`None` (random initialization) or `imagenet` '
'(pre-training on ImageNet).')
if weights == 'imagenet' and include_top and classes != 1000:
raise ValueError('If using `weights` as imagenet with `include_top`'
' as true, `classes` should be 1000')
# Determine proper input shape
input_shape = _obtain_input_shape(
input_shape,
default_size=299,
min_size=139,
data_format=K.image_data_format(),
require_flatten=False,
weights=weights)
if input_tensor is None:
img_input = Input(shape=input_shape)
else:
if not K.is_keras_tensor(input_tensor):
img_input = Input(tensor=input_tensor, shape=input_shape)
else:
img_input = input_tensor
# Stem block: 35 x 35 x 192
x = conv2d_bn(img_input, 32, 3, strides=2, padding='valid')
x = conv2d_bn(x, 32, 3, padding='valid')
x = conv2d_bn(x, 64, 3)
x = MaxPooling2D(3, strides=2)(x)
x = conv2d_bn(x, 80, 1, padding='valid')
x = conv2d_bn(x, 192, 3, padding='valid')
x = MaxPooling2D(3, strides=2)(x)
# Mixed 5b (Inception-A block): 35 x 35 x 320
branch_0 = conv2d_bn(x, 96, 1)
branch_1 = conv2d_bn(x, 48, 1)
branch_1 = conv2d_bn(branch_1, 64, 5)
branch_2 = conv2d_bn(x, 64, 1)
branch_2 = conv2d_bn(branch_2, 96, 3)
branch_2 = conv2d_bn(branch_2, 96, 3)
branch_pool = AveragePooling2D(3, strides=1, padding='same')(x)
branch_pool = conv2d_bn(branch_pool, 64, 1)
branches = [branch_0, branch_1, branch_2, branch_pool]
channel_axis = 1 if K.image_data_format() == 'channels_first' else 3
x = Concatenate(axis=channel_axis, name='mixed_5b')(branches)
# 10x block35 (Inception-ResNet-A block): 35 x 35 x 320
for block_idx in range(1, 11):
x = inception_resnet_block(x,
scale=0.17,
block_type='block35',
block_idx=block_idx)
# Mixed 6a (Reduction-A block): 17 x 17 x 1088
branch_0 = conv2d_bn(x, 384, 3, strides=2, padding='valid')
branch_1 = conv2d_bn(x, 256, 1)
branch_1 = conv2d_bn(branch_1, 256, 3)
branch_1 = conv2d_bn(branch_1, 384, 3, strides=2, padding='valid')
branch_pool = MaxPooling2D(3, strides=2, padding='valid')(x)
branches = [branch_0, branch_1, branch_pool]
x = Concatenate(axis=channel_axis, name='mixed_6a')(branches)
# 20x block17 (Inception-ResNet-B block): 17 x 17 x 1088
for block_idx in range(1, 21):
x = inception_resnet_block(x,
scale=0.1,
block_type='block17',
block_idx=block_idx)
# Mixed 7a (Reduction-B block): 8 x 8 x 2080
branch_0 = conv2d_bn(x, 256, 1)
branch_0 = conv2d_bn(branch_0, 384, 3, strides=2, padding='valid')
branch_1 = conv2d_bn(x, 256, 1)
branch_1 = conv2d_bn(branch_1, 288, 3, strides=2, padding='valid')
branch_2 = conv2d_bn(x, 256, 1)
branch_2 = conv2d_bn(branch_2, 288, 3)
branch_2 = conv2d_bn(branch_2, 320, 3, strides=2, padding='valid')
branch_pool = MaxPooling2D(3, strides=2, padding='valid')(x)
branches = [branch_0, branch_1, branch_2, branch_pool]
x = Concatenate(axis=channel_axis, name='mixed_7a')(branches)
# 10x block8 (Inception-ResNet-C block): 8 x 8 x 2080
for block_idx in range(1, 10):
x = inception_resnet_block(x,
scale=0.2,
block_type='block8',
block_idx=block_idx)
x = inception_resnet_block(x,
scale=1.,
activation=None,
block_type='block8',
block_idx=10)
# Final convolution block: 8 x 8 x 1536
x = conv2d_bn(x, 1536, 1, name='conv_7b')
if include_top:
# Classification block
x = GlobalAveragePooling2D(name='avg_pool')(x)
x = Dense(classes, activation='softmax', name='predictions')(x)
else:
if pooling == 'avg':
x = GlobalAveragePooling2D()(x)
elif pooling == 'max':
x = GlobalMaxPooling2D()(x)
# Ensure that the model takes into account
# any potential predecessors of `input_tensor`
if input_tensor is not None:
inputs = get_source_inputs(input_tensor)
else:
inputs = img_input
# Create model
model = Model(inputs, x, name='inception_resnet_v2')
# Load weights
if weights == 'imagenet':
if K.image_data_format() == 'channels_first':
if K.backend() == 'tensorflow':
warnings.warn('You are using the TensorFlow backend, yet you '
'are using the Theano '
'image data format convention '
'(`image_data_format="channels_first"`). '
'For best performance, set '
'`image_data_format="channels_last"` in '
'your Keras config '
'at ~/.keras/keras.json.')
if include_top:
weights_filename = 'inception_resnet_v2_weights_tf_dim_ordering_tf_kernels.h5'
weights_path = get_file(weights_filename,
BASE_WEIGHT_URL + weights_filename,
cache_subdir='models',
file_hash='e693bd0210a403b3192acc6073ad2e96')
else:
weights_filename = 'inception_resnet_v2_weights_tf_dim_ordering_tf_kernels_notop.h5'
weights_path = get_file(weights_filename,
BASE_WEIGHT_URL + weights_filename,
cache_subdir='models',
file_hash='d19885ff4a710c122648d3b5c3b684e4')
model.load_weights(weights_path)
return model
| [
"f.blain@sheffield.ac.uk"
] | f.blain@sheffield.ac.uk |
e91efcbec9bf3bc0b4d5011eb6b094e4876d2698 | e337afd8cf452fab98713249c536074d0032e0a6 | /homebudget/urls.py | 83e2da24049b7da487774bd03cfa687612ecb63c | [] | no_license | daria-trask/home-budget-api | d445b45e068407cc03d0b7faea04c0b9696bab9a | 7f99f7245f98c545d17bdcf3fc3ccf0470fa8e57 | refs/heads/master | 2020-03-19T11:03:20.147809 | 2018-06-06T20:41:52 | 2018-06-06T20:41:52 | 136,425,754 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 752 | py | """homebudget URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.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
urlpatterns = [
path('admin/', admin.site.urls),
]
| [
"rowdyswa@gmail.com"
] | rowdyswa@gmail.com |
4a4ff6a93cb90986c19b93d5508f1f7dfd998bca | bbff6cb11688224a5749037693614229d44915cf | /networks/meta_learner.py | 420b76cca603bf5f1f934ec39719953078a655b7 | [
"MIT"
] | permissive | yongliang-qiao/fscc | f4b02db2523cc0884816451b4788917ceba4506d | 9ca20128117f789433986971c5cc77f631c102e6 | refs/heads/master | 2023-04-15T13:58:11.619582 | 2020-07-18T07:17:12 | 2020-07-18T07:17:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,652 | py | import logging
import os
from tensorboardX import SummaryWriter
from torch import nn
from torch.utils.data import DataLoader
from dataloader.get_task import TaskGenerator
from dataloader.test_dataloader import TestDataset
from dataloader.train_dataloader import GetDataLoader
from .backbone import CSRMetaNetwork
from .base_network import BaseNetwork
from .network_utils import *
device = 'cuda' if torch.cuda.is_available() else 'cpu'
class MetaLearner(object):
def __init__(self, dataset, data_path, num_instances, num_tasks, meta_batch, meta_lr, base_batch, base_lr,
meta_updates, base_updates, experiment):
# model hyperparameters
self.loss_function = nn.MSELoss()
self.data_path = data_path
self.num_instances = num_instances
self.num_tasks = num_tasks
self.meta_batch = meta_batch
self.meta_lr = meta_lr
self.base_batch = base_batch
self.base_lr = base_lr
self.meta_updates = meta_updates
self.base_updates = base_updates
self.get_loader = GetDataLoader()
self.dataset = dataset
self.experiment = experiment
self.save_models = '../models/{}/'.format(self.experiment)
self.writer = SummaryWriter()
self.best_mae = 1e+10
self.best_epoch = -1
if not os.path.exists(self.save_models):
os.makedirs(self.save_models)
# training details
self.num_input_channels = 3
self.network = CSRMetaNetwork(self.loss_function)
self.network.to(device)
self.fast_network = BaseNetwork(self.loss_function, self.base_updates, self.base_lr, self.base_batch,
self.meta_batch)
self.model_path = "" # TODO: path of the pre-trained backbone CSRNet
self.checkpoint = torch.load(self.model_path)
self.network.load_state_dict(self.checkpoint['state_dict'])
self.fast_network.to(device)
self.optimizer = torch.optim.Adam(self.network.parameters(), lr=self.meta_lr)
logging.info("Loaded model: {}".format(self.model_path))
def get_task(self, path, mode='train', num_instances=5, num_tasks=10):
return TaskGenerator(dataset=self.dataset, data_path=path, mode=mode, num_of_tasks=num_tasks,
num_of_instances=num_instances)
def meta_network_update(self, task, ls):
logging.info("===> Updating meta network")
dataloader = self.get_loader.get_data(task, self.base_batch, mode='validation')
_input, _target = dataloader.__iter__().next()
# perform a dummy forward forward to compute the gradients and replace the calculated gradients with the
# accumulated in the base network training.
_, loss = forward_pass(self.network, _input, _target, mode='training')
# unpack the list of gradient dictionary
gradients = {g: sum(d[g] for d in ls) for g in ls[0].keys()}
logging.info("===> Gradients updated: {}".format(gradients))
# inorder to replace the grads with base gradients, use the hook operation provided by PyTorch
hooks = []
for key, value in self.network.named_parameters():
def get_closure():
k = key
def replace_grad(grad):
return gradients[k]
return replace_grad
if 'frontend' not in key:
hooks.append(value.register_hook(get_closure()))
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
for hook in hooks:
hook.remove()
def test(self):
test_network = CSRMetaNetwork(self.loss_function, pre_trained=False)
mtr_loss, mtr_acc, mtr_mse, mval_acc, mval_mse = 0.0, 0.0, 0.0, 0.0, 0.0
test_network.to(device)
test_iterations = 10
logging.info("** Testing meta network for {} iterations".format(test_iterations))
for _ in range(10):
test_network.copy_weights(self.network)
for param in test_network.frontend.parameters():
param.requires_grad = False
test_optimizer = torch.optim.SGD(test_network.parameters(), lr=self.base_lr)
task = TaskGenerator(dataset=self.dataset, data_path=self.data_path, mode='test',
num_of_tasks=self.num_tasks, num_of_instances=self.num_instances)
# train the test meta-network on the train images using the same number of training updates
train_loader = self.get_loader.get_data(task, self.base_batch, mode='train')
validation_loader = self.get_loader.get_data(task, self.base_batch, mode='test')
for idx, data in enumerate(train_loader):
_input, _target = data[0], data[1]
_, loss = forward_pass(test_network, _input, _target, mode='training')
test_optimizer.zero_grad()
loss.backward()
test_optimizer.step()
# evaluate the trained model on the train and validation samples in the test split
tloss, tacc, tmse = evaluate(test_network, train_loader, mode='training')
vacc, vmse = evaluate(test_network, validation_loader)
logging.info("** Evaluated test and train steps")
mtr_loss += tloss
mtr_acc += tacc
mtr_mse += tmse
mval_mse += vmse
mval_acc += vacc
mtr_loss /= test_iterations
mtr_acc /= test_iterations
mtr_mse /= test_iterations
mval_mse /= test_iterations
mval_acc /= test_iterations
logging.info("==========================")
logging.info("(Meta-testing) train loss:{}, MAE: {}, MSE: {}".format(mtr_loss, mtr_acc, mtr_mse))
logging.info("(Meta-testing) test MAE: {}, MSE: {}".format(mval_acc, mval_mse))
logging.info("==========================")
del test_network
return mtr_loss, mtr_acc, mtr_mse, mval_acc, mval_mse
def train(self):
# train_loss, train_accuracy, validation_accuracy = [], [], []
mtrain_loss, mtrain_accuracy, mtrain_mse, mvalidation_accuracy, mvalidation_mse = [], [], [], [], []
for param in self.fast_network.frontend.parameters():
param.requires_grad = False
# training epochs (meta_updates)
for idx, epoch in enumerate(range(self.meta_updates)):
print("===> Training epoch: {}/{}".format(idx + 1, self.meta_updates))
logging.info("===> Training epoch: {}/{}".format(idx + 1, self.meta_updates))
# evaluate the model on test data (tasks)
mtr_loss, mtr_acc, mtr_mse, vtr_acc, vtr_mse = self.test()
mtrain_loss.append(mtr_loss)
mtrain_accuracy.append(mtr_acc)
mtrain_mse.append(mtr_mse)
mvalidation_accuracy.append(vtr_acc)
mvalidation_mse.append(vtr_mse)
meta_gradients = []
tr_loss, tr_acc, tr_mse, val_acc, val_mse = 0.0, 0.0, 0.0, 0.0, 0.0
# compute the meta batch upate by calling base network
for idx, mu in enumerate(range(self.meta_batch)):
logging.info("==> Training scene: {}".format(idx + 1))
print("==> Training scene: {}".format(idx + 1))
task = TaskGenerator(dataset=self.dataset, data_path=self.data_path,
num_of_tasks=self.num_tasks, num_of_instances=self.num_instances)
self.fast_network.copy_weights(self.network)
self.fast_network.to(device)
metrics, grad = self.fast_network.forward(task)
logging.info("Sum of gradients in VGG: {}".format(
{n: torch.sum(p).item() for n, p in self.fast_network.frontend.named_parameters()}))
logging.info("Sum of gradients in backend: {}".format(
{n: torch.sum(x).item() for n, x in self.fast_network.backend.named_parameters()}))
logging.info("Sum of gradients in output layer: {}".format(
{n: torch.sum(x) for n, x in self.fast_network.output_layer.named_parameters()}))
logging.info("Sum of the total gradients: {}".format({n: torch.sum(x) for n, x in grad.items()}))
(tl, ta, tm, va, vm) = metrics
meta_gradients.append(grad)
tr_loss += tl
tr_acc += ta
tr_mse += tm
val_acc += va
val_mse += vm
self.meta_network_update(task, meta_gradients)
if (epoch + 1) % 5 == 0:
mae, mse = 0, 0
print("==> Evaluating the model at: {}".format(epoch + 1))
logging.info("==> Evaluating the model at: {}".format(epoch + 1))
test_dataloader = DataLoader(TestDataset(self.dataset), shuffle=False)
test_network = CSRMetaNetwork(self.loss_function, pre_trained=False)
test_network.copy_weights(self.network)
test_network.eval()
with torch.no_grad():
for idx, data in enumerate(test_dataloader):
img, target = data
_img = img.to(device)
target = target.float().unsqueeze(0).to(device)
output = test_network(_img)
difference = output.sum() - target.sum()
_mae = torch.abs(difference)
_mse = difference ** 2
mae += _mae.item()
mse += _mse.item()
mae /= len(test_dataloader)
mse = np.sqrt(mse / len(test_dataloader))
print("==> Evaluation MAE: {}, MSE: {}".format(mae, mse))
logging.info("==> Evaluation results: MAE: {}, MSE: {}".format(mae, mse))
if mae < self.best_mae:
self.best_mae = mae
self.best_epoch = epoch + 1
print("Saving checkpoint at: {}".format(self.best_epoch))
logging.info("Saving checkpoint at: {}/{}.pt".format(self.save_models, self.best_epoch))
torch.save(self.network.state_dict(),
'{}/epoch_{}.pt'.format(self.save_models, self.best_epoch))
tr_loss = tr_loss / self.meta_batch
tr_acc = tr_acc / self.meta_batch
tr_mse = tr_mse / self.meta_batch
val_acc = val_acc / self.meta_batch
val_mse = val_mse / self.meta_batch
self.writer.add_scalar('(meta-train): train loss', tr_loss, epoch + 1)
self.writer.add_scalar('(meta-train): train MAE', tr_acc, epoch + 1)
self.writer.add_scalar('(meta-train): train MSE', tr_mse, epoch + 1)
self.writer.add_scalar('(meta-train): test MAE', val_acc, epoch + 1)
self.writer.add_scalar('(meta-train): test MSE', val_mse, epoch + 1)
self.writer.add_scalar('(meta-test) train loss', mtr_loss, epoch + 1)
self.writer.add_scalar('(meta-test) train MAE', mtr_acc, epoch + 1)
self.writer.add_scalar('(meta-test) train MSE', mtr_mse, epoch + 1)
self.writer.add_scalar('(meta-test) test MAE', vtr_acc, epoch + 1)
self.writer.add_scalar('(meta-test) test MSE', vtr_mse, epoch + 1)
for name, param in self.network.named_parameters():
if 'bn' not in name:
self.writer.add_histogram(name, param, epoch + 1)
| [
"maheshk2194@gmail.com"
] | maheshk2194@gmail.com |
8333137c128e54828c5eee264b4aee1b358fa310 | f0a1a85e8cae69144ce304d4c91b53b8f8cf5116 | /mysite/blog/models.py | 6bc8deb3e116bb18d028e1c31219e4e91c1c6bb9 | [
"MIT"
] | permissive | ohduran-attempts/by-example | 0a96b59cf41e3c955e8e744b0604c909168fd998 | a56385c169d426090970f3f481d15fec50a9c603 | refs/heads/master | 2020-04-22T16:41:53.512719 | 2019-02-15T07:32:51 | 2019-02-15T07:32:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,995 | py | from common.models import TimeStamped
from django.conf import settings
from django.db import models
from django.urls import reverse_lazy
from django.utils import timezone
from taggit.managers import TaggableManager
class PublishedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='published')
class Post(TimeStamped, models.Model):
STATUS_CHOICES_TPL = (
('draft', 'Draft'),
('published', 'Published'),
)
objects = models.Manager()
published = PublishedManager()
tags = TaggableManager()
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,
unique_for_date='publish')
author = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
status = models.CharField(max_length=10,
choices=STATUS_CHOICES_TPL,
default='draft')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse_lazy('blog:post_detail',
args=[self.publish.year,
self.publish.month,
self.publish.day,
self.slug])
class Comment(TimeStamped, models.Model):
post = models.ForeignKey(Post,
on_delete=models.CASCADE,
related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
def __str__(self):
return f"Comment by {self.name} on {self.post}"
| [
"alvaro.duranb@gmail.com"
] | alvaro.duranb@gmail.com |
3d4c5885546641826a28ff668a553291b34246c5 | 5d1db376865994da89fc80566eef547e3e1868ed | /new.py | 4f42c8a769f03175b98fe66164f530ffde8772d1 | [] | no_license | sflocascio/retsite | f86c8aa29ced0821f065ae5a1e5188b654690d7b | 81680465a470fb42b83b89c2691d612a1f84c88e | refs/heads/master | 2022-11-25T07:09:44.380268 | 2020-07-01T02:47:03 | 2020-07-01T02:47:03 | 239,164,765 | 0 | 0 | null | 2022-11-22T05:50:16 | 2020-02-08T16:32:18 | HTML | UTF-8 | Python | false | false | 1,430 | py | import json
import csv
# Turn one TXT file into JSON RET object
filename = '4.txt'
commands = {}
with open(filename) as fh:
for line in fh:
command, description = line.strip().split(':', 1)
commands[command] = description.strip()
# Define the title of the JSON document
with open('1.txt', 'r') as title:
myvar = title.readline()
myvar = myvar.strip()
myvar = myvar.replace("\\","/")
# Add the title to the JSON object with extra formatting and dump into JSON File
with open('result.json', 'w') as fp:
fp.write("{" + "\n" + '"' + myvar + '":[' )
json.dump(commands, fp, indent=2, sort_keys=True)
fp.write("\n" + "]" + "\n" + "}" )
###### Write JSON to CSV file ######
#Opening JSON file and loading the data
#into the variable data
with open('retjson.json') as json_file:
data = json.load(json_file)
employee_data = data['emp_details']
# now we will open a file for writing
data_file = open('data_file.csv', 'w')
# create the csv writer object
csv_writer = csv.writer(data_file)
# Counter variable used for writing
# headers to the CSV file
count = 0
for emp in employee_data:
if count == 0:
# Writing headers of CSV file
header = emp.keys()
csv_writer.writerow(header)
count += 1
# Writing data of CSV file
csv_writer.writerow(emp.values())
data_file.close()
#print(my_dict) | [
"sflocascio@gmail.com"
] | sflocascio@gmail.com |
5aaa810e755a0d5fc3fd5629e677aade6584b299 | c6ba2339d79c0452cb3a181fd50fb3f8e0ae13ce | /django_rest_imageupload_backend/imageupload/admin.py | dba9207b47e6adeaddf0758f42c14c7926642024 | [] | no_license | sandynigs/django_rest_imageupload_example | ac46896d8ea9318931f66bcd18c82662c8c63cfd | 72d07eda4d086165f75af37c9d2f3d945c1ff424 | refs/heads/master | 2021-01-20T06:04:47.902049 | 2017-08-26T16:03:45 | 2017-08-26T16:03:45 | 101,480,002 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 204 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
# Register your models here.
from imageupload.models import UploadImage
admin.site.register(UploadImage) | [
"sandeepnigam379@gmail.com"
] | sandeepnigam379@gmail.com |
eaa767ce7d873d2b5ae1bb27c52d8a11783a223d | ea295d3422392eb2fe1fe25bc01bb9179912c513 | /src/newKeras.py | 02e8da96891a6b12998114058619ab105c2239a1 | [] | no_license | llambrecht/train_segmentation | 1b81b15c70bf2f4684d971ffdbb4a40d412c3cb8 | 348c28cd8a3095c6c10aeee73d61f1af3a802de7 | refs/heads/master | 2021-04-18T18:53:03.973439 | 2018-05-10T17:47:29 | 2018-05-10T17:47:29 | 126,201,075 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,502 | py | from __future__ import print_function
import os
from skimage.transform import resize
from skimage.io import imsave
import numpy as np
from keras.models import Model
from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
from keras import backend as K
from PIL import Image
from keras.utils import plot_model
from keras import metrics
from data_loader import DataCreator, DataLoader, load_test_data
K.set_image_data_format('channels_last') # TF dimension ordering in this code
img_rows = 48
img_cols = 48
smooth = 1.
def dice_coef(y_true, y_pred):
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
intersection = K.sum(y_true_f * y_pred_f)
return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
def dice_coef_loss(y_true, y_pred):
return -dice_coef(y_true, y_pred)
def get_unet():
inputs = Input((img_rows, img_cols, 1))
conv1 = Conv2D(32, (3, 3), activation='relu', padding='same')(inputs)
conv1 = Conv2D(32, (3, 3), activation='relu', padding='same')(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
conv2 = Conv2D(64, (3, 3), activation='relu', padding='same')(pool1)
conv2 = Conv2D(64, (3, 3), activation='relu', padding='same')(conv2)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
conv3 = Conv2D(128, (3, 3), activation='relu', padding='same')(pool2)
conv3 = Conv2D(128, (3, 3), activation='relu', padding='same')(conv3)
pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
conv4 = Conv2D(256, (3, 3), activation='relu', padding='same')(pool3)
conv4 = Conv2D(256, (3, 3), activation='relu', padding='same')(conv4)
pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)
conv5 = Conv2D(512, (3, 3), activation='relu', padding='same')(pool4)
conv5 = Conv2D(512, (3, 3), activation='relu', padding='same')(conv5)
up6 = concatenate([Conv2DTranspose(256, (2, 2), strides=(2, 2), padding='same')(conv5), conv4], axis=3)
conv6 = Conv2D(256, (3, 3), activation='relu', padding='same')(up6)
conv6 = Conv2D(256, (3, 3), activation='relu', padding='same')(conv6)
up7 = concatenate([Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(conv6), conv3], axis=3)
conv7 = Conv2D(128, (3, 3), activation='relu', padding='same')(up7)
conv7 = Conv2D(128, (3, 3), activation='relu', padding='same')(conv7)
up8 = concatenate([Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(conv7), conv2], axis=3)
conv8 = Conv2D(64, (3, 3), activation='relu', padding='same')(up8)
conv8 = Conv2D(64, (3, 3), activation='relu', padding='same')(conv8)
up9 = concatenate([Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(conv8), conv1], axis=3)
conv9 = Conv2D(32, (3, 3), activation='relu', padding='same')(up9)
conv9 = Conv2D(32, (3, 3), activation='relu', padding='same')(conv9)
conv10 = Conv2D(1, (1, 1), activation='sigmoid')(conv9)
model = Model(inputs=[inputs], outputs=[conv10])
model.compile(optimizer=Adam(lr=1e-5), loss=dice_coef_loss, metrics=[dice_coef])
return model
def preprocess(imgs):
imgs_p = np.ndarray((imgs.shape[0], img_rows, img_cols), dtype=np.uint8)
for i in range(imgs.shape[0]):
imgs_p[i] = resize(imgs[i], (img_cols, img_rows), preserve_range=True)
imgs_p = imgs_p[..., np.newaxis]
return imgs_p
def train_and_predict():
DataCreator()
print('-'*30)
print('Loading and preprocessing train data...')
print('-'*30)
imgs_train, imgs_mask_train = DataLoader()
print(imgs_train.shape)
imgs_train = preprocess(imgs_train)
imgs_mask_train = preprocess(imgs_mask_train)
imgs_train = imgs_train.astype('float32')
mean = np.mean(imgs_train) # mean for data centering
std = np.std(imgs_train) # std for data normalization
imgs_train -= mean
print(std)
imgs_train /= std
imgs_mask_train = imgs_mask_train.astype('float32')
imgs_mask_train /= 255. # scale masks to [0, 1]
print('-'*30)
print('Creating and compiling model...')
print('-'*30)
model = get_unet()
model_checkpoint = ModelCheckpoint('weights.h5', monitor='val_loss', save_best_only=True)
print('-'*30)
print('Fitting model...')
print('-'*30)
model.fit(imgs_train, imgs_mask_train, batch_size=16, nb_epoch=50, verbose=1, shuffle=True,
validation_split=0.2,
callbacks=[model_checkpoint])
print('-'*30)
print('Loading and preprocessing test data...')
print('-'*30)
imgs_test, imgs_id_test = load_test_data()
imgs_test = preprocess(imgs_test)
imgs_test = imgs_test.astype('float32')
imgs_test -= mean
imgs_test /= std
print('-'*30)
print('Loading saved weights...')
print('-'*30)
model.load_weights('weights.h5')
print('-'*30)
print('Predicting masks on test data...')
print('-'*30)
imgs_mask_test = model.predict(imgs_test, verbose=1)
np.save('imgs_mask_test.npy', imgs_mask_test)
print('-' * 30)
print('Saving predicted masks to files...')
print('-' * 30)
pred_dir = 'preds'
if not os.path.exists(pred_dir):
os.mkdir(pred_dir)
i=0
for image in imgs_mask_test:
image = (image[:, :, 0] * 255.).astype(np.uint8)
imsave(os.path.join(pred_dir, str(i) + '_pred.png'), image)
i+=1
if __name__ == '__main__':
train_and_predict()
| [
"lambrecht.louis@yahoo.fr"
] | lambrecht.louis@yahoo.fr |
74041d4d8e6752824bac3357a3407c6a73b755c5 | c3b982f0b0a16c81a94c98b8cdd80e5d461f0a6f | /mwparse.py | 559e8a931ac2b02ec053996c45087924c145b57c | [
"MIT"
] | permissive | moonpotato/mwparse | 32ca18fb21813c64ea54441cb41a7effde45392e | fef1c9ed85b775d947a21277e55cf83e22694e12 | refs/heads/master | 2021-05-05T13:26:41.076782 | 2017-09-27T21:08:37 | 2017-09-27T21:08:37 | 105,058,993 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,635 | py | #/usr/bin/env python3
from string import whitespace
block_tokens = {}
inline_tokens = {}
def parse_into(file, store, minelems=2):
msg = 'error: invalid line: {}\nnote: in file "{}"'
gen = (line.rstrip('\n') for line in file)
for line in gen:
if not line.strip():
continue
parts = [part.strip() for part in line.split('\t')]
nparts = len(parts)
if nparts < minelems or nparts > 4:
raise Exception(msg.format(line, file.name))
toklen = len(parts[0])
if toklen not in store:
store[toklen] = {}
if parts[0] in store[toklen]:
raise Exception(msg.format(line, file.name))
if nparts == 4:
if parts[-1] == "yes":
parts[-1] = True
elif parts[-1] == "no":
parts[-1] = False
else:
raise Exception(msg.format(line, file.name))
elif nparts == 3:
parts.append(True)
store[toklen][parts[0]] = tuple(parts[1:])
def parse_block_config(fname):
with open(fname, 'r') as f:
parse_into(f, block_tokens, 3)
def parse_inline_config(fname):
with open(fname, 'r') as f:
parse_into(f, inline_tokens)
def block_step_length():
return max(key for key in block_tokens)
def inline_step_length():
return max(key for key in inline_tokens)
file_sheader = '''<!DOCTYPE html>
<html lang="{}">
<head>
<meta charset="utf-8">
<title>{}</title>'''
file_stylesheet = ''' <link rel="stylesheet" type="text/css" href="{}">'''
file_eheader = ''' </head>
<body class="{}">'''
file_footer = ''' </body>
</html>'''
class InlineParser:
def __init__(self, outf):
self._outf = outf
self._tmax = inline_step_length()
self._tokstate = []
self._noadmit = False
def _print(self, text):
return print(text, file=self._outf, end='')
def _translate_token(self, token, token_rep):
if self._noadmit:
if token == self._tokstate[-1]:
self._noadmit = False
else:
return token
if len(token_rep) == 1:
return token_rep[0]
elif token not in self._tokstate:
self._tokstate.append(token)
if not token_rep[2]: self._noadmit = True
return token_rep[0]
elif token == self._tokstate[-1]:
self._tokstate.pop()
return token_rep[1]
else:
msg = "error: encountered unexpected token: {}"
raise Exception(msg.format(token))
def _emit_token(self, buf):
for i in range(self._tmax, 0, -1):
bufpart = str().join(buf[0:i])
if bufpart in inline_tokens[i]:
token_rep = inline_tokens[i][bufpart]
output = self._translate_token(bufpart, token_rep)
self._print(output)
del buf[0:i]
return
self._print(buf.pop(0))
def reset(self, indent=6):
if len(self._tokstate) > 0:
self._print(' ' * indent)
for token in reversed(self._tokstate):
output = inline_tokens[len(token)][token][1]
self._print(output)
self._print('\n')
self._tokstate.clear()
def parse(self, line, indent=6):
if not line.strip():
return
self._print(' ' * indent)
buf = []
for letter in line:
buf.append(letter)
if len(buf) >= self._tmax:
self._emit_token(buf)
while len(buf) > 0:
self._emit_token(buf)
self._print('\n')
class BlockParser:
ACCEPTING = 1
INBLOCK = 2
def __init__(self, outf, iparser):
self._outf = outf
self._iparser = iparser
self._tmax = block_step_length()
self._bstate = []
self._ilevel = 0
self._gstate = BlockParser.ACCEPTING
self._pclasses = ""
self._noadmit = False
def _print(self, text):
print(' ' * self._level(), file=self._outf, end='')
print(text, file=self._outf)
def _next_token(self, line, pos):
start = min(self._tmax, len(line) - pos)
for i in range(start, 0, -1):
bufpart = str().join(line[pos:pos + i])
if bufpart in block_tokens[i]:
return (True, bufpart)
return (False, line[pos:].rstrip())
def _tokenize(self, line):
toklist = []
linepos = 0
cont = True
while cont:
while linepos < len(line) and line[linepos] in whitespace:
linepos += 1
cont, tok = self._next_token(line, linepos)
linepos += len(tok)
toklist.append(tok)
return toklist
def _emit_para_start(self):
self._print('<p class="{}">'.format(self._pclasses))
self._ilevel += 1
def _emit_para_end(self):
self._ilevel -= 1
self._print('</p>')
def _emit_block_start(self, blist):
msg = "error: expected same or greater indentation"
msg += "\nnote: have {}, got {}".format(str(self._bstate), str(blist))
if len(blist) >= self._ilevel:
for x, y in zip(blist, self._bstate):
if x != y: raise Exception(msg)
additional = blist[self._ilevel:]
for block in additional:
block_info = block_tokens[len(block)][block]
self._print(block_info[0])
self._bstate.append(block)
self._ilevel += 1
if len(block_info) == 3 and not block_info[-1]:
self._noadmit = True
break
if not self._noadmit:
self._emit_para_start()
else:
print(blist, self._ilevel)
raise Exception(msg)
def _emit_block_end(self, blist):
self._iparser.reset(self._level())
msg = "error: expected same or lesser indentation"
msg += "\nnote: have {}, got {}".format(str(self._bstate), str(blist))
if len(blist) <= self._ilevel:
for x, y in zip(blist, self._bstate):
if x != y: raise Exception(msg)
if not self._noadmit:
self._emit_para_end()
blen = len(blist)
if self._ilevel > len(blist):
self._noadmit = False
while self._ilevel > len(blist):
currblock = self._bstate.pop()
output = block_tokens[len(currblock)][currblock][1]
self._ilevel -= 1
self._print(output)
else: raise Exception(msg)
def _level(self):
return 6 + (2 * self._ilevel)
def parse(self, line):
toklist = self._tokenize(line)
del line
blocks = toklist[:-1]
text = toklist[-1]
del toklist
if self._gstate == BlockParser.ACCEPTING:
if text != '':
self._emit_block_start(blocks)
self._gstate = BlockParser.INBLOCK
elif blocks != self._bstate:
msg = "error: expected same indentation"
msg += "\nnote: expected {}, got {}"
raise Exception(msg.format(str(self._bstate), str(blocks)))
else:
if text == '':
self._emit_block_end(blocks)
self._gstate = BlockParser.ACCEPTING
elif len(blocks) > 0:
msg = "error: didn't expect an indentation spec"
raise Exception(msg)
self._iparser.parse(text, self._level())
def end(self):
self.parse('')
def set_paragraphing(self, gap, drop):
classes = []
if gap: classes.append("gap")
if drop: classes.append("drop")
self._pclasses = " ".join(classes)
def set_config(bconf="block.cfg", iconf="inline.cfg"):
parse_block_config(bconf)
parse_inline_config(iconf)
def parse_file(inname, outname,
title="Document", stylesheets=["rules.css"],
invert=False, gap=True, drop=False, lang="en"):
with open(inname, 'r') as inf, open(outname, 'w') as outf:
parser = BlockParser(outf, InlineParser(outf))
parser.set_paragraphing(gap, drop)
print(file_sheader.format(lang, title), file=outf)
for sheet in stylesheets:
print(file_stylesheet.format(sheet), file=outf)
print(file_eheader.format("invert" if invert else ''), file=outf)
gen = (line.rstrip('\n') for line in inf)
for line in gen:
try:
parser.parse(line)
except Exception as e:
msg = e.args[0] + "\non line: {}"
e.args = (msg.format(line),)
raise
parser.end()
print(file_footer, file=outf)
import getopt
from sys import argv, exit
if __name__ == "__main__":
shortopts = "b:l:t:s:i"
opts, args = getopt.getopt(argv[1:], shortopts)
blockconf = "~/.mwp/block.cfg"
inlineconf = "~/.mwp/inline.cfg"
title = "Document"
stylesheets = []
invert = False
for o, a in opts:
if o == "-b":
blockconf = a
elif o == "-l":
inlineconf = a
elif o == "-t":
title = a
elif o == "-s":
stylesheets.append(a)
elif o == "-i":
invert = True
set_config(blockconf, inlineconf)
for arg in args:
parse_file(arg, arg + ".html", title, stylesheets, invert)
| [
"noreply@github.com"
] | moonpotato.noreply@github.com |
000630fb41fd092985ccd43956f8e3d36c540362 | 529a9486106db7932c720dc2881676118b1bdd7c | /Pyramid pattern.py | 38a11097629eebc868e8fd024545c350a0da44b4 | [] | no_license | KaloriaSid/GeneralPythonPrograms | 40b486b68774013f452d72a017e6931c508de9c1 | aae9b34f8dc0d0b96088d1a9b844ada01324f129 | refs/heads/main | 2023-04-02T19:28:38.957671 | 2021-04-04T04:47:26 | 2021-04-04T04:47:26 | 354,457,359 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 365 | py | while True:
row = input('Upto which row: ')
try:
row = int(row)
spacing = row - 1
for i in range(1, row + 1):
print(' ' * spacing, end='')
for j in range(i):
print(i, end=' ')
print()
spacing -= 1
except:
print('Invalid input')
quit()
| [
"noreply@github.com"
] | KaloriaSid.noreply@github.com |
d4c5b23e8919dab8fb8ea89103ef4f17d564c3f5 | 1c8be1113e1cd5868e06a4ddf1b86fe5b9732a89 | /CitrineTestVenv/venv/lib/python3.7/site-packages/citrination_client/data/client.py | 9edad06bba90a84817136dd0b3966628c03eff9f | [] | no_license | joselle4/Citrine | a33c5a9397f31f818de5a1d1f9c87c9296de9b1b | c06eacd4c4f959194099e0686d06fd2d71a17baf | refs/heads/master | 2023-06-25T18:27:02.913931 | 2021-07-13T00:48:53 | 2021-07-13T00:48:53 | 385,425,784 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,514 | py | from citrination_client.base.base_client import BaseClient
from citrination_client.base.errors import *
from citrination_client.data import *
from citrination_client.data import routes as routes
from pypif import pif
import os
import shutil
import requests
class DataClient(BaseClient):
"""
Client encapsulating data management behavior.
"""
def __init__(self, api_key, host="https://citrination.com", suppress_warnings=False, proxies=None):
"""
Constructor.
:param api_key: A users API key, as a string
:type api_key: str
:param host: The base URL of the citrination site, e.g. https://citrination.com
:type host: str
:param suppress_warnings: Whether or not usage warnings should be
printed to stdout
:type suppress_warnings: bool
"""
members = [
"upload",
"list_files",
"matched_file_count",
"get_dataset_files",
"get_dataset_file",
"download_files",
"create_dataset",
"create_dataset_version",
"get_ingest_status"
]
super(DataClient, self).__init__(api_key, host, members, suppress_warnings, proxies)
def upload(self, dataset_id, source_path, dest_path=None):
"""
Upload a file, specifying source and dest paths a file (acts as the scp command).asdfasdf
:param source_path: The path to the file on the source host asdf
:type source_path: str
:param dest_path: The path to the file where the contents of the upload will be written (on the dest host)
:type dest_path: str
:return: The result of the upload process
:rtype: :class:`UploadResult`
"""
upload_result = UploadResult()
source_path = str(source_path)
if not dest_path:
dest_path = source_path
else:
dest_path = str(dest_path)
if os.path.isdir(source_path):
for path, subdirs, files in os.walk(source_path):
relative_path = os.path.relpath(path, source_path)
current_dest_prefix = dest_path
if relative_path is not ".":
current_dest_prefix = os.path.join(current_dest_prefix, relative_path)
for name in files:
current_dest_path = os.path.join(current_dest_prefix, name)
current_source_path = os.path.join(path, name)
try:
if self.upload(dataset_id, current_source_path, current_dest_path).successful():
upload_result.add_success(current_source_path)
else:
upload_result.add_failure(current_source_path,"Upload failure")
except (CitrinationClientError, ValueError) as e:
upload_result.add_failure(current_source_path, str(e))
return upload_result
elif os.path.isfile(source_path):
file_data = { "dest_path": str(dest_path), "src_path": str(source_path)}
j = self._get_success_json(self._post_json(routes.upload_to_dataset(dataset_id), data=file_data))
s3url = _get_s3_presigned_url(j)
with open(source_path, 'rb') as f:
if os.stat(source_path).st_size == 0:
# Upload a null character as a placeholder for
# the empty file since Citrination does not support
# truly empty files
data = "\0"
else:
data = f
r = requests.put(s3url, data=data, headers=j["required_headers"])
if r.status_code == 200:
data = {'s3object': j['url']['path'], 's3bucket': j['bucket']}
self._post_json(routes.update_file(j['file_id']), data=data)
upload_result.add_success(source_path)
return upload_result
else:
raise CitrinationClientError("Failure to upload {} to Citrination".format(source_path))
else:
raise ValueError("No file at specified path {}".format(source_path))
def list_files(self, dataset_id, glob=".", is_dir=False):
"""
List matched filenames in a dataset on Citrination.
:param dataset_id: The ID of the dataset to search for files.
:type dataset_id: int
:param glob: A pattern which will be matched against files in the dataset.
:type glob: str
:param is_dir: A boolean indicating whether or not the pattern should match against the beginning of paths in the dataset.
:type is_dir: bool
:return: A list of filepaths in the dataset matching the provided glob.
:rtype: list of strings
"""
data = {
"list": {
"glob": glob,
"isDir": is_dir
}
}
return self._get_success_json(self._post_json(routes.list_files(dataset_id), data, failure_message="Failed to list files for dataset {}".format(dataset_id)))['files']
def matched_file_count(self, dataset_id, glob=".", is_dir=False):
"""
Returns the number of files matching a pattern in a dataset.
:param dataset_id: The ID of the dataset to search for files.
:type dataset_id: int
:param glob: A pattern which will be matched against files in the dataset.
:type glob: str
:param is_dir: A boolean indicating whether or not the pattern should match against the beginning of paths in the dataset.
:type is_dir: bool
:return: The number of matching files
:rtype: int
"""
list_result = self.list_files(dataset_id, glob, is_dir)
return len(list_result)
def get_ingest_status(self, dataset_id):
"""
Returns the current status of dataset ingestion. If any file uploaded to a dataset is in an error/failure state
this endpoint will return error/failure. If any files are still processing, will return processing.
:param dataset_id: Dataset identifier
:return: Status of dataset ingestion as a string
"""
failure_message = "Failed to create dataset ingest status for dataset {}".format(dataset_id)
response = self._get_success_json(
self._get('v1/datasets/' + str(dataset_id) + '/ingest-status',
failure_message=failure_message))['data']
if 'status' in response:
return response['status']
return ''
def get_dataset_files(self, dataset_id, glob=".", is_dir=False, version_number=None):
"""
Retrieves URLs for the files matched by a glob or a path to a directory
in a given dataset.
:param dataset_id: The id of the dataset to retrieve files from
:type dataset_id: int
:param glob: A regex used to select one or more files in the dataset
:type glob: str
:param is_dir: Whether or not the supplied pattern should be treated as a directory to search in
:type is_dir: bool
:param version_number: The version number of the dataset to retrieve files from
:type version_number: int
:return: A list of dataset files whose paths match the provided pattern.
:rtype: list of :class:`DatasetFile`
"""
if version_number is None:
latest = True
else:
latest = False
data = {
"download_request": {
"glob": glob,
"isDir": is_dir,
"latest": latest
}
}
failure_message = "Failed to get matched files in dataset {}".format(dataset_id)
versions = self._get_success_json(self._post_json(routes.matched_files(dataset_id), data, failure_message=failure_message))['versions']
# if you don't provide a version number, only the latest
# will be included in the response body
if version_number is None:
version = versions[0]
else:
try:
version = list(filter(lambda v: v['number'] == version_number, versions))[0]
except IndexError:
raise ResourceNotFoundException()
return list(
map(
lambda f: DatasetFile(path=f['filename'], url=f['url']), version['files']
)
)
def get_dataset_file(self, dataset_id, file_path, version = None):
"""
Retrieves a dataset file matching a provided file path
:param dataset_id: The id of the dataset to retrieve file from
:type dataset_id: int
:param file_path: The file path within the dataset
:type file_path: str
:param version: The dataset version to look for the file in. If nothing is supplied, the latest dataset version will be searched
:type version: int
:return: A dataset file matching the filepath provided
:rtype: :class:`DatasetFile`
"""
return self.get_dataset_files(dataset_id, "^{}$".format(file_path), version_number=version)[0]
def download_files(self, dataset_files, destination='.'):
"""
Downloads file(s) to a local destination.
:param dataset_files:
:type dataset_files: list of :class: `DatasetFile`
:param destination: The path to the desired local download destination
:type destination: str
:param chunk: Whether or not to chunk the file. Default True
:type chunk: bool
"""
if not isinstance(dataset_files, list):
dataset_files = [dataset_files]
for f in dataset_files:
filename = f.path.lstrip('/')
local_path = os.path.join(destination, filename)
if not os.path.isdir(os.path.dirname(local_path)):
os.makedirs(os.path.dirname(local_path))
r = requests.get(f.url, stream=True)
with open(local_path, 'wb') as output_file:
shutil.copyfileobj(r.raw, output_file)
def get_pif(self, dataset_id, uid, dataset_version = None):
"""
Retrieves a PIF from a given dataset.
:param dataset_id: The id of the dataset to retrieve PIF from
:type dataset_id: int
:param uid: The uid of the PIF to retrieve
:type uid: str
:param dataset_version: The dataset version to look for the PIF in. If nothing is supplied, the latest dataset version will be searched
:type dataset_version: int
:return: A :class:`Pif` object
:rtype: :class:`Pif`
"""
failure_message = "An error occurred retrieving PIF {}".format(uid)
if dataset_version == None:
response = self._get(routes.pif_dataset_uid(dataset_id, uid), failure_message=failure_message)
else:
response = self._get(routes.pif_dataset_version_uid(dataset_id, uid, dataset_version), failure_message=failure_message)
return pif.loads(response.content.decode("utf-8"))
def create_dataset(self, name=None, description=None, public=False):
"""
Create a new data set.
:param name: name of the dataset
:type name: str
:param description: description for the dataset
:type description: str
:param public: A boolean indicating whether or not the dataset should be public.
:type public: bool
:return: The newly created dataset.
:rtype: :class:`Dataset`
"""
data = {
"public": _convert_bool_to_public_value(public)
}
if name:
data["name"] = name
if description:
data["description"] = description
dataset = {"dataset": data}
failure_message = "Unable to create dataset"
result = self._get_success_json(self._post_json(routes.create_dataset(), dataset, failure_message=failure_message))
return _dataset_from_response_dict(result)
def update_dataset(self, dataset_id, name=None, description=None, public=None):
"""
Update a data set.
:param dataset_id: The ID of the dataset to update
:type dataset_id: int
:param name: name of the dataset
:type name: str
:param description: description for the dataset
:type description: str
:param public: A boolean indicating whether or not the dataset should
be public.
:type public: bool
:return: The updated dataset.
:rtype: :class:`Dataset`
"""
data = {
"public": _convert_bool_to_public_value(public)
}
if name:
data["name"] = name
if description:
data["description"] = description
dataset = {"dataset": data}
failure_message = "Failed to update dataset {}".format(dataset_id)
response = self._get_success_json(self._post_json(routes.update_dataset(dataset_id), data=dataset, failure_message=failure_message))
return _dataset_from_response_dict(response)
def create_dataset_version(self, dataset_id):
"""
Create a new data set version.
:param dataset_id: The ID of the dataset for which the version must be bumped.
:type dataset_id: int
:return: The new dataset version.
:rtype: :class:`DatasetVersion`
"""
failure_message = "Failed to create dataset version for dataset {}".format(dataset_id)
number = self._get_success_json(self._post_json(routes.create_dataset_version(dataset_id), data={}, failure_message=failure_message))['dataset_scoped_id']
return DatasetVersion(number=number)
def _dataset_from_response_dict(dataset):
return Dataset(dataset['id'], name=dataset['name'],
description=dataset['description'], created_at=dataset['created_at'])
def _convert_bool_to_public_value(val):
if val == None:
return None
if val == False:
return '0'
if val == True:
return '1'
# for backwards compatability, support the old API #utahisrad
if val == '0' or val == '1':
return val
def _get_s3_presigned_url(response_dict):
"""
Helper method to create an S3 presigned url from the response dictionary.
"""
url = response_dict['url']
return url['scheme']+'://'+url['host']+url['path']+'?'+url['query']
| [
"joselle4@gmail.com"
] | joselle4@gmail.com |
8df83cf1b86c276ff58c9980f99da614048dc05e | 8773b5781d09ca3ad75cebd31d08ca858a4767cd | /euler35.py | bc4fbfcf7ba27634e0f052f1830efe0b900e5fa7 | [] | no_license | davidbeg/EulerProject | 50df8e6f578f9a3016f662f137e0e803d49bf23a | 2d9dc3901db2ec8b0e6006bf779c6f6653d334d5 | refs/heads/master | 2020-07-31T20:08:48.250185 | 2020-04-17T23:09:53 | 2020-04-17T23:09:53 | 210,739,616 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 601 | py | from math import floor, sqrt
def is_prime(x):
for i in range(2, floor(sqrt(x)) + 1):
if x % i == 0:
return False
return True
selected = set()
primes = set()
for i in range(2, 10 ** 6):
good_permutations = []
test_num = i
for _ in range(len(str(i))):
if test_num in primes or is_prime(test_num):
good_permutations.append(test_num)
primes.add(test_num)
s = str(test_num)
test_num = int(s[-1] + s[:-1])
if len(good_permutations) == len(str(i)):
selected.add(i)
print(selected)
print(len(selected))
| [
"begun.david@gmail.com"
] | begun.david@gmail.com |
616f22ddc31c0e0980782a5f8a374f65e36a3be3 | b66d3fdfe77e26142b2915f571a5c3add79547ae | /3) data quality evaluation/propensity score/bioresponse/propensity_score_plot.py | 6b849e7144aa5f230498920894e575ec8fcf15a0 | [] | no_license | amarek1/MSc-Project | 2319a57edbf78680dacc88f2261ce7e02092e3eb | 0c4fb6bd82c9a93fcca1ee2b140468921667583d | refs/heads/master | 2022-02-20T23:39:31.294769 | 2019-09-06T15:25:22 | 2019-09-06T15:25:22 | 197,189,640 | 5 | 2 | null | null | null | null | UTF-8 | Python | false | false | 904 | py | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(7)
score_synthpop = 0.17208491030541753
score_GAN = 0.24996948323493387
score_cGAN =0.249997663829577
score_WGAN =0.24998105907491794
score_WcGAN =0.24999997979218513
score_tGAN = 0
fig = plt.figure()
x = np.arange(6)
distance = [score_synthpop, score_GAN, score_cGAN, score_WGAN, score_WcGAN, score_tGAN]
plt.title('Propensity score for bioresponse dataset')
plt.ylabel('Score')
plt.xlabel('data generator')
a = plt.bar(x, distance)
plt.xticks(x, ('synthpop', 'GAN', 'cGAN', 'WGAN', 'WcGAN', 'tGAN'))
plt.tight_layout()
a[0].set_color('yellowgreen')#'lightseagreen')
a[1].set_color('gold')
a[2].set_color('darkorange')
a[3].set_color('grey')
a[4].set_color('royalblue')#'dodgerblue')
a[5].set_color('mediumvioletred')
plt.savefig('3) data quality evaluation/propensity score/bioresponse/propensity_score_plot.png') | [
"31806815+amarek1@users.noreply.github.com"
] | 31806815+amarek1@users.noreply.github.com |
481e0aa05a4a8aba80d4a34675a3b0c0634a5fe2 | c144681ee28a2d9a429dbaf4cb1dc40781684737 | /venv/bin/flask | 5babb3727aa923e98838a9d2c7432fafeffe2e04 | [] | no_license | krpraveen0/shannentech | e5368f0dafb0d76f097355b8b445a782cfaa8f65 | 05b97fada2710e0d134da306612ff7d83055f3b1 | refs/heads/main | 2023-01-10T09:03:05.937500 | 2020-10-21T07:38:58 | 2020-10-21T07:38:58 | 305,941,176 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 252 | #!/Users/peeyushpandey/Desktop/shannentech/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from flask.cli import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"pkec151015@gmail.com"
] | pkec151015@gmail.com | |
85f83b10ec9eaa8088dbc2d0ee23c1d2892477bf | 90f4e30f430679dcb9c8782d410ed251e10d8a9f | /mislnet_mri_train.py | 00550e9b750cd7ae9f9fbc74973930d50e0fd48c | [] | no_license | XenBond/MRI_training | 90daef22cce94c7047f8e99e89b3f10101807208 | ba92be5073f0268cd59932e4acf36dfe18e49043 | refs/heads/master | 2023-03-30T14:48:19.145106 | 2021-03-29T13:49:23 | 2021-03-29T13:49:23 | 352,648,607 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,468 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 10 13:54:24 2019
@author: shengbang
"""
import os
from os import path
#import tensorlayer as tl
import sys
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from six.moves import urllib
from tensorflow.python.framework import ops
from mislnet_mri import *
import math
# This script is in lab24
print(tf.VERSION)
tf.reset_default_graph()
# Project naming and parameters setting
exp_name = 'mislnet_MRI_128_2_MIXED_LESS_80k'
model_scope = 'mislnet_MRI_2_Class'
ep = 200
ep_decay = 5
weight_decay = 0.001
learning_rate = 0.00001
lr_decay = 0.8
cls_num = 2
tot_patch = int(40000 * cls_num)
tot_patch_test = int(2000 * cls_num)
channel = 1
im_size = 128
batch_size = 64
test_size = 50
test_iter = int(tot_patch_test/test_size)
generations = int(ep * tot_patch/batch_size)
stepsize = int(ep_decay * tot_patch/batch_size)
eval_every = int(tot_patch/batch_size)
GLOBAL_STEP = 0
save_dir = '/data/shengbang/tensorflow_MRI/'
save_path = path.join(save_dir, exp_name)
if not os.path.exists(save_path):
os.mkdir(save_path)
log_path = path.join(save_path, 'tflog')
if not os.path.exists(log_path):
os.mkdir(log_path)
tfboard = path.join(save_path, 'tfboard')
if not os.path.exists(tfboard):
os.mkdir(tfboard)
trained_model_path = path.join(save_path, 'model')
if not os.path.exists(trained_model_path):
os.mkdir(trained_model_path)
def bar_f(x):
if(abs(x)>1):
return np.sign(x)
else:
return x
vfunc = np.vectorize(bar_f)
def sigmoid(x):
return 1/(1+(math.e**-x))
def constrain(w):
w = w * 10000
w[2, 2, :, :] = 0
w = w.reshape([1, 25, channel, 3])
w = w / w.sum(1)
w = w.reshape([5, 5, channel, 3])
# prevent w from explosion
#w = sigmoid(w) * 2 - 1
w = vfunc(w)
w[2, 2, :, :] = -1
return w
def get_loss(logits, targets):
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=targets)
cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')
# tot_loss = cross_entropy_mean + sum(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))
#weights_norm = weight_decay * tf.stack([tf.nn.l2_loss(i) for i in tf.get_collection('weights')])
#weights_norm_mean = tf.reduce_sum(weights_norm)
#total_loss = cross_entropy_mean + weights_norm_mean
#return (cross_entropy_mean)
return cross_entropy_mean
def train_step(loss_value):
#model_learning_rate = tf.train.exponential_decay(learning_rate, global_step, stepsize, lr_decay, staircase=True)
#my_optimizer = tf.train.GradientDescentOptimizer(model_learning_rate)
my_optimizer = tf.train.AdamOptimizer(learning_rate)
#my_optimizer = tf.train.MomentumOptimizer(model_learning_rate,0.9)
train_step = my_optimizer.minimize(loss_value, global_step=global_step)
return (train_step)
def accuracy_of_batch(logits, targets):
labels = tf.cast(targets, tf.int32)
batch_predictions = tf.cast(tf.argmax(logits, 1), tf.int32)
predicted_correctly = tf.equal(batch_predictions, labels)
accuracy = tf.reduce_mean(tf.cast(predicted_correctly, tf.float32))
return (accuracy)
#initialize dataset and iterator, return image and labels
TFRECORD_PATH = '/data/shengbang/MRI_128_2_ALL_MIXED/'
tfrecords_train = TFRECORD_PATH + 'MRI_2_Class_TRAIN_MIXED_80k.tfrecords'
tfrecords_test = TFRECORD_PATH + 'MRI_2_Class_VALID_MIXED_4k.tfrecords'
dataset = tf.data.TFRecordDataset([tfrecords_train]).map(lambda x: read_decode(x, 1)).repeat().batch(batch_size=batch_size)
dataset_test = tf.data.TFRecordDataset([tfrecords_test]).map(lambda x: read_decode(x, 1)).repeat().batch(batch_size=test_size)
data_iter = dataset.make_initializable_iterator()
test_data_iter = dataset_test.make_initializable_iterator()
el = data_iter.get_next()
el_val = test_data_iter.get_next()
# input vector for images and labels
x = tf.placeholder(dtype=tf.float32,shape=[None,im_size,im_size,channel],name='x_placeholder')
y = tf.placeholder(dtype=tf.int64,shape=[None,],name= 'y_placeholder')
bn_phase = tf.placeholder(tf.bool,name='bn_phase_placeholder')
model_output = mislnet(x, False, bn_phase, cls_num, model_scope)
tf.add_to_collection('model_output',model_output)
loss = get_loss(model_output, y)
tf.add_to_collection('loss',loss)
train_summ = tf.summary.scalar("loss", loss)
accuracy = accuracy_of_batch(model_output, y)
tf.add_to_collection('accuracy',accuracy)
test_acc = tf.placeholder(tf.float32, shape=(),name='test_acc_placeholder')
test_summ = tf.summary.scalar('test_acc', test_acc)
global_step = tf.Variable(GLOBAL_STEP, trainable=False)
tf.add_to_collection('global_step',global_step)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = train_step(loss)
tf.add_to_collection('train_op',train_op)
convF_placeholder = tf.placeholder(tf.float32, shape=[5,5,channel,3],name='convF_placeholder')
convF_w = tf.get_collection('convF_w')[0]
constrain_op = convF_w.assign(convF_placeholder)
print('Initializing the Variables.')
sys.stdout.flush()
init_op = tf.global_variables_initializer()
saver = tf.train.Saver(max_to_keep=None, keep_checkpoint_every_n_hours=1)
save_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=model_scope)
#testing_summ = []
acc_tuple = []
loss_tuple = []
with tf.Session() as sess:
sess.run(init_op)
sess.run(data_iter.initializer)
sess.run(test_data_iter.initializer)
print('Starting Training')
sys.stdout.flush()
summary_writer = tf.summary.FileWriter(tfboard, tf.get_default_graph())
summary_writer.reopen()
w = sess.run(convF_w)
w = constrain(w)
sess.run([constrain_op], {convF_placeholder: w})
sess.graph.finalize()
for i in range(generations):
#for i in range(5):
itr = sess.run(global_step)
#print itr
ims, lbs = sess.run(el)
# print(ims.shape, lbs.shape)
sys.stdout.flush()
_, loss_value, training_summ = sess.run([train_op, loss,train_summ],feed_dict={x:ims,y:lbs,bn_phase:1})
summary_writer.add_summary(training_summ, global_step=itr)
output = 'Iter {}/{}: Loss = {:.5f}'.format(itr,generations, loss_value)
print(output)
w = sess.run(convF_w)
w = constrain(w)
sess.run([constrain_op], {convF_placeholder: w})
if (i + 1) % eval_every == 0:
saver.save(sess, trained_model_path + '/model', global_step=global_step)
#tl.files.save_npz_dict(save_list=save_list, name=trained_model_path + '/model-'+str(i+1)+'.npz', sess=sess)
acc_tot = 0
for ii in range(test_iter):
#test_ims, test_lbs = sess.run([test_images, test_targets])
test_ims, test_lbs = sess.run(el_val)
temp_accuracy = sess.run(accuracy,feed_dict={x:test_ims,y:test_lbs,bn_phase:0})
acc_tot = acc_tot + temp_accuracy
acc_tot = acc_tot / test_iter
# testing_summ.append(acc_tot)
acc_tuple.append(acc_tot)
loss_tuple.append(loss_value)
testing_summ = sess.run(test_summ, feed_dict={test_acc: acc_tot})
summary_writer.add_summary(testing_summ, global_step=itr)
acc_output = ' --- Test Accuracy = {:.2f}%.'.format(100. * acc_tot)
print(acc_output)
del ims,lbs,output,w,itr
| [
"542179363@qq.com"
] | 542179363@qq.com |
a25581851ebc08774e92788b3f4f132d9410d65a | 2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02 | /PyTorch/built-in/cv/detection/SSD_for_PyTorch/configs/regnet/mask_rcnn_regnetx-8GF_fpn_1x_coco.py | 21f9a34973365b59715f06155431771e0ff8f61e | [
"Apache-2.0",
"GPL-1.0-or-later",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Ascend/ModelZoo-PyTorch | 4c89414b9e2582cef9926d4670108a090c839d2d | 92acc188d3a0f634de58463b6676e70df83ef808 | refs/heads/master | 2023-07-19T12:40:00.512853 | 2023-07-17T02:48:18 | 2023-07-17T02:48:18 | 483,502,469 | 23 | 6 | Apache-2.0 | 2022-10-15T09:29:12 | 2022-04-20T04:11:18 | Python | UTF-8 | Python | false | false | 1,112 | py | # Copyright 2022 Huawei Technologies Co., Ltd.
# 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.
_base_ = './mask_rcnn_regnetx-3.2GF_fpn_1x_coco.py'
model = dict(
backbone=dict(
type='RegNet',
arch='regnetx_8.0gf',
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch',
init_cfg=dict(
type='Pretrained', checkpoint='open-mmlab://regnetx_8.0gf')),
neck=dict(
type='FPN',
in_channels=[80, 240, 720, 1920],
out_channels=256,
num_outs=5))
| [
"chenyong84@huawei.com"
] | chenyong84@huawei.com |
ca75be8929ecbfb06dee42cdb627d8e143aef079 | a460284649d1cf770069547b8fba24ed5e1a742a | /pytorch_segmentation_detection/models/unet.py | a5b9cb7a3238d71ce9af7ea4fd82a0fed46951d3 | [
"MIT"
] | permissive | Pandinosaurus/pytorch-segmentation-detection | 949e411f6f9950f1ad8d6f9d512b43512275e8d6 | 79ed72c14d7d81432ea9bd37d9148173c366ba49 | refs/heads/master | 2022-05-21T03:32:55.874924 | 2022-03-28T17:43:02 | 2022-03-28T17:43:02 | 372,073,733 | 0 | 0 | MIT | 2022-03-30T03:41:52 | 2021-05-29T21:39:19 | null | UTF-8 | Python | false | false | 6,634 | py | import torch
import torch.nn as nn
def conv3x3(in_planes, out_planes):
"3x3 convolution with padding"
return nn.Conv2d(in_planes,
out_planes,
kernel_size=3,
padding=1,
bias=True)
class UnetDownBlock(nn.Module):
""" Downsampling block of Unet.
The whole architercture of Unet has a one common pattern: a block
that spatially downsamples the input followed by two layers of 3x3 convolutions that
has 'inplanes' number of input planes and 'planes' number of channels.
"""
def __init__(self, inplanes, planes, predownsample_block):
super(UnetDownBlock, self).__init__()
self.predownsample_block = predownsample_block
self.conv1 = conv3x3(inplanes, planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
def forward(self, x):
x = self.predownsample_block(x)
x = self.conv1(x)
x = self.relu(x)
x = self.conv2(x)
return x
class UnetUpBlock(nn.Module):
""" Upsampling block of Unet.
The whole architercture of Unet has a one common pattern: a block
that has two layers of 3x3 convolutions that
has 'inplanes' number of input planes and 'planes' number of channels,
followed by 'postupsample_block' which increases the spatial resolution
"""
def __init__(self, inplanes, planes, postupsample_block=None):
super(UnetUpBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
if postupsample_block is None:
self.postupsample_block = torch.nn.ConvTranspose2d(in_channels=planes,
out_channels=planes/2,
kernel_size=2,
stride=2)
else:
self.postupsample_block = postupsample_block
def forward(self, x):
x = self.conv1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.postupsample_block(x)
return x
class Unet(nn.Module):
"""Unet network. ~297 ms on hd image."""
def __init__(self, num_classes=2):
super(Unet, self).__init__()
self.predownsample_block = nn.MaxPool2d(kernel_size=2, stride=2)
self.identity_block = nn.Sequential()
self.block1 = UnetDownBlock(
predownsample_block=self.identity_block,
inplanes=3,
planes=64,
)
self.block2_down = UnetDownBlock(
predownsample_block=self.predownsample_block,
inplanes=64,
planes=128,
)
self.block3_down = UnetDownBlock(
predownsample_block=self.predownsample_block,
inplanes=128,
planes=256
)
self.block4_down = UnetDownBlock(
predownsample_block=self.predownsample_block,
inplanes=256,
planes=512
)
self.block5_down = UnetDownBlock(
predownsample_block=self.predownsample_block,
inplanes=512,
planes=1024
)
self.block1_up = torch.nn.ConvTranspose2d(in_channels=1024,
out_channels=512,
kernel_size=2,
stride=2)
self.block2_up = UnetUpBlock(
inplanes=1024,
planes=512
)
self.block3_up = UnetUpBlock(
inplanes=512,
planes=256
)
self.block4_up = UnetUpBlock(
inplanes=256,
planes=128
)
self.block5 = UnetUpBlock(
inplanes=128,
planes=64,
postupsample_block=self.identity_block
)
self.logit_conv = nn.Conv2d(64,
num_classes,
kernel_size=1)
def forward(self, x):
input_spatial_dim = x.size()[2:]
# Left part of the U figure in the Unet paper
features_1s_down = self.block1(x)
features_2s_down = self.block2_down(features_1s_down)
features_4s_down = self.block3_down(features_2s_down)
features_8s_down = self.block4_down(features_4s_down)
# Bottom part of the U figure in the Unet paper
features_16s = self.block5_down(features_8s_down)
# Right part of the U figure in the Unet paper
features_8s_up = self.block1_up(features_16s)
features_8s_up = torch.cat([features_8s_down, features_8s_up], dim=1)
features_4s_up = self.block2_up(features_8s_up)
features_4s_up = torch.cat([features_4s_down, features_4s_up], dim=1)
features_2s_up = self.block3_up(features_4s_up)
features_2s_up = torch.cat([features_2s_down, features_2s_up], dim=1)
features_1s_up = self.block4_up(features_2s_up)
features_1s_up = torch.cat([features_1s_down, features_1s_up], dim=1)
features_final = self.block5(features_1s_up)
logits = self.logit_conv(features_final)
return logits | [
"warmspringwinds@gmail.com"
] | warmspringwinds@gmail.com |
97c870de2c5378f0519f9e7bd9a9a4a4ac4a7ca5 | 79b4ab3fe4e743f4e1d1b686d92c408ad0f656c1 | /bodies/ld3w/gps.py | 34758a1eb040d1c7d45e083e596b5eb06ca34346 | [] | no_license | garysb/neuron-robotics | d4db8f64972f3072b07b93ed549aaeaf51fbbdd0 | bff3fbc97dd3b8b9373a08250e49a2f1113db0f2 | refs/heads/master | 2015-07-29T04:19:46.614508 | 2015-07-01T15:20:32 | 2015-07-01T15:20:32 | 826,182 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 4,873 | py | import threading
import Queue
import time
import cPickle
import thread_template
from bodies.ld3w import nmea
class gps(thread_template.ThreadTemplate):
""" Threaded object to send bluetooth messages to the ld3w controller. This
lets us generate information about our true location within the world.
We use this information to try keep track of positions that our relative
data generator gathers. Once we create a map, we get the gps coordinates
and name the map by the coordinates. When we read a map, we get the gps
coordinates and try find a map of the location we are in.
"""
def __init__(self, s_queues, s_connects, s_conds, s_locks, s_sema):
thread_template.ThreadTemplate.__init__(self, s_queues, s_connects, s_conds, s_locks, s_sema)
self.s_queues.create('gps')
self.waypoints = []
self.true_heading = 1
def run(self):
""" Our gps loop keeps polling the gps reciever to try get a new reading
for our location. Once we have a reading, we tell the rest of the
system.
"""
self.setName('gps')
self.display('%s:\t\t\t\tStarting thread' % self.getName(), level=10)
# Loop in the thread and wait for items in the queue
while True:
self.parse_queue()
time.sleep(1)
# All done. Close the thread
self.display('%s:\t\t\t\tClosing thread' % self.getName(), level=10)
def parse_command(self, buff):
""" The parse_command method defines a list of actions that the drive
object can perform. When we recieve a command in our buffer, we try
to call the required method by placing it in the gps queue stack.
This lets us keep our priority system running properly. Please note
that actions that only return data arnt placed into the queue stack
because they dont block the device.
"""
# We have a command, proccess it
if buff == '':
return
else:
buff_v = buff.split(' ')
# Parse all gps functions
if buff_v[0] == 'gps':
# Check we have enough commands
if not len(buff_v) >= 2:
print "Not enough options"
return
if buff_v[1] == 'position':
print 'getting position'
# Check debug level
elif buff_v[1] == 'debug':
# if we dont have a value, just return the current level
if len(buff_v) >= 3:
self.s_queues.put('gps','set_debug',{'level':buff_v[2]})
else:
self.s_queues.put('gps','show_debug',{})
else:
print 'Command %s not found' % buff_v[1]
def get_position(self):
""" We query the gps device to try get a position. When we have a new
position, we return it to the caller.
"""
try:
cur_pos = {}
cur_pos['type'] = 'NON'
# Make sure we only use GGA nmea packets
while cur_pos['type'] != 'GGA':
self.parse_queue(timeout=1)
self.s_locks['ld3w'].acquire()
cur_pos = nmea.get_data(self.s_connects.bodies['ld3w']['cons'][0]['sock'])
self.s_locks['ld3w'].release()
self.display('%s:\t\t\t\tew:%s sn:%s' % (self.getName(), cur_pos['long'], cur_pos['lat']), level=0)
except:
self.display('%s:\t\t\t\tUnable to get position' % self.getName(), level=0)
def _poll(self):
try:
# Check the gps module
self.s_locks['ld3w'].acquire()
state = nmea.get_data(self.s_connects.bodies['ld3w']['cons'][0]['sock'])
self.s_locks['ld3w'].release()
# Display very detailed information
self.display('%s:\t\t\t\t%s' % (self.getName(), state), level=75)
# Display not-so detailed information
self.display('', level=50)
self.display('%s:\t\t\t\tType:\t\t\t%s' % (self.getName(), state['type']), level=50)
if state['type'] == 'GGA':
self.display('%s:\t\t\t\tLongitude:\t\t%s' % (self.getName(), state['long']), level=50)
self.display('%s:\t\t\t\tLatitude:\t\t%s' % (self.getName(), state['lat']), level=50)
self.display('%s:\t\t\t\tQuality:\t\t%s' % (self.getName(), state['quality']), level=50)
if state['type'] == 'GSA':
self.display('%s:\t\t\t\tH dilute:\t\t%s' % (self.getName(), state['hdop']), level=50)
self.display('%s:\t\t\t\tV dilute:\t\t%s' % (self.getName(), state['vdop']), level=50)
self.display('%s:\t\t\t\tDimentions:\t\t%s' % (self.getName(), state['fix']), level=50)
if state['type'] == 'GSV':
self.display('%s:\t\t\t\tSatellites:\t\t%s' % (self.getName(), state['count']), level=50)
if state['type'] == 'RMC':
self.display('%s:\t\t\t\tStatus:\t\t\t%s' % (self.getName(), state['status']), level=50)
self.display('%s:\t\t\t\tSpeed:\t\t\t%s' % (self.getName(), state['speed']), level=50)
self.display('%s:\t\t\t\tTrack:\t\t\t%s' % (self.getName(), state['track']), level=50)
self.display('%s:\t\t\t\tLongitude:\t\t%s' % (self.getName(), state['long']), level=50)
self.display('%s:\t\t\t\tLatitude:\t\t%s' % (self.getName(), state['lat']), level=50)
except:
self.display('%s:\t\t\t\tUnable to poll for position' % self.getName(), level=25)
| [
"gary@stroppytux.net"
] | gary@stroppytux.net |
a2cebe4f90c92e553be71dc3304d8b2439e15062 | 6e33115d368ef9fdb5760ec36f83c136ef882bf1 | /Tema1/main.py | 1556c1ac8727bf8ebffcd286c0dc544fbfb3244f | [] | no_license | IrinaGrigore7/Limbaje-Formale-si-Automate | 9fe927e335f0282ea31222c86ce7e8bf7f9a584b | b3e2321d234865396836b790b650ffe6915e8a4f | refs/heads/main | 2023-03-22T05:11:32.385855 | 2021-03-01T12:26:51 | 2021-03-01T12:26:51 | 343,361,782 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,736 | py | import sys
def findNextState(nextWord, patternList):
#caut un prefix al cuvantului format in lista de prefixe ale pattern-ului
for i in range (0, len(nextWord)):
for j in range(0, len(patternList)):
if patternList[j] == nextWord[i:len(nextWord)]:
return len(patternList[j])
return 0
def getMatrix(numberOfStates, patternList):
deltaMatrix = []
for i in range(0, numberOfStates):
currentRow = [] #linia care trebuie completata in matricea delta
currentWord = patternList[i] #linia curenta
for j in range(0, 26): #parcurg coloanele
nextWord = currentWord + chr(j + 65) #adaug fiecare litera pe rand
#pentru a gasi urmatoarea stare
currentRow.append(findNextState(nextWord, patternList))
deltaMatrix.append(currentRow)
return deltaMatrix
def printSolution(deltaMatrix, pattern, word):
q = 0
#printez indicii la care se gaseste pattern in word
for i in range(0, len(word)):
q = deltaMatrix[q][ord(word[i]) - 65]
if q == len(pattern):
f2.write(str((i - (len(pattern) - 1))))
f2.write(" ")
f2.write("\n")
if __name__ == '__main__':
filename1 = sys.argv[1]
filename2 = sys.argv[2]
f1 = open(filename1, "r")
f2 = open(filename2, "w")
stringsList = f1.readlines()
string1 = stringsList[0]
pattern = string1[0:len(string1) - 1] #elimin \n
string2 = stringsList[1]
word = string2[0:len(string2) - 1] #elimin \n
numberOfStates = len(pattern) + 1
patternList = [] # contine prefixele pattern-ului
patternList.append("")
for i in range(1, numberOfStates):
patternList.append(pattern[0:i])
deltaMatrix = getMatrix(numberOfStates, patternList)
printSolution(deltaMatrix, pattern, word)
| [
"noreply@github.com"
] | IrinaGrigore7.noreply@github.com |
abba1b90596fb5991864120524e9d37def0bf100 | 841fb0a6866f9fc7dcd8c0832375bc265cd56e8b | /.history/test_20210723133933.py | 52347259fdfe703ac52d5964a825dc457dd79c3a | [] | no_license | Yurun-LI/CodeEx | f12f77b214bcf98f3fa4acd2658a9c0597c1a2e6 | 5b3a427961ab87ce4c4536362a2ba1e34d438859 | refs/heads/master | 2023-06-21T23:52:26.624127 | 2021-07-27T03:44:34 | 2021-07-27T03:44:34 | 345,563,512 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,019 | py | import numpy as np
import matplotlib.pyplot as plt
class Sort:
def insertSort(self,ls):
arr = ls.copy()
Len = len(arr)
if Len <=1:
return arr
for i in range(1,Len):
curVal = arr[i]
j = i-1
while j>=0 and arr[j] > curVal:
arr[j+1] = arr[j]
j-=1
arr[j+1] = curVal
return arr
def shellSort(self,ls):
arr = ls.copy()
Len = len(arr)
if Len <=1:
return arr
h = 1
while h <=len(arr)//3:
h = h*3+1
while h>0:
for i in range(h,len(arr)):
val = arr[i]
j = i-h
while j>=0 and arr[j] > val:
arr[j+h] = arr[j]
j-=h
arr[j+h] = val
h = (h-1)//3
return arr
def bubbleSort(self,ls):
arr = ls.copy()
Len = len(arr)
if Len <=1:
return arr
for i in range(Len-1):
for j in range(Len-1-i):
if arr[j] > arr[j+1]:
arr[j],arr[j+1] = arr[j+1],arr[j]
return arr
def selectSort(self,ls):
arr = ls.copy()
Len = len(arr)
for i in range(Len-1):
minIdx = i
for j in range(i+1,Len):
if arr[j] < arr[minIdx]:
minIdx = j
arr[i],arr[minIdx] = arr[minIdx],arr[i]
# print(f'i={i},arr={arr}')
return arr
def mergeSort(self,ls):
arr = ls.copy()
def sort(arr,left,right):
if left == right:
return
mid = left+ (right-left) // 2
sort(arr,left,mid)
sort(arr,mid+1,right)
self.merge(arr,left,mid+1,right)
print(arr)
sort(arr,0,len(arr)-1)
return arr
def merge(self,arr,left,right,rightBound):
if left == right:
return
leftBound = right-1
i,j = left,right
temp = []
while i<=leftBound and j<= rightBound:
if arr[j]<arr[i]:
temp.append(arr[j])
j+=1
else:
temp.append(arr[i])
i+=1
if i>leftBound:
while j<=rightBound:
temp.append(arr[j])
else:
while i<=leftBound:
temp.append(arr[i])
arr[left:rightBound+1] = temp.copy()
# arr = np.random.permutation(np.arange(10))
# print(Sort().insertSort(arr))
def check():
for i in range(10):
arr = np.random.permutation(np.arange(100))
arr_ex = np.sort(arr)
# arr_insert = Sort().insertSort(arr)
arr_test = Sort().selectSort(arr)
for i,j in zip(arr_test,arr_ex):
if i != j:
print('Error')
return
print('right')
return
# check()
print([4,2,6,1,7,3])
Sort().mergeSort([4,2,6,1,7,3]) | [
"li1042278644@icloud.com"
] | li1042278644@icloud.com |
bffe3775877350a0d53f049549cc6499bd1d2cee | 36901e58fbdeabc7380ae2c0278010b2c51fe54d | /gatheros_subscription/urls/me.py | 4823370a6d4c79d1b4002d326f190346c0136ed1 | [] | no_license | hugoseabra/congressy | e7c43408cea86ce56e3138d8ee9231d838228959 | ac1e9b941f1fac8b7a13dee8a41982716095d3db | refs/heads/master | 2023-07-07T04:44:26.424590 | 2021-08-11T15:47:02 | 2021-08-11T15:47:02 | 395,027,819 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 269 | py | from django.conf.urls import include, url
from gatheros_subscription import views
urls = [
url(
r'^subscriptions/$',
views.MySubscriptionsListView.as_view(),
name='my-subscriptions'
),
]
urlpatterns_me = [url(r'^me/', include(urls))]
| [
"hugoseabra19@gmail.com"
] | hugoseabra19@gmail.com |
f8608f6744f69891b368c1f81d28e858fdd12402 | 44d2c12c5fccbfcd4813914a2a78a93edc8484aa | /week01/week01_homework_02/scrapy_movies/scrapy_movies/spiders/maoyan.py | 69a8c6cc80982207c577b313d58dcb6cc1f03455 | [] | no_license | chenjincheng/Python001-class01 | 20aaf3d3f0790abd87293ed2ac68b161f8e4cdeb | 9453b6d636dc3933c2c3936aa445f5988015be46 | refs/heads/master | 2022-11-18T02:07:46.312947 | 2020-06-30T17:24:47 | 2020-06-30T17:24:47 | 273,888,464 | 0 | 0 | null | 2020-06-21T11:14:53 | 2020-06-21T11:14:53 | null | UTF-8 | Python | false | false | 1,967 | py | # -*- coding: utf-8 -*-
import scrapy
from scrapy.selector import Selector
from ..items import ScrapyMoviesItem
class MaoyanSpider(scrapy.Spider):
name = 'maoyan'
allowed_domains = ['maoyan.com']
start_urls = ['http://maoyan.com/']
# ็ฌฌไธๆฌก่ฟ่ก๏ผไธๅช่ฟ่กไธๆฌก
def start_requests(self):
url = 'file:///D:/index.html'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36',
'Cookie' : 'uuid_n_v=v1; uuid=1F401820B95E11EA8E55532676AF0F4AF41FE8F97E5C4729B0B94E46AD3FA877; mojo-uuid=20f3a7cc12fb2a06f2a5000a5ab96acc; _lxsdk_cuid=172fbcd87e3c8-089042fd9b8e51-b791b36-144000-172fbcd87e3c8; _lxsdk=1F401820B95E11EA8E55532676AF0F4AF41FE8F97E5C4729B0B94E46AD3FA877; _csrf=9168db558e10cf4c19acd18727733fd8ffd838d449c56e3fe9b2cc2cb563d49e; mojo-session-id={"id":"2e910fe95029cf2774da33f934d34294","time":1593529453996}; lt=zzMA7xegfdyZO0-6pOQdMDxYUj4AAAAAAAsAADqAh3WgNbfffVfdxuWa7Rem_maGlcdnJhtHjM1Arenzmmfdy07dIWaV2BD7O9cWTw; lt.sig=HKiDA9FlTKDmyYToCupoJXfrsWM; mojo-trace-id=3; Hm_lvt_703e94591e87be68cc8da0da7cbd0be2=1593448430,1593448447,1593526128,1593530487; Hm_lpvt_703e94591e87be68cc8da0da7cbd0be2=1593530487; __mta=217488681.1593362450474.1593529454106.1593530487339.28; _lxsdk_s=17305c1ca68-56b-5d2-236%7C%7C5',
}
yield scrapy.Request(url=url, headers=headers, callback=self.parse)
def parse(self, response):
movies = Selector(response).xpath('//*[@class="movie-item film-channel"]')
for movie in movies :
item = ScrapyMoviesItem()
item['movie_name'] = movie.xpath('./div[2]/a/div/div[1]/span[1]/text()').extract_first().strip()
item['movie_type'] = movie.xpath('./div[2]/a/div/div[2]/text()').extract()[1].strip()
item['movie_date'] = movie.xpath('./div[2]/a/div/div[4]/text()').extract()[1].strip()
yield item | [
"cjcstc@163.com"
] | cjcstc@163.com |
070fc92166fd5c5e64836d1cf9676f441f1cdd5c | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_6404600001200128_1/Python/ihadanny/r1_p1.py | f67fc6f333dd5df96ae47855e77a0df26307669e | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | Python | false | false | 412 | py | from sys import stdin
import re
import operator
import bisect
import sys
import random
cases = int(stdin.next().strip())
for case in range(1, cases+1):
N = int(stdin.next().strip())
M = map(int, stdin.next().split())
drops = [max(i-j,0) for i, j in zip(M[:-1], M[1:])]
max_eaten = [min(max(drops), x) for x in M[:-1]]
print 'Case #%d: %d %d' % (case, sum(drops), sum(max_eaten)) | [
"eewestman@gmail.com"
] | eewestman@gmail.com |
81370fb27ca8ee771d8333b297381817241fd383 | 9193e2743434893c76e45b85a6a2ebcef71e8e2d | /ch03/ans27.py | 7e4795a48c12edf941443c284fa07ea89d030dc3 | [] | no_license | kyodocn/nlp100v2020 | d4f06a0eb089d7f056aa00817f79199fb4edfed2 | 99c66511352092a0f4c5028b1f440e09d6401331 | refs/heads/master | 2022-04-15T02:43:12.003780 | 2020-04-13T18:41:15 | 2020-04-13T18:41:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 741 | py | import re
import pandas as pd
df = pd.read_json('ch03/jawiki-country.json.gz', lines=True)
ukText = df.query('title=="ใคใฎใชใน"')['text'].values
ls, fg = [], False
template = 'ๅบ็คๆ
ๅ ฑ'
p1 = re.compile('\{\{' + template)
p2 = re.compile('\}\}')
p3 = re.compile('\|')
p4 = re.compile('<ref(\s|>).+?(</ref>|$)')
for l in ukText[0].split('\n'):
if fg:
ml = [p2.match(l), p3.match(l)]
if ml[0]:
break
if ml[1]:
ls.append(p4.sub('', l.strip()))
if p1.match(l):
fg = True
p = re.compile('\|(.+?)\s=\s(.+)')
ans = {m.group(1): m.group(2) for m in [p.match(c) for c in ls]}
r = re.compile('\[\[(.+\||)(.+?)\]\]')
ans = {k: r.sub(r'\2', v) for k, v in ans.items()}
print(ans)
| [
"upura0@gmail.com"
] | upura0@gmail.com |
9858e60b687ed2eda187ed1738782b3ff65ff931 | 8c1d90fddecdd90c9c4327ba0caeabf576b5246a | /Resources/PyPoll.py | 84f745334403fb6a6e7f0623c12bbf15bffdf23d | [] | no_license | michellemzx/election_analysis | 88a2405c882052af6418bb13ec195ac8e3b2c8c1 | c113b6c380fd6d3dfcb3abed21313854736d8ade | refs/heads/main | 2023-04-18T18:52:37.199852 | 2021-05-07T16:30:52 | 2021-05-07T16:30:52 | 365,104,221 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,631 | py | # # Open the data file.
import csv
import os
from collections import defaultdict
# Assign a variable for the file to load and the path.
file_to_load = os.path.join("Resources", "election_results.csv")
# Open the election results and read the file.
with open(file_to_load) as election_data:
# Print the file object.
print(election_data)
# Create a filename variable to a direct or indirect path to the file.
file_to_save = os.path.join("analysis", "election_analysis.txt")
# Using the with statement open the file as a text file.
with open(file_to_save, "w") as txt_file:
# Write some data to the file.
txt_file.write("Hello World\n")
txt_file.write("Counties in the Election\n--------------------\nArapahoe\nDenver\nJefferson")
############
# Add our dependencies.
import csv
import os
# Assign a variable to load a file from a path.
file_to_load = os.path.join("Resources", "election_results.csv")
# Assign a variable to save the file to a path.
file_to_save = os.path.join("analysis", "election_analysis.txt")
# 1. Initialize a total vote counter.
total_votes = 0
# Candidate Options
candidate_options = []
# 1. Declare the empty dictionary.
candidate_votes = {}
# Open the election results and read the file.
with open(file_to_load) as election_data:
file_reader = csv.reader(election_data)
# Read and print the header row.
headers = next(file_reader)
print(headers)
# Print each row in the CSV file.
for row in file_reader:
# print(row)
# 2. Add to the total vote count.
total_votes += 1
# Print the candidate name from each row.
candidate_name = row[2]
# If the candidate does not match any existing candidate...
if candidate_name not in candidate_options:
# Add it to the list of candidates.
candidate_options.append(candidate_name)
# Begin tracking that candidate's vote count.
candidate_votes[candidate_name] = 0
# Add a vote to that candidate's count
candidate_votes[candidate_name] += 1
# 3. Print the total votes.
print(total_votes)
print(candidate_options)
print(candidate_votes)
percentage_votes = {}
for x in candidate_votes:
percentage_votes[x] = f"{round(candidate_votes[x]/total_votes*100,2)}%"
print(percentage_votes)
print(f"winning candidate: {[x for x in percentage_votes if percentage_votes[x] == max(percentage_votes.values())][0]}")
# # Write down the names of all the candidates.
# # Add a vote count for each candidate.
# # Get the total votes for each candidate.
# # Get the total votes cast for the election. | [
"michelle.miao@audaciousfutures.co"
] | michelle.miao@audaciousfutures.co |
b65be87cc338e3dd2e208d1a0d95fd3a4d16b418 | 61ba2d4886dfafa8fc3349b203f7e677006da0be | /sp12.py | 742b85c3a4819a5830a91dfc715d1b90e70396fa | [] | no_license | Saumay85/erc2017 | 2dcca219ffc8961bbee4843139d10a25303223b5 | 812c39ee0c36eb9de321a53a158761ea434039d1 | refs/heads/master | 2020-06-11T09:01:40.164805 | 2017-01-11T20:28:26 | 2017-01-11T20:28:26 | 75,704,673 | 0 | 1 | null | 2016-12-09T18:48:59 | 2016-12-06T07:08:21 | Python | UTF-8 | Python | false | false | 106,724 | py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'sp10.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
import PySide
import datetime
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Main_Window(QtGui.QDialog, QtGui.QMainWindow):
def setupUi(self, Main_Window):
Main_Window.setObjectName(_fromUtf8("Main_Window"))
Main_Window.resize(703, 510)
Main_Window.move(380,100)
"""global silver # seat count of each class per booking
global gold
global plt
silver = 0
gold = 0
plt = 0"""
self.silver=0
self.gold = 0
self.plt = 0
#self.hour = 13
self.now = datetime.datetime.now()
self.centralwidget = QtGui.QWidget(Main_Window)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.TabWidget = QtGui.QTabWidget(self.centralwidget)
self.TabWidget.setGeometry(QtCore.QRect(0, 0, 711, 481))
self.TabWidget.setStyleSheet(_fromUtf8(""))
self.TabWidget.setObjectName(_fromUtf8("TabWidget"))
self.Home = QtGui.QWidget()
self.Home.setObjectName(_fromUtf8("Home"))
self.Label_background_0 = QtGui.QLabel(self.Home)
self.Label_background_0.setGeometry(QtCore.QRect(0, -10, 701, 901))
self.Label_background_0.setText(_fromUtf8(""))
self.Label_background_0.setPixmap(QtGui.QPixmap(_fromUtf8("Home2.png")))
self.Label_background_0.setObjectName(_fromUtf8("Label_background_0"))
self.Cancel_0 = QtGui.QPushButton(self.Home)
self.Cancel_0.setGeometry(QtCore.QRect(590, 396, 99, 31))
self.Cancel_0.setStyleSheet(_fromUtf8("QPushButton\n"
"{\n"
"background-color: #555555;\n"
" color: white;\n"
"border-radius:4px;\n"
"}\n"
"\n"
"QPushButton:hover\n"
"{\n"
"font-size:15px;\n"
"}\n"
""))
self.Cancel_0.setDefault(True)
self.Cancel_0.setObjectName(_fromUtf8("Cancel_0"))
self.Label2_0 = QtGui.QLabel(self.Home)
self.Label2_0.setGeometry(QtCore.QRect(370, 190, 291, 51))
self.Label2_0.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"font-family:Calibri;\n"
"}"))
self.Label2_0.setObjectName(_fromUtf8("Label2_0"))
self.radio1_0 = QtGui.QRadioButton(self.Home)
self.radio1_0.setGeometry(QtCore.QRect(380, 250, 181, 41))
self.radio1_0.setStyleSheet(_fromUtf8("QRadioButton\n"
"{\n"
"font-size:25px;\n"
"}\n"
""))
self.radio1_0.setObjectName(_fromUtf8("radio1_0"))
self.OK_0 = QtGui.QPushButton(self.Home)
self.OK_0.setGeometry(QtCore.QRect(490, 396, 99, 31))
self.OK_0.setStyleSheet(_fromUtf8("QPushButton\n"
"{ background-color: white;\n"
" color: black;\n"
" border-radius:4px;\n"
"border: 2px solid #e7e7e7;\n"
"}\n"
"QPushButton:hover\n"
"{\n"
"background-color: #e7e7e7;\n"
"box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);\n"
"font-size:15px;\n"
"}"))
self.OK_0.setObjectName(_fromUtf8("OK_0"))
self.Label1_0 = QtGui.QLabel(self.Home)
self.Label1_0.setGeometry(QtCore.QRect(60, 310, 300, 51))
self.Label1_0.setStyleSheet(_fromUtf8("QLineEdit:hover\n"
"{\n"
"font-size:40px;\n"
"}"))
self.Label1_0.setObjectName(_fromUtf8("Label1_0"))
self.setCurrentMovie()
self.radio2_0 = QtGui.QRadioButton(self.Home)
self.radio2_0.setGeometry(QtCore.QRect(380, 280, 281, 61))
self.radio2_0.setStyleSheet(_fromUtf8("QRadioButton\n"
"{\n"
"font-size:25px;\n"
"}\n"
""))
self.radio2_0.setObjectName(_fromUtf8("radio2_0"))
self.line_5 = QtGui.QFrame(self.Home)
self.line_5.setGeometry(QtCore.QRect(10, 300, 331, 16))
self.line_5.setFrameShadow(QtGui.QFrame.Plain)
self.line_5.setLineWidth(4)
self.line_5.setFrameShape(QtGui.QFrame.HLine)
self.line_5.setObjectName(_fromUtf8("line_5"))
self.line_6 = QtGui.QFrame(self.Home)
self.line_6.setGeometry(QtCore.QRect(10, 360, 331, 16))
self.line_6.setStyleSheet(_fromUtf8("QFrame HLine\n"
"{\n"
"color:black;\n"
"}"))
self.line_6.setFrameShadow(QtGui.QFrame.Plain)
self.line_6.setLineWidth(4)
self.line_6.setFrameShape(QtGui.QFrame.HLine)
self.line_6.setObjectName(_fromUtf8("line_6"))
self.TabWidget.addTab(self.Home, _fromUtf8(""))
self.tab_2 = QtGui.QWidget()
self.tab_2.setObjectName(_fromUtf8("tab_2"))
self.Label_background_1 = QtGui.QLabel(self.tab_2)
self.Label_background_1.setGeometry(QtCore.QRect(0, 0, 711, 451))
self.Label_background_1.setStyleSheet(_fromUtf8(""))
self.Label_background_1.setText(_fromUtf8(""))
self.Label_background_1.setPixmap(QtGui.QPixmap(_fromUtf8("theatre_blur3.jpeg")))
self.Label_background_1.setObjectName(_fromUtf8("Label_background_1"))
self.radio1_1 = QtGui.QRadioButton(self.tab_2)
self.radio1_1.setGeometry(QtCore.QRect(170, 110, 351, 21))
self.radio1_1.setStyleSheet(_fromUtf8("QRadioButton\n"
"{\n"
"font-size:18px;\n"
"}"))
self.radio1_1.setObjectName(_fromUtf8("radio1_1"))
self.radio2_1 = QtGui.QRadioButton(self.tab_2)
self.radio2_1.setGeometry(QtCore.QRect(170, 150, 351, 21))
self.radio2_1.setStyleSheet(_fromUtf8("QRadioButton\n"
"{\n"
"font-size:18px;\n"
"}"))
self.radio2_1.setObjectName(_fromUtf8("radio2_1"))
self.radio4_1 = QtGui.QRadioButton(self.tab_2)
self.radio4_1.setGeometry(QtCore.QRect(170, 230, 351, 21))
self.radio4_1.setStyleSheet(_fromUtf8("QRadioButton\n"
"{\n"
"font-size:18px;\n"
"}"))
self.radio4_1.setObjectName(_fromUtf8("radio4_1"))
self.Label2_1 = QtGui.QLabel(self.tab_2)
self.Label2_1.setGeometry(QtCore.QRect(450, 70, 41, 21))
self.Label2_1.setObjectName(_fromUtf8("Label2_1"))
self.Label4_1 = QtGui.QLabel(self.tab_2)
self.Label4_1.setGeometry(QtCore.QRect(20, 340, 461, 71))
self.Label4_1.setObjectName(_fromUtf8("Label4_1"))
self.Label3_1 = QtGui.QLabel(self.tab_2)
self.Label3_1.setGeometry(QtCore.QRect(260, 270, 261, 51))
self.Label3_1.setObjectName(_fromUtf8("Label3_1"))
self.line_4 = QtGui.QFrame(self.tab_2)
self.line_4.setGeometry(QtCore.QRect(400, 60, 16, 201))
self.line_4.setFrameShape(QtGui.QFrame.VLine)
self.line_4.setFrameShadow(QtGui.QFrame.Sunken)
self.line_4.setObjectName(_fromUtf8("line_4"))
self.Label1_1 = QtGui.QLabel(self.tab_2)
self.Label1_1.setGeometry(QtCore.QRect(260, 70, 59, 21))
self.Label1_1.setObjectName(_fromUtf8("Label1_1"))
self.radio3_1 = QtGui.QRadioButton(self.tab_2)
self.radio3_1.setGeometry(QtCore.QRect(170, 190, 351, 21))
self.radio3_1.setStyleSheet(_fromUtf8("QRadioButton\n"
"{\n"
"font-size:18px;\n"
"}"))
self.radio3_1.setObjectName(_fromUtf8("radio3_1"))
self.OK_1 = QtGui.QPushButton(self.tab_2)
self.OK_1.setGeometry(QtCore.QRect(490, 400, 99, 31))
self.OK_1.setStyleSheet(_fromUtf8("QPushButton\n"
"{ background-color: white;\n"
" color: black;\n"
" border-radius:4px;\n"
"border: 2px solid #e7e7e7;\n"
"}\n"
"QPushButton:hover\n"
"{\n"
"background-color: #e7e7e7;\n"
"box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);\n"
"font-size:15px;\n"
"}"))
self.OK_1.setObjectName(_fromUtf8("OK_1"))
self.Cancel_1 = QtGui.QPushButton(self.tab_2)
self.Cancel_1.setGeometry(QtCore.QRect(590, 400, 99, 31))
self.Cancel_1.setStyleSheet(_fromUtf8("QPushButton\n"
"{\n"
"background-color: #555555;\n"
" color: white;\n"
"border-radius:4px;\n"
"}\n"
"\n"
"QPushButton:hover\n"
"{\n"
"font-size:15px;\n"
"}\n"
""))
self.Cancel_1.setDefault(True)
self.Cancel_1.setObjectName(_fromUtf8("Cancel_1"))
self.TabWidget.addTab(self.tab_2, _fromUtf8(""))
self.tab_7 = QtGui.QWidget()
self.tab_7.setObjectName(_fromUtf8("tab_7"))
self.Label_background_2 = QtGui.QLabel(self.tab_7)
self.Label_background_2.setGeometry(QtCore.QRect(0, 0, 701, 451))
self.Label_background_2.setText(_fromUtf8(""))
self.Label_background_2.setPixmap(QtGui.QPixmap(_fromUtf8("seats_blur.jpeg")))
self.Label_background_2.setObjectName(_fromUtf8("Label_background_2"))
self.gold06 = QtGui.QPushButton(self.tab_7)
self.gold06.setGeometry(QtCore.QRect(250, 150, 41, 41))
self.gold06.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold06.setObjectName(_fromUtf8("gold06"))
self.silver20 = QtGui.QPushButton(self.tab_7)
self.silver20.setGeometry(QtCore.QRect(170, 230, 41, 41))
self.silver20.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver20.setObjectName(_fromUtf8("silver20"))
self.gold16 = QtGui.QPushButton(self.tab_7)
self.gold16.setGeometry(QtCore.QRect(250, 230, 41, 41))
self.gold16.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold16.setObjectName(_fromUtf8("gold16"))
self.plt15 = QtGui.QPushButton(self.tab_7)
self.plt15.setGeometry(QtCore.QRect(650, 190, 41, 41))
self.plt15.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt15.setObjectName(_fromUtf8("plt15"))
self.plt14 = QtGui.QPushButton(self.tab_7)
self.plt14.setGeometry(QtCore.QRect(610, 190, 41, 41))
self.plt14.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt14.setObjectName(_fromUtf8("plt14"))
self.gold07 = QtGui.QPushButton(self.tab_7)
self.gold07.setGeometry(QtCore.QRect(290, 150, 41, 41))
self.gold07.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold07.setObjectName(_fromUtf8("gold07"))
self.silver06 = QtGui.QPushButton(self.tab_7)
self.silver06.setGeometry(QtCore.QRect(10, 150, 41, 41))
self.silver06.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver06.setObjectName(_fromUtf8("silver06"))
self.gold18 = QtGui.QPushButton(self.tab_7)
self.gold18.setGeometry(QtCore.QRect(330, 230, 41, 41))
self.gold18.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold18.setObjectName(_fromUtf8("gold18"))
self.plt06 = QtGui.QPushButton(self.tab_7)
self.plt06.setGeometry(QtCore.QRect(490, 150, 41, 41))
self.plt06.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt06.setObjectName(_fromUtf8("plt06"))
self.gold21 = QtGui.QPushButton(self.tab_7)
self.gold21.setGeometry(QtCore.QRect(250, 270, 41, 41))
self.gold21.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold21.setObjectName(_fromUtf8("gold21"))
self.gold20 = QtGui.QPushButton(self.tab_7)
self.gold20.setGeometry(QtCore.QRect(410, 230, 41, 41))
self.gold20.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold20.setObjectName(_fromUtf8("gold20"))
self.plt05 = QtGui.QPushButton(self.tab_7)
self.plt05.setGeometry(QtCore.QRect(650, 110, 41, 41))
self.plt05.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt05.setObjectName(_fromUtf8("plt05"))
self.gold13 = QtGui.QPushButton(self.tab_7)
self.gold13.setGeometry(QtCore.QRect(330, 190, 41, 41))
self.gold13.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold13.setObjectName(_fromUtf8("gold13"))
self.gold02 = QtGui.QPushButton(self.tab_7)
self.gold02.setGeometry(QtCore.QRect(290, 110, 41, 41))
self.gold02.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold02.setObjectName(_fromUtf8("gold02"))
self.silver03 = QtGui.QPushButton(self.tab_7)
self.silver03.setGeometry(QtCore.QRect(90, 110, 41, 41))
self.silver03.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver03.setObjectName(_fromUtf8("silver03"))
self.plt08 = QtGui.QPushButton(self.tab_7)
self.plt08.setGeometry(QtCore.QRect(570, 150, 41, 41))
self.plt08.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt08.setObjectName(_fromUtf8("plt08"))
self.plt22 = QtGui.QPushButton(self.tab_7)
self.plt22.setGeometry(QtCore.QRect(530, 270, 41, 41))
self.plt22.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt22.setObjectName(_fromUtf8("plt22"))
self.spinBox3_2 = QtGui.QSpinBox(self.tab_7)
self.spinBox3_2.setGeometry(QtCore.QRect(570, 40, 61, 27))
self.spinBox3_2.setMaximum(25)
self.spinBox3_2.setObjectName(_fromUtf8("spinBox3_2"))
self.gold10 = QtGui.QPushButton(self.tab_7)
self.gold10.setGeometry(QtCore.QRect(410, 150, 41, 41))
self.gold10.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold10.setObjectName(_fromUtf8("gold10"))
self.label1_2 = QtGui.QLabel(self.tab_7)
self.label1_2.setGeometry(QtCore.QRect(20, 340, 501, 91))
self.label1_2.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label1_2.setObjectName(_fromUtf8("label1_2"))
self.plt12 = QtGui.QPushButton(self.tab_7)
self.plt12.setGeometry(QtCore.QRect(530, 190, 41, 41))
self.plt12.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt12.setObjectName(_fromUtf8("plt12"))
self.silver16 = QtGui.QPushButton(self.tab_7)
self.silver16.setGeometry(QtCore.QRect(10, 230, 41, 41))
self.silver16.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver16.setObjectName(_fromUtf8("silver16"))
self.silver13 = QtGui.QPushButton(self.tab_7)
self.silver13.setGeometry(QtCore.QRect(90, 190, 41, 41))
self.silver13.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver13.setObjectName(_fromUtf8("silver13"))
self.gold25 = QtGui.QPushButton(self.tab_7)
self.gold25.setGeometry(QtCore.QRect(410, 270, 41, 41))
self.gold25.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold25.setObjectName(_fromUtf8("gold25"))
self.gold11 = QtGui.QPushButton(self.tab_7)
self.gold11.setGeometry(QtCore.QRect(250, 190, 41, 41))
self.gold11.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold11.setObjectName(_fromUtf8("gold11"))
self.plt17 = QtGui.QPushButton(self.tab_7)
self.plt17.setGeometry(QtCore.QRect(530, 230, 41, 41))
self.plt17.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt17.setObjectName(_fromUtf8("plt17"))
self.plt21 = QtGui.QPushButton(self.tab_7)
self.plt21.setGeometry(QtCore.QRect(490, 270, 41, 41))
self.plt21.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt21.setObjectName(_fromUtf8("plt21"))
self.gold17 = QtGui.QPushButton(self.tab_7)
self.gold17.setGeometry(QtCore.QRect(290, 230, 41, 41))
self.gold17.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold17.setObjectName(_fromUtf8("gold17"))
self.gold22 = QtGui.QPushButton(self.tab_7)
self.gold22.setGeometry(QtCore.QRect(290, 270, 41, 41))
self.gold22.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold22.setObjectName(_fromUtf8("gold22"))
self.plt25 = QtGui.QPushButton(self.tab_7)
self.plt25.setGeometry(QtCore.QRect(650, 270, 41, 41))
self.plt25.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt25.setObjectName(_fromUtf8("plt25"))
self.gold19 = QtGui.QPushButton(self.tab_7)
self.gold19.setGeometry(QtCore.QRect(370, 230, 41, 41))
self.gold19.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold19.setObjectName(_fromUtf8("gold19"))
self.silver05 = QtGui.QPushButton(self.tab_7)
self.silver05.setGeometry(QtCore.QRect(170, 110, 41, 41))
self.silver05.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver05.setObjectName(_fromUtf8("silver05"))
self.gold15 = QtGui.QPushButton(self.tab_7)
self.gold15.setGeometry(QtCore.QRect(410, 190, 41, 41))
self.gold15.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold15.setObjectName(_fromUtf8("gold15"))
self.Cancel_2 = QtGui.QPushButton(self.tab_7)
self.Cancel_2.setGeometry(QtCore.QRect(590, 400, 99, 31))
self.Cancel_2.setStyleSheet(_fromUtf8("QPushButton\n"
"{\n"
"background-color: #555555;\n"
" color: white;\n"
"border-radius:4px;\n"
"}\n"
"\n"
"QPushButton:hover\n"
"{\n"
"font-size:15px;\n"
"}\n"
""))
self.Cancel_2.setDefault(True)
self.Cancel_2.setObjectName(_fromUtf8("Cancel_2"))
self.gold09 = QtGui.QPushButton(self.tab_7)
self.gold09.setGeometry(QtCore.QRect(370, 150, 41, 41))
self.gold09.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold09.setObjectName(_fromUtf8("gold09"))
self.silver12 = QtGui.QPushButton(self.tab_7)
self.silver12.setGeometry(QtCore.QRect(50, 190, 41, 41))
self.silver12.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver12.setObjectName(_fromUtf8("silver12"))
self.gold03 = QtGui.QPushButton(self.tab_7)
self.gold03.setGeometry(QtCore.QRect(330, 110, 41, 41))
self.gold03.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold03.setObjectName(_fromUtf8("gold03"))
self.plt01 = QtGui.QPushButton(self.tab_7)
self.plt01.setGeometry(QtCore.QRect(490, 110, 41, 41))
self.plt01.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt01.setObjectName(_fromUtf8("plt01"))
self.gold24 = QtGui.QPushButton(self.tab_7)
self.gold24.setGeometry(QtCore.QRect(370, 270, 41, 41))
self.gold24.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold24.setObjectName(_fromUtf8("gold24"))
self.gold23 = QtGui.QPushButton(self.tab_7)
self.gold23.setGeometry(QtCore.QRect(330, 270, 41, 41))
self.gold23.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold23.setObjectName(_fromUtf8("gold23"))
self.gold05 = QtGui.QPushButton(self.tab_7)
self.gold05.setGeometry(QtCore.QRect(410, 110, 41, 41))
self.gold05.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold05.setObjectName(_fromUtf8("gold05"))
self.silver01 = QtGui.QPushButton(self.tab_7)
self.silver01.setGeometry(QtCore.QRect(10, 110, 41, 41))
self.silver01.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver01.setObjectName(_fromUtf8("silver01"))
self.silver10 = QtGui.QPushButton(self.tab_7)
self.silver10.setGeometry(QtCore.QRect(170, 150, 41, 41))
self.silver10.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver10.setObjectName(_fromUtf8("silver10"))
self.line_2 = QtGui.QFrame(self.tab_7)
self.line_2.setGeometry(QtCore.QRect(220, 0, 20, 311))
self.line_2.setFrameShape(QtGui.QFrame.VLine)
self.line_2.setFrameShadow(QtGui.QFrame.Sunken)
self.line_2.setObjectName(_fromUtf8("line_2"))
self.label2_2 = QtGui.QLabel(self.tab_7)
self.label2_2.setGeometry(QtCore.QRect(10, 10, 101, 91))
self.label2_2.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label2_2.setObjectName(_fromUtf8("label2_2"))
self.plt20 = QtGui.QPushButton(self.tab_7)
self.plt20.setGeometry(QtCore.QRect(650, 230, 41, 41))
self.plt20.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt20.setObjectName(_fromUtf8("plt20"))
self.silver15 = QtGui.QPushButton(self.tab_7)
self.silver15.setGeometry(QtCore.QRect(170, 190, 41, 41))
self.silver15.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver15.setObjectName(_fromUtf8("silver15"))
self.silver22 = QtGui.QPushButton(self.tab_7)
self.silver22.setGeometry(QtCore.QRect(50, 270, 41, 41))
self.silver22.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver22.setObjectName(_fromUtf8("silver22"))
self.gold12 = QtGui.QPushButton(self.tab_7)
self.gold12.setGeometry(QtCore.QRect(290, 190, 41, 41))
self.gold12.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold12.setObjectName(_fromUtf8("gold12"))
self.silver09 = QtGui.QPushButton(self.tab_7)
self.silver09.setGeometry(QtCore.QRect(130, 150, 41, 41))
self.silver09.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver09.setObjectName(_fromUtf8("silver09"))
self.silver11 = QtGui.QPushButton(self.tab_7)
self.silver11.setGeometry(QtCore.QRect(10, 190, 41, 41))
self.silver11.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver11.setObjectName(_fromUtf8("silver11"))
self.plt02 = QtGui.QPushButton(self.tab_7)
self.plt02.setGeometry(QtCore.QRect(530, 110, 41, 41))
self.plt02.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt02.setObjectName(_fromUtf8("plt02"))
self.gold01 = QtGui.QPushButton(self.tab_7)
self.gold01.setGeometry(QtCore.QRect(250, 110, 41, 41))
self.gold01.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold01.setObjectName(_fromUtf8("gold01"))
self.plt03 = QtGui.QPushButton(self.tab_7)
self.plt03.setGeometry(QtCore.QRect(570, 110, 41, 41))
self.plt03.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt03.setObjectName(_fromUtf8("plt03"))
self.silver21 = QtGui.QPushButton(self.tab_7)
self.silver21.setGeometry(QtCore.QRect(10, 270, 41, 41))
self.silver21.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver21.setObjectName(_fromUtf8("silver21"))
self.silver18 = QtGui.QPushButton(self.tab_7)
self.silver18.setGeometry(QtCore.QRect(90, 230, 41, 41))
self.silver18.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver18.setObjectName(_fromUtf8("silver18"))
self.silver25 = QtGui.QPushButton(self.tab_7)
self.silver25.setGeometry(QtCore.QRect(170, 270, 41, 41))
self.silver25.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver25.setObjectName(_fromUtf8("silver25"))
self.silver14 = QtGui.QPushButton(self.tab_7)
self.silver14.setGeometry(QtCore.QRect(130, 190, 41, 41))
self.silver14.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver14.setObjectName(_fromUtf8("silver14"))
self.spinBox2_2 = QtGui.QSpinBox(self.tab_7)
self.spinBox2_2.setGeometry(QtCore.QRect(330, 40, 61, 27))
self.spinBox2_2.setMaximum(25)
self.spinBox2_2.setObjectName(_fromUtf8("spinBox2_2"))
self.gold04 = QtGui.QPushButton(self.tab_7)
self.gold04.setGeometry(QtCore.QRect(370, 110, 41, 41))
self.gold04.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold04.setObjectName(_fromUtf8("gold04"))
self.spinBox1_2 = QtGui.QSpinBox(self.tab_7)
self.spinBox1_2.setGeometry(QtCore.QRect(110, 40, 61, 27))
self.spinBox1_2.setMaximum(25)
self.spinBox1_2.setObjectName(_fromUtf8("spinBox1_2"))
self.plt10 = QtGui.QPushButton(self.tab_7)
self.plt10.setGeometry(QtCore.QRect(650, 150, 41, 41))
self.plt10.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt10.setObjectName(_fromUtf8("plt10"))
self.OK_2 = QtGui.QPushButton(self.tab_7)
self.OK_2.setGeometry(QtCore.QRect(490, 400, 99, 31))
self.OK_2.setStyleSheet(_fromUtf8("QPushButton\n"
"{ background-color: white;\n"
" color: black;\n"
" border-radius:4px;\n"
"border: 2px solid #e7e7e7;\n"
"}\n"
"QPushButton:hover\n"
"{\n"
"background-color: #e7e7e7;\n"
"box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);\n"
"font-size:15px;\n"
"}"))
self.OK_2.setObjectName(_fromUtf8("OK_2"))
self.plt09 = QtGui.QPushButton(self.tab_7)
self.plt09.setGeometry(QtCore.QRect(610, 150, 41, 41))
self.plt09.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt09.setObjectName(_fromUtf8("plt09"))
self.silver02 = QtGui.QPushButton(self.tab_7)
self.silver02.setGeometry(QtCore.QRect(50, 110, 41, 41))
self.silver02.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver02.setObjectName(_fromUtf8("silver02"))
self.silver08 = QtGui.QPushButton(self.tab_7)
self.silver08.setGeometry(QtCore.QRect(90, 150, 41, 41))
self.silver08.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver08.setObjectName(_fromUtf8("silver08"))
self.gold14 = QtGui.QPushButton(self.tab_7)
self.gold14.setGeometry(QtCore.QRect(370, 190, 41, 41))
self.gold14.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold14.setObjectName(_fromUtf8("gold14"))
self.silver17 = QtGui.QPushButton(self.tab_7)
self.silver17.setGeometry(QtCore.QRect(50, 230, 41, 41))
self.silver17.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver17.setObjectName(_fromUtf8("silver17"))
self.silver07 = QtGui.QPushButton(self.tab_7)
self.silver07.setGeometry(QtCore.QRect(50, 150, 41, 41))
self.silver07.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver07.setObjectName(_fromUtf8("silver07"))
self.silver23 = QtGui.QPushButton(self.tab_7)
self.silver23.setGeometry(QtCore.QRect(90, 270, 41, 41))
self.silver23.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver23.setObjectName(_fromUtf8("silver23"))
self.plt18 = QtGui.QPushButton(self.tab_7)
self.plt18.setGeometry(QtCore.QRect(570, 230, 41, 41))
self.plt18.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt18.setObjectName(_fromUtf8("plt18"))
self.plt24 = QtGui.QPushButton(self.tab_7)
self.plt24.setGeometry(QtCore.QRect(610, 270, 41, 41))
self.plt24.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt24.setObjectName(_fromUtf8("plt24"))
self.plt16 = QtGui.QPushButton(self.tab_7)
self.plt16.setGeometry(QtCore.QRect(490, 230, 41, 41))
self.plt16.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt16.setObjectName(_fromUtf8("plt16"))
self.silver19 = QtGui.QPushButton(self.tab_7)
self.silver19.setGeometry(QtCore.QRect(130, 230, 41, 41))
self.silver19.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}\n"
""))
self.silver19.setObjectName(_fromUtf8("silver19"))
self.plt13 = QtGui.QPushButton(self.tab_7)
self.plt13.setGeometry(QtCore.QRect(570, 190, 41, 41))
self.plt13.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt13.setObjectName(_fromUtf8("plt13"))
self.line_3 = QtGui.QFrame(self.tab_7)
self.line_3.setGeometry(QtCore.QRect(460, 0, 20, 311))
self.line_3.setFrameShape(QtGui.QFrame.VLine)
self.line_3.setFrameShadow(QtGui.QFrame.Sunken)
self.line_3.setObjectName(_fromUtf8("line_3"))
self.plt23 = QtGui.QPushButton(self.tab_7)
self.plt23.setGeometry(QtCore.QRect(570, 270, 41, 41))
self.plt23.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt23.setObjectName(_fromUtf8("plt23"))
self.plt07 = QtGui.QPushButton(self.tab_7)
self.plt07.setGeometry(QtCore.QRect(530, 150, 41, 41))
self.plt07.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt07.setObjectName(_fromUtf8("plt07"))
self.silver24 = QtGui.QPushButton(self.tab_7)
self.silver24.setGeometry(QtCore.QRect(130, 270, 41, 41))
self.silver24.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver24.setObjectName(_fromUtf8("silver24"))
self.silver04 = QtGui.QPushButton(self.tab_7)
self.silver04.setGeometry(QtCore.QRect(130, 110, 41, 41))
self.silver04.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.silver04.setObjectName(_fromUtf8("silver04"))
self.gold08 = QtGui.QPushButton(self.tab_7)
self.gold08.setGeometry(QtCore.QRect(330, 150, 41, 41))
self.gold08.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.gold08.setObjectName(_fromUtf8("gold08"))
self.plt19 = QtGui.QPushButton(self.tab_7)
self.plt19.setGeometry(QtCore.QRect(610, 230, 41, 41))
self.plt19.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt19.setObjectName(_fromUtf8("plt19"))
self.plt04 = QtGui.QPushButton(self.tab_7)
self.plt04.setGeometry(QtCore.QRect(610, 110, 41, 41))
self.plt04.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt04.setObjectName(_fromUtf8("plt04"))
self.plt11 = QtGui.QPushButton(self.tab_7)
self.plt11.setGeometry(QtCore.QRect(490, 190, 41, 41))
self.plt11.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.plt11.setObjectName(_fromUtf8("plt11"))
self.Button_silver_2 = QtGui.QPushButton(self.tab_7)
self.Button_silver_2.setGeometry(QtCore.QRect(70, 80, 89, 27))
self.Button_silver_2.setStyleSheet(_fromUtf8("QPushButton\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"border-radius:3px;\n"
"color:black;\n"
"}"))
self.Button_silver_2.setObjectName(_fromUtf8("Button_silver_2"))
self.Button_gold_2 = QtGui.QPushButton(self.tab_7)
self.Button_gold_2.setGeometry(QtCore.QRect(310, 80, 89, 27))
self.Button_gold_2.setStyleSheet(_fromUtf8("QPushButton\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"border-radius:3px;\n"
"color:black;\n"
"}"))
self.Button_gold_2.setObjectName(_fromUtf8("Button_gold_2"))
self.Button_platinum_2 = QtGui.QPushButton(self.tab_7)
self.Button_platinum_2.setGeometry(QtCore.QRect(550, 80, 89, 27))
self.Button_platinum_2.setStyleSheet(_fromUtf8("QPushButton\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"border-radius:3px;\n"
"color:black;\n"
"}"))
self.Button_platinum_2.setObjectName(_fromUtf8("Button_platinum_2"))
self.TabWidget.addTab(self.tab_7, _fromUtf8(""))
self.tab_8 = QtGui.QWidget()
self.tab_8.setObjectName(_fromUtf8("tab_8"))
self.Label_background_3 = QtGui.QLabel(self.tab_8)
self.Label_background_3.setGeometry(QtCore.QRect(0, -10, 701, 471))
self.Label_background_3.setText(_fromUtf8(""))
self.Label_background_3.setPixmap(QtGui.QPixmap(_fromUtf8("popcorn_blur.jpeg")))
self.Label_background_3.setObjectName(_fromUtf8("Label_background_3"))
self.label4_3 = QtGui.QLabel(self.tab_8)
self.label4_3.setGeometry(QtCore.QRect(40, 260, 150, 21))
self.label4_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label4_3.setObjectName(_fromUtf8("label4_3"))
self.lineEdit2_3 = QtGui.QLineEdit(self.tab_8)
self.lineEdit2_3.setGeometry(QtCore.QRect(40, 190, 211, 41))
self.lineEdit2_3.setObjectName(_fromUtf8("lineEdit2_3"))
self.line = QtGui.QFrame(self.tab_8)
self.line.setGeometry(QtCore.QRect(340, 0, 20, 451))
self.line.setFrameShape(QtGui.QFrame.VLine)
self.line.setFrameShadow(QtGui.QFrame.Sunken)
self.line.setObjectName(_fromUtf8("line"))
self.lineEdit3_3 = QtGui.QLineEdit(self.tab_8)
self.lineEdit3_3.setGeometry(QtCore.QRect(40, 280, 211, 41))
self.lineEdit3_3.setObjectName(_fromUtf8("lineEdit3_3"))
self.Cancel_3 = QtGui.QPushButton(self.tab_8)
self.Cancel_3.setGeometry(QtCore.QRect(460, 360, 161, 41))
self.Cancel_3.setStyleSheet(_fromUtf8("QPushButton\n"
"{\n"
"background-color: #555555;\n"
" color: white;\n"
"border-radius:4px;\n"
"font-size:15px;\n"
"}\n"
"\n"
"QPushButton:hover\n"
"{\n"
"font-size:18px;\n"
"background-color:white;\n"
"color:black;\n"
"}\n"
""))
self.Cancel_3.setDefault(True)
self.Cancel_3.setObjectName(_fromUtf8("Cancel_3"))
self.generateTicket_3 = QtGui.QPushButton(self.tab_8)
self.generateTicket_3.setGeometry(QtCore.QRect(70, 360, 161, 41))
self.generateTicket_3.setStyleSheet(_fromUtf8("QPushButton\n"
"{\n"
" font-size:16px;\n"
"color:black;\n"
"}\n"
"QPushButton:hover\n"
"{\n"
"color:white;\n"
"background-color:#555555;\n"
"font-size:19px;\n"
"}"))
self.generateTicket_3.setObjectName(_fromUtf8("generateTicket_3"))
self.generateTicket_3.clicked.connect(self.handleTicket)
self.label3_3 = QtGui.QLabel(self.tab_8)
self.label3_3.setGeometry(QtCore.QRect(40, 170, 150, 21))
self.label3_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label3_3.setObjectName(_fromUtf8("label3_3"))
self.label2_3 = QtGui.QLabel(self.tab_8)
self.label2_3.setGeometry(QtCore.QRect(40, 80, 61, 21))
self.label2_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label2_3.setObjectName(_fromUtf8("label2_3"))
self.label1_3 = QtGui.QLabel(self.tab_8)
self.label1_3.setGeometry(QtCore.QRect(70, 30, 281, 31))
self.label1_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
" font-variant: small-caps;\n"
" color:black;\n"
"}"))
self.label1_3.setObjectName(_fromUtf8("label1_3"))
self.lineEdit1_3 = QtGui.QLineEdit(self.tab_8)
self.lineEdit1_3.setGeometry(QtCore.QRect(40, 100, 211, 41))
self.lineEdit1_3.setObjectName(_fromUtf8("lineEdit1_3"))
self.label_cost_3 = QtGui.QLabel(self.tab_8)
self.label_cost_3.setGeometry(QtCore.QRect(360, 90, 321, 241))
self.label_cost_3.setText(_fromUtf8(""))
self.label_cost_3.setPixmap(QtGui.QPixmap(_fromUtf8("bill_resized.jpeg")))
self.label_cost_3.setObjectName(_fromUtf8("label_cost_3"))
self.LABEL15_3 = QtGui.QLabel(self.tab_8)
self.LABEL15_3.setGeometry(QtCore.QRect(610, 230, 59, 14))
self.LABEL15_3.setObjectName(_fromUtf8("LABEL15_3"))
self.LABEL15_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label5_3 = QtGui.QLabel(self.tab_8)
self.label5_3.setGeometry(QtCore.QRect(500, 90, 171, 31))
self.label5_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"font: 12pt \"Noto Sans Mono CJK SC\";\n"
"color:black;\n"
"}"))
self.label5_3.setObjectName(_fromUtf8("label5_3"))
self.label7_3 = QtGui.QLabel(self.tab_8)
self.label7_3.setGeometry(QtCore.QRect(400, 170, 140, 16))
self.label7_3.setObjectName(_fromUtf8("label7_3"))
self.label7_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label9_3 = QtGui.QLabel(self.tab_8)
self.label9_3.setGeometry(QtCore.QRect(400, 230, 160, 16))
self.label9_3.setObjectName(_fromUtf8("label9_3"))
self.label9_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.LABEL12_3 = QtGui.QLabel(self.tab_8)
self.LABEL12_3.setGeometry(QtCore.QRect(570, 130, 59, 16))
self.LABEL12_3.setObjectName(_fromUtf8("LABEL12_3"))
self.LABEL12_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label10_3 = QtGui.QLabel(self.tab_8)
self.label10_3.setGeometry(QtCore.QRect(420, 260, 59, 31))
self.label10_3.setObjectName(_fromUtf8("label10_3"))
self.label10_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.LABEL14_3 = QtGui.QLabel(self.tab_8)
self.LABEL14_3.setGeometry(QtCore.QRect(610, 200, 59, 14))
self.LABEL14_3.setObjectName(_fromUtf8("LABEL14_3"))
self.LABEL14_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label11_3 = QtGui.QLabel(self.tab_8)
self.label11_3.setGeometry(QtCore.QRect(420, 310, 321, 16))
self.label11_3.setObjectName(_fromUtf8("label11_3"))
self.label11_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label8_3 = QtGui.QLabel(self.tab_8)
self.label8_3.setGeometry(QtCore.QRect(400, 200, 120, 16))
self.label8_3.setObjectName(_fromUtf8("label8_3"))
self.label8_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label6_3 = QtGui.QLabel(self.tab_8)
self.label6_3.setGeometry(QtCore.QRect(440, 130, 141, 16))
self.label6_3.setObjectName(_fromUtf8("label6_3"))
self.label6_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.LABEL13_3 = QtGui.QLabel(self.tab_8)
self.LABEL13_3.setGeometry(QtCore.QRect(560, 170, 121, 14))
self.LABEL13_3.setObjectName(_fromUtf8("LABEL13_3"))
self.LABEL13_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.LABEL16_3 = QtGui.QLabel(self.tab_8)
self.LABEL16_3.setGeometry(QtCore.QRect(610, 270, 59, 14))
self.LABEL16_3.setObjectName(_fromUtf8("LABEL16_3"))
self.LABEL16_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label_18 = QtGui.QLabel(self.tab_8)
self.label_18.setGeometry(QtCore.QRect(360, 250, 321, 16))
self.label_18.setObjectName(_fromUtf8("label_18"))
self.label_18.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label_27 = QtGui.QLabel(self.tab_8)
self.label_27.setGeometry(QtCore.QRect(360, 150, 321, 16))
self.label_27.setObjectName(_fromUtf8("label_27"))
self.TabWidget.addTab(self.tab_8, _fromUtf8(""))
self.Time = QtGui.QLabel(self.centralwidget)
self.Time.setGeometry(QtCore.QRect(640, 480, 61, 31))
self.Time.setObjectName(_fromUtf8("Time"))
self.Date = QtGui.QLabel(self.centralwidget)
self.Date.setGeometry(QtCore.QRect(10, 480, 120, 31))
self.Date.setObjectName(_fromUtf8("Date"))
self.Date_label = QtGui.QLabel(self.centralwidget)
self.Date_label.setGeometry(QtCore.QRect(125, 480, 61, 31))
self.Date_label.setObjectName(_fromUtf8("Date_label"))
self.Time_label = QtGui.QLabel(self.centralwidget)
self.Time_label.setGeometry(QtCore.QRect(590, 480, 61, 31))
self.Time_label.setObjectName(_fromUtf8("Time_label"))
Main_Window.setCentralWidget(self.centralwidget)
self.menuBar = QtGui.QMenuBar(Main_Window)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 703, 22))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
self.menuAbout = QtGui.QMenu(self.menuBar)
self.menuAbout.setObjectName(_fromUtf8("menuAbout"))
Main_Window.setMenuBar(self.menuBar)
self.actionFont_Designer = QtGui.QAction(Main_Window)
self.actionFont_Designer.setObjectName(_fromUtf8("actionFont_Designer"))
self.actionChange_Background_color = QtGui.QAction(Main_Window)
self.actionChange_Background_color.setObjectName(_fromUtf8("actionChange_Background_color"))
self.actionDevelopers = QtGui.QAction(Main_Window)
self.actionDevelopers.setObjectName(_fromUtf8("actionDevelopers"))
self.menuAbout.addAction(self.actionDevelopers)
self.menuBar.addAction(self.menuAbout.menuAction())
self.retranslateUi(Main_Window)
self.TabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(Main_Window)
#####################
self.Cost_gold_2 = QtGui.QLabel(self.tab_7)
self.Cost_gold_2.setGeometry(QtCore.QRect(80, 310, 71, 21))
self.Cost_gold_2.setText("Rs. 200")
self.Cost_gold_2.setStyleSheet("font-size:18px; color:white; font-weight:bold;")
self.Cost_silver_2 = QtGui.QLabel(self.tab_7)
self.Cost_silver_2.setGeometry(QtCore.QRect(320, 310, 71, 21))
self.Cost_silver_2.setText("Rs. 300")
self.Cost_silver_2.setStyleSheet("font-size:18px; color:white; font-weight:bold;")
self.Cost_plt_2 = QtGui.QLabel(self.tab_7)
self.Cost_plt_2.setGeometry(QtCore.QRect(560, 310, 71, 21))
self.Cost_plt_2.setText("Rs. 400")
self.Cost_plt_2.setStyleSheet("font-size:18px; color:white; font-weight:bold;")
self.Loop_3 = QtGui.QPushButton(self.tab_8)
self.Loop_3.setGeometry(QtCore.QRect(260, 400, 170, 50))
self.Loop_3.setStyleSheet(_fromUtf8("QPushButton\n"
"{\n"
"background-color: white;\n"
" color: black;\n"
"border-radius:4px;\n"
"font-size:15px;\n"
"font-weight:bold;\n"
"border: 4px solid #008CBA;\n"
"}\n"
"\n"
"QPushButton:hover\n"
"{\n"
"background-color:#008CBA;\n"
"color:white;\n"
"font-size:17px;\n"
"font-weight:bold;\n"
"}\n"
""))
self.Loop_3.setDefault(True)
self.Loop_3.setObjectName(_fromUtf8("Cancel_3"))
self.Loop_3.setText("Book another ticket")
self.Loop_3.clicked.connect(self.handleLoop)
# OK buttons
self.OK_0.clicked.connect(self.handleOK1)
self.OK_1.clicked.connect(self.handleOK2)
self.OK_2.clicked.connect(self.handleOK3)
# Cancel buttons
self.Cancel_0.clicked.connect(self.close_application)
self.Cancel_1.clicked.connect(self.close_application)
self.Cancel_2.clicked.connect(self.close_application)
self.Cancel_3.clicked.connect(self.close_application)
# Seat buttons
self.gold01.setCheckable(True)
self.gold01.toggle()
self.gold01_text = self.gold01.text()
self.gold01.clicked.connect(lambda: self.btnstate_gold(self.gold01, self.gold01_text))
self.gold02.setCheckable(True)
self.gold02.toggle()
self.gold02_text = self.gold02.text()
self.gold02.clicked.connect(lambda: self.btnstate_gold(self.gold02, self.gold02_text))
self.gold04.setCheckable(True)
self.gold04.toggle()
self.gold04_text = self.gold04.text()
self.gold04.clicked.connect(lambda: self.btnstate_gold(self.gold04, self.gold04_text))
self.gold03.setCheckable(True)
self.gold03.toggle()
self.gold03_text = self.gold03.text()
self.gold03.clicked.connect(lambda: self.btnstate_gold(self.gold03, self.gold03_text))
self.gold05.setCheckable(True)
self.gold05.toggle()
self.gold05_text = self.gold05.text()
self.gold05.clicked.connect(lambda: self.btnstate_gold(self.gold05, self.gold05_text))
self.gold06.setCheckable(True)
self.gold06.toggle()
self.gold06_text = self.gold06.text()
self.gold06.clicked.connect(lambda: self.btnstate_gold(self.gold06, self.gold06_text))
self.gold07.setCheckable(True)
self.gold07.toggle()
self.gold07_text = self.gold07.text()
self.gold07.clicked.connect(lambda: self.btnstate_gold(self.gold07, self.gold07_text))
self.gold08.setCheckable(True)
self.gold08.toggle()
self.gold08_text = self.gold08.text()
self.gold08.clicked.connect(lambda: self.btnstate_gold(self.gold08, self.gold08_text))
self.gold09.setCheckable(True)
self.gold09.toggle()
self.gold09_text = self.gold09.text()
self.gold09.clicked.connect(lambda: self.btnstate_gold(self.gold09, self.gold09_text))
self.gold10.setCheckable(True)
self.gold10.toggle()
self.gold10_text = self.gold10.text()
self.gold10.clicked.connect(lambda: self.btnstate_gold(self.gold10, self.gold10_text))
self.gold11.setCheckable(True)
self.gold11.toggle()
self.gold11_text = self.gold11.text()
self.gold11.clicked.connect(lambda: self.btnstate_gold(self.gold11, self.gold11_text))
self.gold12.setCheckable(True)
self.gold12.toggle()
self.gold12_text = self.gold12.text()
self.gold12.clicked.connect(lambda: self.btnstate_gold(self.gold12, self.gold12_text))
self.gold13.setCheckable(True)
self.gold13.toggle()
self.gold13_text = self.gold13.text()
self.gold13.clicked.connect(lambda: self.btnstate_gold(self.gold13, self.gold13_text))
self.gold14.setCheckable(True)
self.gold14.toggle()
self.gold14_text = self.gold14.text()
self.gold14.clicked.connect(lambda: self.btnstate_gold(self.gold14, self.gold14_text))
self.gold15.setCheckable(True)
self.gold15.toggle()
self.gold15_text = self.gold06.text()
self.gold15.clicked.connect(lambda: self.btnstate_gold(self.gold15, self.gold15_text))
self.gold16.setCheckable(True)
self.gold16.toggle()
self.gold16_text = self.gold16.text()
self.gold16.clicked.connect(lambda: self.btnstate_gold(self.gold16, self.gold16_text))
self.gold17.setCheckable(True)
self.gold17.toggle()
self.gold17_text = self.gold17.text()
self.gold17.clicked.connect(lambda: self.btnstate_gold(self.gold17, self.gold17_text))
self.gold18.setCheckable(True)
self.gold18.toggle()
self.gold18_text = self.gold18.text()
self.gold18.clicked.connect(lambda: self.btnstate_gold(self.gold18, self.gold18_text))
self.gold19.setCheckable(True)
self.gold19.toggle()
self.gold19_text = self.gold19.text()
self.gold19.clicked.connect(lambda: self.btnstate_gold(self.gold19, self.gold19_text))
self.gold20.setCheckable(True)
self.gold20.toggle()
self.gold20_text = self.gold20.text()
self.gold20.clicked.connect(lambda: self.btnstate_gold(self.gold20, self.gold20_text))
self.gold21.setCheckable(True)
self.gold21.toggle()
self.gold21_text = self.gold21.text()
self.gold21.clicked.connect(lambda: self.btnstate_gold(self.gold21, self.gold21_text))
self.gold22.setCheckable(True)
self.gold22.toggle()
self.gold22_text = self.gold22.text()
self.gold22.clicked.connect(lambda: self.btnstate_gold(self.gold22, self.gold22_text))
self.gold23.setCheckable(True)
self.gold23.toggle()
self.gold23_text = self.gold23.text()
self.gold23.clicked.connect(lambda: self.btnstate_gold(self.gold23, self.gold23_text))
self.gold24.setCheckable(True)
self.gold24.toggle()
self.gold24_text = self.gold24.text()
self.gold24.clicked.connect(lambda: self.btnstate_gold(self.gold24, self.gold24_text))
self.gold25.setCheckable(True)
self.gold25.toggle()
self.gold25_text = self.gold25.text()
self.gold25.clicked.connect(lambda: self.btnstate_gold(self.gold25, self.gold25_text))
self.silver01.setCheckable(True)
self.silver01.toggle()
self.silver01_text = self.silver01.text()
self.silver01.clicked.connect(lambda: self.btnstate_silver(self.silver01, self.silver01_text))
self.silver02.setCheckable(True)
self.silver02.toggle()
self.silver02_text = self.silver02.text()
self.silver02.clicked.connect(lambda: self.btnstate_silver(self.silver02, self.silver02_text))
self.silver03.setCheckable(True)
self.silver03.toggle()
self.silver03_text = self.silver03.text()
self.silver03.clicked.connect(lambda: self.btnstate_silver(self.silver03, self.silver03_text))
self.silver04.setCheckable(True)
self.silver04.toggle()
self.silver04_text = self.silver04.text()
self.silver04.clicked.connect(lambda: self.btnstate_silver(self.silver04, self.silver04_text))
self.silver05.setCheckable(True)
self.silver05.toggle()
self.silver05_text = self.silver05.text()
self.silver05.clicked.connect(lambda: self.btnstate_silver(self.silver05, self.silver05_text))
self.silver06.setCheckable(True)
self.silver06.toggle()
self.silver06_text = self.silver06.text()
self.silver06.clicked.connect(lambda: self.btnstate_silver(self.silver06, self.silver06_text))
self.silver07.setCheckable(True)
self.silver07.toggle()
self.silver07_text = self.silver07.text()
self.silver07.clicked.connect(lambda: self.btnstate_silver(self.silver07, self.silver07_text))
self.silver08.setCheckable(True)
self.silver08.toggle()
self.silver08_text = self.silver08.text()
self.silver08.clicked.connect(lambda: self.btnstate_silver(self.silver08, self.silver08_text))
self.silver09.setCheckable(True)
self.silver09.toggle()
self.silver09_text = self.silver09.text()
self.silver09.clicked.connect(lambda: self.btnstate_silver(self.silver09, self.silver09_text))
self.silver10.setCheckable(True)
self.silver10.toggle()
self.silver10_text = self.silver10.text()
self.silver10.clicked.connect(lambda: self.btnstate_silver(self.silver10, self.silver10_text))
self.silver11.setCheckable(True)
self.silver11.toggle()
self.silver11_text = self.silver11.text()
self.silver11.clicked.connect(lambda: self.btnstate_silver(self.silver11, self.silver11_text))
self.silver12.setCheckable(True)
self.silver12.toggle()
self.silver12_text = self.silver12.text()
self.silver12.clicked.connect(lambda: self.btnstate_silver(self.silver12, self.silver12_text))
self.silver13.setCheckable(True)
self.silver13.toggle()
self.silver13_text = self.silver13.text()
self.silver13.clicked.connect(lambda: self.btnstate_silver(self.silver13, self.silver13_text))
self.silver14.setCheckable(True)
self.silver14.toggle()
self.silver14_text = self.silver14.text()
self.silver14.clicked.connect(lambda: self.btnstate_silver(self.silver14, self.silver14_text))
self.silver15.setCheckable(True)
self.silver15.toggle()
self.silver15_text = self.silver15.text()
self.silver15.clicked.connect(lambda: self.btnstate_silver(self.silver15, self.silver15_text))
self.silver16.setCheckable(True)
self.silver16.toggle()
self.silver16_text = self.silver16.text()
self.silver16.clicked.connect(lambda: self.btnstate_silver(self.silver16, self.silver16_text))
self.silver17.setCheckable(True)
self.silver17.toggle()
self.silver17_text = self.silver17.text()
self.silver17.clicked.connect(lambda: self.btnstate_silver(self.silver17, self.silver17_text))
self.silver18.setCheckable(True)
self.silver18.toggle()
self.silver18_text = self.silver18.text()
self.silver18.clicked.connect(lambda: self.btnstate_silver(self.silver18, self.silver18_text))
self.silver19.setCheckable(True)
self.silver19.toggle()
self.silver19_text = self.silver19.text()
self.silver19.clicked.connect(lambda: self.btnstate_silver(self.silver19, self.silver19_text))
self.silver20.setCheckable(True)
self.silver20.toggle()
self.silver20_text = self.silver20.text()
self.silver20.clicked.connect(lambda: self.btnstate_silver(self.silver20, self.silver20_text))
self.silver21.setCheckable(True)
self.silver21.toggle()
self.silver21_text = self.silver21.text()
self.silver21.clicked.connect(lambda: self.btnstate_silver(self.silver21, self.silver21_text))
self.silver22.setCheckable(True)
self.silver22.toggle()
self.silver22_text = self.silver22.text()
self.silver22.clicked.connect(lambda: self.btnstate_silver(self.silver22, self.silver22_text))
self.silver23.setCheckable(True)
self.silver23.toggle()
self.silver23_text = self.silver23.text()
self.silver23.clicked.connect(lambda: self.btnstate_silver(self.silver23, self.silver23_text))
self.silver24.setCheckable(True)
self.silver24.toggle()
self.silver24_text = self.silver24.text()
self.silver24.clicked.connect(lambda: self.btnstate_silver(self.silver24, self.silver24_text))
self.silver25.setCheckable(True)
self.silver25.toggle()
self.silver25_text = self.silver25.text()
self.silver25.clicked.connect(lambda: self.btnstate_silver(self.silver25, self.silver25_text))
self.plt01.setCheckable(True)
self.plt01.toggle()
self.plt01_text = self.plt01.text()
self.plt01.clicked.connect(lambda: self.btnstate_plt(self.plt01, self.plt01_text))
self.plt02.setCheckable(True)
self.plt02.toggle()
self.plt02_text = self.plt02.text()
self.plt02.clicked.connect(lambda: self.btnstate_plt(self.plt02, self.plt02_text))
self.plt03.setCheckable(True)
self.plt03.toggle()
self.plt03_text = self.plt03.text()
self.plt03.clicked.connect(lambda: self.btnstate_plt(self.plt03, self.plt03_text))
self.plt04.setCheckable(True)
self.plt04.toggle()
self.plt04_text = self.plt04.text()
self.plt04.clicked.connect(lambda: self.btnstate_plt(self.plt04, self.plt04_text))
self.plt05.setCheckable(True)
self.plt05.toggle()
self.plt05_text = self.plt05.text()
self.plt05.clicked.connect(lambda: self.btnstate_plt(self.plt05, self.plt05_text))
self.plt06.setCheckable(True)
self.plt06.toggle()
self.plt06_text = self.plt06.text()
self.plt06.clicked.connect(lambda: self.btnstate_plt(self.plt06, self.plt06_text))
self.plt07.setCheckable(True)
self.plt07.toggle()
self.plt07_text = self.plt07.text()
self.plt07.clicked.connect(lambda: self.btnstate_plt(self.plt07, self.plt07_text))
self.plt08.setCheckable(True)
self.plt08.toggle()
self.plt08_text = self.plt08.text()
self.plt08.clicked.connect(lambda: self.btnstate_plt(self.plt08, self.plt08_text))
self.plt09.setCheckable(True)
self.plt09.toggle()
self.plt09_text = self.plt09.text()
self.plt09.clicked.connect(lambda: self.btnstate_plt(self.plt09, self.plt09_text))
self.plt10.setCheckable(True)
self.plt10.toggle()
self.plt10_text = self.plt10.text()
self.plt10.clicked.connect(lambda: self.btnstate_plt(self.plt10, self.plt10_text))
self.plt11.setCheckable(True)
self.plt11.toggle()
self.plt11_text = self.plt11.text()
self.plt11.clicked.connect(lambda: self.btnstate_plt(self.plt11, self.plt11_text))
self.plt12.setCheckable(True)
self.plt12.toggle()
self.plt12_text = self.plt12.text()
self.plt12.clicked.connect(lambda: self.btnstate_plt(self.plt12, self.plt12_text))
self.plt13.setCheckable(True)
self.plt13.toggle()
self.plt13_text = self.plt13.text()
self.plt13.clicked.connect(lambda: self.btnstate_plt(self.plt13, self.plt13_text))
self.plt14.setCheckable(True)
self.plt14.toggle()
self.plt14_text = self.plt14.text()
self.plt14.clicked.connect(lambda: self.btnstate_plt(self.plt14, self.plt14_text))
self.plt15.setCheckable(True)
self.plt15.toggle()
self.plt15_text = self.plt15.text()
self.plt15.clicked.connect(lambda: self.btnstate_plt(self.plt15, self.plt15_text))
self.plt16.setCheckable(True)
self.plt16.toggle()
self.plt16_text = self.plt16.text()
self.plt16.clicked.connect(lambda: self.btnstate_plt(self.plt16, self.plt16_text))
self.plt17.setCheckable(True)
self.plt17.toggle()
self.plt17_text = self.plt17.text()
self.plt17.clicked.connect(lambda: self.btnstate_plt(self.plt17, self.plt17_text))
self.plt18.setCheckable(True)
self.plt18.toggle()
self.plt18_text = self.plt18.text()
self.plt18.clicked.connect(lambda: self.btnstate_plt(self.plt18, self.plt18_text))
self.plt19.setCheckable(True)
self.plt19.toggle()
self.plt19_text = self.plt19.text()
self.plt19.clicked.connect(lambda: self.btnstate_plt(self.plt19, self.plt19_text))
self.plt20.setCheckable(True)
self.plt20.toggle()
self.plt20_text = self.plt20.text()
self.plt20.clicked.connect(lambda: self.btnstate_plt(self.plt20, self.plt20_text))
self.plt21.setCheckable(True)
self.plt21.toggle()
self.plt21_text = self.plt21.text()
self.plt21.clicked.connect(lambda: self.btnstate_plt(self.plt21, self.plt21_text))
self.plt22.setCheckable(True)
self.plt22.toggle()
self.plt22_text = self.plt22.text()
self.plt22.clicked.connect(lambda: self.btnstate_plt(self.plt22, self.plt22_text))
self.plt23.setCheckable(True)
self.plt23.toggle()
self.plt23_text = self.plt23.text()
self.plt23.clicked.connect(lambda: self.btnstate_plt(self.plt23, self.plt23_text))
self.plt24.setCheckable(True)
self.plt24.toggle()
self.plt24_text = self.plt24.text()
self.plt24.clicked.connect(lambda: self.btnstate_plt(self.plt24, self.plt24_text))
self.plt25.setCheckable(True)
self.plt25.toggle()
self.plt25_text = self.plt25.text()
self.plt25.clicked.connect(lambda: self.btnstate_plt(self.plt25, self.plt25_text))
self.timer = QtCore.QTimer()
self.timer.setInterval(1000)
self.timer.timeout.connect(self.displayTime)
self.timer.start()
self.date=QtCore.QDate.currentDate().toString()
self.Date.setText("%s"%(self.date))
self.Date.setStyleSheet("QLabel\n"
"{\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}")
QtCore.QMetaObject.connectSlotsByName(Main_Window)
self.g_checked = 0
self.s_checked = 0
self.p_checked = 0
self.spinBox1_2.setSingleStep(0)
self.spinBox2_2.setSingleStep(0)
self.spinBox3_2.setSingleStep(0)
def handleTicket(self):
if self.lineEdit1_3.text()=="":
msg = QtGui.QMessageBox()
msg.setIcon(QtGui.QMessageBox.Critical)
msg.setText("Please fill the name feild.")
msg.setInformativeText("It is mandatory.")
msg.setWindowTitle("ENTER THE NAME!!")
msg.setEscapeButton(QtGui.QMessageBox.Ok)
msg.exec_()
else:
self.Ticket = MyDialog(self)
self.Ticket.exec_()
def resetSeatCount(self):
self.silver=0
self.gold=0
self.plt=0
def setCost(self):
"""print self.silver
print self.gold
print self.plt"""
self.totalSeats = self.silver + self.gold + self.plt
self.sCost=self.silver*200
self.gCost = self.gold * 300
self.pCost = self.plt * 400
self.tCost=self.sCost + self.gCost + self.pCost
self.serviceTax=(self.tCost*15)/100
self.enterTax=(self.tCost*20)/100
self.totalCost = self.tCost + self.serviceTax + self.enterTax
self.LABEL12_3.setText("%d" % self.totalSeats)
if self.sCost!=0 and self.gCost!=0 and self.pCost!=0:
self.LABEL13_3.setGeometry(QtCore.QRect(560, 170, 121, 14))
elif self.sCost==0 or self.gCost==0 or self.pCost==0:
self.LABEL13_3.setGeometry(QtCore.QRect(580, 170, 121, 14))
self.LABEL13_3.setText("Rs.%d + %d + %d"%(self.sCost , self.gCost , self.pCost))
self.LABEL14_3.setText("Rs.%d" % self.serviceTax)
self.LABEL15_3.setText("Rs.%d" % self.enterTax)
self.LABEL16_3.setText("Rs.%d" % self.totalCost)
def setCurrentMovie(self):
if 9<=self.now.hour<12:
self.Label1_0.setText(_translate("Main_Window","<html><head/><body><p><span style=\" font-size:28pt; font-weight:600; color:#0a064c;\">S</span><span style=\" font-size:24pt; font-weight:600; color:#0a064c;\">UICIDE</span><span style=\" font-size:28pt; font-weight:600; color:#0a064c;\"> S</span><span style=\" font-size:24pt; font-weight:600; color:#0a064c;\">QUAD</span></p></body></html>",None))
if 12 <= self.now.hour < 15:
self.Label1_0.setText(_translate("Main_Window","<html><head/><body><p><span style=\" font-size:28pt; font-weight:600; color:#0a064c;\">G</span><span style=\" font-size:24pt; font-weight:600; color:#0a064c;\">ONE</span><span style=\" font-size:28pt; font-weight:600; color:#0a064c;\"> G</span><span style=\" font-size:24pt; font-weight:600; color:#0a064c;\">IRL</span></p></body></html>",None))
self.Label1_0.move(110,310)
elif 15 <= self.now.hour < 19:
self.Label1_0.setText(_translate("Main_Window","<html><head/><body><p><span style=\" font-size:28pt; font-weight:600; color:#0a064c;\">T</span><span style=\" font-size:24pt; font-weight:600; color:#0a064c;\">HE</span><span style=\" font-size:28pt; font-weight:600; color:#0a064c;\"> C</span><span style=\" font-size:24pt; font-weight:600; color:#0a064c;\">ONJURING</span></p></body></html>",None))
elif 19 <= self.now.hour < 22:
self.Label1_0.setText(_translate("Main_Window","<html><head/><body><p><span style=\" font-size:28pt; font-weight:600; color:#0a064c;\">T</span><span style=\" font-size:24pt; font-weight:600; color:#0a064c;\">HE</span><span style=\" font-size:28pt; font-weight:600; color:#0a064c;\"> R</span><span style=\" font-size:24pt; font-weight:600; color:#0a064c;\">USH</span></p></body></html>",None))
self.Label1_0.move(110, 310)
else:
print "Closed"#self.label1_0.setText("THEATRE CLOSED.")
def displayTime(self):
self.Time.setStyleSheet("QLabel\n"
"{\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}")
self.Time.setText(QtCore.QTime.currentTime().toString())
def btnstate_silver(self, Button, btn_text):
if Button.isChecked():
self.s_checked = self.s_checked - 1
self.silver=self.silver-1
self.spinBox1_2.setValue(self.s_checked)
Button.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
Button.setText("%s" % (btn_text))
else:
self.s_checked=self.s_checked+1
self.silver=self.silver+1
self.spinBox1_2.setValue(self.s_checked)
Button.setStyleSheet(_fromUtf8("QPushButton\n"
"{\n"
"background-color:#C0C0C0;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
Button.setText("%s B" % btn_text)
def btnstate_gold(self, Button, btn_text):
if Button.isChecked():
self.g_checked = self.g_checked - 1
self.gold=self.gold-1
self.spinBox2_2.setValue(self.g_checked)
Button.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
Button.setText("%s" % btn_text)
else:
self.g_checked = self.g_checked + 1
self.gold=self.gold+1
self.spinBox2_2.setValue(self.g_checked)
Button.setStyleSheet(_fromUtf8("QPushButton\n"
"{\n"
"background-color:rgb(223, 199, 14);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
Button.setText("%s B" % btn_text)
def btnstate_plt(self, Button, btn_text):
if Button.isChecked():
self.p_checked = self.p_checked - 1
self.plt=self.plt-1
self.spinBox3_2.setValue(self.p_checked)
Button.setStyleSheet(_fromUtf8("QPushButton:hover\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
Button.setText("%s" % btn_text)
else:
self.p_checked = self.p_checked + 1
self.plt=self.plt+1
self.spinBox3_2.setValue(self.p_checked)
Button.setStyleSheet(_fromUtf8("QPushButton\n"
"{\n"
"background-color:#E5E4E2;\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
Button.setText("%s B" % btn_text)
def close_application(self):
msg = QtGui.QMessageBox()
msg.setIcon(QtGui.QMessageBox.Question)
msg.setText("You clicked Cancel button")
msg.setInformativeText("Are you sure you want to quit?")
msg.setWindowTitle("Quit")
# msg.setDText("The details are as follows:")
choice = msg.setStandardButtons(QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel)
retval = msg.exec_()
if retval == QtGui.QMessageBox.Ok:
#print "BYEE"
sys.exit()
def handleOK1(self):
if self.radio1_0.isChecked()==True:
self.TabWidget.setCurrentIndex(1)
elif self.radio2_0.isChecked() == True:
self.TabWidget.setCurrentIndex(2)
else:
self.radio_message_0()
def handleOK2(self):
#Main_Window.resize(703,650)
if (self.now.hour) < 9 or (self.now.hour) >= 19:
if self.radio2_1.isChecked() == True or self.radio3_1.isChecked() == True or self.radio4_1.isChecked() == True:
self.radio_message_1()
self.radio1_1.setChecked(True)
elif self.radio1_1.isChecked()==True:
self.resetSeatCount()
self.TabWidget.setCurrentIndex(2)
else:
self.radio_message_0()
self.radio1_1.setChecked(True)
elif 9 <= (self.now.hour) < 12:
if self.radio1_1.isChecked() == True or self.radio3_1.isChecked() == True or self.radio4_1.isChecked() == True:
self.radio_message_1()
self.radio2_1.setChecked(True)
elif self.radio2_1.isChecked()==True:
self.resetSeatCount()
self.TabWidget.setCurrentIndex(2)
else:
self.radio_message_0()
self.radio2_1.setChecked(True)
elif 12 <= (self.now.hour) < 15:
if self.radio2_1.isChecked() == True or self.radio1_1.isChecked() == True or self.radio4_1.isChecked() == True:
self.radio_message_1()
self.radio3_1.setChecked(True)
elif self.radio3_1.isChecked()==True:
self.resetSeatCount()
self.TabWidget.setCurrentIndex(2)
else:
self.radio_message_0()
self.radio3_1.setChecked(True)
elif 15 <= (self.now.hour) < 19:
if self.radio2_1.isChecked() == True or self.radio3_1.isChecked() == True or self.radio1_1.isChecked() == True:
self.radio_message_1()
self.radio4_1.setChecked(True)
elif self.radio4_1.isChecked()==True:
self.resetSeatCount()
self.TabWidget.setCurrentIndex(2)
else:
self.radio_message_0()
self.radio4_1.setChecked(True)
def handleOK3(self):
if self.silver==0 and self.gold==0 and self.plt==0:
msg = QtGui.QMessageBox()
msg.setIcon(QtGui.QMessageBox.Critical)
msg.setText("Please select any of the available seats.")
#msg.setInformativeText("Please select any of the available seats.")
msg.setWindowTitle("NO SEATS SELECTED!!")
msg.setEscapeButton(QtGui.QMessageBox.Ok)
msg.exec_()
else:
self.setCost()
self.TabWidget.setCurrentIndex(3)
def handleLoop(self):
self.TabWidget.setCurrentIndex(1)
def radio_message_0(self):
msg = QtGui.QMessageBox()
msg.setIcon(QtGui.QMessageBox.Critical)
msg.setText("No options were selected.")
msg.setInformativeText("Selecting an option is mandatory.")
msg.setWindowTitle("NOTHING SELECTED!!")
msg.setEscapeButton(QtGui.QMessageBox.Ok)
msg.exec_()
def radio_message_1(self):
msg = QtGui.QMessageBox()
msg.setIcon(QtGui.QMessageBox.Information)
msg.setText("Sorry, tickets can't be booked for this show right now.")
msg.setInformativeText("At this time, tickets can be booked for the marked show only.")
msg.setWindowTitle("WRONG SHOW!!")
msg.setEscapeButton(QtGui.QMessageBox.Ok)
msg.exec_()
#######################
def retranslateUi(self, Main_Window):
Main_Window.setWindowTitle(_translate("Main_Window", "MainWindow", None))
self.TabWidget.setWhatsThis(_translate("Main_Window", "<html><head/><body><p>HOME</p></body></html>", None))
self.Cancel_0.setText(_translate("Main_Window", "Cancel", None))
self.Label2_0.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:18pt; font-weight:600; text-decoration: underline; color:#00557f;\">Enter your choice:</span></p></body></html>", None))
self.radio1_0.setText(_translate("Main_Window", "Book a ticket", None))
self.OK_0.setText(_translate("Main_Window", "OK", None))
#self.Label1_0.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:28pt; font-weight:600; color:#0a064c;\">S</span><span style=\" font-size:24pt; font-weight:600; color:#0a064c;\">UICIDE</span><span style=\" font-size:28pt; font-weight:600; color:#0a064c;\"> S</span><span style=\" font-size:24pt; font-weight:600; color:#0a064c;\">QUAD</span></p></body></html>", None))
self.radio2_0.setText(_translate("Main_Window", "Seat Availability", None))
self.TabWidget.setTabText(self.TabWidget.indexOf(self.Home), _translate("Main_Window", "Home", None))
self.Label_background_1.setWhatsThis(_translate("Main_Window", "Instructions", None))
self.radio2_1.setText(_translate("Main_Window", "Gone Girl 12:00", None))
self.radio4_1.setText(_translate("Main_Window", "The Rush 19:00", None))
self.Label2_1.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:12pt; font-weight:600; text-decoration: underline;\">Time</span></p></body></html>", None))
self.Label4_1.setToolTip(_translate("Main_Window", "Instructions", None))
self.Label4_1.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:14pt; font-weight:600; color:#632603;\">*List of all the movies are displayed alongwith their timings</span></p><p><span style=\" font-size:14pt; font-weight:600; color:#632603;\">*Tickets can only be booked for the next show.</span></p></body></html>", None))
self.radio1_1.setText(_translate("Main_Window", "Suicide Squad 09:00", None))
self.Label3_1.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:36pt; color:#101010;\">S</span><span style=\" font-size:26pt; color:#101010;\">HOWS</span><span style=\" font-size:36pt; color:#101010;\"> L</span><span style=\" font-size:26pt; color:#101010;\">IST</span></p></body></html>", None))
self.Label1_1.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:12pt; font-weight:600; text-decoration: underline;\">Movies</span></p></body></html>", None))
self.radio3_1.setText(_translate("Main_Window", "The Conjuring 15:00", None))
self.OK_1.setText(_translate("Main_Window", "OK", None))
self.Cancel_1.setText(_translate("Main_Window", "Cancel", None))
self.TabWidget.setTabText(self.TabWidget.indexOf(self.tab_2), _translate("Main_Window", "Shows", None))
self.gold06.setText(_translate("Main_Window", "06", None))
self.silver20.setText(_translate("Main_Window", "20", None))
self.gold16.setText(_translate("Main_Window", "16", None))
self.plt15.setText(_translate("Main_Window", "15", None))
self.plt14.setText(_translate("Main_Window", "14", None))
self.gold07.setText(_translate("Main_Window", "07", None))
self.silver06.setText(_translate("Main_Window", "06", None))
self.gold18.setText(_translate("Main_Window", "18", None))
self.plt06.setText(_translate("Main_Window", "06", None))
self.gold21.setText(_translate("Main_Window", "21", None))
self.gold20.setText(_translate("Main_Window", "20", None))
self.plt05.setText(_translate("Main_Window", "05", None))
self.gold13.setText(_translate("Main_Window", "13", None))
self.gold02.setText(_translate("Main_Window", "02", None))
self.silver03.setText(_translate("Main_Window", "03", None))
self.plt08.setText(_translate("Main_Window", "08", None))
self.plt22.setText(_translate("Main_Window", "22", None))
self.gold10.setText(_translate("Main_Window", "10", None))
self.label1_2.setToolTip(_translate("Main_Window", "Instructions", None))
self.label1_2.setWhatsThis(_translate("Main_Window", "Instructions", None))
self.label1_2.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:12pt; font-weight:600;\">*Select the desired seats by clicking on the corresponding seat number.</span></p><p><span style=\" font-size:12pt; font-weight:600;\">*Deselect the seat by again clicking on it.</span></p><p><span style=\" font-size:12pt; font-weight:600;\">*No. of booked seats in a class are displayed in box above that class.</span></p></body></html>", None))
self.plt12.setText(_translate("Main_Window", "12", None))
self.silver16.setText(_translate("Main_Window", "16", None))
self.silver13.setText(_translate("Main_Window", "13", None))
self.gold25.setText(_translate("Main_Window", "25", None))
self.gold11.setText(_translate("Main_Window", "11", None))
self.plt17.setText(_translate("Main_Window", "17", None))
self.plt21.setText(_translate("Main_Window", "21", None))
self.gold17.setText(_translate("Main_Window", "17", None))
self.gold22.setText(_translate("Main_Window", "22", None))
self.plt25.setText(_translate("Main_Window", "25", None))
self.gold19.setText(_translate("Main_Window", "19", None))
self.silver05.setText(_translate("Main_Window", "05", None))
self.gold15.setText(_translate("Main_Window", "15", None))
self.Cancel_2.setText(_translate("Main_Window", "Cancel", None))
self.gold09.setText(_translate("Main_Window", "09", None))
self.silver12.setText(_translate("Main_Window", "12", None))
self.gold03.setText(_translate("Main_Window", "03", None))
self.plt01.setText(_translate("Main_Window", "01", None))
self.gold24.setText(_translate("Main_Window", "24", None))
self.gold23.setText(_translate("Main_Window", "23", None))
self.gold05.setText(_translate("Main_Window", "05", None))
self.silver01.setText(_translate("Main_Window", "01", None))
self.silver10.setText(_translate("Main_Window", "10", None))
self.label2_2.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:14pt; font-weight:600; color:#000000;\">No. of seats-</span></p></body></html>", None))
self.plt20.setText(_translate("Main_Window", "20", None))
self.silver15.setText(_translate("Main_Window", "15", None))
self.silver22.setText(_translate("Main_Window", "22", None))
self.gold12.setText(_translate("Main_Window", "12", None))
self.silver09.setText(_translate("Main_Window", "09", None))
self.silver11.setText(_translate("Main_Window", "11", None))
self.plt02.setText(_translate("Main_Window", "02", None))
self.gold01.setText(_translate("Main_Window", "01", None))
self.plt03.setText(_translate("Main_Window", "03", None))
self.silver21.setText(_translate("Main_Window", "21", None))
self.silver18.setText(_translate("Main_Window", "18", None))
self.silver25.setText(_translate("Main_Window", "25", None))
self.silver14.setText(_translate("Main_Window", "14", None))
self.gold04.setText(_translate("Main_Window", "04", None))
self.plt10.setText(_translate("Main_Window", "10", None))
self.OK_2.setText(_translate("Main_Window", "OK", None))
self.plt09.setText(_translate("Main_Window", "09", None))
self.silver02.setText(_translate("Main_Window", "02", None))
self.silver08.setText(_translate("Main_Window", "08", None))
self.gold14.setText(_translate("Main_Window", "14", None))
self.silver17.setText(_translate("Main_Window", "17", None))
self.silver07.setText(_translate("Main_Window", "07", None))
self.silver23.setText(_translate("Main_Window", "23", None))
self.plt18.setText(_translate("Main_Window", "18", None))
self.plt24.setText(_translate("Main_Window", "24", None))
self.plt16.setText(_translate("Main_Window", "16", None))
self.silver19.setText(_translate("Main_Window", "19", None))
self.plt13.setText(_translate("Main_Window", "13", None))
self.plt23.setText(_translate("Main_Window", "23", None))
self.plt07.setText(_translate("Main_Window", "07", None))
self.silver24.setText(_translate("Main_Window", "24", None))
self.silver04.setText(_translate("Main_Window", "04", None))
self.gold08.setText(_translate("Main_Window", "08", None))
self.plt19.setText(_translate("Main_Window", "19", None))
self.plt04.setText(_translate("Main_Window", "04", None))
self.plt11.setText(_translate("Main_Window", "11", None))
self.Button_silver_2.setText(_translate("Main_Window", "SILVER", None))
self.Button_gold_2.setText(_translate("Main_Window", "GOLD", None))
self.Button_platinum_2.setText(_translate("Main_Window", "PLATINUM", None))
self.TabWidget.setTabText(self.TabWidget.indexOf(self.tab_7), _translate("Main_Window", "Seats", None))
self.label4_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:14pt;\">Phone No.(Optional)</span></p></body></html>", None))
self.lineEdit2_3.setPlaceholderText(_translate("Main_Window", "Enter e-mail id", None))
self.lineEdit3_3.setPlaceholderText(_translate("Main_Window", "Enter Phone No.", None))
self.Cancel_3.setText(_translate("Main_Window", "Exit", None))
self.generateTicket_3.setText(_translate("Main_Window", "Generate Ticket", None))
self.label3_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:14pt;\">Email Id(Optional)</span></p></body></html>", None))
self.label2_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:14pt;\">Name</span></p></body></html>", None))
self.label1_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:22pt; font-weight:600;\">P</span><span style=\" font-size:16pt; font-weight:600;\">ERSONAL</span><span style=\" font-size:22pt; font-weight:600;\"> D</span><span style=\" font-size:18pt; font-weight:600;\">ETAILS </span></p></body></html>", None))
self.lineEdit1_3.setPlaceholderText(_translate("Main_Window", "Enter full name", None))
self.LABEL15_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:12pt;\">10</span></p></body></html>", None))
self.label5_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:16pt; font-weight:600; text-decoration: underline;\">COST</span></p></body></html>", None))
self.label7_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:12pt;\">Tickets Cost(S+G+P)</span></p></body></html>", None))
self.label9_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:12pt;\">Entertainment Tax(20%)</span></p></body></html>", None))
self.LABEL12_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:12pt;\">00</span></p></body></html>", None))
self.label10_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:14pt; font-weight:600;\">TOTAL-</span></p></body></html>", None))
self.LABEL14_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:12pt;\">20</span></p></body></html>", None))
self.label11_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:12pt;\">Thank You for visiting </span><span style=\" font-size:12pt; font-weight:600;\">VITPLEX</span><span style=\" font-size:12pt;\">!</span></p></body></html>", None))
self.label8_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:12pt;\">Service Tax(15%)</span></p></body></html>", None))
self.label6_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:12pt;\">Number of Seats =</span></p></body></html>", None))
self.LABEL13_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:12pt;\">00</span></p></body></html>", None))
self.LABEL16_3.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:12pt;\">00</span></p></body></html>", None))
self.label_18.setText(_translate("Main_Window", "-----------------------------------------------------------------------------------", None))
self.label_27.setText(_translate("Main_Window", "-----------------------------------------------------------------------------------", None))
self.TabWidget.setTabText(self.TabWidget.indexOf(self.tab_8), _translate("Main_Window", "Personal Details", None))
self.Time.setToolTip(_translate("Main_Window", "Time", None))
self.Time.setWhatsThis(_translate("Main_Window", "Time", None))
self.Time.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:18pt; font-weight:600;\">00:00</span></p></body></html>", None))
self.Date.setToolTip(_translate("Main_Window", "Date", None))
self.Date.setWhatsThis(_translate("Main_Window", "Date", None))
self.Date.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:18pt; font-weight:600;\">11/11/11</span></p></body></html>", None))
self.Date_label.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:14pt;\">--Date</span></p></body></html>", None))
self.Time_label.setText(_translate("Main_Window", "<html><head/><body><p><span style=\" font-size:14pt;\">Time--</span></p></body></html>", None))
self.menuAbout.setTitle(_translate("Main_Window", "About", None))
self.actionFont_Designer.setText(_translate("Main_Window", "Change Font Style", None))
self.actionChange_Background_color.setText(_translate("Main_Window", "Change Background color", None))
self.actionDevelopers.setText(_translate("Main_Window", "Developers", None))
class MyDialog(Ui_Main_Window):
def __init__(self, parent=None):
super(MyDialog, self).__init__(parent)
#Form.setObjectName(_fromUtf8("Form"))
#Form.resize(529, 201)
#self.setGeometry(300,300,541,221)
#self.mainMenu = self.menuBar()
#self.mainMenu.setNativeMenuBar(False)
self.saveFile = QtGui.QAction("&Save File", self)
self.saveFile.setShortcut("Ctrl+S")
self.saveFile.setStatusTip('Save File')
self.saveFile.triggered.connect(self.file_save)
self.now = datetime.datetime.now()
self.setWindowTitle("TICKET")
self.move(490,270)
self.label_19 = QtGui.QLabel(self)
self.label_19.setGeometry(QtCore.QRect(-10, 0, 541, 201))
self.label_19.setText(_fromUtf8(""))
self.label_19.setPixmap(QtGui.QPixmap(_fromUtf8("ticket_resized2.jpg")))
self.label_19.setObjectName(_fromUtf8("label_19"))
self.label = QtGui.QLabel(self)
self.label.setGeometry(QtCore.QRect(210, 30, 151, 41))
self.label.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"font-size:20pt;\n"
"font-weight:bold;\n"
"}"))
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(self)
self.label_2.setGeometry(QtCore.QRect(60, 29, 100, 31))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.label_2.setStyleSheet("font-size:12px; color:white; font-weight:bold;")
self.label_3 = QtGui.QLabel(self)
self.label_3.setGeometry(QtCore.QRect(390, 30, 61, 31))
self.label_3.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:rgb(255, 255, 255);\n"
"font-weight:bold;\n"
"font-size:15px;\n"
"}"))
self.label_3.setObjectName(_fromUtf8("label_3"))
self.label_4 = QtGui.QLabel(self)
self.label_4.setGeometry(QtCore.QRect(80, 75, 61, 21))
self.label_4.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"font-size:13px;\n"
"color:black;\n"
"}"))
self.label_4.setObjectName(_fromUtf8("label_4"))
self.label_5 = QtGui.QLabel(self)
self.label_5.setGeometry(QtCore.QRect(160, 76, 59, 20))
self.label_5.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label_5.setObjectName(_fromUtf8("label_5"))
self.label_6 = QtGui.QLabel(self)
self.label_6.setGeometry(QtCore.QRect(230, 77, 59, 21))
self.label_6.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label_6.setObjectName(_fromUtf8("label_6"))
self.label_7 = QtGui.QLabel(self)
self.label_7.setGeometry(QtCore.QRect(310, 76, 59, 20))
self.label_7.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label_7.setObjectName(_fromUtf8("label_7"))
self.label_8 = QtGui.QLabel(self)
self.label_8.setGeometry(QtCore.QRect(360, 70, 91, 31))
self.label_8.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"color:black;\n"
"}"))
self.label_8.setObjectName(_fromUtf8("label_8"))
self.line = QtGui.QFrame(self)
self.line.setGeometry(QtCore.QRect(150, 20, 211, 20))
self.line.setFrameShadow(QtGui.QFrame.Plain)
self.line.setLineWidth(3)
self.line.setFrameShape(QtGui.QFrame.HLine)
self.line.setObjectName(_fromUtf8("line"))
self.line_2 = QtGui.QFrame(self)
self.line_2.setGeometry(QtCore.QRect(150, 60, 211, 21))
self.line_2.setFrameShadow(QtGui.QFrame.Plain)
self.line_2.setLineWidth(2)
self.line_2.setMidLineWidth(0)
self.line_2.setFrameShape(QtGui.QFrame.HLine)
self.line_2.setObjectName(_fromUtf8("line_2"))
self.line_3 = QtGui.QFrame(self)
self.line_3.setGeometry(QtCore.QRect(140, 80, 16, 91))
self.line_3.setFrameShadow(QtGui.QFrame.Plain)
self.line_3.setFrameShape(QtGui.QFrame.VLine)
self.line_3.setObjectName(_fromUtf8("line_3"))
self.line_4 = QtGui.QFrame(self)
self.line_4.setGeometry(QtCore.QRect(200, 80, 16, 91))
self.line_4.setFrameShadow(QtGui.QFrame.Plain)
self.line_4.setFrameShape(QtGui.QFrame.VLine)
self.line_4.setObjectName(_fromUtf8("line_4"))
self.line_5 = QtGui.QFrame(self)
self.line_5.setGeometry(QtCore.QRect(290, 80, 16, 91))
self.line_5.setFrameShadow(QtGui.QFrame.Plain)
self.line_5.setFrameShape(QtGui.QFrame.VLine)
self.line_5.setObjectName(_fromUtf8("line_5"))
self.line_6 = QtGui.QFrame(self)
self.line_6.setGeometry(QtCore.QRect(340, 80, 16, 91))
self.line_6.setFrameShadow(QtGui.QFrame.Plain)
self.line_6.setFrameShape(QtGui.QFrame.VLine)
self.line_6.setObjectName(_fromUtf8("line_6"))
self.label_9 = QtGui.QLabel(self)
self.label_9.setGeometry(QtCore.QRect(70, 80, 81, 101))
self.label_9.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"font-size:12pt;\n"
"}"))
self.label_9.setObjectName(_fromUtf8("label_9"))
self.label_10 = QtGui.QLabel(self)
self.label_10.setGeometry(QtCore.QRect(158, 120, 61, 20))
self.label_10.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"font-size:12pt;\n"
"}"))
self.label_10.setObjectName(_fromUtf8("label_10"))
self.label_11 = QtGui.QLabel(self)
self.label_11.setGeometry(QtCore.QRect(230, 110, 71, 41))
self.label_11.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"font-size:12pt;\n"
"}"))
self.label_11.setObjectName(_fromUtf8("label_11"))
self.label_12 = QtGui.QLabel(self)
self.label_12.setGeometry(QtCore.QRect(310, 120, 59, 14))
self.label_12.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"font-size:12pt;\n"
"}"))
self.label_12.setObjectName(_fromUtf8("label_12"))
self.label_13 = QtGui.QLabel(self)
self.label_13.setGeometry(QtCore.QRect(360, 110, 59, 14))
self.label_13.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"font-size:12pt;\n"
"}"))
self.label_13.setObjectName(_fromUtf8("label_13"))
self.label_14 = QtGui.QLabel(self)
self.label_14.setGeometry(QtCore.QRect(360, 130, 59, 14))
self.label_14.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"font-size:12pt;\n"
"}"))
self.label_14.setObjectName(_fromUtf8("label_14"))
self.label_15 = QtGui.QLabel(self)
self.label_15.setGeometry(QtCore.QRect(360, 150, 59, 14))
self.label_15.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"font-size:12pt;\n"
"}"))
self.label_15.setObjectName(_fromUtf8("label_15"))
self.label_16 = QtGui.QLabel(self)
self.label_16.setGeometry(QtCore.QRect(430, 110, 59, 14))
self.label_16.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"font-size:12pt;\n"
"}"))
self.label_16.setObjectName(_fromUtf8("label_16"))
self.label_17 = QtGui.QLabel(self)
self.label_17.setGeometry(QtCore.QRect(430, 130, 59, 14))
self.label_17.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"font-size:12pt;\n"
"}"))
self.label_17.setObjectName(_fromUtf8("label_17"))
self.label_18 = QtGui.QLabel(self)
self.label_18.setGeometry(QtCore.QRect(430, 150, 59, 14))
self.label_18.setStyleSheet(_fromUtf8("QLabel\n"
"{\n"
"font-size:12pt;\n"
"}"))
self.label_18.setObjectName(_fromUtf8("label_18"))
self.line_7 = QtGui.QFrame(self)
self.line_7.setGeometry(QtCore.QRect(140, 30, 16, 41))
self.line_7.setFrameShadow(QtGui.QFrame.Plain)
self.line_7.setLineWidth(3)
self.line_7.setFrameShape(QtGui.QFrame.VLine)
self.line_7.setObjectName(_fromUtf8("line_7"))
self.line_8 = QtGui.QFrame(self)
self.line_8.setGeometry(QtCore.QRect(350, 30, 16, 41))
self.line_8.setFrameShadow(QtGui.QFrame.Plain)
self.line_8.setLineWidth(2)
self.line_8.setFrameShape(QtGui.QFrame.VLine)
self.line_8.setObjectName(_fromUtf8("line_8"))
self.retranslateUi()
#QtCore.QMetaObject.connectSlotsByName(Form)
self.setTicket()
self.save_button=QtGui.QPushButton(self)
self.save_button.setGeometry(220,170,120,30)
self.save_button.clicked.connect(self.file_save)
self.save_button.setText("SAVE TICKET")
self.save_button.setStyleSheet("background-color:black; color:white; font-weight:bold;")
def file_save(self):
self.name = QtGui.QFileDialog.getSaveFileName(self, 'Save File')
self.file = open(self.name, 'w')
self.text = self.textEdit.toPlainText()
self.file.write(self.text)
self.file.close()
def setTicket(self):
#NAME
self.name = ui.lineEdit1_3.text()
self.label_9.setText("%s"%self.name)
#Cost
self.cost = ui.totalCost
self.label_10.setText("Rs.%d"%(self.cost))
#TIME
self.label_3.setText(QtCore.QTime.currentTime().toString())
#DATE
self.date = QtCore.QDate.currentDate().toString()
self.label_2.setText("%s" % (self.date))
#SHOW and TIME
if self.now.hour<9 or self.now.hour>=19:
self.label_11.setText("Suicide\nSquad")
self.label_12.setText("09:00")
elif 9<=self.now.hour<12:
self.label_11.setText("Gone\nGirl")
self.label_12.setText("12:00")
elif 12<=self.now.hour<15:
self.label_11.setText("The\nConjuring")
self.label_12.setText("15:00")
elif 15<=self.now.hour<19:
self.label_11.setText("The\nRush")
self.label_12.setText("19:00")
#Number of seats
self.label_16.setText("%d"%(ui.silver))
self.label_17.setText("%d" % (ui.gold))
self.label_18.setText("%d" % (ui.plt))
def retranslateUi(self):
#Form.setWindowTitle(_translate("Form", "Form", None))
#print ui.gold
self.label.setText(_translate("Form", "<html><head/><body><p> VITPLEX</p></body></html>", None))
self.label_2.setText(_translate("Form", "<html><head/><body><p><span style=\" font-size:12pt; font-weight:600; color:#ffffff;\">Date</span></p></body></html>", None))
self.label_3.setText(_translate("Form", "<html><head/><body><p><span style=\" font-size:12pt; color:#ffffff;\">Time</span></p></body></html>", None))
self.label_4.setText(_translate("Form", "<html><head/><body><p><span style=\" text-decoration: underline;\">NAME</span></p></body></html>", None))
self.label_5.setText(_translate("Form", "<html><head/><body><p><span style=\" text-decoration: underline;\">COST</span></p></body></html>", None))
self.label_6.setText(_translate("Form", "<html><head/><body><p><span style=\" text-decoration: underline;\">SHOW</span></p></body></html>", None))
self.label_7.setText(_translate("Form", "<html><head/><body><p><span style=\" text-decoration: underline;\">TIME</span></p></body></html>", None))
self.label_8.setText(_translate("Form", "<html><head/><body><p><span style=\" text-decoration: underline;\">NO. OF SEATS</span></p></body></html>", None))
self.label_9.setText(_translate("Form", "<html><head/><body><p>Saumay </p><p>Khandelwal</p></body></html>", None))
self.label_10.setText(_translate("Form", "Rs. 000", None))
self.label_11.setText(_translate("Form", "<html><head/><body><p>Suicide </p><p>Squad</p></body></html>", None))
self.label_12.setText(_translate("Form", "00:00", None))
self.label_13.setText(_translate("Form", "Silver", None))
self.label_14.setText(_translate("Form", "Gold", None))
self.label_15.setText(_translate("Form", "Platinum", None))
self.label_16.setText(_translate("Form", "00", None))
self.label_17.setText(_translate("Form", "00", None))
self.label_18.setText(_translate("Form", "00", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Main_Window = QtGui.QMainWindow()
ui = Ui_Main_Window()
ui.setupUi(Main_Window)
Main_Window.show()
sys.exit(app.exec_()) | [
"noreply@github.com"
] | Saumay85.noreply@github.com |
a2111854ac54c26359b72bf65a3d4e34aa50b31e | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /EYojuPCtvSzF2chkZ_1.py | d247c0967894694c7c4e84c2701804484f99a9dd | [] | no_license | daniel-reich/turbo-robot | feda6c0523bb83ab8954b6d06302bfec5b16ebdf | a7a25c63097674c0a81675eed7e6b763785f1c41 | refs/heads/main | 2023-03-26T01:55:14.210264 | 2021-03-23T16:08:01 | 2021-03-23T16:08:01 | 350,773,815 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 576 | py | """
Create a function that returns the selected **filename** from a path. Include
the **extension** in your answer.
### Examples
get_filename("C:/Projects/pil_tests/ascii/edabit.txt") โ "edabit.txt"
get_filename("C:/Users/johnsmith/Music/Beethoven_5.mp3") โ "Beethoven_5.mp3"
get_filename("ffprobe.exe") โ "ffprobe.exe"
### Notes
* Tests will include both absolute and relative paths.
* For simplicity, all paths will include forward slashes.
"""
from pathlib import PurePath
โ
def get_filename(path):
return PurePath(path).name
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
7aad5605b239da7034298a049419589656d75fc5 | 4eb99b4089d111ec0a93970ca2d1d4b6cbb35f80 | /venv/Scripts/pip3.6-script.py | c477610d6fdb091f1ba024c3ff017f3c02b464a5 | [] | no_license | Changkyuuu/Chapter2_1 | d41dc75bebe4318c32c75c1dad2049f8112dc645 | e31005e34731fec6143daa0610e441616ab6b281 | refs/heads/master | 2020-05-20T13:39:14.480373 | 2019-05-08T12:44:12 | 2019-05-08T12:44:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 418 | py | #!D:\PythonStudy\PyChamProject\Chapter2_1\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3.6'
__requires__ = 'pip==19.0.3'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==19.0.3', 'console_scripts', 'pip3.6')()
)
| [
"ricaid@naver.com"
] | ricaid@naver.com |
c0a4e784d62e314e68a94a3ec01d95d0b75de946 | 39e9adceb3a32775a023a23f6a95d20abe434f53 | /test/core/test_object.py | 9cf2c1ce2e4c370fd744475220090d759ec65ba5 | [] | no_license | wjbotham/colorchord | 47750aab1944f71ab2611a51363389b5ae492094 | 2f3a967ee2a8c124936a2451a0504ac06cb8f1d1 | refs/heads/master | 2021-01-10T01:03:20.721482 | 2014-03-25T23:54:49 | 2014-03-25T23:54:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,199 | py | import unittest
from core.object import Object
class TestObject(unittest.TestCase):
def test_distance(self):
a = Object(10,5)
self.assertEqual(a.distance(a), 0)
b = Object(0,0)
self.assertEqual(a.distance(b), 125**0.5)
self.assertEqual(b.distance(a), 125**0.5)
c = Object(5.25,5)
self.assertEqual(a.distance(c), 4.75)
def test_motion(self):
a = Object(0,0,5.5,4)
a.tick()
self.assertEqual(a.x, 5.5)
self.assertEqual(a.y, 4)
a.tick()
self.assertEqual(a.x, 11)
self.assertEqual(a.y, 8)
a.dx = -1
a.dy = -0.5
a.tick()
self.assertEqual(a.x, 10)
self.assertEqual(a.y, 7.5)
def test_lifespan(self):
a = Object(0,0,0,0,2)
self.assertTrue(not a.needs_cleanup)
a.tick()
self.assertTrue(not a.needs_cleanup)
a.tick()
self.assertTrue(a.needs_cleanup)
def test_position(self):
a = Object(0.4,0.6)
self.assertEqual(a.position, (0,1))
b = Object(1,2)
self.assertEqual(b.position, (1,2))
c = Object(31.1,1/3)
self.assertEqual(c.position, (31,0))
| [
"wjbotham@gmail.com"
] | wjbotham@gmail.com |
53d2fd523551820fab2e02a7938908c792d930e6 | 6c7a23a453114831572f61f1a58e3ba993571644 | /main/migrations/0004_alter_tomeet_date_of_meeting.py | 11a8a9e48c1a8cbe9b2e7b28dc4d43e7882401d8 | [] | no_license | lolaazizova/todo | 1e9e72f3ddb27447638de984f9cce8367fd7fd18 | 6bc928cfd3e8f5d5dd1fc707b9de37e50614496e | refs/heads/main | 2023-07-20T08:03:32.300370 | 2021-08-23T12:29:44 | 2021-08-23T12:29:44 | 395,904,093 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 399 | py | # Generated by Django 3.2.6 on 2021-08-21 15:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0003_alter_todo_created_at'),
]
operations = [
migrations.AlterField(
model_name='tomeet',
name='date_of_meeting',
field=models.DateField(auto_now_add=True),
),
]
| [
"lolaazizova082@gmail.com"
] | lolaazizova082@gmail.com |
fde97c8249d30b9f96310f9a0f91c45db0dcdc11 | 4fe971fdd0fb1d87b2bfaa5fe4b249b121501836 | /vignewton/managers/admin/images.py | a76a68be13c22e69ecf041c2f50c32321f7ec221 | [
"Unlicense"
] | permissive | umeboshi2/vignewton | 709c3395b74951385d1d3f9a932e4e6a6c1e0350 | bf55f90a25ae616e003ff0f71643dbe5084e924f | refs/heads/master | 2021-01-20T13:47:26.052679 | 2013-10-25T18:36:29 | 2013-10-25T18:36:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,186 | py | from cStringIO import StringIO
from datetime import datetime
import transaction
from PIL import Image
from vignewton.models.sitecontent import SiteImage
class ImageManager(object):
def __init__(self, session):
self.session = session
self.thumbnail_size = 128, 128
def images_query(self):
return self.session.query(SiteImage)
def make_thumbnail(self, content):
imgfile = StringIO(content)
img = Image.open(imgfile)
img.thumbnail(self.thumbnail_size, Image.ANTIALIAS)
outfile = StringIO()
img.save(outfile, 'JPEG')
outfile.seek(0)
thumbnail_content = outfile.read()
return thumbnail_content
def add_image(self, name, fileobj):
content = fileobj.read()
with transaction.manager:
image = SiteImage(name, content)
image.thumbnail = self.make_thumbnail(content)
self.session.add(image)
return self.session.merge(image)
def delete_image(self, id):
with transaction.manager:
image = self.session.query(SiteImage).get(id)
self.session.delete(image)
| [
"joseph.rawson.works@littledebian.org"
] | joseph.rawson.works@littledebian.org |
76542110083e8161b587805da9a86b78f4d62837 | b06a6a7e4e42cabdda60a6ce2c4b6478d1ef61ba | /Chapter-01/function.py | 4cff7cb7014102e040363e0786320bb91d0c7468 | [] | no_license | cstpimentel/coursera | 319e901aa5d6eeb527839da7d8ba10961c67d2c3 | dc7ce27db8ec569af0e7372b9e6b611d40261645 | refs/heads/master | 2021-01-18T17:40:17.124608 | 2016-09-25T08:34:51 | 2016-09-25T08:34:51 | 69,152,452 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 287 | py | def computepay(h,r):
if h <= base :
pay = h * r
elif h > base :
OT = h - base
OTpay = OT * r * 1.5
pay = OTpay + base * r
return pay
hrs = raw_input("Enter Hours:")
h = float(hrs)
rph = raw_input("Enter rate per hour:")
r = float(rph)
base = 40
p = computepay(h,r)
print p
| [
"root@amjdagasuan.local"
] | root@amjdagasuan.local |
9f77e916c511b53114f58ea7fa8a56b79e0034a7 | 7a8bb4c1de15f987e3231590eae74c051bf33726 | /SJVA_Scanner_KoreaTV_Download.py | 6a40cfa985904b82d46ef3644e0cc39210ea8b19 | [] | no_license | sunyruru/SJVA-Scanners | cbe6efa56be4c74a96059a91b32b60ff2ba4f3b6 | 5028c8c4aa58d4514f77ab46f3155f288c64b6f5 | refs/heads/master | 2020-04-21T13:40:04.306951 | 2019-01-28T08:21:35 | 2019-01-28T08:21:35 | 169,606,889 | 2 | 0 | null | 2019-02-07T16:53:39 | 2019-02-07T16:53:39 | null | UTF-8 | Python | false | false | 3,916 | py | # -*- coding: UTF-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import re, os, os.path
import Media, VideoFiles, Stack, Utils
import time, json, traceback, io
episode_regexps = [
r'(?P<show>.*?)[\s\.]E?(?P<ep>\d{1,2})[\-\~]E?\d{1,2}', #ํฉ๋ณธ ๊ฑธ๋ฆฌ๊ฒ
r'(?P<show>.*?)[eE](?P<ep>[0-9]{1,4})'
]
date_regexps = [
r'(?P<show>.*?)[^0-9a-zA-Z](?P<year>[0-9]{2})(?P<month>[0-9]{2})(?P<day>[0-9]{2})[^0-9a-zA-Z]', # 6์๋ฆฌ
]
try:
import logging
import logging.handlers
logger = logging.getLogger('sjva_scanner')
logger.setLevel(logging.ERROR)
formatter = logging.Formatter(u'[%(asctime)s|%(lineno)s]:%(message)s')
#file_max_bytes = 10 * 1024 * 1024
filename = os.path.join(os.path.dirname( os.path.abspath( __file__ ) ), '../../', 'Logs', 'sjva.scanner.korea.tv.download.log')
fileHandler = logging.FileHandler(filename, encoding='utf8')
#fileHandler = logging.handlers.RotatingFileHandler(filename=filename), maxBytes=file_max_bytes, backupCount=5, encoding='euc-kr')
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
except:
pass
def Scan(path, files, mediaList, subdirs, language=None, root=None):
VideoFiles.Scan(path, files, mediaList, subdirs, root)
paths = Utils.SplitPath(path)
shouldStack = True
logger.debug('=====================================================')
logger.debug('- path:%s' % path)
logger.debug('- files count:%s' % len(files))
logger.debug('- subdir count:%s' % len(subdirs))
for _ in subdirs:
logger.debug(' * %s' % _)
if len(paths) != 0:
logger.debug('- paths[0] : %s' % paths[0])
logger.debug('- files count : %s', len(files))
for i in files:
tempDone = False
try:
file = os.path.basename(i)
logger.debug(' * FILE : %s' % file)
#for idx, rx in enumerate(episode_regexps):
for rx in episode_regexps:
match = re.search(rx, file, re.IGNORECASE)
if match:
show = match.group('show').replace('.', '') if match.groupdict().has_key('show') else ''
season = 1
episode = int(match.group('ep'))
name, year = VideoFiles.CleanName(show)
name = re.sub(r'((.*?๊ธฐํ)|(๋ฏธ๋์๋ฆฌ์ฆ)|(.*?๋๋ผ๋ง)|(.*?ํน์ง))', '', name).strip()
logger.debug(' - MATCH show:[%s] name:[%s] episode:[%s] year:[%s]', show, name, episode, year)
if len(name) > 0:
tv_show = Media.Episode(name, season, episode, '', year)
tv_show.display_offset = 0
tv_show.parts.append(i)
mediaList.append(tv_show)
logger.debug(' - APPEND by episode: %s' % tv_show)
tempDone = True
break
if tempDone == False:
for rx in date_regexps:
match = re.search(rx, file)
if match:
year = int(match.group('year')) + 2000
month = int(match.group('month'))
day = int(match.group('day'))
show = match.group('show')
tv_show = Media.Episode(show, year, None, None, None)
tv_show.released_at = '%d-%02d-%02d' % (year, month, day)
tv_show.parts.append(i)
mediaList.append(tv_show)
logger.debug(' - APPEND by date: %s' % tv_show)
tempDone = True
break
if tempDone == False:
logger.error(' NOT APPEND!!')
except Exception, e:
logger.error(e)
if shouldStack:
Stack.Scan(path, files, mediaList, subdirs)
| [
"cybersol@naver.com"
] | cybersol@naver.com |
583c037e7bb9335de5e660d5aa38cc5c6f4b681c | 26484bb3c967a7ab6a751877247681565a79a37e | /Unlockable/repo/common/tests/models.py | c0ebbb4303ae9adae44527353c97f721c3c7d6fe | [] | no_license | manuptime/JAKT | 309a5343815babe76484b190016be0fa7ac23616 | 89ac9e1055942e4fa61231f4484c46ed4a3947b5 | refs/heads/master | 2022-08-14T07:45:29.275257 | 2015-03-28T19:10:53 | 2015-03-28T19:10:53 | 16,158,361 | 0 | 0 | null | 2022-07-21T22:34:37 | 2014-01-23T01:21:38 | JavaScript | UTF-8 | Python | false | false | 457 | py | import models
import unittest
class TestTriviaModels(unittest.TestCase):
def setUp(self):
self.a = models.Answer(answer="bad gps", correct=True)
self.q = models.Question(answers=[self.a], copy="What caused the problem")
def test_question_validates(self):
self.assertTrue(self.q.validate())
def test_answer_validates(self):
self.assertTrue(self.a.validate())
if __name__ == '__main__':
unittest.main()
| [
"bruce@manuptimestudios.com"
] | bruce@manuptimestudios.com |
219d5820aa6968a3a5d10434a75112d7036ac6fc | 572980f2fcdacc526887141bd34b60cb6246429a | /Behavioral-Cloning/model.py | d17d68642231e90b1a46e13b659d6833bbf6c1ac | [] | no_license | vamshidhar-pandrapagada/Self-Driving-Car | 4a8908de11c4de069f4d647038967d4e981563ad | 18b9352e62edc929b6ce0fc1eb3e46d151feb055 | refs/heads/master | 2021-09-16T21:03:15.433849 | 2018-06-25T04:10:12 | 2018-06-25T04:10:12 | 103,869,650 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,760 | py | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 28 00:41:43 2017
@author: Vamshidhar P
"""
import csv
import cv2
import numpy as np
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Dropout, Flatten, Dense, Lambda, Cropping2D, Activation
from keras.layers.advanced_activations import ELU
from keras.models import Sequential
from keras.layers.normalization import BatchNormalization
from keras import optimizers
from keras.callbacks import ModelCheckpoint
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import random
import tensorflow as tf
import math
from keras.layers.core import SpatialDropout2D
class BehaviorCloning(object):
def __init__(self, epochs, learning_rate, batch_size, path):
self.epochs = epochs
self.batch_size = batch_size
self.learning_rate = learning_rate
self.path = path
self.model = Sequential()
print('...Reading Data Set...')
self.driving_data = self.read_dataset()
def read_dataset(self):
driving_data = []
with open(self.path, 'r') as csvfile:
data = csv.reader(csvfile)
for row in data:
driving_data.append(row)
return driving_data
def generator(self, samples, batch_size):
"""
Training the neural network with large number of images loaded into memory may slow down the entire process.
Data generator functions in python are used to mitigate this problem by reading the required set of images
in chunks using the batch size.
Args:
samples: Image Samples read from Driving Log
batch_size: batch size
Return:
generator Yield: Images and Labels
Step 1: Read Image
Step 2: Calculate the Steer angle using the correction factor
Step 3: Invoke data_augment function
"""
# Only full batches
n_batches = len(samples)//batch_size
samples = samples[:n_batches*batch_size]
num_samples = len(samples)
while 1:
shuffle(samples)
for idx in range(0, num_samples, batch_size):
images = []
labels = []
for row in samples[idx: idx + batch_size]:
for camera in range(3):
img_read = cv2.imread(row[camera])
#Crop Image to get rid of SKY and Car Hood
#img_shape = img_read.shape
#top_crop = math.floor(img_shape[0]/5)
#bottom_crop = img_shape[0]-22
#img_read = img_read[top_crop:bottom_crop, 0:img_shape[1]]
images.append(img_read)
angle = float(row[3])
steer_angle = angle if camera == 0 else (angle + 0.2) if camera == 1 else (angle - 0.2)
labels.append(float(steer_angle))
images = np.array(images)
labels = np.array(labels)
images, labels = self.data_augment(images, labels)
yield shuffle(images, labels)
def data_augment(self, images, labels):
"""
Deep artificial neural networks require a large corpus of training data in order to effectively learn,
where collection of such training data is often expensive and laborious.
Data augmentation overcomes this issue by artificially inflating the training set with label
preserving transformations. Recently there has been extensive use of generic data augmentation
to improve Convolutional Neural Network (CNN) task performance.
Args:
images: list of images
labels: list of labels
Return:
Augmented Images and Labels
Step 1: Randomly Adjust Brightness of images using random brightness value
Generator function uses CV2 to read images in BGR format
Convert images to HSV(Hue-Saturation-Value), randomly alter V value and convert back to RGB
Drive.py gets the images from simulator using PIL image and is also read in RGB format
Step 2: Randomly shift the image virtially and horizontally and adjust the steeing angle using correction factor
Step 3: Randomly select images and Flip them and append to main Set
Step 4: Return Augmented Images and Labels
"""
augmented_images = []
augmented_labels = []
for idx, img in enumerate(images):
##Randomly Adjust Brightness of images
#
new_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
brightness_level = (0.2 * np.random.uniform()) + 0.4
new_img[:,:,2] = new_img[:,:,2] * brightness_level
new_img = cv2.cvtColor(new_img, cv2.COLOR_HSV2RGB)
# Randomly shift the image virtially and horizontally
x_shift = 100 * (np.random.rand() - 0.6)
y_shift = 20 * (np.random.rand() - 0.4)
new_steer_angle = labels[idx] + x_shift * 0.002
transition_matrix = np.float32([[1, 0, x_shift],[0, 1, y_shift]])
height, width = new_img.shape[:2]
new_img = cv2.warpAffine(new_img, transition_matrix, (width, height))
augmented_images.append(new_img)
augmented_labels.append(new_steer_angle)
#Randomly select images and Flip them and append to main Set
num_imgs = len(augmented_images)
random_flip_idx = random.sample(range(num_imgs), num_imgs//2)
for idx in random_flip_idx:
new_img = np.fliplr(augmented_images[idx])
new_steer_angle = -augmented_labels[idx]
augmented_images.append(new_img)
augmented_labels.append(new_steer_angle)
images = np.array(augmented_images)
labels = np.array(augmented_labels)
return images, labels
def model_pipeline(self, input_shape):
"""
This architecture used here is published by autonomous vehicle team in NVIDIA.
Hyper Parameters:
The number of epochs used: 35
Learning Rate: 0.01.
Batch size : 32
Momentum
Weights updated using back propagation and stochastic gradient descent optimizer.
Learning rate exponential decay was applied with global_step value computed as (learning_rate / epochs).
When training a model, it is often recommended to lower the learning rate
as the training progresses, which helps the model converge and reach global minimum.
Args:
input_shape: shape of the input image
Step 1: Normalize the pixel values to a range between -1 and 1
Step 2: Crop Image: If you observe the images plotted , almost 1/5th of the image from the top is the sky
and around 20 pixels from the bottom is the hood of the car. These pixels provide no added value to the
neural network.
Cropping the image to get rid of these pixels will help the neural network look only at the road as the car moves.
Step 3: Build Model Pipleline
The model follows The All Convolutional Net achitecture.
Max-pooling layers are simply replaced by a convolutional layer with increased stride without loss in accuracy.
This yielded competitive or state of the art performance on several object
recognition datasets (CIFAR-10, CIFAR-100, ImageNet).
After several attempts, Spatial Dropout regularization on third and fourth convolutions followed by regular dropout
on fisth convolution provided least loss on validation set.
Our network is fully convolutional and images exhibit strong spatial correlation, the feature map activations
are also strongly correlated. In the standard dropout implementation, network activations are "dropped-out"
during training with independent probability without considering the spatial correlation.
On the other hand Spatial dropout extends the dropout value across the entire feature map.
Therefore, adjacent pixels in the dropped-out feature map are either all 0 (dropped-out) or all active.
This technique proved to be very effective and improves performance
Maxpool layer is used only on the last convolution layer with regular drop out.
"""
self.model = Sequential()
#As for any data-set, image data has been normalized so that the numerical rangeof the pixels is between -1 and 1.
self.model.add(Lambda(lambda x: x/127.5 - 1.0, input_shape = input_shape))
self.model.add(Cropping2D(cropping=((50,22), (0,0))))
self.model.add(Conv2D(filters = 24, kernel_size = (5,5), padding = 'same',
kernel_initializer= 'truncated_normal'))
self.model.add(Activation('elu'))
self.model.add(Conv2D(filters = 24, kernel_size = (5,5), strides = (2,2), padding = 'same',
kernel_initializer= 'truncated_normal'))
self.model.add(Conv2D(filters = 36, kernel_size = (5,5), padding = 'same',
kernel_initializer= 'truncated_normal'))
self.model.add(Activation('elu'))
self.model.add(Conv2D(filters = 36, kernel_size = (5,5), strides = (2,2), padding = 'same',
kernel_initializer= 'truncated_normal'))
self.model.add(Conv2D(filters = 48, kernel_size = (5,5), padding = 'same',
kernel_initializer= 'truncated_normal'))
self.model.add(Activation('elu'))
self.model.add(Conv2D(filters = 48, kernel_size = (5,5), strides = (2,2), padding = 'same',
kernel_initializer= 'truncated_normal'))
self.model.add(SpatialDropout2D(0.3))
self.model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'same',
kernel_initializer= 'truncated_normal'))
self.model.add(Activation('elu'))
self.model.add(SpatialDropout2D(0.3))
self.model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'same',
kernel_initializer= 'truncated_normal'))
self.model.add(Activation('elu'))
self.model.add(MaxPooling2D(pool_size=(1,1)))
self.model.add(Dropout(0.3))
self.model.add(Flatten())
self.model.add(Activation('elu'))
self.model.add(Dropout(0.3))
self.model.add(Dense(100,kernel_initializer= 'truncated_normal'))
self.model.add(Activation('elu'))
self.model.add(Dense(50, kernel_initializer= 'truncated_normal'))
self.model.add(Activation('elu'))
self.model.add(Dense(10, kernel_initializer= 'truncated_normal'))
self.model.add(Activation('elu'))
self.model.add(Dense(1))
self.model.summary()
momentum = 0.9
decay_rate = self.learning_rate / self.epochs
sgd_opt = optimizers.SGD(lr = self.learning_rate, momentum = momentum, decay = decay_rate, nesterov=False)
#adam_opt = optimizers.Adam(lr = self.learning_rate)
self.model.compile(optimizer = sgd_opt, loss='mean_squared_error')
def train(self):
"""
Train the Network
Args:
None
Return:
None
Step 1: Split the samples into Train and Validation sets.
Step 2: Invoke the train and validation generator functions created above.
Step 3: Calculate Train and Validation sample lengths
Step 4: Trigger Keras model.fit_generator to initiate training
Step 5: Print Model Stats (Training and Validation Loss)
"""
train_samples, validation_samples = train_test_split(self.driving_data, test_size=0.25, shuffle = True)
train_generator = self.generator(train_samples, self.batch_size)
validation_generator = self.generator(validation_samples, self.batch_size)
for i ,j in train_generator:
input_shape = i.shape[1:]
train_sample_length = i.shape[0] * (len(train_samples)//self.batch_size)
break
for i ,j in validation_generator:
valid_sample_length = i.shape[0] * (len(validation_samples)//self.batch_size)
break
print(train_sample_length,valid_sample_length, input_shape)
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', save_best_only=True)
print('...Constructing Model Pipeline...')
self.model_pipeline(input_shape)
print('...Training...')
with tf.device('/gpu:0'):
model_stats = self.model.fit_generator(train_generator,
steps_per_epoch=train_sample_length//self.batch_size,
epochs = self.epochs, verbose=2, callbacks=[checkpointer],
validation_data = validation_generator,
validation_steps=valid_sample_length//self.batch_size)
self.model.save('saved_models/model.h5')
print(model_stats.history.keys())
plt.plot(model_stats.history['loss'])
plt.plot(model_stats.history['val_loss'])
plt.title('model mean squared error loss')
plt.ylabel('mean squared error loss')
plt.xlabel('epoch')
plt.legend(['training set', 'validation set'], loc='upper right')
plt.show()
| [
"vamshidhar.pandrapagada@gmail.com"
] | vamshidhar.pandrapagada@gmail.com |
f7b236b52e96f9728be98b8a433d15f28ceaa875 | 4089860db033639545ce76ecd352732cfdec6411 | /bioinfo_python/030.py | 04eeacc6896ac6025a943f4b2e1707c70e6de53d | [] | no_license | gayoung0838/bioinfo-lecture-2021 | 6cda74f39906e08a388e2d0097e7e8ffe3f5a20c | 0557e7013381b591c73e73a4437940a598572d65 | refs/heads/main | 2023-06-25T06:34:05.139608 | 2021-07-30T11:07:19 | 2021-07-30T11:07:19 | 390,179,014 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 144 | py | #!/usr/bin/python
Seq1 = "AGTTTATAG"
for i in range(len(Seq1)):
#print(i, i+2, Seq1[i:i+2])
if Seq1[i:i+2] == "TT":
print(i, Seq1[i:i+2])
| [
"rlarkdud0838@gmail.com"
] | rlarkdud0838@gmail.com |
9e0ed93c65839146d4639537314916ed89f2de42 | cdd5c3238ba9feba53f95a04c247a846b15ecd09 | /code/client/munkilib/updatecheck/unused_software.py | 6c770cb491ffacf602e09ea131244321d63ffc2c | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | munki/munki | 13d786513f8fd5dba6f533bfbea76d28c4836d8e | d3c9eb4ffccd280fe3e4bbce9544171cb6c2cc80 | refs/heads/main | 2023-08-27T23:19:04.095339 | 2023-08-01T23:44:10 | 2023-08-01T23:44:10 | 24,219,473 | 2,890 | 474 | NOASSERTION | 2023-08-22T15:15:44 | 2014-09-19T06:51:32 | Python | UTF-8 | Python | false | false | 5,577 | py | # encoding: utf-8
#
# Copyright 2017-2023 Greg Neagle.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
updatecheck.unused_software
Created by Greg Neagle on 2017-02-18.
Functions for removing unused optional install items
"""
from __future__ import absolute_import, print_function
# Apple frameworks via PyObjC
# PyLint cannot properly find names inside Cocoa libraries, so issues bogus
# No name 'Foo' in module 'Bar' warnings. Disable them.
# pylint: disable=E0611
from AppKit import NSWorkspace
# pylint: enable=E0611
# our libs
from .. import app_usage
from .. import display
def bundleid_is_running(app_bundleid):
'''Returns a boolean indicating if the application with the given
bundleid is currently running.'''
workspace = NSWorkspace.sharedWorkspace()
running_apps = workspace.runningApplications()
for app in running_apps:
if app.bundleIdentifier() == app_bundleid:
return True
return False
def bundleids_from_installs_list(pkginfo_pl):
'''Extracts a list of application bundle_ids from the installs list of a
pkginfo item'''
installs_list = pkginfo_pl.get('installs', [])
bundle_ids = [item.get('CFBundleIdentifier') for item in installs_list
if (item.get('CFBundleIdentifier') and
item.get('type') == 'application'
or (item.get('type') == 'bundle' and
item.get('path', '').endswith('.app')))]
return bundle_ids
def should_be_removed(item_pl):
"""Determines if an optional install item should be removed due to lack of
use.
Returns a boolean."""
name = item_pl['name']
removal_info = item_pl.get('unused_software_removal_info')
# do we have unused_software_removal_info?
if not removal_info:
return False
display.display_debug1(
'\tChecking to see if %s should be removed due to lack of use...', name)
try:
removal_days = int(removal_info.get('removal_days', 0))
if removal_days < 1:
raise ValueError
except ValueError:
display.display_warning('Invalid removal_days: %s for item %s'
% (removal_info.get('removal_days'), name))
return False
display.display_debug1(
'\t\tNumber of days until removal is %s', removal_days)
usage = app_usage.ApplicationUsageQuery()
usage_data_days = usage.days_of_data()
if usage_data_days is None or usage_data_days < removal_days:
# we don't have usage data old enough to judge
display.display_debug1(
'\t\tApplication usage data covers fewer than %s days.',
removal_days)
return False
# check to see if we have an install request within the removal_days
days_since_install_request = usage.days_since_last_install_event(
'install', name)
if (days_since_install_request is not None and
days_since_install_request != -1 and
days_since_install_request <= removal_days):
display.display_debug1('\t\t%s had an install request %s days ago.',
name, days_since_install_request)
return False
# get list of application bundle_ids to check
if 'bundle_ids' in removal_info:
bundle_ids = removal_info['bundle_ids']
else:
# get application bundle_ids from installs list
bundle_ids = bundleids_from_installs_list(item_pl)
if not bundle_ids:
display.display_debug1('\\tNo application bundle_ids to check.')
return False
# now check each bundleid to see if it's currently running or has been
# activated in the past removal_days days
display.display_debug1('\t\tChecking bundle_ids: %s', bundle_ids)
for bundle_id in bundle_ids:
if bundleid_is_running(bundle_id):
display.display_debug1(
'\t\tApplication %s is currently running.' % bundle_id)
return False
days_since_last_activation = usage.days_since_last_usage_event(
'activate', bundle_id)
if days_since_last_activation == -1:
display.display_debug1(
'\t\t%s has not been activated in more than %s days...',
bundle_id, usage.days_of_data())
elif days_since_last_activation <= removal_days:
display.display_debug1('\t\t%s was last activated %s days ago',
bundle_id, days_since_last_activation)
return False
else:
display.display_debug1('\t\t%s was last activated %s days ago',
bundle_id, days_since_last_activation)
# if we get this far we must not have found any apps used in the past
# removal_days days, so we should set up a removal
display.display_info('Will add %s to the removal list since it has been '
'unused for at least %s days...', name, removal_days)
return True
if __name__ == '__main__':
print('This is a library of support tools for the Munki Suite.')
| [
"gregneagle@mac.com"
] | gregneagle@mac.com |
cb8930dfdd27405a23c87b5b9d932317f2d64346 | 8ff881523f65e13fcb682b93756ed3113937cee3 | /setup_environment.py | a44ff7881f0b7f3e864440ba12effb30f729f2b3 | [] | no_license | wyq730/scripts | a43d1045c96c54011d3501aa556f41321bdb2b11 | d07d3ca03a29a889c8d08f08466207320737659b | refs/heads/main | 2023-08-24T17:31:49.350436 | 2021-10-18T18:38:54 | 2021-10-18T18:38:54 | 355,764,043 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,258 | py | #!/usr/bin/env python3
import subprocess
import os
import textwrap
def main():
subprocess.run('apt-get update', shell=True, check=True)
# Setup Zsh.
try:
subprocess.run(
'yes | ZSH=$HOME/.oh-my-zsh RUNZSH=no sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"',
shell=True, check=True)
except subprocess.CalledProcessError as e:
if e.returncode == 1: # Zsh is already installed.
subprocess.run('rm -r $HOME/.oh-my-zsh', shell=True, check=True)
subprocess.run(
'yes | ZSH=$HOME/.oh-my-zsh RUNZSH=no sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"',
shell=True, check=True)
print('finish')
else:
raise e
subprocess.run('sed -i \'s/ZSH_THEME.*/ZSH_THEME="kphoen"/\' ~/.zshrc', shell=True, check=True)
subprocess.run('chsh -s $(which zsh)', shell=True, check=True)
# Setup tmux.
tmux_conf_filepath = os.path.expanduser('~/.tmux.conf')
tmux_conf_content = textwrap.dedent("""
unbind C-b
set-option -g prefix `
bind ` send-prefix
setenv -g SSH_AUTH_SOCK $HOME/.ssh/ssh_auth_sock
""")
with open(tmux_conf_filepath, 'w') as tmux_conf_file:
tmux_conf_file.write(tmux_conf_content)
# Setup Git.
git_config_filepath = os.path.expanduser('~/.gitconfig')
git_config_content = textwrap.dedent("""
[user]
name = Yanqing Wang
email = yanqing.wang@tusimple.ai
[push]
default = simple
[pull]
rebase = false
[alias]
st = status
co = commit
di = diff
lo = log --color --graph --decorate -M --pretty=oneline --abbrev-commit -M
""")
with open(git_config_filepath, 'w') as git_config_file:
git_config_file.write(git_config_content)
# Add tspkg entry to zshrc.
zshrc_tspkg_entry = textwrap.dedent('eval $(cd && .tspkg/bin/tsp --env)')
zshrc_path = os.path.expanduser('~/.zshrc')
with open(zshrc_path, 'a') as zshrc_config_file:
zshrc_config_file.write(zshrc_tspkg_entry)
if __name__ == "__main__":
main()
| [
"yanqing.wang@tusimple.ai"
] | yanqing.wang@tusimple.ai |
557bf137bc25e4d59e0decca306d6f73d6757955 | 82300a12386d685dec09f0285258a69af371ade4 | /Sampling.py | 5c933b643222cf29daa2d0264e1441c8a6e81344 | [] | no_license | pixas/EI331 | aae130d69370876b2f2a05659dbc1a1f564a9db6 | 9df3051f1b6fe4bbe24d916f8f942c82f6aaf726 | refs/heads/main | 2023-06-10T01:23:17.008374 | 2021-07-05T13:07:13 | 2021-07-05T13:07:13 | 379,834,616 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,427 | py | import numpy as np
import matplotlib.pyplot as plt
import math
import Amplitude_Modulation
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
plt.style.use("seaborn-whitegrid")
class MyFigure(FigureCanvas):
def __init__(self,width=5, height=4):
self.fig=Figure(figsize=(width,height))
super(MyFigure,self).__init__(self.fig)
def sampling_sinusoid(amplitude = 1,fre1 = np.pi,theta1 = 0,fre2 = np.pi/2,sampling_rate = 1.7):
"""calculate the sampled signal of the modulated signal
Args:
amplitude (float, optional): [the amplitude of modulating waveform]. Defaults to 1.
fre1 (float, optional): [the frequency of modulating waveform]. Defaults to np.pi.
theta1 (float, optional): [the phase of modulating waveform]. Defaults to 0.
fre2 (float, optional): [the frequency of carrier waveform]. Defaults to np.pi/2.
sampling_rate (float, optional): [the sampling rate of sampling]. Defaults to 1.7.
Returns:
tuple[np.ndarray,np.ndarray,np.ndarray,np.ndarray,np.ndarray,np.ndarray]
"""
amplitude = float(amplitude)
fre1 = float(fre1)
theta1 = float(theta1)
fre2 = float(fre2)
sampling_rate = float(sampling_rate)
(_,_,_,y1,y2,y3) = Amplitude_Modulation.AM_sinusoid(amplitude,fre1,theta1,fre2)
#time domain
t_ = np.linspace(int(-8 - theta1 / fre1), int(8 - theta1 / fre1),num = int(16 * sampling_rate + 1))
y1_ = np.zeros(int(16 * sampling_rate + 1))
for i in range(int(16 * sampling_rate + 1)):
y1_[i] = y1[int(i * 1024 / (16 * sampling_rate))]
# spectrum of real part
omega1_ = np.linspace(-fre1 * 3 - fre2 * 3,fre1 * 3 + fre2 * 3,num = 1537)
y21 = np.zeros(512) #shrink the index in order to simplify calculation
y2_ = np.zeros(1537)
for i in range(512):
y21[i] = y2[i + 256]
for i in range(512,1024):
y2_[i] = sampling_rate * y21[i - 512]
for i in range(512):
y2_[i] = sampling_rate * y2_[int(i + 2 * np.pi * sampling_rate * 256 / (fre1 + fre2))]
for i in range(1025,1536):
y2_[i] = sampling_rate * y2_[int(i - 2 * np.pi * sampling_rate * 256 / (fre1 + fre2))]
# spectrum of real part
omega2_ = np.linspace(-fre1 * 3 - fre2 * 3,fre1 * 3 + fre2 * 3,num = 1537)
y31 = np.zeros(512) #shrink the index in order to simplify calculation
y3_ = np.zeros(1537)
for i in range(512):
y31[i] = y3[i + 256]
for i in range(512,1024):
y3_[i] = sampling_rate * y31[i - 512]
for i in range(512):
y3_[i] = sampling_rate * y3_[int(i + 2 * np.pi * sampling_rate * 256 / (fre1 + fre2))]
for i in range(1025,1536):
y3_[i] = sampling_rate * y3_[int(i - 2 * np.pi * sampling_rate * 256 / (fre1 + fre2))]
return t_,omega1_,omega2_,y1_,y2_,y3_
def sampling_sinusoid_plot(amplitude = 1,fre1 = np.pi,theta1 = 0,fre2 = np.pi/2,sampling_rate = 1.7):
"""plot the sampled signal above
Args:
amplitude (float, optional): [the amplitude of modulating waveform]. Defaults to 1.
fre1 (float, optional): [the frequency of modulating waveform]. Defaults to np.pi.
theta1 (float, optional): [the phase of modulating waveform]. Defaults to 0.
fre2 (float, optional): [the frequency of carrier waveform]. Defaults to np.pi/2.
sampling_rate (float, optional): [the sampling rate of sampling]. Defaults to 1.7.
"""
(t,omega1,omega2,y1,y2,y3) = Amplitude_Modulation.AM_sinusoid(amplitude,fre1,theta1,fre2)
(t_,omega1_,omega2_,y1_,y2_,y3_) = sampling_sinusoid(amplitude,fre1,theta1,fre2,sampling_rate)
#original signal
#plot in time domain
F=MyFigure()
F.ax1=F.fig.add_subplot(231)
F.ax1.plot(t,y1)
F.ax1.set_xlabel("$t$")
F.ax1.set_ylabel("$y(t)$")
F.ax1.set_title('modulated signal in time domain')
#spectrum of real part
F.ax2=F.fig.add_subplot(232)
F.ax2.plot(omega1,y2)
F.ax2.set_xlabel("$\omega$")
F.ax2.set_ylabel("$Re\{Y(j\omega)\}$")
F.ax2.set_title('spectrum of modulated signal-Re')
#spectrum of imaginary part
F.ax3=F.fig.add_subplot(233)
F.ax3.plot(omega2,y3)
F.ax3.set_xlabel("$\omega$")
F.ax3.set_ylabel("$Im\{Y(j\omega)\}$")
F.ax3.set_title('spectrum of modulated signal-Im')
#sampled signal
#spectrum of real part
F.ax4=F.fig.add_subplot(234)
F.ax4.stem(t_,y1_)
F.ax4.set_xlabel("$t$")
F.ax4.set_ylabel("$y(t)$")
F.ax4.set_title('sampled signal in time domain')
#spectrum of real part
F.ax5=F.fig.add_subplot(235)
F.ax5.plot(omega1_,y2_)
F.ax5.set_xlabel("$\omega$")
F.ax5.set_ylabel("$Re\{Y(j\omega)\}$")
F.ax5.set_title('spectrum of sampled signal-Re')
#spectrum of imaginary part
F.ax6=F.fig.add_subplot(236)
F.ax6.plot(omega2_,y3_)
F.ax6.set_xlabel("$\omega$")
F.ax6.set_ylabel("$Im\{Y(j\omega)\}$")
F.ax6.set_title('spectrum of sampled signal-Im')
F.fig.subplots_adjust(wspace = 1,hspace = 0.7)
return F
#if __name__ == "__main__":
# sampling_sinusoid_plot(theta1=-np.pi/3,fre1=np.pi/2,fre2=2*np.pi)
# plt.subplots_adjust(wspace = 0.7,hspace = 0.7)
# plt.show()
| [
"noreply@github.com"
] | pixas.noreply@github.com |
7942255ce3e00ae3769a7cdbbb8edc73fc986e87 | 6b1cac18b81a4704c310fb30a30e2906c6137511 | /onepanman_api/views/api/notice.py | 26a0a1f3a0327c3e7ae9f34146fc170cb14d8ea3 | [
"MIT"
] | permissive | Capstone-onepanman/api-server | 973c73a4472637e5863d65ae90ec53db83aeedf7 | 1a5174fbc441d2718f3963863590f634ba2014e1 | refs/heads/master | 2022-12-09T22:43:23.720837 | 2020-03-20T00:43:21 | 2020-03-20T00:43:21 | 234,227,137 | 0 | 0 | MIT | 2022-12-08T02:37:19 | 2020-01-16T03:29:36 | Python | UTF-8 | Python | false | false | 247 | py | from rest_framework import viewsets
from onepanman_api.models import Notice
from onepanman_api.serializers.notice import NoticeSerializer
class NoticeViewSet(viewsets.ModelViewSet):
queryset = Notice
serializer_class = NoticeSerializer
| [
"dngusdnd@gmail.com"
] | dngusdnd@gmail.com |
f60e1bb59993ddae4b890f2c7f9beca934aafd6c | 2cf960de809f16b49a699f43d8126859b4209bef | /qrgen/venv/Scripts/pip3.8-script.py | 0e4a44cd1e787af646f07fcfa3b38bae423c904e | [] | no_license | i2117/qr-generator-py | 5ab32fdc52b6bc0642ad613c68e15a9d5cc965b2 | 7a70701356120e37115b8089579400c6e0a764f7 | refs/heads/master | 2022-11-30T21:10:51.412212 | 2019-12-15T14:08:18 | 2019-12-15T14:08:18 | 228,199,269 | 0 | 0 | null | 2022-11-22T04:54:35 | 2019-12-15T14:39:57 | Python | UTF-8 | Python | false | false | 398 | py | #!C:\PyProjects\QRgen\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3.8'
__requires__ = 'pip==19.0.3'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==19.0.3', 'console_scripts', 'pip3.8')()
)
| [
"qqq@gmail.com"
] | qqq@gmail.com |
76e930f0b8549e87342e1da1ae52b26f6055003c | 88aa879ce4975f4ca9480c1e58b113e400e9cc66 | /main_support.py | 163370cd42127efed8152979c2efe384946fd458 | [
"MIT"
] | permissive | metal-velcro/psvimgtools-frontend | 0bc4c7a8a337c8715af8253d78e82248f9816016 | 8a96a7b314ceb32610e683362755954dd4fe521f | refs/heads/master | 2021-01-21T17:47:21.283147 | 2017-05-18T04:36:27 | 2017-05-18T04:36:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 912 | py | #! /usr/bin/env python
#
# Support module generated by PAGE version 4.8.9
# In conjunction with Tcl version 8.6
# Feb 25, 2017 12:38:54 PM
import sys
try:
from Tkinter import *
except ImportError:
from tkinter import *
try:
import ttk
py3 = 0
except ImportError:
import tkinter.ttk as ttk
py3 = 1
def accMan():
import accMgr
accMgr.vp_start_gui()
sys.stdout.flush()
def bkupMgr():
import bkupMgr
bkupMgr.vp_start_gui()
sys.stdout.flush()
def esyInstall():
import easyInstallers
easyInstallers.vp_start_gui()
sys.stdout.flush()
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def destroy_window():
# Function which closes the window.
global top_level
top_level.destroy()
top_level = None
if __name__ == '__main__':
import main
main.vp_start_gui()
| [
"noreply@github.com"
] | metal-velcro.noreply@github.com |
5c901104b99ece9d8af7cfae27ced520d597a350 | 0cff97e59ef00a716c5bc6086984a44c0fb1cf84 | /PycharmProjects/Tutorial/venv/Scripts/pip-script.py | f647cac56b21acd24ee453e0ccc9dc3440f4b55e | [] | no_license | Pruthvi77/Cent | 0747789ad303d44b2991159b1d8682eb1145ec32 | ecb898c4ded644bb92756f12c4f376c064c663d0 | refs/heads/master | 2023-01-23T19:48:45.024405 | 2020-11-23T04:56:52 | 2020-11-23T04:56:52 | 170,821,752 | 0 | 3 | null | 2022-12-21T06:41:37 | 2019-02-15T07:38:05 | Python | UTF-8 | Python | false | false | 410 | py | #!C:\Users\prudvi\PycharmProjects\Tutorial\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==9.0.1','console_scripts','pip'
__requires__ = 'pip==9.0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==9.0.1', 'console_scripts', 'pip')()
)
| [
"pruthvich.1994@gmail.com"
] | pruthvich.1994@gmail.com |
5187af59415f8278a3d1a4a24949e077df2933b2 | e36a8872d91264b504e532131f494b38b740ca91 | /spiegel_scraper/article.py | 3cd3e967aeaa9a2ac15397518d52cf264c707d1a | [] | no_license | ietz/spiegel-scraper | 0269f5b9686621f0a5a30111de85cbaf5abc3cda | e40e32101b1f6fe686e34ef86ff147587cb5e3fc | refs/heads/master | 2020-12-22T13:35:02.643689 | 2020-02-03T17:20:41 | 2020-02-03T17:20:41 | 236,801,284 | 7 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,813 | py | import json
import re
import lxml.html
import requests
def by_url(article_url: str):
html = html_by_url(article_url)
return scrape_html(html)
def html_by_url(article_url: str):
return requests.get(article_url).text
def scrape_html(article_html: str):
doc = lxml.html.fromstring(article_html)
ld_content = doc.xpath('string(//script[@type="application/ld+json"]/text())')
ld = json.loads(ld_content)
ld_by_type = {ld_entry['@type']: ld_entry for ld_entry in ld}
news_ld = ld_by_type['NewsArticle']
settings = json.loads(doc.xpath('string(//script[@type="application/settings+json"]/text())'))
info = settings['editorial']['info']
text_node_selector = \
'main .word-wrap > p,' \
'main .word-wrap > h3, ' \
'main .word-wrap > ul > li, ' \
'main .word-wrap > ol > li'
text_nodes = doc.cssselect(text_node_selector)
text = re.sub(r'\n+', '\n', '\n'.join([node.text_content() for node in text_nodes])).strip()
return {
'url': doc.xpath('string(//link[@rel="canonical"]/@href)'),
'id': info['article_id'],
'channel': info['channel'],
'subchannel': info['subchannel'],
'headline': {
'main': info['headline'],
'social': info['headline_social']
},
'intro': info['intro'],
'text': text,
'topics': info['topics'],
'author': settings['editorial']['author'],
'comments_enabled': settings['editorial']['attributes']['is_comments_enabled'],
'date_created': news_ld['dateCreated'],
'date_modified': news_ld['dateModified'],
'date_published': news_ld['datePublished'],
'breadcrumbs': [breadcrumb['item']['name'] for breadcrumb in ld_by_type['BreadcrumbList']['itemListElement']],
}
| [
"tim@pietz.me"
] | tim@pietz.me |
87be5e5ab69a0137437df7340bd28ac0c71105e1 | 88994e2e840a70ec702cee09e1a13813aa6f800c | /cg/constants/backup.py | 16d3c41653d24f57dbede48641c08572ba634d6f | [] | no_license | Clinical-Genomics/cg | 1e9eb0852f742d555a48e8696914ebe177f7d436 | d2ec6d25b577dd6938bbf92317aeff1d6b3c5b08 | refs/heads/master | 2023-09-01T02:04:04.229120 | 2023-08-31T13:50:31 | 2023-08-31T13:50:31 | 82,567,026 | 19 | 8 | null | 2023-09-14T15:24:13 | 2017-02-20T14:29:43 | Python | UTF-8 | Python | false | false | 35 | py | MAX_PROCESSING_FLOW_CELLS: int = 1
| [
"noreply@github.com"
] | Clinical-Genomics.noreply@github.com |
78fc2fd83134852c5bf3f7a109c6ad89ee877db8 | 8bd3c9fe423da6658abc40edda85abe25841eaa5 | /listing/listing/settings.py | 37fcab4a1ecf747e91bcc3c73db822790ecda049 | [] | no_license | sylvia198591/Rizwalk1 | 341082e3bdb1443cda598e55cbea4e209051c810 | 7147ede14c3e57acc708e9b4bf2ecf38fb2ab5f0 | refs/heads/main | 2023-01-19T11:12:17.714091 | 2020-11-25T06:43:23 | 2020-11-25T06:43:23 | 315,821,734 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,093 | py | """
Django settings for listing project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = Path(BASE_DIR, 'templates')
STATIC_DIR = Path(BASE_DIR,'static')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+1@)h$h^d646m31-=+m#n9i2r-2+80$_#02n^$20mk+av_$ri$'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social_django',
'listapp1',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware',
]
ROOT_URLCONF = 'listing.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'social_django.context_processors.backends', # <--
'social_django.context_processors.login_redirect', # <--
],
},
},
]
WSGI_APPLICATION = 'listing.wsgi.application'
AUTHENTICATION_BACKENDS = (
'social_core.backends.github.GithubOAuth2',
'social_core.backends.twitter.TwitterOAuth',
'social_core.backends.facebook.FacebookOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
# AUTHENTICATION_BACKENDS = [
# 'social_core.backends.facebook.FacebookOAuth2',
# 'django.contrib.auth.backends.ModelBackend',
# ]
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
SOCIAL_AUTH_FACEBOOK_KEY = '2773352989611930' # App ID
SOCIAL_AUTH_FACEBOOK_SECRET = 'a5ceb9b7b928c55fd1f7922dc3737a33' # App Secret
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_URL = 'logout'
LOGOUT_REDIRECT_URL = 'login'
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [STATIC_DIR,]
MEDIA_URL = '/media/'
MEDIA_ROOT = Path(BASE_DIR, 'media') | [
"sylvia.anitha@gmail.com"
] | sylvia.anitha@gmail.com |
dd17276b517f0934344b4de656f26eca45e56c03 | df9b342f71cee4306c52ee5e29d105f8712d7439 | /BOJ/ํ๋
ธ์ดํ/๋ค๋ฅธ์ฌ๋.py | b447ae5dea94644e425cae796590c5652794ad21 | [] | no_license | qkreltms/problem-solvings | a3fbd93d5664830761c70ef6a476e94ada399af0 | cade3fc738c0b7b40ae4bf0385fdd552313ad5a1 | refs/heads/master | 2023-07-19T08:17:48.580833 | 2021-08-31T08:45:57 | 2021-08-31T08:45:57 | 136,621,853 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 187 | py | def f(n, a, b, c):
if(n == 1):
print(a, c, sep = " ")
else:
f(n-1, a, c, b)
f(1, a, b, c)
f(n-1, b, a, c)
n = int(input())
print(2**n-1)
if(n <= 20):
f(n, 1, 2, 3)
| [
"junghooncentralpark@gmail.com"
] | junghooncentralpark@gmail.com |
f7c6093d2fd3a6442a646474189a09aedb766eb7 | 7238d663f4cdc175e3e5363aa2e44040b6c6ae69 | /optalg/constrained/penalty/penalty_base.py | 74012a4941e483babfc4f6f5db15db19f4117259 | [
"MIT"
] | permissive | ShkalikovOleh/OptAlg | c3d7c4fe5fd3bfdcd871bf432f9fc6c5a8f7aaf1 | 03399eee50203dcba834a4d9ab48751142a6de2b | refs/heads/master | 2023-06-01T17:17:34.930796 | 2021-02-22T14:57:15 | 2021-02-22T14:57:15 | 295,201,186 | 0 | 3 | null | null | null | null | UTF-8 | Python | false | false | 2,240 | py | import numpy as np
from typing import Callable, List, Generator
from abc import abstractmethod
from ...optimizer import OptimizeResult, Optimizer
class PenaltyBase(Optimizer):
def __init__(self, unc_optimizer: Optimizer, epsilon: float) -> None:
self._unc_opt = unc_optimizer
self._epsilon = epsilon
@abstractmethod
def _get_P(self, xk: np.ndarray, eq_constraints: List[Callable],
ineq_constraints: List[Callable]) -> Callable:
pass
def optimize(self, f: Callable, x0: np.ndarray,
eq_constraints: List[Callable] = [],
ineq_constraints: List[Callable] = []) -> OptimizeResult:
xk = x0
iter = 0
def P(x):
return self._epsilon + 1 # for initial check
while np.linalg.norm(P(xk)) > self._epsilon:
P = self._get_P(xk, eq_constraints, ineq_constraints)
def F(x):
return f(x) + P(x)
res = self._unc_opt.optimize(F, xk)
xk = res.x
iter += 1
res = OptimizeResult(f=f, x=xk,
n_iter=iter,
equality_constraints=eq_constraints,
inequality_constraints=ineq_constraints)
return res
class CustomizablePenaltyBase(PenaltyBase):
def __init__(self, unc_optimizer: Optimizer,
r_eq_generator: Generator[float, None, None],
r_ineq_generator: Generator[float, None, None],
eq_penalfty_func: Callable,
ineq_penalty_func: Callable,
epsilon: float) -> None:
super().__init__(unc_optimizer, epsilon)
self._eq_penalty_func = eq_penalfty_func
self._ineq_penalty_func = ineq_penalty_func
self._r_eq_gen = r_eq_generator
self._r_ineq_gen = r_ineq_generator
def optimize(self, f: Callable, x0: np.ndarray,
eq_constraints: List[Callable] = [],
ineq_constraints: List[Callable] = []) -> OptimizeResult:
self._r_eq_generator = self._r_eq_gen()
self._r_ineq_generator = self._r_ineq_gen()
return super().optimize(f, x0, eq_constraints, ineq_constraints)
| [
"Shkalikov.Oleh@outlook.com"
] | Shkalikov.Oleh@outlook.com |
e55e764e483c897c03080652a54fd3f5d6bd486d | 6e1e9b57f179c7091377dca0ffaabf087272e569 | /simprocs/rotate-simp.py | 14692da460626c1e4300a41fdd57fb33feff0cec | [] | no_license | rossduncan/quanto-topt | 4f8689051b613b3f9042f91e6e442dbca484a8b7 | 54c4003021fbe6f198ce01333a6da9059127e4d5 | refs/heads/master | 2020-03-23T19:47:14.906018 | 2018-08-20T09:13:26 | 2018-08-20T09:13:26 | 142,002,177 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,130 | py | from quanto.util.Scripting import *
simps0 = load_rules([
"rules/axioms/red_copy", "rules/axioms/green_copy",
"rules/axioms/red_sp", "rules/axioms/green_sp",
"rules/axioms/hopf",
"rules/axioms/red_scalar", "rules/axioms/green_scalar",
"rules/axioms/red_loop", "rules/axioms/green_loop"])
simps = simps0 + load_rules(["rules/axioms/green_id", "rules/axioms/red_id"])
green_id_inv = load_rule("rules/axioms/green_id").inverse()
red_id_inv = load_rule("rules/axioms/red_id").inverse()
rotate = load_rule("rules/theorems/rotate_targeted")
def num_boundary_X(g):
return len([v for v in verts(g)
if g.isBoundary(v) and g.isAdjacentToType(v, 'X')])
def next_rotation_Z(g):
vs = [(g.arity(v),v) for v in verts(g)
if g.typeOf(v) == 'Z' and
vertex_angle_is(g, v, '0') and
not g.isAdjacentToBoundary(v)]
if (len(vs) == 0): return None
else: return min(vs)[1]
simproc = (
REDUCE(simps) >>
REDUCE_METRIC(green_id_inv, num_boundary_X) >>
REPEAT(
REDUCE_TARGETED(rotate, "v10", next_rotation_Z) >>
REDUCE(simps0)
) >>
REDUCE(simps)
)
register_simproc("rotate-simp", simproc)
| [
"dr.ross.duncan@gmail.com"
] | dr.ross.duncan@gmail.com |
50082455f3b90bbf2d729128692dbe14bc977d1b | 7f8c82b43980e7d0c3c618afd9d520c533e6c1e2 | /qmsolve/visualization/complex_slider_widget.py | 7d482dc115c12b5b2854574ee9cb0e58ef371dcc | [
"BSD-3-Clause"
] | permissive | lukepolson/qmsolve | fe62af121111e15ec9d5414239ed76a97898254f | 373dbc6349509984139a59746acb140b48414fdf | refs/heads/main | 2023-06-28T17:38:21.985569 | 2021-07-26T19:53:45 | 2021-07-26T19:53:45 | 392,483,308 | 9 | 0 | BSD-3-Clause | 2021-08-03T23:22:07 | 2021-08-03T23:22:07 | null | UTF-8 | Python | false | false | 1,824 | py | import matplotlib.pyplot as plt
from matplotlib import widgets
class ComplexSliderWidget(widgets.AxesWidget):
"""
A circular complex slider widget for manipulating complex
values.
References:
- https://matplotlib.org/stable/api/widgets_api.
- https://github.com/matplotlib/matplotlib/blob/
1ba3ff1c273bf97a65e19892b23715d19c608ae5/lib/matplotlib/widgets.py
"""
def __init__(self, ax, angle, r, animated=False):
line, = ax.plot([angle, angle], [0.0, r], linewidth=2.0)
super().__init__(ax)
self._rotator = line
self._is_click = False
self.animated = animated
self.update = lambda x, y: None
self.connect_event('button_press_event', self._click)
self.connect_event('button_release_event', self._release)
self.connect_event('motion_notify_event', self._motion)
def get_artist(self):
return self._rotator
def _click(self, event):
self._is_click = True
self._update_plots(event)
def _release(self, event):
self._is_click = False
def on_changed(self, update):
self.update = update
def _motion(self, event):
self._update_plots(event)
def _update_plots(self, event):
if (self._is_click and event.xdata != None
and event.ydata != None
and event.x >= self.ax.bbox.xmin and
event.x < self.ax.bbox.xmax and
event.y >= self.ax.bbox.ymin and
event.y < self.ax.bbox.ymax
):
phi, r = event.xdata, event.ydata
if r < 0.2:
r = 0.0
self.update(phi, r)
self._rotator.set_xdata([phi, phi])
self._rotator.set_ydata([0.0, r])
if not self.animated:
event.canvas.draw()
| [
"noreply@github.com"
] | lukepolson.noreply@github.com |
fbe5bbf72cfc77e0e0a289bbf4f3e02ff45f6c7d | c421330a5e03df01aa4ec9dc1c60dd2b9c514423 | /movieproject/movieapp/urls.py | 29e716810f30b03d4a9e060a55a905cdf4dcd5f1 | [] | no_license | sayanth123/movieapp | 16051774cbb1766c513a3e2b28c45b905c45c4d0 | f4e50a7f1b7441390ab234c11a13e1d989ec3118 | refs/heads/master | 2023-05-06T05:41:09.735871 | 2021-05-26T12:46:47 | 2021-05-26T12:46:47 | 371,027,811 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 328 | py | from . import views
from django.urls import path
app_name='movieapp'
urlpatterns = [
path('', views.index,name='index'),
path('movie/<int:movie_id>/', views.detail,name='detail'),
path('add/', views.add,name='add'),
path('update/<int:id>/', views.update,name='update'),
path('delete/<int:id>/', views.delete,name='delete'),
]
| [
"you@example.com"
] | you@example.com |
ed240a9b8c320c845e868db9965f90f251a6047b | c80b2398e6f8b7342329cabb01082115d262b3bb | /app/admin/views.py | 14a3364618164dd8e7a5186143f51e38867c6886 | [] | no_license | dylanchu/flask-web-frame | bd8a25621aba442dcc87cb4f3c3e26cccbf0f890 | 03770cabba922008ba5d2934bd9f833a2ac55c1a | refs/heads/master | 2020-04-25T23:53:15.705042 | 2019-02-28T18:29:04 | 2019-02-28T18:29:04 | 173,159,886 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 211 | py | #!/usr/bin/env python3
# coding: utf-8
#
# Created by dylanchu on 19-2-28
from . import admin
from flask_login import login_required
@admin.route('/')
@login_required
def index():
return 'admin homepage'
| [
"chdy.uuid@gmail.com"
] | chdy.uuid@gmail.com |
15b1866beb9e28d3493396f5db8601976d2c9d31 | 7d88d4c9b692821ad23bf167409de70beacddb3a | /proj/mystorage/migrations/0001_initial.py | d2fe50e5485c7cce641711ecff1396f4f0b96c5d | [] | no_license | gbwlxhd97/django_rest_framework | 0908886dea8d7f76ea59f8c90838b7164e3d7cf9 | b3858ce5fc47a6d88e940bd23ce248b236de0491 | refs/heads/master | 2023-02-14T17:02:04.102545 | 2021-01-06T10:59:14 | 2021-01-06T10:59:14 | 326,606,731 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 796 | py | # Generated by Django 3.1.4 on 2020-12-23 10:57
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Essay',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=30)),
('body', models.TextField()),
('author', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"gbwlxhd97@naver.com"
] | gbwlxhd97@naver.com |
34032886024fad16ca26c435818ded9f868bbab5 | 8f55f023b692084bb735a2ab7c303a3115647a82 | /CodeEval/roman-numerals.py | 38eb9ba464fd62088bde064aa1593d760ab7a48d | [] | no_license | JnrMasero/Hackbook | e48a3d8d16a0a338f7da7c23e1a31b221ca51858 | 766d17a6ce84da54ddb2d9a63a10321276488f99 | refs/heads/master | 2020-06-04T21:15:02.719885 | 2015-03-30T18:35:24 | 2015-03-30T18:35:24 | 32,822,061 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,652 | py | #!/usr/bin/env python
"""
Roman Numerals
Challenge Description:
Many persons are familiar with the Roman numerals for relatively small numbers. The symbols I (capital i), V, X, L, C, D, and M represent the decimal values 1, 5, 10, 50, 100, 500 and 1000 respectively. To represent other values, these symbols, and multiples where necessary, are concatenated, with the smaller-valued symbols written further to the right. For example, the number 3 is represented as III, and the value 73 is represented as LXXIII. The exceptions to this rule occur for numbers having units values of 4 or 9, and for tens values of 40 or 90. For these cases, the Roman numeral representations are IV (4), IX (9), XL (40), and XC (90). So the Roman numeral representations for 24, 39, 44, 49, and 94 are XXIV, XXXIX, XLIV, XLIX, and XCIV, respectively.
Write a program to convert a cardinal number to a Roman numeral.
Input sample:
Your program should accept as its first argument a path to a filename. Input example is the following
159
296
3992
Input numbers are in range [1, 3999]
Output sample:
Print out Roman numerals.
CLIX
CCXCVI
MMMCMXCII
"""
import sys
conv = {
1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC',
100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'
}
def decimal_to_roman(n):
s = ''
if n < 5000:
for k, v in sorted(conv.items(), reverse = True):
while n >= k:
s += v
n -= k
return s
if __name__ == '__main__':
with open(sys.argv[1]) as f:
for line in f:
print(decimal_to_roman(int(line)))
| [
"cmsllince@gmail.com"
] | cmsllince@gmail.com |
63b6f5beff30f469db12c028c0a1fefdad4c79f5 | d507d0846902e0012a4b2a0aaaea1cbbdb21db46 | /supervisely_lib/annotation/json_geometries_map.py | 394b5674ece0eb53c38ebf1dfc6160b66988b185 | [] | no_license | wpilibsuite/supervisely | a569fdc0d5e5f2fb912f32beab8f3fedb277504e | 19805ca9b2bd20e31d6d41a99dc37dc439bc257a | refs/heads/master | 2022-09-09T02:32:54.883109 | 2020-06-01T20:55:49 | 2020-06-01T20:55:49 | 267,916,361 | 2 | 3 | null | 2020-06-03T13:59:56 | 2020-05-29T17:27:30 | Python | UTF-8 | Python | false | false | 843 | py | # coding: utf-8
from supervisely_lib.geometry.bitmap import Bitmap
from supervisely_lib.geometry.cuboid import Cuboid
from supervisely_lib.geometry.point import Point
from supervisely_lib.geometry.polygon import Polygon
from supervisely_lib.geometry.polyline import Polyline
from supervisely_lib.geometry.rectangle import Rectangle
from supervisely_lib.geometry.graph import GraphNodes
from supervisely_lib.geometry.any_geometry import AnyGeometry
from supervisely_lib.geometry.cuboid_3d import Cuboid3d
_INPUT_GEOMETRIES = [Bitmap, Cuboid, Point, Polygon, Polyline, Rectangle, GraphNodes, AnyGeometry, Cuboid3d]
_JSON_SHAPE_TO_GEOMETRY_TYPE = {geometry.geometry_name(): geometry for geometry in _INPUT_GEOMETRIES}
def GET_GEOMETRY_FROM_STR(figure_shape: str):
geometry = _JSON_SHAPE_TO_GEOMETRY_TYPE[figure_shape]
return geometry
| [
"austinshalit@gmail.com"
] | austinshalit@gmail.com |
ccba15b353e7a0f74efe1ed58f94f3204f09d443 | 9d25079774ac51a63c54eb0fd5e56cf80f4ad49a | /CarSalon_Project/CarSalon_Project/wsgi.py | 2ef776af9770f14219ebaa34e684b57e987c53fc | [
"MIT"
] | permissive | KSD9/Car-Salon-Web-App | 9dedb8c0f908b35a0f920e3b236903d240ea17aa | e9d28053a5688176709850d406bebdead4f8631f | refs/heads/master | 2020-03-23T19:29:43.034324 | 2020-02-24T17:38:01 | 2020-02-24T17:38:01 | 141,982,315 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 409 | py | """
WSGI config for CarSalon_Project 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.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CarSalon_Project.settings")
application = get_wsgi_application()
| [
"evtimov9@gmail.com"
] | evtimov9@gmail.com |
c7bbc1477580b16be83f8c34d972bda810c70fb8 | d363b47b111aa47f7007ff10657a30143e083196 | /hw1/task_2a.py | 84c779708bf5c33d2361fe2e1a99617736d53a46 | [] | no_license | yangyang-pro/2AMU20-Assignments | 3ed47e782dc7a3516b13e8c0fa5bd7f77d4e99fe | 9ee3dc34db805cf6500eb82566303d2d09c536eb | refs/heads/main | 2023-06-02T17:04:36.754885 | 2021-06-19T14:36:10 | 2021-06-19T14:36:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,336 | py | from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import math
def monte_carlo_simulation():
np.random.seed(54321)
nmax = 10000
# number of samples
n_samples = np.arange(100, nmax + 100, 100)
normalizing_constant = math.exp(4) / (1 + 4 + (16 / 2) + (64 / 6) + (256 / 24))
print('M =', normalizing_constant)
inputs = [0, 1, 2, 3, 4]
probs = [normalizing_constant * (4 ** k) * math.exp(-4) / math.factorial(k) for k in inputs]
# To store each approximation of the expected value
mu_estim = []
mu_true = sum([i * probs[i] for i in inputs])
my_distribution = stats.rv_discrete(values=(inputs, probs))
for n in tqdm(n_samples):
# Obtain a sample of size n
# sample contains the x_i's
sample = my_distribution.rvs(size=n)
# Calculate the average of the sample
mu_estim.append(sample.mean())
# Create the convergence plot
plt.plot(n_samples, mu_estim, '-g', alpha=0.5)
plt.hlines(y=mu_true, xmin=n_samples[0],
xmax=n_samples[-1], colors='blue', lw=6.5)
plt.title(f'Convergence to $Np = ${mu_true}')
plt.xlabel('Sample size')
plt.ylabel('$E[X]$')
plt.xticks(rotation=90)
plt.grid()
plt.show()
if __name__ == '__main__':
monte_carlo_simulation()
| [
"yangyang.tue@gmail.com"
] | yangyang.tue@gmail.com |
996df35200d2adc6b93a637fd11c0fe8b8974d26 | f576f0ea3725d54bd2551883901b25b863fe6688 | /sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/receipt/_claims_models.py | 9859688f266bb0aff4d28d6e620d07a0fd31064e | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | permissive | Azure/azure-sdk-for-python | 02e3838e53a33d8ba27e9bcc22bd84e790e4ca7c | c2ca191e736bb06bfbbbc9493e8325763ba990bb | refs/heads/main | 2023-09-06T09:30:13.135012 | 2023-09-06T01:08:06 | 2023-09-06T01:08:06 | 4,127,088 | 4,046 | 2,755 | MIT | 2023-09-14T21:48:49 | 2012-04-24T16:46:12 | Python | UTF-8 | Python | false | false | 4,138 | py | # ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
"""Models for application claims."""
from typing import Any, Dict, Optional, Union
from dataclasses import dataclass
@dataclass
class LedgerEntryClaim:
"""
LedgerEntryClaim represents an Application Claim derived from ledger entry data.
:keyword protocol: The protocol used to compute the claim.
:paramtype protocol: str
:keyword collectionId: The collection ID of the ledger entry.
:paramtype collectionId: str
:keyword contents: The contents of the ledger entry.
:paramtype contents: str
:keyword secretKey: The secret key used to compute the claim digest.
:paramtype secretKey: str
"""
protocol: str
collectionId: str
contents: str
secretKey: str
@classmethod
def from_dict(cls, ledger_entry_claim_dict: Dict[str, Any]):
"""Create a new instance of this class from a dictionary.
:param dict[str, any] ledger_entry_claim_dict: The dictionary representation of the ledger entry claim.
:return: A new instance of this class corresponding to the provided dictionary.
:rtype: LedgerEntryClaim
"""
return cls(**ledger_entry_claim_dict)
@dataclass
class ClaimDigest:
"""
ClaimDigest represents an Application Claim in digested form.
:keyword protocol: The protocol used to compute the claim.
:paramtype protocol: str
:keyword value: The digest of the claim.
:paramtype value: str
"""
protocol: str
value: str
@classmethod
def from_dict(cls, ledger_entry_claim_dict: Dict[str, Any]):
"""Create a new instance of this class from a dictionary.
:param dict[str, any] ledger_entry_claim_dict: The dictionary representation of the claim digest.
:return: A new instance of this class corresponding to the provided dictionary.
:rtype: ClaimDigest
"""
return cls(**ledger_entry_claim_dict)
@dataclass
class ApplicationClaim:
"""
ApplicationClaim represents a claim of a ledger application.
:keyword kind: The kind of the claim.
:paramtype kind: str
:keyword ledgerEntry: The ledger entry claim.
:paramtype ledgerEntry: Optional[Union[Dict[str, Any], LedgerEntryClaim]]
:keyword digest: The claim digest object.
:paramtype digest: Optional[Union[Dict[str, Any], ClaimDigest]]
"""
kind: str
ledgerEntry: Optional[LedgerEntryClaim] = None
digest: Optional[ClaimDigest] = None
def __init__(
self,
kind: str,
ledgerEntry: Optional[Union[Dict[str, Any], LedgerEntryClaim]] = None,
digest: Optional[Union[Dict[str, Any], ClaimDigest]] = None,
**kwargs: Any
):
"""
:keyword kind: The kind of the claim.
:paramtype kind: str
:keyword ledgerEntry: The ledger entry claim.
:paramtype ledgerEntry: Optional[Union[Dict[str, Any], LedgerEntryClaim]]
:keyword digest: The claim digest object.
:paramtype digest: Optional[Union[Dict[str, Any], ClaimDigest]]
"""
self.kind = kind
if ledgerEntry:
if isinstance(ledgerEntry, LedgerEntryClaim):
self.ledgerEntry = ledgerEntry
else:
self.ledgerEntry = LedgerEntryClaim.from_dict(ledgerEntry)
else:
self.ledgerEntry = None
if digest:
if isinstance(digest, ClaimDigest):
self.digest = digest
else:
self.digest = ClaimDigest.from_dict(digest)
else:
self.digest = None
self.kwargs = kwargs
@classmethod
def from_dict(cls, claim_dict: Dict[str, Any]):
"""Create a new instance of this class from a dictionary.
:param dict[str, any] claim_dict: The dictionary representation of the application claim.
:return: A new instance of this class corresponding to the provided dictionary.
:rtype: ApplicationClaim
"""
return cls(**claim_dict)
| [
"noreply@github.com"
] | Azure.noreply@github.com |
26e789d7342c17eca74b1517a488156518bd056b | b89a46a1b2eeaf6f32fca4f0adb44185ac85b287 | /hello_world.py | 859dc0728df2ddc8187f097e8d08a456f59cbf38 | [] | no_license | dfarr/domino-evaluation | 42dde7ecb4120569ff96520669da04dc3586c8fc | 932b09ed790db5ce2e1fe179834f6c6371908246 | refs/heads/main | 2023-08-03T17:14:00.676150 | 2021-09-14T20:28:05 | 2021-09-14T20:28:05 | 406,470,617 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 92 | py | print("*************************")
print("Hello World.")
print("*************************")
| [
"david_farr@intuit.com"
] | david_farr@intuit.com |
e4487cea1eed76254a96e7765097286af0eeaa12 | e0a6e2afe5eafd36fd99113e935f35fa2220094e | /main/models.py | 7214cf641da710b045597d4b1549ab1a4dfbc6b9 | [] | no_license | RihardsT/cloud_project_django | 600701a1553cb81e98bfa2c4557150fd3681f75b | 331cac65e2bb80540bdb62183d0ffc9ba63c6fab | refs/heads/master | 2021-01-01T19:22:24.998031 | 2017-08-12T22:06:25 | 2017-08-12T22:06:25 | 98,574,821 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 251 | py | from django.db import models
# Create your models here.
class PageDescription(models.Model):
page_description = models.TextField()
display_on_page = models.CharField(max_length=200)
def __str__(self):
return self.page_description | [
"richitislv@gmail.com"
] | richitislv@gmail.com |
0185c4f4c626389ea2464ebda9f072d8a3b86e50 | 1fe8d4133981e53e88abf633046060b56fae883e | /venv/lib/python3.8/site-packages/tensorflow/python/keras/api/_v2/keras/applications/xception/__init__ 2.py | bf93ae01110de2a54ca5eaeaa25020b85ad82eab | [] | no_license | Akira331/flask-cifar10 | 6c49db8485038731ce67d23f0972b9574746c7a7 | 283e7a2867c77d4b6aba7aea9013bf241d35d76c | refs/heads/master | 2023-06-14T16:35:06.384755 | 2021-07-05T14:09:15 | 2021-07-05T14:09:15 | 382,864,970 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 128 | py | version https://git-lfs.github.com/spec/v1
oid sha256:bdac5cda377d4d39bccb19a4cdeafc9b8f2a51c4983a1c81f5f33a22b6729864
size 731
| [
"business030301@gmail.com"
] | business030301@gmail.com |
b33a3e9c772fca05363c64395a9fc45615f577a0 | faf5553ccf72d8f147e8462226a286b6e8d61133 | /dim/generators/generate_location.py | 814cdd2076d5ebfcc8bff5370ec8c8aaabe6044e | [
"MIT"
] | permissive | pgesek/ksgmet-etl | 594ba0609e7297a8e4152555c320e6ee197e5f71 | a87d3cc51f04003de96c578deca1e627cd2fc62f | refs/heads/master | 2020-04-16T08:50:10.063547 | 2019-11-06T23:57:34 | 2019-11-06T23:57:34 | 165,439,986 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 461 | py | #!/usr/bin/python
# coding=utf-8
from string import Template
print('id,x,y,europe')
hours_long = 7 * 24
hours_short = 48
line = Template('$id,$x,$y,$europe')
i = 1
for x_range, y_range, europe in zip([range(252), range(325)], [range(97), range(170)], [True, False]):
for x in x_range:
for y in y_range:
values = dict(id = i, x = x, y = y, europe = europe)
print(line.substitute(values))
i += 1
| [
"pgesek@soldevelo.com"
] | pgesek@soldevelo.com |
5528da26ff17297745c4e882767344421f6747fc | 5da373c7f45b65894804002ef33fd53264d976f9 | /ppim/models/__init__.py | 375413f9f747aca74a305719606c6d34f8708fba | [
"Apache-2.0"
] | permissive | chenhaohan88/Paddle-Image-Models | 55bfafdbb43ef001faa4ea2e53570ab3248e4786 | c80e3423ce57779b3426c3c024f3fc51cdb9d1b7 | refs/heads/main | 2023-04-10T22:52:45.251251 | 2021-04-04T02:20:15 | 2021-04-04T02:20:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 955 | py | # Transformer
# from .tnt import tnt_s, TNT
from .vit import VisionTransformer
from .pit import pit_ti, pit_s, pit_xs, pit_b, pit_ti_distilled, pit_s_distilled, pit_xs_distilled, pit_b_distilled, PoolingTransformer, DistilledPoolingTransformer
from .deit import deit_ti, deit_s, deit_b, deit_b_384, deit_ti_distilled, deit_s_distilled, deit_b_distilled, deit_b_distilled_384, DistilledVisionTransformer
# CNN
# from .dla import dla_34, dla_46_c, dla_46x_c, dla_60, dla_60x, dla_60x_c, dla_102, dla_102x, dla_102x2, dla_169, DLA
from .rexnet import rexnet_1_0, rexnet_1_3, rexnet_1_5, rexnet_2_0, rexnet_3_0, ReXNet
from .repvgg import repvgg_a0, repvgg_a1, repvgg_a2, repvgg_b0, repvgg_b1, repvgg_b2, repvgg_b3, repvgg_b1g2, repvgg_b1g4, repvgg_b2g4, repvgg_b3g4, RepVGG
# from .hardnet import hardnet_68, hardnet_85, hardnet_39_ds, hardnet_68_ds, HarDNet
# Involution
from .rednet import rednet_26, rednet_38, rednet_50, rednet_101, rednet_152, RedNet
| [
"2286040843@qq.com"
] | 2286040843@qq.com |
de9883ebf4e9b195992a3a40d7ed18ada729acc7 | ab1c920583995f372748ff69d38a823edd9a06af | /hw/day9/day9_hw3.py | 16f8486856923f4b36925b819f6988b3d58adbad | [] | no_license | adyadyat/pyprojects | 5e15f4e33892f9581b8ebe518b82806f0cd019dc | c8f79c4249c22eb9e3e19998d5b504153faae31f | refs/heads/master | 2022-11-12T16:59:17.482303 | 2020-07-04T09:08:18 | 2020-07-04T09:08:18 | 265,461,663 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 513 | py | for i in range(1,9):
for j in range(8,i,-1):
print(' ',end='')
for k in range(1,i+1):
print(i,end='')
for x in range(2,i+1):
print(i,end='')
print()
for i in range(7,0,-1):
for j in range(i,8):
print(' ',end='')
for k in range(i,0,-1):
print(i,end='')
for x in range(i,1,-1):
print(i,end='')
print()
'''
1
222
33333
4444444
555555555
66666666666
7777777777777
888888888888888
7777777777777
66666666666
555555555
4444444
33333
222
1
'''
| [
"omorbekov.a@gmail.com"
] | omorbekov.a@gmail.com |
cd9da7141673112b048d4e7cd9ccb7e2816784a6 | fdb643ae8ed2f1d67ea37c02ca4c1d95360bcc9c | /BirthdayWish_day32/main.py | cb056bf4209cf8389ff85e120412db7022f67753 | [] | no_license | katytran/100daysPython | 5013ea5adff7122e70723ab6950fbf6bbadcf261 | c11094cee58b5a884323bb0f9f1ef1a62edb50cb | refs/heads/master | 2023-04-18T03:51:06.676741 | 2021-04-18T06:06:38 | 2021-04-18T06:06:38 | 358,255,020 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,496 | py | ##################### Extra Hard Starting Project ######################
# 1. Update the birthdays.csv
# 2. Check if today matches a birthday in the birthdays.csv
# 3. If step 2 is true, pick a random letter from letter templates and replace the [NAME] with the person's actual name from birthdays.csv
# 4. Send the letter generated in step 3 to that person's email address.
import pandas
import datetime as dt
import random
import smtplib
# Get today day and month
dt = dt.datetime.today()
current_day = dt.day
current_month = dt.month
birthday_data = pandas.read_csv("birthdays.csv")
for index, row in birthday_data.iterrows():
if row['day'] == current_day and row['month'] == current_month:
random_letter = random.randint(1, 3)
with open(f"./letter_templates/letter_{random_letter}.txt", "r") as letter:
content = letter.read().replace("[NAME]", row['name'])
receiver_email = row['email']
gmail_user = 'oppajeongpython@gmail.com'
gmail_password = 'jeongpython123'
sent_from = gmail_user
to = receiver_email
subject = 'I love you so much!!!'
body = content
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, to, subject, body)
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(user=gmail_user, password=gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print('Email sent!')
except:
print('Something went wrong...')
| [
"CAT"
] | CAT |
42466fcb31699a41b42c3899872672bd5caf2acf | 0f800790db465cb9d676edbf47d4a2d46e5c2d6b | /ModelFunction/SVD.py | e6bb724b8aaa80569395d3aa638438b620cb6c9f | [] | no_license | AlinaLei/RecommendCQ | 54204f3a5ab5990ee6e06e61e7dccc2c23d6d65e | 9671ead4b0a2f81cbfc5eb1d34a872d081fb64ea | refs/heads/master | 2020-05-26T08:33:00.210029 | 2019-05-28T07:48:32 | 2019-05-28T07:48:32 | 188,169,034 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,549 | py | # !/usr/bin/env python3
# -*- coding:utf8 -*-
import numpy as np
import pandas as pd
import math
#ๅบไบๅ
ฑๅๅๆฌข็ฉๅ่ฎก็ฎ็ธไผผๅบฆ
class SVDCommonLike():
def __init__(self,df):
self.df = df
###ๆ็
ง็จๆทIDๆฅ่ฟ่ก็ฉๅ็ไธไธชๆฑๆป๏ผ็ๆไธไธช็จๆทๅ็ปๅ็็ฉๅๅ่กจ
def create_item_list_by_user(self, user_name, item_name):
"""
:param df: DataFrameๆฐๆฎๆบ
:param user_name: ๆ็
ง็จๆทๅๅๆฅๅๅ
:param item_name: ๅฏนๅบ็็ฉๅๅๅๆฏๅฆๆฏ็ฉๅID
:return : ่ฟๅ็ปๆไธบๆ็
ง็จๆทID ๅๅฏนๅบ็็ฉๅIDๅ่กจ็ๅญๅ
ธๅฝขๅผ
"""
res = {}
item_list = []
for i in self.df.itertuples():
res.setdefault(getattr(i, user_name), []).append(getattr(i, item_name))
for i in res.keys():
item_list.append(res[i])
return item_list
def create_item_matrics(self, items, item_len, item_name_list):
"""
:param items ็ฉๅ้ๅ
:param item_len ๆป็ฉๅๆฐ
:return : ่ฟๅ็ฉๅๅ็ฐ็ฉ้ต๏ผๆญคๅคๅฎ้
่ฟๅไธบDataFrame็ฑปๅ
"""
item_matrix = pd.DataFrame(np.zeros((item_len, item_len)), index=item_name_list, columns=item_name_list)
for im in items:
for i in range(len(im)):
# print(i)
for j in range(len(im) - i):
item_matrix.loc[im[i], im[j + i]] += 1
item_matrix.loc[im[j + i], im[i]] = item_matrix.loc[im[i], im[j + i]]
return item_matrix
def item_similarity(self,item_matrix):
"""
่ฎก็ฎ็ฉๅ็ธไผผๅบฆ็ฉ้ต ่ฟ้็่ฎก็ฎ็ฉๅ็ธไผผๅบฆๅ
ฌๅผไธบ๏ผ
ๅๅญไธบๅๆถ่ดญไนฐ็ฉๅiๅj็็จๆทๆฐ๏ผๅๆฏไธบ่ดญไนฐ็ฉๅi็็จๆทๆฐไธ่ดญไนฐ็ฉๅj็็จๆทๆฐ็ไน็งฏๅผๆ นๅท
:param item_matrix: ็ฉๅๅ็ฐ็ฉ้ต
:return: ็ฉๅ็ธไผผๅบฆ็ฉ้ต๏ผไธบDataFrame็ฑปๅ
"""
res = pd.DataFrame(np.zeros(item_matrix.shape), index=item_matrix.index, columns=item_matrix.columns)
for i in range(item_matrix.shape[0]):
for j in range(item_matrix.shape[0] - i):
res.iloc[i, j + i] = round(
item_matrix.iloc[i, j + i] / math.sqrt(item_matrix.iloc[i, i] * item_matrix.iloc[j + i, j + i]),
4) # ไฟ็ๅไฝๅฐๆฐ
res.iloc[j + i, i] = res.iloc[i, j + i]
return res
##็ๆ็จๆทๅฏน็ฉๅ็่ฏๅ่กจ
def user_item_score(self, user_name, item_name, score_name):
"""
:param df:ๆฐๆฎๆบ
:param user_name: ็จๆทๅๅ
:param item_name: ็ฉๅๅๅ
:param score_name: ่ฏๅๅๅ
:return : ่ฟๅ็จๆทๅฏน็ฉๅ็่ฏๅ็ฉ้ต,ๆญคๅคๅฎ้
่ฟๅไธบDataFrame็ฑปๅ,่กไธบ็จๆท๏ผๅไธบitem
"""
user_names = self.df[user_name].unique()
item_names = self.df[item_name].unique()
user_n = len(user_names)
item_n = len(item_names)
zero_test = pd.DataFrame(np.zeros((user_n, item_n)), index=user_names, columns=item_names)
for i in self.df.itertuples():
zero_test.loc[getattr(i, user_name), getattr(i, item_name)] = getattr(i, score_name)
return zero_test
def base_cosine_similarity(self,item_matrix,user_score):
"""
่ฟ้ๅผๅ
ฅ็จๆท่ฏๅๆฐๆฎ๏ผ่ฟ่กๅบไบไฝๅผฆ็็ธไผผๅบฆ่ฎก็ฎ
ๅๅญไธบ็จๆทkๅฏน็ฉๅi็่ฏๅไธ็ฉๅj็่ฏๅ็ไน็งฏ่ฟ่ก็ดฏๅ ๆ็
ง็จๆทๆฅ๏ผๅๆฏไธบ็จๆทkๅฏน็ฉๅi็่ฏๅ่ฏๅ็ดฏๅ ๅผๆ นๅทไนไปฅ็จๆทkๅฏน็ฉๅj็่ฏๅ่ฏๅ็ดฏๅ ๅผๆ นๅท
:param item_matrix: ็ฉๅๅ็ฐ็ฉ้ต
:param user_score: ็จๆท่ฏๅ็ฉ้ต
:return res: ๅบไบ่ฏๅ็ฉ้ต็ ็ธไผผๅบฆ็ฉ้ต
"""
res = pd.DataFrame(np.zeros(item_matrix.shape), index=item_matrix.index, columns=item_matrix.columns)
sum_score = lambda x, y: sum(x*y)
for i in range(item_matrix.shape[0]):
for j in range(item_matrix.shape[0] - i):
result1 = 0.0
result2 = 0.0
result3 = 0.0
#print('columns is :',item_matrix.columns[i])
result1 += sum_score(user_score.loc[:,item_matrix.columns[i]] ,user_score.loc[:,item_matrix.columns[j+i]])
result2 += sum_score(user_score.loc[:,item_matrix.columns[i]] ,user_score.loc[:,item_matrix.columns[i]])
result3 += sum_score(user_score.loc[:,item_matrix.columns[j+i]] ,user_score.loc[:,item_matrix.columns[j+i]])
res.iloc[i, j + i] =round( result1 /( math.sqrt(result2)* math.sqrt(result3)),4) # ไฟ็ๅไฝๅฐๆฐ
res.iloc[j + i, i] = res.iloc[i, j + i]
return res
def base_cosine_alpha_similarity(self,item_matrix,user_score,alpha=0.3):
"""
่ฟ้ๅผๅ
ฅ็จๆท่ฏๅๆฐๆฎๅ็ญ้จ็ฉๅๆฉ็ฝๆกไปถ๏ผ
ๅๅญไธบ็จๆทkๅฏน็ฉๅi็่ฏๅไธ็ฉๅj็่ฏๅ็ไน็งฏ่ฟ่ก็ดฏๅ ๆ็
ง็จๆทๆฅ๏ผๅๆฏไธบ็จๆทkๅฏน็ฉๅi็่ฏๅ่ฏๅ็ดฏๅ ๅผๆ นๅทไนไปฅ็จๆทkๅฏน็ฉๅj็่ฏๅ่ฏๅ็ดฏๅ ๅผๆ นๅท
:param item_matrix: ็ฉๅๅ็ฐ็ฉ้ต
:param user_score: ็จๆท่ฏๅ็ฉ้ต
:return res: ๅบไบ่ฏๅ็ฉ้ต็ ็ธไผผๅบฆ็ฉ้ต
"""
res = pd.DataFrame(np.zeros(item_matrix.shape), index=item_matrix.index, columns=item_matrix.columns)
sum_score = lambda x, y: sum(x * y)
for i in range(item_matrix.shape[0]):
for j in range(item_matrix.shape[0] - i):
result1 = 0.0
result2 = 0.0
result3 = 0.0
# print('columns is :',item_matrix.columns[i])
result1 += sum_score(user_score.loc[:, item_matrix.columns[i]],
user_score.loc[:, item_matrix.columns[j + i]])
result2 += sum_score(user_score.loc[:, item_matrix.columns[i]],
user_score.loc[:, item_matrix.columns[i]])
result3 += sum_score(user_score.loc[:, item_matrix.columns[j + i]],
user_score.loc[:, item_matrix.columns[j + i]])
res.iloc[i, j + i] = round(result1 / (math.pow(result2,alpha) * math.pow(result3,1-alpha)), 4) # ไฟ็ๅไฝๅฐๆฐ
res.iloc[j + i, i] = res.iloc[i, j + i]
return res
# ็ๆๆจ่็ปๆ
def get_itemCF(self,item_matrix, user_score,user_id,K,col_name='rank'):
"""
item_matrix: ็ฉๅ็ธไผผๅบฆ็ฉ้ต๏ผDataFrame็ฑปๅ
user_score: ็จๆท่ฏๅ็ฉ้ต๏ผDataFrame็ฑปๅ,ๆไธไธชๆๅฎ็็จๆท็่ฏๅ็ฉ้ต
col_name: ็จๆท็ปๆฐๅๆๅฎ็ๅๅ
k : ็จๆฅๆๅฎ่ฟๅTOP K ไธช็ฉๅ
return: ็จๆทๅฏนๅฏนๅบ็็ฉๅ็ๅ
ด่ถฃๅผ ๅพๅฐ็็ฑปๅไธบDataFrame็ฑปๅ๏ผ
"""
user_score = user_score.loc[user_id, :]
columns = item_matrix.columns
user_score = user_score[columns]
# ่ฟๆปคๆ็จๆทๆพ็ป็่ฟ็็ตๅฝฑ
user_movie = user_score[user_score.values == 0].index
item_matrix = np.mat(item_matrix.as_matrix(columns=None))
user_score = np.mat(user_score.as_matrix(columns=None)).T
result_score = item_matrix * user_score
result = pd.DataFrame(result_score, index=columns, columns=['rating'])
result[col_name] = columns
result = result.sort_values(by='rating', ascending=False)
return result[result[col_name].isin(user_movie)].head(K)
| [
"573493657@qq.com"
] | 573493657@qq.com |
4be2b0914ad2ed119005626ee9b0b65db7b74e16 | a274ef18270b5af1d7c9c92a6183979c7f6ddf8d | /day11.py | d1108e7c3cefacb14c77e26ae93929fcb253f118 | [] | no_license | iownthegame/AdventofCode2020 | cbacddd9d3f5b325aa8e0b88ac3caf148fe0369d | 79de340621a000c44f186c0276da0168c76f9db8 | refs/heads/main | 2023-02-05T16:08:43.921615 | 2020-12-20T20:52:09 | 2020-12-20T20:52:09 | 317,670,651 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,622 | py | def run(filename):
with open(filename) as f:
data = f.read().splitlines()
res = sol(data)
print('ans: %s' % res)
def sol(data):
"""
L.LL.LL.LL
LLLLLLL.LL
L.L.L..L..
LLLL.LL.LL
L.LL.LL.LL
L.LLLLL.LL
..L.L.....
LLLLLLLLLL
L.LLLLLL.L
L.LLLLL.LL
"""
grid = []
# 1st round: change L to #
for line in data:
grid.append([c if c == '.' else '#' for c in line])
cnt = 1
m = len(grid)
n = len(grid[0])
while True:
new_grid = process(grid, m, n)
if new_grid == grid:
break
grid = new_grid
return sum([row.count('#') for row in grid])
def process(grid, m, n):
new_grid = [row[:] for row in grid]
for i in range(m):
for j in range(n):
adj_map = get_adj_map(grid, i, j, m, n)
if grid[i][j] == 'L' and adj_map['#'] == 0:
# empty and there are no occupied seats adjacent to it, the seat becomes occupied.
new_grid[i][j] = '#'
elif grid[i][j] == '#' and adj_map['#'] >= 4:
# occupied and four or more seats adjacent to it are also occupied, the seat becomes empty.
new_grid[i][j] = 'L'
return new_grid
def get_adj_map(grid, i, j, m, n):
dirs = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
table = {'#': 0, 'L': 0, '.': 0}
for x, y in dirs:
if 0 <= i + x < m and 0 <= j + y < n:
table[grid[i + x][j + y]] += 1
return table
if __name__ == '__main__':
# run('input/day11_test')
run('input/day11')
| [
"iownthegame@gmail.com"
] | iownthegame@gmail.com |
adedc2ad8b9085febe0d87f4ffb8d9462786c3be | 8e00311b591f46dd563a26b123a69714745c54f9 | /ScoutFinal.py | 98e500a1947383ade36f806828851d916e9b6c97 | [] | no_license | chaare24/Starcraft-2-bot | 6b6d3e7da269198b214745cd2a3211007bbe6ae4 | 64f46794f3ec7575c0ac550222a0b9c1a03da598 | refs/heads/master | 2020-06-29T14:39:37.361764 | 2018-06-10T06:08:39 | 2018-06-10T06:08:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 27,075 | py | import random
import math
import os.path
import numpy as np
import pandas as pd
from pysc2.agents import base_agent
from pysc2.lib import actions
from pysc2.lib import features
#SOURCES:
#https://github.com/skjb/pysc2-tutorial A pysc2 tutorial
#https://github.com/MorvanZhou/Reinforcement-learning-with-tensorflow A base for our QLearning
#http://mnemstudio.org/path-finding-q-learning-tutorial.htm Learning about QLearning
_NO_OP = actions.FUNCTIONS.no_op.id
_SELECT_POINT = actions.FUNCTIONS.select_point.id
_BUILD_SUPPLY_DEPOT = actions.FUNCTIONS.Build_SupplyDepot_screen.id
_BUILD_BARRACKS = actions.FUNCTIONS.Build_Barracks_screen.id
_TRAIN_MARINE = actions.FUNCTIONS.Train_Marine_quick.id
_TRAIN_REAPER = actions.FUNCTIONS.Train_Reaper_quick.id
_SELECT_ARMY = actions.FUNCTIONS.select_army.id
_ATTACK_MINIMAP = actions.FUNCTIONS.Attack_minimap.id
_MOVE_MINIMAP = actions.FUNCTIONS.Move_minimap.id
_BUILD_ENGBAY = actions.FUNCTIONS.Build_EngineeringBay_screen.id
_BUILD_TURRET = actions.FUNCTIONS.Build_MissileTurret_screen.id
_HARVEST_GATHER = actions.FUNCTIONS.Harvest_Gather_screen.id
_BUILD_REFINERY = actions.FUNCTIONS.Build_Refinery_screen.id
_BUILD_TECHLAB = actions.FUNCTIONS.Build_TechLab_Barracks_quick.id
_PLAYER_RELATIVE = features.SCREEN_FEATURES.player_relative.index
_UNIT_TYPE = features.SCREEN_FEATURES.unit_type.index
_PLAYER_ID = features.SCREEN_FEATURES.player_id.index
_PLAYER_RELATIVE_MINI = features.MINIMAP_FEATURES.player_relative.index
_MINI_VISIBILITY = features.MINIMAP_FEATURES.visibility_map.index
_PLAYER_SELF = 1
_PLAYER_ENEMY = 4
_VISIBLE = 1
_TERRAN_COMMANDCENTER = 18
_TERRAN_SCV = 45
_TERRAN_SUPPLY_DEPOT = 19
_TERRAN_BARRACKS = 21
_TERRAN_TURRET = 23
_TERRAN_ENGBAY = 22
_NEUTRAL_MINERAL_FIELD = 341
_TERRAN_MARINE = 49
_NEUTRAL_VESPENEGEYSER = 342
_TERRAN_REFINERY = 20
_NOT_QUEUED = [0]
_QUEUED = [1]
_SELECT_ALL = [2]
ACTION_DO_NOTHING = 'donothing'
ACTION_BUILD_SUPPLY_DEPOT = 'buildsupplydepot'
ACTION_BUILD_BARRACKS = 'buildbarracks'
ACTION_BUILD_MARINE = 'buildmarine'
ACTION_BUILD_REAPER = 'buildreaper'
ACTION_SCOUT = 'scout'
ACTION_BUILD_ENGBAY = 'buildengineeringbay'
ACTION_BUILD_TURRET = 'buildturret'
ACTION_BUILD_REFINERY = 'buildrefinery'
ACTION_BUILD_TECHLAB = 'buildtechlab'
smart_actions = [
ACTION_DO_NOTHING,
ACTION_BUILD_SUPPLY_DEPOT,
ACTION_BUILD_BARRACKS,
ACTION_BUILD_ENGBAY,
ACTION_BUILD_TURRET,
ACTION_BUILD_REFINERY,
ACTION_BUILD_TECHLAB,
ACTION_BUILD_REAPER
]
# Split scout actions into 16 quadrants to minimize action space
for mm_x in range(0, 64):
for mm_y in range(0, 64):
if (mm_x + 1) % 16 == 0 and (mm_y + 1) % 16 == 0:
smart_actions.append(ACTION_SCOUT + '_' + str(mm_x - 8) + '_' + str(mm_y - 8))
SEE_ENEMY_REWARD = 0.001
NOT_DIE_REWARD = 0.5
REWARDGL = 0
DATA_FILE = 'Scout_data'
# Stolen from https://github.com/MorvanZhou/Reinforcement-learning-with-tensorflow
class QLearningTable:
def __init__(self,actions,learningRate = 0.01, rewardDecay = 0.9, epsilon = 0.9):
self.actions = actions #Table of possible actions
self.learningRate = learningRate
self.gamma = rewardDecay
self.epsilon = epsilon
self.qTable = pd.DataFrame(columns = self.actions, dtype = np.float64) #create a column for each, data type is float
self.forbiddenActions = {} #No forbidden actions to start
def choose_action(self, states, excludedActions = []):
self.stateExist(states) #check to see if the state is in the table and add it if not
self.forbiddenActions[states] = excludedActions #States is a string so this works, i dont know how python works
action = self.qTable.ix[states,:] #string magic, clone all the columns of qTable
for excludedActions in excludedActions:
del action[excludedActions] #delete the excluded actions from action
if np.random.uniform() < self.epsilon:
action = action.reindex(np.random.permutation(action.index)) #Randomly permute the actions
action = action.idxmax() #choose the maximum value over 0
else:
#choose random action
action = np.random.choice(self.actions)
return action
def learn(self,prevState,prevAction,reward,currentState):
if prevState == currentState:
return #If the state hasn't changed do no learning
self.stateExist(currentState)
self.stateExist(prevState)
qPredict = self.qTable.ix[prevState,prevAction]
sRewards = self.qTable.ix[currentState,:]
if currentState in self.forbiddenActions: #if current state is a forbidden action delete all the forbidden state rewards
for excludedAction in self.forbiddenActions[currentState]:
del sRewards[excludedAction]
if currentState != 'terminal':
qTarget = reward + self.gamma * self.qTable.ix[currentState,:].max() #decay
else:
qTarget = reward #at end of game
#update the rewards
self.qTable.ix[prevState,prevAction] += self.learningRate *(qTarget-qPredict) #add in the difference
def stateExist(self,state):
if state not in self.qTable.index:
#If state is not in the qTable append a column at the end of the table and init it to 0
self.qTable = self.qTable.append(pd.Series([0] * (len(self.actions)), index =self.qTable.columns, name=state))
class SmartAgent(base_agent.BaseAgent):
def __init__(self):
super(SmartAgent, self).__init__()
self.qlearn = QLearningTable(actions=list(range(len(smart_actions))))
self.previous_action = None
self.previous_state = None
self.previousSupply = 0
self.stepNum = 0
self.CommandCenterX = None
self.CommandCenterY = None
self.timeTillBase = 0
self.baseFound = False
if os.path.isfile(DATA_FILE + '.gz'):
self.qlearn.qTable = pd.read_pickle(DATA_FILE + '.gz', compression='gzip')
def transformDistance(self, x, x_distance, y, y_distance):
if not self.base_top_left:
return [x - x_distance, y - y_distance]
return [x + x_distance, y + y_distance]
def transformLocation(self, x, y):
if not self.base_top_left:
return [63 - x, 63 - y]
return [x, y]
def splitAction(self, action_id):
smart_action = smart_actions[action_id]
x = 0
y = 0
if '_' in smart_action:
smart_action, x, y = smart_action.split('_')
return (smart_action, x, y)
def foundBase(self,obs):
enemy_y, enemy_x = (obs.observation['minimap'][_PLAYER_RELATIVE_MINI] == _PLAYER_ENEMY).nonzero()
if self.base_top_left and not self.baseFound:
found = False
if 45 in enemy_y and 35 in enemy_x:
found = True
if found and not self.baseFound:
self.baseFound = True
print(self.timeTillBase)
if not self.base_top_left and not self.baseFound:
found = False
if 25 in enemy_y and 20 in enemy_x:
found = True
if found and not self.baseFound:
self.baseFound = True
print(self.timeTillBase)
def step(self, obs):
super(SmartAgent, self).step(obs)
if obs.last():
self.obsLast()
return actions.FunctionCall(_NO_OP, [])
unit_type = obs.observation['screen'][_UNIT_TYPE]
if obs.first():
self.obsFirst(unit_type,obs)
self.foundBase(obs)
self.timeTillBase = self.timeTillBase + 1
#############SETTING UP THE STATE#############
supply_depot_count = self.supplyDepotCount(unit_type)
cc_count = self.commandCenterCount(unit_type)
barracks_count = self.barracksCount(unit_type)
turrets_count = self.turretCount(unit_type)
engbay_count = self.engbayCount(unit_type)
refinery_count = self.refineryCount(unit_type)
supply_used = obs.observation['player'][3]
supply_limit = obs.observation['player'][4]
army_supply = obs.observation['player'][5] # check vs 8 #################
worker_supply = obs.observation['player'][6]
supply_free = supply_limit - supply_used
if self.stepNum == 0: # if this is the first step
self.stepNum += 1
return self.firstStep(unit_type,obs,cc_count,supply_depot_count, worker_supply, barracks_count, engbay_count,
turrets_count, refinery_count, supply_free, army_supply,supply_limit)
elif self.stepNum == 1:
self.stepNum += 1
return self.secondStep(unit_type,obs,cc_count,supply_depot_count, worker_supply, barracks_count, engbay_count,
turrets_count, refinery_count, supply_free, army_supply,supply_limit)
elif self.stepNum == 2:
self.stepNum = 0
return self.thirdStep(unit_type,obs,cc_count,supply_depot_count, worker_supply, barracks_count, engbay_count,
turrets_count, refinery_count, supply_free, army_supply,supply_limit)
return actions.FunctionCall(_NO_OP, [])
def obsLast(self):
global REWARDGL
# print("REWARD VALUE")
#print(REWARDGL)
self.qlearn.learn(str(self.previous_state), self.previous_action, REWARDGL, 'terminal')
self.qlearn.qTable.to_pickle(DATA_FILE + '.gz', 'gzip')
self.previous_action = None
self.previous_state = None
self.stepNum = 0
self.kill_check = 0
self.structure_kill = 0
self.geyser_farm = 0
REWARDGL = 0
return
def obsFirst(self,unit_type,obs):
player_y, player_x = (obs.observation['minimap'][_PLAYER_RELATIVE] == _PLAYER_SELF).nonzero()
self.base_top_left = 1 if player_y.any() and player_y.mean() <= 31 else 0
self.previous_action = None
self.previous_state = None
self.previousSupply = 0
self.structure_kill = 0
self.kill_check = 0
self.stepNum = 0
self.geyser_farm = 0
self.CommandCenterY, self.CommandCenterX = (unit_type == _TERRAN_COMMANDCENTER).nonzero()
self.timeTillBase = 0
self.baseFound = False
return
def firstStep(self,unit_type,obs,cc_count,supply_depot_count, worker_supply, barracks_count, engbay_count,
turrets_count, refinery_count, supply_free, army_supply,supply_limit):
# current state is an array holding all the state values
current_state = self.currentState(cc_count, supply_depot_count, barracks_count, engbay_count, turrets_count,
refinery_count, supply_limit, army_supply)
# marks all the current regions with a 1 where it sees enemies
enemy_squares = self.markEnemies(obs)
for i in range(0, 16):
current_state[i + 8] = enemy_squares[i] # write in enemy squares location into the state
# Dont learn from the first step#
if self.previous_action is not None:
self.learn(unit_type, obs,current_state)
excluded_actions = self.excludeActions(supply_depot_count, worker_supply, barracks_count, engbay_count,
turrets_count, refinery_count, supply_free, army_supply)
rl_action = self.qlearn.choose_action(str(current_state), excluded_actions)
self.previous_state = current_state
self.previous_action = rl_action
smart_action, x, y = self.splitAction(self.previous_action)
self.previousSupply = army_supply
# select SCV for building
if smart_action == ACTION_BUILD_BARRACKS or smart_action == ACTION_BUILD_SUPPLY_DEPOT or smart_action == ACTION_BUILD_TURRET or smart_action == ACTION_BUILD_ENGBAY or smart_action == ACTION_BUILD_REFINERY:
return self.selectSCV(unit_type)
# selecting barracks for making marine units
elif smart_action == ACTION_BUILD_REAPER:
return self.selectBarracks(unit_type)
# selecting marine units for scouting
elif smart_action == ACTION_SCOUT:
if _SELECT_ARMY in obs.observation['available_actions']:
return actions.FunctionCall(_SELECT_ARMY, [_NOT_QUEUED])
return actions.FunctionCall(_NO_OP, [])
def secondStep(self,unit_type,obs,cc_count,supply_depot_count, worker_supply, barracks_count, engbay_count,
turrets_count, refinery_count, supply_free, army_supply,supply_limit):
smart_action, x, y = self.splitAction(self.previous_action) # get the action
if smart_action == ACTION_BUILD_SUPPLY_DEPOT:
return self.buildSupplyDepot(obs, supply_depot_count)
elif smart_action == ACTION_BUILD_BARRACKS:
return self.buildBarracks(obs, barracks_count)
elif smart_action == ACTION_BUILD_ENGBAY:
return self.buildEngbay(obs, engbay_count)
elif smart_action == ACTION_BUILD_REFINERY:
return self.buildRefinery(obs,refinery_count)
elif smart_action == ACTION_BUILD_TURRET:
return self.buildTurret(obs, turrets_count)
elif smart_action == ACTION_BUILD_REAPER:
return self.trainReaper(obs)
elif smart_action == ACTION_SCOUT:
return self.scout(obs,x,y)
return actions.FunctionCall(_NO_OP, [])
def thirdStep(self, unit_type, obs, cc_count, supply_depot_count, worker_supply, barracks_count, engbay_count,
turrets_count, refinery_count, supply_free, army_supply,supply_limit):
smart_action, x, y = self.splitAction(self.previous_action)
if smart_action == ACTION_BUILD_BARRACKS or smart_action == ACTION_BUILD_SUPPLY_DEPOT or smart_action == ACTION_BUILD_TURRET or smart_action == ACTION_BUILD_ENGBAY:
if _HARVEST_GATHER in obs.observation['available_actions']:
self.geyser_farm += 1
if self.geyser_farm % 4 == 0:
unit_y, unit_x = (unit_type == _TERRAN_REFINERY).nonzero()
if unit_y.any():
i = random.randint(0, len(unit_y) - 1)
m_x = unit_x[i]
m_y = unit_y[i]
target = [int(m_x), int(m_y)]
return actions.FunctionCall(_HARVEST_GATHER, [_QUEUED, target])
else:
unit_y, unit_x = (unit_type == _NEUTRAL_MINERAL_FIELD).nonzero()
if unit_y.any():
i = random.randint(0, len(unit_y) - 1)
m_x = unit_x[i]
m_y = unit_y[i]
target = [int(m_x), int(m_y)]
return actions.FunctionCall(_HARVEST_GATHER, [_QUEUED, target])
return actions.FunctionCall(_NO_OP, [])
def currentState(self,cc_count,supply_depot_count,barracks_count,engbay_count,
turrets_count,refinery_count,supply_limit,army_supply):
current_state = np.zeros(24) # Generate array of 22
current_state[0] = cc_count
current_state[1] = supply_depot_count
current_state[2] = barracks_count
current_state[3] = engbay_count
current_state[4] = turrets_count
current_state[5] = refinery_count
current_state[6] = supply_limit
current_state[7] = army_supply
return current_state
def markEnemies(self,obs):
enemy_squares = np.zeros(16)
enemy_y, enemy_x = (obs.observation['minimap'][_PLAYER_RELATIVE_MINI] == _PLAYER_ENEMY).nonzero()
for i in range(0, len(enemy_y)):
y = int(math.ceil((enemy_y[i] + 1) / 16))
x = int(math.ceil((enemy_x[i] + 1) / 16))
enemy_squares[((y - 1) * 4) + (x - 1)] = 1 # mark location of enemy squares
if not self.base_top_left: # Invert the quadrants
enemy_squares = enemy_squares[::-1]
return enemy_squares
def learn(self,unit_type,obs,current_state):
global REWARDGL
unit_y, unit_x = (unit_type == _TERRAN_COMMANDCENTER).nonzero()
enemy_y, enemy_x = (obs.observation['minimap'][_PLAYER_RELATIVE_MINI] == _PLAYER_ENEMY).nonzero()
if enemy_y.any() and unit_y.mean() > 0 and unit_y.mean() < 1000:
xdist = round((unit_x.mean() - enemy_x.mean()) ** 2)
ydist = round((unit_y.mean() - enemy_y.mean()) ** 2)
distance_multiplier = math.sqrt(xdist + ydist)
# print("distance mult", distance_multiplier)
else:
distance_multiplier = 0
killed_units = obs.observation["score_cumulative"][5]
killed_structures = obs.observation["score_cumulative"][6]
killbonus = 0
structure_kill_bonus = 0
if self.kill_check < killed_units:
killbonus = 1
self.kill_check = killed_units
if self.structure_kill < killed_structures:
structure_kill_bonus = 15
self.structure_kill = killed_structures
added_value = len(enemy_x) * SEE_ENEMY_REWARD * distance_multiplier + structure_kill_bonus + killbonus
## army_bonus = army_supply*0.01
REWARDGL += added_value
self.qlearn.learn(str(self.previous_state), self.previous_action, 0, str(current_state))
return
# Returns supply depot count
def excludeActions(self,supply_depot_count,worker_supply,barracks_count,engbay_count,
turrets_count,refinery_count,supply_free,army_supply):
excluded_actions = []
if supply_depot_count == 3 or worker_supply == 0:
excluded_actions.append(1)
# supplydepots = True
if supply_depot_count == 0 or barracks_count == 4 or worker_supply == 0:
excluded_actions.append(2)
# barracks = True
if barracks_count == 0 or engbay_count == 1:
excluded_actions.append(3)
# engbay = True
if engbay_count == 0 or turrets_count == 2:
excluded_actions.append(4)
if turrets_count == 0 or refinery_count == 2:
excluded_actions.append(5)
if supply_free == 0 or barracks_count == 0 or refinery_count == 0:
excluded_actions.append(7)
if army_supply == 0:
for i in range(0, 16):
excluded_actions.append(i + 8)
return excluded_actions
def selectSCV(self,unit_type):
unit_y, unit_x = (unit_type == _TERRAN_SCV).nonzero()
if unit_y.any():
i = random.randint(0, len(unit_y) - 1)
target = [unit_x[i], unit_y[i]]
return actions.FunctionCall(_SELECT_POINT, [_NOT_QUEUED, target])
return actions.FunctionCall(_NO_OP, [])
def selectBarracks(self,unit_type):
barracks_y, barracks_x = (unit_type == _TERRAN_BARRACKS).nonzero()
if barracks_y.any():
i = random.randint(0, len(barracks_y) - 1)
target = [barracks_x[i], barracks_y[i]]
return actions.FunctionCall(_SELECT_POINT, [_SELECT_ALL, target])
return actions.FunctionCall(_NO_OP, [])
def buildSupplyDepot(self,obs,supply_depot_count):
if supply_depot_count < 3 and _BUILD_SUPPLY_DEPOT in obs.observation['available_actions']:
if self.CommandCenterY.any():
global REWARDGL
if supply_depot_count == 0:
target = self.transformDistance(round(self.CommandCenterX.mean()), -35,
round(self.CommandCenterY.mean()), 0)
elif supply_depot_count == 1:
target = self.transformDistance(round(self.CommandCenterX.mean()), -5,
round(self.CommandCenterY.mean()), -32)
elif supply_depot_count == 2:
target = self.transformDistance(round(self.CommandCenterX.mean()), 13,
round(self.CommandCenterY.mean()), 0)
REWARDGL += 5
return actions.FunctionCall(_BUILD_SUPPLY_DEPOT, [_NOT_QUEUED, target])
return actions.FunctionCall(_NO_OP, [])
def buildBarracks(self,obs,barracks_count):
if barracks_count < 4 and _BUILD_BARRACKS in obs.observation['available_actions']:
if self.CommandCenterY.any():
global REWARDGL
if barracks_count == 0:
target = self.transformDistance(round(self.CommandCenterX.mean()), 32,
round(self.CommandCenterY.mean()), -20)
REWARDGL += 2
elif barracks_count == 1:
target = self.transformDistance(round(self.CommandCenterX.mean()), 22,
round(self.CommandCenterY.mean()), -20)
REWARDGL += 2
elif barracks_count == 2:
target = self.transformDistance(round(self.CommandCenterX.mean()), 28,
round(self.CommandCenterY.mean()), -10)
REWARDGL += 2
elif barracks_count == 3:
target = self.transformDistance(round(self.CommandCenterX.mean()), 10,
round(self.CommandCenterY.mean()), 17)
REWARDGL += 4
return actions.FunctionCall(_BUILD_BARRACKS, [_NOT_QUEUED, target])
return actions.FunctionCall(_NO_OP, [])
def buildEngbay(self,obs,engbay_count):
if engbay_count < 1 and _BUILD_ENGBAY in obs.observation['available_actions']:
if self.CommandCenterY.any():
if engbay_count < 1:
global REWARDGL
target = self.transformDistance(round(self.CommandCenterX.mean()), -8,
round(self.CommandCenterY.mean()), 28)
REWARDGL += 5
return actions.FunctionCall(_BUILD_ENGBAY, [_NOT_QUEUED, target])
return actions.FunctionCall(_NO_OP, [])
def buildRefinery(self,obs,refinery_count):
if refinery_count < 2 and _BUILD_REFINERY in obs.observation['available_actions']:
if self.CommandCenterY.any():
unit_type = obs.observation['screen'][_UNIT_TYPE]
global REWARDGL
if refinery_count == 0:
vespene_y, vespene_x = (unit_type == _NEUTRAL_VESPENEGEYSER).nonzero()
first_y = vespene_y[0:97]
first_x = vespene_x[0:97]
target = self.transformDistance(round(first_x.mean()), 0, round(first_y.mean()), 0)
elif refinery_count == 1:
vespene_y, vespene_x = (unit_type == _NEUTRAL_VESPENEGEYSER).nonzero()
target = self.transformDistance(round(vespene_x.mean()), 0, round(vespene_y.mean()), 0)
REWARDGL += 5
return actions.FunctionCall(_BUILD_REFINERY, [_NOT_QUEUED, target])
return actions.FunctionCall(_NO_OP, [])
def buildTurret(self,obs,turrets_count):
if turrets_count < 2 and _BUILD_TURRET in obs.observation['available_actions']:
if self.CommandCenterY.any():
global REWARDGL
if turrets_count == 0:
target = self.transformDistance(round(self.CommandCenterX.mean()), 29,
round(self.CommandCenterY.mean()), 24)
elif turrets_count == 1:
target = self.transformDistance(round(self.CommandCenterX.mean()), 24,
round(self.CommandCenterY.mean()), 29)
REWARDGL += 5
return actions.FunctionCall(_BUILD_TURRET, [_NOT_QUEUED, target])
return actions.FunctionCall(_NO_OP, [])
def trainReaper(self,obs):
if _TRAIN_REAPER in obs.observation['available_actions']:
global REWARDGL
REWARDGL += 1
return actions.FunctionCall(_TRAIN_REAPER, [_QUEUED])
return actions.FunctionCall(_NO_OP, [])
def scout(self,obs,x,y):
do_it = True
if len(obs.observation['single_select']) > 0 and obs.observation['single_select'][0][0] == _TERRAN_SCV:
do_it = False
if len(obs.observation['multi_select']) > 0 and obs.observation['multi_select'][0][0] == _TERRAN_SCV:
do_it = False
if _MOVE_MINIMAP in obs.observation["available_actions"] and do_it:
target = self.transformLocation((int(x)), int(y))
return actions.FunctionCall(_ATTACK_MINIMAP, [_NOT_QUEUED, target])
return actions.FunctionCall(_NO_OP, [])
def supplyDepotCount(self,unit_type):
depot_y, depot_x = (unit_type == _TERRAN_SUPPLY_DEPOT).nonzero()
return int(round(len(depot_y) / 69)) #69 is the size of the depot in pixels
#returns commandCenter count
def commandCenterCount(self,unit_type):
cc_y, cc_x = (unit_type == _TERRAN_COMMANDCENTER).nonzero()
cc_count = 1 if cc_y.any() else 0
return cc_count
#Returns barracks count
def barracksCount(self,unit_type):
barracks_y, barracks_x = (unit_type == _TERRAN_BARRACKS).nonzero()
return int(round(len(barracks_y) / 137))
#returns # of turrets
def turretCount(self,unit_type):
turrets_y, turrets_x = (unit_type == _TERRAN_TURRET).nonzero()
return int(round(len(turrets_y) / 52))
#returns # of engbays
def engbayCount(self,unit_type):
engbay_y, engbay_x = (unit_type == _TERRAN_ENGBAY).nonzero()
engbay_count = 1 if engbay_y.any() else 0
return engbay_count
#returns # of refineries
def refineryCount(self,unit_type):
refinery_y, refinery_x = (unit_type == _TERRAN_REFINERY).nonzero()
return int(round(len(refinery_y) / 97))
| [
"noreply@github.com"
] | chaare24.noreply@github.com |
45ee33f2b96eb380d8ed54ad93aab76653c54a7a | c3396691665741fe3c680e7d44ee127b05b54a0d | /tensorflow/python/training/sync_replicas_optimizer_test.py | e340a22374f7487b4ab4d96cd1720203e8322f36 | [
"Apache-2.0"
] | permissive | ravi-teja-mullapudi/tensorflow | 72506388755fae70e27bb6b907f3f7e6c3208c3d | e8d0ce80414e2402f648a86b1d3bf3ad435467a9 | refs/heads/master | 2021-05-04T08:35:00.029305 | 2016-11-08T22:49:42 | 2016-11-08T22:49:42 | 70,420,798 | 0 | 0 | null | 2016-10-09T17:57:48 | 2016-10-09T17:57:47 | null | UTF-8 | Python | false | false | 11,997 | py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for sync_replicas_optimizer.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.python.util import net_lib
def create_local_cluster(num_workers, num_ps, protocol="grpc"):
"""Create local GRPC servers and return them."""
worker_ports = [net_lib.pick_unused_port_or_die() for _ in range(num_workers)]
ps_ports = [net_lib.pick_unused_port_or_die() for _ in range(num_ps)]
cluster_dict = {
"worker": ["localhost:%s" % port for port in worker_ports],
"ps": ["localhost:%s" % port for port in ps_ports]}
cs = tf.train.ClusterSpec(cluster_dict)
workers = [
tf.train.Server(
cs, job_name="worker", protocol=protocol, task_index=ix, start=True)
for ix in range(num_workers)]
ps_servers = [
tf.train.Server(
cs, job_name="ps", protocol=protocol, task_index=ix, start=True)
for ix in range(num_ps)]
return workers, ps_servers
# Creates the workers and return their sessions, graphs, train_ops.
def get_workers(num_workers, replicas_to_aggregate, workers):
sessions = []
graphs = []
train_ops = []
for worker_id in range(num_workers):
graph = tf.Graph()
is_chief = (worker_id == 0)
with graph.as_default():
with tf.device("/job:ps/task:0"):
global_step = tf.Variable(0, name="global_step", trainable=False)
var_0 = tf.Variable(0.0, name="v0")
with tf.device("/job:ps/task:1"):
var_1 = tf.Variable(1.0, name="v1")
var_sparse = tf.Variable([[3.0], [4.0]], name="v_sparse")
with tf.device("/job:worker/task:"+str(worker_id)):
grads_0 = tf.constant(0.1+worker_id*0.2)
grads_1 = tf.constant(0.9+worker_id*0.2)
# This is to test against sparse gradients.
grads_sparse = tf.IndexedSlices(
tf.constant([0.1+worker_id*0.2], shape=[1, 1]),
tf.constant([1], dtype=tf.int64),
tf.constant([2, 1], dtype=tf.int64))
sgd_opt = tf.train.GradientDescentOptimizer(2.0)
sync_rep_opt = tf.train.SyncReplicasOptimizerV2(
sgd_opt, replicas_to_aggregate=replicas_to_aggregate,
total_num_replicas=num_workers)
train_op = [sync_rep_opt.apply_gradients(
zip([grads_0, grads_1, grads_sparse], [var_0, var_1, var_sparse]),
global_step=global_step)]
init_op = tf.initialize_all_variables()
# Needed ops from the sync_rep optimizer. This is mainly for the
# local_step initialization.
local_init_op = sync_rep_opt.local_step_init_op
if is_chief:
local_init_op = sync_rep_opt.chief_init_op
ready_for_local_init_op = sync_rep_opt.ready_for_local_init_op
# Chief_queue_runner
chief_queue_runner = sync_rep_opt.get_chief_queue_runner()
sync_init_op = sync_rep_opt.get_init_tokens_op(num_workers)
# Creates session for chief.
supervisor = tf.train.Supervisor(
graph=graph,
is_chief=is_chief,
recovery_wait_secs=1,
init_op=init_op,
local_init_op=local_init_op,
ready_for_local_init_op=ready_for_local_init_op)
session = supervisor.prepare_or_wait_for_session(workers[worker_id].target)
# Chief should execute the sync_init_op and start the chief queue runner.
if is_chief:
session.run(sync_init_op)
supervisor.StartQueueRunners(session, [chief_queue_runner])
sessions.append(session)
graphs.append(graph)
train_ops.append(train_op)
return sessions, graphs, train_ops
class SyncReplicasOptimizerV2Test(tf.test.TestCase):
def _run(self, train_op, sess):
sess.run(train_op)
def test2Workers(self):
num_workers = 2
replicas_to_aggregate = 2
num_ps = 2
workers, _ = create_local_cluster(num_workers=num_workers, num_ps=num_ps)
# Creates and returns all the workers.
sessions, graphs, train_ops = get_workers(num_workers,
replicas_to_aggregate,
workers)
# Chief should have already initialized all the variables.
var_0_g_0 = graphs[0].get_tensor_by_name("v0:0")
var_1_g_0 = graphs[0].get_tensor_by_name("v1:0")
local_step_0 = graphs[0].get_tensor_by_name("sync_rep_local_step:0")
self.assertAllEqual(0.0, var_0_g_0.eval(session=sessions[0]))
self.assertAllEqual(1.0, var_1_g_0.eval(session=sessions[0]))
self.assertAllEqual(0, local_step_0.eval(session=sessions[0]))
# Will just use session 1 to verify all the variables later.
var_0_g_1 = graphs[1].get_tensor_by_name("v0:0")
var_1_g_1 = graphs[1].get_tensor_by_name("v1:0")
var_sparse_g_1 = graphs[1].get_tensor_by_name("v_sparse:0")
local_step_1 = graphs[1].get_tensor_by_name("sync_rep_local_step:0")
global_step = graphs[1].get_tensor_by_name("global_step:0")
# The steps should also be initialized.
self.assertAllEqual(0, global_step.eval(session=sessions[1]))
self.assertAllEqual(0, local_step_1.eval(session=sessions[1]))
self.assertAllClose([[3.0], [4.0]],
var_sparse_g_1.eval(session=sessions[1]))
# We have initial tokens in the queue so we can call this one by one. After
# the first step, this will no longer work as there will be no more extra
# tokens in the queue.
sessions[0].run(train_ops[0])
sessions[1].run(train_ops[1])
# The global step should have been updated and the variables should now have
# the new values after the average of the gradients are applied.
self.assertAllEqual(1, global_step.eval(session=sessions[1]))
self.assertAllClose(0-(0.1+0.3)/2*2.0, var_0_g_1.eval(session=sessions[1]))
self.assertAllClose(1-(0.9+1.1)/2*2.0, var_1_g_1.eval(session=sessions[1]))
self.assertAllClose([[3.0], [4.0-(0.1+0.3)/2*2.0]],
var_sparse_g_1.eval(session=sessions[1]))
# The local step for both workers should still be 0 because the initial
# tokens in the token queue are 0s. This means that the following
# computation of the gradients will be wasted as local_step is smaller than
# the current global step. However, this only happens once when the system
# just starts and this is necessary to make the system robust for the case
# when chief gets restarted by errors/preemption/...
self.assertAllEqual(0, local_step_0.eval(session=sessions[0]))
self.assertAllEqual(0, local_step_1.eval(session=sessions[1]))
sessions[0].run(train_ops[0])
sessions[1].run(train_ops[1])
# Although the global step should still be 1 as explained above, the local
# step should now be updated to 1. The variables are still the same.
self.assertAllEqual(1, global_step.eval(session=sessions[1]))
self.assertAllEqual(1, local_step_0.eval(session=sessions[0]))
self.assertAllEqual(1, local_step_1.eval(session=sessions[1]))
self.assertAllClose(0-(0.1+0.3)/2*2.0, var_0_g_1.eval(session=sessions[1]))
self.assertAllClose(1-(0.9+1.1)/2*2.0, var_1_g_1.eval(session=sessions[1]))
# At this step, the token queue is empty. So the 2 workers need to work
# together to proceed.
threads = []
threads.append(self.checkedThread(target=self._run,
args=(train_ops[0], sessions[0])))
threads.append(self.checkedThread(target=self._run,
args=(train_ops[1], sessions[1])))
# The two workers starts to execute the train op.
for thread in threads:
thread.start()
for thread in threads:
thread.join()
# The global step should now be 2 and the gradients should have been
# applied twice.
self.assertAllEqual(2, global_step.eval(session=sessions[1]))
self.assertAllClose(0 - 2 * (0.1 + 0.3) / 2 * 2.0,
var_0_g_1.eval(session=sessions[1]))
self.assertAllClose(1 - 2 * (0.9 + 1.1) / 2 * 2.0,
var_1_g_1.eval(session=sessions[1]))
# 3 workers and one of them is backup.
def test3Workers1Backup(self):
num_workers = 3
replicas_to_aggregate = 2
num_ps = 2
workers, _ = create_local_cluster(num_workers=num_workers, num_ps=num_ps)
# Creates and returns all the workers.
sessions, graphs, train_ops = get_workers(num_workers,
replicas_to_aggregate,
workers)
# Chief should have already initialized all the variables.
var_0_g_1 = graphs[1].get_tensor_by_name("v0:0")
var_1_g_1 = graphs[1].get_tensor_by_name("v1:0")
local_step_1 = graphs[1].get_tensor_by_name("sync_rep_local_step:0")
global_step = graphs[1].get_tensor_by_name("global_step:0")
# The steps should also be initilized.
self.assertAllEqual(0, global_step.eval(session=sessions[1]))
self.assertAllEqual(0, local_step_1.eval(session=sessions[1]))
# We have initial tokens in the queue so we can call this one by one. After
# the token queue becomes empty, they should be called concurrently.
# Here worker 0 and worker 2 finished first.
sessions[0].run(train_ops[0])
sessions[2].run(train_ops[2])
# The global step should have been updated since we only need to collect 2
# gradients. The variables should now have the new values after the average
# of the gradients from worker 0/2 are applied.
self.assertAllEqual(1, global_step.eval(session=sessions[1]))
self.assertAllClose(0-(0.1+0.5)/2*2.0, var_0_g_1.eval(session=sessions[1]))
self.assertAllClose(1-(0.9+1.3)/2*2.0, var_1_g_1.eval(session=sessions[1]))
# Worker 1 finished later and its gradients will now be dropped as it is
# stale.
sessions[1].run(train_ops[1])
# As shown in the previous test, the local_step for all workers should be
# still 0 so their next computation will also be dropped.
sessions[0].run(train_ops[0])
sessions[1].run(train_ops[1])
sessions[2].run(train_ops[2])
# Although the global step should still be 1 as explained above, the local
# step should now be updated to 1. Just check worker 1 as an example.
self.assertAllEqual(1, global_step.eval(session=sessions[1]))
self.assertAllEqual(1, local_step_1.eval(session=sessions[1]))
thread_0 = self.checkedThread(target=self._run,
args=(train_ops[0], sessions[0]))
thread_1 = self.checkedThread(target=self._run,
args=(train_ops[1], sessions[1]))
# Lets worker 0 execute first.
# It will wait as we need 2 workers to finish this step and the global step
# should be still 1.
thread_0.start()
self.assertAllEqual(1, global_step.eval(session=sessions[1]))
# Starts worker 1.
thread_1.start()
thread_1.join()
# The global step should now be 2 and the gradients should have been
# applied again.
self.assertAllEqual(2, global_step.eval(session=sessions[1]))
self.assertAllClose(-0.6 -(0.1 + 0.3) / 2 * 2.0,
var_0_g_1.eval(session=sessions[1]))
self.assertAllClose(-1.2 - (0.9 + 1.1) / 2 * 2.0,
var_1_g_1.eval(session=sessions[1]))
if __name__ == "__main__":
tf.test.main()
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
5c899b554a9be61f967ded9f7bdb175a528802fe | 0260ac6d1f005b8e5bfa642fbb3e721b0883397f | /app/libs/non_local.py | c97c310820fb21afd74b5bd4ed415e6dc4577d84 | [] | no_license | xiaofanzhi/Fisher | c8d75d1807d569f17c57d2ee7cef7db139f3b6a0 | 5ce50541e58c070bcb302416601262bcc13f8795 | refs/heads/master | 2022-12-09T19:26:14.059909 | 2019-07-18T06:22:23 | 2019-07-18T06:22:23 | 177,928,777 | 1 | 0 | null | 2021-03-20T01:12:48 | 2019-03-27T06:07:02 | Python | UTF-8 | Python | false | false | 80 | py | class NoneLocal:
def __init__(self,v):
self.v = v
n = NoneLocal(1)
| [
"648215109@qq.com"
] | 648215109@qq.com |
243d73085f72cbb45a474ca74715e29638fa36d3 | 1adf0095f19618c74f3cce45c9c5bb4dad9358b5 | /Algo 01 Desvon Akbar.py | 60092066435f2ea4c9ee427676a878ac2163cca0 | [] | no_license | Divon2/Desvon-Akbar_064002100041-Uprak-Algo01 | 8d826f808c6077537fe8fa6689fc53533fbb97b9 | de53c717d16c23286f1bef888b50b27c3680c031 | refs/heads/main | 2023-08-23T10:56:40.807749 | 2021-09-22T03:35:58 | 2021-09-22T03:35:58 | 409,049,609 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 436 | py |
print ( "@@@ @@@@ @@@ @ @ @ @ @" )
print ( "@ @ @ @ @ @ @ @ @ @ @ ")
print (" @ @ @@@@ @ @ @ @ @ @ @ @" )
print ( "@ @ @ @ @ @ @ @ @ @ @")
print ( "@ @@@@ @@@ @ @ @ @ ")
print ('he told me, "go grab your laundry"')
print ("i'm making a bread")
| [
"noreply@github.com"
] | Divon2.noreply@github.com |
476ed612d214179e545bc7fd4db0f462091804e2 | 8e48dbad8b50b88ed71d332483b4fe94c953af40 | /gaurav/settings.py | 86fe54ecb5d029b16e860306bac807ed39996ee9 | [] | no_license | Ram-Avtar/Quotes-generator- | 2b78848ee9795e126d9fa5a0be10c2ad1453cdc6 | f71cddb96219cdd89f8a97bb703b7e2644e37fb5 | refs/heads/master | 2022-04-23T01:26:13.734233 | 2020-04-21T14:20:57 | 2020-04-21T14:20:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,234 | py | """
Django settings for gaurav project.
Generated by 'django-admin startproject' using Django 3.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'hx+tt)+^r==xkpzj0etqw@8cx4)0&fibc)asehg&n3auw!dv1='
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'quote.apps.QuoteConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'gaurav.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'gaurav.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'blog_app',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
| [
"ram29avtar@gmail.com"
] | ram29avtar@gmail.com |
a30a74ef63e610b8720e62c333587fb4c2073374 | 7276a4afce6886f3e4773a3f61f3af28097ca2dc | /apps/goods/urls.py | 10ce0184eb8442b20d197582359728b7448243c0 | [] | no_license | Huym510/DailyFresh | 142af2ef1613b55a51f55b35882f291428a0099e | a5e209c5e53d118b8ecace8d7c72ec0e4448f996 | refs/heads/master | 2020-06-07T15:28:24.583571 | 2019-06-21T07:21:54 | 2019-06-21T07:21:54 | 193,049,614 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 128 | py | from django.conf.urls import url
from goods import views
urlpatterns = [
url(r'^$', views.index, name="index"), # ้ฆ้กต
] | [
"chenyang95510@163.com"
] | chenyang95510@163.com |
152f41075af7869dd7ce1fc7b195488fa4072fc6 | 1acf6961af97b04b19d33e6a3537772502332b24 | /pi_surv_backup/surv/TempImage.py | b78373aefd1ec016e03c050e8ffda5c970902df6 | [] | no_license | 40tudor/RPiOpenCV | 341ee6781ab4cf6a3870e6688afd8c4eb7eb2a4e | f29d128cac84300a16afedb213fa6a8c0a0956fd | refs/heads/master | 2021-09-02T06:36:09.794038 | 2017-12-31T03:37:33 | 2017-12-31T03:37:33 | 115,726,230 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 314 | py | # import the necessary packages
import uuid
import os
class TempImage:
def __init__(self, basePath="./", ext=".jpg"):
# construct the file path
self.path = "{base_path}{rand}{ext}".format(base_path=basePath,
rand=str(uuid.uuid4()), ext=ext)
def cleanup(self):
# remove the file
os.remove(self.path)
| [
"cyoung40@gmail.com"
] | cyoung40@gmail.com |
5b809ff208831e26008b58b30ecc4453fe7f150d | fcc665fc2792820e438d32339cc12ae796c1835c | /opps/core/models/profile.py | d012047a545730de5be9f658dfa00941a86911e5 | [
"MIT"
] | permissive | marcelomilo/opps | e3614e644d97ebc6b62e0083aee9a42c242f567c | bf92a003b6ad1f521d662d767a29f58a6033cb3d | refs/heads/master | 2021-01-16T18:50:12.146646 | 2013-03-02T05:15:51 | 2013-03-02T05:15:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 435 | py | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
class Profile(models.Model):
user = models.ForeignKey(User, related_name='user')
twitter = models.CharField(_(u"Twitter"), max_length=75, blank=True,
null=True)
class Meta:
app_label = 'core'
def __unicode__(self):
return self.user
| [
"thiagoavelinoster@gmail.com"
] | thiagoavelinoster@gmail.com |
ef2d18211c323bd7603ec0938ce87dce09755d62 | b4c2bbf32748f381f8918c2c20d2a86b5453dc87 | /plugins/convert/mask/box_blend.py | f42177463e6d8e748353a1bd9354d1eaf432d0ff | [
"MIT"
] | permissive | oveis/DeepVideoFaceSwap | d45c7a18204f851a5c8b9cb6c9618284d4314b59 | e507f94d4f5d74c36e41c386c6fb14bb745a4885 | refs/heads/dev-gan-model | 2022-07-14T10:06:08.131201 | 2019-07-09T00:48:16 | 2019-07-09T00:48:16 | 184,978,011 | 6 | 5 | MIT | 2022-06-21T22:00:38 | 2019-05-05T04:09:53 | Python | UTF-8 | Python | false | false | 1,990 | py | #!/usr/bin/env python3
""" Adjustments for the swap box for faceswap.py converter """
import numpy as np
from ._base import Adjustment, BlurMask, logger
class Mask(Adjustment):
""" Manipulations that occur on the swap box
Actions performed here occur prior to warping the face back to the background frame
For actions that occur identically for each frame (e.g. blend_box), constants can
be placed into self.func_constants to be compiled at launch, then referenced for
each face. """
def __init__(self, mask_type, output_size, predicted_available=False, config=None):
super().__init__(mask_type, output_size, predicted_available, config)
self.mask = self.get_mask() if not self.skip else None
def get_mask(self):
""" The box for every face will be identical, so set the mask just once
As gaussian blur technically blurs both sides of the mask, reduce the mask ratio by
half to give a more expected box """
logger.debug("Building box mask")
mask_ratio = self.config["distance"] / 200
facesize = self.dummy.shape[0]
erode = slice(round(facesize * mask_ratio), -round(facesize * mask_ratio))
mask = self.dummy[:, :, -1]
mask[erode, erode] = 1.0
mask = BlurMask(self.config["type"],
mask,
self.config["radius"],
self.config["passes"]).blurred
logger.debug("Built box mask. Shape: %s", mask.shape)
return mask
def process(self, new_face):
""" The blend box function. Adds the created mask to the alpha channel """
if self.skip:
logger.trace("Skipping blend box")
return new_face
logger.trace("Blending box")
mask = np.expand_dims(self.mask, axis=-1)
new_face = np.clip(np.concatenate((new_face, mask), axis=-1), 0.0, 1.0)
logger.trace("Blended box")
return new_face
| [
"jinil@nyu.edu"
] | jinil@nyu.edu |
84328ef5770412c0a5171f80e6f74068fbef6c78 | 3fcbd3ce64d9dcdf1ab701800b3da492a3e83a2a | /xml/parse_xml.py | 35dd4db4651fde50d5a6898decf9c51ba241f80d | [
"CC-BY-4.0"
] | permissive | bruce-webber/python-intro | f803d29e58169ea36dd4f5f29c7d01c8d8193352 | 78881eb65951e2c4451df1d62da1b7d79f5b1970 | refs/heads/master | 2021-05-07T03:17:24.492632 | 2017-11-15T13:45:30 | 2017-11-15T13:45:30 | 110,837,924 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 713 | py | """
This is a demonstration of xml.etree (part of the standard library), which is used
to parse, modify and create XML files.
"""
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
# The top level tag.
print(root.tag)
# The tag of the first sub-element.
print(root[0].tag)
# The attributes of the first sub-element.
print(root[0].attrib)
print()
# The names of the countries and their neighbors.
for country in root:
if 'name' in country.attrib:
print(country.attrib['name'])
for element in country:
if element.tag == 'neighbor':
if 'name' in element.attrib:
print(' ' + element.attrib['name'])
| [
"self@brucewebber.us"
] | self@brucewebber.us |
03b8b0e40b805a728b80ddc793e4807261985a44 | c5f37573982007c5ef4297cd73a8f900f7217028 | /frontend.py | 20ca91e0cbd5dabee622aafafa40e2d26613ee77 | [] | no_license | Joepolymath/dictionary | 6f2f80e01ed558e8cbfd1afc374112c7bcc4cf00 | e9cee380b8979537f0825ceb059aace6d7bebdc4 | refs/heads/master | 2023-04-21T13:03:44.074948 | 2021-05-11T10:52:24 | 2021-05-11T10:52:24 | 366,345,255 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,808 | py | import tkinter as tk
from tkinter import *
import json
from difflib import get_close_matches
import tkinter.messagebox
data = json.load(open('original.json'))
def search_engine():
word = searchbox.get()
list.delete('1.0', END)
x=0
y = 1
if word in data:
results = data[word]
for result in results:
list.insert(END, str(y) + ". " + result + "\n")
x+=1
y+=1
elif len(get_close_matches(word, data.keys())) > 0:
real_list = get_close_matches(word, data.keys(), cutoff=0.8)
real_word = real_list[0]
answer = tkinter.messagebox.askquestion("Word Suggestion", "Is your word " + real_word + "?")
if answer == 'yes':
results = data[real_word]
list.insert(END, "Result for " + real_word + " instead of " + word + ".\n")
for result in results:
list.insert(END, str(y) + ". " + result + "\n")
x += 1
y += 1
else:
list.insert(END, "No word found")
else:
list.insert(END, "No word found")
def display_command(word):
list.delete(0, END)
home = tk.Tk()
home.title('Joecode Dictionary')
home_canvas = Canvas(home, width =1000, height=500, bg = "#C1B1D6")
home_canvas.pack()
"""
home_canvas2 = Canvas(home_canvas,bg = "#D3C9A7")
home_canvas2.place( relwidth=0.2, relheight = 0.8, relx=0.78, rely= 0.1)
"""
#title label
heading = Label(home_canvas, text="TJ Dictionary", bg = "#C1B1D6", fg = "#1A80AC")
heading.config(font=('forte 20'))
heading.place(relx=0.425, rely = 0.02)
homeframe= Frame(home_canvas, bg='#D3C9A7', bd =5)
homeframe.place(relwidth=0.9, relheight=0.8, relx=0.05, rely=0.1)
search = Label(homeframe, text = "Enter your word here", bg='#D3C9A7', fg="black")
search.config(font=('jokerman 12'))
search.place(relx=0.15, rely=0.14)
word_text = StringVar()
searchbox = Entry(homeframe, bg = "white", fg="black", textvariable=word_text)
searchbox.config(width=42)
searchbox.place(relx=0.36, rely=0.15)
searchbut = Button(homeframe, text="search", relief = FLAT, command=search_engine)
searchbut.place(relx=0.5, rely= 0.24, anchor=CENTER)
#result_label = Label(homeframe, bg = "#C1B1D6")
#result_label.place(relwidth=0.85, relheight= 0.6, relx=0.1, rely=0.3)
#lower_frame= Frame(result_label, bg ='white')
#lower_frame.place(relwidth=0.95, relheight= 0.9, relx=0.025, rely=0.05)
list = Text(homeframe, bg="white")
list.place(relwidth=0.9, relheight= 0.6, relx=0.06, rely=0.3)
footer= Label(home_canvas, text="Software Developed by Joshua Tobi Ajagbe", fg="red", bg = "#C1B1D6")
footer.config(font=('perpetua 15'))
footer.place(relx=0.35, rely=0.93)
home.mainloop()
| [
"joshuaajagbe96@gmail.com"
] | joshuaajagbe96@gmail.com |
67ef9e2d6dd5453906b1ff9cac1f7265ee15ff17 | 33c612f6e2dc8392bd715d47af5e89c28695443a | /Chapter5/9. ์๋๊ทธ๋จ(๊ตฌ๊ธ)/sj.py | b019a5cdde4a4a6f782c9a55978b94358da59f93 | [] | no_license | SaeSimcheon/employee_or_farm | 7877f9534ba70b5b0d0206c49d9d116dc89fcb4f | 048fb4ab6ed772bf688bfc970d5bcbcc938f52ad | refs/heads/main | 2023-07-30T04:15:26.914173 | 2021-09-16T13:06:52 | 2021-09-16T13:06:52 | 353,000,472 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,938 | py | import sys
#sys.stdin = open("input.txt", "rt")
'''a = input()
b = input()
if sorted(a) == sorted(b):
print("YES")
else:
print("NO")'''
# dictionary๋ก๋ ํ์ด๋ณด์
'''a = input()
b = input()
w1 = dict()
w2 = dict()
for i in a:
if i in w1:
w1[i] += 1
else:
w1[i] = 1
for j in b:
if j in w2:
w2[j] += 1
else:
w2[j] = 1
if w1 == w2:
print("YES")
else:
print("NO")'''
# ๋๋ค 100
'''a = input()
b = input()
str1 = dict()
str2 = dict()
for x in a:
str1[x] = str1.get(x,0)+1
for x in b:
str2[x] = str2.get(x,0)+1
for i in str1.keys():
if i in str2.keys():
if str1[i]!=str2[i]: # ๊ฐ์ key์ value๊ฐ ๋ค๋ฅผ๋
print("NO")
break
else: # key๊ฐ ๋ค๋ฅผ๋
print("NO")
break
else:
print("YES")
# ๋น๊ต ๋ฐฉ๋ฒ์ด ๋๋ฌด ๋ณต์กํด์, ๊ฐ์ ํ ์ฝ๋
a = input()
b = input()
sH = dict()
for x in a:
sH[x] = sH.get(x,0)+1
for x in b:
sH[x] = sH.get(x,0)-1
for x in a:
if sH.get(x)>0:
print("NO")
break
else:
print("YES")'''
# ๋ฆฌ์คํธ ๋ฒ์ / ์์คํค ๋๋ฒ ์ด์ฉ
# ๋๋ฌธ์๋ 65~90(64๋ฅผ ๋บด๊ธฐ) / ์๋ฌธ์๋ 97~(71๋ฅผ ๋นผ๊ธฐ)
a = input()
b = input()
str1 = [0]*52
str2 = [0]*52
for x in a:
if x.isupper():
str1[ord(x)-65]+=1
else:
str1[ord(x)-71]+=1
for x in b:
if x.isupper():
str2[ord(x)-65]+=1
else:
str2[ord(x)-71]+=1
for i in range(52):
if str1[i]!=str2[i]:
print("NO")
break
else:
print("YES")
# ๋๋์
# 1. ํด์ฑ ์กฐ๊ฑด์ด ์ข ๊น๋ค๋กญ๋ค
# ๋ฐฐ์ด์
# 1. dict.get(x,0) : key x์ value๋ฅผ ํธ์ถํ๊ณ ์์ผ๋ฉด 0์ ํธ์ถ
# 2. ์์คํค ๋๋ฒ ์ฌ์ฉ
# 3. ๋ฆฌ์คํธ๋ ๋์
๋๋ฆฌ๊ฐ์ ์ง์ ๋น๊ต๋ ์ง์ / c++ ์ฒ๋ผ ํ๋ํ๋ ๋น๊ตํ๋ ์์ผ๋ก ์ฝ๋ฉํด์ผํจํจ | [
"noreply@github.com"
] | SaeSimcheon.noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.