blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
7bd54a47b0950d29f681a2819a18fa7fe7a084a3
|
ChrisMcK1/shutTheBox
|
/shutTheBox.py
| 6,061 | 4.09375 | 4 |
#! /usr/bin/python3
import random
import sys #to trigger game over for incorrect input
import time
import itertools #to calculate all possible play comibinations based on available board integers
#setting up the Board to show which number slot we're in, which will have an integer
#until it is selected by the user to be removed from the board, then it will be 'X'
theBoard = [1, 2, 3, 4,\
5, 6, 7, 8, 9, \
10]
## Need to add """ """ notation to functions
#defining function for the visual of the board, starts with showing each integer 1 thru 10
def printBoard(board):
print(str(board[0]) + '|' + str(board[1]) + '|' + str(board[2]) + '|' \
+ str(board[3]) + '|' + str(board[4]) + '|' + str(board[5]) + '|' \
+ str(board[6]) + '|' + str(board[7]) + '|' + str(board[8]) + '|' \
+ str(board[9]) + '|')
#function to check if game has been won, need to expand on this to give the option to start a new game
def winCon():
winTotal = 0
if theBoard == ['X', 'X', 'X','X',\
'X', 'X', 'X', 'X', 'X', \
'X']:
print('Congratulations, you\'ve won!')
winTotal += 1
print('You\'ve won ' + str(winTotal) + ' games.')
def newGame():
while True:
print('Would you like to start a new game? y/n?')
response = input()
if response == 'n':
print('Goodbye!')
sys.exit()
if response == 'y':
diceRollFunc()
else:
continue
#function to show all available plays, using itertools module
#def combos():
def diceRollFunc():
theBoard = [1, 2, 3, 4,\
5, 6, 7, 8, 9, \
10]
while theBoard != ['X', 'X', 'X','X',\
'X', 'X', 'X', 'X', 'X', \
'X']:
diceRoll = random.randint(1, 6) + random.randint(1,6)
while True:
print('Roll the pair of dice by typing \'r\'.')
roll = input()
if roll == ('r'):
print('You rolled a ' + str(diceRoll) + '. Now choose which \
numbers to remove from the board.')
print('Here\'s the board again, enter one number \
at a time to remove it from the board.')
printBoard(theBoard)
print('Here are your available plays.')
availablePlay = [] #empty list that will then populate with current integers on the board
for i in theBoard[:10]: #iterate through the board, creating a new list to remove all "X' and keep only integers
try:
if i == 'X':
continue
else:
availablePlay.append(i)
except ValueError:
continue
except TypeError:
continue
result = [seq for i in range(len(availablePlay), 0 , -1) for seq in itertools.combinations(availablePlay, i) if sum(seq) == diceRoll] #itertools sequence to create list variable containing all available plays
if result == []:
print('You have none. Game over.')
newGame()
else:
print(result)
newBoard = input()
newBoard1 = 0
newBoard2 = 0
newBoard3 = 0
try:
if int(newBoard) != int(theBoard[int(newBoard)-1]): #test to check if input is an available space on board and not already an 'X'
continue
except ValueError:
print('That is an invalid input, start over.')
newGame()
except IndexError:
print('That is an invalid input, start over.')
newGame()
if int(newBoard) > 0 and int(newBoard) < 11 and int(newBoard) <= diceRoll:
theBoard[int(newBoard)-1] = 'X'
if (int(diceRoll) - int(newBoard)) == 0:
break
if int(newBoard) > int(diceRoll):
print('That is an invalid input, start over.')
newGame()
if (int(diceRoll) - int(newBoard)) != 0:
print('Please enter another number to remove')
newBoard1 = input()
theBoard[int(newBoard1)-1] = 'X'
if (int(newBoard1) + int(newBoard)) > diceRoll:
print('That is an invalid input, start over.')
newGame()
if (int(diceRoll) - int(newBoard) - int(newBoard1)) == 0:
break
if (int(diceRoll) - int(newBoard) - int(newBoard1)) != 0:
print('Please enter another number to remove')
newBoard2 = input()
theBoard[int(newBoard2)-1] = 'X'
if (int(newBoard1) + int(newBoard2) + int(newBoard)) > diceRoll:
print('That is an invalid input, start over.')
newGame()
if (int(diceRoll) - int(newBoard) - int(newBoard1) - int(newBoard2)) == 0:
break
if (int(diceRoll) - int(newBoard) - int(newBoard1) - int(newBoard2)) != 0:
print('Please enter another number to remove')
newBoard3 = input()
theBoard[int(newBoard3)-1] = 'X'
if (int(newBoard1) + int(newBoard2) + int(newBoard3) + int(newBoard)) > diceRoll:
print('That is an invalid input, start over.')
newGame()
if (int(diceRoll) - int(newBoard) - int(newBoard1) - int(newBoard2) - int(newBoard3)) == 0:
break
#Need to define function or statement that will check if current dice roll is playable on the available board integer spaces in the list, if not, the game needs to end.
printBoard(theBoard)
print('Welcome to Shut the Box! Here is your board, let\'s get started.')
printBoard(theBoard)
diceRollFunc()
winCon()
|
4c1571e0eb11d604f630c2ef8627165b73db14a5
|
SinigribovS/Rezolvarea-problemelor-IF-WHILE-FOR
|
/3.py
| 434 | 3.703125 | 4 |
#Se dau numerele naturale m şi n, unde m <n. Să se verifice dacă n este o putere a lui m.
m=int(input('Dati numarul natural m (baza): '))
n=int(input('Dati numarul natural n (puterea): '))
if (n<m):
print('Eroare: n<m')
else:
a=True
for i in range(1,n+1):
if(m**i==n):
print('Da,',n,' este putere a lui ',m)
a=False
if a:
print('Nu,',n,' nu este putere a lui ',m)
|
5aea25fbfc44841612b271c36b61f15b6c52d552
|
s4yhii/jesus-repo-clase
|
/jes.py
| 637 | 3.75 | 4 |
#ejercicio7
antiguedad=5
sueldo=300
if antiguedad>5:
print(sueldo*1.2)
if antiguedad<=5 and antiguedad>1:
print(sueldo*1.1)
else:
print(sueldo)
#ejercicio9
control1=int(input("ingrese el primer peso"))
control2=int(input("ingrese el segundo peso"))
control3=int(input("ingrese el tercer peso"))
if control2-control1<300 :
print("el incremento del control 2 y 1 es menor que 300g")
elif (control3-control2<300):
print("el incremento del control 3 y 2 es menor que 300g")
#ejercicio de la sumatoria
tot=0
numero=4
for i in range(0,numero+1):
tot=tot+(i**5+4*i**3+3*(i**2)+5)
print(tot)
|
dd6b8c830ace6f94415534cdc3e650c1911537bd
|
s4yhii/jesus-repo-clase
|
/ejercicio8.py
| 425 | 3.9375 | 4 |
#ejercicio8
num1=int(input("ingrese un numero menor que 1000: "))
num2=int(input("ingrese otro numero menor que 1000:"))
if num1<1000 and num2<1000 :
a=int((num1/10)%10)
b=int((num2)%10)
c=int((num2/100)%10)
suma=a+b+c
union=(f"{a}{b}{c}")
print(f"el numero formado es: {union}")
print(f"la suma de los digitos es: {suma}")
else:
print("los numeros ingresados son incorrectos")
|
ad353b9d60b68942de19669b70c19147b59ba6ba
|
c3drive/my_scraping
|
/python_scraper.py
| 3,543 | 3.671875 | 4 |
import csv
import re
import sqlite3
from typing import List
import requests
import lxml.html
def main():
"""
メインの処理。fetch(), scrape(), save()の3つの関数を呼び出す。
"""
url = 'https://gihyo.jp/dp'
html = fetch(url)
books = scrape(html, url)
save('books.db', books)
save_file('books.csv', books)
def fetch(url: str)-> str:
"""
引数urlで与えられたURLのWebページを取得する。
WebページのエンコーディングはConetnt-Typeヘッダーから取得する。
戻り値:str型のHTML
"""
r = requests.get(url)
return r.text #HTTPヘッダーから取得したエンコーディングでデコードした文字列を返す
def scrape(html: str, base_url: str)-> List[dict]:
"""
引数htmlで与えらえたHTMLから正規表現で書籍の情報を抜き出す。
引数base_urlは絶対URLに変換する際の基準となるURLを指定する。
戻り値:書籍(dict)のリスト
"""
books =[]
html = lxml.html.fromstring(html)
html.make_links_absolute(base_url) #すべてのa要素のhref属性を絶対URLに変換する。
#cssselect()メソッドで、セレクターに該当するa要素のリストを取得して、ここのa要素に対して処理を行う。
#セレクターの意味:id="listBook"である要素 の直接の子であるli要素 の直接の子であるitemprop="url"という属性を持つa要素
for a in html.cssselect('#listBook > li > a[itemprop="url"]'):
#a要素のhref属性から書籍のurlを取得する。
url = a.get('href')
#書籍のタイトルはitemprop="name"という属性を持つp要素から取得する。
p = a.cssselect('p[itemprop="name"]')[0]
title = p.text_content() #wbr要素などが含まれているのでtextではなくtext_contentを使う
books.append({'url':url, 'title':title})
return books
def save(db_path: str, books: List[dict]):
"""
引数booksで与えたれた書籍のリストをSQLiteデータベースに保存する。
データベースのパスは引数db_pathで与えられる。
戻り値:無し
"""
conn = sqlite3.connect(db_path)
c = conn.cursor()
c.execute('DROP TABLE IF EXISTS books')
c.execute('''
CREATE TABLE books(
title text,
url text
)
''')
c.executemany('INSERT INTO books VALUES(:title, :url)', books)
conn.commit()
conn.close()
def save_file(file_path: str, books: List[dict]):
"""
引数booksで与えたれた書籍のリストをCSV形式のファイルに保存する。
ファイルのパスは引数file_pathで与えられる。
戻り値:無し
"""
with open(file_path, 'w', newline='') as f:
#第1引数にファイルオブジェクトを、第2引数にフィールド名のリストを指定する。
writer = csv.DictWriter(f, ['url', 'title'])
writer.writeheader() #1行目のヘッダーを出力する
#writerows()で複数の行を1度に出力する。引数は辞書のリスト。
writer.writerows(books)
#pythonコマンドで実行された場合にmain()関数を呼び出す。これはモジュールとして他のファイルから
#インポートされたときに、mail()関数が実行されないようにするための、pythonにおける一般的なイディオム。
if __name__ == '__main__':
main()
|
17f0ed42a9f3b1bb9d7ec6fa25aa6fb1915e08d1
|
dev2404/Babber_List
|
/heap4.py
| 347 | 3.515625 | 4 |
import heapq as hp
def kLargest(arr, n, k):
# code here
q = []
for i in range(n):
hp.heappush(q, arr[i])
if len(q) > k:
hp.heappop(q)
q.sort(reverse=True)
return q[-1]
#[hp._heappop_max(q) for i in range(len(q))]
N = 7
K = 3
Arr = [1, 23, 12, 9, 30, 2, 50, 89]
print(kLargest(Arr, N, K))
|
f136808d4f9f2e6bc029dd6034841761557a10cb
|
dev2404/Babber_List
|
/three_sum.py
| 824 | 3.578125 | 4 |
# solution-1
def triplet(arr, n, k):
count = 0
for i in range(0, n-2):
for j in range(i+1, n-1):
for x in range(j+1, n):
if arr[i]+arr[j]+arr[x] == k:
return 1
return 0
# Solution-2
def triplet(arr, n, k):
count = 0
arr.sort()
for i in range(0, n-2):
left = i+1
right = n-1
while left < right:
if arr[i]+arr[left]+arr[right] == k:
return 1
elif arr[i]+arr[left]+arr[right] < k:
left += 1
else:
right -= 1
return 0
T = int(input())
for i in range(T):
n, k = list(map(int, input().split()))
arr = list(map(int, input().split()))
print(triplet(arr, n, k))
|
dff4a52d4660596cf585512cf527b27ea21a686f
|
dev2404/Babber_List
|
/heap.py
| 671 | 3.734375 | 4 |
def heapify(arr, i):
largest = i
left = (2 * i) + 1
right = (2 * i) + 2
if left < len(arr) and arr[left] > arr[largest]:
largest = left
if right < len(arr) and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[largest], arr[i] = arr[i], arr[largest]
heapify(arr, largest)
def buildHeap(arr, n):
startind = n//2 - 1
for i in range(startind, -1, -1):
heapify(arr, i)
def printHeap(arr, n):
for i in range(n):
print(arr[i], end=" ")
print()
arr = [ 1, 3, 5, 4, 6, 13,10, 9, 8, 15, 17 ];
n = len(arr);
buildHeap(arr, n);
printHeap(arr, n);
|
51ae8c3f304209e5d867be6d3fbf13a6d9fa4778
|
dev2404/Babber_List
|
/dublicate.py
| 422 | 3.53125 | 4 |
def findDuplicate(self, nums: List[int]) -> int:
# X = set(nums)
# for i in X:
# if nums.count(i) > 1:
# return i
# for i in range(len(nums)):
# x = nums.pop(0)
# if x in nums:
# return x
while nums[nums[0]] != nums[0]:
nums[nums[0]], nums[0] = nums[0], nums[nums[0]]
return nums[0]
|
d00e37f34de2103a220f1fc5f15009c1a5ed2013
|
wlsanders/dsp
|
/python/advanced_python_regex.py
| 2,022 | 4.09375 | 4 |
# Q1. Find how many different degrees there are, and their frequencies: Ex: PhD, ScD, MD, MPH, BSEd, MS, JD, etcimport csv
#
import csv
facultyFile = open('faculty.csv')
facultyReader = csv.reader(facultyFile)
facultyData = list(facultyReader)
def differentDegrees(facultyData):
degreeType = []
count = 0
for row in facultyData:
# print row
if row[1] not in degreeType and count > 0:
degreeType.append(row[1])
count += 1
return degreeType
degreeTypes = differentDegrees(facultyData)
# print degreeTypes
def cleaningDegreeTypes(degreeTypes):
degreeList = dict()
# print degreeTypes
for degree in degreeTypes:
a = degree.replace('.', "")
if " " not in a:
if a not in degreeList:
degreeList[a] = 1
else:
degreeList[a] += 1
# print degreeList, "list"
else:
delimiter = ' '
b = a.split(delimiter)
for degree in b:
if degree not in degreeList:
degreeList[degree] = 1
else:
degreeList[degree] += 1
return degreeList
cleaningDegreeTypes(degreeTypes)
"""
QUESTION 2: FIND HOW MANY DIFFERENT TITLES THERE ARE, AND THEIR FREQUENCIES
"""
def differentTitles(facultyData):
count = 0
titleDict = dict()
for row in facultyData:
# print row
title = row[2]
if count > 0:
if title not in titleDict:
titleDict[title] = 1
else:
titleDict[title] += 1
count += 1
return titleDict
# print differentTitles(facultyData)
"""
QUESTION 3
"""
def differentEmails(facultyData):
differentEmails = []
count = 0
for row in facultyData:
# print row
if row[3] not in differentEmails and count > 0:
differentEmails.append(row[3])
count += 1
return differentEmails
emails = differentEmails(facultyData)
""" Question 4"""
def differentDomains(emailList):
emailDict = dict()
for email in emailList:
print email
addr = email
uname, domain = addr.split('@')
if domain not in emailDict:
emailDict[domain] = 1
else:
emailDict[domain] += 1
print len(emailDict)
return emailDict
print differentDomains(emails)
|
cfdd6598e2c3adcfea9b5e9a9a4e7cff38ababdb
|
commutatif/ctf_2019
|
/challs/123-anticaptcha-et-vernam/guess.py
| 1,449 | 3.609375 | 4 |
#!/usr/bin/env python3
from random import choice
from string import ascii_lowercase
# on peut deviner KEY_LENGTH en chiffrant plein de fois la même minuscule
KEY_LENGTH = 6
TXT = "aaaaaaaaaaaaaaaaaaaaaaaaaaaa"
C = [
"g:ydkzunydkzunydkzunydkzunydkz",
"h:zunydkzunydkzunydkzunydkzuny",
"f:xmhalqxmhalqxmhalqxmhalqxmha"
]
def gen_random_str(n):
return "".join(choice(ascii_lowercase) for _ in range(n))
def keep_lower_only(str):
return "".join([c for c in str if ord("a") <= ord(c) <= ord("z")])
def shift_char(c, n):
if ord("a") <= ord(c) <= ord("z"):
return to_char((from_char(c) + n) % 26)
else:
return c
def from_char(c):
return ord(c) - ord("a")
def to_char(i):
return chr(i + ord("a"))
def xor(str1, str2):
if len(str1) != len(str2):
raise Exception("str length")
return "".join([to_char((from_char(str1[i]) ^ from_char(str2[i])) % 26) for i in range(len(str1))])
def xor2(str1, str2):
if len(str1) != len(str2):
raise Exception("str length")
return "".join([to_char((from_char(str1[i]) - from_char(str2[i])) % 26) for i in range(len(str1))])
def shift_str(str, n):
return "".join([shift_char(c, n) for c in str])
def remove_nonce(m):
v = from_char(m[0]) * (-1)
return "".join([shift_char(c, v) for c in m[2:]])
if __name__ == "__main__":
if len(TXT) < KEY_LENGTH:
raise Exception("txt length")
for j in range(len(C)):
if len(C[j]) - 2 != len(TXT):
raise Exception("C{} length".format(j))
|
7f37652057d62733f72c52572916954f098693e6
|
lupetimayaraturbiani/EstudoPython
|
/Ex_EstruturaSequencial/ex6.py
| 166 | 3.828125 | 4 |
# -*- coding: utf-8 -*-
l = int(input("Informe a medida do lado do quadrado: "))
area = l * l
print("O dobro da medida da área do quadrado é de " + str(area * 2))
|
66daf6e7b080b52000fb5b7c5056bf89cd6d7891
|
lupetimayaraturbiani/EstudoPython
|
/Ex_EstruturaSequencial/ex5.py
| 169 | 4 | 4 |
# -*- coding: utf-8 -*-
r = float(input("Digite o valor do raio do círculo: "))
area_c = 2 * 3.14 * r
print("A área do círculo corresponde a: " + str(area_c) + ".")
|
f9de5ebacd27919f7966554c3597d56f2c0e2e05
|
chaminnk/Project-Euler
|
/20)sum of digits of 100!.py
| 231 | 3.65625 | 4 |
import time
start = time.time()
total = 1
for num in range(1,100):
total*=num #getting 100!
total2 = 0
for digit in str(total):
total2+=int(digit) #getting sum of digits in 100!
print total2
print (time.time() - start),'s'
|
5c94921ebb2ef33abac1c369670d5f878cbd2aa2
|
hscannell/MHW-tableau
|
/code/LSTM/marineHeatWaves.py
| 44,481 | 3.53125 | 4 |
'''
A set of functions which implement the Marine Heat Wave (MHW)
definition of Hobday et al. (2016)
'''
import numpy as np
import scipy as sp
from scipy import linalg
from scipy import stats
import scipy.ndimage as ndimage
from datetime import date
def detect(t, temp, climatologyPeriod=[None,None], pctile=90, windowHalfWidth=5, smoothPercentile=True, smoothPercentileWidth=31, minDuration=5, joinAcrossGaps=True, maxGap=2, maxPadLength=False, coldSpells=False, alternateClimatology=False):
'''
Applies the Hobday et al. (2016) marine heat wave definition to an input time
series of temp ('temp') along with a time vector ('t'). Outputs properties of
all detected marine heat waves.
Inputs:
t Time vector, in datetime format (e.g., date(1982,1,1).toordinal())
[1D numpy array of length T]
temp Temperature vector [1D numpy array of length T]
Outputs:
mhw Detected marine heat waves (MHWs). Each key (following list) is a
list of length N where N is the number of detected MHWs:
'time_start' Start time of MHW [datetime format]
'time_end' End time of MHW [datetime format]
'time_peak' Time of MHW peak [datetime format]
'date_start' Start date of MHW [datetime format]
'date_end' End date of MHW [datetime format]
'date_peak' Date of MHW peak [datetime format]
'index_start' Start index of MHW
'index_end' End index of MHW
'index_peak' Index of MHW peak
'duration' Duration of MHW [days]
'intensity_max' Maximum (peak) intensity [deg. C]
'intensity_mean' Mean intensity [deg. C]
'intensity_var' Intensity variability [deg. C]
'intensity_cumulative' Cumulative intensity [deg. C x days]
'rate_onset' Onset rate of MHW [deg. C / days]
'rate_decline' Decline rate of MHW [deg. C / days]
'intensity_max_relThresh', 'intensity_mean_relThresh', 'intensity_var_relThresh',
and 'intensity_cumulative_relThresh' are as above except relative to the
threshold (e.g., 90th percentile) rather than the seasonal climatology
'intensity_max_abs', 'intensity_mean_abs', 'intensity_var_abs', and
'intensity_cumulative_abs' are as above except as absolute magnitudes
rather than relative to the seasonal climatology or threshold
'category' is an integer category system (1, 2, 3, 4) based on the maximum intensity
in multiples of threshold exceedances, i.e., a value of 1 indicates the MHW
intensity (relative to the climatology) was >=1 times the value of the threshold (but
less than 2 times; relative to climatology, i.e., threshold - climatology).
Category types are defined as 1=strong, 2=moderate, 3=severe, 4=extreme. More details in
Hobday et al. (in prep., Oceanography). Also supplied are the duration of each of these
categories for each event.
'n_events' A scalar integer (not a list) indicating the total
number of detected MHW events
clim Climatology of SST. Each key (following list) is a seasonally-varying
time series [1D numpy array of length T] of a particular measure:
'thresh' Seasonally varying threshold (e.g., 90th percentile)
'seas' Climatological seasonal cycle
'missing' A vector of TRUE/FALSE indicating which elements in
temp were missing values for the MHWs detection
Options:
climatologyPeriod Period over which climatology is calculated, specified
as list of start and end years. Default is to calculate
over the full range of years in the supplied time series.
Alternate periods suppled as a list e.g. [1983,2012].
pctile Threshold percentile (%) for detection of extreme values
(DEFAULT = 90)
windowHalfWidth Width of window (one sided) about day-of-year used for
the pooling of values and calculation of threshold percentile
(DEFAULT = 5 [days])
smoothPercentile Boolean switch indicating whether to smooth the threshold
percentile timeseries with a moving average (DEFAULT = True)
smoothPercentileWidth Width of moving average window for smoothing threshold
(DEFAULT = 31 [days])
minDuration Minimum duration for acceptance detected MHWs
(DEFAULT = 5 [days])
joinAcrossGaps Boolean switch indicating whether to join MHWs
which occur before/after a short gap (DEFAULT = True)
maxGap Maximum length of gap allowed for the joining of MHWs
(DEFAULT = 2 [days])
maxPadLength Specifies the maximum length [days] over which to interpolate
(pad) missing data (specified as nans) in input temp time series.
i.e., any consecutive blocks of NaNs with length greater
than maxPadLength will be left as NaN. Set as an integer.
(DEFAULT = False, interpolates over all missing values).
coldSpells Specifies if the code should detect cold events instead of
heat events. (DEFAULT = False)
alternateClimatology Specifies an alternate temperature time series to use for the
calculation of the climatology. Format is as a list of numpy
arrays: (1) the first element of the list is a time vector,
in datetime format (e.g., date(1982,1,1).toordinal())
[1D numpy array of length TClim] and (2) the second element of
the list is a temperature vector [1D numpy array of length TClim].
(DEFAULT = False)
Notes:
1. This function assumes that the input time series consist of continuous daily values
with few missing values. Time ranges which start and end part-way through the calendar
year are supported.
2. This function supports leap years. This is done by ignoring Feb 29s for the initial
calculation of the climatology and threshold. The value of these for Feb 29 is then
linearly interpolated from the values for Feb 28 and Mar 1.
3. The calculation of onset and decline rates assumes that the heat wave started a half-day
before the start day and ended a half-day after the end-day. (This is consistent with the
duration definition as implemented, which assumes duration = end day - start day + 1.)
4. For the purposes of MHW detection, any missing temp values not interpolated over (through
optional maxPadLLength) will be set equal to the seasonal climatology. This means they will
trigger the end/start of any adjacent temp values which satisfy the MHW criteria.
5. If the code is used to detect cold events (coldSpells = True), then it works just as for heat
waves except that events are detected as deviations below the (100 - pctile)th percentile
(e.g., the 10th instead of 90th) for at least 5 days. Intensities are reported as negative
values and represent the temperature anomaly below climatology.
Written by Eric Oliver, Institue for Marine and Antarctic Studies, University of Tasmania, Feb 2015
'''
#
# Initialize MHW output variable
#
mhw = {}
mhw['time_start'] = [] # datetime format
mhw['time_end'] = [] # datetime format
mhw['time_peak'] = [] # datetime format
mhw['date_start'] = [] # datetime format
mhw['date_end'] = [] # datetime format
mhw['date_peak'] = [] # datetime format
mhw['index_start'] = []
mhw['index_end'] = []
mhw['index_peak'] = []
mhw['duration'] = [] # [days]
mhw['duration_moderate'] = [] # [days]
mhw['duration_strong'] = [] # [days]
mhw['duration_severe'] = [] # [days]
mhw['duration_extreme'] = [] # [days]
mhw['intensity_max'] = [] # [deg C]
mhw['intensity_mean'] = [] # [deg C]
mhw['intensity_var'] = [] # [deg C]
mhw['intensity_cumulative'] = [] # [deg C]
mhw['intensity_max_relThresh'] = [] # [deg C]
mhw['intensity_mean_relThresh'] = [] # [deg C]
mhw['intensity_var_relThresh'] = [] # [deg C]
mhw['intensity_cumulative_relThresh'] = [] # [deg C]
mhw['intensity_max_abs'] = [] # [deg C]
mhw['intensity_mean_abs'] = [] # [deg C]
mhw['intensity_var_abs'] = [] # [deg C]
mhw['intensity_cumulative_abs'] = [] # [deg C]
mhw['category'] = []
mhw['rate_onset'] = [] # [deg C / day]
mhw['rate_decline'] = [] # [deg C / day]
#
# Time and dates vectors
#
# Generate vectors for year, month, day-of-month, and day-of-year
T = len(t)
year = np.zeros((T))
month = np.zeros((T))
day = np.zeros((T))
doy = np.zeros((T))
for i in range(len(t)):
year[i] = date.fromordinal(t[i]).year
month[i] = date.fromordinal(t[i]).month
day[i] = date.fromordinal(t[i]).day
# Leap-year baseline for defining day-of-year values
year_leapYear = 2012 # This year was a leap-year and therefore doy in range of 1 to 366
t_leapYear = np.arange(date(year_leapYear, 1, 1).toordinal(),date(year_leapYear, 12, 31).toordinal()+1)
dates_leapYear = [date.fromordinal(tt.astype(int)) for tt in t_leapYear]
month_leapYear = np.zeros((len(t_leapYear)))
day_leapYear = np.zeros((len(t_leapYear)))
doy_leapYear = np.zeros((len(t_leapYear)))
for tt in range(len(t_leapYear)):
month_leapYear[tt] = date.fromordinal(t_leapYear[tt]).month
day_leapYear[tt] = date.fromordinal(t_leapYear[tt]).day
doy_leapYear[tt] = t_leapYear[tt] - date(date.fromordinal(t_leapYear[tt]).year,1,1).toordinal() + 1
# Calculate day-of-year values
for tt in range(T):
doy[tt] = doy_leapYear[(month_leapYear == month[tt]) * (day_leapYear == day[tt])]
# Constants (doy values for Feb-28 and Feb-29) for handling leap-years
feb28 = 59
feb29 = 60
# Set climatology period, if unset use full range of available data
if (climatologyPeriod[0] is None) or (climatologyPeriod[1] is None):
climatologyPeriod[0] = year[0]
climatologyPeriod[1] = year[-1]
#
# Calculate threshold and seasonal climatology (varying with day-of-year)
#
# if alternate temperature time series is supplied for the calculation of the climatology
if alternateClimatology:
tClim = alternateClimatology[0]
tempClim = alternateClimatology[1]
TClim = len(tClim)
yearClim = np.zeros((TClim))
monthClim = np.zeros((TClim))
dayClim = np.zeros((TClim))
doyClim = np.zeros((TClim))
for i in range(TClim):
yearClim[i] = date.fromordinal(tClim[i]).year
monthClim[i] = date.fromordinal(tClim[i]).month
dayClim[i] = date.fromordinal(tClim[i]).day
doyClim[i] = doy_leapYear[(month_leapYear == monthClim[i]) * (day_leapYear == dayClim[i])]
else:
tempClim = temp.copy()
TClim = np.array([T]).copy()[0]
yearClim = year.copy()
monthClim = month.copy()
dayClim = day.copy()
doyClim = doy.copy()
# Flip temp time series if detecting cold spells
if coldSpells:
temp = -1.*temp
tempClim = -1.*tempClim
# Pad missing values for all consecutive missing blocks of length <= maxPadLength
if maxPadLength:
temp = pad(temp, maxPadLength=maxPadLength)
tempClim = pad(tempClim, maxPadLength=maxPadLength)
# Length of climatological year
lenClimYear = 366
# Start and end indices
clim_start = np.where(yearClim == climatologyPeriod[0])[0][0]
clim_end = np.where(yearClim == climatologyPeriod[1])[0][-1]
# Inialize arrays
thresh_climYear = np.NaN*np.zeros(lenClimYear)
seas_climYear = np.NaN*np.zeros(lenClimYear)
clim = {}
clim['thresh'] = np.NaN*np.zeros(TClim)
clim['seas'] = np.NaN*np.zeros(TClim)
# Loop over all day-of-year values, and calculate threshold and seasonal climatology across years
for d in range(1,lenClimYear+1):
# Special case for Feb 29
if d == feb29:
continue
# find all indices for each day of the year +/- windowHalfWidth and from them calculate the threshold
tt0 = np.where(doyClim[clim_start:clim_end+1] == d)[0]
# If this doy value does not exist (i.e. in 360-day calendars) then skip it
if len(tt0) == 0:
continue
tt = np.array([])
for w in range(-windowHalfWidth, windowHalfWidth+1):
tt = np.append(tt, clim_start+tt0 + w)
tt = tt[tt>=0] # Reject indices "before" the first element
tt = tt[tt<TClim] # Reject indices "after" the last element
thresh_climYear[d-1] = np.percentile(nonans(tempClim[tt.astype(int)]), pctile)
seas_climYear[d-1] = np.mean(nonans(tempClim[tt.astype(int)]))
# Special case for Feb 29
thresh_climYear[feb29-1] = 0.5*thresh_climYear[feb29-2] + 0.5*thresh_climYear[feb29]
seas_climYear[feb29-1] = 0.5*seas_climYear[feb29-2] + 0.5*seas_climYear[feb29]
# Smooth if desired
if smoothPercentile:
# If the climatology contains NaNs, then assume it is a <365-day year and deal accordingly
if np.sum(np.isnan(seas_climYear)) + np.sum(np.isnan(thresh_climYear)):
valid = ~np.isnan(thresh_climYear)
thresh_climYear[valid] = runavg(thresh_climYear[valid], smoothPercentileWidth)
valid = ~np.isnan(seas_climYear)
seas_climYear[valid] = runavg(seas_climYear[valid], smoothPercentileWidth)
# >= 365-day year
else:
thresh_climYear = runavg(thresh_climYear, smoothPercentileWidth)
seas_climYear = runavg(seas_climYear, smoothPercentileWidth)
# Generate threshold for full time series
clim['thresh'] = thresh_climYear[doy.astype(int)-1]
clim['seas'] = seas_climYear[doy.astype(int)-1]
# Save vector indicating which points in temp are missing values
clim['missing'] = np.isnan(temp)
# Set all remaining missing temp values equal to the climatology
temp[np.isnan(temp)] = clim['seas'][np.isnan(temp)]
#
# Find MHWs as exceedances above the threshold
#
# Time series of "True" when threshold is exceeded, "False" otherwise
exceed_bool = temp - clim['thresh']
exceed_bool[exceed_bool<=0] = False
exceed_bool[exceed_bool>0] = True
# Find contiguous regions of exceed_bool = True
events, n_events = ndimage.label(exceed_bool)
# Find all MHW events of duration >= minDuration
for ev in range(1,n_events+1):
event_duration = (events == ev).sum()
if event_duration < minDuration:
continue
mhw['time_start'].append(t[np.where(events == ev)[0][0]])
mhw['time_end'].append(t[np.where(events == ev)[0][-1]])
# Link heat waves that occur before and after a short gap (gap must be no longer than maxGap)
if joinAcrossGaps:
# Calculate gap length for each consecutive pair of events
gaps = np.array(mhw['time_start'][1:]) - np.array(mhw['time_end'][0:-1]) - 1
if len(gaps) > 0:
while gaps.min() <= maxGap:
# Find first short gap
ev = np.where(gaps <= maxGap)[0][0]
# Extend first MHW to encompass second MHW (including gap)
mhw['time_end'][ev] = mhw['time_end'][ev+1]
# Remove second event from record
del mhw['time_start'][ev+1]
del mhw['time_end'][ev+1]
# Calculate gap length for each consecutive pair of events
gaps = np.array(mhw['time_start'][1:]) - np.array(mhw['time_end'][0:-1]) - 1
if len(gaps) == 0:
break
# Calculate marine heat wave properties
mhw['n_events'] = len(mhw['time_start'])
categories = np.array(['Moderate', 'Strong', 'Severe', 'Extreme'])
for ev in range(mhw['n_events']):
mhw['date_start'].append(date.fromordinal(int(mhw['time_start'][ev])))
mhw['date_end'].append(date.fromordinal(int(mhw['time_end'][ev])))
# Get SST series during MHW event, relative to both threshold and to seasonal climatology
tt_start = np.where(t==mhw['time_start'][ev])[0][0]
tt_end = np.where(t==mhw['time_end'][ev])[0][0]
mhw['index_start'].append(tt_start)
mhw['index_end'].append(tt_end)
temp_mhw = temp[tt_start:tt_end+1]
thresh_mhw = clim['thresh'][tt_start:tt_end+1]
seas_mhw = clim['seas'][tt_start:tt_end+1]
mhw_relSeas = temp_mhw - seas_mhw
mhw_relThresh = temp_mhw - thresh_mhw
mhw_relThreshNorm = (temp_mhw - thresh_mhw) / (thresh_mhw - seas_mhw)
mhw_abs = temp_mhw
# Find peak
tt_peak = np.argmax(mhw_relSeas)
mhw['time_peak'].append(mhw['time_start'][ev] + tt_peak)
mhw['date_peak'].append(date.fromordinal(int(mhw['time_start'][ev] + tt_peak)))
mhw['index_peak'].append(tt_start + tt_peak)
# MHW Duration
mhw['duration'].append(len(mhw_relSeas))
# MHW Intensity metrics
mhw['intensity_max'].append(mhw_relSeas[tt_peak])
mhw['intensity_mean'].append(mhw_relSeas.mean())
mhw['intensity_var'].append(np.sqrt(mhw_relSeas.var()))
mhw['intensity_cumulative'].append(mhw_relSeas.sum())
mhw['intensity_max_relThresh'].append(mhw_relThresh[tt_peak])
mhw['intensity_mean_relThresh'].append(mhw_relThresh.mean())
mhw['intensity_var_relThresh'].append(np.sqrt(mhw_relThresh.var()))
mhw['intensity_cumulative_relThresh'].append(mhw_relThresh.sum())
mhw['intensity_max_abs'].append(mhw_abs[tt_peak])
mhw['intensity_mean_abs'].append(mhw_abs.mean())
mhw['intensity_var_abs'].append(np.sqrt(mhw_abs.var()))
mhw['intensity_cumulative_abs'].append(mhw_abs.sum())
# Fix categories
tt_peakCat = np.argmax(mhw_relThreshNorm)
cats = np.floor(1. + mhw_relThreshNorm)
mhw['category'].append(categories[np.min([cats[tt_peakCat], 4]).astype(int) - 1])
mhw['duration_moderate'].append(np.sum(cats == 1.))
mhw['duration_strong'].append(np.sum(cats == 2.))
mhw['duration_severe'].append(np.sum(cats == 3.))
mhw['duration_extreme'].append(np.sum(cats >= 4.))
# Rates of onset and decline
# Requires getting MHW strength at "start" and "end" of event (continuous: assume start/end half-day before/after first/last point)
if tt_start > 0:
mhw_relSeas_start = 0.5*(mhw_relSeas[0] + temp[tt_start-1] - clim['seas'][tt_start-1])
mhw['rate_onset'].append((mhw_relSeas[tt_peak] - mhw_relSeas_start) / (tt_peak+0.5))
else: # MHW starts at beginning of time series
if tt_peak == 0: # Peak is also at begining of time series, assume onset time = 1 day
mhw['rate_onset'].append((mhw_relSeas[tt_peak] - mhw_relSeas[0]) / 1.)
else:
mhw['rate_onset'].append((mhw_relSeas[tt_peak] - mhw_relSeas[0]) / tt_peak)
if tt_end < T-1:
mhw_relSeas_end = 0.5*(mhw_relSeas[-1] + temp[tt_end+1] - clim['seas'][tt_end+1])
mhw['rate_decline'].append((mhw_relSeas[tt_peak] - mhw_relSeas_end) / (tt_end-tt_start-tt_peak+0.5))
else: # MHW finishes at end of time series
if tt_peak == T-1: # Peak is also at end of time series, assume decline time = 1 day
mhw['rate_decline'].append((mhw_relSeas[tt_peak] - mhw_relSeas[-1]) / 1.)
else:
mhw['rate_decline'].append((mhw_relSeas[tt_peak] - mhw_relSeas[-1]) / (tt_end-tt_start-tt_peak))
# Flip climatology and intensties in case of cold spell detection
if coldSpells:
clim['seas'] = -1.*clim['seas']
clim['thresh'] = -1.*clim['thresh']
for ev in range(len(mhw['intensity_max'])):
mhw['intensity_max'][ev] = -1.*mhw['intensity_max'][ev]
mhw['intensity_mean'][ev] = -1.*mhw['intensity_mean'][ev]
mhw['intensity_cumulative'][ev] = -1.*mhw['intensity_cumulative'][ev]
mhw['intensity_max_relThresh'][ev] = -1.*mhw['intensity_max_relThresh'][ev]
mhw['intensity_mean_relThresh'][ev] = -1.*mhw['intensity_mean_relThresh'][ev]
mhw['intensity_cumulative_relThresh'][ev] = -1.*mhw['intensity_cumulative_relThresh'][ev]
mhw['intensity_max_abs'][ev] = -1.*mhw['intensity_max_abs'][ev]
mhw['intensity_mean_abs'][ev] = -1.*mhw['intensity_mean_abs'][ev]
mhw['intensity_cumulative_abs'][ev] = -1.*mhw['intensity_cumulative_abs'][ev]
return mhw, clim
def blockAverage(t, mhw, clim=None, blockLength=1, removeMissing=False, temp=None):
'''
Calculate statistics of marine heatwave (MHW) properties averaged over blocks of
a specified length of time. Takes as input a collection of detected MHWs
(using the marineHeatWaves.detect function) and a time vector for the source
SST series.
Inputs:
t Time vector, in datetime format (e.g., date(1982,1,1).toordinal())
mhw Marine heat waves (MHWs) detected using marineHeatWaves.detect
Outputs:
mhwBlock Time series of block-averaged MHW properties. Each key (following list)
is a list of length N where N is the number of blocks:
'years_start' Start year blocks (inclusive)
'years_end' End year of blocks (inclusive)
'years_centre' Decimal year at centre of blocks
'count' Total MHW count in each block
'duration' Average MHW duration in each block [days]
'intensity_max' Average MHW "maximum (peak) intensity" in each block [deg. C]
'intensity_max_max' Maximum MHW "maximum (peak) intensity" in each block [deg. C]
'intensity_mean' Average MHW "mean intensity" in each block [deg. C]
'intensity_var' Average MHW "intensity variability" in each block [deg. C]
'intensity_cumulative' Average MHW "cumulative intensity" in each block [deg. C x days]
'rate_onset' Average MHW onset rate in each block [deg. C / days]
'rate_decline' Average MHW decline rate in each block [deg. C / days]
'total_days' Total number of MHW days in each block [days]
'total_icum' Total cumulative intensity over all MHWs in each block [deg. C x days]
'intensity_max_relThresh', 'intensity_mean_relThresh', 'intensity_var_relThresh',
and 'intensity_cumulative_relThresh' are as above except relative to the
threshold (e.g., 90th percentile) rather than the seasonal climatology
'intensity_max_abs', 'intensity_mean_abs', 'intensity_var_abs', and
'intensity_cumulative_abs' are as above except as absolute magnitudes
rather than relative to the seasonal climatology or threshold
Options:
blockLength Size of block (in years) over which to calculate the
averaged MHW properties. Must be an integer greater than
or equal to 1 (DEFAULT = 1 [year])
removeMissing Boolean switch indicating whether to remove (set = NaN)
statistics for any blocks in which there were missing
temperature values (DEFAULT = FALSE)
clim The temperature climatology (including missing value information)
as output by marineHeatWaves.detect (required if removeMissing = TRUE)
temp Temperature time series. If included mhwBlock will output block
averages of mean, max, and min temperature (DEFAULT = NONE)
If both clim and temp are provided, this will output annual counts
of moderate, strong, severe, and extreme days.
Notes:
This function assumes that the input time vector consists of continuous daily values. Note that
in the case of time ranges which start and end part-way through the calendar year, the block
averages at the endpoints, for which there is less than a block length of data, will need to be
interpreted with care.
Written by Eric Oliver, Institue for Marine and Antarctic Studies, University of Tasmania, Feb-Mar 2015
'''
#
# Time and dates vectors, and calculate block timing
#
# Generate vectors for year, month, day-of-month, and day-of-year
T = len(t)
year = np.zeros((T))
month = np.zeros((T))
day = np.zeros((T))
for i in range(T):
year[i] = date.fromordinal(t[i]).year
month[i] = date.fromordinal(t[i]).month
day[i] = date.fromordinal(t[i]).day
# Number of blocks, round up to include partial blocks at end
years = np.unique(year)
nBlocks = np.ceil((years.max() - years.min() + 1) / blockLength).astype(int)
#
# Temperature time series included?
#
sw_temp = None
sw_cats = None
if temp is not None:
sw_temp = True
if clim is not None:
sw_cats = True
else:
sw_cats = False
else:
sw_temp = False
#
# Initialize MHW output variable
#
mhwBlock = {}
mhwBlock['count'] = np.zeros(nBlocks)
mhwBlock['count'] = np.zeros(nBlocks)
mhwBlock['duration'] = np.zeros(nBlocks)
mhwBlock['intensity_max'] = np.zeros(nBlocks)
mhwBlock['intensity_max_max'] = np.zeros(nBlocks)
mhwBlock['intensity_mean'] = np.zeros(nBlocks)
mhwBlock['intensity_cumulative'] = np.zeros(nBlocks)
mhwBlock['intensity_var'] = np.zeros(nBlocks)
mhwBlock['intensity_max_relThresh'] = np.zeros(nBlocks)
mhwBlock['intensity_mean_relThresh'] = np.zeros(nBlocks)
mhwBlock['intensity_cumulative_relThresh'] = np.zeros(nBlocks)
mhwBlock['intensity_var_relThresh'] = np.zeros(nBlocks)
mhwBlock['intensity_max_abs'] = np.zeros(nBlocks)
mhwBlock['intensity_mean_abs'] = np.zeros(nBlocks)
mhwBlock['intensity_cumulative_abs'] = np.zeros(nBlocks)
mhwBlock['intensity_var_abs'] = np.zeros(nBlocks)
mhwBlock['rate_onset'] = np.zeros(nBlocks)
mhwBlock['rate_decline'] = np.zeros(nBlocks)
mhwBlock['total_days'] = np.zeros(nBlocks)
mhwBlock['total_icum'] = np.zeros(nBlocks)
if sw_temp:
mhwBlock['temp_mean'] = np.zeros(nBlocks)
mhwBlock['temp_max'] = np.zeros(nBlocks)
mhwBlock['temp_min'] = np.zeros(nBlocks)
# Calculate category days
if sw_cats:
mhwBlock['moderate_days'] = np.zeros(nBlocks)
mhwBlock['strong_days'] = np.zeros(nBlocks)
mhwBlock['severe_days'] = np.zeros(nBlocks)
mhwBlock['extreme_days'] = np.zeros(nBlocks)
cats = np.floor(1 + (temp - clim['thresh']) / (clim['thresh'] - clim['seas']))
mhwIndex = np.zeros(t.shape)
for ev in range(mhw['n_events']):
mhwIndex[mhw['index_start'][ev]:mhw['index_end'][ev]+1] = 1.
# Start, end, and centre years for all blocks
mhwBlock['years_start'] = years[range(0, len(years), blockLength)]
mhwBlock['years_end'] = mhwBlock['years_start'] + blockLength - 1
mhwBlock['years_centre'] = 0.5*(mhwBlock['years_start'] + mhwBlock['years_end'])
#
# Calculate block averages
#
for i in range(mhw['n_events']):
# Block index for year of each MHW (MHW year defined by start year)
iBlock = np.where((mhwBlock['years_start'] <= mhw['date_start'][i].year) * (mhwBlock['years_end'] >= mhw['date_start'][i].year))[0][0]
# Add MHW properties to block count
mhwBlock['count'][iBlock] += 1
mhwBlock['duration'][iBlock] += mhw['duration'][i]
mhwBlock['intensity_max'][iBlock] += mhw['intensity_max'][i]
mhwBlock['intensity_max_max'][iBlock] = np.max([mhwBlock['intensity_max_max'][iBlock], mhw['intensity_max'][i]])
mhwBlock['intensity_mean'][iBlock] += mhw['intensity_mean'][i]
mhwBlock['intensity_cumulative'][iBlock] += mhw['intensity_cumulative'][i]
mhwBlock['intensity_var'][iBlock] += mhw['intensity_var'][i]
mhwBlock['intensity_max_relThresh'][iBlock] += mhw['intensity_max_relThresh'][i]
mhwBlock['intensity_mean_relThresh'][iBlock] += mhw['intensity_mean_relThresh'][i]
mhwBlock['intensity_cumulative_relThresh'][iBlock] += mhw['intensity_cumulative_relThresh'][i]
mhwBlock['intensity_var_relThresh'][iBlock] += mhw['intensity_var_relThresh'][i]
mhwBlock['intensity_max_abs'][iBlock] += mhw['intensity_max_abs'][i]
mhwBlock['intensity_mean_abs'][iBlock] += mhw['intensity_mean_abs'][i]
mhwBlock['intensity_cumulative_abs'][iBlock] += mhw['intensity_cumulative_abs'][i]
mhwBlock['intensity_var_abs'][iBlock] += mhw['intensity_var_abs'][i]
mhwBlock['rate_onset'][iBlock] += mhw['rate_onset'][i]
mhwBlock['rate_decline'][iBlock] += mhw['rate_decline'][i]
if mhw['date_start'][i].year == mhw['date_end'][i].year: # MHW in single year
mhwBlock['total_days'][iBlock] += mhw['duration'][i]
else: # MHW spans multiple years
year_mhw = year[mhw['index_start'][i]:mhw['index_end'][i]+1]
for yr_mhw in np.unique(year_mhw):
iBlock = np.where((mhwBlock['years_start'] <= yr_mhw) * (mhwBlock['years_end'] >= yr_mhw))[0][0]
mhwBlock['total_days'][iBlock] += np.sum(year_mhw == yr_mhw)
# NOTE: icum for a MHW is assigned to its start year, even if it spans mult. years
mhwBlock['total_icum'][iBlock] += mhw['intensity_cumulative'][i]
# Calculation of category days
if sw_cats:
for i in range(int(nBlocks)):
mhwBlock['moderate_days'][i] = ((year >= mhwBlock['years_start'][i]) * (year <= mhwBlock['years_end'][i]) * mhwIndex * (cats == 1)).astype(int).sum()
mhwBlock['strong_days'][i] = ((year >= mhwBlock['years_start'][i]) * (year <= mhwBlock['years_end'][i]) * mhwIndex * (cats == 2)).astype(int).sum()
mhwBlock['severe_days'][i] = ((year >= mhwBlock['years_start'][i]) * (year <= mhwBlock['years_end'][i]) * mhwIndex * (cats == 3)).astype(int).sum()
mhwBlock['extreme_days'][i] = ((year >= mhwBlock['years_start'][i]) * (year <= mhwBlock['years_end'][i]) * mhwIndex * (cats >= 4)).astype(int).sum()
# Calculate averages
count = 1.*mhwBlock['count']
count[count==0] = np.nan
mhwBlock['duration'] = mhwBlock['duration'] / count
mhwBlock['intensity_max'] = mhwBlock['intensity_max'] / count
mhwBlock['intensity_mean'] = mhwBlock['intensity_mean'] / count
mhwBlock['intensity_cumulative'] = mhwBlock['intensity_cumulative'] / count
mhwBlock['intensity_var'] = mhwBlock['intensity_var'] / count
mhwBlock['intensity_max_relThresh'] = mhwBlock['intensity_max_relThresh'] / count
mhwBlock['intensity_mean_relThresh'] = mhwBlock['intensity_mean_relThresh'] / count
mhwBlock['intensity_cumulative_relThresh'] = mhwBlock['intensity_cumulative_relThresh'] / count
mhwBlock['intensity_var_relThresh'] = mhwBlock['intensity_var_relThresh'] / count
mhwBlock['intensity_max_abs'] = mhwBlock['intensity_max_abs'] / count
mhwBlock['intensity_mean_abs'] = mhwBlock['intensity_mean_abs'] / count
mhwBlock['intensity_cumulative_abs'] = mhwBlock['intensity_cumulative_abs'] / count
mhwBlock['intensity_var_abs'] = mhwBlock['intensity_var_abs'] / count
mhwBlock['rate_onset'] = mhwBlock['rate_onset'] / count
mhwBlock['rate_decline'] = mhwBlock['rate_decline'] / count
# Replace empty years in intensity_max_max
mhwBlock['intensity_max_max'][np.isnan(mhwBlock['intensity_max'])] = np.nan
# Temperature series
if sw_temp:
for i in range(int(nBlocks)):
tt = (year >= mhwBlock['years_start'][i]) * (year <= mhwBlock['years_end'][i])
mhwBlock['temp_mean'][i] = np.nanmean(temp[tt])
mhwBlock['temp_max'][i] = np.nanmax(temp[tt])
mhwBlock['temp_min'][i] = np.nanmin(temp[tt])
#
# Remove years with missing values
#
if removeMissing:
missingYears = np.unique(year[np.where(clim['missing'])[0]])
for y in range(len(missingYears)):
iMissing = np.where((mhwBlock['years_start'] <= missingYears[y]) * (mhwBlock['years_end'] >= missingYears[y]))[0][0]
mhwBlock['count'][iMissing] = np.nan
mhwBlock['duration'][iMissing] = np.nan
mhwBlock['intensity_max'][iMissing] = np.nan
mhwBlock['intensity_max_max'][iMissing] = np.nan
mhwBlock['intensity_mean'][iMissing] = np.nan
mhwBlock['intensity_cumulative'][iMissing] = np.nan
mhwBlock['intensity_var'][iMissing] = np.nan
mhwBlock['intensity_max_relThresh'][iMissing] = np.nan
mhwBlock['intensity_mean_relThresh'][iMissing] = np.nan
mhwBlock['intensity_cumulative_relThresh'][iMissing] = np.nan
mhwBlock['intensity_var_relThresh'][iMissing] = np.nan
mhwBlock['intensity_max_abs'][iMissing] = np.nan
mhwBlock['intensity_mean_abs'][iMissing] = np.nan
mhwBlock['intensity_cumulative_abs'][iMissing] = np.nan
mhwBlock['intensity_var_abs'][iMissing] = np.nan
mhwBlock['rate_onset'][iMissing] = np.nan
mhwBlock['rate_decline'][iMissing] = np.nan
mhwBlock['total_days'][iMissing] = np.nan
if sw_cats:
mhwBlock['moderate_days'][iMissing] = np.nan
mhwBlock['strong_days'][iMissing] = np.nan
mhwBlock['severe_days'][iMissing] = np.nan
mhwBlock['extreme_days'][iMissing] = np.nan
mhwBlock['total_icum'][iMissing] = np.nan
return mhwBlock
def meanTrend(mhwBlock, alpha=0.05):
'''
Calculates the mean and trend of marine heatwave (MHW) properties. Takes as input a
collection of block-averaged MHW properties (using the marineHeatWaves.blockAverage
function). Handles missing values (which should be specified by NaNs).
Inputs:
mhwBlock Time series of block-averaged MHW statistics calculated using the
marineHeatWaves.blockAverage function
alpha Significance level for estimate of confidence limits on trend, e.g.,
alpha = 0.05 for 5% significance (or 95% confidence) (DEFAULT = 0.05)
Outputs:
mean Mean of all MHW properties over all block-averaged values
trend Linear trend of all MHW properties over all block-averaged values
dtrend One-sided width of (1-alpha)% confidence intevfal on linear trend,
i.e., trend lies within (trend-dtrend, trend+dtrend) with specified
level of confidence.
Both mean and trend have the following keys, the units the trend
are the units of the property of interest per year:
'duration' Duration of MHW [days]
'intensity_max' Maximum (peak) intensity [deg. C]
'intensity_mean' Mean intensity [deg. C]
'intensity_var' Intensity variability [deg. C]
'intensity_cumulative' Cumulative intensity [deg. C x days]
'rate_onset' Onset rate of MHW [deg. C / days]
'rate_decline' Decline rate of MHW [deg. C / days]
'intensity_max_relThresh', 'intensity_mean_relThresh', 'intensity_var_relThresh',
and 'intensity_cumulative_relThresh' are as above except relative to the
threshold (e.g., 90th percentile) rather than the seasonal climatology
'intensity_max_abs', 'intensity_mean_abs', 'intensity_var_abs', and
'intensity_cumulative_abs' are as above except as absolute magnitudes
rather than relative to the seasonal climatology or threshold
Notes:
This calculation performs a multiple linear regression of the form
y ~ beta * X + eps
where y is the MHW property of interest and X is a matrix of predictors. The first
column of X is all ones to estimate the mean, the second column is the time vector
which is taken as mhwBlock['years_centre'] and offset to be equal to zero at its
mid-point.
Written by Eric Oliver, Institue for Marine and Antarctic Studies, University of Tasmania, Feb-Mar 2015
'''
# Initialize mean and trend dictionaries
mean = {}
trend = {}
dtrend = {}
# Construct matrix of predictors, first column is all ones to estimate the mean,
# second column is the time vector, equal to zero at mid-point.
t = mhwBlock['years_centre']
X = np.array([np.ones(t.shape), t-t.mean()]).T
# Loop over all keys in mhwBlock
for key in mhwBlock.keys():
# Skip time-vector keys of mhwBlock
if (key == 'years_centre') + (key == 'years_end') + (key == 'years_start'):
continue
# Predictand (MHW property of interest)
y = mhwBlock[key]
valid = ~np.isnan(y) # non-NaN indices
# Perform linear regression over valid indices
if np.isinf(nonans(y).sum()): # If contains Inf values
beta = [np.nan, np.nan]
elif np.sum(~np.isnan(y)) > 0: # If at least one non-NaN value
beta = linalg.lstsq(X[valid,:], y[valid])[0]
else:
beta = [np.nan, np.nan]
# Insert regression coefficients into mean and trend dictionaries
mean[key] = beta[0]
trend[key] = beta[1]
# Confidence limits on trend
yhat = np.sum(beta*X, axis=1)
t_stat = stats.t.isf(alpha/2, len(t[valid])-2)
s = np.sqrt(np.sum((y[valid] - yhat[valid])**2) / (len(t[valid])-2))
Sxx = np.sum(X[valid,1]**2) - (np.sum(X[valid,1])**2)/len(t[valid]) # np.var(X, axis=1)[1]
dbeta1 = t_stat * s / np.sqrt(Sxx)
dtrend[key] = dbeta1
# Return mean, trend
return mean, trend, dtrend
def rank(t, mhw):
'''
Calculate the rank and return periods of marine heatwaves (MHWs) according to
each metric. Takes as input a collection of detected MHWs (using the
marineHeatWaves.detect function) and a time vector for the source SST series.
Inputs:
t Time vector, in datetime format (e.g., date(1982,1,1).toordinal())
mhw Marine heat waves (MHWs) detected using marineHeatWaves.detect
Outputs:
rank The rank of each MHW according to each MHW property. A rank of 1 is the
largest, 2 is the 2nd largest, etc. Each key (listed below) is a list
of length N where N is the number of MHWs.
returnPeriod The return period (in years) of each MHW according to each MHW property.
The return period signifies, statistically, the recurrence interval for
an event at least as large/long as the event in quetion. Each key (listed
below) is a list of length N where N is the number of MHWs.
'duration' Average MHW duration in each block [days]
'intensity_max' Average MHW "maximum (peak) intensity" in each block [deg. C]
'intensity_mean' Average MHW "mean intensity" in each block [deg. C]
'intensity_var' Average MHW "intensity variability" in each block [deg. C]
'intensity_cumulative' Average MHW "cumulative intensity" in each block [deg. C x days]
'rate_onset' Average MHW onset rate in each block [deg. C / days]
'rate_decline' Average MHW decline rate in each block [deg. C / days]
'total_days' Total number of MHW days in each block [days]
'total_icum' Total cumulative intensity over all MHWs in each block [deg. C x days]
'intensity_max_relThresh', 'intensity_mean_relThresh', 'intensity_var_relThresh',
and 'intensity_cumulative_relThresh' are as above except relative to the
threshold (e.g., 90th percentile) rather than the seasonal climatology
'intensity_max_abs', 'intensity_mean_abs', 'intensity_var_abs', and
'intensity_cumulative_abs' are as above except as absolute magnitudes
rather than relative to the seasonal climatology or threshold
Notes:
This function assumes that the MHWs were calculated over a suitably long record that return
periods make sense. If the record length is a few years or less than this becomes meaningless.
Written by Eric Oliver, Institue for Marine and Antarctic Studies, University of Tasmania, Sep 2015
'''
# Initialize rank and return period dictionaries
rank = {}
returnPeriod = {}
# Number of years on record
nYears = len(t)/365.25
# Loop over all keys in mhw
for key in mhw.keys():
# Skip irrelevant keys of mhw, only calculate rank/returns for MHW properties
if (key == 'date_end') + (key == 'date_peak') + (key == 'date_start') + (key == 'date_end') + (key == 'date_peak') + (key == 'date_start') + (key == 'index_end') + (key == 'index_peak') + (key == 'index_start') + (key == 'n_events'):
continue
# Calculate ranks
rank[key] = mhw['n_events'] - np.array(mhw[key]).argsort().argsort()
# Calculate return period as (# years on record + 1) / (# of occurrences of event)
# Return period is for events of at least the event magnitude/duration
returnPeriod[key] = (nYears + 1) / rank[key]
# Return rank, return
return rank, returnPeriod
def runavg(ts, w):
'''
Performs a running average of an input time series using uniform window
of width w. This function assumes that the input time series is periodic.
Inputs:
ts Time series [1D numpy array]
w Integer length (must be odd) of running average window
Outputs:
ts_smooth Smoothed time series
Written by Eric Oliver, Institue for Marine and Antarctic Studies, University of Tasmania, Feb-Mar 2015
'''
# Original length of ts
N = len(ts)
# make ts three-fold periodic
ts = np.append(ts, np.append(ts, ts))
# smooth by convolution with a window of equal weights
ts_smooth = np.convolve(ts, np.ones(w)/w, mode='same')
# Only output central section, of length equal to the original length of ts
ts = ts_smooth[N:2*N]
return ts
def pad(data, maxPadLength=False):
'''
Linearly interpolate over missing data (NaNs) in a time series.
Inputs:
data Time series [1D numpy array]
maxPadLength Specifies the maximum length over which to interpolate,
i.e., any consecutive blocks of NaNs with length greater
than maxPadLength will be left as NaN. Set as an integer.
maxPadLength=False (default) interpolates over all NaNs.
Written by Eric Oliver, Institue for Marine and Antarctic Studies, University of Tasmania, Jun 2015
'''
data_padded = data.copy()
bad_indexes = np.isnan(data)
good_indexes = np.logical_not(bad_indexes)
good_data = data[good_indexes]
interpolated = np.interp(bad_indexes.nonzero()[0], good_indexes.nonzero()[0], good_data)
data_padded[bad_indexes] = interpolated
if maxPadLength:
blocks, n_blocks = ndimage.label(np.isnan(data))
for bl in range(1, n_blocks+1):
if (blocks==bl).sum() > maxPadLength:
data_padded[blocks==bl] = np.nan
return data_padded
def nonans(array):
'''
Return input array [1D numpy array] with
all nan values removed
'''
return array[~np.isnan(array)]
|
bca49786c266839dc0da317a76d6af24b20816e5
|
mtahaakhan/Intro-in-python
|
/Python Practice/input_date.py
| 708 | 4.28125 | 4 |
# ! Here we have imported datetime and timedelta functions from datetime library
from datetime import datetime,timedelta
# ! Here we are receiving input from user, when is your birthday?
birthday = input('When is your birthday (dd/mm/yyyy)? ')
# ! Here we are converting input into birthday_date
birthday_date = datetime.strptime(birthday, '%d/%m/%Y')
# ! Here we are printing birthday date
print('Birthday: ' + str(birthday_date))
# ! Here we are again just asking one day before from timedelta
one_day = timedelta(days=1)
birthday_eve = birthday_date - one_day
print('Day before birthday: ' + str(birthday_eve))
# ! Now we will see Error Handling if we receive birthday date in spaces or ashes.
|
2937f2007681af5aede2a10485491f8d2b5092cf
|
mtahaakhan/Intro-in-python
|
/Python Practice/date_function.py
| 649 | 4.34375 | 4 |
# Here we are asking datetime library to import datetime function in our code :)
from datetime import datetime, timedelta
# Now the datetime.now() will return current date and time as a datetime object
today = datetime.now()
# We have done this in last example.
print('Today is: ' + str(today))
# Now we will use timedelta
# Here, from timedelta we are getting yesterdays date time
one_day = timedelta(days=1)
yesterday = today - one_day
print('Yesterday was: ' + str(yesterday))
# Here, from timedelta we are getting last weeks date time
one_week = timedelta(weeks=1)
last_week = today - one_week
print('Last week was: ' + str(last_week))
|
e797aa24ce9fbd9354c04fbbf853ca63e967c827
|
xtdoggx2003/CTI110
|
/P4T2_BugCollector_AnthonyBarnhart.py
| 657 | 4.3125 | 4 |
# Bug Collector using Loops
# 29MAR2020
# CTI-110 P4T2 - Bug Collector
# Anthony Barnhart
# Initialize the accumlator.
total = 0
# Get the number of bugs collected for each day.
for day in range (1, 6):
# Prompt the user.
print("Enter number of bugs collected on day", day)
# Input the number of bugs.
bugs = int (input())
# Add bugs to toal.
total = total + bugs
# Display the total bugs.
print("You have collected a total of", total, "bugs")
# Psuedo Code
# Set total = 0
# For 5 days:
# Input number of bugs collected for a day
# Add bugs collected to total number of bugs
# Display the total bugs
|
6e7401d2ed0a82b75f1eaec51448f7f20476d46e
|
xtdoggx2003/CTI110
|
/P3HW1_ColorMix_AnthonyBarnhart.py
| 1,039 | 4.40625 | 4 |
# CTI-110
# P3HW1 - Color Mixer
# Antony Barnhart
# 15MAR2020
# Get user input for primary color 1.
Prime1 = input("Enter first primary color of red, yellow or blue:")
# Get user input for primary color 2.
Prime2 = input("Enter second different primary color of red, yellow or blue:")
# Determine secondary color and error if not one of three listed colors
if Prime1 == "red" and Prime2 == "yellow" or Prime1 == "yellow" and Prime2 == "red":
print("orange")
elif Prime1 == "blue" and Prime2 == "yellow" or Prime1 == "yellow" and Prime2 == "blue":
print("green")
elif Prime1 == "blue" and Prime2 == "red" or Prime1 == "red" and Prime2 == "blue":
print("purple")
else:
print("error")
# Pseudocode
# Ask user to input prime color one
# Ask user to imput prime color two
# Only allow input of three colors Red, Yellow, Blue
# Determine the secondary color based off of user input
# Display secondary color
# Display error if any color outside of given perameters is input
|
fb64f35e7947840cb7bd32c847fdfb17b45a022e
|
Near-River/robot_spider
|
/spider/url_manager.py
| 734 | 3.71875 | 4 |
# 管理待爬取和已爬取的URL集合
class UrlManager(object):
def __init__(self):
self.urls = set() # 待爬取的URL集合
self.over_urls = set() # 已爬取的URL集合
def add_url(self, root_url):
if root_url is None:
return
if root_url not in self.over_urls and root_url not in self.urls:
self.urls.add(root_url)
def has_more_url(self):
return len(self.urls) > 0
def get_url(self):
new_url = self.urls.pop()
self.over_urls.add(new_url)
return new_url
def add_urls(self, new_urls):
if new_urls is None or len(new_urls) <= 0:
return
for url in new_urls:
self.add_url(url)
|
d8e20c074639e3a4a224cf67640e9c54d2a666bb
|
wasi-9274/DL_Directory
|
/DL_Projects/ETL_scripts/Load_excercise_script_important.py
| 10,623 | 3.515625 | 4 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from pycountry import countries
from collections import defaultdict
import sqlite3
sns.set()
# read in the projects data set and do basic wrangling
gdp = pd.read_csv('/home/wasi/ML_FOLDER/DSND_Term2-master/lessons/ETLPipelines/data/gdp_data.csv', skiprows=4)
gdp.drop(['Unnamed: 62', 'Indicator Name', 'Indicator Code'], inplace=True, axis=1)
population = pd.read_csv('/home/wasi/ML_FOLDER/DSND_Term2-master/lessons/ETLPipelines/data/population_data.csv',
skiprows=4)
population.drop(['Unnamed: 62', 'Indicator Name', 'Indicator Code'], inplace=True, axis=1)
# Reshape the data sets so that they are in long format
gdp_melt = gdp.melt(id_vars=['Country Name', 'Country Code'],
var_name='year',
value_name='gdp')
# Use back fill and forward fill to fill in missing gdp values
gdp_melt['gdp'] = gdp_melt.sort_values('year').groupby(['Country Name', 'Country Code'])['gdp'].fillna(method='ffill').fillna(method='bfill')
population_melt = population.melt(id_vars=['Country Name', 'Country Code'],
var_name='year',
value_name='population')
# Use back fill and forward fill to fill in missing population values
population_melt['population'] = population_melt.sort_values('year').groupby('Country Name')['population'].fillna(method='ffill').fillna(method='bfill')
# merge the population and gdp data together into one data frame
df_indicator = gdp_melt.merge(population_melt, on=('Country Name', 'Country Code', 'year'))
# filter out values that are not countries
non_countries = ['World',
'High income',
'OECD members',
'Post-demographic dividend',
'IDA & IBRD total',
'Low & middle income',
'Middle income',
'IBRD only',
'East Asia & Pacific',
'Europe & Central Asia',
'North America',
'Upper middle income',
'Late-demographic dividend',
'European Union',
'East Asia & Pacific (excluding high income)',
'East Asia & Pacific (IDA & IBRD countries)',
'Euro area',
'Early-demographic dividend',
'Lower middle income',
'Latin America & Caribbean',
'Latin America & the Caribbean (IDA & IBRD countries)',
'Latin America & Caribbean (excluding high income)',
'Europe & Central Asia (IDA & IBRD countries)',
'Middle East & North Africa',
'Europe & Central Asia (excluding high income)',
'South Asia (IDA & IBRD)',
'South Asia',
'Arab World',
'IDA total',
'Sub-Saharan Africa',
'Sub-Saharan Africa (IDA & IBRD countries)',
'Sub-Saharan Africa (excluding high income)',
'Middle East & North Africa (excluding high income)',
'Middle East & North Africa (IDA & IBRD countries)',
'Central Europe and the Baltics',
'Pre-demographic dividend',
'IDA only',
'Least developed countries: UN classification',
'IDA blend',
'Fragile and conflict affected situations',
'Heavily indebted poor countries (HIPC)',
'Low income',
'Small states',
'Other small states',
'Not classified',
'Caribbean small states',
'Pacific island small states']
# remove non countries from the data
df_indicator = df_indicator[~df_indicator['Country Name'].isin(non_countries)]
df_indicator.reset_index(inplace=True, drop=True)
df_indicator.columns = ['countryname', 'countrycode', 'year', 'gdp', 'population']
# output the first few rows of the data frame
print(df_indicator.head())
################################### END OF THE PART OF CODE NEXT STARTS NEW CODE ######################################
# read in the projects data set with all columns type string
df_projects = pd.read_csv('/home/wasi/ML_FOLDER/DSND_Term2-master/lessons/ETLPipelines/data/projects_data.csv',
dtype=str)
df_projects.drop(['Unnamed: 56'], axis=1, inplace=True)
df_projects['countryname'] = df_projects['countryname'].str.split(';').str.get(0)
# set up the libraries and variables
country_not_found = [] # stores countries not found in the pycountry library
project_country_abbrev_dict = defaultdict(str) # set up an empty dictionary of string values
# TODO: iterate through the country names in df_projects.
# Create a dictionary mapping the country name to the alpha_3 ISO code
for country in df_projects['countryname'].drop_duplicates().sort_values():
try:
# TODO: look up the country name in the pycountry library
# store the country name as the dictionary key and the ISO-3 code as the value
project_country_abbrev_dict[country] = countries.lookup(country).alpha_3
except:
# If the country name is not in the pycountry library, then print out the country name
# And store the results in the country_not_found list
country_not_found.append(country)
# run this code cell to load the dictionary
country_not_found_mapping = {'Co-operative Republic of Guyana': 'GUY',
'Commonwealth of Australia':'AUS',
'Democratic Republic of Sao Tome and Prin':'STP',
'Democratic Republic of the Congo':'COD',
'Democratic Socialist Republic of Sri Lan':'LKA',
'East Asia and Pacific':'EAS',
'Europe and Central Asia': 'ECS',
'Islamic Republic of Afghanistan':'AFG',
'Latin America':'LCN',
'Caribbean':'LCN',
'Macedonia':'MKD',
'Middle East and North Africa':'MEA',
'Oriental Republic of Uruguay':'URY',
'Republic of Congo':'COG',
"Republic of Cote d'Ivoire":'CIV',
'Republic of Korea':'KOR',
'Republic of Niger':'NER',
'Republic of Kosovo':'XKX',
'Republic of Rwanda':'RWA',
'Republic of The Gambia':'GMB',
'Republic of Togo':'TGO',
'Republic of the Union of Myanmar':'MMR',
'Republica Bolivariana de Venezuela':'VEN',
'Sint Maarten':'SXM',
"Socialist People's Libyan Arab Jamahiriy":'LBY',
'Socialist Republic of Vietnam':'VNM',
'Somali Democratic Republic':'SOM',
'South Asia':'SAS',
'St. Kitts and Nevis':'KNA',
'St. Lucia':'LCA',
'St. Vincent and the Grenadines':'VCT',
'State of Eritrea':'ERI',
'The Independent State of Papua New Guine':'PNG',
'West Bank and Gaza':'PSE',
'World':'WLD'}
project_country_abbrev_dict.update(country_not_found_mapping)
df_projects['countrycode'] = df_projects['countryname'].apply(lambda x: project_country_abbrev_dict[x])
df_projects['boardapprovaldate'] = pd.to_datetime(df_projects['boardapprovaldate'])
df_projects['year'] = df_projects['boardapprovaldate'].dt.year.astype(str).str.slice(stop=4)
df_projects['totalamt'] = pd.to_numeric(df_projects['totalamt'].str.replace(',', ""))
df_projects = df_projects[['id', 'countryname', 'countrycode', 'totalamt', 'year']]
print(df_projects.head())
################################### END OF THE PART OF CODE NEXT STARTS NEW CODE ######################################
# TODO: merge the projects and indicator data frames together using countrycode and year as common keys
# Use a left join so that all projects are returned even if the country/year combination does not have
# indicator data
df_merged = df_projects.merge(df_indicator, how='left', on=['countrycode', 'year'])
print(df_merged.head(30))
################################### END OF THE PART OF CODE NEXT STARTS NEW CODE ######################################
# Run this code to check your work
print(df_merged[(df_merged['year'] == '2017') & (df_merged['countryname_y'] == 'Jordan')])
################################### END OF THE PART OF CODE NEXT STARTS NEW CODE ######################################
# TODO: Output the df_merged data frame as a json file
# HINT: Pandas has a to_json() method
# HINT: use orient='records' to get one of the more common json formats
# HINT: be sure to specify the name of the json file you want to create as the first input into to_json
df_merged.to_json('/home/wasi/Desktop/junk/countrydata.json', orient='records')
################################### END OF THE PART OF CODE NEXT STARTS NEW CODE ######################################
# TODO: Output the df_merged data frame as a csv file
# HINT: The to_csv() method is similar to the to_json() method.
# HINT: If you do not want the data frame indices in your result, use index=False
df_merged.to_csv('/home/wasi/Desktop/junk/countrydata.csv', index=False)
################################### END OF THE PART OF CODE NEXT STARTS NEW CODE ######################################
#
# # connect to the database
# # the database file will be worldbank.db
# # note that sqlite3 will create this database file if it does not exist already
# conn = sqlite3.connect('worldbank.db')
#
# # TODO: output the df_merged dataframe to a SQL table called 'merged'.
# # HINT: Use the to_sql() method
# # HINT: Use the conn variable for the connection parameter
# # HINT: You can use the if_exists parameter like if_exists='replace' to replace a table if it already exists
#
# df_merged.to_sql('merged', con=conn, if_exists='replace', index=False)
################################### END OF THE PART OF CODE NEXT STARTS NEW CODE ######################################
|
4172fba04d1af39171f32cdaabbda8bdf3618556
|
wasi-9274/DL_Directory
|
/DL_Projects/dummy_data_storage/recommendations_script_2.py
| 4,468 | 3.640625 | 4 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# read in the datasets
movies = pd.read_csv("/home/wasi/ML_FOLDER/Udacity-DSND-master/Experimental Design & Recommandations/Recommendations/"
"1_Intro_to_Recommendations/movies_clean.csv")
reviews = pd.read_csv("/home/wasi/ML_FOLDER/Udacity-DSND-master/Experimental Design & Recommandations/Recommendations/"
"1_Intro_to_Recommendations/reviews_clean.csv")
# del movies['Unnamed: 0']
# del reviews['Unnamed: 0']
def create_ranked_df(movies, reviews):
'''
INPUT
movies - the movies dataframe
reviews - the reviews dataframe
OUTPUT
ranked_movies - a dataframe with movies that are sorted by highest avg rating, more reviews,
then time, and must have more than 4 ratings
'''
# Pull the average ratings and number of ratings for each movie
movie_ratings = reviews.groupby('movie_id')['rating']
avg_ratings = movie_ratings.mean()
num_ratings = movie_ratings.count()
last_rating = pd.DataFrame(reviews.groupby('movie_id').max()['date'])
last_rating.columns = ['last_rating']
# Add Dates
rating_count_df = pd.DataFrame({'avg_rating': avg_ratings, 'num_ratings': num_ratings})
rating_count_df = rating_count_df.join(last_rating)
# merge with the movies dataset
movie_recs = movies.set_index('movie_id').join(rating_count_df)
# sort by top avg rating and number of ratings
ranked_movies = movie_recs.sort_values(['avg_rating', 'num_ratings', 'last_rating'], ascending=False)
# for edge cases - subset the movie list to those with only 5 or more reviews
ranked_movies = ranked_movies[ranked_movies['num_ratings'] > 4]
return ranked_movies
def popular_recommendations(user_id, n_top, ranked_movies):
'''
INPUT:
user_id - the user_id (str) of the individual you are making recommendations for
n_top - an integer of the number recommendations you want back
ranked_movies - a pandas dataframe of the already ranked movies based on avg rating, count, and time
OUTPUT:
top_movies - a list of the n_top recommended movies by movie title in order best to worst
'''
top_movies = list(ranked_movies['movie'][:n_top])
return top_movies
# Top 20 movies recommended for id 1
ranked_movies = create_ranked_df(movies, reviews) # only run this once - it is not fast
recs_20_for_1 = popular_recommendations('1', 20, ranked_movies)
# Top 5 movies recommended for id 53968
recs_5_for_53968 = popular_recommendations('53968', 5, ranked_movies)
# Top 100 movies recommended for id 70000
recs_100_for_70000 = popular_recommendations('70000', 100, ranked_movies)
# Top 35 movies recommended for id 43
recs_35_for_43 = popular_recommendations('43', 35, ranked_movies)
def popular_recs_filtered(user_id, n_top, ranked_movies, years=None, genres=None):
'''
INPUT:
user_id - the user_id (str) of the individual you are making recommendations for
n_top - an integer of the number recommendations you want back
ranked_movies - a pandas dataframe of the already ranked movies based on avg rating, count, and time
years - a list of strings with years of movies
genres - a list of strings with genres of movies
OUTPUT:
top_movies - a list of the n_top recommended movies by movie title in order best to worst
'''
# Filter movies based on year and genre
if years is not None:
ranked_movies = ranked_movies[ranked_movies['date'].isin(years)]
if genres is not None:
num_genre_match = ranked_movies[genres].sum(axis=1)
ranked_movies = ranked_movies.loc[num_genre_match > 0, :]
# create top movies list
top_movies = list(ranked_movies['movie'][:n_top])
return top_movies
# Top 20 movies recommended for id 1 with years=['2015', '2016', '2017', '2018'], genres=['History']
recs_20_for_1_filtered = popular_recs_filtered('1', 20, ranked_movies, years=['2015', '2016', '2017', '2018'], genres=['History'])
# Top 5 movies recommended for id 53968 with no genre filter but years=['2015', '2016', '2017', '2018']
recs_5_for_53968_filtered = popular_recs_filtered('53968', 5, ranked_movies, years=['2015', '2016', '2017', '2018'])
# Top 100 movies recommended for id 70000 with no year filter but genres=['History', 'News']
recs_100_for_70000_filtered = popular_recs_filtered('70000', 100, ranked_movies, genres=['History', 'News'])
|
453748851a21420a9d7aa3851a803e2294b2feea
|
SandeshKulung/User_Interface
|
/user_interface.py
| 3,031 | 3.734375 | 4 |
from tkinter import*
from tkinter import messagebox
def cancel():
messagebox.showinfo("Cancelled")
def display():
messagebox.showinfo("Registered")
window=Tk()
window.geometry("760x550")
window.resizable(width=0,height=0)
window.title("ADMISSION")
name=StringVar()
l1=Label(window, text="Student Admission form",font=('Helvetica',20,'bold'))
l1.place(x=250,y=30)
l2=Label(window,text="Sunway Int'l Business School",font=10)
l2.place(x=310,y=70)
l3=Label(window,text="Full Name",width=15,font=10)
l3.place(x=15,y=130)
e3=Entry(window,textvariable=name,width=30, font=20)
e3.place(x=150,y=130)
sex=StringVar()
number=StringVar()
number1=StringVar()
name1=StringVar()
name2=StringVar()
day=StringVar()
month=StringVar()
year=StringVar()
mobile=StringVar()
email=StringVar()
updat=Label(window,text="Gender",width=15,font=10)
updat.place(x=450,y=125)
sex.set("Select gender")
box=OptionMenu(window,sex,"male","female","other")
box.place(x=570,y=125)
l4=Label(window,text="Father's Name",width=15,font=10)
l4.place(x=15,y=170)
e4=Entry(window,textvariable=name1,width=30, font=20)
e4.place(x=150,y=170)
l5=Label(window,text="Mother's Name",width=15,font=10)
l5.place(x=15,y=210)
e5=Entry(window,textvariable=name2,width=30, font=20)
e5.place(x=150,y=210)
c1=Label(window,text="contact number",font=10)
c1.place(x=450,y=170)
ec1=Entry(window,textvariable="number",width=15,font=15)
ec1.place(x=570,y=170)
c2=Label(window,text="contact number",font=10)
c2.place(x=450,y=210)
ec2=Entry(window,textvariable=number1,width=15,font=15)
ec2.place(x=570,y=210)
l6=Label(window,text="Date of birth",width=15,font=10)
l6.place(x=15,y=250)
e6=Entry(window,textvariable=day,width=3,font=10)
e6.place(x=150,y=250)
l61=Label(window,text="Day",width=3)
l61.place(x=150,y=275)
e61=Entry(window,textvariable=month,width=3,font=10)
e61.place(x=190,y=250)
l62=Label(window,text="month",width=4)
l62.place(x=188,y=275)
e62=Entry(window,textvariable=year,width=5,font=10)
e62.place(x=230,y=250)
l63=Label(window,text="year",width=3)
l63.place(x=240,y=275)
n1=Label(window,text="Mobile number",width=15,font=10)
n1.place(x=15,y=300)
ne1=Entry(window,textvariable=mobile,width=20,font=20)
ne1.place(x=150,y=300)
n2=Label(window,text="Email-Id",width=15,font=10)
n2.place(x=15,y=340)
ne2=Entry(window,textvariable=email,width=30,font=20)
ne2.place(x=150,y=340)
n3=Label(window,text="Qualification",width=15,font=10)
n3.place(x=15,y=380)
qual=StringVar()
qual.set("select the level")
ne3=OptionMenu(window,qual,"+2 level","A-level","Bachelor's completed")
ne3.place(x=150,y=380)
t=Label(window,text="choose Level",width=15,font=10)
t.place(x=15,y=420)
level=StringVar()
level.set("choose level to study")
t1=OptionMenu(window,level,"BCS-Hons","MBA")
t1.place(x=150,y=420)
b1=Button(window,text="Register",fg='red',width=15,command=display)
b1.place(x=380,y=490)
b2=Button(window,text="Cancel",width=15,fg='red',command=cancel)
b2.place(x=250,y=490)
window.mainloop()
|
816ede0c29039d73385b94472d973fbc1c10424a
|
waynegakuo/nlp2018_waynegakuo
|
/lab_2/med.py
| 1,125 | 3.5 | 4 |
# coding: utf-8
# In[1]:
import sys
def medistance(source, target):
#length of the source and target assigned to n and m respecitvely
n= len(source)
m= len(target)
#initializing the costs of insertion, substitution and deletion
ins_cost=1
sub_cost=2
del_cost=1
#creation of the distance matrix using a 2-D array
D=[[0 for a in range(m+1)] for a in range(n+1)]
#initializing the zeroth row
for i in range (0, n+1):
D[i][0]=i
#initializing the zeroth column
for j in range (0, m+1):
D[0][j]=j
#Recurrence relation
for i in range (1, n+1):
for j in range (1, m+1):
if source[i-1]==target[j-1]:
D[i][j]=D[i-1][j-1]
else:
D[i][j]=min(D[i-1][j]+del_cost,
D[i-1][j-1]+sub_cost,
D[i][j-1]+ins_cost)
#Termination
return D [n][m]
medistance(sys.argv[1], sys.argv[2])
s=sys.argv[1]
t=sys.argv[2]
print ("Minimum edit distance between", s, "and", t, "is", medistance(s,t))
|
c81f6eb1684183e44bae7c816777c73231c365ea
|
btalahmb/.PyFiles
|
/tablePrinter.py
| 1,341 | 3.78125 | 4 |
#tablePrinter.py
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alicia', 'Bert', 'Czech', 'David'],
['Dogs', 'chicken', 'moose', 'goose']]
def printTable():
colWidths = [0] * len(tableData)
#Solve for longest string in each column and store values in a list
for i in range(len(tableData)):
for j in range(len(colWidths)):
curr = len(tableData[j][i])
nex = len(tableData[j][i+1])
if(curr < nex):
temp = curr
curr = nex
nex = temp
else:
pass
colWidths[j] = curr
#Find longest string value in list of string values
for i in range(len(colWidths)):
curr1 = colWidths[i]
nex1 = colWidths[i+1]
if((curr1 > len(colWidths)) or (nex1 > len(colWidths))):
break
if(curr1 < nex1):
temp1 = curr1
curr1 = nex1
nex1 = temp1
else:
pass
newTable = []
#Transpose list of lists
for i in range(len(tableData[0])):
row = []
for item in tableData:
row.append(item[i])
newTable.append(row)
#Print list as table
print()
for i in (newTable):
value = ' '.join(i)
print(value.rjust(curr1))
printTable()
|
c3ffa8b82e2818647adda6c69245bbc9841ffd76
|
tsuganoki/practice_exercises
|
/strval.py
| 951 | 4.125 | 4 |
"""In the first line, print True if has any alphanumeric characters. Otherwise, print False.
In the second line, print True if has any alphabetical characters. Otherwise, print False.
In the third line, print True if has any digits. Otherwise, print False.
In the fourth line, print True if has any lowercase characters. Otherwise, print False.
In the fifth line, print True if has any uppercase characters. Otherwise, print False."""
s = "6$%^#"
alph = False
alphanumeric = False
digits = False
lowercase = False
uppercase = False
if len(s) < 1000:
for l in s:
if l.isalpha():
alph = True
if l.isdigit():
digits = True
if l.isalnum():
alphanumeric = True
if l.islower():
lowercase = True
if l.isupper():
uppercase = True
print(alphanumeric)
print(alph)
print(digits)
print(lowercase)
print(uppercase)
|
c8e30738d8f5ec2f26a5ff285890983a6a1c9c16
|
tsuganoki/practice_exercises
|
/ProjectEuler/024.py
| 524 | 3.796875 | 4 |
"""
A permutation is an ordered arrangement of objects. For example, 3124 is one
possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are
listed numerically or alphabetically, we call it lexicographic order. The
lexicographic permutations of 0, 1 and 2 are:
012
021
102
120
201
210
What is the millionth lexicographic permutation of the digits
0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
the first n start with 0
the second n start with 1
"""
def get_permutations(n):
perms = []
return perms
|
7bdca56dc7a7e86e3a94977552da4b739b98949f
|
tsuganoki/practice_exercises
|
/yahtzee.py
| 12,116 | 3.875 | 4 |
from random import randint
import pdb
#import numpy as np
"""import pandas as pd
import json"""
# with open("somefi")
"""
import logging
logging.basicConfig(
filename="yahtzeelog.txt",
level = logging.DEBUG)
logging.disable(logging.CRITICAL)
"""
# rolls all 5 dice and returns a dictionary
def roll_all():
rolls = {}
dice = "ABCDE"
for i in range(5):
rolls[(dice[i])] = randint(1,6)
return rolls
# takes a user input and outputs a list containing only the letters ABCDE
def convert_to_list(us_sel):
us_sel_list = []
for i in us_sel:
if ord(i.lower()) > 96 and ord(i.lower()) <102:
us_sel_list.append(i.upper())
return us_sel_list
#function which sanitizes any input and returns a lowercase string
def sanit(input):
input = input.lower()
output = ""
for i in input:
if ord(i) > 96 and ord(i) <102:
output = output + i
return i
# rerolls specified dice from a list of user inputs
def reroll(l,rolls):
for i in l:
rolls[i] = randint(1,6)
return rolls
# function for displaying the dice results to the user
def display_roll(rolls):
for key in sorted(rolls.iterkeys()):
print "%s: %s" % (key, rolls[key])
print(" ")
# This function gets the user's reroll choice and returns a list with [choice, round]
def reroll_choice():
#pdb.set_trace()
rerollyn = raw_input("Reroll? (Y / N) ")
print(" ")
try:
choice = sanit(rerollyn[0])
except:
print("I didn't understand that input. Please Try again.")
return reroll_choice()
if choice == "n":
#if the user inputs a string starting with "n", no re-roll happens
return True
elif choice == "y":
#if the user inputs a string starting with "y"
return False
else:
#if the user does a keyboard smash, it will start over
print("I didn't understand that input. Please Try again.")
return reroll_choice()
"""def get_reroll_choice(rolls):
#this section asks the user for a reroll choice
output = []
rerollyn = ""
rerollyn = raw_input("Reroll? (Y / N) ")
print(" ")
if sanit(rerollyn[0]) == "n":
#if the user inputs a string starting with "n", no re-roll happens
return True
elif sanit(rerollyn[0]) == "y":
#if the user inputs a string starting with "y" it will ask for which dice to reroll
user_selection = raw_input("Reroll? (A, B, C, D, E?) ")
print(" ")
print("Rerolling....")
reroll(convert_to_list(user_selection),rolls)
print("Your new rolls are: ")
display_roll(rolls)
return False
else:
#if the user does a keyboard smash, it will start over
print("I didn't understand that input. Please Try again.")
get_reroll_choice(rolls)
"""
def select_dice(rolls):
user_selection = raw_input("Enter which die or dice to reroll: A, B, C, D, E ")
print(" ")
user_selection_list = convert_to_list(user_selection)
if len(user_selection_list) < 1:
print("Your input was not understod. Please try again (not case sensitive)")
return select_dice(rolls)
print("Rerolling....")
rolls = reroll(user_selection_list,rolls)
return rolls
def stringify_key_value_cat(key,value):
return value + "(" + str(key) + ")"
def display_categories(categories):
string_list_up = []
string_list_low = []
for key in filter(lambda key: categories[key][0],categories):
if key < 7:
string_list_up.append(stringify_key_value_cat(key,categories[key][1]))
else:
string_list_low.append(stringify_key_value_cat(key,categories[key][1]))
print("Remaining options: ")
if string_list_up == []:
print("Upper: None")
else:
print("Upper: "+ ", ".join(string_list_up))
if string_list_low == []:
print("Lower: None.")
else:
print("Lower: " + ", ".join(string_list_low))
def select_category_fun(categories):
display_categories(categories)
cat_selection = raw_input("Select a category to score this round: ")
try:
cat_selection = int(cat_selection)
except:
print("Response not understood. Please try again.\n")
return select_category_fun(categories)
if cat_selection > 0 and cat_selection < 14:
if categories[cat_selection][0] == False:
print("That category is no longer available. Please try again. ")
return select_category_fun(categories)
else:
return int(cat_selection)
else:
print("Response not understood. Please try again.\n")
return select_category_fun(categories)
#This function takes in a user selection and a set of rolls, and returns a list of points for that roll
def score_fun(rolls_dict,cat_selection,game_score):
score_upper = 0
score_lower = 0
yahtzee = 0
is_yahtzee = False
score_list = [0,0,0]
#Changes rolls to a simple ordered list
rolls = []
for key in rolls_dict:
rolls.append(rolls_dict[key])
rolls.sort()
rolls_string = ""
for i in rolls:
rolls_string += str(i)
#checks if yahtzee
if all(x==rolls[0] for x in rolls):
is_yahtzee = True
if cat_selection < 7:
for i in rolls:
if i == cat_selection:
score_upper += i
elif cat_selection == 7: #three of a Kind
rolls1 = rolls[:3]
rolls2 = rolls[1:4]
rolls3 = rolls[2:]
if all(x==rolls1[0] for x in rolls1) or all(x==rolls2[0] for x in rolls2) or all(x==rolls3[0] for x in rolls3):
score_lower = 17
elif cat_selection == 8:#four of a kind
if rolls[0] == rolls [3] or rolls[1] == rolls[4]:
score_lower = 24
elif cat_selection == 9: #Full House (two of a kind and three of a kind)
rolls1=rolls[:3]
rolls2 = rolls[3:]
rolls3 = rolls[:2]
rolls4 = rolls[2:]
if all(x==rolls1[0] for x in rolls1) and all(x==rolls2[0] for x in rolls2):
score_lower = 25
elif all(x==rolls3[0] for x in rolls3) and all(x==rolls4[0] for x in rolls4):
score_lower = 25
elif cat_selection == 10: #large Straight (5)
if rolls == [1,2,3,4,5] or rolls == [2,3,4,5,6]:
score_lower = 40
print("i am a potato")
elif cat_selection == 11:#Small Straight (4)
if "1234" in rolls_string or "2345" in rolls_string or "3456" in rolls_string:
score_lower = 30
elif cat_selection == 12: #Chance(sum of all dice)
for i in rolls:
score_lower += i
elif cat_selection == 13: #yahtzee
if is_yahtzee == True:
yahtzee = 1
score_lower = 50
if is_yahtzee == True and game_score[2] > 0:
score_lower +=100
score_list[0] = score_upper
score_list[1] = score_lower
score_list[2] = yahtzee
return score_list
# Function for Displaying Score:
def display_score(score_list):
u_bonus = ""
y_bonus = ""
if score_list[0] > 63:
u_bonus = "Upper Section Bonus: +35 Points for hitting 63!"
if score_list[2] == 0:
yahtzee_score = 0
elif score_list[2] > 1:
y_bonus = "Yahtzee Bonus: +100 points!"
total = score_list[0] + score_list[1]
print("Score Upper: %s %s" % (score_list[0],u_bonus))
print("Score Lower: %s" % (score_list[1]))
print("Yahtzees: %s %s" % (score_list[2],y_bonus))
print("Score Total: %s" % (total))
print(" ")
def add_round_score(score,points):
sum = []
for i,k in zip(score,points):
sum.append(i+k)
return sum
# Function for running a single round
def new_round(categories,game_score):
round_output = {}
round_score = [0,0,0]
#this section gives the initial roll
rolls = roll_all()
print("Your initial rolls are: ")
display_roll(rolls)
#sets the roll count for the round to 2 remaining
round_roll_count = 2
#asks the user for a reroll up to two times
print("You have %s rolls remaining." % (round_roll_count))
while round_roll_count >0:
reroll_choice_var = reroll_choice()
if reroll_choice_var == False:
rolls = select_dice(rolls)
round_roll_count += -1
print("Your new rolls are: ")
display_roll(rolls)
else:
print("Keeping rolls. ")
print(" ")
round_roll_count += -3
cat_selection = select_category_fun(categories)
#this line sets the selected category to False, so it can't be used again
categories[cat_selection][0]= False
#round is scored here
#this function takes in your rolls, and your selection, and returns a list of round points
round_score = score_fun(rolls,cat_selection,game_score)
print(" ")
print("Your score for this round was: %s" %(round_score[0]+round_score[1]))
#display_score(round_score)
#round info is added to a dictionary
round_output["round_score"] = round_score
round_output["categories"] = categories
# returns a dictionary with all the round info in it
return round_output
def play_yahtzee():
round_count = 1
upper_bonus = False
yahtzee_bonus = 0
game_score = [0,0,0]
number_of_rounds = 13
game = {}
#This is how scoring categories are tracked
categories = {1:[True,"Aces"],2:[True,"Twos"],3:[True,"Threes"],4:[True,"Fours"],5:[True,"Fives"],6:[True,"Sixes"],
7:[True,"Three of a Kind",7],8:[True,"Four of a Kind",8],9:[True,"Full House",9],10:[True,"Small Straight",10],
11:[True,"Large Straight"],12:[True,"Chance"],13:[True,"Yahtzee"]}
# this is the section where the game happens
while round_count < (number_of_rounds+1):
#this section lists the round number
print("Round "+ str(round_count)),
print(" ")
#runs 1 round and stores the rolls, score, and categories in round_output, also adds it to a dictionary
round_output = new_round(categories,game_score)
categories = round_output["categories"]
#stores the round in a master game dictionary
game[round_count] = round_output
#add round_pounds to game_points
game_score = add_round_score(game_score,round_output["round_score"])
#checks for Upper Bonus and Yahtzee Bonus
if game_score[0] > 63 and upper_bonus == False:
game_score[0] += 35
upper_bonus = True
if game_score[2] > 1:
game_score[1] += 100
display_score(game_score)
if round_count < number_of_rounds:
pause = raw_input("Hit any key to start next round...")
#uh?
#print("upper score from round output:", round_output["score_upper"])
#incriments the round number
round_count +=1
restart = raw_input("Good Game! You scored a total of %s Points! Play again?" % (game_score[0] + game_score[1]))
if sanit(restart)[0] == "y":
play_yahtzee()
if __name__ == '__main__':
play_yahtzee()
pass
categories = {1:[True,"Aces",1],2:[True,"Twos",2],3:[True,"Threes",3],4:[True,"Fours",4],5:[True,"Fives",5],6:[True,"Sixes",6],
7:[True,"Three of a Kind",7],8:[True,"Four of a Kind",8],9:[True,"Full House",9],10:[True,"Small Straight",10],
11:[True,"Large Straight",11],12:[True,"Chance",12],13:[True,"Yahtzee",13]}
"""
game_score = [0,0,0]
rolls = {
'A': 1,
'B': 1,
'C': 1,
'D': 1,
'E': 1,
}
#score_fun(rolls,cat_selection,game_score):
#n = int(raw_input(" : "))
round_score = score_fun(rolls,12,game_score)
display_score(round_score)
"""
|
653a376baa3e3f30164ba6f4b9bdf6006b572a34
|
verepcode/Computer-Vision-Projects
|
/Put a glass on a face.py
| 3,103 | 3.515625 | 4 |
#The aim is to put any size of glasses on any size of frontal face image. The code has already been developing,
#and for future, I want to help people choose their glasses by just looking a front facing camera at the end of the work.
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('Haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('Haarcascades/haarcascade_eye.xml')
# read both the images of the face and the glasses
image = cv2.imread('images/putin.jpg')
glass_img = cv2.imread('images/glasses2.png')
#show the frontal face image and glasses
cv2.imshow('image',image)
cv2.waitKey(0)
cv2.imshow('glasses',glass_img)
cv2.waitKey(0)
#Convert the color scale BGR to GRAY
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
centers=[]
faces = face_cascade.detectMultiScale(gray,1.3,5)
#Iterating over the face detected
for (x,y,w,h) in faces:
#Create two Regions of Interest.
roi_gray = gray[y:y+h, x:x+w]
roi_color = image[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
# Store the cordinates of eyes in the image to the 'center' array
for (ex,ey,ew,eh) in eyes:
centers.append((x+int(ex+0.5*ew), y+int(ey+0.5*eh)))
if len(centers)>0:
#Change the given value of 2.15 according to the size of the detected face
glasses_width = 2.16*abs(centers[1][0]-centers[0][0])
#Construct a weigth image which have the same size of the frontal face image
overlay_img = np.ones(image.shape,np.uint8)*255
#Resize the glasses image in proportion to face
h,w = glass_img.shape[:2]
scaling_factor = glasses_width/w
overlay_glasses = cv2.resize(glass_img,None,fx=scaling_factor,fy=scaling_factor,interpolation=cv2.INTER_AREA)
x = centers[0][0] if centers[0][0]<centers[1][0] else centers[1][0]
# The x and y variables below depend upon the size of the detected face.
x -= 0.26*overlay_glasses.shape[1]
y += 0.85*overlay_glasses.shape[0]
#Slice the height, width of the overlay image.
h, w = overlay_glasses.shape[:2]
#Decide a ratio which means distance between eye center and top of glass over the glass heigth.
#This helps the glass locate better
RoG = 0.34
overlay_img[int(centers[0][1] - (y + h/2) + y + RoG * h ):int(centers[0][1] + h/2 + RoG * h),int(x):int(x+w)] = overlay_glasses
#Create a mask and generate it's inverse.
gray_glasses = cv2.cvtColor(overlay_img, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(gray_glasses, 110, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
temp = cv2.bitwise_and(image, image, mask=mask)
temp2 = cv2.bitwise_and(overlay_img, overlay_img, mask=mask_inv)
final_img = cv2.add(temp, temp2)
cv2.imshow('Lets wear Glasses', final_img)
cv2.waitKey()
cv2.destroyAllWindows()
|
ae99131ca37b4c71f72cd387438590cafac01423
|
rgvsiva/learn
|
/func_arguments.py
| 469 | 3.875 | 4 |
def update(a):
print(id(a))
a=10
print(id(a))
print ('a',a)
def update1(a):
print(id(a))
a[1]=10
print(id(a))
print ('lst',a)
x=8
print(id(x))
update(x)
print ('x',x) #id's of variables are changing inside and outside of function.
#pass by value, pass by reference---not applicable in python---none of these
lst=[1,4,2,3]
print (id(lst))
update1(lst)
print('ls:',lst) #list immutable but id doesn't change
|
3feecc6c94f430f3c15ded3290fe00e67387c72a
|
rgvsiva/learn
|
/fibonacci assign.py
| 417 | 3.984375 | 4 |
x=int(input("upto which fibonacci no's u want: "))
def fib(x):
a=0
b=1
if x<=0:
print('not possible')
elif x==1:
print(a)
elif x>=2:
print(a)
print(b)
for i in range(2,x):
c=a+b
if c<=x:
print(c)
else:
break
a=b
b=c
fib(x)
|
864cd59a002cd981a74c84813d6ba9837c1d8b10
|
rgvsiva/learn
|
/break,cont,pass.py
| 367 | 3.875 | 4 |
x=int(input('how many u want: '))
i = 1
av=5
while i<=x:
if i>=av:
print ('out of stock')
break
print ('biryani')
i+=1
print ('bye')
print ()
for i in range(1,31):
if i%3==0 or i%5==0:
continue
print (i)
print()
for i in range(1,16):
if i%2!=0:
pass
else:
print(i)
|
bcfa60b524376285629d2208c7e9ee29dfccc339
|
rgvsiva/learn
|
/global keyword.py
| 345 | 3.875 | 4 |
#scope
a=10 #global variable
print(id(a))
def some():
# global a # to access global variable
a = 23 #local variable
x = globals()['a']
print(id(x))
print('inside:',x)
print('ins:',a)
globals()['a']=45 #to change the global variable without effecting local variable
some()
print('outside:',a)
|
a652cc7c4fb44c7da3cdb40bf62729709a7fc170
|
Dennisdoug/trandangdung-fundamental-c4e15
|
/Session 1/Homework 1/temperatureconverter.py
| 148 | 3.890625 | 4 |
def Temperature():
F = input('Enter temperature in Fahrenheit')
C = ((5.0/9.0)*(F - 32))
print "Temperature in degree Celsius is %f" %C
|
ff83fb8d53ed313c4887468e722c753454890782
|
Dennisdoug/trandangdung-fundamental-c4e15
|
/Session 2/session02/maze.py
| 142 | 4.03125 | 4 |
from turtle import *
shape('turtle')
speed(0)
length = 10
for i in range (100):
forward(length)
length += 5
left(90)
mainloop()
|
36822cf538431e720fb90e7bc07dd4b0e4e41985
|
Dennisdoug/trandangdung-fundamental-c4e15
|
/Session 3/Session 3/randoom.py
| 284 | 3.921875 | 4 |
from random import randint
x = randint(1, 100)
loop = True
while loop:
num = int(input("Enter a number 1 - 100: "))
if num == x:
print("Bingo")
loop = False
elif num < x:
print("A little too small")
else:
print("A little too large")
|
33599a05c8a0eb38df5c56e430582ac5b77e786d
|
Dennisdoug/trandangdung-fundamental-c4e15
|
/Session 5/Homework/count.py
| 227 | 4.03125 | 4 |
numbers = [1, 6, 8, 1, 2, 1, 5, 6, 1, 4, 5, 2, 7, 8, 4, 5, 9, 2, 1, 6, 8, 0, 0, 5, 6]
x = int(input("Enter a number? "))
count = numbers.count(x)
print(x, "appears " + str(count) + " times in the list")
#With count() function
|
03d426f76941366bdf75cae2ff1cbed5fad9b0ef
|
PLJTZS/AI
|
/DeepLearning/1-ImprovingNeuralNetworks/Initialization.py
| 6,720 | 4.28125 | 4 |
#coding:utf8
import numpy as np
"""
- Understand that different regularization methods that could help your model.
- Implement dropout and see it work on data.
- Recognize that a model without regularization gives you a better accuracy on the training set but nor necessarily on the test set.
- Understand that you could use both dropout and regularization on your model.
"""
"""
A well chosen initialization can:
Speed up the convergence of gradient descent
Increase the odds of gradient descent converging to a lower training (and generalization) error
"""
"""
一、Zero initialization
n general, initializing all the weights to zero results in the network failing to break symmetry.
This means that every neuron in each layer will learn the same thing, and you might as well be training
a neural network with n[l]=1n[l]=1 for every layer, and the network is no more powerful than a linear
classifier such as logistic regression.
What you should remember:
The weights W[l]W[l] should be initialized randomly to break symmetry.
It is however okay to initialize the biases b[l]b[l] to zeros. Symmetry is still broken so long as
W[l]W[l] is initialized randomly.
"""
# GRADED FUNCTION: initialize_parameters_zeros
def initialize_parameters_zeros(layers_dims):
"""
Arguments:
layer_dims -- python array (list) containing the size of each layer.
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])
b1 -- bias vector of shape (layers_dims[1], 1)
...
WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])
bL -- bias vector of shape (layers_dims[L], 1)
"""
parameters = {}
L = len(layers_dims) # number of layers in the network
for l in range(1, L):
### START CODE HERE ### (≈ 2 lines of code)
parameters['W' + str(l)] = np.zeros((layers_dims[l], layers_dims[l - 1]))
parameters['b' + str(l)] = np.zeros((layers_dims[l], 1))
### END CODE HERE ###
return parameters
"""
二、Random initialization
To break symmetry, lets intialize the weights randomly. Following random initialization, each neuron can
then proceed to learn a different function of its inputs.
In this exercise, you will see what happens if the weights are intialized randomly, but to very large values.
If you see "inf" as the cost after the iteration 0, this is because of numerical roundoff;
a more numerically sophisticated implementation would fix this. But this isn't worth worrying about
for our purposes.
Anyway, it looks like you have broken symmetry, and this gives better results. than before.
The model is no longer outputting all 0s.
"""
def initialize_parameters_random(layers_dims):
"""
Arguments:
layer_dims -- python array (list) containing the size of each layer.
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])
b1 -- bias vector of shape (layers_dims[1], 1)
...
WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])
bL -- bias vector of shape (layers_dims[L], 1)
"""
np.random.seed(3) # This seed makes sure your "random" numbers will be the as ours
parameters = {}
L = len(layers_dims) # integer representing the number of layers
for l in range(1, L):
### START CODE HERE ### (≈ 2 lines of code)
parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l - 1]) * 10
parameters['b' + str(l)] = np.zeros((layers_dims[l], 1))
### END CODE HERE ###
return parameters
"""
三、He initialization
Finally, try "He Initialization"; this is named for the first author of He et al., 2015.
(If you have heard of "Xavier initialization", this is similar except Xavier initialization uses
a scaling factor for the weights W[l]W[l] of sqrt(1./layers_dims[l-1]) where He initialization would use
sqrt(2./layers_dims[l-1]).)
Exercise: Implement the following function to initialize your parameters with He initialization.
Hint: This function is similar to the previous initialize_parameters_random(...). The only difference is that
instead of multiplying np.random.randn(..,..) by 10, you will multiply it by 2dimension of the previous
layer⎯⎯⎯⎯⎯√2dimension of the previous layer , which is what He initialization
recommends for layers with a ReLU activation.
"""
# GRADED FUNCTION: initialize_parameters_he
def initialize_parameters_he(layers_dims):
"""
Arguments:
layer_dims -- python array (list) containing the size of each layer.
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])
b1 -- bias vector of shape (layers_dims[1], 1)
...
WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])
bL -- bias vector of shape (layers_dims[L], 1)
"""
np.random.seed(3)
parameters = {}
L = len(layers_dims) - 1 # integer representing the number of layers
for l in range(1, L + 1):
### START CODE HERE ### (≈ 2 lines of code)
parameters['W' + str(l)] = np.multiply(np.random.randn(layers_dims[l], layers_dims[l - 1]),
np.sqrt(2 / layers_dims[l - 1]))
parameters['b' + str(l)] = np.zeros((layers_dims[l], 1))
### END CODE HERE ###
return parameters
"""
You have seen three different types of initializations. For the same number of iterations and same
hyper parameters the comparison is:
Model Train accuracy Problem/Comment
3-layer NN with zeros initialization 50% fails to break symmetry
3-layer NN with large random initialization 83% too large weights
3-layer NN with He initialization 99% recommended method
What you should remember from this notebook:
Different initializations lead to different results
Random initialization is used to break symmetry and make sure different hidden units can learn different things
Don't intialize to values that are too large
He initialization works well for networks with ReLU activations.
"""
|
4d1605f77acdf29ee15295ba9077d47bc3f62607
|
zakwan93/python_basic
|
/python_set/courses.py
| 1,678 | 4.125 | 4 |
# write a function named covers that accepts a single parameter, a set of topics.
# Have the function return a list of courses from COURSES
# where the supplied set and the course's value (also a set) overlap.
# For example, covers({"Python"}) would return ["Python Basics"].
COURSES = {
"Python Basics": {"Python", "functions", "variables",
"booleans", "integers", "floats",
"arrays", "strings", "exceptions",
"conditions", "input", "loops"},
"Java Basics": {"Java", "strings", "variables",
"input", "exceptions", "integers",
"booleans", "loops"},
"PHP Basics": {"PHP", "variables", "conditions",
"integers", "floats", "strings",
"booleans", "HTML"},
"Ruby Basics": {"Ruby", "strings", "floats",
"integers", "conditions",
"functions", "input"}
}
def covers(courses):
answer = []
for key,value in COURSES.items():
if value.intersections(courses):
answer.append(key)
return answer
# Create a new function named covers_all that takes a single set as an argument.
# Return the names of all of the courses, in a list, where all of the topics
# in the supplied set are covered.
# For example, covers_all({"conditions", "input"}) would return
# ["Python Basics", "Ruby Basics"]. Java Basics and PHP Basics would be excluded
# because they don't include both of those topics.
def covers_all(topics):
answer = []
for course,value in COURSES.items():
if (value & topics) == topics:
answer.append(course)
return answer
|
b9feb110f9df7260309a94d18bd3994aa18f8037
|
zakwan93/python_basic
|
/python_collection/slices_in_python.py
| 681 | 3.890625 | 4 |
favorite_things = ['raindrops on roses', 'whiskers on kittens',
'bright copper kettles','warm woolen mittens',
'bright paper packages tied up with string',
'cream colored ponies', 'crisp apple strudels']
# Question 1. Create a new variable named slice1 that has the
# second, third, and fourth items from favorite_things.
slice1 = favorite_things[1:4]
# Question 2. Get the last two items from favorite_things and put them into slice2.
slice2 = favorite_things[5:]
# Question 3. Make a copy of favorite_things and name it sorted_things.
# Then use .sort() to sort sorted_things.
sorted_things = favorite_things[:]
sorted_things.sort()
|
2e183f4fe20f994cdde4f50993b5ea410a39966b
|
cliefsengkey/text_preprocessing
|
/elongated.py
| 2,300 | 3.59375 | 4 |
#!/usr/bin/env python
"""Remove consecutive duplicate characters unless inside a known word.
"""
import fileinput
import re
import sys
from itertools import groupby, product
import enchant # $ pip install pyenchant
tripled_words = set(['ballless', 'belllike', 'crosssection', 'crosssubsidize', 'jossstick', 'shellless','aaadonta', 'flying','jibbboom', 'peeent', 'freeer', 'freeest', 'ishiii', 'frillless', 'wallless', 'laparohysterosalpingooophorectomy', 'goddessship', 'countessship', 'duchessship', 'governessship', 'hostessship', 'vertuuus','crossselling','crossshaped','crossstitch','fulllength','illlooking','massspectrometry','missstay','offform','palllike','pressstud','smallleaved','shellless','shelllike','stilllife','threeedged'])
def remove_consecutive_dups(s):
# return number of letter >= 1
# return re.sub(r'(?i)(.)\1+', r'\1', s)
# return number of letter >= 2
return re.sub(r'(?i)(.)\1+', r'\1\1', s)
def all_consecutive_duplicates_edits(word, max_repeat=float('inf')):
chars = [[c*i for i in range(min(len(list(dups)), max_repeat), 0, -1)]
for c, dups in groupby(word)]
return map(''.join, product(*chars))
def has_long(sentence):
elong = re.compile("([a-zA-Z])\\1{2,}")
return bool(elong.search(sentence))
if __name__ == '__main__':
words = enchant.Dict("en")
is_known_word = words.check
sentence = "that's good if you keep the bees safe. happy life. cooooll. let's play fooooootballll"
# print has_long(sentence)
input_w = "fooooootballll"
if has_long(sentence):
if not any(input_w in x for x in tripled_words):
print remove_consecutive_dups(input_w),is_known_word(remove_consecutive_dups(input_w)), words.suggest(remove_consecutive_dups(input_w))
words_map = all_consecutive_duplicates_edits(input_w)
print "-----------------------------------------\n"
for word in words_map:
print word, is_known_word(word)
if is_known_word(word):
print words.suggest(word)
# for line in fileinput.input(inplace=False):
# #NOTE: unnecessary work, optimize if needed
# output = [next((e for e in all_consecutive_duplicates_edits(s)
# if e and is_known_word(e)), remove_consecutive_dups(s))
# for s in re.split(r'(\W+)', line)]
# sys.stdout.write(''.join(output))
|
55abc569fa46bcce6c6f4220398cabeaa1b208d2
|
Jeevan1351/Python_Bootcamp
|
/Activity_05.py
| 110 | 3.890625 | 4 |
string = input().split()
numbers = [int(num) for num in string]
print(f"Sum of all numbers is {sum(numbers)}")
|
ba18b9f9762a1ba1508498c9477a70231f0b0551
|
Jeevan1351/Python_Bootcamp
|
/Activity_16.py
| 404 | 3.53125 | 4 |
def get_cs():
return input()
def cs_to_lot(string):
separated = string.split(';')
listOt = [tuple(i.split('=')) for i in separated]
return listOt
def lot_to_cs(listOfTuples):
string = ""
for (a, b) in listOfTuples:
string += a+"="+b+";"
return string
def display(l):
print(l)
def main():
cs = get_cs()
lot = cs_to_lot(cs)
display(lot)
main()
|
a3758742978f5c16ff5458b081d608ffbf94f3b9
|
mayukhpankaj/python-course
|
/variables.py
| 431 | 4 | 4 |
print("hello world")
# x = 1 # int
y = 2.5 # float
# name = 'john' #string
# is_cool = True # bool
#multiple assignment
x,y, name, is_cool = (1,2.5,'john',True)
# print(x+y)
# x= str(x)
''' type casting '''
# y = int(y);
# z = float(y)
# print(y,z)
""" arguments by position """
name = 'may'
age=20
print('My name is {nm} & Im {yr} years old'.format(nm=name,yr=age))
|
8864c656c917602b6add9f62aa7ae489c9513e8d
|
N8Brooks/lcs_hash_search
|
/lcs_finder.py
| 1,458 | 3.875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 23 13:50:03 2019
@author: Nathan
"""
import sys
import serial_hash_search
import parallel_hash_search
PARALLEL = False
# function to read in utf-8 txt file
def read_text(file_name):
with open(file_name, 'r', encoding='utf-8') as file:
return file.read()
if __name__ == '__main__':
"""
Command line arguments:
str: the path to the text file to compute the lcs of
str: the path to the second text file to compute the lcs of
Prints:
int: the length of the lcs
list: a list of all longest common substrings
"""
# read in command line arguments
if len(sys.argv) is 3:
# read in text files
a = read_text(str(sys.argv[1]))
b = read_text(str(sys.argv[2]))
else:
print('Please enter to txt file arguments to read.')
exit()
# grab parallel version if indicated
lcs = parallel_hash_search.lcs if PARALLEL else serial_hash_search.lcs
# get the length of lcs and list of longest common substrings
length, substrings = lcs(a, b)
if len(substrings) is 1:
multiple = ['is', len(substrings), '']
else:
multiple = ['are', len(substrings), 's']
# print
print(f'The length of the longest common substring is: {length}')
print('There {} {} longest common substring{}:'.format(*multiple))
print('\n'.join(f'"{s}"' for s in substrings), end='')
|
c994d133c51deeeaa55531bb945cde1661e6be87
|
sleumas2000/FF2-Code
|
/ff2 encode.py
| 5,428 | 3.953125 | 4 |
version = "v. 0.1.0"
#Error #01 textinput() - Invalid Input (empty)
#Error #02 keyinput() - Invalid input (02.1: Invalid Length ;02.2: Char1 Bad ;02.3: Char2 Bad)
#Error #03 keygen() - Unspecified Error
import string
import time
import random
from datetime import datetime
alphabet = list(map(chr, range(ord('a'), ord('z')+1)))
alphabet = alphabet + ['0','1','2','3','4','5','6','7','8','9']
errorlog = []
debuglog = ""
def logerror(errorNo):
global errorlog
errorlog += [[errorNo,datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")]]
def keygen():
a = alphabet[random.randint(0,35)]+alphabet[random.randint(0,35)]
return a
def FF2textinput():
input = ""
input = raw_input(">")
input = input.lower()
input = input.replace(" ","")
input = str("" if input is None else input)
for c in input
if c in alphabet: #
input2 += c #
input = input2
if not (input == ""):
return input
else:
logerror("01")
return False
def keyinput():
key = raw_input("\n\nIf you want to use a random key (recommended) press ENTER, else type the two characters. you wish to use as the key. Only type standard Letters or Numbers. Type help for more info.\n\n>")
key = str("" if key is None else key)
key = key.lower()
if (key == "help" or key == "h" or key == "?"):
FF2help(keyinput)
elif key == "":
key = keygen()
if ((len(key) == 2) and (key[0] in alphabet) and (key[1] in alphabet)):
return key
else:
print("Sorry, something went wrong with the random key generator. Please enter a key manually:")
logerror("03")
return False
elif ((len(key) == 2) and (key[0] in alphabet) and (key[1] in alphabet)):
print("A Custom key of \""+key+"\" will be used to encode your message")
return key
else:
if not (len(key) == 2):
print("Sorry, your input was not a valid key. Your input should be two characters long. (#02.1)\n")
logerror("02.1")
elif not (key[0] in alphabet):
print("Sorry, your input was not a valid key. Please type two standard letters or numbers. The first character is not a legal character. (#02.2)\n")
logerror("02.2")
elif not (key[0] in alphabet):
print("Sorry, your input was not a valid key. Please type two standard letters or numbers. The second character is not a legal character. (#02.3)\n")
logerror("02.3")
else:
print("Sorry, your input was not a valid key. Please type two standard letters or numbers. Symbols are not supported. (#02)\n")
logerror("02")
return False
def tonum(char):
i=0
for c in alphabet:
if c == char:
return i
i += 1
logerror("04")
return False
def NumCat(grid):
output = 0
for i in grid:
output = output*36
output += i
return output
def debugadd(debugData):
global debuglog
debuglog += debugData
debuglog += "\n"
##############################
# REAL ENCODER STARTS HERE #
##############################
def obtainxy(char,grid):
y = 0
for r in grid:
x=0
for c in r:
if c == char:
return (x,y)
x +=1
y += 1
def encode3(char1,char2,gridItems):
# print gridItems
grid=[gridItems[0:6],gridItems[6:12],gridItems[12:18],gridItems[18:24],gridItems[24:30],gridItems[30: ]]
# print 1,char1
# print "g",grid
y = 0
char1x,char1y = obtainxy(char1,grid)
char2x,char2y = obtainxy(char2,grid)
if char1x == char2x:
return alphabet[grid[(char1y+1)%6][(char2x+1)%6]] + alphabet[grid[(char2y+1)%6][(char1x+1)%6]]
if char1y == char2y:
return alphabet[grid[(char1y+1)%6][(char2x+1)%6]] + alphabet[grid[(char2y+1)%6][(char1x+1)%6]]
# print char1x
# print char1y
# print char2x
# print char2y
# print grid
# print grid[char2x][char1y]
# print grid[char1x][char2y]
# print alphabet[grid[char2x][char1y]]
# print alphabet[grid[char1x][char2y]]
return alphabet[grid[char1y][char2x]] + alphabet[grid[char2y][char1x]]
def encode2(char1,char2,key):
grid = []
diff = (tonum(key[1])-tonum(key[0]))%36
letter = tonum(key[0])
for i in range(0,36):
if letter in grid:
letter += 1
grid += [letter]
letter = (letter+diff)%36
if not alphabet[letter] == key[0]:
logerror("05")
debugadd(char1+key[0]+"."+str(tonum(char2))+","+str(tonum(char1))+"."+str(NumCat(grid))+"\\"+char2+key[1])
return encode3(tonum(char1),tonum(char2),grid)
def encode(inputText,key): #TODO
if not len(key) == 2:
print "THIS SHOULD NOT HAPPEN. PYTHON IS BROKEN!"
i = 0
encoded = ""
activekey = key
output = ""
while i < ((len(inputText)+1)/2):
char1 = inputText[(2*i)]
if ((len(inputText))%2) == 0 or len(inputText) > i*2+1:
char2 = inputText[(2*i)+1]
else:
char2 = 'x'
output += encode2(char1,char2,activekey)
activekey = output[-2:]
i += 1
output = output[0]+key[0]+output[1:]+key[1]
return output
####################
# START OF PROGRAM #
####################
print("FF2 Cipher encoder: "+version+"\n\n\n Type the text you wish to encode. Press enter when finished\n")
text = False
while text == False:
text = FF2textinput()
key = False
while key == False: #loop if keyinput() returns False (if it encounters an error)
key = keyinput()
output = encode(text,key)
print "\n\nEncoded message:\n "+output+"\n\n\nPress enter to quit"
finalcommand=raw_input()
if finalcommand.lower() == "e":
print errorlog
elif finalcommand.lower() == "d":
print debuglog
elif finalcommand.lower() == "b":
print str(errorlog)+"\n\n"+str(debuglog)
elif finalcommand.lower() == "r":
restart()
elif finalcommand.lower() == "br":
print errorlog
|
d633cbd6250f0bc4db56d073cc59c7ecb9eb3b51
|
krvavizmaj/codechallenges
|
/src/codesignal/areSimilar.py
| 283 | 3.734375 | 4 |
def areSimilar(a, b):
da = []
db = []
for i,n in enumerate(a):
if a[i] != b[i]:
da.append(a[i])
db.append(b[i])
return len(da) <= 2 and len(db) <= 2 and sorted(da) == sorted(db)
a = [1, 1, 4]
b = [1, 2, 3]
print(areSimilar(a,b))
|
728d2995b0d5d34a4a71e85f8050e50d784e2047
|
krvavizmaj/codechallenges
|
/src/codesignal/naturalNumbers.py
| 230 | 3.859375 | 4 |
def naturalNumbersListing(n):
s = 0
i = 1
t = 2
while i <= n:
s += i
if i < n: s += i + 1
i += t
t += 1
i += t
t += 1
return s
print(naturalNumbersListing(3))
|
6119f7a769b58aeae30c9f31e7f4bbcbf945da0a
|
IrfanChairurrachman/CS50x-2020
|
/pset7/houses/roster.py
| 713 | 3.734375 | 4 |
# TODO
import sys, cs50
# check argv
if len(sys.argv) != 2 or sys.argv[1] not in ['Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherin']:
sys.exit("Usage: python roster.py [house name] or there's no house name")
sys.exit(1)
# connect to db
db = cs50.SQL("sqlite:///students.db")
# execute SQL command and store to students list
students = db.execute("SELECT * FROM students WHERE house = (?) order by last, first", sys.argv[1])
for student in students:
if student['middle'] == None:
print("{} {}, born {}".format(student['first'], student['last'], student['birth']))
else:
print("{} {} {}, born {}".format(student['first'], student['middle'], student['last'], student['birth']))
|
8b3133a4c9d25ef07b543e50c9e870c5c8d624f3
|
Helyosis/ChessBot
|
/utils.py
| 2,562 | 3.6875 | 4 |
import random
alphabet = "abcdefghijklmnopqrstuvwxyz1234567890"
VIDE, PION_BLANC, PION_NOIR, TOUR_BLANC, TOUR_NOIR, CAVALIER_BLANC, CAVALIER_NOIR, FOU_BLANC, FOU_NOIR, REINE_BLANC, REINE_NOIR, ROI_BLANC, ROI_NOIR = \
'O', 'P', 'p', 'T', 't', 'C', 'c', 'F', 'f', 'R', 'r', 'K', 'k'
def generate_random_name():
name = ['c-']
for i in range(10):
name.append(random.choice(alphabet))
return "".join(name)
def create_blank_game():
"""
Sens de lecture de haut en bas puis de gauche à droite
:return text version of blank game
"""
tableau = [
TOUR_NOIR, CAVALIER_NOIR, FOU_NOIR, REINE_NOIR, ROI_NOIR, FOU_NOIR, CAVALIER_NOIR, TOUR_NOIR,
PION_NOIR * 8,
VIDE * 8 * 4,
PION_BLANC * 8,
TOUR_BLANC, CAVALIER_BLANC, FOU_BLANC, REINE_BLANC, ROI_BLANC, FOU_BLANC, CAVALIER_BLANC, TOUR_BLANC
]
tableau = "".join(tableau)
return tableau
def place_to_coordinates(place):
"""
Return a number indicating the coordinate in single-dimension array containing the description of the chess game using the place in chess
:param place: str matching the regex [abcdefgh][12345678]
:return: coordinate of corresponding place
"""
letter, num = list(place)
y = 8 - int(num)
x = ord(letter) - ord('a')
return 8 * y + x
def coordinates_to_place(index):
"""
Return the matching place on the board on a certain index. Index go from up to bottom and then from left to right
:param index: int
:return: Char[2]
"""
y, x = index // 8, index % 8
row = str(8 - y)
column = chr(x + ord('a'))
return column + row
def can_go_to(piece1, piece2):
"""
Returns True if one piece is black (lowercase) and the other is white (uppercase) and vice-versa
Used to determine if one piece can eat the other.
Return False otherwise
:param piece1: Char
:param piece2: Char
:return: Bool
"""
return ((piece1.isupper() and piece2.islower()) or (piece1.islower() and piece2.isupper())) or 'O' in {piece1,
piece2}
def are_differents(piece1, piece2):
"""
Same as can_go_to but return False if p1 or p2 == 'O'
:param piece1: Char
:param piece2: Char
:return: Bool
"""
return ((piece1.isupper() and piece2.islower()) or (piece1.islower() and piece2.isupper())) and 'O' not in {piece1,
piece2}
|
be7cfbeedb0c2a6df04bb57e4bf7539fe0438ce0
|
ligb1023561601/CodeOfLigb
|
/OOP.py
| 3,875 | 4.1875 | 4 |
# Author:Ligb
# 1.定义一个类,规定类名的首字母大写,括号是空的,所以是从空白创建了这个类
# _init_()方法在创建类的新实例的时候就会自动运行,两个下划线是用来与普通方法进行区分
# self是一个自动传递的形参,指向实例本身的引用,在调用方法时,不必去给它传递实参
# 以self作前缀的变量称之为属性
# 命名规则
# object() 共有方法 public
# __object()__ 系统方法,用户不这样定义
# __object() 全私有,全保护方法 private protected,无法继承调用
# _object() private 常用这个来定义私有方法,不能通过import导入,可被继承调用
# 两种私有元素会被转换成长格式(公有的),称之为私有变量矫直,如类A有一私有变量__private,将会被转换成
# _A__private作为其公有变量,可以被继承下去
class Dog(object):
def __init__(self, name, age):
"""初始化属性name与age"""
self.name = name
self.age = age
def sit(self):
"""类中的函数称为方法"""
print(self.name.title() + " is now sitting!.")
def roll_over(self):
print(self.name.title() + " rolled over!")
my_dog = Dog("he", 2)
my_dog.sit()
my_dog.roll_over()
class Car(object):
"""创建一个汽车类"""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 属性具有默认值
def _get_information(self):
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def update_info(self,date):
"""通过方法修改属性"""
self.year = date
def increment_info(self,miles):
"""通过方法进行属性递增"""
self.odometer_reading += miles
def fill_gas_tank(self):
print("This car's gas tank is full!")
my_car = Car("audi", "big", "1993")
my_car_info = my_car._get_information()
print(my_car_info)
# 2.给属性指定默认值
# 3.三种方法进行修改:通过实例修改,通过方法进行设置,通过方法进行递增(类似于方法进行设置)
my_car.model = "small"
# 4.继承
# 在括号中的类称为父类,super()函数可以令子类包含父类的所有实例
# 在Python2.7中,继承语法为
# super(Electric_Car,self)._init_(make,model,year)
# 5.重写父类中的方法,可实现多态,父类中的方法将被忽略,包括init方法,若子类不写,则用父类的init方法
class Battery(object):
"""将电动车的电池相关属性提取出来"""
def __init__(self,battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kwh battery.")
def get_mileage(self):
"""显示行驶里程"""
if self.battery_size == 70:
mileage = 240
elif self.battery_size == 85:
mileage = 270
message = "This car can go approxiamately " + str(mileage)
message += "miles on a full charge."
print(message)
class ElectricCar(Car):
def __init__(self,make,model,year):
"""初始化父类属性,并定义电动车独有的属性"""
super().__init__(make, model, year)
self.battery_size = Battery()
def fill_gas_tank(self):
print("Electric Cars do not have a gas tank!")
my_tesla = ElectricCar("Tesla", "medium","2017")
print(my_tesla._get_information())
my_tesla.battery_size.describe_battery()
my_tesla.battery_size.get_mileage()
# 6.将实例用作属性,将类中某些相近的属性再疯封装成小类,然后将这些小类实例化后作为大类的属性,以达到更清晰的结构
# 7.导入类:实现代码的简洁原则,内容在my_car.py中
|
f67f4de0d26bc09bf7e9aed47455b94f222d8417
|
otterchurchill/CircleCITest
|
/scopeChecker.py
| 1,358 | 3.625 | 4 |
def isOpener(chara, openers):
return (chara in openers)
def isCloser(chara, closers):
return(chara in closers)
def scopeCheck(scopeSequence, scopeMatch):
s = []
for x,chara in enumerate(scopeSequence):
print(chara)
if isOpener(chara, scopeMatch.values()):
print(chara, "was appended")
s.append(chara)
if isCloser(chara, scopeMatch.keys()):
if s == []:
print("got to closer but empty stack")
return False
else:
if s[-1] == scopeMatch[chara]:
print("popped because", chara, "is paired to the top:", s[-1])
s.pop()
if s == [] and x == (len(scopeSequence)-1):
return True
else:
continue
else:
print("failed because", chara, "is not equal to the top:", s[-1])
return False
if s != []:
print("failed because something left on the stack")
return False
def main():
scopeMatch = { ')':'(', ']':'[', '}':'{' }
scopeSeqs = ["{()[]}", "{([)]}", "{[()][]}", "{}]", "[{}"]
for seq in scopeSeqs:
print(seq, scopeCheck(seq, scopeMatch))
if __name__ == '__main__':
main()
|
cba1b0b5f23f3f4044813a11a1dd4c973856ee84
|
kawsing/mypython
|
/radom-learn.py
| 638 | 3.765625 | 4 |
import random
#從列表隨機取一個資料
data=random.choice([1,4,6,9])
print(data)
#從列表中隨機取n個資料,n < 列表數量
data=random.sample([1,2,3,4,5,6], 5)
print(data)
#隨機調換資料(修改原列表) ,就地修改data列表
data=[1,2,3,4]
random.shuffle(data)
print(data)
#取0~1中的隨機數字,每個數字出現機率『相同』,random.random()=random.uniform(0.0,1.0)
print(random.random())
print(random.uniform(0.0, 1.0))
#指定範圍,uniform指機率相同
print(random.uniform(60, 100))
#常態分配
#取平均數100,標準差10
#常態分配亂數
print(random.normalvariate(100,10))
|
f99b66ba14100c318077afb9c03dbdddbbda55f6
|
kawsing/mypython
|
/function.py
| 273 | 3.546875 | 4 |
#-*- coding: utf-8 -*-
#範例
def sayHello():
print("Hello")
#使用parameter
def sayIt(msg):
print(msg)
#two parameter
def add(n1, n2):
result=n1+n2
print(result)
sayHello()
sayIt("你好,python")
sayIt("第二次呼叫python")
add(3,5)
add(1000,18090)
|
86a0653f30732b468566eb5dc9758a88bfddca8d
|
luciano00filho/python-homeworks
|
/questao4.py
| 980 | 3.71875 | 4 |
#/usr/bin/python3.6
import sys
def montaMatriz(linhas,colunas):
matriz = [0.0] * linhas
for i in range(linhas):
matriz[i] = [0.0] * colunas
return matriz
def geraNumeros(vmin,vmax,linhas,colunas):
for x in range(vmin,(linhas * colunas),1):
print("x1 =",x)
def main():
dimension, interval, matrix, rows, cols, vmin, vmax, listaNum, cont = '','',[[]],0,0,0,0,[],0
dimension = input("Qual o tamanho da matriz? ").split()
rows = int(dimension[0]) # linhas
cols = int(dimension[1]) # colunas
interval = input("Qual o intervalo de valores? ").split()
vmin = int(interval[0]) # mínimo
vmax = int(interval[1]) # máximo
# crio a matriz zerada
matrix = montaMatriz(rows,cols)
print("matrix =",matrix)
# gero os números
geraNumeros(vmin,vmax,rows,cols)
sys.exit()
# modifico a matriz
for i in range(rows):
for j in range(cols):
print("cont =",cont)
matrix[i][j] = listaNum[cont]
cont += 1
print(matrix)
if __name__ == '__main__':
main()
|
5019da761a24822a02a49ac8a7abca2e5d12b28c
|
aryan2412/sample
|
/evenoroddinlist.py
| 272 | 3.984375 | 4 |
even=0
odd=0
a=[]
b=int(input("Enter no. of elements=")) #User Input for list size
for i in range(0,b):
t=int(input("Enter in list=")) #User Input for elements of List
a.append(t)
for i in a:
if(i%2==0):
even+=1
else:
odd+=1
|
ecb83cf2aaf43a4610880ade0ec6d222f9eb6fef
|
jswojcik/Py4e
|
/Assignment 7.2.py
| 361 | 3.765625 | 4 |
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
count = 0
tot = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"): continue
pos = line.find(' ')
num = line[pos:]
num = float(num)
count = count + 1
tot = num + tot
print(tot)
ans = tot / count
print("Average spam confidence:", ans)
|
ceb571472cd16c49dc15cb002126dff8e2b50da9
|
imn00133/PythonSeminar19
|
/Users/softwareMaestro/convert_fahrenheit_celsisus/convert_fahrenheit_celsisus.py
| 611 | 3.75 | 4 |
#-*- coding: utf-8 -*-
inputNumber=float(input("변환할 화씨온도(℉를) 입력하십시오: "))
print("%0.2f℉는 %0.2f℃입니다." %(inputNumber, (inputNumber-32)*5/9))
# 1. #-*- coding: utf-8 -*-은 python2.x버전에서 인코딩을 알려주는 규약입니다.
# python3에서는 사용하지 않으셔되 됩니다.
# 2. 1번 줄에서의 빨간 줄은 # 뒤에 공백이 없어서 발생합니다.
# 3. 2번 줄에서의 빨간 줄은 '=' 연산자 주변에 공백이 없어서 그렇습니다.
# 4. 3번 줄에서의 빨간 줄은 '%' 뒤에 공백이 없어서 그렇습니다.
# 김재형
|
0cb3637b005033512e14949647e04b08a78d4f5a
|
imn00133/PythonSeminar19
|
/Users/Miya/times_table/times_table.py
| 170 | 3.640625 | 4 |
for i in range(1, 10):
for j in range(2, 10):
print("%d * %d = %2d" % (j, i, j*i), end=' ')
print("")
# 잘 해결하셨습니다.
# 주강사 김재형
|
82912fd6df868d125842abaf22b4fc50b60073ea
|
imn00133/PythonSeminar19
|
/Users/Miya/BMI_calculator/BMI_calculator.py
| 625 | 3.921875 | 4 |
height = float(input("본인의 키를 입력하세요.(m): "))
weight = int(input("본인의 몸무게를 입력하세요.(kg): "))
calc = float("%.1f" % (weight / pow(height, 2)))
if calc < 18.5:
print("저체중")
elif calc < 23:
print("정상")
elif calc < 25:
print("과체중")
elif calc < 30:
print("경도비만")
elif calc < 35:
print("중증도 비만")
elif calc >= 35:
print("고도 비만")
else:
print("안알랴줌")
# 마지막에 cal >=35와 else를 따로 넣은 이유가 궁금합니다?
# 그 이외에는 잘 해결했습니다. 수고하셨습니다.
# 주강사 김재형
|
28cc003d0526bb94d79c3e77f0d4c3dbbec6d880
|
ReviewEdge/Text-Based-Operating-System
|
/main.py
| 18,535 | 3.78125 | 4 |
# -*- coding: utf-8 -*-
import time
import requests
import datetime
import smtplib
import imapclient
import imaplib
imaplib._MAXLINE = 10000000
import pprint
import pyzmail
# Declares globals
global logged_in
logged_in = False
global has_email
has_email = False
# creates date and time variables
now = datetime.datetime.now()
date_and_time_data = now.strftime("%b %d, %Y %I:%M %p")
date_data = now.strftime("%b %d, %Y")
time_data = now.strftime("%I:%M %p")
# for email
email_search_date = now.strftime("%Y/%m/%d")
def new_file():
new_file_name = input("Enter a name for your file:\n") + ".txt"
file_1 = open(new_file_name, "w")
new_file_text = input("Enter text for your new file. Press ENTER when you are finnished:\n") + "\n\n"
file_1.write(new_file_text)
file_1.close()
print("File created. Closing file creator...\n")
time.sleep(1)
def open_file_func():
file_name_op = input("Enter the name of the file you would like to access (without .txt):\n") + ".txt"
try:
open_file = open(file_name_op, "r+")
except IOError:
print("\nFile not found.\n")
time.sleep(.8)
open_file_func()
else:
#open_file.read()
print("\n\n" + open_file.read() + "\n\n")
ans = input("Would you like to edit this file? (Y/n)\n").lower()
if ans == "y":
print("Enter text to add to the file.\nPress ENTER when you are finnished:\n")
text_to_add = input() + "\n\n"
open_file.write(text_to_add)
print("Closing editor...\n")
open_file.close()
time.sleep(1)
# runs the files app
def files():
x = "on"
while x != "off":
print("\tFILES\n")
print("\t\t'create' 'open' 'off'")
x = input()
if x == "create":
new_file()
if x == "open":
open_file_func()
def weather():
city_id = "5122534"
url = "http://api.openweathermap.org/data/2.5/weather?id=" + city_id + "&units=imperial&APPID=c3e072c5029f60ac53dac3d1c7d9b06f"
json_data = requests.get(url).json()
temp_val = str(json_data["main"]["temp"])
description = str(json_data["weather"][0]["description"])
description = description.capitalize()
format_add = description + "\n" + "Temperature: " + temp_val + " " + "°F"
# prints what is being returned
#print("Current weather in Jamesown, NY: \n\n" + format_add)
return "Current weather in Jamesown, NY: \n" + format_add
def save_email_know(email_ad,password):
# ADD ABILITY TO CHECK IF NUMBER HAS BEEN USED
account_num = input("Enter a user number for your account:")
new_file_name = "email_account_" + account_num + ".txt"
file_1 = open(new_file_name, "w")
new_file_text = "A" + email_ad + "P" + password
file_1.write(new_file_text)
file_1.close()
print("Your email account information has been saved as account #" + account_num + "\n\n")
time.sleep(2)
def send_email():
if logged_in and has_email:
email = global_email_address
password = global_email_password
if logged_in and (has_email == False):
print("\nYou have not saved an email to your account. You can do this in the 'account' app.\n")
time.sleep(1)
if has_email == False:
email = input("Enter your email adress: ")
password = input("Enter password: ")
#save_it = input("\nWould you like to save your information? (Y/n):\n").lower()
#if save_it == "y":
# save_email_know(email,password)
# starts connection
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
'''
saved = input("Do you have a saved account (Y/n)?\n").lower()
if saved == "y":
account_num = input("Enter you account #:\n")
open_file = open("email_account_" + account_num + ".txt", "r+")
info = open_file.read()
pas_idx = info.index("P")
email = info[1:pas_idx]
password = info[pas_idx+1:]
'''
time.sleep(.4)
print("\nSending email as " + email + "\n")
time.sleep(1)
# creates variables
sendaddress = input("Enter the recipient's email address:\n")
subject = input("Enter the email's subject:\n")
message = input("Enter the email's message:\n")
full_message = "Subject: " + subject + " " + " \n" + message
# sends email
smtpObj.login(email, password)
smtpObj.sendmail(email, sendaddress, full_message)
# quits connection
smtpObj.quit()
print("\nEmail sent.\n")
time.sleep(1.5)
#add ability to search for emails -google search?
#ability to show only beginning of email then ask to see more
def read_email():
global has_email
if logged_in and has_email:
email = global_email_address
password = global_email_password
if logged_in and (has_email == False):
print("\nYou have not saved an email to your account. You can do this in the 'account' app.\n")
time.sleep(1)
if has_email == False:
email = input("Enter your email address: ")
password = input("Enter password: ")
#save_it = input("\nWould you like to save your information? (Y/n):\n").lower()
#if save_it == "y":
# save_email_know(email, password)
'''
saved = input("Do you have a saved account (Y/n)?\n").lower()
if saved == "y":
account_num = input("Enter you account #:\n")
open_file = open("email_account_" + account_num + ".txt", "r+")
info = open_file.read()
pas_idx = info.index("P")
email = info[1:pas_idx]
password = info[pas_idx + 1:]
'''
print("\nViewing email as " + email + "\n")
imapObj = imapclient.IMAPClient("imap.gmail.com", ssl=True)
imapObj.login(email, password)
imapObj.select_folder("INBOX", readonly=True)
#print(email_search_date)
#choses search terms:
UIDs = imapObj.gmail_search("after:" + email_search_date)
#UIDs = imapObj.search(['SINCE '+ email_search_date])
#print(UIDs)
print("You have " + str(len(UIDs)) + " recent emails.\n")
time.sleep(1)
def fetch_email(pos,email_num):
rawMessages = imapObj.fetch(UIDs, ["BODY[]"])
message = pyzmail.PyzMessage.factory(rawMessages[UIDs[pos]][b'BODY[]'])
readable_text = ""
if message.text_part != None:
readable_text += str(message.text_part.get_payload().decode())
# this is code for handling HTML:
# if message.html_part != None:
# readable_text += "\n" + str(message.html_part.get_payload().decode(message.html_part.charset))
print("\t" + "Email " + str(email_num) + "\n")
time.sleep(.6)
print("\nEmail from: " + str(message.get_address('from')[1]) + "\n\n\"" + str(
message.get_subject()) + "\"\n\n" + readable_text)
if pos > 0:
email_num += 1
pos -= 1
next_ask = input("\n\n\t'n' for next email, 'off' to stop: \n").lower()
print("\n")
if next_ask == "n":
fetch_email(pos,email_num)
fetch_email(len(UIDs)-1,1)
# This is now obsolete:
def save_email():
x = input("\n'save' allows you to enter and store your email account information.\nWould you like to proceed (Y/n)?\n").lower()
if x == "y":
email_ad = input("Enter your email adress: ").lower()
password = input("Enter password: ")
# ADD ABILITY TO CHECK IF NUMBER HAS BEEN USED
account_num = input("Enter a user number for your account:")
new_file_name = "email_account_" + account_num + ".txt"
file_1 = open(new_file_name, "w")
new_file_text = "A" + email_ad + "P" + password
file_1.write(new_file_text)
file_1.close()
print("Your email account information has been saved as account #" + account_num + "\n\n")
time.sleep(2)
# runs the email app
def email():
x = "on"
while x != "off":
print("\tEMAIL\n")
print("\t\t'send' 'read' 'save' 'off'")
x = input()
if x == "send":
send_email()
if x == "read":
read_email()
if x == "save":
save_email()
def phys():
print("\nEnter knowns. Enter unknowns as \".0\"\n")
time.sleep(.5)
try:
v_i = float(input("Initial Velocity (m/s): "))
v_f = float(input("Final Velocity (m/s): "))
a = float(input("Acceleration (m/s^2): "))
t = float(input("Time (s): "))
d = float(input("Distance (d): "))
except(ValueError):
time.sleep(.5)
print("\nInvalid Input")
time.sleep(1)
phys()
print("\n")
# finds final velocity
def find_v_f(v_i, a, t):
return v_i + a * t
# finds initial velocity
def find_v_i(v_f, a, t):
return v_f - (a * t)
# finds acceleration
def find_a(v_f, v_i, t):
return (v_f - v_i) / t
# finds time
def find_t(v_f, v_i, a):
return (v_f - v_i) / a
# finds v_i (with distance)
def find_v_i_with_d(a, t, d):
return (-0.5 * a * t * t + d) / t
time.sleep(.5)
# decides what function to run
# runs if doesn't have v_f, and fines v_i
if v_f == .0 and v_i != .0 and a != .0 and t != .0:
print("Final Velocity: " + str(find_v_f(v_i, a, t)))
# runs if doensn't have v_i, and finds v_i
elif v_i == .0 and v_f != .0 and a != .0 and t != .0:
print("Initial Velocity: " + str(find_v_i(v_f, a, t)))
# runs if doensn't have a, and finds a
elif a == .0 and v_f != .0 and v_i != .0 and t != .0:
print("Acceleration: " + str(find_a(v_f, v_i, t)))
# runs if doensn't have t, and finds t
elif t == .0 and v_f != .0 and v_i != .0 and a != .0:
t = find_t(v_f, v_i, a)
if t >= 0:
print("Time: " + str(t))
else:
print("Invalid Knowns (would result in negative time)")
print("Time: " + str(t))
# runs if doesn't have v_i or v_f but has d, t, and a
elif v_f == .0 and v_i == .0 and t != .0 and a != .0 and d != .0:
v_i = find_v_i_with_d(a, t, d)
print("Initial Velocity: " + str(v_i))
# now finds v_f
v_f = find_v_f(v_i, a, t)
print("Final Velocity: " + (str(v_f)))
else:
print("Knowns are invalid, or calculator does not yet have this ability.")
# finds distance
if d == .0:
d = (v_i * t) + 0.5 * a * t * t
print("Distance: " + str(d))
print("\n")
time.sleep(1)
#FINNISH THIS
def calc_nums():
calculate = input("Enter math problem:\n")
print("\n" + str(calculate) + " = " + str(eval(calculate)) + "\n\n")
time.sleep(1.2)
def calc():
x = "on"
while x != "off":
print("\tCALCULATOR\t")
print("\t\t'calc' 'phys' 'off'")
x = input()
if x == "calc":
calc_nums()
if x == "phys":
phys()
user = "***"
def log_in():
saved = input("Do you have a login account (Y/n)?\n").lower()
if saved == "y":
username = input("Enter your username:\n").lower()
def password_check(username_param):
file_name_op = ("user_" + username_param + ".txt")
try:
open_file = open(file_name_op, "r+")
except IOError:
print("\nThat username doesn't exist.\n")
time.sleep(1)
log_in()
return
else:
open_file = open(file_name_op, "r+")
info = open_file.read()
pas_attempt = input("Enter your password:\n")
pas_idx_start = info.index(";2P;")
pas_idx_end = info.index("#2P#")
password = info[pas_idx_start + 4:pas_idx_end]
if pas_attempt == password:
open_file.close()
global logged_in
logged_in = True
global user
user = username
time.sleep(.4)
print("\nYou are now logged in as " + username + ".\n\n")
time.sleep(1.5)
else:
time.sleep(.5)
print("Incorrect Password\n")
continue_pascheck = input("Do you know your password? (Y/n)\n")
if continue_pascheck != "Y" or "y":
log_in()
return
time.sleep(.5)
open_file.close()
password_check(username)
return
password_check(username)
else:
def revert(entering):
print("\nInvalid " + entering + "\n")
time.sleep(.5)
print("Please restart.\n")
time.sleep(.8)
log_in()
save_it = input("\nWould you like to create a login account? (Y/n):\n").lower()
if save_it == "y":
username = input("Enter a username (do not use special characters):\n").lower()
if "#" in username:
revert("username")
elif ";" in username:
revert("username")
else:
new_file_name = ("user_" + username + ".txt")
"""
file_1 = open(new_file_name, "w")
new_file_text = ";1U;" + username + "#1U#" + ";2P;" + password + "#2P#"
file_1.write(new_file_text)
file_1.close()
print("Your login, " + username + ", has been saved\n\n")
time.sleep(2)
log_in()
"""
password = input("Enter password (case sensitive, do not use special characters): \n")
if "#" in password:
revert("password")
elif ";" in password:
revert("password")
else:
new_file_name = ("user_" + username + ".txt")
file_1 = open(new_file_name, "w")
new_file_text = ";1U;" + username + "#1U#" + ";2P;" + password + "#2P#" + "#"
file_1.write(new_file_text)
file_1.close()
print("Your login, " + username + ", has been saved\n\n")
time.sleep(2)
log_in()
# allows user to save email to account
def email_account():
file_name_op = ("user_" + user + ".txt")
open_file = open(file_name_op, "r+")
info = open_file.read()
pas_idx_end = info.index("#2P#")
if info[pas_idx_end + 4:] == "#":
email_address = input("Enter your email address:\n")
email_password = input("Enter your email password:\n")
new_file_text = ";3A;" + email_address + "#3A#" + ";4E;" + email_password + "#4E#" + "#"
open_file.write(new_file_text)
#set_email_info_vari()
time.sleep(1.8)
print("Your email, " + email_address + ", has been saved.\n\n")
else:
try:
info[pas_idx_end + 8] == None
except IndexError:
yes = input("\nYou have an outdated account. Would you like to update your account? (Y/n)\n").lower()
if yes == "y":
open_file.write("#")
time.sleep(1.2)
print("Your account has been updated.\n\n")
open_file.close()
time.sleep(1)
email_account()
return
else:
return
print("You have already saved an email to your account.\n")
time.sleep(1)
open_file.close()
# runs the account app
def account():
x = "on"
while x != "off":
print("\tACCOUNT\t")
print("\t\t'email' 'view' 'off'")
x = input()
if x == "email":
email_account()
if x == "view":
print("still in progress...")
# checks if account has email, sets email info as global variables
def set_email_info_vari():
if logged_in:
file_name_op = ("user_" + user + ".txt")
open_file = open(file_name_op, "r+")
info = open_file.read()
try:
pas_idx_end = info.index("#2P#")
info[pas_idx_end + 6] == "3"
except IndexError:
return
pas_idx_end = info.index("#2P#")
if info[pas_idx_end + 6] == "3":
global has_email
has_email = True
global global_email_address
global global_email_password
email_ad_idx_start = info.index(";3A;")
email_ad_idx_end = info.index("#3A#")
global_email_address = info[email_ad_idx_start + 4:email_ad_idx_end]
email_pas_idx_start = info.index(";4E;")
email_pas_idx_end = info.index("#4E#")
global_email_password = info[email_pas_idx_start + 4:email_pas_idx_end]
open_file.close()
# runs the program
x = "on"
print("Hello!\n")
time.sleep(.5)
log_in()
set_email_info_vari()
while x != "off":
if logged_in == True:
print("\n" + date_and_time_data + "\nLogged in as: " + user + "\n")
else:
print("\n" + date_and_time_data + "\nUsing as guest." + "\n")
x = input("Enter: 'files' 'weather' 'email' 'calc' 'login' 'account' 'off' '?'\n").lower()
if x == "files":
files()
if x == "weather":
print("\n" + weather()+ "\n")
if x == "email":
email()
if x == "calc":
calc()
if x == "login":
if logged_in == True:
print("\nYou are already logged in.\n")
else:
print("\n")
log_in()
if x == "account":
if logged_in == True:
account()
else:
print("You are not logged in.")
if x == "?":
print("Enter: \n'files' to open the files app and work with files \n'weather' to get a weather report \n'email' to send an email \n'calc' to use the calculator app \n'login' to login with an account, or to create an account \n'account' to edit your user account \n'off' to close the program")
print("Ending Program...")
time.sleep(1)
#tag files with profile, only let you open if tagged with your profile
#list users files
#check if username is taken (look for file) -handle no file found erorr
#make profile as a class (save email info, files, etc.)
#create activity log (times, apps opened)
|
51a566cd2d6025d7bc557df0ba0a29f4087a7f17
|
Bsq-collab/k05
|
/util/Occ.py
| 2,304 | 3.8125 | 4 |
'''
Team B2-4ac- Bayan Berri, Alessandro Cartegni
SoftDev1 pd7
HW03: StI/O: Divine your Destiny!
2017-09-14
'''
import random
def makedict(filename):
"""
makes a dictionary from csv file param
arg:
string filename csv file
ret:
dictionary d keys: jobs values: percents
"""
d = dict()
for line in open(filename):
newline= line[line.rfind("n")]
d[line[0:line.rfind(',')]] = line[line.rfind(',')+1:len(line)-1]#deals with the categories that include commas by searching from the end.
#rfind returns index of last comma.
if "Job Class" in d:
del d["Job Class"]
return d
def make_float(d):
"""
makes string numbers into floats (first line of csv value is a string)
arg:
dictionary d whose values are to be typecasted into floats
ret:
dictionary with values changed into floats
"""
for k in d:
try:
d[k]=float(d[k])
except:
d[k]=d[k]
return d
def make_arr(d):
"""
makes an array of 998 based on dictionary values to then select a random choice
for each key in the dictionary it adds it to an array as many times as ten times
the value. If the key is x and the value is 6.1 then x would be added to the array 61 times.
arg:
dictionary d of keys type string and values type float
ret:
array of compiled jobs based on percentages
"""
jobs=[]
for k in d:
if type(d[k])!= str and k!="Total":
ctr= int(d[k]*10) #adds every job 10 times the percentage.
while ctr!=0:
jobs.append(k)
ctr-=1
return jobs
#final selectio
def get_random(arr):
"""
Uses an array to randomly choose a job using python builtin function random.choice(arr)
arg:
array arr compilation of jobs of type string from make_arr
ret:
string from array parameter which will be the name of the job
"""
return random.choice(arr)#random.choice picks a random item from the array
def getRandom(f):
"""
wrapper function to make executing it easier
arg:
string f will be the file name used in makedict
ret:
string randomly generated from choosing a job from the array randomly
"""
return get_random(make_arr(make_float(makedict(f))))
|
2221806a1f358e55afa5692220f4586f03872c96
|
firewebteam/main-repository
|
/figury.py
| 901 | 3.828125 | 4 |
class Figury():
def __init__(self, kolor, x, y):
self.kolor = kolor
self.x = x
self.y = y
def prostokat(self):
print("Pole prostokata to", self.x*self.y)
print("Kolor prostokąta to", self.kolor)
def trojkat(self):
print("Pole trójkąta to", (self.x*self.y)/2)
print("Kolor trójkąta to", self.kolor)
def trapez(self):
print("Pole trapezu to", ((self.x*self.y)/2)*10)
print("Kolor trapezu to", self.kolor)
def romb(self):
print("Pole rombu to", self.x*self.y) #y w tym przypadku to wysokość
print("Kolor rombu to", self.kolor)
prostokat=Figury("żółty", 5, 11)
prostokat.prostokat()
trojkat=Figury("niebieski", 12, 8)
trojkat.trojkat()
trapez=Figury("zielony", 6, 16)
trapez.trapez()
romb=Figury("brązowy", 4, 6)
romb.romb()
|
ae91e9d855546eb8121f06b75df88f41b8e337d4
|
firewebteam/main-repository
|
/J.Karasek/Zadanie_6_Jasiek.py
| 156 | 3.703125 | 4 |
t = float(input("Czas:"))
v = 3.8
s = v*t
if t <= 100:
print("Jasiek przeszedł %s metrów" %s)
else:
print("Jasiek przeszedł całą drogę")
|
8cc66caa916630c06f511596bf7c55f5d9c9314d
|
firewebteam/main-repository
|
/Kamil Ko-odziej/6_Jasiek - 2.py
| 293 | 3.640625 | 4 |
v = ((3 ** 2) + (2 ** 2)) ** (1 / 2)
t = int(input('Podaj sekundę ruchu Jaśka:'))
if t > 100:
print('Jasiek przeszedł już całe %.3f metrów' % (100*v))
elif t < 0:
print('Jasiek jeszcze nie zaczął się poruszać')
else:
print('Jasiek przeszedł %.3f metrów' % (t*v))
|
59a32850a0e162a0085c334b200747d300e5e9c0
|
firewebteam/main-repository
|
/J.Karasek/Zadanie_3_konto_bankowe.py
| 878 | 3.859375 | 4 |
x = input("Imię: ")
y = input("Hasło: ")
z = 2130
while True:
if x == "Arnold" and y == "icra2013":
print ("Saldo:", z)
print("Jaką czynność chcesz wykonać?\nA - wpłata\nB - wypłata")
czynnosc = input("Czynność: ")
if czynnosc == "A":
wplata = int(input("Podaj kwotę: "))
if wplata > 0:
z += wplata
print("Twoje saldo wynosi teraz:", z)
break
else:
print("Błędna kwota")
break
elif czynnosc == "B":
wyplata = int(input("Podaj kwotę: "))
if wyplata < z:
z -= wyplata
print("Twoje saldo wynosi teraz:", z)
break
else:
print("Idź do pracy!")
break
else:
print("Błędne dane")
break
|
6ce838e30b83b79bd57c65231de2656f63945486
|
prashant2109/django_login_tas_practice
|
/python/Python/oops/polymorphism_info.py
| 2,144 | 4.40625 | 4 |
# Method Overriding
# Same method in 2 classes but gives the different output, this is known as polymorphism.
class Bank:
def rateOfInterest(self):
return 0
class ICICI(Bank):
def rateOfInterest(self):
return 10.5
if __name__ == '__main__':
b_Obj = Bank()
print(b_Obj.rateOfInterest())
##############################################################################################33
# Polymorphism with class
class Cat:
def __init__(self, name):
self.name = name
def info(self):
print(f'My name is {self.name}. I belong to cat family.')
def make_sound(self):
print('meow')
class Dog:
def __init__(self, name):
self.name = name
def info(self):
print(f'My name is {self.name}. I belong to Dog family.')
def make_sound(self):
print('Bark')
cat = Cat('kitty')
dog = Dog('tommy')
# Here we are calling methods of 2 different class types with common variable 'animal'
for animal in (cat, dog):
print(animal.info())
print(animal.make_sound())
#############################################################################################################
class India():
def capital(self):
print("New Delhi")
def language(self):
print("Hindi and English")
class USA():
def capital(self):
print("Washington, D.C.")
def language(self):
print("English")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
########################################################################################################
class Bird:
def intro(self):
print("There are different types of birds")
def flight(self):
print("Most of the birds can fly but some cannot")
class parrot(Bird):
def flight(self):
print("Parrots can fly")
class penguin(Bird):
def flight(self):
print("Penguins do not fly")
obj_bird = Bird()
obj_parr = parrot()
obj_peng = penguin()
obj_bird.intro()
obj_bird.flight()
obj_parr.intro()
obj_parr.flight()
obj_peng.intro()
obj_peng.flight()
|
5cb6c9094fd1d69972f5369331082a8af7892156
|
o0Marianne0o/cp1404practicals
|
/prac_02/files.py
| 921 | 4.09375 | 4 |
# program 1 - Enter a name and save to text file
username = input("Enter your name: ")
output_file = open("name.txt", 'w')
print("{}".format(username), file=output_file)
output_file.close()
# program 2 - open file and print the stored name
open_file = open("name.txt", 'r')
print("Your name is {}".format(open_file.read()))
open_file.close()
# program 3 - adding stored value in the text file
number_file = open("numbers.txt", 'r')
first_number = int(number_file.readline())
second_number = int(number_file.readline())
sum_of_two_numbers = first_number + second_number
print("the sum of the two number is {}".format(sum_of_two_numbers))
# program 4 - sum of all numbers in numbers.txt
all_numbers = (number_file.readlines())
sum_of_numbers = 0
for numbers in all_numbers:
all_number = int(numbers)
sum_of_numbers += all_number
number_file.close()
print("The sum of all numbers is {}".format(sum_of_numbers))
|
1ce7099585cf1f42ae66519907fdf2b5d720afb2
|
KrisCheng/HackerPractice
|
/Python/oop/hello.py
| 483 | 3.75 | 4 |
# OOP basic
class Student(object):
def __init__(self, __name, score):
self.__name = __name
self.score = score
def print_score(self):
print('%s %s' % (self.__name, self.score))
def get_name(self):
return self.__name
def set_name(self,name):
self.__name = name
bart = Student('Kris Chan', 100)
bart.print_score()
print(bart.get_name())
bart.name = "Devils"
print(bart.name)
print(bart.get_name())
print(bart)
print(Student)
|
390ebfe44b76ebfcebe368a92c3a6002c1f077c7
|
KrisCheng/HackerPractice
|
/Python/module/itertools.py
| 135 | 3.859375 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools
cs = itertools.cycle('ABC')
for c in cs:
print(c) #无限重复
|
710b2baa4bd86c79b91492c061f4ebb183ad5688
|
WeihanSun/python_sample
|
/standard/zip.py
| 2,070 | 3.703125 | 4 |
# zip and unzip file and folder
# zip is to loop list meanwhile (see container)
import zipfile
import os
import shutil
# zip folder
def zip_directory(path):
zip_targets = []
# pathからディレクトリ名を取り出す
base = os.path.basename(path)
# 作成するzipファイルのフルパス
zipfilepath = os.path.abspath('%s.zip' % base)
# walkでファイルを探す
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
# 作成するzipファイルのパスと同じファイルは除外する
if filepath == zipfilepath:
continue
arc_name = os.path.relpath(filepath, os.path.dirname(path))
print(filepath, arc_name)
zip_targets.append((filepath, arc_name))
for dirname in dirnames:
filepath = os.path.join(dirpath, dirname)
arc_name = os.path.relpath(filepath, os.path.dirname(path)) + os.path.sep
print(filepath, arc_name)
zip_targets.append((filepath, arc_name))
# zipファイルの作成
zip = zipfile.ZipFile(zipfilepath, 'w')
for filepath, name in zip_targets:
zip.write(filepath, name)
zip.close()
if __name__ == '__main__':
file1 = './new.zip'
file2 = './packages.zip'
if os.path.exists(file1):
os.remove(file1)
if os.path.exists(file2):
os.remove(file2)
# ZIP_STORED: no compression
# ZIP_DEFLATED: compression
zFile = zipfile.ZipFile(file1, 'w', zipfile.ZIP_STORED)
zFile.write('class_compare.py')
zFile.write('class_inherit.py')
zFile.close()
# zip dir
zip_directory('./packages')
# unzip file or folder
unzip_dir = 'unzip_folder'
if os.path.exists(unzip_dir):
shutil.rmtree(unzip_dir)
os.mkdir(unzip_dir)
with zipfile.ZipFile(file1, 'r') as zip_ref:
zip_ref.extractall(unzip_dir)
with zipfile.ZipFile(file2, 'r') as zip_ref:
zip_ref.extractall(unzip_dir)
|
9aa02643ad00c618f323b127bdb01fb076c86e0e
|
redoctoberbluechristmas/100DaysOfCodePython
|
/Day27 - TKInter, Args, Kwars/main.py
| 309 | 4 | 4 |
import tkinter
# Create a window
window = tkinter.Tk()
window.title("My First GUI Program")
window.minsize(width=500, height=300)
# Create a label
my_label = tkinter.Label()
#mainloop is what keeps window on-screen and listening; has to be at very end of program.
window.mainloop()
|
f7b7853e9332ef9fd2a5c16733f1908c00ea2a04
|
redoctoberbluechristmas/100DaysOfCodePython
|
/Day03 - Control Flow and Logical Operators/Day3Exercise3_LeapYearCalculator.py
| 826 | 4.375 | 4 |
#Every year divisible by 4 is a leap year.
#Unless it is divisible by 100, and not divisible by 400.
#Conditional with multiple branches
year = int(input("Which year do you want to check? "))
if(year % 4 == 0):
if(year % 100 == 0):
if(year % 400 == 0):
print("Leap year.")
else:
print("Not leap year.")
else:
print("Leap year.")
else:
print("Not leap year.")
#Refactored using more condense conditional statement.
#"If a year is divisible by 4, and it is either not divisible by 100, or is not not divisible by 100 but is
# divisible by 400, then it is a leap year. Otherwise, it is not a leap year."
if(year % 4 == 0) and ((not year % 100 == 0) or (year % 400 == 0)):
#if(year % 4 == 0) and ((year % 100 != 0) or (year % 400 == 0)):
print("Leap year.")
else:
print("Not leap year.")
|
d167ac2865745d4e015ac1c8565dd07fba06ef4d
|
redoctoberbluechristmas/100DaysOfCodePython
|
/Day21 - Class Inheritance/main.py
| 777 | 4.625 | 5 |
# Inheriting and modifying existing classes allows us to modify without reinventing the wheel.add
class Animal:
def __init__(self):
self.num_eyes = 2
def breathe(self):
print("Inhale, exhale.")
class Fish(Animal):
def __init__(self):
super().__init__() # The call to super() in the initializer is recommended, but not strictly required.
def breathe(self):
# Extend an inherited method. Running this will produce "Inhale, exhale" \n "doing this underwater." Wont' totally override the method.
super().breathe()
print("doing this underwater.")
def swim(self):
print("moving in water.")
nemo = Fish()
nemo.swim()
# Inherit methods.
nemo.breathe()
# Inherit attributes.
print(nemo.num_eyes)
|
d999a0fd4f5a5516a6b810e76852594257174245
|
redoctoberbluechristmas/100DaysOfCodePython
|
/Day08 - Functions with Parameters/cipherfunctions.py
| 846 | 4.125 | 4 |
alphabet = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
]
def caesar(start_text, shift_amount, cipher_direction):
output_text = ""
# Will divide the shift amount to fit into length of alphabet.
shift_amount = shift_amount % 26
if cipher_direction == "decode":
shift_amount *= -1
for char in start_text:
if char in alphabet:
start_index = alphabet.index(char)
end_index = start_index + shift_amount
output_text += alphabet[end_index]
else:
output_text += char
print(f"The {cipher_direction}d text is {output_text}.")
|
cd9d2b973f33c724e9b85ebb00acb12ba5dbd2b8
|
redoctoberbluechristmas/100DaysOfCodePython
|
/Day08 - Functions with Parameters/Day8_CaesarCipher.py
| 676 | 3.90625 | 4 |
from cipherfunctions import caesar
#from roughcipherfunctions import caesar
from art import logo
print(logo)
should_continue = True
while should_continue:
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
caesar(start_text=text, shift_amount=shift, cipher_direction=direction)
#caesar(input_text=text, shift_amount=shift, code_direction=direction)
will_continue = input("Type 'yes' if you want to go again. Otherwise type 'no'. ")
if will_continue != "yes":
print("Goodbye")
should_continue = False
|
d47a13ae0fe6c8de5c90852efe91435be06dafca
|
redoctoberbluechristmas/100DaysOfCodePython
|
/Day14 - Higher Lower Game/Day14Exercise1_HigherLowerGame.py
| 1,390 | 3.9375 | 4 |
import random
import art
from os import system
from game_data import data
# Need to select two celebrities
def choose_accounts():
return random.choice(data)
def format_entry(choice):
return f'{choice["name"]}, a {choice["description"]}, from {choice["country"]}'
def compare_accounts(player_choice, not_choice):
if player_choice["follower_count"] > not_choice["follower_count"]:
return -1
else:
return 1
score = 0
choice_a = choose_accounts()
# Start Loop Here
correct_choice = True
while correct_choice:
print(art.logo)
choice_b = choose_accounts()
# Make it so you can't compare same things
while choice_a == choice_b:
choice_b = choose_accounts()
print(f"Compare A: {format_entry(choice_a)}")
print(art.vs)
print(f"Against B: {format_entry(choice_b)}")
player_choice = input("Who has more followers? Type 'A' or 'B': ").lower()
if player_choice == 'a':
player_choice = choice_a
not_choice = choice_b
elif player_choice == 'b':
player_choice = choice_b
not_choice = choice_a
system("clear")
if compare_accounts(player_choice, not_choice) == 1:
print(f"Sorry, that's wrong. Final score = {score}")
correct_choice = False
break
else:
score += 1
print(f"Correct! Your score is {score}")
choice_a = choice_b
|
d9d6d4b6b6e623aaa2d8c9a6c11424d8ee2454c8
|
tommasopierazzini/projectAI
|
/DecisionTreeLearning.py
| 5,191 | 3.546875 | 4 |
import DecisionTree
import math
def DecisionTreeLearner(dataset):
def decisionTreeLearning(examples, attributes, parents_examples=()):
if len(examples) == 0:
return pluralityValue(parents_examples) #returns the most frequent classification among the examples
elif allSameClass(examples):
return DecisionTree.Leaf(examples[0][dataset.target]) #if they all have the same class, I return the class of the first example
elif len(attributes) == 0:
return pluralityValue(examples) #returns the most frequent classification among the examples
else:
mostImpAtt, threshold = chooseAttribute(attributes, examples)
tree = DecisionTree.DecisionTree(mostImpAtt, threshold, dataset.attrnames[mostImpAtt])
ExampleMinor, ExampleMajor = splittingOnThreshold(mostImpAtt, threshold, examples)#separate based on threshold
#do recursion and add to the tree
branchesLeft = decisionTreeLearning(ExampleMinor, removeAttr(mostImpAtt, attributes), examples)#recursion
branchesRight = decisionTreeLearning(ExampleMajor, removeAttr(mostImpAtt, attributes), examples)#recursion
tree.addLeft(threshold, branchesLeft)
tree.addRight(threshold, branchesRight)
return tree
def chooseAttribute(attributes, examples): # found the most important attribute, ande threshold, according to information gain
maxgainAttr = 0
thresholdAttr = 0
listValuesForAttribute = getListValuesForAttribute(dataset.examples, dataset.target) # prepare a list of values for each attribute to find the most important
global mostImportanceA
for attr in attributes:
maxgainValue = 0
threshValue = 0
for i in listValuesForAttribute[attr]: # for each attribute of each "column" (values) in the dataset
gain = float(informationGain(attr, float(i), examples)) # calcolate his gain
if gain > maxgainValue : # if gain greater assign it
maxgainValue = gain
threshValue = float(i)
if maxgainValue >= maxgainAttr:
maxgainAttr = maxgainValue
mostImportanceA = attr
thresholdAttr = threshValue
return mostImportanceA, thresholdAttr
def pluralityValue(examples):
i = 0
global popular
for v in dataset.values: #for each classification count the occurrences. Then choose the most popular
count = counting(dataset.target, v, examples)
if count > i:
i = count
popular = v
return DecisionTree.Leaf(popular)
def allSameClass(examples): # return True if all examples have the same class
sameClass = examples[0][dataset.target] #take that of the first example as a reference
for e in examples:
if e[dataset.target] != sameClass:
return False
return True
def informationGain(attribute, threshold, examples):
def entropy(examples):
entr = 0
if len(examples) != 0:
for v in dataset.values:
p = float(counting(dataset.target, v, examples)) / len(examples)
if p != 0:
entr += (-p) * math.log(p, 2.0)
return float(entr)
def remainder(examples):
N = float(len(examples))
ExampleMinor, ExampleMajor = splittingOnThreshold(attribute, threshold, examples)
remainderExampleMinor = (float((len(ExampleMinor))) / N) * entropy(ExampleMinor)
remainderExampleMajor = (float((len(ExampleMajor))) / N) * entropy(ExampleMajor)
return (remainderExampleMinor + remainderExampleMajor)
# formula to calculate information gain
return entropy(examples) - remainder(examples)
def counting(attribute, value, example): #count the number of examples that have attribute = value
return sum(e[attribute] == value for e in example)
def removeAttr(delAttr, attributes): #delAttr is the attribute to remove
result=list(attributes)
result.remove(delAttr)
return result
def splittingOnThreshold(attribute, threshold, examples):
ExampleMinor, ExampleMajor = [], []
for e in examples:
if float(e[attribute]) <= threshold: # divide the examples based on the threshold with respect to a given attribute
ExampleMinor.append(e)
else:
ExampleMajor.append(e)
return ExampleMinor, ExampleMajor
return decisionTreeLearning(dataset.examples, dataset.inputs)
def getListValuesForAttribute(exemples, nA): #create a list of list with singles values of attributes
valuesList = []
for n in range(nA):
l = []
for i in range(0,len(exemples)):
l.append(exemples[i][n])#values for each attribute
l = list(set(l))#remove duplicates
valuesList.append(l) #attributes without duplicate (to improve speed)
return valuesList
|
2406a145b15c23937ed8f3887e907f552794a6b5
|
Yeahp/nebula
|
/acrobatic_demo/email_service.py
| 1,095 | 3.578125 | 4 |
import smtplib
from email.mime.text import MIMEText
from email.header import Header
"""
We send email via SMTP(Simple Mail Transfer Protocol) and MIME(Multipurpose Internet Mail Extensions),
which require that both the sender and receiver should open his SMTP service.
Otherwise, the request for sending email will fail.
"""
if __name__ == "__main__":
sender = "yeerxi@163.com"
receivers = ['yeerxi@163.com']
# three parameters: text content, text format and encoding
message = MIMEText("test for sending email ", "plain", "utf-8")
message["From"] = Header("yeerxi <yeerxi@163.com>", "utf-8")
message["To"] = "qierpeng <qierpeng@163.com>"
subject = "Python SMTP email test"
message["Subject"] = Header(subject, "utf-8").encode()
try:
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com', 25)
smtp.set_debuglevel(1)
smtp.login('yeerxi', 'qierpeng')
smtp.sendmail(sender, receivers, message.as_string())
print("Success: finish sending email!")
smtp.quit()
except smtplib.SMTPException:
print("Error: cannot send email!")
|
c42e1c0f609302b069f8818fd33412d2e0a4ecd8
|
kasra28/emialspammer
|
/spammer.py
| 5,077 | 3.515625 | 4 |
# email spammer
# imports
import smtplib
import sys
import time
# start
class bcolors:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
def banner():
a = "welcom to my first email spammer its feel good to f**k some one whit spam try it...."
b = "made by <kasra akhavan> <IRANIAN HACKER>"
c = "big tnx to you for using my tool..."
d = '''
you can tell me if you like this tool by like it in git hub ......
.. .. ;;;;;;;;;;
. .. . ;;; ;;;
. . ;;; ;;; ;;; ;;;
. . ;;;; ;;; ;;;; ------> this is you :)
. . ;;;;; ; ; ;;;;;
. . ;;;;; ;; ;; ;;;;;
. ;;;;; ;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
LOVE YOU MEN
'''
print(bcolors.RED + a)
time.sleep(2)
print(bcolors.GREEN + b)
print(bcolors.DARKCYAN + c)
print(bcolors.BLUE + d)
class Email_Bomber:
count = 0
def __init__(self):
try:
print(bcolors.GREEN + "\n starting program...")
self.target = str(input(bcolors.RED + "please enter target email \nexample:(kasra@kasra.com)\n<box>: "))
self.mode =int(input(bcolors.RED + 'enter Bomb count (1,2,3,4) || 1:(1000) 2:(500) 3:(250) 4:(custom)\n<box>: '))
if int(self.mode) > int(4) or int(self.mode) < int(1):
print("that number is suck <FUCK YOU>")
time.sleep(2)
print("oh sorry men i was wronge but at less your math is suck...\nbye bye")
sys.exit(1)
except Exception as e:
print(f'ERROR: {e}')
def bomb(self):
try:
print(bcolors.BLUE + 'set up bomb to fuck they mother')
self.amount = None
if self.mode == int(1):
self.amount = int(1000)
elif self.mode == int(2):
self.amount = int(500)
elif self.mode == int(3):
self.amount = int(250)
else:
self.amount = int(input(bcolors.BLUE + 'choose a custom amount\n<box>: '))
print( bcolors.GREEN + f"\n you select bomb at mode {self.mode} and {self.amount} amount ")
except Exception as e:
print(f"ERROR: {e}")
def email(self):
try:
print(bcolors.RED + "setup the email to fuck them...........")
self.server = str(input(bcolors.GREEN + 'Enter email server || or choose one of the options 1)Gmail 2)Yahoo 3)Outlook \n <box>:'))
premade = ['1', '2', '3']
default_port = True
if self.server not in premade:
default_port = False
self.port = int(input(bcolors.GREEN + "enter your port number\n<box>: "))
if default_port == True:
self.port = int(587)
if self.server == '1':
self.server = 'smtp.google.com'
elif self.server == '2':
self.server = 'smtp.mail.yahoo.com'
elif self.server == '3':
self.server = 'smtp.mail.outlook.com'
self.fromAddr = str(input(bcolors.GREEN + 'Enter from address\n<box>:'))
self.fromPwd = str(input(bcolors.GREEN + 'Enter from password\n<box>:'))
self.subject = str(input(bcolors.GREEN + 'Enter from subject of email\n<box>:'))
self.message = str(input(bcolors.GREEN + 'Enter message\n<box>:'))
self.msg = '''From: %s\nTo: %s\nSubject %s\n%s\n
''' % (self.fromAddr, self.target, self.subject, self.message)
self.s = smtplib.SMTP(self.server, self.port)
self.s.ehlo()
self.s.starttls()
self.s.ehlo()
self.login(self.fromAddr, self.fromPwd)
except Exception as e:
print(f"ERROR: {e}")
def send(self):
try:
self.s.send_message(self.fromAddr, self.target, self.msg)
self.count +=1
print(bcolors.YELLOW + f'BOMB: {self.count}')
except Exception as e:
print(f"ERROR: {e}")
def attack(self):
for email in range(20):
print(bcolors.GREEN + '\n Attempting secure account login')
self.s.login(self.fromAddr, self.fromPwd)
print(bcolors.RED + '\n ATTACK IS START B!TCH')
for email in range(50):
self.send()
time.sleep(0.5)
time.sleep(60)
self.s.close()
print(bcolors.RED + '---Attack finished---')
if __name__ =='__main__':
banner()
bomb = Email_Bomber()
bomb.bomb()
bomb.email()
bomb.attack()
|
223bc3092d41737c75c588f9fdb6fcc9a82b062f
|
MaryTalvistu/prog_alused
|
/1/yl6.py
| 426 | 3.671875 | 4 |
inimeste_arv = input("Sisestage inimeste arv: ")
kohtade_arv_bussis = input("Sisestage kohtade arv bussis: ")
busside_arv = int(int(inimeste_arv) / int(kohtade_arv_bussis))
j22k = int(inimeste_arv) - int(busside_arv) * int(kohtade_arv_bussis)
print("Inimeste arv " + str(inimeste_arv) + ", kohtade arv bussis " + str(kohtade_arv_bussis) + ", busside arv " + str(busside_arv) + ", mahajäänud inimeste arv " + str(j22k) + ".")
|
55e07398df2ade057dd922bcc853d4c9014094be
|
MaryTalvistu/prog_alused
|
/2/2.2.py
| 276 | 3.859375 | 4 |
perekonnanimi = input("Sisestage oma perekonnanimi: ")
if perekonnanimi[-2:] == "ne":
print("Abielus")
elif perekonnanimi[-2:] == "te":
print("Vallaline")
elif perekonnanimi[-1] == "e":
print("Määramata")
else:
print("Pole ilmselt leedulanna perekonnanimi")
|
19ea81db06a5ca5ab5b6af1bdd37f803c9a54b79
|
Joftus/CS-474
|
/hw3/P3.py
| 291 | 3.625 | 4 |
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 5))
x = np.linspace(-50, 50, 1000)
# Problem 3A
plt.plot(x, (1+3*x), color='black')
# Problem 3B
plt.plot(x, (2-x)/2, color='blue')
plt.xlabel('x1')
plt.ylabel('x2')
plt.title('Problem 3 A / B')
plt.show()
|
b3d7ab36cba905360151af3ab3be233dd2e2de9b
|
Cangozler/PythonHomeWorks
|
/vebek.py
| 355 | 3.6875 | 4 |
def enbuyuk(liste1):
sayi = max(liste1)
return sayi
def enkucuk(liste1):
sayi = min(liste1)
return sayi
liste=[]
adet=int(input("kaç adet sayı girmek istiyon :"))
for n in range(adet):
sayi = int(input('Sayıyı Gir: '))
liste.append(sayi)
print("en buyuk sayi",enbuyuk(liste) , "en küçük sayı",enkucuk(liste))
|
d1ac4626ab6b2531788696aa29a9732f65c8e0e0
|
Cangozler/PythonHomeWorks
|
/çarpim.py
| 135 | 3.75 | 4 |
for i in range(1,10):
print("*************************")
for k in range(1,10):
print("{} x {} = {}".format(k,i,i*k))
|
9f6da873b18a0c733c92f6b929c7c4d5ca3d898a
|
guihunkun/LearnPythonCrashCourse
|
/solution_02/changeString-finished.py
| 267 | 3.90625 | 4 |
'''
定义一个变量sentence,赋值为"I Love you!",然后分别用title(), upper(), lower()函数对变量sentence执行操作后输出。
'''
print("\n")
sentence="I Love you!"
print(sentence.title())
print(sentence.upper())
print(sentence.lower())
|
6cf08fa094cdef5c940c2094d7cc0234c7b02101
|
brianwesterman/computer-science-projects
|
/data_analysis_and_visualization_system/knn_test2.py
| 2,589 | 3.59375 | 4 |
# Bruce Maxwell
# Spring 2015
# CS 251 Project 8
#
# KNN class test
#
import sys
import data
import classifiers
def main(argv):
'''Reads in a training set and a test set and builds two KNN
classifiers. One uses all of the data, one uses 10
exemplars. Then it classifies the test data and prints out the
results.
'''
# usage
if len(argv) < 3:
print('Usage: python %s <training data file> <test data file> <optional training category file> <optional test category file>' % (argv[0]))
exit(-1)
# read the training and test sets
dtrain = data.Data(argv[1])
dtest = data.Data(argv[2])
# get the categories and the training data A and the test data B
if len(argv) > 4:
traincatdata = data.Data(argv[3])
testcatdata = data.Data(argv[4])
traincats = traincatdata.get_data( [traincatdata.get_headers()[0]] )
testcats = testcatdata.get_data( [testcatdata.get_headers()[0]] )
A = dtrain.get_data( dtrain.get_headers() )
B = dtest.get_data( dtest.get_headers() )
else:
# assume the categories are the last column
traincats = dtrain.get_data( [dtrain.get_headers()[-1]] )
testcats = dtest.get_data( [dtest.get_headers()[-1]] )
A = dtrain.get_data( dtrain.get_headers()[:-1] )
B = dtest.get_data( dtest.get_headers()[:-1] )
# create two classifiers, one using 10 exemplars per class
knncall = classifiers.KNN()
knnc10 = classifiers.KNN()
# build the classifiers
knncall.build( A, traincats )
knnc10.build(A, traincats, 10)
# use the classifiers on the test data
allcats, alllabels = knncall.classify(B)
tencats, tenlabels = knnc10.classify(B)
# print the results
print('Results using All Exemplars:')
print(' True Est')
for i in range(allcats.shape[0]):
if int(testcats[i,0]) == int(allcats[i,0]):
print("%03d: %4d %4d" % (i, int(testcats[i,0]), int(allcats[i,0]) ))
else:
print("%03d: %4d %4d **" % (i, int(testcats[i,0]), int(allcats[i,0]) ))
print(knnc10)
print('Results using 10 Exemplars:')
print(' True Est')
for i in range(tencats.shape[0]):
if int(testcats[i,0]) == int(tencats[i,0]):
print("%03d: %4d %4d" % (i, int(testcats[i,0]), int(tencats[i,0]) ))
else:
print("%03d: %4d %4d **" % (i, int(testcats[i,0]), int(tencats[i,0]) ))
print(knnc10.confusion_matrix_str(knnc10.confusion_matrix(testcats, tencats)))
return
if __name__ == "__main__":
main(sys.argv)
|
d763736bc38eae023d9d17a1ab8fb3c853ab40b0
|
Alexsimulation/pulsar-classifier
|
/main.py
| 20,318 | 3.921875 | 4 |
# Machine learning - Pulsar detector
# Ref (we all learn somewhere) https://machinelearningmastery.com/implement-backpropagation-algorithm-scratch-python/
# Implements a simple 'multi layer perceptron' neural network (fully connected), with variable number and size of layers
# Datset: https://www.kaggle.com/charitarth/pulsar-dataset-htru2
# By Alexis Angers [https://github.com/Alexsimulation]
import random
import math
import pickle
import csv
# Single hidden neuron in a network
class neuron:
def __init__(self, size):
# Class variables
self.v = 0 # value, zero by default
self.vp = 0 # derivative value, zero by default
self.w = [] # weights, empty by default
self.wu = [] # weights update, used for batch gradient descent
self.b = 0 # bias, zero by default
self.bu = 0 # bias update, used for batch gradient descent
self.e = 0 # error signal, used for backpropagation
self.b = random.uniform(-1, 1)
for i in range(size):
self.w.append( random.uniform(-1, 1) )
self.wu.append( 0 )
def get(self, x):
self.v = self.b
for i in range(len(self.w)):
self.v += self.w[i]*x[i]
# Activation
try:
self.v = 1/(1 + math.exp(-1*self.v))
except OverflowError:
self.v = float('inf')
# Derivative of activation
self.vp = self.v * (1 - self.v)
return self.v
# Fully connected hidden/output layer
class layer:
def __init__(self, num_neurons, input_size):
# Class variables
self.ns = [] # Array of neurons, start empty
for i in range(num_neurons):
ni = neuron(input_size)
self.ns.append( ni )
def get(self, x):
v = []
for i in range(len(self.ns)):
v.append( self.ns[i].get(x) )
return v
# Neural network class
class network:
def __init__(self, layers_size ):
# Class variables
self.la = [] # Array of layers
self.x = [] # last input values
self.z = [] # value of the network output
self.ls = [] # Network loss value
self.lr = 0.5 # network learning rate
num_layers = len(layers_size)
# Num layers includes the input and output layers, but the network will actually have num_layers-1 layers
for i in range(num_layers-1):
# Input layer of hidden/output layers is always the output of the last layer
lai = layer(layers_size[i+1], layers_size[i])
self.la.append( lai )
def get(self, x):
self.x = x[:]
self.z = x[:]
z2 = x[:]
# For each layer, compute the value of the layer output, and pass it to the next layer
for i in range(len(self.la)):
z2 = self.la[i].get(z2)
self.z.append(z2)
return self.z
def loss(self, answ):
# Make sure the answ is in a list object
if not isinstance(answ, list):
answ = [answ]
self.ls = []
for i in range(len(answ)):
zi = self.z[len(self.z)-1][i]
ai = answ[i]
self.ls.append( -1*(ai*math.log(zi) + (1-ai)*math.log(1-zi)) ) # Log loss
return self.ls
def reset_error(self):
endlay = len(self.la)-1
# Work backward through all layers
for i in range(endlay, -1, -1): # Loop over all layers, in reverse
for j in range(len(self.la[i].ns)): # Loop over layer i's neurons
self.la[i].ns[j].e = 0
def backprop_error(self, answ):
endlay = len(self.la)-1
# Make sure the answ is in a list object
if not isinstance(answ, list):
answ = [answ]
self.reset_error() # Resets error values to zero
# Work backward through all layers
for i in range(endlay, -1, -1): # Loop over all layers, in reverse
if i == endlay:
for j in range(len(self.la[i].ns)): # Loop over layer i's neurons
dLdv = ( self.la[i].ns[j].v - answ[j] ) / ( self.la[i].ns[j].v - self.la[i].ns[j].v**2 ) # Derivative of the loss function
self.la[i].ns[j].e = dLdv * self.la[i].ns[j].vp
else:
for j in range(len(self.la[i].ns)): # Loop over layer i's neurons
for k in range(len(self.la[i+1].ns)): # Loop over layer i+1's neuron
self.la[i].ns[j].e += self.la[i+1].ns[k].w[j] * self.la[i+1].ns[k].e * self.la[i].ns[j].vp
def update_weights_stochastic(self):
endlay = len(self.la)-1
# Work backward through all layers
for i in range(endlay, -1, -1): # Loop over all layers, in reverse
if i != 0:
for j in range(len(self.la[i].ns)): # Loop over layer i's neurons
self.la[i].ns[j].b -= self.lr * self.la[i].ns[j].e
for k in range(len(self.la[i].ns[j].w)): # Loop over layer i's neuron j's weights
self.la[i].ns[j].w[k] -= self.lr * self.la[i].ns[j].e * self.la[i].ns[j].v
else:
for j in range(len(self.la[i].ns)): # Loop over layer i's neurons
self.la[i].ns[j].b -= self.lr * self.la[i].ns[j].e
for k in range(len(self.la[i].ns[j].w)): # Loop over layer i's neuron j's weights
self.la[i].ns[j].w[k] -= self.lr * self.la[i].ns[j].e * self.x[i]
def save_weight_updates_batch(self, batch_size):
endlay = len(self.la)-1
# Work backward through all layers
for i in range(endlay, -1, -1): # Loop over all layers, in reverse
if i != 0:
for j in range(len(self.la[i].ns)): # Loop over layer i's neurons
self.la[i].ns[j].bu += (self.lr * self.la[i].ns[j].e) / batch_size
for k in range(len(self.la[i].ns[j].w)): # Loop over layer i's neuron j's weights
self.la[i].ns[j].wu[k] += (self.lr * self.la[i].ns[j].e * self.la[i].ns[j].v) / batch_size
else:
for j in range(len(self.la[i].ns)): # Loop over layer i's neurons
self.la[i].ns[j].bu += (self.lr * self.la[i].ns[j].e) / batch_size
for k in range(len(self.la[i].ns[j].w)): # Loop over layer i's neuron j's weights
self.la[i].ns[j].wu[k] += (self.lr * self.la[i].ns[j].e * self.x[i]) / batch_size
def update_weights_batch(self):
endlay = len(self.la)-1
# Work backward through all layers
for i in range(endlay, -1, -1): # Loop over all layers, in reverse
for j in range(len(self.la[i].ns)): # Loop over layer i's neurons
self.la[i].ns[j].b -= self.la[i].ns[j].bu # Update it's bias
self.la[i].ns[j].bu = 0 # Reset bias update
for k in range(len(self.la[i].ns[j].w)): # Loop over layer i's neuron j's weights
self.la[i].ns[j].w[k] -= self.la[i].ns[j].wu[k] # Update it's weight
self.la[i].ns[j].wu[k] = 0 # Reset weight update
def train_step_stochastic(self, x, a):
self.get(x)
self.backprop_error(a)
self.update_weights_stochastic()
def train_step_batch(self, x, a, batch_size, step):
if step == (batch_size-1):
# If current step is the last one (batch size-1), update the weights
self.update_weights_batch()
else:
# If current step is not a batch size multiple, compute and save the weights updates
self.get(x)
self.backprop_error(a)
self.save_weight_updates_batch(batch_size)
def disp(self):
for i in range(len(self.la)):
print(' - Layer',i)
for j in range(len(self.la[i].ns)):
print(' - Neuron',j)
print(' - w:',self.la[i].ns[j].w)
print(' - b:',self.la[i].ns[j].b)
print('')
def save(self, outfile):
with open(outfile, 'wb') as output:
pickle.dump(self, output, pickle.HIGHEST_PROTOCOL)
print('Network saved to output file',outfile)
def load(self, infile):
with open(infile, 'rb') as input:
new_n = pickle.load(input)
print('Newtork loaded from file',infile)
return new_n
# Utility functions
def meanc(x):
# Check if member is a list
if isinstance(x[0], list):
y = []
for i in range(len(x[0])):
y.append(0)
for i in range(len(x)):
for j in range(len(y)):
y[j] += x[i][j]/len(x)
else:
y = 0
for i in range(len(x)):
y += x[i]/len(x)
return y
def sumc(x):
# Check if member is a list
if isinstance(x[0], list):
y = []
for i in range(len(x[0])):
y.append(0)
for i in range(len(x)):
for j in range(len(y)):
y[j] += x[i][j]
else:
y = 0
for i in range(len(x)):
y += x[i]
return y
def sigmoid(x):
return 1/(1 + math.exp(-1*x))
def create_train(n_in, n_out):
# Create a training array of values to fit a function
x = []
a = []
for v in range(10): # Loop over all the batches
xb = []
ab = []
for i in range(50): # Loop over all the sets in the batch i
xi = []
ai = []
for j in range(n_out):
ai.append(0)
for j in range(n_in):
xi.append(random.uniform(0,1))
for k in range(n_out):
ai[k] += xi[j]/n_in
for k in range(n_out):
if k == 0:
ai[k] = (1/math.pi * math.atan(-1*ai[k]) + 0.5)**2
else:
ai[k] = 1/( 1 + math.exp(-1*ai[k]) )
xb.append( xi )
ab.append( ai )
x.append(xb)
a.append(ab)
return x, a
def create_test(n_in, n_out):
# Create a test array
xt = []
at = []
for i in range(2000):
xti = []
ati = []
for j in range(n_out):
ati.append(0)
for j in range(n_in):
xti.append(random.uniform(0,1))
for k in range(n_out):
ati[k] += xti[j]/n_in
for k in range(n_out):
if k == 0:
ati[k] = (1/math.pi * math.atan(-1*ati[k]) + 0.5)**2
else:
ati[k] = 1/( 1 + math.exp(-1*ati[k]) )
xt.append( xti )
at.append( ati )
return xt, at
def load_data_train():
print('Loading training data...')
with open('data/pulsar_train.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
x = []
xb = []
a = []
ab = []
n0 = 0
n1 = 1
batch_size = 100
for row in csv_reader: # Read each row as a list
arow = float(row[len(row)-1]) # Read the answer in the last line
if arow == 1:
if n0 >= n1:
# If the answer is 1, just add it
al = [ arow ]
ab.append(al)
xl = [] # Read the input in first line
for i in range(0, len(row)-2):
xl.append( float(row[i]) )
xb.append(xl)
n1 += 1
else:
if n1 >= n0: # To unbias database, only add the 0 data is there's the same amount or more of 1s
al = [ arow ]
ab.append(al)
xl = [] # Read the input in first line
for i in range(0, len(row)-2):
xl.append( float(row[i]) )
xb.append(xl)
n0 += 1
# If batch is full, save and reset batch variables
if len(xb) == batch_size:
x.append(xb)
a.append(ab)
xb = []
ab = []
line_count += 1
# Add last batch that isn't full
if not len(xb) == 0:
x.append(xb)
a.append(ab)
return x, a
def load_data_test():
print('Loading testing data...')
with open('data/pulsar_test.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
x = []
a = []
for row in csv_reader: # Read each row as a list
al = [ float(row[len(row)-1]) ] # Read the answer in the last line
a.append(al)
xl = [] # Read the input in first line
for i in range(0, len(row)-2):
xl.append( float(row[i]) )
x.append(xl)
line_count += 1
return x, a
# Run function, handles the command line interface logic
def run(x, a, xt, at, n):
run = 0
while run != -1:
choice = input('Enter a command: ')
print('')
if choice[:5] == 'train':
# Get number of runs from input
numvalid = 1
try:
num2run = int(choice[5:])
except:
numvalid = 0
print('Invalid run number. Please enter an integer.')
if numvalid == 1:
# Loop over runs number
for k in range(num2run):
loss = []
# Check if training data is separated in batches or if it's just a stochastic run
if isinstance(x[0], list):
if isinstance(x[0][0], list):
# This means x[0] is a set of data sets -> do a batch run
batch_size = len(x[0])
for i in range(len(x)): # Loop over all training batches
for j in range(len(x[i])): # Loop over all the sets in the batch i
n.train_step_batch(x[i][j], a[i][j], batch_size, j)
loss.append(n.loss(a[i][j]))
print('Batch',i+1,'/',len(x),'done ',end="\r")
else:
# This means x[0] is a set of values -> stochastic run
for i in range(len(x)): # Loop over training values
n.train_step_stochastic(x[i], a[i])
loss.append(n.loss(a[i]))
if k%1 == 0: # Each 1 run
if (k > 0)|(run == 0):
print(run,' : ',meanc(loss))
# After a run, end
run += 1
print(run,' : ',meanc(loss))
elif choice[:4] == 'test':
# Loop over the test batches
dev = []
dev0 = []
dev1 = []
c0 = 0
c0r = 0
c1 = 0
c1r = 0
for i in range(len(at[0])):
dev.append(0)
dev0.append(0)
dev1.append(0)
for i in range(len(xt)):
z = n.get(xt[i]) # Get network output for xt[i]
z = z[len(z)-1]
for j in range(len(z)): # Loop over output
dev[j] += abs(z[j] - at[i][j])/len(xt)
if at[i][j] < 0.5:
dev0[j] += abs(z[j] - at[i][j])
c0 += 1
if round(z[j]) == at[i][j]:
c0r += 1
else:
dev1[j] += abs(z[j] - at[i][j])
c1 += 1
if round(z[j]) == at[i][j]:
c1r += 1
if i%50 == 0:
print('Progress:',100*i/(len(xt)-1),'% ',end="\r")
for i in range(len(dev0)):
dev0[i] = dev0[i]/c0
for i in range(len(dev1)):
dev1[i] = dev1[i]/c1
print('Average overall deviation:',dev)
print('Average dev. on negatives:',dev0)
print('Average dev. on positives:',dev1)
print('Right overall --- :',100*(c0r+c1r)/(c0+c1),'%')
print('Right on negatives:',100*c0r/c0,'%')
print('Right on positives:',100*c1r/c1,'%')
elif choice[:3] == 'try':
xstrtest = choice[4:].split()
if len(xstrtest) == len(x[0]):
xtest = []
for i in range(len(xstrtest)):
xtest.append(float(xstrtest[i]))
ztest = n.get(xtest)
print('Answer: ',ztest[len(ztest)-1])
else:
print('Invalid input values length.')
elif choice[:7] == 'example':
try:
totest = int(choice[7:])
except:
totest = random.randint(0, len(xt))
print('No test index provided, using random integer ',totest)
print('')
print('Input:',xt[totest])
print('Dataset answer:',at[totest])
zc = n.get(xt[totest])
print('Network answer:',zc[len(zc)-1])
elif choice[:4] == 'edit':
toedit = choice[4:]
if toedit == ' learning rate':
print('Current learning rate:',n.lr)
lrin = input('Enter new learning rate: ')
try:
lrin = float(lrin)
n.lr = lrin
except:
print('Invalid learning rate.')
elif choice[:5] == 'print':
n.disp()
elif choice[:4] == 'save':
try:
outfile = choice[4:]
out_valid = 1
except:
out_valid = 0
print('Invalid file string.')
if out_valid == 1:
n.save(outfile)
elif choice[:4] == 'load':
try:
infile = choice[4:]
in_valid = 1
except:
in_valid = 0
print('Invalid file string.')
if in_valid == 1:
try:
n = n.load(infile)
except:
print('Failed to load file',infile)
elif choice[:4] == 'exit':
run = -1
else:
print('Invalid command')
if not run == -1:
print('')
# Main function
if __name__ == '__main__':
random.seed(10)
# Print generic program info
print('')
print('A Machine Learning Project [version xx - public release]')
print('(c) 2021 Alexis Angers [https://github.com/Alexsimulation]. Private and educational use only.')
print('')
x, a = load_data_train() # Load training data
xt, at = load_data_test() # Load testing data
print('')
n_in = len(xt[0]) # Number of data inputs
n_out = len(at[0]) # Number of data outputs
n = network([n_in, 16, 8, n_out]) # Create new network sized for MNIST uses
run(x, a, xt, at, n) # Main run
print('End training')
|
71e8cdbc1f94ae156674d5f53814fe971b87fb52
|
ysymi/leetcode
|
/algorithms/basic/36.valid-sudoku.py
| 785 | 3.59375 | 4 |
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
def has_equal_num(s):
s = ''.join(sorted(s)).strip('.')
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
return True
return False
for i in range(9):
row = board[i]
line = ''.join([r[i] for r in board])
if has_equal_num(row) or has_equal_num(line):
return False
for i in [0, 3, 6]:
for j in [0, 3, 6]:
sq = board[j][i:i + 3] + board[j + 1][i:i + 3] + board[j + 2][i:i + 3]
if has_equal_num(sq):
return False
return True
|
3d8c5feb11438fa9bc7adf5a137d9d8bb285d7cf
|
yngtodd/hacker_rank
|
/python/ave_distint_elems.py
| 533 | 3.78125 | 4 |
from __future__ import division, print_function
def average(array):
"""
Compute the average of distinct items in an array.
Parameters
----------
* `array` [list]
array of potentially non-unique numbers.
Returns
-------
Mean of the unique elements in the array. [float]
"""
my_set = set(array)
return sum(my_set) / len(my_set)
def main():
n = int(input())
arr = map(int, input().split())
result = average(arr)
print(result)
if __name__ == main():
main()
|
61e11b2986a28391be97631a82b7a81caf71496a
|
nephidei2/python
|
/3.py
| 623 | 3.734375 | 4 |
#!/usr/bin/python
def counting(string):
words_freq = dict()
letters = [str(symbol).lower() for symbol in list(string) if symbol.isalpha()]
for l in letters:
if l in words_freq:
words_freq[l] += 1
else:
words_freq[l] = 1
return words_freq
def main():
with open('input.txt') as f:
text = ' '.join(f.readlines())
freq = counting(text)
if len(freq) > 0:
for w in [w[0] for w in sorted(freq.iteritems(), key=lambda(k, v): (-v, k))]:
print w + ': ' + str(freq[w])
else:
print ''
if __name__ == '__main__':
main()
|
9fc0c60e681cd14adb34e100fcd07a85932c672e
|
behry/hello-world
|
/Assignment6_Kosar.py
| 329 | 3.6875 | 4 |
#Exercise_1
Week = ('Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday','Saturday','Sunday')
#Exercise_2
fruits = set(['apple', 'mango', 'orange'])
#Exercise_3
new_fruits = {'chery', 'peach','apple', 'mango'}
#Exercise_4
print(new_fruits.difference(fruits))
#Exercise_5
print(new_fruits.intersection(fruits))
|
e50c1045677d6a8df58caa2e9a16963c4c961093
|
Dudo-z/FIrst-Github-Repository
|
/python_ex1.py
| 143 | 3.890625 | 4 |
list1 = list(range(5))
list2 = list1
list3 = list1[:]
list1.append(8)
list2.append(11)
list3.append(10)
print(list1)
print(list2)
print(list3)
|
9006fe1d04ceee567b8ced73bddd2562d0239fb8
|
zhartole/my-first-django-blog
|
/python_intro.py
| 1,313 | 4.21875 | 4 |
from time import gmtime, strftime
def workWithString(name):
upper = name.upper()
length = len(name)
print("- WORK WITH STRING - " + name * 3)
print(upper)
print(length)
def workWithNumber(numbers):
print('- WORK WITH NUMBERS')
for number in numbers:
print(number)
if number >= 0:
print("--positive val")
else:
print("--negative val")
def addItemToDictionary(key,value):
dictionaryExample = {'name': 'Olia', 'country': 'Ukraine', 'favorite_numbers': [90, 60, 90]}
dictionaryExample[key] = value
print('- WORK WITH DICTIONARY')
print(dictionaryExample)
def workWithFor():
for x in range(0, 3):
print("We're in for ")
def workWithWhile():
x = 1
while (x < 4):
print("Were in while")
x += 1
def showBasicType():
text = "Its a text"
number = 3
bool = True
date = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
print(text)
print(number)
print(bool)
print(date)
def hi(name):
print('Hi ' + name + '!' + ' Lets show you a few example of Python code')
def init():
hi('Victor')
workWithString("Igor")
workWithNumber([1, 5, 4, -3])
addItemToDictionary('new', 'child')
workWithFor()
workWithWhile()
showBasicType()
init()
|
bdfb8412a2af6e326cacb239345afac5d6caf79e
|
Elsamaxl/Learn_Python
|
/inherit.py
| 992 | 3.921875 | 4 |
#Filename:inherit.py
class SchoolMenmber():
'''Represents any school member.'''
def __init__(self,name,age):
self.name=name
self.age=age
print '(Initialized SchoolMenmber: %s)' %self.name
def tell(self):
'''Tell my details.'''
print 'Name: %s,Age: %d'%(self.name,self.age)
class Teacher(SchoolMenmber):
'''Represents a teacher.'''
def __init__(self,name,age,salary):
SchoolMenmber.__init__(self,name,age)
self.salary=salary
print '(Initialized Teacher: %s)'%self.name
def tell(self):
SchoolMenmber.tell(self)
print 'Salary: %d' %self.salary
class Student(SchoolMenmber):
'''Represents a student.'''
def __init__(self,name,age,marks):
SchoolMenmber.__init__(self,name,age)
self.marks=marks
def tell(self):
SchoolMenmber.tell(self)
print 'Maeks: %d' %self.marks
t=Teacher('Mrs.Shrividya',40,30000)
s=Student('Swaroop',22,75)
print #prints a blank line
members=[t,s]
for member in members:
member.tell() #works for both Teacher and Students
|
af6f78db36a02d7f48b0254839a8012ff0a44b43
|
Elsamaxl/Learn_Python
|
/func_doc.py
| 242 | 3.921875 | 4 |
#Filename:func_doc.py
def printMax(x,y):
'''Print the maximum of two numbers.
The two values must be integer.'''
x=int(x)
y=int(y)
if x>y:
print x,'is maximum.'
else :
print y,'is maximum.'
printMax(3,5)
print printMax.__doc__
|
e68276092cd593674fb19fa5319fac86c02fb87a
|
Elsamaxl/Learn_Python
|
/using_dict.py
| 521 | 3.578125 | 4 |
#Filename:using_dict.py
#'ab' is short for 'a'ddress'b'ook
ab={'Swaroop':'swaroop@byteopython.info',
'Lary':'larry@wall.org',
'Matsumoto':'matsumoto@ruby-lang.org',
'Spammer':'spammer@hotmail.com'
}
print "Swaroop's address is %s." %ab['Swaroop']
#Adding a key/value pair
ab['Guido']='guido@python.org'
#Deleting a key/value pair
del ab['Spammer']
print '\nThere are %d contacts in the address-book\n' %len(ab)
for name,address in ab.items():
print 'Contact %s at %s ' %(name,address)
if 'Guido' in ab:#OR ab.has_key('Guido')
print "\nGuido's address is %s" %ab['Guido']
|
fe5f9eb6a1548706c990cca435649116dbc3945a
|
ganesh-rk/Python-Assignment-Basic
|
/String_Ops.py
| 267 | 3.875 | 4 |
def main():
str1="Chennai"
str2="city"
for i in str1:
print "\nCurrent letter is ",i
str3=str1[2:5]
print "\nSubstring is ",str3
print "\nRepeated string is ",str1*100
print "\nConcatenated string is ",str1+str2
main()
|
6944c502687c85549642f8ec67cc69d35f923ff7
|
ganesh-rk/Python-Assignment-Basic
|
/Even or Odd.py
| 144 | 3.796875 | 4 |
def main():
a=10
b=a%2
if b==0:
print "Given number is even"
else:
print "Given number is odd"
main()
|
b5b8ad763c493b7e79cd419bdc08170b1a11dd58
|
TranshumanSoft/quotient-and-rest
|
/modulexercises.py
| 268 | 4.15625 | 4 |
fstnumber = float(input("Introduce a number:"))
scndnumber = float(input("Introduce another number:"))
quotient = fstnumber//scndnumber
rest = fstnumber%scndnumber
print(f"Between {fstnumber} and {scndnumber} there's a quotient of {quotient} and a rest of {rest}")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.