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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
42a7d87f9364fcc413cd3285305610c714315aaa | Python | yylhyyw/Python_Crash_Course_Exercise | /Chapter2/2-9_Favorite_Number.py | UTF-8 | 75 | 2.96875 | 3 | [] | no_license | favorite_number = 11
print('My favorite number is ' + str(favorite_number)) | true |
2b3e754cf80e379ab144d9c71f5e7794594a230a | Python | rosshochwert/machine-learning-with-songs | /scraper/lyricwiki.py | UTF-8 | 1,283 | 3.21875 | 3 | [] | no_license | ##############################################
# Test script to scrape lyrics from lyricwiki.
# It's not six-sigma, so a few glitches may occur.
##############################################
import requests, ast, re
from bs4 import BeautifulSoup, Comment
def get_lyric_url(artist, song):
url = "http://lyrics.wikia.com/api.php?func=getSong"
url += "&artist=" + artist
url += "&song=" + song
url += "&fmt=json"
response = requests.get(url).text
stripped = response.replace("song = ", "")
json_song = ast.literal_eval(stripped)
lyric_url = json_song["url"]
return lyric_url
def scrape(url):
data = requests.get(url).text
soup = BeautifulSoup(data, "lxml")
lyric_box = soup.find("div", {"class": "lyricbox"})
for element in lyric_box(text=lambda text: isinstance(text, Comment)):
element.extract()
scripts = lyric_box.findAll("script")
[s.extract() for s in scripts]
bold = lyric_box.findAll("b")
[s.extract() for s in bold]
lyrics = lyric_box.renderContents().replace("<br/>","\n")
lyrics = lyrics.replace('<div class="lyricsbreak"></div>','')
return lyrics
if __name__ == "__main__":
url = get_lyric_url("the lonely island", "jack sparrow")
lyrics = scrape(url)
print lyrics
| true |
156a4a036fbfcce39cf09e0a2b8e1537a401d6ac | Python | Nedra1998/sysutil | /util.py | UTF-8 | 2,084 | 2.984375 | 3 | [] | no_license | import re
def get_bar(percent, minmum=False):
if minmum is False:
if percent <= 11.11:
return ' '
elif percent <= 22.22:
return '\u2581'
elif percent <= 33.33:
return '\u2582'
elif percent <= 44.44:
return '\u2583'
elif percent <= 55.55:
return '\u2584'
elif percent <= 66.66:
return '\u2585'
elif percent <= 77.77:
return '\u2586'
elif percent <= 88.88:
return '\u2587'
else:
return '\u2588'
elif minmum is True:
if percent <= 12.5:
return '\u2581'
elif percent <= 25:
return '\u2582'
elif percent <= 37.5:
return '\u2583'
elif percent <= 50:
return '\u2584'
elif percent <= 62.5:
return '\u2585'
elif percent <= 75:
return '\u2586'
elif percent <= 87.5:
return '\u2587'
else:
return '\u2588'
def gen_color_code(string):
string = string.strip('{')
string = string.strip('}')
string = string.strip('#')
rgb_color = tuple(int(string[i:i + 2], 16) for i in (0, 2, 4))
return "\033[38;2;{};{};{}m".format(rgb_color[0], rgb_color[1],
rgb_color[2])
def fmt_print(data, fmt, end=''):
fmt = fmt.replace("{#}", "\033[39m")
colors = re.findall("{#.{6}}", fmt)
for i, match in enumerate(colors):
fmt = fmt.replace(match, ">>{}<<".format(i))
fmt = fmt.format(**data)
for i, match in enumerate(colors):
# fmt = fmt.replace(">>{}<<".format(i), '%{F' + match.lstrip('{'))
fmt = fmt.replace(">>{}<<".format(i), gen_color_code(match))
print(fmt, end=end)
def fmt_percent(percent, whole=False):
if whole is True:
return "{:.0f}".format(percent)
if percent >= 100:
return "{:3.0f}".format(percent)
elif percent >= 10:
return "{:4.1f}".format(percent)
else:
return "{:4.2f}".format(percent)
| true |
87d697f5ae5cc59968207444cc2c221e5f614173 | Python | bluexm/airquality | /scraper.py | UTF-8 | 975 | 2.6875 | 3 | [] | no_license | import pandas as pd
import requests
import bs4
import sqlite3
import json
DB_FILE = "data.sqlite"
DB_TITLES = ["station","reading"]
import sqlite3
from sqlite3 import Error
try:
CONNEXION = sqlite3.connect(DB_FILE)
print("connexion with DB successful, using SQLlite ", sqlite3.version)
except Error as e:
print(e)
dfdb = pd.DataFrame(columns=DB_TITLES)
# or read column titles from database
try:
curDB = pd.read_sql("select * from indeed_ads", CONNEXION)
except:
print("database empty")
curDB = None
#------------- Scraping ------------------------
urlstations=['https://api.waqi.info/map/bounds/?token=7c88a4e043854ed6beeb8e06052616ef3d0fd01f&latlng=22.29,113.37,22.03,113.92']
response = requests.get(urlstations[0])
json_raw = json.loads(response.text)
data=json_raw["data"]
#------------- Saving in DB ------------------------
dfdb.to_sql('indeed_ads',CONNEXION,if_exists='append', index=False)
print('{:d} new ads recorded'.format(len(dfdb)))
CONNEXION.close()
| true |
8f3fd0f2be6520c4e5b1dbac5c02cc0028d9e1fe | Python | totai02/ip-project-g5 | /client_test.py | UTF-8 | 566 | 2.5625 | 3 | [] | no_license | import requests
import base64
import json
addr = 'http://localhost:5000'
test_url = addr + '/api/classify'
# prepare headers for http request
content_type = 'image/jpeg'
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
with open("data/Equations/Clean/eq1_hr.jpg", 'rb') as f:
img_encode = base64.b64encode(f.read())
data = {
"img_encode": img_encode.decode(),
"format": "file"
}
# send http request with image and receive response
response = requests.post(test_url, json=json.dumps(data), headers=headers)
print(response.text) | true |
3839842750ecab5a225f61d65addeaa4c8184967 | Python | hectorlopezv/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/9-multiply_by_2.py | UTF-8 | 120 | 2.96875 | 3 | [] | no_license | #!/usr/bin/python3
def multiply_by_2(a_dictionary):
return {key: value*2 for key, value in a_dictionary.items()}
| true |
26f84f6df9cba30af6990a253a08742d062a5c2b | Python | ArindomSharma76/Face-Recognition-ML-project-University-of-London | /Face Recognition system/ready dataset for training.py | UTF-8 | 2,321 | 3.28125 | 3 | [] | no_license |
import cv2
import numpy as np#not used in the program
#we need harcascade classifier to make the machine know that what it is seeing is actually a face of a human
#classifiers classify the objects that defines face, hair, cheek etc.
face_classifier = cv2.CascadeClassifier('C:/Python37/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')
#extracting face features
def face_extractor(img):
#we have the image in RGB but converting it into grayscale as it is easy to use
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#detectMultiScale Detects objects of different sizes in the input image. The detected objects are returned as a list . of rectangles. .
faces=face_classifier.detectMultiScale(gray,1.3,5) #1.3 is the scaling factor and min neighbours is 5, higher no. of neighbours is for more accuracy
if faces is(): #if face is not there
return None
for(x,y,w,h) in faces:#x for coloums and y for rows, w is width and h is height
cropped_face=img[y:y+h, x:x+w]
return cropped_face
#configuring camera
cap=cv2.VideoCapture(0)
count=0
while True:
ret,frame= cap.read()
if face_extractor(frame) is not None: #if a face is detected in front of webcam
count+=1
#camera frame size needs to be similar to our face size
face=cv2.resize(face_extractor(frame),(200,200))#200x200 dimension of the frame required
face=cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)#resize face is converted to gray scale
#saving face's values in a address
file_name_path='C:/Users/Arindom/Desktop/My projects/Face Recognition system/faces/user'+str(count)+'.jpg'
cv2.imwrite(file_name_path,face)
#to count no. of images
cv2.putText(face,str(count),(50,50),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2)#(50,50) is the starting point,cv2.FONT_HERSHEY_COMPLEX is the font style,1 is the scaling of font,(0,255,0) is the color and 2 is the font thickness
cv2.imshow('Face Cropper',face)
else:
print('Face not found')
pass
if cv2.waitKey(1)==13 or count==100:# the program will close either we press enter or after it takes 100 samples
break
cap.release()#to close the camera
cv2.destroyAllWindows()
print('Collecting samples complete!!!!')
| true |
3839d449ea530ac9c15ea207e86abfe0bdd34a36 | Python | kannan-c1609/Accenture | /20_String_Permutation.py | UTF-8 | 1,247 | 4.46875 | 4 | [] | no_license | """
String Permutations
You are given two strings ‘X’ and ‘Y’, each containing same no of characters.
Write a program that can determine whether the characters of string ‘X’ can be rearranged to form the second string ‘Y’. print “yes” if this is possible and “no” if not.
Input Specification:
input1: the string ‘X’
input2: the string ‘Y’
Output Specification:
Return “yes” or “no” accordingly.
Example 1:
input:
zbk
zkb
Output: yes
Explanation:
You can rearrange zbk to be zkb (by switching the characters, output is “Yes”.)
Example 2:
Input:
sample
pleamc
Output: no
Explanation:
You can not rearrange “pleam” to be “sample” ( output is “No”.)
"""
NO_OF_CHARS = 256
def String_Permutation(str1, str2):
count1 = [0] * NO_OF_CHARS
count2 = [0] * NO_OF_CHARS
for i in str1:
count1[ord(i)] += 1
for i in str2:
count2[ord(i)] += 1
if len(str1) != len(str2):
return 0
for i in range(NO_OF_CHARS):
if count1[i] != count2[i]:
return 0
return 1
str1 = input()
str2 = input()
if String_Permutation(str1, str2):
print("yes")
else:
print("no") | true |
7e9863b30fe97d7d8c7a666ee2ba6175fec4ede6 | Python | TigranDan998/HomeWorks | /homework_lesson6_1_1_easy.py | UTF-8 | 403 | 3.734375 | 4 | [] | no_license | #задача 1 easy
def avg(a,b):
if a*b>=0:
return(a*b)**0.5
else:
raise ValueError
try:
a=float(input("a="))
b=float(input("b="))
c=avg(a,b)
print("среднее геометрическое= {:.2f}".format(c))
except ValueError as error:
print("ошибка",error)
except Exception as error:
print("ошибка",error)
| true |
f732cad782df44fa267b8578de7867274547ae4a | Python | jiheonkim21/python-challenge | /PyPoll/main.py | UTF-8 | 2,407 | 3.40625 | 3 | [] | no_license | #Ji-Heon Kim
#PyPoll
#main.py
import os
import csv
# Set file path
csvpath = os.path.join('Resources', 'election_data.csv')
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter = ',')
csv_header = next(csvreader)
listOfVotes = []
listOfCandidates = []
totalVoteCount = 0
candidateVoteCount = {}
# Read each row of data after the header. Add 1 to vote count for each row.
for row in csvreader:
totalVoteCount += 1
listOfVotes.append(row[2])
listOfCandidates = list(set(listOfVotes)) #unique list of all candidates
numVotes = 0
winningVoteCount = 0
currentWinner = ""
# For each candidate, count number of votes.
for candidate in listOfCandidates:
for candidateName in listOfVotes:
if candidate == candidateName:
numVotes += 1
candidateVoteCount[candidate] = numVotes
# Keep track of the highest vote count and who the current winner is
if numVotes > winningVoteCount:
currentWinner = candidate
winningVoteCount = numVotes
numVotes = 0
# Print results to console, including Total vote count and votes per candidate. Print winning candidates name.
print("\n")
print(f"Election Results")
print("-----------------------")
print(f"Total Votes: {totalVoteCount}")
print("-----------------------")
for candidateName in sorted(candidateVoteCount, key=candidateVoteCount.get, reverse = True):
print(f'{candidateName}: {round(candidateVoteCount[candidateName]/totalVoteCount*100,3)}% ({candidateVoteCount[candidateName]})')
print("-----------------------")
print(f'Winner: {currentWinner}')
print("-----------------------")
# Export results that were printed to console to text file "voteCount.txt"
outputFile = open("voteCount.txt", "w")
outputFile.write(f"Election Results\n")
outputFile.write("-----------------------\n")
outputFile.write(f"Total Votes: {totalVoteCount}\n")
outputFile.write("-----------------------\n")
for candidateName in sorted(candidateVoteCount, key=candidateVoteCount.get, reverse = True):
outputFile.write(f'{candidateName}: {round(candidateVoteCount[candidateName]/totalVoteCount*100,3)}% ({candidateVoteCount[candidateName]})\n')
outputFile.write("-----------------------\n")
outputFile.write(f'Winner: {currentWinner}')
outputFile.write("-----------------------\n") | true |
71aabffd5c2de6bb47993b7afc3b6d5eacc44cbf | Python | JeremyPaulPalmer/Python-Projects | /Yahtzee/Two_Players (Working)/upper_lower_p1.py | UTF-8 | 875 | 3.03125 | 3 | [] | no_license | import upper_score
import lower_score
import card
import classes
#allows player to choose upper or lower. if lower is full, to to upper and vice versa
#otherwise, 'u' is uppoer and 'l' is lower
def upper_lower_p1():
if classes.active_player1:
card.card()
if classes.player1_var.counter_lower == 7:
upper_score.upper_score()
return
if classes.player1_var.counter_upper == 6:
lower_score.lower_score()
return
answer = input('\nWhere would you like to score? Upper or Lower? (u/l) ')
while (answer != 'u'.lower().strip()) and (answer != 'l'.lower().strip()):
answer = input('Please enter Upper or Lower (u/l) ')
else:
if answer == 'u'.lower().strip():
upper_score.upper_score()
else:
lower_score.lower_score() | true |
71d7eca8849268537e3c52aec4ca6c407d8eb36d | Python | Thiele/markovjokes | /generate.py | UTF-8 | 2,185 | 3.09375 | 3 | [] | no_license | import json
import markovify
### LOADING
jokes = []
with open('stupidstuff.json') as json_data:
tmp_jokes = json.load(json_data)
for d in tmp_jokes:
try:
jokes.append(d["body"])
except:
pass
with open('wocka.json') as json_data:
wocka = json.load(json_data)
for d in wocka:
try:
jokes.append(d["body"])
except:
pass
with open('reddit_jokes.json') as json_data:
reddit = json.load(json_data)
for d in reddit:
try:
jokes.append(d["title"]+" "+d["body"])
except:
pass
def replace_special_characters(jokes):
tmp_jokes = []
for j in jokes:
tmp_jokes.append(j.replace('\r',' ').replace('\n', ' ').replace("'",""))
return tmp_jokes
def lower(jokes):
tmp_jokes = []
for j in jokes:
tmp_jokes.append(j.lower())
return tmp_jokes
def remove_long_jokes(jokes, l):
tmp_jokes = []
for j in jokes:
if len(j) <= l:
tmp_jokes.append(j)
return tmp_jokes
def replace(jokes, needle, r):
tmp_jokes = []
for j in jokes:
tmp_jokes.append(j.replace(needle,r))
return tmp_jokes
def remove_empty(jokes):
tmp_jokes = []
for j in jokes:
if len(j) > 0:
tmp_jokes.append(j)
return tmp_jokes
### PREPROCESSING
tmp_jokes = []
for j in jokes:
joke = j
while "..." in joke:
joke = joke.replace("...","..")
tmp_jokes.append(joke)
jokes = tmp_jokes
jokes = replace(jokes, "."," DOT ")
jokes = replace(jokes, "?"," QUESTIONMARK ")
jokes = replace_special_characters(jokes)
jokes = lower(jokes)
jokes = remove_long_jokes(jokes, 80)
jokes = remove_empty(jokes)
#Now we have the jokes. Generate some original ones
text_model = markovify.NewlineText(jokes, state_size=4)
generated_jokes = []
while len(generated_jokes) <= 500:
joke = text_model.make_sentence()
if not joke == None and joke not in generated_jokes:
clean_joke = joke.replace(" dot",".").replace(" questionmark", "?")
generated_jokes.append(clean_joke)
with open("generated_jokes.json", "w") as f:
f.write(json.dumps(generated_jokes))
| true |
ce375d88aa5651755b25d7d01c9a8f6281fc84e3 | Python | zhuli2/RideSharingSimulation | /driver.py | UTF-8 | 6,030 | 3.78125 | 4 | [] | no_license | from location import Location, manhattan_distance
from rider import *
class Driver:
"""A driver for a ride-sharing service.
=== Attributes ===
@type id: str
A unique identifier for the driver.
@type location: Location
The current location of the driver.
@type speed: int
The constant speed provided by the driver
"""
# === Private Attribute ===
# @type destination: Location
# The possible location where the driver is driving to.
# If it is None, the driver is idle. Otherwise, the driver is driving.
def __init__(self, identifier, location, speed):
"""Initialize a Driver.
@param self: Driver
@param identifier: str
@param location: Location
@param speed: int
@rtype: None
>>> driver_Atom = Driver('Atom', Location(0,0), 1)
>>>
"""
self.id = identifier
self.location = location
self.speed = speed
self.destination = None
def __str__(self):
"""Return a string representation.
@param self: Driver
@rtype: str
>>> driver_Atom = Driver('Atom', Location(0,0), 1)
>>> print(driver_Atom)
Driver_ID: Atom, current location: (0,0), speed: 1
>>>
"""
return "Driver_ID: {}, current location: {}, " \
"speed: {}".format(self.id, self.location, self.speed)
def __eq__(self, other):
"""Return True if self equals other, and false otherwise.
@param self: Driver
@rtype: bool
>>> driver_Atom = Driver('Atom', Location(0,0), 1)
>>> driver_Bathe = Driver('Bathe', Location(5,5), 1)
>>> driver_Atom == driver_Atom
True
>>> driver_Atom == driver_Bathe
False
"""
return type(self) == type(other) and self.id == other.id
def get_travel_time(self, destination):
"""Return the time it will take to arrive at the destination,
rounded to the nearest integer.
@param self: Driver
@param destination: Location
@rtype: int
>>> driver_Atom = Driver('Atom', Location(0,0), 1)
>>> driver_Atom.get_travel_time(Location(5,8))
13
>>>
"""
return round(manhattan_distance(self.location, destination) / self.speed)
def start_drive(self, location):
"""Start driving to the location and return the time the drive will take.
The driver is given a location as the temporary destination
when starting drive.
@param self: Driver
@param location: Location
@rtype: int
>>> driver_Atom = Driver('Atom', Location(0,0), 1)
>>> driver_Atom.start_drive(Location(5,8))
13
>>>
"""
self.destination = location
return self.get_travel_time(location)
def end_drive(self):
"""End the drive and arrive at the rider's origin.
Precondition: self.destination is not None when self starts drive.
When the driver arrives the rider's origin, his location becomes the rider's
origin regardless if he picks up the rider or not.
@param self: Driver
@rtype: None
>>> driver_Atom = Driver('Atom', Location(0,0), 1)
>>> driver_Atom.start_drive(Location(5,8))
13
>>> driver_Atom.end_drive()
>>> print(driver_Atom.location)
(5,8)
>>>
"""
self.location = self.destination
self.destination = None
def start_ride(self, rider):
"""Start a ride and return the time the ride will take.
@param self: Driver
@param rider: Rider
@rtype: int
>>> driver_Atom = Driver('Atom', Location(1, 2), 1)
>>> rider_Bathe = Rider('Bathe','waiting', 5, Location(1, 2), Location(5, 8))
>>> driver_Atom.start_ride(rider_Bathe)
10
>>>
"""
self.destination = rider.destination
return self.get_travel_time(rider.destination)
def end_ride(self):
"""End the current ride, and arrive at the rider's destination.
Precondition: The driver has a rider.
Precondition: self.destination is not None when the driver starts ride.
When the driver drops off the rider, self.location becomes the rider's
destination and hence temporary self.destination is None.
@param self: Driver
@rtype: None
>>> driver_Atom = Driver('Atom', Location(1,2), 1)
>>> rider_Bathe = Rider('Bathe','waiting', 5, Location(1,2), Location(5,8))
>>> driver_Atom.start_ride(rider_Bathe)
10
>>> driver_Atom.end_ride()
>>> print(driver_Atom.location)
(5,8)
>>>
"""
self.location = self.destination
self.destination = None
def is_idle(self):
""" Check if a driver is idle: True if the driver has a destination or False.
@param self: Driver
@return: bool
>>> driver_Atom = Driver('Atom', Location(0,0), 1)
>>> driver_Atom.start_drive(Location(5,8))
13
>>> driver_Atom.is_idle()
False
>>> driver_Atom.end_drive()
>>> driver_Atom.is_idle()
True
>>>
"""
if self.destination is None:
return True
else:
return False
if __name__ == '__main__':
import doctest
doctest.testmod()
driver1 = Driver('Driver1', Location(1, 1), 1)
print(driver1)
print(driver1.is_idle())
rider1 = Rider('Rider1', WAITING, 3, Location(2, 2), Location(5, 5))
print(driver1.start_drive(rider1.origin))
print(driver1.is_idle())
driver1.end_drive()
print(driver1.is_idle())
print(driver1.location)
print(driver1.start_ride(rider1))
print(driver1.is_idle())
driver1.end_ride()
print(driver1.is_idle())
print(driver1.location)
print(driver1 == rider1)
| true |
c84a5b00e3a5d0a1b5f9eba2c5ddb21270fe7aa5 | Python | Aasthaengg/IBMdataset | /Python_codes/p02793/s229589102.py | UTF-8 | 222 | 2.59375 | 3 | [] | no_license | from fractions import gcd
MOD = 10**9+7
N = int(input())
A = list(map(int, input().split()))
now = A[0]
ans = 0
for i in range(1,N):
now = now//gcd(now, A[i])*A[i]
for i in range(N):
ans += now//A[i]
print(ans%MOD) | true |
c6a4af764b645effdbab363632facaa9d9d4cd23 | Python | slaneslane/PythonExamples | /CoreySchaferPythonCourse/pythonic.py | UTF-8 | 1,201 | 4.15625 | 4 | [] | no_license | # pythonic.py
# based on: https://www.youtube.com/watch?v=x3v9zMX1s4s&t=1s
# Duck Typing and Easier to ask forgiveness then persmission (EAFP)
class Duck(object):
def quack(self):
print('Quack, quack')
def fly(self):
print('Flap, flap')
class Person(object):
def quack(self):
print('I am Quacking like a duck!')
def fly(self):
print('I am flapping my arms!')
#def quack_and_fly(thing):
# # not Duck-Typed(non-Pythonic)
# if isinstance(thing, Duck):
# thing.quack()
# thing.fly()
# else:
# print('This has to be a duck!')
#def quack_and_fly(thing):
# # Duck-Typed(Pythonic)
# thing.quack()
# thing.fly()
#def quack_and_fly(thing):
# # LBYL (non-Pythonic)
# if hasattr(thing, 'quack'):
# if callable(thing.quack):
# thing.quack()
#
# if hasattr(thing, 'fly'):
# if callable(thing.fly):
# thing.fly()
def quack_and_fly(thing):
# LBYL (Pythonic)
try:
thing.quack()
thing.fly()
thing.bark() # doesn't exists!
except AttributeError as e:
print(e)
print()
d = Duck()
quack_and_fly(d)
p = Person()
quack_and_fly(p)
| true |
7ca3e0d5522c1a2d7770de81879f159382ec505a | Python | fredsa/pamelafox-samplecode | /petition_au/geocoder.py | UTF-8 | 1,036 | 2.9375 | 3 | [] | no_license | #!/usr/bin/python2.5
#
# Copyright 2009 Google Inc.
# Licensed under the Apache License, Version 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
"""A helper module for geocoding addresses over HTTP.
This module contains a function that sends a call to
the Google Maps API HTTP Geocoder to geocode an address.
"""
import urllib
from google.appengine.api import urlfetch
from google.appengine.ext import db
def GeocodeAddress(address):
"""Retrieves a lat/lng from the geocoder.
Args:
address: The address. Punctuation/case don't matter.
Returns:
A db.GeoPt() object if successful, None otherwise.
"""
base_path = ('http://maps.google.com/maps/geo?output=csv&sensor=false'
'&key=ABQIAAAAndLQTfJ9k_JvMh7lbOFC1RS4My7l3P1CJ6Hnc875WZ'
'oO7BnwWBT9WQb3OhuPByEjaQs33G5wM5s5Ng&q=')
enc_address = urllib.quote_plus(address)
response = urlfetch.fetch(base_path + enc_address)
if response.status_code == 200 and response.content.startswith('200'):
[lat, lng] = [float(x) for x in response.content.split(',')[2:4]]
return db.GeoPt(lat, lng)
return None
| true |
fcf8a089bfec636adb81e75ec2494e596022596b | Python | gdhGaoFei/Python01 | /20181202/正则表达式/zhengzebiaodashi.py | UTF-8 | 3,539 | 4.03125 | 4 | [
"MIT"
] | permissive | '''
什么是正则表达式: 记录文本规则的代码
是一个特殊的字符序列
普通字符串和元字符组成的。其实就是对元字符的学习
'''
import re
reg_str = "124231njsndjnabcskdjkaksobabc>/asd[]中国;."
reg = "abc"
print(re.findall(reg, reg_str))
'''
元字符:
. 匹配除换行符以外的任意字符
\w 匹配字母 或者 数字 或者 下划线 或者 汉子
\s 匹配任意的空白符
\d 匹配数字
\b 匹配单词的开始或者结束
^ 匹配字符串的开始
$ 匹配字符串的结束
'''
print(re.findall("\d", reg_str))
print(re.findall("^124", reg_str))
print(re.findall("\w", reg_str))
'''
反义代码
\W 匹配任意不是字母、下划线、数字、汉字的字符
\S 匹配任意不是空白符的字符
\D 非数字
\B 匹配不是单词开头或者结束的位置
[^] 匹配除了xx以外的任意字符
'''
'''
限定符
* 重复零次或者多次
+ 重复一次或者多次
? 重复零次或者1次
{n} 重复n次
{n,} 重复n次或者更多次
{n, m}重复n到m次
'''
print(re.findall("\d{3}", reg_str))
print(re.findall("[0-9a-z]{3}", reg_str))
ip = "this is ip: 192.168.1.123 , 172.138.2.245"
reg1 = "\d{1,3}.\d+.\d+.\d+"
print(re.findall(reg1, ip))
# search
reg2 = "(\d{1,3}.){3}.\d{1,3}"
result = re.search(reg2, ip)
print(result[0])
'''
search 和 findall
search 只匹配第一个
findall 是匹配所有符合要求的
'''
'''
组匹配
'''
s = "this is phone:13688888888 and this is my postcode:012345"
reg3 = "this is phone:(\d+) and this is my postcode:(\d+)"
result = re.search(reg3, s)
print(result)
result = re.search(reg3, s).group(0)
print(result)
result = re.search(reg3, s).group(1)
print(result)
result = re.search(reg3, s).group(2)
print(result)
# match 只匹配开头的
reg_str1 = "hellopayhsdadHelloasdastring"
reg4 = "Hello"
result = re.match(reg4, reg_str1, re.I).group() # re.I 忽略大小写
print(result)
'''
# 贪婪 与 非贪婪 贪婪与懒惰
什么是贪婪 尽可能多的匹配
非贪婪 尽可能少的匹配
非贪婪操作符:?
这个操作符是用在 * + ? 后边的 要求正则匹配的越少越好
* 重复零次或者更多次 *? 重复零次
+ 重复一次或者更多次 +? 重复一次
? 重复零次或者一次 ?? 重复零次
'''
# 贪婪
reg_tl = "pythonnnnnnnnnHellopython"
reg1 = "python*"
print(re.findall(reg1, reg_tl))
# 非贪婪
reg1 = "python*?"
print(re.findall(reg1, reg_tl))
reg1 = "python+"
print(re.findall(reg1, reg_tl))
reg1 = "python+?"
print(re.findall(reg1, reg_tl))
'''
匹配手机号码
移动:139, 138, 137, 136, 135, 134
150,151, 152, 157, 158, 159
182,183,187,188
联通:130,131,132,185,186,145,166,176
电信:133,153,180,189
'''
def check_cellphone(number):
reg_phone = "^(13[0-9]|14[5]|15([0-3]|[7-9])|16[6]|17[6]|18([0]|[2-3]|[7-9]))\d{8}$"
result = re.findall(reg_phone, number)
if result:
print("匹配成功:", number)
return True
else:
print("匹配失败:", number)
return False
cell_phone = "18819980914"
print(check_cellphone(cell_phone))
'''
验证邮箱的合法性:
新浪 网易 搜狐 QQ
xxx@sina.com
xxx@sina.cn
xxx@163.com
xxx@qq.com
'''
def check_mail(mail):
reg_mail = "^([a-zA-Z0-9_-]+)@([a-zA-Z0-9_-]+).[a-zA-Z0-9_-]{1,6}$"
result = re.findall(reg_mail, mail)
if result:
print("匹配成功:", mail)
return True
else:
print("匹配失败:", mail)
return False
mail = "9661asda@qq.icloud"
print(check_mail(mail))
| true |
990a9be3254b35011cb2bc944ab4c198be40c89c | Python | easternpillar/AlgorithmTraining | /Baekjoon/분리집합/여러분의 다리가 되어 드리겠습니다!.py | UTF-8 | 702 | 3.1875 | 3 | [] | no_license | # Problem:
# Reference: https://www.acmicpc.net/problem/17352
# My Solution:
import sys
sys.setrecursionlimit(10**9)
def find(target):
if parent[target] == target:
return parent[target]
parent[target] = find(parent[target])
return parent[target]
def union(a, b):
ta, tb = find(a), find(b)
if ta != tb:
parent[ta] = tb
N = int(sys.stdin.readline().rstrip())
parent = [i for i in range(N + 1)]
for _ in range(N - 2):
f, t = map(int, sys.stdin.readline().split())
if find(f) != find(t):
union(f, t)
s = set()
answer=[]
for i in range(1, N + 1):
temp=find(i)
if temp not in s:
s.add(temp)
answer.append(temp)
print(*answer) | true |
ecfe0722c73230e542f43c0d626c298bafdbab6b | Python | MePankaj07/Python_Practice | /CelToFeh.py | UTF-8 | 221 | 4.25 | 4 | [] | no_license | def CelToFeh():
Cel_Input = float(input("Ente a number to convert it to fehrenheit : "))
ResFehren = (Cel_Input * 1.8) + 32
print(f"{Cel_Input} degree Celsius to {ResFehren} degree Fehrenheit ")
CelToFeh() | true |
a1bfae8f00f28ee3dfff370e790c594bbc4f2118 | Python | maheswarasunil/pythonprogramming | /word_counter.py | UTF-8 | 265 | 2.828125 | 3 | [] | no_license | #!/usr/bin/python
#
# Python script to word repitations in file.
#
word_counter = {}
file = open("test.txt","r")
for word in file.read().split():
if word in word_counter:
word_counter[word]+=1
else:
word_counter[word]=1
print word_counter | true |
c82dd5ce6d770924f1eab7bb310ff31be7859f74 | Python | kmustzjq/StudyPython | /GridSearch_SVC.py | UTF-8 | 2,145 | 2.828125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 20 15:52:36 2021
@author: M172468
"""
#import all necessary libraries
#import sklearn
from sklearn.datasets import load_breast_cancer
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.datasets import load_breast_cancer
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
#load the dataset and split it into training and testing sets
dataset = load_breast_cancer()
X=dataset.data
Y=dataset.target
X_train, X_test, y_train, y_test = train_test_split(
X,Y,test_size = 0.30, random_state = 101)
# train the model on train set without using GridSearchCV
model = SVC()
model.fit(X_train, y_train)
# print prediction results
predictions = model.predict(X_test)
print(classification_report(y_test, predictions))
# defining parameter range
param_grid = {'C': [0.1, 1, 10, 100],
'gamma': [1, 0.1, 0.01, 0.001, 0.0001],
# 'gamma':['scale', 'auto'],
'kernel': ['linear']}
grid = GridSearchCV(SVC(), param_grid, refit = True, verbose = 3,n_jobs=-1)
# fitting the model for grid search
grid.fit(X_train, y_train)
# print best parameter after tuning
print(grid.best_params_)
grid_predictions = grid.predict(X_test)
# print classification report
print(classification_report(y_test, grid_predictions))
##########################################################################
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
from sklearn import datasets
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
digits = datasets.load_digits()
X = digits.data
y = digits.target
clf_ = SVC(kernel='rbf')
Cs = [1, 10, 100, 1000]
Gammas = [1e-3, 1e-4]
clf = GridSearchCV(clf_,
dict(C=Cs,
gamma=Gammas),
cv=2,
pre_dispatch='1*n_jobs',
n_jobs=1)
clf.fit(X, y)
print(clf.best_params_)
| true |
eba74a9577fae693528f9c268f6130d418e9abf8 | Python | cerchiariluiza/CodigosScrapsCompiladosPython | /8SacrpyFramework/exemplo03.py | UTF-8 | 241 | 2.546875 | 3 | [] | no_license | from scrapy import Selector
from urllib.request import urlopen
html = urlopen("https://www.pythonparatodos.com.br/formulario.html")
sel = Selector(text = html.read())
lista = sel.xpath('//input[@type="text"]')
print(lista.extract_first())
| true |
80ed1a899893a774ad558128779219612592b6ee | Python | davidhuangdw/leetcode | /python/91_DecodeWays.py | UTF-8 | 1,139 | 3.21875 | 3 | [] | no_license | from unittest import TestCase
# https://leetcode.com/problems/decode-ways
class DecodeWays(TestCase):
def numDecodings(self, s: 'str') -> 'int':
pp, pre, below_six, a = 0, 1, "0123456", ''
for b in s:
if not (pp or pre): break
cnt = (pre if b != '0' else 0) + \
(pp if a == '1' or (a == '2' and b in below_six) else 0)
pp, pre, a = pre, cnt, b
return pre
# use int()
# def numDecodings(self, s: 'str') -> 'int':
# pp, pre, a = 0, 1, ''
# for b in s:
# if not (pp or pre): break
# cnt = (pre if b != '0' else 0) + \
# (pp if 9 < int(a+b) < 27 else 0)
# pp, pre, a = pre, cnt, b
# return pre
def test1(self):
self.assertEqual(2, self.numDecodings("12"))
def test2(self):
self.assertEqual(3, self.numDecodings("226"))
def test3(self):
self.assertEqual(0, self.numDecodings("012"))
def test4(self):
self.assertEqual(1, self.numDecodings("10"))
def test5(self):
self.assertEqual(1, self.numDecodings("27"))
| true |
3156457be0e1de0ee5bf5160b72be857898f69a4 | Python | huseyindalbudak/mathpy | /gamesAlgorithms/islemGames.py | UTF-8 | 1,656 | 3.21875 | 3 | [
"MIT"
] | permissive | import numpy as np
# this code is wrote for a Bir Kelime Bir Islem game
# It estimates the math operation among many number with respec to a result
def feval(funcName, *args):
return eval(funcName)(*args)
def topla(x,y):
toplam = x+y
return toplam
def cikar(x,y):
cikarim = x-y
return cikarim
def carp(x,y):
carp = x*y
return carp
def bol(x,y):
if y != 0:
#bol =np.float(x)/y
bol = np.float(x)/y
else:
bol = 0
return bol
def recEleman(el1,el2,funcname):
print el1,funcname,el2
def tislem(args):
#args = np.array(args)
#args = args.tolist()
numEleman = np.size(args)
islemSirasi = np.random.randint(4)
islemArray = ['topla', 'cikar','carp','bol']
funcname = islemArray[islemSirasi]
elemanSirasi1 = np.random.randint(numEleman)
eleman1 = args[elemanSirasi1]
args.remove(eleman1)
elemanSirasi2 = np.random.randint(numEleman-1)
eleman2 = args[elemanSirasi2]
#print eleman1,eleman2,islemSirasi
sonuc = feval(funcname, eleman1, eleman2)
args.remove(eleman2)
args.insert(0,sonuc)
recEleman(eleman1,eleman2,funcname)
return args
def dondur(girdi):
num = 2 #for while loop it is not important
while num>1:
girdi = tislem(girdi)
num = np.size(girdi)
#print girdi
return girdi
bayrak =1
it = 0
while bayrak==1:
girdi = dondur([13,12,3,4])
print 'olmamis',girdi
girdim = girdi[0]
if girdim == 27:
print 'oldu', girdim
bayrak = 0
else:
it = it +1
bayrak = 1
print 'girdi',girdim
print 'total iteration',it
| true |
6f0e4a915c36c23cbfcd0134d8f4244348258b82 | Python | Mateus-Silva11/AulasPython | /Aula_4/Aula4(if).py | UTF-8 | 692 | 3.796875 | 4 | [
"MIT"
] | permissive | idade = 17.5
# If simples, validação de apenas uma condição
if idade == 18:
print('Maior')
# if com else, caso a condicão validada pelo if não seja verdadeira, o else é executado
if idade < 18:
print('Menor')
else:
print('Maior')
# if com ELIF e else Caso a condição do validada no if seja falsa é validado a condição do ELIF caso a condição do elif seja falsa else é executado
if idade < 18:
print('Menor')
elif idade==18:
print('sla')
else:
print('Maior')
#if com variavel booleana em caso de variavel booleana, não é necessario a validação(==True) Pois o If ja valida o se o conteúdo da variável é True, senão vai para o Else
| true |
b41bc01bf323a9823c0c2c7e17ccb49040f59c63 | Python | Rifleman354/Python | /Python Crash Course/Chapter 4 Exercises/FavVehicles.py | UTF-8 | 316 | 2.9375 | 3 | [] | no_license | Favorite_Vehicles = ['Shadowswords', 'Kastelan Robot', 'Leman Russ Tanks', 'Basilisks']
for Favorite_Vehicles in Favorite_Vehicles:
print('I need at least 5 ' + Favorite_Vehicles.title() + ' in all my deployments!')
print("\nI love vehicles!")
# Prints a for loop for the list specified in "Favorite_Vehicles"
| true |
276d9563489d3a76e5f52a00026bc661282a0c1e | Python | 2448845600/LeetCodeDayDayUp | /LeetCode题解/id123.py | UTF-8 | 577 | 3.109375 | 3 | [
"MIT"
] | permissive | class Solution:
def maxProfit(self, prices) -> int:
n = len(prices)
dp = [[0 for _ in range(3)] for _ in range(n)]
for k in range(1, 3):
prof = dp[0][k - 1] - prices[0]
for i in range(1, n):
prof = max(prof, dp[i][k - 1] - prices[i])
dp[i][k] = max(dp[i - 1][k], prices[i] + prof)
return max(dp[-1][1], dp[-1][2])
if __name__ == '__main__':
s = Solution()
# print(s.maxProfit([2, 1, 2, 0, 1]))
print(s.maxProfit([7, 6, 4, 3, 1]))
print(s.maxProfit([1, 2, 3, 4, 5]))
| true |
5fe027d24aecd5b913c15159c3d1cc2df899cb98 | Python | KIMGEEK/Python-Ruby_training | /Loop/5.py | UTF-8 | 76 | 3.015625 | 3 | [] | no_license | i = 0
while i<10:
if i != 4:
print(i)
i= i+1
pass
| true |
6ea8488241d3f20cb0d340d30b785a753ee2baa0 | Python | sriharish01/Project-Euler | /#56.py | UTF-8 | 189 | 2.78125 | 3 | [
"MIT"
] | permissive | n= int (raw_input())
maxx=0
for i in xrange(1,n):
for j in xrange(1,n):
a=sum(map(int,str(i**j)))
if a>maxx:
maxx=a
print maxx
| true |
5d34d0334cf0314b4b31ebb6d7e48a9a745daab6 | Python | jortiz-hi/TFM | /preprocessing.py | UTF-8 | 1,365 | 2.734375 | 3 | [] | no_license | import pickle
import pandas as pd
import numpy as np
# se cargan los datos serializados en una variable diccionario donde se establecen los keypoints
inp = './pose-net/posenet-pytorch/cl02_cam1_s1_a4_R04_png.pickle'
with open(inp, 'rb') as data_serialized:
dic_kp = pickle.load(data_serialized)
# se filtran los keypoints relevantes (se quita ojos y orejas -4-)
kp_frames = []
for i in range(len(dic_kp.values())):
kp_values = list(dic_kp.values())[i][0].tolist()
del kp_values[1:5]
kp_frames.append(kp_values)
df_kp = pd.DataFrame(kp_frames, index=list(dic_kp.keys()))
# se crea la lista de tuplas de mag y ang ([M, A]) para cada kp de cada frame, [2 (x, y) x 13 (keypoints) x f (frames)]
T = []
for f in range(len(df_kp.index)-1):
t = []
for g in range(len(df_kp.values[0])):
M = np.sqrt(np.square(df_kp.values[f+1][g][0] - df_kp.values[f][g][0]) +
np.square(df_kp.values[f+1][g][1] - df_kp.values[f][g][1]))
A = np.arctan((df_kp.values[f+1][g][1] - df_kp.values[f][g][1]) /
(df_kp.values[f+1][g][0] - df_kp.values[f][g][0]))
t.append([M, A])
T.append(t)
# se serializan los datos de salida para la red LSTM
print(np.array(T).shape)
name = input.split('.')[0] + '_tupla' +'.pickle'
print(name)
filename = open("tupla.pickle", "wb")
pickle.dump(T, filename)
| true |
a31f723759e9109a1921fb732a6d3db31dddd3ed | Python | RohanChacko/Public-Arena-Booking-Web-App | /app/utility.py | UTF-8 | 1,440 | 2.71875 | 3 | [] | no_license | from app import db
import time
def get_event_data_single(event):
venue_name = db.engine.execute("SELECT name FROM venues WHERE id == :id", {'id': event[3]}).fetchall()[0][0]
try:
creator = db.engine.execute("SELECT username FROM user WHERE id == :id", {'id': event[4]}).fetchall()[0][0]
except:
creator = ''
date = time.strftime("%d/%m/%Y", time.localtime(event[5]))
start = time.strftime("%H:%M", time.localtime(event[5]))
end = time.strftime("%H:%M", time.localtime(event[6]))
return {'id': event[0], 'name': event[1], 'description': event[2], 'date': date, 'start_time': start, 'end_time': end, 'venue': venue_name, 'creator': creator, 'tags': ' #'.join(event[7].split('#')), 'type': ['Public', 'Private'][event[8]]}
def get_event_data_multiple(query_list):
event_list = list()
for event in query_list:
# venue_name = db.engine.execute("SELECT name FROM venues WHERE id == :id", {'id': event[3]}).fetchall()[0][0]
# try:
# creator = db.engine.execute("SELECT username FROM user WHERE id == :id", {'id': event[4]}).fetchall()[0][0]
# except:
# creator = ''
# date = time.strftime("%d/%m/%Y", time.localtime(event[5]))
# start = time.strftime("%H:%M", time.localtime(event[5]))
# end = time.strftime("%H:%M", time.localtime(event[6]))
event_list.append(get_event_data_single(event))
return event_list
| true |
97a47d0778e838353fc8ce8c567481bfdc35346f | Python | veselovmark/CS120DataAnalysis | /SemanticLocation/show_accuracy.py | UTF-8 | 1,206 | 2.71875 | 3 | [] | no_license |
# coding: utf-8
# In[15]:
import pickle
import numpy as np
with open('accuracy.dat') as f:
aucs, confs, labels = pickle.load(f)
f.close()
with open('top10.dat') as f:
state_top10 = pickle.load(f)
f.close()
auc = list(np.array([]) for i in range(len(state_top10)))
for (i,state) in enumerate(state_top10):
auc[i] = np.array([])
for (j,lab) in enumerate(labels):
if state in lab:
ind = np.where(lab==state)[0]
auc[i] = np.append(auc[i], aucs[j][ind])
auc_mean = np.array([])
auc_ci = np.array([])
for (i, a) in enumerate(auc):
print state_top10[i]
auc_mean = np.append(auc_mean, np.nanmean(a))
auc_ci = np.append(auc_ci, 2*np.nanstd(a)/np.sqrt(208))
# In[16]:
import matplotlib.pyplot as plt
get_ipython().magic(u'matplotlib inline')
plt.figure(figsize=(12,5))
plt.barh(range(len(auc_mean)), auc_mean, xerr=auc_ci, align='center', color=(.3,.5,1), alpha=0.9, ecolor=(0,0,0))
plt.xlabel('AUC',fontsize=15,color=(0,0,0))
axes = plt.gca()
axes.set_ylim([-1, len(auc_mean)])
axes.set_xlim([0, 1])
plt.yticks(range(len(auc_mean)), state_top10, fontsize=15, color=(0,0,0));
plt.plot([.5, .5], [-1, len(auc_mean)],color=(0,0,0))
print auc_mean
| true |
bf70d4de1b2f1151d97e95bf6f589b3b68ab38c7 | Python | astrojysun/COinTIGRESS | /module/map_circular_beam.py | UTF-8 | 1,644 | 3.03125 | 3 | [] | no_license | import numpy as np
import math
from scipy.integrate import quad
def get_gauss_stamp(n):
nx = n
ny = n
nxc = nx/2
nyc = ny/2
ix = np.zeros((nx, ny))
iy = np.zeros((nx, ny))
for i in range(nx):
for j in range(ny):
ix[i, j] = j-nyc
iy[i, j] = i-nxc
def gauss(x):
sigmax = 0.5
ret = 1./(np.sqrt(2*math.pi)*sigmax) * np.exp(-0.5*(x/sigmax)**2)
return ret
stamp = np.zeros((nx, ny))
for i in range(nx):
for j in range(ny):
x1 = ix[i, j] - 0.5
x2 = x1 + 1.
y1 = iy[i, j] - 0.5
y2 = y1 + 1.
inte = quad(gauss, x1, x2)[0] * quad(gauss, y1, y2)[0]
stamp[i, j] = inte
return stamp
#average data using a stamp
def stamp_avg(data, stamp):
nxd, nyd = data.shape
nxs, nys = stamp.shape
ret = np.zeros(data.shape)
nxc = nxs/2
nyc = nys/2
ix = np.zeros((nxs, nys))
iy = np.zeros((nxs, nys))
for i in range(nxs):
for j in range(nys):
ix[i, j] = i-nxc
iy[i, j] = j-nyc
for i in range(nxd):
for j in range(nyd):
for istamp in range(nxs):
for jstamp in range(nys):
iret = i + ix[istamp, jstamp]
jret = j + iy[istamp, jstamp]
if (iret >= 0) and (iret < nxd
) and (jret >= 0) and (jret < nyd):
ret[iret, jret] += data[i, j]*stamp[istamp, jstamp]
return ret
def map_circular_beam(data, nstamp=9):
stamp = get_gauss_stamp(nstamp)
return stamp_avg(data, stamp)
| true |
4407523c90157d2a26bc177ddf9029ec013093b5 | Python | XuQiao/codestudy | /python/pythonfordataanalysis/pythonplot.py | UTF-8 | 9,293 | 2.859375 | 3 | [] | no_license | plot(np.arange(10))
close()
fig = plt.figure()
fig = plt.figure(2)
ax1=fig.add_subplot(2,2,1)
fig = plt.figure()
ax1=fig.add_subplot(2,2,1)
ax1=fig.add_subplot(2,2,2)
ax1=fig.add_subplot(2,2,3)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
from numpy.random import randn
plt.plot(randn(50).cumsum(),'k--')
_ = ax1.hist(randn(100),bins=20,color='k',alpha=0.3)
close()
ax1=fig.add_subplot(2,2,2)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
fig = plt.figure()
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
plt.plot(randn(50).cumsum(),'k--')
_ = ax1.hist(randn(100),bins=20,color='k',alpha=0.3)
ax2 = scatter(np.arange(30),np.arange(30)+3.randn(30))
ax2 = scatter(np.arange(30),np.arange(30)+3*randn(30))
ax2
ax3=fig.add_subplot(2,2,3)
plt.plot(randn(50).cumsum(),'k--')
ax2.scatter(np.arange(30),np.arange(30)+3*randn(30))
ax2
fig, axes= plt.subplots(2,3)
axes
import matplotlib.pyplot as plt
plt
fig, axes= plt.subplots(2,3)
axes
axes.ndim
axes[0,1]
axes[0,1].nrows
axes.nrows
subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=None,hspace=None)
fig,axes=plt.subplots(2,2,sharex=True,sharey=True)
for i in range(2):
for j in range(2):
axes[i,j].hist(randn(500),bins=50,color='k',alpha=0.5)
plt.subplots_adjust(wspace=0,hspace=0)
ax.plot(x,y,'g--')
plot(x,y,'g--')
axes.plot(x,y,'g--')
ax1.plot(x,y,'g--')
plt.plot(randn(30).cumsum(),'ko--')
close()
close()
close()
close()
plt.plot(randn(30).cumsum(),'ko--')
plot(randn(30).cumsum(),color='k',linestyle='dashed',marker='o')
data=randn(30).cumsum()
plt.plot(data,'k--',label='Default')
plt.plot(data,'k--',drawstyle='steps-post',label='steps-post')
plt.legend(loc='best')
plt.xlim()
plt.xlim([0,10])
fig = plt.figure();ax=fig.add_subplot(1,1,1)
ax.plot(randn(1000).cumsum())
ticks = ax.set_xticks([0,250,500,750,1000])
labels = ax.set_xticklabels(['one','two','three','four','five'],rotation=30,fontsize='small')
ax.set_title('My first matplotlib plot')
ax.set_xlabel('Stages')
fig=plt.figure();ax=fig.add_subplot(1,1,1)
ax.plot(randn(1000).cumsum(),'k',label='one')
ax.plot(randn(1000).cumsum(),'k--',label='two')
ax.plot(randn(1000).cumsum(),'k.',label='three')
ax.legend(loc='best')
ax.text(x,y,'hello world!',family='monospace',fontsize=10)
ax.text(1,2,'hello world!',family='monospace',fontsize=10)
ax.text(-80,2,'hello world!',family='monospace',fontsize=10)
ax.text(2,-80,'hello world!',family='monospace',fontsize=10)
close()
from datetime import datetime
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
data = pd.read_csv('pydata-book/ch08/spx.csv',index_col=0,parse_dates=True)
import pandas as pd
data = pd.read_csv('pydata-book/ch08/spx.csv',index_col=0,parse_dates=True)
spx = data['SPX']
spx.plot(ax=ax,style='k-')
crisis_data = [(datetime(2007,10,10),'Peak of bull market'),(datetime(2008,3,12),'Bear Sterns Fails'),datetime(2008,9,15),'Lehman Bankruptcy']
for date, label in crisis_data:
ax.annotate(label,xy=(date, spx.asof(date) + 50), xytext=(date, spx.asof(date) + 200), arrowprops=dict(facecolor='black'),horizontalalignment='left',verticalalignment='top')
crisis_data
for date, label in crisis_data:
ax.annotate(label,xy=(date, spx.asof(date) + 50), xytext=(date, spx.asof(date) + 200), arrowprops=dict(facecolor='black'),horizontalalignment='left',verticalalignment='top')
spx.asof(date)
date
label
crisis_data = [(datetime(2007,10,10),'Peak of bull market'),(datetime(2008,3,12),'Bear Sterns Fails'),(datetime(2008,9,15),'Lehman Bankruptcy')]
for date, label in crisis_data:
ax.annotate(label,xy=(date, spx.asof(date) + 50), xytext=(date, spx.asof(date) + 200), arrowprops=dict(facecolor='black'),horizontalalignment='left',verticalalignment='top')
ax.set_xlim(['1/1/2017','1/1/2011']
)
ax.set_ylim([600,800])
ax.set_title('Important dates in 2008-2009 financial crisis')
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
rect=plt.Rectangle((0.2,0.75),0.4,0.15,color='k',alpha=0.3)
circ=plt.Circle((0.7,0.2),0.15,color='b',alpha=0.3)
pgon = plt.Polygon([[0.15,0.15],[0.35,0.4],[0.2,0.6]],color='g',alpha=0.5)
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)
close()
close()
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
spx = data['SPX']
spx.plot(ax=ax,style='k-')
ax.set_title('Important dates in 2008-2009 financial crisis')
for date, label in crisis_data:
ax.annotate(label,xy=(date, spx.asof(date) + 50), xytext=(date, spx.asof(date) + 200), arrowprops=dict(facecolor='black'),horizontalalignment='left',verticalalignment='top')
ax.set_xlim(['1/1/2017','1/1/2011'])
ax.set_xlim(['1/1/2007','1/1/2011'])
ax.set_ylim([600,800])
ax.set_ylim([600,1800])
plt.savefig('figpath.pdf')
plt.savefig('figpath.png',dpi=400,bbox_inches='tight')
from io import StringIO
buffer = StringIO()
plt.savefig(buffer)
plot_data = buffer.getvalue()
plt.rc('figure',figsize=(10,10))
font_options={'family':'monospace','weight':'bold','size':'small'}
plt.rc('font',**font_options)
font_options={'family':'monospace','weight':'bold','size':'small'}
plt.rc('font',**font_options)
s=Series(np.random.randn(10).cumsum(), index=np.arange(0,100,10))
import numpy
s=Series(np.random.randn(10).cumsum(), index=np.arange(0,100,10))
from numpy import *
s=Series(np.random.randn(10).cumsum(), index=np.arange(0,100,10))
from pandas import *
s=Series(np.random.randn(10).cumsum(), index=np.arange(0,100,10))
s.plot()
s=Series(np.random.randn(10).cumsum(), index=np.arange(0,100,10))
s
s
s.plot()
np.random.randn(10).cumsum()
np.arange(0,100,10)
s
s.plot()
df= DataFrame(np.random.randn(10,4).cumsum(0), columns=['A','B','C','D'],index=np.arange(0,100,10))
df
df.plot()
fig.axes=plt.subplots(2,1)
fig.axes=plt.subplots(2,1)
fig,axes=plt.subplots(2,1)
data=Series(np.random.rand(16),index=list('abcdefghijklmnop'))
data.plot(kind='bar',ax=axes[0],color='k',alpha=0.7_
)
data.plot(kind='bar',ax=axes[0],color='k',alpha=0.7)
data.plot(kind='barh',ax=axes[1],color='k',alpha=0.7)
df = DataFrame(np.random.rand(6,4),index=['one','two','three','four','five','six'],columns=pd.Index(['A','B','C','D'],name='Genus'))
df
df.plot(kind='bar')
df.plot(kind='barh',stacked=True,alpha=0.5)
close()
close()
close()
close()
df.values
tips=pd.read_csv('pydata-book/ch08/tips.csv')
party_counts=pd.crosstab(tips.day,tips.size_
)
party_counts=pd.crosstab(tips.day,tips.size)
party_counts
party_counts=pd.crosstab(tips.day,tips.size)
party_counts
party_counts = party_counts.ix[:,2:5]
party_counts
tips
tips['tip_pct'] = tips['tip']/tips['total_bill']
tips['tip_pct'].hist(bins=50)
tips['tip_pct'].plot(kind='kde')
comp1 = np.random.normal(0,1,size=200)
comp2 = np.random.normal(10,2,size=200)
values= Series(np.concatenate([comp1,comp2])
)
values.hist(bins=100,alpha=0.3,color='k',normed=True)
values.plot(kind='kde',style='k--')
values
macrp = pd.read_csv('pydata-book/ch08/macrodata.csv')
data=macrp[['cpi','m1','tbilrate','unemp']]
trans_data = np.log(data).diff().dropna()
trans_data[-5:]
plt.scatter(trans_data['m1'],trans_data['unemp'])
close
close()
plt.scatter(trans_data['m1'],trans_data['unemp'])
plt.title('Change in log %s vs. log %s' % ('m1', 'unemp'))
scatter_matrix(trans_data,diagonal='kde',color='k',alpha=0.3)
scatter_matrix(trans_data,diagonal='kde',alpha=0.3)
close()
close()
close()
data = pd.read_csv('pydata-book/ch08/Haiti.csv')
data
data[['INCIDENT DATE', 'LATTITUDE','LONGITUDE'][:10]
]
data[['INCIDENT DATE', 'LATTITUDE','LONGITUDE']][:10]
data[['INCIDENT DATE', 'LATITUDE','LONGITUDE']][:10]
data['CATEGORY'][:6]
data.describe()
data = data[(data.LATITUDE>18) & (data.LATITUDE < 20) & (data.LONGITUDE>-75) & (data.LONGITUDE<-70) & data.CATEGORY.notnull()]
data
def to_cat_list(catstr):
stripped = (x.strip() for x in catstr.split(','))
def to_cat_list(catstr):
stripped = (x.strip() for x in catstr.split(','))
return [x for x in stripped if x]
def get_all_categories(cat_series):
cat_sets = (set(to_cat_list(x)) for x in cat_series)
return sorted(set.union(*cat_sets))
def get_englist(cat):
code, name = cat.split(',')
code, name = cat.split('.')
if '|' in name:
name = name.split(' | ')[1]
def get_englist(cat):
code, name = cat.split(',')
code, name = cat.split('.')
if '|' in name:
name = name.split(' | ')[1]
return code, name.strip()
get_englist('2. Urgences logistiques | Vital Lines')
def get_englist(cat):
code, name = cat.split('.')
if '|' in name:
name = name.split(' | ')[1]
return code, name.strip()
def get_englist(cat):
code, name = cat.split('.')
if '|' in name:
name = name.split(' | ')[1]
return code, name.strip()
get_englist('2. Urgences logistiques | Vital Lines')
all_cats = get_all_categories(data.CATEGORY)
english_mapping = dict(get_englist(x) for x in all_cats)
english_mapping['2a']
english_mapping['6c']
def get_code(seq):
return [x.split('.')[0] for x in seq if x]
all_codes = get_code(all_cats)
code_index = pd.Index(np.unique(all_codes))
dummy_frame = DataFrame(np.zeros((len(data), len(code_index))), index= data.index, columns=code_index)
dummy_frame.ix[:,:6]
for row, cat in zip(data.index, data.CATEGORY):
codes = get_code(to_cat_list(cat))
dummy_frame.ix[row, codes] = 1
data = data.join(dummy_frame.add_prefix('category_'))
data.ix[:,10:15]
from mpl_toolkits.basemap import Basemap
from mpl_toolkits import Basemap
| true |
821429af10e7cb825e60b6a04115b5fd39288b26 | Python | LuisOlCo/Semantic_Similarity | /loss_functions.py | UTF-8 | 854 | 2.96875 | 3 | [] | no_license | import torch
import torch.nn as nn
class CosineSimilarityLoss(nn.Module):
'''
Loss function, computes cosine similarity from for batch of sentence embeddings
'''
def __init__(self, model, loss_fct = nn.MSELoss(), cos_score_transformation=nn.Identity()):
super(CosineSimilarityLoss, self).__init__()
self.model = model
self.loss_fct = loss_fct
#self.cos_score_transformation = cos_score_transformation
def forward(self, sentences_information, labels):
embeddings = [self.model(sentence_information)['sentence_embedding'] for sentence_information in sentences_information]
#output = self.cos_score_transformation(torch.cosine_similarity(embeddings[0], embeddings[1]))
output = torch.cosine_similarity(embeddings[0], embeddings[1])
return self.loss_fct(output, labels)
| true |
cf57d03f4bbe8999ea48e7462edb6c30e8bee53f | Python | PlumpMath/designpatterns-428 | /Prototype/vehicle_cache.py | UTF-8 | 1,045 | 3.359375 | 3 | [] | no_license | #!/usr/bin/env python
from car import Car
from bus import Bus
from three_wheel import ThreeWheel
class VehicleCache(object):
"""Cache class for the vehicle types
_vehicle_dict keeps track of the 3 types of vehicles mentioned here. For
requesting type of vehicles, new vehicle is created by deep copying the
existing vehicle caches of _vechicle_dict. get_vehicle() returns None
unless load_cache() is not called before.
Attributes:
_vehicle_dict: cache dictionary of vehicles (str => Vehicle)
"""
_vehicle_dict = {}
@classmethod
def load_cache(cls):
"""Load cache objects before get_vehicle() method"""
car = Car()
cls._vehicle_dict["car"] = car
bus = Bus()
cls._vehicle_dict["bus"] = bus
three_wheel = ThreeWheel()
cls._vehicle_dict["three wheel"] = three_wheel
@classmethod
def get_vehicle(cls, vehicle_type = None):
"""Get vehicle for given typename of the vehicle"""
try:
if not vehicle_type:
return None
else:
return cls._vehicle_dict[vehicle_type]
except KeyError:
return None
| true |
cda43141b8c690145ab640a06b6791e8da7854a2 | Python | KevHg/tictactoe-cli | /main.py | UTF-8 | 7,950 | 3.703125 | 4 | [
"MIT"
] | permissive | import random
from copy import deepcopy
def print_board(board, max_width):
for row in range(len(board)):
for col in range(len(board)):
print("{:>{}}".format(board[row][col], max_width), end='')
print()
def win_check(board, player, n, row, col):
horizontal, vertical, diagonal_down, diagonal_up = True, True, True, True
# Check for horizontal win
for i in range(n):
if board[row][i] != player:
horizontal = False
# Check for vertical win
for i in range(n):
if board[i][col] != player:
vertical = False
# check for downwards diagonal (i.e. top left to bottom right)
for i in range(n):
if board[i][i] != player:
diagonal_down = False
# Check for upwards diagonal (i.e. bottom left to top right)
for i in range(n):
if board[i][n - 1 - i] != player:
diagonal_up = False
return horizontal or vertical or diagonal_down or diagonal_up
def vs_bot(board, n, possible_moves, difficulty):
max_width = len(str(n ** 2)) + 1
while True:
print_board(board, max_width)
num = int(input("Player - Input location: "))
if num < 0 or num >= (n ** 2):
print("Please choose a valid location!")
continue
row = num // n
col = num % n
if board[row][col] == 'O' or board[row][col] == 'X':
print("Cannot replace a player's piece!")
continue
board[row][col] = 'O'
possible_moves.remove(num)
if win_check(board, 'O', n, row, col):
print_board(board, max_width)
print("You win!")
break
if not possible_moves:
print_board(board, max_width)
print("Draw! Board is full.")
break
# Bot move begins here
print("Bot is thinking...")
bot_num = -1
check = random.randint(0, 100)
# Medium difficulty - 50% chance of bot being easy, 50% chance being abyssal
if difficulty == 2:
if check <= 50:
difficulty = 0
else:
difficulty = 4
# Hard difficulty - 20% chance of bot being easy, 80% chance being abyssal
elif difficulty == 3:
if check <= 20:
difficulty = 0
else:
difficulty = 4
print(possible_moves)
# Easy difficulty - Bot selects a random move
if difficulty == 1:
bot_num = random.choice(possible_moves)
# Abyssal difficulty - Bot utilizes minimax to find optimal move
elif difficulty == 4:
temp, bot_num = minimax(board, n, possible_moves, True)
if bot_num == -1:
print("Bot has forfeited! You won!")
break
row = bot_num // n
col = bot_num % n
board[row][col] = 'X'
possible_moves.remove(bot_num)
if win_check(board, 'X', n, row, col):
print_board(board, max_width)
print("You lost!")
break
if not possible_moves:
print_board(board, max_width)
print("Draw! Board is full.")
break
# Returns winning player (O or X), or D if draw
def find_winner(board, n):
for i in range(n):
horizontal = True
for j in range(0, n - 1):
if board[i][j] == '.':
break
if board[i][j] != board[i][j + 1]:
horizontal = False
if horizontal:
return board[i][0]
for i in range(n):
vertical = True
for j in range(0, n - 1):
if board[j][i] == '.':
break
if board[j][i] != board[j + 1][i]:
vertical = False
if vertical:
return board[0][i]
diagonal_down = True
for i in range(0, n - 1):
if board[i][i] == '.':
break
if board[i][i] != board[i + 1][i + 1]:
diagonal_down = False
if diagonal_down:
return board[0][0]
diagonal_up = True
for i in range(0, n - 1):
if board[i][n - 1 - i] == '.':
break
if board[i][n - 1 - i] != board[i + 1][n - 2 - i]:
diagonal_up = False
if diagonal_up:
return board[0][n - 1]
return 'D'
def minimax(board, n, possible_moves, maximizing_player):
best_move = -1
if not possible_moves:
winner = find_winner(board, n)
if winner == 'O':
return -1, best_move
elif winner == 'X':
return 1, best_move
else:
return 0, best_move
if maximizing_player:
value = -10
for move in possible_moves:
new_board = deepcopy(board)
new_possible = deepcopy(possible_moves)
row = move // n
col = move % n
new_board[row][col] = 'X'
new_possible.remove(move)
new_value, new_move = minimax(new_board, n, new_possible, False)
if new_value > value:
value = new_value
best_move = move
return value, best_move
else:
value = 10
for move in possible_moves:
new_board = deepcopy(board)
new_possible = deepcopy(possible_moves)
row = move // n
col = move % n
new_board[row][col] = 'O'
new_possible.remove(move)
new_value, new_move = minimax(new_board, n, new_possible, True)
if new_value < value:
value = new_value
best_move = move
return value, best_move
def vs_player(board, n, possible_moves):
max_width = len(str(n ** 2)) + 1
player = 'O'
while True:
print_board(board, max_width)
num = int(input("Player " + player + " - Input location: "))
if num < 0 or num >= (n ** 2):
print("Please choose a valid location!")
continue
row = num // n
col = num % n
if board[row][col] == 'O' or board[row][col] == 'X':
print("Cannot replace a player's piece!")
continue
board[row][col] = player
possible_moves.remove(num)
if not possible_moves:
print_board(board, max_width)
print("Draw! Board is full.")
break
if win_check(board, player, n, row, col):
print_board(board, max_width)
print("Player " + player + " wins!")
break
if player == 'O':
player = 'X'
else:
player = 'O'
def main():
while True:
n = int(input("Input size of tic-tac-toe board: "))
if n > 1:
break
else:
print("Board cannot be smaller than size 2!")
board = []
possible_moves = []
for i in range(n):
new_row = []
for j in range(n):
new_row.append(i * n + j)
possible_moves.append(i * n + j)
board.append(new_row)
print("Select game mode:")
while True:
print("1 - Easy bot")
print("2 - Medium bot")
print("3 - Hard bot")
print("4 - Abyssal bot (You're not expected to win!)")
print("5 - Multiplayer")
play_type = int(input("Your choice: "))
if play_type == 1:
vs_bot(board, n, possible_moves, 1)
break
elif play_type == 2:
vs_bot(board, n, possible_moves, 2)
break
elif play_type == 3:
vs_bot(board, n, possible_moves, 3)
break
elif play_type == 4:
vs_bot(board, n, possible_moves, 4)
break
elif play_type == 5:
vs_player(board, n, possible_moves)
break
else:
print("Invalid option!")
print("Game over! Press return to close...")
input()
main()
| true |
7278816a5fd10ce503091a4b9b8e97907aef38c5 | Python | HSx3/SWEA | /D3/4676_늘어지는소리만들기.py | UTF-8 | 347 | 2.65625 | 3 | [] | no_license | import sys
sys.stdin = open("4676_input.txt")
T = int(input())
for test_case in range(1, T+1):
data = list(input())
H = int(input())
hyphen = list(map(int, input().split()))
temp = data + ['']
count = 0
check = []
for i in hyphen:
temp[i] = '-'+temp[i]
print('#{} {}'.format(test_case, ''.join(temp)))
| true |
f9317a9d9919b62615e853d0e7bc1f414bbd7cf3 | Python | JMine97/ProblemSolvingByPy | /week3/JeongMin/수들의합2_2003.py | UTF-8 | 613 | 3.09375 | 3 | [] | no_license | import sys
input=sys.stdin.readline
n, m = map(int, input().split())
a=list(map(int, input().split()))
cnt=0
start=0
sum=0
for end in range(n):
sum += a[end]
if sum == m:
cnt += 1
elif sum < m:
continue
elif sum>m:
while start<=end:
sum-=a[start]
start+=1
if sum==m:
cnt+=1
break
elif sum<m:
break
print(cnt)
''''''''''''''''''''''
이렇게 하면 될 것 같아서 그냥 풀었는데
이게 슬라이딩 윈도우 알고리즘이라고 하네요
'''''''''''''''''''''''
| true |
6c9c7472bed1896949a2dcf47d68eaf21bd2f9c2 | Python | kfiryehuda/3-classification-learning | /test_room_model.py | UTF-8 | 1,554 | 2.59375 | 3 | [] | no_license | # import the necessary packages
import time
from imutils.video import WebcamVideoStream
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
from imutils import build_montages
from imutils import paths
import numpy as np
import argparse
import random
import cv2
# load the pre-trained network
print("[INFO] loading pre-trained network...")
model = load_model('floorModel')
# grab all image paths in the input directory and randomly sample them
video_src = 'http://192.168.1.15:8080/video'
_video_stream = WebcamVideoStream(video_src).start()
# allow the camera to warm up
time.sleep(2.0)
i = 1
while i < 100000:
orig = _video_stream.read()
orig = cv2.flip(orig, 0)
if orig is None:
break
frame = cv2.resize(orig, (64, 64))
frame = frame.astype("float") / 255.0
i+=1
frame = img_to_array(frame)
frame = np.expand_dims(frame, axis=0)
# make predictions on the input image
pred = model.predict(frame)
pred = pred.argmax(axis=1)[0]
# an index of zero is the 'parasitized' label while an index of
# one is the 'uninfected' label
label = "above" if pred == 0 else "bounds" if pred == 1 else "floor"
color = (0, 0, 255) if pred == 0 else (0, 255, 0) if pred == 1 else (255, 0, 0)
# resize our original input (so we can better visualize it) and
# then draw the label on the image
cv2.putText(orig, label, (3, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
color, 2)
cv2.imshow("Results", orig)
cv2.waitKey(1) | true |
2fa33c24736e719ac285eea77e6794df3eab43cc | Python | priyansh210/Airline_Reservation_and_Management_System-python | /menu/adminmenu.py | UTF-8 | 847 | 2.875 | 3 | [] | no_license |
import admin.add_a_flight as add_a_flight
import admin.cancel_a_flight as cancel_a_flight
import admin.flightstats as flightstats
import menu.login as login
import admin.sql_csv_updator as sql_csv_updator
def admin_menu():
print("")
print("----WELCOME ADMIN ----")
print("")
print("1 . ADD A FLIGHT >")
print("2 . CANCEL A FLIGHT >")
print("3 . FLIGHT STATS >")
print('4 . UPDATE SQL OR CSV ')
print("5 . EXIT TO LOGIN PAGE... ")
print(" " )
option=int(input(" : "))
if option ==1 :
return add_a_flight.add_flight()
elif option == 2:
return cancel_a_flight.cancel_flight()
elif option == 3:
return flightstats.flight_stats()
elif option == 4:
return sql_csv_updator.update_menu()
elif option == 5:
return login.login()
| true |
f3b4efffc0032b4ab7f9cdeb379705c0318d980c | Python | manuck/Algorithm | /codexpert/원안의 마을.py | UTF-8 | 584 | 2.703125 | 3 | [] | no_license | import sys
sys.stdin = open("원안의 마을_input.txt")
n = int(input())
a = [[0 for _ in range(n)]for _ in range(n)]
for i in range(n):
a[i] = list(input())
# print(a[i])
d = 0
xx=0
yy=0
for i in range(n):
for j in range(n):
if a[i][j]=='2':
xx = j
yy = i
for i in range(n):
for j in range(n):
if a[i][j] == '1':
a[i][j] = '0'
if d < ((j-xx)**2 + (i-yy)**2)**0.5:
d = ((j-xx)**2 + (i-yy)**2)**0.5
# print()
# for i in range(n):
# print(a[i])
# print(d)
print(round(d+0.49))
| true |
da8b46e3daec11a2b649e40c940b25392bc4ceb1 | Python | sanha-hwang/Baekjoon_my_sol | /5.1차원배열단계/평균.py | UTF-8 | 1,008 | 3.9375 | 4 | [] | no_license | """
문제
"OOXXOXXOOO"와 같은 OX퀴즈의 결과가 있다. O는 문제를 맞은 것이고, X는 문제를 틀린 것이다. 문제를 맞은 경우 그 문제의 점수는 그 문제까지 연속된 O의 개수가 된다. 예를 들어, 10번 문제의 점수는 3이 된다.
"OOXXOXXOOO"의 점수는 1+2+0+0+1+0+0+1+2+3 = 10점이다.
OX퀴즈의 결과가 주어졌을 때, 점수를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 테스트 케이스의 개수가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있고, 길이가 0보다 크고 80보다 작은 문자열이 주어진다. 문자열은 O와 X만으로 이루어져 있다.
출력
각 테스트 케이스마다 점수를 출력한다.
"""
import sys
num_subject = int(sys.stdin.readline())
scores = list(map(int, sys.stdin.readline().split(" ")))
max_score = max(scores)
sum = 0
for score in scores:
score = score*(100/max_score)
sum += score
new_mean = sum / num_subject
print(new_mean) | true |
46171d5d92e853d257bd28f0ee4d5bd61457d747 | Python | ruisunyc/leetcode_Solution | /leetcode/1563.石子游戏V/1563-石子游戏V.py | UTF-8 | 1,659 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | class Solution:
def stoneGameV(self, stoneValue: List[int]) -> int:
# presum=[stoneValue[0]]
# for i in range(1,len(stoneValue)):
# presum.append(stoneValue[i]+presum[-1])
# @lru_cache(None)
# def dfs(left,right):
# if left>=right: return 0
# ans = 0
# allsum = presum[right]-presum[left-1] if left>0 else presum[right]
# for i in range(left,right):
# suml = presum[i]-presum[left-1] if left>0 else presum[i]
# sumr = allsum - suml
# if suml<sumr:
# ans = max(ans,dfs(left,i)+suml)
# elif suml>sumr:
# ans =max(ans,dfs(i+1,right)+sumr)
# else:
# ans = max(ans,dfs(left,i)+suml,dfs(i+1,right)+sumr)
# return ans
# return dfs(0,len(presum)-1)
@lru_cache(None)
def dfs(left: int, right: int) -> int:
if left == right:
return 0
total = sum(stoneValue[left:right+1])
suml = ans = 0
for i in range(left, right):
suml += stoneValue[i]
sumr = total - suml
if suml < sumr:
ans = max(ans, dfs(left, i) + suml)
elif suml > sumr:
ans = max(ans, dfs(i + 1, right) + sumr)
else:
ans = max(ans, max(dfs(left, i), dfs(i + 1, right)) + suml)
return ans
n = len(stoneValue)
return dfs(0, n - 1)
| true |
dc5f81163c6d6455224fdb0fc3a9bf10ac9a2ee9 | Python | yanickdi/info4bm | /loesung_assignment_1/assignment_1.py | UTF-8 | 1,696 | 2.9375 | 3 | [] | no_license | import sys, struct, pickle
def parse_data_file(filename, num_frames):
"""Reads the file and returns a sensor_data dictionary"""
sensor_data = {0: {"name": "i", "data": []},
1: {"name": "ii", "data": []},
2: {"name": "iii", "data": []},
3: {"name": "avr", "data": []},
4: {"name": "avl", "data": []},
5: {"name": "avf", "data": []},
6: {"name": "v1", "data": []},
7: {"name": "v2", "data": []},
8: {"name": "v3", "data": []},
9: {"name": "v4", "data": []},
10: {"name": "v5", "data": []},
11: {"name": "v6", "data": []}
}
with open(filename, 'rb') as filep:
for frame_index in range(num_frames):
for lead in range(12):
# read a signed short (2 bytes)
shortVal = struct.unpack('h', filep.read(2))[0]
sensor_data[lead]['data'].append(shortVal)
return sensor_data
def dump_data(filename, sensor_data):
assert filename.split('.')[-1] != 'dat'
with open(filename, 'wb') as filep:
pickle.dump(sensor_data, filep)
def main():
if len(sys.argv) != 3:
print('usage: python {} <data_file_name> <num_frames>'.format(sys.argv[0]))
return -1;
inp_filename = sys.argv[1]
num_frames = sys.argv[2]
out_filename = '.'.join(inp_filename.split('.')[0:-1]) + '.p'
sensor_data = parse_data_file(sys.argv[1], int(sys.argv[2]))
dump_data(out_filename, sensor_data)
return 0
if __name__ == '__main__':
sys.exit(main()) | true |
56a59321d7a848b935fa2d123ecf55ff58e12cfb | Python | soreana/vanet-bandit | /filePlacement.py | UTF-8 | 3,597 | 3.015625 | 3 | [] | no_license |
from random import randint
from random import uniform
import copy
class FilePlacement :
def __init__(self,number_of_caches=5,number_of_files=25,
epsilon=0.5,min_epsilon=0.01,min_cache_size=5,max_cache_size=10,remove_chance=0.5,resize_chance=0.5,log=False):
self.caches = []
self.epsilon = epsilon
self.min_epsilon = min_epsilon
self.number_of_files = number_of_files
self.max_cache_size = max_cache_size
self.min_cache_size = min_cache_size
self.remove_chance = remove_chance
self.resize_chance = resize_chance
self.previouse_caches = []
self.log = log
for i in range(1,number_of_caches +1):
files_in_cache = []
current_cache_size = randint(self.min_cache_size, self.max_cache_size)
for j in range (0,current_cache_size):
files_in_cache.append(self.get_new_random_file(files_in_cache))
self.caches.append(files_in_cache)
def get_new_random_file(self,arr=[]):
new_file_num = randint(1, self.number_of_files)
while new_file_num in arr:
new_file_num = randint(1, self.number_of_files)
return new_file_num
def my_print(self,s):
if self.log :
print (s)
def mixed_up(self):
for cache in self.caches:
self.previouse_caches.append(cache[:])
self.my_print( "raw cache %s" % (cache) )
# remove phase
for i in cache:
should_remove = uniform(0,1)
if should_remove < self.remove_chance:
self.my_print("%s removed"%(i))
cache.remove(i)
self.my_print( "removed cache %s" % (cache) )
# replace phase
for i in range(0,len(cache)):
should_replace = uniform(0,1)
if should_replace < self.epsilon:
file_num = self.get_new_random_file(cache)
self.my_print("%s replaced with %s"%(cache[i],file_num))
cache[i] = file_num
self.my_print( "replaced cache %s" % (cache) )
# add new elements
should_resize = uniform(0,1)
if should_resize < self.resize_chance or len(cache) < self.min_cache_size:
new_size = randint(self.min_cache_size, self.max_cache_size)
if new_size <= len(cache):
while new_size != len(cache):
remove_candidate_index = randint(0, len(cache) -1)
self.my_print("removed %s"%(remove_candidate_index))
cache.remove(cache[remove_candidate_index])
else:
while new_size != len(cache):
add_candidate = self.get_new_random_file(cache)
self.my_print("added %s"%(add_candidate))
cache.append(add_candidate)
self.my_print( "resized cache %s" % (cache) )
self.show_all()
def ended(self):
return self.epsilon < self.min_epsilon
def request_cache_hits(self,req,cache_index):
hits = 0;
for i in req:
if i in self.caches[cache_index]:
hits += 1
return hits
def show_all(self):
print ("************ current cache ******************")
for cache in self.caches:
print (cache)
print ("************ previouse cache ******************")
for cache in self.previouse_caches:
print (cache)
| true |
be83e37b7620e9ff3c2e34d0e4b3fa49b80e7fe7 | Python | PirateRoberts98/capstone-hygeine-managment | /hardware/src/api.py | UTF-8 | 1,629 | 2.84375 | 3 | [
"MIT"
] | permissive | #! usr/bin/python3
import requests
import datetime
import json
import logging
from datetime import datetime
import time
import pytz
from requests.exceptions import Timeout
def get_time():
return time.time()
def timestamp_data(value):
return '{{"timestamp":{},"value":{}}}'.format(get_time(),value)
#TODO: Add documentation and ensure API well defined
class User:
def __init__(self,id=None):
self.id = id
def to_json(self):
return json.dumps(self.__dict__)
#TODO: Add documentation and ensure API well defined
class Sensor:
def __init__(self,type="temp"):
self.type = type
def to_json(self):
return json.dumps(self.__dict__)
json_format = "{{\"user\":{},\"sensor\":{},\"data\":{}}}"
class WebAPI:
def __init__(self,user_info,base_url="localhost:8080",offline=True):
self.base_url = base_url
self.offline = offline
self.user_info = user_info
def send_data(self,sensor,data):
if self.offline:
print("Sending Data => " + json_format.format(self.user_info.to_json(),sensor.to_json(),data))
else:
try:
r2 = requests.post(self.base_url,
json= json_format.format(self.user_info.to_json(),sensor.to_json(),data),
timeout=10)
logging.info("status code: {}".format(r2.status_code))
except Timeout:
logging.error("Timeout Occured")
return None
if __name__ == "__main__":
offline_api = WebAPI(User("Hello World"),offline=True)
offline_api.send_data(Sensor("Test"),"{foobar:30}")
| true |
d615fe5420b73ae30fa575e1f377b72b9a06df75 | Python | andresvanegas19/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/101-remove_char_at.py | UTF-8 | 139 | 3.453125 | 3 | [] | no_license | #!/usr/bin/python3
def remove_char_at(str, n):
if(len(str) > n):
return (str[:n] + str[n + 1:])
else:
return (str)
| true |
f0ee08c50cb10bb0c054e22ac6461bfe0616d3ea | Python | VictorCaiShen/LeetCode | /leetcode860.py | UTF-8 | 699 | 3.375 | 3 | [] | no_license | bills = [5, 5, 10, 20]
count_5 = 0
count_10 = 0
flag = 0
for i in range(0, len(bills)):
if bills[i] - 5 == 0:
count_5 += 1
flag += 1
elif bills[i] - 5 == 5:
if count_5 > 0:
count_5 -= 1
count_10 += 1
flag += 1
else:
print(False)
break
elif bills[i] - 5 == 15:
if count_10 > 0 and count_5 > 0:
count_10 -= 1
count_5 -= 1
flag += 1
elif count_5 >= 3 and count_10 == 0:
count_5 -= 3
flag += 1
else:
print(False)
break
if flag == len(bills):
print(True)
| true |
57386c2372a8f0749f3dcea6463f53e1efc551e3 | Python | chaochaocodes/PY4E | /03-accessing-web-data/urllinks.py | UTF-8 | 816 | 3.890625 | 4 | [] | no_license | '''
Parsing HTML using BeautifulSoup
Use urllib to read the page and then use BeautifulSoup to extract the href attributes from the anchor (a) tags.
The program prompts for a web address, then opens the web page, reads the data and passes the data to the BeautifulSoup parser, and then retrieves all of the anchor tags and prints out the href attribute for each tag.
'''
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter - ')
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
# Retrieve all of the anchor tags
tags = soup('a')
for tag in tags:
print(tag.get('href', None))
| true |
e69e597ec6af47674171ffc305c058fcbe58a32e | Python | jevy146/python | /tomcat_deamon/monitor.py | UTF-8 | 2,392 | 2.546875 | 3 | [] | no_license | #!-*- encoding: utf-8 -*-
import urllib2
import logging
import os
import time
from ConfigParser import ConfigParser
from logging.handlers import TimedRotatingFileHandler
LOG_FILE = "./logs/output.log"
logger = logging.getLogger()
logger.setLevel(logging.INFO)
fh = TimedRotatingFileHandler(LOG_FILE,when='midnight',interval=1,backupCount=30)
datefmt = '%Y-%m-%d %H:%M:%S'
format_str = '%(asctime)s %(levelname)s %(message)s '
formatter = logging.Formatter(format_str, datefmt)
fh.setFormatter(formatter)
fh.suffix = "%Y%m%d%H%M"
logger.addHandler(fh)
def getUrlcode(url):
try:
start = time.time()
response = urllib2.urlopen(url,timeout=10)
msg = 'httpcode is ' + str(response.getcode()) + ' - open url use time ' + str((time.time()-start)*1000) + 'ms'
logging.info(msg)
return response.getcode()
except urllib2.URLError as e:
msg = 'open url error ,reason is:' + str(e.reason)
logging.info(msg)
def get(field, key):
result = ""
try:
result = cf.get(field, key)
except:
result = ""
return result
def read_config(config_file_path, field, key):
cf = ConfigParser()
try:
cf.read(config_file_path)
result = cf.get(field, key)
except:
sys.exit(1)
return result
CONFIGFILE='./cfg/config.ini'
os.environ["JAVA_HOME"] = read_config(CONFIGFILE,'MonitorProgram','JAVA_HOME')
os.environ["CATALINA_HOME"] = read_config(CONFIGFILE,'MonitorProgram','CATALINA_HOME')
ProgramPath = read_config(CONFIGFILE,'MonitorProgram','StartPath')
ProcessName = read_config(CONFIGFILE,'MonitorProcessName','ProcessName')
url = read_config(CONFIGFILE,'MonitorUrl','Url')
#url = "http://dh.361way.com/"
while True:
HttpCode = getUrlcode(url)
if HttpCode is not 200:
command = 'taskkill /F /FI "WINDOWSTITLE eq ' + ProcessName + '"'
os.system(command)
os.system(ProgramPath)
time.sleep(30)
'''
import os
import socket
def IsOpen(ip,port):
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((ip,int(port)))
s.shutdown(2)
print '%d is open' % port
return True
except:
print '%d is down' % port
return False
if __name__ == '__main__':
IsOpen('127.0.0.1',800) '''
| true |
f6312705a446407b96efafd3c1a8d2ce0aa64a43 | Python | Gustavo-Lourenco/Python | /Exercícios/ex114.py | UTF-8 | 208 | 2.65625 | 3 | [
"MIT"
] | permissive | import urllib.request
try:
site = (urllib.request.urlopen("http://www.pudim.com.br").getcode())
except:
print('O site não está acessível no momento!')
else:
print('O site está disponível!')
| true |
6d6bfea5779c917d85b4ff4575aa634542cdfcb5 | Python | torudro/TD-Game | /enemies.py | UTF-8 | 4,802 | 3.296875 | 3 | [] | no_license | import pygame
import settings
import enemy_track
pygame.init()
class Enemy_Type:
def __init__(self, *args):
self.health = args[0][0]
self.worth = args[0][1]
self.speed = args[0][2]
self.image = args[0][3]
# list_counter = 0
class Enemy:
def __init__(self, enemy_type):
# again, depending on settings, will either be XMAS or TG
self.list_counter = 0
self.dead = False
self.worth = enemy_type.worth
self.speed = enemy_type.speed
self.health = enemy_type.health
self.image = enemy_type.image
self.rotated_image = self.image
self.image_display_dimensions = None
# can't go left in this game due to layout of maps
self.direction_left = False
self.direction_right = False
self.direction_up = False
self.direction_down = False
self.stop_list_count = False
self.cont_list_count = False
# to be able to go through lists
self.enemy_path_list_x = enemy_track.enemy_path_list_x
self.enemy_path_list_y = enemy_track.enemy_path_list_y
def continue_list_counter(self):
self.stop_list_count = False
self.cont_list_count = True
self.list_counter += 1
def stop_list_counter(self):
self.stop_list_count = False
self.stop_list_count = True
def draw(self):
# print('LIST COUNTER: ',self.list_counter)
# used for loops - current position in enemy_path_list_x or _y
# self.list_counter = 0
self.incr_x = self.enemy_path_list_x[self.list_counter] + enemy_track.dist_x_list[self.list_counter] * (1 / self.speed)
self.incr_y = self.enemy_path_list_y[self.list_counter] + enemy_track.dist_y_list[self.list_counter] * (1 / self.speed)
self.decr_y = self.enemy_path_list_y[self.list_counter] - enemy_track.dist_y_list[self.list_counter] * (1 / self.speed)
# image drawn to surface with tuple as dimensions
self.image_display_dimensions = pygame.Surface((59, 64))
# gives enemy a collision area that's the same location of the image so it can be hit/know if at endpoint
self.image_display_dimensions.get_rect(center=(self.enemy_path_list_x[self.list_counter], self.enemy_path_list_y[self.list_counter]))
# subtracts 59 from x and 64 from y because they have to adapt to the location of the points on the map
settings.display.blit(self.rotated_image, (
self.enemy_path_list_x[self.list_counter] - 59, self.enemy_path_list_y[self.list_counter] - 64))
# print(enemy_track.enemy_path_list_x[list_counter])
# doesn't need to be called in for loop because it's only necessary for each central tile point (not fractions of it)
if self.enemy_path_list_x[self.list_counter] < self.enemy_path_list_x[len(self.enemy_path_list_x) - 1] \
and self.enemy_path_list_x[self.list_counter + 1] >= self.enemy_path_list_x[self.list_counter] \
and self.enemy_path_list_y[self.list_counter] == self.enemy_path_list_y[self.list_counter]:
self.direction_up = False
self.direction_down = False
self.direction_right = True
# orientates facing right
self.rotated_image = pygame.transform.rotate(self.image, 0)
# first condition can be x or y, doesn't matter. if next y pos is less than, then the enemy is going up
if self.enemy_path_list_x[self.list_counter] < self.enemy_path_list_x[len(self.enemy_path_list_x) - 1] \
and self.enemy_path_list_y[self.list_counter + 1] < self.enemy_path_list_y[self.list_counter]:
self.direction_right = False
self.direction_down = False
self.direction_up = True
# orientates facing up
self.rotated_image = pygame.transform.rotate(self.image, 90)
# down direction because greater than sign
if self.enemy_path_list_x[self.list_counter] < self.enemy_path_list_x[len(self.enemy_path_list_x) - 1] \
and self.enemy_path_list_y[self.list_counter + 1] > self.enemy_path_list_y[self.list_counter]:
self.direction_right = False
self.direction_up = False
self.direction_down = True
# orientates facing down
self.rotated_image = pygame.transform.rotate(self.image, 270)
# Makes it so the enemy does not move anymore.
if self.list_counter < 28:
self.continue_list_counter()
if self.list_counter == 28:
self.stop_list_counter()
# loop dependent on how many tiles the enemy moves per second. goes speed-1 times because don't want to draw to same tile point twice
# might be okay to add this before the for loop
# self.list_counter += 1
| true |
e9280c0f3e1077a8ae2037a1a3633dca94b66f70 | Python | Ablay09/BFDjango | /Week 1/Codingbat/Logic - 1/8.py | UTF-8 | 258 | 2.90625 | 3 | [] | no_license | def alarm_clock(day, vacation):
str_7 = "7:00"
str_10 = "10:00"
if(1<=day<=5 and not vacation):
return str_7
if (vacation and (day == 0 or day == 6)):
return "off"
if((day == 0 or day == 6) or (vacation and 1<=day<=5)):
return str_10
| true |
dcdff4e392e51bbf9bde39aad99637dcc3441a85 | Python | tgardela/project_euler_python | /028_Number_spiral_diagonals.py | UTF-8 | 496 | 3.90625 | 4 | [] | no_license | import timeit
# n - side length
# corner for n is (start to end):
# n * n, (n-1)*n + 1, (n-2)*n + 2, (n-3)* + 3
def find_sum_of_diagonals():
diagonalSum = 1
for n in range(3,1002,2):
diagonalSum = diagonalSum + (n * n) + ((n-1)*n + 1) +((n-2)*n + 2) + ((n-3)*n + 3)
return diagonalSum
if __name__ == '__main__':
start = timeit.default_timer()
print(find_sum_of_diagonals())
stop = timeit.default_timer()
print("Time: ", stop - start, " s")
| true |
61954f00c2bd3922857ca307cf330a204823b26c | Python | acceleraterA/google_foobar | /level2_1.py | UTF-8 | 198 | 3.15625 | 3 | [] | no_license | def solution(l):
#'1.2.1' -> [1, 2 ,1]
l.sort(key=lambda s: list(map(int, s.split('.'))))
return l
l=["1.0", "1.0.2", "1.0.12", "1.1.2", "1.3.3"]
solution(l)
print(solution(l)) | true |
27ef5f12bbcb19c9a99588dd9713852fac812001 | Python | Psingh12354/GeeksPy | /Evens.py | UTF-8 | 96 | 2.9375 | 3 | [] | no_license | list1 = [10, 21, 4, 45, 66, 93, 11]
evens=list(filter(lambda n : n%2==0,list1))
print(evens)
| true |
6a6485a4ad791407d877e717b4e29f881ab8de4f | Python | Py-Winning/pubg-seer | /PUBG Kaggle.py | UTF-8 | 1,704 | 2.625 | 3 | [] | no_license |
# coding: utf-8
# # PUBGGGGG
# #drop rankPoints, killStreaks, longestKill, matchId, roadKills, vehicleDestroys, weaponsAcquired,
# #one-hot encoding matchType
# #One USer has 64 kills and 1.0 win percentage
# #Combine distances (walk, swim, and rideDistance) by adding them for totalDistance
# #Take into account afks
# In[57]:
get_ipython().magic(u'matplotlib inline')
print(__doc__)
import numpy as np
import scipy as sp
import pandas as pd
from sklearn import datasets
from sklearn.model_selection import train_test_split # Used to split the dataset effeciently
from sklearn import tree
from sklearn.metrics import accuracy_score
from sklearn.externals.six import StringIO
#read the csv into a datafram
df = pd.read_csv('Documents/pubg-seer/pubgdataset/train_V2.csv')
# In[58]:
df.head()
# In[59]:
df.count()
# In[60]:
#Drops all objects with NAs
df2 = df.dropna()
df2.count()
# In[61]:
#Combines walkDistance, swimDistance, and rideDistance into totalDistance
df2['totalDistance'] = df2['walkDistance'] + df2['swimDistance'] + df2['rideDistance']
df2.head()
# In[62]:
#Drops walkDistance, rideDistance, and swimDistance attributes
df3 = df2.drop(columns=['walkDistance', 'rideDistance', 'swimDistance'])
df3.head()
# In[63]:
#One hot encodes matchType
one_hot = pd.get_dummies(df3['matchType'])
# In[64]:
df3 = df3.drop('matchType',axis = 1)
# In[65]:
df3 = df3.join(one_hot)
df3
# In[66]:
df3.head()
# In[73]:
df4 = df3.copy()
# In[74]:
y = df4.pop('winPlacePerc').values
X = df4.values
# In[75]:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.8, random_state=42)
| true |
dfecbbddfd6bb7d67eb43bc8bff5d8d1e90b97cf | Python | john-m-hanlon/Python | /General Python/LTP - Introduction to Python [PluralSight]/LTP - 02 - Functions, Strings, and Lists.py | UTF-8 | 2,727 | 4.71875 | 5 | [] | no_license | #
# Simple game to find the secret word!!
# LTP - 02 - Functions, Strings, and Lists.py
#
__author__ = 'JohnHanlon'
def get_random_word():
''' Pulls in a random word for future analysis
Parameters
==========
N/A : takes no parameters
Returns
=======
word : str
random word
'''
import random
words = ['pizza', 'cheese', 'apples']
word = words[random.randint(0, len(words) - 1)]
return word
def show_word(word):
''' Shows the blanked out word we are trying to guess
Parameters
==========
word : str
the word we are trying to guess
Returns
=======
hidden_word : str
word hidden in underscore and spaces
'''
for character in word:
print('{} '.format(character), end='')
print('')
def get_guess():
''' Guesses a letter in the hidden word
Parameters
==========
N/A : takes no parameters
Returns
=======
input : str
user input
'''
print('Enter a letter: ')
return input()
def process_letter(letter, secret_word, blanked_word):
''' figures out if the letter is in the secret word
Parameter
=========
letter : str
the guess entered
secret_word : str
the hidden word being evaluated
blanked_word : str
converted hidden word
Return
======
result : binary
Ture or false if the letter has been found
'''
result = False
for i in range(0, len(secret_word)):
if secret_word[i] == letter:
result = True
blanked_word[i] = letter
return result
def print_strikes(number_of_strikes):
''' Tests to see if how many strikes have been used
Parameters
==========
strikes : int
takes in how many strikes have occured
Returns
=======
remaining : int
how many strikes are remaining
'''
for i in range(0, number_of_strikes):
print('X', end='')
print('')
def play_word_game():
'''
Parameters
==========
Returns
=======
'''
strikes = 0
max_strikes = 3
playing = True
word = get_random_word()
blanked_word = list('_' * len(word))
while playing:
show_word(blanked_word)
letter = get_guess()
found = process_letter(letter, word, blanked_word)
if not found:
strikes += 1
print_strikes(strikes)
if strikes >= max_strikes:
playing = False
if '_' not in blanked_word:
playing = False
if strikes >= max_strikes:
print('Loser!')
else:
print('Winner')
print('Game started')
play_word_game()
print('Game over')
| true |
863b4b7499d54816b194bccf1bf878c6a8040e8a | Python | SergeyEroshenko/RLcrypto | /draft.py | UTF-8 | 259 | 2.765625 | 3 | [] | no_license | import pandas as pd
import numpy as np
a = np.array([[1, 2, 3, 3, 4], [2, 5, 4, 7, 8], [0, 0, 0, 0, 0]]).T
df = pd.DataFrame(a, columns=['price', 'timestamp', 'other'])
idx = df.groupby('price')['timestamp'].transform(max) == df['timestamp']
print(df[idx]) | true |
e148ab6cc2cd04fa86561e105f7b2be4dfefc34a | Python | jerinviju/jerin_viju | /hello.py | UTF-8 | 4,759 | 2.84375 | 3 | [] | no_license | import sys
from Class import node
from reportlab.pdfgen import canvas
import os
import json
from importlib import import_module
movie=""
duration=""
stars=""
num=""
cont=""
simplelist=[]
i=1
j=1
objforpass=node("","","","")
c=canvas.Canvas("output/data.pdf")
def getdata():
#get data from the user
movie = raw_input("Please enter the name of the film: ")
duration = raw_input("Please enter the duration of the film: ")
stars = raw_input("Please enter the name of the actors with , seperation: ")
num = raw_input("Please enter the format of the file to be saved(1-plaintext,2-pdf,3-plugins): ")
cont = raw_input("Do you want to continue(y|n): ")
#data is stored as a list objects of class node in samplelist
newnode=node(movie,duration,stars,num)
simplelist.append(newnode)
print "\n\n"
if cont=="y":
getdata()
else:
filetype()
def filetype():
#this function sends each objects to the function to plain text,pdf and plugin based on the users choice
global simplelist
global c
for ele in simplelist:
if ele.num=="1":
plaintxt(ele)
elif ele.num=="2":
pdf(ele)
else:
reflection(ele)
c.save()
def plaintxt(data):
#this fuction changes the data into a plain text and stores it in the output folder
global i
f=open("output/data.txt","a+")
f.write("Movie %d\r\n"%i)
i=i+1
f.write("Name of the movie: %s\n" %data.movie)
f.write("duration of the movie: %s\n"%data.duration)
f.write("actors of the movie: %s\n"%data.stars)
f.write("\n")
f.close
print "check the output folder for plaintext"
def pdf(data):
#this function uses the library reportlab to convert the data into a pdf
global j
global c
c.drawString(3,800-((j-1)*50),"Movie %d"%j)
c.drawString(3,800-(((j-1)*50)+10),"Name of the Movie: %s"%data.movie)
c.drawString(3,800-(((j-1)*50)+20),"Duration of the Movie: %s"%data.duration)
c.drawString(3,800-(((j-1)*50)+30),"Stars of the Movie: %s"%data.stars)
j=j+1
print "check the output folder for pdf"
def reflection(data):
flag=0
#this function checks the plugin directory for plugins .if there is a plugin gets the name of the plugin and name of the plugin file name from the manifest file of the plugin.then this fuction sends store the data as aplain text in the plugin directory for the .The plugins can use this data as they like.
num=1
print "the available plugins are \n"
for f in os.listdir("plugins/"):
child=os.path.join("plugins/",f)
if os.path.exists(child+"/manifest.json"):
flag=1
Json=json.loads(open(child+"/manifest.json").read())
try:
print Json["name"]+"-%d"%num
num=num+1
except Exception:
print "please check your manifest"
if flag==0:
print "srry there is no plugins available now\n"
nums = raw_input("please choose plaintext|pdf (1|2): ")
if nums=="1":
plaintxt(data)
elif nums=="2":
pdf(data)
else:
z=1
option= input("Choose your plugin: ")
for f in os.listdir("plugins/"):
if option==z:
plugin=os.path.join("plugins/",f)
Json=json.loads(open(plugin+"/manifest.json").read())
f=open(plugin+"/data.txt","a+")
f.write("Name of the movie: %s\n" %data.movie)
f.write("duration of the movie: %s\n"%data.duration)
f.write("actors of the movie: %s\n"%data.stars)
f.close
try:
x=Json["classname"]
import_module(x)
except Exception:
print "please check your manifest"
break
else:
z=z+1
getdata()
| true |
35b30815eb54283c6881412d8b6c9d82e32180f9 | Python | scottshepard/advent-of-code | /2016/day05.py | UTF-8 | 4,683 | 4 | 4 | [] | no_license | # --- Day 5: How About a Nice Game of Chess? ---
#
# You are faced with a security door designed by Easter Bunny engineers that
# seem to have acquired most of their security knowledge by watching hacking
# movies.
#
# The eight-character password for the door is generated one character at a
# time by finding the MD5 hash of some Door ID (your puzzle input) and an
# increasing integer index (starting with 0).
#
# A hash indicates the next character in the password if its hexadecimal
# representation starts with five zeroes. If it does, the sixth character in
# the hash is the next character of the password.
#
# For example, if the Door ID is abc:
#
# The first index which produces a hash that starts with five zeroes is
# 3231929, wwhich we find by hashing abc3231929; the sixth character of the
# hash, and thus the first character of the password, is 1.
# 5017308 produces the next interesting hash, which starts with 000008f82...,
# so the second character of the password is 8.
# The third time a hash starts with five zeroes is for abc5278568, discovering
# the character f.
# In this example, after continuing this search a total of eight times, the
# password is 18f47a30.
#
# Given the actual Door ID, what is the password?
#
# --- Part Two ---
#
# As the door slides open, you are presented with a second door that uses a
# slightly more inspired security mechanism. Clearly unimpressed by the last
# version (in what movie is the password decrypted in order?!),
# the Easter Bunny engineers have worked out a better solution.
#
# Instead of simply filling in the password from left to right, the hash now
# also indicates the position within the password to fill. You still look for
# hashes that begin with five zeroes; however, now, the sixth character
# represents the position (0-7), and the seventh character is the character
# to put in that position.
#
# A hash result of 000001f means that f is the second character in the password
# Use only the first result for each position, and ignore invalid positions.
#
#
# For example, if the Door ID is abc:
#
# The first interesting hash is from abc3231929, which produces 0000015...;
# so, 5 goes in position 1: _5______.
# In the previous method, 5017308 produced an interesting hash; however,
# it is ignored, because it specifies an invalid position (8).
# The second interesting hash is at index 5357525, which produces 000004e...;
# so, e goes in position 4: _5__e___.
# You almost choke on your popcorn as the final character falls into place,
# producing the password 05ace8e3.
#
# Given the actual Door ID and this new method, what is the password?
# Be extra proud of your solution if it uses a cinematic "decrypting" animation
#
# ----------------------------------------------------------------------------
#
# To run this script, you need to input the text string on the command line
#
# So usage looks like
#
# python day05.py ffykfhsq
from hashlib import md5
import sys
def decode_fully1(string):
code = []
for i in range(0, 8):
if(i == 0):
digit, n = decode_once1(string)
code.append(digit)
else:
digit, n = decode_once1(string, n+1)
code.append(digit)
return code
def decode_once1(string, n=0):
while True:
code = encode(string + str(n))
if(fivechars(code) == '00000'):
return char6(code), n
else:
n += 1
def decode_fully2(string):
solution = ['', '', '', '', '', '', '', '']
n = -1
for i in range(0, 8):
digit, index, n = decode_digit(string, n+1, solution)
solution[int(index)] = digit
print(solution)
return solution
def decode_digit(string, n, solution):
while True:
code = encode(string + str(n))
if(code[:5] == '00000' and valid_char6(code[5:6], solution)):
return code[6:7], code[5:6], n
else:
n += 1
def valid_char6(char6, solution):
return char6.isdigit() and int(char6) <= 7 and solution[int(char6)] == ''
def encode(string):
return md5(string.encode('utf-8')).hexdigest()
def fivechars(string):
return string[:5]
def char6(string):
return string[5:6]
if __name__ == '__main__':
if(len(sys.argv) < 2):
print("This script needs an input string as a",
"command-line argument to work")
elif(sys.argv[2] == '1'):
print(''.join(decode_fully1(sys.argv[1])))
elif(sys.argv[2] == '2'):
print(''.join(decode_fully2(sys.argv[1])))
else:
print("This script requires a 1 or 2 as the second",
"command-line argument")
| true |
b6aaaac5509e73fe54c754d7d0ab4316fc7bf8a7 | Python | EmilioAlzarif/intro-to-python | /week 2/Homework/hom3.py | UTF-8 | 437 | 3.65625 | 4 | [] | no_license | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("text", type= str)
parser.add_argument("first_word", type= str)
parser.add_argument("second_word", type= str)
args = parser.parse_args()
print("enter a text please : ", args.text)
print("choose a word you want to change from the text : ", args.first_word)
print("choose a new word : ", args.second_word)
print(args.text.replace(args.first_word, args.second_word)) | true |
7c84e75f55a5eafce5b1ead561db31b6634c5681 | Python | podhmo/individual-sandbox | /daily/20190408/example_python/00iter.py | UTF-8 | 197 | 2.890625 | 3 | [] | no_license | import itertools
def consume(itr):
for line in itr:
yield line
if line == 2:
yield from consume(itertools.chain([-2], itr))
print(list(consume(iter(range(5)))))
| true |
ca74cd1be5e8b3afe88eba58a7f9356a43c537b3 | Python | wmm98/homework1 | /7章之后刷题/9章/复数类.py | UTF-8 | 4,890 | 3.875 | 4 | [] | no_license | '''【问题描述】
定义复数类Complex,使用方法实现复数的加法、减法、乘法,所有方法都返回Complex类型的对象。
程序输入两个复数,而后依次输出加法结果,减法结果和乘法结果。
【输入形式】
每个复数的输入形式是:(实部,虚部)。实部和虚部都是整数。
【输出形式】
以"(被加数)+(加数)=结果"形式输出每一个结果。中间不带任何空格。注意被加数和加数两边的括号。
每个复数都以"实部+虚部i"形式输出。即使实部或虚部为零,也不要省略。
【样例输入】
(1,0)
(0,1)
【样例输出】
(1+0i)+(0+1i)=1+1i
(1+0i)-(0+1i)=1-1i
(1+0i)*(0+1i)=0+1i
'''
# class Complex:
# def __init__(self, t1, t2):
# self.t1 = t1
# self.t2 = t2
#
# def jia_fa(self):
# if (self.t1[1] - self.t2[1]) < 0:
# re = str(self.t1[0] + self.t2[0]) + "+" + str(self.t1[1] + self.t2[1]) + "i"
# result = "(%s)%s(%s)%s%s" % ((str(self.t1[0]) + "+" + str(self.t1[1]) + "i"), "+", (str(self.t2[0]) + "+" + str(self.t2[1]) + "i"), "=", re)
# print(result)
# else:
# re = str(self.t1[0] + self.t2[0]) + "+" + str(self.t1[1] + self.t2[1]) + "i"
# result = "(%s)%s(%s)%s%s" % (
# (str(self.t1[0]) + "+" + str(self.t1[1]) + "i"), "+", (str(self.t2[0]) + "+" + str(self.t2[1]) + "i"),
# "=", re)
# print(result)
#
# def jian_fa(self):
# re1 = str(self.t1[0] - self.t2[0])
# re2 = str(self.t1[1] - self.t2[1]) + "i"
# if self.t1[1] - self.t2[1] < 0:
# re3 = re1 + re2
# result1 = "(%s)%s(%s)%s%s" % (
# (str(self.t1[0]) + "+" + str(self.t1[1]) + "i"), "-", (str(self.t2[0]) + str(self.t2[1]) + "i"), "=",
# re3)
# print(result1)
# else:
# re3 = re1 + re2
# result11 = "(%s)%s(%s)%s%s" % (
# (str(self.t1[0]) + "+" + str(self.t1[1]) + "i"), "+", (str(self.t2[0]) + "+" + str(self.t2[1]) + "i"), "=",
# re3)
# print(result11)
#
# def chen_fa(self):
# re22 = self.t1[0] * self.t2[0]
# re33 = self.t1[1] * self.t1[0] + self.t1[1] * self.t2[1]
# re333 = str(re33) + "i"
# if re33 < 0:
# pass
# else:
#
# result1 = "(%s)%s(%s)%s%s" % (
# (str(self.t1[0]) + "+" + str(self.t1[1]) + "i"), "*", (str(self.t2[0]) + "+" + str(self.t2[1]) + "i"), "=",
# re3)
#
# num1 = tuple(eval(input()))
# num2 = tuple(eval(input()))
# one = Complex(num1, num2)
# one.jia_fa()
# one.jian_fa()
# # one.chen_fa()
class Complex:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
self.num1_shi = self.num1[0]
self.num1_xu = self.num1[1]
self.num2_shi = self.num2[0]
self.num2_xu = self.num2[1]
self.jiafa = ""
self.jianfa = ""
self.chengfa = ""
def jia(self):
if int(self.num1_xu)+int(self.num2_xu) < 0:
temp = "("+self.num1_shi+"+"+self.num1_xu+"i)+("+self.num2_shi+"+"+self.num2_xu+"i)="+str(int(self.num1_shi)+int(self.num2_shi))+str(int(self.num1_xu)+int(self.num2_xu))+"i"
else:
temp = "("+self.num1_shi+"+"+self.num1_xu+"i)+("+self.num2_shi+"+"+self.num2_xu+"i)="+str(int(self.num1_shi)+int(self.num2_shi))+"+"+str(int(self.num1_xu)+int(self.num2_xu))+"i"
self.jiafa = temp
def jian(self):
if int(self.num1_xu)-int(self.num2_xu) < 0:
temp = "("+self.num1_shi+"+"+self.num1_xu+"i)-("+self.num2_shi+"+"+self.num2_xu+"i)="+str(int(self.num1_shi)-int(self.num2_shi))+str(int(self.num1_xu)-int(self.num2_xu))+"i"
else:
temp = "("+self.num1_shi+"+"+self.num1_xu+"i)-("+self.num2_shi+"+"+self.num2_xu+"i)="+str(int(self.num1_shi)-int(self.num2_shi))+"+"+str(int(self.num1_xu)-int(self.num2_xu))+"i"
self.jianfa = temp
def cheng(self):
if int(self.num1_xu)*int(self.num2_xu) < 0:
temp = "("+self.num1_shi+"+"+self.num1_xu+"i)*("+self.num2_shi+"+"+self.num2_xu+"i)="+str(int(self.num1_shi)*int(self.num2_shi)-int(self.num1_xu)*int(self.num2_xu))+str(int(self.num2_shi)*int(self.num1_xu)+int(self.num1_shi)*int(self.num2_xu))+"i"
else:
temp = "("+self.num1_shi+"+"+self.num1_xu+"i)*("+self.num2_shi+"+"+self.num2_xu+"i)="+str(int(self.num1_shi)*int(self.num2_shi)-int(self.num1_xu)*int(self.num2_xu))+"+"+str(int(self.num2_shi)*int(self.num1_xu)+int(self.num1_shi)*int(self.num2_xu))+"i"
self.chengfa = temp
# (5+0i)+(-3+0i)
num1 = input()
num2 = input()
num1 = num1[1:len(num1)-1].split(",")
num2 = num2[1:len(num2)-1].split(",")
jisuan = Complex(num1, num2)
jisuan.jia()
print(jisuan.jiafa)
jisuan.jian()
print(jisuan.jianfa)
jisuan.cheng()
print(jisuan.chengfa)
| true |
34d21d881faf18d73a0f14adea156a2238c44c2c | Python | austin-j-taylor/sphero-mini-control | /gamepadControl.py | UTF-8 | 2,210 | 2.59375 | 3 | [] | no_license | from multiprocessing import Process, Value
from inputs import get_gamepad
from inputs import devices
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
style.use('fivethirtyeight')
for device in devices:
print(device)
def runGraph(currX, currY, currRX, currRY, currRZ):
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.set_aspect(1)
def plotInputs(i):
ax1.clear()
ax1.plot([0, currX.value], [0, currY.value])
ax1.plot([0, currRX.value], [0, currRY.value])
ax1.plot([0, currRZ.value * 128], [0, 0])
ax1.set_xlim(-40000, 40000)
ax1.set_ylim(-40000, 40000)
#print("Showing: %i" % currX.value)
ani = animation.FuncAnimation(fig, plotInputs, interval = 250)
plt.show()
def MainProgram(currX, currY, currRX, currRY, currRZ):
while 1:
#print("---")
events = get_gamepad()
for event in events:
#print(event.ev_type, event.code, event.state)
if(event.code == "ABS_X"):
currX.value = event.state
elif(event.code == "ABS_Y"):
currY.value = -event.state
if(event.code == "ABS_RX"):
currRX.value = event.state
elif(event.code == "ABS_RY"):
currRY.value = -event.state
elif(event.code == "ABS_RZ"):
currRZ.value = event.state
elif(event.code == "SYN_REPORT"):
# Process the last changes
#print("X: %i" % (currX.value))
#print("Y: %i" % (currY.value))
#print("RX: %i" % (currRX.value))
#print("RY: %i" % (currRY.value))
#print("RZ: %i" % (currRZ.value))
plt.show(block=False)
if __name__ == '__main__':
currX = Value('i', 0)
currY = Value('i', 0)
currRX = Value('i', 0)
currRY = Value('i', 0)
currRZ = Value('i', 0)
p = Process(target = runGraph, args = (currX, currY, currRX, currRY, currRZ)).start()
MainProgram(currX, currY, currRX, currRY, currRZ)
p.join() | true |
214540eb4e43f8ace673dde043665b3d290c5695 | Python | Thiago-Mauricio/Curso-de-python | /Curso em Video/Aula07 Operadores Aritiméticos/Ex_011 Pintando Paredes.py | UTF-8 | 166 | 3.6875 | 4 | [] | no_license | L = float(input('Largura da parede: '))
A = float(input('Altura da parede: '))
T = L * A / 2
print(f'Para pintar sua parede, será necessário {T} litros de tinta.')
| true |
79ab1dab09b89ffec6052b2173fd06bc82e0f24d | Python | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/3094/codes/1709_3060.py | UTF-8 | 550 | 3.296875 | 3 | [] | no_license | d1 = int(input("valor dado 1: "))
d2 = int(input("valor dado 2: "))
r = int(input("rodada: "))
if(d1 <= 0 or d1> 6 or d2<=0 or d2>6):
a = "Entrada invalida"
print(a)
elif(d1 + d2 == 12):
a = "CONSTRICAO"
dano = d1 + d2 + 1
print(a)
print(dano)
elif(d1 + d2 < 5):
a = "POLEN"
dano = (d1 + d2 + 1) * r
print(a)
print(dano)
else:
a = "FRAQUEZA"
dano = d1 * d2
print(a)
print(dano)
#if(a == "CONSTRICAO"):
#dano = d1 + d2 + 1
#elif(a == "POLEN"):
# dano = (d1 + d2 + 1)*r
#elif(a == "FRAQUEZA"):
#dano = d1 * d2
#print(dano)
| true |
7102021711b0cb265c8e64cc5bc86e18b507ae22 | Python | spacetiller/experiment | /py/tool/xirr.py | UTF-8 | 600 | 3.078125 | 3 | [] | no_license | # -*- coding=utf-8 -*-
# __author = 'zhanghui'__
import datetime
from scipy import optimize
# 函数
def xnpv(rate, cashflows):
return sum([cf/(1+rate)**((t-cashflows[0][0]).days/365.0) for (t,cf) in cashflows])
def xirr(cashflows, guess=0.1):
try:
res = optimize.newton(lambda r: xnpv(r,cashflows),guess)
print(res)
return res
except:
print('Calc Wrong')
# 测试
data = [(datetime.date(2006, 1, 24), -39967), (datetime.date(2008, 2, 6), -19866), (datetime.date(2010, 10, 18), 245706), (datetime.date(2013, 9, 14), 52142)]
print(data)
xirr(data)
| true |
69b1cabc2d75c761ed549ecb926d86f69960fa31 | Python | bingerambo/python | /MyDemo/web_spider/text_parser.py | UTF-8 | 2,088 | 2.96875 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@version: ??
@author: Binge
@file: text_parser.py
@time: 2016-11-07 9:15
@description:
"""
import urllib
from web_spider.lib.html_parser import HtmlParser
class Text_HtmlParser(HtmlParser):
""" Crawling qiushi text content
and set crawling data regulation
example: http://www.qiushibaike.com/text/page/2/?s=4926983
"""
def parse(self, crawling_url, html_cont, encoding):
""" 子类的parse处理,自定义相应的解析规则
"""
# 通用parse操作,调用基类parse方法,
super(Text_HtmlParser, self).parse(crawling_url, html_cont, encoding)
new_urls = self.__get_new_urls(crawling_url)
new_datas = self.__get_new_datas(crawling_url)
return new_urls, new_datas
def __get_new_urls(self, crawling_url):
new_urls = set()
# <ul class="pagination"><li><a href="/text/page/2?s=4926902" rel="nofollow"><span class="next">下一页</span></a></li></ul>
next_span = self.soup.find('ul', class_='pagination').find('span', class_='next')
if next_span is None:
print("crawling the last web page, will end!")
return None
# link = next_span.parent
new_url = next_span.parent['href']
new_full_url = urllib.parse.urljoin(crawling_url, new_url)
# print(new_full_url)
new_urls.add(new_full_url)
return new_urls
def __get_new_datas(self, crawling_url):
new_data_group = []
contents = self.soup.find('div', id='content').find('div', id='content-left').find_all('div', class_='content')
if contents is None:
print("this web page crawling none!")
return None
for content in contents:
# print(content)
new_data_item = {}
new_data_item['html_content'] = content
new_data_item['raw_content'] = content.get_text().strip()
new_data_group.append(new_data_item)
return new_data_group
if __name__ == '__main__':
pass | true |
7d5f7d53742b58c13edc4d039da8d95f51bcb0e0 | Python | sagar-sharma-netizen/productimporter | /utils/handlers.py | UTF-8 | 2,981 | 2.5625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# python imports
from __future__ import unicode_literals
import json
import traceback
from contextlib import suppress
from json.decoder import JSONDecodeError
from typing import Dict, List, Tuple
from utils.logger import Logger
# lib imports
from django.http import HttpRequest, HttpResponse
from utils.exception import CustomException, HTTPException
def _request_handler(
request: HttpRequest, config: Dict
) -> Tuple[Dict, Dict, Dict]:
"""
Process Django request instance and returns version, params, post data
"""
params = request.GET.dict()
body = {}
headers = {
header: request.META.get(header) for header in config.get("headers")
} if config.get("headers") else {}
if request.content_type == "application/json":
with suppress(JSONDecodeError):
body = json.loads(request.body)
else:
body = request.POST.dict()
for file, value in request.FILES.items():
body[file] = value
return headers, params, body
def handle_api_exception(func):
"""
Decorator function to handle any exception from APIs.
It serialise error data as dict response.
"""
def inner(*args, **kwargs):
"""
handler api exception
"""
request = args[0]
content_type = "application/json"
try:
body, status = func(*args, **kwargs)
except CustomException as error:
exp = HTTPException.from_custom_exception(error)
body = _serialize(exp.as_dict())
status = exp.status
except HTTPException as error:
body = _serialize(error.as_dict())
status = error.status
except Exception as error:
error_traceback = traceback.format_exc()
Logger.error(error_traceback)
body = "Something went wrong"
status = 500
return HttpResponse(
json.dumps(body), status=status, content_type=content_type
)
return inner
def _serialize(
body
) -> Dict:
"""
Serialize fields into json dumpable objects
"""
return body
def api_handler():
"""
API Handler
:return:
"""
def decorator(func):
"""
Decorator
:param func:
:return:
"""
def inner(request, *args, **kwargs):
module_name = func.__module__.split(".")[-1]
api_name = func.__name__
method = request.method
headers, params, body = _request_handler(
request=request, config={}
)
request_params = {
"method": method,
"headers": headers,
}
print("params", params)
body, status = func(
request_params, params, body, *args, **kwargs
)
response = _serialize(body)
return response, status
return inner
return decorator
| true |
b1a741b5ffd79ea206df6d0afb5a9815d42a9b3b | Python | jgreen7773/python_stack | /django/django_full_stack/login_and_registration/apps/login_app/models.py | UTF-8 | 1,500 | 2.59375 | 3 | [] | no_license | from __future__ import unicode_literals
from django.db import models
import re
class UserManager(models.Manager):
def login_validation(self, request, postData):
errors = {}
print('---------------------------')
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
if not EMAIL_REGEX.match(request.form['email']):
errors['email'] = ("Invalid email address!")
if len(postData['f_name']) < 2:
errors['first'] = "First name should contain at least two characters."
elif len(postData['f_name']) < 1:
errors['field_first'] = "First Name field is required."
if len(postData['l_name']) < 2:
errors['last'] = "Last name should contain at least two characters."
elif len(postData['l_name']) < 1:
errors['field_last'] = "Last Name field is required."
if len(postData['email']) < 1:
errors['email'] = "Email field is required."
if len(postData['password']) < 8:
errors['password'] = "Password field must contain at least 8 characters."
if postData['password'] != postData['cpassword']:
errors['passwords'] = "Passwords must match!"
return errors
class User(models.Model):
first_name = models.CharField(max_length=55)
last_name = models.CharField(max_length=55)
email = models.CharField(max_length=155)
password = models.CharField(max_length=255)
objects = UserManager() | true |
19672b78ade2cdcc993aeed2e19ac1582e7fa29f | Python | markbrough/uk-cooperatives | /scrape.py | UTF-8 | 1,695 | 2.546875 | 3 | [
"MIT"
] | permissive | import urllib
import urllib2
import json
import unicodecsv
URL = "http://www.co-operative.coop/Controls/StoreFinder/storefinderservice.asmx/GetStoreInfoByID"
headers = [
('User-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:37.0) Gecko/20100101 Firefox/37.0'),
('Accept', 'application/json, text/javascript, */*; q=0.01'),
('Content-Type', 'application/json; charset=utf-8'),
('Pragma', 'no-cache'),
('X-Requested-With', 'XMLHttpRequest')
]
headers = dict(map(lambda x: (x[0], x[1]), headers))
csv_headers = ['id', 'Name', 'Mon', 'Tues', 'Weds', 'Thurs', 'Fri', 'Sat',
'Sun', 'Address_1', 'Address_2', 'Address_3', 'Address_4', 'Address_5',
'Postcode', 'Tel', 'type', 'part_of']
csvf = open("coop.csv", 'w')
csvout = unicodecsv.DictWriter(csvf, fieldnames=csv_headers)
csvout.writerow(dict(map(lambda k: (k,k), csv_headers)))
# Think they start at this number, but I could be wrong...
for store_id in range(3634501, 3649999):
print store_id
data = '{id:"%s"}' % store_id
req = urllib2.Request(URL, data, headers)
try:
response = urllib2.urlopen(req)
except urllib2.HTTPError:
continue
jsond = json.loads(response.read())
td = json.loads(jsond['d'])[0]
csvout.writerow({
'id': td[0],
'Name': td[3],
'Mon': td[4],
'Tues': td[5],
'Weds': td[6],
'Thurs': td[7],
'Fri': td[8],
'Sat': td[9],
'Sun': td[10],
'Address_1': td[11],
'Address_2': td[12],
'Address_3': td[13],
'Address_4': td[14],
'Address_5': td[15],
'Postcode': td[16],
'Tel': td[17],
'type': td[29],
'part_of': td[30],
})
| true |
fe83205c7238455a8dc0bf9d7105dfa979484c8f | Python | kjco/bioinformatics-algorithms | /ba3d-db-graph/db_graph.py | UTF-8 | 1,490 | 3.671875 | 4 | [
"MIT"
] | permissive | # Programming solution for:
# Construct the De Bruijn Graph of a String
# http://rosalind.info/problems/ba3d/
#
# Given a genome Text, PathGraphk(Text) is the path consisting of |Text| - k +
# 1 edges, where the i-th edge of this path is labeled by the i-th k-mer in
# Text and the i-th node of the path is labeled by the i-th (k - 1)-mer in
# Text. The de Bruijn graph DeBruijnk(Text) is formed by gluing identically
# labeled nodes in PathGraphk(Text).
#
# **De Bruijn Graph from a String Problem**
#
# Construct the de Bruijn graph of a string.
# - Given: An integer k and a string Text.
# - Return:DeBruijnk(Text), in the form of an adjacency list.
def comp_string(text,k):
comp_list = []
for i in range(len(text)-k+1):
comp = text[i:i+k]
comp_list.append(comp)
lex_comp_list = sorted(comp_list)
return lex_comp_list
# Sample test input:
# input_text = 'AAGATTCTCTAC'
# input_k = 4
with open('dataset_53_6.txt','r') as f:
input_k = int(f.readline().rstrip('\n'))
input_text = f.readline().rstrip('\n')
kmer_list = comp_string(input_text,input_k-1)
d = dict()
for kmer in kmer_list:
v_list = []
for alt in kmer_list:
if kmer[1:len(kmer)] == alt[0:len(alt)-1]:
v_list.append(alt)
d[kmer] = v_list
for key in sorted(d.iterkeys()):
print "%s -> %s" % (key, ','.join(sorted(list(set(d[key])))))
# list(set(my_list)) removes duplicates in list
| true |
943176ef5e80230eb47c51ea61ae3bfb72a0f270 | Python | serkef/covid_bot | /gsheet_bot/fetchers.py | UTF-8 | 6,827 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | """ A module for all Fetcher classes """
import logging
import socket
import pandas as pd
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from gsheet_bot.config import (
GSHEET_API_SERVICE_ACCOUNT_FILE,
GSHEET_SHEET_DAILY_NAME,
GSHEET_SPREADSHEET_ID,
DB_GET_LATEST_UPDATES,
DB_GET_TOTAL_COUNTS,
DbSession,
DB_INSERT_RAW_DAILY_DATA,
GSHEET_SHEET_LIVE_NAME,
DB_INSERT_RAW_HOME_DATA,
)
from gsheet_bot.utilities import read_file
socket.setdefaulttimeout(600)
class GsheetFetcher:
""" A generic fetcher for Google sheets. Knows how to auth and fetch. """
def __init__(self, spreadsheet_id, spreadsheet_range, scopes=None):
self.scopes = scopes or ["https://www.googleapis.com/auth/spreadsheets"]
self.api = self.get_gsheet_api()
self.spreadsheet_id = spreadsheet_id
self.spreadsheet_range = spreadsheet_range
self.db = DbSession().bind
def get_gsheet_api(self):
""" Initializes Google API using service account """
credentials = service_account.Credentials.from_service_account_file(
filename=GSHEET_API_SERVICE_ACCOUNT_FILE, scopes=self.scopes
)
service = build("sheets", "v4", credentials=credentials)
return service.spreadsheets()
def data(self):
""" Fetches data from gsheet """
logger = logging.getLogger("GsheetFetcher.fetch")
logger.debug("Fetching data...")
try:
return (
self.api.values()
.get(spreadsheetId=self.spreadsheet_id, range=self.spreadsheet_range)
.execute()
)
except (HttpError, socket.timeout) as exc:
logger.error("Cannot fetch values.", exc_info=True)
return
class DailyData(GsheetFetcher):
MAX_YIELD_SIZE = 10
def __init__(self):
super().__init__(
spreadsheet_id=GSHEET_SPREADSHEET_ID,
spreadsheet_range=GSHEET_SHEET_DAILY_NAME,
)
def fetch(self):
""" Fetches and process gsheet data. Returns a well structured data frame """
logger = logging.getLogger("DailyData.fetch")
data = self.data()
if data is None:
logger.debug("Fetched no data")
return
logger.info("Processing fetched data...")
df = pd.DataFrame(data["values"]).iloc[3:, 1:67] # col: BL (Mar 17)
df.columns = df.iloc[0] # Set first line as headers
df = (
df.drop(df.index[0]) # Remove first row
.set_index(df.columns[0]) # Set first column as index
.unstack() # transform to unpivoted
.replace(r"^\s*$", "0", regex=True) # replace empties
.reset_index() # Fix index
)
df = df.drop(df[df[df.columns[1]].replace("", pd.NaT).isnull()].index)
df.columns = ["rec_dt", "rec_territory", "rec_value"]
df.rec_dt = pd.to_datetime(df.rec_dt, utc=True).dt.date
df.rec_value = pd.to_numeric(
df.rec_value.fillna("0").str.replace("+", "").str.replace(",", ""),
errors="coerce",
)
df.rec_value = pd.to_numeric(df.rec_value.fillna("0"))
df = df.sort_values(by=["rec_dt", "rec_territory"])
return df
def process(self):
""" Processes data and stores to db """
logger = logging.getLogger("DailyData.process")
daily_data = self.fetch()
if daily_data is None:
logger.debug("Fetched empty dataset")
return
logger.info("Storing processed data...")
daily_data.to_sql(
"latest_daily_data", self.db, if_exists="replace", index=False
)
self.db.execute(
read_file(DB_INSERT_RAW_DAILY_DATA),
[
(rec.rec_dt, rec.rec_territory, rec.rec_value)
for _, rec in daily_data.iterrows()
],
)
latest = pd.read_sql(read_file(DB_GET_LATEST_UPDATES), con=self.db)
latest.to_sql("post_daily_data", self.db, if_exists="append", index=False)
if len(latest) <= self.MAX_YIELD_SIZE:
return latest
logger.warning("Too many changes. Won't post")
logger.warning(latest.to_dict())
def updates(self):
""" Iterate over the latest fetched and processed """
df = self.process()
if df is None:
return
for _, entry in df.iterrows():
total_count = self.db.execute(
read_file(DB_GET_TOTAL_COUNTS).format(
territory=entry.rec_territory.replace("'", "''")
)
).fetchone()
yield int(total_count[0]), entry.rec_dt, entry.rec_territory, int(
entry.rec_value
)
class HomeData(GsheetFetcher):
def __init__(self):
super().__init__(
spreadsheet_id=GSHEET_SPREADSHEET_ID,
spreadsheet_range=GSHEET_SHEET_LIVE_NAME,
)
def fetch(self):
""" Fetches and process gsheet data. Returns a well structured data frame """
logger = logging.getLogger("HomeData.fetch")
data = self.data()
if data is None:
logger.debug("Fetched no data")
return
logger.info("Processing fetched data...")
df = pd.DataFrame(data["values"]).iloc[3:, [2, 4, 8, 13, 17, 21, 24]]
df = df.replace(r"^\s*$", "0", regex=True).fillna(0).reset_index(drop=True)
df = df.drop(df[df[df.columns[0]].replace("0", pd.NaT).isnull()].index)
val_cols = ["cases", "deaths", "recovered", "severe", "tested", "active"]
df.columns = ["rec_territory"] + val_cols
for field in val_cols:
df[field] = pd.to_numeric(
df[field].fillna("0").str.replace(",", ""), errors="coerce"
)
df[field] = pd.to_numeric(df[field].fillna("0"))
return df
def process(self):
""" Processes data and stores to db """
logger = logging.getLogger("HomeData.process")
home_data = self.fetch()
if home_data is None:
logger.debug("Fetched empty dataset")
return
logger.info("Storing processed data...")
home_data.to_sql("latest_home_data", self.db, if_exists="replace", index=False)
self.db.execute(
read_file(DB_INSERT_RAW_HOME_DATA),
[
(
rec.rec_territory,
rec.cases,
rec.deaths,
rec.recovered,
rec.severe,
rec.tested,
rec.active,
)
for _, rec in home_data.iterrows()
],
)
| true |
7a902e2fd93cfffcb4475dd72116eeed999468e3 | Python | darren6337/PLIFluorescence | /plif_temperature.py | UTF-8 | 7,415 | 2.6875 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""
PLIF Temperature Calculator
Created on Wed Feb 3 16:51:48 2016
@author: Darren Banks
plif_temperature calculates temperature in a plane of rhodamine-B solution
based on the intensity at which the rhodamine fluoresces under planar laser
irradiation. plif_temperature requires the module plif_tools to run.
"""
import logging
import matplotlib.pyplot as plt
import numpy as np
from os import makedirs
from os.path import exists
import plif_tools as pt
import sys
""" Logging setup """
logger = logging.getLogger('plif')
logger.setLevel(logging.DEBUG)
con_format = '%(asctime)s - %(name)s - %(levelname)-8s: %(message)s'
console_format = logging.Formatter(con_format, datefmt='%H:%M:%S')
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(console_format)
logger.addHandler(console_handler)
""" Create console handler. """
log_file = 'C:\\Users\\Darren\\Documents\\GitHub\\PLIFluorescence\\debug.log'
if not exists(log_file):
file = open(log_file, 'a')
file.close()
log_format = '%(asctime)s %(name)-24s %(levelname)-8s %(message)s'
logfile_format = logging.Formatter(log_format, datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logfile_format)
logger.addHandler(file_handler)
""" Create debug logging file handler. """
info_file = 'C:\\Users\\Darren\\Documents\\GitHub\\PLIFluorescence\\info.log'
if not exists(info_file):
file = open(info_file, 'a')
file.close()
info_handler = logging.FileHandler(info_file, mode='w')
info_handler.setLevel(logging.INFO)
info_handler.setFormatter(logfile_format)
logger.addHandler(info_handler)
""" Creating info logging file handler. """
logger.debug('Starting.')
plt.ioff
""" Suppressing graph output to the iPython console. """
""" Literals """
num_reference_images = 100
""" Number of frames to establish base fluorescence within images. """
grid_number = 40
""" Number of grid cells applied to the images for analysis. """
want_plots = False
""" If want_plots is False, the temperature surface plots will
not be produced. Generally a time-saving value if False.
"""
plot_path = 'figures 2'
""" The folder name that will contain temperatures plots. """
plot_type = '.png'
""" Image file extension for saving results. """
results = 'temperatures 2.xlsx'
""" Name of MS Excel file to save results. """
statistics = 'statistics 2.xlsx'
""" Name of MS Excel file to save summarizing statistics. """
plot_width = 4
""" The base width in inches for output plots. """
plt.rc('font', family='serif', size=24.0, serif='Times New Roman')
""" Set the default font for plotting to Times New Roman, so it
matches that used in the paper.
"""
""" Image import """
root_directory = ('I:\\PLIF\\test 11\\images 2 - Copy')
if not exists(root_directory):
logger.error('Experiment directory does not exist!')
sys.exit()
logger.info('Directory: ' + root_directory)
""" Directory containing experiment images and calibration. """
figure_path = root_directory + '\\' + plot_path
""" Directory for result figures to be saved. """
if not exists(figure_path):
makedirs(figure_path)
[image_path, calib_paths] = pt.exptDirectory(root_directory, '', 'cal')
all_images = pt.listImages(image_path)
all_averages = pt.gridAverage(all_images, grid_number)
reference_averages = all_averages[:num_reference_images]
image_averages = all_averages[num_reference_images:]
logger.debug('First {} images used as reference'.format(num_reference_images))
""" Take the RGB mean value for the images in each grid square. """
aspect_ratio = pt.getAspectRatio(all_images[0])
logger.info('File import complete')
""" Calibration of intensity to temperature """
mean_reference_averages = np.mean(reference_averages)
""" Take the average of each grid square over the collection of
calibration images.
"""
calib_temperatures = [path[-2:] for path in calib_paths]
calib_image_sets = [pt.listImages(path) for path in calib_paths]
""" Gather the images located in the calibration directories. """
calib_averages = pt.getCalibrationAverages(calib_image_sets,
calib_temperatures, grid_number)
""" Apply grid and get RGB averages for each calibration temperature. """
grid_slopes = pt.getGridSlopes(calib_averages, calib_temperatures)
logger.info('Temperature calibration complete.')
""" Calculating temperature """
delta_intensity = image_averages - mean_reference_averages
delta_temperature = delta_intensity / grid_slopes
delta_temperature.to_excel(image_path+'\\temperature_deltas.xlsx')
plot_temperatures = delta_intensity / grid_slopes + int(calib_temperatures[0])
""" Calculate the temperature based on the difference between the
calibration and the image's grid RGB averages.
"""
if min(plot_temperatures.min()) < 25:
logger.warn('Subcooled, possibly erroneous temperatures')
plot_temperatures.to_excel(image_path + '\\' + results)
""" Save the calculated temperatures for analysis. """
""" Reporting the temperature statistics. """
stats_list = pt.getTemperatureStats(plot_temperatures, image_path, statistics)
pt.plotTemperatureStats(stats_list, image_path, plot_type)
""" Plotting temperature contour in each video frame. """
if want_plots:
z_minimum = 25
z_maximum = 100
""" User sets the graph maximum and minimum temperature values. """
plot_range = np.arange(grid_number)
x_grid, y_grid = np.meshgrid(plot_range, plot_range)
""" Setting up the X and Y array for plotting purposes. """
temperature_intervals = np.arange(z_minimum, z_maximum, 1)
""" The temperature range to scale the color map. """
fig = plt.figure(figsize=(2.5*plot_width, 2.0*plot_width/aspect_ratio))
for index, row in plot_temperatures.iterrows():
frame_title = 'Frame {}'.format(index-99)
""" Title of each plot corresponds to its frame number in video. """
plot_temperature_array = np.reshape(row, (grid_number, grid_number))
""" plotTemperatureArray is the calculated temperature for a
3-D surface plot. It takes the row of the temperature
dataFrame and fits it to the x- and y-grid set on the
image during analysis.
"""
plt.contourf(x_grid, y_grid, plot_temperature_array,
temperature_intervals, cmap='jet', extend='both',
vmin=z_minimum, vmax=z_maximum)
plt.title(frame_title)
plt.xticks(np.arange(0, grid_number, 1))
plt.yticks(np.arange(0, grid_number, 1))
plt.colorbar()
plt.grid(color='k', linestyle='solid', which='both')
""" Creating and formatting the plot with a colormap, the
previously set Z limits, ticks with intervals of 1,
and a black grid.
"""
""" Save the figure within a subfolder of the initial
directory, and then clear the figure.
"""
plt.savefig(figure_path + '\\' + frame_title + plot_type, dpi=50)
plt.clf()
if np.mod(index-99, 100) == 0:
logger.debug('Frame {} graphed'.format(index-99))
""" Iterating over the frames. """
plt.close('all')
if not want_plots:
logger.info('Temperatures not plotted.')
logger.info('Complete\n')
| true |
f958606cbfcc171249a87a6d69810cef33a1edb3 | Python | baha312/Chapter1_Part2_Task5 | /task5.py | UTF-8 | 387 | 4.125 | 4 | [] | no_license | from math import ceil
# Read an integer:
a = int(input("Gr. a: "))
b = int(input("Gr. b: "))
c = int(input("Gr. c: "))
# Math
# ceil = возвращает предельное значение х, т.е. наименьшее целое число не меньше, чем х
classa=ceil(a/2)
classb=ceil(b/2)
classc=ceil(c/2)
classall=(classa+classb+classc)
print("%s" % classall) | true |
50334121cc900dbb8289cb0069bb709f2ca4b39a | Python | CarlosVillarrealSi/LookupBuy | /LookupBuy/best_price.py | UTF-8 | 1,350 | 2.984375 | 3 | [] | no_license | import pandas as pd
from LookupBuy.concat_files import load_csv2df
def best_price_by_list(data, lista):
selection = (
data.groupby(['Fecha','Lugar', 'Producto'])['Precio'].min()
.unstack(level=0)
.swaplevel()
.sort_index()
.sort_index(axis=1)
.fillna(method='ffill', axis=1)
.iloc[:, -1]
.unstack()
.loc[lista]
)
def review(item):
return pd.Series({
'Suma': item.sum(),
'p_value': item[item.notna()].size / item.size ,
'missing': item[item.isna()].index.to_list()
})
def cheapest(item):
return item[item['Suma'] == item['Suma'].min()].iloc[-1]
res = (
selection.apply(review, axis=0)
.T.reset_index()
.groupby(['p_value']).apply(cheapest)
)
return res
if __name__ == '__main__':
data = load_csv2df()
product_list = ['arroz', 'frijoles']
print(best_price_by_list(data=data, lista=product_list))
print('-'* 100)
product_list = ['pan', 'queso', 'tomate']
print(best_price_by_list(data=data, lista=product_list))
print('-' * 100)
product_list = [ 'queso', 'tomate']
print(best_price_by_list(data=data, lista=product_list))
print('-' * 100)
product_list = [ 'cereal', 'jugo']
print(best_price_by_list(data=data, lista=product_list))
| true |
76941ddfd2da8ca12680625053db4fa1c60c7704 | Python | cal-app/char-rnn | /utils.py | UTF-8 | 307 | 3.015625 | 3 | [] | no_license | import io
def text_cleaner(in_path, charset, out_path):
with io.open(in_path, encoding='utf-8') as f:
text = f.read().lower()
textclean = text
for char in textclean:
if char not in charset:
textclean = textclean.replace(char, "")
f = open(out_path,"w")
f.write(textclean)
f.close()
| true |
af3946ade66196ea1948918e6167d0bac6dfe590 | Python | james-soohyun/CodingDojoAssignments | /Python/Assignments/9052017/multSumAvg.py | UTF-8 | 336 | 3.765625 | 4 | [] | no_license | #Multiples
#Part I
for i in range(0,1001):
if i%2==1:
print i
#Part II
for i in range(5,1000001):
if i%5==0:
print i
#Sum List
listA = [1, 2, 5, 10, 255, 3]
sumA = 0
for item in listA:
sumA+=item
print sumA
#Average List
listB = [1, 2, 5, 10, 255, 3]
sumB = 0
for item in listB:
sumB+=item
avg = sumB / len(listB)
print avg | true |
847ee5362bf534df62d1d70609cdebe39cc69762 | Python | AnHongIl/Udacity_Nanodegree | /p1_navigation/src/DQN.py | UTF-8 | 1,488 | 2.859375 | 3 | [] | no_license | import tensorflow as tf
class Network():
def __init__(self, state_size, action_size, hidden_size, learning_rate, scope):
with tf.variable_scope(scope, reuse=False):
self.states = tf.placeholder(tf.float32, [None, state_size], name='states')
self.Ys = tf.placeholder(tf.float32, [None, 1], name='targetQ')
self.actions = tf.placeholder(tf.int32, [None], name='actions')
self.one_hot_actions = tf.one_hot(self.actions, action_size)
self.hidden1 = tf.layers.dense(self.states, hidden_size, tf.nn.relu, name='hidden1')
self.hidden2 = tf.layers.dense(self.hidden1, hidden_size, tf.nn.relu, name='hidden2')
self.hidden_V1 = tf.layers.dense(self.hidden2, hidden_size / 2, tf.nn.relu, name='hidden_V1')
self.V = tf.layers.dense(self.hidden_V1, 1, None, name="state_function")
self.hidden_As1 = tf.layers.dense(self.hidden2, hidden_size / 2, tf.nn.relu, name='hidden_As1')
self.As = tf.layers.dense(self.hidden_As1, action_size, None, name="action_function")
self.Qs = self.V + tf.subtract(self.As, tf.reduce_mean(self.As, axis=1, keepdims=True))
self.Q = tf.reduce_sum(tf.multiply(self.Qs, self.one_hot_actions), axis=1, keepdims=True)
self.loss = tf.reduce_mean(tf.square(self.Ys - self.Q))
self.opt = tf.train.AdamOptimizer(learning_rate).minimize(self.loss) | true |
d082e9882f3ce0ccd9ae2bf2329d527f182dacde | Python | sungjae-cho/my-python-utils | /shuffle_np_arrays.py | UTF-8 | 579 | 3.765625 | 4 | [] | no_license | import numpy as np
def shuffle_np_arrays(x, y):
'''
This only shuffle two numpy arrays along 0-dimension.
Reference: https://tech.pic-collage.com/tips-of-numpy-shuffle-multiple-arrays-e4fb3e7ae2a
'''
# The dimension to shuffle is 0.
dim_to_shuffle = 0
# Generate the permutation index array.
permutation = np.random.permutation(x.shape[dim_to_shuffle])
# Shuffle the arrays by giving the permutation in the square brackets.
shuffled_x = x[permutation]
shuffled_y = y[permutation]
return shuffled_x, shuffled_y
| true |
44ed47006bdb2e9f416be9a19eab50fb867088f4 | Python | nekapoor7/Python-and-Django | /IMP_CONCEPTS/String/divide_stringqeually.py | UTF-8 | 152 | 3.625 | 4 | [] | no_license | #Program to divide a string in 'N' equal parts.
string = str(input())
"""#Stores the length of the string """
length = len(string)
n = int(input())
| true |
3ad43861e925850e68e2faecbf65fc1609cd8981 | Python | Hironobu-Kawaguchi/atcoder | /atcoder/abc176_d_01bfs_pypy.py | UTF-8 | 1,331 | 2.703125 | 3 | [] | no_license | # https://atcoder.jp/contests/abc176/tasks/abc176_d
import sys
# input = sys.stdin.buffer.readline
# sys.setrecursionlimit(10 ** 7)
from collections import deque
from itertools import product
INF = 1001001001
DX = [ 1, 0,-1, 0]
DY = [ 0, 1, 0,-1]
H, W = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
ch -= 1; cw -= 1; dh -= 1; dw -= 1;
S = [input() for _ in range(H)]
visited = [[False]*W for _ in range(H)]
cost = [[INF]*W for _ in range(H)]
cost[ch][cw] = 0
que = deque()
que.appendleft((ch, cw))
while que:
x, y = que.popleft()
if visited[x][y]: continue
visited[x][y] = True
if x==dh and y==dw: break
for dx, dy in zip(DX, DY):
nx = x + dx
ny = y + dy
if nx<0 or nx>=H: continue
if ny<0 or ny>=W: continue
if S[nx][ny]=='#': continue
cost[nx][ny] = min(cost[nx][ny], cost[x][y])
que.appendleft((nx, ny))
for i, j in product(range(-2, 3), repeat=2):
nx = x + i
ny = y + j
if nx<0 or nx>=H: continue
if ny<0 or ny>=W: continue
if S[nx][ny]=='#': continue
if cost[nx][ny]<cost[x][y] + 1: continue
cost[nx][ny] = min(cost[nx][ny], cost[x][y] + 1)
que.append((nx, ny))
if visited[dh][dw]:
print(cost[dh][dw])
else:
print(-1)
| true |
aa899c4f4b5854d12ed68ddd1319147ea1137d40 | Python | PythonStriker/calculator | /version_2.1.py | UTF-8 | 11,630 | 2.921875 | 3 | [] | no_license | from tkinter import *
from math import *
# 计算器主窗体
root = Tk()
root.geometry('250x380+600+220')
root.title('一个普通计算器 version_2.1')
root.resizable(width=False, height=False)
frame_show = Frame(width=300, height=150, bg='#dddddd')
# 主窗体顶部区域
v = StringVar()
v.set('0')
show_label = Label(frame_show, textvariable=v, width=13,bg='white', height=1,fg = '#000' ,font=("黑体", 20, "bold"), justify=LEFT,anchor='e')
show_label.pack(padx=10, pady=10)
frame_show.pack()
# 是否按下了运算符
isopear = False
# 控制弹窗个数
newWindowNumber = 0
# 操作数中小数点个数
pointnumber = 0
# 统计输入运算符个数
opearnumber = 0
# 操作序列
calc = []
# 区分计算与按键计算flag
equal_flag = False
def change(num):
global equal_flag
global isopear
global pointnumber
if isopear == False:
if v.get() == '0' and num != '.':
v.set('')
v.set(num)
elif v.get() == '0' and num == '.':
v.set('0.')
pointnumber = 1
else:
if num == '.' and pointnumber == 1:
pass
elif num == '.' and pointnumber == 0:
v.set(v.get() + num)
pointnumber = 1
else:
if equal_flag:
v.set(num)
equal_flag = False
else:
v.set(v.get() + num)
else:
if num == '.':
v.set('0.')
pointnumber = 1
elif v.get() == '-':
v.set(v.get() + num)
else:
v.set(num)
isopear = False
# 运算
def operation(sign):
global isopear
global calc
global pointnumber
global opearnumber
if isopear == False and opearnumber == 0:
calc.append(v.get())
if sign == '+':
calc.append('+')
elif sign == '-':
calc.append('-')
elif sign == '*':
calc.append('*')
elif sign == '/':
calc.append('/')
elif sign == '%':
calc.append('%')
else:
# 加上符号的情况
if sign == '+':
equal('+')
elif sign == '-':
equal('-')
elif sign == '*':
equal('*')
elif sign == '/':
equal('/')
elif sign == '%':
equal('%')
opearnumber = opearnumber + 1
isopear = True
pointnumber = 0
def equal(sign):
global calc
# 获取当前界面的数值准备运算
calc.append(v.get())
# 组成运算字符串
calcstr = ''.join('%s' % id for id in calc)
# 检测最后一位是否是运算符,是就删除
if calcstr[-1] in '+*/%':
calcstr = calcstr[0:-1]
if lastNoteZero(calcstr):
# 运算操作
if sign == '/':
new_calcstr = calcstr.replace('/', '%')
result = eval(new_calcstr)
if result == 0:
result = int(eval(calcstr))
else:
result = eval(calcstr)
else:
result = eval(calcstr)
else:
result = '输入有误!'
# 显示结果
if result != '输入有误!' and result // 10000000 == 0 and result > 0.001 or result == 0:
if type(result) == float:
v.set('%7.3f' % result)
elif type(result) == int:
v.set(result)
elif result == '输入有误!':
v.set(result)
else:
v.set('%e' % result)
calc.clear()
if result != '输入有误!':
calc.append(result)
calc.append(sign)
def button_equal():
global equal_flag
global calc
global opearnumber
global isopear
# 获取当前界面的数值准备运算
calc.append(v.get())
# 组成运算字符串
calcstr = ''.join('%s' % id for id in calc)
# 检测最后一位是否是运算符,是就删除
if calcstr[-1] in '+*/%':
calcstr = calcstr[0:-1]
if lastNoteZero(calcstr):
# 运算操作
if '/' in calcstr:
new_calcstr = calcstr.replace('/', '%')
result = eval(new_calcstr.strip())
if result == 0:
result = int(eval(calcstr.strip()))
else:
result = eval(calcstr.strip())
else:
result = eval(calcstr.strip())
else:
result = '输入有误!'
# 显示结果
if result != '输入有误!' and result > 0.001 and result//10000000 == 0 or result == 0:
if type(result) == float:
v.set('%7.3f' % result)
elif type(result) == int:
v.set(result)
elif result == '输入有误!':
v.set(result)
else:
v.set('%e' % result)
calc.clear()
opearnumber = 0
isopear = False
equal_flag = True
# 删除操作
def delete():
global pointnumber
if v.get().strip() == '' or v.get().strip() == '0':
v.set('0')
return
else:
num = len(v.get().strip())
if num > 1:
strnum = v.get()
if strnum[num - 1] == '.':
pointnumber = 0
strnum = strnum[0:num - 1]
v.set(strnum)
else:
v.set('0')
# 清空操作
def clear():
global calc
global isopear
global pointnumber
global opearnumber
global equal_flag
calc = []
opearnumber = 0
v.set('0')
isopear = False
pointnumber = 0
equal_flag = False
# 正负操作
def fan():
global calc
global isopear
strnum = v.get()
if isopear == False:
if strnum[0] == '-':
v.set(strnum[1:])
elif strnum[0] != '-' and strnum != '0':
v.set('-' + strnum)
else:
if v.get() == '-':
v.set('0')
else:
v.set('-')
# 判断除数是否为0
def lastNoteZero(String):
LenOfString = len(String)
for CharNumber in range(0, LenOfString):
if String[CharNumber] == '/' and CharNumber != LenOfString:
if String[CharNumber + 1] == '0':
return False
else:
pass
return True
def higherFunction(sign):
result = 0
flag = 0
if sign == '√x':
result = sqrt(eval(v.get()))
elif sign == 'sin':
result = sin(eval(v.get()))
elif sign == 'cos':
result = cos(eval(v.get()))
elif sign == 'tan':
result = tan(eval(v.get()))
elif sign == 'lnx':
if eval(v.get()) <= 0:
flag = 1
else:
result = log(eval(v.get()))
elif sign == 'e^x':
result = exp(eval(v.get()))
elif sign == 'log10(x)':
if eval(v.get()) <= 0:
flag = 1
else:
result = log10(eval(v.get()))
elif sign == '1/x':
if eval(v.get()) != 0:
result = eval('1'+'/'+v.get())
else:
flag = 1
else:
if v.get() == '0':
result = pi
v.set(result)
else:
result = eval(v.get())*pi
if flag == 0 :
if result < 0.001 and result // 10000000 == 0 :
if type(result) == float:
v.set('%7.3f' % result)
elif type(result) == int:
v.set(result)
else:
v.set('%e' % result)
else:
pass
def creatNewWindows():
# 计算器高级窗体
higher = Toplevel(root)
higher.title('一个高级计算器 version_2.1')
higher.geometry('240x192+852+280')
higher.resizable(width=False, height=False)
button_sin = Button(higher,text='sin', width=10, height=3, command=lambda:higherFunction('sin')).grid(row=0, column=0)
button_cos = Button(higher,text='cos', width=10, height=3, command=lambda:higherFunction('cos')).grid(row=0, column=1)
button_tan = Button(higher,text='tan', width=10, height=3, command=lambda:higherFunction('tan')).grid(row=0, column=2)
button_sqrt= Button(higher,text='√x', width=10, height=3, command=lambda:higherFunction('√x')).grid(row=1, column=0)
button_dao = Button(higher,text='1/x', width=10, height=3, command=lambda:higherFunction('1/x')).grid(row=1, column=1)
button_ln = Button(higher, text='lnx', width=10, height=3, command=lambda:higherFunction('lnx')).grid(row=1, column=2)
button_e = Button(higher, text='e^x', width=10, height=3, command=lambda:higherFunction('e^x')).grid(row=2, column=0)
button_log = Button(higher, text='log10(x)', width=10, height=3, command=lambda:higherFunction('log10(x)')).grid(row=2, column=1)
button_Pi = Button(higher, text='Π', width=10, height=3, command=lambda:higherFunction('Π')).grid(row=2, column=2)
# 按键区域
frame_bord = Frame(width=400, height=350)
button_del = Button(frame_bord, text='←', width=5, height=1, command=delete ).grid(row=0, column=0)
button_yv = Button(frame_bord, text='%', width=5, height=1, command=lambda: operation('%')).grid(row=0, column=1)
button_fan = Button(frame_bord, text='±', width=5, height=1, command=fan).grid(row=0, column=2)
button_ce = Button(frame_bord, text='CE', width=5, height=1, command=clear).grid(row=0, column=3)
button_1 = Button(frame_bord, text='1', width=5, height=2, command=lambda: change('1')).grid(row=1, column=0)
button_2 = Button(frame_bord, text='2', width=5, height=2, command=lambda: change('2')).grid(row=1, column=1)
button_3 = Button(frame_bord, text='3', width=5, height=2, command=lambda: change('3')).grid(row=1, column=2)
button_jia = Button(frame_bord, text='+', width=5, height=2, command=lambda: operation('+')).grid(row=1, column=3)
button_4 = Button(frame_bord, text='4', width=5, height=2, command=lambda: change('4')).grid(row=2, column=0)
button_5 = Button(frame_bord, text='5', width=5, height=2, command=lambda: change('5')).grid(row=2, column=1)
button_6 = Button(frame_bord, text='6', width=5, height=2, command=lambda: change('6')).grid(row=2, column=2)
button_jian = Button(frame_bord, text='-', width=5, height=2, command=lambda: operation('-')).grid(row=2, column=3)
button_7 = Button(frame_bord, text='7', width=5, height=2, command=lambda: change('7')).grid(row=3, column=0)
button_8 = Button(frame_bord, text='8', width=5, height=2, command=lambda: change('8')).grid(row=3, column=1)
button_9 = Button(frame_bord, text='9', width=5, height=2, command=lambda: change('9')).grid(row=3, column=2)
button_cheng = Button(frame_bord, text='x', width=5, height=2, command=lambda: operation('*')).grid(row=3, column=3)
button_0 = Button(frame_bord, text='0', width=5, height=2, command=lambda: change('0')).grid(row=4, column=0)
button_dian = Button(frame_bord, text='.', width=5, height=2, command=lambda: change('.')).grid(row=4, column=1)
button_deng = Button(frame_bord, text='=', width=5, height=2, command=button_equal).grid(row=4, column=2)
button_chu = Button(frame_bord, text='/', width=5, height=2, command=lambda: operation('/')).grid(row=4, column=3)
button_auther = Button(frame_bord, text='查看出版团队', width=25, height=2,command=lambda: print('It is a very nice team!This project made by Mr ma,nie,shao,song!')).grid(row=5, column=0, columnspan=4)
button_higher = Button(frame_bord, text='高级', width=5, height=1, command=creatNewWindows).grid(row=6, column=3)
frame_bord.pack(padx=10, pady=10)
root.mainloop() | true |
c2dd1ea00df102b7cc4e92274d77308ed48fbad6 | Python | SocioProphet/CodeGraph | /kaggle/python_files/sample370.py | UTF-8 | 15,152 | 3.296875 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# # Exploratory data analysis of the human protein atlas image dataset
# update 5/10/2018: beginning of cell segmentation algorithm
#
# update 5/10/2018: add red + blue channels stack and whole cell identification (does not give a clean result, though)
#
# This kernel is just the beginning of a work in progress and will be updated very often.
# We will explore the dataset available for the human protein atlas image competition. Questions we would like to answer include:
# * what channels of the image contain the relevant information
# * how much can we reduce dimensionality of data while retaining important information
# In[ ]:
#import modules
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import cv2
from PIL import Image
from collections import Counter
import os
print(os.listdir("../input"))
# ## What's in the data?
# Let's import the *train.csv* data files to see what they contain. We also define a dictionary containing the map between labels of the training data (the column *target* in *train.csv*) and their biological meaning.
# In[ ]:
#import training data
train = pd.read_csv("../input/train.csv")
print(train.head())
#map of targets in a dictionary
subcell_locs = {
0: "Nucleoplasm",
1: "Nuclear membrane",
2: "Nucleoli",
3: "Nucleoli fibrillar center" ,
4: "Nuclear speckles",
5: "Nuclear bodies",
6: "Endoplasmic reticulum",
7: "Golgi apparatus",
8: "Peroxisomes",
9: "Endosomes",
10: "Lysosomes",
11: "Intermediate filaments",
12: "Actin filaments",
13: "Focal adhesion sites",
14: "Microtubules",
15: "Microtubule ends",
16: "Cytokinetic bridge",
17: "Mitotic spindle",
18: "Microtubule organizing center",
19: "Centrosome",
20: "Lipid droplets",
21: "Plasma membrane",
22: "Cell junctions",
23: "Mitochondria",
24: "Aggresome",
25: "Cytosol",
26: "Cytoplasmic bodies",
27: "Rods & rings"
}
# Each image is a 4-channel image with the protein of interest in the green channel. It is the subcellular localization of this protein which is recorded in the *Target* column of the *train.csv* file. The red channel corresponds to microtubules, the blue channel to the nucleus and the yellow channel to the endoplasmid reticulum. Let's display the different channels of the image with ID == 1, since it contains several subcelullar locations for our protein of interest. Then we will overlay the green and yellow channel, as the yellow channel gives a good indication of the cell shape.
# In[ ]:
print("The image with ID == 1 has the following labels:", train.loc[1, "Target"])
print("These labels correspond to:")
for location in train.loc[1, "Target"].split():
print("-", subcell_locs[int(location)])
#reset seaborn style
sns.reset_orig()
#get image id
im_id = train.loc[1, "Id"]
#create custom color maps
cdict1 = {'red': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'green': ((0.0, 0.0, 0.0),
(0.75, 1.0, 1.0),
(1.0, 1.0, 1.0)),
'blue': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0))}
cdict2 = {'red': ((0.0, 0.0, 0.0),
(0.75, 1.0, 1.0),
(1.0, 1.0, 1.0)),
'green': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0))}
cdict3 = {'red': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'green': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 0.0),
(0.75, 1.0, 1.0),
(1.0, 1.0, 1.0))}
cdict4 = {'red': ((0.0, 0.0, 0.0),
(0.75, 1.0, 1.0),
(1.0, 1.0, 1.0)),
'green': ((0.0, 0.0, 0.0),
(0.75, 1.0, 1.0),
(1.0, 1.0, 1.0)),
'blue': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0))}
plt.register_cmap(name='greens', data=cdict1)
plt.register_cmap(name='reds', data=cdict2)
plt.register_cmap(name='blues', data=cdict3)
plt.register_cmap(name='yellows', data=cdict4)
#get each image channel as a greyscale image (second argument 0 in imread)
green = cv2.imread('../input/train/{}_green.png'.format(im_id), 0)
red = cv2.imread('../input/train/{}_red.png'.format(im_id), 0)
blue = cv2.imread('../input/train/{}_blue.png'.format(im_id), 0)
yellow = cv2.imread('../input/train/{}_yellow.png'.format(im_id), 0)
#display each channel separately
fig, ax = plt.subplots(nrows = 2, ncols=2, figsize=(15, 15))
ax[0, 0].imshow(green, cmap="greens")
ax[0, 0].set_title("Protein of interest", fontsize=18)
ax[0, 1].imshow(red, cmap="reds")
ax[0, 1].set_title("Microtubules", fontsize=18)
ax[1, 0].imshow(blue, cmap="blues")
ax[1, 0].set_title("Nucleus", fontsize=18)
ax[1, 1].imshow(yellow, cmap="yellows")
ax[1, 1].set_title("Endoplasmic reticulum", fontsize=18)
for i in range(2):
for j in range(2):
ax[i, j].set_xticklabels([])
ax[i, j].set_yticklabels([])
ax[i, j].tick_params(left=False, bottom=False)
plt.show()
# In[ ]:
#stack nucleus and microtubules images
#create blue nucleus and red microtubule images
nuclei = cv2.merge((np.zeros((512, 512),dtype='uint8'), np.zeros((512, 512),dtype='uint8'), blue))
microtub = cv2.merge((red, np.zeros((512, 512),dtype='uint8'), np.zeros((512, 512),dtype='uint8')))
#create ROI
rows, cols, _ = nuclei.shape
roi = microtub[:rows, :cols]
#create a mask of nuclei and invert mask
nuclei_grey = cv2.cvtColor(nuclei, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(nuclei_grey, 10, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
#make area of nuclei in ROI black
red_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)
#select only region with nuclei from blue
blue_fg = cv2.bitwise_and(nuclei, nuclei, mask=mask)
#put nuclei in ROI and modify red
dst = cv2.add(red_bg, blue_fg)
microtub[:rows, :cols] = dst
#show result image
fig, ax = plt.subplots(figsize=(8, 8))
ax.imshow(microtub)
ax.set_title("Nuclei (blue) + microtubules (red)", fontsize=15)
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.tick_params(left=False, bottom=False)
# Let's see how the targets are distributed.
# In[ ]:
labels_num = [value.split() for value in train['Target']]
labels_num_flat = list(map(int, [item for sublist in labels_num for item in sublist]))
labels = ["" for _ in range(len(labels_num_flat))]
for i in range(len(labels_num_flat)):
labels[i] = subcell_locs[labels_num_flat[i]]
fig, ax = plt.subplots(figsize=(15, 5))
pd.Series(labels).value_counts().plot('bar', fontsize=14)
# According to [Chen *et al*. 2007](https://academic.oup.com/bioinformatics/article-lookup/doi/10.1093/bioinformatics/btm206), if images are segmented into single cell regions, additional features that are not appropriate for whole fields can be calculated after *seeded watershed segmentation*. Nucleus images provide a means to identify each cell, so image segmentation may start by identification of nuclei in images. The function `cv2.connectedComponents` provides a simple and effective means to label nuclei in images. Conversely, as shown on the following notebook cell, identification of whole cells using `cv2.connectedComponents` is not as efficient, due to the less homogeneous signal in the yellow channel of the image.
# In[ ]:
#apply threshold on the nucleus image
ret, thresh = cv2.threshold(blue, 0, 255, cv2.THRESH_BINARY)
#display threshold image
fig, ax = plt.subplots(ncols=3, figsize=(20, 20))
ax[0].imshow(thresh, cmap="Greys")
ax[0].set_title("Threshold", fontsize=15)
ax[0].set_xticklabels([])
ax[0].set_yticklabels([])
ax[0].tick_params(left=False, bottom=False)
#morphological opening to remove noise
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
ax[1].imshow(opening, cmap="Greys")
ax[1].set_title("Morphological opening", fontsize=15)
ax[1].set_xticklabels([])
ax[1].set_yticklabels([])
ax[1].tick_params(left=False, bottom=False)
# Marker labelling
ret, markers = cv2.connectedComponents(opening)
# Map component labels to hue val
label_hue = np.uint8(179 * markers / np.max(markers))
blank_ch = 255 * np.ones_like(label_hue)
labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])
# cvt to BGR for display
labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)
# set bg label to black
labeled_img[label_hue==0] = 0
ax[2].imshow(labeled_img)
ax[2].set_title("Markers", fontsize=15)
ax[2].set_xticklabels([])
ax[2].set_yticklabels([])
ax[2].tick_params(left=False, bottom=False)
# In[ ]:
#apply threshold on the endoplasmic reticulum image
ret, thresh = cv2.threshold(yellow, 4, 255, cv2.THRESH_BINARY)
#display threshold image
fig, ax = plt.subplots(ncols=4, figsize=(20, 20))
ax[0].imshow(thresh, cmap="Greys")
ax[0].set_title("Threshold", fontsize=15)
ax[0].set_xticklabels([])
ax[0].set_yticklabels([])
ax[0].tick_params(left=False, bottom=False)
#morphological opening to remove noise
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
ax[1].imshow(opening, cmap="Greys")
ax[1].set_title("Morphological opening", fontsize=15)
ax[1].set_xticklabels([])
ax[1].set_yticklabels([])
ax[1].tick_params(left=False, bottom=False)
#morphological closing
closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel)
ax[2].imshow(closing, cmap="Greys")
ax[2].set_title("Morphological closing", fontsize=15)
ax[2].set_xticklabels([])
ax[2].set_yticklabels([])
ax[2].tick_params(left=False, bottom=False)
# Marker labelling
ret, markers = cv2.connectedComponents(closing)
# Map component labels to hue val
label_hue = np.uint8(179 * markers / np.max(markers))
blank_ch = 255 * np.ones_like(label_hue)
labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])
# cvt to BGR for display
labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)
# set bg label to black
labeled_img[label_hue==0] = 0
ax[3].imshow(labeled_img)
ax[3].set_title("Markers", fontsize=15)
ax[3].set_xticklabels([])
ax[3].set_yticklabels([])
ax[3].tick_params(left=False, bottom=False)
# Let's try different simple thresholding methods. Description of threshold types can be found [here](https://docs.opencv.org/3.4/d7/d4d/tutorial_py_thresholding.html) and [here](https://docs.opencv.org/3.4/d7/d1b/group__imgproc__misc.html#gaa9e58d2860d4afa658ef70a9b1115576).
# In[ ]:
#apply threshold on the endoplasmic reticulum image
ret, thresh1 = cv2.threshold(yellow, 4, 255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(yellow, 4, 255, cv2.THRESH_TRUNC)
ret, thresh3 = cv2.threshold(yellow, 4, 255, cv2.THRESH_TOZERO)
#display threshold images
fig, ax = plt.subplots(ncols=3, figsize=(20, 20))
ax[0].imshow(thresh1, cmap="Greys")
ax[0].set_title("Binary", fontsize=15)
ax[1].imshow(thresh2, cmap="Greys")
ax[1].set_title("Trunc", fontsize=15)
ax[2].imshow(thresh3, cmap="Greys")
ax[2].set_title("To zero", fontsize=15)
# *To zero* simple thresholding is not adapted at all for identifying cell boundaries based on the yellow channel. Even after playing with the upper and lower parameter values, no satisfactory result is obtained. *Binary* and *truncate* methods work better. Let's see how *connectedComponents* work after both thresholding methods.
# In[ ]:
fig, ax = plt.subplots(ncols=4, figsize=(20, 20))
#morphological opening to remove noise after binary thresholding
kernel = np.ones((5,5),np.uint8)
opening1 = cv2.morphologyEx(thresh1, cv2.MORPH_OPEN, kernel)
ax[0].imshow(opening1, cmap="Greys")
ax[0].set_title("Morphological opening (binary)", fontsize=15)
ax[0].set_xticklabels([])
ax[0].set_yticklabels([])
ax[0].tick_params(left=False, bottom=False)
#morphological closing after binary thresholding
closing1 = cv2.morphologyEx(opening1, cv2.MORPH_CLOSE, kernel)
ax[1].imshow(closing1, cmap="Greys")
ax[1].set_title("Morphological closing (binary)", fontsize=15)
ax[1].set_xticklabels([])
ax[1].set_yticklabels([])
ax[1].tick_params(left=False, bottom=False)
#morphological opening to remove noise after truncate thresholding
kernel = np.ones((5,5),np.uint8)
opening2 = cv2.morphologyEx(thresh2, cv2.MORPH_OPEN, kernel)
ax[2].imshow(opening2, cmap="Greys")
ax[2].set_title("Morphological opening (truncate)", fontsize=15)
ax[2].set_xticklabels([])
ax[2].set_yticklabels([])
ax[2].tick_params(left=False, bottom=False)
#morphological closing after truncate thresholding
closing2 = cv2.morphologyEx(opening2, cv2.MORPH_CLOSE, kernel)
ax[3].imshow(closing2, cmap="Greys")
ax[3].set_title("Morphological closing (truncate)", fontsize=15)
ax[3].set_xticklabels([])
ax[3].set_yticklabels([])
ax[3].tick_params(left=False, bottom=False)
fig, ax = plt.subplots(ncols=2, figsize=(10, 10))
# Marker labelling for binary thresholding
ret, markers1 = cv2.connectedComponents(closing1)
# Map component labels to hue val
label_hue1 = np.uint8(179 * markers1 / np.max(markers1))
blank_ch1 = 255 * np.ones_like(label_hue1)
labeled_img1 = cv2.merge([label_hue1, blank_ch1, blank_ch1])
# cvt to BGR for display
labeled_img1 = cv2.cvtColor(labeled_img1, cv2.COLOR_HSV2BGR)
# set bg label to black
labeled_img1[label_hue1==0] = 0
ax[0].imshow(labeled_img1)
ax[0].set_title("Markers (binary)", fontsize=15)
ax[0].set_xticklabels([])
ax[0].set_yticklabels([])
ax[0].tick_params(left=False, bottom=False)
# Marker labelling for truncate thresholding
ret, markers2 = cv2.connectedComponents(closing2)
# Map component labels to hue val
label_hue2 = np.uint8(179 * markers2 / np.max(markers2))
blank_ch2 = 255 * np.ones_like(label_hue2)
labeled_img2 = cv2.merge([label_hue2, blank_ch2, blank_ch2])
# cvt to BGR for display
labeled_img2 = cv2.cvtColor(labeled_img2, cv2.COLOR_HSV2BGR)
# set bg label to black
labeled_img2[label_hue2==0] = 0
ax[1].imshow(labeled_img2)
ax[1].set_title("Markers (truncate)", fontsize=15)
ax[1].set_xticklabels([])
ax[1].set_yticklabels([])
ax[1].tick_params(left=False, bottom=False)
# At this point it's not clear if truncate thresholding is an improvement compared to binary thresholding. Some cells are fused to each other while they should not be.
#
# On the other hand. Adaptive thresholding methods apply a different threshold on different parts of the image, let's see how well it does on our images. See [here](https://docs.opencv.org/3.4/d7/d1b/group__imgproc__misc.html#gaa42a3e6ef26247da787bf34030ed772c) for more explanations.
# In[ ]:
#apply adaptive threshold on endoplasmic reticulum image
y_blur = cv2.medianBlur(yellow, 3)
#apply adaptive thresholding
ret,th1 = cv2.threshold(y_blur, 5,255, cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(y_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, 3)
th3 = cv2.adaptiveThreshold(y_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, 3)
#display threshold images
fig, ax = plt.subplots(ncols=3, figsize=(20, 20))
ax[0].imshow(th1, cmap="Greys")
ax[0].set_title("Binary", fontsize=15)
ax[1].imshow(th2, cmap="Greys_r")
ax[1].set_title("Adaptive: mean", fontsize=15)
ax[2].imshow(th3, cmap="Greys_r")
ax[2].set_title("Adaptive: gaussian", fontsize=15)
# In[ ]:
| true |
ae361972238f6e9935731de59162521da6eb9cc0 | Python | Berteun/adventofcode2018 | /day13/day13.py | UTF-8 | 3,310 | 3.1875 | 3 | [] | no_license | import sys
def read_input():
f = open("input.txt")
grid = [list(l.strip('\n')) for l in f]
carts = []
for y in range(len(grid)):
for x in range(len(grid[y])):
if grid[y][x] in ('^', 'v'):
carts.append((y, x, grid[y][x], 0))
grid[y][x] = '|'
if grid[y][x] in ('<', '>'):
carts.append((y, x, grid[y][x], 0))
grid[y][x] = '-'
return grid, carts
def print_state(track, carts):
c = {}
for (y, x, d, s) in carts:
c[(y,x)] = d
for y in range(len(track)):
for x in range(len(track[y])):
if (y,x) in c:
sys.stdout.write(c[(y,x)])
else:
sys.stdout.write(track[y][x])
sys.stdout.write("\n")
sys.stdout.write("\n")
def evaluate(track, carts):
adjust = {
'^' : (-1, 0),
'<' : ( 0,-1),
'>' : ( 0, 1),
'v' : ( 1, 0),
}
while True:
carts.sort()
print carts
new_carts = []
old_locations = set((y,x) for (y,x,_,_) in carts)
new_locations = set()
crashed = set()
for (y, x, direction, state) in carts:
if (y,x) in crashed:
continue
new_y = y + adjust[direction][0]
new_x = x + adjust[direction][1]
new_state = state
new_direction = direction
if track[new_y][new_x] == '\\':
new_direction = {
'^' : '<',
'<' : '^',
'>' : 'v',
'v' : '>',
}[direction]
elif track[new_y][new_x] == '/':
new_direction = {
'^' : '>',
'<' : 'v',
'>' : '^',
'v' : '<',
}[direction]
elif track[new_y][new_x] == '+':
new_direction = {
('^',0) : ('<'),
('^',1) : ('^'),
('^',2) : ('>'),
('<',0) : ('v'),
('<',1) : ('<'),
('<',2) : ('^'),
('>',0) : ('^'),
('>',1) : ('>'),
('>',2) : ('v'),
('v',0) : ('>'),
('v',1) : ('v'),
('v',2) : ('<'),
}[direction,state]
new_state = (state + 1) % 3
if (new_y, new_x) in old_locations:
crashed.add((new_y, new_x))
old_locations.remove((new_y,new_x))
elif (new_y, new_x) in new_locations:
new_carts = [(cy,cx,cd,cs) for (cy,cx,cd,cs) in new_carts if (cy,cx) != (new_y,new_x)]
new_locations.remove((new_y,new_x))
else:
old_locations.remove((y,x))
new_locations.add((new_y, new_x))
new_carts.append((new_y, new_x, new_direction, new_state))
carts = new_carts
if len(carts) == 1:
print "{},{}".format(carts[0][1],carts[0][0])
return
#print_state(track, carts)
def run():
track, carts = read_input()
evaluate(track, carts)
if __name__ == '__main__':
run()
| true |
71a3747bde6768dce5ed8589d690e0f545fd17fe | Python | danyesss/parakeet | /lab3/bulldog.py | UTF-8 | 3,592 | 3.15625 | 3 | [] | no_license | from graph import *
import math
windowSize(649, 918)
canvasSize(649, 918)
def elips(x1,y1,x2,y2):
a=(x2-x1)/2
b=(y2-y1)/2
kost=[]
for fi in range(1,360,1):
y=int(b*math.sin(fi*math.pi/180)+y1+b)
x=int(a*math.cos(fi*math.pi/180)+x1+a)
kost.append((x,y))
obj=polygon(kost)
def dog(x, a, y, b):
penColor('gray')
brushColor('gray')
elips(x*125+a,y*194+b,x*263+a,y*283+b)
brushColor('gray')
elips(x*147+a,y*248+b,x*191+a,y*334+b)
brushColor('gray')
elips(x*137+a,y*232+b,x*103+a,y*307+b)
brushColor('gray')
elips(x*125+a,y*311+b,x*80+a,y*296+b)
brushColor('gray')
elips(x*186+a,y*329+b,x*130+a,y*342+b)
brushColor('gray')
elips(x*224+a,y*191+b,x*314+a,y*260+b)
brushColor('gray')
elips(x*274+a,y*232+b,x*333+a,y*299+b)
brushColor('gray')
elips(x*309+a,y*274+b,x*329+a,y*335+b)
brushColor('gray')
elips(x*326+a,y*334+b,x*271+a,y*352+b)
brushColor('gray')
elips(x*216+a,y*225+b,x*276+a,y*180+b)
brushColor('gray')
elips(x*248+a,y*208+b,x*267+a,y*293+b)
brushColor('gray')
elips(x*267+a,y*289+b,x*223+a,y*299+b)
brushColor('gray')
elips(x*164+a,y*225+b,x*114+a,y*217+b)
penColor('black')
brushColor('gray')
polygon([[x*178+a, y*230+b], [x*178+a, y*138+b], [x*87+a, y*138+b], [x*87+a, y*230+b], [x*178+a, y*230+b]])
brushColor('gray')
elips(x*92+a,y*153+b,x*73+a,y*192+b)
brushColor('gray')
elips(x*194+a,y*154+b,x*176+a,y*190+b)
brushColor('white')
elips(x*97+a,y*162+b,x*127+a,y*176+b)
brushColor('white')
elips(x*137+a,y*162+b,x*167+a,y*176+b)
brushColor('black')
circle(x*112+a, y*169+b, 6*abs(x))
brushColor('black')
circle(x*152+a,y*169+b, 6*abs(x))
polyline([[x*148+a, y*210+b], [x*147+a, y*193+b],[x*142.5+a, y*188+b], [x*132.5+a, y*185+b],[x*122.5+a,y*188+b],[x*118+a,y*193+b],[x*117+a, y*210+b]])
brushColor('white')
polygon([[x*147+a, y*193+b],[x*142.5+a, y*188+b], [x*144.5+a, y*182+b],[x*147+a, y*193+b]])
polygon([[x*122.5+a,y*188+b],[x*118+a,y*193+b], [x*120.5+a, y*182+b],[x*122.5+a,y*188+b]])
brushColor(114, 198, 219)
polygon([(0,0), (0,1000), (1500,1000), (1500,0)])
brushColor(104,216,116)
polygon([(0,350), (0,1000), (1500,1000), (1500,350)])
brushColor(193,141,49)
for i in range(25):
polygon([(150 + 35 * i, 30), (150 + 35 * i,350), (150 + 35 * (i + 1),350), (150 + 35 * (i + 1),30)])
for i in range(16):
polygon([(25 * i,200), (25 * i,450), (25 * (i + 1),450), (25 * (i + 1),200)])
for i in range(14):
polygon([(23 * i,350), (23 * i,600), (23 * (i + 1),600), (23 * (i + 1),350)])
for i in range(25):
polygon([(350 + 30 * i,300), (350 + 30 * i,550), (350 + 30 * (i + 1),550), (350 + 30 * (i + 1),300)])
dog(-0.9, 660, 0.9, 290);
brushColor(193,141,49)
d_bud = -90
polygon([(300,400-d_bud), (300,500-d_bud), (400,550-d_bud), (400,430-d_bud)])
polygon([(400,550-d_bud), (400,430-d_bud), (450,400-d_bud), (450,500-d_bud)])
polygon([(300,400-d_bud), (370,300-d_bud), (400,430-d_bud)])
polygon([(370,300-d_bud), (400,430-d_bud), (450,400-d_bud), (410,290-d_bud)])
brushColor("black")
circle(350, 470-d_bud, 20)
x = -1
y = 1
a = 370
b = 200
##
dog(1, -20, 1, 340);
dog(-1.2, 370, 1.2 , 500);
dog(3, 100, 3, 400);
penSize(2)
brushColor('#FFFFFF')
d_ring = - 50
d_ringy = 0
elips(300-d_ring,530-d_bud-d_ringy,280-d_ring,520-d_bud-d_ringy)
elips(286-d_ring,525-d_bud-d_ringy,276-d_ring,550-d_bud-d_ringy)
d_ring = -35
d_ringy = -25
elips(300-d_ring,530-d_bud-d_ringy,280-d_ring,520-d_bud-d_ringy)
##
run() | true |
7f9412d37282eaccd6baa441b774142dd9c61b2e | Python | Nick-Omen/coursera-yandex-introduce-ml | /lessons/perceptron/main.py | UTF-8 | 1,515 | 2.875 | 3 | [] | no_license | import os
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Perceptron
from sklearn.metrics import accuracy_score
from utils import save_answer
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
train_data = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'train.csv'), header=None)
test_data = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test.csv'), header=None)
def train_perceptron(X, y) -> Perceptron:
perceptron = Perceptron(random_state=241)
perceptron.fit(X, y)
return perceptron
def run():
train = train_data.values
test = test_data.values
X_train = train[:, 1:]
y_train = train[:, 0]
X_test = test[:, 1:]
y_test = test[:, 0]
perceptron = train_perceptron(X_train, y_train)
predictions = perceptron.predict(X_test)
default_ac = accuracy_score(y_test, predictions)
print('Default accuracy:', default_ac)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train, y_train)
X_test_scaled = scaler.transform(X_test)
perceptron_scaled = train_perceptron(X_train_scaled, y_train)
predictions_scaled = perceptron_scaled.predict(X_test_scaled)
scaled_ac = accuracy_score(y_test, predictions_scaled)
print('Scaled accuracy:', scaled_ac)
diff = scaled_ac - default_ac
print('Difference between default and scaled is:', diff)
save_answer(os.path.join(BASE_DIR, 'answer.txt'), round(diff, 3))
| true |
f22a53883f417382d0de821017e6335362627fbd | Python | glotzerlab/freud | /freud/plot.py | UTF-8 | 18,732 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive | # Copyright (c) 2010-2023 The Regents of the University of Michigan
# This file is from the freud project, released under the BSD 3-Clause License.
import io
import warnings
import numpy as np
import freud
try:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.ticker import FormatStrFormatter, MaxNLocator
except ImportError:
raise ImportError("matplotlib must be installed for freud.plot.")
def _ax_to_bytes(ax):
"""Helper function to convert figure to png file.
Args:
ax (:class:`matplotlib.axes.Axes`): Axes object to plot.
Returns:
bytes: Byte representation of the diagram in png format.
"""
f = io.BytesIO()
# Sets an Agg backend so this figure can be rendered
fig = ax.figure
FigureCanvasAgg(fig)
fig.savefig(f, format="png")
fig.clf()
return f.getvalue()
def _set_3d_axes_equal(ax, limits=None):
"""Make axes of 3D plot have equal scale so that spheres appear as spheres,
cubes as cubes, etc. This is one possible solution to Matplotlib's
ax.set_aspect('equal') and ax.axis('equal') not working for 3D.
Args:
ax (:class:`matplotlib.axes.Axes`): Axes object.
limits (:math:`(3, 2)` :class:`np.ndarray`):
Axis limits in the form
:code:`[[xmin, xmax], [ymin, ymax], [zmin, zmax]]`. If
:code:`None`, the limits are auto-detected (Default value =
:code:`None`).
"""
# Adapted from https://stackoverflow.com/a/50664367
if limits is None:
limits = np.array([ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d()])
else:
limits = np.asarray(limits)
origin = np.mean(limits, axis=1)
radius = 0.5 * np.max(limits[:, 1] - limits[:, 0])
ax.set_xlim3d([origin[0] - radius, origin[0] + radius])
ax.set_ylim3d([origin[1] - radius, origin[1] + radius])
ax.set_zlim3d([origin[2] - radius, origin[2] + radius])
return ax
def box_plot(box, title=None, ax=None, image=[0, 0, 0], *args, **kwargs):
"""Helper function to plot a :class:`~.box.Box` object.
Args:
box (:class:`~.box.Box`):
Simulation box.
title (str):
Title of the graph. (Default value = :code:`None`).
ax (:class:`matplotlib.axes.Axes`): Axes object to plot.
If :code:`None`, make a new axes and figure object.
If plotting a 3D box, the axes must be 3D.
(Default value = :code:`None`).
image (list):
The periodic image location at which to draw the box (Default
value = :code:`[0, 0, 0]`).
``*args``, ``**kwargs``:
All other arguments are passed on to
:meth:`mpl_toolkits.mplot3d.Axes3D.plot` or
:meth:`matplotlib.axes.Axes.plot`.
"""
box = freud.box.Box.from_box(box)
if ax is None:
fig = plt.figure()
if box.is2D:
ax = fig.subplots()
else:
# This import registers the 3d projection
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
ax = fig.add_subplot(111, projection="3d")
if box.is2D:
# Draw 2D box
corners = [[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]]
# Need to copy the last point so that the box is closed.
corners.append(corners[0])
corners = np.asarray(corners)
corners += np.asarray(image)
corners = box.make_absolute(corners)[:, :2]
color = kwargs.pop("color", "k")
ax.plot(corners[:, 0], corners[:, 1], color=color, *args, **kwargs)
ax.set_aspect("equal", "datalim")
ax.set_xlabel("$x$")
ax.set_ylabel("$y$")
else:
# Draw 3D box
corners = np.array(
[
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1],
]
)
corners += np.asarray(image)
corners = box.make_absolute(corners)
paths = [
corners[[0, 1, 3, 2, 0]],
corners[[4, 5, 7, 6, 4]],
corners[[0, 4]],
corners[[1, 5]],
corners[[2, 6]],
corners[[3, 7]],
]
for path in paths:
color = kwargs.pop("color", "k")
ax.plot(path[:, 0], path[:, 1], path[:, 2], color=color)
ax.set_xlabel("$x$")
ax.set_ylabel("$y$")
ax.set_zlabel("$z$")
limits = [
[corners[0, 0], corners[-1, 0]],
[corners[0, 1], corners[-1, 1]],
[corners[0, 2], corners[-1, 2]],
]
_set_3d_axes_equal(ax, limits)
return ax
def system_plot(system, title=None, ax=None, *args, **kwargs):
"""Helper function to plot a system object.
Args:
system
Any object that is a valid argument to
:class:`freud.locality.NeighborQuery.from_system`.
title (str):
Title of the plot. (Default value = :code:`None`).
ax (:class:`matplotlib.axes.Axes`): Axes object to plot.
If :code:`None`, make a new axes and figure object.
(Default value = :code:`None`).
"""
system = freud.locality.NeighborQuery.from_system(system)
if ax is None:
fig = plt.figure()
if system.box.is2D:
ax = fig.subplots()
else:
# This import registers the 3d projection
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
ax = fig.add_subplot(111, projection="3d")
if system.box.is2D:
box_plot(system.box, ax=ax)
sc = ax.scatter(system.points[:, 0], system.points[:, 1], *args, **kwargs)
ax.set_aspect("equal", "datalim")
else:
box_plot(system.box, ax=ax)
sc = ax.scatter(
system.points[:, 0],
system.points[:, 1],
system.points[:, 2],
*args,
**kwargs,
)
box_min = system.box.make_absolute([0, 0, 0])
box_max = system.box.make_absolute([1, 1, 1])
points_min = np.min(system.points, axis=0)
points_max = np.max(system.points, axis=0)
limits = [
[np.min([box_min[i], points_min[i]]), np.max([box_max[i], points_max[i]])]
for i in range(3)
]
_set_3d_axes_equal(ax, limits=limits)
return ax, sc
def bar_plot(x, height, title=None, xlabel=None, ylabel=None, ax=None):
"""Helper function to draw a bar graph.
Args:
x (list): x values of the bar graph.
height (list): Height values corresponding to :code:`x`.
title (str): Title of the graph. (Default value = :code:`None`).
xlabel (str): Label of x axis. (Default value = :code:`None`).
ylabel (str): Label of y axis. (Default value = :code:`None`).
ax (:class:`matplotlib.axes.Axes`): Axes object to plot.
If :code:`None`, make a new axes and figure object.
(Default value = :code:`None`).
Returns:
:class:`matplotlib.axes.Axes`: Axes object with the diagram.
"""
if ax is None:
fig = plt.figure()
ax = fig.subplots()
ax.bar(x=x, height=height)
ax.set_title(title)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_xticks(x)
ax.set_xticklabels(x)
return ax
def clusters_plot(keys, freqs, num_clusters_to_plot=10, ax=None):
"""Helper function to plot most frequent clusters in a bar graph.
Args:
keys (list): Cluster keys.
freqs (list): Number of particles in each clusters.
num_clusters_to_plot (unsigned int): Number of largest clusters to
plot.
ax (:class:`matplotlib.axes.Axes`): Axes object to plot.
If :code:`None`, make a new axes and figure object.
(Default value = :code:`None`).
Returns:
:class:`matplotlib.axes.Axes`: Axes object with the diagram.
"""
count_sorted = sorted(
((freq, key) for key, freq in zip(keys, freqs)), key=lambda x: -x[0]
)
sorted_freqs = [i[0] for i in count_sorted[:num_clusters_to_plot]]
sorted_keys = [str(i[1]) for i in count_sorted[:num_clusters_to_plot]]
return bar_plot(
sorted_keys,
sorted_freqs,
title="Cluster Frequency",
xlabel="Keys of {} largest clusters (total clusters: "
"{})".format(len(sorted_freqs), len(freqs)),
ylabel="Number of particles",
ax=ax,
)
def line_plot(x, y, title=None, xlabel=None, ylabel=None, ax=None):
"""Helper function to draw a line graph.
Args:
x (list): x values of the line graph.
y (list): y values corresponding to :code:`x`.
title (str): Title of the graph. (Default value = :code:`None`).
xlabel (str): Label of x axis. (Default value = :code:`None`).
ylabel (str): Label of y axis. (Default value = :code:`None`).
ax (:class:`matplotlib.axes.Axes`): Axes object to plot.
If :code:`None`, make a new axes and figure object.
(Default value = :code:`None`).
Returns:
:class:`matplotlib.axes.Axes`: Axes object with the diagram.
"""
if ax is None:
fig = plt.figure()
ax = fig.subplots()
ax.plot(x, y)
ax.set_title(title)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
return ax
def histogram_plot(
values, title=None, xlabel=None, ylabel=None, ax=None, legend_labels=None
):
"""Helper function to draw a histogram graph.
Args:
values (list): values of the histogram.
title (str): Title of the graph. (Default value = :code:`None`).
xlabel (str): Label of x axis. (Default value = :code:`None`).
ylabel (str): Label of y axis. (Default value = :code:`None`).
ax (:class:`matplotlib.axes.Axes`): Axes object to plot.
If :code:`None`, make a new axes and figure object.
(Default value = :code:`None`).
Returns:
:class:`matplotlib.axes.Axes`: Axes object with the diagram.
"""
if ax is None:
fig = plt.figure()
ax = fig.subplots()
ax.hist(values)
ax.set_title(title)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if legend_labels is not None:
ax.legend(legend_labels)
return ax
def pmft_plot(pmft, ax=None):
"""Helper function to draw 2D PMFT diagram.
Args:
pmft (:class:`freud.pmft.PMFTXY2D`):
PMFTXY2D instance.
ax (:class:`matplotlib.axes.Axes`): Axes object to plot.
If :code:`None`, make a new axes and figure object.
(Default value = :code:`None`).
Returns:
:class:`matplotlib.axes.Axes`: Axes object with the diagram.
"""
from matplotlib.colorbar import Colorbar
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
# Plot figures
if ax is None:
fig = plt.figure()
ax = fig.subplots()
pmft_arr = np.copy(pmft.PMFT)
pmft_arr[np.isinf(pmft_arr)] = np.nan
xlims = (pmft.X[0], pmft.X[-1])
ylims = (pmft.Y[0], pmft.Y[-1])
ax.set_xlim(xlims)
ax.set_ylim(ylims)
ax.xaxis.set_ticks([i for i in range(int(xlims[0]), int(xlims[1] + 1))])
ax.yaxis.set_ticks([i for i in range(int(ylims[0]), int(ylims[1] + 1))])
ax.set_xlabel(r"$x$")
ax.set_ylabel(r"$y$")
ax.set_title("PMFT")
ax_divider = make_axes_locatable(ax)
cax = ax_divider.append_axes("right", size="7%", pad="10%")
im = ax.imshow(
np.flipud(pmft_arr),
extent=[xlims[0], xlims[1], ylims[0], ylims[1]],
interpolation="nearest",
cmap="viridis",
vmin=-2.5,
vmax=3.0,
)
cb = Colorbar(cax, im)
cb.set_label(r"$k_B T$")
return ax
def density_plot(density, box, ax=None):
r"""Helper function to plot density diagram.
Args:
density (:math:`\left(N_x, N_y\right)` :class:`numpy.ndarray`):
Array containing density.
box (:class:`freud.box.Box`):
Simulation box.
ax (:class:`matplotlib.axes.Axes`): Axes object to plot.
If :code:`None`, make a new axes and figure object.
(Default value = :code:`None`).
Returns:
:class:`matplotlib.axes.Axes`: Axes object with the diagram.
"""
from matplotlib.colorbar import Colorbar
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
if ax is None:
fig = plt.figure()
ax = fig.subplots()
xlims = (-box.Lx / 2, box.Lx / 2)
ylims = (-box.Ly / 2, box.Ly / 2)
ax.set_title("Gaussian Density")
ax.set_xlabel(r"$x$")
ax.set_ylabel(r"$y$")
ax_divider = make_axes_locatable(ax)
cax = ax_divider.append_axes("right", size="7%", pad="10%")
im = ax.imshow(
np.flipud(density.T), extent=[xlims[0], xlims[1], ylims[0], ylims[1]]
)
cb = Colorbar(cax, im)
cb.set_label("Density")
return ax
def voronoi_plot(box, polytopes, ax=None, color_by_sides=True, cmap=None):
"""Helper function to draw 2D Voronoi diagram.
Args:
box (:class:`freud.box.Box`):
Simulation box.
polytopes (:class:`numpy.ndarray`):
Array containing Voronoi polytope vertices.
ax (:class:`matplotlib.axes.Axes`): Axes object to plot.
If :code:`None`, make a new axes and figure object.
(Default value = :code:`None`).
color_by_sides (bool):
If :code:`True`, color cells by the number of sides.
If :code:`False`, random colors are used for each cell.
(Default value = :code:`True`).
cmap (str):
Colormap name to use (Default value = :code:`None`).
Returns:
:class:`matplotlib.axes.Axes`: Axes object with the diagram.
"""
from matplotlib import cm
from matplotlib.collections import PatchCollection
from matplotlib.colorbar import Colorbar
from matplotlib.patches import Polygon
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
if ax is None:
fig = plt.figure()
ax = fig.subplots()
# Draw Voronoi polytopes
patches = [Polygon(poly[:, :2]) for poly in polytopes]
patch_collection = PatchCollection(patches, edgecolors="black", alpha=0.4)
if color_by_sides:
colors = np.array([len(poly) for poly in polytopes])
num_colors = np.ptp(colors) + 1
else:
colors = np.random.RandomState().permutation(np.arange(len(patches)))
num_colors = np.unique(colors).size
# Ensure we have enough colors to uniquely identify the cells
if cmap is None:
if color_by_sides and num_colors <= 10:
cmap = "tab10"
else:
if num_colors > 20:
warnings.warn(
"More than 20 unique colors were requested. "
"Consider providing a colormap to the cmap "
"argument.",
UserWarning,
)
cmap = "tab20"
cmap = cm.get_cmap(cmap, num_colors)
bounds = np.arange(np.min(colors), np.max(colors) + 1)
patch_collection.set_array(np.array(colors) - 0.5)
patch_collection.set_cmap(cmap)
patch_collection.set_clim(bounds[0] - 0.5, bounds[-1] + 0.5)
ax.add_collection(patch_collection)
# Draw box
corners = [[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]]
# Need to copy the last point so that the box is closed.
corners.append(corners[0])
corners = box.make_absolute(corners)[:, :2]
ax.plot(corners[:, 0], corners[:, 1], color="k")
# Set title, limits, aspect
ax.set_title("Voronoi Diagram")
ax.set_xlim((np.min(corners[:, 0]), np.max(corners[:, 0])))
ax.set_ylim((np.min(corners[:, 1]), np.max(corners[:, 1])))
ax.set_aspect("equal", "datalim")
# Add colorbar for number of sides
if color_by_sides:
ax_divider = make_axes_locatable(ax)
cax = ax_divider.append_axes("right", size="7%", pad="10%")
cb = Colorbar(cax, patch_collection)
cb.set_label("Number of sides")
cb.set_ticks(bounds)
return ax
def diffraction_plot(
diffraction, k_values, N_points, ax=None, cmap="afmhot", vmin=None, vmax=None
):
"""Helper function to plot diffraction pattern.
Args:
diffraction (:class:`numpy.ndarray`):
Diffraction image data.
k_values (:class:`numpy.ndarray`):
:math:`k` value magnitudes for each bin of the diffraction image.
N_points (int):
Number of points in the system.
ax (:class:`matplotlib.axes.Axes`):
Axes object to plot. If :code:`None`, make a new axes and figure
object (Default value = :code:`None`).
cmap (str):
Colormap name to use (Default value = :code:`'afmhot'`).
vmin (float):
Minimum of the color scale Uses :code:`4e-6 * N_points` if
not provided or :code:`None` (Default value = :code:`None`).
vmax (float):
Maximum of the color scale. Uses :code:`0.7 * N_points` if
not provided or :code:`None` (Default value = :code:`None`).
Returns:
:class:`matplotlib.axes.Axes`: Axes object with the diagram.
"""
import matplotlib.colors
from matplotlib.colorbar import Colorbar
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
if vmin is None:
vmin = 4e-6 * N_points
if vmax is None:
vmax = 0.7 * N_points
if ax is None:
fig = plt.figure()
ax = fig.subplots()
# Plot the diffraction image and color bar
norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax)
extent = (np.min(k_values), np.max(k_values), np.min(k_values), np.max(k_values))
im = ax.imshow(
np.clip(diffraction, vmin, vmax),
interpolation="nearest",
cmap=cmap,
norm=norm,
extent=extent,
)
ax_divider = make_axes_locatable(ax)
cax = ax_divider.append_axes("right", size="7%", pad="10%")
cb = Colorbar(cax, im)
cb.set_label(r"$S(\vec{k})$")
# Set tick locations and labels
ax.xaxis.set_major_locator(MaxNLocator(nbins=6, symmetric=True, min_n_ticks=7))
ax.yaxis.set_major_locator(MaxNLocator(nbins=6, symmetric=True, min_n_ticks=7))
formatter = FormatStrFormatter("%.3g")
ax.xaxis.set_major_formatter(formatter)
ax.yaxis.set_major_formatter(formatter)
# Set title, limits, aspect
ax.set_title("Diffraction Pattern")
ax.set_aspect("equal", "datalim")
ax.set_xlabel("$k_x$")
ax.set_ylabel("$k_y$")
return ax
| true |
532ef438a6508188affbb4d97e47cb1c1a35fd82 | Python | Aasthaengg/IBMdataset | /Python_codes/p02722/s144769360.py | UTF-8 | 423 | 3.046875 | 3 | [] | no_license | n = int(input())
n_ = n-1
a = [n]
if n_ == 1:
a_ = []
else:
a_ = [n_]
for i in range(2,int(n**0.5//1+1)):
if n%i == 0:
a.append(i)
if n/i != i:
a.append(n/i)
if n_%i == 0:
a_.append(i)
if n_/i != i:
a_.append(n_/i)
ans = len(a_)
for i in a:
num = n
while num%i == 0:
num /= i
if num % i == 1:
ans += 1
print(ans) | true |
78aced0a9abdf25b9f302049032f5184376a247c | Python | nkukarl/leetcode | /find_minimum_in_rotated_sorted_array_test.py | UTF-8 | 1,204 | 3.125 | 3 | [] | no_license | from unittest import TestCase
from nose_parameterized import parameterized
from find_minimum_in_rotated_sorted_array import Solution
class TestFindMinimumInRotatedSortedArray(TestCase):
@parameterized.expand([
[
{
'nums': [1, 2, 3, 4, 5, 6, 7],
},
],
[
{
'nums': [2, 3, 4, 5, 6, 7, 1],
},
],
[
{
'nums': [3, 4, 5, 6, 7, 1, 2],
},
],
[
{
'nums': [4, 5, 6, 7, 1, 2, 3],
},
],
[
{
'nums': [5, 6, 7, 1, 2, 3, 4],
},
],
[
{
'nums': [6, 7, 1, 2, 3, 4, 5],
},
],
[
{
'nums': [7, 1, 2, 3, 4, 5, 6],
},
],
])
def test_find_min(self, kwargs):
# Setup
sol = Solution()
# Exercise
ans = sol.find_min(**kwargs)
# Verify
expected_ans = self.find_min(**kwargs)
self.assertEqual(ans, expected_ans)
def find_min(self, nums):
return min(nums)
| true |
7eab3da07bd16af4a07ea519c2d0bdb4f0556d31 | Python | bezitok/Python-Tutorial | /GiaiPhuongTrinhBacHai/PhuongTrinhBacHai.py | UTF-8 | 499 | 3.703125 | 4 | [] | no_license | import math
print("Chương trinh giải phương trình bậc hai")
a = int(input("Nhập a>0: "))
b = int(input("Nhập b: "))
c = int(input("Nhập c: "))
d = b*b - 4*a*c
if d<0:
print("Phương trình vô nghiệm")
elif d == 0:
x = float((-b) / 2 * a)
print("Phương trình có nghiệm kép là: x = ", x)
else:
x1 = ((-b) + math.sqrt(d)) / (2 * a)
x2 = ((-b) - math.sqrt(d)) / (2 * a)
print("Phương trình có 2 nghiệm phân biệt là: x1 = ", x1, " x2 = ", x2)
| true |
e0f93b9214b4305a7505f5b813aa943200912849 | Python | AndrewIjano/pgel-sat | /pgel_sat/util.py | UTF-8 | 2,313 | 2.859375 | 3 | [
"MIT"
] | permissive | def print_gelpp_max_sat_problem(function):
def name(kb, obj):
iri = obj
if obj == kb.graph.top:
return '⊤'
if obj == kb.graph.bot:
return '⊥'
if not isinstance(obj, str):
iri = obj.iri
if kb.is_existential(obj):
return f'∃{name(kb, obj.role_iri)}.{name(kb, obj.concept_iri)}'
if kb.is_individual(obj):
return '{' + name(kb, obj.iri) + '}'
if '#' not in str(iri):
return str(iri)
return ''.join(iri.split('#')[1:])
def str_axiom(kb, sub_concept, role, sup_concept):
s = f'{name(kb, sub_concept)} ⊑ '
if role != kb.graph.is_a:
s += f'∃{name(kb, role)}.'
s += name(kb, sup_concept)
return s
def is_real_axiom(kb, sub_concept, sup_arrow):
is_init = kb.graph.init in [sub_concept, sup_arrow.concept]
return not(is_init or sup_arrow.is_derivated)
def str_weight(pbox_id, weights):
return ' ∞' if pbox_id < 0 else '{:+5.3f}'.format(weights[pbox_id])
def get_ids_weights_axioms(kb, weights):
for concept in kb.concepts():
for sup_arrow in concept.sup_arrows:
sup_concept = sup_arrow.concept
role = sup_arrow.role
pbox_id = sup_arrow.pbox_id
if is_real_axiom(kb, concept, sup_arrow):
a = str_axiom(kb, concept, role, sup_concept)
w = str_weight(pbox_id, weights)
yield pbox_id, w, a
def wrapper(kb, weights):
print()
print('-' * 18, 'GEL++ MAX-SAT PROBLEM', '-' * 19)
print(' i \t\t w(Ax_i) \t\t Ax_i')
print('-' * 60)
i = 0
real_id = {}
for pbox_id, weight, axiom in get_ids_weights_axioms(kb, weights):
print('{:3}\t\t{}\t\t{}'.format(i, weight, axiom))
real_id[pbox_id] = i
i += 1
result = function(kb, weights)
print('-' * 60)
print('HAS SOLUTION:', result['success'])
if result['success']:
print('SOLUTION:', [real_id[i]
for i in result['prob_axiom_indexes']])
print('-' * 60)
print('\n')
return result
return wrapper
| true |
713c5ba80941d8645c659dd0eaf5978f3e4658e6 | Python | chakki-works/elephant_sense | /scripts/features/post_feature.py | UTF-8 | 1,045 | 2.90625 | 3 | [
"Apache-2.0"
] | permissive | import re
class PostFeature():
def __init__(self, post):
self.post = post
self._features = {}
def add(self, feature_extractor):
feature = feature_extractor.extract(self.post, self._features)
key = self.to_camel(feature_extractor.__class__.__name__.replace("Extractor", ""))
self._features[key] = feature
return self
def to_camel(self, text):
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", text)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
def to_dict(self, drop_disused_feature=True):
post_d = vars(self.post)
if "annotations" in post_d:
post_d["quality"] = self.post.quality()
del post_d["annotations"]
if drop_disused_feature:
del post_d["post_id"]
del post_d["body"]
del post_d["title"]
del post_d["url"]
del post_d["user_id"]
for f in self._features:
post_d[f] = self._features[f]
return post_d
| true |
335dbc285af5437727c72d9b6c18898efaaf78e3 | Python | itspratham/Python-tutorial | /Python_Contents/data_structures/Pattern_Programming/Pattern_numbers/patterns_of_codes/pattern16.py | UTF-8 | 248 | 3.234375 | 3 | [] | no_license | r = 7
h = 8
k = 1
for i in range(1, 9):
for j in range(i + r):
if i % 2 != 0:
print(h, end=" ")
h = h - 1
else:
print(k, end=" ")
k = k + 1
print(" ")
r = r - 2
h = 8
| true |
79904be6800ec7c55df168cbaeae2933b2a78990 | Python | AndresLindner/spotify | /SpotifyDAO.py | UTF-8 | 3,185 | 2.859375 | 3 | [
"MIT"
] | permissive | import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
class SpotifyDAO:
MAX_QUERY_RESULTS = 50
def __init__(self):
client_credentials_manager = SpotifyClientCredentials()
self.sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
def get_all_playlist_by_category(self, category, query_results=50):
playlists_refs = []
print('querying all playlists with category: {}', category)
playlists = self.sp.category_playlists(category_id=category, limit=query_results)['playlists']
while playlists:
playlists_refs = playlists_refs + playlists['items']
if playlists['next']:
playlists = self.sp.next(playlists)['playlists']
else:
playlists = None
print('completed {} playlists for: {}'.format(len(playlists_refs), category))
return playlists_refs
def enrich_playlist(self, user_id, playlist_id):
tracks_refs = []
playlist = self.sp.user_playlist(user_id, playlist_id)
tracks = playlist['tracks']
while tracks:
tracks_refs = tracks_refs + [tr for tr in playlist['tracks']['items'] if tr['track']['id'] is not None]
if tracks['next']:
tracks = self.sp.next(tracks)
else:
tracks = None
playlist['tracks']['items'] = tracks_refs
audio_features = self.enrich_audio_features([tr['track']['id'] for tr in tracks_refs])
for i in range(0, len(audio_features)):
playlist['tracks']['items'][i]['track']['audio_features'] = audio_features[i]
print('enriched playlist:{}'.format(playlist['name']))
return playlist
def enrich_audio_features(self, track_ids):
audio_features = []
for i in range(0, len(track_ids), self.MAX_QUERY_RESULTS):
audio_features += self.sp.audio_features(tracks=track_ids[i:i + self.MAX_QUERY_RESULTS])
return audio_features
def get_list_of_categories(self, country=None, locale=None):
cat_refs = [];
categories = self.sp.categories(country, locale, limit=self.MAX_QUERY_RESULTS)['categories']
while categories:
cat_refs += categories['items'];
if categories['next']:
categories = self.sp.next(categories)['categories']
else:
categories = None
return [ref['id'] for ref in cat_refs]
def search(self, q, type='playlist', market=None, max_results=None):
res_refs = []
type_map = {
'playlist': 'playlists',
'track': 'tracks',
'album': 'albums',
'artist': 'artists',
}
results = self.sp.search(q, self.MAX_QUERY_RESULTS, type=type, market=market)[type_map[type]]
while results:
res_refs += results['items']
if max_results is not None and len(res_refs) + self.MAX_QUERY_RESULTS > max_results:
break
if results['next']:
results = self.sp.next(results)[type_map[type]]
else:
results = None
return res_refs
| true |
e93fb4041588d4f2d8292d53a4da0f9c6f969f10 | Python | niteshsrivats/Labs | /5th Semester/Python/Fourth Lab/DivisorGenerator.py | UTF-8 | 162 | 3.703125 | 4 | [] | no_license | number = int(input("Enter a number: "))
divisors = [1]
for i in range(2, int(number / 2) + 1):
if number % i == 0:
divisors.append(i)
print(divisors)
| true |
8a5e67a811fe8a3c269897d8b69ca29ab617ae80 | Python | Elizabethelu/python-lab | /sum of 3 numbers.py | UTF-8 | 342 | 3.75 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 1 19:45:38 2021
@author: 91994
"""
def sum(a,b,c):
sum=a+b+c
if(a==b==c):
sum=sum*3
return sum
n1=int(input("Enter first number : "))
n2=int(input("Enter second number : "))
n3=int(input("Enter third number : "))
print("Sum : " ,sum(n1,n2,n3))
| true |
30863f2193ceff389d393e6c46a3bcdbdfbd0a3c | Python | daiyeyue/Python_Advanced_Grammar | /异常使用/简单异常案例.py | UTF-8 | 1,521 | 4.34375 | 4 | [] | no_license | #简单异常案例
try:
num = int(input("plz input your number:"))
rst = 100/num
#如果上面的运算出错,下面的print就不执行了,直接跳到except里面了。
print("计算结果是:{0}".format(rst))
except:
print("你输入的数字有错误")
exit()
#简单异常案例
#给出错误提示
try:
num = int(input("plz input your number:"))
rst = 100/num
#如果上面的运算出错,下面的print就不执行了,直接跳到except里面了。
prnt("计算结果是:{0}".format(rst))
#如果是多种error情况
#需要把越具体的错误越往前放
#在异常类继承关系中,越是子类的异常,越要往前放
#越是父类的异常,越要往后放
#在处理异常时,一旦拦截了某个异常,则不继续往下查看,直接执行下一个代码,即有finally则执行finally语句块,否则就执行下一个大的语句
except ZeroDivisionError as e:
print("你输入的数字有错误")
print(e)
exit()
except NameError as e:
print("名字起错了")
print(e)
exit()
except AttributeError as e:
print("好像属性有问题")
print(e)
except Exception as e:
print("我也不知道就错了")
print(e)
print("hahah")
#作业:为什么我们可以直接打印出实例e,此时实例e应该事先调哪个函数
#用户手动引发异常
#当某些情况,用户希望自己引发一个异常的时候,可以使用
#raise 关键字来引发异常 | true |