index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
37,697
|
andytrandaoanh/map-words
|
refs/heads/master
|
/text_processor_2.py
|
import os, sys
import system_handler as sH
from mysql_handler import getWordList
import re
def getOutPath(inFile, outDir):
filePath = os.path.basename(inFile)
#fname, fext = os.path.splitext(temp_path)
pathOut = os.path.join(outDir, filePath)
return(pathOut)
def processText(inFile, outDir):
outFilePath = getOutPath(inFile, outDir)
matches = sH.readTextFile(inFile)
listMatch = matches.split("\n")
cleanList = []
for item in listMatch:
parts = item.split(",")
if(parts[0].strip()):
cleanList.append(item)
listMatch = list( dict.fromkeys(cleanList))
sH.writeListToFile(listMatch, outFilePath)
#print(listMatch)
sH.openDir(outDir)
sys.exit()
|
{"/text_processor_2.py": ["/system_handler.py", "/mysql_handler.py"], "/database_handler.py": ["/mysql_handler.py"], "/text_processor.py": ["/system_handler.py"]}
|
37,698
|
andytrandaoanh/map-words
|
refs/heads/master
|
/system_handler.py
|
import os, sys
def openDir(targetdir):
#open directory when done
rpath = os.path.realpath(targetdir)
os.startfile(rpath)
def getNormalPath(bookID, outDir):
fname = "Matches Book"
TEXT_EXT = ".txt"
incString = str(bookID)
increment = incString.zfill(4)
normal_path = os.path.join(outDir, fname + increment + TEXT_EXT)
return(normal_path)
def readTextFile(filepath):
try:
ofile = open(filepath, 'r', encoding = 'utf-8')
data = ofile.read()
return data
except FileNotFoundError:
print("file not found")
except Exception as e:
print(e)
def writeTupleToFile(dataTuple, outPath):
with open(outPath, 'w', encoding ='utf-8') as file:
for item in dataTuple:
lineData = str(item[0]) + ',' + str(item[1])
file.write(lineData + "\n")
def writeListToFile(vlist, vpath):
with open(vpath, 'w', encoding ='utf-8') as file:
for item in vlist:
file.write(item + "\n")
|
{"/text_processor_2.py": ["/system_handler.py", "/mysql_handler.py"], "/database_handler.py": ["/mysql_handler.py"], "/text_processor.py": ["/system_handler.py"]}
|
37,699
|
andytrandaoanh/map-words
|
refs/heads/master
|
/database_handler.py
|
import os, sys
import json
from mysql_handler import prepare_data_for_update
def getCorrectPath(fileIn, dirIn):
JSON_EXTENSION = ".json"
temp_path = fileIn
temp_path = os.path.basename(temp_path)
fname, fext = os.path.splitext(temp_path)
pathOut = os.path.join(dirIn, fname + JSON_EXTENSION)
return(pathOut)
def read_text_file(filepath):
try:
ofile = open(filepath, 'r', encoding = 'utf-8')
data = ofile.read()
words = data.split()
return words
except FileNotFoundError:
print("file not found")
except Exception as e:
print(e)
def write_list_to_file(vlist, vpath):
with open(vpath, 'w', encoding ='utf-8') as file:
for item in vlist:
if (str(item) != ''):
file.write(item + "\n")
def uploadData(inPath, dbDir, bookID):
#print('inPath:', inPath, 'dbDir:', dbDir, 'bookID:', bookID)
#print(pathNin, pathSin)
jsonPath = getCorrectPath(inPath, dbDir)
#print(jsonPath)
with open(jsonPath) as f:
sentences = json.load(f)
dbData = []
for sentence in sentences:
temp = sentence[0]
dbData.append((int(bookID), temp['sent_cont'], temp['sent_num']))
prepare_data_for_update(dbData)
|
{"/text_processor_2.py": ["/system_handler.py", "/mysql_handler.py"], "/database_handler.py": ["/mysql_handler.py"], "/text_processor.py": ["/system_handler.py"]}
|
37,700
|
andytrandaoanh/map-words
|
refs/heads/master
|
/extracts.py
|
import os, sys
import re
from nltk import tokenize
import json
def open_dir(targetdir):
#open directory when done
rpath = os.path.realpath(targetdir)
os.startfile(rpath)
def read_text_file(filepath):
try:
ofile = open(filepath, 'r', encoding = 'utf-8')
data = ofile.read()
return data
except FileNotFoundError:
print("file not found")
except Exception as e:
print(e)
def cleanText(input_text):
line = input_text
line = line.replace('\n',' ')
line = line.replace('\t',' ')
return line
def getCorrectPath(fileIn, dirIn, dirOut):
TEXT_EXTENSION = ".txt"
JSON_EXTENSION = ".json"
temp_path = fileIn
temp_path = os.path.basename(temp_path)
fname, fext = os.path.splitext(temp_path)
pathIn = os.path.join(dirIn, fname + TEXT_EXTENSION)
pathOut = os.path.join(dirOut, fname + JSON_EXTENSION)
return(pathIn, pathOut)
def write_list_to_file(vlist, vpath):
with open(vpath, 'w', encoding ='utf-8') as file:
for item in vlist:
if (str(item) != ''):
file.write(item + "\n")
def extractSentences(fileIn, dirIn, dirOut):
pathIn, pathOut = getCorrectPath(fileIn, dirIn, dirOut)
#print ('pathIn:', pathIn, 'pathOut', pathOut)
contents = read_text_file(pathIn)
sentences = tokenize.sent_tokenize(contents)
#print(sentences)
index = 0
results =[]
MIN_LENGTH = 20
for sentence in sentences:
if (len(sentence) > MIN_LENGTH):
index += 1
sent_cont = cleanText(sentence)
sentence_object = {"sent_num": index, "sent_cont": sent_cont }
results.append([sentence_object])
#print(results)
with open(pathOut, 'w', encoding ="utf-8") as outfile:
json.dump(results, outfile)
open_dir(dirOut)
sys.exit()
|
{"/text_processor_2.py": ["/system_handler.py", "/mysql_handler.py"], "/database_handler.py": ["/mysql_handler.py"], "/text_processor.py": ["/system_handler.py"]}
|
37,701
|
andytrandaoanh/map-words
|
refs/heads/master
|
/text_processor.py
|
import sys
import re
import system_handler as sysHand
import mysql_data as sqlData
def matchWordToSent(wordList, sentList, bookID):
results = []
for word in wordList:
for item in sentList:
sentText = item[0]
sentID = item[1]
reWord = re.escape(word)
pattern = re.compile(r'\b%s\b' % reWord, re.I)
try:
matchObj = pattern.search(sentText)
if (matchObj):
results.append((word, sentID))
print(matchObj)
except:
print('Some error occurred')
return results
def processText(bookID, outDir):
outPath = sysHand.getNormalPath(bookID, outDir)
#print('outPath:', outPath)
wordList = sqlData.getWordList(bookID)
wordList.sort()
sentList = sqlData.getSentences(bookID)
matchList = matchWordToSent(wordList, sentList, bookID)
sysHand.writeTupleToFile(matchList, outPath)
sysHand.openDir(outDir)
sys.exit()
|
{"/text_processor_2.py": ["/system_handler.py", "/mysql_handler.py"], "/database_handler.py": ["/mysql_handler.py"], "/text_processor.py": ["/system_handler.py"]}
|
37,702
|
andytrandaoanh/map-words
|
refs/heads/master
|
/mysql_handler.py
|
import os, sys
import mysql.connector
from mysql.connector import errorcode
def getConnection(dbname=''):
try:
connection = mysql.connector.connect(
user='andyanh', password='DGandyanh#1234',
host='127.0.0.1', database = dbname)
if connection.is_connected():
return connection
except Error as e:
return e
def getWordList():
DB_NAME = "lexicon"
db = getConnection(DB_NAME)
cursor = db.cursor()
select_sql= ("select word_form from pure_words order by 1;")
try:
words =[]
cursor.execute(select_sql)
data = cursor.fetchall()
for w in data:
words.append(w[0])
return words
except Exception as e:
print("Error encountered:", e)
finally:
cursor.close
db.close
|
{"/text_processor_2.py": ["/system_handler.py", "/mysql_handler.py"], "/database_handler.py": ["/mysql_handler.py"], "/text_processor.py": ["/system_handler.py"]}
|
37,733
|
jmacario-gmu/gmuj-python-web-scraping
|
refs/heads/master
|
/functions.py
|
### import libraries
import sys, os, urllib.request, requests, bs4, datetime, re, webbrowser, getpass, time, winsound, argparse
from urllib.error import URLError, HTTPError
### define classes
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
### define functions
## GENERAL
def fnIsYes(inputString):
##
# Summary: checks to see if the input is a 'yes' ("y" or "Y" character)
# Details:
# Last Modified: 20170929
# Modified by: JM
##
# check to see if input string represents a yes
if inputString=='y' or inputString=="Y":
varReturn=True
else:
varReturn=False
# return value
return varReturn
def fnIfBlankDefaultValue(input_string,default_value):
##
# Summary: if the input is blank, use the provided default value
# Details:
# Last Modified: 20190714
# Modified by: JM
##
# is the input string blank?
if input_string == "":
return default_value
else:
return input_string
## DATE/TIME-RELATED
def fnTimestamp():
##
# Summary: returns a timestamp
# Details: format: YYYYMMDDHHMMSS
# Last Modified: 20160926
# Modified by: JM
##
# return timestamp
return '{:%Y%m%d%H%M%S}'.format(datetime.datetime.now())
## FILE-RELATED
def fnOutputStringToFile(inputString,outputFileName):
##
# Summary: outputs a string to a file
# Details: string to output and the name of the file to output to are specified as parameters
# Last Modified: 20161004
# Modified by: JM
##
# this script had been using: open(outputFileName, "w"), but some pages had characters that failed unless in binary mode
# therefore I am now doing: open(outputFileName, "wb"),
# this then requires that the string be encoded as binary, hence the: text_file.write(inputString.encode('utf-8'))
# prior to switching the file open mode to binary, this encoding was not needed
# open/create text file for output ("wb" indicates opening file for writing binary data)
text_file = open(outputFileName, "wb")
# write output string to file
text_file.write(inputString.encode('utf-8'))
# close text file
text_file.close()
## TEXT-RELATED
def fnPadString(inputString,intLength):
##
# Summary: pads a string
# Details:
# Last Modified: 20190720
# Modified by: JM
##
if len(inputString)<intLength:
# initialize working string
workingString=inputString
# while it still needs padding
while len(workingString)<intLength:
workingString="0"+workingString
return workingString
else:
return inputString
def fnGetTabs(intNumberOfTabs):
##
# Summary: returns a specified number of tab characters
# Details:
# Last Modified: 20190713
# Modified by: JM
##
# initialize return variable
return_value=""
for i in range(intNumberOfTabs):
return_value+='\t'
return return_value
def fnTrueFalseGreenRed(inputString,bolValue):
##
# Summary: wraps the input string in color codes for green or red, depending on boolean value
# Details:
# Last Modified: 20190713
# Modified by: JM
##
# set color based on boolean status
if bolValue:
return_value = bcolors.OKGREEN
else:
return_value = bcolors.FAIL
# append input string
return_value += inputString
# reset colors
return_value += bcolors.ENDC
return return_value
def fnCheckFirstChar(inputString,specifiedChar):
##
# Summary: checks if the last char is a certain specified character
# Details:
# Last Modified: 20190708
# Modified by: JM
##
if inputString[:1]==specifiedChar:
return True
else:
return False
def fnCheckLastChar(inputString,specifiedChar):
##
# Summary: checks if the last char is a certain specified character
# Details:
# Last Modified: 20190708
# Modified by: JM
##
if inputString[-1:]==specifiedChar:
return True
else:
return False
## HTTP-RELATED
def good_url_response(strURL):
##
# Summary: returns a boolean representing whether this url returned a 200 response or not
# Details:
# Last Modified: 20190731
# Modified by: JM
##
# set user agent string
strUserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0'
request_headers = {
'User-Agent': strUserAgent
}
# Get HTML document from specified URL
myResponse=requests.get(strURL, headers=request_headers)
# check status
myResponse.raise_for_status
# print('Status: ' + str(myResponse.status_code))
# if status is not 200, print message and exit
if myResponse.status_code!=200:
# print error
print (bcolors.FAIL + "Error " + str(myResponse.status_code) + ' ' + myResponse.reason + bcolors.ENDC)
#print (bcolors.FAIL + myResponse.headers + bcolors.ENDC)
# return value
return False
else:
return True
def getHTTPResponseContent(strURL):
##
# Summary: returns a string representing the HTTP response from a given URL
# Details:
# Last Modified: 20190713
# Modified by: JM
##
# set user agent string
strUserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0'
request_headers = {
'User-Agent': strUserAgent
}
# Get HTML document from specified URL
myResponse=requests.get(strURL, headers=request_headers)
# check status
myResponse.raise_for_status
# print('Status: ' + str(myResponse.status_code))
# if status is not 200, print message and exit
if myResponse.status_code!=200:
# print error
print (bcolors.FAIL + "Error " + str(myResponse.status_code) + ' ' + myResponse.reason + bcolors.ENDC)
#print (bcolors.FAIL + myResponse.headers + bcolors.ENDC)
# return value
return False
else:
# output progress message
#print("URL fetched successfully.")
# output response text
#print(myResponse.text)
# return value
return myResponse.text
def fnSaveFileFromURL(strURL,strFilename,bolShowDetailedErrors):
##
# Summary: given a URL and a local filename, save the file at that URL to the local file
# Details:
# Last Modified: 20190712
# Modified by: JM
##
# set user agent string
strUserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0'
# replace spaces in URL with %20
strURL=re.sub(r' ','%20',strURL)
# set up HTTP request
myRequest = urllib.request.Request(
strURL,
data=None,
headers={
'User-Agent': strUserAgent
}
)
# initiate request, checking for errors
try:
workingFileURL = urllib.request.urlopen(myRequest)
workingFile = open(strFilename, 'wb')
workingFile.write(workingFileURL.read())
workingFile.close()
return True
except HTTPError as e:
print(bcolors.FAIL + 'HTTP Error: ' + str(e.code) + ' ' + e.reason + bcolors.ENDC)
if bolShowDetailedErrors: print(bcolors.FAIL + str(e.headers) + bcolors.ENDC, end='')
return False
except URLError as e:
print(bcolors.FAIL + 'URL Error: ', e.reason , bcolors.ENDC)
return False
except FileNotFoundError as e:
print(bcolors.FAIL + 'File Not Found Error')
print('Errno: ' + str(e.errno) + ' WinError: ' + str(e.winerror) + bcolors.ENDC)
print(bcolors.FAIL + 'Error String: ' + e.strerror + bcolors.ENDC)
print(bcolors.FAIL + 'Related file(s): ' + str(e.filename) + ' ' + str(e.filename2) + bcolors.ENDC)
## URL-RELATED
def fnConvertURLToPath(inputString):
##
# Summary: cleans-up URLs to remove difficult characters
# Details: replaces special chars in URLs
# Last Modified: 20190719
# Modified by: JM
##
# create output string
outputString=inputString
# replace the ://
outputString=outputString.replace("://",".")
# replace other chars
outputString=re.sub("[\/\?\=\#\_\>\<\:\{\}\']","-",outputString)
# replace trailing dash
outputString=re.sub('-$','',outputString)
# return value
return outputString
def fnURLIsAbsolutePath(inputString):
##
# Summary: returns whether a given URL string is an absolute or relative path within the site root
# Details: uses fnCheckFirstChar to check the first character of the URL
# Last Modified: 20190708
# Modified by: JM
##
if fnCheckFirstChar(inputString,"/"):
return True
else:
return False
def fnURLIsDirectory(inputString):
##
# Summary: returns whether a given URL string is a directory or an individual file, by seeing if it ends in a slash
# Details: uses fnCheckLastChar to check the last character of the URL
# Last Modified: 20190720
# Modified by: JM
##
# first, strip off any querystring
workingString=re.sub(r'(\?.*)','',inputString)
# does it end with a slash?
if fnCheckLastChar(workingString,"/"):
return True
else:
return False
def fnGetURLComponent(strURL,strComponent,defaultFilename="index.html"):
##
# Summary: returns a part of the URL as specified by the strComponent argument
# Details:
# Last Modified: 20190720
# Modified by: JM
##
# process and return value based on strComponent
if strComponent == "protocol":
# return just the part of the URL representing the protocol
return (re.search(r'(https?)',strURL).group(1))
elif strComponent == "domain":
# return the domain
# finds the first slash (beyond the http:// or https:// - character 8 should do) and returns everything up to that point
workingString = strURL[:strURL.find("/",8)]
#remove the protocol and return value
return re.sub(r'^https?://','',workingString)
elif strComponent == "directory":
# strip any querystring
workingString=re.sub(r'(\?.*)','',strURL)
# return the part of the URL representing the directory but not the actual filename
workingString=(re.search(r'https?://([^/]*)(/.*)',workingString).group(2))
# get everything up to the final slash
return(re.search(r'(.*/)(.*)',workingString).group(1))
elif strComponent == "filename":
# return the part of the URL representing the actual filename
# remove anchor part of URL
workingString=re.sub(r'#.*','',strURL)
# if the filename is not provided, but query parameters are used, insert the default filename where it woud go
# for this we are checking to see if we have a "/?" in the URL. querystring with no filename
workingString = re.sub(r'\/\?','/' + defaultFilename + '?',workingString)
# if no filename was specified...
if fnURLIsDirectory(workingString):
# use the default filename.
return defaultFilename
else:
# does the URL contain a querystring?
if re.search(r'\?',strURL):
# this URL contains a querystring. this means that there could be a slash as a query parameter
# return URL from last slash PRIOR TO A QUESTION MARK to end
return re.search(r'(.*)/(.*\?.*)',workingString).group(2)
else:
# return URL from last slash to end
return re.search(r'(.*)/(.*)',workingString).group(2)
elif strComponent == "querystring":
# return the querystring
if re.search(r'\?',strURL):
return re.search(r'(\?.*)',strURL).group(1)
else:
return False
else:
print("Specified URL component (" + strComponent + ") not recognized.")
return False
def fnGetAbsoluteURL(strURL,strStartingURL):
##
# Summary: given an starting URL and a second URL that may be relative to it, determines the absolute URL
# Details: strURL stores the URL in question, which can begin with "http://" "https://" "//" "/" or just the relative path. strStartingURL stores the absolute URL that this URL may be relative to
# Last Modified: 20190712
# Modified by: JM
##
# get info about URL
strStartingURLProtocol = fnGetURLComponent(strStartingURL,"protocol")
strStartingURLDomain = fnGetURLComponent(strStartingURL,"domain")
strStartingURLDirectory = fnGetURLComponent(strStartingURL,"directory")
# does this URL start with two slashes?
if re.search("^//",strURL):
# add the appropriate protocol
strURL=re.sub('^//',strStartingURLProtocol+'://',strURL)
# does this URL start with http:// or https://?
if re.search("^https?://",strURL.lower()):
# we already have an absolute URL
final_url=strURL
else:
# is this link an absolute or relative URL?
if fnURLIsAbsolutePath(strURL):
# set the URL using the domain part and the url in question
final_url=strStartingURLProtocol+'://'+strStartingURLDomain+strURL
else:
# set the URL using the domain and directory parts and the url in question
final_url=strStartingURLProtocol+'://'+strStartingURLDomain+strStartingURLDirectory+strURL
return final_url
def fnGetURLLocalPath(strURL,strStartingURL,strLocalFolderBase,strLocalFolder,strResourceType):
##
# Summary:
# Details:
# Last Modified: 20190712
# Modified by: JM
##
# get info about starting URL
strStartingURLProtocol = fnGetURLComponent(strStartingURL,"protocol")
strStartingURLDomain = fnGetURLComponent(strStartingURL,"domain")
# does this URL start with two slashes?
if re.search("^//",strURL):
# add the appropriate protocol
strURL=re.sub('^//',strStartingURLProtocol+'://',strURL)
# is this an absolute URL? (does it start with http:// or https://)?
if re.search("^https?://",strURL.lower()):
# If so, then this is already the complete URL
# get info about this URL
strURLProtocol=fnGetURLComponent(strURL,"protocol")
strURLDomain=fnGetURLComponent(strURL,"domain")
strURLDirectory=fnGetURLComponent(strURL,"directory")
strURLFilename=fnGetURLComponent(strURL,"filename")
# remove the querystring from the filename if necessary
#strURLFilename=re.sub(r"(.*)\?.*$",r"\1",strURLFilename)
# so this is an absolute URL, but it is the same domain we are starting from?
if (strURLProtocol==strStartingURLProtocol) and (strURLDomain==strStartingURLDomain):
# if so, put this in the normal place in the local filesystem (chop the trailing slash from the strLocalFolderBase variable)
local_filename=strLocalFolderBase[:-1]+strURLDirectory+strURLFilename
else:
# if not, put this in the offsite files folder under this domain
local_filename=strLocalFolderBase+'_offsite-files/'+strResourceType+'/'+fnConvertURLToPath(strURLProtocol+'://'+strURLDomain)+strURLDirectory+strURLFilename
else:
# is this link absolute or relative to the domain root?
if fnURLIsAbsolutePath(strURL):
# set local filename by using the domain part and the resource URL
local_filename=strLocalFolderBase+strURL[1:]
else:
# set local filename by using the directory part and the resource URL
local_filename=strLocalFolder+strURL
# remove the querystring from the filename if necessary
local_filename=re.sub(r"(.*)\?.*$",r"\1",local_filename)
return local_filename
## OTHER
def fnCleanHTMLContent(inputString):
##
# Summary: an example function of cleaning-up HTML
# Details: uses regex to find and replace parts of the content
# Last Modified: 20171004
# Modified by: JM
##
# create output string
outputString=inputString
# replace newline chars after line break tags
# outputString=re.sub('<br/>\n','<br/>',outputString)
# replace table class
# outputString=re.sub('class="tablepress tablepress-id-\d+"','class="datatable"',outputString)
# add table style
# outputString=re.sub('<table class="datatable"','<table class="datatable" style="width:98%;"',outputString)
# remove table id
# outputString=re.sub(' id="tablepress-\d+"','',outputString)
# remove tr classes
# outputString=re.sub(' class="row-\d+ (odd|even)"','',outputString)
# remove th and td classes
# outputString=re.sub(' class="column-\d+"','',outputString)
# add th styles
#outputString=re.sub('<th>','<th style="width:20%">',outputString)
# remove tbody class
# outputString=re.sub(' class="row-hover"','',outputString)
# return value
return outputString
|
{"/gmuj-scrape.py": ["/functions.py"]}
|
37,734
|
jmacario-gmu/gmuj-python-web-scraping
|
refs/heads/master
|
/gmuj-scrape.py
|
# Summary: Program to scrape a list of URLs pages and output the main content HTML to an HTML file and as well as saving all linked stylesheets, javascript files, images, documents to local subfolders
# Details: This program requires a text file in the working directory containing a list of URLs to fetch. Each URL should be on its own line.
# Command line options:
# if you do not specify any parameters, the script will ask you what types of resources you want to save (html, css, js, images, documents)
# you can specify what types of output to save by using any of the following command line arguments, in any combination: "html" "css" "js" "img" "doc"
# you can also use the argument "all" to do all, or "none" to do none. in that case it will only scan but not save anything
# if you want to separate saved files by timestamp, use the argument "time"
# Last Modified: 20200302
# Modified by: JM
### import my base library
from functions import *
def main():
##
# Summary:
# Details:
# Last Modified: 20190702
# Modified by: JM
##
# clear screen (cross platform - cls for windows, clear for linux)
# os.system('cls' if os.name == 'nt' else 'clear')
os.system('clear')
# initialize variables
bolTimestamp = False
bolSaveHTML = False
bolSaveCSS = False
bolSaveJS = False
bolSaveImages = False
bolSaveDocs = False
# if "all" options was specified, set to do all
if "all" in sys.argv:
bolSaveHTML = True
#print("Saving HTML files.")
bolSaveCSS = True
#print("Saving CSS files.")
bolSaveJS = True
#print("Saving JavaScript files.")
bolSaveImages = True
#print("Saving image files.")
bolSaveDocs = True
#print("Saving document files.")
# did we specify to do timestamps?
if "time" in sys.argv: bolTimestamp = True
elif "none" in sys.argv:
pass
else:
# see if arguments were specified
if len(sys.argv)==1:
# no arguments specified (the first item in sys.argv is the name of the script)
# ask the user what to do
print(bcolors.HEADER + 'Select Options:'+ bcolors.ENDC)
bolTimestamp = fnIsYes(input('Timestamp output? (Y/N): '))
bolSaveHTML = fnIsYes(input('Save HTML files? (Y/N): '))
bolSaveCSS = fnIsYes(input('Save CSS files? (Y/N): '))
bolSaveJS = fnIsYes(input('Save JavaScript files? (Y/N): '))
bolSaveImages = fnIsYes(input('Save image files? (Y/N): '))
bolSaveDocs = fnIsYes(input('Save document files? (Y/N): '))
print()
else:
# determine which options were specified via command line parameters
if "time" in sys.argv:
bolTimestamp = True
#print("Saving HTML files.")
if "html" in sys.argv:
bolSaveHTML = True
#print("Saving HTML files.")
if "css" in sys.argv:
bolSaveCSS = True
#print("Saving CSS files.")
if "js" in sys.argv:
bolSaveJS = True
#print("Saving JavaScript files.")
if "img" in sys.argv:
bolSaveImages = True
#print("Saving image files.")
if "doc" in sys.argv:
bolSaveDocs = True
#print("Saving document files.")
# output selected options
print(bcolors.HEADER + 'Selected Options:'+ bcolors.ENDC)
# do we have something to do?
if (bolSaveHTML or bolSaveCSS or bolSaveJS or bolSaveImages or bolSaveDocs):
print(fnTrueFalseGreenRed('HTML',bolSaveHTML) + '\t', end='')
print(fnTrueFalseGreenRed('CSS',bolSaveCSS) + '\t', end='')
print(fnTrueFalseGreenRed('JS',bolSaveJS) + '\t', end='')
print(fnTrueFalseGreenRed('IMAGES',bolSaveImages) + '\t', end='')
print(fnTrueFalseGreenRed('DOCUMENTS',bolSaveDocs) + '\t', end='')
print()
print()
if bolTimestamp:
print("Saving output with timestamp.")
else:
print(bcolors.WARNING + "Saving output with no timestamp." + bcolors.ENDC)
if bolSaveHTML: print("Saving HTML files.")
if bolSaveCSS: print("Saving CSS files.")
if bolSaveJS: print("Saving JavaScript files.")
if bolSaveImages: print("Saving image files.")
if bolSaveDocs: print("Saving document files.")
else:
print(bcolors.WARNING + "Nothing to output. Scan only." + bcolors.ENDC)
print()
# set environment variables
print(bcolors.HEADER + 'Environment variables:'+ bcolors.ENDC)
# set run timestamp
strTimestamp=fnTimestamp()
print('Timestamp: ' + strTimestamp)
# set current directory
current_directory=os.path.dirname(os.path.realpath(__file__))
print("Working directory: "+current_directory)
# set text file URL list info
print('URL list file: '+current_directory+"\\"+urlListFile)
print()
# shall we continue?
if not fnIsYes(input('Continue? (Y/N): ')):
print(bcolors.WARNING + "Quitting Process" + bcolors.ENDC)
exit()
print()
# Prepare to loop through URLs in URL file
print(bcolors.HEADER + 'Processing URL(s):'+ bcolors.ENDC)
print()
# flush output
sys.stdout.flush()
# Open URL list text file for reading
input_file = open(urlListFile, 'r')
# Set initial value for URLs processed (lines read)
count_lines = 0
# Loop through lines in input file
for line in input_file:
# check to see if line begins with a number sign (which indicates a comment)
# TODO: this could be improved to ignore whitespace and comments
if line[0]!="#":
# Increment number of lines read
count_lines += 1
# Get URL to fetch data from, from current line of text file
strFetchURL=line.strip()
# Output
print(bcolors.HEADER + bcolors.UNDERLINE + 'URL: '+strFetchURL + bcolors.ENDC)
print()
# get info about URL
print(bcolors.HEADER + "URL information:" + bcolors.ENDC)
# get URL protocol
strFetchURLProtocol=fnGetURLComponent(strFetchURL,"protocol")
print('Protocol: '+strFetchURLProtocol)
# get URL domain part
strFetchURLDomain=fnGetURLComponent(strFetchURL,"domain")
print('Domain: '+strFetchURLDomain)
# get URL directory part
strFetchURLDirectory=fnGetURLComponent(strFetchURL,"directory")
print('Remote directory: '+strFetchURLDirectory)
# get URL filename part
strFetchURLFilename=fnGetURLComponent(strFetchURL,"filename",defaultFilename)
print("Remote filename: "+strFetchURLFilename)
# get URL querystring part
strFetchURLQuerystring=fnGetURLComponent(strFetchURL,"querystring")
#print("Querystring: "+strFetchURLQuerystring)
print()
# figure out where to put it on the local filesystem
print(bcolors.HEADER + "Local filesystem information:" + bcolors.ENDC)
#print("Working directory: "+current_directory)
# set local folder and file info
# set local domain folder
# start local domain folder string
strLocalDomainFolder='_scrape-results/'+fnConvertURLToPath(strFetchURLProtocol+"://"+strFetchURLDomain)
# should we add a timestamp to the folder name?
if bolTimestamp: strLocalDomainFolder+='-'+strTimestamp
# finish local domain folder string
strLocalDomainFolder+='/'
#print('Local Domain folder: '+strLocalDomainFolder)
# set local path folder
strLocalFolder=strLocalDomainFolder+strFetchURLDirectory[1:] # clip the directory to remove the leading slash
#print('Local folder: '+strLocalFolder)
# set local filename
strLocalFilename=strFetchURLFilename
# replace first instance of question mark
strLocalFilename=re.sub(r'\?','-QUERY-',strLocalFilename, 1)
# clean up the local filename
strLocalFilename = fnConvertURLToPath(strLocalFilename)
# append or fix file extension
# does filename part of URL contain a question mark?
if "?" in strFetchURLFilename:
# append html extension
strLocalFilename+=".html"
else:
# rename dynamic files to .html files
strLocalFilename=re.sub(r'\.(php|cfm)$','.html',strLocalFilename)
# fix long filenames
if len(strLocalFilename)>=125:
#print("I THINK THIS FILENAME IS TOO LONG: " + str(len(strLocalFilename)))
temp_filename = strLocalFilename[:113] + '-' + fnPadString(str(count_lines),4) + '.html'
#print("Maybe it should be: " + temp_filename)
#print("(Which is " + str(len(temp_filename)) + " long)")
strLocalFilename=temp_filename
#print('Local filename: '+strLocalFilename)
# set local path for HTML file
strLocalPath=strLocalFolder+strLocalFilename
print('Local file target: '+current_directory+'/'+strLocalPath)
#print('Local filename: '+strLocalFilename)
print()
# Get data from URL
print(bcolors.HEADER + 'Fetching URL:' + bcolors.ENDC, flush=True)
# Attempt to get text content response from specified URL
strResponse=getHTTPResponseContent(strFetchURL)
# did we get a response?
if strResponse==False:
# HTTP request did not respond with with 200 ("OK") response code
print(bcolors.FAIL + "There was an error accessing this URL. Skipping."+ bcolors.ENDC)
# set the variable that indicating the save has not been successful
bolSaveHTMLSuccessful=False
print()
else:
# HTTP request received a 200 ("OK") response code
print(bcolors.OKGREEN + "200 OK"+ bcolors.ENDC)
print()
# output response text
#print("Response text: " + str(strResponse.encode('utf-8')))
# Should we save the response text?
if bolSaveHTML:
print(bcolors.HEADER + 'Saving URL HTTP response content:' + bcolors.ENDC)
# reset the variable that indicates whether the save has been successful
bolSaveHTMLSuccessful=False
# get directory name(s)
directory = os.path.dirname(strLocalPath)
# create directory for this URL, if it doesn't exist
if not os.path.exists(directory):
# create directories
os.makedirs(directory)
#print("Creating directory: " + directory)
#else:
# #do nothing
# #print("Diectory already exists: " + directory)
# does this file exist?
#if os.path.exists(strLocalPath):
# pass
# #print("This path does not exist: " + strLocalPath)
#else:
# pass
# #print("This path does exist: " + strLocalPath)
#print("Current working directory is: " + os.getcwd())
# save response text
#print("Attempting to save to: " + strLocalPath)
try:
fnOutputStringToFile(strResponse,strLocalPath)
print(bcolors.OKGREEN + "HTML written to file: "+current_directory+'/'+strLocalPath + bcolors.ENDC)
bolSaveHTMLSuccessful=True
except (FileNotFoundError) as e:
print(bcolors.FAIL + "Unable to write to file: "+current_directory+'/'+strLocalPath + bcolors.ENDC)
print(e)
bolSaveHTMLSuccessful=False
print()
# Are we doing something that requires parsing the HTML?
if bolSaveCSS or bolSaveJS or bolSaveImages or bolSaveDocs:
# parse HTML document to variable using BeautifulSoup
print(bcolors.HEADER + "Parsing URL HTTP response content:"+ bcolors.ENDC)
parsedHTMLContent=bs4.BeautifulSoup(strResponse,"html.parser")
print(bcolors.OKGREEN + "HTML content parsed!" + bcolors.ENDC)
print()
# if we are saving stylesheets
if bolSaveCSS:
# find stylesheet tags
print(bcolors.HEADER + 'Finding Stylesheets:' + bcolors.ENDC)
# initialize image array
arrSavedStylesheets = []
# find all stylesheet tags and loop through them
for stylesheet in parsedHTMLContent.find_all('link', rel='stylesheet'):
# output current stylesheet source
print('Stylesheet found: '+stylesheet['href'])
# get full stylesheet URL
stylesheetURL = fnGetAbsoluteURL(stylesheet['href'],strFetchURL)
print('Stylesheet URL: '+stylesheetURL)
# set the appropriate corresponding local path
localFilename = fnGetURLLocalPath(stylesheet['href'],strFetchURL,strLocalDomainFolder,strLocalFolder,"CSS")
print('Local Filename: '+localFilename)
# do we have this stylesheet URL in the arrSavedStylesheets array already?
if stylesheetURL in arrSavedStylesheets:
print(bcolors.WARNING + "This stylesheet has already been saved!" + bcolors.ENDC)
else:
# does this file already exist?
if os.path.exists(localFilename):
print(bcolors.WARNING + "File already exists. Skipping." + bcolors.ENDC)
else:
print("Attempting download...", flush=True)
# get directory name(s)
directory = os.path.dirname(localFilename)
#print("Saving to directory: "+directory)
# if directories don't exist
if not os.path.exists(directory):
# make them
os.makedirs(directory)
# download and save CSS file
if fnSaveFileFromURL(stylesheetURL,localFilename,bolShowDetailedHTTPErrors):
print(bcolors.OKGREEN + "Stylesheet saved!" + bcolors.ENDC)
# add this URL to the arrSavedStylesheets array
arrSavedStylesheets.append(stylesheetURL)
else:
print(bcolors.FAIL + "Unable to save CSS file." + bcolors.ENDC)
print("", flush=True)
# output summary information
print(bcolors.WARNING, end='') if len(arrSavedStylesheets) == 0 else print(bcolors.OKGREEN, end='')
print("Total stylesheets saved: "+str(len(arrSavedStylesheets)))
print(bcolors.ENDC, end='')
print()
# if we are saving javascripts
if bolSaveJS:
# Find javascript file links
print(bcolors.HEADER + 'Finding Javascript files:' + bcolors.ENDC)
# initialize javascript file array
arrSavedJavascripts = []
# find all script tags and loop through them
for script in parsedHTMLContent.find_all('script', src=True):
# output current script src
print("Script found: "+script['src'])
# does this URL meet the javascript file criteria
urlMatch = re.search('\.js(\?|$)',script['src'].lower())
if urlMatch:
#print("This is a Javascript file. We should download it!")
# get full javascript URL
javascriptURL = fnGetAbsoluteURL(script['src'],strFetchURL)
print('Javascript URL: '+javascriptURL)
# set the appropriate corresponding local path
localFilename = fnGetURLLocalPath(script['src'],strFetchURL,strLocalDomainFolder,strLocalFolder,"JS")
print('Local Filename: '+localFilename)
# do we have this javascript file URL in the arrSavedJavascripts array already?
if javascriptURL in arrSavedJavascripts:
print(bcolors.WARNING + "This javascript file has already been saved!" + bcolors.ENDC)
else:
# does this file already exist?
if os.path.exists(localFilename):
print(bcolors.WARNING + "File already exists. Skipping." + bcolors.ENDC)
else:
print("Attempting to download...", flush=True)
# get directory name(s)
directory = os.path.dirname(localFilename)
#print("Saving to directory: "+directory)
# if directories don't exist
if not os.path.exists(directory):
# make them
os.makedirs(directory)
# download and save javascript file
if fnSaveFileFromURL(javascriptURL,localFilename,bolShowDetailedHTTPErrors):
print(bcolors.OKGREEN + "Javascript File saved!" + bcolors.ENDC)
# add this URL to the arrSavedJavascripts array
arrSavedJavascripts.append(javascriptURL)
else:
print(bcolors.FAIL + "Unable to save Javascript file." + bcolors.ENDC)
print("", flush=True)
# output summary information
print(bcolors.WARNING, end='') if len(arrSavedJavascripts) == 0 else print(bcolors.OKGREEN, end='')
print("Total Javascript files saved: "+str(len(arrSavedJavascripts)))
print(bcolors.ENDC, end='')
print()
# if we are saving images
if bolSaveImages:
# find image links
print(bcolors.HEADER + 'Finding Images:' + bcolors.ENDC)
# initialize image array
arrSavedImages = []
# find all img tags and loop through them
for img in parsedHTMLContent.find_all('img', src=True):
# output current image source
print('Image found: '+img['src'])
# does this image meet the image file restritction criteria
urlMatch = re.search(r'^data:',img['src'])
if not urlMatch:
# get full image URL
imageURL = fnGetAbsoluteURL(img['src'],strFetchURL)
print('Image URL: '+imageURL)
# set the appropriate corresponding local path
localFilename = fnGetURLLocalPath(img['src'],strFetchURL,strLocalDomainFolder,strLocalFolder,"images")
print('Local Filename: '+localFilename)
# do we have this image URL in the arrSavedImages array already?
if imageURL in arrSavedImages:
print(bcolors.WARNING + "This image has already been saved!" + bcolors.ENDC)
else:
# does this file already exist?
if os.path.exists(localFilename):
print(bcolors.WARNING + "File already exists. Skipping." + bcolors.ENDC)
else:
print("Attempting to download...", flush=True)
# get directory name(s)
directory = os.path.dirname(localFilename)
#print("Saving to directory: "+directory)
# if directories don't exist
if not os.path.exists(directory):
# make them
os.makedirs(directory)
# download and save file
if fnSaveFileFromURL(imageURL,localFilename,bolShowDetailedHTTPErrors):
print(bcolors.OKGREEN + "Image saved!" + bcolors.ENDC)
# add this URL to the arrSavedImages array
arrSavedImages.append(imageURL)
else:
print(bcolors.FAIL + "Unable to save image file." + bcolors.ENDC)
else:
print(bcolors.WARNING + "Image doesn't meet criteria. Skipping..." + bcolors.ENDC)
print("", flush=True)
# output summary information
print(bcolors.WARNING, end='') if len(arrSavedImages) == 0 else print(bcolors.OKGREEN, end='')
print("Total Images saved: "+str(len(arrSavedImages)))
print(bcolors.ENDC, end='')
print()
# if we are saving documents
if bolSaveDocs:
# Find document file links
print(bcolors.HEADER + 'Finding Documents:' + bcolors.ENDC)
# initialize document file array
arrSavedDocuments = []
# find all a tags and loop through them
for a in parsedHTMLContent.find_all('a', href=True):
# output current a href
#print("Link found: "+a['href'])
# does this URL meet the document file criteria
urlMatch = re.search(fileRegex,a['href'].lower())
if urlMatch:
print("Document file found: " + a['href'])
# get full file URL
fileURL = fnGetAbsoluteURL(a['href'],strFetchURL)
print('File URL: '+fileURL)
# set the appropriate corresponding local path
localFilename = fnGetURLLocalPath(a['href'],strFetchURL,strLocalDomainFolder,strLocalFolder,"documents")
print('Local Filename: '+localFilename)
# do we have this file URL in the arrSavedDocuments array already?
if fileURL in arrSavedDocuments:
print(bcolors.WARNING + "This document has already been saved!" + bcolors.ENDC)
else:
# does this file already exist?
if os.path.exists(localFilename):
print(bcolors.WARNING + "File already exists. Skipping." + bcolors.ENDC)
else:
print("Attempting to download...", flush=True)
# get directory name(s)
directory = os.path.dirname(localFilename)
#print("Saving to directory: "+directory)
# if directories don't exist
if not os.path.exists(directory):
# make them
os.makedirs(directory)
# download and save file
if fnSaveFileFromURL(fileURL,localFilename,bolShowDetailedHTTPErrors):
print(bcolors.OKGREEN + "Document file saved!" + bcolors.ENDC)
# add this URL to the arrSavedDocuments array
arrSavedDocuments.append(fileURL)
else:
print(bcolors.FAIL + "Unable to save document file." + bcolors.ENDC)
print("", flush=True)
# output summary information
print(bcolors.WARNING, end='') if len(arrSavedDocuments) == 0 else print(bcolors.OKGREEN, end='')
print("Total document files saved: "+str(len(arrSavedDocuments)))
print(bcolors.ENDC, end='')
print()
# print completed message
print(bcolors.HEADER + "URL processing complete!" + bcolors.ENDC)
print()
if bolSaveHTML or bolSaveCSS or bolSaveJS or bolSaveImages or bolSaveDocs:
print(bcolors.HEADER + "URL Summary:" + bcolors.ENDC)
if bolSaveHTML:
if bolSaveHTMLSuccessful:
print(bcolors.OKGREEN + "* HTML written to file: "+current_directory+'/'+strLocalPath + bcolors.ENDC)
else:
print(bcolors.FAIL + "* Unable to write HTML to file: "+current_directory+'/'+strLocalPath + bcolors.ENDC)
if bolSaveCSS: print("* Total stylesheets saved: "+str(len(arrSavedStylesheets)))
if bolSaveJS: print("* Total Javascript files saved: "+str(len(arrSavedJavascripts)))
if bolSaveImages: print("* Total images saved: "+str(len(arrSavedImages)))
if bolSaveDocs: print("* Total document files saved: "+str(len(arrSavedDocuments)))
print()
print()
print()
# print completed message
print()
print(bcolors.HEADER + 'Process complete.' + bcolors.ENDC)
print()
print('Total number of URLs processed: '+str(count_lines))
print()
# make alert sound
print('\a', end='')
### define global variables
# Set timestamp variable
timestamp = fnTimestamp()
# Text file list of URLs to scrape
urlListFile='input-urls.txt'
# regex to determine which file links to match
fileRegex = "(pdf|docx?|xlsx?|pptx?|zip|msi|dmg|gz)$"
# set default html file name
defaultFilename='index.html'
# show detailed HTTP request errors
bolShowDetailedHTTPErrors=False
### run main function if this file is running as the main program
if __name__ == "__main__":
main()
|
{"/gmuj-scrape.py": ["/functions.py"]}
|
37,735
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/predict_subject.py
|
from scipy.io import loadmat
import numpy as np
from path import path
data_dir = path('data')
train_subject_ids = range(1, 11)
train_subject_names = ["train_subject%02d.mat" % sid
for sid in train_subject_ids]
all_data = []
all_targets = []
all_sids = []
for sid, subject in zip(train_subject_ids, train_subject_names):
print subject
f = loadmat(data_dir / subject)
X = f['X'][:, 160:, 125:250]
y = f['y'].ravel() * 2 - 1
all_data.append(X)
all_targets.append(y)
all_sids.append([sid] * len(y))
all_data = np.concatenate(all_data)
all_targets = np.concatenate(all_targets)
all_sids = np.concatenate(all_sids)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression(C=1e-5)
pipeline = Pipeline([('scaler', StandardScaler()),
('clf', lr)])
from sklearn.cross_validation import StratifiedShuffleSplit, cross_val_score
cv = StratifiedShuffleSplit(all_sids, n_iter=10, test_size=.1)
scores = cross_val_score(pipeline,
all_data.reshape(len(all_data), -1),
all_sids,
cv=cv,
verbose=1000)
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,736
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/svm_test.py
|
import numpy as np
from sklearn.externals.joblib import Memory
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.pipeline import make_pipeline
from utils import load_train_subjects, load_test_subjects
import matplotlib.pyplot as plt
mem = Memory(cachedir="cache", verbose=10)
load_train_subjects = mem.cache(load_train_subjects)
load_test_subjects = mem.cache(load_test_subjects)
all_train_data, all_train_targets, all_train_labels = load_train_subjects()
all_test_data, all_test_labels = load_test_subjects()
val_idx = np.where(all_train_labels == 16)[0]
all_val_data = all_train_data[val_idx]
all_val_targets = all_train_targets[val_idx]
all_val_labels = all_train_labels[val_idx]
train_idx = np.where(all_train_labels < 15)[0]
all_train_data = all_train_data[train_idx]
all_train_targets = all_train_targets[train_idx]
all_train_labels = all_train_labels[train_idx]
X_train = all_train_data
y_train = all_train_targets
X_val = all_val_data
y_val = all_val_targets
X_train = X_train.reshape(len(X_train), -1)
X_val = X_val.reshape(len(X_val), -1)
# Train pipeline
bg = make_pipeline(StandardScaler(), SVC())
print("Training...")
bg.fit(X_train, y_train)
y_pred = bg.predict(X_train)
print("Accuracy on training data")
print(accuracy_score(y_train, y_pred))
y_pred = bg.predict(X_val)
print("Accuracy on validation data")
print(accuracy_score(y_val, y_pred))
# Try some cleanup...
del X_train
del all_train_data
del X_val
del all_val_data
# Load test data
print("Load testing data.")
all_test_data, all_test_labels = load_test_subjects()
X_test = all_test_data
X_test = X_test.reshape(len(X_test), -1)
y_pred = bg.predict(X_test)
predictions = y_pred
submission_file = "submission.csv"
print("Creating submission file", submission_file)
indices = np.zeros_like(predictions)
for l in np.unique(all_test_labels):
indices[all_test_labels == l] = 1000 * l + np.arange(
(all_test_labels == l).sum())
with open(submission_file, "w") as f:
f.write("Id,Prediction\n")
for ind, pred in zip(indices, predictions):
f.write("%d,%d\n" % (ind, pred))
print("Done.")
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,737
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/minimal_clf.py
|
import numpy as np
from sktensor import dtensor, cp_als
from sklearn.externals.joblib import Memory
from sklearn.pipeline import make_union, make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegressionCV
from sklearn.metrics import accuracy_score
from sklearn.base import BaseEstimator, TransformerMixin, ClassifierMixin
from scipy.stats import kurtosis
from sklearn.ensemble import BaggingClassifier
from utils import load_train_subjects, load_test_subjects
import matplotlib.pyplot as plt
def separate_grad_mag(X):
itr = np.arange(X.shape[1])
grad1 = np.where(itr % 3 == 0)[0]
grad2 = np.where((itr - 1) % 3 == 0)[0]
mag1 = np.where((itr - 2) % 3 == 0)[0]
return grad1, grad2, mag1
def drop_fifty_and_ten_hz(X):
idx = np.where(kurtosis(X) > 2)[0]
return idx
def get_basis(labels, data, n_components):
# Generate decompositions
print("Performing tensor decomposition of training data.")
all_basis = []
for n in np.unique(labels):
idx = np.where(labels == n)[0]
X = data[idx]
grad1, grad2, mag1 = separate_grad_mag(X)
grad = np.concatenate((grad1, grad2))
# Magnetometers look real rough
for idx in [grad, mag1]:
Xi = X[:, idx, :]
r = cp_als(dtensor(Xi), n_components, init="nvecs")
r_good_idx = drop_fifty_and_ten_hz(r[0].U[2])
basis = r[0].U[2][:, r_good_idx]
all_basis.append(basis)
basis = np.hstack(all_basis)
del all_basis
return basis
mem = Memory(cachedir="cache", verbose=10)
cp_als = mem.cache(cp_als)
get_basis = mem.cache(get_basis)
load_train_subjects = mem.cache(load_train_subjects)
load_test_subjects = mem.cache(load_test_subjects)
def subject_splitter(X, y, sids):
# Total hack but interesting idea if it can be generalized
all_X = []
all_y = []
for n in np.unique(sids):
idx = np.where(sids != n)[0]
all_X.append(X[idx])
all_y.append(y[idx])
# all_y.append(2 * n + y[idx])
#all_y.append((2 * y[idx] - 1) * n)
return zip(all_X, all_y)
class TensorTransform(BaseEstimator, TransformerMixin):
def __init__(self, subject_ids, n_components):
self.subject_ids = subject_ids
self.n_components = n_components
self.locked = False
def fit(self, X, y=None):
if not self.locked:
components = get_basis(self.subject_ids, X, self.n_components)
self.components_ = components
self.locked = True
return self
def transform(self, X, y=None):
return np.dot(X, self.components_).reshape(len(X), -1)
class FeatureUnionWrapper(BaseEstimator, TransformerMixin):
def __init__(self, clf):
self.clf = clf
def fit(self, X, y=None):
return self
def transform(self, X, y=None):
return self.clf.predict_proba(X).reshape(len(X), -1)
class StackedGeneralizer(BaseEstimator, ClassifierMixin):
def __init__(self):
pass
def fit(self, X, y):
# Filthy hack
sids = X[:, -1]
all_pipelines = [make_pipeline(LogisticRegressionCV()).fit(X_s, y_s) for
X_s, y_s in subject_splitter(X[:, :-1], y, sids)]
f_union = make_union(*[FeatureUnionWrapper(p) for p in all_pipelines])
self.clf_ = make_pipeline(f_union, LogisticRegressionCV()).fit(X[:, :-1], y)
return self
def predict(self, X, y=None):
# Dirty hack
return self.clf_.predict(X[:, :-1])
all_train_data, all_train_targets, all_train_labels = load_train_subjects()
all_test_data, all_test_labels = load_test_subjects()
tf = TensorTransform(np.concatenate((all_train_labels, all_test_labels)),
n_components=10)
tf.fit(np.vstack((all_train_data, all_test_data)))
val_idx = np.where(all_train_labels == 16)[0]
all_val_data = all_train_data[val_idx]
all_val_targets = all_train_targets[val_idx]
all_val_labels = all_train_labels[val_idx]
train_idx = np.where(all_train_labels < 15)[0]
all_train_data = all_train_data[train_idx]
all_train_targets = all_train_targets[train_idx]
all_train_labels = all_train_labels[train_idx]
X_train = all_train_data
y_train = all_train_targets
X_val = all_val_data
y_val = all_val_targets
X_train = tf.transform(X_train)
X_val = tf.transform(X_val)
X_train = np.hstack((X_train, all_train_labels[:, np.newaxis]))
X_val = np.hstack((X_val, all_val_labels[:, np.newaxis]))
# Train pipeline
bc = BaggingClassifier(base_estimator=StackedGeneralizer(),
n_estimators=10,
max_samples=.8,
max_features=1.0,
random_state=1999)
bg = make_pipeline(StandardScaler(), bc)
print("Training...")
bg.fit(X_train, y_train)
y_pred = bg.predict(X_train)
print("Accuracy on training data")
print(accuracy_score(y_train, y_pred))
y_pred = bg.predict(X_val)
print("Accuracy on validation data")
print(accuracy_score(y_val, y_pred))
# Try some cleanup...
del X_train
del all_train_data
del X_val
del all_val_data
# Load test data
print("Load testing data.")
all_test_data, all_test_labels = load_test_subjects()
X_test = all_test_data
X_test = tf.transform(X_test)
X_test = np.hstack((X_test, all_test_labels[:, np.newaxis]))
y_pred = bg.predict(X_test)
predictions = y_pred
submission_file = "submission.csv"
print("Creating submission file", submission_file)
indices = np.zeros_like(predictions)
for l in np.unique(all_test_labels):
indices[all_test_labels == l] = 1000 * l + np.arange(
(all_test_labels == l).sum())
with open(submission_file, "w") as f:
f.write("Id,Prediction\n")
for ind, pred in zip(indices, predictions):
f.write("%d,%d\n" % (ind, pred))
print("Done.")
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,738
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/subject_autoencoder.py
|
import numpy as np
import theano
import theano.tensor as T
theano.config.floatX = 'float32'
from utils import load_train_subjects, load_test_subjects
train_data, train_targets, train_labels = load_train_subjects([4])
rank = 2
all_subject_labels = train_labels
unique_subject_labels, label_associations = np.unique(
all_subject_labels, return_inverse=True)
rng = np.random.RandomState(42)
init_time_components = (
rng.rand(rank, train_data.shape[-1]) - 0.5
).astype(np.float32)[np.newaxis] * \
np.ones([len(unique_subject_labels), 1, 1])
init_sensor_components = (
rng.rand(rank, train_data.shape[1]) - 0.5
).astype(np.float32)[np.newaxis] * \
np.ones([len(unique_subject_labels), 1, 1])
init_offsets = np.zeros(len(unique_subject_labels))
time_components = theano.shared(init_time_components,
name='time_components',
borrow=False)
sensor_components = theano.shared(init_sensor_components,
name='sensor_components',
borrow=False)
offsets = theano.shared(init_offsets, name='offsets', borrow=False)
input_data = T.tensor3(name='input_data')
input_labels = T.lvector(name='input_labels')
with_offset = input_data - offsets[input_labels].dimshuffle(0, 'x', 'x')
sensor_projections = (
sensor_components[input_labels].dimshuffle(0, 1, 2, 'x') *
with_offset.dimshuffle(0, 'x', 1, 2)).sum(axis=2)
time_projections = (sensor_projections *
time_components[input_labels]).sum(axis=-1)
blowup = (time_projections.dimshuffle(0, 1, 'x', 'x') *
sensor_components[input_labels].dimshuffle(0, 1, 2, 'x') *
time_components[input_labels].dimshuffle(0, 1, 'x', 2)).sum(1)
blowup_with_offset = blowup + offsets[input_labels].dimshuffle(0, 'x', 'x')
autoencoder_mse = T.mean((input_data - blowup_with_offset) ** 2)
smoothness_penalty = T.mean((time_components[:, :, 1:] -
time_components[:, :, :-1]) ** 2)
penalty_factor = 10.
grad_ae_mse = T.grad(cost=autoencoder_mse +
penalty_factor * smoothness_penalty,
wrt=[sensor_components,
time_components,
offsets])
learning_rate = .1
batchsize = 50
updates = [(sensor_components,
sensor_components - learning_rate * grad_ae_mse[0]),
(time_components,
time_components - learning_rate * grad_ae_mse[1])]
i = T.lscalar('index')
s_train_data = theano.shared(train_data, borrow=True)
s_train_labels = theano.shared(label_associations, borrow=True)
if __name__ == "__main__":
f_time_projections = theano.function([input_data, input_labels],
time_projections)
f_blowup = theano.function([input_data, input_labels], blowup)
from sklearn.cross_validation import StratifiedShuffleSplit
cv = StratifiedShuffleSplit(label_associations, n_iter=1, test_size=.1)
train, val = iter(cv).next()
s_train, s_val = theano.shared(train), theano.shared(val)
givens_train = {input_data:
s_train_data[s_train[i * batchsize:
(i + 1) * batchsize]],
input_labels:
s_train_labels[s_train[i * batchsize:
(i + 1) * batchsize]]}
train_model = theano.function(inputs=[i],
outputs=autoencoder_mse,
updates=updates,
givens=givens_train)
num_batches = len(train) / batchsize
num_epochs = 1000
all_train_mses = []
for e in range(num_epochs):
train_mses = []
all_train_mses.append(train_mses)
for i in range(num_batches):
train_mses.append(train_model(i))
print np.mean(train_mses)
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,739
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/basic_clf.py
|
"""
DecMeg2014 example code.
Simple prediction of the class labels of the test set by:
- pooling all the training trials of all subjects in one dataset.
- Extracting the MEG data in the first 500ms from when the
stimulus starts.
- Projecting with RandomProjection
- Using a classifier.
Copyright Emanuele Olivetti 2014, BSD license, 3 clauses.
"""
import numpy as np
from sklearn.linear_model import LogisticRegression
from scipy.io import loadmat
import scipy.signal as sig
from sktensor import dtensor, cp_als
from sklearn.cross_validation import LeaveOneLabelOut
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
from IPython import embed
def view_filter(b, a):
w, h = sig.freqz(b, a)
plt.plot(w / abs(w), np.abs(h))
def notch(Wn, bandwidth):
"""
Notch filter to kill line-noise.
"""
f = Wn / 2.0
R = 1.0 - 3.0 * (bandwidth / 2.0)
num = 1.0 - 2.0 * R * np.cos(2 * np.pi * f) + R ** 2.
denom = 2.0 - 2.0 * np.cos(2 * np.pi * f)
K = num / denom
b = np.zeros(3)
a = np.zeros(3)
a[0] = 1.0
a[1] = -2.0 * R * np.cos(2 * np.pi * f)
a[2] = R ** 2.
b[0] = K
b[1] = -2.0 * K * np.cos(2 * np.pi * f)
b[2] = K
return b, a
def create_features(XX, tmin, tmax,
sfreq, tmin_original=-0.5,
perform_baseline_correction=True,
plot_name=""):
"""
Creation of the feature space.
- restricting the time window of MEG data to [tmin, tmax]sec.
- Concatenating the 306 timeseries of each trial in one long
vector.
- Normalizing each feature independently (z-scoring).
- optional: "baseline correction", a data centering concept often
used in M/EEG, will calculate a mean value per sensor
from pre-stimulus measurements, and subtract this from
the relevant measurement. Replaces centering based on
post-stimulus data
Returns a feature vector XX,
"""
print("Applying the desired time window and dropping sensors.")
lower_limit = 240
XX = XX[:, lower_limit:, :]
# instead of post-stimulus centering
baseline = XX[..., :125].mean(-1)
beginning = np.round((tmin - tmin_original) * sfreq).astype(np.int)
end = np.round((tmax - tmin_original) * sfreq).astype(np.int)
XX = XX[:, :, beginning:end].copy()
XX /= np.linalg.norm(XX, axis=2)[..., np.newaxis]
#Assuming 250Hz == fs, 125Hz == fs/2, 50Hz = 50/125 = .4
#5 Hz bw = 5/125 = .04
print("Applying notch filter for powerline.")
bw = .04
freq = .4
b, a = notch(freq, bw)
XX = sig.lfilter(b, a, XX)
#Assuming 250Hz == fs, 125Hz == fs/2, 50Hz = 10/125 = .08
#5 Hz bw = 5/125 = .04
print("Applying filter for alpha wave.")
bw = .04
freq = .08
b, a = notch(freq, bw)
XX = sig.lfilter(b, a, XX)
XX -= baseline[..., np.newaxis]
print("CP-ALS Decomposition.")
T = dtensor(XX)
P, fit, itr, exectimes = cp_als(T, 2, init='nvecs')
#P, fit, itr, exectimes = cp_als(T, 8, init='random')
proj = P.U[2]
fproj = np.abs(np.fft.fft(proj, axis=0))[:XX.shape[-1] // 2, :]
plt.figure()
plt.plot(proj)
plt.title(plot_name)
print("Projecting.")
XX = np.dot(XX, proj)
print("New shape is %sx%sx%s" % XX.shape)
print("2D Reshaping: concatenating all 306 timeseries.")
XX = XX.reshape(XX.shape[0], XX.shape[1] * XX.shape[2])
print("Features Normalization.")
XX -= XX.mean(0)
XX = np.nan_to_num(XX / XX.std(0))
return XX
if __name__ == '__main__':
print("DecMeg2014: https://www.kaggle.com/c/decoding-the-human-brain")
subjects_train = range(1, 17)
print("Training on subjects", subjects_train)
# We throw away all the MEG data outside the first 0.5sec from when
# the visual stimulus start:
tmin = 0.0
tmax = 0.500
print("Restricting MEG data to the interval [%s, %s] sec." % (tmin, tmax))
X_train = []
y_train = []
X_test = []
ids_test = []
label_count = []
print("Creating the trainset.")
for n, subject in enumerate(subjects_train):
filename = 'data/train_subject%02d.mat' % subject
print("Loading", filename)
data = loadmat(filename, squeeze_me=True)
XX = data['X']
yy = data['y']
sfreq = data['sfreq']
tmin_original = data['tmin']
print("Dataset summary:")
print("XX:", XX.shape)
print("yy:", yy.shape)
print("sfreq:", sfreq)
XX = create_features(XX, tmin, tmax, sfreq, plot_name=filename)
X_train.append(XX)
y_train.append(yy)
label_count += [subject] * len(XX)
X_train = np.vstack(X_train)
y_train = np.concatenate(y_train)
print("Trainset:", X_train.shape)
print("Creating the testset.")
subjects_test = range(17, 24)
for n, subject in enumerate(subjects_test):
filename = 'data/test_subject%02d.mat' % subject
print("Loading", filename)
data = loadmat(filename, squeeze_me=True)
XX = data['X']
ids = data['Id']
sfreq = data['sfreq']
tmin_original = data['tmin']
print("Dataset summary:")
print("XX:", XX.shape)
print("ids:", ids.shape)
print("sfreq:", sfreq)
XX = create_features(XX, tmin, tmax, sfreq, plot_name=filename)
X_test.append(XX)
ids_test.append(ids)
X_test = np.vstack(X_test)
ids_test = np.concatenate(ids_test)
print("Testset:", X_test.shape)
clf = LogisticRegression(C=.1)
in_subject = []
out_subject = []
lol = LeaveOneLabelOut(label_count)
embed()
itr = 0
for train_index, test_index in lol:
print("Patient %s" % itr)
clf.fit(X_train[train_index], y_train[train_index])
y_pred = clf.predict(X_train[test_index])
osub = accuracy_score(y_train[test_index], y_pred)
print("Accuracy on unknown: %0.2f" % osub)
clf.fit(X_train[train_index], y_train[train_index])
y_pred = clf.predict(X_train[train_index])
isub = accuracy_score(y_train[train_index], y_pred)
print("Accuracy on known: %0.2f" % isub)
itr += 1
print("LeaveOneSubjectOut scores.")
in_scores = np.array(in_subject)
out_scores = np.array(out_subject)
print(in_scores)
print(out_scores)
print("Accuracy: %0.2f (+/- %0.2f)" % (in_scores.mean(),
in_scores.std() * 2))
print("Accuracy: %0.2f (+/- %0.2f)" % (out_scores.mean(),
out_scores.std() * 2))
print("Training.")
print(X_train.shape)
clf.fit(X_train, y_train)
print("Predicting.")
y_pred = clf.predict(X_test)
filename_submission = "submission.csv"
print("Creating submission file", filename_submission)
with open(filename_submission, "w") as f:
f.write("Id,Prediction\n")
for i in range(len(y_pred)):
f.write(str(ids_test[i]) + "," + str(y_pred[i]) + "\n")
print("Done.")
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,740
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/energy_maximum.py
|
import numpy as np
from scipy.io import loadmat
import mne
import scipy
from path import path
train_subject_ids = range(1, 17)
train_subject_names = ["train_subject%02d.mat" % sid
for sid in train_subject_ids]
test_subject_ids = range(17, 24)
test_subject_names = ["test_subject%02d.mat" % sid
for sid in test_subject_ids]
subject_names = train_subject_names + test_subject_names
data_dir = path('data')
import matplotlib.pyplot as plt
fig1 = plt.figure()
fig2 = plt.figure()
fig3 = plt.figure()
for i, subject in enumerate(subject_names):
print i
f = loadmat(data_dir / subject)
X = f['X']
# y = f['y'].ravel() * 2 - 1
X = X[:, 160:, 125:250]
X /= np.sqrt((X ** 2).sum(-1))[..., np.newaxis]
energy = (X ** 2).mean(0)
plt.figure(fig1.number)
plt.subplot(3, 8, i + 1)
plt.imshow(energy)
plt.xlabel("sub%02d" % (i + 1))
plt.figure(fig2.number)
plt.subplot(3, 8, i + 1)
plt.plot(np.arange(0, 0.5, 0.004), np.linalg.svd(energy)[2][:3].T)
plt.xlabel("sub%02d" % (i + 1))
plt.figure(fig3.number)
plt.subplot(3, 8, i + 1)
plt.plot(np.arange(0, 0.5, 0.004), energy.mean(0), 'k', lw=2)
plt.plot(np.arange(0, 0.5, 0.004),
scipy.ndimage.gaussian_filter(energy.mean(0), sigma=10), 'b')
plt.xlabel("sub%02d" % (i + 1))
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression(C=5e-1, penalty="l2")
# from sklearn.cross_validation import cross_val_score, StratifiedShuffleSplit
fig4 = plt.figure()
for i, subject in enumerate(train_subject_names):
print i
f = loadmat(data_dir / subject)
X = f['X']
y = f['y'].ravel() * 2 - 1
X = X[:, 160:, 125:250]
X /= np.sqrt((X ** 2).sum(-1))[..., np.newaxis]
weights = lr.fit(X.reshape(len(X), -1), y).coef_.reshape(X.shape[1:])
plt.subplot(3, 8, i + 1)
plt.plot((weights ** 2).sum(0))
plt.show()
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,741
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/lasso_timecourse_selection.py
|
import numpy as np
from scipy.io import loadmat
from path import path
from sklearn.externals.joblib import Memory
train_subject_ids = range(1, 17)
train_subject_names = ["train_subject%02d.mat" % sid
for sid in train_subject_ids]
data_dir = path("data")
from sklearn.linear_model import LassoLarsCV, LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.cross_validation import StratifiedShuffleSplit, cross_val_score
from sktensor import dtensor, cp_als
mem = Memory(cachedir='cache')
cp_als = mem.cache(cp_als)
all_decomps = []
all_weights = []
all_selected_timecourses = []
all_scores = []
for subject in train_subject_names:
print subject
f = loadmat(data_dir / subject)
X = f['X'][:, 160:, 125:250]
y = f['y'].ravel() * 2 - 1
cv = StratifiedShuffleSplit(y, n_iter=50, test_size=.1)
pipeline = Pipeline([('scaler', StandardScaler()),
('estimator', LassoLarsCV(cv=cv))])
T = dtensor(X)
r = cp_als(T, rank=10)
sample_axes = r[0].U[0]
pipeline.fit(sample_axes, y)
weights = pipeline.steps[1][1].coef_
all_weights.append(weights)
selected = np.where(weights != 0)[0]
all_selected_timecourses.append(r[0].U[2][:, selected])
pipeline_global_eval = Pipeline([
('scaler', StandardScaler()),
('estimator', LogisticRegression(C=1., penalty="l1"))])
global_scores = cross_val_score(pipeline_global_eval,
sample_axes, y, cv=cv,
verbose=1000)
all_scores.append(global_scores)
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,742
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/tensor_decomp_clf.py
|
"""
DecMeg2014 example code.
Simple prediction of the class labels of the test set by:
- pooling all the training trials of all subjects in one dataset.
- Extracting the MEG data in the first 500ms from when the
stimulus starts.
- Projecting with RandomProjection
- Using a classifier.
Copyright Emanuele Olivetti 2014, BSD license, 3 clauses.
"""
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from scipy.io import loadmat
import scipy.signal as sig
from sktensor import dtensor, cp_als
from sklearn.cross_validation import LeavePLabelOut
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import os
def view_filter(b, a):
w, h = sig.freqz(b, a)
plt.plot(w / abs(w), np.abs(h))
def notch(Wn, bandwidth):
"""
Notch filter to kill line-noise.
"""
f = Wn / 2.0
R = 1.0 - 3.0 * (bandwidth / 2.0)
num = 1.0 - 2.0 * R * np.cos(2 * np.pi * f) + R ** 2.
denom = 2.0 - 2.0 * np.cos(2 * np.pi * f)
K = num / denom
b = np.zeros(3)
a = np.zeros(3)
a[0] = 1.0
a[1] = -2.0 * R * np.cos(2 * np.pi * f)
a[2] = R ** 2.
b[0] = K
b[1] = -2.0 * K * np.cos(2 * np.pi * f)
b[2] = K
return b, a
def window(XX, lower_limit=160, tmin=0.0, tmax=0.5, sfreq=250, tmin_original=-.5):
# We throw away all the MEG data outside the first 0.5sec from when
# the visual stimulus start:
print("Restricting MEG data to the interval [%s, %s] sec." % (tmin, tmax))
XX = XX[:, lower_limit:, :]
# instead of post-stimulus centering
print("Apply desired time window and drop sensors 0 to %i." % lower_limit)
beginning = np.round((tmin - tmin_original) * sfreq).astype(np.int)
end = np.round((tmax - tmin_original) * sfreq).astype(np.int)
XX = XX[:, :, beginning:end].copy()
return XX
def notch_filter(XX):
# Assuming 250Hz == fs, 125Hz == fs/2, 50Hz = 50/125 = .4
# 5 Hz bw = 5/125 = .04
print("Applying notch filter for powerline.")
bw = .04
freq = .4
b, a = notch(freq, bw)
XX = sig.lfilter(b, a, XX)
# Assuming 250Hz == fs, 125Hz == fs/2, 50Hz = 10/125 = .08
# 5 Hz bw = 5/125 = .04
print("Applying filter for alpha wave.")
bw = .04
freq = .08
b, a = notch(freq, bw)
XX = sig.lfilter(b, a, XX)
return XX
def window_baseline(XX, lower_limit=160):
baseline = XX[:, lower_limit:, :125].mean(-1)
XX = window(XX)
print("Baseline.")
XX -= baseline[..., np.newaxis]
return XX
def window_filter(XX):
XX = window(XX)
XX = notch_filter(XX)
return XX
def window_filter_baseline(XX, lower_limit=160):
baseline = XX[:, lower_limit:, :125].mean(-1)
XX = window(XX)
XX = notch_filter(XX)
XX -= baseline[..., np.newaxis]
return XX
def get_outlier_mask(XX):
print("Getting outlier mask.")
mask = (XX ** 2).sum(axis=-1).sum(axis=-1)
mask = mask.argsort()[10:-10]
return mask
def get_tensor_decomposition(XX, n=2):
print("CP-ALS Decomposition.")
T = dtensor(XX)
P, fit, itr, exectimes = cp_als(T, n, init='nvecs')
proj = P.U
return proj
def load_train_data(exclude_subject=16):
subjects_train = [i for i in range(1, 17) if i != exclude_subject]
print("Loading subjects", subjects_train)
X_train = []
y_train = []
label_count = []
print("Creating the trainset.")
for n, subject in enumerate(subjects_train):
filename = 'data/train_subject%02d.mat' % subject
print("Loading", filename)
data = loadmat(filename, squeeze_me=True)
XX = data['X']
yy = data['y']
XX = window_filter_baseline(XX)
X_train.append(XX)
y_train.append(yy)
label_count += [subject] * len(XX)
X_train = np.vstack(X_train)
y_train = np.concatenate(y_train)
print("Trainset:", X_train.shape)
return X_train, y_train, label_count
def load_val_data(subject=16):
subjects_val = [subject]
print("Loading subjects", subjects_val)
X_val = []
y_val = []
label_count = []
print("Creating the validation set.")
for n, subject in enumerate(subjects_val):
filename = 'data/train_subject%02d.mat' % subject
print("Loading", filename)
data = loadmat(filename, squeeze_me=True)
XX = data['X']
yy = data['y']
XX = window_filter_baseline(XX)
X_val.append(XX)
y_val.append(yy)
label_count += [subject] * len(XX)
X_val = np.vstack(X_val)
y_val = np.concatenate(y_val)
print("Validation set:", X_val.shape)
return X_val, y_val, label_count
def load_test_data():
subjects_test = range(17, 24)
print("Loading subjects", subjects_test)
X_test = []
ids_test = []
label_count = []
print("Creating the testset.")
for n, subject in enumerate(subjects_test):
filename = 'data/test_subject%02d.mat' % subject
print("Loading", filename)
data = loadmat(filename, squeeze_me=True)
XX = data['X']
ids = data['Id']
XX = window_filter_baseline(XX)
X_test.append(XX)
ids_test.append(ids)
label_count += [subject] * len(XX)
X_test = np.vstack(X_test)
ids_test = np.concatenate(ids_test)
print("Testset:", X_test.shape)
return X_test, ids_test, label_count
def get_data(val_index=16):
if val_index > 16:
raise ValueError("There are only 16 training patients!")
saved_data_path = "saved_data_val_%i.npz" % val_index
if not os.path.exists(saved_data_path):
print("Saved, preprocessed data not found in %s" % saved_data_path)
X_train, y_train, label_count_train = load_train_data()
X_test, ids_test, label_count_test = load_test_data()
X_val, y_val, label_count_val = load_val_data()
np.savez(saved_data_path,
X_train=X_train,
y_train=y_train,
X_val=X_val,
y_val=y_val,
X_test=X_test,
ids_test=ids_test,
label_count_train=label_count_train,
label_count_test=label_count_test,
label_count_val=label_count_val)
else:
print("Saved, preprocessed data found in %s" % saved_data_path)
npzfile = np.load(saved_data_path)
X_train = npzfile['X_train']
y_train = npzfile['y_train']
X_val = npzfile['X_val']
y_val = npzfile['y_val']
X_test = npzfile['X_test']
ids_test = npzfile['ids_test']
label_count_train = npzfile['label_count_train']
label_count_test = npzfile['label_count_test']
label_count_val = npzfile['label_count_val']
return (X_train, y_train, label_count_train, X_test, ids_test,
label_count_test, X_val, y_val, label_count_val)
def project_against_timeseries_tensors(X_train, X_test, X_val, label_count_train,
label_count_test, label_count_val):
n_basis = 75
saved_proj = "saved_time_projs_%s.npz" % n_basis
if not os.path.exists(saved_proj):
X_full = np.vstack((X_train, X_test, X_val))
label_count_full = np.concatenate((label_count_train, label_count_test,
label_count_val))
print("Saved time projection file not found in %s" % saved_proj)
print("Creating projections")
lol = LeavePLabelOut(label_count_full, p=1)
proj = []
for n, (train_index, test_index) in enumerate(lol):
print("Getting dictionary for patient %s" % n)
trial_proj, sensor_proj, time_proj = get_tensor_decomposition(
X_full[test_index], n_basis)
proj.append(time_proj)
proj = np.array(proj)
np.savez(saved_proj, proj=proj)
else:
print("Saved projection files found in %s" % saved_proj)
npzfile = np.load(saved_proj)
proj = npzfile['proj']
proj = np.max(proj, axis=-1)
X_train = np.dot(X_train, proj.T)
X_test = np.dot(X_test, proj.T)
X_val = np.dot(X_val, proj.T)
print("Shape of reduced train data %i x %i x %i" % X_train.shape)
print("Shape of reduced test data %i x %i x %i" % X_test.shape)
print("Shape of reduced val data %i x %i x %i" % X_val.shape)
return X_train, X_test, X_val
if __name__ == '__main__':
print("DecMeg2014: https://www.kaggle.com/c/decoding-the-human-brain")
validation_subject = 16
(X_train, y_train, label_count_train,
X_test, ids_test, label_count_test,
X_val, y_val, label_count_val) = get_data(val_index=validation_subject)
pipe = Pipeline([("scaler", StandardScaler()),
("clf", LogisticRegression(C=.1, penalty='l2'))])
X_train, X_test, X_val = project_against_timeseries_tensors(
X_train, X_test, X_val, label_count_train, label_count_test,
label_count_val)
print("Projection complete.")
X_train = X_train.reshape(X_train.shape[0], -1)
X_test = X_test.reshape(X_test.shape[0], -1)
X_val = X_val.reshape(X_val.shape[0], -1)
print("Training.")
pipe.fit(X_train, y_train)
print("Predicting validation subject.")
y_val_pred = pipe.predict(X_val)
acc = accuracy_score(y_val, y_val_pred)
print("Accuracy on validation subject %s" % acc)
print("Predicting test set.")
y_pred = pipe.predict(X_test)
filename_submission = "submission.csv"
print("Creating submission file", filename_submission)
with open(filename_submission, "w") as f:
f.write("Id,Prediction\n")
for i in range(len(y_pred)):
f.write(str(ids_test[i]) + "," + str(y_pred[i]) + "\n")
print("Done.")
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,743
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/conv_mp.py
|
import numpy as np
from numpy.lib.stride_tricks import as_strided
from sklearn.utils import check_random_state
def fft_convolution_product(a, b, axes=((0,), (0,)), mode="valid"):
"""Does an fft convolution product along given axes.
If sizes along axes correspond and `valid` is chosen, then this reduces
to the common matrix product."""
a_axes, b_axes = axes
if len(a_axes) > 1 or len(b_axes) > 1:
raise NotImplementedError("Only implemented for 1D conv right now")
# Make smaller template be in first array
if a.shape[a_axes[0]] > b.shape[b_axes[0]]:
raise ValueError("Please specify smaller conv kernel in first place")
# embed smaller array in larger one
size = list(a.shape)
for aa, ab in zip(a_axes, b_axes):
size[aa] = b.shape[ab]
a_ = np.zeros(size)
slices = [slice(None, s) for s in a.shape]
a_[slices] = a
a_ = np.fft.fftn(a_, axes=a_axes)
b_ = np.fft.fftn(b, axes=b_axes)
# roll convolution axes to the end
a_ = np.rollaxis(a_, a_axes[0], a_.ndim)
b_ = np.rollaxis(b_, b_axes[0], b_.ndim)
remaining_axes_a = tuple(slice(None, s) for s in a_.shape[:-1])
remaining_axes_b = tuple(slice(None, s) for s in b_.shape[:-1])
broad_axes_a = remaining_axes_a + (np.newaxis,) * len(remaining_axes_b)
broad_axes_b = (np.newaxis,) * len(remaining_axes_a) + remaining_axes_b
convolution = np.fft.ifftn(a_[broad_axes_a] *
b_[broad_axes_b],
axes=(-1,))
if mode == "valid":
convolution = convolution[..., a.shape[a_axes[0]] - 1:]
else:
raise NotImplementedError
return np.real(convolution)
def mp_code_update(residual, filters, copy_residual=True):
"""Does one MP update. Works on last axis. Filters should be 2D"""
if filters.ndim > 2:
raise ValueError("filters should be 2D")
filter_length = filters.shape[-1]
filter_norms = np.sqrt((filters.reshape(len(filters), -1) ** 2).sum(-1))
normalized_filters = filters / filter_norms[..., np.newaxis]
convolutions = fft_convolution_product(
normalized_filters[..., ::-1],
residual,
axes=((filters.ndim - 1,), (residual.ndim - 1,)))
abs_convolutions = np.abs(np.rollaxis(convolutions, 0, -1))
argmaxes = abs_convolutions.reshape(
residual.shape[:-1] + (-1,)).argmax(-1)
argmax_fil = argmaxes // convolutions.shape[-1]
argmax_t = argmaxes % convolutions.shape[-1]
if copy_residual:
residual = residual.copy()
channel_index_slices = [slice(0, p) for p in residual.shape[:-1]]
channel_indices = np.mgrid[channel_index_slices]
activation_value = np.rollaxis(convolutions, 0, -1)[
list(channel_indices) + [argmax_fil, argmax_t]]
activations = np.zeros_like(np.rollaxis(convolutions, 0, -1))
activations[list(channel_indices) +
[argmax_fil, argmax_t]] = activation_value
for chind in channel_indices.reshape(len(channel_indices), -1).T:
fil_index = argmax_fil[list(chind[:, np.newaxis])][0]
t_index = argmax_t[list(chind[:, np.newaxis])][0]
activation = activation_value[list(chind[:, np.newaxis])][0]
sl = [slice(c, c + 1) for c in chind] + \
[slice(t_index, t_index + filter_length)]
# [slice(fil_index, fil_index + 1)] + \
residual[sl] -= activation * normalized_filters[fil_index]
# Watch out, as of now, activations are wrt normed filters
return activations, residual
def conv_mp(signal, filters, n_components=1):
counter = 0
residual = signal.copy()
global_activations = 0
while counter < n_components:
counter += 1
activations, residual = mp_code_update(residual, filters)
global_activations = global_activations + activations
return global_activations, residual
def kron_id_view(vec, id_length, axis=-1):
shape = (vec.shape[:axis] +
(vec.shape[axis] - id_length + 1, id_length) +
vec.shape[axis % vec.ndim + 1:])
strides = vec.strides[:axis] + (vec.strides[axis],) + vec.strides[axis:]
return as_strided(vec, shape=shape, strides=strides)
def update_filters(signal, activations):
signal_length = signal.shape[-1]
activation_length = activations.shape[-1]
filter_length = signal_length - activation_length + 1
num_filters = activations.shape[-2]
ata = np.einsum('ijkl, ijml -> km', activations, activations)
inv_ata = np.linalg.inv(ata)
v_ = np.zeros([num_filters, filter_length])
for i in range(filter_length):
v_[:, i] = np.einsum(
"ijkl, ijl -> k",
activations,
signal[:, :, i:-(filter_length - i - 1) or None])
return inv_ata.dot(v_)
def conv_dict_learning(signal,
n_components=20,
n_iter=100,
n_templates=3,
template_length=20,
init_templates=None,
random_state=42,):
rng = check_random_state(random_state)
if init_templates is not None:
templates = init_templates.copy()
else:
templates = rng.randn(n_templates, template_length)
for i in xrange(n_iter):
activations, residual = conv_mp(signal, templates, n_components)
templates = update_filters(signal, activations)
return templates, activations, residual
from numpy.testing import assert_array_almost_equal
def test_simple_convolution():
b = np.arange(20)
A = np.eye(5)
for a in A:
npconv = np.convolve(a, b, mode="valid")
convprod = fft_convolution_product(a, b)
assert_array_almost_equal(npconv, convprod)
def test_multiple_convolution():
b = np.arange(100).reshape(5, 20)
a = np.eye(4)
convprod = fft_convolution_product(a, b, axes=((1,), (1,)))
convolutions = np.array([[np.convolve(aa, bb, mode="valid") for bb in b]
for aa in a])
assert_array_almost_equal(convprod, convolutions)
def generate_conv_sparse_signal():
filter_size = 20
filter_1 = np.zeros(filter_size)
filter_1[0] = 1.
x = np.arange(filter_size)
filter_2 = np.maximum(
0, 1. - ((x - filter_size / 2.) / (filter_size / 4.)) ** 2)
filter_3 = np.maximum(
0, 1. - np.abs((x - filter_size / 2.) / (filter_size / 4.)))
filters = np.array([filter_1, filter_2, filter_3])
rng = np.random.RandomState(42)
signal_length = 400
support_fraction = .02
support = rng.rand(3, signal_length) < support_fraction
activation_values = rng.randn(support.sum())
activations = np.zeros_like(support, dtype=np.float64)
activations[support] = activation_values
signals = fft_convolution_product(
filters,
activations,
axes=((1,), (1,)))[[0, 1, 2], [0, 1, 2]]
return signals, filters, activations
def test_mp_code_update():
signals, filters, activations = generate_conv_sparse_signal()
signal1 = signals[0:2].sum(0)
signal2 = signals[1:].sum(0)
signal = np.array([
[signals.sum(0), signals[2]],
[signals[0], signals[1]],
[signal1, signal2]])
act, res = mp_code_update(signal, filters)
return signal, filters, act, res
def test_conv_mp():
signals, filters, activations = generate_conv_sparse_signal()
signal1 = signals[0:2].sum(0)
signal2 = signals[1:].sum(0)
signal = np.array([
[signals.sum(0), signals[2]],
[signals[0], signals[1]],
[signal1, signal2]])
act, res = conv_mp(signal, filters, n_components=10)
return signal, filters, act, res
def test_filter_update():
signals, filters, activations = generate_conv_sparse_signal()
signal1 = signals[0:2].sum(0)
signal2 = signals[1:].sum(0)
signal = np.array([
[signals.sum(0), signals[2]],
[signals[0], signals[1]],
[signal1, signal2]])
rng = np.random.RandomState(42)
init_filters = rng.randn(*filters.shape)
act, res = conv_mp(signal, filters, n_components=20)
new_filters = update_filters(signal, act)
return init_filters, new_filters
def test_conv_dict_learning():
signals, filters, activations = generate_conv_sparse_signal()
signal1 = signals[0:2].sum(0)
signal2 = signals[1:].sum(0)
signal = np.array([
[signals.sum(0), signals[2]],
[signals[0], signals[1]],
[signal1, signal2]])
filters, activations, residual = conv_dict_learning(signal,
n_components=20,
n_iter=10,
n_templates=3,
template_length=20,
)
return filters, activations, residual, signal
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,744
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/intra_subject_decoding.py
|
import numpy as np
from path import path
from scipy.io import loadmat
subject_ids = [4]
subject_names = ["train_subject%02d.mat" % sid for sid in subject_ids]
data_dir = path("data")
timecourses = np.load('timecourses.npz')["A"]
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
pipeline = Pipeline([
("scaler", StandardScaler()),
("classifier", LogisticRegression(C=1e-1, penalty="l2"))
])
from sklearn.cross_validation import cross_val_score, StratifiedShuffleSplit
for subject in subject_names:
f = loadmat(data_dir / subject)
X = f['X'][:, 160:, 125:250]
y = f['y'].ravel() * 2 - 1
cv = StratifiedShuffleSplit(y, n_iter=20, test_size=.1)
scores_raw = cross_val_score(pipeline, X.reshape(len(X), -1), y, cv=cv,
verbose=100)
projected = X.dot(timecourses)
scores_projected = cross_val_score(
pipeline, projected.reshape(len(X), -1), y, cv=cv, verbose=100)
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,745
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/theano_lowrank_net.py
|
import numpy as np
# from scipy.io import loadmat
# train_subject_ids = range(1, 17)
# test_subject_ids = range(17, 24)
# train_subject_names = ["train_subject%02d.mat" % sid
# for sid in train_subject_ids]
# test_subject_names = ["test_subject%02d.mat" % sid
# for sid in test_subject_ids]
# from path import path
# data_dir = path("data")
# train_data = []
# train_targets = []
# train_labels = []
# for sid, subject in zip(train_subject_ids, train_subject_names):
# print subject
# f = loadmat(data_dir / subject)
# X = f['X'][:, 159:, 125:250]
# y = f['y'].ravel()
# labels = [sid] * len(y)
# # try standard scaling here
# X -= X.mean(0)
# X /= X.std(0)
# train_data.append(X)
# train_targets.append(y)
# train_labels.append(labels)
# train_data = np.concatenate(train_data)
# train_targets = np.concatenate(train_targets)
# train_labels = np.concatenate(train_labels)
from utils import load_train_subjects
train_data, train_targets, train_labels = load_train_subjects()
joint_labels = np.array(["%s_%s" % (str(l), str(t))
for t, l in zip(train_labels, train_targets)])
unique_labels, label_indices = np.unique(joint_labels, return_inverse=True)
train_gradiometers = train_data.reshape(
len(train_data), -1, 3,
train_data.shape[-1])[:, :, :2, :].reshape(
len(train_data), -1,
train_data.shape[-1])
import theano
import theano.tensor as T
theano.config.floatX = 'float32'
rank_s, rank_t = 4, 4
n_joint_outputs = 32
# initialize shared variables
rng = np.random.RandomState(42)
# matrices attacking each side of a trial matrix
W_sensors = (rng.rand(rank_s, train_data.shape[1]) - 0.5).astype('float32')
W_time = (rng.rand(train_data.shape[2], rank_t) - 0.5).astype('float32')
# the matrix from the low rank representation to joint output and offset
W_joint_outputs = (rng.rand(rank_s * rank_t, n_joint_outputs) - 0.5
).astype('float32')
b_joint_outputs = np.zeros(n_joint_outputs, dtype=np.float32)
input_data = T.tensor3(name='input_data', dtype='float32')
SW_sensors = theano.shared(W_sensors, name='SW_sensors')
SW_time = theano.shared(W_time, name='SW_time')
SW_joint_outputs = theano.shared(W_joint_outputs, name='SW_joint_outputs')
Sb_joint_outputs = theano.shared(b_joint_outputs, name='Sb_joint_outputs')
sensor_projections = SW_sensors.dot(input_data).dimshuffle(1, 0, 2)
time_projections = sensor_projections.dot(SW_time)
joint_outputs_raw = time_projections.reshape(
(-1, rank_s * rank_t)).dot(SW_joint_outputs)
joint_outputs_raw_b = joint_outputs_raw + Sb_joint_outputs.dimshuffle('x', 0)
joint_outputs_softmax = T.nnet.softmax(joint_outputs_raw_b)
y = T.lvector('y')
negative_log_likelihood = -T.mean(
T.log(joint_outputs_softmax)[T.arange(y.shape[0]), y])
classify = T.argmax(joint_outputs_softmax, axis=1)
accuracy = T.cast(T.eq(classify, y), 'float32').mean()
grad_log_lik = T.grad(cost=negative_log_likelihood,
wrt=[SW_sensors,
SW_time,
SW_joint_outputs,
Sb_joint_outputs])
# write this gradient separately because the other won't output float32 ...
gll_SWjo = T.grad(cost=negative_log_likelihood, wrt=SW_joint_outputs)
gll_SWsen = T.grad(cost=negative_log_likelihood, wrt=SW_sensors)
learning_rate = .01
batch_size = 50
updates = [(SW_sensors, SW_sensors - learning_rate * gll_SWsen),
(SW_time, SW_time - learning_rate * grad_log_lik[1]),
(SW_joint_outputs, SW_joint_outputs -
learning_rate * gll_SWjo),
(Sb_joint_outputs, Sb_joint_outputs -
learning_rate * grad_log_lik[3])]
index = T.lscalar('index')
from sklearn.cross_validation import StratifiedShuffleSplit
train, val_test = iter(StratifiedShuffleSplit(label_indices,
n_iter=1,
test_size=.5)).next()
val = val_test[:len(val_test) / 2]
test = val_test[len(val_test) / 2:]
reduced_label_indices = np.unique(label_indices,
return_inverse=True)[1]
s_label_indices = theano.shared(reduced_label_indices)
s_train_data = theano.shared(train_data)
s_train = theano.shared(train)
givens = {y: s_label_indices[s_train[index * batch_size:
(index + 1) * batch_size]],
input_data: s_train_data[s_train[index * batch_size:
(index + 1) * batch_size]]}
train_model = theano.function(inputs=[index],
outputs=negative_log_likelihood,
updates=updates,
givens=givens)
val_model = theano.function(inputs=[],
outputs=negative_log_likelihood,
givens={y: s_label_indices[val],
input_data: s_train_data[val]})
val_accuracy = theano.function(inputs=[],
outputs=accuracy,
givens={y: s_label_indices[val],
input_data: s_train_data[val]})
len_train = len(train)
n_batches = len_train / batch_size
W_l2_targets = rng.rand(n_joint_outputs, 2).astype('float32')
b_l2_targets = np.zeros(2, dtype=np.float32)
SW_l2_targets = theano.shared(W_l2_targets)
Sb_l2_targets = theano.shared(b_l2_targets)
l2_target_raw = joint_outputs_softmax.dot(SW_l2_targets) + \
Sb_l2_targets.dimshuffle('x', 0)
l2_target_softmax = T.nnet.softmax(l2_target_raw)
y2 = T.lvector()
l2_neg_log_lik = -T.mean(T.log(l2_target_softmax)[T.arange(y2.shape[0]), y2])
l2_classify = T.argmax(l2_target_softmax, axis=1)
l2_accuracy = T.cast(T.eq(l2_classify, y2), 'float32').mean()
s_targets = theano.shared(train_targets)
grad_l2_neg_log_lik = T.grad(cost=l2_neg_log_lik,
wrt=[SW_l2_targets,
Sb_l2_targets])
learning_rate2 = 0.01
l2_updates = [(SW_l2_targets,
SW_l2_targets - learning_rate2 * grad_l2_neg_log_lik[0]),
(Sb_l2_targets,
Sb_l2_targets - learning_rate2 * grad_l2_neg_log_lik[1])]
l2_givens = {y2: s_targets[s_train[index * batch_size:
(index + 1) * batch_size]],
input_data: s_train_data[s_train[index * batch_size:
(index + 1) * batch_size]]}
train_l2 = theano.function(inputs=[index],
outputs=l2_neg_log_lik,
updates=l2_updates,
givens=l2_givens)
val_l2 = theano.function(inputs=[],
outputs=l2_neg_log_lik,
givens={y2: s_targets[val],
input_data: s_train_data[val]})
val_l2_accuracy = theano.function(inputs=[],
outputs=l2_accuracy,
givens={y2: s_targets[val],
input_data: s_train_data[val]})
grad_l2_everybody = T.grad(cost=l2_neg_log_lik,
wrt=[SW_sensors,
SW_time,
SW_joint_outputs,
Sb_joint_outputs,
SW_l2_targets,
Sb_l2_targets])
updates_everybody = [(SW_sensors,
SW_sensors - learning_rate * grad_l2_everybody[0]),
(SW_time,
SW_time - learning_rate * grad_l2_everybody[1]),
(SW_joint_outputs,
SW_joint_outputs -
learning_rate * grad_l2_everybody[2]),
(Sb_joint_outputs,
Sb_joint_outputs -
learning_rate * grad_l2_everybody[3]),
(SW_l2_targets,
SW_l2_targets - learning_rate2 * grad_l2_everybody[4]),
(Sb_l2_targets,
Sb_l2_targets - learning_rate2 * grad_l2_everybody[5])]
train_l2_everybody = theano.function(inputs=[index],
outputs=l2_neg_log_lik,
updates=updates_everybody,
givens=l2_givens)
if __name__ == "__main__":
# f_sensor_projections = theano.function([input_data],
# sensor_projections)
# f_time_projections = theano.function([input_data],
# time_projections)
# f_joint_outputs_raw = theano.function([input_data],
# joint_outputs_raw)
# f_joint_outputs_raw_b = theano.function([input_data],
# joint_outputs_raw_b)
f_joint_outputs_softmax = theano.function([input_data],
joint_outputs_softmax)
# f_neg_log_lik = theano.function([input_data, y],
# negative_log_likelihood)
# f_grad_neg_log_lik = theano.function([input_data, y],
# grad_log_lik)
# f_gll_SWjo = theano.function([input_data, y], gll_SWjo)
# f_gll_SWsen = theano.function([input_data, y], gll_SWsen)
f_accuracy = theano.function([input_data, y], accuracy)
train_energy = []
val_energy = []
val_acc = []
n_epochs = 200
for e in range(n_epochs):
train_epoch = []
train_energy.append(train_epoch)
for i in range(n_batches):
train_epoch.append(train_model(i))
val_energy.append(val_model())
val_acc.append(val_accuracy())
print "Epoch %d: mean train %1.3f, val %1.3f, acc %1.3f" % (
e, np.mean(train_epoch), val_energy[-1], val_acc[-1])
n_l2_epochs = 200
train_energy_l2 = []
val_energy_l2 = []
val_acc_l2 = []
for e in range(n_l2_epochs):
train_epoch = []
train_energy_l2.append(train_epoch)
for i in range(n_batches):
train_epoch.append(train_l2(i))
val_energy_l2.append(val_l2())
val_acc_l2.append(val_l2_accuracy())
print "Epoch %d: mean train %1.3f, val %1.3f, acc %1.3f" % (
e, np.mean(train_epoch), val_energy_l2[-1],
val_acc_l2[-1])
n_everybody_epochs = 200
train_energy_everybody = []
val_energy_everybody = []
val_acc_everybody = []
for e in range(n_everybody_epochs):
train_epoch = []
train_energy_everybody.append(train_epoch)
for i in range(n_batches):
train_epoch.append(train_l2_everybody(i))
val_energy_everybody.append(val_l2())
val_acc_everybody.append(val_l2_accuracy())
print "Epoch %d: mean train %1.3f, val %1.3f, acc %1.3f" % (
e, np.mean(train_epoch), val_energy_everybody[-1],
val_acc_everybody[-1])
# softmax_on_val_set = f_joint_outputs_softmax(train_data[val])
# softmax_on_test_set = f_joint_outputs_softmax(train_data[test])
# from sklearn.linear_model import LogisticRegression
# from sklearn.multiclass import OneVsRestClassifier
# from sklearn.pipeline import Pipeline
# from sklearn.preprocessing import StandardScaler
# from sklearn.metrics import accuracy_score
# pipeline = Pipeline([('scaler', StandardScaler()),
# ('clf',
# (LogisticRegression(
# C=1e-1, penalty="l2")))])
# pipeline.fit(softmax_on_val_set, train_targets[val])
# predictions = pipeline.predict(softmax_on_test_set)
# acc = accuracy_score(train_targets[test], predictions)
# predictions = pipeline.fit(
# train_data.reshape(len(train_data), -1)[train],
# label_indices[train]).predict(
# train_data.reshape(len(train_data), -1)[val])
# acc = accuracy_score(label_indices[val], predictions)
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,746
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/shift_to_energy_peak.py
|
import numpy as np
from scipy.ndimage import gaussian_filter
from scipy.io import loadmat
from path import path
from sklearn.decomposition import PCA
import scipy.signal as sig
def notch(Wn, bandwidth):
"""
Notch filter to kill line-noise.
"""
f = Wn / 2.0
R = 1.0 - 3.0 * (bandwidth / 2.0)
num = 1.0 - 2.0 * R * np.cos(2 * np.pi * f) + R ** 2.
denom = 2.0 - 2.0 * np.cos(2 * np.pi * f)
K = num / denom
b = np.zeros(3)
a = np.zeros(3)
a[0] = 1.0
a[1] = -2.0 * R * np.cos(2 * np.pi * f)
a[2] = R ** 2.
b[0] = K
b[1] = -2.0 * K * np.cos(2 * np.pi * f)
b[2] = K
return b, a
def apply_notch(X):
bw = .04
freq = .4
b, a = notch(freq, bw)
return sig.lfilter(b, a, X)
def normalize(X):
norms = np.sqrt((X ** 2).sum(-1))
X /= norms[:, :, np.newaxis]
def energy_peak(X, sigma=10):
energy = (X ** 2).mean(0).mean(0)
smoothed = gaussian_filter(energy, sigma=sigma)
return smoothed.argmax()
def shift_to_energy_peak(X, before=20, after=40, sigma=10):
peak = energy_peak(X, sigma=sigma)
start = peak - before
end = peak + after
return X[:, start:end]
def dim_reduce_sensors(X, n_components=30):
XX = X.transpose(1, 0, 2).reshape(X.shape[1], -1).T
pca = PCA(n_components=n_components)
return pca.inverse_transform(pca.fit_transform(XX
)).reshape(len(X), X.shape[-1], X.shape[1]).transpose(0, 2, 1)
def dim_reduce_sensors_svd(X, n_components=10):
XX = X.transpose(1, 0, 2).reshape(X.shape[1], -1)
U, S, VT = np.linalg.svd(XX, full_matrices=False)
S[n_components:] = 0.
XX = U.dot(S[:, np.newaxis] * VT)
return XX.reshape(X.shape[1], X.shape[0], X.shape[2]).transpose(1, 0, 2)
def project_to_nice_timecourses(X):
timecourses = np.load("timecourses.npz")["A"]
timecourses /= np.sqrt((timecourses ** 2).sum(0))
return X.dot(timecourses)
def remove_worst_trials(X, y, n_remove=10):
keep_indices = sorted((X ** 2).sum(1).sum(1).argsort()[::-1][n_remove:])
return X[keep_indices], y[keep_indices]
data_dir = path('data')
train_subject_ids = range(1, 17)
test_subject_ids = range(17, 24)
train_subject_names = ["train_subject%02d.mat" % sid
for sid in train_subject_ids]
test_subject_names = ["test_subject%02d.mat" % sid
for sid in test_subject_ids]
all_train_data = []
all_train_targets = []
labels = []
for i, subject in enumerate(train_subject_names):
f = loadmat(data_dir / subject)
X = f['X'][:, 160:]
y = f['y'].ravel() * 2 - 1
X, y = remove_worst_trials(X, y)
X = apply_notch(X)
normalize(X)
# X = dim_reduce_sensors(X, n_components=2)[:, :, 125:250]
X = X[:, :, 125:250]
X_cropped = X[:, :, 20:80] # shift_to_energy_peak(X, before=20, after=40)
# X_cropped = project_to_nice_timecourses(X)
all_train_data.append(X_cropped)
all_train_targets.append(y)
labels.append([i] * len(X_cropped))
all_train_data = np.concatenate(all_train_data)
all_train_targets = np.concatenate(all_train_targets)
labels = np.concatenate(labels)
from sklearn.cross_validation import cross_val_score, LeaveOneLabelOut
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import ExtraTreesClassifier
scaler = StandardScaler()
clf = LogisticRegression(C=1e-1, penalty="l2")
# clf = ExtraTreesClassifier(n_estimators=100)
pipeline = Pipeline([('scaler', scaler), ('estimator', clf)])
cv = LeaveOneLabelOut(labels)
# all_train_data = dim_reduce_sensors_svd(all_train_data, n_components=10)
all_scores = []
for i in xrange(all_train_data.shape[-1]):
scores = cross_val_score(pipeline,
all_train_data[:, :, i],
all_train_targets,
cv=cv,
verbose=100)
all_scores.append(scores)
# scores = cross_val_score(pipeline,
# all_train_data.reshape(len(all_train_data), -1),
# all_train_targets,
# cv=cv,
# verbose=100)
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,747
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/epochs_analysis_mne.py
|
import numpy as np
from scipy.io import loadmat
import mne
from path import path
subject_ids = [1] # range(1, 17)
subject_names = ["train_subject%02d.mat" % sid for sid in subject_ids]
data_dir = path('data')
reject = dict(mag=5e-12, grad=400e-13)
layout = mne.layouts.read_layout('Vectorview-all')
info = mne.create_info(
layout.names, 250, ['grad', 'grad', 'mag'] * 102)
broken_epochs = {
1 : [535], # Subject 1 has weird spikes in almost every epoch,
# at different times. Need to check if specific channels
4 : [105, 360, 388, 439]}
for subject in subject_names:
f = loadmat(data_dir / subject)
X = f['X']
y = f['y'].ravel() * 2 - 1
events = np.zeros([len(X), 3], dtype=np.int64)
events[:, 0] = np.arange(len(events))
events[:, 2] = y
epochs = mne.epochs.EpochsArray(
X, info, events, event_id=dict(face=1, scramble=-1), tmin=-.5)
epochs.reject = reject
epochs.plot()
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,748
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/full_ds.py
|
"""
DecMeg2014 example code.
Simple prediction of the class labels of the test set by:
- pooling all the training trials of all subjects in one dataset.
- Extracting the MEG data in the first 500ms from when the
stimulus starts.
- Projecting with RandomProjection
- Using a classifier.
Copyright Emanuele Olivetti 2014, BSD license, 3 clauses.
"""
import numpy as np
from sklearn.linear_model import LassoLarsCV, LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.externals.joblib import Memory
from scipy.io import loadmat
from scipy import signal as sig
from matplotlib import pyplot as plt
from sktensor import dtensor, cp_als
from sklearn.cross_validation import StratifiedShuffleSplit
_LOCAL_MEM = Memory(cachedir='cache')
cp_als = _LOCAL_MEM.cache(cp_als)
def view_filter(b, a):
w, h = sig.freqz(b, a)
plt.plot(w / abs(w), np.abs(h))
def notch(Wn, bandwidth):
"""
Notch filter to kill line-noise.
"""
f = Wn / 2.0
R = 1.0 - 3.0 * (bandwidth / 2.0)
num = 1.0 - 2.0 * R * np.cos(2 * np.pi * f) + R ** 2.
denom = 2.0 - 2.0 * np.cos(2 * np.pi * f)
K = num / denom
b = np.zeros(3)
a = np.zeros(3)
a[0] = 1.0
a[1] = -2.0 * R * np.cos(2 * np.pi * f)
a[2] = R ** 2.
b[0] = K
b[1] = -2.0 * K * np.cos(2 * np.pi * f)
b[2] = K
return b, a
def window(XX, lower_limit=160, tmin=0.0, tmax=0.5, sfreq=250, tmin_original=-.5):
# We throw away all the MEG data outside the first 0.5sec from when
# the visual stimulus start:
print("Restricting MEG data to the interval [%s, %s] sec." % (tmin, tmax))
XX = XX[:, lower_limit:, :]
# instead of post-stimulus centering
print("Apply desired time window and drop sensors 0 to %i." % lower_limit)
beginning = np.round((tmin - tmin_original) * sfreq).astype(np.int)
end = np.round((tmax - tmin_original) * sfreq).astype(np.int)
XX = XX[:, :, beginning:end].copy()
return XX
def notch_filter(XX):
# Assuming 250Hz == fs, 125Hz == fs/2, 50Hz = 50/125 = .4
# 5 Hz bw = 5/125 = .04
print("Applying notch filter for powerline.")
bw = .04
freq = .4
b, a = notch(freq, bw)
XX = sig.lfilter(b, a, XX)
# Assuming 250Hz == fs, 125Hz == fs/2, 50Hz = 10/125 = .08
# 5 Hz bw = 5/125 = .04
print("Applying filter for alpha wave.")
bw = .04
freq = .08
b, a = notch(freq, bw)
XX = sig.lfilter(b, a, XX)
return XX
def window_filter_baseline(XX, lower_limit=160):
baseline = XX[:, lower_limit:, :125].mean(-1)
XX = window(XX)
XX = notch_filter(XX)
XX -= baseline[..., np.newaxis]
return XX
def get_outlier_mask(XX):
print("Getting outlier mask.")
mask = (XX ** 2).sum(axis=-1).sum(axis=-1)
mask = mask.argsort()[10:-10]
return mask
def load_data():
all_subjects = range(1, 24)
X = []
y = []
ids_test = []
label_count = []
n_basis = 10
all_U0 = []
all_U2 = []
for n, subject in enumerate(all_subjects):
if subject < 17:
filename = 'data/train_subject%02d.mat' % subject
else:
filename = 'data/test_subject%02d.mat' % subject
print("Loading", filename)
data = loadmat(filename, squeeze_me=True)
XX = window_filter_baseline(data['X'])
mask = get_outlier_mask(XX)
T = dtensor(XX)
r = cp_als(T, rank=n_basis)
U0 = r[0].U[0]
U1 = r[0].U[1]
U2 = r[0].U[2]
X.append(XX)
all_U0.append(U0)
all_U2.append(U2)
if subject < 17:
yy = data['y'].ravel()
y.append(yy)
else:
ids = data['Id']
ids_test.append(ids)
label_count += [subject] * len(XX)
all_U0 = np.vstack(all_U0)
all_U2 = np.vstack(all_U2)
X = np.vstack(X)
y = np.concatenate(y)
cv = StratifiedShuffleSplit(yy, n_iter=50, test_size=.1)
selection_pipe = Pipeline([('scaler', StandardScaler()),
('estimator', LassoLarsCV(cv=cv))])
selection_pipe.fit(all_U0[:y.shape[0]], y * 2 - 1)
weights = selection_pipe.steps[1][1].coef_
selected = np.where(weights != 0)[0]
proj = all_U2[:, selected].T
ids_test = np.concatenate(ids_test)
from IPython import embed; embed()
return np.dot(X, proj), y, ids_test, label_count
if __name__ == '__main__':
print("DecMeg2014: https://www.kaggle.com/c/decoding-the-human-brain")
X, y, ids_test, label_count = load_data()
X_train = X[:len(y)]
X_train = X_train.reshape(X_train.shape[0], -1)
X_test = X[len(y):]
X_test = X_test.reshape(X_test.shape[0], -1)
pipe = Pipeline([('scaler', StandardScaler()),
('estimator', LogisticRegression(C=.01))])
print("Fitting predictor.")
pipe.fit(X_train, y)
y_pred = pipe.predict(X_test)
filename_submission = "submission.csv"
print("Creating submission file", filename_submission)
with open(filename_submission, "w") as f:
f.write("Id,Prediction\n")
for i in range(len(y_pred)):
f.write(str(ids_test[i]) + "," + str(y_pred[i]) + "\n")
print("Done.")
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,749
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/utils.py
|
"""Utilities for data preprocessing"""
from path import path
from scipy.io import loadmat
import numpy as np
from math import sqrt
from IPython import embed
TRIAL_NORM_REJECTION_THRESHOLD = sqrt(1e-21)
TRIAL_REJECTION_THRESHOLD_AFTER_NORMALIZING = 2.5
# subject_index, channel, channel_type, watch out subject_index off by 1
# the actual channel is channel * 3 + channel_type
REJECTED_CHANNELS = ([(16, 85, 0),
(18, 51, 0),
(18, 51, 1),
(18, 51, 2)] + # all by hand, the rest by thresholdin
[(5, 0, 2),
(5, 1, 2),
(8, 64, 2),
(12, 28, 2),
(12, 29, 2),
(14, 28, 2),
(15, 78, 2),
(15, 79, 2),
(15, 80, 2),
(18, 49, 0),
(18, 60, 1),
(19, 28, 2),
(19, 29, 2),
(20, 6, 0),
(20, 49, 0),
(20, 76, 0),
(22, 42, 2),
(22, 84, 2)] +
[(2, 82, 2),
(2, 83, 2),
(3, 77, 1),
(18, 99, 1),
(20, 76, 1),
(20, 78, 0),
(21, 76, 2),
(22, 88, 2)]
)
def reject_channels(X, rejected_channels=REJECTED_CHANNELS):
"""We reject channels by setting their time courses to 0.
This way we can preserve shape.
Kicks out channel for any array you pass it"""
Y = X.view()
Y.shape = (len(X), 102, 3, -1)
for _, c, t in rejected_channels:
Y[:, c, t, :] = 0.
return X
def crop_channels(X, crop_slice=slice(159, None)):
return X[:, crop_slice, :]
def crop_time(X, time_slice=slice(125, 250)):
return X[:, :, time_slice]
def reject_trials_norm(X, threshold=TRIAL_NORM_REJECTION_THRESHOLD):
"""Reject trials using norm. Make sure to apply this before cropping
and other preprocessing"""
squared_norms = (X ** 2).mean(-1).mean(-1)
norms = np.sqrt(squared_norms)
keep_trials = norms < threshold
return X[keep_trials], keep_trials
def impute_trials_norm(X, threshold=TRIAL_NORM_REJECTION_THRESHOLD,
also_impute=None,
impute_random=42):
"""Replaces trials that pass threshold with the mean of the others.
Used for the test data.
impute_random will impute randomly chose trials, otherwise the mean
"""
squared_norms = (X ** 2).mean(-1).mean(-1)
norms = np.sqrt(squared_norms)
keep_trials = norms < threshold
if also_impute is not None:
keep_trials = keep_trials & ~also_impute
kept_trial_mean = X[keep_trials].mean(0)
if not impute_random:
X[~keep_trials] = kept_trial_mean[np.newaxis]
else:
rng = np.random.RandomState(impute_random)
num_trials_to_impute = (~keep_trials).sum()
random_indices = rng.randint(0, keep_trials.sum(),
num_trials_to_impute)
X[~keep_trials] = X[keep_trials][random_indices]
return X, keep_trials
def subtract_sensor_specific_subject_mean(X, ):
Y = X.view()
Y.shape = (len(X), -1, 3, X.shape[-1])
grad_mean = Y[:, :, :2, :].mean()
mag_mean = Y[:, :, 2, :].mean()
Y[:, :, :2, :] -= grad_mean
Y[:, :, 2, :] -= mag_mean
return X
def divide_by_sensor_specific_subject_std(X):
Y = X.view()
Y.shape = (len(X), -1, 3, X.shape[-1])
grad_std = Y[:, :, :2, :].std()
mag_std = Y[:, :, 2, :].std()
Y[:, :, :2, :] /= grad_std
Y[:, :, 2, :] /= mag_std
return X
def _load_subjects(train_test, ids=None, preproc=None, concatenated=True):
"""load train subjects corresponding to given ids, or all.
Apply preproc if provided."""
if preproc is None:
if train_test == 'train':
preproc = lambda x, y: (x, y)
else:
preproc = lambda x: (x, None)
subject_names = ["%s_subject%02d.mat" % (train_test, sid) for sid in ids]
data_dir = path('data')
all_data = []
if train_test == 'train':
all_targets = []
all_labels = []
for sid, subject in zip(ids, subject_names):
print(subject)
f = loadmat(data_dir / subject)
if train_test == 'train':
y = f['y'].ravel()
X, y = preproc(f['X'], y)
else:
X, unimputed = preproc(f['X'])
labels = [sid] * len(X)
all_data.append(X)
if train_test == 'train':
all_targets.append(y)
all_labels.append(labels)
if concatenated:
all_data = np.concatenate(all_data)
if train_test == 'train':
all_targets = np.concatenate(all_targets)
all_labels = np.concatenate(all_labels)
if train_test == 'train':
return all_data, all_targets, all_labels
else:
return all_data, all_labels
def preprocessing_train(X, y, normalize_trials=False):
X = reject_channels(X)
X, keep = reject_trials_norm(X)
y = y[keep]
keep_indices = np.where(keep)[0]
X = crop_channels(X)
X = crop_time(X)
X = subtract_sensor_specific_subject_mean(X)
X = divide_by_sensor_specific_subject_std(X)
X, keep2 = reject_trials_norm(
X, TRIAL_REJECTION_THRESHOLD_AFTER_NORMALIZING)
keep_indices = keep_indices[keep2]
y = y[keep2]
X = subtract_sensor_specific_subject_mean(X)
X = divide_by_sensor_specific_subject_std(X)
return X, y
def preprocessing_test(X, normalize_trials=False):
X = reject_channels(X)
X, keep = impute_trials_norm(X)
X = crop_channels(X)
X = crop_time(X)
X = subtract_sensor_specific_subject_mean(X)
X = divide_by_sensor_specific_subject_std(X)
X, keep2 = impute_trials_norm(
X, TRIAL_REJECTION_THRESHOLD_AFTER_NORMALIZING,
also_impute=~keep)
keep_indices = np.where(keep2)[0]
X = subtract_sensor_specific_subject_mean(X)
X = divide_by_sensor_specific_subject_std(X)
return X, keep_indices
def load_train_subjects(ids=None, preproc=preprocessing_train,
concatenated=True):
if ids is None:
ids = range(1, 17)
return _load_subjects("train", ids, preproc, concatenated)
def load_test_subjects(ids=None, preproc=preprocessing_test,
concatenated=True):
if ids is None:
ids = range(17, 24)
return _load_subjects("test", ids, preproc, concatenated)
def _calibrate_reject_trials():
all_norms = []
all_channel_norms = []
for train_id in range(1, 17):
print(train_id)
X, _, _ = load_train_subjects(ids=[train_id])
X = reject_channels(X)
X, keep = reject_trials_norm(X)
X = crop_channels(X)
X = crop_time(X)
X = subtract_sensor_specific_subject_mean(X)
X = divide_by_sensor_specific_subject_std(X)
X, keep2 = reject_trials_norm(X,
TRIAL_REJECTION_THRESHOLD_AFTER_NORMALIZING)
X = subtract_sensor_specific_subject_mean(X)
X = divide_by_sensor_specific_subject_std(X)
norms_squared = (X.squeeze() ** 2).mean(-1).mean(-1)
norms = np.sqrt(norms_squared)
channel_norms = (X ** 2).mean(0).mean(-1)
all_channel_norms.append(channel_norms)
all_norms.append(norms)
for test_id in range(17, 24):
print(test_id)
X, _ = load_test_subjects(ids=[test_id])
X = reject_channels(X)
X, kept = impute_trials_norm(X)
X = crop_channels(X)
X = crop_time(X)
X = subtract_sensor_specific_subject_mean(X)
X = divide_by_sensor_specific_subject_std(X)
X, kept_again = impute_trials_norm(X,
TRIAL_REJECTION_THRESHOLD_AFTER_NORMALIZING,
also_impute=~kept)
X = subtract_sensor_specific_subject_mean(X)
X = divide_by_sensor_specific_subject_std(X)
norms_squared = (X.squeeze() ** 2).mean(-1).mean(-1)
norms = np.sqrt(norms_squared)
all_norms.append(norms)
channel_norms = (X ** 2).mean(0).mean(-1)
all_channel_norms.append(channel_norms)
all_norms.append(norms)
import pylab as pl
pl.figure()
pl.plot(np.concatenate(all_norms))
pl.yscale('log')
pl.figure()
pl.plot(np.array(all_channel_norms).reshape(-1, 3))
return all_norms, all_channel_norms
if __name__ == "__main__":
# X_train, y_train, train_labels = load_train_subjects()
X_test, test_labels = load_test_subjects()
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,750
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/amievil_clf.py
|
from scipy.io import loadmat
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
def load_training_data():
print("Creating the trainset.")
labels = []
X_train = []
y_train = []
for n, subject in enumerate(range(1,17)):
filename = 'data/train_subject%02d.mat' % subject
print("Loading", filename)
data = loadmat(filename, squeeze_me=True)
XX = data['X'][:, 159:, 125:250]
yy = data['y']
X_train.append(XX)
y_train.append(yy)
labels.extend([subject] * len(XX))
X_train = np.vstack(X_train)
y_train = np.concatenate(y_train)
labels = np.array(labels)
return X_train, y_train, labels
all_train_data, all_train_targets, all_train_labels = load_training_data()
val_idx = np.where(all_train_labels == 16)[0]
all_val_data = all_train_data[val_idx]
all_val_targets = all_train_targets[val_idx]
all_val_labels = all_train_labels[val_idx]
train_idx = np.where(all_train_labels != 16)[0]
all_train_data = all_train_data[train_idx]
all_train_targets = all_train_targets[train_idx]
all_train_labels = all_train_labels[train_idx]
X_train = all_train_data
y_train = all_train_targets
X_val = all_val_data
y_val = all_val_targets
X_train = X_train.reshape(len(X_train), -1)
X_val = X_val.reshape(len(X_val), -1)
bg = Pipeline([('scaler', StandardScaler()),
('lr',LogisticRegression(C=1e-5))])
print("Training...")
bg.fit(X_train, y_train)
y_pred = bg.predict(X_train)
print("Accuracy on training data")
print(accuracy_score(y_train, y_pred))
y_pred = bg.predict(X_val)
print("Accuracy on validation data")
print(accuracy_score(y_val, y_pred))
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,751
|
smileyk/kaggle-decmeg2014
|
refs/heads/master
|
/one_pred_all.py
|
import numpy as np
from scipy.io import loadmat
from path import path
train_subject_ids = range(1, 17)
train_subject_names = ["train_subject%02d.mat" % sid
for sid in train_subject_ids]
data_dir = path("data")
all_data = []
all_targets = []
all_labels = []
for subject, sid in zip(train_subject_names, train_subject_ids):
print subject
f = loadmat(data_dir / subject)
X = f['X'][:, 160:, 125:250]
y = f['y'].ravel() * 2 - 1
all_data.append(X)
all_targets.append(y)
all_labels.append([sid] * len(X))
from sklearn.cross_validation import cross_val_score, StratifiedShuffleSplit
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
pipeline = Pipeline([('scaler', StandardScaler()),
('lr', LogisticRegression(C=1e-2))])
all_scores = []
# out of subject predictions
for sid, X, y in zip(train_subject_ids, all_data, all_targets):
print "Fitting on %d" % sid
cv = StratifiedShuffleSplit(y, test_size=.5, n_iter=10)
for train, test in cv:
pipeline.fit(X.reshape(len(X), -1)[train], y[train])
fold_scores = []
all_scores.append(fold_scores)
for sid2, X2, y2 in zip(train_subject_ids, all_data, all_targets):
if sid2 == sid:
predictions = pipeline.predict(X.reshape(len(X), -1)[test])
fold_scores.append(accuracy_score(y[test], predictions))
else:
predictions = pipeline.predict(X2.reshape(len(X2), -1))
fold_scores.append(accuracy_score(y2, predictions))
print "%d %1.3f" % (sid2, fold_scores[-1])
# predicting subject label of left out subject
all_data = np.concatenate(all_data)
all_targets = np.concatenate(all_targets)
all_labels = np.concatenate(all_labels)
from sklearn.cross_validation import LeaveOneLabelOut
from sklearn.multiclass import OneVsRestClassifier
pipeline2 = Pipeline([('scaler', StandardScaler()),
#('lr', OneVsRestClassifier(LogisticRegression(C=1e-2)))
('lr', LogisticRegression(C=1e-2))
])
lolo = LeaveOneLabelOut(all_labels)
left_out_labels = []
all_label_probabilities = []
for train, test in lolo:
cv = StratifiedShuffleSplit(all_labels[train], test_size=.875, n_iter=5)
left_out_labels.append(np.unique(all_labels[test]))
print left_out_labels[-1]
label_probabilities = []
all_label_probabilities.append(label_probabilities)
for train2, test2 in cv:
pipeline2.fit(all_data.reshape(len(all_data), -1)[train[train2]],
all_labels[train[train2]])
prediction_probas = pipeline2.predict_proba(
all_data.reshape(len(all_data), -1)[test])
label_probabilities.append(prediction_probas)
print prediction_probas
|
{"/svm_test.py": ["/utils.py"], "/minimal_clf.py": ["/utils.py"]}
|
37,752
|
emildiaz/Twitter-Bot
|
refs/heads/master
|
/goodreads.py
|
import random
import requests
from bs4 import BeautifulSoup
def getSoup(page):
url = f'https://www.goodreads.com/quotes/tag/love?page={page}'
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
return soup
def getQuotes(soup):
quotes = soup.find_all('div', {'class':'quoteText'})
return quotes
def formatAuthor(raw_author):
try:
# name = raw_author[:raw_author.find('(')].strip()
# book = raw_author[raw_author.find('('):].strip()
# author = f'{name}\n\n{book}'
name = raw_author[:raw_author.find(',')+1]
book = raw_author[raw_author.find(',')+1:].strip()
author = f'{name} {book}'
except:
author = raw_author
finally:
return author
def main():
validQuote = False
page = random.randrange(1, 100)
#want to keep picking a quote until it is fits the twitter quota
while not validQuote:
#load up the random page and pick a random quote from the page
soup = getSoup(page)
quotes = getQuotes(soup)
raw_quote = random.choice(quotes).text
#seperate the quote and author
quote = raw_quote[:raw_quote.rfind('―')].strip()
raw_author = raw_quote[raw_quote.rfind('―')+1:].strip()
author = formatAuthor(raw_author)
q_and_a = f'{quote}\n{author}'
#check to see if fit in twitter character limit
if len(q_and_a) <= 280:
validQuote = True
return (q_and_a)
if __name__ == '__main__':
main()
|
{"/twitter_bot.py": ["/goodreads.py"], "/cronjobs.py": ["/twitter_bot.py"]}
|
37,753
|
emildiaz/Twitter-Bot
|
refs/heads/master
|
/twitter_bot.py
|
import tweepy
import requests
import random
import time
import goodreads
from datetime import datetime
consumer_key = 'JKJajqHdI4bKiih5xH16VBKal'
consumer_secret = 'FD7UgwNlx4lCJTvLzmEjES4TsDAA5vTtsvQN3hpZoB7h9Ohsjt'
access_token = '1079243430038028288-shSBTbf57mgg0YDXrVuTjAla26Fz3Q'
access_token_secret = 'cWmD8ySydu05JhYIkg2yfHPBRXd7xE6jfQmq8DE3r39BZ'
#quotes_url = 'https://type.fit/api/quotes'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
def find_quote():
#request = requests.get(quotes_url)
#r_json = request.json()
#quote = random.choice(r_json)
quote = goodreads.main()
return quote
def tweet(api, quote):
#text = quote["text"]
#author = quote["author"]
#if author == None:
# author = "Anonymous"
#tweet = f'\"{text}\" \n{author}'
tweet = quote
api.update_status(tweet)
def main():
print("Finding quote...")
quote = find_quote()
print("Setting up tweet...")
tweet(api, quote)
print(f"Tweeted! : {datetime.now()}")
if __name__ == '__main__':
#tweets once an hour
main()
|
{"/twitter_bot.py": ["/goodreads.py"], "/cronjobs.py": ["/twitter_bot.py"]}
|
37,754
|
emildiaz/Twitter-Bot
|
refs/heads/master
|
/cronjobs.py
|
from apscheduler.schedulers.blocking import BlockingScheduler
import twitter_bot
#creating a time scheduler to run code every two hours
scheduler = BlockingScheduler()
scheduler.add_job(twitter_bot.main, 'interval', hours=2)
scheduler.start()
|
{"/twitter_bot.py": ["/goodreads.py"], "/cronjobs.py": ["/twitter_bot.py"]}
|
37,827
|
mhalittokluoglu/python_doc_scanner
|
refs/heads/main
|
/th_image.py
|
import cv2
import os
images = os.listdir('./Scanned_images/')
images.sort()
c = 12
a = 125
image_counter = 0
for image in images:
image_counter += 1
os. system('rm -f ./TH_Images/*')
for image in images:
img = cv2.imread('./Scanned_images/'+image)
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th2 = cv2.adaptiveThreshold(gray_img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,a,c)
cv2.imwrite('./TH_Images/'+image,th2)
convert_line = 'convert '
counter = 0
for image in images:
if counter == 35:
break
convert_line += "'./TH_Images/" + image + "' "
counter += 1
convert_line += 'TH_images.pdf'
os.system(convert_line)
convert_line = 'convert '
counter = 0
if image_counter > 35:
for image in images:
counter += 1
if counter > 35:
convert_line += "'./TH_Images/" + image + "' "
convert_line += 'TH_images2.pdf'
os.system(convert_line)
merge_line = 'pdfunite TH_images.pdf TH_images2.pdf TH_images_merged.pdf'
os.system(merge_line)
os.system('rm -f TH_images.pdf TH_images2.pdf')
|
{"/main.py": ["/utilities.py"]}
|
37,828
|
mhalittokluoglu/python_doc_scanner
|
refs/heads/main
|
/utilities.py
|
import cv2
import numpy as np
def order_points(h):
h = h.reshape((4,2))
hnew = np.zeros((4,2), dtype = "float32")
s = h.sum(1)
hnew[0] = h[np.argmin(s)]
hnew[2] = h[np.argmax(s)]
diff = np.diff(h, axis = 1)
hnew[1] = h[np.argmin(diff)]
hnew[3] = h[np.argmax(diff)]
return hnew
def scan_image(image_str):
img = cv2.imread(image_str)
orig = img.copy()
width_ratio = img.shape[1]/480
height_ratio = img.shape[0]/640
img = cv2.resize(img,(480,640))
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray,(5,5),0)
edged = cv2.Canny(blurred,30,50)
contours,hierarchy = cv2.findContours(edged,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours,key=cv2.contourArea,reverse = True)
for c in contours:
area = cv2.contourArea(c)
if area> 1000:
p = cv2.arcLength(c,True)
approx = cv2.approxPolyDP(c,0.02*p,True)
if len(approx) == 4:
target = approx
break
approx2 = order_points(target)
approx3 = np.zeros((4,2), dtype = "float32")
for i in range(0,4):
approx3[i][0] = approx2[i][0]*width_ratio
for i in range(0,4):
approx3[i][1] = approx2[i][1]*height_ratio
w1 = approx3[1][0] - approx3[0][0]
w2 = approx3[2][0] - approx3[3][0]
wdth = max(w1,w2)
h1 = approx3[3][1] - approx3[0][1]
h2 = approx3[2][1] - approx3[1][1]
hgth = max(h1,h2)
pts1 = np.float32([[0,0],[wdth,0],[wdth,hgth],[0,hgth]])
op = cv2.getPerspectiveTransform(approx3,pts1)
dst = cv2.warpPerspective(orig,op,(int(wdth),int(hgth)))
return dst
|
{"/main.py": ["/utilities.py"]}
|
37,829
|
mhalittokluoglu/python_doc_scanner
|
refs/heads/main
|
/main.py
|
import os
import cv2
import utilities
images = os.listdir('./Images/')
images.sort()
image_counter = 0
for image in images:
image_counter += 1
os.system('rm -f ./Scanned_images/*')
for image in images:
img = utilities.scan_image('./Images/'+image)
cv2.imwrite('./Scanned_images/'+image,img)
convert_line = 'convert '
counter = 0
for image in images:
if counter == 35:
break
convert_line += './Scanned_images/'+image+' '
counter = counter + 1
convert_line += 'Scanned_images.pdf'
os.system(convert_line)
if image_counter >= 35:
convert_line = 'convert '
counter = 0
for image in images:
if counter >= 35:
convert_line += './Scanned_images/'+image+' '
counter = counter + 1
convert_line += 'Scanned_images2.pdf'
os.system(convert_line)
merge_line = 'pdfunite Scanned_images.pdf Scanned_images2.pdf Scanned_images_merged.pdf'
os.system(merge_line)
os.system('rm -f Scanned_images.pdf Scanned_images2.pdf')
|
{"/main.py": ["/utilities.py"]}
|
37,830
|
mhalittokluoglu/python_doc_scanner
|
refs/heads/main
|
/del_images.py
|
import os
del_scanned_images = 'rm -f ./Scanned_images/*'
del_img = 'rm -f ./Images/*'
del_th_images = 'rm -f ./TH_Images/*'
os.system(del_scanned_images)
os.system(del_img)
os.system(del_th_images)
|
{"/main.py": ["/utilities.py"]}
|
37,839
|
Te-k/webcache
|
refs/heads/master
|
/webcache/utils.py
|
from urllib.parse import urlparse, parse_qs
def same_url(url1, url2):
"""
Check for minor differences between url1 and url2, return True if they are the same
Currently only consider extra www. in domain, https/http and extra fragment
"""
if url1 == url2:
return True
# Dirty hacks
if not url1.startswith('http'):
url1 = 'http://' + url1
if not url2.startswith('http'):
url2 = 'http://' + url2
if not url1.endswith('/'):
url1 += '/'
if not url2.endswith('/'):
url2 += '/'
purl2 = urlparse(url2)
purl1 = urlparse(url1)
if purl1.path == purl2.path and purl1.params == purl2.params and \
purl1.query == purl2.query:
if purl1.netloc == purl2.netloc:
return True
else:
if ("www." + purl1.netloc) == purl2.netloc:
return True
if ("www." + purl2.netloc) == purl1.netloc:
return True
return False
|
{"/webcache/google.py": ["/webcache/utils.py"], "/webcache/__init__.py": ["/webcache/google.py", "/webcache/yandex.py", "/webcache/bing.py", "/webcache/archiveis.py"], "/webcache/main.py": ["/webcache/google.py", "/webcache/yandex.py", "/webcache/bing.py", "/webcache/archiveis.py"], "/webcache/bing.py": ["/webcache/utils.py"]}
|
37,840
|
Te-k/webcache
|
refs/heads/master
|
/webcache/archiveis.py
|
import requests
import archiveis
from dateutil.parser import parse
from .memento import MementoClient
class ArchiveIs(object):
"""
Class to request achive.is website
"""
@staticmethod
def snapshots(url):
"""
Return all the screenshot of an url
"""
mc = MementoClient(base_url='http://archive.is/')
return mc.snapshots(url)
@staticmethod
def download_cache(cache_url):
"""
return cache data from an archive.is cached url
"""
r = requests.get(cache_url)
data = r.text
t1 = data.find('\n\n\n\n\n\n')
t2 = data.find('</div></div><!--[if !IE]><!--><div style="position:absolute;right:1028px;top:-14px;bottom:-2px">')
#t3 = data.find('<input style="border:1px solid black;height:20px;margin:0 0 0 0;padding:0;width:500px" type="text" name="q"')
#t4 = data[t3+115:].find('"')
t5 = data.find('<meta property="article:modified_time" content="')
cached_data = data[t1+6:t2]
#original_url = data[t3+115:t3+115+t4]
date = parse(data[t5+48:t5+68])
return {
'success': True,
'date': date,
'data': cached_data,
'cacheurl': cache_url
}
@staticmethod
def cache(url):
"""
Get a cache url and download the last one
"""
snapshots = ArchiveIs.snapshots(url)
if len(snapshots) > 0:
last = sorted(snapshots, key=lambda x: x['date'], reverse=True)[0]
return ArchiveIs.download_cache(last['archive'])
else:
return {
'success': False
}
@staticmethod
def capture(url):
"""
Capture an url in archive.is
"""
# Easiest way to do it for now, archive.is API sucks
# FIXME replace this lib
return archiveis.capture(url)
|
{"/webcache/google.py": ["/webcache/utils.py"], "/webcache/__init__.py": ["/webcache/google.py", "/webcache/yandex.py", "/webcache/bing.py", "/webcache/archiveis.py"], "/webcache/main.py": ["/webcache/google.py", "/webcache/yandex.py", "/webcache/bing.py", "/webcache/archiveis.py"], "/webcache/bing.py": ["/webcache/utils.py"]}
|
37,841
|
Te-k/webcache
|
refs/heads/master
|
/webcache/google.py
|
import requests
import html
from dateutil.parser import parse
from bs4 import BeautifulSoup
from urllib.parse import urlparse, parse_qs
from webcache.utils import same_url
class Google(object):
@staticmethod
def download_cache(url):
"""
Download cache from a cache url
"""
r = requests.get(url)
if r.status_code == 200:
mark1 = r.text.find("It is a snapshot of the page as it appeared on ")
timestamptext = r.text[mark1+47:mark1+47+24]
timestamp = parse(timestamptext)
return {
"success": True,
"date": timestamp,
"data": html.unescape(r.text[r.text.find("<pre>")+5:r.text.find("</pre>")]),
'cacheurl': r.url
}
else:
if r.status_code != 404:
print("Weird, it should return 404...")
return {"success": False}
@staticmethod
def search(query, num=10):
payload = {
"q": query,
"num": num
}
r = requests.get(
"https://www.google.com/search",
params=payload
)
soup = BeautifulSoup(r.text, 'lxml')
res = []
divs = soup.find_all('div', class_='g')
for d in divs:
if d.h3:
data = {
'name': d.h3.a.text
}
link = parse_qs(urlparse(d.h3.a['href']).query)
if 'q' in link:
data['url'] = link['q'][0]
else:
# Abnormal link (for instance Google books)
data['url'] = d.h3.a['href']
text = d.find('span', class_='st')
if text is not None:
data['text'] = text.text
if d.ul:
for i in d.ul.children:
l = parse_qs(urlparse(i.a['href']).query)
if 'webcache.googleusercontent.com' in l['q'][0]:
data['cache'] = l['q'][0]
res.append(data)
return res
@staticmethod
def cache(url):
payload = {
"q": "cache:" + url,
"num": 1,
"strip":0,
"vwsrc":1
}
r = requests.get(
"https://webcache.googleusercontent.com/search",
params=payload
)
if r.status_code == 200:
# Copy code here to avoid doing another request
mark1 = r.text.find("It is a snapshot of the page as it appeared on ")
if mark1 > 0:
timestamptext = r.text[mark1+47:mark1+47+24]
timestamp = parse(timestamptext)
if mark1 > 0:
return {
"success": True,
"date": timestamp,
"data": html.unescape(r.text[r.text.find("<pre>")+5:r.text.find("</pre>")]),
'cacheurl': r.url,
'url': url
}
else:
return {
"success": True,
"data": html.unescape(r.text[r.text.find("<pre>")+5:r.text.find("</pre>")]),
'cacheurl': r.url,
'url': url
}
else:
# If not in cache directly, search on google for the cached url
# Weirdly google does not find well url starting with a scheme
if url.startswith('http://'):
url = url[7:]
elif url.startswith('https://'):
url = url[8:]
res = Google.search(url)
for r in res:
if same_url(url, r['url']) and 'cache' in r:
return Google.download_cache(r['cache'])
return { 'success': False }
|
{"/webcache/google.py": ["/webcache/utils.py"], "/webcache/__init__.py": ["/webcache/google.py", "/webcache/yandex.py", "/webcache/bing.py", "/webcache/archiveis.py"], "/webcache/main.py": ["/webcache/google.py", "/webcache/yandex.py", "/webcache/bing.py", "/webcache/archiveis.py"], "/webcache/bing.py": ["/webcache/utils.py"]}
|
37,842
|
Te-k/webcache
|
refs/heads/master
|
/webcache/__init__.py
|
from .google import Google
from .yandex import Yandex
from .bing import Bing
from .archiveis import ArchiveIs
from .archiveorg import ArchiveOrg
|
{"/webcache/google.py": ["/webcache/utils.py"], "/webcache/__init__.py": ["/webcache/google.py", "/webcache/yandex.py", "/webcache/bing.py", "/webcache/archiveis.py"], "/webcache/main.py": ["/webcache/google.py", "/webcache/yandex.py", "/webcache/bing.py", "/webcache/archiveis.py"], "/webcache/bing.py": ["/webcache/utils.py"]}
|
37,843
|
Te-k/webcache
|
refs/heads/master
|
/webcache/main.py
|
import argparse
from .google import Google
from .yandex import Yandex
from .bing import Bing
from .archiveis import ArchiveIs
from .archiveorg import ArchiveOrg
def main():
parser = argparse.ArgumentParser(description='Search or do cache')
subparsers = parser.add_subparsers(help='subcommand')
parser_a = subparsers.add_parser('search', help='Search in cache')
parser_a.add_argument('URL', help='URL of the cache')
parser_a.set_defaults(subcommand='search')
parser_b = subparsers.add_parser('save', help='Save in cache platforms')
parser_b.add_argument('URL', help='URL ')
parser_b.set_defaults(subcommand='save')
args = parser.parse_args()
if 'subcommand' in args:
if args.subcommand == 'search':
# Google
google = Google.cache(args.URL)
if google['success']:
if 'date' in google:
print('Google: FOUND %s (%s)' % (
google['cacheurl'],
google['date']
))
else:
print('Google: FOUND %s' % (google['cacheurl']))
else:
print("Google: NOT FOUND")
# Yandex
yandex = Yandex.cache(args.URL)
if yandex['success']:
if yandex['found']:
print('Yandex: FOUND %s' % yandex['cacheurl'])
else:
print("Yandex: NOT FOUND")
else:
print("Yandex : Query failed (captcha likely)")
# Bing
bing = Bing.cache(args.URL)
if bing['success']:
print('Bing: FOUND %s (%s)' % (
bing['cacheurl'],
bing['date']
))
else:
print("Bing: NOT FOUND")
# Archive.is
try:
arch = ArchiveIs.snapshots(args.URL)
if len(arch) > 0:
print('Archive.is: FOUND')
for s in arch:
print('-%s: %s' % (s['date'], s['archive']))
else:
print('Archive.is: NOT FOUND')
except requests.exceptions.ConnectTimeout:
print('Archive.is: TIME OUT')
# Web Archive
web = ArchiveOrg.snapshots(args.URL)
if len(web) > 0:
print('Archive.org: FOUND')
for s in web:
print('-%s: %s' % (s['date'], s['archive']))
else:
print('Archive.org: NOT FOUND')
elif args.subcommand == "save":
# Archive.ord
res = ArchiveOrg.capture(args.URL)
print("Saved in Internet Archive : {}".format(res))
# Archive.is
res = ArchiveIs.capture(args.URL)
print("Saved in Archive.is : {}".format(res))
else:
parser.print_help()
else:
parser.print_help()
|
{"/webcache/google.py": ["/webcache/utils.py"], "/webcache/__init__.py": ["/webcache/google.py", "/webcache/yandex.py", "/webcache/bing.py", "/webcache/archiveis.py"], "/webcache/main.py": ["/webcache/google.py", "/webcache/yandex.py", "/webcache/bing.py", "/webcache/archiveis.py"], "/webcache/bing.py": ["/webcache/utils.py"]}
|
37,844
|
Te-k/webcache
|
refs/heads/master
|
/webcache/yandex.py
|
import urllib
import requests
from bs4 import BeautifulSoup
class Yandex:
@staticmethod
def search(req):
'''
Search for a request in Yandex and return results
Does not work all the time, Yandex has a captcha often
'''
r = requests.get('https://yandex.ru/search/?text=%s' %
urllib.parse.quote(req, safe='')
)
if r.status_code != 200:
return False, []
soup = BeautifulSoup(r.text, 'lxml')
if soup.find('main') is None:
return False, []
res = []
for l in soup.find_all('li', class_='serp-item'):
url = l.a['href']
result = {
'url': l.a['href'],
'name': l.a.text,
}
text = l.find('div', class_="text-container")
if text:
result['text'] = text.text
popup = l.find_all('div', class_='popup2')
if len(popup) > 0:
for link in popup[0].find_all('a'):
if 'translate.yandex.ru' in link['href']:
if link['href'].startswith('http'):
result['translate'] = link['href']
else:
result['translate'] = 'http:' + link['href']
if 'yandexwebcache.net' in link['href']:
result['cache'] = link['href']
res.append(result)
return True, res
@staticmethod
def download_cache(cache_url):
'''
Extract content from a cached Yandex url
'''
# FIXME: do not get date and url
r = requests.get(cache_url)
if r.status_code == 200:
return {
'success': True,
'data': r.text[:-90],
'cacheurl': cache_url,
}
else:
return {'success': False}
@staticmethod
def cache(url):
"""
Search for a cache url in yandex and if found get its content
"""
# FIXME: miss obvious pages, like www.domain.com instead of domain.com
v, res = Yandex.search(url)
if v:
for i in res:
if i['url'] == url:
if 'cache' in i:
c = Yandex.download_cache(i['cache'])
c['found'] = True
return c
return {'success': True, 'found': False}
else:
return {'success': False}
|
{"/webcache/google.py": ["/webcache/utils.py"], "/webcache/__init__.py": ["/webcache/google.py", "/webcache/yandex.py", "/webcache/bing.py", "/webcache/archiveis.py"], "/webcache/main.py": ["/webcache/google.py", "/webcache/yandex.py", "/webcache/bing.py", "/webcache/archiveis.py"], "/webcache/bing.py": ["/webcache/utils.py"]}
|
37,845
|
Te-k/webcache
|
refs/heads/master
|
/webcache/bing.py
|
import requests
from bs4 import BeautifulSoup
from urllib.parse import urlencode
from dateutil.parser import parse
from .utils import same_url
class Bing(object):
@staticmethod
def search(query):
"""
Search in bing
"""
# FIXME : change default UA
r = requests.get(
"https://www.bing.com/search",
params = {'q': query }
)
soup = BeautifulSoup(r.text, 'lxml')
res = []
divs = soup.find_all('li', class_='b_algo')
for d in divs:
data = {
'name': d.a.text,
'url': d.a['href'],
'text': d.p.text
}
attribution = d.find('div', class_='b_attribution')
# Check if cache infos in attribute
if 'u' in attribution.attrs:
b = attribution['u'].split('|')
data['cache'] = "http://cc.bingj.com/cache.aspx?d=%s&w=%s" % (
b[2],
b[3]
)
res.append(data)
return res
@staticmethod
def download_cache(url):
"""
Download cache data from a cached page
"""
r = requests.get(url)
if r.status_code == 200:
if "Could not find the requested document in the cache" in r.text:
# Bing bug
return {"success": False}
else:
soup = BeautifulSoup(r.text, 'lxml')
content = soup.find('div', class_='cacheContent')
data = r.text[r.text.find('<div class="cacheContent">')+26:len(r.text)-41]
return {
"success": True,
"date": parse(soup.find_all('strong')[1].text),
"data": str(content)[26:-40],
'url': soup.strong.a['href'],
'cacheurl': url
}
else:
if r.status_code != 404:
print('Weird, it should return 200 or 404')
return {"success": False}
@staticmethod
def cache(url):
"""
Search for an url in Bing cache
"""
res = Bing.search(url)
for i in res:
if same_url(url, i['url']):
if 'cache' in i:
return Bing.download_cache(i['cache'])
return {'success': False}
|
{"/webcache/google.py": ["/webcache/utils.py"], "/webcache/__init__.py": ["/webcache/google.py", "/webcache/yandex.py", "/webcache/bing.py", "/webcache/archiveis.py"], "/webcache/main.py": ["/webcache/google.py", "/webcache/yandex.py", "/webcache/bing.py", "/webcache/archiveis.py"], "/webcache/bing.py": ["/webcache/utils.py"]}
|
37,846
|
AjayRad/project3.5_catalog_app_v2
|
refs/heads/master
|
/catalogapp/models/__init__.py
|
from catalog_dao import get_all_categories, get_catg_by_id, get_products_by_catg
|
{"/catalogapp/models/dbsetup.py": ["/config.py"]}
|
37,847
|
AjayRad/project3.5_catalog_app_v2
|
refs/heads/master
|
/catalogapp/models/db_sampledata.py
|
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# get config file from the /vagrant/catlog dir
import sys
sys.path.insert(0, '/vagrant/catalog')
print sys.path
from config import SQLALCHEMY_DATABASE_URI
from dbsetup import ProdCat, Base, ProdItem, User
from catalog_dao import get_all_categories, get_catg_by_id
from catalog_dao import get_products_by_catg, get_all_users
engine = create_engine(SQLALCHEMY_DATABASE_URI)
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
session.query(ProdCat).delete(synchronize_session=False)
session.query(User).delete(synchronize_session=False)
session.query(ProdItem).delete(synchronize_session=False)
new_user = User(social_id="tst123", nickname="tst123", email="test@yahoo.com")
session.add(new_user)
session.commit()
print "added new tst user"
new_ProdCat1 = ProdCat(name="Soccer", desc="the beautiful game", owner_id=1)
session.add(new_ProdCat1)
session.commit()
print "added new product category"
new_ProdCat2 = ProdCat(name="Tennis", desc="Serve, volley and more", owner_id=1)
session.add(new_ProdCat2)
session.commit()
print "added new product category"
new_ProdCat3 = ProdCat(name="Football", desc="The ball is a foot long", owner_id=1)
session.add(new_ProdCat3)
session.commit()
print "added new product category"
new_ProdItem1 = ProdItem(prdname="Soccer ball", prd_desc="Machined-stitched",
price=10, featured=True, prod_category=new_ProdCat1)
session.add(new_ProdItem1)
session.commit()
new_ProdItem2 = ProdItem(prdname="Soccer cleats", prd_desc="Best cleats ever",
price=60, featured=True, prod_category=new_ProdCat1)
session.add(new_ProdItem2)
session.commit()
new_ProdItem3 = ProdItem(prdname="Soccer gloves", prd_desc="goalkeeper gloves",
price=35, prod_category=new_ProdCat1)
session.add(new_ProdItem3)
session.commit()
new_ProdItem4 = ProdItem(prdname="Tennis racquet", prd_desc="light & powerful",
price=89, prod_category=new_ProdCat2)
session.add(new_ProdItem4)
session.commit()
new_ProdItem5 = ProdItem(prdname="tennis balls", prd_desc="3 hardcourt balls",
price=12.00, prod_category=new_ProdCat2)
session.add(new_ProdItem5)
session.commit()
new_ProdItem6 = ProdItem(prdname="Helmet", prd_desc="Protect your head",
price=120, prod_category=new_ProdCat3)
session.add(new_ProdItem6)
session.commit()
all_categories = get_all_categories()
for category in all_categories:
print category.name, category.id
one_category = get_catg_by_id(1)
print one_category.name, one_category.id
all_items = get_products_by_catg(2)
for item in all_items:
print item.prdname, item.prd_desc, item.id
users = get_all_users()
print "users:"
for user in users:
print user.email
print user.id
print user.social_id
|
{"/catalogapp/models/dbsetup.py": ["/config.py"]}
|
37,848
|
AjayRad/project3.5_catalog_app_v2
|
refs/heads/master
|
/run.py
|
#!flask/bin/python
from catalogapp import app
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--debug", help="run Falsk app in debug mode",
action="store_true")
args = parser.parse_args()
if __name__ == '__main__':
if args.debug:
print "debug mode turned on"
app.debug = True
else:
app.debug = False
app.run(host='0.0.0.0', port=5000)
|
{"/catalogapp/models/dbsetup.py": ["/config.py"]}
|
37,849
|
AjayRad/project3.5_catalog_app_v2
|
refs/heads/master
|
/catalogapp/models/dbsetup.py
|
from sqlalchemy import Column, ForeignKey, Integer, String, Float, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from flask.ext.login import UserMixin
from config import SQLALCHEMY_DATABASE_URI
Base = declarative_base()
class User(UserMixin, Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
social_id = Column(String(64), nullable=False, unique=True)
nickname = Column(String(64), nullable=False)
email = Column(String(64), nullable=True)
class ProdCat(Base):
__tablename__ = 'prod_category'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
desc = Column(String(250))
owner_id = Column(Integer, ForeignKey('users.id'))
users = relationship(User)
@property
def serialize(self):
return {
'id': self.id,
'name': self.name,
'desc': self.desc,
}
class ProdItem(Base):
__tablename__ = 'prod_item'
prdname = Column(String(80), nullable=False)
id = Column(Integer, primary_key=True)
prd_desc = Column(String(250))
price = Column(Float)
num_in_stock = Column(Integer)
featured = Column(Boolean, default=False)
prdcat_id = Column(Integer, ForeignKey('prod_category.id'))
prod_category = relationship(ProdCat)
def __repr__(self):
r = '<Product {:d} {} {}>'
return r.format(self.id, self.prd_desc, self.price)
@property
def serialize(self):
return {
'name': self.prdname,
'description': self.prd_desc,
'id': self.id,
'price': self.price,
'Instock': self.num_in_stock,
'Featured': self.featured,
}
engine = create_engine(SQLALCHEMY_DATABASE_URI)
Base.metadata.create_all(engine)
|
{"/catalogapp/models/dbsetup.py": ["/config.py"]}
|
37,850
|
AjayRad/project3.5_catalog_app_v2
|
refs/heads/master
|
/config.py
|
import os
GOOGLE_LOGIN_CLIENT_ID = "83450637791-rob75ftrerqkh3hsohmgndjrhl76ifbh.apps.googleusercontent.com"
GOOGLE_LOGIN_CLIENT_SECRET = "K3-8LX3y9187INWj1mvl04AN"
FB_LOGIN_CLIENT_ID = '470154729788964'
FB_LOGIN_CLIENT_SECRET = '010cc08bd4f51e34f3f3e684fbdea8a7'
OAUTH_CREDENTIALS = {
'google': {
'id': GOOGLE_LOGIN_CLIENT_ID,
'secret': GOOGLE_LOGIN_CLIENT_SECRET
},
'facebook': {
'id': FB_LOGIN_CLIENT_ID,
'secret': FB_LOGIN_CLIENT_SECRET
}
}
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'postgresql:///' + os.path.join(basedir, 'catalogapp/models/catalog_pg')
|
{"/catalogapp/models/dbsetup.py": ["/config.py"]}
|
37,851
|
AjayRad/project3.5_catalog_app_v2
|
refs/heads/master
|
/catalogapp/views.py
|
from flask import render_template, url_for, request, redirect, flash, jsonify
from flask.ext.login import login_user, logout_user, login_required
from flask.ext.login import current_user, LoginManager
from catalogapp import app
from models import catalog_dao
from oauth import OAuthSignIn
from functools import wraps
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
@lm.user_loader
def load_user(id):
return catalog_dao.get_user_by_id(int(id))
def has_permission(func_check):
"""
decorator checks whether user has permission to add/update/del
products in a category
"""
@wraps(func_check)
def wrapped_f(*args, **kwargs):
category_id = kwargs['category_id']
category_details = catalog_dao.get_catg_by_id(category_id)
if category_details.owner_id != int(current_user.get_id()):
flash('Only category owners can add/update/delete products .')
flash('For permission, please contact admin@bas.com')
return redirect(url_for('get_categories'))
else:
return func_check(*args, **kwargs)
return wrapped_f
# Flasks error handler decorators
@app.errorhandler(404)
def not_found_error(error):
return render_template('Err_404.html'), 404
@app.errorhandler(500)
def internal_error(error):
return render_template('Err_500.html'), 500
@app.route('/')
@app.route('/index')
@app.route('/catalog')
def get_categories():
''' main index page;
gets & renders all categories & featured product from DB.'''
all_categories = catalog_dao.get_all_categories()
is_feat = True
products = catalog_dao.get_featured_products(is_feat)
return render_template("index.html",
title='Product Catalog',
products=products,
all_categories=all_categories)
@app.route('/login', methods=['GET', 'POST'])
def login():
return redirect(url_for('get_categories'))
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('get_categories'))
@app.route('/authorize/<provider>')
def oauth_authorize(provider):
# Flask-Login function
if not current_user.is_anonymous():
return redirect(url_for('get_categories'))
oauth = OAuthSignIn.get_provider(provider)
return oauth.authorize()
@app.route('/callback/<provider>')
def oauth_callback(provider):
if not current_user.is_anonymous():
return redirect(url_for('get_categories'))
oauth = OAuthSignIn.get_provider(provider)
social_id, username, email = oauth.callback()
print social_id
print email
if social_id is None or email is None:
# Need a valid email address for my user identification
flash('Authentication failed.')
return redirect(url_for('get_categories'))
# Look if the user already exists
user = catalog_dao.get_user(email)
if not user:
# Create the user. Try and use their name returned by provider,
# but if it is not set, split the email address at the @.
nickname = username
if nickname is None or nickname == "":
nickname = email.split('@')[0]
success = catalog_dao.add_user(social_id, nickname, email)
print success
if success:
user = catalog_dao.get_user(email)
# Log in the user, by default remembering them for their next visit
# unless they log out.
login_user(user, remember=True)
return redirect(url_for('get_categories'))
@app.route('/catalog/<int:category_id>/products')
def products_by_catg(category_id):
''' get & render product for a particular categoty.
Input needed: category_id'''
products = catalog_dao.get_products_by_catg(category_id)
all_categories = catalog_dao.get_all_categories()
return render_template('products.html',
products=products,
category_id=category_id,
all_categories=all_categories)
@app.route('/catalog/add',
methods=['GET', 'POST'])
@login_required
def add_category():
''' Allows user to add a category to catalog.
User needs to be logged in.
Will be setup of the owner for this category
Input param: none/blank
'''
# Capture category details entered on form
if request.method == 'POST':
if request.form['name']:
catg_name_new = request.form['name']
if request.form['desc']:
catg_desc_new = request.form['desc']
catg_owner_id = int(current_user.get_id())
# Call add catg query in catalog_dao with given data
success = (catalog_dao.add_category(catg_name_new, catg_desc_new,
catg_owner_id))
if success:
flash(" Success ! : Category Added. You are the Category Owner")
else:
flash("OOPS! did not add category. db error. Contact admin")
return (redirect(url_for('get_categories')))
else:
return (render_template('add_category.html'))
@app.route('/catalog/<int:category_id>/products/add',
methods=['GET', 'POST'])
@login_required
@has_permission
def add_product(category_id):
''' Allows user to add products for a category.
User needs to be logged in. And
have permissions for that category i.e. (be the category owner).
both checks implemented using decorators.
Input param : category_id '''
product_feat_new = None
product_name_new = None
product_desc_new = None
product_price_new = None
# Capture product details entered on form
if request.method == 'POST':
if request.form['name']:
product_name_new = request.form['name']
if request.form['prd_desc']:
product_desc_new = request.form['prd_desc']
if request.form['price']:
product_price_new = request.form['price']
if request.form['feat']:
product_feat_new = (True if request.form['feat'] == 'True'
else False)
# Call add query in catalog_dao with given data
success = (catalog_dao.add_product(category_id,
product_name_new, product_desc_new, product_price_new,
product_feat_new))
if success:
flash(" Success ! : Product Added ")
else:
flash("OOPS! did not add product. db error. Contact admin")
return (redirect(url_for('products_by_catg',
category_id=category_id)))
else:
return (render_template('add_product.html',
category_id=category_id))
@app.route('/catalog/<int:category_id>/products/<int:product_id>')
def get_product_details(category_id, product_id):
product_details = catalog_dao.get_product_details(category_id, product_id)
all_categories = catalog_dao.get_all_categories()
return (render_template('product_details.html',
product_details=product_details,
all_categories=all_categories))
@app.route('/catalog/<int:category_id>/products/<int:product_id>/edit',
methods=['GET', 'POST'])
@login_required
@has_permission
def edit_product_details(category_id, product_id):
''' Allows user to edit product details.
User needs to be logged in. And
have permissions for that category i.e. (be the category owner).
both checks implemented using decorators.
Input param : category_id , product_id'''
product_feat_new = None
product_name_new = None
product_desc_new = None
product_price_new = None
# Capture product details from form
if request.method == 'POST':
if request.form['name']:
product_name_new = request.form['name']
if request.form['prd_desc']:
product_desc_new = request.form['prd_desc']
if request.form['price']:
product_price_new = request.form['price']
if request.form['feat']:
product_feat_new = (True if request.form['feat'] == 'True'
else False)
# call update methods in catalog_dao
success = (catalog_dao.update_product_details(category_id, product_id,
product_name_new, product_desc_new, product_price_new,
product_feat_new))
if success:
flash(" Success ! : Product Updated ")
else:
flash(" OOPS!Did not update: Db error. Please contact admin")
return (redirect(url_for('get_product_details',
category_id=category_id,
product_id=product_id)))
else:
product_details = catalog_dao.get_product_details(category_id,
product_id)
return (render_template('edit_product_details.html',
category_id=category_id, product_details=product_details,
product_id=product_id))
@app.route('/catalog/<int:category_id>/products/<int:product_id>/delete',
methods=['GET', 'POST'])
@login_required
@has_permission
def del_product_details(category_id, product_id):
''' Allows user to delete products for a category.
User needs to be logged in. And
have permissions for that category i.e. (be the category owner).
both checks implemented using decorators.
Input param : category_id, product_id '''
if request.method == 'POST':
success = catalog_dao.del_product_details(category_id, product_id)
if success:
flash(" Success ! : Product deleted ")
return (redirect(url_for('products_by_catg',
category_id=category_id)))
else:
return (render_template('del_product_details.html',
category_id=category_id, product_id=product_id))
# JSON endpoint for all categories
@app.route('/catalog/categories/JSON')
def get_categoriesjson():
all_categories = catalog_dao.get_all_categories()
return jsonify(Categories=[i.serialize for i in all_categories])
# JSON endpoint for all products within a category_id
@app.route('/catalog/<int:category_id>/products/JSON')
def products_by_catgjson(category_id):
products = catalog_dao.get_products_by_catg(category_id)
return jsonify(ProductItems=[i.serialize for i in products])
|
{"/catalogapp/models/dbsetup.py": ["/config.py"]}
|
37,852
|
AjayRad/project3.5_catalog_app_v2
|
refs/heads/master
|
/catalogapp/__init__.py
|
from flask import Flask
app = Flask(__name__)
app.secret_key = 'genrandomnum'
app.config.from_object('config')
from catalogapp import views
if not app.debug:
# Setup logging for application
import logging
from logging.handlers import RotatingFileHandler
file_handler = RotatingFileHandler('tmp/catalogapp.log', 'a',
1 * 1024 * 1024, 10)
file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
app.logger.setLevel(logging.INFO)
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.info('catalogapp startup')
|
{"/catalogapp/models/dbsetup.py": ["/config.py"]}
|
37,853
|
AjayRad/project3.5_catalog_app_v2
|
refs/heads/master
|
/catalogapp/models/catalog_dao.py
|
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from dbsetup import ProdCat, Base, ProdItem, User
from flask import current_app
from config import SQLALCHEMY_DATABASE_URI
def db_init():
engine = create_engine(SQLALCHEMY_DATABASE_URI)
Base.metadata.bind = engine
dbsession = sessionmaker(bind=engine)
# dbsession() instance establishes all conversations with the database
# and represents a "staging zone" for all the objects loaded into the
# database session object. Any change made against the objects in the
# session won't be persisted into the database until you call
# session.commit().
session = dbsession()
return session
def get_all_categories():
''' returns all categories in db '''
session1 = db_init()
all_categories = session1.query(ProdCat).all()
return all_categories
def get_catg_by_id(category_id):
'''input parameter: category_id
Returns category details in given category_id '''
session2 = db_init()
category_details = (session2.query(ProdCat).
filter(ProdCat.id == category_id).first())
return category_details
def get_products_by_catg(category_id):
'''input parameter: category_id
Returns all products in category '''
session = db_init()
category_details = get_catg_by_id(category_id)
products = (session.query(ProdItem).
filter(ProdItem.prod_category == category_details).all())
return products
def get_featured_products(is_feat):
'''input parameter: boolean values True or False
Returns 10 featured or not featured products across all categories '''
session = db_init()
products = (session.query(ProdItem).
filter(ProdItem.featured == is_feat).limit(10))
return products
def get_product_details(category_id, product_id):
'''input parameter: category_id, product_id
Returns all product details for a category/product_id combo '''
session = db_init()
product_details = (session.query(ProdItem).
filter(ProdItem.id == product_id and ProdItem.prdcat_id
== category_id).all())
return product_details
def add_category(catg_name_new, catg_desc_new,
catg_owner_id):
'''
mandatory input parameter: new category name.
Optional parameters include other category details.
SQLAlchemy query adds new category to prod_category table.
'''
session = db_init()
new_catg = ProdCat(name=catg_name_new, desc=catg_desc_new,
owner_id=catg_owner_id)
session.add(new_catg)
success = True
try:
# Commit changes to DB
session.commit()
except Exception as e:
current_app.logger.error(e, exc_info=True)
# If commit fails, rollback changes from db
session.rollback()
session.flush()
success = False
return success
def update_product_details(category_id, product_id,
product_name_new=None, product_desc_new=None,
product_price_new=None, product_feat_new=None):
'''mandatory input parameter: category_id, product_id.
Optional parameters include other product details.
SQLAlchemy query updates product details for the given product_id '''
session = db_init()
cur_product_det = (session.query(ProdItem).
filter(ProdItem.id == product_id
and ProdItem.prdcat_id == category_id).first())
if product_name_new is not None:
cur_product_det.prdname = product_name_new
if product_desc_new is not None:
cur_product_det.prd_desc = product_desc_new
if product_price_new is not None:
cur_product_det.price = product_price_new
if product_feat_new is not None:
cur_product_det.featured = product_feat_new
success = True
try:
# Commit updates to DB
session.commit()
except Exception as e:
current_app.logger.error(e, exc_info=True)
# rollback updates if commit fails
session.rollback()
session.flush()
success = False
return success
def add_product(category_id, product_name_new, product_desc_new=None,
product_price_new=None, product_feat_new=None):
'''mandatory input parameter: category_id, new product name.
Optional parameters include other product details.
SQLAlchemy query adds new product to prod_item table. '''
session = db_init()
new_product = ProdItem(prdname=product_name_new, prd_desc=product_desc_new,
price=product_price_new, num_in_stock=1,
featured=product_feat_new,
prdcat_id=category_id)
session.add(new_product)
success = True
try:
# Commit changes to DB
session.commit()
except Exception as e:
current_app.logger.error(e, exc_info=True)
# If commit fails, rollback changes from db
session.rollback()
session.flush()
success = False
return success
def del_product_details(category_id, product_id):
'''mandatory input parameter: category_id, product_id.
SQLAlchemy query deletes product from prod_item table. '''
session = db_init()
session.query(ProdItem).filter(ProdItem.id == product_id and
ProdItem.prdcat_id == category_id).delete(synchronize_session=False)
success = True
try:
# Commit changes to DB
session.commit()
except Exception as e:
current_app.logger.error(e, exc_info=True)
# if commit fails, rollback changes from DB
session.rollback()
session.flush()
success = False
return success
def get_all_users():
session1 = db_init()
all_users = session1.query(User).all()
return all_users
def get_user(email):
session = db_init()
user = session.query(User).filter(User.email == email).first()
return user
def get_user_by_id(id):
session = db_init()
user = session.query(User).filter(User.id == id).first()
return user
def add_user(social_id, nickname, email):
print nickname, email
session = db_init()
new_user = User(social_id=social_id, nickname=nickname, email=email)
session.add(new_user)
success = True
try:
session.commit()
except Exception as e:
current_app.logger.error(e)
session.rollback()
session.flush()
success = False
return success
|
{"/catalogapp/models/dbsetup.py": ["/config.py"]}
|
37,999
|
joaobose/CI3641-exam-1
|
refs/heads/main
|
/pregunta-3/tests/buddy_test.py
|
from ..src.buddy import BuddySystem
import unittest
class TestBuddy(unittest.TestCase):
def test_allocate(self):
system = BuddySystem(120)
out = system.allocate(16, 'A')
self.assertEqual(out, 'Se reservaron 30 bloques para 16 bloques de A')
self.assertTrue('A' in system.allocated)
self.assertTrue(system.allocated['A'].size(), 16)
out = system.allocate(1, 'A')
self.assertEqual(
out, 'Error: A ya se encuentra asignado a un bloque, por favor escoja un nombre distinto.')
out = system.allocate(80, 'B')
self.assertEqual(
out, 'Error: no existe forma de almacenar 80 bloques sin quebrantar el BuddySystem. Memoria llena')
self.assertFalse('B' in system.allocated)
def test_deallocate(self):
system = BuddySystem(120)
out = system.deallocate('B')
self.assertEqual(out, 'Error: "B" no esta reservado en el sistema.')
system.allocate(16, 'A')
system.allocate(1, 'B')
system.allocate(28, 'C')
system.allocate(28, 'D')
out = system.deallocate('B')
self.assertEqual(out, 'B liberado. Se liberaron 1 bloques')
self.assertFalse('B' in system.allocated)
def test_representacion(self):
system = BuddySystem(120)
system.allocate(16, 'A')
system.allocate(1, 'B')
representantion = system.representation()
expected_representation = '\n-------- Bloques libres: \n'
expected_representation += '(31,32) | 2 blocks\n'
expected_representation += '(33,36) | 4 blocks\n'
expected_representation += '(37,44) | 8 blocks\n'
expected_representation += '(45,59) | 15 blocks\n'
expected_representation += '(60,119) | 60 blocks\n'
expected_representation += 'Total disponible: 89\n'
expected_representation += '\n-------- Bloques reservados: \n'
expected_representation += 'A | (0,29) | 30 blocks | 16 used blocks\n'
expected_representation += 'B | (30,30) | 1 blocks | 1 used blocks\n'
expected_representation += 'Total reservado: 31\n'
self.assertEqual(representantion, expected_representation)
|
{"/pregunta-3/tests/buddy_test.py": ["/pregunta-3/src/buddy.py"], "/pregunta-6/tests/expression_test.py": ["/pregunta-6/src/expression.py"], "/pregunta-3/src/main.py": ["/pregunta-3/src/buddy.py"], "/pregunta-6/src/main.py": ["/pregunta-6/src/expression.py"]}
|
38,000
|
joaobose/CI3641-exam-1
|
refs/heads/main
|
/pregunta-4/misterio.py
|
# --- Parte a)
def zip(a, b):
if a and b:
yield (a[0], b[0])
for p in zip(a[1:], b[1:]):
yield p
# for p in zip([1, 2, 3], ['a', 'b', 'c']):
# print(p)
def zipWith(a, b, f):
if a and b:
yield f(a[0], b[0])
for p in zipWith(a[1:], b[1:], f):
yield p
# for p in zipWith([0, 1, 2, 1], [1, 2, 1, 0], lambda x, y: x + y):
# print(p)
# --- Parte b)
def misterio(p):
yield p
acum = []
for p in zipWith([0, *p], [*p, 0], lambda x, y: x + y):
acum += [p]
for m in misterio(acum):
yield m
# for m in misterio([1]):
# print(m)
def suspenso(p):
for m in p:
yield m
acum = []
for p in zipWith([0, *p], [*p, 0], lambda x, y: x + y):
acum += [p]
for m in suspenso(acum):
yield m
# for m in suspenso([1]):
# print(m)
|
{"/pregunta-3/tests/buddy_test.py": ["/pregunta-3/src/buddy.py"], "/pregunta-6/tests/expression_test.py": ["/pregunta-6/src/expression.py"], "/pregunta-3/src/main.py": ["/pregunta-3/src/buddy.py"], "/pregunta-6/src/main.py": ["/pregunta-6/src/expression.py"]}
|
38,001
|
joaobose/CI3641-exam-1
|
refs/heads/main
|
/pregunta-6/src/expression.py
|
def isOperator(x):
return x == '+' or x == '-' or x == '*' or x == '/'
def hasLowestPrecedence(x):
return x == '+' or x == '-'
def hasHighestPrecedence(x):
return x == '*' or x == '/'
# Representamos una expresion como un arbol binario.
# Esto porque todos lo operadores soportados son binarios.
class ExpressionTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def infix(self):
# Los nodos hojas son numeros
if self.right is None and self.left is None:
return f'{self.value}'
leftExp = self.left.infix()
ownExp = f'{self.value}'
rightExp = self.right.infix()
if hasHighestPrecedence(ownExp):
# Check de menor precedencia izquierda
if hasLowestPrecedence(self.left.value):
leftExp = f'({leftExp})'
# Check de menor precedencia derecha
# Check de asociatividad del (/)
if hasLowestPrecedence(self.right.value) or self.right.value == '/':
rightExp = f'({rightExp})'
# Check de asociatividad del (-)
elif ownExp == '-':
if hasLowestPrecedence(self.right.value):
rightExp = f'({rightExp})'
return f'{leftExp} {ownExp} {rightExp}'
def __call__(self):
# Los nodos hojas son numeros
if self.left is None and self.right is None:
return self.value
# Evaluamos izquierda y derecha
leftEval = self.left()
rightEval = self.right()
# Operamos izquierda y derecha
if self.value == '+':
return leftEval + rightEval
if self.value == '-':
return leftEval - rightEval
if self.value == '*':
return leftEval * rightEval
else:
return leftEval // rightEval
# Construye un ExpressionTree a partir de una expresion en postfix
def postfixToExpressionTree(postfix):
# Utilizamos un stack
stack = []
# Iteramos por cada caracter de la expresion
for char in postfix.strip().split(' '):
# Caso: es un un numero
if not isOperator(char):
# Agregamos al stack un nodo hoja
stack.append(ExpressionTree(int(char)))
# Caso: es un operador
else:
# Creamos un nodo operador
operator = ExpressionTree(char)
# Como estamos es postfix, los operandos son los dos operandos calculados mas recientemente
right = stack.pop()
left = stack.pop()
operator.right = right
operator.left = left
# Agregamos el nodo al stack
stack.append(operator)
# Retornamos la expresion mas reciente
# Es decir, la padre
return stack.pop()
# Construye un ExpressionTree a partir de una expresion en prefix
def prefixToExpressionTree(prefix):
# Funcion auxiliar que obtiene el ExpressionTree de un expression (en prefix) comenzando en el indice start
# Retorna el ExpressionTree (de existir) y el indice en donde termina dicho ExpressionTree.
def parse(expression, start):
# Si hay overflow retornamos None
if start >= len(expression):
return None, start
# Obtenemos el primero caracter
char = expression[start]
# Caso: es un numero
if not isOperator(char):
# Retornamos un nodo hoja
return ExpressionTree(int(char)), start
# Caso: es un operador
else:
# Hacemos parse de la expresion de la izquierda
(leftExp, leftEnd) = parse(expression, start + 1)
# Hacemos parse de la expresion de la derecha (a partir de donde termino leftExp)
(rightExp, rightEnd) = parse(expression, leftEnd + 1)
# Creamos el nodo operador
currentExp = ExpressionTree(char)
currentExp.left = leftExp
currentExp.right = rightExp
# Retornamos el nodo operador junto con el indice donde termina
return currentExp, rightEnd
(tree, _) = parse(prefix.strip().split(' '), 0)
return tree
|
{"/pregunta-3/tests/buddy_test.py": ["/pregunta-3/src/buddy.py"], "/pregunta-6/tests/expression_test.py": ["/pregunta-6/src/expression.py"], "/pregunta-3/src/main.py": ["/pregunta-3/src/buddy.py"], "/pregunta-6/src/main.py": ["/pregunta-6/src/expression.py"]}
|
38,002
|
joaobose/CI3641-exam-1
|
refs/heads/main
|
/pregunta-3/src/buddy.py
|
import math
class Partition:
def __init__(self, lower, upper, relative_order):
self.upper = upper
self.lower = lower
self.name = None
self.used = None
self.relative_order = relative_order
def size(self):
return self.upper - self.lower + 1
def representation(self):
out = f'{self.name} | ' if self.name != None else ''
out += f'({self.lower},{self.upper}) | {self.size()} blocks'
out += f' | {self.used} used blocks' if self.used != None else ''
return out
class BuddySystem:
def __init__(self, size):
self.size = size
# Maxima potencia de 2
self.n = self.order(self.size)
# Lista de particiones
# Las guardamos por orden de potencias de dos
# Agregamos un elemento mas para poder indexar con log2
# self.partitions[i] contiene las particiones de tamaño proporcional a 2^i
self.partitions = [[] for x in range(self.n + 1)]
# Diccionario de particiones reservadas
self.allocated = {}
# Inicialmente existe una sola particion, la mas grande posible
self.partitions[self.n].append(Partition(0, self.size - 1, self.n))
def order(self, size):
return math.ceil(math.log2(size))
def allocate(self, size, name):
# Verificamos que el nombre no este referenciado
if name in self.allocated:
return self.__allocation_conflict(name)
order = self.order(size)
# Si tenemos al menos una particion adecuada
if len(self.partitions[order]) > 0:
discarted = []
selected = self.partitions[order].pop()
# seleccionamos aquella que admita el tamaño adecuado
while len(self.partitions[order]) > 0 and selected.size() < size:
discarted.append(selected)
selected = self.partitions[order].pop()
self.partitions[order] += discarted
# Si la mejor particion admite los bloques necesarios
if selected.size() >= size:
return self.__allocation_success(selected, name, size)
else:
# Si no, la descartamos
self.partitions[order].append(selected)
# No existe una particion adecuada
# Particionaremos la particion ya existente de orden superior mas pequeña
# Obtenemos los orderes superiores con particiones disponibles
biggerOrders = [i for i in range(
order, self.n + 1) if len(self.partitions[i]) > 0]
# Si no hay bloques de orden superior para particionar
# Memoria llena
if len(biggerOrders) == 0:
return self.__allocation_failed(size)
# Obtenemos el orden de la particion a particionar
biggerOrder = biggerOrders[0]
# Obtenemos la particion en cuestion
selected = self.partitions[biggerOrder].pop()
# Particionamos hasta tener una particion adecuada
while biggerOrder > order and (selected.size() // 2) >= size:
biggerOrder -= 1
# Particionamos mitad y mitad
lowerHalf = Partition(
selected.lower, selected.lower + (selected.size() // 2) - 1, selected.relative_order - 1)
upperHalf = Partition(
selected.lower + (selected.size()) // 2, selected.upper, selected.relative_order - 1)
# Seleccionamos la mitad adecuada
if size <= lowerHalf.size():
self.partitions[biggerOrder].append(upperHalf)
selected = lowerHalf
else:
self.partitions[biggerOrder].append(lowerHalf)
selected = upperHalf
# La mejor particion esta en el mismo orden lo que lo quiere reservar
# Si la mejor particion no puede contener lo solicitado
if selected.size() < size:
# Retornamos error
self.partitions[order].append(selected)
return self.__allocation_failed(size)
# Ya tenemos la particion adecuada, asi que la reservamos
return self.__allocation_success(selected, name, size)
def deallocate(self, name):
# Verificamos que el nombre este referenciado
if not name in self.allocated:
return self.__deallocation_failed(name)
# Liberamos la particion
deallocated = self.allocated[name]
del self.allocated[name]
deallocated.used = None
deallocated.name = None
# Hacemos merge de buddies si es necesario
lost = deallocated
while lost != None:
current_order = lost.relative_order
# buscamos los posibles buddies
posibleBuddies = [i for i in range(0, len(self.partitions[current_order]))
if self.partitions[current_order][i].upper == lost.lower - 1
or self.partitions[current_order][i].lower == lost.upper + 1]
# Si no hay posibles buddies, no hay nada por hacer
if len(posibleBuddies) == 0:
self.partitions[current_order].append(lost)
break
# Sabemos que si existe un buddy, es uno solo
buddy = self.partitions[current_order].pop(posibleBuddies[0])
# Hacemos merge
merged = Partition(0, 0, lost.relative_order + 1)
if buddy.upper == lost.lower - 1:
merged.lower = buddy.lower
merged.upper = lost.upper
elif buddy.lower == lost.upper + 1:
merged.lower = lost.lower
merged.upper = buddy.upper
lost = merged
return self.__deallocation_success(deallocated, name)
def representation(self):
return self.__free_blocks_representation() + self.__allocated_blocks_representation()
def __free_blocks_representation(self):
out = '\n-------- Bloques libres: \n'
memory = 0
for order in self.partitions:
for partition in order:
out += f'{partition.representation()}\n'
memory += partition.size()
out += f'Total disponible: {memory}\n'
return out
def __allocated_blocks_representation(self):
out = '\n-------- Bloques reservados: \n'
memory = 0
for partition in self.allocated.values():
out += f'{partition.representation()}\n'
memory += partition.size()
out += f'Total reservado: {memory}\n'
return out
def __allocation_success(self, partition, name, size):
partition.name = name
partition.used = size
self.allocated[name] = partition
return f'Se reservaron {partition.size()} bloques para {size} bloques de {name}'
def __allocation_conflict(self, name):
return f'Error: {name} ya se encuentra asignado a un bloque, por favor escoja un nombre distinto.'
def __allocation_failed(self, size):
return f'Error: no existe forma de almacenar {size} bloques sin quebrantar el BuddySystem. Memoria llena'
def __deallocation_failed(self, name):
return f'Error: "{name}" no esta reservado en el sistema.'
def __deallocation_success(self, partition, name):
return f'{name} liberado. Se liberaron {partition.size()} bloques'
|
{"/pregunta-3/tests/buddy_test.py": ["/pregunta-3/src/buddy.py"], "/pregunta-6/tests/expression_test.py": ["/pregunta-6/src/expression.py"], "/pregunta-3/src/main.py": ["/pregunta-3/src/buddy.py"], "/pregunta-6/src/main.py": ["/pregunta-6/src/expression.py"]}
|
38,003
|
joaobose/CI3641-exam-1
|
refs/heads/main
|
/pregunta-6/tests/expression_test.py
|
from ..src.expression import ExpressionTree, postfixToExpressionTree, prefixToExpressionTree
import unittest
class TestBuddy(unittest.TestCase):
def test_infix(self):
expression = postfixToExpressionTree('8 3 - 8 4 4 + * +')
infix = expression.infix()
self.assertEqual(infix, '8 - 3 + 8 * (4 + 4)')
# -- prueba de parentesis de precedencia
expression = postfixToExpressionTree('5 3 * 5 1 + 2 / +')
infix = expression.infix()
self.assertEqual(infix, '5 * 3 + (5 + 1) / 2')
# -- prueba de parentisis de asociatividad del -
expression = postfixToExpressionTree('5 3 * 5 1 + -')
infix = expression.infix()
self.assertEqual(infix, '5 * 3 - (5 + 1)')
expression = postfixToExpressionTree('5 3 * 5 -')
infix = expression.infix()
self.assertEqual(infix, '5 * 3 - 5')
# -- prueba de parentisis de asociatividad del /
expression = postfixToExpressionTree('10 2 5 / *')
infix = expression.infix()
self.assertEqual(infix, '10 * (2 / 5)')
expression = postfixToExpressionTree('10 2 * 5 /')
infix = expression.infix()
self.assertEqual(infix, '10 * 2 / 5')
expression = postfixToExpressionTree('10 2 / 5 /')
infix = expression.infix()
self.assertEqual(infix, '10 / 2 / 5')
expression = postfixToExpressionTree('10 2 5 / /')
infix = expression.infix()
self.assertEqual(infix, '10 / (2 / 5)')
def test_postfix(self):
expression = postfixToExpressionTree('8 3 - 8 4 4 + * +')
self.assertEqual(expression(), 69)
expression = postfixToExpressionTree('5 3 * 5 1 + 2 / +')
self.assertEqual(expression(), 18)
expression = postfixToExpressionTree('5 3 * 5 1 + -')
self.assertEqual(expression(), 9)
expression = postfixToExpressionTree('5 3 * 5 -')
self.assertEqual(expression(), 10)
expression = postfixToExpressionTree('10 2 5 / *')
self.assertEqual(expression(), 0)
expression = postfixToExpressionTree('10 2 * 5 /')
self.assertEqual(expression(), 4)
expression = postfixToExpressionTree('10 2 / 5 /')
self.assertEqual(expression(), 1)
expression = postfixToExpressionTree('10 2 5 / /')
with self.assertRaises(ZeroDivisionError):
expression()
def test_prefix(self):
expression = prefixToExpressionTree('+ - 8 3 * 8 + 4 4')
self.assertEqual(expression(), 69)
expression = prefixToExpressionTree('+ * 5 3 / + 5 1 2')
self.assertEqual(expression(), 18)
expression = prefixToExpressionTree('- * 5 3 + 5 1')
self.assertEqual(expression(), 9)
expression = prefixToExpressionTree('- * 5 3 5')
self.assertEqual(expression(), 10)
expression = prefixToExpressionTree('* 10 / 2 5')
self.assertEqual(expression(), 0)
expression = prefixToExpressionTree('/ * 10 2 5')
self.assertEqual(expression(), 4)
expression = prefixToExpressionTree('/ / 10 2 5')
self.assertEqual(expression(), 1)
expression = prefixToExpressionTree('/ 10 / 2 5')
with self.assertRaises(ZeroDivisionError):
expression()
|
{"/pregunta-3/tests/buddy_test.py": ["/pregunta-3/src/buddy.py"], "/pregunta-6/tests/expression_test.py": ["/pregunta-6/src/expression.py"], "/pregunta-3/src/main.py": ["/pregunta-3/src/buddy.py"], "/pregunta-6/src/main.py": ["/pregunta-6/src/expression.py"]}
|
38,004
|
joaobose/CI3641-exam-1
|
refs/heads/main
|
/pregunta-3/src/main.py
|
from .buddy import BuddySystem
n = int(input('Ingrese el numero de bloques de memoria a manejar: '))
system = BuddySystem(n)
while True:
args = input("Introduzca su comando: ").split()
command = args[0]
if command == 'SALIR':
break
if command == 'MOSTRAR':
print(system.representation())
continue
if command == 'RESERVAR':
name = args[1]
size = int(args[2])
print(system.allocate(size, name))
continue
if command == 'LIBERAR':
name = args[1]
print(system.deallocate(name))
continue
|
{"/pregunta-3/tests/buddy_test.py": ["/pregunta-3/src/buddy.py"], "/pregunta-6/tests/expression_test.py": ["/pregunta-6/src/expression.py"], "/pregunta-3/src/main.py": ["/pregunta-3/src/buddy.py"], "/pregunta-6/src/main.py": ["/pregunta-6/src/expression.py"]}
|
38,005
|
joaobose/CI3641-exam-1
|
refs/heads/main
|
/pregunta-6/src/main.py
|
from .expression import ExpressionTree, postfixToExpressionTree, prefixToExpressionTree
while True:
args = input("Introduzca su comando: ").split()
command = args[0]
if command == 'SALIR':
break
if command == 'EVAL':
orden = args[1]
expression = ' '.join(args[2:])
if orden == 'PRE':
print(prefixToExpressionTree(expression)())
elif orden == 'POST':
print(postfixToExpressionTree(expression)())
continue
if command == 'MOSTRAR':
orden = args[1]
expression = ' '.join(args[2:])
if orden == 'PRE':
print(prefixToExpressionTree(expression).infix())
elif orden == 'POST':
print(postfixToExpressionTree(expression).infix())
continue
|
{"/pregunta-3/tests/buddy_test.py": ["/pregunta-3/src/buddy.py"], "/pregunta-6/tests/expression_test.py": ["/pregunta-6/src/expression.py"], "/pregunta-3/src/main.py": ["/pregunta-3/src/buddy.py"], "/pregunta-6/src/main.py": ["/pregunta-6/src/expression.py"]}
|
38,033
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio17.py
|
# Desafio 17 Curso em Video Python
# Calcula o valor da hipotenusa de um triângulo retângulo a partir dos catetos informados
#By Rafabr
import sys,time
import math as matematica
print('\nDesafio 17')
print('Este programa calcula o valor da hipotenusa de um triângulo retângulo a partir dos catetos informados\n')
cateto1 = float(input("Informe o valor de um dos catetos do triângulo retângulo: "))
cateto2 = float(input("Informe o valor do outro cateto: "))
hip = matematica.hypot(cateto1,cateto2)
print("\nO valor da hipotenusa é : {:.5f}".format(hip))
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,034
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio51.py
|
# Desafio 51 Curso em Video Python
# By Rafabr
from sys import exit
from estrutura_modelo import cabecalho, rodape
cabecalho(51, "Termos de uma Progressão Aritmética - I")
try:
p0 = float(input('Digite o Termo inicial da PA: '))
r = float(input('Digite a razão da PA: '))
except ValueError:
print('Voçe digitou um valor indevido!')
exit()
print()
pa = []
for i in range(0, 10):
pa.append(p0 + r*i)
print(f'A 10 primeiros termos da PA será:\n\n{pa}')
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,035
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio22.py
|
# Desafio 22 Curso em Video Python
# Este programa utiliza diversos métodos de strings para mostrar algumas informações.
# By Rafabr
print('\nDesafio 22')
print('Este programa utiliza diversos métodos de strings para mostrar algumas informações.\n')
print()
nome = str(input('Digite seu nome completo: ')).strip()
print()
print('Maiúsculo: '+nome.upper())
print('Minúsculo: '+nome.lower())
nome_sem_espaco = nome.replace(" ", "")
print(f'O nome digitado tem {len(nome_sem_espaco)} caracteres e {len(nome) - len(nome_sem_espaco)} espaços entre as palavras')
nome_separado = nome.split()
print(f'A primeira palavra ({nome_separado[0]}) possui {len(nome_separado[0])} caracteres')
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,036
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio25.py
|
# Desafio 25 Curso em Video Python
# Este programa verifica se uma pessoa tem 'silva' no nome.
# By Rafabr
import os
os.system('clear')
print('\nDesafio 25')
print('Este programa verifica se uma pessoa tem \'silva\' no nome.\n\n')
nome = input('Digite seu nome completo: ')
print()
nome = nome.lower()
lista_nome = nome.split()
if 'silva' in lista_nome:
print("Parabéns!\nVoçe faz parte da família 'SILVA'!!!")
else:
print("Voçe não tem o nome silva no seu nome!")
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,037
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio9.py
|
# Desafio 9 Curso em Video Python
# Mostra a tabuada multiplicativa de um número digitado!
#By Rafabr
import sys,time
import os
os.system('clear')
print('\033[1;47;30m',end="")
print('\n'+'*'*80)
print('Desafio 9'.center(80))
print('Este programa mostra a tabuada multiplicativa de um número digitado!'.center(80))
print(80*'*')
print('\033[m',end="")
print('\033[1;36m')
try:
n = int(input('Digite um número inteiro: '))
print()
except ValueError:
print('\nNao foi digitado um valor válido\n')
time.sleep(2)
sys.exit()
print(f'A tabuada multiplicativa do número {n} é:')
for k in [0,1,2,3,4,5,6,7,8,9]:
print(f'--> {n}*{k} = {n*k}')
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,038
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio46.py
|
# Desafio 46 Curso em Video Python
# By Rafabr
from time import sleep
from sys import exit
from os import system
from estrutura_modelo import cabecalho,rodape
from emoji import emojize as em
def fireworks():
system('clear')
cabecalho(46,"Contagem Regressiva!")
print(em(':balloon::balloon::balloon:'))
sleep(0.5)
print(em(':sparkles::sparkles::sparkles::sparkles:'))
sleep(0.5)
print(em(':fireworks::fireworks::fireworks::fireworks::fireworks:'))
sleep(0.5)
print(em(':eight-pointed_star: :eight-pointed_star: :eight-pointed_star: :eight-pointed_star: :eight-pointed_star: :eight-pointed_star:'))
sleep(0.5)
print(em(':fireworks::fireworks::fireworks::fireworks::fireworks:'))
sleep(0.5)
print(em(':sparkles::sparkles::sparkles::sparkles:'))
sleep(0.5)
print(em(':balloon::balloon::balloon:'))
sleep(1)
print('FELIZ ANO NOVO!!!')
sleep(2)
def contagem(num:int):
cabecalho(46,"Contagem Regressiva!")
print(em(':partying_face::partying_face: Festa de Fim de Ano :party_popper::party_popper:\n\n'))
for k in range(10,0,-1):
if (k == 10):
print(em(f' -{k} - '.center(30,em(':raising_hands:'))))
else:
print(em(f' - {k} - '.center(30,em(':raising_hands:'))))
sleep(1)
cabecalho(46,"Contagem Regressiva!")
print('Vamos a contagem regressiva?!')
sleep(2)
system('clear')
contagem(10)
fireworks()
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,039
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/aula11-FimModulo1-exemplos.py
|
#Aula 11 do Curso Python em Video!
#By Rafabr
import time,sys
import os
os.system('clear')
print('\033[7;1;47;34m',end="")
print('\n'+'*'*80)
print('Aula XX'.center(80))
print('Esta programa ...'.center(80))
print('*'*80+'\n')
print('\033[m',end="")
print('\033[1;36m')
print('TESTE'.center(80,"*"))
print('\033[m')
print('\033[1;41;37m',end="")
print('\n'+'Fim da execução'.center(80))
print('*'*80)
print('\033[m',end="")
time.sleep(2)
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,040
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio47.py
|
# Desafio 47 Curso em Video Python
# By Rafabr
from time import sleep
from sys import exit
from os import system
from estrutura_modelo import cabecalho,rodape
cabecalho(47,"Números pares entre 1 e um número positivo qualquer!")
try:
numeroLimite = int(input("Digite um número positivo inteiro: "))
except ValueError:
print("Valor inválido!")
sleep(1)
exit()
print(f'\nOs números pares entre 1 e {numeroLimite} são:')
numerosPares = []
for k in range(0,numeroLimite,2):
numerosPares.append(k)
print(numerosPares)
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,041
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio13.py
|
# Desafio 13 Curso em Video Python
# Calcula um aumento de 15% no salário de uma pessoa
#By Rafabr
import sys,time
import os
os.system('clear')
print('\033[1;47;30m',end="")
print('\n'+'*'*80)
print('Desafio 13'.center(80))
print('Este programa calcula um aumento de 15% no salário de uma pessoa.'.center(80))
print(80*'*')
print('\033[m',end="")
print('\033[1;36m')
try:
salario = float(input('Digite o valor de seu Salário atual: '))
print()
except ValueError:
print('\nNao foi digitado um valor válido\n')
time.sleep(2)
sys.exit()
print('Seu Salário atual é R$ {:.2f}'.format(salario))
print('Seu novo salário com aumento de 15% é de R$ {:.2f}'.format(salario*1.15))
print('Parabéns!')
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,042
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio14.py
|
# Desafio 14 Curso em Video Python
# Transforma uma temperatura em Celsuis para Fahrenheit
#By Rafabr
import sys,time
import os
os.system('clear')
print('\033[1;47;30m',end="")
print('\n'+'*'*80)
print('Desafio 14'.center(80))
print('Este programa transforma uma temperatura em Celsuis para Fahrenheit!'.center(80))
print(80*'*')
print('\033[m',end="")
print('\033[1;36m')
try:
temp_c = float(input('Digite a temperatura em ºC: '))
print()
except ValueError:
print('\nNao foi digitado um valor válido\n')
time.sleep(2)
sys.exit()
temp_f = temp_c*1.8+32
print('Resultado: {}ºC equivalem a {}ºF'.format(temp_c,temp_f))
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,043
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio19.py
|
# Desafio 19 Curso em Video Python
# Sorteia um aluno entre quatro alunos informados
#By Rafabr
import sys,time
import random as ale
print('\nDesafio 19')
print('Este programa sorteia um aluno entre quatro alunos informados\n')
a1 = input("Digite o nome do primeiro aluno: ")
a2 = input("Digite o nome do segundo aluno: ")
a3 = input("Digite o nome do terceiro aluno: ")
a4 = input("Digite o nome do quarto aluno: ")
alunos = [a1,a2,a3,a4]
sorteio = ale.randint(0,3)
print("\nSorteando um dos alunos...")
time.sleep(2)
print("\nO aluno sorteado foi: {}".format(alunos[sorteio]))
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,044
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio43.py
|
# Desafio 43 Curso em Video Python
# By Rafabr
import os,time,sys
from estrutura_modelo import cabecalho,rodape
cabecalho(43,"Cálculo e Avaliação de IMC")
try:
peso = float(input("Informe o seu peso(Em Kg - Ex.: 80) : ").replace(',','.'))
altura = float(input('Informe sua altura(Em metros - Ex.: 1,73): ').replace(',','.'))
print()
except ValueError:
print('Voçe não digitou valores válidos!\nUse virgulas para casa decimais!')
time.sleep(0.5)
sys.exit()
if peso<0 or altura<0:
print('Voçe digitou valores negativos!')
time.sleep(0.5)
sys.exit()
imc = peso/pow(altura,2)
print('Seu IMC é',f'{imc:.2f}'.replace('.',','),'!\n')
if imc < 18.5:
print('Voçe está ABAIXO do Peso!')
elif imc <= 25:
print('Voçe está com Peso Normal ou Ideal!')
elif imc <= 30:
print('Voçe está com SOBREPESO!')
elif imc <= 40:
print('Voçe está com OBESIDADE!')
else:
print('Voçe está com OBESIDADE MÓRBIDA!')
peso_ideal_min = 18.5 * (altura**2)
peso_ideal_max = 25 * (altura**2)
print(f'\nPara um IMC ideal, seu peso deveria está entre: '+f'{peso_ideal_min:.2f}Kg → {peso_ideal_max:.2f}Kg'.replace('.',','))
print('\033[1;33;41m'+'''
A verificação de Obesidade pelo Índice IMC pode não ser
eficaz, pois não considera a gordura corporal!
Para uma melhor avaliação veja um Nutrólogo ou Nutricionista!
'''+'\033[m')
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,045
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio32.py
|
# Desafio 32 Curso em Video Python
# Este programa verifica se o ano informado é bissexto.
# By Rafabr
import sys
import time
import os
import random
os.system('clear')
print('\nDesafio 32')
print('Este programa verifica se o ano informado é bissexto\n\n')
try:
ano = int(input('Informe o ano que deseja verificar: ').strip())
except ValueError:
os.system('clear')
print('Voçe não digitou um ano válido!')
time.sleep(1)
sys.exit()
if ano < 0:
os.system('clear')
print('Voçe digitou um ano negativo!\n')
time.sleep(1)
sys.exit()
os.system('clear')
if (ano % 4) == 0:
print(f'\nVoçe informou o ano {ano}.')
print(f'\n{ano} é um ano bissexto!')
else:
print(f'\nVoçe informou o ano {ano}.')
print(f'\n{ano} não é um ano bissexto!')
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,046
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio64.py
|
# Desafio 64 Curso em Video Python
# By Rafabr
from estrutura_modelo import cabecalho, rodape
cabecalho(64, "Soma de números informados - com while")
print('Digite abaixo os números que deseja incluir ou digite 999 para sair!')
numeros = []
while True:
try:
n = float(input('Digite um número: '))
except ValueError:
print('Voçe digitou um valor indevido!\n')
continue
if int(n) == 999:
break
else:
numeros.append(n)
print(f'\nForam digitados {len(numeros)} números no total!')
print(f'A soma de todos os números é {sum(numeros):.2f}!')
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,047
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio21.py
|
# Desafio 21 Curso em Video Python
# Executa um arquivo de música MP3
# By Rafabr
import time
import playsound
try:
import replit
except ImportError:
import pygame
print('\nDesafio 21')
print('Este programa executa um arquivo de música MP3.\n')
# playsound.playsound('a.mp3')
try:
source = replit.audio.play_file('a.mp3')
time.sleep(10)
except NameError:
playsound.playsound('a.mp3')
time.sleep(10)
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,048
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio56.py
|
# Desafio 56 Curso em Video Python
# By Rafabr
from time import sleep
from sys import exit
from estrutura_modelo import cabecalho, rodape
from statistics import fmean
cabecalho(56, "Analisar dados - médio, maior, menor")
try:
dicionario_pessoas = {}
quantidade_pessoas = int(input("Informe quantas pessoas deseja cadastrar\
para serem analisadas: "))
for _ in range(quantidade_pessoas):
print('\nIniciando o cadastro de uma nova pessoa!')
nome = input("Informe o nome da pessoa: ").strip()
dicionario_pessoas[nome.split()[0]] = [nome]
dicionario_pessoas[nome.split()[0]] += [
int(input('Informe a idade da pessoa: '))
]
dicionario_pessoas[nome.split()[0]] += [
input('Informe o sexo da pessoa:(M ou F) ')
]
except ValueError:
print("Voçe digitou algum valor errado ou indevido!")
sleep(1)
exit()
print()
idades = [dicionario_pessoas[item][1] for item in dicionario_pessoas]
dict_idade_crescente = sorted(
dicionario_pessoas.items(),
key=lambda x: x[1][1],
reverse=True
)
lista_homem_velho = []
for lista in dict_idade_crescente:
if lista[1][2] == 'M':
lista_homem_velho.append(lista)
print()
mulheres_menor20 = []
for item in dicionario_pessoas:
if (dicionario_pessoas[item][2] == 'F' and
dicionario_pessoas[item][1] < 20):
mulheres_menor20.append(item)
print(
f"A média de idade das pessoas informadas é {fmean(idades):.2f}"
)
print(
f"O homem mais velho se chama {lista_homem_velho[0][0]}"
)
print(
f"{len(mulheres_menor20)} mulheres possuem menos de 20 anos!"
)
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,049
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio23.py
|
# Desafio 23 Curso em Video Python
# Este programa separa um número em unidades, dezenas, centenas e milhares de um número.
# By Rafabr
import sys
import time
import os
os.system('clear')
print('\nDesafio 23')
print('Este programa separa um número em unidades, dezenas, centenas e milhares de um número.\n')
numero = input('Digite um número natural (Máximo: 9999): ')
print()
if not(numero.isdecimal()) or int(numero) > 9999:
print("Voçe digitou número diferente do especificado!\n\n")
sys.exit()
print("Processando...\n")
time.sleep(1)
numero = int(numero)
unidade = numero // 1 % 10
dezena = numero // 10 % 10
centeza = numero // 100 % 10
milhar = numero // 1000 % 10
print(f"Número Digitado: {numero}")
print(f"Unidade: {unidade}")
print(f"Dezena: {dezena}")
print(f"Centena: {centeza}")
print(f"Milhar: {milhar}")
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,050
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio3.py
|
# Desafio 3 Curso em Video Python
# Fazer a soma e diferença de valores informados pelo usuário, convertendo a entrada para números!
#By Rafabr
'''O detalhe do exercício e saber como converter caractere de entrada
em uma variável do tipo float para poder realizar a soma dos números'''
import os
os.system('clear')
print('\033[1;47;30m',end="")
print('\n'+'*'*80)
print('Desafio 3'.center(80))
print('Este programa calcula a soma ou a diferença de 2 números informados!'.center(80))
print(80*'*')
print('\033[m',end="")
print('\033[1;36m')
#solicita dois números do usuário
x=float(input('\nDigite um número qualquer:\n\t'))
y=float(input('\nDigite outro número:\n\t'))
'''realiza a soma e a diferença dos números informados convertendo
os caracteres informados para números'''
soma=x+y
dif=x-y
#Imprime como saida a soma e a diferença dos números informados
print('\n\t+ A soma dos dois números é: {} + {} = {}'.format(x,y,soma))
print('\t- A diferença entre eles é: {} - {} = {}'.format(x,y,dif))
print('\n---Fim da execução---\n')
print(80*'*')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,051
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio57.py
|
# Desafio 57 Curso em Video Python
# By Rafabr
from estrutura_modelo import cabecalho, rodape
cabecalho(57, "Solicitar entrada enquanto valor padrão não for digitado")
while True:
sexo = input('Informe qual é o seu sexo (M ou F): ').strip().upper()
if sexo in 'MmFf':
break
print('Dado Inválido!')
print(f'\nFoi informado o sexo {sexo}')
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,052
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/aula04-exemplo1.py
|
#Aula 04 do Curso Python em Video!
#Exercício de Desafio da Aula 04!
#By Rafabr
'''Este programa pergunta o nome da pessoa e retorna uma saudação, após isso
solicita o dia o mês e o ano do usuário e retorna a data completade nascimento
de forma configurada'''
print('************************************************************')
print('\nAula 04 - Exemplos')
print('Este programa pergunta alguns dados seus e retorna os dados\npara confirmação')
#pergunta o nome do usuário e retorna uma saudação
nome = input('\nQual é o seu nome?\n')
print('\tOlá {}!\n\tSeja bem vindo ao python!'.format(nome))
print('\nATENÇÃO: Aprenda com Sabedoria!\n')
#pergunta os dados de nascimento e retorna o nascimento completo
dia = input('Qual dia voçe nasceu?\n')
mes = input('Qual mês voçe nasceu?\n')
ano = input('E o ano, qual foi?\n')
print('\n\t\tObrigado pelas informações!')
print('\nData de nascimento de',nome,':',dia,'de',mes,'de',ano)
print('\nFim da execução\n')
print('************************************************************')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,053
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio49.py
|
# Desafio 49 Curso em Video Python
# By Rafabr
from time import sleep
from sys import exit
from os import system
from estrutura_modelo import cabecalho,rodape
cabecalho(49,"Tabuada!")
try:
num_tab = int(input('Informe o número que deseja ver a tabuada completa: '))
except ValueError:
print('Voçe digitou um valor indevido!')
exit()
if num_tab not in list(range(1,11)):
print('Voçe digitou um valor indevido!')
exit()
print()
print(f'TABUADA DE SOMA DO {num_tab}'.center(40,'-')+'|'+f'TABUADA MULTIPLIÇÃO DO {num_tab}'.center(40,'-'))
for k in list(range(1,11)):
print(f'{num_tab} + {k} = {num_tab+k}'.ljust(15).center(40)+'|'+f'{num_tab} * {k} = {num_tab*k}'.ljust(15).center(40))
print('-'*81)
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,054
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/aula09-exemplos.py
|
#Aula 9 do Curso Python em Video!
#Exercício da Aula 09!
#By Rafabr
''''''
print('\n'+'*'*80)
print('Aula 09 - Exemplos e Testes'.center(80)+'\n')
frase = input("Digite uma Frase para testar alguns métodos utilizados com Strings: ")
print(f'\nA frase digitada possui {len(frase)} caracteres!\n')
print('\t',end = "")
for k in range(len(frase)):
print(frase[k].center(4),end = "")
print('\n\t',end = "")
for k in range(len(frase)):
print(str(k).center(4),end = "")
print("\n")
print(f"O primeiro caractere (frase[0]) é: ".ljust(50)+f"'{frase[0]}'")
print(f"O quinto caractere (frase[4]) é: ".ljust(50)+f"'{frase[4]}'")
print(f"Os primeiros 10 caracteres (frase[:10]) são: ".ljust(50)+f"'{frase[:10]}'")
print("Caracteres 5º a 15º (frase[4:14]) são: ".ljust(50)+f"'{frase[4:14]}'")
print()
print(f"O último caractere (frase[-1]) é: ".ljust(60)+f"'{frase[-1]}'")
print(f"Os últimos 10 caracteres (frase[-10:]) são: ".ljust(60)+f"'{frase[-10:]}'")
print(f"10 caracteres iniciais pulando de 2 em 2 (frase[:10:2]) é: ".ljust(60)+f"'{frase[:10:2]}'")
print()
print(f"A quantidade de Espaços (frase.count(' ')) na frase digitada é: ".ljust(110)+f"'{frase.count(' ')}'")
print(f"Podemos procurar uma string(Ex.:frase.find('no')) na frase digitada (Retorna índice): ".ljust(110)+f"'{frase.find('no')}'")
print(f"Podemos verificar se existe uma string na frase digitada ('no' in frase): ".ljust(110)+f"'{'no' in frase}'")
print()
print(f"Podemos substituir parte de uma string(frase.replace('a','y')) na frase digitada: ".ljust(85)+f"'{frase.replace('a','y')}'")
print()
print(f"A primeira palavra (frase.split[0]) da frase digitada é: ".ljust(85)+f"'{frase.split()[0]}'")
print(f"A última palavra (frase.split[-1]) da frase digitada é: ".ljust(85)+f"'{frase.split()[-1]}'")
join_teste = " ".join([frase.split()[0],frase.split()[-1]])
print(f"Juntando as duas palavras(" ".join(['frase.split[0]','frase.split[-1]'])) teremos: ".ljust(85)+"'"+" ".join([frase.split()[0],frase.split()[-1]])+"'")
print('\nFim da execução\n')
print('************************************************************')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,055
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio35.py
|
# Desafio 35 Curso em Video Python
# Este programa verifica se 3 comprimentos de retas informados formam um triângulo.
# By Rafabr
import sys
import time
import os
import random
os.system('clear')
print('\nDesafio 35')
print('Este programa verifica se 3 comprimentos de retas informados formam um triângulo.\n\n')
try:
retas = str(input(
"Informe 3 medidas de reta separadas por virgula ','(Ex.: 4,5,6): ")).strip().split(',')
r1 = float(retas[0])
r2 = float(retas[1])
r3 = float(retas[2])
except ValueError:
os.system('clear')
print('Voçe não digitou valores válidos!')
time.sleep(0.5)
sys.exit()
except IndexError:
os.system('clear')
print('Voçe não digitou 3 valores!')
time.sleep(0.5)
sys.exit()
os.system('clear')
if len(retas) > 3:
os.system('clear')
print('Voçe digitou mais que 3 valores!')
time.sleep(0.5)
sys.exit()
if r1 < 0 or r2 < 0 or r3 < 0:
os.system('clear')
print('Voçe digitou valores negativos!')
time.sleep(0.5)
sys.exit()
t = 0
if r1 < r2 + r3:
t = t + 1
if r2 < r1 + r3:
t = t + 1
if r3 < r2 + r1:
t = t + 1
if t == 3:
print(f'As retas de medidas {retas}, formam um triângulo!')
else:
print(f'As retas de medidas {retas}, NÃO formam um triângulo!')
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,056
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio33.py
|
# Desafio 33 Curso em Video Python
# Este programa ordena três números em sequência.
# By Rafabr
import sys
import time
import os
import random
os.system('clear')
print('\nDesafio 33')
print('Este programa ordena três números em sequência.\n\n')
try:
n1 = float(input('Informe o primeiro número: ').strip())
n2 = float(input('Informe o segundo número: ').strip())
n3 = float(input('Informe o terceiro número: ').strip())
except ValueError:
os.system('clear')
print('Voçe não digitou números válido!')
time.sleep(0.5)
sys.exit()
if n1 == n2 or n1 == n3 or n2 == n3:
os.system('clear')
print('Voçe digitou 2 números ou mais iguais!')
time.sleep(0.5)
sys.exit()
os.system('clear')
if n1 < n2:
if n1 < n3:
print(f'O menor número é {n1}')
if n2 < n3:
print(f'O maior número é {n3}')
print(f'A sequência crescente é {n1} -> {n2} -> {n3}')
else:
print(f'O maior número é {n2}')
print(f'A sequência crescente é {n1} -> {n3} -> {n2}')
else:
print(f'O menor número é {n3}')
print(f'O maior número é {n2}')
print(f'A sequência crescente é {n3} -> {n1} -> {n2}')
else:
if n2 < n3:
print(f'O menor número é {n2}')
if n1 < n3:
print(f'O maior número é {n3}')
print(f'A sequência crescente é {n2} -> {n1} -> {n3}')
else:
print(f'O maior número é {n1}')
print(f'A sequência crescente é {n2} -> {n3} -> {n1}')
else:
print(f'O menor número é {n3}')
print(f'O maior número é {n1}')
print(f'A sequência crescente é {n3} -> {n2} -> {n1}')
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,057
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio65.py
|
# Desafio 65 Curso em Video Python
# By Rafabr
from estrutura_modelo import cabecalho, rodape
cabecalho(65, "Média, Maior e Menor valor de numeros informados")
def maisNumeros():
try:
qtd_numeros_incluir = int(
input('\nInforme quantos números deseja incluir: ')
)
except ValueError:
print('Voçe digitou um valor indevido!')
n = 0
numeros = []
while n < qtd_numeros_incluir:
try:
numeros.append(float(input('Digite um número: ')))
except ValueError:
print('Voçe digitou um número invalido!')
n += 1
return numeros
numeros = maisNumeros()
while True:
continuar = input('\nDeseja adicionar mais números (s/n): ').lower()
if continuar == 's':
numeros += maisNumeros()
elif continuar == 'n':
break
else:
print('Digite uma opção válida!')
print(f'\nOs números digitados são:\n»» {numeros} ')
print(f'\nA média dos Números digitados é {sum(numeros)/len(numeros)}')
print(f'O maior número da lista é {max(numeros)}')
print(f'O menor número da lista é {min(numeros)}')
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,058
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio38.py
|
# Desafio 38 Curso em Video Python
# By Rafabr
import os,time,sys
from estrutura_modelo import cabecalho,rodape
cabecalho(38,"Comparar dois números")
try:
n1 = int(input('Digite um número inteiro: '))
n2 = int(input('Digite outro número inteiro: '))
print()
except ValueError:
print('Voçe digitou um valor indevido!')
time.sleep(0.5)
sys.exit()
if n1 > n2:
print(f'O primeiro valor digitado, {n1}, é o maior valor!')
elif n1 < n2:
print(f'O segundo valor digitado, {n2}, é o maior valor!')
else:
print(f'Não existe valor maior entre os dois números, {n1} e {n2}, eles são iguais!')
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,059
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio44.py
|
# Desafio 44 Curso em Video Python
# By Rafabr
import os,time,sys
from estrutura_modelo import cabecalho,rodape
cabecalho(44,"Valor de Produto com Diversas Meios de Pagamentos")
try:
valor_normal = float(input("Informe o preço normal do produto(Em R$ - Ex.: 20,44) : ").replace(',','.'))
meio_pag = int(input('''Informe qual o meio de pagamento:
1 - À vista em Dinheiro ou PIX - Desconto de 10%
2 - À vista no Cartão de Crédito ou Débito - Desconto de 5%
3 - Cartão de Crédito em 2 parcelas - Sem Desconto
4 - Cartão de Crédito em 3 ou mais parcelas - Juros de 20%
: '''))
print()
except ValueError:
print('Voçe não digitou valores válidos!\nUse virgulas para casa decimais!')
time.sleep(0.5)
sys.exit()
if valor_normal<0:
print('Voçe digitou valores negativos!')
time.sleep(0.5)
sys.exit()
if meio_pag not in [1,2,3,4]:
print('Voçe digitou uma condição de pagamento inválida!')
time.sleep(0.5)
sys.exit()
if meio_pag == 1:
print(f'Com o meio de pagamento informado voçe terá um Desconto de 10%\n\nO valor do Produto será R$ {(valor_normal*0.9):.2f}'.replace('.',','))
elif meio_pag == 2:
print(f'Com o meio de pagamento informado voçe terá um Desconto de 5%\n\nO valor do Produto será R$ {(valor_normal*0.95):.2f}'.replace('.',','))
elif meio_pag == 3:
print(f'Com o meio de pagamento informado voçe pagará o valor normal do Produto\n\nO valor do Produto será R$ {valor_normal:.2f}'.replace('.',','))
elif meio_pag == 4:
print(f'Com o meio de pagamento informado voçe pagará Juros de 20%\n\nO valor do Produto será R$ {(valor_normal*1.2):.2f}'.replace('.',','))
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,060
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio42.py
|
# Desafio 42 Curso em Video Python
# By Rafabr
import os,time,sys
from estrutura_modelo import cabecalho,rodape
cabecalho(42,"Classificação de Triângulos 2")
try:
retas = str(input("Informe 3 medidas de reta separadas por virgula ','(Ex.: 4,5,6): ")).strip().split(',')
r = [float(retas[0]),float(retas[1]),float(retas[2])]
print()
except ValueError:
print('Voçe não digitou valores válidos!')
time.sleep(0.5)
sys.exit()
except IndexError:
print('Voçe não digitou 3 valores!')
time.sleep(0.5)
sys.exit()
if len(r)>3:
print('Voçe digitou mais que 3 valores!')
time.sleep(0.5)
sys.exit()
if r[0]<0 or r[1]<0 or r[2]<0:
print('Voçe digitou valores negativos!')
time.sleep(0.5)
sys.exit()
if r[0] < r[1] + r[2] and r[1] < r[0] + r[2] and r[2] < r[1] + r[0]:
print(f'As medidas informadas {r}, formam um triângulo!')
if r[0] == r[1] == r[2]:
print('O triângulo formado é um triângulo Equilátero!')
elif r[0] == r[1] or r[0] == r[2] or r[1] == r[2]:
print('O triângulo formado é um triângulo Isósceles!')
else:
print('O triângulo formado é um triângulo Escaleno!!')
else:
print('As medidas informadas NÃO formam um triângulo!')
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,061
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio39.py
|
# Desafio 39 Curso em Video Python
# By Rafabr
import os,time,sys
from estrutura_modelo import cabecalho,rodape
cabecalho(39,"Informação sobre alistamento militar")
try:
ano_nasc = int(input('Digite o ano de seu nascimento: '))
print()
except ValueError:
print('Voçe digitou um valor indevido!')
time.sleep(0.5)
sys.exit()
idade = time.localtime().tm_year - ano_nasc
if idade < 18:
print('\tVoçe não completou 18 anos, ainda vai se alistar no serviço militar')
print(f'\tFaltam {18 - idade} anos para o alistamento')
elif idade == 18:
print(f'\tVoçe tem {idade} anos!')
print('\tDeverá se listar esse ano no serviço militar')
else:
print('\tVoçe já passou do tempo de alistamento militar')
print(f'\tO prazo para seu alistamento passou há {idade - 18} anos')
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,062
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio52.py
|
# Desafio 52 Curso em Video Python
# By Rafabr
from time import sleep
from sys import exit
from os import system
from estrutura_modelo import cabecalho,rodape
cabecalho(52,"Verificador de número primo!")
try:
numero = int(input('Digite o número a ser análisado: '))
except ValueError:
print('Voçe digitou um valor indevido!')
exit()
if numero < 0:
print('Números negativos não podem ser números primos!')
sleep(1)
exit()
print()
numeros_divisores = []
if numero in [0,1]:
print(f'O número {numero} não é um número primo!')
else:
for i in range(1,numero):
if numero%i == 0:
numeros_divisores.append(i)
if len(numeros_divisores) == 1:
print(f'O número {numero} informado é um número primo!')
else:
print(f'O número informado não é número primo, pois tem os seguintes divisores:\n\n{numeros_divisores}')
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,063
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio10.py
|
# Desafio 10 Curso em Video Python
# Converte um valor em reais para dólares americanos!
#By Rafabr
import sys,time
import os
os.system('clear')
print('\033[1;47;30m',end="")
print('\n'+'*'*80)
print('Desafio 10'.center(80))
print('Este programa converte um valor em reais para dólares americanos!'.center(80))
print(80*'*')
print('\033[m',end="")
print('\033[1;36m')
try:
reais = float(input('Digite o valor em reais que deseja converter: '))
print()
except ValueError:
print('\nNao foi digitado um valor válido\n')
time.sleep(2)
sys.exit()
print('Considerando a taxa de conversão atual: U$ 1.00 = R$ 3.27\n')
dolares = reais / 3.27
print('Com R$ {:.2f}, voçe pode adquirir U$ {:.2f}'.format(round(reais,2),round(dolares-0.005,2)))
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,064
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio54.py
|
# Desafio 54 Curso em Video Python
# By Rafabr
from time import sleep
from datetime import date
from sys import exit
from estrutura_modelo import cabecalho, rodape
cabecalho(54, "Verificar maioridade de pessoas")
print("Este programa irá verificar quantas das pessoas informadas são maiores que 18 anos!\n")
try:
lista_ano_nascimento = list(map(int,input("Digite os anos de nascimento das pessoas separadas por espaço: ").split()))
except ValueError:
print("Voçe digitou algum valor errado ou indevido!")
sleep(1)
exit()
quantidade_maiores = 0
for k in lista_ano_nascimento:
quantidade_maiores += 1 if (date.today().year - k >= 18) else 0
print(f"\nForam digitados anos de nascimento de {len(lista_ano_nascimento)} pessoas!")
print(f"{quantidade_maiores} pessoas são maiores de 18 anos!")
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,065
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/aula13-exemplos.py
|
#Aula 13 do Curso Python em Video!
#By Rafabr
import time,sys
import os
from estrutura_modelo import cabecalho,rodape
cabecalho(13,"Esta Aula será sobre Estruturas de Repetição FOR!")
print('Exemplo 01 - Imprimindo usando repetição!')
for c in range(0,6):
print(c)
print('Usado range(0,6)')
print('─── Fim Exemplo 01!\n'.upper()+'─'*30)
print('Exemplo 02 - Imprimindo usando repetição - Testando iteração reversa!')
for c in range(6,0,-1):
print(c)
print('Usado range(6,0,-1)')
print('─── Fim Exemplo 02!\n'.upper()+'─'*30)
print('Exemplo 03 - Imprimindo usando repetição - Testando iterações com incrementos diversos!')
for c in range(6,0,-2):
print(c)
print('Usado range(6,0,-2)')
for c in range(0,10,3):
print(c)
print('Usado range(0,10,3)')
for c in range(0,4,5):
print(c)
print('Usado range(0,4,5)')
print('─── Fim Exemplo 03!\n'.upper()+'─'*30)
print('Exemplo 04 - Imprimindo usando repetição - Lendo dados do usuário para as repetições!')
i = int(input('Digite o início: '))
f = int(input('Digite o final: '))
passo = int(input('Digite o passo(incremento): '))
for c in range(i,f+1,passo):
print(c)
print('Usado range(6,0,-1)')
print('─── Fim Exemplo 04!\n'.upper()+'─'*30)
print('Exemplo 05 - Leitura de varios dados usando repetição!')
dados = []
for c in range(0,5):
dados.append(input(f'Digite o dado{c}: '))
print(dados)
print('─── Fim Exemplo 05!\n'.upper()+'─'*30)
print('Exemplo 06 - Somando varios valores informados usando repetição!')
soma = 0
for c in range(0,5):
n = int(input('Digite um número: '))
soma += n
print(f'A soma dos números digitados é {soma}!')
print('─── Fim Exemplo 06!\n'.upper()+'─'*30)
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,066
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio7.py
|
# Desafio 7 Curso em Video Python
# Ler duas notas do aluno, calcula e mostra a média!
#By Rafabr
import sys,time
import os
os.system('clear')
print('\033[1;47;30m',end="")
print('\n'+'*'*80)
print('Desafio 7'.center(80))
print('Este programa recebe duas notas e calcula a média delas!'.center(80))
print(80*'*')
print('\033[m',end="")
print('\033[1;36m')
try:
nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a segunda nota: '))
print()
except ValueError:
print('\nNao foi digitado um valor válido.\n')
time.sleep(2)
sys.exit()
media_notas = (nota1 + nota2) / 2
print(f'A média das notas {nota1} e {nota2} é: {media_notas}')
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,067
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio36.py
|
# Desafio 36 Curso em Video Python
# By Rafabr
import os,time
from estrutura_modelo import cabecalho,rodape
cabecalho(36,"Análise de um financiamento de Imóvel")
print('\tPrezado Cliente,\n\tIremos coletar algumas informações para analisar sua solicitação de financiamento.\n')
valor_casa = float(input('Informe o valor do imóvel que deseja financiar: '))
prazo_finan = int(input('Informe qual o prazo desejado do financiamento (em anos): '))
salario = float(input('Informe qual o seu salário: '))
prestacao_mensal = valor_casa/(prazo_finan*12)
limite_prest = salario*0.3
print('\nCadastrando dados informados')
time.sleep(1)
cabecalho(36,"Verificar se uma pessoa pode fazer um financiamento de Imóvel")
print('Processando dados de sua análise')
time.sleep(0.5)
cabecalho(36,"Verificar se uma pessoa pode fazer um financiamento de Imóvel")
print('Processando dados de sua análise.')
time.sleep(0.8)
cabecalho(36,"Verificar se uma pessoa pode fazer um financiamento de Imóvel")
print('Processando dados de sua análise..')
time.sleep(1.1)
cabecalho(36,"Verificar se uma pessoa pode fazer um financiamento de Imóvel")
print('Processando dados de sua análise...')
time.sleep(1.5)
cabecalho(36,"Verificar se uma pessoa pode fazer um financiamento de Imóvel")
print('\nSeus dados foram processados pelo sistema e sua análise foi concluída.')
print(f'Valor do financiamento:'.ljust(25)+f'R$ {valor_casa:.2f}')
print(f'Prazo do financiamento:'.ljust(25)+f'{prazo_finan} Anos')
print(f'Prestação mensal:'.ljust(25)+f'R$ {prestacao_mensal:.2f}\n')
if prestacao_mensal <= limite_prest:
print('\n\tParabens!\n\tSeu financiamento foi aprovado!')
print('\tEntraremos em contato para prosseguirmos com o financiamento.\n\tObrigado por usar nossos serviços.')
else:
print('\n\tSeu financiamento não foi aprovado!\n\tTente novamente quando tiver um aumento salarial ou procure uma casa de menor valor.')
print(f'\nPrestação mensal máxima para o seu salário: R$ {limite_prest:.2f}')
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,068
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio12.py
|
# Desafio 12 Curso em Video Python
# Recebe o preço de um produto e cálcula uma desconto de 5% eno preço.
#By Rafabr
import sys,time
import os
os.system('clear')
print('\033[1;47;30m',end="")
print('\n'+'*'*80)
print('Desafio 12'.center(80))
print('Este programa recebe o preço de um produto e calcula uma desconto de 5%.'.center(80))
print(80*'*')
print('\033[m',end="")
print('\033[1;36m')
try:
preco = float(input('Digite o preço do produto a ser calculado o desconto: '))
print()
except ValueError:
print('\nNao foi digitado um valor válido\n')
time.sleep(2)
sys.exit()
preco = preco *0.95
print('O preço do produto com desconto de 5% é R$ {:.2f}'.format(preco))
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,069
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio6.py
|
# Desafio 6 Curso em Video Python
# Receber um número da usuário e informar o seu dobro, triplo e a raiz quadrada
#By Rafabr
import sys,time
import os
os.system('clear')
print('\033[1;47;30m',end="")
print('\n'+'*'*80)
print('Desafio 6'.center(80))
print('Este programa mostra o dobro, o triplo e a raiz quadrada de qualquer número.'.center(80))
print(80*'*')
print('\033[m',end="")
print('\033[1;36m')
try:
x = float(input('Digite número qualquer: '))
print()
except ValueError:
print('\nNao foi digitado um valor válido\n')
time.sleep(2)
sys.exit()
print(f'O dobro de {x} é {2*x}')
print(f'O triplo de {x} é {3*x}')
print (f'A raiz quadrada de {x} é {x**(1/2)}')
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,070
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio31.py
|
# Desafio 31 Curso em Video Python
# Este programa calcula o preço de viagem cujo valor depende da distâcia a ser percorrida.
# By Rafabr
import sys
import time
import os
import random
os.system('clear')
print('\nDesafio 31')
print('Este programa calcula o preço de viagem cujo valor depende da distâcia a ser percorrida.\n\n')
try:
km = int(input(
'Informe a distâcia a ser percorrida na viagem que pretende fazer (Em km): ').strip())
except ValueError:
os.system('clear')
print('Voçe digitou um valor não númerico!')
time.sleep(1)
sys.exit()
if km < 0:
os.system('clear')
print('Voçe digitou um valor negativo!\nNão existe distância negativa!')
time.sleep(1)
sys.exit()
os.system('clear')
if km <= 200:
print('\nPara essa viagem, o valor por kilometro percorrido será R$ 0,50!')
print(f'Voçe pagará o total de R$ {km*0.5:.2f}')
else:
print('\nPara essa viagem, o valor por kilometro percorrido será R$ 0,45!')
print(f'Voçe pagará o total de R$ {km*0.45:.2f}')
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,071
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio15.py
|
# Desafio 15 Curso em Video Python
# Calcula o valor a pagar pelo aluguel de um carro
#By Rafabr
import sys,time
print('\nDesafio 15')
print('Este programa calcula o valor a pagar pelo aluguel de um carro.\n')
try:
km = float(input('Informe quantos Km (número inteiro ou decimal) voçe percorreu com o carro alugado\n: '))
dias = int(input('Informe quantos Dias (número inteiro) voçe ficou com o carro\n: '))
print()
except ValueError:
print('\nNao foi digitado um valor numérico!\n')
time.sleep(1)
sys.exit()
print('Valores a pagar por Km e por Dia do carro alugado:\n1 dia --> R$ 60.00\n1 km --> R$ 0.15\n')
valor_aluguel = dias * 60 + km * 0.15
print('O valor total a pagar pelo aluguel do carro será R$ {:.2f}'.format(valor_aluguel))
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,072
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/estrutura_modelo.py
|
# Estruturas para os desafios Curso em Video Python
# By Rafabr
import os
def cabecalho(aula, sobre: str):
os.system('clear')
print('\033[;1;44;37m', end="")
print('\n'+'*'*100)
print(f'Aula/Desafio {aula}'.center(100))
print(sobre.center(100))
print('*'*100+'\n')
print('\033[m', end="")
def rodape():
print('\n')
print('\033[1;41;37m', end="")
print('Fim da Execução'.center(100))
print('*'*100+'\n')
print('\033[m', end="")
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,073
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio4.py
|
# Desafio 4 Curso em Video Python
# Usa uma função que retorna o tipo primitivo e utiliza alguns métodos utilizados com strings!
# By Rafabr
import os
os.system('clear')
print('\033[1;47;30m',end="")
print('\n'+'*'*80)
print('Desafio 4'.center(80))
print('Este programa estuda os tipos primitivos de Python e utiliza'.center(80))
print('alguns métodos utilizados com strings!'.center(80))
print(80*'*')
print('\033[m',end="")
print('\033[1;36m')
n1=input('Digite número: ')
print('\nEsse programa importou o valor como o seguinte tipo primitivo:\n',type(n1))
n=input('\nDigite algo:')
print('\nVoçe digitou algum número?')
print(n.isnumeric())
print('Voçe difitou alguma palavra?')
print(n.isalpha())
print('Voçe digitou uma palavra maiúscula?')
print(n.isupper())
print('Voçe digitou uma palavra minúscula?')
print(n.islower())
print('Voçe digitou uma palavra alfanumérica?')
print(n.isalnum())
print('Voçe digitou um espaço?')
print(n.isspace())
print('\n---Fim da execução---\n')
print(80*'*')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,074
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio5.py
|
# Desafio 5 Curso em vídeo Python
# Receber um número do usuário emostrar sucessor e antecessor
#By Rafabr
import sys,time
import os
os.system('clear')
print('\033[1;47;30m',end="")
print('\n'+'*'*80)
print('Desafio 5'.center(80))
print('Este programa mostra o antecessor e o sucessor de qualquer número'.center(80))
print(80*'*')
print('\033[m',end="")
print('\033[1;36m')
try:
x = int(input('Digite um número inteiro: '))
print()
except ValueError:
print('\nNao foi digitado um número inteiro\n')
time.sleep(2)
sys.exit()
print (f'O antecessor do número digitado é {x-1}')
print (f'O sucessor do número digitado é {x+1}')
print ('Sequência:',x-1,x,x+1)
print('\n---Fim da execução---\n')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,075
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio59.py
|
# Desafio 59 Curso em Video Python
# By Rafabr
from time import sleep
from os import system
from estrutura_modelo import cabecalho, rodape
cabecalho(59, "Menu de Operações Aritméticas")
print('Este programa calcula uma operação matemática com os números \
informados.'.center(100).upper(), end='\n\n')
while True:
try:
numeros = list(
map(
float, input(
"Digite os números separados por espaço: \n »"
).split()
)
)
except ValueError:
print('Valor(es) inválidos inseridos! Tente Novamente!')
continue
break
while True:
while True:
try:
menu = int(input('''
[1] Somar
[2] Multiplicar
[3] Maior
[4] Novos Números
[5] Sair do Programa
'''))
except ValueError:
print('Opção do menu inválida, tente novamente!')
sleep(2)
system('clear')
cabecalho(59, "Menu de Operações Aritméticas")
print(f'{numeros=}')
continue
break
if menu == 1:
system('clear')
cabecalho(59, "Menu de Operações Aritméticas")
print(f'{numeros=}')
print(f'\nA soma dos números é:\n» {sum(numeros):.2f}')
elif menu == 2:
system('clear')
cabecalho(59, "Menu de Operações Aritméticas")
print(f'{numeros=}')
multiplicacao = 1
for n in numeros:
multiplicacao *= n
print(f'\nA multiplicação dos números é:\n» {multiplicacao:.2f}')
elif menu == 3:
system('clear')
cabecalho(59, "Menu de Operações Aritméticas")
print(f'{numeros=}')
print(f'\nO maior número é:\n» {max(numeros)}')
elif menu == 4:
system('clear')
cabecalho(59, "Menu de Operações Aritméticas")
print(f'Números Antigos: {numeros}')
while True:
try:
numeros = list(
map(
float, input(
"Digite os novos números separados por espaço:\n »"
).split()
)
)
except ValueError:
print('Valor(es) inválidos inseridos! Tente Novamente!')
continue
break
print(f'\nNovos Números: {numeros}')
elif menu == 5:
print('Saindo do Programa...')
sleep(1)
break
else:
print('Menu inválido! Tente Novamente!')
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,076
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio45.py
|
# Desafio 45 Curso em Video Python
# By Rafabr
import os,time,sys
import random
from estrutura_modelo import cabecalho,rodape
cabecalho(45,"Jogo do Jokenpô!")
try:
player = int(input('''Bem vindo ao Jogo da Pedra, Papel e Tesoura!
Para Jogar escolha umas das opções abaixo:
1 - Pedra
2 - Papel
3 - Tesoura
0 - Não Quero Jogar - Sair
: '''))
print()
except ValueError:
print('Voçe não escolheu uma opção válida!\n')
time.sleep(0.5)
sys.exit()
if player not in [1,2,3,0]:
print('Voçe não escolheu uma opção válida!')
time.sleep(0.5)
sys.exit()
choice_pc = random.choice(['PEDRA','PAPEL','TESOURA'])
if player == 0:
print('Ta com medo de perder?!\n')
time.sleep(1)
print('Quando ganhar coragem volte para jogar!\n')
sys.exit()
if player == 1:
os.system('clear')
cabecalho(45,"Jogo do Jokenpô!")
print(f'Voçe escolheu PEDRA!')
time.sleep(1)
print(f'O computador escolheu {choice_pc}')
if choice_pc == 'TESOURA':
print('\n\tPARABÉNS, Pedra quebra Tesoura, Voçe Ganhou!')
elif choice_pc == 'PAPEL':
print('\n\tTente Novamente,Papel enrola Pedra, Voçe Perdeu!')
else:
print('\n\tDeu Empate!')
if player == 2:
os.system('clear')
cabecalho(45,"Jogo do Jokenpô!")
print(f'Voçe escolheu PAPEL!')
time.sleep(1)
print(f'O computador escolheu {choice_pc}')
if choice_pc == 'PEDRA':
print('\n\tPARABÉNS, Papel enrola Pedra, Voçe Ganhou!')
elif choice_pc == 'TESOURA':
print('\n\tTente Novamente, Tesoura corta Papel, Voçe Perdeu!')
else:
print('\n\tDeu Empate!')
if player == 3:
os.system('clear')
cabecalho(45,"Jogo do Jokenpô!")
print(f'Voçe escolheu TESOURA!')
time.sleep(1)
print(f'O computador escolheu {choice_pc}')
if choice_pc == 'PAPEL':
print('\n\tPARABÉNS, Tesoura corta Papel, Voçe Ganhou!')
elif choice_pc == 'PEDRA':
print('\n\tTente Novamente, Pedra quebra Tesoura, Voçe Perdeu!')
else:
print('\n\tDeu Empate!')
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,077
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/desafio63.py
|
# Desafio 63 Curso em Video Python
# By Rafabr
from estrutura_modelo import cabecalho, rodape
cabecalho(63, "Sequência de Fibonacci")
while True:
try:
print('Esse programa mostra alguns termos da Sequência de Finobacci!')
termos = float(input('Digite o número de Termos que deseja ver: '))
except ValueError:
print('Voçe digitou um valor indevido!\n')
continue
break
n = 3
n1 = 0
n2 = 1
n_atual = 0
print('\n0 » 1', end="")
while (n <= termos):
n_atual = n1 + n2
print(f' » {n_atual}', end="")
n1, n2 = n2, n_atual
n += 1
print()
rodape()
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
38,078
|
rafarbop/Python-Curso-em-Video
|
refs/heads/master
|
/aula08-exemplos.py
|
#Aula 8 do Curso Python em Video!
#Exercício da Aula 08!
#By Rafabr
'''Este exercicio testa o comando import para importar módulos com comandos
não disponíveis em python. Foi testado a biblioteca math para importar.
Foi testado também a importação somente da função específica através do comando from'''
from math import sqrt,floor,ceil
import math,random,emoji
print('************************************************************')
print('\nAula 08 - Exemplos e Testes')
num = int(input('Digite um número: '))
raiz = sqrt(num)
print(f'\nA Raiz de {num} é igual a {raiz:.10f} - Aproximado com 10 casas decimais!')
print(f'A Raiz de {num} é igual a {floor(raiz)} - Aproximado com para baixo!')
print(f'A Raiz de {num} é igual a {ceil(raiz)} - Aproximado com para cima!')
print(f'A Raiz de {num} é igual a {math.trunc(raiz)} - Truncado, sem casas decimais!')
print()
print('Teste de número aleatório usando a biblioteca ramdom: {}'.format(random.random()))
print('Teste de número aleatório entre 1 e 5: {}'.format(random.randint(1,5)))
print(emoji.emojize("teste emoji :cry:",use_aliases=True))
print('\nFim da execução\n')
print('************************************************************')
|
{"/desafio51.py": ["/estrutura_modelo.py"], "/desafio46.py": ["/estrutura_modelo.py"], "/desafio47.py": ["/estrutura_modelo.py"], "/desafio43.py": ["/estrutura_modelo.py"], "/desafio64.py": ["/estrutura_modelo.py"], "/desafio56.py": ["/estrutura_modelo.py"], "/desafio57.py": ["/estrutura_modelo.py"], "/desafio49.py": ["/estrutura_modelo.py"], "/desafio65.py": ["/estrutura_modelo.py"], "/desafio38.py": ["/estrutura_modelo.py"], "/desafio44.py": ["/estrutura_modelo.py"], "/desafio42.py": ["/estrutura_modelo.py"], "/desafio39.py": ["/estrutura_modelo.py"], "/desafio52.py": ["/estrutura_modelo.py"], "/desafio54.py": ["/estrutura_modelo.py"], "/aula13-exemplos.py": ["/estrutura_modelo.py"], "/desafio36.py": ["/estrutura_modelo.py"], "/desafio59.py": ["/estrutura_modelo.py"], "/desafio45.py": ["/estrutura_modelo.py"], "/desafio63.py": ["/estrutura_modelo.py"], "/desafio53.py": ["/estrutura_modelo.py"], "/desafio50.py": ["/estrutura_modelo.py"], "/desafio60.py": ["/estrutura_modelo.py"], "/desafio62.py": ["/estrutura_modelo.py"], "/desafio61.py": ["/estrutura_modelo.py"], "/aula12-exemplos.py": ["/estrutura_modelo.py"], "/desafio58.py": ["/estrutura_modelo.py"], "/desafio41.py": ["/estrutura_modelo.py"], "/desafio40.py": ["/estrutura_modelo.py"], "/desafio55.py": ["/estrutura_modelo.py"], "/desafio48.py": ["/estrutura_modelo.py"], "/desafio37.py": ["/estrutura_modelo.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.