blob_id stringlengths 40 40 | language stringclasses 1 value | repo_name stringlengths 5 133 | path stringlengths 2 333 | src_encoding stringclasses 30 values | length_bytes int64 18 5.47M | score float64 2.52 5.81 | int_score int64 3 5 | detected_licenses listlengths 0 67 | license_type stringclasses 2 values | text stringlengths 12 5.47M | download_success bool 1 class |
|---|---|---|---|---|---|---|---|---|---|---|---|
a44c04c2078ee528fffa057993935e23c06912b6 | Python | BaekJongHwan/algorithm | /Baekjoon Online Judge/Python/5543.상근날드.py | UTF-8 | 309 | 3.109375 | 3 | [] | no_license | minVal = 0
minVal2 = 0
for i in range(0, 5):
a = int(input())
if i < 3:
if minVal == 0:
minVal = a
elif minVal > a:
minVal = a
else:
if minVal2 == 0:
minVal2 = a
elif minVal2 > a:
minVal2 = a
print(minVal+minVal2-50) | true |
3d9ffc440467023ec0186476a9ec0f5a0d12c51e | Python | kbhalerao/gdalCompose | /async_file_copier.py | UTF-8 | 1,592 | 2.65625 | 3 | [
"MIT"
] | permissive | ## Author: Kaustubh Bhalerao, Soil Diagnostics, Inc.
import os
import shutil
from contextlib import asynccontextmanager
import tempfile
import asyncio
from functools import wraps, partial
def async_wrap(func):
@wraps(func)
async def run(*args, loop=None, executor=None, **kwargs):
if loop is None:
loop = asyncio.get_event_loop()
pfunc = partial(func, *args, **kwargs)
return await loop.run_in_executor(executor, pfunc)
return run
@asynccontextmanager
async def managed_tempfolder(*args, **kwargs):
prefix = kwargs.get('prefix', 'mgd')
suffix = kwargs.get('suffix', '')
resource = tempfile.mkdtemp(suffix=suffix, prefix=prefix)
try:
yield resource
finally:
try:
shutil.rmtree(resource)
except OSError as e:
print(f"Error {resource}-{repr(e)}")
def read_in_chunks(file_object, chunk_size=1024):
"""Lazy function (generator) to read a file piece by piece.
Default chunk size: 1k."""
while True:
data = file_object.read(chunk_size)
if not data:
break
yield data
@asynccontextmanager
async def tempfile_copy(file):
async with managed_tempfolder(prefix="cpy") as folder:
fname = os.path.basename(file.name)
with open(f"{folder}/{fname}", "wb") as copied_file:
for chunk in read_in_chunks(file):
await async_wrap(copied_file.write)(chunk)
try:
yield f"{folder}/{fname}"
finally:
pass
## Let the managed tempfolder deal with cleanup.
| true |
faf065ec6e1bba246ade45ce6cebdd9b2450cc32 | Python | WholesomeM3me/Per3_PatrickDalton_pygame | /game_window.py | UTF-8 | 346 | 3.375 | 3 | [
"MIT"
] | permissive | import pygame
x = int(input("How many pixels wide do you want the window resolution to be?"))
y = int(input("How many pixels tall do you want the window resolution to be?"))
screen = pygame.display.set_mode((x, y))
while True:
event = pygame.event.poll()
if event.type == pygame.QUIT:
break
screen.fill((250, 70, 0))
pygame.display.flip() | true |
61a624708bdf90ed90937acd1181c68fc65220dd | Python | rdestefa/python_server_js_client | /server/test/test_users_key.py | UTF-8 | 5,797 | 2.765625 | 3 | [] | no_license | import unittest
import requests
import json
class TestUsersKey(unittest.TestCase):
SITE_URL = 'http://localhost:51080'
USERS_URL = SITE_URL + '/users/'
RESET_URL = SITE_URL + '/reset/'
print(f'Testing for server: {SITE_URL} USERS KEY EVENT HANDLERS')
def reset_data(self):
m = {}
r = requests.put(self.RESET_URL, data=json.dumps(m))
def is_json(self, resp):
try:
json.loads(resp)
return True
except ValueError:
return False
def test_users_get_key(self):
self.reset_data()
uid = 'conor-holahan'
uid2 = 'nonexistent-user'
# Check if the response is formatted correctly as JSON
r = requests.get(self.USERS_URL + str(uid))
self.assertTrue(self.is_json(r.content.decode('utf-8')))
# Check if the response is accurate
resp = json.loads(r.content.decode('utf-8'))
self.assertEqual(resp['result'], 'success')
self.assertEqual(resp[uid]['name'], 'Conor Holahan')
self.assertEqual(resp[uid]['email'], 'cholahan@nd.edu')
self.assertEqual(resp[uid]['favorite-genres'], ['Comedy', 'Drama', 'Crime'])
# Check error handling
r2 = requests.get(self.USERS_URL + str(uid2))
self.assertTrue(self.is_json(r2.content.decode('utf-8')))
# Check if the error response is accurate
resp2 = json.loads(r2.content.decode('utf-8'))
self.assertEqual(resp2['result'], 'error')
self.assertEqual(resp2['message'], 'User not found')
def test_users_put_key(self):
self.reset_data()
uid = 'conor-holahan'
uid2 = 'nonexistent-user'
body = {
"email" : "cholahan@gmail.com",
"recently-watched" : "rick-and-morty",
"preferred-episode-length" : 30,
"least-favorite-show": "icarly"
}
# Check if the initial response is formatted correctly as JSON
r_get = requests.get(self.USERS_URL + str(uid))
self.assertTrue(self.is_json(r_get.content.decode('utf-8')))
# Check if the initial response is accurate
resp_get = json.loads(r_get.content.decode('utf-8'))
self.assertEqual(resp_get['result'], 'success')
self.assertEqual(resp_get[uid]['email'], 'cholahan@nd.edu')
self.assertEqual(resp_get[uid]['recently-watched'], 'the-wire')
self.assertEqual(resp_get[uid]['preferred-episode-length'], 60)
# Check if the PUT response is formatted correctly as JSON
r_put = requests.put(self.USERS_URL + str(uid), data=json.dumps(body))
self.assertTrue(self.is_json(r_put.content.decode('utf-8')))
# Check if the PUT response is accurate
resp_put = json.loads(r_put.content.decode('utf-8'))
self.assertEqual(resp_put['result'], 'success')
self.assertEqual(resp_put['attributes']['email'], 'Changed')
self.assertEqual(resp_put['attributes']['least-favorite-show'], 'Not changed')
# Check if the final response is formatted correctly as JSON
r_get = requests.get(self.USERS_URL + str(uid))
self.assertTrue(self.is_json(r_get.content.decode('utf-8')))
# Check if the final response is accurate
resp_get = json.loads(r_get.content.decode('utf-8'))
self.assertEqual(resp_get['result'], 'success')
self.assertEqual(resp_get[uid]['email'], 'cholahan@gmail.com')
self.assertEqual(resp_get[uid]['recently-watched'], 'rick-and-morty')
self.assertEqual(resp_get[uid]['preferred-episode-length'], 30)
# Check error handling
r_put = requests.put(self.USERS_URL + str(uid2), data=json.dumps(body))
self.assertTrue(self.is_json(r_put.content.decode('utf-8')))
# Check if the error response is accurate
resp_put = json.loads(r_put.content.decode('utf-8'))
self.assertEqual(resp_put['result'], 'error')
self.assertEqual(resp_put['message'], 'User not found')
def test_users_delete_key(self):
self.reset_data()
uid = 'ryan-destefano'
# Check that user is initially present
r_get= requests.get(self.USERS_URL + str(uid))
self.assertTrue(self.is_json(r_get.content.decode('utf-8')))
# Check if the GET response is accurate
resp_get = json.loads(r_get.content.decode('utf-8'))
self.assertEqual(resp_get['result'], 'success')
self.assertEqual(resp_get[uid]['name'], 'Ryan DeStefano')
self.assertEqual(resp_get[uid]['email'], 'rdestefa@nd.edu')
# Delete user with ID of ryan-destefano
r_delete = requests.delete(self.USERS_URL + str(uid), data=json.dumps({}))
self.assertTrue(self.is_json(r_delete.content.decode('utf-8')))
# Check if DELETE response is accurate
resp_delete = json.loads(r_delete.content.decode('utf-8'))
self.assertEqual(resp_delete['result'], 'success')
# Check if user was deleted
r_get= requests.get(self.USERS_URL + str(uid))
self.assertTrue(self.is_json(r_get.content.decode('utf-8')))
# Check if the GET response is accurate
resp_get = json.loads(r_get.content.decode('utf-8'))
self.assertEqual(resp_get['result'], 'error')
self.assertEqual(resp_get['message'], 'User not found')
# Check error handling
r_delete = requests.delete(self.USERS_URL + str(uid), data=json.dumps({}))
self.assertTrue(self.is_json(r_delete.content.decode('utf-8')))
# Check if DELETE response is accurate
resp_delete = json.loads(r_delete.content.decode('utf-8'))
self.assertEqual(resp_delete['result'], 'error')
self.assertEqual(resp_delete['message'], 'User not found')
if __name__ == '__main__':
unittest.main()
| true |
b000cde9413840b03e861416f95c1ae6f8982a90 | Python | MMaltez/FileIndexer | /exp/exp001.py | UTF-8 | 193 | 2.625 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Hello world.
@author Miguel Maltez Jose
@date 20210314
"""
def main():
"""There can be only one."""
print("Hello.")
if __name__ == "__main__":
main()
| true |
6d2ef745e5143eef9a1b8db59c9ea06d9affff80 | Python | TrentHand/Django-Music-History-RestAPI | /quickstart/models/artistmodels.py | UTF-8 | 381 | 2.890625 | 3 | [] | no_license | from django.db import models
from .genremodels import Genre
class Artist(models.Model):
"""
Stores a single Artist
fields:
'name' is a character field
'genre' is a foreign key
"""
name = models.CharField(max_length=55)
genre = models.ForeignKey(Genre, on_delete=models.CASCADE)
def __str__(self):
return 'Artist: {}'.format(self.name)
| true |
ff97dbd9a105848e0c506615564f40a9fbb8e4ba | Python | hortonew/SpaceInvaders-Like-Game | /classes/game.py | UTF-8 | 3,196 | 2.640625 | 3 | [] | no_license | import logging
import random
from config import *
from classes import player
from classes.bullet import Bullet
from classes.enemy import EnemyGroup, Enemy
from classes.scenes import MainMenu, WinScreen, LoseScreen
from classes.gameitem import GameItem
from classes.hud import Score, Lives
import pyglet
logger = logging.getLogger(__name__)
class Game(object):
def __init__(self):
self.win = GameItem.win = pyglet.window.Window(*WINDOW_SIZE)
self.graphics_batch = pyglet.graphics.Batch()
self.objects = []
self.win.on_draw = self.on_draw
self.lost_game = False
GameItem.game = self
def add(self, new_game_object):
self.objects.append(new_game_object)
def remove(self, obj_to_remove):
self.objects.remove(obj_to_remove)
def on_draw(self):
self.win.clear()
self.graphics_batch.draw()
def update(self, dt):
for obj in self.objects:
# todo: seriously clean up this hackjob
if type(obj) in [player.Player, Bullet]:
if type(obj) == Bullet:
if self.player.collides_with(obj):
self.player.handle_collision_with(obj)
for enemy in [oo for oo in self.objects if type(oo) == Enemy]:
if obj.collides_with(enemy):
obj.handle_collision_with(enemy)
enemy.handle_collision_with(obj)
# wonky score function for that arcade feel
self.score.update_score(self.score.score + (MYSTERY_SCORE_NUMBER * (enemy.row + 1)))
# update all game objects
obj.update(dt)
for to_remove in [obj for obj in self.objects if obj.remove_from_game]:
self.objects.remove(to_remove)
to_remove.clean_up()
#del(to_remove)
def enemy_fire(self, dt):
# pick random enemy and make it fire
enemies = [obj for obj in self.objects if type(obj) == Enemy]
if enemies:
random_enemy = enemies[random.randint(0, len(enemies) - 1)]
random_enemy.fire()
def start(self, _):
# Initialize the player sprite
self.player = player.Player(x=WINDOW_SIZE[0]//2, y=100, batch=self.graphics_batch)
self.lives = Lives(self.player.lives)
self.score = Score()
self.enemy_group = EnemyGroup(NUM_ENEMIES, 0, self.graphics_batch)
self.objects.append(self.player)
self.objects.append(self.enemy_group)
self.objects.append(self.score)
self.objects.append(self.lives)
def win_game(self):
if not self.lost_game:
for o in self.objects:
pyglet.clock.schedule_once(o.remove, 0)
self.add(WinScreen())
def lose_game(self):
self.lost_game = True
for o in self.objects:
pyglet.clock.schedule_once(o.remove, 0)
self.add(LoseScreen())
def main(self):
self.add(MainMenu())
pyglet.clock.schedule_interval(self.update, 1/120.0)
pyglet.clock.schedule_interval(self.enemy_fire, 3)
pyglet.app.run()
# start main menu
| true |
79a4b55978c5e6bc329ed0571f9cfefd62e22f12 | Python | Reqin/Network-Video-Transmission | /modules/network/Communicator.py | UTF-8 | 960 | 2.96875 | 3 | [] | no_license | # coding:utf8
import socket
import time
class Communicator:
def __init__(self, address, conn=None):
self.message_send = None
self.message_recv = None
self.sock = conn
if not conn:
print(55)
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__connect(address)
def __connect(self, address):
while True:
try:
self.sock.connect(address)
break
except socket.error as error:
print(error)
time.sleep(1)
def set_message(self, message):
self.message_send = message
return self
def send(self):
self.sock.send(self.message_send)
def recv(self, length):
return self.sock.recv(length, socket.MSG_WAITALL)
def encode(self, length):
self.message_send = str.encode(str(self.message_send).ljust(length))
return self
| true |
d13056670ea9f2c59988c7da8128ec421886245d | Python | sumin123/CodingTest | /0825/불량 사용자.py | UTF-8 | 762 | 2.625 | 3 | [] | no_license |
from itertools import permutations
def solution(user_id, banned_id):
def check(id):
for i in range(len(id)):
if len(id[i]) != len(banned_id[i]):
return False
for j in range(len(id[i])):
if banned_id[i][j] == '*':
continue
if banned_id[i][j] != id[i][j]:
return False
return True
answer = []
N = len(banned_id)
user_list = list(permutations(user_id, N))
for user in user_list:
# print(check(user))
if check(user):
user = set(user)
if user not in answer:
answer.append(user)
# print(user_list)
return len(answer) | true |
68ffc4a9fc224d972a52410dd89d6f34d43c0973 | Python | yanshugang/study_data_structures_and_algorithms | /sort_algorithms/s03_insertion_sort.py | UTF-8 | 770 | 3.890625 | 4 | [] | no_license | # -*- coding: utf-8 -*-
# @Author: ysg
# @Contact: yanshugang11@163.com
# @Time: 2019/7/24 下午6:07
"""
插入排序
每次挑选下一个元素插入已经排序的数组中,初始时已排序数组只有一个火元素。
"""
def insertion_sort(seq):
n = len(seq)
print(seq)
for i in range(1, n):
value = seq(i) # 保存当前位置的值, 因为转移的过程中它的位置可能被覆盖
# 找到这个值的合适位置,使得前边的数组有序,即[0, i]是有序的
pos = i
while pos > 0 and value < seq[pos - 1]:
seq[pos] = seq[pos - 1] # 如果前边的元素比它大,就让它一直前移
pos -= 1
seq[pos] = value
print(seq)
def test_insertion_sort():
pass
| true |
92a6b3b77b443538f900a7da063570e48a3e5443 | Python | alexandraback/datacollection | /solutions_5634697451274240_1/Python/Alon/foo.py | UTF-8 | 305 | 3.09375 | 3 | [] | no_license | #!/usr/bin/python
import sys
def calc(pan):
cnt = 0
curr = '+'
for c in pan[::-1]:
if c != curr:
cnt += 1
curr = c
return cnt
def main():
d = file(sys.argv[1]).readlines()
n = int(d[0])
for j in xrange(1,n+1):
print "Case #%d: %d" % (j, calc(list(d[j][:-1])))
main()
| true |
e03aff4ff8608a8877763d37513c8bea9501d6e4 | Python | zompi2/HouseOffersCrawler | /mailsender.py | UTF-8 | 508 | 3.125 | 3 | [] | no_license | # Sends an email with given content
import smtplib
def sendMail(receivers, subject, content) :
sender = "me@example.com"
message = """From: <{}>
To: {}
MIME-Version: 1.0
Content-type: text/html
Subject: {}
{}
""".format(sender, '<' + '>,<'.join(receivers) + '>', subject, content)
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print("Successfully sent email")
except smtplib.SMTPException:
print ("Error: unable to send email") | true |
2e1c8471b6a9912b8cc97d981e7b903832363cb0 | Python | junyoung-o/PS-Python | /by date/2021.02.08/1010.py | UTF-8 | 603 | 3.3125 | 3 | [] | no_license | t = int(input())
def get_mul(m, n):
result = 1
for i in range(n):
result *= (m - i)
return result
def get_result(n, m):
source = get_mul(m, n)
target = get_mul(n, n)
return source // target
def is_extra(n, m):
if(n == m):
print(1)
return True
if(n == 1):
print(m)
return True
return False
def main():
import sys
for _ in range(t):
n, m = list(map(int, sys.stdin.readline().split()))
if(not is_extra(n, m)):
print(get_result(n, m))
return
if(__name__=="__main__"):
main()
| true |
b7395feb15526974fdb71fbc7267f9fb9a650ccb | Python | ddlinz/PBnB | /testfunction_rosenbrock.py | UTF-8 | 437 | 2.59375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 23 21:47:31 2017
@author: TingYu Ho
r: number of replication
"""
import numpy as np
def testfunction_rosenbrock(X,r):
mu, sigma = 0, 0 # mean and standard deviation
s = np.random.normal(mu, sigma, r)
x = X[0]
y = X[1]
a = 1. - x
b = y - x*x
noise_funtion=a*a + b*b*100.+s
l_noise_funtion = noise_funtion.tolist()
return l_noise_funtion
| true |
e8b48c599a27e6024ae461da09c69ef06d4b9c75 | Python | rizquuula/PaperRockScissor-DicodingSubmission | /MLpredict.py | UTF-8 | 1,868 | 2.53125 | 3 | [] | no_license | from keras.models import load_model
import cv2
import numpy as np
import os
img_width, img_height = 300//2, 200//2
def preprocessing(img_name = None, i = None):
# print(img_name, i)
if i == 0:
img_dir = paperDir
elif i == 1:
img_dir = rockDir
else:
img_dir = scissorDir
img = cv2.imread(img_dir+img_name) # Open image
min_HSV = np.array([0, 60, 40], dtype = "uint8")
max_HSV = np.array([33, 255, 255], dtype = "uint8")
hsvImg = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
binaryImg = cv2.inRange(hsvImg, min_HSV, max_HSV)
masked = cv2.bitwise_and(img, img, mask=binaryImg)
result = cv2.cvtColor(masked, cv2.COLOR_BGR2GRAY)
result = cv2.resize(result, (img_width, img_height))
result = np.expand_dims(result, axis=2)
# print(binaryImg)
# cv2.imshow('See This', result)
# cv2.waitKey(0)
return result
paperDir = 'rockpaperscissors/paper/'
rockDir = 'rockpaperscissors/rock/'
scissorDir = 'rockpaperscissors/scissors/'
paperList = os.listdir(paperDir)
rockList = os.listdir(rockDir)
scissorList = os.listdir(scissorDir)
dirTest = [paperList[650:], rockList[650:], scissorList[650:]]
model = load_model('model-dicoding-razif.h5')
model.compile(loss='binary_crossentropy',
optimizer='SGD',
# optimizer='adam',
metrics=['accuracy'])
print(model.summary())
iTrain = 0
trueThings = 0
total = 0
for dir in dirTest:
for file in dir:
newImage = preprocessing(file, iTrain)
newImage = [newImage]
newImage = np.array(newImage)
predict = model.predict_classes(newImage)
print(file, ' is ', iTrain, ' predicted as ', predict)
if iTrain == predict:
trueThings+=1
total+=1
else:
total+=1
iTrain+=1
print('persentase benar = ', (trueThings/total)*100) | true |
2fce39586ac7c684f2cfe54f3525556f4a37b455 | Python | maxblunck/irony_detection | /src/surface_patterns.py | UTF-8 | 1,766 | 3.125 | 3 | [] | no_license | from collections import Counter
from ngram_feature import NgramFeature
import config
class SurfacePatternFeature(NgramFeature):
"""
Class representing feature f3
extract-method returns a feature-vector of length of its vocabulary
containing surface-pattern-n-gram counts
"""
corpus_key = 'SURFACE_PATTERNS'
n_range = config.n_range_surface_patterns
name = "Surface Pattern"
# below are functions for creating surface patterns when loading corpus
def extract_surface_patterns(corpus, frequency_per_million):
tokens = get_tokens_lower(corpus)
frequencies = frequency_breakdown(tokens)
threshold = frequency_threshold(tokens, frequency_per_million)
hfws = get_high_frequency_words(frequencies, threshold)
extended_corpus = substitute_content_words(corpus, hfws)
return extended_corpus
def get_tokens_lower(corpus):
tokens = []
for instance in corpus:
for token in instance["TOKENS"]:
tokens.append(token.lower())
return tokens
def frequency_breakdown(tokens):
frequencies = Counter(tokens)
return frequencies
def frequency_threshold(tokens, frequency_per_million):
length = len(tokens)
ratio = length/1000000
threshold = int(ratio*frequency_per_million)
return threshold
def get_high_frequency_words(frequencies, threshold):
hfws = []
for key, value in frequencies.items():
if value >= threshold:
hfws.append(key)
return sorted(hfws)
def substitute_content_words(corpus, hfws):
extended_corpus = corpus
for instance in extended_corpus:
sub_tokens = []
for token in instance["TOKENS"]:
if not token.lower() in hfws:
token = "CW"
sub_tokens.append(token)
instance["SURFACE_PATTERNS"] = " ".join(sub_tokens)
return extended_corpus
| true |
a8742c59f79409445384b99674a8eb7d6abadfe5 | Python | Gubba-Jaydeep/MissionRnDPythonCourse | /finalproblems/finaltest_problem2.py | UTF-8 | 1,154 | 4.34375 | 4 | [] | no_license | __author__ = 'Kalyan'
max_marks = 25
problem_notes = '''
A palindrome is a word which spells the same from both ends (case-insensitive).
If a word is not a palindrome, you can make a palindrome out of it by adding letters to either ends of the word.
Your goal is to make a palindrome of the minimum length.
For e.g. cat is not a palindrome, you can add letters at the ends to make palidromes like catac (ending), cattac (ending),
taccat (beginning), tacat (beginning), acattaca (both ends). However, of all this the minimum length ones are catac and tacat.
Notes:
1. If word is not a str, raise TypeError
2. empty string is considered to be a palindrome.
3. if multiple palindromes of same length are possible, return the one earlier in alphabetical ordering (catac in
the example above, keep it case insensitive)
4. Only small letters should be added. The casing of original letters should be unchanged.
5. Write your own tests and test thoroughly.
'''
# returns the min length palidrome defined by the criteria given above.
def make_palindrome(word):
pass
def test_make_palindrome():
assert "cATac" == make_palindrome("cAT") | true |
e172897340f94bfa85f39d2286e073883fb06417 | Python | rakieu/python | /pop cidades igual.py | UTF-8 | 220 | 3.296875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
def main ():
x = 1
fim = int(input("Digite um número: "))
while x <= fim:
print (x)
x = x = 1
# ------
main () | true |
5565750dd483317b2e8bc573e2e70717ef451247 | Python | imdduoming/GameProject | /gui.py | UTF-8 | 43,364 | 3.03125 | 3 | [] | no_license | from tkinter import *
import random as rd
import time
from tkinter import messagebox
from PIL import Image as pim # png 이미지 활용을 위해 사용
from PIL import ImageTk as pit
# ------tk, 프레임 클래스--------
class GameMain(Tk): # Tk(프로그램) 클래스
def __init__(self): # 초기화 - 화면 크기, 크기 조정 불가능 설정
Tk.__init__(self)
self.geometry("1200x900")
self.title("야구 게임")
self.resizable(False, False)
self.frame = None
self.switch_frame(StartPage)
def switch_frame(self, frame_class): # 창 전환 함수
new_frame = frame_class(self)
if self.frame is not None:
self.frame.destroy()
self.frame = new_frame
self.frame.pack()
class StartPage(Frame): # 최초 페이지
def __init__(self, master):
Frame.__init__(self, master, bg='#509134', width='1200', height='900')
self.grid_propagate(0)
self.bgimg = pit.PhotoImage(pim.open('main.png'))
self.bc = Canvas(self, width='1200', height='900')
self.bc.place(x=0, y=0)
self.bg = self.bc.create_image(0, 0, anchor='nw', image=self.bgimg)
self.but1 = Button(self, text="게임 시작", command=lambda: master.switch_frame(NewGame), width='20', height='5')
self.but1.grid(column='0', row='0', padx=125, pady=650)
self.but2 = Button(self, text="튜토리얼", width='20',
height='5', command=lambda: master.switch_frame(Tutorial))
self.but2.grid(column='1', row='0', padx=125, pady=650)
self.but3 = Button(self, text="게임종료", command=quit, width='20', height='5')
self.but3.grid(column='2', row='0', padx=125, pady=650)
class NewGame(Frame): # 게임 시작 페이지, 이름과 횟수를 설정
def __init__(self, master):
Frame.__init__(self, master, width='1200', height='900')
self.grid_propagate(0)
self.bgimg = pit.PhotoImage(pim.open('background.png'))
self.bc = Canvas(self, width='1200', height='900')
self.bc.place(x=0, y=0)
self.bc.create_image(0, 0, anchor='nw', image=self.bgimg)
self.lab1 = Label(self, text='당신의 팀 이름을 입력해주세요: ', font=("맑은 고딕", 20))
self.lab1.grid(column='0', row='0', padx='100', pady='50')
self.ent1 = Entry(self, font=("맑은 고딕", 20))
self.ent1.grid(column='1', row='0', padx='100', pady='50')
self.lab2 = Label(self, text='진행할 게임 횟수를 입력해주세요(1~9): ', font=("맑은 고딕", 20))
self.lab2.grid(column='0', row='1', padx='100', pady='50')
self.ent2 = Entry(self, font=("맑은 고딕", 20))
self.ent2.grid(column='1', row='1', padx='100', pady='50')
self.but1 = Button(self, text='게임 시작', command=lambda: self.game_start(master),
width='20', height='6', font=("맑은 고딕", 20))
self.but1.grid(column='1', row='2', padx='100', pady='50')
def game_start(self, master): # 게임 시작 버튼 작동함수
if 1 <= int(self.ent2.get()) <= 9:
global playerOp, player, playerName, gameNum, inning_num
player = rd.choice(playerOp)
playerName = self.ent1.get()
gameNum = int(self.ent2.get())
if player == '선공':
inning_num += 1
messagebox.showinfo("선공", "당신은 선공입니다.")
# self.destroy()
master.switch_frame(PlayerAttack)
elif player == '후공':
inning_num += 1
messagebox.showinfo("후공", "당신은 후공입니다.")
# self.destroy()
master.switch_frame(ComAttack)
else:
messagebox.showwarning("게임 횟수", "게임 횟수를 재설정해주세요.\n (1~9) ")
class ResultPage(Frame): # 결과 페이지, 게임 진행을 연결, 끝났을지 결과를 표출하고 종료
def __init__(self, master):
Frame.__init__(self, master, width='1200', height='900')
self.pack_propagate(0)
self.bgimg = pit.PhotoImage(pim.open('background.png'))
self.bc = Canvas(self, width='1200', height='900')
self.bc.place(x=0, y=0)
self.bc.create_image(0, 0, anchor='nw', image=self.bgimg)
self.blab1 = Label(self, text=''.format(), height='20')
self.blab1.pack()
self.tot = TotalScore(self)
self.tot.pack()
self.blab1 = Label(self, height='10')
self.blab1.pack()
self.pg_button = Button(self, text='진행', command=lambda: self.progress(master), width='20', height='5')
if half_game == '말' and inning_num == gameNum:
self.pg_button.config(text='종료')
self.pg_button.pack()
# noinspection PyMethodMayBeStatic
def progress(self, master): # 진행 버튼 작동함수수
global half_game, inning_num
if half_game == '말':
if inning_num == gameNum:
if user_score > com_score:
messagebox.showinfo("승리", "당신의 승리입니다!")
elif user_score == com_score:
messagebox.showinfo("무승부", "무승부입니다.")
else:
messagebox.showerror("패배", "당신의 패배입니다.")
master.switch_frame(StartPage)
else:
inning_num += 1
half_game = '초'
if player == '선공':
master.switch_frame(PlayerAttack)
elif player == '후공':
master.switch_frame(ComAttack)
elif half_game == '초':
half_game = '말'
if player == '선공':
master.switch_frame(ComAttack)
elif player == '후공':
master.switch_frame(PlayerAttack)
class PlayerAttack(Frame): # 공격 화면 함수
def __init__(self, master):
Frame.__init__(self, master, width='1200', height='900')
self.bgimg = pit.PhotoImage(pim.open('background.png'))
self.bc = Canvas(self, width='1200', height='900')
self.bc.place(x=0, y=0)
self.bc.create_image(0, 0, anchor='nw', image=self.bgimg)
self.bfr = BaseFrame(self)
self.bfr.place(x=40, y=40)
self.sbo = SBO(self)
self.sbo.place(x=1000, y=700)
self.but = BallButton(self)
self.but.place(x=400, y=600)
self.atn = attackNum(self)
self.atn.place(x=500, y=250)
self.scr = ScoreBoard(self)
self.scr.place(x=950, y=40)
self.start_button = Button(self, text='시작', width="25", height="8", command=self.play, font=("맑은 고딕", 15))
self.start_button.place(x=475, y=300)
def play(self): # 공격 게임 진행함수
self.start_button.destroy()
strikeNum = 0
ballNum = 0
outNum = 0
global inning_score, base
inning_score = 0
base = [0, 0, 0, 0, 0]
while outNum < 3:
self.bfr.base_update()
self.sbo.sbo_update(strikeNum, ballNum, outNum)
self.scr.score_update()
self.but.button_reset()
self.atn.all_reset()
self.master.update()
time.sleep(1.5)
defen = 0
player_hit = []
num_list = list(range(1, 10))
com_pitch = rd.sample(num_list, 3) # 수비자(컴퓨터)의 투구(리스트)
coms = sum(com_pitch)
# 숫자 표시부분 초기화
self.atn.pitch_update(coms) # 컴퓨터가 던진 수 합
self.atn.lab2.config(text='당신이 고른 수는')
self.atn.master.update()
# 플레이어의 입력을 받는 부분
self.wait_variable(self.but.n)
player_hit.append(self.but.n.get())
self.atn.box21.config(text=str(self.but.n.get()))
self.atn.master.update()
self.wait_variable(self.but.n)
player_hit.append(self.but.n.get())
self.atn.box22.config(text=str(self.but.n.get()))
self.atn.master.update()
self.wait_variable(self.but.n)
player_hit.append(self.but.n.get())
self.atn.box23.config(text=str(self.but.n.get()))
self.atn.master.update()
user_decision = decision(player_hit, com_pitch)
self.atn.lab3.config(text=user_decision)
self.atn.master.update()
time.sleep(1.5)
if user_decision == 'homerun':
messagebox.showwarning("홈런", "홈런! 축하합니다!")
elif (((
user_decision != 'homerun' and user_decision != 'foul') and user_decision != 'strike') and user_decision != 'ball'):
defen = com_defense(com_pitch, player_hit)
if defen == 1:
messagebox.showerror("적 수비 성공", "적이 수비를 성공했습니다.")
strikeNum, ballNum, outNum = attack_score(user_decision, defen, strikeNum, ballNum,
outNum) # out횟수와 각 1,2,3,4루의 상황 결정
global user_score, come_home
user_score += come_home
come_home = 0
time.sleep(1.5)
uin_score.append(inning_score)
messagebox.showinfo("3 OUT", "3 OUT 으로 공수교대합니다.")
self.master.switch_frame(ResultPage)
class ComAttack(Frame): # 수비 게임 화면
def __init__(self, master):
Frame.__init__(self, master, width='1200', height='900')
self.bgimg = pit.PhotoImage(pim.open('background.png'))
self.bc = Canvas(self, width='1200', height='900')
self.bc.place(x=0, y=0)
self.bc.create_image(0, 0, anchor='nw', image=self.bgimg)
self.bfr = BaseFrame(self)
self.bfr.place(x=40, y=40)
self.sbo = SBO(self)
self.sbo.place(x=1000, y=700)
self.but = BallButton(self)
self.but.place(x=400, y=600)
self.atn = attackNum(self)
self.atn.place(x=450, y=250)
self.scr = ScoreBoard(self)
self.scr.place(x=950, y=40)
self.start_button = Button(self, text='시작', width=25, height=8, command=self.play, font=("맑은 고딕", 15))
self.start_button.place(x=475, y=300)
self.d_list = []
def play(self): # 수비 게임 진행함수
self.start_button.destroy()
strikeNum = 0
ballNum = 0
outNum = 0
global inning_score, base
inning_score = 0
base = [0, 0, 0, 0, 0]
while outNum < 3:
self.bfr.base_update()
self.sbo.sbo_update(strikeNum, ballNum, outNum)
self.scr.score_update()
self.but.button_reset()
self.atn.all_reset()
self.master.update()
time.sleep(1)
player_pitch = []
defen = 2
self.atn.lab1.config(text='숫자 세개를 골라주세요!')
self.atn.master.update()
# 플레이어의 입력을 받는 부분
self.wait_variable(self.but.n)
player_pitch.append(self.but.n.get())
self.atn.box11.config(text=str(self.but.n.get()))
self.atn.master.update()
self.wait_variable(self.but.n)
player_pitch.append(self.but.n.get())
self.atn.box12.config(text=str(self.but.n.get()))
self.atn.master.update()
self.wait_variable(self.but.n)
player_pitch.append(self.but.n.get())
self.atn.box13.config(text=str(self.but.n.get()))
self.atn.master.update()
self.atn.lab1.config(text='내가 고른 수는')
self.atn.lab2.config(text="상대가 숫자를 예측중입니다.")
self.master.update()
time.sleep(1.5)
c_hit = com_hit(player_pitch)
user_decision = decision(player_pitch, c_hit)
self.atn.lab3.config(text=user_decision)
self.atn.master.update()
time.sleep(2)
if (((
user_decision != 'homerun' and user_decision != 'foul') and user_decision != 'strike') and user_decision != 'ball'):
while defen > 1:
self.d_list = []
self.player_defense()
defen = user_defense(player_pitch, c_hit, self.d_list)
if defen == 1:
messagebox.showerror("수비 성공", "수비 성공! 적을 아웃시켰습니다.")
outNum += 1
break
elif defen == 0:
messagebox.showerror("수비 실패", "수비 실패! 적이 진루합니다.")
strikeNum, ballNum, outNum = attack_score(user_decision, defen, strikeNum, ballNum,
outNum)
break
else:
self.atn.lab2.config(text='실제 오차와 가깝습니다!')
self.atn.lab3.config(text='다시 예측해보세요.')
self.master.update()
time.sleep(2)
else:
strikeNum, ballNum, outNum = attack_score(user_decision, 0, strikeNum, ballNum,
outNum)
global com_score, come_home
com_score += come_home
come_home = 0
time.sleep(1)
cin_score.append(inning_score)
messagebox.showinfo("3 OUT", "3 OUT 으로 공수교대합니다.")
self.master.switch_frame(ResultPage)
def player_defense(self):
self.atn.lab2.config(text="상대의 안타! 얼마나 차이날까요?")
self.atn.lab3.config(text="오차를 예측하세요")
self.atn.box2_reset()
self.but.button_reset()
self.but.button0.config(text='0', state='normal')
self.master.update()
self.wait_variable(self.but.n)
self.d_list.append(self.but.n.get())
self.atn.box21.config(text=str(self.but.n.get()))
self.but.button_reset()
self.but.button0.config(text='0', state='normal')
self.atn.master.update()
self.wait_variable(self.but.n)
self.d_list.append(self.but.n.get())
self.atn.box22.config(text=str(self.but.n.get()))
self.but.button_reset()
self.but.button0.config(text='0', state='normal')
self.atn.master.update()
self.wait_variable(self.but.n)
self.d_list.append(self.but.n.get())
self.atn.box23.config(text=str(self.but.n.get()))
self.but.button_reset()
self.but.button0.config(text='0', state='normal')
self.atn.master.update()
class Tutorial(Frame): # 튜토리얼 화면 함수
def __init__(self, master):
Frame.__init__(self, master, width='1200', height='900')
self.bgimg = pit.PhotoImage(pim.open('background.png'))
self.bc = Canvas(self, width='1200', height='900')
self.bc.place(x=0, y=0)
self.bc.create_image(0, 0, anchor='nw', image=self.bgimg)
self.d_list = []
self.bfr = BaseFrame(self)
self.bfr.place(x=40, y=40)
self.sbo = SBO(self)
self.sbo.place(x=1000, y=700)
self.but = BallButton(self)
self.but.place(x=400, y=600)
self.atn = attackNum(self)
self.atn.place(x=450, y=250)
self.scr = ScoreBoard(self)
self.scr.place(x=950, y=40)
self.explain_frame = Frame(self, width=800, height=400, bg='#C5FFFF', relief='solid', bd='2')
self.explain_frame.pack_propagate(0)
self.explain_frame.place(x=200, y=200)
self.elab = Label(self.explain_frame, text='''
간단한 조작을 통해 게임을 배워봅시다.''', bg='#C5FFFF',
font=("맑은 고딕", 12))
self.elab.pack(anchor='center', pady=10)
self.ebtn = Button(self.explain_frame, text='다음', command=self.tutorial)
self.ebtn.pack(side='bottom', anchor='center', pady=10)
self.tflag = 0
def tutorial(self): # flag가 올라갈때마다 진행됨
if self.tflag == 0:
self.elab.config(text='''
이 게임은 숫자로 하는 야구 게임입니다.
서로 상대방이 어떤 숫자 3개를 선택했는지 예상하면서 공격과 수비를 합니다.
상대방의 숫자 3개가 각각 무엇이고 어디에 있는지 맞춰보는 게임입니다.''')
self.tflag += 1
elif self.tflag == 1:
self.elab.config(text='''
어떻게 하는지 이해해보기 위해 직접 해봅시다.
게임은 수비 플레이어가 투수가 되어 숫자 세개를 상대방에게 던지면서 시작합니다.
세 숫자는 모두 달라야 합니다.
숫자 3 6 5을 입력해보세요.''')
self.tflag += 1
elif self.tflag == 2:
self.explain_frame.place_forget()
self.play1()
elif self.tflag == 3:
self.explain_frame.place(x=200, y=200)
self.elab.config(text='''
잘 하셨습니다!
이제 적(컴퓨터)이 당신이 던진 숫자 3개의 합을 보고 숫자를 예측합니다.
상대가 맞추면 베이스로 나가게 되어 득점의 기회를 얻게 됩니다.
하지만 수비쪽에서도 이를 다시 한번 방어할 기회가 있습니다.''')
self.tflag += 1
elif self.tflag == 4:
self.elab.config(text='''
적이 숫자를 입력했는데 일정 개수 이상 맟춘다면
상대방은 안타를 치게 됩니다. 이때가 바로 당신의 수비 기회입니다.
수비하라는 메세지가 뜨면 내가 보낸 숫자와 적이 예측한 숫자가
얼마나 다를지 예측해야 합니다.''')
self.tflag += 1
elif self.tflag == 5:
self.elab.config(text='''
실제로 해보겠습니다.
당신이 보낸 365와 87만큼 차이난다고 예측했다고 합시다.
예측 숫자에 0 8 7을 입력해주세요''')
self.tflag += 1
elif self.tflag == 6:
self.explain_frame.place_forget()
self.play2()
elif self.tflag == 7:
self.explain_frame.place(x=200, y=200)
self.elab.config(text='''
잘 하셨습니다!
예측한 오차가 100보다 작으면 수비에 성공하여 적을 아웃시킵니다.
200보다 작고 100보다 크다면 다시 한번 예측할 기회를 갖게 됩니다.
기존에 예측한 것보다 적의 숫자에 다가가야겠죠?''')
self.tflag += 1
elif self.tflag == 8:
self.elab.config(text='''
이번엔 공격을 연습해봅시다.
공격 플레이어는 상대방이 던진 숫자 3개의 합을 보고
적이 어떤 숫자를 입력했는지 예상합니다.''')
self.tflag += 1
elif self.tflag == 9:
self.elab.config(text='''
이때 예측하는 숫자의 합이 꼭 적이 던진 수가 아니여도 됩니다.
예측되는 숫자를 전략적으로 제시해보세요.
상대방이 9 라고 제시했을 때 당신은 어떤 숫자 3개라고 생각하시나요?''')
self.tflag += 1
elif self.tflag == 10:
self.explain_frame.place_forget()
self.play3()
elif self.tflag == 11:
self.explain_frame.place(x=200, y=200)
self.elab.config(text='''
잘 하셨습니다!
이렇게 공격에 성공하여 홈런을 하거나 안타를 통해
주자를 홈까지 보내면 득점하게 됩니다.''')
self.tflag += 1
elif self.tflag == 12:
self.elab.config(text='''
이제 게임 진행이 이해되시나요?
만약 잘 이해되지 않는다면 한번 더 튜토리얼을 플레이하시고
이해된다면 게임 시작을 통해 실제 게임을 플레이해보세요!''')
self.tflag += 1
elif self.tflag == 13:
self.master.switch_frame(StartPage)
def play1(self):
self.bfr.base_update()
self.scr.score_update()
self.but.button_reset()
self.atn.all_reset()
self.master.update()
time.sleep(1)
pitch_flag = 0
player_pitch = [0, 0, 0]
while player_pitch != [3, 6, 5]:
self.atn.all_reset()
self.atn.lab1.config(text='3 6 5를 차례로 입력하세요')
self.atn.master.update()
player_pitch = [0, 0, 0]
if pitch_flag == 1:
self.atn.lab1.config(text='다시 3 6 5를 입력해보세요')
self.atn.master.update()
self.but.button_reset()
self.wait_variable(self.but.n)
player_pitch[0] = self.but.n.get()
self.atn.box11.config(text=str(self.but.n.get()))
self.atn.master.update()
self.wait_variable(self.but.n)
player_pitch[1] = self.but.n.get()
self.atn.box12.config(text=str(self.but.n.get()))
self.atn.master.update()
self.wait_variable(self.but.n)
player_pitch[2] = self.but.n.get()
self.atn.box13.config(text=str(self.but.n.get()))
self.atn.master.update()
pitch_flag = 1
self.tflag += 1
self.tutorial()
def play2(self):
self.atn.lab2.config(text="상대의 안타! 얼마나 차이날까요?")
self.atn.lab3.config(text="0 8 7 을 입력하세요")
self.atn.box2_reset()
self.but.button_reset()
self.but.button0.config(text='0', state='normal')
self.master.update()
def_flag = 0
while self.d_list != [0, 8, 7]:
self.d_list = [0, 0, 0]
self.atn.box2_reset()
if def_flag == 1:
self.atn.lab3.config(text='다시 0 8 7을 입력해보세요')
self.atn.master.update()
self.wait_variable(self.but.n)
self.d_list[0] = self.but.n.get()
self.atn.box21.config(text=str(self.but.n.get()))
self.but.button_reset()
self.but.button0.config(text='0', state='normal')
self.atn.master.update()
self.wait_variable(self.but.n)
self.d_list[1] = self.but.n.get()
self.atn.box22.config(text=str(self.but.n.get()))
self.but.button_reset()
self.but.button0.config(text='0', state='normal')
self.atn.master.update()
self.wait_variable(self.but.n)
self.d_list[2] = self.but.n.get()
self.atn.box23.config(text=str(self.but.n.get()))
self.but.button_reset()
self.but.button0.config(text='0', state='normal')
self.atn.master.update()
def_flag = 1
messagebox.showerror("수비 성공", "수비 성공! 적을 아웃시켰습니다.")
self.tflag += 1
self.tutorial()
def play3(self):
self.bfr.base_update()
self.scr.score_update()
self.but.button_reset()
self.atn.all_reset()
self.master.update()
time.sleep(0.5)
player_hit = []
hit_flag = 0
coms = 9
while player_hit != [5, 1, 3]:
player_hit = [0, 0, 0]
self.atn.all_reset()
self.but.button_reset()
self.atn.master.update()
self.atn.pitch_update(coms) # 컴퓨터가 던진 수 합
self.atn.lab2.config(text='당신이 고른 수는')
self.atn.lab3.config(text='5 1 3을 입력해보세요')
if hit_flag == 1:
self.atn.lab3.config(text='다시 5 1 3을 입력해보세요')
self.atn.master.update()
self.atn.master.update()
self.wait_variable(self.but.n)
player_hit[0] = self.but.n.get()
self.atn.box21.config(text=str(self.but.n.get()))
self.atn.master.update()
self.wait_variable(self.but.n)
player_hit[1] = self.but.n.get()
self.atn.box22.config(text=str(self.but.n.get()))
self.atn.master.update()
self.wait_variable(self.but.n)
player_hit[2] = self.but.n.get()
self.atn.box23.config(text=str(self.but.n.get()))
self.atn.master.update()
hit_flag = 1
messagebox.showinfo("홈런", "축하합니다! 홈런입니다!")
self.tflag += 1
self.tutorial()
# ---------화면구성요소---------
class BaseFrame(Frame): # 진루 상황 부분 프레임
def __init__(self, master):
Frame.__init__(self, master)
self.config(width='200', height='200', relief='solid', bd='1')
self.c_base = Canvas(self, width='200', height='200')
self.c_base.pack()
self.base_update()
self.master.update()
def base_update(self):
global base
if base[1] == 1: # 1루
self.c_base.create_polygon(145, 73, 109, 109, 145, 145, 181, 109, fill='yellow', outline='black')
else:
self.c_base.create_polygon(145, 73, 109, 109, 145, 145, 181, 109, fill='white', outline='black')
if base[2] == 1: # 2루
self.c_base.create_polygon(100, 29, 64, 65, 100, 101, 136, 65, fill='yellow', outline='black')
else:
self.c_base.create_polygon(100, 29, 64, 65, 100, 101, 136, 65, fill='white', outline='black')
if base[3] == 1: # 3루
self.c_base.create_polygon(56, 73, 20, 109, 56, 145, 92, 109, fill='yellow', outline='black')
else:
self.c_base.create_polygon(56, 73, 20, 109, 56, 145, 92, 109, fill='white', outline='black')
class SBO(Frame): # 스트라이크, 볼, 아웃 표시 부분
def __init__(self, master):
Frame.__init__(self, master)
self.config(width='150', height='100', relief='solid', bd='1')
self.grid_propagate(0)
for i in range(3):
self.rowconfigure(i, weight=1)
for i in range(3):
self.columnconfigure(i, weight=1)
self.S = Label(self, text='S ')
self.S.grid(column=0, row=0, padx='2')
self.S_count = Label(self, text='', fg='orange')
self.S_count.grid(column=1, row=0)
self.B = Label(self, text='B ', padx='2')
self.B.grid(column=0, row=1)
self.B_count = Label(self, text='', fg='green')
self.B_count.grid(column=1, row=1)
self.O = Label(self, text='O ', padx='2')
self.O.grid(column=0, row=2)
self.O_count = Label(self, text='', fg='red')
self.O_count.grid(column=1, row=2)
def sbo_update(self, s, b, o):
s_st = '●' * s + ' ' * (3 - s)
b_st = '●' * b + ' ' * (3 - b)
o_st = '●' * o + ' ' * (3 - o)
self.S_count.config(text=s_st)
self.B_count.config(text=b_st)
self.O_count.config(text=o_st)
class ScoreBoard(Frame): # 점수판 표시 프레임
def __init__(self, master):
Frame.__init__(self, master)
self.config(width='200', height='150', relief='solid', bd='1')
self.grid_propagate(0)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.columnconfigure(1, weight=1)
self.rowconfigure(1, weight=1)
self.team_name1 = Label(self)
self.team_name2 = Label(self)
self.team_name1.grid(column='0', row='0')
self.team_name2.grid(column='0', row='1')
self.team_score1 = Label(self, text="0")
self.team_score2 = Label(self, text="0")
self.team_score1.grid(column='1', row='0')
self.team_score2.grid(column='1', row='1')
self.innnum = Label(self, text="0회")
self.innnum.grid(column='0', row='2', columnspan='2')
if player == '선공':
self.team_name1.config(text=playerName)
self.team_name2.config(text="COM")
elif player == '후공':
self.team_name1.config(text="COM")
self.team_name2.config(text=playerName)
self.innnum.config(text='{}회 {}'.format(inning_num, half_game))
self.score_update()
def score_update(self):
if player == '선공':
self.team_score1.config(text=user_score)
self.team_score2.config(text=com_score)
elif player == '후공':
self.team_score2.config(text=user_score)
self.team_score1.config(text=com_score)
self.master.update()
class BallButton(Frame): # 버튼 입력부 프레임
def __init__(self, master):
Frame.__init__(self, master)
self.config(width='400', height='200', relief='solid', bd='1')
self.n = IntVar()
self.grid_propagate(0)
self.rowconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
for i in range(5):
self.columnconfigure(i, weight=1)
self.button0 = Button(self, width='9', height='4', text='', state='disabled')
self.button0.config(command=lambda: [self.number_select(0), self.button1.config(state='disabled')])
self.button1 = Button(self, width='9', height='4', text='1')
self.button1.config(command=lambda: [self.number_select(1), self.button1.config(state='disabled')])
self.button2 = Button(self, width='9', height='4', text='2')
self.button2.config(command=lambda: [self.number_select(2), self.button2.config(state='disabled')])
self.button3 = Button(self, width='9', height='4', text='3')
self.button3.config(command=lambda: [self.number_select(3), self.button3.config(state='disabled')])
self.button4 = Button(self, width='9', height='4', text='4')
self.button4.config(command=lambda: [self.number_select(4), self.button4.config(state='disabled')])
self.button5 = Button(self, width='9', height='4', text='5')
self.button5.config(command=lambda: [self.number_select(5), self.button5.config(state='disabled')])
self.button6 = Button(self, width='9', height='4', text='6')
self.button6.config(command=lambda: [self.number_select(6), self.button6.config(state='disabled')])
self.button7 = Button(self, width='9', height='4', text='7')
self.button7.config(command=lambda: [self.number_select(7), self.button7.config(state='disabled')])
self.button8 = Button(self, width='9', height='4', text='8')
self.button8.config(command=lambda: [self.number_select(8), self.button8.config(state='disabled')])
self.button9 = Button(self, width='9', height='4', text='9')
self.button9.config(command=lambda: [self.number_select(9), self.button9.config(state='disabled')])
self.button0.grid(column='0', row='0')
self.button1.grid(column='1', row='0')
self.button2.grid(column='2', row='0')
self.button3.grid(column='3', row='0')
self.button4.grid(column='4', row='0')
self.button5.grid(column='0', row='1')
self.button6.grid(column='1', row='1')
self.button7.grid(column='2', row='1')
self.button8.grid(column='3', row='1')
self.button9.grid(column='4', row='1')
def number_select(self, n):
self.n.set(n)
def button_reset(self):
self.button0.config(text='', state='disabled')
self.button1.config(state='normal')
self.button2.config(state='normal')
self.button3.config(state='normal')
self.button4.config(state='normal')
self.button5.config(state='normal')
self.button6.config(state='normal')
self.button7.config(state='normal')
self.button8.config(state='normal')
self.button9.config(state='normal')
class attackNum(Frame): # 공수 숫자 표시 프레임
def __init__(self, master):
Frame.__init__(self, master)
self.config(width='300', height='300', relief='solid', bd='1')
self.lab1 = Label(self)
self.box11 = Label(self, width='9', height='4', relief='solid')
self.box12 = Label(self, width='9', height='4', relief='solid')
self.box13 = Label(self, width='9', height='4', relief='solid')
self.lab2 = Label(self)
self.box21 = Label(self, width='9', height='4', relief='solid')
self.box22 = Label(self, width='9', height='4', relief='solid')
self.box23 = Label(self, width='9', height='4', relief='solid')
self.lab3 = Label(self)
self.lab1.grid(column='0', row='0', columnspan='3')
self.box11.grid(column='0', row='1', padx='2')
self.box12.grid(column='1', row='1', padx='2')
self.box13.grid(column='2', row='1', padx='2')
self.lab2.grid(column='0', row='2', columnspan='3')
self.box21.grid(column='0', row='3', padx='2')
self.box22.grid(column='1', row='3', padx='2')
self.box23.grid(column='2', row='3', padx='2')
self.lab3.grid(column='0', row='4', columnspan='3')
def all_reset(self):
self.lab1.config(text='')
self.box11.config(text='')
self.box12.config(text='')
self.box13.config(text='')
self.lab2.config(text='')
self.box21.config(text='')
self.box22.config(text='')
self.box23.config(text='')
self.lab3.config(text='')
def box1_reset(self):
self.box11.config(text='')
self.box12.config(text='')
self.box13.config(text='')
def box2_reset(self):
self.box21.config(text='')
self.box22.config(text='')
self.box23.config(text='')
def pitch_update(self, coms):
self.lab1.config(text='상대방이 고른 숫자 3개의 합은')
tfactor = str(int(coms / 10))
ofactor = str(coms % 10)
self.box12.config(text=tfactor)
self.box13.config(text=ofactor)
class TotalScore(Frame): # 종합 점수판 프레임
def __init__(self, master):
Frame.__init__(self, master)
self.config(width='800', height='600', relief='solid', bd='1')
self.box0l = []
self.tname1 = Label(self, width='5', height='4', relief='solid', bd='1')
self.tname2 = Label(self, width='5', height='4', relief='solid', bd='1')
self.tname1.grid(column=0, row=1)
self.tname2.grid(column=0, row=2)
for i in range(9):
self.box0l.append(Label(self, width='7', height='2', relief='solid', bd='1', text=str(i + 1)))
self.box0l[i].grid(column=i + 1, row=0)
self.box0l.append(Label(self, width='7', height='2', relief='solid', text='총점', bd='1'))
self.box0l[9].grid(column=10, row=0)
self.box1l = []
for i in range(10):
self.box1l.append(Label(self, width='7', height='4', relief='solid', bd='1'))
self.box1l[i].grid(column=i + 1, row=1)
self.box2l = []
for i in range(10):
self.box2l.append(Label(self, width='7', height='4', relief='solid', bd='1'))
self.box2l[i].grid(column=i + 1, row=2)
if player == '선공':
self.tname1.config(text=playerName)
for i in range(len(uin_score)):
self.box1l[i].config(text=uin_score[i])
self.box1l[9].config(text=user_score)
self.tname2.config(text='COM')
for i in range(len(cin_score)):
self.box2l[i].config(text=cin_score[i])
self.box2l[9].config(text=com_score)
elif player == '후공':
self.tname2.config(text=playerName)
for i in range(len(uin_score)):
self.box2l[i].config(text=uin_score[i])
self.box2l[9].config(text=user_score)
self.tname1.config(text='COM')
for i in range(len(cin_score)):
self.box1l[i].config(text=cin_score[i])
self.box1l[9].config(text=com_score)
# ------함수--------
def randpart(n): # 합(n)을 받았을 때, 임의의 3개 한자리 수로 분할하는 함수
from random import randint
while True:
if n < 12: # n은 항상 6보다 큼
i = 1
f = n - 3
elif n < 18:
i = 1
f = 9
else:
i = n - 17
f = 9
a = randint(i, f)
if n - a < 11:
i = 1
f = n - a - 1
else:
i = n - a - 9
f = 9
b = randint(i, f)
c = n - a - b
if a != b and b != c and c != a:
res = [a, b, c]
return res
def com_hit(player_pitch_list): # 타자가 투수가 공던지면 배트 휘두름
player_pitch_sum = sum(player_pitch_list) # 세자리수 합
cpitch = randpart(player_pitch_sum)
return cpitch
def decision(playhit, compitch):
bothcorrect = 0
numcorrect = 0
# 변수 초기화
for i in range(0, 3):
if playhit[i] == compitch[i]: # 타자의 i번째 숫자/자리 판정
bothcorrect += 1 # 자릿수o숫자o
if playhit[i] in compitch:
numcorrect += 1 # 자릿수x 숫자o
if bothcorrect == 0 and numcorrect == 0:
return 'strike' # 1out
elif (bothcorrect == 0 and numcorrect == 1) or (bothcorrect == 0 and numcorrect == 2):
return 'foul'
elif bothcorrect == 1 and numcorrect == 1:
return 'ball'
elif (bothcorrect == 0 and numcorrect == 3) or (bothcorrect == 1 and numcorrect == 2):
return 'singlehit'
elif bothcorrect == 2 and numcorrect == 2:
return 'doublehit'
elif bothcorrect == 1 and numcorrect == 3:
return 'triplehit'
elif bothcorrect == 3 and numcorrect == 3:
return 'homerun'
def defense_num(player_pitch_list, c_hit): # 투수의 수와 타자의 수 오차 구하기(선수비일때)
num_pitch = 100 * player_pitch_list[0] + 10 * player_pitch_list[1] + player_pitch_list[2]
num_hit = 100 * c_hit[0] + 10 * c_hit[1] + c_hit[2]
hit_margin = abs(num_pitch - num_hit)
return hit_margin
def user_defense(player_pitch, c_hit, d_list): # 수비수가 타자의 오차 예측하기
d_predict = 100 * d_list[0] + 10 * d_list[1] + d_list[2]
hit_margin = defense_num(player_pitch, c_hit) # 타자의 오차
defense_margin = abs(d_predict - hit_margin) # 수비수의 오차
# print(player_pitch, c_hit, d_list, d_predict, hit_margin, defense_margin)
if defense_margin <= 100:
defen = 1
return defen
elif defense_margin <= 200:
defen = 2
return defen
else:
defen = 0
return defen
def playerhit(pitch): # 원소 3개의 리스트를 받으면 합을 표출하고, 플레이어의 반응을 얻고 플레이어가 입력한 리스트 구하기
com_sum = 0
for i in pitch:
com_sum += i
print('투수가 던진 공의 합은 {}입니다.'.format(com_sum))
a, b, c = input('합이 {}인 9 이하의 서로 다른 자연수 세 개를 고르시오(쉼표로 구분): '.format(com_sum)).split(',')
hit = [a, b, c]
play_hit = [int(i) for i in hit]
return play_hit
def cdefense_num(com_pitch, player_hit): # 투수의 수와 타자의 수 오차 구하기(컴퓨터가 수비할때)
num_pitch = 100 * com_pitch[0] + 10 * com_pitch[1] + com_pitch[2]
num_hit = 100 * player_hit[0] + 10 * player_hit[1] + player_hit[2]
hit_margin = abs(num_pitch - num_hit)
return hit_margin
def com_defense(com_pitch, player_hit): # 수비수(컴퓨터)가 타자의 오차 예측하기
com_defense_predict = rd.randint(1, 987 - 123) # 수비자(컴퓨터)가 예측한 오차값
hit_margin = cdefense_num(com_pitch, player_hit) # 실제 오차
defense_margin = abs(com_defense_predict - hit_margin) # 실제 값과 오차값의 차
if defense_margin <= 100:
defen = 1 # 수비성공
return defen
elif defense_margin <= 200:
return com_defense(com_pitch, player_hit)
else:
defen = 0
return defen
def getonbase(n=1):
global base, inning_score, come_home
base[0] = 1 # 한명을 타석으로 보냄
for _ in range(n): # n루타 는 곧 n회의 한칸 진루
for i in range(3, -1, -1):
if base[i] > 0: # i루에 사람이 있을경우 앞으로 보내야함, 3루부터 한칸씩 전진.
base[i] -= 1
base[i + 1] += 1
come_home = base[4]
inning_score += base[4] # 홈에 도착한 인원들을 합산
base[4] = 0 # 홈 초기화
def gon_ball():
global base
if base[1] == 1:
if base[2] == 1:
getonbase(1)
elif base[2] == 0:
base[2] = 1
elif base[1] == 0:
base[1] = 1
def attack_score(user_decision, defen, strikeNum, ballNum, outNum): # 타자의 결정에따라 상황 정해짐
if user_decision == 'strike':
strikeNum += 1
elif user_decision == 'foul':
if strikeNum != 2:
strikeNum += 1
elif user_decision == 'ball':
ballNum += 1
if ballNum == 4: # 볼넷일 때
strikeNum = 0
ballNum = 0
gon_ball()
elif user_decision == 'singlehit':
if defen == 0:
getonbase(1)
else:
outNum += 1
strikeNum = 0
ballNum = 0
elif user_decision == 'doublehit':
if defen == 0:
getonbase(2)
else:
outNum += 1
strikeNum = 0
ballNum = 0
elif user_decision == 'triplehit':
if defen == 0:
getonbase(3)
else:
outNum += 1
strikeNum = 0
ballNum = 0
elif user_decision == 'homerun':
getonbase(4)
strikeNum = 0
ballNum = 0
if strikeNum == 3:
outNum += 1
strikeNum = 0
ballNum = 0
return strikeNum, ballNum, outNum
if __name__ == '__main__': # 이 py 파일이 실행되었을 때만 실행
base = [0, 0, 0, 0, 0] # 타석 1루 2루 3루 홈
inning_score = 0
user_score = 0
com_score = 0
uin_score = []
cin_score = []
come_home = 0
playerOp = ['선공', '후공']
player = ''
playerName = ''
inning_num = 0
half_game = '초'
gameNum = 0
game = GameMain()
game.mainloop()
| true |
029279c8d1a5bedb0e6396dc91ed6ed751eb99d1 | Python | huozhiwei/SafeNL | /UI/ProcessCCSL.py | UTF-8 | 450 | 3 | 3 | [] | no_license | # -*- encoding:utf-8 -*-
from Process.CCSLToMyCCSL import CCSLToMyCCSL
def ProcessCCSL(inputMyCCSLstr):
# 传入的每条CCSL元素包含着用";"隔开的各种MyCCSL语句
tmpList = inputMyCCSLstr.split(";")
text = ""
for i,tmpstr in enumerate(tmpList):
tmpList[i] = tmpstr.strip()
for i,tmpstr in enumerate(tmpList):
if tmpstr and not tmpstr.isspace():
text = text + tmpstr + "\n"
return text
| true |
d6adca89673bb9524adb08b9ee38e21d7074b567 | Python | tonysyu/deli | /deli/stylus/segment_stylus.py | UTF-8 | 993 | 3.640625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | import numpy as np
from .line_stylus import LineStylus
class SegmentStylus(LineStylus):
""" A Flyweight object for drawing line segemnts.
Line segments, unlike lines drawn by `LineStylus`, are strictly straight
line pairs of start and end points ((x0, y0), (x1, y2)).
"""
def draw(self, gc, starts, ends):
""" Draw a series of straight line segments between points.
Parameters
----------
gc : GraphicsContext
The graphics context where elements are drawn.
starts, ends : array, shape (N, 2) or (2,)
Starting and ending points for straight line segments. Each row
of `starts` and `ends` define an (x, y) point.
"""
# Turn arrays with shape (2,) to (1, 2)
starts = np.atleast_2d(starts)
ends = np.atleast_2d(ends)
with gc:
self.update_style(gc)
gc.begin_path()
gc.line_set(starts, ends)
gc.stroke_path()
| true |
469d8b52287f86d131828934c76874f851931e75 | Python | voussoir/etiquette | /etiquette/searchhelpers.py | UTF-8 | 16,383 | 2.921875 | 3 | [
"BSD-3-Clause"
] | permissive | '''
This file provides helper functions used to normalize the arguments that
go into search queries. Mainly converting the strings given by the user
into proper data types.
'''
from . import constants
from . import exceptions
from . import helpers
from . import objects
from voussoirkit import expressionmatch
from voussoirkit import pathclass
from voussoirkit import sqlhelpers
from voussoirkit import stringtools
def expand_mmf(tag_musts, tag_mays, tag_forbids):
'''
In order to generate SQL queries for `tagid IN (options)`, we need to
expand the descendents of the given must/may/forbid tags to generate the
complete list of options able to satisfy each query.
- musts becomes a list of sets and the photo must have at least one tag
from each set.
- mays becomes a set and the photo must have at least one.
- forbids becomes a set and the photo must not have any.
'''
def _set(x):
if x is None:
return set()
return set(x)
tag_musts = _set(tag_musts)
tag_mays = _set(tag_mays)
tag_forbids = _set(tag_forbids)
forbids_expanded = set()
def _remove_redundant_musts(tagset):
'''
Suppose B is a child of A, and the user searches for tag_musts=[A, B]
for some reason. In this case, A is redundant since having B already
satisfies A, so it makes sense to only expand and generate SQL for B.
This function will remove any tags which are ancestors of other tags
in the set so that we generate the minimum amount of SQL queries.
'''
ancestors = set()
for tag in tagset:
if tag in ancestors:
continue
ancestors.update(tag.walk_parents())
pruned = tagset.difference(ancestors)
return pruned
def _expand_flat(tagset):
# I am not using tag.walk_children because if the user happens to give
# us two tags in the same lineage, we have the opportunity to bail
# early, which walk_children won't know about. So instead I'm doing the
# queue popping and pushing myself.
expanded = set()
while len(tagset) > 0:
tag = tagset.pop()
if tag in forbids_expanded:
continue
if tag in expanded:
continue
expanded.add(tag)
tagset.update(tag.get_children())
return expanded
# forbids must come first so that musts and mays don't waste their time
# expanding the forbidden subtrees.
forbids_expanded = _expand_flat(tag_forbids)
musts_expanded = [_expand_flat({tag}) for tag in _remove_redundant_musts(tag_musts)]
mays_expanded = _expand_flat(tag_mays)
return (musts_expanded, mays_expanded, forbids_expanded)
def minmax(key, value, minimums, maximums, warning_bag=None):
'''
Dissects a dotdot_range string and inserts the correct k:v pair into
both minimums and maximums.
('area', '100..200', {}, {})
-->
{'area': 100}, {'area': 200} (MODIFIED IN PLACE)
'''
if value is None:
return
if isinstance(value, str):
value = value.strip()
if value == '':
return
if isinstance(value, (int, float)):
minimums[key] = value
return
try:
(low, high) = helpers.dotdot_range(value)
except ValueError as exc:
if warning_bag:
exc = exceptions.MinMaxInvalid(field=key, value=value)
warning_bag.add(exc)
return
else:
raise
except exceptions.MinMaxOutOfOrder as exc:
if warning_bag:
warning_bag.add(exc)
return
else:
raise
if low is not None:
minimums[key] = low
if high is not None:
maximums[key] = high
def normalize_author(authors, photodb, warning_bag=None):
'''
Either:
- A string, where the user IDs are separated by commas
- An iterable containing IDs or User objects
Returns: A set of User objects.
'''
if authors is None:
authors = []
if isinstance(authors, str):
authors = stringtools.comma_space_split(authors)
users = set()
for requested_author in authors:
if isinstance(requested_author, objects.User):
if requested_author.photodb == photodb:
users.add(requested_author)
continue
else:
requested_author = requested_author.id
try:
user = photodb.get_user_by_id(requested_author)
except exceptions.NoSuchUser as exc:
if warning_bag:
warning_bag.add(exc)
else:
raise
else:
users.add(user)
return users
def normalize_extension(extensions):
'''
Either:
- A string, where extensions are separated by commas or spaces.
- An iterable containing extensions as strings.
Returns: A set of strings with no leading dots.
'''
if extensions is None:
extensions = set()
elif isinstance(extensions, str):
extensions = stringtools.comma_space_split(extensions)
extensions = [e.lower().strip('.').strip() for e in extensions]
extensions = set(e for e in extensions if e)
return extensions
def normalize_filename(filename_terms):
'''
Either:
- A string.
- An iterable containing search terms as strings.
Returns: A string where terms are separated by spaces.
'''
if filename_terms is None:
return None
if not isinstance(filename_terms, str):
filename_terms = ' '.join(filename_terms)
filename_terms = filename_terms.strip()
return filename_terms
def normalize_has_albums(has_albums):
'''
See voussoirkit.stringtools.truthystring.
'''
return stringtools.truthystring(has_albums, None)
def normalize_has_tags(has_tags):
'''
See voussoirkit.stringtools.truthystring.
'''
return stringtools.truthystring(has_tags, None)
def normalize_has_thumbnail(has_thumbnail):
'''
See voussoirkit.stringtools.truthystring.
'''
return stringtools.truthystring(has_thumbnail, None)
def normalize_is_searchhidden(is_searchhidden):
'''
See voussoirkit.stringtools.truthystring.
'''
return stringtools.truthystring(is_searchhidden, None)
def _limit_offset(number, warning_bag):
if number is None:
return None
try:
number = normalize_positive_integer(number)
except ValueError as exc:
if warning_bag:
warning_bag.add(exc)
number = 0
return number
def normalize_limit(limit, warning_bag=None):
'''
Either:
- None to indicate unlimited.
- A non-negative number as an int, float, or string.
Returns: None or a positive integer.
'''
return _limit_offset(limit, warning_bag)
def normalize_mimetype(mimetype, warning_bag=None):
'''
Either:
- A string, where mimetypes are separated by commas or spaces.
- An iterable containing mimetypes as strings.
Returns: A set of strings.
'''
return normalize_extension(mimetype, warning_bag)
def normalize_mmf_vs_expression_conflict(
tag_musts,
tag_mays,
tag_forbids,
tag_expression,
warning_bag=None,
):
'''
The user cannot provide both mmf sets and tag expression at the same time.
If both are provided, nullify everything.
'''
if (tag_musts or tag_mays or tag_forbids) and tag_expression:
exc = exceptions.NotExclusive(['tag_musts+mays+forbids', 'tag_expression'])
if warning_bag:
warning_bag.add(exc)
else:
raise exc
conflict = True
conflict = False
if conflict:
tag_musts = None
tag_mays = None
tag_forbids = None
tag_expression = None
return (tag_musts, tag_mays, tag_forbids, tag_expression)
def normalize_offset(offset, warning_bag=None):
'''
Either:
- None.
- A non-negative number as an int, float, or string.
Returns: None or a positive integer.
'''
if offset is None:
return 0
return _limit_offset(offset, warning_bag)
def normalize_orderby(orderby, warning_bag=None):
'''
Either:
- A string of orderbys separated by commas, where a single orderby consists
of 'column' or 'column-direction' or 'column direction'.
- A list of such orderby strings.
- A list of tuples of (column, direction)
With no direction, direction is implied desc.
Returns: A list of tuples of (column_friendly, column_expanded, direction)
where friendly is the name as the user would see it and expanded is the
expression to be used in the SQL query. This is important for columns like
"area" which is expanded into width*height.
'''
if orderby is None:
orderby = []
if isinstance(orderby, str):
orderby = orderby.replace('-', ' ')
orderby = orderby.split(',')
final_orderby = []
for requested_order in orderby:
if isinstance(requested_order, str):
requested_order = requested_order.strip().lower()
if not requested_order:
continue
split_order = requested_order.split()
else:
split_order = tuple(x.strip().lower() for x in requested_order)
if len(split_order) == 2:
(column, direction) = split_order
elif len(split_order) == 1:
column = split_order[0]
direction = 'desc'
else:
exc = exceptions.OrderByInvalid(request=requested_order)
if warning_bag:
warning_bag.add(exc)
continue
else:
raise exc
if direction not in ('asc', 'desc'):
exc = exceptions.OrderByBadDirection(column=column, direction=direction)
if warning_bag:
warning_bag.add(exc)
direction = 'desc'
else:
raise exc
if column not in constants.ALLOWED_ORDERBY_COLUMNS:
exc = exceptions.OrderByBadColumn(column=column)
if warning_bag:
warning_bag.add(exc)
continue
else:
raise exc
column_friendly = column
column_expanded = {
'random': 'RANDOM()',
}.get(column, column)
final_orderby.append( (column_friendly, column_expanded, direction) )
return final_orderby
def normalize_positive_integer(number):
if number is None:
number = 0
elif isinstance(number, str):
# Convert to float, then int, just in case they type '-4.5'
# because int('-4.5') does not work.
number = float(number)
number = int(number)
if number < 0:
raise ValueError(f'{number} must be >= 0.')
return number
def normalize_sha256(sha256, warning_bag=None):
if sha256 is None:
return None
if isinstance(sha256, (tuple, list, set)):
pass
elif isinstance(sha256, str):
sha256 = stringtools.comma_space_split(sha256)
else:
raise TypeError('sha256 should be the 64 character hexdigest string or a set of them.')
shas = set(sha256)
goodshas = set()
for sha in shas:
if isinstance(sha, str) and len(sha) == 64:
goodshas.add(sha)
else:
exc = TypeError(f'sha256 should be the 64-character hexdigest string.')
if warning_bag is not None:
warning_bag.add(exc)
else:
raise exc
return goodshas
def normalize_tag_expression(expression):
if not expression:
return None
if not isinstance(expression, str):
expression = ' '.join(expression)
expression = expression.strip()
if not expression:
return None
return expression
def normalize_within_directory(paths, warning_bag=None):
if paths is None:
return set()
if isinstance(paths, set):
pass
elif isinstance(paths, (str, pathclass.Path)):
paths = {paths}
elif isinstance(paths, (list, tuple)):
paths = set(paths)
else:
exc = TypeError(paths)
if warning_bag:
warning_bag.add(exc)
return set()
else:
raise exc
paths = {pathclass.Path(p) for p in paths}
directories = {p for p in paths if p.is_dir}
not_directories = paths.difference(directories)
if not_directories:
exc = pathclass.NotDirectory(not_directories)
if warning_bag:
warning_bag.add(exc)
else:
raise exc
return directories
def normalize_yield_albums(yield_albums):
'''
See voussoirkit.stringtools.truthystring.
'''
return stringtools.truthystring(yield_albums, None)
def normalize_yield_photos(yield_photos):
'''
See voussoirkit.stringtools.truthystring.
'''
return stringtools.truthystring(yield_photos, None)
EXIST_FORMAT = '''
{operator} (
SELECT 1 FROM photo_tag_rel WHERE photos.id == photo_tag_rel.photoid
AND tagid IN {tagset}
)
'''.strip()
def photo_tag_rel_exist_clauses(tag_musts, tag_mays, tag_forbids):
(tag_musts, tag_mays, tag_forbids) = expand_mmf(
tag_musts,
tag_mays,
tag_forbids,
)
clauses = []
# Notice musts is a loop and the others are ifs.
for tag_must_group in tag_musts:
clauses.append( ('EXISTS', tag_must_group) )
if tag_mays:
clauses.append( ('EXISTS', tag_mays) )
if tag_forbids:
clauses.append( ('NOT EXISTS', tag_forbids) )
clauses = [
(operator, sqlhelpers.listify(tag.id for tag in tagset))
for (operator, tagset) in clauses
]
clauses = [
EXIST_FORMAT.format(operator=operator, tagset=tagset)
for (operator, tagset) in clauses
]
return clauses
def normalize_tagset(photodb, tags, warning_bag=None):
if not tags:
return None
if isinstance(tags, objects.Tag):
tags = {tags}
if isinstance(tags, str):
tags = stringtools.comma_space_split(tags)
tagset = set()
for tag in tags:
if isinstance(tag, objects.Tag):
if tag.photodb == photodb:
tagset.add(tag)
continue
else:
tag = tag.name
tag = tag.strip()
if tag == '':
continue
tag = tag.split('.')[-1]
try:
tag = photodb.get_tag(name=tag)
except exceptions.NoSuchTag as exc:
if warning_bag:
warning_bag.add(exc)
continue
else:
raise exc
tagset.add(tag)
return tagset
def tag_expression_tree_builder(
tag_expression,
photodb,
warning_bag=None
):
if not tag_expression:
return None
try:
expression_tree = expressionmatch.ExpressionTree.parse(tag_expression)
except expressionmatch.NoTokens:
return None
except Exception as exc:
warning_bag.add(f'Bad expression "{tag_expression}"')
return None
for node in expression_tree.walk_leaves():
try:
node.token = photodb.get_tag(name=node.token).name
except (exceptions.NoSuchTag) as exc:
if warning_bag:
warning_bag.add(exc)
node.token = None
else:
raise
if node.token is None:
continue
expression_tree.prune()
if expression_tree.token is None:
return None
return expression_tree
def tag_expression_matcher_builder(frozen_children):
frozen_children = {
(tag.name if not isinstance(tag, str) else tag): children
for (tag, children) in frozen_children.items()
}
def match_function(photo_tags, tagname):
'''
Used as the `match_function` for the ExpressionTree evaluation.
photo_tags:
The set of tag names owned by the photo in question.
tagname:
The tag which the ExpressionTree wants it to have.
'''
if not photo_tags:
return False
options = frozen_children[tagname]
return any(option in photo_tags for option in options)
return match_function
| true |
e70b0c9952f24f76c7019808a541c3d699c72f78 | Python | harshp8l/deep-learning-lang-detection | /data/train/python/4178666cbde24e15bbb5996f3d3ee2851278135ctasks.py | UTF-8 | 1,671 | 2.53125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
if __name__ == "__main__":
import dev_appserver
dev_appserver.fix_sys_path()
import os, webapp2, logging, datetime
from xml.dom.minidom import Text, Element, Document
from models import SharkAttack, Country, Country, Area
from utils import StringUtils
from repositories import SharkAttackRepository, CountryRepository, AreaRepository, PlaceSummary
class SummaryGenerator():
def __init__(self):
self._sharkAttackRepository = SharkAttackRepository()
self._countryRepository = CountryRepository()
self._areaRepository = AreaRepository()
def generateCountrySummaries(self):
for country in self._countryRepository.getCountries():
attacksForCountry = self._sharkAttackRepository.getDescendantAttacksForCountry(country.urlPart)
ps = PlaceSummary(attacksForCountry)
self._countryRepository.updatePlaceSummary(country, ps)
message = "Generated place summary for %s.\n%s\n" % (country.name, ps)
logging.info(message)
yield message
class GenerateSummaries(webapp2.RequestHandler):
def __init__(self, request, response):
self.initialize(request, response)
self._sg = SummaryGenerator()
def get(self):
for message in self._sg.generateCountrySummaries():
self.response.out.write(message)
if __name__ == "__main__":
from mocks.repositories import SharkAttackRepository, CountryRepository, AreaRepository
sg = SummaryGenerator()
sg.generateCountrySummaries()
for country in sg._countryRepository.getCountries():
print "%s: %s" % (country.name, country.place_summary)
| true |
a3db2c8b161778651c2d55ef14efd6cb5d3a093d | Python | BensonMuriithi/python | /lpthw pys/ex11.py | UTF-8 | 274 | 4.0625 | 4 | [] | no_license | #introduction to input
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh in kilograms?",
weight = raw_input()
print """
So you're %r years old, %r cm tall and %rkg in weight
""" % (age, height, weight) | true |
c948cf05896c4c71633aed8dd561339629d14c6a | Python | avivko/pythonWS1819 | /myTurt.py | UTF-8 | 922 | 3.328125 | 3 | [] | no_license | import tkinter
window = tkinter.Tk()
'''button = tkinter.Button(window, text="do not press", width=40)
button.pack(padx=10, pady=10)
clickCount = 0
def on_click(event):
global clickCount
clickCount = clickCount + 1
if clickCount == 1:
button.configure(text='seriously?')
elif clickCount == 2:
button.configure(text='twice?')
else:
button.pack_forget()
button.bind("<ButtonRelease-1>", on_click)'''
canvas = tkinter.Canvas(window, width=750, height=500, bg="white")
canvas.pack()
lastX, lastY = 0, 0
color = "black"
def store_position(event):
global lastX, lastY
lastX = event.x
lastY = event.y
def on_click(event):
store_position(event)
def on_drag(event):
canvas.create_line(lastX, lastY, event.x, event.y, fill=color, width=3)
store_position(event)
canvas.bind("<Button-1>", on_click)
canvas.bind("<B1-Motion>", on_drag)
window.mainloop()
| true |
f379088dfeffa120d98d00c74dc9e18a761d2f7e | Python | acurzons/c | /BootstrapCorrelation.py | UTF-8 | 3,126 | 3.453125 | 3 | [] | no_license |
# coding: utf-8
# In[235]:
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import pearsonr
from scipy.optimize import curve_fit
from scipy import stats
# # Uncertainty of Correlation Coefficient
#
# ... due to uncertainty of data points.
# In[184]:
def korr(x,y,xerr,yerr,plot=False):
xx = np.random.normal(x,xerr)
yy = np.random.normal(y,yerr)
if plot==True:
plt.errorbar(xx, yy, xerr=xerr, yerr=yerr, fmt='o')
plt.errorbar(x, y, xerr=xerr, yerr=yerr, fmt='o', color='y')
plt.show()
print(pearsonr(xx,yy))
return pearsonr(xx,yy)[0]
# In[191]:
# Put your data here
xray = np.random.normal(5,2,20)
gas = np.random.normal(15,5,20)
xray_err = np.random.normal(0.5,0.1,20)
gas_err = np.random.normal(2,0.5,20)
# In[192]:
korr(xray, gas, xray_err, gas_err, True)
# In[198]:
k = []
for i in range(100000):
k.append(korr(xray,gas,xray_err,gas_err))
plt.hist(k, bins=81, range=[-1,1])
# 3 sigma
plt.axvline(np.percentile(k, (100.0 - 99.73)/2.0), color='black', ls="--",)
plt.axvline(np.percentile(k, (100.0 - (100.0 - 99.73)/2.0)), color='black', ls="--")
# 5 sigma
plt.axvline(np.percentile(k, (100.0 - 99.99994)/2.0), color='black', ls=":")
plt.axvline(np.percentile(k, (100.0 - (100.0 - 99.99994)/2.0)), color='black', ls=":")
# correlation of original data set
plt.axvline(pearsonr(xray, gas)[0], color='black')
plt.show()
# --> One could use (correlation coefficient + uncertainty) as some extreme value like "in the most optimistic case (uncertainty of Z sigma),
# the most extreme correlation coefficient is X." And then use this extreme value in the following to determine the corresponding p-value.
# # p-value
# In[200]:
def korr2(x_mean, x_sigm, y_mean, y_sigm, number):
x = np.random.normal(x_mean,x_sigm,number)
y = np.random.normal(y_mean,y_sigm,number)
return pearsonr(x,y)[0]
# In[202]:
# Make some assumptions about your data
# For example that they are normal distributed with specific values
# Specifiy the values
x_mean = np.mean(xray)
x_sigm = np.std(xray)
y_mean = np.mean(gas)
y_sigm = np.std(gas)
number = len(xray)
print(x_mean, x_sigm, y_mean, y_sigm)
# --> Decide a confidence level for your test if the data is correlated and determine the corresponding correlation coefficient.
# Then check if your optimistic value is larger (then it is correlated wrt to the CL) or smaller. You can also quote the p-value then.
# In[232]:
kk = []
for i in range(100000):
kk.append(korr2(x_mean, x_sigm, y_mean, y_sigm, number))
plt.hist(np.abs(kk), bins=81, range=[0,1])
print('2 sigma', np.percentile(np.abs(kk),95.449))
print('3 sigma', np.percentile(np.abs(kk),99.73))
print('5 sigma', np.percentile(np.abs(kk),99.99994))
plt.show()
# In[234]:
# A check of the method
# Compare if bootstrap result is consistent with Pearson result
print(np.abs(pearsonr(xray,gas)[0]))
print(np.percentile(np.abs(kk),100-pearsonr(xray,gas)[1]*100.))
| true |
651b4bd0d262c8ae9fda4105d0bf3b12e7ddb6f1 | Python | DrewRust/DS-Unit-3-Sprint-2-SQL-and-Databases | /module3-nosql-and-document-oriented-databases/mongo_explorer.py | UTF-8 | 3,439 | 2.984375 | 3 | [
"MIT"
] | permissive | import os
import json
import pymongo
from dotenv import load_dotenv
from pdb import set_trace as breakpoint
#### importing from my_sql_to_mong.py the function put_sqltable_in_dict
from my_sql_to_mongo import put_sqltable_in_dict
#### loading .env file and credentials for MongoDB
load_dotenv()
DB_USER = os.getenv("MONGO_USER", default="OOPS")
DB_PASSWORD = os.getenv("MONGO_PASSWORD", default="OOPS")
CLUSTER_NAME = os.getenv("MONGO_CLUSTER_NAME", default="OOPS")
#### Connecting to MongoDB
connection_uri = f"mongodb+srv://{DB_USER}:{DB_PASSWORD}@{CLUSTER_NAME}.mongodb.net/drew_rust?retryWrites=true&w=majority"
print("\n")
print("----------------")
print("\n")
print("URI:", connection_uri)
print("\n")
client = pymongo.MongoClient(connection_uri)
print("----------------")
print("\n")
print("CLIENT:", type(client), client)
print("\n")
#### This prints clients from a sample db
# print("These are your database names: \n")
# print(client.list_database_names())
# print("\n")
#### This prints from the column sample_analytics
# db = client.sample_analytics
# print("These are the list of collection names: \n")
# print(db.list_collection_names())
# print("\n")
#### This prints from customers
# customers = db.customers
# print("These are how many customer documents we have: \n")
# print(customers.count_documents({}))
# print("\n")
#### Creates an rpg_data database called my_db
my_db = client.rpg_data
#### Characters ####
#### Write JSON Data from RPG DB to MongoDB
#### Read the JSON file
#### (copied from:
#### https://raw.githubusercontent.com/LambdaSchool/Django-RPG/master/testdata.json)
#### This uses the test_data_json.txt file and loads it into rpg_data
# with open('test_data_json.txt') as json_file:
# rpg_data = json.load(json_file)
#### Create a "characters" collection in the rpg_data DB
# character_table = my_db.characters
#### Insert the JSON data into "characters" collection
# character_table.insert_many(rpg_data)
# print(character_table.count_documents({}))
#### armory_items ####
#### importing this from the other file my_sql_to_mongo
qu= 'SELECT * FROM armory_item'
dictionary = put_sqltable_in_dict(qu)
print(dictionary)
### create armory_items table on mongoDB
### it will show up as "armory_collection"
armory_table = my_db.armory_collection
armory_table.insert_many(dictionary)
### prints how many armory_table documents
print(armory_table.count_documents({}))
#### mage_characters ####
#### Will print the mage's table (id, has_pet (true or false), mana_count)
#### importing this from the other file my_sql_to_mongo
query_mage = '''
SELECT * FROM charactercreator_mage;
'''
dictionary2 = put_sqltable_in_dict(query_mage)
print(dictionary2)
mage_table = my_db.mage_collection
mage_table.insert_many(dictionary2)
#### prints how many mage_table documents
print(mage_table.count_documents({}))
#### Used to debug and run code in the terminal below live before the code finishes
# breakpoint()
#### Examples of running code in the terminal below
#### (Pdb) is the indication of breakpoint
#### (Pdb) customers = db.customers
#### (Pdb) dir(customers)
#### (Pdb) customers.count_documents({})
#### (Pdb) all_customers = customers.find()
#### (Pdb) df = pd.DataFrame(all_customers)
#### (Pdb) df.shape
#### (501, 10)
#### (Pdb) df.tail()
#### (Pdb) customers.find_one()
#### crud - acronymn for create the data, read the data, update, and delete the data | true |
d9cd7cfc89b5f6645db7afc7121617d35f40c1d2 | Python | ammardodin/daily-coding-problem | /2021-01-13/solution.py | UTF-8 | 898 | 3.546875 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env python3
from collections import OrderedDict
def make_palindrome(candidate):
freq = OrderedDict()
for c in candidate:
freq[c] = freq.get(c, 0) + 1
num_odd = 0
odd_char = ''
for c, f in freq.items():
if f & 1:
num_odd = num_odd + 1
odd_char = c
if num_odd > 1:
return ""
left = []
right = []
for c, f in freq.items():
half = f // 2
left = left + [c] * half
right = [c] * half + right
if num_odd:
return "".join(left + [odd_char] + right)
return "".join(left + right)
assert make_palindrome("") == ""
assert make_palindrome("a") == "a"
assert make_palindrome("aab") == "aba"
assert make_palindrome("aaa") == "aaa"
assert(make_palindrome("bbaa")) == "baab"
assert(make_palindrome("aaaabbc")) == "aabcbaa"
assert(make_palindrome("bab")) == "bab"
| true |
7cf10a17ac662d87945453bd4c2e97402865f4bd | Python | andreag-dev/Natural-Language-Processing-class | /hw2/homework2.py | UTF-8 | 3,912 | 3.5 | 4 | [] | no_license | from nltk import word_tokenize
from nltk import pos_tag
from nltk import sent_tokenize
from nltk.text import Text
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.stem.porter import *
from collections import Counter
from random import seed
from random import randint
import random
import nltk
import sys
import re
def process_data(text):
# reduce tokens to tokens that are alpha, not stopwords and length > 5
text = [t for t in text if t.isalpha() and t not in stopwords.words('english') and len(t) > 5]
# lemmatize tokens and used set() to retrieve list of unique lemmas
wnl = WordNetLemmatizer()
lemmas = [wnl.lemmatize(t) for t in text]
unique_lemmas = list(set(lemmas))
# pos tagging on unique lemmas, print out first 20 tagged items
tags = nltk.pos_tag(unique_lemmas)
print(tags[:20])
# create list of unique lemmas nouns
nouns = [token for token, pos in pos_tag(unique_lemmas) if pos.startswith('N')]
# print number of tokens and nouns
print("\nNumber of tokens: ", len(text))
print("\nNumber of nouns: ", len(nouns))
return tokens, nouns
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Please enter a filename for system arg")
quit()
# read file as plain text
with open('anat19.txt', 'r') as f:
text = f.read()
tokens = word_tokenize(text)
# lowercase the text, remove punctuation and numbers
tokens = [t.lower() for t in tokens if t.isalpha()]
# calc lexical diversity(num of unique tokens / total tokens)
print("Lexical diversity: %.2f" % (len(set(tokens)) / len(tokens)))
# print(tokens)
tokens, nouns = process_data(tokens)
# create empty dictionary
dict = {}
for noun in nouns:
dict[noun] = tokens.count(noun)
# sort dictionary by the greatest values of occurrence, in descending order
sorted_dict = sorted(dict.items(), key=lambda x: x[1], reverse=True)
print(sorted_dict[:50])
# Save 50 most common words and counts to a list
common_words = []
for word in sorted_dict:
common_words.append(word[0])
# user gets 5 points to start with
score = 5
end = 0
seed(1234)
print('\nLets play a word guessing game!')
# randomly choose one of the 50 words from common_words list
random_word = common_words[random.randint(0, len(common_words))]
# add underscore for each letter in the random chosen word
underscore = ['_'] * len(random_word)
print('_' * len(random_word))
game_finished = False
while game_finished is False:
# prompt user to enter a letter
guess = input('Enter a letter:')
if score == 0 or guess == '!':
print("Out of points, game over.")
break
if guess in random_word:
score = score + 1
print("Right! Score is ", score)
# loop through letters in the random word
for i, letter in enumerate(random_word):
if letter != "_" and guess == letter:
# replace underscore with letter
underscore[i] = letter
# print list of joined guessed letters
print(''.join(underscore))
# if all letters guessed end game and print score
if "_" not in underscore:
game_finished = True
print("You solved it!")
print("Current score: ", score)
else:
game_finished = False
# if user enters wrong letter, -1 score
else:
score = score - 1
print("Sorry, guess again. Score is ", score)
| true |
f737cee548279ee7a92b36ac27e67493585ad182 | Python | engshorouq/Marks | /student.py | UTF-8 | 734 | 3.46875 | 3 | [] | no_license | import marks
class student():
Student=[]
def __init__(self,student_id,student_name):
assert type(student_id)==int,'Plesae enter number'
assert type(student_name)==str,'Plesae enter string'
self.student_id=student_id
self.student_name=student_name
def add_student(self):
student.Student.append(self)
def display():
for x in student.Student:
print('Student ID : '+str(x.student_id))
print('Student Name : '+x.student_name)
c1=int(input('mark course 1 : '))
c2=int(input('mark course 2 : '))
c3=int(input('mark course 3 : '))
c4=int(input('mark course 4 : '))
c5=int(input('mark course 5 : '))
mark=marks.marks(c1,c2,c3,c4,c5,x.student_name)
marks.marks.add_marks(mark)
print('*'*10)
| true |
e6616d36ead7d592c8d6e8b9f099aa2bdad0647f | Python | grassriver/Zhidao | /Portfolio_Optimization/analytical.py | UTF-8 | 4,406 | 2.90625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 5 10:54:48 2018
@author: Kai Zheng
"""
import numpy as np
import pandas as pd
from numpy.linalg import pinv
#%%
def form_mat(mu, sigma):
if not (isinstance(mu, np.ndarray) and isinstance(sigma, np.ndarray)):
raise ValueError('mu and sigma should be np.ndarray')
i = np.matrix(np.ones((np.max(mu.shape),1)))
mu = np.matrix(mu)
sigma = np.matrix(sigma)
if mu.shape[1] != 1:
mu = mu.T
return i, mu, sigma
def form_wt(weights):
if not (isinstance(weights, list) or
isinstance(weights, np.ndarray) or
isinstance(weights, pd.Series)):
raise ValueError('weights should be a list or np.ndarray')
w = np.matrix(weights)
if w.shape[1] != 1:
w = w.T
return w
def eff_frt(mu0, mu, sigma):
'''
calculate the risky asset weights on
unconstraint efficient frontier with short-selling
'''
i,mu,sigma = form_mat(mu,sigma)
a = float(i.T*pinv(sigma)*i)
b = float(i.T*pinv(sigma)*mu)
c = float(mu.T*pinv(sigma)*mu)
g = pinv(sigma)*(c*i - b*mu)/(a*c - b**2)
h = pinv(sigma)*(a*mu - b*i)/(a*c - b**2)
w = g + h*mu0
return w
def gmv(mu, sigma):
'''
weights of GMV port
'''
i,mu,sigma = form_mat(mu,sigma)
w = pinv(sigma)*i
w = w/np.sum(w)
return w
def CML(mu0, mu, sigma, rf=0.01):
'''
calculate the risky asset weights on the capital market line
given target return
'''
i,mu,sigma = form_mat(mu,sigma)
C = float((mu0-rf)/((mu-rf*i).T * pinv(sigma) * (mu-rf*i)))
w_R = C*pinv(sigma)*(mu-rf*i)
return w_R
def mkt_port(mu, sigma, rf=0.01):
'''
Market Portfolio
'''
i,mu,sigma = form_mat(mu,sigma)
w_M = pinv(sigma)*(mu-rf*i)
w_M = w_M/np.sum(w_M)
r_M = float(mu.T*w_M)
vol_M = float(np.sqrt(w_M.T*sigma*w_M))
return w_M, r_M, vol_M
def statistics(weights, mu, sigma, rf=0.01):
'''
Returns portfolio statistics.
Parameters
==========
rets: pd.DataFrame
daily returns of each stock
weights : array-like
weights for different securities in portfolio
Returns
=======
pret : float
expected portfolio return
pvol : float
expected portfolio volatility
pret / pvol : float
Sharpe ratio for rf=0
'''
w = form_wt(weights)
_,mu,sigma = form_mat(mu, sigma)
pret = float(w.T*mu)
pvol = float(np.sqrt(w.T*sigma*w))
return np.array([pret, pvol, (pret-rf) / pvol])
def proportion_R(mu0, mu, sigma, rf=0.01):
'''
proportion of risky assets in total assets
in order to satisfy the target return
'''
_, r_M, _ = mkt_port(mu, sigma, rf)
_,mu,sigma = form_mat(mu, sigma)
p = (mu0-rf)/(r_M-rf)
return p
def statistics_wrf(p, mu, sigma, rf=0.01):
'''
predicted return and volatility for portfolio with risk-free asset
according to proportion on risky asset.
'''
w_M, r_M, vol_M = mkt_port(mu, sigma, rf)
_,mu,sigma = form_mat(mu, sigma)
pret = rf + p*(r_M - rf)
pvol = p*vol_M
return np.array([pret, pvol])
def statistics_wrf2(w_R, mu, sigma, rf=0.01):
'''
predicted return and volatility for portfolio with risk-free asset
according to weights on risky asset.
'''
w_M, r_M, vol_M = mkt_port(mu, sigma, rf)
_,mu,sigma = form_mat(mu, sigma)
pret = float(w_R.T*mu + (1-w_R.sum())*rf)
pvol = float(np.sqrt(w_R.T*sigma*w_R))
return np.array([pret, pvol])
def risk_premium(mu, sigma, rf=0.01):
'''
market price of risk
'''
w_M, r_M, vol_M = mkt_port(mu, sigma, rf)
return (r_M-rf)/vol_M
#%%
if __name__ == '__main__':
mu = np.array([[0.079, 0.079, 0.09, 0.071],])
std = np.array([[0.195, 0.182, 0.183, 0.165],])
corr = np.array([[1, 0.24, 0.25, 0.22],
[0.24, 1, 0.47, 0.14],
[0.25, 0.47, 1, 0.25],
[0.22, 0.14, 0.25, 1]])
sigma = np.multiply(np.dot(std.T, std), corr)
mu0 = 0.04
w_R = CML(mu0, mu, sigma)
w_R
p = proportion_R(mu0, mu, sigma)
p
pret, pvol = statistics_wrf(p, mu, sigma)
pret
pvol
pret, pvol = statistics_wrf2(w_R, mu, sigma)
pret
pvol
w = eff_frt(mu0, mu, sigma)
w
pret, pvol, sharpe = statistics(w_R, mu, sigma)
pret
pvol
sharpe
| true |
939f7aa99992370aee38f6fb568096a2d6e4edf1 | Python | JoshuaW1990/leetcode-session1 | /leetcode321.py | UTF-8 | 834 | 3.03125 | 3 | [] | no_license | class Solution(object):
def maxNumber(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[int]
"""
def preprocess(nums, k):
stack = []
drop = len(nums) - k
for ch in nums:
while drop > 0 and stack and stack[-1] < ch:
stack.pop()
drop -= 1
stack.append(ch)
return stack[:k]
def merge(num1, num2):
return [max(num1, num2).pop(0) for _ in num1 + num2]
result = []
for i in xrange(k + 1):
if i <= len(nums1) and k - i <= len(nums2):
result.append(merge(preprocess(nums1, i), preprocess(nums2, k - i)))
return max(result) | true |
343f8841386cbb6dd8995ea76e18e929d4d7499b | Python | gtambi143/Discussion-Forum | /syncclient.py | UTF-8 | 723 | 2.75 | 3 | [] | no_license | import socket # Import socket module
import time
#s = socket.socket() # Create a socket object
# Reserve a port for your service.
#s.connect((host, port))
#s.send("Hello server!")
f = open('sync1.txt','rb')
print 'syncronising...'
l = f.read(1024)
while(1):
s = socket.socket()
host = socket.gethostname() # Get local machine name
port = 12345
s.connect((host,port))
while (l):
print 'Syncronising...'
s.send(l)
l = f.read(1024)
f.close()
print "Done Syncronising"
f = open('sync1.txt','rb')
l = f.read(1024)
s.shutdown(socket.SHUT_WR)
print s.recv(1024)
s.close()
time.sleep(10)
| true |
905fae2b859b6208b59c96f272d85a75c8c926b0 | Python | sonesuke/Kata | /Bowling/python/SerializeService.py | UTF-8 | 3,032 | 2.90625 | 3 | [] | no_license | from Model import Game, Roll
class Stream:
def write_header(self, tag):
raise NotImplemented
def write_footer(self, tag):
raise NotImplemented
def write_count(self, count):
raise NotImplemented
def write_body(self, body):
raise NotImplemented
def load_header(self):
raise NotImplemented
def load_footer(self):
raise NotImplemented
def load_count(self):
raise NotImplemented
def load_body(self):
raise NotImplemented
def close(self):
raise NotImplemented
class Pack:
def __init__(self, archive, tag):
self.archive = archive
self.tag = tag
def __enter__(self):
self.archive.write_header(self.tag)
def __exit__(self, exc_type, exc_value, traceback):
self.archive.write_footer(self.tag)
return True
class SaveService:
def __init__(self, archive):
self.archive = archive
def save(self, game):
with Pack(self.archive, "game"):
frames = game.get_frames()
self.save_frames(frames)
self.archive.close()
def save_frames(self, frames):
with Pack(self.archive, "frames"):
self.archive.write_count(len(frames))
[self.save_frame(f) for f in frames]
def save_frame(self, frame):
with Pack(self.archive, "frame"):
rolls = frame.get_rolls()
self.save_rolls(rolls)
def save_rolls(self, rolls):
with Pack(self.archive, "rolls"):
self.archive.write_count(len(rolls))
[self.save_roll(r) for r in rolls]
def save_roll(self, roll):
with Pack(self.archive, "roll"):
self.archive.write_body(roll.to_pins())
class Unpack:
def __init__(self, archive, tag):
self.archive = archive
self.tag = tag
def __enter__(self):
if self.tag != self.archive.load_header():
raise ValueError
def __exit__(self, exc_type, exc_value, traceback):
if self.tag != self.archive.load_footer():
raise ValueError
return True
class LoadService:
def __init__(self, archive):
self.archive = archive
def load(self):
with Unpack(self.archive, "game"):
g = Game()
self.load_frames(g.frames)
self.archive.close()
return g
def load_frames(self, frames):
with Unpack(self.archive, "frames"):
count = self.archive.load_count()
[self.load_frame(frames) for i in range(count)]
def load_frame(self, frames):
with Unpack(self.archive, "frame"):
frames.create_next()
[frames.last().append(r) for r in self.load_rolls()]
def load_rolls(self):
with Unpack(self.archive, "rolls"):
for i in range(self.archive.load_count()):
yield self.load_roll()
def load_roll(self):
with Unpack(self.archive, "roll"):
return Roll(self.archive.load_body())
| true |
6647cd0adfb6b6c8e3a877045013057220c4947e | Python | somous-jhzhao/bayesian-free-energies | /bams/convergence_analysis_tools.py | UTF-8 | 11,233 | 2.9375 | 3 | [] | no_license | import numpy as np
from copy import deepcopy
from bams.example_systems import *
from bams.bayes_adaptor import BayesAdaptor
from bams.sams_adapter import SAMSAdaptor
#---Functions to compute SAMS and BAMS mean-squared error using the `GaussianMixtureSampler`---#
def gaussian_thermodynamic_length(s_min, s_max):
"""
Function to compute the thermodynamic length between one-dimensional Gaussian distributions that differ
only by their standard deviation.
"""
return np.sqrt(2.0) * np.log(s_max / s_min)
def gen_optimal_sigmas(s_min, s_max, N):
"""
Generate N standard deviations between s_min and s_max (inclusive) such that the resultant Gaussian distributions
are equally spaced with respect to thermodynamic length.
"""
sigmas = np.repeat(s_min, N)
n = np.arange(0, N)
return sigmas * np.exp((n * gaussian_thermodynamic_length(s_min, s_max)) / (np.sqrt(2) * (N - 1)))
def gen_sigmas(sigma1, f):
"""
Generate standard deviations for one-dimensional Gaussian distributions by the relative free energy of the
normalizing constants.
Parameters
----------
sigma1: float
the standard deviation from which all other standard deviations are calculated relative to
f: numpy.ndarray or float
the relative free energy of the other Gaussian distributions to sigma1
Returns
-------
numpy.ndarray
vector of standard deviations
"""
return sigma1 * np.exp(-f)
def rb_mse_gaussian(sigmas, niterations, nmoves=1, save_freq=1, beta=0.6, flat_hist=0.2):
"""
Function to compute the mean-squared error from the Rao-Blackwellized update scheme in when sampling
states with GaussianMixtureSampler.
Parameters
----------
sigmas: numpy array
The standard deviations of the Gaussians that are centered on zero
niterations: int
The number of iterations of mixture sampling and SAMS updates that will be performed
nmoves: int
The number of moves from the Gaussian Gibbs sampler. One position step and state step
constitute one move.
save_freq: int
The frequency with which to save the state in the Gaussian mixture sampler, used to decorrelate trajectory
beta: float
The exponent in the burn-in phase of the two stage SAMS update scheme.
flat_hist: float
The average fractional difference between the target weights of the mixture and count frequency
Returns
-------
mse: numpy array
the mean-squared error of the SAMS estimate for each iteration
"""
generator = GaussianMixtureSampler(sigmas=sigmas)
nstates = len(sigmas)
adaptor = SAMSAdaptor(nstates=nstates, beta=beta, flat_hist=flat_hist)
# The target free energy
f_true = -np.log(sigmas)
f_true = f_true - f_true[0]
mse = np.zeros((niterations))
for i in range(niterations):
generator.step(nmoves, save_freq)
state = generator.state
noisy = generator.weights
z = -adaptor.update(state=state, noisy_observation=noisy, histogram=generator.histogram)
generator.zetas = z
mse[i] = np.mean((f_true[1:] - z[1:]) ** 2)
return mse
def binary_mse_gaussian(sigmas, niterations, nmoves=1, save_freq=1, beta=0.6, flat_hist=0.2):
"""
Function to compute the mean-squared error from the binary update scheme in when sampling
states with GaussianMixtureSampler.
Parameters
----------
sigmas: numpy array
The standard deviations of the Gaussians that are centered on zero
niterations: int
The number of iterations of mixture sampling and SAMS updates that will be performed
nmoves: int
The number of moves from the Gaussian Gibbs sampler. One position step and state step
constitute one move.
save_freq: int
The frequency with which to save the state in the Gaussian mixture sampler, used to decorrelate trajectory
beta: float
The exponent in the burn-in phase of the two stage SAMS update scheme.
flat_hist: float
The average fractional difference between the target weights of the mixture and count frequency
Returns
-------
mse: numpy array
the mean-squared error of the SAMS estimate for each iteration
"""
generator = GaussianMixtureSampler(sigmas=sigmas)
nstates = len(sigmas)
adaptor = SAMSAdaptor(nstates=nstates, beta=beta, flat_hist=flat_hist)
# The target free energy
f_true = -np.log(sigmas)
f_true = f_true - f_true[0]
mse = np.zeros((niterations))
for i in range(niterations):
noisy = generator.step(nmoves, save_freq)
state = generator.state
z = -adaptor.update(state=state, noisy_observation=noisy, histogram=generator.histogram)
generator.zetas = z
mse[i] = np.mean((f_true[1:] - z[1:]) ** 2)
return mse
def bayes_mse_gaussian(sigmas, niterations, nmoves=1, save_freq=1, method='thompson', enwalkers=30, enmoves=100):
"""
Function to compute the mean-squared error from a Bayesian update scheme when sampling
states with GaussianMixtureSampler.
Parameters
----------
sigmas: numpy array
The standard deviations of the Gaussians that are centered on zero
niterations: int
The number of iterations of mixture sampling and SAMS updates that will be performed
nmoves: int
The number of moves from the Gaussian Gibbs sampler. One position step and state step
constitute one move.
save_freq: int
The frequency with which to save the state in the Gaussian mixture sampler, used to decorrelate trajectory
method: string
the method with which new samples are generated. Either 'map', 'thompson', 'mean', or 'median'.
Returns
-------
mse: numpy array
the mean-squared error of the Bayesian estimate for each iteration
"""
# Initialize the sampler
generator = GaussianMixtureSampler(sigmas=sigmas)
generator.step(nmoves, save_freq)
histogram = generator.histogram
generator.reset_statistics()
# Intialize the Bayesian adaptor
adaptor = BayesAdaptor(counts=histogram, zetas=generator.zetas, method=method)
# The target free energy
f_true = -np.log(sigmas)
f_true = f_true - f_true[0]
mse = np.zeros((niterations))
for i in range(niterations):
# Generate new biases
z = adaptor.update(nwalkers=enwalkers, nmoves=enmoves)
generator.zetas = z
# Sample from Gaussian mixture, recording the histogram
generator.step(nmoves, save_freq)
h = deepcopy(generator.histogram)
generator.reset_statistics()
# Keep track of new counts and biases
adaptor.counts = np.vstack((adaptor.counts, h))
adaptor.zetas = np.vstack((adaptor.zetas, z))
# Calculate the error
estimate = adaptor.map_estimator()
mse[i] = np.mean((f_true[1:] - estimate) ** 2)
return mse
#---Functions to compute SAMS and BAMS mean-squared error using the `IndependentMultinomialSamper`---#
def binary_mse_multinomial(repeats, niterations, f_range, beta, nstates=2):
"""
Function to compute the mean-squared error of the SAMS binary update scheme when drawing samples from
the multinomial distribution. Over many repeats, target free energies will be drawn randomly and uniformly
from a specified range and SAMS will adapt to those free energies.
Parameters
----------
repeats: int
The number of repeats with which to draw target free energies and run SAMS
ninterations:
The number of state samples generated and SAMS adaptive steps
f_range: float
The interval over which target free energies will be drawn
beta: float
The exponent for the SAMS burn-in stage
nstates: int
The number of states and target free energies.
"""
binary_aggregate_msd = np.zeros((repeats, niterations))
for r in range(repeats):
f_true = np.random.uniform(low=-f_range / 2.0, high=f_range / 2.0, size=nstates)
f_true -= f_true[0]
generator = IndependentMultinomialSamper(free_energies=f_true)
adaptor = SAMSAdaptor(nstates=nstates, beta=beta)
for i in range(niterations):
noisy = generator.step()
state = np.where(noisy != 0)[0][0]
z = -adaptor.update(state=state, noisy_observation=noisy, histogram=generator.histogram)
generator.zetas = z
binary_aggregate_msd[r, i] = np.mean((f_true - z) ** 2)
return binary_aggregate_msd
def bayes_mse_multinomial(niterations, prior, spread, location, f_true, method, logistic=False, nsamps=1, enmoves=200,
enwalkers=50):
"""
Function to estimate the bias and variance of the BAMS method as a function of iteration
Parameters
----------
niterations = int
The number of iterations for state sampling and adaptive estimation
prior = str
The type of prior used, either 'gaussian', 'laplace', or 'cauchy'
spread = numpy array
The value of spread parameter for the prior, e.g the standard deviation for the Gaussian prior
location = numpy array
The location parameter for the prior, e.g the mode for the Laplace prior
method = string
The method used in the update procedure, either 'thompson' or 'map'
logistic = bool
Whether to convolute the bias generation procedure with the logisitic distribution
nsamps = int
The number of state samples generated per cycle
enmoves = int
The number of emcee moves performed for each walker
enwalkers = int
The number emcee walkers
Returns
-------
bias: numpy array
The mean-squared distance between the MAP estimate and target free energy for each iteration
variance: numpy array
The variance of the posterior distribution at each stage of the iteration
"""
# Generating the true state probabilities:
p = np.hstack((1, np.exp(-f_true)))
p = p / np.sum(p)
# Pre-assigment
map_estimate = []
zetas = [np.repeat(0, len(f_true) + 1)] # Starting the initial bias at zero
counts = []
variance = []
# Online estimation of free energies:
for i in range(niterations):
# Sample from multinomial
q = p * np.exp(zetas[-1])
q = q / np.sum(q)
counts.append(np.random.multinomial(nsamps, q))
# Sample from the posterior
adaptor = BayesAdaptor(zetas=np.array(zetas), counts=np.array(counts), prior=prior, spread=spread,
location=location, logistic=logistic, method=method)
new_zeta = adaptor.update(nwalkers=enwalkers, nmoves=enmoves)
# Sample a new biasing potential
zetas.append(new_zeta)
# Collect data
f_guess = np.hstack((0.0, adaptor.flat_samples.mean(axis=0)))
map_estimate.append(adaptor.map_estimator(f_guess=f_guess))
variance.append(np.var(adaptor.flat_samples))
# Calculate the bias
map_estimate = np.array(map_estimate)
bias = (map_estimate - f_true) ** 2
variance = np.array(variance)
return bias, variance
| true |
9629bca437bf1b8d6ca4e5f3668f449852bd09f1 | Python | xrw560/ai_bf | /DecisionTree/决策树分类买模型可视化.py | UTF-8 | 5,726 | 3.359375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import warnings
from sklearn import tree #决策树
from sklearn.tree import DecisionTreeClassifier #分类树
from sklearn.model_selection import train_test_split#测试集和训练集
from sklearn.pipeline import Pipeline #管道
from sklearn.feature_selection import SelectKBest #特征选择
from sklearn.feature_selection import chi2 #卡方统计量
from sklearn.preprocessing import MinMaxScaler #数据归一化
from sklearn.decomposition import PCA #主成分分析
from sklearn.model_selection import GridSearchCV #网格搜索交叉验证,用于选择最优的参数
## 设置属性防止中文乱码
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
warnings.filterwarnings('ignore', category=FutureWarning)
iris_feature_E = 'sepal length', 'sepal width', 'petal length', 'petal width'
iris_feature_C = '花萼长度', '花萼宽度', '花瓣长度', '花瓣宽度'
iris_class = 'Iris-setosa', 'Iris-versicolor', 'Iris-virginica'
#读取数据
path = './datas/iris.data'
data = pd.read_csv(path, header=None)
x=data[list(range(4))]#获取X变量
y=pd.Categorical(data[4]).codes#把Y转换成分类型的0,1,2
print("总样本数目:%d;特征属性数目:%d" % x.shape)
#数据进行分割(训练数据和测试数据)
x_train1, x_test1, y_train1, y_test1 = train_test_split(x, y, train_size=0.8, random_state=14)
x_train, x_test, y_train, y_test = x_train1, x_test1, y_train1, y_test1
print ("训练数据集样本数目:%d, 测试数据集样本数目:%d" % (x_train.shape[0], x_test.shape[0]))
y_train = y_train.astype(np.int)
y_test = y_test.astype(np.int)
#数据标准化
#StandardScaler (基于特征矩阵的列,将属性值转换至服从正态分布)
#标准化是依照特征矩阵的列处理数据,其通过求z-score的方法,将样本的特征值转换到同一量纲下
#常用与基于正态分布的算法,比如回归
#数据归一化
#MinMaxScaler (区间缩放,基于最大最小值,将数据转换到0,1区间上的)
#提升模型收敛速度,提升模型精度
#常见用于神经网络
#Normalizer (基于矩阵的行,将样本向量转换为单位向量)
#其目的在于样本向量在点乘运算或其他核函数计算相似性时,拥有统一的标准
#常见用于文本分类和聚类、logistic回归中也会使用,有效防止过拟合
ss = MinMaxScaler ()
#用标准化方法对数据进行处理并转换
x_train = ss.fit_transform(x_train)
x_test = ss.transform(x_test)
print ("原始数据各个特征属性的调整最小值:",ss.min_)
print ("原始数据各个特征属性的缩放数据值:",ss.scale_)
#特征选择:从已有的特征中选择出影响目标值最大的特征属性
#常用方法:{ 分类:F统计量、卡方系数,互信息mutual_info_classif
#{ 连续:皮尔逊相关系数 F统计量 互信息mutual_info_classif
#SelectKBest(卡方系数)
ch2 = SelectKBest(chi2,k=3)#在当前的案例中,使用SelectKBest这个方法从4个原始的特征属性,选择出来3个
#K默认为10
#如果指定了,那么就会返回你所想要的特征的个数
x_train = ch2.fit_transform(x_train, y_train)#训练并转换
x_test = ch2.transform(x_test)#转换
select_name_index = ch2.get_support(indices=True)
print ("对类别判断影响最大的三个特征属性分布是:",ch2.get_support(indices=False))
print(select_name_index)
#降维:对于数据而言,如果特征属性比较多,在构建过程中,会比较复杂,这个时候考虑将多维(高维)映射到低维的数据
#常用的方法:
#PCA:主成分分析(无监督)
#LDA:线性判别分析(有监督)类内方差最小,人脸识别,通常先做一次pca
pca = PCA(n_components=2)#构建一个pca对象,设置最终维度是2维
# #这里是为了后面画图方便,所以将数据维度设置了2维,一般用默认不设置参数就可以
x_train = pca.fit_transform(x_train)#训练并转换
x_test = pca.transform(x_test)#转换
#模型的构建
model = DecisionTreeClassifier(criterion='entropy',random_state=0, min_samples_split=10)#另外也可选gini
#模型训练
model.fit(x_train, y_train)
#模型预测
y_test_hat = model.predict(x_test)
#模型结果的评估
y_test2 = y_test.reshape(-1)
result = (y_test2 == y_test_hat)
print ("准确率:%.2f%%" % (np.mean(result) * 100))
#实际可通过参数获取
print ("Score:", model.score(x_test, y_test))#准确率
print ("Classes:", model.classes_)
# 方式一:输出形成dot文件,然后使用graphviz的dot命令将dot文件转换为pdf
from sklearn import tree
with open('iris.dot', 'w') as f:
# 将模型model输出到给定的文件中
f = tree.export_graphviz(model, out_file=f)
# 命令行执行dot命令: dot -Tpdf iris.dot -o iris.pdf
# 方式二:直接使用pydotplus插件生成pdf文件
from sklearn import tree
import pydotplus
dot_data = tree.export_graphviz(model, out_file=None)
graph = pydotplus.graph_from_dot_data(dot_data)
# graph.write_pdf("iris2.pdf")
graph.write_png("0.png")
# 方式三:直接生成图片
from sklearn import tree
from IPython.display import Image
import pydotplus
dot_data = tree.export_graphviz(model, out_file=None,
feature_names=['sepal length', 'sepal width', 'petal length', 'petal width'],
class_names=['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'],
filled=True, rounded=True,
special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())
| true |
f58999acedbd548cf7fb47b860c57b7a3620f249 | Python | italovinicius18/urisolutionspy | /1134.py | UTF-8 | 294 | 3.640625 | 4 | [] | no_license | ver = 0
gas = 0
alc = 0
die = 0
while ver!=4:
ver = int(input())
if ver == 1:
alc+=1
elif ver == 2:
gas+=1
elif ver == 3:
die+=1
elif ver == 4:
break
print('MUITO OBRIGADO')
print('Alcool:',alc)
print('Gasolina:',gas)
print('Diesel:',die) | true |
ce2e36b4f4623ed1c21d8a33994457ecd2f0da11 | Python | shubhamsinha1/Python | /PythonDemos/1.Introduction_of_Python/6.Iterable/0.Introduction.py | UTF-8 | 821 | 4.375 | 4 | [] | no_license | #anything which can be traversed is iterator
#There are 3 concepts : Iteration , Interable and iterator
#iterable is any object which can provide us with an iterator.
#Iterator is any object which has next method
#Iteration is the process of accessing element one by one
#Generator are iterators but they are interated only once. It requires less resources
# It is mainly implemented as functions but they yield value not return.
def fibonacci(n):
a = b = 1
for i in range(n):
yield a
a , b = b , a + b
for x in fibonacci(5):
print(x)
def get_first_three_number():
for i in range(3):
yield i
gen=get_first_three_number()
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen)) # you will get StopIteration error here, becuase there are no elements left to iterate | true |
ccf4b56e552d739be89988ad7deadc4dabcaa59b | Python | YuriQueriquelli/fatec_tg | /classifier.py | UTF-8 | 1,582 | 2.9375 | 3 | [] | no_license | from naive_bayes import postgresql_to_dataframe
import pickle
import psycopg2
from instance.config import config
def de_para_previsao(previsao):
return {
'Análise e Desenvolvimento de Sistemas':1,
'Comércio Exterior':2,
'Gestão Empresarial':3,
'Gestão de Serviços':4,
'Logística Aeroportuária':5,
'Redes de Computadores':6
}[previsao]
# update table vagas_geral
def table_update(url, previsao):
conn = None
try:
params = config()
conn = psycopg2.connect(**params)
cur = conn.cursor()
cur.execute("""UPDATE vaga_geral SET curso_id = %s WHERE geral_url = %s""",(previsao, url))
conn.commit()
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print("Error: %s" % error)
cur.close()
return 2
finally:
if conn is not None:
conn.close()
def main():
#load data
data_geral = postgresql_to_dataframe("SELECT geral_url, geral_desc FROM vaga_geral WHERE curso_id = 7;", (r'geral_url', r'geral_desc'))
# Open pickle file
f = open('my_classifier.pickle', 'rb')
classifier = pickle.load(f)
f.close()
for index, row in data_geral.iterrows():
text = row['geral_desc']
previsao = classifier.predict([text])
previsao = str(previsao).replace("'", "").replace("[", "").replace("]", "")
table_update(row['geral_url'], de_para_previsao(previsao))
print(de_para_previsao(previsao) , row['geral_url'])
if __name__ == '__main__':
main() | true |
3be9b0c1b1cf54ef2f000683d868798e33b319ea | Python | yw7vvAW611/LeecodePracticeNotes | /Combinations.py | UTF-8 | 1,592 | 3.6875 | 4 | [] | no_license | '''
77. Combinations
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
You may return the answer in any order.
Example 1:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
Example 2:
Input: n = 1, k = 1
Output: [[1]]
Constraints:
1 <= n <= 20
1 <= k <= n
'''
'''
思路:
Backtracking is a general algorithm for finding all solutions to some computational problems, notably constraint
satisfaction problems, that incrementally builds candidates to the solutions, and abandons a candidate as soon as it determines that the
candidate cannot possibly be completed to a valid solution.
Time Complexity O((n k)*k)
Space Complexity O(k)
'''
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
##明显用回溯法:
res = []
def backtrace(curr_res,index):
# print("curr_res:",curr_res)
if len(curr_res)==k:
#most by deep copy because python pass by object reference
res.append(curr_res[:]) ##浅拷贝,这一步很重要
return
for i in range(index,n+1):
curr_res.append(i)
# print(curr_res, 'after append')
backtrace(curr_res,i+1)
# print(curr_res, 'before pop')
curr_res.pop()
# print(curr_res, 'after pop')
# ##特殊情况处理 (d但constraint已经帮助排除)
# if n==0 or k==0:
# return res
backtrace([],1)
return res
| true |
56e2414c45b1a646939b65624ad371ff3472aeab | Python | yang4978/Huawei-OJ | /Python/1900. 【认证试题】字符排序.py | UTF-8 | 947 | 3.296875 | 3 | [] | no_license | """
Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
Description: 上机编程认证
Note: 缺省代码仅供参考,可自行决定使用、修改或删除
"""
class Solution:
def character_sort(self, input_str):
# 在此添加你的代码
arr = [[] for _ in range(3)]
index = []
for c in input_str:
if c.isdigit():
index.append(0)
elif c.islower():
index.append(1)
else:
index.append(2)
arr[index[-1]].append(c)
for x in arr:
x.sort(reverse = True)
arr[1] = arr[2] + arr[1]
return [arr[min(1,n)].pop() for n in index]
if __name__ == "__main__":
input_str = str(input().strip())
function = Solution()
results = function.character_sort(input_str)
print(str.join("", map(str, results)))
| true |
b2eadcf90c4fcb1f689ec169c083e3f8189856e5 | Python | gabminamedez/kattis | /1.9/abc.py | UTF-8 | 334 | 3.546875 | 4 | [] | no_license | nums = input()
nums = [int(num) for num in nums.split()]
letters = input()
nums.sort()
new = []
for letter in letters:
if letter == "A":
new.append(nums[0])
elif letter == "B":
new.append(nums[1])
elif letter == "C":
new.append(nums[2])
print(str(new[0]) + " " + str(new[1]) + " " + str(new[2])) | true |
2a2454b1020ea6107487a8f91020fda5f8016949 | Python | CaioBrighenti/fake-news | /data/FakeNewsNet/code/util/util.py | UTF-8 | 2,829 | 2.640625 | 3 | [
"MIT"
] | permissive | import csv
import errno
import os
import sys
from multiprocessing.pool import Pool
from tqdm import tqdm
from util.TwythonConnector import TwythonConnector
class News:
def __init__(self, info_dict, label, news_platform):
self.news_id = info_dict["id"]
self.news_url = info_dict["news_url"]
self.news_title = info_dict["title"]
self.tweet_ids =[]
try:
tweets = [int(tweet_id) for tweet_id in info_dict["tweet_ids"].split("\t")]
self.tweet_ids = tweets
except:
pass
self.label = label
self.platform = news_platform
class Config:
def __init__(self, data_dir, data_collection_dir, tweet_keys_file, num_process):
self.dataset_dir = data_dir
self.dump_location = data_collection_dir
self.tweet_keys_file = tweet_keys_file
self.num_process = num_process
self.twython_connector = TwythonConnector("localhost:5000", tweet_keys_file)
class DataCollector:
def __init__(self, config):
self.config = config
def collect_data(self, choices):
pass
def load_news_file(self, data_choice):
maxInt = sys.maxsize
while True:
# decrease the maxInt value by factor 10
# as long as the OverflowError occurs.
try:
csv.field_size_limit(maxInt)
break
except OverflowError:
maxInt = int(maxInt / 10)
news_list = []
with open('{}/{}_{}.csv'.format(self.config.dataset_dir, data_choice["news_source"],
data_choice["label"]), encoding="UTF-8") as csvfile:
reader = csv.DictReader(csvfile)
for news in reader:
news_list.append(News(news, data_choice["label"], data_choice["news_source"]))
return news_list
def create_dir(dir_name):
if not os.path.exists(dir_name):
try:
os.makedirs(dir_name)
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
def is_folder_exists(folder_name):
return os.path.exists(folder_name)
def equal_chunks(list, chunk_size):
"""return successive n-sized chunks from l."""
chunks = []
for i in range(0, len(list), chunk_size):
chunks.append(list[i:i + chunk_size])
return chunks
def multiprocess_data_collection(function_reference, data_list, args, config: Config):
# Create process pool of pre defined size
pool = Pool(config.num_process)
pbar = tqdm(total=len(data_list))
def update(arg):
pbar.update()
for i in range(pbar.total):
pool.apply_async(function_reference, args=(data_list[i],)+ args, callback=update)
pool.close()
pool.join()
| true |
f723464bcef5f79dc833c76221b7d7e62ca6b3f7 | Python | creich/CarND-Advanced-Lane-Lines | /calibrate_camera.py | UTF-8 | 6,033 | 2.8125 | 3 | [
"MIT"
] | permissive | import cv2
import numpy as np
import glob
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import pickle
DEBUG = False
#TODO make filename a parameter
PICKLE_FILE_NAME = 'camera_calibration_data.p'
def calibrate_camera():
## find chessboard corners
# prepare object points
nx = 9# the number of inside corners in x
ny = 6# the number of inside corners in y
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(8,5,0)
objp = np.zeros((nx*ny,3), np.float32)
objp[:,:2] = np.mgrid[0:nx, 0:ny].T.reshape(-1,2)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d points in real world space
imgpoints = [] # 2d points in image plane.
# Make a list of calibration images
images = glob.glob('camera_cal/calibration*.jpg')
for index, filename in enumerate(images):
image = mpimg.imread(filename)
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
if DEBUG:
print("find chessboard corners in: {} [which has the shape: {}]".format(filename, image.shape))
#NOTE some of the images have the shape (721, 1281, 3)! i guess it's small enough to NOT be a problem,
# but we may have to rescale them later to get all images into the same shape, since cv2.calibrateCamera()
# will get all points at once, while taking one image size as parameter
# Find the chessboard corners
ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)
# If found, draw corners
if ret == True:
objpoints.append(objp)
imgpoints.append(corners)
# Draw and display the corners
cv2.drawChessboardCorners(image, (nx, ny), corners, ret)
write_name = 'corners_found_' + str(index) + '.jpg'
cv2.imwrite('output_images/' + write_name, image)
# use the last image to get the shape/size of the images
#NOTE for some reason openCV puts y before x as output of image.shape, so x has index 1 instead of 0
imageSize = (image.shape[1], image.shape[0])
if DEBUG:
print(imageSize)
## Do camera calibration given object points and image points
return cv2.calibrateCamera(objpoints, imgpoints, imageSize, None, None)
def calc_perspactive_transform_matrix(cameraMatrix, distortionCoeffs):
# top_left top_right bot_left bot_right
# from undistorted straight_lines2
src = np.float32([[585, 460], [702, 460], [310, 660], [1000, 660]])
# from orig straight_lines1
#src = np.float32([[580, 460], [700, 460], [300, 660], [1000, 660]])
dst = np.float32([[400, 200], [900, 200], [400, 660], [900, 660]])
#dst = np.float32([[400, 460], [900, 460], [400, 660], [900, 660]])
# use cv2.getPerspectiveTransform() to get M, the transform matrix
M = cv2.getPerspectiveTransform(src, dst)
# load one image even in non-DEBUG-mode to determine image.shape of the camera
image = mpimg.imread('test_images/straight_lines1.jpg')
if DEBUG:
print("using image shape: {}".format(image.shape))
y_max, x_max = image.shape[0], image.shape[1]
if DEBUG:
image = undistort_image(image, cameraMatrix, distortionCoeffs)
warped = cv2.warpPerspective(image, M, (x_max, y_max), flags=cv2.INTER_LINEAR)
image2 = mpimg.imread('test_images/straight_lines2.jpg')
image2 = undistort_image(image2, cameraMatrix, distortionCoeffs)
warped2 = cv2.warpPerspective(image2, M, (x_max, y_max), flags=cv2.INTER_LINEAR)
f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(24, 9))
f.tight_layout()
ax1.imshow(image)
ax1.set_title('image', fontsize=15)
ax2.imshow(image2)
ax2.set_title('image2', fontsize=15)
ax3.imshow(warped)
ax3.set_title('warped', fontsize=15)
ax4.imshow(warped2)
ax4.set_title('warped2', fontsize=15)
plt.savefig('output_images/warped_straight_lines2.jpg')
plt.close()
return M, (x_max, y_max)
def undistort_image(image, camera_matrix, distortion_coeffs):
image = cv2.undistort(image, camera_matrix, distortion_coeffs, None, camera_matrix)
#TODO uncomment to save undistorted image
#mpimg.imwrite('output_images/test_undist.jpg', image)
return image
## Compute the camera calibration matrix and distortion coefficients given a set of chessboard images.
print("calibrate camera...")
ret, camera_matrix, distortion_coeffs, rvecs, tvecs = calibrate_camera()
print("done.")
if DEBUG:
image = mpimg.imread('test_images/straight_lines1.jpg')
mpimg.imsave('output_images/straight_lines1_distorted.jpg', image)
image = undistort_image(image, camera_matrix, distortion_coeffs)
mpimg.imsave('output_images/straight_lines1_undistorted.jpg', image)
image = mpimg.imread('test_images/straight_lines2.jpg')
mpimg.imsave('output_images/straight_lines2_distorted.jpg', image)
image = undistort_image(image, camera_matrix, distortion_coeffs)
mpimg.imsave('output_images/straight_lines2_undistorted.jpg', image)
image = mpimg.imread('camera_cal/calibration1.jpg')
mpimg.imsave('output_images/calibration1_distorted.jpg', image)
image = undistort_image(image, camera_matrix, distortion_coeffs)
mpimg.imsave('output_images/calibration1_undistorted.jpg', image)
# calculate transformation matrix
transformation_matrix, image_size = calc_perspactive_transform_matrix(camera_matrix, distortion_coeffs)
# thx to ajsmilutin for the snippet of 'how to use pickle'
# https://github.com/ajsmilutin/CarND-Advanced-Lane-Lines/blob/master/calibrate.py
# pickle the data and save it
calibration_data = {'camera_matrix': camera_matrix,
'distortion_coeffs': distortion_coeffs,
'transformation_matrix': transformation_matrix,
'image_size': image_size}
with open(PICKLE_FILE_NAME, 'wb') as f:
pickle.dump(calibration_data, f)
| true |
f2bb501da4e5b05c84b633dc8210efed2dddfde7 | Python | Gozea/Danmaku | /End_menu.py | UTF-8 | 2,556 | 3 | 3 | [] | no_license | import pygame
from Player import *
from Enemy import *
class End_menu:
"""Classe qui représente le menu d'accueil du jeu"""
def __init__(self, game):
"""Constructeur de classe"""
self.game = game
self.title = pygame.image.load('assets/title/game_over.png').convert_alpha()
self.title = pygame.transform.scale(self.title, (740, 200))
self.title_rect = self.title.get_rect()
self.title_rect.x = game.width / 2 - self.title_rect.width / 2
self.title_rect.y = game.height / 6
self.restart = pygame.image.load('assets/buttons/restart.png').convert_alpha()
self.restart = pygame.transform.scale(self.restart, (200, 200))
self.restart_rect = self.restart.get_rect()
self.restart_rect.x = self.restart_rect.width / 2
self.restart_rect.y = game.height / 2
self.menu = pygame.image.load('assets/buttons/menu.png').convert_alpha()
self.menu = pygame.transform.scale(self.menu, (200, 200))
self.menu_rect = self.menu.get_rect()
self.menu_rect.x = game.width - 3 * self.menu_rect.width/2
self.menu_rect.y = game.height / 2
self.music_is_playing = False
def end_menu(self, screen):
if not self.music_is_playing:
pygame.mixer.music.load('assets/music/deathscreenv2.ogg')
pygame.mixer.music.play(-1)
pygame.mixer.music.set_volume(0.3)
self.music_is_playing = True
self.game.all_enemies.empty()
screen.blit(self.restart, self.restart_rect)
screen.blit(self.title, self.title_rect)
screen.blit(self.menu, self.menu_rect)
for event in pygame.event.get():
# detection de la fermeture de la fenetre
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# détection de pression d'une touche
elif event.type == pygame.MOUSEBUTTONDOWN:
if self.restart_rect.collidepoint(event.pos):
self.game.is_playing = True
self.game.is_dead = False
self.music_is_playing = False
pygame.mixer.music.stop()
self.game.new_game()
if self.menu_rect.collidepoint(event.pos):
self.game.is_playing = False
self.game.is_dead = False
self.music_is_playing = False
pygame.mixer.music.stop()
| true |
b6122ee53357088e6ef11240134bd9eb5ad13bdd | Python | Andos25/CodeforFundFlow | /stephanie/data-analysis/correlation-analysis.py | UTF-8 | 1,488 | 2.78125 | 3 | [] | no_license | # coding=UTF-8
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats.stats import pearsonr
from scipy.stats.mstats import zscore
# ['Interest_O_N', 'Interest_1_W', 'Interest_2_W', 'Interest_1_M', 'Interest_3_M', 'Interest_6_M', 'Interest_9_M', 'Interest_1_Y']
tianchi_path = '/home/lt/data/tianchi/'
cleaned_path = tianchi_path + 'cleaned/'
stat_path = tianchi_path + 'stat/'
pearson_outputpath = stat_path + 'after_201404_pearson.csv'
def normalize(data):
for column in data.columns:
data[column] = zscore(data[column])
return data
# calculate pearson's correlation coefficient of each 2 of data columns
def pearson_cor(data):
out = open(pearson_outputpath, 'w')
for col1 in data.columns:
for col2 in data.columns:
[coef, p_value] = pearsonr(data[col1], data[col2])
out.write(col1+'*'+col2+','+str(coef) + ',' + str(p_value)+'\n')
out.close()
if __name__ == '__main__':
purchase = pd.read_csv(cleaned_path+'purchase_by_day.csv', header=0, parse_dates='report_date', index_col='report_date').ix[274:]
redeem = pd.read_csv(cleaned_path+'redeem_by_day.csv', header=0, parse_dates='report_date', index_col='report_date').ix[274:]
intervel = 7
print pearsonr(purchase[:-intervel], redeem[intervel:])
# interest = pd.read_csv(tianchi_path + 'mfd_day_share_interest.csv')
# redeem.plot()
# plt.show()
# print pearsonr(purchase['total_purchase_amt'], data['day_of_week'].values)
| true |
cfd4e9903031b5dcf849f9cfdffa856ee72281e8 | Python | changhoonhahn/central_quenching | /CenQue/archive/test_smf.py | UTF-8 | 1,194 | 2.71875 | 3 | [] | no_license | '''
Test integrated mass evolution
'''
import numpy as np
from scipy import interpolate
from smf import SMF
from util.cenque_utility import get_z_nsnap
from defutility.plotting import prettyplot
from defutility.plotting import prettycolors
def analytic_smf_evol(source='li-drory-march'):
'''
Evolution of the analytic SMF evolution
'''
prettyplot()
pretty_colors = prettycolors()
fig = plt.figure(figsize=(10,10))
sub = fig.add_subplot(111)
for i_z, z in enumerate(np.arange(0.0, 1.5, 0.25)):
smf = SMF()
analytic_mass, analytic_phi = smf.analytic(z, source=source)
sub.plot(analytic_mass, analytic_phi, lw=4, ls='--', c=pretty_colors[i_z],
label=r"$ z = "+str(round(z,2))+"$")
sub.set_yscale('log')
sub.set_ylim([10**-5, 10**-1])
sub.set_xlim([8.0, 12.0])
sub.legend(loc='upper right')
fig.savefig(
''.join([
'figure/'
'analytic_smf_', source, '.png'
]),
bbox_inches='tight'
)
plt.close()
if __name__=="__main__":
analytic_smf_evol(source='fontana')
analytic_smf_evol(source='li-march')
| true |
c9f45ed5f93af6408b3a9b69a89ff9f9f6e1ed30 | Python | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/nth-prime/febc67306da24d3785b9b60e51b729c5.py | UTF-8 | 820 | 2.96875 | 3 | [] | no_license | import math,cProfile
def nth_prime(number):
primes = []
i=1
while True:
i+=1
if i%2==1 or i==2:
prime = True
if primes:
if len(primes) == number:
return primes[len(primes)-1]
i_root = math.sqrt(i)
for j in primes:
if j>i_root and i>3:
break
if i%j==0:
prime = False
break
if i not in primes and prime:
primes.append(i)
else:
primes.append(i)
| true |
259a7bd523d77dd3504cf02494391f04ec970fc4 | Python | Aasthaengg/IBMdataset | /Python_codes/p03567/s724524410.py | UTF-8 | 58 | 2.890625 | 3 | [] | no_license | N=input()
if N.find('AC')+1:print("Yes")
else :print("No") | true |
6551f0a8276c4353b5433977b2bea0fddebce275 | Python | alexliqu09/Python_for_ML_and_DL | /src/parser.py | UTF-8 | 484 | 3.484375 | 3 | [] | no_license | import numpy as np
import argparse
def tanh(x):
return (np.exp(x) + np.exp(-x)) / (np.exp(x) - np.exp(-x))
def parser(funct):
parser = argparse.ArgumentParser()
parser.add_argument("argument", help = "If you want to compute the tanh we need you give a x parammeters",
type = int)
args = parser.parse_args()
print(f"Your argument is: {args.argument} and the result is: {funct(args.argument)}")
if __name__=="__main__":
parser(tanh) | true |
ee6b7acdd67065f27800e35e347da3eb9c8ab9bc | Python | Orelm32/Hotel-Project | /hotel.py | UTF-8 | 15,040 | 3.484375 | 3 | [] | no_license | from time import sleep
room1 = open("C:/Users/Orel Moshe/Desktop/Python Projects/room1.txt", "r")
room2 = open("C:/Users/Orel Moshe/Desktop/python Projects/room2.txt", "r")
room3 = open("C:/Users/Orel Moshe/Desktop/Python Projects/room3.txt", "r")
room4 = open("C:/Users/Orel Moshe/Desktop/Python Projects/room4.txt", "r")
room1res = open("C:/Users/Orel Moshe/Desktop/Python Projects/room1res.txt", "r")
room2res = open("C:/Users/Orel Moshe/Desktop/Python Projects/room2res.txt", "r")
room3res = open("C:/Users/Orel Moshe/Desktop/Python Projects/room3res.txt", "r")
room4res = open("C:/Users/Orel Moshe/Desktop/Python Projects/room4res.txt", "r")
def dates():
sleep(1)
print("\nfor room 1 with 2 adults:\n" + str(room1.read()))
sleep(1)
print("\nfor room 2 with 2 adults:\n" + str(room2.read()))
sleep(1)
print("\nfor room 3 with 3 adults:\n" + str(room3.read()))
sleep(1)
print("\nfor room 4 with 3 adults:\n" + str(room4.read()))
room1.close()
room2.close()
room3.close()
room4.close()
def invitation():
boolean = 0
while boolean == 0:
date = input("enter your date: ")
days = input("How many days do you want? ")
cost2 = (int(days) * 300)
cost3 = (int(days) * 400)
while True:
try:
adults = int(input("How many adults are you? "))
break
except ValueError:
print("That was not a valid number!")
print("Answer with numbers only!")
if adults == 2:
room1_list = room1.read().splitlines()
room2_list = room2.read().splitlines()
boolean = 1
if date in room1_list and date in room2_list:
print("Both room 1 and room 2 are available.")
print("you can invite " + str(days) + " days from " + str(date) + "for a room of 2 adults.")
print("This will cost you: " + str(cost2))
elif date in room1_list:
print("you can invite " + str(days) + " days from " + str(date) + " for " + str(adults) + " adults for room 1")
print("This will cost you: " + str(cost2))
elif date in room2_list:
print("you can invite " + str(days) + " days from " + str(date) + " for " + str(adults) + " adults for room 2")
print("This will cost you: " + str(cost2))
else:
print("This date is taken for both room 1 and room 2")
room1.close()
room2.close()
elif adults == 3:
room3_list = room3.read().splitlines()
room4_list = room4.read().splitlines()
boolean = 1
if date in room3_list and date in room4_list:
print("Both room 3 and room 4 are available.")
print("you can invite " + str(days) + " days from " + str(date) + "for a room of 3 adults.")
print("This will cost you: " + str(cost3))
elif date in room3_list:
print("you can invite " + str(days) + " days from " + str(date) + " for " + str(adults) + " adults for room 3")
print("This will cost you: " + str(cost3))
elif date in room4_list:
print("you can invite " + str(days) + " days from " + str(date) + " for " + str(adults) + " adults for room 4")
print("This will cost you: " + str(cost3))
else:
print("This date is taken for both room 3 and room 4")
print("Please choose another date.")
room3.close()
room4.close()
else:
print("We offer only rooms for 2 or 3 adults.")
sleep(1)
print("If you are more adults then we suggest you divide the order and take more rooms.")
def calculate():
while True:
try:
days = int(input("How many days do you want?: "))
adults = int(input("How many adults are you?: "))
break
except ValueError:
print("Answer with numbers only please")
cost2 = (int(days) * 300)
cost3 = (int(days) * 400)
boolean = 0
while boolean == 0:
date = input("Enter your desired date: ")
if adults == 2:
room1_list = room1.read().splitlines()
room2_list = room2.read().splitlines()
if date in room1_list or date in room2_list:
print("This order of " + str(days) + " days at a room of " + str(adults) + " adults will cost you: " + str(cost2) + " shekels")
choice = input("Would you like to continue? ")
if choice == "yes":
room1res = open("C:/Users/Orel Moshe/Desktop/Python Projects/room1res.txt", "a")
room2res = open("C:/Users/Orel Moshe/Desktop/Python Projects/room2res.txt", "a")
print("Then give us your money!")
sleep(1)
full = input("Enter your full name: ")
credit = input("Enter your credit card: ")
if date in room1_list and date in room2_list:
v = 0
while v == 0:
number = input("Both room 1 and 2 are available on this date.\n Please choose 1/2:\n")
if number == "1":
room1res.write("\n" + "Full Name:" + "\n" + full + "\n" + "Date:" + "\n" + date + "\n" + "Number of days: " + "\n" + str(days))
print("The order of " + str(adults) + " adults room for " + str(days) + " days from " + str(date) + " is confirmed for the price of " + str(cost2) + " shekels on the name of: " + str(full) )
sleep(1)
print("Your room number is:\nRoom number " + str(number))
v = 1
boolean=1
elif number == "2":
room2res.write("\n" + "Full Name:" + "\n" + full + "\n" + "Date:" + "\n" + date + "\n" + "Number of days: " + "\n" + str(days))
print("The order of " + str(adults) + " adults room for " + str(days) + " days from " + str(date) + " is confirmed for the price of " + str(cost2) + " shekels on the name of: " + str(full))
sleep(1)
print("Your room number is:\nRoom number " + str(number))
v = 1
boolean=1
else:
print("Please answer with 1/2 only.")
elif date in room1_list:
room1res.write("\n" + "Full Name:" + "\n" + full + "\n" + "Date:" + "\n" + date + "\n" + "Number of days: " + "\n" + str(days))
print("The order of " + str(adults) + " adults room for " + str(days) + " days from " + str(date) + " is confirmed for the price of " + str(cost2) + " shekels on the name of: " + str(full))
sleep(1)
print("Your room number is:\nRoom number 1")
boolean = 1
elif date in room2_list:
room2res.write("\n" + "Full Name:" + "\n" + full + "\n" + "Date:" + "\n" + date + "\n" + "Number of days: " + "\n" + str(days))
print("The order of " + str(adults) + " adults room for " + str(days) + " days from " + str(date) + " is confirmed for the price of " + str(cost2) + " shekels on the name of: " + str(full))
sleep(1)
print("Your room number is:\nRoom number 2")
boolean=1
elif choice == "no":
again = input("would you like to change your order?: ")
if again == "yes":
room1.close()
room2.close()
calculate()
elif again == "no":
room1.close()
room2.close()
print("That's ok, have a good day!")
boolean = 1
else:
print("This date is taken for both rooms for " + str(adults) + " adults.")
taken = input("would you like to choose a different date?: ")
if taken == "yes":
room2.close()
room1.close()
elif taken == "no":
room1.close()
room2.close()
print("OK, have a good day!")
boolean = 1
elif adults == 3:
room3_list = room3.read().splitlines()
room4_list = room4.read().splitlines()
if date in room3_list or date in room4_list:
print("This order of " + str(days) + " days at a room of " + str(adults) + " adults will cost you: " + str(cost3) + " shekels")
choice = input("Would you like to continue? ")
if choice == "yes":
room3res = open("C:/Users/Orel Moshe/Desktop/Python Projects/room3res.txt", "a")
room4res = open("C:/Users/Orel Moshe/Desktop/Python Projects/room4res.txt", "a")
print("Then give us your money!")
sleep(1)
full = input("Enter your full name: ")
credit = input("Enter your credit card: ")
if date in room3_list and date in room4_list:
v = 0
while v == 0:
number = input("Both room 3 and 4 are available on this date.\n Please choose 3/4:\n")
if number == "3":
room3res.write("\n" + "Full Name:" + "\n" + full + "\n" + "Date:" + "\n" + date + "\n" + "Number of days: " + "\n" + str(days))
print("The order of " + str(adults) + " adults room for " + str(days) + " days from " + str(date) + " is confirmed for the price of " + str(cost3) + " shekels on the name of: " + str(full))
sleep(1)
print("Your room number is:\nRoom number " + str(number))
v = 1
boolean=1
elif number == "4":
room4res.write("\n" + "Full Name:" + "\n" + full + "\n" + "Date:" + "\n" + date + "\n" + "Number of days: " + "\n" + str(days))
print("The order of " + str(adults) + " adults room for " + str(days) + " days from " + str(date) + " is confirmed for the price of " + str(cost3) + " shekels on the name of: " + str(full))
sleep(1)
print("Your room number is:\nRoom number " + str(number))
v = 1
boolean=1
else:
print("Please answer with 3/4 only.")
elif date in room3_list:
room3res.write("\n" + "Full Name:" + "\n" + full + "\n" + "Date:" + "\n" + date + "\n" + "Number of days: " + "\n" + str(days))
print("The order of " + str(adults) + " adults room for " + str(days) + " days from " + str(date) + " is confirmed for the price of " + str(cost3) + " shekels on the name of: " + str(full))
sleep(1)
print("Your room number is:\nRoom number 3")
boolean = 1
elif date in room4_list:
room4res.write("\n" + "Full Name:" + "\n" + full + "\n" + "Date:" + "\n" + date + "\n" + "Number of days: " + "\n" + str(days))
print("The order of " + str(adults) + " adults room for " + str(days) + " days from " + str(date) + " is confirmed for the price of " + str(cost3) + " shekels on the name of: " + str(full))
sleep(1)
print("Your room number is:\nRoom number 4")
boolean = 1
elif choice == "no":
again = input("would you like to change your order?: ")
if again == "yes":
room1.close()
room2.close()
calculate()
boolean = 1
elif again == "no":
room1.close()
room2.close()
print("That's ok, have a good day!")
boolean = 1
else:
print("This date is taken for both rooms for " + str(adults) + " adults.")
taken = input("would you like to choose a different date?: ")
if taken == "yes":
room2.close()
room1.close()
boolean = 0
elif taken == "no":
room1.close()
room2.close()
print("OK, have a good day!")
boolean = 1
def cancel():
print("This will fine you for 10% of the price!")
choice = input("Are you sure you want to cancel your order? ")
if choice == "yes":
name = input("Enter your full name: ")
room1_list = room1res.read().splitlines()
room2_list = room2res.read().splitlines()
room3_list = room3res.read().splitlines()
room4_list = room4res.read().splitlines()
# date = input("Enter your order`s date: ")
print(room1_list)
adults = str(input("How many adults were you?: "))
if adults == "2":
if name in room1_list:
room1.close()
with open("C:/Users/Orel Moshe/Desktop/Python Projects/room1res.txt", "r+") as f:
s = f.readlines()
f.seek(0)
for i in s:
clean_line = i.replace(name, "")
f.truncate()
print("Done")
# cost = input("How much did your order cost?: ")
# fine = int(cost) * 0.1
# print("you need to pay " + str(fine) + " shekels to cancel the order on the name of " + str(name) + " at the date " + str(date) + " please.")
# elif choice == "no":
# print("We are glad and waiting to see you")
def anyelse():
need = input("do you need anything else?")
if need == "yes":
boolean = 0
elif need == "no":
print("enjoy your trip!")
boolean = 1 | true |
3953c407856ef83db643609335dc8526bd470ba6 | Python | sallarak/Automation | /pyAutomation/pyStuff/print_numbers.py | UTF-8 | 90 | 3.578125 | 4 | [] | no_license | #!/usr/bin/python
# Script that prints numbers 1 -10
for i in range(1,11):
print(i)
| true |
1339f21e5eef6e918fa33ccc9c9f0fb86728c016 | Python | agyenes/greenfox-exercises | /08 tkinter_python/02.py | UTF-8 | 441 | 3.859375 | 4 | [] | no_license | # create a 300x300 canvas.
# draw a box that has different colored lines on each edge.
from tkinter import *
root = Tk()
canvas = Canvas(root, width='300', height='300')
canvas.pack()
side_1 = canvas.create_line(30, 30, 270, 30, fill='red')
side_2 = canvas.create_line(270, 30, 270, 270, fill='blue')
side_3 = canvas.create_line(270, 270, 30, 270, fill='green')
side_4 = canvas.create_line(30, 270, 30, 30, fill='cyan')
root.mainloop()
| true |
6a8ce1abad64ee9a1195a7d8b38a44118dfbdd92 | Python | BrendanMoore42/midi_infinite | /main.py | UTF-8 | 3,900 | 3.265625 | 3 | [] | no_license | import time
import rtmidi
import random
from card import *
"""
rtmidi version = 1.1.0
Cards! to Midi!:
A deck of cards has 52! possible permutations - there are
52 * 51 * 50 ... * 2 * 1 possible orders the deck can have.
52! = 8.1 x 10^67 possible configurations.
The current estimated age of the universe
is currently around 4.42 x 10^17, much less than the
possible ordering to a shuffled deck of cards.
Leaving a possible Eight-Septensexagintillion possible
combinations of the generated melody.
Requirements:
- Rtmidi @ http://www.music.mcgill.ca/~gary/rtmidi/index.html
-Python-rtmidi
-Xcode (if OSx)
- Midi controller
- M-Audio USB (for output to MIDI devices)
- Virtual Midi port if supported by target DAW
Other:
- 120 bpm default
- Conversion chart: https://msu.edu/course/asc/232/song_project/dectalk_pages/note_to_%20ms.html
- Suits type of note, Hearts = 16th, Spades = 8th, Clubs = Half, Diamonds = Dotted Half
"""
def create_deck():
cards = [(v, s) for s in ['H', 'S', 'C', 'D']
for v in [int(i) for i in range(1, 14)]]
random.shuffle(cards)
return list(cards)
def create_midi_input(deck):
"""
Returns a list of notes in the format taken by rtmidi:
[channel, note, velocity]
Note - card values can be shifted +/- to bring notes within more
pleasant listening ranges. +40 is a good middle balance.
"""
song_list = []
ch = 0x90
print(f"Shuffled deck: {deck}")
for card, suit in deck:
song_list.extend([[ch, card+40, 100]])
print(f'Midi out: {song_list}')
return song_list
def midi_off_deck(deck):
"""
Midi must be depressed after pressed, or note will hold. This fn
takes the same note from the current card deck and turns the velocity
to 0 and close the channel.
"""
song_list_off = []
closed_ch = 0x80
vel = 0
for card, suit in deck:
song_list_off.extend([[closed_ch, card+40, vel]])
return song_list_off
def add_rests(deck):
"""
Takes the suit and converts that to a beat:
Hearts = 16th, Spades = 8th, Clubs = Half, Diamonds = Dotted Half
"""
rest_time = []
#h=16th, s=8th, c=1/2, d=d1/2 @ 120bpm
h, s, c, d = 0.125, 0.250, 1, 1.5
for suit in deck:
if suit[1] == 'H':
rest_time.append(h)
if suit[1] == 'S':
rest_time.append(s)
if suit[1] == 'C':
rest_time.append(c)
if suit[1] == 'D':
rest_time.append(d)
return rest_time
def main():
"""
Main fn, creates deck, assigns values, rests and midi points
"""
# note_on = [0x90, 14, 112] # channel 1, middle C, velocity 112
# note_off = [0x80, 14, 0]
deck = create_deck()
deck_midi_out = list(create_midi_input(deck))
rest_to_add = add_rests(deck)
rest_times = [i for i in rest_to_add]
off_deck = list(midi_off_deck(deck))
user_input = input(('Play track? (y/n)?'))
if user_input == 'y':
midiout = rtmidi.MidiOut()
available_ports = midiout.get_ports()
"""Looks for active midi, if none found opens virtual port...
Set up of a virtual port for garageband through Audio Midi Setup
"""
if available_ports:
midiout.open_port(0)
else:
midiout.open_virtual_port("My virtual output")
for note, rest, note_off in zip(deck_midi_out, rest_times, off_deck):
midiout.send_message(note)
time.sleep(rest)
midiout.send_message(note_off)
print(note)
print(rest)
play_again = input('Play again? (y/n)?')
if play_again == 'y':
main()
if play_again == 'n':
print('Maybe next time.')
del midiout
if user_input == 'n':
print('Suit yourself.')
if __name__ == '__main__':
main()
| true |
d9c8ca35dc21e355f3b80db1dea6ec1a63363f18 | Python | KoreyEnglert/HW4-unit-testing | /Q2_unit_test.py | UTF-8 | 511 | 3.0625 | 3 | [] | no_license | import unittest
import Q2
class TestCase(unittest.TestCase):
def test_average(self):
self.assertAlmostEqual(Q2.average([3,4,5]), 4);
def test_average2(self):
self.assertAlmostEqual(Q2.average([3,4,5]), 5);
def test_average3(self):
self.assertAlmostEqual(Q2.average([3.2,4.7,5.1,-.1,100]), 22.58);
def test_average4(self):
self.assertAlmostEqual(Q2.average([]), 0);
def test_average5(self):
self.assertAlmostEqual(Q2.average(["a","b","c"]), "b");
| true |
46bb3fb46cf43152398ab8cff912f41097aea8da | Python | alexandraback/datacollection | /solutions_2652486_1/Python/jbochi/3.py | UTF-8 | 1,432 | 2.96875 | 3 | [] | no_license | import itertools
from collections import defaultdict
def cards(m):
return range(2, m + 1)
def combinations(c, n):
return itertools.combinations_with_replacement(c, n)
def select(n):
return itertools.product([True, False], repeat=n)
def choices(m, n):
for cs in combinations(cards(m), n):
products = defaultdict(int)
for ss in select(n):
p = reduce(lambda a, b: a * b, (c for c, s in zip(cs, ss) if s), 1)
products[p] += 1
yield cs, products
def most_possible(products, choices):
bestt = 0
best = None
for c, pp in choices:
total = 0
impossible = False
for p in products:
t = pp[p]
if t == 0:
impossible = True
break
total += t
if not impossible and total > bestt:
bestt = total
best = c
return best
def solve():
with open("3.in") as f:
c = [map(int, l.strip().split()) for l in f.readlines()]
for t in range(c[0][0]):
R, N, M, K = c[1]
print "Case #%d:" % (t + 1)
#C = list(choices(M, N))
import pickle;
with open("C2", "r") as f:
C = pickle.load(f)
for i in xrange(R):
best = most_possible(c[i+2], C)
best = best or [2 for i in range(K)]
print ''.join(map(str, best))
if __name__ == "__main__":
solve()
| true |
489c5fd3d8dc334f227a5b8ed4d0e51a95c4c81b | Python | dst1213/python_canslim | /CANSLIM/get_stock_df.py | UTF-8 | 2,019 | 2.890625 | 3 | [] | no_license | from datetime import date
import pandas as pd
from get_eps import get_quarterly_eps
from get_roe_revenue import get_roe, get_revenue_quarterly
columns = ['TICKER', 'Q1', 'Q2', 'Q3', 'Q4',
"Q1'", 'EPS%', 'ROE', 'REV%', 'UPDATED DATE']
tickers_row = []
tickers_dict = {}
def get_revenue_growth_quarterly(revenue_list):
try:
revenue_growth = round(
(revenue_list[0] - revenue_list[4]) / revenue_list[4] * 100, 2)
return revenue_growth
except:
pass
def get_stock_df(tickers_to_analyze):
try:
global tickers_row
i = 0
while i < len(tickers_to_analyze):
quarterly_eps = get_quarterly_eps(
tickers_to_analyze[i]) # get a list of quarterly eps
eps_growth_pct = round(
(quarterly_eps[4] - quarterly_eps[0]) / abs(quarterly_eps[0]) * 100, 2) # calculate eps growth btwn current quarter and same quarter last year
roe = get_roe(tickers_to_analyze[i])
revenue_list = get_revenue_quarterly(tickers_to_analyze[i])
revenue_growth_pct = get_revenue_growth_quarterly(
revenue_list)
# Append EPS growth percentage to eps_growth list
tickers_row.append(tickers_to_analyze[i].upper())
tickers_row.append(quarterly_eps[0])
tickers_row.append(quarterly_eps[1])
tickers_row.append(quarterly_eps[2])
tickers_row.append(quarterly_eps[3])
tickers_row.append(quarterly_eps[4])
tickers_row.append(eps_growth_pct)
tickers_row.append(roe)
tickers_row.append(revenue_growth_pct)
tickers_row.append(date.today().strftime("%m/%d/%Y"))
tickers_dict[i] = tickers_row
tickers_row = []
i += 1
# Put data to DataFrame
stock_df = pd.DataFrame.from_dict(tickers_dict, orient='index')
stock_df.columns = columns
return stock_df
except:
pass
| true |
b9b2cebbd0ca305e379e9f0eeab8f961fcc968f5 | Python | judgegc/se-res-calc | /scripts/extract_blocks.py | UTF-8 | 2,590 | 2.5625 | 3 | [] | no_license | import re
import json
import xml.etree.ElementTree as ET
SOURCE = 'CubeBlocks.sbc'
def extract_block(el):
componentMap = {
'SteelPlate': 'steel_plate',
'Construction': 'construction_component',
'PowerCell': 'power_cell',
'Computer': 'computer',
'MetalGrid': 'metal_grid',
'BulletproofGlass': 'bulletproof_glass',
'LargeTube': 'large_steel_tube',
'Girder': 'girder',
'SmallTube': 'small_steel_tube',
'InteriorPlate': 'interior_plate',
'Reactor': 'reactor_components',
'Display': 'display',
'Explosives': 'explosives',
'Medical': 'medical_components',
'Detector': 'detector_components',
'GravityGenerator': 'gravity_generator_components',
'Motor': 'motor',
'RadioCommunication': 'radio-communication_components',
'Superconductor': 'superconductor_component',
'Thrust': 'thruster_components',
'SolarCell': 'solar_cell'}
display_name = el.find('DisplayName').text
if not display_name.startswith('DisplayName_Block'):
return {}
words = re.findall('[A-Z][^A-Z]*', display_name.replace('DisplayName_Block_', ''))
compoents = {}
for component in el.findall('Components/Component'):
if componentMap[component.attrib['Subtype']] in compoents:
compoents[componentMap[component.attrib['Subtype']]] += int(component.attrib['Count'])
else:
compoents[componentMap[component.attrib['Subtype']]] = int(component.attrib['Count'])
return {'name': '_'.join(words).lower(), 'title': ' '.join(words).capitalize(), 'size': el.find('CubeSize').text.lower(), 'components': compoents}
def main():
root = ET.parse(SOURCE).getroot()
blocks = []
for el in root.find('.//CubeBlocks'):
block = extract_block(el)
if block:
blocks.append(block)
print('Total blocks: {0}'.format(len(blocks)))
blocksObj = {}
for block in blocks:
if block['name'] in blocksObj:
continue
combinedBlock = {'title': block['title'], 'components': {block['size']: block['components']}}
for b in blocks:
if block is b:
continue
if block['name'] == b['name']:
combinedBlock['components'][b['size']] = b['components']
blocksObj[block['name']] = combinedBlock
blocksObj[block['name']]['icon'] = '{0}.png'.format(block['name'])
with open('blocks.json', 'w') as f:
json.dump(blocksObj, f)
if __name__ == "__main__":
main()
| true |
ca926994c6288e4cfdf174bf4ff63638a362fa0f | Python | JenZhen/LC | /lc_ladder/Adv_Algo/dp/Longest_Continuous_Increasing_Subsequence_II.py | UTF-8 | 3,883 | 3.828125 | 4 | [] | no_license | #! /usr/local/bin/python3
# https://www.lintcode.com/problem/longest-continuous-increasing-subsequence-ii/description
# https://leetcode.com/problems/longest-increasing-path-in-a-matrix/submissions/
# Same as LC329 Longest Increasing Path in a Matrix
# Example -- 从山顶滑雪问题, 最长下山路径
# Give you an integer matrix (with row size n, column size m),find the longest increasing continuous subsequence in this matrix.
# (The definition of the longest increasing continuous subsequence here can start at any row or column and go up/down/right/left any direction).
#
# Example
# Given a matrix:
#
# [
# [1 ,2 ,3 ,4 ,5],
# [16,17,24,23,6],
# [15,18,25,22,7],
# [14,19,20,21,8],
# [13,12,11,10,9]
# ]
# return 25
#
# Challenge
# O(nm) time and memory.
"""
Algo: DP
D.S.:
Solution:
难点:
1. 遍历来自四面,不是顺序遍历
2. dp起点不好找,初始状态不好找
所以传统动归思路,不好做。
可以想到的思路, 时间复杂度非常高,如何利用以求解的小问题
i: 0 -> n
j: 0 -> n
dfs(i, j) # 以i,j 结尾的最长自序列
dfs(i, j, A):
for i in range(4):
nx, ny = i + dx[i], j + dx[j]
if A[nx][ny] < A[i][j]:
continue
return ans
Solution1: 记忆化搜索方式
Time: O(mn) ie size of f[][], Space O(nm)
DP 分析
1. 状态
f[i][j]: 以i,j 结尾的最长自序列
2. 方程
遍历上下左右,以i,j结尾的最长子序列
if f[i][j] > f[nx][ny]:
f[i][j] = f[nx][ny] + 1
3. 初始化
f[i][j] = 1
4. 答案
max(f[i][j])
Solution2:
Corner cases:
"""
class Solution1:
"""
@param matrix: A 2D-array of integers
@return: an integer
"""
def longestContinuousIncreasingSubsequence2(self, matrix):
# write your code here
if not matrix or not matrix[0]:
return 0
row = len(matrix)
col = len(matrix[0])
f = [[1] * col for i in range(row)]
flag = [[False] * col for i in range(row)]
res = 1
for i in range(row):
for j in range(col):
f[i][j] = self.dfs(i, j, f, flag, matrix)
res = max(res, f[i][j])
return res
def dfs(self, i, j, f, flag, matrix):
if flag[i][j] == True:
return f[i][j]
dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]
ans = 1
for (dx, dy) in dirs:
nx, ny = i + dx, j + dy
if nx < 0 or nx >= len(f) or ny < 0 or ny >= len(f[0]):
continue
if matrix[i][j] > matrix[nx][ny]:
ans = max(ans, self.dfs(nx, ny, f, flag, matrix) + 1)
flag[i][j] = True
f[i][j] = ans
return ans
class Solution2:
"""
@param matrix: A 2D-array of integers
@return: an integer
"""
def longestContinuousIncreasingSubsequence2(self, matrix):
# write your code here
if not matrix or not matrix[0]:
return 0
row = len(matrix)
col = len(matrix[0])
seq = []
for i in range(row):
for j in range(col):
seq.append((matrix[i][j], i, j))
seq.sort()
print("check seq: %s" %repr(seq))
res = 1
LCIS = {} # key: coor, val: LCIS number
for ele in seq:
coor = (ele[1], ele[2])
LCIS[coor] = 1 # init the LCIS is 1
for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
x = coor[0] + dx
y = coor[1] + dy
if x < 0 or x >= row or y < 0 or y >= col:
continue
else:
if (x, y) in LCIS and matrix[x][y] < ele[0]:
LCIS[coor] = max(LCIS[coor], LCIS[(x, y)] + 1)
res = max(res, LCIS[coor])
return res
# Test Cases
if __name__ == "__main__":
solution = Solution()
| true |
9a1f38f15cd412e6ed42d0e931aa84889ccb45e2 | Python | yuxueCode/Python-from-the-very-beginning | /01-Python-basics/05-Lists-and-dictionaries/chapter05/list/sample1.py | UTF-8 | 138 | 4 | 4 | [] | no_license | #列表的创建
#变量名=[元素1,元素2,....]
list = ['a' , 'b' , 'c' , 'd' , 1 , 2 , 3 , 4]
print(list)
list1 = []
print(list1) | true |
803450c0a3075f119b124d251b591847887a372e | Python | AndreasWituschek/fermi_analysis | /fermi_analysis/functions.py | UTF-8 | 26,507 | 2.59375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 13 13:22:02 2019
@author: Andreas
"""
import numpy as np
import matplotlib.pyplot as plt
import sys
#import pandas as pd
import scipy as sp
import scipy.constants as spc
from scipy import optimize
from scipy import fftpack
import h5py
import os
#physical constants:
c = spc.speed_of_light / 1000000.0 # speed of light in nm/fs
hPlanck = 4.135667662 # plancks constant in 10e-15 eV*s
def importFile(path):
with open(path, 'r') as document:
data = {}
header = document.readline().split()
for i in header:
data[i] = []
for line in document:
line = line.split()
for idx, i in enumerate(line):
data[header[idx]].append(float(i))
return data
def Curve(l_He, l_ref, h, phi, A, offset, start, stop, length):
"creates datapoints on cosine/sine curve with given parameters for frequency, ampliotude and phase."
points=30000 # number of TD points for plotting of theroetical curve
plotRange = np.linspace(start-10,stop+10,points)
tau = np.linspace(start,stop,length)
Xtd=offset+A*np.cos(-2.*np.pi *c*plotRange*(h*l_He-l_ref)/(l_ref*l_He) + phi/180.0*np.pi)
Ytd=offset+A*np.sin(-2.*np.pi *c*plotRange*(h*l_He-l_ref)/(l_ref*l_He) + phi/180.0*np.pi)
X=offset+A*np.cos(-2.*np.pi *c*tau*(h*l_He-l_ref)/(l_ref*l_He) + phi/180.0*np.pi)
Y=offset+A*np.sin(-2.*np.pi *c*tau*(h*l_He-l_ref)/(l_ref*l_He) + phi/180.0*np.pi)
return Xtd,Ytd,X,Y
def CurveCreator(l_He,l_ref,h,phi,A, delay,pNoise,aNoise):
"creates datapoints on cosine/sine curve with given parameters for frequency, ampliotude and phase. Phase noise and amplitude noise can be imparted."
n=len(delay)
delPhiX= np.random.rand(n)*2*np.pi*pNoise
delPhiY= np.random.rand(n)*2*np.pi*pNoise
X=np.cos(2.*np.pi *c*delay*(h*l_He-l_ref)/(l_ref*l_He) + phi/180*np.pi + delPhiX)
Y=np.cos(2.*np.pi *c*delay*(h*l_He-l_ref)/(l_ref*l_He) + (phi+90)/180*np.pi + delPhiY)
X=((np.random.rand(n)-.5)*aNoise+1)*X
Y=((np.random.rand(n)-.5)*aNoise+1)*Y
return X,Y
def PlotCurve(X,Y,start, stop):
points=100000 # number of TD points for plotting of theroetical curve
plotRange = np.linspace(start-10,stop+10,points)
plt.plot(plotRange,X,'b--', label="theoretical curve demodX")
plt.plot(plotRange,Y, 'r--', label="theoretical curve demodY")
plt.xlabel('Delay [fs]')
plt.ylabel('Amplitude [V]')
plt.title("Downshifted quantum interferences (TD)")
plt.legend()
def PlotTdData(data,demod):
#plot data points
plt.errorbar(data['delay'],data['mX%d' % demod], yerr=data['sX%d' % demod],color='b',linestyle='')
plt.plot(data['delay'],data['mX%d' % demod],'bo')
plt.errorbar(data['delay'],data['mY%d' % demod], yerr=data['sY%d' % demod],color='r',linestyle='')
plt.plot(data['delay'],data['mY%d' % demod],'ro')
def PlotFdCurve(stop,start,cdft,cdft_d,l_ref,l_He,h):
"plots the absoprtion spectrum of theoretical curve and data, x- axis is downshifted frequency"
plt.figure()
fDown = abs(c*1000*(h*l_He-l_ref)/(l_ref*l_He)) # downshifted frequency of demodulated signal
cdft= cdft/max(abs(cdft))*max(abs(cdft_d)) #normalizing theoretical curve on experimental data
xaxis=[i* 10**3./(stop-start) for i in range(len(cdft))] #x-axis conversion in THz
plt.plot(xaxis,abs(cdft),linestyle='-', label="theoretical curve")
plt.plot(xaxis,abs(cdft_d),linestyle='-', label="experimental data")
plt.xlim([0,200])
plt.axvline(x=fDown, color='black', linestyle='--')
plt.xlabel('Downshifted quantum interference frequency [THz]')
plt.ylabel('Intensity [a.U.]')
plt.legend()
plt.title("Downshifted quantum interference")
def PlotFdCurveAbsEV(stop,start,cdft,cdft_d,l_ref,l_He,h):
"plots the absoprtion spectrum of theoretical curve and data"
plt.figure()
transition=c/l_He*hPlanck #helium transition energy
cdft= cdft/max(abs(cdft))*max(abs(cdft_d)) #normalizing theoretical curve on experimental data
xaxis=[(i* (1./(stop-start)*hPlanck)+h*c/l_ref*hPlanck) for i in range(len(cdft))] # x-axis, convert from downshifted frequency axis to eV
plt.plot(xaxis,abs(cdft),linestyle='-', label="theoretical curve")
plt.plot(xaxis,abs(cdft_d),linestyle='-', label="experimental data")
#plt.xlim([23,25])
plt.axvline(x=transition, color='black', linestyle='--')
plt.text(transition+0.02,0.8*max(abs(cdft)),'He 4P') #position of He4P transition
plt.xlabel('Energy [eV]')
plt.ylabel('Intensity [a.U.]')
plt.legend()
plt.title("Absorption spectrum")
def PlotFdCurveEV(xaxis,cdft,cdft_d,l_ref,l_He,h):
"plots the absorptive and dispersive part of the spectrum of theoretical curve and data"
plt.figure()
transition=c/l_He*hPlanck #helium transition energy
cdft= cdft/max(abs(cdft))*max(abs(cdft_d)) #normalizing theoretical curve on experimental data
plt.plot(xaxis,cdft.real,linestyle='-', label="theoretical curve absorptive")
plt.plot(xaxis,cdft_d.real,linestyle='-', label="experimental data absorptive")
plt.plot(xaxis,cdft.imag,linestyle='-', label="theoretical curve dispersive")
plt.plot(xaxis,cdft_d.imag,linestyle='-', label="experimental data dispersive")
plt.xlim([23,25])
plt.axvline(x=transition, color='black', linestyle='--')
plt.text(transition+0.02,0.8*max(abs(cdft)),'He 4P') #position of He4P transition
plt.xlabel('Energy [eV]')
plt.ylabel('Intensity [a.U.]')
plt.legend()
plt.title("Absorptive and dispersive spectra")
def ReadMfliData_fake(mfli_file_path,bunches): #bunches= number of shots in one file
"reads data from files created with mfli.py containing the raw demodulated data. ONLY DUMMY TO CREATE SOME DATA RIGHT NOW"
X = [np.random.rand(bunches) for i in np.arange(0,4)] #demodulated X data for each bunch
Y = [np.random.rand(bunches) for i in np.arange(0,4)] #demodulated Y data for each bunch
modfreq= 1000+np.random.rand(bunches) # modulation frequency for each bunch in Hz
run= 1 # run number
timestamp = 10 # timestamp of first bunch in this run
bunchnumber = 3 #bunchnumber of first bunch in this run
mfli_data = {'run': run,
'bunchnumber': bunchnumber,
'timestamp': timestamp,
'modfreq': modfreq,
'X': X,
'Y': Y,} #write all into one dictionary
return mfli_data
def ReadMfliData(mfli_file_path): #bunches= number of shots in one file
""" reads data from files created with mfli.py containing the raw
demodulated data.
"""
h5f = h5py.File(mfli_file_path, 'r')
# Create dict with:
mfli_data = {}
for key in h5f.keys():
mfli_data.update({key: np.array(h5f[key])})
h5f.close()
return mfli_data
def AveragingMfliData(mfli_data,I0,apply_filter,I0_threshold,modfreq_set,modfreq_threshold,ignore):
"Applys filters (IO and modfreq) on mfli data and averages filtered values"
if apply_filter:
I0_filter=np.asarray([i>I0_threshold for i in I0])*1 #I0 filter
I0_filter=np.concatenate([I0_filter,np.ones(ignore)])
a=np.zeros((ignore,len(I0_filter)))
for i in range(ignore):
a[i]=np.roll(I0_filter,i)
I0_filter=(np.sum(a,0)>(ignore-1))[ignore-1:len(I0)+(ignore-1)] #I0 filter extended by number of ignored shots
modfreq_filter= np.asarray([-modfreq_threshold < i-modfreq_set < modfreq_threshold for i in mfli_data['frequency']]) #filter for modfreq
modfreq_filter=np.concatenate([modfreq_filter,np.ones(ignore)])
a=np.zeros((ignore,len(modfreq_filter)))
for i in range(ignore):
a[i]=np.roll(modfreq_filter,i)
modfreq_filter=(np.sum(a,0)>(ignore-1))[ignore-1:len(I0)+ignore-1] #modfreq filter extended by number of ignored shots
b = np.logical_and(I0_filter,modfreq_filter) #combining both filters above
if sum(b)>0:
print("# total bunches = %d" % len(I0))
print("# filtered Bunches = %d" % sum(b))
mX= [np.mean(mfli_data['x2'][i][np.where(b)]) for i in range(len(mfli_data['X']))]
mY= [np.mean(mfli_data['y2'][i][np.where(b)]) for i in range(len(mfli_data['Y']))]
sX= [np.std(mfli_data['x2'][i][np.where(b)]) for i in range(len(mfli_data['X']))]
sY= [np.std(mfli_data['y2'][i][np.where(b)]) for i in range(len(mfli_data['Y']))]
else:
print('Filters to tight, no data to average over. Script stopped, no data written in masterData.csv!')
sys.exit(1)
else:
mX= np.mean((mfli_data['x2']))
mY= np.mean((mfli_data['y2']))
sX= np.std((mfli_data['x2']))
sY= np.std((mfli_data['y2']))
print("# averaged bunches = %d" % len(I0))
I0_filter=[]
modfreq_filter=[]
return mX,mY,sX,sY,I0_filter,modfreq_filter
#def MasterFileWriter(mfli_data, delay, mX, mY, sX, sY):
# d = {'run': [mfli_data['run']],\
# 'delay': [delay],\
# 'mX0': [mX[0]],'mY0': [mY[0]],'mX1': [mX[1]],'mY1': [mY[1]],'mX2': [mX[2]],'mY2': [mY[2]],'mX3': [mX[3]],'mY3': [mY[3]],\
# 'sX0': [sX[0]],'sY0': [sY[0]],'sX1': [sX[1]],'sY1': [sY[1]],'sX2': [sX[2]],'sY2': [sY[2]],'sX3': [sX[3]],'sY3': [sY[3]],\
# 'bunchnumber': [mfli_data['bunchnumber']],\
# 'timestamp' : [mfli_data['timestamp']]\
# }
# df = pd.DataFrame.from_dict(d)
# return df
#def MasterFileReader(path):
# data = np.genfromtxt(path, delimiter='\t', dtype='|S')
# a = np.array(data[1:]).astype(np.float)
# sorted_data = np.array(sorted(a, key=lambda a_entry: a_entry[2]))
# data_dict = dict(zip(data[0][1:], sorted_data.astype(np.float).T[1:]))
## print(sorted_data)
# print('dict anfang')
# print(data_dict['delay'])
# print('dict ende')
# return data_dict
def DelayMove(delay_pos):
if all(x == delay_pos[0] for x in delay_pos):
delay_pos=delay_pos[0]
else: print("Delaystage moved during run!")
def GaussWindow(T, X, suscept):
"""
Applies Gaussian window to data set which decays to 5% at edges of data set
. If suscept==False, the window function is centered with respect to the
data set. Otherwise, it is centered at T[0] which is 0fs if susceptibility
is wanted.
"""
start = T[0]
stop = T[-1]
if suscept:
mu = 0.0
std = 2*(abs(stop-start))/sp.sqrt(48) # so Gaussian will be dropped to 5% (e.g. 1/e^3) at edges of dataset
else:
mu = (stop+start)/2
std = (abs(stop-start))/sp.sqrt(48) # so Gaussian will be dropped to 5% (e.g. 1/e^3) at edges of dataset
return X*sp.exp(-((T-mu)/(2*std))**2)
def zero_padding(T, factor):
return 2**(int(round(np.log2(T.size)+0.5))+factor) # Anzahl Datenpunkte auf die zur Not mit Zero-Padding aufgefuellt wird
def find_index(array, value):
return np.argmin(abs(array-value)) # loops through array from index zero and returns first index that is closest to value
def redistribute(array, index):
return np.concatenate((array[index:],array[0:index]))
def CutDataSet(T, X, Y, data_window):
# T and data_window should be of same unit, e.g. femtoseconds
# sort start,stop according to increasing/decreasing numbers in T
if T[-1]>T[0]:
start_user = min(data_window)
stop_user = max(data_window)
else:
start_user = max(data_window)
stop_user = min(data_window)
# cut data
lower_index = np.argmin(np.abs(T-start_user))
upper_index = np.argmin(np.abs(T-stop_user))+1
T = T[lower_index : upper_index]
X = X[lower_index : upper_index]
Y = Y[lower_index : upper_index]
return (T,X,Y)
def DFT(T, Z, dT, l_ref, harmonic, zeroPaddingFactor):
"""
Calculates DFT of complex valued input array Z. Applays zero padding as spe
cified by input factor. Establishes correct monotonoic order of frequency
axis. Returns wavenumber array and complex valued DFT.
"""
step = dT
wn_Mono = 1E7/l_ref
# determine zero padding
N = zero_padding(T, zeroPaddingFactor)
# calculate wavenumber axis
freq = fftpack.fftfreq(N, d = step*10**(-15)) # frequency axis in Hz
if step<0:
freq = freq[::-1] # reverse array
cut_index = np.argmin(freq)
freq = redistribute(freq, cut_index) # sortiere wn Array so, dass Wellenzahlen monoton steigen
wn = freq/100.0/spc.c + harmonic*wn_Mono # wn wird um Mono geshiftet wie in rpt File gegeben
# calculate DFT
DFT = redistribute(fftpack.fft(Z, n=N), cut_index) # sortiere wn Array so, dass Wellenzahlen monoton steigen
if step < 0:
DFT = DFT[::-1] # reverse array
# correct for delay offset error
# offset = T[find_index(T,0.0)]*10**(-15) # in s
# phaseCorrection = np.array([np.exp(-1j*2*np.pi*f*offset) for f in freq])
# DFT *= phaseCorrection
return wn, DFT
def slide_window(T, Z, t_center, FWHM):
# multiplies a gaussion onto the dataset and returns the data set of the whole range of T
# T, t_center, FWHM in ps
# Z may be complex
return Z*sp.exp(-4*sp.log(2)*((T-t_center)/FWHM)**2)
def weighting_coeff(t, t_center, FWHM): # calculates amplitude of gaussian at time t
gauss_window = sp.exp(-4*sp.log(2)*((t-t_center)/FWHM)**2)
rect_window = np.where(abs(gauss_window)<=0.5,1,0)
return gauss_window
def plot_spectrogram(fig, wn, T, S, l_fel,l_trans, wn_lim, t_lim):
fs = 15
lw = 2
ax = fig.add_subplot(111) # define current axes
xmin_index = np.argmin(abs(wn-wn_lim[0]))
xmax_index = np.argmin(abs(wn-wn_lim[1]))
tmin_index = np.argmin(abs(T-t_lim[0]))
tmax_index = np.argmin(abs(T-t_lim[1]))
clim= [0.0, 1.0*S.max()] # 0.65
ax.imshow(S.transpose()[xmin_index:xmax_index, tmin_index:tmax_index], clim=clim, origin='lower', aspect='auto', extent=[T[tmin_index],T[tmax_index], wn[xmin_index],wn[xmax_index]])
ax.set_ylabel('frequency [cm$^{-1}$]', fontsize = fs)
ax.set_xlabel('delay [fs]', fontsize = fs)
ax.tick_params(labelsize=fs)
locs, labels = plt.yticks()
plt.setp(labels, rotation=90)
ax.get_xaxis().get_major_formatter().set_useOffset(False)
ax.get_xaxis().set_tick_params(which='both', direction='out', pad=-5, length=5, width=1.5)
ax.get_yaxis().set_tick_params(which='both', direction='out', pad=-5, length=5, width=1.5)
ax.get_xaxis().tick_bottom() # remove unneeded ticks
ax.get_yaxis().tick_left()
ax.get_yaxis().set_tick_params(which='both', length=5, width=1.5)
ax.get_xaxis().set_tick_params(which='both', length=5, width=1.5)
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(1.5)
#ax.axvspan(-overlap,overlap, color='grey', alpha=0.9)
ax.axhline(1E7/l_trans, linestyle='--', color='grey', linewidth=lw)# He atom line
# ax.axhline(1E7/l_fel, linestyle='-', color='grey', linewidth=lw)# Laser frequency
ax.legend([r'He $1s\rightarrow 4p$ ','wn_fel'])
ax.set_xlim(t_lim[0], t_lim[1])
# ax.text(0.9, 0.9, '(b)', transform=ax.transAxes, ha='left', fontweight='bold',fontsize = 22, color='w')
#annotate()
#plotbar()
def PeakWidth(T, peakMargin, suscept, zeroPaddingFactor):
"""
Calculates the FWHM of spectral peaks as well as the full width at which
spectral peaks will be dropped to peakMargin (fraction of peak maximum)
of their amplitude. For this purpose a simuTruelated perfect cosine signal is
Fourier transformed with Gaußian window and zero padding and its FWHM and
peak margin (peakWidth) is measured and returned.
"""
# simulate perferct cosine signal
length = abs(T[-1]-T[0]) # in fs
step = length/(len(T)-1)
w = 2*np.pi*1/(20*step) # choose frequency factor 10 below nyquist
# paras = {'Schrittweite' : step, 'Monochromator Wavenumber' : 0 }
sim = np.exp(1j*w*T) # define simulated signal as in-phase + 1j*in-quad
if suscept:
phase_corr = np.exp(-1j*T[find_index(np.array(T),0)]*w) #phase correction of data to take into account zero delay shifts
sim *= phase_corr
sim = GaussWindow(T, sim, suscept)
wn, dft = DFT(T, sim, step, 1, 1, zeroPaddingFactor)
if suscept:
dft = dft.real
else:
dft = abs(dft)
# normalize dft to 1
dft /= dft.max()
wnFitted, fFitted, fitParas = PeakFit("simulation", 1.0, wn, dft, np.abs(wn[-1]-wn[0]), 0.)
# determine peak width of simulated signal
peakFullWidth = abs(wn[findPeakIndexes(dft, peakMargin)[1]]-wn[findPeakIndexes(dft, peakMargin)[2]])
FWHM = abs(wn[findPeakIndexes(dft, 0.5)[1]]-wn[findPeakIndexes(dft, 0.5)[2]])
# calculate widths from theoretical derivation of gaussian window width
# delta = length*np.sqrt(np.log(2)/3)
# FWHM = 8.0*np.log(2.0)/delta# FWHM of Gaussian Window
# peakFullWidth = 4*np.sqrt(-np.log(2)*np.log(peakMargin))/delta
return FWHM, peakFullWidth
def findPeakIndexes(Y, peakMargin):
"""
Returns index of peak maximum, left and right index where dropped to
fraction defined by peakMargin.
"""
indexMax = np.argmax(abs(Y)) # find peak maximum
indexLow = np.argmin(abs(Y[:indexMax+1]-peakMargin*Y.max())) # search index in first half of peak
indexHigh = np.argmin(abs(Y[indexMax:]-peakMargin*Y.max())) + indexMax # search in second half of peak
return indexMax, indexLow, indexHigh
def PeakFit(peakName, peakWaveNo, wn, spectrum, windowLength, guessNoise):
"""
Performes a gaussian fit of a spectral peak with no constant offset.
windowLength : full width of fit window, usually windowLength=x*PeakWidth(T)
spectrum : should be ABSOLUTE value of spectrum
guessNoise : typical a definition like this is choosen: noiseFloor*(1+(Ham-1)*5)
"""
totalError = False
# construct fit window
# wnFit, spectrumFit = FitData(wn, spectrum, peakWaveNo, windowLength)
wnFit = wn
spectrumFit = spectrum
# guess fit paras
pguess = GuessPeakParameter(wnFit, spectrumFit)
sigmas = np.zeros(len(wnFit)) + guessNoise # assume every data point has same errorbars
# proceed fitting
popt, pcov = optimize.curve_fit(f_fixoff, wnFit, spectrumFit, pguess[0:-1]) #, sigma=sigmas) #, absolute_sigma=True)
#popt, pcov = optimize.curve_fit(f, wnFit, spectrumFit, pguess[0:-1], sigma=sigmas)
errors = sp.sqrt(pcov.diagonal())
if totalError:
# calculate total error of fit function evaluated at maximum of fit function
err_fmax = GaussFitError(wn,popt,pcov)
# use total fit error as estimate for Amp_err
errors[0] = err_fmax
AmpErrText = 'Error Amp tot'
AreaErrText = 'Error Area tot'
else:
AmpErrText = 'Error Amp'
AreaErrText = 'Error Area'
# calculate peak area:
area = popt[0]*popt[2]*np.sqrt(np.pi/np.log(16))
err_area = abs(area)*np.sqrt((errors[0]/popt[0])**2 + (errors[2]/popt[2])**2) # Gaussian error propagation
wnFitted = np.linspace(wnFit[0], wnFit[-1], num=3000)
#f_fitted = f(wn_fitted, popt[0], popt[1], popt[2], popt[3])
fFitted = f_fixoff(wnFitted, popt[0], popt[1], popt[2])
#print('peak_fit: ' + peakName,popt[0],popt[1],popt[2],area)
fitParas = {'Peak': peakName , \
'Amp': round_sig(popt[0],3) , \
AmpErrText: round_sig(errors[0],1) , \
'Center': round(popt[1],3) , \
'Error Center':round_sig(errors[1],1) , \
'FWHM':round(popt[2],2) , \
'Error FWHM':round_sig(errors[2],1) ,\
'Area':round_sig(area,3) , \
AreaErrText:round_sig(err_area,1)}
return wnFitted, fFitted, fitParas
def FitData(wn, spectrum, peakWaveNo, windowLength):
# construct fit window
lowIndex = find_index(wn, peakWaveNo-0.5*windowLength)
highIndex = find_index(wn, peakWaveNo+0.5*windowLength)
wnFit = wn[lowIndex:highIndex+1].copy() # fit window of the wavenumber array
spectrumFit = spectrum[lowIndex:highIndex+1].copy() # fit window of the DFT amplitudes array
return wnFit, spectrumFit
def GuessPeakParameter(Xfit, Yfit):
"""
Estimates peak parameters for peak fit. XFit and Yfit should be restricted
to a small area around the peak of interest. If more than one peak is within
Xfit and Yfit, wrong parameters will be estimated. Provide ABSOLUTE value
of spectrum.
"""
pguess = np.zeros(4)
pguess[0] = Yfit.max() # Amp
pguess[1] = Xfit[np.argmax(Yfit)] # center
pguess[2] = abs(Xfit[findPeakIndexes(Yfit, 0.5)[1]]-Xfit[findPeakIndexes(Yfit, 0.5)[2]]) # FWHM
pguess[3] = 0.0 # offset
return pguess
def GaussFitError(X,popt,pcov):
"""
Calculates the total error of fit function for a Gaussian fit with no offset evaluated at maximum of fit function
"""
a = popt[0]
b = popt[1]
c = popt[2]
Y = f_fixoff(X, a, b, c)
i = find_index(X,popt[1]) # find index of peak maximum
# berechne derivatives
da = Y[i]/a
db = Y[i]*(8*np.log(2)/(c**2)*(X[i]-b))
dc = Y[i]*(8*np.log(2)/(c**3)*(X[i]-b)**2)
dadb = db/a
dadc = dc/a
dbdc = db*dc/Y[i]-2*db*Y[i]/c
var_f = da**2*pcov[0][0] + db**2*pcov[1][1] + dc**2*pcov[2][2] +\
2*(dadb*pcov[0][1] + dadc*pcov[0][2] + dbdc*pcov[1][2])
sigma_f = np.sqrt(abs(var_f))
return sigma_f
def f_fixoff(wn, Amp, wn_center, FWHM):
"""Gaussian function without vertical offset"""
return Amp*sp.exp(-4*sp.log(2)*((wn-wn_center)/FWHM)**2)
def round_sig(x, sig):
return round(x, sig-int(np.floor(np.log10(x)))-1)
def gaus(x,a,x0,sigma):
return a*np.exp(-(x-x0)**2/(2*sigma**2))
def fano(E, E_r,q, gamma, amp,offs):
epsilon = 2.*(E-E_r)/gamma
return offs+amp*(q + epsilon)**2./(epsilon**2.+1.)
def Phasing_TD(data,data_window,E_trans):
phase_corr = np.exp(-1j*data_window[find_index(np.array(data_window),0)]*1e-15*E_trans*spc.e/spc.hbar)
data *= phase_corr
return data
def ImportPadresRun30():
"""
Imports Padres spectrum from Run30 and converts it into eV scale to plot it into Scan31 FD data
"""
padres_spec = [] #padres spectrum of all harmonics(5,7,10)
padres_roi = [] #padres spectrum for all harmonics(5,7,10)
''' Loop over all harmonics '''
ldm_file_path ='//10.5.71.28/FermiServer/Beamtime2/Run_030/rawdata/'
ldm_files = os.listdir(ldm_file_path)
ldm_padres = np.array([]) #raw padres spectrum from ldm files
padres = np.zeros((0, 1000))#padres spectrum
for ldm_file in ldm_files:
ldm_data = h5py.File(ldm_file_path + ldm_file, 'r')
#padres spectrum
ldm_padres = np.array(ldm_data['photon_diagnostics']['Spectrometer']['hor_spectrum'])
padres = np.append(padres, ldm_padres,axis=0)
#padres spectrometer metadata
padres_wavelength = np.array(ldm_data['photon_diagnostics']['Spectrometer']['Wavelength'])
padres_span = np.array(ldm_data['photon_diagnostics']['Spectrometer']['WavelengthSpan'])
padres_pixel2micron = np.array(ldm_data['photon_diagnostics']['Spectrometer']['Pixel2micron'])
padres_lambda = padres_wavelength + (np.arange(1,1001)-500)*padres_pixel2micron*1E-3*padres_span #padres spectrometer calibration
padres_spec.append(padres)
padres_roi.append(padres_lambda)
''' Proper Data windows for 5H '''
padres_low=100
padres_high=310
padres_spec_5H = np.transpose(padres_spec[0])[padres_low:padres_high,::]
padres_spec_5H = np.mean(padres_spec_5H,axis=1)
padres_roi_5H = padres_roi[0][padres_low:padres_high]
padres_roi_5H = spc.h*spc.c*1e9/(padres_roi_5H*spc.e)#
padres_spec_5H *= padres_roi_5H**2
padres_spec_5H = (padres_spec_5H-min(padres_spec_5H))/max(abs(padres_spec_5H-min(padres_spec_5H)))
return padres_roi_5H, padres_spec_5H
def ImportPreanalysedData(root_file_path,run):
file_path = root_file_path + 'scan_{0:03}/'.format(int(run))
h5f = h5py.File(file_path + 'scan_{0:03}.h5'.format(int(run)), 'r')
# sort data by delay in ascending order
sort_inds = np.array(h5f.get('LDM/delay')).argsort()
data = {
'run_numbers': np.array(h5f.get('run_numbers'))[sort_inds],
'LDM': {
'I0': np.array(h5f.get('LDM/I0'))[sort_inds],
's_I0': np.array(h5f.get('LDM/s_I0'))[sort_inds],
'delay': np.array(h5f.get('LDM/delay'))[sort_inds],
's_delay': np.array(h5f.get('LDM/s_delay'))[sort_inds],
'l_seed': np.array(h5f.get('LDM/l_seed'))[sort_inds],
'l_ref': np.array(h5f.get('LDM/l_ref'))[sort_inds],
'i0_fft': np.array(h5f.get('LDM/i0_fft'))[sort_inds]
},
'dev3265': {
'harmonic': np.array(h5f.get('dev3265/harmonic')),
'x0': np.array(h5f.get('dev3265/x0'))[sort_inds],
'y0': np.array(h5f.get('dev3265/y0'))[sort_inds],
'x1': np.array(h5f.get('dev3265/x1'))[sort_inds],
'y1': np.array(h5f.get('dev3265/y1'))[sort_inds],
'x2': np.array(h5f.get('dev3265/x2'))[sort_inds],
'y2': np.array(h5f.get('dev3265/y2'))[sort_inds],
's_x0': np.array(h5f.get('dev3265/s_x0'))[sort_inds],
's_y0': np.array(h5f.get('dev3265/s_y0'))[sort_inds],
's_x1': np.array(h5f.get('dev3265/s_x1'))[sort_inds],
's_y1': np.array(h5f.get('dev3265/s_y1'))[sort_inds],
's_x2': np.array(h5f.get('dev3265/s_x2'))[sort_inds],
's_y2': np.array(h5f.get('dev3265/s_y2'))[sort_inds], },
'dev3269': {
'harmonic': np.array(h5f.get('dev3269/harmonic')),
'x0': np.array(h5f.get('dev3269/x0'))[sort_inds],
'y0': np.array(h5f.get('dev3269/y0'))[sort_inds],
'x1': np.array(h5f.get('dev3269/x1'))[sort_inds],
'y1': np.array(h5f.get('dev3269/y1'))[sort_inds],
'x2': np.array(h5f.get('dev3269/x2'))[sort_inds],
'y2': np.array(h5f.get('dev3269/y2'))[sort_inds],
's_x0': np.array(h5f.get('dev3269/s_x0'))[sort_inds],
's_y0': np.array(h5f.get('dev3269/s_y0'))[sort_inds],
's_x1': np.array(h5f.get('dev3269/s_x1'))[sort_inds],
's_y1': np.array(h5f.get('dev3269/s_y1'))[sort_inds],
's_x2': np.array(h5f.get('dev3269/s_x2'))[sort_inds],
's_y2': np.array(h5f.get('dev3269/s_y2'))[sort_inds], }, }
h5f.close()
return data
| true |
6fce5f57bb9ced1f431fb874865d995c082e23d8 | Python | SURAJNAYA/git-tutodrial- | /input1.py | UTF-8 | 19,090 | 3.5625 | 4 | [] | no_license | # name=input("type your name")
# print ("hello" + name)
# age= input("what is your age ?")
# # print("your age is",age)
# number_first = int(input("enter first number"))
# number_sec = int(input("enter second number"))
# total= number_first + number_sec
# print("totle is" + str(total))
# print(f"totle number {total} ")
# num1=int(input("enter first number "))
# num2=int(input("enter second number"))
# num3=int(input("enter there number"))
# average=nun1+num2+ num3 //3
# print("average is",average )
# num1,num2,num3= input("enter three number").split(",") # seprited by coma ','
# print(f"average is : { (int(num1) + int(num2) + int(num3)) /3}")
# dictionary is nothing key velue pairs
# d1 = {"suraj":{"L":"senvich","B":"megge","D":"fesh"},"mohit":{"L":"pizaa","B":"gobi","D":"Bhindi"},
# "mother":{"L":"eig","B":"fesh","D":"chaken"},"papa":"leadyfinger"}
# d1["lk"]="junkfood"
# print(d1)
# # del d1 ["lk"]
# # print(d1)
# # d1.update({"radhe":"coffe"})
# # print (d1)
# # print (d1.keys())
# # print (d1.items())
# print ( " what is your age ")
# age = int (input ())
# if age < 18:
# print("you can't drive ")
# elif age== 18:
# print("we will thing about it ")
# else:
# print ("You Can Drrive ")
# a=int(input("enter your age"))
# if a>18 and a<100:
# print("YOU CAN DRIVE :)")
# elif a==18:
# print("WE CANNOT DECIDE WETHER YOU ARE ELIGIBLE FOR DRIVING OR NOT")
# elif a<18:
# print("Legeally,YOU ARE NOT AUTHORIZED TO BE A DRIVER")
# else:
# print("Illogical age")
# faulty calculater
# 45*3=55,56+9=77 ,56/6=4
# print ("enter your firts numer")
# num1=int(input())
# print ("enter your second number")
# num2=int(input())
# print("choose your opreation\ n1 adition \ n2 supptraction and n3 multiplication ")
# choice=int(input())
# if num1==56 and num2==9 and choice==1:
# print("The Result is", int(77))
# elif num1==56 and num2==6 and choice==2:
# print("The Reselt is", int(4) )
# elif num1==45 and num2==5 and choice==3:
# print( "The Rseult is", int(555))
# elif choice==1:
# print("Thr sum of the number is", num1+num2)
# elif choice==2:
# print( "The suptraction of the number is", num1/num2)
# else:
# print( "The multiplication is", num1 * num2 )
# list3 = [ ["suraj","piza"],["sonu","buger"],["sonam","magge"]]
# for item,lunch in list3 :
# print(item,";Lunch Food Name is",lunch)
# loop statment
# a=int(input("enter a number "))
# while a<100:
# print(a)
# a=a+1
# print("condition folse")
# The Breck Statment
# a=int(input("enter a number "))
# while a<100:
# if (a==50):
# break
# print(a)
# a=a+1
# print("condition folse")
# while(True):
# ab=int(input("enter a number \n"))
# if ab>100:
# print("congrtulation you are enter grater then 100\n")
# break
# else:
# print("try agane\n")
# continue
# n=18
# number_of_guesses=1
# print("Number of guesses is limited to only 9 times: ")
# while (number_of_guesses<=9):
# guess_number = int(input("Guess the number :\n"))
# if guess_number<18:
# print("you enter less number please input greater number.\n")
# elif guess_number>18:
# print("you enter greater number please input smaller number.\n ")
# else:
# print("you won\n")
# print(number_of_guesses,"no.of guesses he took to finish.")
# break
# print(9-number_of_guesses,"no. of guesses left")
# number_of_guesses = number_of_guesses + 1
# if(number_of_guesses>9):
# print("Game Over")
# Operators In Pythons
# Arithmetic Operators
# Assignment Operators
# Comparison Operators
# Logical Operators
# Identity Operators
# Membership Operators
# Bitwise Operators
# Arithmetic Operators
# print("5 + 6 is ", 5+6)
# print("5 - 6 is ", 5-6)
# print("5 * 6 is ", 5*6)
# print("5 / 6 is ", 5/6)
# print("5 ** 3 is ", 5**3)
# print("5 % 5 is ", 5%5)
# print("15 // 6 is ", 15//6)
# Assignment Operators
# print("Assignment Operators")
# x = 5
# print(x)
# x %=7 # x = x%7
# psrint(x)
# Comparison Operators
# from typing_extensions import Concatenate
# i = 5
# Logical Operators
# a = True
# b = False
# Identity Operators
# print(5 is not 5)
# Membership Operators
# list = [3, 3,2, 2,39, 33, 35,32]
# print(324 not in list)
# Bitwise Operators
# 0 - 00
# 1 - 01
# 2 - 10
# 3 - 11
# 1print(0 & 2)
# print(0 | 3)
# a=int(input("enter number a\n"))
# b=int(input("enter number b \n"))
# print("B A se bada he bhai") if a<b else print("A B se bada hei bhai")
# def function1 (a,b):
# """The Function whicle will calculate sum of two number(this is a docstringty,hjmh`) """
# print(" Sum Number is ",a+b)
# function1(1,9)
# print(function1.__doc__)
# def function2 (a,b):
# """The Function whicle will calculate average of two number"""
# avrage= (a+b)/2
# print(avrage)
# return avrage
# v=function2(12,6 )
# print(v)
# print(function2.__doc__)
# try except handling
# print("enter a num1")
# num1=input()
# print("enter a num2")
# num2=input()
# try:
# print("sum of two number is ",
# int(num1)+int(num2))
# except Exception as e:
# print (e)
# print("This line is very importent")
# Basde on File handling
"""
# "r":- Open File is Reading Mode
# "w":-m Open File is Write Mode
# "x":- Creates File if Not Exists
# "a":- Add More Contant to a File
# "t":-Open File For text Mode
# "b":-Open File For Binary Mode
# "+":-Open File For Read and Wride Mode
"""
# f= open("F:/nayak/exempale.py ","r")
# Content = f.read()#line by line print
# for line in f:
# print(line)
# f.close()
# f= open("F:/nayak/exempale.py ","r")
# contant=f.readline() # only file print
# print(contant)
# f.close()
# f=open("F:/nayak/exempale.py","r")
# contant=(f.readline())# only one Line print in this stat mant
# print(contant)
# f.close()
# f=open("F:/nayak/exempale.py","r")
# contant=(f.readlines())# All Line print in row line
# print(contant)
# f.close()
# f = open("surajn.txt","a")
# a=f.write("suraj is good boy and locking is outstanding \n")
# print(a)
# f.close()
# Handle read and write both
# f = open("suraj.txt","r+")
# print(f.read())
# f.write("thenk you ")
# f.close()
# print star pattern
# print("pattern printing")
# n=int(input("enter a number in star partan "))
# boolean=input("true (1) or false(0)")
# if boolean=="1":
# for i in range(1,n+1):
# print("*" " "*i)
# if boolean=="0":
# for i in range(n,0,-1):
# print("*" " "*i)
# globle variable
# l=15 # global variable
# def function1(n):
# # l=5 #Local
# m=10 #Local
# global l
# l=l+50
# print(l,m)
# print(n,"suraj")
# function1("my name is")
# x = 89
# def harry():
# x = 20
# def rohan():
# global x
# x = 88
# print("before calling rohan()", x)
# rohan()
# print("after calling rohan()", x)
# harry()
# print(x)
# x = 55
# def suraj():
# x = 15
# def rohan():
# global x
# x = 90
# print("suraj nayak",x)
# rohan()
# print("nayak suraj",x)
# suraj()
# print(x)
# recurction function in factorial
# def recurctive_factorial(n):
# if n==1:
# return 1
# else:
# return n * recurctive_factorial(n-1)
# number=int(input("Einrt The Number"))
# print("Factorial use iterative Mathod", number)
# Helth Managemant system
# import datetime
# def gettime():
# return datetime.datetime.now()
# def take(k):
# if k==1:
# c=int(input("enter 1 for excersise and 2 for food"))
# if(c==1):
# value=input("type here\n")
# with open("harry-ex.txt","a") as op:
# op.write(str([str(gettime())])+": "+value+"\n")
# print("successfully written")
# elif(c==2):
# value = input("type here\n")
# with open("harry-food.txt", "a") as op:
# op.write(str([str(gettime())]) + ": " + value + "\n")
# print("successfully written")
# elif(k==2):
# c = int(input("enter 1 for excersise and 2 for food"))
# if (c == 1):
# value = input("type here\n")
# with open("rohan-ex.txt", "a") as op:
# op.write(str([str(gettime())]) + ": " + value + "\n")
# print("successfully written")
# elif (c == 2):
# value = input("type here\n")
# with open("rohan-food.txt", "a") as op:
# op.write(str([str(gettime())]) + ": " + value + "\n")
# print("successfully written")
# elif(k==3):
# c = int(input("enter 1 for excersise and 2 for food"))
# if (c == 1):
# value = input("type here\n")
# with open("hammad-ex.txt", "a") as op:
# op.write(str([str(gettime())]) + ": " + value + "\n")
# print("successfully written")
# elif (c == 2):
# value = input("type here\n")
# with open("hammad-food.txt", "a") as op:
# op.write(str([str(gettime())]) + ": " + value + "\n")
# print("successfully written")
# else:
# print("plz enter valid input (1(harry),2(rohan),3(hammad)")
# def retrieve(k):
# if k==1:
# c=int(input("enter 1 for excersise and 2 for food"))
# if(c==1):
# with open("harry-ex.txt") as op:
# for i in op:
# print(i,end="")
# elif(c==2):
# with open("harry-food.txt") as op:
# for i in op:
# print(i, end="")
# elif(k==2):
# c = int(input("enter 1 for excersise and 2 for food"))
# if (c == 1):
# with open("rohan-ex.txt") as op:
# for i in op:
# print(i, end="")
# elif (c == 2):
# with open("rohan-food.txt") as op:
# for i in op:
# print(i, end="")
# elif(k==3):
# c = int(input("enter 1 for excersise and 2 for food"))
# if (c == 1):
# with open("hammad-ex.txt") as op:
# for i in op:
# print(i, end="")
# elif (c == 2):
# with open("hammad-food.txt") as op:
# for i in op:
# print(i, end="")
# else:
# print("plz enter valid input (harry,rohan,hammad)")
# print("health management system: ")
# a=int(input("press 1 for lock the value and 2 for retrieve "))
# if a==1:
# b = int(input("press 1 for harry 2 for rohan 3 for hammad "))
# take(b)
# else:
# b = int(input("press 1 for harry 2 for rohan 3 for hammad "))
# retrieve(b)
# import datetime
# def gettime():
# return datetime.datetime.now()
# def take(k):
# if k==1:
# c = int(input("Enter 1 for exersise and 2 for food"))
# if (c==1):
# value=input("type her\n")
# with open ("suraj_ex.txt","a") as op:
# op.write(str([str(gettime())])+":"+ value +"\n")
# print(" successfully writen")
# elif (c==2):
# value=input("type her")
# with open ("suraj_food.txt","a") as op:
# op.write (str([str (gettime())]) + ":"+ value + "\n")
# print("successfully writen")
# elif k==2:
# c = int(input("Enter 1 for exersise and 2 for food"))
# if (c==1):
# value=input("type her\n")
# with open ("munni_ex.txt","a") as op:
# op.write(str([str(gettime())])+":"+ value +"\n")
# print(" successfully writen")
# elif (c==2):
# value=input("type her")
# with open ("munni_food.txt","a") as op:
# op.write (str([str (gettime())]) + ":"+ value + "\n")
# print("successfully writen")
# else:
# print("Plz enter veled input(suraj,munni)")
# def retrieve(k):
# if k==1:
# c = int(input("Enter 1 for exersise and 2 for food"))
# if (c==1):
# with open("suraj_ex.txt") as op:
# for i in op:
# print(i,end=" ")
# elif (c==2):
# with open("suraj_food.txt") as op:
# for i in op:
# print(i,end =" ")
# if k==2:
# c = int(input("Enter 1 for exersise and 2 for food"))
# if (c==1):
# with open("munni_ex.txt") as op:
# for i in op:
# print(i,end="")
# elif (c==2):
# with open("munni_food.txt") as op:
# for i in op:
# print(i,end ="")
# else:
# print("plze valed input (suraj, munni)")
# print("helth managemant system")
# a=int(input("press 1 for lock the value and 2 for retrieve "))
# if a ==1:
# b=int(input("Enter press 1 for suraj and 2 for munni"))
# take(b)
# else:
# b = int(input("press 1 for suraj 2 for munni "))
# retrieve(b)
################################Built In Modules##################################################################
# import random
# random_number= random.randint(0,10)
# print(random_number)
# list = ["SUB","sub","UTV","UTV Action","Star Gold"]
# choicee=random.choice(list)
# print(choicee)
# Fibonacci numbers module
# series is Forved order
# def fib (n):
# a = 0
# b = 1
# print(a)
# print(b)
# for i in range (2,n):
# c= a+ b
# a = b
# b = c
# print (b)
# a=int(input("enter a fibo number "))
# fib(a)
# Program to print Fibonacci
# series in reverse order
# def fibreverse(n):
# a=[0]*n
# a[0]=0
# a[1]=1
# for i in range(2,n):
# a[i] = a[i-2]+a[i-1]
# for i in range(n-1, -1, -1):
# print(a[i] ,end= " , ")
# n=int(input("Ednter A Fibonacci Number"))
# fibreverse(n)
######################## *args / **kwargs in python###########################################################
# def funargs(*surj):
# for item in suraj:
# print(item)
# Grocery=["Dio","Solt","Asafoetida"]
# funargs(*Grocery)
# def fun(*suraj):
# print(n)
# for item in suraj:
# print(item)
# n="This is a Monthily Grocery Items "
# grocery_Items=["Rice","Cheni","Daal","Fennel","Cumin","red Chilli"]
# fun(*grocery_Items)
########################################### use of import ##############################################
# # import exempale
# exempale.myline
# import sys
# print(sys.path)
# import exempale
# print(exempale.add(5,6))
# ************************************** map function ******************************************************
# num = [2,6,5,48,55,25,3,62]
# square = list(map(lambda x: x*x, num))
# print (square)
# def square(a):
# return a*a
# def cube(a):
# return a*a*a
# fun=[square,cube]
# num=1,2,3,4,5,6,7,89,9
# for i in range (5):
# val= list(map(lambda x:x(i),fun))
# print(val)
#************************************ Filter *****************************************************************
# list_1=[1,2,3,4,5,6,7,8,9,10]
# def is_greater_5(num):
# return num>5
# gr_then_5 = list (filter(is_greater_5,list_1))
# print(gr_then_5)
#------------------------------------REDUCE----------------------------------------------------------------------
# from functools import reduce
# list1 = 1,2,3,4,5,6,7,8,9
# num=reduce(lambda x,y:x+y,list1)
# print(num)
#--------------------------------------------------------------------------------------------------------
# Snake water gun
import random
lst = ['s','w','g']
chance = 10
no_of_chance = 0
computer_point = 0
human_point = 0
print(" \t \t \t \t Snake,Water,Gun Game\n \n")
print("s for snake \nw for water \ng for gun \n")
# making the game in while
while no_of_chance < chance:
_input = input('Snake,Water,Gun:')
_random = random.choice(lst)
if _input == _random:
print("Tie Both 0 point to each \n ")
# if user enter s
elif _input == "s" and _random == "g":
computer_point = computer_point + 1
print(f"your guess {_input} and computer guess is {_random} \n")
print("computer wins 1 point \n")
print(f"computer_point is {computer_point} and your point is {human_point} \n ")
elif _input == "s" and _random == "w":
human_point = human_point + 1
print(f"your guess {_input} and computer guess is {_random} \n")
print("Human wins 1 point \n")
print(f"computer_point is {computer_point} and your point is {human_point} \n")
# if user enter w
elif _input == "w" and _random == "s":
computer_point = computer_point + 1
print(f"your guess {_input} and computer guess is {_random} \n")
print("computer wins 1 point \n")
print(f"computer_point is {computer_point} and your point is {human_point} \n ")
elif _input == "w" and _random == "g":
human_point = human_point + 1
print(f"your guess {_input} and computer guess is {_random} \n")
print("Human wins 1 point \n")
print(f"computer_point is {computer_point} and your point is {human_point} \n")
# if user enter g
elif _input == "g" and _random == "s":
human_point = human_point + 1
print(f"your guess {_input} and computer guess is {_random} \n")
print("Human wins 1 point \n")
print(f"computer_point is {computer_point} and your point is {human_point} \n")
elif _input == "g" and _random == "w":
computer_point = computer_point + 1
print(f"your guess {_input} and computer guess is {_random} \n")
print("computer wins 1 point \n")
print(f"computer_point is {computer_point} and your point is {human_point} \n ")
else:
print("you have input wrong \n")
no_of_chance = no_of_chance + 1
print(f"{chance - no_of_chance} is left out of {chance} \n")
print("Game over")
if computer_point==human_point:
print("Tie")
elif computer_point > human_point:
print("Computer wins and you loose")
else:
print("you win and computer loose")
print(f"your point is {human_point} and computer point is {computer_point}")
#
# Snake Water Gun Game in Python
# The snake drinks the water, the gun shoots the snake, and gun has no effect on water.
#
| true |
709d55da3f63324cb2b6b460869bc5cfd35e75f6 | Python | ghosthamlet/abstraction-and-reasoning-challenge | /src/operator/transformer/reducer/fill_pattern/periodicity_row_col.py | UTF-8 | 6,667 | 2.96875 | 3 | [
"MIT"
] | permissive | import numpy as np
import numba
from src.data import Problem, Case, Matter
from src.operator.solver.common.shape import is_same
@numba.jit('i8(i8[:, :], i8)', nopython=True)
def find_periodicity_row(x_arr, background):
"""
:param x_arr: np.array(int)
:param background: int
:return: int, minimum period
"""
for p in range(1, x_arr.shape[0]):
res = True
i = 0
while i < p and res:
for j in range(x_arr.shape[1]):
colors = np.unique(x_arr[i::p, j])
if len(colors) >= 3:
res = False
break
elif colors.shape[0] == 2 and background not in list(colors):
res = False
break
i += 1
if res:
return p
return x_arr.shape[0]
@numba.jit('i8[:, :](i8[:, :], i8, i8)', nopython=True)
def fill_periodicity_row(x_arr, p, background):
"""
:param x_arr: np.array(int)
:param p: period
:param background: int
:return: np.array(int), filled array
"""
# assertion
assert x_arr.shape[0] > 0 and x_arr.shape[1] > 0
# trivial case
if p == x_arr.shape[0]:
return x_arr.copy()
y_arr = x_arr.copy()
for i in range(p):
for j in range(x_arr.shape[1]):
v = background
for a in x_arr[i::p, j]:
if a != background:
v = a
y_arr[i::p, j] = v
return y_arr
class AutoFillRowColPeriodicity:
def __init__(self):
pass
@classmethod
def find_periodicity_col(cls, x_arr, background=0):
"""
:param x_arr: np.array(int)
:param background: int
:return: int, minimum period
"""
return find_periodicity_row(x_arr.transpose(), background)
@classmethod
def auto_fill_row(cls, x_arr, background=0):
"""
:param x_arr: np.array(int), must be >= 0 otherwise returns x_arr.copy()
:param background: int
:return: np.array(int), filled array in row_wise
"""
p_row = find_periodicity_row(x_arr, background)
return fill_periodicity_row(x_arr, p_row, background)
@classmethod
def auto_fill_col(cls, x_arr, background=0):
"""
:param x_arr: np.array(int), must be >= 0 otherwise returns x_arr.copy()
:param background: int
:return: np.array(int), filled array in col_wise
"""
return cls.auto_fill_row(x_arr.transpose(), background).transpose()
@classmethod
def auto_fill_row_col(cls, x_arr, background=0):
"""
:param x_arr: np.array(int), must be >= 0 otherwise returns x_arr.copy()
:param background: int
:return: np.array(int), filled array in row_wise and col_wise, row first
"""
y_arr = x_arr.copy()
iter_times = 0
while iter_times < 10000:
z_arr, y_arr = y_arr, cls.auto_fill_row(y_arr, background)
z_arr, y_arr = y_arr, cls.auto_fill_col(y_arr, background)
if np.abs(z_arr - y_arr).sum() == 0:
return z_arr
iter_times += 1
assert iter_times == -1 # break by assertion error
return None
@classmethod
def auto_fill_row_col_background(cls, x_arr):
cost = 10000
background_res = 0
for background in range(10):
z_arr = cls.auto_fill_row_col(x_arr, background)
cost_temp = find_periodicity_row(z_arr, background) * cls.find_periodicity_col(z_arr, background)
if cost_temp < cost:
cost = cost_temp
background_res = background
return cls.auto_fill_row_col(x_arr, background_res)
@classmethod
def case_row(cls, c: Case) -> Case:
new_case = c.copy()
new_values = cls.auto_fill_row(c.repr_values(), c.background_color)
new_case.matter_list = [Matter(new_values, background_color=c.background_color, new=True)]
return new_case
@classmethod
def case_col(cls, c: Case) -> Case:
new_case = c.copy()
new_values = cls.auto_fill_col(c.repr_values(), c.background_color)
new_case.matter_list = [Matter(new_values, background_color=c.background_color, new=True)]
return new_case
@classmethod
def case_row_col(cls, c: Case) -> Case:
new_case = c.copy()
new_values = cls.auto_fill_row_col(c.repr_values(), c.background_color)
new_case.matter_list = [Matter(new_values, background_color=c.background_color, new=True)]
return new_case
@classmethod
def problem(cls, p: Problem) -> Problem:
assert is_same(p)
if p.is_periodic_row and p.is_periodic_col:
q: Problem = p.copy()
q.train_x_list = [cls.case_row_col(c) for c in p.train_x_list]
q.test_x_list = [cls.case_row_col(c) for c in p.test_x_list]
elif p.is_periodic_row:
q: Problem = p.copy()
q.train_x_list = [cls.case_row(c) for c in p.train_x_list]
q.test_x_list = [cls.case_row(c) for c in p.test_x_list]
elif p.is_periodic_col:
q: Problem = p.copy()
q.train_x_list = [cls.case_col(c) for c in p.train_x_list]
q.test_x_list = [cls.case_col(c) for c in p.test_x_list]
else:
raise AssertionError
return q
if __name__ == "__main__":
x = np.ones((5, 3), dtype=np.int)
print(find_periodicity_row(x, 0))
x[1, :] = 2
print(find_periodicity_row(x, 0))
x[3, :] = 2
print(find_periodicity_row(x, 0))
print(AutoFillRowColPeriodicity.find_periodicity_col(x))
x = np.zeros((5, 3), dtype=np.int)
print(find_periodicity_row(x, 0))
print(find_periodicity_row(x, -1))
x[1, :] = 2
print(find_periodicity_row(x, 0))
print(find_periodicity_row(x, -1))
x[3, :] = 2
print(find_periodicity_row(x, 0))
print(find_periodicity_row(x, -1))
print(AutoFillRowColPeriodicity.find_periodicity_col(x))
print(AutoFillRowColPeriodicity.find_periodicity_col(x, -1))
x = np.zeros((5, 3), dtype=np.int)
x[1, :] = 2
print(fill_periodicity_row(x, 2, 0))
print(fill_periodicity_row(x, 3, 0))
x = np.zeros((5, 3), dtype=np.int)
x[:2, :2] = 1
x[1, 1] = 2
print(find_periodicity_row(x, 0))
print(fill_periodicity_row(x, 2, 0))
print(AutoFillRowColPeriodicity.auto_fill_row(x))
print(AutoFillRowColPeriodicity.auto_fill_row_col(x))
x = np.ones((5, 3), dtype=np.int)
x[1, :] = 3
x[3:, :] = 5
print(x)
print(AutoFillRowColPeriodicity.auto_fill_row_col_background(x))
| true |
d48bc5947439c12a819ff73ff614de287b766fe8 | Python | DaehanKim/projectEuler | /29.py | UTF-8 | 1,103 | 3.390625 | 3 | [
"MIT"
] | permissive | import math
from tqdm import tqdm
from collections import Counter
def is_prime(num):
if num == 2: return True
for i in range(2, math.ceil(math.sqrt(num))+1):
if num % i == 0 : return False
return True
def get_largest_prime_factor(num):
if is_prime(num) : return int(num)
for i in range(math.ceil(math.sqrt(num)), 1, -1):
if num % i == 0 and is_prime(i): return i
def prime_fact(num):
factors = []
result = num
while(True):
fact = get_largest_prime_factor(result)
factors.append(fact)
result /= fact
if int(result) == 1 : break
return factors
def mult(factor_dict, other):
return {k : v*other for k,v in factor_dict.items()}
def to_string(factor_dict):
factor_list = sorted(list(factor_dict.items()), key=lambda x:x[0])
return "*".join([f"{k}^{v}" for k,v in factor_list])
num_list = []
# cnt = 0
for a in range(2,101):
for b in range(2,101):
fact_list = prime_fact(a)
fact_dict = Counter(fact_list)
a_powers_b = mult(fact_dict, b)
num_list.append(to_string(a_powers_b))
# cnt += 1
# if cnt > 100 :
# print(num_list)
# exit()
print(len(set(num_list))) | true |
c9627ada6e77a4da27f064659cfb69cd3b158c50 | Python | ferologics/twitter-bot-python-ferologics | /section_3/word_frequency.py | UTF-8 | 811 | 3.546875 | 4 | [] | no_license | import sys
import re
def histogram(source_text):
file = open(source_text)
string = file.read()
compiled_rgx = re.compile(r"[^a-zA-Z0-9]*")
list = re.split(compiled_rgx, string.lower())
histogram = {}
for word in list:
if word in histogram:
histogram[word] += 1
else:
histogram[word] = 1
return histogram
def unique_words(histogram):
uniques = 0
for key in histogram:
uniques += 1
return uniques
def frequency(histogram, word):
return histogram.get(word, 0)
if __name__ == "__main__":
path = str(sys.argv[1])
hist = histogram(path)
uniques = unique_words(hist)
frequency_of_word_are = frequency(hist, "are")
print(path)
print(hist)
print(uniques)
print(frequency_of_word_are)
| true |
bdde447852c575313d164f408f37f21d551afa0a | Python | seagullQ77/nfd-autotest | /codewars/high.py | UTF-8 | 462 | 3.1875 | 3 | [] | no_license | #Highest Scoring Word
def high(x):
listx= x.split()
sumhigh = 0
for i in listx:
sum=0
for j in i:
sum += ord(j.lower())-96
if sum>sumhigh:
sumhigh = sum
highstr = i
return highstr
highstr=high('take me to semynak')
print(highstr)
#, 'taxi')
#test.assert_equals(high('what time are we climbing up the volcano'), 'volcano')
#test.assert_equals(high('take me to semynak'), 'semynak')
| true |
ba5dbc3edf68473e453cadc5d30f54a50cb0f1fb | Python | angvp/ursine | /ursine/parsing.py | UTF-8 | 4,185 | 3.171875 | 3 | [
"Apache-2.0"
] | permissive | '''Regex based parsing for sip uris.'''
import re
import multidict
# optionally extract either a quoted or unquoted
# contact name and extract the rest discarding the <>
# brackets if present
contact_re = re.compile(r'("(?P<quoted>[^"]+)" '
r'|(?P<unquoted>[^\<"]+) )?'
r'\<(?P<the_rest>.*)\>\Z')
# extract a scheme, discard the : and extract the rest
scheme_re = re.compile(r'(?P<scheme>[^:]+):(?P<the_rest>.*)')
# optionally extract a user part (either user
# or user:pass) and discard the @ symbol
user_part_re = re.compile(r'(?P<user_part>[^:@]+(:[^@:]+)?)@(?P<the_rest>.*)')
# extract a host component that may be [...]
# delimited in order to support ipv6 hosts
host_re = re.compile(r'(?P<host>('
r'\[[^\]]+])|([^:;?&]+)'
r')(?P<the_rest>.*)')
# optionally discard a : and extract a port number
port_re = re.compile(r':(?P<port>[^;?]*)(?P<the_rest>.*)')
# optionally discard a ; and extract a single key=val pair
param_re = re.compile(r';(?P<key>[^=]+)=(?P<val>[^;?]*)(?P<the_rest>.*)')
# optionally extract a key=val pair
base_header_re = r'(?P<key>[^=]+)=(?P<val>[^&]*)(?P<the_rest>.*)'
# match a ? then a key=val pair - only first header starts with ?
first_header_re = re.compile(rf'\?{base_header_re}')
# match a & then a key=val pair - matches (n>1)th headers
nth_header_re = re.compile(rf'&{base_header_re}')
def parse_contact(uri):
'''Attempt a contact match, and remove the
proper sip uri from a <> pair if present
'''
match = contact_re.match(uri)
if not match:
return None, uri
groups = match.groupdict()
contact = groups.get('quoted')
if contact is None:
contact = groups.get('unquoted')
return contact, groups['the_rest']
def parse_scheme(uri):
'''Require a scheme match.'''
match = scheme_re.match(uri)
if match is None:
raise ValueError('no scheme specified')
groups = match.groupdict()
scheme = groups['scheme'].lower()
if scheme not in ('sip', 'sips'):
raise ValueError(f'invalid scheme {scheme}')
return scheme, groups['the_rest']
def parse_user_part(uri):
'''Attempt to match user@ or user:pass@.'''
match = user_part_re.match(uri)
if match is None:
return None, None, uri
groups = match.groupdict()
subparts = groups['user_part'].split(':')
if len(subparts) == 2:
user, password = subparts
else:
user, password = subparts[0], None
return user, password, groups['the_rest']
def parse_host(uri):
'''Require a host match.
The host can either be anything ending
with the EOL, a ; or a :, and optionally
can be enclosed in [...] to allow
containing : characters.
'''
match = host_re.match(uri)
if match is None:
raise ValueError('host must be specified')
groups = match.groupdict()
return groups['host'], groups['the_rest']
def parse_port(uri):
'''Attempt to match a : and port number.'''
match = port_re.match(uri)
if match is None:
return None, uri
groups = match.groupdict()
try:
port = int(groups['port'])
except ValueError:
raise ValueError('port must be an integer')
return port, groups['the_rest']
def parse_parameters(uri):
'''Attempt to match many ;key=val pairs.'''
the_rest = uri
params = {}
match = param_re.match(the_rest)
while match:
groups = match.groupdict()
if params.get(groups['key']):
raise ValueError('parameters must be unique')
params[groups['key']] = groups['val']
the_rest = groups['the_rest']
match = param_re.match(the_rest)
return params, the_rest
def parse_headers(uri):
'''Attempt to match a ?key=val pair, then
attempt to match many &key=val pairs.
'''
the_rest = uri
headers = multidict.MultiDict()
match = first_header_re.match(the_rest)
while match:
groups = match.groupdict()
headers.add(groups['key'], groups['val'])
the_rest = groups['the_rest']
match = nth_header_re.match(the_rest)
return headers, the_rest
| true |
afeefd3cc6f8598379f13e29ba5bf1ae91ad26e4 | Python | israkir/sentiment-analyzer | /src/sentiment_analyzer.py | UTF-8 | 6,774 | 3.328125 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------------------------------------------------------
#
# Program Name : sentiment_analyzer.py
# Authors : W.B.Lee, H.C.Lee, Y.K.Wang, T.T.Mutlugun, H.C.Kirmizi
# Date : December 30, 2012
# Description : Analyze
# Running command : python sentiment_analyzer.py [in-file] [out-file] [pos-lexicons-file] [neg-lexicons-file]
# Python version : Python 2.7.1
#
# --------------------------------------------------------------------------------------------------------------------
import sys
import codecs
def train_sentiment_lexicons(pos_lexicons_filename, neg_lexicons_filename):
'''
Assigns the sentiment polarity for each lexicons.
Returns positive lexicons and negative lexicons in dictionary format.
'''
pos_file = codecs.open(pos_lexicons_filename, 'r', 'utf-8')
neg_file = codecs.open(neg_lexicons_filename, 'r', 'utf-8')
pos_lexicons = []
for i in range(9365):
s = pos_file.readline().strip()
pos_lexicons.append(s)
neg_lexicons = []
for i in range(11230):
s = neg_file.readline().strip()
neg_lexicons.append(s)
pos_file.close()
neg_file.close()
return pos_lexicons, neg_lexicons
def filter_punctuation(text):
punctuations = u"。「」.・,﹁﹂“”、·《》—~;:?——!!\"%$'&)(+*-/.;:=<?>@[]\\_^`{}|~\#"
translate_table = dict((ord(char), None) for char in punctuations)
return text.translate(translate_table)
def analyze_sentence_sentiment(input_filename, output_filename, pos_lexicons, neg_lexicons, probability_filename):
'''
Analyzes the input file in given format and writes the
analysis results to an output file.
Basic algorithm:
----------------
Initialize a score for each clause.
For each word segment in clause:
If word segment is a positive lexicon, then score++
If word segment is a negative lexicon, then score--
If score > 0, then clause polarity is 1.
If score < 0, then clause polarity is -1,
If score = 0, then clause polarity is 0.
'''
input_file = codecs.open(input_filename, 'r', 'utf-8')
output_file = codecs.open(output_filename, 'w', 'utf-8')
total_sentences = input_file.readline().strip()
# retrieve the probability model
tem_dict, con_dict, com_dict, exp_dict = retrieve_probability_model(probability_filename)
p1 = ''
p2 = ''
for i in range(3 * int(total_sentences)):
line = input_file.readline().strip('\n')
line = filter_punctuation(line)
# write the score for whole sentences
if (i % 3) == 2:
p3 = getAllPolarity(p1, p2, line, tem_dict, con_dict, com_dict, exp_dict)
output_file.write(unicode(p3, 'utf-8') + u'\n')
# analyze each clause in the sentence
else:
score = 0
token = ''
for word in line.split():
if word in pos_lexicons:
#print 'pos found: %s' % word
score += 1
elif word in neg_lexicons:
#print 'neg found: %s' % word
score -= 1
if score > 0:
output_file.write(u'1\n')
token = '+'
elif score < 0:
output_file.write(u'-1\n')
token = '-'
else:
output_file.write(u'0\n')
token = 'x'
if (i % 3) == 0:
p1 = token
elif (i % 3) == 1:
p2 = token
input_file.close()
output_file.close()
def retrieve_probability_model(probability_filename):
prob_file = codecs.open(probability_filename, 'r', 'utf8')
tem = {}
con = {}
com = {}
exp = {}
if prob_file.readline().strip() == "Temporal":
for i in range(27):
polarity = prob_file.readline().strip();
probability = prob_file.readline().strip();
tem[polarity] = probability;
#print 'tem['+polarity+']:'+str(probability)
if prob_file.readline().strip() == "Contingency":
for i in range(27):
polarity = prob_file.readline().strip();
probability = prob_file.readline().strip();
con[polarity] = probability;
#print 'con['+polarity+']:'+str(probability)
if prob_file.readline().strip() == "Comparison":
for i in range(27):
polarity = prob_file.readline().strip();
probability = prob_file.readline().strip();
com[polarity] = probability;
#print 'com['+polarity+']:'+str(probability)
if prob_file.readline().strip() == "Expansion":
for i in range(27):
polarity = prob_file.readline().strip();
probability = prob_file.readline().strip();
exp[polarity] = probability;
#print 'exp['+polarity+']:'+str(probability)
prob_file.close()
return tem, con, com, exp
def getAllPolarity(p1, p2, relation, tem_dict, con_dict, com_dict, exp_dict):
relArray = {}
if relation == "Temporal":
relArray = tem_dict
elif relation == "Contingency":
relArray = con_dict
elif relation == "Comparison":
relArray = com_dict
elif relation == "Expansion":
relArray = exp_dict
polarArray = ['+', 'x', '-']
rToken = '+'
probValue = 0
for p3 in polarArray:
polarity = p1+p2+p3
if relArray[polarity] > probValue:
probValue = relArray[polarity]
rToken = p3
if rToken == "+":
return "1"
elif rToken == "x":
return "0"
elif rToken == "-":
return "-1"
def main():
'''
Main procedure drives the whole analysis process.
'''
input_filepath = sys.argv[1]
output_filepath = sys.argv[2]
positive_lexicons_filepath = sys.argv[3]
negative_lexicons_filepath = sys.argv[4]
probability_filepath = sys.argv[5]
print 'Training positive and negative sentiment lexicons...'
pos_lexicons, neg_lexicons = train_sentiment_lexicons(positive_lexicons_filepath, negative_lexicons_filepath)
print 'Analyzing sentence sentiments from the input file...'
analyze_sentence_sentiment(input_filepath, output_filepath, pos_lexicons, neg_lexicons, probability_filepath)
if __name__ == '__main__':
main()
| true |
71f58ae469b897c3a90eafed0b81933588e7e148 | Python | jercamadalina/python-codewars-exercises | /8kyu/hello-name-or-world.py | UTF-8 | 976 | 4.40625 | 4 | [] | no_license | def hello(name=""):
return "Hello, World!" if name == "" else "Hello, {}!".format(name.capitalize())
tests = (
("John", "Hello, John!"),
("aLIce", "Hello, Alice!"),
("", "Hello, World!"),
)
for inp, exp in tests:
print(hello(inp), exp)
print(hello(), "Hello, World!")
'''
# Details
Define a method hello that returns "Hello, Name!" to a given name, or says Hello, World! if name is
not given (or passed as an empty String).
Assuming that name is a String and it checks for user typos to return a name with a first capital
letter (Xxxx).
Examples:
hello "john" => "Hello, John!"
hello "aliCE" => "Hello, Alice!"
hello => "Hello, World!" # name not given
hello '' => "Hello, World!" # name is an empty String
# Exemplu 1
def hello(name=''):
return f"Hello, {name.title() or 'World'}!"
def hello(name=""):
return f"Hello, {name.capitalize() if name else 'World'}!"
'''
| true |
b7d1482e6c6e0bd0c7f2103e0e94a6a11bd3f5b0 | Python | miskamvedebel/miskamvedebel | /HSE/lines_other.py | UTF-8 | 758 | 3.296875 | 3 | [] | no_license | def lines(a):
deleted = 0
counter = 1
i = 0
while i < len(a)-2:
j = i + 1
while j <= len(a)-1 and a[i] == a[j] :
j += 1
counter += 1
if counter >= 3:
indexes = list(range(i,j))
a[:] = [a[k] for k in range(len(a)) if k not in indexes]
deleted += len(indexes)
i = 0
counter = 1
else:
i += 1
counter = 1
return deleted
# some test code
if __name__ == "__main__":
test_a = [2, 2, 1, 1, 1, 2, 1]
# should print 6
print(lines(test_a))
test_a = [0, 0, 0, 0, 0]
# should print 5
print(lines(test_a))
test_a = [2, 3, 1, 4]
# should print 0
print(lines(test_a))
| true |
b2461333398e3a11683aaa13544765337a35ca6a | Python | raajeshlr/Python-Stuffs | /additional basic programs/power of 2.py | UTF-8 | 192 | 3.546875 | 4 | [] | no_license | nterms = int(input("enter the count"))
result = list(filter(lambda x : 2**x , range(nterms+1)))
for i in range(0,nterms+1):
print("2 raised to the power {} is {}".format(i,result[i]))
| true |
e2298e97cadd334c00a3d2dc076e7fbaab49c9a8 | Python | sangeethapl/count | /search.py | UTF-8 | 215 | 2.84375 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
import re
count=0
url=input()
search=input()
r=requests.get(url)
bs=BeautifulSoup(r.text,'html.parser')
b=bs.get_text()
l=b.lower()
s=re.findall(search,l)
print(len(s))
| true |
6e566876e9120b56a7c3bee79ab21f2d35c24859 | Python | ylliu/send-converted-contents-to-cloud-note | /test/unittest/test_content_extractor.py | UTF-8 | 676 | 2.9375 | 3 | [] | no_license | import unittest
from app.ContentExtractor import ContentExtractor
class ContentExtractorTest(unittest.TestCase):
def test_should_extract_content_from_xunfei_converted_result(self):
content_expected = "大家好,我是某某某,今天由我跟大家"
json_convert_result = '[{\"bg\":\"610\",\"ed\":\"7580\",\"onebest\":\"大家好,\",\"speaker\":\"0\"},' \
'{\"bg\":\"7580\",\"ed\":\"15400\",\"onebest\":\"我是某某某,今天由我跟大家\",\"speaker\":\"0\"}]'
self.content_extractor = ContentExtractor(json_convert_result)
self.assertEqual(content_expected, self.content_extractor.extract())
| true |
6a43d1a29bdd07af278883e40f2f692218fcb11f | Python | python-ops-org/python-ops | /aws/compute/lambda+/ec2/v.0.1/instance-debug-2.py | UTF-8 | 1,756 | 2.8125 | 3 | [] | no_license | #python in-2.py -a lambda_start -r us-east-1 -s started
import boto3
import argparse
def ec2_control():
parser = argparse.ArgumentParser()
#parser.add_argument("file", type=str, help="File name of JSON file")
parser.add_argument("-a", dest="command", required=False, type=str, help="Command")
parser.add_argument("-r", dest="region", required=False, type=str, help="Region")
parser.add_argument("-s", dest="start", required=False, type=str, help="Receive this parameter to start")
parser.add_argument("-k", dest="stop", required=False, type=str, help="Receive this parameter to stop")
args = parser.parse_args()
if args.start and args.start != "started":
print("Kindly parse correct key")
return
elif args.stop and args.stop != "stopped":
print("Kindly parse correct key")
return
elif (args.command and args.command not in ["lambda_start", "lambda_stop"]) or (args.command == "lambda_start" and not args.start) or (args.command == "lambda_stop" and not args.stop):
print("Kindly parse correct key")
return
ec2 = boto3.resource('ec2', args.region)
if args.command == "lambda_stop" or args.stop is not None:
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
for instance in instances:
print(instance.id)
instance.stop()
elif args.command == "lambda_start" or args.start is not None:
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
for instance in instances:
print(instance.id)
instance.start()
if __name__ == "__main__":
ec2_control()
| true |
e11c4c465f32623af14df1a918d0ac25d4b53209 | Python | kangli-bionic/algorithm | /lintcode/832.1.py | UTF-8 | 682 | 3.0625 | 3 | [
"MIT"
] | permissive | """
832. Count Negative Number
https://www.lintcode.com/problem/count-negative-number/description?_from=ladder&&fromId=152
o(n+m)
https://www.jiuzhang.com/solution/count-negative-number/#tag-other
"""
class Solution:
"""
@param nums: the sorted matrix
@return: the number of Negative Number
"""
def countNumber(self, nums):
# Write your code here
count = 0
if not nums:
return count
n = len(nums)
m = len(nums[0])
i = m - 1
for row in nums:
while i >= 0:
if row[i] < 0:
break
i -= 1
count += i + 1
return count | true |
efa5beb4a245ec4d5fa58a2a2dbd19d4ddb18364 | Python | IncompleteInformation/Live_Dubstep | /ZZZ-Deprecated/Pre-Mac/AccelGrapher/writetime.py | UTF-8 | 101 | 2.921875 | 3 | [] | no_license | import time
w=open("file.txt",'w')
for i in range(1000):
w.write(str(time.clock())+'\n')
w.close() | true |
1b378b2b6d42eaf5297fb15ab4a871184ddaac67 | Python | Rachneet/PySpark | /kmeans.py | UTF-8 | 886 | 2.640625 | 3 | [] | no_license | from pyspark.sql import SparkSession
from pyspark.ml.clustering import KMeans
from pyspark.ml.feature import VectorAssembler, StandardScaler
from pyspark.ml.evaluation import BinaryClassificationEvaluator, MulticlassClassificationEvaluator
spark = SparkSession.builder.appName("clustering").getOrCreate()
df = spark.read.csv("./files/seeds_dataset.csv", inferSchema=True, header=True)
# df.show()
assembler = VectorAssembler(inputCols=df.columns,
outputCol='features')
data = assembler.transform(df)
scaler = StandardScaler(inputCol='features', outputCol='scaledFeatures')
scaled_data = scaler.fit(data).transform(data)
kmeans = KMeans(featuresCol='scaledFeatures').setK(3)
model = kmeans.fit(scaled_data)
# print("WSSSE")
# print(model.computeCost(scaled_data))
print(model.clusterCenters())
model.transform(scaled_data).select('prediction').show()
| true |
851fcf8676e4f38e88d568480b485158208273ca | Python | mlforcada/Appraise | /eval/similar_words.py | UTF-8 | 1,413 | 2.703125 | 3 | [
"BSD-3-Clause"
] | permissive | __author__ = 'Sereni'
import networkx
import itertools
from operator import itemgetter
def similarity(word1, word2, gr, pos_tags):
pos = ''
for tag in pos_tags:
if tag in word1[1][1]:
pos = tag
break
if pos in word2[1][1]:
tags1 = set(word1[1][1])
tags2 = set(word2[1][1])
common_tags = tags1.intersection(tags2)
gr.add_edge(word1[0], word2[0], {'weight': len(common_tags)})
gr.add_edge(word1[0], word1[0], {'weight': 99}) # should always have a choice for the original word in the gap
return
def generate_choices(words, kw, n=3): # n for number of choices
gr = networkx.Graph()
pos_tags = ['n', 'vblex', 'vbmod', 'vbser', 'vbhaver', 'vaux', 'adj', 'post', 'adv',
'preadv', 'postadv', 'mod', 'det', 'prn', 'pr', 'num', 'np', 'ij', 'cnjcoo',
'cnjsub', 'cnjadv']
for (word1, word2) in itertools.combinations_with_replacement(words, 2):
similarity(word1, word2, gr, pos_tags)
alternatives = {}
for word in gr.nodes():
records = sorted([(j, gr[i][j]['weight']) for (i, j) in gr.edges(word)], key=itemgetter(1), reverse=True)
top = [item for (item, score) in records[:n]]
alternatives[word] = top
filtered = [(form, alternatives[form]) for form in kw]
# fixme choices should be the same case as input, not lowercase
return filtered | true |
8feb13810e8bb7a84a16c42559a222e2c977479e | Python | reddymadhira111/Python | /programs/filter.py | UTF-8 | 293 | 4.15625 | 4 | [] | no_license | '''
The function filter(function, list) offers a convenient way
to filter out all the elements of an iterable, for which the function returns True.
'''
def even(n):
if n %2 == 0:
return True
x=filter(even, range(10))
print(list(x))
x=filter(lambda n:n%2==0, range(10,20))
print(list(x)) | true |
cb579ae5e2430886afab295c12610d3761591059 | Python | tiagniuk/daily_expenses | /models/Locations.py | UTF-8 | 959 | 2.734375 | 3 | [] | no_license | from sqlalchemy import Column, Integer, String, Text, DateTime, \
UniqueConstraint, func
from models import Base
class Locations(Base):
__singular__ = 'location'
id = Column(Integer, primary_key=True)
city = Column(String(100), nullable=False)
country = Column(String(100), nullable=False)
note = Column(Text, nullable=True)
datetime_created = Column(DateTime, default=func.current_timestamp(),
nullable=False)
datetime_modified = Column(DateTime, onupdate=func.current_timestamp(),
nullable=True)
__table_args__ = (
UniqueConstraint('city', 'country', name='city_country_uc'),
)
def title(self):
return self.city + ' ' + self.country
def __repr__(self):
return "<Locations(city='{:s}', country='{:s}', " \
"datetime_created='{:s}')>" \
.format(self.city, self.country, self.datetime_created)
| true |
f19313dbb048684d9dc117347ad2e0735dcad4e9 | Python | Chacon-Miguel/Project-Euler-Solutions | /Multiples_Of_3_And_5.py | UTF-8 | 152 | 3.890625 | 4 | [] | no_license | count = 0
for x in range(3, 1000):
# If its divisible by three or 5, add it to count
if not x%3 or not x%5:
count += x
print(count) | true |
24b20bf25eaf4a9eca400b8302f0d123f1966254 | Python | msproteomicstools/msproteomicstools | /analysis/data_conversion/pseudoreverseDB.py | UTF-8 | 3,719 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================================
msproteomicstools -- Mass Spectrometry Proteomics Tools
=========================================================================
Copyright (c) 2013, ETH Zurich
For a full list of authors, refer to the file AUTHORS.
This software is released under a three-clause BSD license:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of any author or any participating institution
may be used to endorse or promote products derived from this software
without specific prior written permission.
--------------------------------------------------------------------------
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------
$Maintainer: Lorenz Blum$
$Authors: Pedro Navarro, Lorenz Blum$
--------------------------------------------------------------------------
"""
from __future__ import print_function
import shutil
import sys
import getopt
import re
def pseudoreverse(seq, cleavage_rule):
split = re.split("(%s)" % cleavage_rule, seq)
return "".join([s[::-1] for s in split])
def usage():
print("""Usage: python pseudoreverseDB [options]
Options:
-i input.fasta input fasta file
-o output.fasta output file with decoys
[-t] tag for decoys (optional, default 'DECOY_')
[-c] cleavage rule (optional, default '[KR](?!P)' =trypsin)
Creates pseudo-reversed decoys (peptide level reversion). If no cleavage site is found protein is simply reversed.
See http://dx.doi.org/10.1038/nmeth1019 Figure 6""")
sys.exit(1)
def main(argv):
# Get options
try:
opts, args = getopt.getopt(argv, "i:o:t:c:")
except getopt.GetoptError:
usage()
decoytag = "DECOY_"
cleavage_rule = '[KR](?!P)'
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
if opt in ("-i", "--input"):
i = arg
if opt in ("-o", "-output"):
o = arg
if opt in ("-t", "--tag"):
decoytag = arg
if opt in ("-c", "--cleavage_rule"):
cleavage_rule = arg
# copy orig
try:
shutil.copy(i, o)
except UnboundLocalError:
usage()
# append decoys
out = open(o, 'a')
seq = ""
for line in open(i):
if line.startswith('>'):
out.write(pseudoreverse(seq, cleavage_rule) + '\n')
seq = ""
out.write('>%s%s' % (decoytag, line[1:]))
else:
seq += line.strip()
#flush last one
out.write(pseudoreverse(seq, cleavage_rule) + '\n')
if __name__ == '__main__':
main(sys.argv[1:])
| true |
e1f8259e5f9cd52561750c1bd4e81fd565208e80 | Python | AlexPav217/BubbleSort | /tests.py | UTF-8 | 1,914 | 3.375 | 3 | [] | no_license | import unittest
from main import bubbleSort
class TestStringMethods(unittest.TestCase):
def test_empty(self):
self.assertEqual(bubbleSort([]), [])
def test_one_element_array(self):
self.assertEqual(bubbleSort(["1"]), ["1"])
def test_simple_strings(self):
self.assertEqual(bubbleSort(["b", "a", "c"]), ["a", "b", "c"])
def test_numbers(self):
self.assertEqual(bubbleSort([3, 1, 2]), [1, 2, 3])
def test_number_long(self):
self.assertEqual(bubbleSort([5, 7, 4, 1, 8, 10]), ([1, 4, 5, 7, 8, 10]))
def test_simple_strings_different_register(self):
self.assertEqual(bubbleSort(["a", "A", "B", "b"]), ["A", "B", "a", "b"])
def test_simple_strings_special_symbol(self):
self.assertEqual(bubbleSort(["a", "A", "!", "B"]), ["!", "A", "B", "a"])
def test_simple_strings_special_symbol_and_numbers_and_register(self):
self.assertEqual(bubbleSort(["a", "5", "!", "B"]), ["!", "5", "B", "a"])
def test_long_strings(self):
self.assertEqual(bubbleSort(["aaa", "aba", "aab", "bba"]), ["aaa", "aab", "aba", "bba"])
def test_long_strings_different_cases_1(self):
self.assertEqual(bubbleSort(["Aaa", "aba", "Bab", "bba"]), ["Aaa", "Bab", "aba", "bba"])
def test_long_strings_different_cases_2(self):
self.assertEqual(bubbleSort(["bbF", "Aaa", "ABA", "Cba", "Bab", "bba"]), ["ABA", "Aaa", "Bab", "Cba", "bbF", "bba"])
def test_long_strings_special_symbol(self):
self.assertEqual(bubbleSort(["!", "a!", "@a!"]), ["!", "@a!", "a!"])
def test_long_strings_special_symbol_different_cases(self):
self.assertEqual(bubbleSort(["A!", "a!", "@a!"]), ["@a!", "A!", "a!"])
def test_equal_elements(self):
self.assertEqual(bubbleSort(["a", "a", "a"]), ["a", "a", "a"])
if __name__ == '__main__':
unittest.main() | true |
e3163d1e5e30d828072849aa1dcfec57fed8476b | Python | alisw/AliPhysics | /PWGJE/EMCALJetTasks/Tracks/analysis/base/Graphics.py | UTF-8 | 22,061 | 2.625 | 3 | [] | permissive | #**************************************************************************
#* Copyright(c) 1998-2014, ALICE Experiment at CERN, All rights reserved. *
#* *
#* Author: The ALICE Off-line Project. *
#* Contributors are mentioned in the code where appropriate. *
#* *
#* Permission to use, copy, modify and distribute this software and its *
#* documentation strictly for non-commercial purposes is hereby granted *
#* without fee, provided that the above copyright notice appears in all *
#* copies and that both the copyright notice and this permission notice *
#* appear in the supporting documentation. The authors make no claims *
#* about the suitability of this software for any purpose. It is *
#* provided "as is" without express or implied warranty. *
#**************************************************************************
"""
Graphics module, containing basic ROOT plot helper functionality and
base classes for specific kinds of plots
@author: Markus Fasel ,
@contact: <markus.fasel@cern.ch>
@organization: Lawrence Berkeley National Laboratory
@organization: ALICE Collaboration
@copyright: 1998-2014, ALICE Experiment at CERN, All rights reserved
"""
from ROOT import TCanvas,TH1F,TLegend,TPad,TPaveText,TF1, TGraph, TH1
from ROOT import kBlack
class Frame:
"""
Helper class handling frame drawing in plots
"""
def __init__(self, name, xmin, xmax, ymin, ymax):
"""
Construct frame with name and ranges for x and y coordinate
@param name: Name of the frame
@param xmin: Min. value of the x-coordinate
@param xmax: Max. value of the x-coordinate
@param ymin: Min. value of the y-coordinate
@param ymax: Max. value of the y-coordinate
"""
self.__framehist = TH1F(name, "", 100, xmin, xmax)
self.__framehist.SetStats(False)
self.__framehist.GetYaxis().SetRangeUser(ymin, ymax)
def SetXtitle(self, title):
"""
Set title of the x axis
@param title: Title of the x-axis
"""
self.__framehist.GetXaxis().SetTitle(title)
def SetYtitle(self, title):
"""
Set title of the y axis
@param title: Title of the y-axis
"""
self.__framehist.GetYaxis().SetTitle(title)
def Draw(self):
"""
Draw the frame.
"""
self.__framehist.Draw("axis")
class Style:
"""
Class for plot styles (currently only color and marker)
"""
def __init__(self, color, marker, options = None):
"""
Constructor
@param color: Color definition of the style
@param marker: Marker definition of the style
@param option: Optional other style definitions
"""
self.__color = color
self.__marker = marker
self.__linestyle = None
self.__linewidth = None
self.__fillstyle = None
self.__fillcolor = None
if options:
if "fillstyle" in options.keys():
self.__fillstyle = options["fillstyle"]
if "fillcolor" in options.keys():
self.__fillcolor = options["fillcolor"]
if "linestyle" in options.keys():
self.__linestyle = options["linestyle"]
if "linewidth" in options.keys():
self.__linewidth = options["linewidth"]
def SetColor(self, color):
"""
Change color of the graphics object
@param color: The color of the object
"""
self.__color = color
def SetMarker(self, marker):
"""
Change marker style of the graphics object
@param marker: The marker style
"""
self.__marker = marker
def SetLineStyle(self, linestyle):
"""
Change the line style
@param linestyle: New line style
"""
self.__linestyle = linestyle
def SetLineWidth(self, linewidth):
"""
Change the line width
@param linewidth: New line width
"""
self.__linewidth = linewidth
def SetFillStyle(self, fillstyle):
"""
Change the fill style
@param fillstyle: New fill style
"""
self.__fillstyle = fillstyle
def SetFillColor(self, fillcolor):
"""
Change the fill color
@param fillcolor: the new fill color
"""
self.__fillcolor = fillcolor
def GetColor(self):
"""
Access color of the graphics object
@return: Marker color
"""
return self.__color
def GetMarker(self):
"""
Access marker style
@return: Marker style
"""
return self.__marker
def GetLineStyle(self):
"""
Get the line style (if defined)
@return: The line style
"""
return self.__linestyle
def GetLineWidth(self):
"""
Get the line width
@return: The line width
"""
return self.__linewidth
def GetFillStyle(self):
"""
Get the fill style (if defined)
@return: The fill style
"""
return self.__fillstyle
def GetFillColor(self):
"""
Get the fill color (if defined)
@return: The fill color
"""
return self.__fillcolor
def DefineROOTPlotObject(self, rootobject):
"""
Sets the style to the root object
@param rootobject: The ROOT graphics object to be defined
"""
#print "Defining root object"
rootobject.SetMarkerColor(self.__color)
if self.__linestyle is not None:
rootobject.SetLineStyle(self.__linestyle)
if self.__linewidth is not None:
rootobject.SetLineWidth(self.__linewidth)
if not type(rootobject) is TF1:
rootobject.SetMarkerStyle(self.__marker)
rootobject.SetLineColor(self.__color)
if self.__fillstyle is not None:
rootobject.SetFillStyle(self.__fillstyle)
if self.__fillcolor is not None:
rootobject.SetFillColor(self.__fillcolor)
class GraphicsObject:
"""
Container for styled objects, inheriting from TGraph, TH1 or TF1
"""
def __init__(self, data, style = None, drawoption = "epsame"):
"""
Initialise new graphics object with underlying data (can be TH1 or TGraph(Errors)),
and optionally a plot style. If no plot style is provided, then the default style (black,
filled circles) is chosen.
@param data: Underlying data as root object
@param style: Plot style applied
@param drawoption: Draw option
"""
self.__data = data
mystyle = Style(kBlack, 20)
if style:
mystyle = style
self.SetStyle(mystyle)
self.__drawoption = "epsame"
if drawoption:
self.__drawoption = drawoption
if not "same" in self.__drawoption:
self.__drawoption += "same"
if type(self.__data) is TF1:
self.__drawoption = "lsame"
def SetStyle(self, style):
"""
Initialise underlying object with style
@param style: The plot style used
"""
style.DefineROOTPlotObject(self.__data)
def GetData(self):
"""
Provide access to underlying data
@return: The underlying root object
"""
return self.__data
def Draw(self):
"""
Draw graphics object. By default, the plot option is
"epsame". Option strings will always have the option same
"""
#print "Drawing option %s" %(self.__drawoption)
self.__data.Draw(self.__drawoption)
def AddToLegend(self, legend, title):
"""
Add graphics object to a legend provided from outside
@param legend: The legend the object is added to
@param title: Legend entry title
"""
option = "lep"
if type(self.__data) is TF1:
option = "l"
elif self.__IsBoxStyle(self.__data):
option = "f"
legend.AddEntry(self.__data, title, option)
def __IsBoxStyle(self, plotobject):
"""
Check whether plot object is drawn in a box style
@param plotobject: The object to check
@return: True if in box style, False otherwise
"""
if type(self.__data) is TF1:
return False
elif issubclass(type(self.__data), TGraph):
for i in range(2, 6):
if "%d" %(i) in self.__drawoption.lower():
return True
return False
elif issubclass(type(self.__data), TH1):
return True if "b" in self.__drawoption.lower() else False
class PlotBase:
"""
base class for plot objects
"""
class _FramedPad:
"""
Defining the pad structure inside the canvas. A pad has a frame with
axes definition, and optionally a legend and one or several label(s)
"""
class GraphicsEntry:
"""
Definition of a graphics entry
"""
def __init__(self, graphobject, title = None, addToLegend = False):
self.__object = graphobject
self.__title = title
self.__addToLegend = addToLegend
def __cmp__(self, other):
"""
Comparison is done accoring to the object title
@param other: object to compare with
@return: 0 if objects are equal, 1 if this object is larger, -1 if object is smaller
"""
# 1st case: either or both of the titles missing
if not self.__title and not other.GetTitle():
return None
if not self.__title and other.GetTitle():
return -1
if self.__title and not other.GetTitle():
return 1
# second case: both of the titles available
if self.__title == other.GetTitle():
return 0
if self.__title < other.GetTitle():
return -1
return 1
def GetObject(self):
"""
Accessor to graphics object
@return: Underlying object
"""
return self.__object
def GetTitle(self):
"""
Get the title of the object
@return: Title of the object
"""
return self.__title
def IsAddToLegend(self):
"""
Check whether graphics is foreseen to be added to legend
@return: True if the object is added to the legend
"""
return self.__addToLegend
def SetTitle(self, title):
"""
Change title of the graphics object
@param title: Title of the object
"""
self.__title = title
def SetAddToLegend(self, doAdd):
"""
Define whether object should be added to a legend
@param doAdd: Switch for adding object to a legend
"""
self.__addToLegend = doAdd
def __init__(self, pad):
"""
Constructor, creating a framed pad structure for a TPad
@param pad: Underlying ROOT pad
"""
self.__pad = pad
self.__Frame = None
self.__legend = None
self.__graphicsObjects = []
self.__labels = []
def DrawFrame(self, frame):
"""
Draw a frame, defined from outside, within the pad
The pad becomes owner of the frame
@param frame: Frame of the pad
"""
self.__frame = frame
self.__frame.Draw()
def DrawGraphicsObject(self, graphics, addToLegend = False, title = None):
"""
Draw a graphics object into the pad. If addToLegend is set, then the object is added to to the
legend.
"""
self.__graphicsObjects.append(self.GraphicsEntry(graphics, title, addToLegend))
graphics.Draw()
def DefineLegend(self, xmin, ymin, xmax, ymax):
"""
create a new legend within the frame with the
given boundary coordinates
@param xmin: Min. x value of the legend
@param xmin: Max. x value of the legend
@param xmin: Min. y value of the legend
@param xmin: Max. y value of the legend
"""
if not self.__legend:
self.__legend = TLegend(xmin, ymin, xmax, ymax)
self.__legend.SetBorderSize(0)
self.__legend.SetFillStyle(0)
self.__legend.SetTextFont(42)
def CreateLegend(self, xmin, ymin, xmax, ymax):
"""
Create Legend from all graphics entries
@param xmin: Min. x value of the legend
@param xmin: Max. x value of the legend
@param xmin: Min. y value of the legend
@param xmin: Max. y value of the legend
"""
if not self.__legend:
self.DefineLegend(xmin, ymin, xmax, ymax)
for entry in sorted(self.__graphicsObjects):
if entry.IsAddToLegend():
self.AddToLegend(entry.GetObject(), entry.GetTitle())
self.DrawLegend()
def GetLegend(self):
"""
Provide access to legend
@return: the legend
"""
return self.__legend
def AddToLegend(self, graphicsObject, title):
"""
Special method adding graphics objects to a legend
@param graphicsObject: graphics object to be added to the legend
@param title: Legend entry title
"""
if self.__legend:
graphicsObject.AddToLegend(self.__legend, title)
def DrawLegend(self):
"""
Draw the legend
"""
if self.__legend:
self.__legend.Draw()
def DrawLabel(self, xmin, ymin, xmax, ymax, text):
"""
Add a new label to the pad and draw it
@param xmin: Min. x value of the label
@param xmin: Max. x value of the label
@param xmin: Min. y value of the label
@param xmin: Max. y value of the label
@param text: Label text
"""
label = TPaveText(xmin, ymin, xmax, ymax, "NDC")
label.SetBorderSize(0)
label.SetFillStyle(0)
label.SetTextFont(42)
label.AddText(text)
label.Draw()
self.__labels.append(label)
def GetPad(self):
"""
Provide direct access to the pad
@return: Underlying ROOT pad
"""
return self.__pad
class _FrameContainer:
"""
Container for framed pad objects
"""
def __init__(self):
"""
Create new empty frame container
"""
self.__Frames = {}
def AddFrame(self, frameID, frame):
"""
Add a new framed pad to the frame container
@param frameID: ID of the frame
@param frame: Frame to be added for pad with ID
"""
self.__Frames[frameID] = frame
def GetFrame(self, frameID):
"""
Provide access to frame
@param frameID: ID of the frame
@return: The frame for the pad
"""
if not self.__Frames.has_key(frameID):
return None
return self.__Frames[frameID]
def __init__(self):
"""
Initialise new plot
"""
self._canvas = None
self._frames = self._FrameContainer()
def _OpenCanvas(self, canvasname, canvastitle, xsize = 1000, ysize = 800):
"""
Initialise canvas with name, title and sizes
@param canvasname: Name of the canvas
@param canvastitle: Title of the canvas
@param xsize: Canvas size in x-direction
@param ysize: Canvas size in y-direction
"""
self._canvas = TCanvas(canvasname, canvastitle, xsize, ysize)
self._canvas.cd()
def SaveAs(self, filenamebase):
"""
Save plot to files:
Creating a file with a common name in the formats
eps, pdf, jpeg, gif and pdf
@param filenamebase: Basic part of the filename (without endings)
"""
for t in ["eps", "pdf", "jpeg", "gif", "png"]:
self._canvas.SaveAs("%s.%s" %(filenamebase, t))
class SinglePanelPlot(PlotBase):
def __init__(self):
"""
Initialise single panel plot
"""
PlotBase.__init__(self)
def _OpenCanvas(self, canvasname, canvastitle):
"""
Create canvas and add it to the list of framed pads
@param canvasname: Name of the canvas
@param canvastitle: Title of the canvas
"""
PlotBase._OpenCanvas(self, canvasname, canvastitle, 1000, 800)
self._frames.AddFrame(0, self._FramedPad(self._canvas))
def _GetFramedPad(self):
"""
Access to framed pad
@return: The underlying framed pad
"""
return self._frames.GetFrame(0)
class MultipanelPlot(PlotBase):
"""
Base Class For multiple panel plots
"""
def __init__(self, nrow, ncol):
"""
Create new Multi-panel plot with a given number of row and cols
"""
PlotBase.__init__(self)
self.__nrow = nrow
self.__ncol = ncol
def _OpenCanvas(self, canvasname, canvastitle, xsize, ysize):
"""
Create new canvas and split it into the amount of pads as defined
@param canvasname: Name of the canvas
@param canvastitle: Title of the canvas
@param xsize: Canvas size in x-direction
@param ysize: Canvas size in y-direction
"""
PlotBase._OpenCanvas(self, canvasname, canvastitle, xsize, ysize)
self._canvas.Divide(self.__ncol, self.__nrow)
def _OpenPad(self, padID):
"""
Create new framed pad in a multi-panel plot for a given pad ID
@param padID: ID number of the pad
@return: The framed pad
"""
if padID < 0 or padID > self.__GetMaxPadID():
return None
mypad = self._GetPad(padID)
if not mypad:
mypad = self._FramedPad(self._canvas.cd(padID+1))
self._frames.AddFrame(padID, mypad)
return mypad
def _OpenPadByRowCol(self, row, col):
"""
Create new framed pad in a multi-panel plot for a given row an col
@param row: row of the pad
@param col: column of the pad
@return: The new pad at this position
"""
return self._OpenPad(self.__GetPadID(row, col))
def _GetPad(self, padID):
"""
Access to Pads by pad ID
@param padID: ID number of the pad
@return: The framed pad
"""
return self._frames.GetFrame(padID)
def _GetPadByRowCol(self, row, col):
"""
Access Pad by row and col
@param row: row of the pad
@param col: column of the pad
@return: The pad at this position
"""
return self._frames.GetFrame(self.__GetPadID(row, col))
def __GetPadID(self, row, col):
"""
Calculate ID of the pad
@param row: row of the pad
@param col: column of the pad
@return: The pad ID for this combination
"""
if (row < 0 or row >= self.__nrow) or (col < 0 or col >= self.__ncol):
return -1
return 1 + row * self.__ncol + col
def __GetMaxPadID(self):
"""
Calculate the maximum allowed pad ID
@return: The maximum pad ID
"""
return 1 + self.__ncol * self.__nrow
class TwoPanelPlot(MultipanelPlot):
"""
A plot with two panels
"""
def __init__(self):
"""
Initialise two-panel plot
"""
MultipanelPlot.__init__(self, 1, 2)
def _CreateCanvas(self, canvasname, canvastitle):
"""
Create Canvas with the dimensions of a four-panel plot
@param canvasname: Name of the canvas
@param canvastitle: Title of the canvas
"""
MultipanelPlot._OpenCanvas(self, canvasname, canvastitle, 1000, 500)
class FourPanelPlot(MultipanelPlot):
"""
A plot with four (2x2) panels
"""
def __init__(self):
"""
Initialise four-panel plot
"""
MultipanelPlot.__init__(self, 2, 2)
def _OpenCanvas(self, canvasname, canvastitle):
"""
Create Canvas with the dimensions of a four-panel plot
@param canvasname: Name of the canvas
@param canvastitle: Title of the canvas
"""
MultipanelPlot._OpenCanvas(self, canvasname, canvastitle, 1000, 1000) | true |
cc2f4f4a68e90c1953071b0494e6f01cf79c9d2e | Python | AllaZhulyanova/Autotests_for_ADUKAR | /Fixture/List_items_before_autorization.py | UTF-8 | 9,601 | 3.015625 | 3 | [
"Apache-2.0"
] | permissive |
class BeforeAutorizationHelper:
def __init__(self,app):
self.app = app
# выбор предмета по порядку, возвращает кол-во уроков/тестов
def Test_list_of_all_items(self, TEXT):
driver = self.app.driver
Items = driver.find_elements_by_class_name('subject-card') # кнопка списка предметов
lenght_Items = len(Items)
number_all_tests = 0 # общее кол-во тестов по всем предметам
number_all_tests_access = 0 # общее кол-во тестов по всем предметам, которые имеют доступ
for i in range(0, lenght_Items):
Items[i].click() # нажимаем на предмет по порядку
Lenght_Objects = len(driver.find_elements_by_class_name(
'subject-number')) # длина списка уроков и тестов, нет атрибута текст
if Lenght_Objects != 0:
number_tests = self.Test_list_of_tests_and_lessons(TEXT) # функция выбор теста по порядку
number_all_tests = number_all_tests + number_tests[0]
number_all_tests_access = number_all_tests_access + number_tests[1]
Button_courses = driver.find_element_by_partial_link_text('курсы') # кнопка "<- курсы"
Button_courses.click() # после нажатия возвращает на список предметов
Items = driver.find_elements_by_class_name('subject-card') # кнопка списка предметов
lenght_Items = len(Items)
return number_all_tests, number_all_tests_access
# выбор предмета по порядку для ТТ, возвращает кол-во ТТ
def Test_list_of_all_items_for_TT (self, TEXT):
driver = self.app.driver
Items = driver.find_elements_by_class_name('subject-card') # кнопка списка предметов
lenght_Items = len(Items)
number_all_tests = 0 # общее кол-во тестов по всем предметам
number_all_tests_access = 0 # общее кол-во тестов по всем предметам, которые имеют доступ
for i in range(0, lenght_Items):
Items[i].click() # нажимаем на предмет по порядку
Buttons = driver.find_elements_by_class_name(
'subject-number') # список уроков и тестов, нет атрибута текст
Lenght_Objects = len(Buttons)
if Lenght_Objects != 0:
number_tests = self.Test_list_of_TT(TEXT) # функция выбор теста по порядку
number_all_tests = number_all_tests + number_tests[0]
number_all_tests_access = number_all_tests_access + number_tests[1]
Button_courses = driver.find_element_by_partial_link_text('курсы') # кнопка "<- курсы"
Button_courses.click() # после нажатия возвращает на список предметов
driver.implicitly_wait(1)
Items = driver.find_elements_by_class_name('subject-card') # кнопка списка предметов
return number_all_tests, number_all_tests_access
# доступ к уроку/тесту, возвращает кол-во уроков/тестов в предмете
def Test_list_of_tests_and_lessons(self,TEXT):
driver = self.app.driver
Text_sub = driver.find_element_by_tag_name('h1').text # название предмета на списке тестов/уроков
Lenght_buttons_objects = len(driver.find_elements_by_class_name('info'))
k = 0 # Кол-во всех разработанных уроков/тестов на странице
n = 0 # Кол-во всех доступных уроков/тестов на странице
for i in range(4, Lenght_buttons_objects):
Buttons_objects = driver.find_elements_by_class_name('info') # кнопка список уроков и тестов и еще 4 кпоки, есть атрибут текст
Text_buttons_objects = Buttons_objects[i].text
Lesson_or_test = Text_buttons_objects.split()
if TEXT == Lesson_or_test[0] and TEXT == "ТЕСТ":
Buttons_objects[i].click()
k = k + 1
message = self.Test_messаge() #функция, которая возварщает текст "Зарегистрируйся и тренируйся без ограничений!"
if message == "Зарегистрируйся и тренируйся без ограничений!":
n = n + 1
Button_close = driver.find_elements_by_class_name('icon_close')[4] # кнопка "Х"
Button_close.click()
else:
print("Ошибка в доступе к тесту")
print("Предмет:", Text_sub)
print(Text_buttons_objects)
elif TEXT == Lesson_or_test[0] and TEXT == "УРОК":
Buttons_objects[i].click()
driver.implicitly_wait(1)
if len(driver.find_elements_by_class_name('test-button')) != 0 or len(driver.find_element_by_tag_name('iframe').get_attribute("src")) != 0:
k = k + 1
if len(driver.find_elements_by_class_name('test-button')) != 0 and len(driver.find_element_by_tag_name('iframe').get_attribute("src")) != 0:
n = n + 1
Button_back = driver.find_element_by_class_name('icon_back') # кнопка <- АДУКАР
Button_back.click()
else:
print("Ошибка в доступе к уроку")
print("Предмет:", Text_sub)
print(Text_buttons_objects)
else:
pass
Lenght_buttons_objects = len(driver.find_elements_by_class_name('info'))
return k, n
# доступ к ТТ1/ТТ2
def Test_list_of_TT(self, TEXT):
driver = self.app.driver
Buttons_objects = driver.find_elements_by_class_name(
'info') # кнопка список уроков и тестов и еще 4 кпоки, есть атрибут текст
Lenght_buttons_objects = len(Buttons_objects)
kTT = 0 # Кол-во всех разработанных тренировочных тестов в уроках
nTT = 0 # Кол-во всех доступных тренировочных тестов в уроках
for i in range(4, Lenght_buttons_objects):
Text_sub = driver.find_element_by_tag_name('h1').text # название предмета на списке тестов/уроков
Text_buttons_objects = Buttons_objects[i].text
Lesson_or_test = Text_buttons_objects.split()
if Lesson_or_test[0] == 'УРОК':
Buttons_objects[i].click()
driver.implicitly_wait(1)
if len(driver.find_elements_by_class_name('test-button')) != 0 and len(driver.find_element_by_tag_name('iframe').get_attribute("src")):
Button_TT = driver.find_elements_by_class_name('test-button') # ТТ1/ТТ2
Lenght_buttons_TT = len(Button_TT)
for j in range(0, Lenght_buttons_TT):
Button_TT[j].click()
kTT = kTT + 1
message = self.Test_messаge() # функция, которая возварщает текст "Зарегистрируйся и тренируйся без ограничений!"
if message == "Зарегистрируйся и тренируйся без ограничений!":
nTT = nTT + 1
driver.back()
Buttons_objects = driver.find_elements_by_class_name('info') # кнопка список уроков
Buttons_objects[i].click()
else:
print("Ошибка в доступе")
print("Предмет:", Text_sub)
print(Text_buttons_objects)
print(Button_TT[j].text)
Button_TT = driver.find_elements_by_class_name('test-button')
Lenght_buttons_TT = len(Button_TT)
Button_back = driver.find_element_by_class_name('icon_back') # кнопка <- АДУКАР
Button_back.click()
Buttons_objects = driver.find_elements_by_class_name('info') # кнопка список уроков/тестов и еще 4 кнопки
Lenght_buttons_objects = len(Buttons_objects)
return kTT, nTT
# возвращение сообщения "Зарегистрируйся и тренируйся без ограничений!"
def Test_messаge(self):
driver = self.app.driver
alert = driver.find_elements_by_tag_name('h2')[-2]
alert_text = alert.text
return alert_text
| true |
f7170aa5c149ebc6edb88e9058bffeb4102ea876 | Python | entbappy/My-python-projects | /Ex7 Healty programmer50.py | UTF-8 | 1,582 | 3.4375 | 3 | [] | no_license | #Healthy programmer
# 9am - 5pm
# Water = water.mp3 (3.5 liters)every 40min - Drank - log
# Eyes = eyes.mp3 (Every 30 min) - EyesDone - log
# Pysical Activity = pysical.mp3 (every 45 min)- ExDone - log
#
# Rules - pygame module to play audio
from pygame import mixer
from datetime import datetime
from time import time
def musiconloop(file,stopper):
mixer.init()
mixer.music.load(file)
mixer.music.play()
while True:
input_of_user = input()
if input_of_user == stopper:
mixer.music.stop()
break
def log_now(msg):
with open("mylogs.txt","a") as f:
f.write(f"{msg} {datetime.now()}\n")
if __name__ == '__main__':
init_waters = time()
init_eyes = time()
init_exercise = time()
watersecs = 10 #40min
eyessecs = 30 #30 min
exsecs = 50 #45 min
while True:
if time() - init_waters > watersecs:
print ("Drink Water!! ..Write 'drank' to stop the alarm")
musiconloop('waters.mp3' ,'drank')
init_waters = time()
log_now("Drank water at")
if time() - init_eyes > eyessecs:
print ("Eyes Exercise time!! ..Write 'doneeyes' to stop the alarm")
musiconloop('eyes.mp3' ,'doneeyes')
init_eyes = time()
log_now("Eyes relaxed done at")
if time() - init_exercise > exsecs:
print ("Exercise Time!! ..Write 'doneex' to stop the alarm")
musiconloop('excercise.mp3' ,'doneex')
init_exercise = time()
log_now("Exercise done at")
| true |
648b3bbb0f553cb74d2289663a2cb2306a0e7c14 | Python | murning/EEE4022S_Final_Year_Project | /localisation_software/simulation.py | UTF-8 | 12,161 | 2.640625 | 3 | [] | no_license | import numpy as np
import data_generator_lib
import pandas as pd
import librosa
import data_cnn_format as cnn
import gccphat
import constants
import rotate
import final_models
import utility_methods
from plotting import plotting
class Simulation:
"""
Class for running a single simulation of doa estimation based on synthetic data
"""
def __init__(self, directory, source_azimuth, source_distance, model):
self.current_position = 0
self.iteration = 0
self.directory = directory
self.predictions = []
self.source_azimuth = source_azimuth
self.source_distance = source_distance
self.model = model
self.rotation = 0
self.mic_centre = np.array([1.5, 1.5])
self.rotation_list = [0]
self.prediction = 0
self.initial_adjust = False
self.current_model = self.get_model() # init
self.results = []
self.audio_number = 0
# TODO: move doa to here
def store_prediction(self, doa_list):
"""
convert relative prediction to home coordinates
"""
true_doas = [utility_methods.cylindrical(self.current_position + doa_list[0]),
utility_methods.cylindrical(self.current_position + doa_list[1])]
self.predictions.append(true_doas)
def get_model(self):
model = None
if self.model == "gcc_cnn":
model = final_models.gcc_cnn()
elif self.model == "raw_cnn":
model = final_models.raw_cnn()
elif self.model == "raw_resnet":
model = final_models.raw_resnet()
elif self.model == "gcc_dsp":
model = final_models.gcc_dsp()
else:
print("Error -> No file found")
return model
def simulated_record(self, mic_rotation):
"""
Simulation of recording audio. Takes source position and mic rotation,
simulates acoustics, and records to wav
:param mic_rotation: angle of rotation of microphone to simulate the head movements
"""
data_point = data_generator_lib.get_data(subset_size=1)[self.audio_number]
wav_id, true_azimuth = data_generator_lib.generate_training_data(source_azimuth_degrees=self.source_azimuth,
source_distance_from_room_centre=self.source_distance,
SNR=-20,
RT60=0.3,
source=data_point,
mic_centre=self.mic_centre,
mic_rotation_degrees=mic_rotation,
binaural_object=constants.room,
dir=self.directory)
output = [wav_id, true_azimuth, self.iteration]
df = pd.DataFrame([output], columns=['stereo wav', 'True Azimuth', 'Rotation Iteration'])
df.to_csv("{dir}/iteration_{iter}.csv".format(dir=self.directory, iter=self.iteration))
def load_audio(self):
"""
Reads wav file based on csv values, resamples audio to 8000hz, fixes length to 1 second
:return: numpy array of stereo audio, DOA from file
"""
df = pd.read_csv("{dir}/iteration_{iter}.csv".format(dir=self.directory, iter=self.iteration),
usecols=[1, 2, 3])
doa_from_file = df.iloc[0][1]
wav_name = df.iloc[0][0]
filename = "{dir}/{wav_name}".format(dir=self.directory, wav_name=wav_name)
y, sr = librosa.load(filename, mono=False)
y_8k = librosa.resample(y, sr, 8000)
result_x = librosa.util.fix_length(y_8k, 8000)
return result_x, doa_from_file
def format_raw_audio_cnn(self):
"""
Format the stereo Audio file for input to the raw audio CNN
:return: data formatted for raw audio CNN, DOA read from file
"""
result_x, doa_from_file = self.load_audio()
x = np.array([result_x])
x_data = cnn.reshape_x_for_cnn(cnn.normalize_x_data(cnn.flatten_stereo(x)))
return x_data, doa_from_file
def format_gcc_cnn(self):
"""
Format the stereo Audio file for input to the gcc_phat CNN
:return: data formatted for gcc_phat CNN, DOA read from file
"""
result_x, doa_from_file = self.load_audio()
signal = result_x[0]
reference_signal = result_x[1]
_, raw_gcc_vector = gccphat.gcc_phat(signal=signal, reference_signal=reference_signal, fs=8000)
cross_correlation_vector = cnn.reshape_x_for_cnn(cnn.normalize_x_data(np.array([raw_gcc_vector])))
return cross_correlation_vector, doa_from_file
def format_gcc_dsp(self):
"""
Format stereo audio file for gcc_dsp model
:return: signal, reference signal and doa_from_file
"""
result_x, doa_from_file = self.load_audio()
return result_x, doa_from_file
def load_and_process_audio(self):
"""
Wrapping loading and processing of models into a single function
"""
output_vector = None
doa = None
if self.model == "gcc_cnn":
output_vector, doa = self.format_gcc_cnn()
elif self.model == "gcc_dsp":
output_vector, doa = self.format_gcc_dsp()
elif self.model == "raw_cnn":
output_vector, doa = self.format_raw_audio_cnn()
elif self.model == "raw_resnet":
output_vector, doa = self.format_raw_audio_cnn()
else:
print("Error -> No file found")
return output_vector, doa
def compute_rotation(self):
"""
compute rotation based on current and prior predictions
:return:
"""
if self.predictions[self.iteration][0] == 90.0 or self.predictions[self.iteration][0] == 270.0:
self.rotation = 20
self.initial_adjust = True
return
if self.iteration == 0 or (self.iteration == 1 and self.initial_adjust):
self.rotation = rotate.get_90_deg_rotation(self.predictions[self.iteration])
elif self.iteration == 1 or (self.iteration == 2 and self.initial_adjust):
self.rotation = rotate.get_45_deg_rotation(self.predictions, self.current_position)
elif self.iteration >= 2 or (self.iteration > 2 and self.initial_adjust):
self.rotation = rotate.get_fine_rotation(self.iteration)
def update_position(self):
"""
update current position of microphone based on rotation
:param rotation:
:return:
"""
self.current_position = utility_methods.cylindrical(self.current_position + self.rotation)
self.rotation_list.append(self.current_position)
def rotate_to_prediction(self):
self.rotation = self.prediction - self.current_position - 90
def simulate(self):
while self.iteration < 6:
self.simulated_record(mic_rotation=self.current_position)
print("Recording Successful")
vector, doa = self.load_and_process_audio()
doa_list = self.current_model.predict(vector)
print("Model Prediction: {list}".format(list=doa_list))
self.store_prediction(doa_list)
print("Prediction List: {list}".format(list=self.predictions))
val = utility_methods.check_if_twice(self.predictions, self.iteration)
if val is not None:
self.prediction = val
self.rotate_to_prediction()
self.update_position()
for i in range(4):
self.rotation_list.append(self.current_position)
self.rotation_list.append(0)
return self.prediction
self.compute_rotation()
print("Rotation: {rotation}".format(rotation=self.rotation))
self.update_position()
print("Current Position: {position}".format(position=self.current_position))
self.iteration += 1
self.prediction = utility_methods.get_mean_prediction(prediction_list=self.predictions)
self.rotate_to_prediction()
self.update_position()
self.rotation_list.append(0)
return self.prediction
def evaluate(self, test_number):
for i in np.arange(0, 355, 5):
self.source_azimuth = i
print("-------------------------------------------------------------------")
print("Source Azimuth: {azimuth}".format(azimuth=self.source_azimuth))
pred = self.simulate()
print("final prediction: {pred}".format(pred=pred))
print("-------------------------------------------------------------------")
self.save_results()
self.reset()
df = pd.DataFrame(self.results, columns=['prediction', 'source_azimuth',
'Number of iterations',
'source distance'])
df.to_csv("{dir}/base_test_{test_number}_{model}.csv".format(test_number=test_number,
dir="evaluation_results",
model=self.model))
def evaluate_distance(self, test_number):
azimuth = 0
for i in np.arange(0.3, 1.5, 0.1):
self.source_distance = i
self.source_azimuth = azimuth
print("Source Azimuth: {azimuth}".format(azimuth=self.source_azimuth))
pred = self.simulate()
print("final prediction: {pred}".format(pred=pred))
print("-------------------------------------------------------------------")
self.save_results()
self.reset()
azimuth += 35
df = pd.DataFrame(self.results, columns=['prediction', 'source_azimuth',
'Number of iterations',
'source distance'])
df.to_csv("{dir}/distance_test_{test_number}_{model}.csv".format(dir="evaluation_results", model=self.model,
test_number=test_number))
def save_results(self):
results_row = [self.prediction, self.source_azimuth, self.iteration, self.source_distance]
self.results.append(results_row)
def reset(self):
"""
This method resets the prediction, iteration, position and rotation values to initial state. Rotates The
motor back to 0 degrees
:return:
"""
self.rotation = 0
self.iteration = 0
self.predictions = []
self.prediction = 0
self.current_position = 0
self.rotation_list = [0]
self.prediction = 0
self.initial_adjust = False
if __name__ == '__main__':
source_distance = 1 # source distance in meters
source_azimuth = 10 # source azimuth in degrees
# Instantiation of the simulation class
sim = Simulation(directory="simulation_test",
source_azimuth=source_azimuth,
source_distance=source_distance,
model="raw_resnet")
prediction = sim.simulate() # Run simulation and get prediction
plot = plotting(room_dim=constants.room_dim,
source_distance=source_distance,
source_azimuth=source_azimuth,
mic_centre=sim.mic_centre,
rotation_list=sim.rotation_list,
prediction_list=sim.predictions,
prediction=sim.prediction)
plot.plot_room()
print("Final Prediction: {prediction}".format(prediction=prediction))
| true |
a8545612e79a2e6d7e82e963b2634727828f9ba6 | Python | Meziel/TradingHarvester | /mbt/recovery_agent.py | UTF-8 | 1,596 | 3.03125 | 3 | [] | no_license | import requests
import datetime
import pymongo
class RecoveryAgent:
def __init__(self, database_info):
self.database_info = database_info
self.mongo_connection = None
self.database = None
self.collection = None
async def recover(self, last_close, current_close):
self.mongo_connection = pymongo.MongoClient(host=self.database_info["database_hostname"],
port=self.database_info["database_port"])
self.database = self.mongo_connection[self.database_info["database_name"]]
self.collection = self.database[self.database_info["collection"]]
url = "https://api.binance.com/api/v1/klines?symbol=BTCUSDT&interval=1m"
request = requests.get(url=url)
data = request.json()
for kline in data:
kline_close = kline[6]
is_between = last_close < kline_close < current_close
if is_between:
kline = {
"symbol": "BTCUSDT",
"start_time": kline[0],
"close_time": kline[6],
"open": kline[1],
"close": kline[4],
"high": kline[2],
"low": kline[3],
"volume": kline[5]
}
await self.store(kline)
self.mongo_connection.close()
async def store(self, data):
self.collection.insert_one(data)
print("Recovered: " + datetime.datetime.fromtimestamp(data["close_time"] / 1000.0).strftime("%I:%M %p"))
| true |
45a278347752b22ad8dc91e7a78437a4a322c245 | Python | AmenehForouz/leetcode-1 | /python/problem-1389.py | UTF-8 | 862 | 4.375 | 4 | [] | no_license | """
Problem 1389 - Create Target Array in the Given Order
Given two arrays of integers nums and index. Your task is to create target
array under the following rules:
Initially target array is empty.
- From left to right read nums[i] and index[i], insert at index index[i] the
value nums[i] in target array.
- Repeat the previous step until there are no elements to read in nums and
index.
Return the target array.
"""
from typing import List
class Solution:
def createTargetArray(
self, nums: List[int], index: List[int]
) -> List[int]:
target = []
for i in range(len(nums)):
target.insert(index[i], nums[i])
return target
if __name__ == "__main__":
nums = [0, 1, 2, 3, 4]
index = [0, 1, 2, 2, 1]
# Should return [0, 4, 1, 3, 2]
print(Solution().createTargetArray(nums, index))
| true |
8d747c51cbf72fa1e35d373f553797f3ab112370 | Python | AhnDogeon/algorithm_study | /날짜별 문제/0222/사다리.py | UTF-8 | 568 | 2.859375 | 3 | [] | no_license | import sys
sys.stdin = open("input.txt", "r")
for t in range(1, 11):
x = input()
num = []
for i in range(100):
num.append([0]+list(map(int, input().split()))+[0])
last = num[99].index(2)
idx = [99, last]
x = idx[0]
y = idx[1]
while 0 < x <= 100 and 0 < y <= 100:
if num[x][y - 1] == 1 and y - 1 != res:
res = y
y = y - 1
if num[x][y + 1] == 1 and y + 1 != res:
res = y
y = y + 1
if num[x-1][y] == 1:
res = y
x = x - 1
print(f'#{t} {y-1}') | true |
a589586ebb686cd4f7bb558eb560b0f61f185056 | Python | mit-ll/spacegym-kspdg | /scripts/example_agent_runner.py | UTF-8 | 1,534 | 2.515625 | 3 | [
"MIT"
] | permissive | # Copyright (c) 2023, MASSACHUSETTS INSTITUTE OF TECHNOLOGY
# Subject to FAR 52.227-11 – Patent Rights – Ownership by the Contractor (May 2014).
# SPDX-License-Identifier: MIT
"""
This example shows how to define agents so that they can be systematically run
in a specific environment (important for agent evaluation purpuses)
Instructions to Run:
- Start KSP game application.
- Select Start Game > Play Missions > Community Created > pe1_i3 > Continue
- In kRPC dialog box click Add server. Select Show advanced settings and select Auto-accept new clients. Then select Start Server
- In a terminal, run this script
"""
from kspdg.agent_api.base_agent import KSPDGBaseAgent
from kspdg.pe1.e1_envs import PE1_E1_I3_Env
from kspdg.agent_api.runner import AgentEnvRunner
class NaivePursuitAgent(KSPDGBaseAgent):
"""An agent that naively burns directly toward it's target"""
def __init__(self):
super().__init__()
def get_action(self, observation):
""" compute agent's action given observation
This function is necessary to define as it overrides
an abstract method
"""
return [1.0, 0, 0, 1.0] # forward throttle, right throttle, down throttle, duration [s]
if __name__ == "__main__":
naive_agent = NaivePursuitAgent()
runner = AgentEnvRunner(
agent=naive_agent,
env_cls=PE1_E1_I3_Env,
env_kwargs=None,
runner_timeout=100, # agent runner that will timeout after 100 seconds
debug=True)
runner.run()
| true |
f56cbe8fe7c05d7d33abadc609c85379c51a9857 | Python | Camebax/Sonoluminescence | /venv/Functions.py | UTF-8 | 7,899 | 3.125 | 3 | [] | no_license | import math
import random
import time
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d
# Функция для цветного вывода всего кубика
def show_cube_3d(array):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
z, y, x = array.nonzero()
cube = ax.scatter(x, y, z, zdir='z', c=array[z, y, x], cmap=plt.cm.rainbow) # Plot the cube
cbar = fig.colorbar(cube, shrink=0.06, aspect=5) # Add a color bar which maps values to colors.
plt.show()
def cube_geometry(n=51,
x_source=25, #
y_source=25,
z_source=25):
start_time = time.time()
down_slice = np.zeros((n, n))
up_slice = np.zeros((n, n))
left_slice = np.zeros((n, n))
right_slice = np.zeros((n, n))
back_slice = np.zeros((n, n))
front_slice = np.zeros((n, n))
angle_weight = np.zeros((n, n))
sum_weight = 0
'''Перебор всех наружных слоев'''
for x in range(0, n):
for y in range(0, n):
# down_slice
xa = 0
ya = 0
za = - z_source
xb = x - x_source
yb = y - y_source
zb = - z_source
cos_alpha = (xa * xb + ya * yb + za * zb) / math.sqrt(
(xa ** 2 + ya ** 2 + za ** 2) * (xb ** 2 + yb ** 2 + zb ** 2))
distance = math.sqrt((x - x_source) ** 2 + (y - y_source) ** 2 + z_source ** 2)
down_slice[x, y] = cos_alpha * (1 / distance ** 2)
angle_weight[x, y] = cos_alpha * down_slice[x, y]
# up_slice
xa = 0
ya = 0
za = n - 1 - z_source
xb = x - x_source
yb = y - y_source
zb = n - 1 - z_source
cos_alpha = (xa * xb + ya * yb + za * zb) / math.sqrt(
(xa ** 2 + ya ** 2 + za ** 2) * (xb ** 2 + yb ** 2 + zb ** 2))
distance = math.sqrt((x - x_source) ** 2 + (y - y_source) ** 2 + (z_source - n + 1) ** 2)
up_slice[x, y] = cos_alpha * (1 / distance ** 2)
for z in range(0, n):
# left_slice
xa = 0
ya = - y_source
za = 0
xb = x - x_source
yb = - y_source
zb = z - z_source
cos_alpha = (xa * xb + ya * yb + za * zb) / math.sqrt(
(xa ** 2 + ya ** 2 + za ** 2) * (xb ** 2 + yb ** 2 + zb ** 2))
distance = math.sqrt((x - x_source) ** 2 + y_source ** 2 + (z - z_source) ** 2)
left_slice[x, z] = cos_alpha * (1 / distance ** 2)
# right_slice
xa = 0
ya = n - 1 - y_source
za = 0
xb = x - x_source
yb = n - 1 - y_source
zb = z - z_source
cos_alpha = (xa * xb + ya * yb + za * zb) / math.sqrt(
(xa ** 2 + ya ** 2 + za ** 2) * (xb ** 2 + yb ** 2 + zb ** 2))
distance = math.sqrt((x - x_source) ** 2 + (y_source - n + 1) ** 2 + (z - z_source) ** 2)
right_slice[x, z] = cos_alpha * (1 / distance ** 2)
for y in range(0, n):
for z in range(0, n):
# back_slice
xa = - x_source
ya = 0
za = 0
xb = - x_source
yb = y - y_source
zb = z - z_source
cos_alpha = (xa * xb + ya * yb + za * zb) / math.sqrt(
(xa ** 2 + ya ** 2 + za ** 2) * (xb ** 2 + yb ** 2 + zb ** 2))
distance = math.sqrt(x_source ** 2 + (y - y_source) ** 2 + (z - z_source) ** 2)
back_slice[y, z] = cos_alpha * (1 / distance ** 2)
# front_slice
xa = n - 1 - x_source
ya = 0
za = 0
xb = n - 1 - x_source
yb = y - y_source
zb = z - z_source
cos_alpha = (xa * xb + ya * yb + za * zb) / math.sqrt(
(xa ** 2 + ya ** 2 + za ** 2) * (xb ** 2 + yb ** 2 + zb ** 2))
distance = math.sqrt((x_source - n + 1) ** 2 + (y - y_source) ** 2 + (z - z_source) ** 2)
front_slice[y, z] = cos_alpha * (1 / distance ** 2)
'''Часть углов'''
r = round(n / 2) # радиус кругового клеточного слоя
innerdot = 0
x0 = round(n / 2) - 1 # координаты центра круглого клеточного слоя
y0 = round(n / 2) - 1
for x in range(0, n): # расчет отношения числа точек в нужной области к их общему числу
for y in range(0, n):
if (x - x0) ** 2 + (y - y0) ** 2 <= r ** 2: # условие попадения в круг на дне ячейки
innerdot += down_slice[x, y]
sum_weight += angle_weight[x, y]
# Часть расчета углов падения
sum_points = np.sum([down_slice, up_slice, left_slice, right_slice, front_slice, back_slice])
runtime = time.time() - start_time
print("--- %s seconds ---" % runtime) # Вывод времени работы программы
return innerdot / sum_points # , innerdot_up/sum_points, innerdot_left/sum_points, innerdot_right/sum_points,
# innerdot_front/sum_points, innerdot_back/sum_points
def cube_monte_carlo(n=51, n_iter=10000, #
x_source=3, #
y_source=3,
z_source=3): # Возвращает 3D массив cell с распределением излучения на наружных слоях
start_time = time.time()
cell = np.zeros((n, n, n)) # Задаём ячейку (3-мерный массив из нулей)
h = 0.45
for _ in range(n_iter):
x = x_source
y = y_source
z = z_source
theta = math.acos(random.uniform(-1, 1))
phi = random.uniform(0, 2 * math.pi)
sin_theta = math.sin(theta)
cos_theta = math.cos(theta)
sin_phi = math.sin(phi)
cos_phi = math.cos(phi)
while (x < n - 1) and (x > 0) and (y < n - 1) and (y > 0) and (z < n - 1) and (z > 0):
x += (sin_theta * cos_phi) * h
y += (sin_theta * sin_phi) * h
z += (cos_theta) * h
cell[round(x), round(y), round(z)] += 1
'''Часть Монте-Карло и углов'''
r = round(n / 2) # радиус кругового клеточного слоя
innerdot = 0
angles = np.zeros((n, n))
angle_weight = np.zeros((n, n))
x0 = round(n / 2) - 1 # координаты центра круглого клеточного слоя
y0 = round(n / 2) - 1
for x in range(0, n): # расчет отношения числа точек в нужной области к их общему числу
for y in range(0, n):
if (x - x0) ** 2 + (y - y0) ** 2 <= r ** 2: # условие попадения в круг на дне ячейки
innerdot += cell[x, y, 0]
'''Часть расчета углов падения'''
alpha = math.atan(math.sqrt((x - x_source) ** 2 + (y - y_source) ** 2) / z_source)
angles[x, y] = alpha
angle_weight[x, y] = alpha * cell[x, y, 0]
dots_in_area = innerdot / np.sum(cell)
# print('Часть точек, попавших в нужную область:', dots_in_area)
np.savetxt('text_files/angle_weight.txt', angle_weight)
np.savetxt('text_files/angles.txt', angles)
np.savetxt('text_files/cell_down.txt', cell[:, :, 0])
# print('Средний угол падения:', (np.sum(angle_weight) / innerdot) / math.pi * 180)
runtime = time.time() - start_time
# print("--- %s seconds ---" % (runtime)) # Вывод времени работы программы
return dots_in_area
| true |
2d40c2b72e90f90b85bddde809e6e5ed28c578a0 | Python | abhinandanbaheti/python-tricks | /Algos/trees/trees.py | UTF-8 | 1,178 | 4.15625 | 4 | [] | no_license | # bfs traversal
class Tree(object):
def bfs(self, graph, start):
visited = list()
queue = list()
visited.append(start)
queue.append(start)
while queue:
val = queue.pop(0)
print(val)
for neighbour in graph[val]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
def dfs(self, graph, start):
visited = list()
stack = list()
visited.append(start)
stack.append(start)
while stack:
val = stack.pop()
print(val)
for neighbour in reversed(graph[val]):
if neighbour not in visited:
visited.append(neighbour)
stack.append(neighbour)
if __name__ == "__main__":
tree = Tree()
# graph as a Adjacency List
graph = {'A': ['B', 'C'],
'B': ['D', 'E', 'A'],
'C': ['F', 'G', 'A'],
'D': ['B'],
'E': ['B'],
'F': ['C'],
'G': ['C']
}
#tree.bfs(graph, 'A')
tree.dfs(graph, 'A')
| true |
67d83abdc9254ad37b04ff4f73658cab2d73a8da | Python | Easy-Shu/shapenet-reconstruction-jittor | /losses.py | UTF-8 | 613 | 2.828125 | 3 | [] | no_license | def iou(predict, target, eps=1e-6):
dims = tuple(range(len(predict.shape))[1:])
intersect = (predict * target).sum(dims)
union = (predict + target - predict * target).sum(dims) + eps
return (intersect / union).sum() / intersect.numel()
def iou_loss(predict, target):
return 1 - iou(predict, target)
def multiview_iou_loss(predicts, targets_a, targets_b):
loss = (iou_loss(predicts[0], targets_a[:, 3]) + \
iou_loss(predicts[1], targets_a[:, 3]) + \
iou_loss(predicts[2], targets_b[:, 3]) + \
iou_loss(predicts[3], targets_b[:, 3])) / 4
return loss | true |
42dedc7fe7adc492ddaa8dc131b42b2c42910f0c | Python | nikiluk/signalife-moo-spine-analysis | /iofunctions.py | UTF-8 | 2,087 | 2.796875 | 3 | [] | no_license | #
# functions to process file loading and data manipulation
import datetime
import os
import numpy as np
import pandas as pd
def list_files(path,ext):
# returns a list of names (with extension, without full path) of all files
# in folder path ext could be '.txt'
#
files = []
for name in os.listdir(path):
if os.path.isfile(os.path.join(path, name)):
if ext in name:
files.append(name)
return files
def printDate():
# returns the string with the current date/time in minute
# example output '2016-05-23_16-31'
printDate = datetime.datetime.now().isoformat().replace(":", "-")[:16].replace("T", "_")
return printDate
def outputFile(fileName, projectFolder=os.getcwd(), folderSuffix='_output'):
# creates the output folder with current datetime and returns the path url for the file to be used further
outputFolder = os.path.join(projectFolder, printDate() + folderSuffix)
if not os.path.exists(outputFolder):
os.makedirs(outputFolder)
outputFile = os.path.join(outputFolder, fileName)
return outputFile
def intensityThresholding(inputProfile, intensityColumn='intensity', intensityThreshold=0):
#drop rows with intensity les than threshold
inputProfile = inputProfile[inputProfile[intensityColumn] > intensityThreshold]
outputProfile = inputProfile.reset_index(drop=True)
return outputProfile
def genotyping(imageName):
#depending on imageName returns the genotype string
#genotype filtering
list_WT = ['f-f_cre-neg','f-p_cre-neg','p-p_cre-neg','p-p_cre-pos']
list_CKO = ['f-f_cre-pos']
list_HTZ = ['f-p_cre-pos']
if any(ext in str(imageName) for ext in list_CKO):
return 'CKO'
if any(ext in str(imageName) for ext in list_WT):
return 'WT'
if any(ext in str(imageName) for ext in list_HTZ):
return 'HTZ'
def returnID(imageName, list_ID):
# depending on imageName string returns the ID string
ext = ''
for ext in list_ID:
if ext in str(imageName):
return ext | true |
f76416d327b09df4a4261ef20d5a2e5016631fb1 | Python | EeshaanJain/ML-Algorithms | /Concept Learning/CandidateElimination.py | UTF-8 | 4,002 | 3.65625 | 4 | [] | no_license | """
The CE algorithm incrementally builds the version space given hypothesis space H and set E of examples.
This is an extended form of the Find-S algorithm. We add the examples one by one and shrink the version space
by removing the inconsistent hypotheses.
Algorithm :
For each training sample d = <x, c(x)> :
1. If d is a positive example :
a. Remove from G any hypothesis inconsistent with d
b. For each hypothesis s in S not consistent with d:
i. Remove s
ii. Add to S all minimal generalizations h of s such that h is consistent with d
iii. Some member of G is more general than h, so remove from S any hypothesis more general than
any other hypothesis in S
2. If d is a negative example:
a. Remove from S any hypothesis inconsistent with d
b. For each hypothesis g in G that is not consistent with d
i. Remove g
ii. Add to G all minimal specializations h of g such that h is consistent with d
iii. Some member of S is more specific than h, so remove from G any hypothesis less general than
any other hypothesis in G
The code is inspired from https://github.com/profthyagu/Python--Candidate-Elimination-Algorithm
"""
import pandas as pd
import sample_data
import display_version_space
def get_domains(df):
domains = []
for col in df.columns:
domains.append(list(df[col].unique()))
return domains
def tuplify(df):
rows = []
for i in range(df.shape[0]):
rows.append(tuple(df.iloc[i]))
return rows
def more_general(h1, h2):
more_general_list = []
for a, b in zip(h1, h2):
m_g = (a == '?') or (a!='-' and (a==b or b=='-'))
more_general_list.append(m_g)
return all(more_general_list)
def fulfills(x, h):
return more_general(h, x)
def min_generalizations(h, x):
h_ = list(h)
for i in range(len(h)):
if not fulfills(x[i], h[i]):
h_[i] = '?' if h[i]!='-' else x[i]
return [tuple(h_)]
def min_specializations(h, domains, x):
result = []
for i in range(len(h)):
if h[i]=='?':
for value in domains[i]:
if x[i] != value:
h_ = h[:i] + (value,) + h[i+1:]
result.append(h_)
elif h[i]!='-':
h_ = h[:i] + ('-',) + h[i+1:]
result.append(h_)
return result
def generalize_S(x, G, S):
prev_S = list(S)
for s in prev_S:
if s not in S:
continue
if not fulfills(x, s):
S.remove(s)
S_ = min_generalizations(s ,x)
S.update([h for h in S_ if any([more_general(g, h) for g in G])])
S.difference_update([h for h in S if any([more_general(h, p) for p in S if h!=p])])
return S
def specialize_G(x, domains, G, S):
prev_G = list(G)
for g in prev_G:
if g not in G:
continue
if fulfills(x, g):
G.remove(g)
G_ = min_specializations(g, domains, x)
G.update([h for h in G_ if any([more_general(h,s) for s in S])])
G.difference_update([h for h in G if any([more_general(p, h) for p in G if h!=p])])
return G
def candidate_elimination(df):
domains = get_domains(df)[:-1]
# Initialising our G and S
G = set([('?',)*len(domains)])
S = set([('-',)*len(domains)])
# Converting data to list of tuples
data = tuplify(df)
for sample in data:
x, cx = sample[:-1], sample[-1] # <x, c(x)> pair
if cx == 'Yes': # i.e x is a positive sample
G = {g for g in G if fulfills(x, g)}
S = generalize_S(x, G, S)
else: # i.e x is a negative sample
S = {s for s in S if not fulfills(x,s)}
G = specialize_G(x, domains, G, S)
return G, S
# Getting the data and domains
df = sample_data.get_sport_data()
G, S = candidate_elimination(df)
display_version_space.draw_hypothesis_space(G, S)
| true |
b41142c080358cdb07dd0784314a67dd2288c019 | Python | lastbyte/dsa-python | /problems/easy/valid_parentheses.py | UTF-8 | 1,535 | 4.375 | 4 | [] | no_license | ```
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'.
'''
def bracket_matching(s: str) -> bool:
if s is None or s == '':
return True
memory = []
for i in range(0, len(s)):
if s[i] == '(' or s[i] == '{' or s[i] == '[' :
memory.append(s[i])
if s[i] == ')':
top_elem = memory.pop()
if top_elem == '(':
continue
else:
return False
if s[i] == '}':
top_elem = memory.pop()
if top_elem == '{':
continue
else:
return False
if s[i] == ']':
top_elem = memory.pop()
if top_elem == '[':
continue
else:
return False
return True if len(memory) == 0 else False
print("(]) : " +str(bracket_matching("(])")))
print("([]) : " + str(bracket_matching("([])")))
print("( : " + str(bracket_matching("(")))
print("({([][]{})}) : " + str(bracket_matching("({([][]{})})")))
| true |
d22fbbaef716174bdddec58b84b8b187707d6e48 | Python | edudawla/scraping | /test scrap.py | UTF-8 | 1,322 | 3.3125 | 3 | [] | no_license | ###...Metodo 1
###...Separei uma classe dentro da Div.
###...Separei a tag <a> e transformei em String
###...Quebrei a lista por ',' usando a biblioteca RE
###...Falta terminar e fazer o CRUD
import requests
from bs4 import BeautifulSoup
import re
url = 'https://www.sjc.sp.gov.br/servicos/mobilidade-urbana/novos-horarios-do-transporte-publico/'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
#dentro da div, encontrar a classe
conteudo = soup.find_all('div', class_='sec_serv_conteudo_box')
for lista in conteudo:
resultado = str(lista.find_all('a')) #lista com dados separados por virgula
novalista = re.split(',',resultado) #quebra da lista por virgula
"""
###...Metodo 2
###...Separei uma classe dentro da Div.
###...Separei a tag <a> e depois iterei o next_element até encontrar o titulo
###...Falta terminar e fazer o CRUD
import requests
from bs4 import BeautifulSoup
import re
url = 'https://www.sjc.sp.gov.br/servicos/mobilidade-urbana/novos-horarios-do-transporte-publico/'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
#dentro da div, encontrar a classe
conteudo = soup.find_all('div', class_='sec_serv_conteudo_box')
for lista in conteudo:
resultado = lista.find_all('a')
for lista2 in resultado:
print(final.next_element)
"""
| true |
24a327e4918d39cb4dbc8ed47971052014c3317b | Python | Jackuna/PythonXample | /aws_bs_inst_health_v0.py | UTF-8 | 3,655 | 2.921875 | 3 | [] | no_license | # ---------------------------------------------------------------------------------------------------------------------------- #
# aws_bs_inst_health_v0.py : AWS Beanstalk Health Status, An xample for the implemenantion of python's boto3 library with
# other python packages.
# Script will show the overall health of beanstalk application with it's respective instances health too.
#
# So what's new ? : The look and feel of all the details in a tabular format.
#
# As comapred to the same first script, no assumption is required over here for max-min instances, it will poppulate by it's own
#
# Author : Jackuna
# ---------------------------------------------------------------------------------------------------------------------------- #
import boto3
import json
from prettytable import PrettyTable
#Color
R = "\033[0;31;40m" # RED
G = "\033[0;32;40m" # GREEN
Y = "\033[0;33;40m" # Yellow
B = "\033[0;34;40m" # Blue
N = "\033[0m" # Reset
CYAN = "\033[1;36m" # CYAN
# Global Varibales
instance_len_list = []
max_instance_len = ""
tabular_fields = ["Application Name","Health","Status"]
def ebs_app_status():
def grab_instance_length():
global instance_len_list
global max_instance_len
beanstalk = boto3.client('elasticbeanstalk')
response = beanstalk.describe_environments()
for val in response['Environments']:
newval = val["EnvironmentName"]
new_response = beanstalk.describe_instances_health(EnvironmentName=newval, AttributeNames=['HealthStatus','Color'])
instance_len_list.append((len(new_response['InstanceHealthList'])))
return max(instance_len_list)
def create_preetyTable_feilds():
global tabular_fields
global max_instance_len
max_instance_len = grab_instance_length()
for new_range in range(0, max_instance_len):
tabular_fields.append("Inst"+str(new_range))
#print(tabular_fields)
def create_preetyTable():
global tabular_fields
global max_instance_lencreate_preetyTable_feilds()
beanstalk = boto3.client('elasticbeanstalk')
response = beanstalk.describe_environments()
tabular_table = PrettyTable()
tabular_table.field_names = tabular_fields
tabular_table.align["Application Name"] = "l"
for val in response['Environments']:
rows = []
rows.append(str(CYAN+val['ApplicationName']+N))
newval = val["EnvironmentName"]
new_response = beanstalk.describe_instances_health(EnvironmentName=newval, AttributeNames=['HealthStatus','Color'])
new_range = len(new_response['InstanceHealthList'])
if val['HealthStatus'] == "Info":
HealthStatus = Y+'Info'+N
elif val['HealthStatus'] == "Ok":
HealthStatus = G+'Ok'+N
if val['Health'] == "Green":
Health = G+'Green'+N
elif val['Health'] == "Info":
Health = Y+'Info'+N
else:
Health = R+'Red'+N
rows.append(HealthStatus)
rows.append(Health)
for ll in range(0, new_range):
Inst = list(new_response['InstanceHealthList'][ll].values())
rows.append(str(Inst))
length_rows = max_instance_len
if length_rows > new_range:
rng = length_rows - new_range
for x_val in range(0, rng):
rows.append("NA")
tabular_table.add_row(rows)
print(tabular_table)
create_preetyTable()
| true |
c3fc019183b5b1a9dd025405cc1455b34793bdf9 | Python | euzivamjunior/pythonbirds | /oo/carro_solucao_instrutor.py | UTF-8 | 3,261 | 3.390625 | 3 | [
"MIT"
] | permissive | # Os comandos escritos abaixos são utilizados para 'doctests', uma forma de testar o código a partir da interação a ser
# realizada no console, para utilizá-lo. basta clicar com o botão direito sobre o doctest e então na opção:
# Run 'Doctests in <this_name_file>'
"""
#Testando motor
>>> motor = Motor()
>>> motor.velocidade
0
>>> motor.acelerar()
>>> motor.velocidade
1
>>> motor.acelerar()
>>> motor.velocidade
2
>>> motor.acelerar()
>>> motor.velocidade
3
>>> motor.frear()
>>> motor.velocidade
1
>>> motor.frear()
>>> motor.velocidade
0
# Testando Direção()
>>> direcao = Direcao()
>>> direcao.valor
'Norte'
>>> direcao.girar_a_direita()
>>> direcao.valor
'Leste'
>>> direcao.girar_a_direita()
>>> direcao.valor
'Sul'
>>> direcao.girar_a_direita()
>>> direcao.valor
'Oeste'
>>> direcao.girar_a_direita()
>>> direcao.valor
'Norte'
>>> direcao.girar_a_esquerda()
>>> direcao.valor
'Oeste'
>>> direcao.girar_a_esquerda()
>>> direcao.valor
'Sul'
>>> direcao.girar_a_esquerda()
>>> direcao.valor
'Leste'
>>> direcao.girar_a_esquerda()
>>> direcao.valor
'Norte'
# Testando Carro
>>> carro = Carro(direcao, motor)
>>> carro.calcular_velocidade()
0
>>> carro.acelerar()
>>> carro.calcular_velocidade()
1
>>> carro.acelerar()
>>> carro.calcular_velocidade()
2
>>> carro.acelerar()
>>> carro.calcular_velocidade()
3
>>> carro.calcular_direcao()
'Norte'
>>> carro.girar_a_direita()
>>> carro.calcular_direcao()
'Leste'
>>> carro.girar_a_esquerda()
>>> carro.calcular_direcao()
'Norte'
>>> carro.girar_a_esquerda()
>>> carro.calcular_direcao()
'Oeste'
"""
class Carro:
def __init__(self, direcao, motor):
self.direcao = direcao
self.motor = motor
def calcular_velocidade(self):
return self.motor.velocidade
def acelerar(self):
self.motor.acelerar()
def frear(self):
self.motor.frear()
def calcular_direcao(self):
return self.direcao.valor
def girar_a_esquerda(self):
self.direcao.girar_a_esquerda()
def girar_a_direita(self):
self.direcao.girar_a_direita()
class Motor:
def __init__(self):
self.velocidade = 0
def acelerar(self):
self.velocidade += 1
def frear(self):
self.velocidade -= 2
# função max abaixo retorna o maior valor dentre os parâmetros especificados, desta forma, caso a velocidade
# retornada na iteração acima seja 'menor que zero', então o valor atribuido pela iteração abaixo será '0'.
self.velocidade = max(0, self.velocidade)
# por convenção da PEP8, uma constante (var que não deve ser alterada) é escrita em letra maiúcula
NORTE = 'Norte'
LESTE = 'Leste'
SUL = 'Sul'
OESTE = 'Oeste'
class Direcao:
rotacao_a_direita_dict = {NORTE: LESTE, LESTE: SUL, SUL: OESTE, OESTE: NORTE}
rotacao_a_esquerda_dict = {NORTE: OESTE, OESTE: SUL, SUL: LESTE, LESTE: NORTE}
def __init__(self):
self.valor = NORTE
def girar_a_direita(self):
self.valor = self.rotacao_a_direita_dict[self.valor]
def girar_a_esquerda(self):
self.valor = self.rotacao_a_esquerda_dict[self.valor]
| true |