blob_id stringlengths 40 40 | language stringclasses 1 value | repo_name stringlengths 5 133 | path stringlengths 2 333 | src_encoding stringclasses 30 values | length_bytes int64 18 5.47M | score float64 2.52 5.81 | int_score int64 3 5 | detected_licenses listlengths 0 67 | license_type stringclasses 2 values | text stringlengths 12 5.47M | download_success bool 1 class |
|---|---|---|---|---|---|---|---|---|---|---|---|
56357769ac3e5404ad93021d7c27d3ff7db580fb | Python | NatalieP-J/python | /usinginit.py | UTF-8 | 402 | 4.09375 | 4 | [] | no_license | #!/usr/bin/python
#File exploring capabilities of __init__
class Colour:
def __init__(self,colour,age):
self.colour=colour
self.age=age
def colourScheme(self):
print 'The colour of the TARDIS is', self.colour
print 'The doctor is', self.age, 'years old'
p=Colour(raw_input('What is your favourite colour?'),raw_input('How old is the world?'))
p.colourScheme()
| true |
9687a924db55c78007c58930a4852b713c61757d | Python | SebaVGit/plt_reader | /utils/fun.py | UTF-8 | 2,924 | 2.53125 | 3 | [] | no_license |
import sys
import glob
import os
import numpy as np
import pandas as pd
import datetime as dt
from datetime import date
from datetime import timedelta
import matplotlib.ticker as tkr
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import FormatStrFormatter
import locale
from collections import OrderedDict
from tqdm import tqdm
import time
#-------------------skip matplotlib warning-------------------------------
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
#------------------------Function------------------------------------------
def suma_lista(lista,a):
lista=[x+a for x in lista]
return lista
def corte(array):
for i in range(0,len(array[4]),1):
if array[2][i]=='Concentration':
aux=i
break
array=array.drop(array.index[aux:])#en este caso borra todo lo que encuentra después de "Concentration"
array.reset_index(drop=True, inplace=True)
return array
def nombre(array):
name=[]
for i in range(0,len(array[4]),1):
if (array[4][i] not in name)==True:
if array[0][i]=='ZONE':
name.append(array[4][i][:-2])
name=list(OrderedDict.fromkeys(name)) #remover duplicados
return name
def indices(array):
indice_sim=[]
indice_obs=[]
for i in range(0,len(array[4]),1):
if type(array[1][i])==str:
if array[1][i][3:]=='Simulated':
indice_sim.append(i)
elif array[1][i][3:]=='Observed':
indice_obs.append(i)
return indice_sim, indice_obs
def datos(array,indice_sim,indice_obs,i):
obs=[]
sim=[]
tiempo_obs=[]
tiempo_sim=[]
for j in range(0,len(array[4]),1):
if i<len(indice_sim)-1:
if j>=indice_sim[i]+1 and j<=indice_obs[i]-1:
sim.append(float(array[4][j]))
tiempo_sim.append(float(array[2][j]))
if j>=indice_obs[i]+1 and j<=indice_sim[i+1]-1:
obs.append(float(array[4][j]))
tiempo_obs.append(float(array[2][j]))
else:
if j>=indice_sim[i]+1 and j<=indice_obs[i]-1:
sim.append(float(array[4][j]))
tiempo_sim.append(float(array[2][j]))
if j>=indice_obs[i]+1 and j<=len(array[4]):
obs.append(float(array[4][j]))
tiempo_obs.append(float(array[2][j]))
return obs, sim, tiempo_obs, tiempo_sim
def To_Date(lista,fecha_ini):
for k in range(0,len(lista),1):
lista[k]=date.fromordinal(fecha_ini+int(lista[k]))
return lista
def ID_particion(lista,fecha):
booleano=np.array(lista,dtype='datetime64')<np.array(fecha,dtype='datetime64')
index=0
for b in booleano:
index=index+1
if b==False:
break
index=index-1
return index
def clear_list(lista):
lista=[]
return lista | true |
089589dea5c1970a905f37aa8c8a1755c8e7159c | Python | LauZyHou/VisualAnalytics_Back | /DataProcess/genres_sublabel.py | UTF-8 | 546 | 2.65625 | 3 | [] | no_license | import pandas as pd
from typing import List, Dict, Set
"""
*本文件作废
生成genres子标签
"""
if __name__ == '__main__':
# links: pd.DataFrame = pd.read_csv('../DataSet/links.csv')
movies: pd.DataFrame = pd.read_csv('../DataSet/movies.csv')
# ratings: pd.DataFrame = pd.read_csv('../DataSet/ratings.csv')
# tags: pd.read_csv = pd.read_csv('../DataSet/tags.csv')
genres: Set = set()
for s in movies.loc[:, 'genres'].values:
genre_list = s.split('|')
genres |= set(genre_list)
print(genres)
| true |
03fe8dc4e2a07bf2d760414870139756edadc314 | Python | RafaelMRosa/alphaFactory | /alpha_research/factor_transformation.py | UTF-8 | 857 | 3.296875 | 3 | [] | no_license | import pandas as pd
import numpy as np
def normalize_factor(factor: pd.DataFrame, mean=None, std=None) -> pd.DataFrame:
if mean is None:
mean = factor.mean()
if std is None:
std = factor.std()
return (factor - mean) / std
def sigmoid(factor: pd.DataFrame) -> pd.DataFrame:
s = 1 / (1 + np.exp(- factor.values))
return pd.DataFrame(s, index=factor.index)
def percentile_factor(factor: pd.DataFrame, percentage: float) -> pd.Series:
percent_factor = factor.fillna(0)
eighty = np.percentile(percent_factor, percentage * 100)
twenty = np.percentile(percent_factor, (1 - percentage) * 100)
percent = np.where(percent_factor.values >= eighty,
1, np.where(percent_factor.values <= twenty, -1, 0))
percent_factor = pd.Series(percent, index=factor.index)
return percent_factor
| true |
6ba1e1a1cfdae9ed155d41d289aef6f934b60c37 | Python | Bubai-Rahaman/CP_2020_Assignment2 | /question_5.py | UTF-8 | 2,229 | 2.71875 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
#define f(t,x,x')
def f(t,x,xp):
g=10
return -g
#define partial derivative of f(t,x,x') w.r.t x
def fx(t,x,xp):
return 0
#define partial derivative of f(t,x,x') w.r.t x'
def fxp(t,x,xp):
return 0
#define exact solution
def x_true(t):
g=10
tf=10
return -g*t**2/2+g*tf*t/2
ti,tf = 0,10 #end points
alpha,beta = 0,0 #boundary condition
N = 50 #number of subinterval
M_max = 10 #maximum number of iterations
TOL = 1e-4 #Tolerance
h = (tf-ti)/N #stepsize
TK = (beta-alpha)/(tf-ti) #initial guess to x'(t)
w1 = np.zeros(N+1)
w2 = np.zeros(N+1)
t = np.linspace(ti,tf,N+1)
k = 1
def shoting(h,w1,w2,u1,u2,t,N):
for i in range(N):
k11 = h*w2[i]
k21 = h*f(t[i],w1[i],w2[i])
k12 = h*(w2[i]+k21/2)
k22 = h*f(t[i]+h/2, w1[i]+k11/2, w2[i]+k21/2)
k13 = h*(w2[i]+k22/2)
k23 = h*f(t[i]+h/2, w1[i]+k12/2, w2[i]+k22/2)
k14 = h*(w2[i]+k23)
k24 = h*f(t[i]+h, w1[i]+k13, w2[i]+k23)
w1[i+1] = w1[i] + (k11+2*k12+2*k13+k14)/6
w2[i+1] = w2[i] + (k21+2*k22+2*k23+k24)/6
l11 = h*u2
l12 = h*(fx(t[i],w1[i],w2[i])*u1 + fxp(t[i], w1[i], w2[i])*u2)
l21 = h*(u2+l12/2)
l22 = h*(fx(t[i]+h/2,w1[i],w2[i])*(u1+l11/2) + fxp(t[i]+h/2, w1[i], w2[i])*(u2+l12/2))
l31 = h*(u2 + l22/2)
l32 = h*(fx(t[i]+h/2,w1[i],w2[i])*(u1+l21/2) + fxp(t[i]+h/2, w1[i], w2[i])*(u2+l22/2))
l41 = h*(u2+l32)
l42 = h*(fx(t[i]+h,w1[i],w2[i])*(u1+l31) + fxp(t[i]+h, w1[i], w2[i])*(u2+l22))
u1 = u1 + (l11+2*l21+2*l31+l41)/6
u2 = u2 +(l12+2*l22+2*l32+l42)/6
return(w1,u1)
while(k<=M_max):
w1[0],w2[0] = np.array([alpha,TK])
u1 = 0
u2 = 1
w1,u1 = shoting(h,w1,w2,u1,u2,t,N)
if(abs(w1[N]-beta)<=TOL):
print("The correct initial value of x'(t) is ",TK)
break
plt.plot(t,w1,'m')
TK = TK-(w1[N]-beta)/u1
k = k+1
plt.plot(t,w1,'b.',label ='Numerical solution')
plt.plot(t,x_true(t),'m',label ='Analytic solution')
#for plotting candidates solution
ini_guess = np.linspace(30,60,6)
for i in range(6):
w1[0],w2[0] = np.array([alpha,ini_guess[i]])
u1 = 0
u2 = 1
w1,u1 = shoting(h,w1,w2,u1,u2,t,N)
plt.plot(t,w1,'g',label = 'candidate solutions')
plt.xlabel('t')
plt.ylabel('x(t)')
plt.legend()
plt.xlim(0,10)
plt.ylim(0,200)
plt.show()
| true |
c3a19617c82457b827c8d2262b9db159c410f25a | Python | SCIInstitute/UncertainSCI | /tests/test_quad.py | UTF-8 | 3,416 | 2.609375 | 3 | [
"MIT"
] | permissive | import unittest
from math import ceil
import numpy as np
from UncertainSCI.utils import quad
from UncertainSCI.families import JacobiPolynomials, jacobi_weight_normalized
from UncertainSCI.families import HermitePolynomials
class QuadTestCase(unittest.TestCase):
"""
Testing for quadrature routines.
"""
def setUp(self):
self.longMessage = True
def test_gq_modification_global(self):
""" gq_modification for a global integral
Testing of gq_modification on an interval [-1,1] with specified
integrand.
"""
alpha = -1. + 6*np.random.rand()
beta = -1. + 6*np.random.rand()
J = JacobiPolynomials(alpha=alpha,beta=beta)
delta = 1e-8
N = 10
G = np.zeros([N,N])
for n in range(N):
for m in range(N):
# Integrate the entire integrand
integrand = lambda x: J.eval(x, m).flatten()*J.eval(x,n).flatten()*jacobi_weight_normalized(x, alpha, beta)
G[n,m] = quad.gq_modification(integrand, -1, 1, ceil(1+(n+m)/2.), gamma=[alpha,beta])
errstr = 'Failed for (N,alpha,beta) = ({0:d}, {1:1.6f}, {2:1.6f})'.format(N, alpha, beta)
self.assertAlmostEqual(np.linalg.norm(G-np.eye(N), ord=np.inf), 0, delta = delta, msg=errstr)
def test_gq_modification_composite(self):
""" gq_modification using a composite strategy
Testing of gq_modification on an interval [-1,1] using a composite
quadrature rule over a partition of [-1,1].
"""
alpha = -1. + 6*np.random.rand()
beta = -1. + 6*np.random.rand()
J = JacobiPolynomials(alpha=alpha,beta=beta)
delta = 5e-6
N = 10
G = np.zeros([N,N])
# Integrate just the weight function. We'll use modifications for the polynomial part
integrand = lambda x: jacobi_weight_normalized(x, alpha, beta)
for n in range(N):
for m in range(N):
coeffs = J.leading_coefficient(max(n,m)+1)
if n != m:
zeros = np.sort(np.hstack( (J.gauss_quadrature(n)[0], J.gauss_quadrature(m)[0]) ))
quadzeros = np.zeros(0)
leading_coefficient = coeffs[n]*coeffs[m]
else:
zeros = np.zeros(0)
quadzeros = J.gauss_quadrature(n)[0]
leading_coefficient = coeffs[n]**2
demarcations = np.sort(zeros)
D = demarcations.size
subintervals = np.zeros([D+1, 4])
if D == 0:
subintervals[0,:] = [-1, 1, beta, alpha]
else:
subintervals[0,:] = [-1, demarcations[0], beta, 0]
for q in range(D-1):
subintervals[q+1,:] = [demarcations[q], demarcations[q+1], 0, 0]
subintervals[D,:] = [demarcations[-1], 1, 0, alpha]
G[n,m] = quad.gq_modification_composite(integrand, -1, 1, 20, subintervals=subintervals,roots=zeros, quadroots=quadzeros,leading_coefficient=leading_coefficient)
errstr = 'Failed for (N,alpha,beta) = ({0:d}, {1:1.6f}, {2:1.6f})'.format(N, alpha, beta)
self.assertAlmostEqual(np.linalg.norm(G-np.eye(N), ord=np.inf), 0, delta = delta, msg=errstr)
if __name__ == "__main__":
unittest.main(verbosity=2)
| true |
9975b051a6983b6480a95d3f8adfa57fca7f4469 | Python | matiasg/allocation | /tests/test_classes_properties.py | UTF-8 | 197 | 2.546875 | 3 | [] | no_license | import pytest
from allocation.allocating import Allocation
def test_Allocation():
allocation = Allocation([('a', '1'), ('b', '2'), (None, '3'), ('c', None)])
assert len(allocation) == 2
| true |
99cc49df8459d5071c9ba25eaa6367c113e4726e | Python | dangillet/Pythoria | /pythoria/events.py | UTF-8 | 4,565 | 3.375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# From http://stackoverflow.com/a/7294148/893822
import weakref
class WeakBoundMethod:
"""
Wrapper around a method bound to a class instance. As opposed to bare
bound methods, it holds only a weak reference to the `self` object,
allowing it to be deleted.
This can be useful when implementing certain kinds of systems that
manage callback functions, such as an event manager.
"""
def __init__(self, meth):
"""
Initializes the class instance. It should be ensured that methods
passed through the `meth` parameter are always bound methods. Static
methods and free functions will produce an `AssertionError`.
"""
assert (hasattr(meth, '__func__') and hasattr(meth, '__self__')),\
'Object is not a bound method.'
self._self = weakref.ref(meth.__self__)
self._func = meth.__func__
def __call__(self, *args, **kw):
"""
Calls the bound method and returns whatever object the method returns.
Any arguments passed to this will also be forwarded to the method.
In case an exception is raised by the bound method, it will be
caught and thrown again to the caller of this `WeakBoundMethod` object.
Calling this on objects that have been collected will result in
an `AssertionError` being raised.
"""
assert self.alive(), 'Bound method called on deleted object.'
try:
return self._func(self._self(), *args, **kw)
except Exception as e:
raise e
def alive(self):
"""
Checks whether the `self` object the method is bound to has
been collected.
"""
return self._self() is not None
class Connection:
"""
A Connection object knows the listener WeakMethod for a given
event type (string) in an event dispatcher.
When the Connection gets deleted, it asks the event dispatcher to remove
itself from its dict of listeners.
A Connection is normally created by the event dispatcher when a listener
binds itself for some event type notifications.
"""
def __init__(self, event_dispatcher, event_type, listener):
"""
event_dispatcher is the object which created the Connection.
eventcls is the type of event this connection is linked to.
listener is the weak bound method called when the event eventcls is
posted.
"""
self.ed = event_dispatcher
self.event_type = event_type
self.listener = listener
def __del__(self):
"""
When the connection gets deleted, the event dispatcher removes the
weak bound method from its dict of listeners for the given event class.
"""
self.ed.remove(self)
class EventDispatcher:
"""
Class that implements events dispatching. Listeners register their
bound method for a given event type (string).
"""
def __init__(self):
# Dict that maps event types to lists of listeners
self._listeners = dict()
def bind(self, event_type, listener):
"""
event_type is a string description of the event type the listener want
to get notified about.
listener is a bound method of the listener. It will get called with
optional arguments depending on the event type when the post method is
called.
Returns a Connection object which when deleted will remove the weak
bound method from the listeners dict.
"""
listener = weakref.WeakMethod(listener)
self._listeners.setdefault(event_type, list()).append(listener)
return Connection(self, event_type, listener)
def post(self, event_type, *args, **kwargs):
"""
Post an event to the interested weak bound methods registered with the
add method.
"""
try:
for listener in self._listeners[event_type]:
if listener():
listener()(*args, **kwargs)
except KeyError:
pass # No listener interested in this event
def remove(self, connection):
"""
Removes a weak bound method for a given event class. The connection
object contains this information.
"""
list_bound_methods = self._listeners[connection.event_type]
if connection.listener in list_bound_methods:
list_bound_methods.remove(connection.listener)
| true |
2fba805bbdea389fb152beee3c781c440bd0dd9c | Python | mcorley1/Intro_Biocom_ND_319_Tutorial5 | /Exercise_5_Part_2.py | UTF-8 | 448 | 3.359375 | 3 | [] | no_license | import pandas
df=pandas.read_csv('wages.csv')
#df=wages.csv data
#Highest earner
highest_earner=df.nlargest(1,'wage')
#output is under highest_earner (male,5,11,39.808917197)
#Lowest earner
lowest_earner=df.nsmallest(1,'wage')
#Output is under lowest_earner (female,9,11,0.07655561)
#Number of females in the top 10
num_of_females=df[df['wage']>=df['wage'].nlargest(10).iloc[-1]]['gender'].eq('female').sum()
#Output is under num_of_females (=2) | true |
999cc110852149b545d3a8e1f14a92771f054000 | Python | kitoriaaa/Algorithms | /ITP1/10_B.py | UTF-8 | 220 | 3.265625 | 3 | [] | no_license | import math
a, b, c = map(int, input().split())
S = (1/2)*a*b*math.sin(math.radians(c))
d_double = a**2 + b**2 - 2*a*b*math.cos(math.radians(c))
d = (d_double)**(1/2)
L = a + b + d
h = S*2/a
print(S)
print(L)
print(h) | true |
a3d3f6f0fc6a01b19b96901b05af766e704711ef | Python | LEEPPEUM/final_project | /DB/juno/connect_mariadb.py | UTF-8 | 336 | 2.671875 | 3 | [] | no_license | import pymysql
db = pymysql.connect(host='localhost',port=3306,user='root',passwd='tiger',db='yojulabdb',charset='utf8',autocommit=True)
cursor = db.cursor(pymysql.cursors.DictCursor)
cursor.execute("SELECT* from DATASET LIMIT 5")
data = cursor.fetchall()
for infor in data:
print("economic : %s " % infor['title'])
db.close() | true |
2d8707e2db85c2c82f39865e31dc85be0d46d18f | Python | unbadfish/NetEase-id-geter | /old/byre.py | UTF-8 | 961 | 3.0625 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: UTF-8 -*-
import re
'''
Copyright 2020 unbadfish@github
Licensed under the Apache License, Version 2.0
'''
def get_id_re(in_string):
id_work = ''
try:
match1 = re.finditer('"id":([0-9]+,)"v":[0-9]*?,"alg":[a-z]+?', in_string) # find all
for each_match in match1:
each_id = each_match.group(1)
id_work = id_work + each_id
out_id = id_work[0:-1]
print(out_id) # like>>1420663042,1423985980
except BaseException:
print('Try again.You should input a string like:')
print('{"trackIds":[{"id":1420663042,"v":5,"alg":null},{"id":1423985980,"v":6,"alg":null}]}')
while True:
# in_str = '{"trackIds":[{"id":1420663042,"v":5,"alg":null},{"id":1423985980,"v":6,"alg":null}]}'
# print(get_id_re(in_str))
# test string
print('Paste the string')
user_in = input()
if user_in.casefold() == 'bye':
break
get_id_re(user_in)
# break
| true |
de9c89b414f42b0045c58ae261a5ede6faaba439 | Python | hivehelsinki/remote-challs | /chall01/rjaakonm.py | UTF-8 | 648 | 3.0625 | 3 | [] | no_license | #!/usr/bin/python3
import sys
morse = [".-",
"-...",
"-.-.",
"-..",
".",
"..-.",
"--.",
"....",
"..",
".---",
"-.-",
".-..",
"--",
"-.",
"---",
".--.",
"--.-",
".-.",
"...",
"-",
"..-",
"...-",
".--",
"-..-",
"-.--",
"--.."]
def main():
if (len(sys.argv) != 2) or (len(sys.argv[1]) == 0):
print("usage: ./rjaakonm.py <a-zA-Z string>")
return
str = ""
sys.argv[1] = sys.argv[1].lower()
for char in sys.argv[1]:
if char.isalpha():
str += morse[ord(char) - 97]
elif char == " ":
str += " "
else:
print("usage: ./rjaakonm.py <a-zA-Z string>")
return
print(str)
if __name__ == "__main__":
main() | true |
963a9f32edec57675ade2010d73f58c9fe68279f | Python | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_138/1184.py | UTF-8 | 1,044 | 3.015625 | 3 | [] | no_license |
import fileinput
def solveD(A,B):
C = sorted(zip(A,[0]*len(A))+zip(B, [1] *len(B)), key = lambda x: x[0])
aux = 0
loses = 0
for i in range(len(C)):
if C[i][1] == 1:
aux += 1
elif C[i][1] == 0:
aux -= 1
if aux < 0:
loses += 1
aux = 0
jane_wins_trick = len(A)-loses
aux = 0
for i in range(len(C)):
if C[i][1] == 0:
aux += 1
if aux > 0 and C[i][1] == 1:
aux -= 1
jane_wins_normal = aux
return jane_wins_trick, jane_wins_normal
def main():
fin = fileinput.input()
T = int(next(fin)) # number of test cases
for case in range(1, T+1):
N = int(next(fin)) # number of blocks
A = [float(x) for x in next(fin).split(" ")]
B = [float(x) for x in next(fin).split(" ")]
R1,R2 = solveD(A, B)
print("Case #{}: {} {}".format(case,R1,R2))
fin.close()
if __name__ == '__main__':
main()
| true |
db276c8a4ec9ca0275b58a342d5ab6740a9fa71a | Python | daishengliang/coding-challenge | /Google/246. Strobogrammatic Number.py | UTF-8 | 898 | 4.125 | 4 | [] | no_license | """
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
"""
class Solution(object):
def isStrobogrammatic(self, num):
"""
:type num: str
:rtype: bool
"""
d = {'0':'0', '1':'1', '8':'8', '6':'9', '9':'6'}
if len(num) == 1 and num[0] not in d:
return False
i, j = 0, len(num) - 1
while 1:
if i>j:
break
if i == j:
return num[i] in ['0', '1', '8']
if num[i] in d and d[num[i]] == num[j]:
i += 1
j -= 1
else:
return False
return True | true |
f15208337d94a368f19eed2200424061cc1176ba | Python | ikeda-hitomi/mypkg | /scripts/turtle.py | UTF-8 | 1,127 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
from turtlesim.msg import Pose
cmd_vel = Twist()
cmd_vel.linear.x = 2.0
cmd_vel.angular.z = 0.0
pose = Pose()
nowRotating = False
def update_pose(data):
global pose
pose.x = data.x
pose.y = data.y
def update_cmd_vel():
global cmd_vel
global nowRotating
boundary = 1.0
if (pose.x < boundary or pose.x > 11.08-boundary or pose.y < boundary or pose.y > 11.08-boundary) and not nowRotating:
cmd_vel.linear.x = 0.0
cmd_vel.angular.z = 10
nowRotating = True
else:
cmd_vel.linear.x = 5.0
cmd_vel.angular.z = 0.0
nowRotating = False
def autonomous_controller():
rospy.init_node('autonomous_controller')
pub = rospy.Publisher('cmd_vel', Twist, queue_size=10)
sub = rospy.Subscriber('pose', Pose, update_pose)
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
update_cmd_vel()
pub.publish(cmd_vel)
rate.sleep()
if __name__ == '__main__':
try:
autonomous_controller()
except rospy.ROSInterruptException:
pass
| true |
7b6fc07740b6224855731ecef524f20d5d50d4d8 | Python | wum5/I529-Group-Projects | /Project2/Python/PredProStr_ghmm.py | UTF-8 | 11,770 | 2.96875 | 3 | [] | no_license | #parse the given training set protein sequence file and generate two list of protein sequence and corresponding feature of i,m,o
import sys, math, argparse
from itertools import groupby
import re
#this class check input format and parse fasta file into two list containing index and sequence
class classFASTA:
def __init__(self, fileFASTA):
self.fileFASTA = fileFASTA
def readFASTA(self):
return self.ParseFASTA(self.fileFASTA)
def ParseFASTA(self, fileFASTA):
fasta_list=[]
for line in fileFASTA:
line = line.rstrip()
if '<>' in line:
curr_data = [[],[]]
elif 'end' in line:
curr_data[0] = ''.join(curr_data[0])
curr_data[1] = ''.join(curr_data[1])
fasta_list.append(curr_data)
elif (re.search('[a-zA-Z]', line)):
curr_data[0].append(line.split()[0])
curr_data[1].append(line.split()[1])
return fasta_list
#table of peptide length frequency in both membrane and non-membrane domain
def generate_length(feature_set):
h_length={}#key is length, value is frequency
e_length={}
c_length={}
for sequence in feature_set:
tmp=[''.join(g) for k,g in groupby(sequence)] #parse the feature sequence into tmp=['mmm','iii','oooo'..]
for each in tmp:
if 'h' in each.lower():#the membrane segment
if len(each) not in h_length.keys():
h_length[len(each)] = 1
else:
h_length[len(each)] += 1
elif 'e' in each.lower():#inside segment
if len(each) not in e_length.keys():
e_length[len(each)] = 1
else:
e_length[len(each)] += 1
elif '_' in each.lower():#outside segment
if len(each) not in c_length.keys():
c_length[len(each)] = 1
else:
c_length[len(each)] += 1
#return three dictionaries
return h_length,e_length,c_length
#calculate the frequency of length for i,m,o domain
def lengthFrequency(length_set):
lengthFreq={}
domain_total=sum(length_set.values())
for key in length_set:
lengthFreq[key]= float(length_set[key])/domain_total
return lengthFreq
# calculate the emission probability from each state to amino acids
def EmissionProb(seq_set, feature_set):
'''seq_set is a list of peptide sequences, feature_set is a list of features'''
element = len(seq_set)#number of protein sequences
emit_dict = {}#the emission table in format emit_dict['M->A']=
for x in range(element):
size = len(seq_set[x])
for y in range(size):
curr_emit = feature_set[x][y]+'->'+seq_set[x][y]
if curr_emit not in emit_dict:
emit_dict[curr_emit] = 1
else:
emit_dict[curr_emit] += 1
alpha, beta, coli = 0, 0, 0
for key in emit_dict:
if 'h->' in key:
alpha += emit_dict[key]
elif 'e->' in key:
beta += emit_dict[key]
elif '_->' in key:
coli += emit_dict[key]
for key in emit_dict:
if 'h->' in key:
emit_dict[key] = float(emit_dict[key])/alpha
elif 'e->' in key:
emit_dict[key] = float(emit_dict[key])/beta
elif '_->' in key:
emit_dict[key] = float(emit_dict[key])/coli
return emit_dict
# calculate the transition probability between states
def TransitionProb(feature):
trans_dict={}
states=['h','e','_']
trans_dict = {'h->e':0, 'h->_':0, 'e->h':0, 'e->_':0, '_->h':0, '_->e':0}
for x in range(len(feature)):
seq = feature[x]
for y in range(len(seq)-1):
if seq[y] != seq[y+1]:
curr_trans = seq[y]+'->'+seq[y+1]
for key in trans_dict:
if key == curr_trans:
trans_dict[curr_trans] += 1
alpha = trans_dict['h->e']+trans_dict['h->_']
beta = trans_dict['e->h']+trans_dict['e->_']
coli = trans_dict['_->h']+trans_dict['_->e']
trans_dict['h->e'] = float(trans_dict['h->e'])/alpha
trans_dict['h->_'] = float(trans_dict['h->_'])/alpha
trans_dict['e->h'] = float(trans_dict['e->h'])/beta
trans_dict['e->_'] = float(trans_dict['e->_'])/beta
trans_dict['_->h'] = float(trans_dict['_->h'])/coli
trans_dict['_->e'] = float(trans_dict['_->e'])/coli
return trans_dict
# calculate the probability of initial state
def InitState(feature_set):
element = len(seq_set)
init_state = {}
for x in range(element):
curr_init = feature_set[x][0]
if curr_init not in init_state:
init_state[curr_init] = 1
else:
init_state[curr_init] += 1
alpha, beta, coli = 0, 0, 0
for key in init_state:
if 'h' in key:
alpha += init_state[key]
elif 'e' in key:
beta += init_state[key]
else:
coli += init_state[key]
for key in init_state:
if 'h' in key:
init_state[key] = float(init_state[key])/alpha
elif 'e' in key:
init_state[key] = float(init_state[key])/beta
else:
init_state[key] = float(init_state[key])/coli
return init_state
#calculate the maximum probability of hidden states sequence
def max_hidden(seq,len_table,emit_dict,trans_dict,initial):
l=len(seq)#length for each test sequence
m=len(len_table)#number of hidden states,len_table is list of three dictionaries
states=['h','e','_']
pro_table = [[1 for x in range(l)]for x in range(m)]#pro_table is the max_hidden states probability table
pos_table = [[1 for x in range(l)]for x in range(m)]#pos_table is the path table for max_hidden states
pro_table[0][0] = 0.00000000001 #actually 0 but since we use log, we assign this very small value for starting M
pro_table[1][0] = 0.00000000001
pro_table[2][0] = initial['_']
for i in range(1,l):
for j in range(m):
'''pro_oneseq is the probability that observed segment ends in state j is continous '''
pro_oneseg = math.log(len_table[j][i+1])+math.log(pro_table[j][0]) ##initial probabilty * length ditribution probability (from position 0)
for aa in seq[:i+1]:
emit = states[j]+'->'+ aa.upper()
pro_oneseg += math.log(emit_dict[emit])
pro_table[j][i] = float(pro_oneseg) ##assign the probabilty of first conditon to [j][i] at first
pos_table[j][i] = (j,0) ##ths position for first conditon is to start from position 0
for k in range(1,i):
for p in range(m):
tmp = 0 ##the probability for second condition
if p!=j: ##the second condition is to start from any cells not in the same row with final state
seg = seq[k+1:i+1]#the duration sequence in state j
trans = states[p] +'->'+ states[j]#state transition from p to j
tmp += pro_table[p][k] + math.log(trans_dict[trans]) + math.log(len_table[j][i-k])#the preceding state [p][k] and transition probability and duration probability
for aa in seg:#the emission of aa in state j, I ignored a typo here that I wrote k instead of j
emit = states[j] + '->' + aa.upper()
tmp += math.log(emit_dict[emit])
if pro_table[j][i]< tmp:
pro_table[j][i] = tmp #tmp max value
pos_table[j][i] = (p,k)#postion of preceding state
return pro_table,pos_table
def TraceBack(seq,emit_dict,pro_table,pos_table):
x = len(seq)-1
HiddenStates = ''
TMScore = max(pro_table[0][x],pro_table[1][x],pro_table[2][x])
if max(pro_table[0][x],pro_table[1][x],pro_table[2][x]) == pro_table[0][x]:
record = pos_table[0][x]
state = 'h'
elif max(pro_table[0][x],pro_table[1][x],pro_table[2][x]) == pro_table[1][x]:
record = pos_table[1][x]
state = 'e'
elif max(pro_table[0][x],pro_table[1][x],pro_table[2][x]) == pro_table[2][x]:
record = pos_table[2][x]
state = '_'
repeats = x - record[1]
HiddenStates += state*repeats
pre_state = record[0]
pre_pos = record[1]
while True:
record = pos_table[pre_state][pre_pos]
if pre_state == 0:
state = 'h'
elif pre_state == 1:
state = 'e'
elif pre_state == 2:
state = '_'
repeats = pre_pos - record[1]
HiddenStates += state*repeats
pre_state = record[0]
pre_pos = record[1]
if pre_pos == 0:
HiddenStates += state
break
HiddenStates = HiddenStates[::-1]
return HiddenStates
def AccuracyTest(real_states, pred_states):
total, positive = 0, 0
for x in range(len(real_states)):
total += 1
if pred_states[x] == real_states[x]:
positive += 1
accuracy = str(float(positive)/total*100)+'%'
return accuracy
###======read traing file and generate GMMM model ======
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-i','--fasta_file',required=True)
parser.add_argument('-o','--out_file',required=True)
parser.add_argument('-l','--length_table')
args = parser.parse_args()
with open("training.txt","r") as training_file:
train_set = classFASTA(training_file)
seq_set = [ x[0] for x in train_set.readFASTA() ]
with open("training.txt","r") as training_file:
train_set = classFASTA(training_file)
feature_set = [ x[1] for x in train_set.readFASTA() ]
h_length,e_length,c_length = generate_length(feature_set)
h_freq = lengthFrequency(h_length)
e_freq = lengthFrequency(e_length)
c_freq = lengthFrequency(c_length)
with open("alpha_freq.txt","w") as ofile:
for key in h_freq.keys():
ofile.write(str(key)+"\t"+str(h_freq[key])+"\n")
with open("beta_freq.txt","w") as ofile:
for key in e_freq.keys():
ofile.write(str(key)+"\t"+str(e_freq[key])+"\n")
with open("coli_freq.txt","w") as ofile:
for key in c_freq.keys():
ofile.write(str(key)+"\t"+str(c_freq[key])+"\n")
emit_prob = EmissionProb(seq_set, feature_set)
trans_prob = TransitionProb(feature_set)
init_state = InitState(feature_set)
test_class = classFASTA(args.fasta_file)
with open(args.fasta_file,"r") as test_set:
test_set = classFASTA(test_set)
test_seqs = [ x[0] for x in test_set.readFASTA() ]
with open(args.fasta_file,"r") as test_set:
test_set = classFASTA(test_set)
test_states = [ x[1] for x in test_set.readFASTA() ]
index = 0
for i in range(len(test_seqs)):#test_seq is each test protein sequence
test_seq = test_seqs[i]
test_label = test_states[i]
tmph_length,tmpe_length,tmpc_length = {}, {}, {}#three dictionaries for m,i,o length distribution
for key in h_length.keys():#use training prior knowledge
tmph_length[key] = h_length[key]
for key in e_length.keys():
tmpe_length[key] = e_length[key]
for key in c_length.keys():
tmpc_length[key] = c_length[key]
for i in range(len(test_seq)):
if i+1 not in tmph_length.keys():
tmph_length[i+1] = 0.00000000001
else:
tmph_length[i+1] += 0.00000000001
if i+1 not in tmpe_length.keys():
tmpe_length[i+1] = 0.00000000001
else:
tmpe_length[i+1] += 0.00000000001
if i+1 not in tmpc_length.keys():
tmpc_length[i+1] = 0.00000000001
else:
tmpc_length[i+1] += 0.00000000001
tmph_len = lengthFrequency(tmph_length)#calculate probability table for each length table
tmpe_len = lengthFrequency(tmpe_length)
tmpc_len = lengthFrequency(tmpc_length)
len_table = [tmph_len,tmpe_len,tmpc_len]#list of length dictionaries
#check length probabilty
#for check in [tmph_len,tmpe_len,tmpc_len]:#check if sum of probability is 1
# print("the sum of probabilty is %f" %(sum(check.values())))
#for domain in tmpm_len.keys():
# print("probability of fragment in length %d in mem is %f" %(domain,tmpm_len[domain]))
#for domain in tmpi_len.keys():
#print("probability of fragment in length %d in in is %f"%(domain,tmpi_len[domain]))
#for domain in tmpo_len.keys():
#print("probability of fragment in length %d in out is %f"%(domain,tmpo_len[domain]))
#calculate the viterbi value table and path table,then produce string of hidden_states
#print len_table
#print len(emit_prob)
#print trans_prob
#print init_state
maxpro_table,pos_table = max_hidden(test_seq,len_table,emit_prob,trans_prob,init_state)
pred_states = TraceBack(test_seq,emit_prob,maxpro_table,pos_table)
index += 1
real_states = ''.join(test_label)
accuracy = AccuracyTest(real_states, pred_states)
print ('%d\t%s') % (index, accuracy)
#append the hidden_states to output file following seq index and protein sequence
with open(args.out_file,"a") as ofile:
ofile.write("%s\n" % (test_seq))
ofile.write("%s\n" % (pred_states))
| true |
8971fb9fb9c60c68d525a19c2b00ebeb72c8c160 | Python | fossilwu/python-News | /excel001/tkui.py | UTF-8 | 873 | 2.671875 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set fileencoding=latin1:
# from tkinter import *
# from tkinter.filedialog import askdirectory,askopenfilename
from start_2 import maines
#
# filename = "1"
# def selectPath():
# path_ = askopenfilename()
# # print path_
# # global filename
# # filename = path_
# path.set(path_)
#
# root = Tk()
# path = StringVar()
# # print filename
# Label(root,text = "目标路径:").grid(row = 0, column = 0)
# Entry(root, textvariable = path).grid(row = 0, column = 1)
# print
# Button(root, text = "路径选择", command = selectPath).grid(row = 0, column = 2)
#
# root.mainloop()
from tkinter import filedialog
filename = filedialog.askopenfilename(initialdir = '',title = "请选择xls文件",filetypes = (("xls文件","*.xls"),("所有文件","*.*")))
print(filename)
maines(filename)
# print 'success' | true |
06f7efb25865ccf49e6483ba359b8e01cb9682b7 | Python | smallfishxz/Practice_Algorithm | /brownbag/task_scheduler.py | UTF-8 | 2,637 | 3.859375 | 4 | [] | no_license | # We have a list of various types of tasks to perform.
# Task types are identified with an integral identifier: task of type 1, task of type 2, task of type 3, etc.
# Each task takes 1 time slot to execute, and once we have executed a task we need cooldown (parameter) time slots to recover
# before we can execute another task of the same type.
# However, we can execute tasks of other types in the meantime. The recovery interval is the same for all task types.
# We do not reorder the tasks: always execute in order in which we received them on input.
# Given a list of input tasks to run, and the cooldown interval, output the minimum number of time slots required to run them.
# time complexity: O(N)
# space: O(num_task_type)
def schedule_task(task_in, cooldown):
# initialize the required time slot as 0, and a dictionary to record the slot number
# that a type of task was last executed
pos = 0
last_execution = dict()
for task in task_in:
# if the task is scheduled for the first time, directly put into the scheduler
# and update the dictionary
if task not in last_execution:
pos += 1
last_execution[task] = pos
print(last_execution)
# if the task has been executed before
else:
# since_last gets how many slots have been past since last execution
since_last = pos - last_execution[task]
# wait to get how many more slots needed to wait
wait = cooldown - since_last
# pos is updated to reflect which slot this task could be inserted
pos += wait+1
# update dictionary to reflect the new last execution slot
last_execution[task] = pos
print(last_execution)
return pos
# This solution can be optimized to use memory O(min(num_task_type, cooldown_time)).
# Iterate over entire hash map every cooldown steps and delete unneeded entries
# Time complexity is still O(N)
def schedule_task1(task_in, cooldown):
pos = 0
last_execution = dict()
for i in range(len(task_in)):
task = task_in[i]
if task not in last_execution:
pos+=1
last_execution[task]=pos
else:
since_last = pos - last_execution[task]
wait_time = cooldown - since_last
pos += wait_time + 1
last_execution[task] = pos
# Optimization
if i % cooldown == 0:
to_remove = []
for tas, etime in last_execution.items():
if cooldown < pos - etime:
to_remove.append(tas)
for tas in to_remove:
del last_execution[task]
return pos
print(schedule_task([1,1,2,1], 2))
print(schedule_task([1,2,3,1,2,3], 3))
print(schedule_task1([1,2,3,4,5,6,2,4,6,1,2,4], 6))
| true |
4d45ebaf7d0781ad37777b7ed36630b300740c34 | Python | rctcwyvrn/advent | /advent2020/day9/cleaned.py | UTF-8 | 834 | 3.359375 | 3 | [] | no_license | def check(buf, val):
for x in buf:
for y in buf:
if x + y == val:
return True
return False
def find_xmas_weakness(nums):
buf = []
ctr = 0
invalid = None
for x in nums:
if ctr >= 25:
if not check(buf, x):
invalid = x
break
buf[ctr % 25] = x
else:
buf.append(x)
ctr +=1
if invalid == None:
return ("failed", None)
# Maybe see if this can be made more efficient?
sums = []
for x in nums:
for s in sums:
if sum(s) == invalid:
return ("ok", min(s) + max(s))
else:
s.append(x)
sums.append([x])
# from input import x
# print(find_xmas_weakness([int(line) for line in x.split("\n")])) | true |
90c25504e2442d455ee7e36e26db0d1f41395b92 | Python | SarthakU/DailyProgrammer | /Python/Daily013_intermediate/ReversedStringA.py | UTF-8 | 275 | 3.0625 | 3 | [] | no_license | ## REVERSED STRING
##
## challenge #13 (intermediate)
## http://www.reddit.com/r/dailyprogrammer/comments/pzo7g/2212012_challenge_13_intermediate/
##
##
## sarthak7u@gmail.com
##
string = list(raw_input("Enter String:"))
string.reverse()
open("reverse.txt", "w").write("".join(string)) | true |
aae9e1275486a8507b55e915d40e66985dadfc22 | Python | jtlai0921/Python- | /ex07/test07_4.py | UTF-8 | 228 | 3.421875 | 3 | [] | no_license | def f(n) :
if (n > 3) :
return 1
elif (n == 2) :
return 3 + f(n+1)
else :
return 1 + f(n+1)
def g(n) :
j = 0
for i in range(1, n) :
j = j + f(i)
return j
print(g(4))
| true |
7c0008ffd898a9f879ec2494b649f71578d19d13 | Python | archane/python | /twitter_feed_tweepy.py | UTF-8 | 1,466 | 2.59375 | 3 | [] | no_license | #!/usr/bin/env python
# Created by Frank Jensen
# This code printed out the username and msg of anyone in the follow list to stdout
# Tweepy is the only required module for this program
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
from tweepy import Stream
import json
from StringIO import StringIO
consumer_key=''
consumer_secret=''
access_token=''
access_token_secret=''
follow_list = ['25073877','1339835893','13115682','822215679726100480','822215673812119553'] #these are just examples
#follow list = trump,hilary,azcentral,POTUS,whitehouse
class StdOutListener(StreamListener):
def on_status(self, status):
user_json = json.load(StringIO(json.dumps(status._json['user'])))
user_lang = json.dumps(user_json['lang'])
user_id = json.dumps(user_json['id'])
is_reply = status.in_reply_to_status_id
temp_user = json.dumps(user_json['screen_name'])
if user_lang == '"en"': # and user_id in follow_list:
print(temp_user.ljust(20) + "," + status.text)
def on_error(self, status_code):
if status_code == 420:
#returning False in on_data disconnects the stream
return False
print(status_code)
if __name__ == '__main__':
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
stream.filter(follow=follow_list)
| true |
e923fdbb51d997358f188ce5b815bbd8c5433a34 | Python | Been-H/Simulations | /simulations/NatSelecPredation.py | UTF-8 | 2,443 | 2.75 | 3 | [] | no_license | class NatSelectPredationSim(Simulation):
def __init__(self, num_generations, max_organisms, hunting_rate):
super().__init__(num_generations)
self.max_organisms = max_organisms
self.hunting_rate = hunting_rate
self.average_speeds = []
def handle_predation(self):
survived = []
for organism in self.organisms:
speed = organism.get_trait("Speed")
if r.random() < self.hunting_rate:
if speed.value <= 2:
continue
elif speed.value < 5:
if r.random() < .5:
continue
survived.append(organism)
elif speed.value < 6:
if r.random() < .4:
continue
survived.append(organism)
else:
if r.random() < .3:
continue
survived.append(organism)
else:
survived.append(organism)
self.organisms = survived
def handle_reproduction(self):
if len(self.organisms) * 2 >= self.max_organisms:
return
super().handle_reproduction("Speed")
def calculate_stats_per_generation(self):
super().calculate_stats_per_generation()
self.calculate_average_speeds()
def calculate_average_speeds(self):
total = 0
for organism in self.organisms:
total += [trait for trait in organism.traits if trait.name == 'Speed'][0].value
average_speed = total / len(self.organisms)
self.average_speeds.append(average_speed)
def plot_results(self):
fig, (plt1, plt2) = plt.subplots(2, 1)
fig.suptitle('Data From Simulation', fontsize=20)
plt1.plot(self.generation_marks, self.average_speeds)
plt1.set_xlabel('Reproductive Generation', fontsize=14)
plt1.set_ylabel('Average Value of Speed Gene', fontsize=14)
plt1.set_xticks(scipy.arange(0, self.num_generations, 50))
plt1.set_yticks(scipy.arange(0, 14, 1))
plt2.plot(self.generation_marks, self.num_organisms)
plt2.set_xlabel('Reproductive Generation', fontsize=14)
plt2.set_ylabel('Number of Bunnies', fontsize=14)
plt2.set_xticks(scipy.arange(0, self.num_generations, 100))
plt2.set_yticks(scipy.arange(0, self.max_organisms, 100))
plt.show()
| true |
29fb1fe00534ea263566b4f15dcab4d0f4b81e43 | Python | Narendranthangavelu/map_alteration | /saya_bringup/script/best_fit_line_finder.py | UTF-8 | 1,713 | 3.765625 | 4 | [] | no_license | #!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
def plot_graphs(x1,y1,x2,y2,x_best_fit_1,y_best_fit_1,x_best_fit_2, y_best_fit_2,slope1,intercept1,slope2,intercept2):
plt.subplot(1, 2, 1)
plt.title('Slope: ' + str(slope1) + ' / Intercept: ' + str(intercept1))
plt.plot(x1,y1)
plt.plot(x_best_fit_1,y_best_fit_1)
plt.subplot(1, 2, 2)
plt.title('Slope: ' + str(slope2) + ' / Intercept: ' + str(intercept2))
plt.plot(x2,y2)
plt.plot(x_best_fit_2, y_best_fit_2)
plt.show()
def find_angle(x,y):
x = [10,9]
y = [10,10.01]
m, b = np.polyfit(x, y, 1)
angle = np.arctan(m)
if x[0] > x[-1]:
angle = np.pi + angle
if angle < 0.0:
angle = 2*np.pi + angle
return(m,b)
def generate_curve(power_value, direction):
x=np.arange(25)
y=[]
for i in range(25):
y.append(direction * (i**power_value))
return (x,y)
def generate_best_fit_line(slope, intercept):
x=np.arange(25)
for i in range(25):
y=(slope*x)+intercept
return(x,y)
def main():
#Variables
power_value_1 = 2
power_value_2 = 2
#Generate Curves
x1,y1 = generate_curve(power_value_1, 1)
x2,y2 = generate_curve(power_value_2, -1)
#Find Slope and Intercept
slope1,intercept1 = find_angle(x1,y1)
slope2,intercept2 = find_angle(x2,y2)
#Generate Best Fit Line
x_best_fit_1, y_best_fit_1 = generate_best_fit_line(slope1,intercept1)
x_best_fit_2, y_best_fit_2 = generate_best_fit_line(slope2,intercept2)
#Plot Graph
plot_graphs(x1,y1,x2,y2,x_best_fit_1,y_best_fit_1,x_best_fit_2, y_best_fit_2,slope1,intercept1,slope2,intercept2)
if __name__=='__main__':
main() | true |
00d0e397477c3956325c7f538aa86621fc2eb476 | Python | acsr/rst2db | /abstrys/sphinx_ext/docbook_builder.py | UTF-8 | 3,235 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | # -*- coding: utf-8 -*-
#
# abstrys.sphinx_ext.docbook_builder
# ------------------------------
#
# A DocBook builder for Sphinx, using rst2db's docbook writer.
#
# by Eron Hennessey
from abstrys.docutils_ext.docbook_writer import DocBookWriter
from docutils.core import publish_from_doctree
from sphinx.builders.text import TextBuilder
import os, sys
class DocBookBuilder(TextBuilder):
"""Build DocBook documents from a Sphinx doctree"""
name = 'docbook'
def process_with_template(self, contents):
"""Process the results with a moustache-style template.
The template variables can be specified as {{data.root_element}} and
{{data.contents}}. You can use this to create a custom DocBook header
for your final output."""
try:
import jinja2
except ImportError:
sys.stderr.write("DocBookBuilder -- Jinja2 is not installed: can't use template!\n")
sys.exit(1)
full_template_path = os.path.join(sphinx_app.env.srcdir,
sphinx_app.config.docbook_template_file)
if not os.path.exists(full_template_path):
sys.stderr.write(
"DocBookBuilder -- template file doesn't exist: %s\n" %
full_template_path)
sys.exit(1)
data = { 'root_element': self.root_element,
'contents': contents }
jinja2env = jinja2.Environment(
loader=jinja2.FileSystemLoader(sphinx_app.env.srcdir),
trim_blocks=True)
try:
t = jinja2env.get_template(self.template_filename)
t.render(data=data)
except:
sys.stderr.write(
"DocBookBuilder -- Jinja2 couldn't load template at: %s" %
full_template_path)
sys.exit(1)
return t.render(data=data)
def get_target_uri(self, docname, typ=None):
return './%s.xml' % docname
def prepare_writing(self, docnames):
self.root_element = sphinx_app.config.docbook_default_root_element
self.template_filename = sphinx_app.config.docbook_template_file
def write_doc(self, docname, doctree):
# If there's an output filename, use its basename as the root
# element's ID.
#(path, filename) = os.path.split(self.output_filename)
#(doc_id, ext) = os.path.splitext(filename)
docutils_writer = DocBookWriter(self.root_element, docname,
output_xml_header=(self.template_filename == None))
# get the docbook output.
docbook_contents = publish_from_doctree(doctree,
writer=docutils_writer)
# process the output with a template if a template name was supplied.
if self.template_filename != None:
docbook_contents = self.process_with_template(docbook_contents)
output_file = open(os.path.join(self.outdir, '%s.xml' % docname), 'w+')
output_file.write(docbook_contents)
def setup(app):
global sphinx_app
sphinx_app = app
app.add_config_value('docbook_default_root_element', 'section', 'env')
app.add_config_value('docbook_template_file', None, 'env')
app.add_builder(DocBookBuilder)
| true |
0f8e58a20bbcf0fcb8867b1ea5c2df70b381a7a6 | Python | pvineet/birds | /download_images.py | UTF-8 | 4,046 | 2.515625 | 3 | [] | no_license | import os, csv
import urllib
num_lines = 0
def write_image_csv(csv_file, image_url, image_file):
with open(csv_file, 'a') as csvfile:
fieldnames = ['image_url', 'image_file']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not image_url == '':
urllib.urlretrieve(image_url,image_file)
writer.writerow({'image_url':image_url, 'image_file':image_file})
current_path = os.getcwd()
image_db_path = current_path+"/image_db"
print "image_db dir exists - %s" % (os.path.isdir(image_db_path))
#cd to images_db
os.chdir(image_db_path)
#open groups.csv
with open('groups.csv', 'rb') as groups_csvfile:
GroupsDictReader = csv.reader(groups_csvfile)
next(GroupsDictReader)
next(GroupsDictReader)
next(GroupsDictReader)
next(GroupsDictReader)
next(GroupsDictReader)
next(GroupsDictReader)
next(GroupsDictReader)
next(GroupsDictReader)
next(GroupsDictReader)
next(GroupsDictReader)
next(GroupsDictReader)
for row in GroupsDictReader:
print row
#enter the spefic group dir
curr_grp_name = row[0].lower()
os.chdir(image_db_path+"/"+curr_grp_name)
with open(curr_grp_name+".csv",'rb') as curr_grp_csvfile:
CurrGrpDictReader = csv.reader(curr_grp_csvfile)
next(CurrGrpDictReader)
for grp_row in CurrGrpDictReader:
curr_family_name = grp_row[0].lower()
#enter family dir
print "Current family %s" % curr_family_name
#print os.getcwd()
os.chdir(os.getcwd()+"/"+curr_family_name)
with open(curr_family_name+".csv", 'rb') as curr_family_csvfile:
CurrFamilyDictReader = csv.reader(curr_family_csvfile)
next(CurrFamilyDictReader)
for family_row in CurrFamilyDictReader:
curr_specie_name = family_row[3].lower().replace(" ","_")
print curr_specie_name
#enter specie dir
os.chdir(os.getcwd()+"/"+curr_specie_name)
if not os.path.exists(curr_specie_name+"_images.csv"):
with open(curr_specie_name+"_images.csv",'wb') as curr_specie_img_csvfile:
fieldnames = ['image_url', 'image_file']
writer = csv.DictWriter(curr_specie_img_csvfile, fieldnames=fieldnames)
writer.writeheader()
else:
with open(curr_specie_name+"_images.csv",'rb') as curr_specie_img_csvfile:
ImagesDictReader = csv.reader(curr_specie_img_csvfile)
num_lines = sum(1 for row in ImagesDictReader)
print "Already downladed images for %s = %d" % (curr_specie_name, num_lines)
with open(curr_specie_name+".csv", 'rb') as curr_specie_csvfile:
CurrSpecieDictReader = csv.reader(curr_specie_csvfile)
count = 0
for i in range(0,num_lines):
next(CurrSpecieDictReader)
count = count+1
print count
for specie_row in CurrSpecieDictReader:
print specie_row
image_file = os.getcwd()+"/"+str(count)+".jpg"
write_image_csv(curr_specie_name+"_images.csv", specie_row[1], image_file)
count = count+1
#exit specie dir
os.chdir("../")
#print os.getcwd()
#exit family dir
os.chdir("../")
print os.getcwd()
#open species csv
#enter specie dir
#if image download csv does not exist create it
#else download image and append the csv
| true |
48fcb9762d0d4b171db4f6382628364effb88c4c | Python | devcre/Python_Review | /day05/MiniSudok.py | UTF-8 | 6,497 | 3.546875 | 4 | [] | no_license | # 미니 수독은 수독과 똑같은 요령으로 숫자를 채워넣는 퍼즐이나
# 가로 4칸, 세로 4칸의 정사각형 보드에 1부터 4까지 채워넣는 것만 다르다.
## 규칙 ##
# 퍼즐보드에 숫자를 채우는 규칙은 수독과 동일하게 같은 줄에 숫자가 겹치지 않아야 하고,
# 2x2 크기로 4등분 한 작은 격자 내부에도 숫자가 겹치지 않아야 한다.
## 개발 요구사항 ##
# 퍼즐을 표준 입출력 창에서 인터액티브하게 진행하도록 한다.
# 빈칸이 많을 수록 퍼즐 풀기가 어려워진다. 따라서 난이도를 다음 중에서
# 사용자가 선택하도록 한다.
# 하: 숫자를 10개 채워준다. 중: 숫자를 8개 채워준다. 빈칸 8개 상: 숫자를 6개 채워준다. 빈칸 10개
# 퍼즐게임을 사작하면서 상 또는 중 또는 하 세가지 난이도 중에서 하나를 선택하여 입력하도록 한다.
# "난이도 (상,중,하) 중에서 하나 선택하여 입력: "
# 보드는 아래와 같이 그린다.
# + 1 2 3 4
# 1 4 3 . .
# 2 . 1 . 4
# 3 . . . .
# 4 . . 4 3
# 빈칸은 점으로 표시한다.
# 가로와 세로 줄번호는 각각 1, 2, 3, 4로 번호를 매겨서 왼쪽과 위쪽에 각각 표시한다.
# 사용자는 가로줄번호, 세로줄번호, 숫자를 차례로 다음 순으로 입력한다.
# 가로줄번호(1~4): 2
# 세로줄번호(1~4): 1
# 숫자(1~4): 2
#위치와 숫자가 모두 맞으면 빈칸을 입력한 숫자로 채우고 갱신된 퍼즐보드를 보여준다.
# 빈칸이 아닌 위치를 입력한 경우 숫자를 입력받기 전에 "빈칸이 아닙니다." 라는 메시지를 보여주면서
# 다시 처음부터 입력받는다.
# 빈칸이지만 틀린 숫자를 입력할 경우 그 숫자를 보여주며 "2가 아닙니다. 다시 해보세요." 라는
# 메시지를 보여주면서 줄 번호부터 다시 입력받는다.
# 사용자 입력은 모두 입력확인하여 부적절한 입력의 경우 재입력 받도록 해야한다.
# 빈칸이 다 채워지면 "잘 하셨습니다. 또 들리세요." 라는 메시지를 보여주면서 프로그램을 종료한다.
import random
def sudokmini():
solution = create_solution_board()
no_of_holes = get_level() # number of holes
puzzle = copy_board(solution)
(puzzle,holeset) = make_holes(puzzle,no_of_holes)
show_board(puzzle)
while True:
i = get_integer("가로줄번호(1~4): ",1,4)-1
j = get_integer("세로줄번호(1~4): ",1,4)-1
if (i,j) not in holeset:
print('빈칸이 아닙니다.')
continue # while 루프의 처음으로
n = get_integer("숫자 (1~4): ",1,4)
sol = solution[i][j]
if n == sol:
puzzle[i][j] = sol
show_board(puzzle)
holeset.remove((i,j))
no_of_holes -= 1
else:
print(n, "가 아닙니다. 다시 해보세요.")
if no_of_holes == 0:
print("잘 하셨습니다. 또 들리세요.")
break
# 무작위로 퍼즐 정답보드를 만들어 내준다. solution 변수에 저장
def create_solution_board():
board = create_board()
board = shuffle_ribbons(board)
board = transpose(board)
board = shuffle_ribbons(board)
board = transpose(board)
return board
def create_board():
seed = [1, 2, 3, 4]
random.shuffle(seed)
row0 = seed[:]
row1 = seed[2:] + seed[:2]
row2 = seed[1:2] + seed[0:1] + seed[3:4] + seed[2:3]
row3 = row2[2:] + row2[:2]
return [row0, row1, row2, row3]
# 가로줄을 두 줄씩 무작위로 바꾸는 함수
def shuffle_ribbons(board):
top = board[:2]
bottom = board[2:]
random.shuffle(top)
random.shuffle(bottom)
return top + bottom
# 보드를 인수로 받아 가로와 세로를 바꾸어 내주는 함수
# (0,1) -> (1,0), (0,2) -> (2,0)
def transpose(board):
transposed = []
for i in range(len(board)):
transposed.append([])
for a in range(0,4):
for z in range(0,4):
transposed[z].append(board[a][z])
return transposed
# 사용자에게서 입력받은 난이도에 따라 빈칸의 개수를 정한다. 빈칸의 개수는 no_of_holes에 저장
def get_level():
level = input("난이도 (상,중,하) 중에서 하나 선택하여 입력 : ")
while level not in {'상','중','하'} :
level = input("난이도 (상,중,하) 중에서 하나 선택하여 입력 : ")
if level == '상':
return 10
elif level == '중':
return 8
else:
return 6
# 퍼즐보드를 만들기 위해 solution과 똑같은 보드를 하나 복사하여 puzzle에 저장
def copy_board(board):
board_clone = []
for row in board:
row_clone = row[:]
board_clone.append(row_clone)
return board_clone
# puzzle과 no_of_holes(빈칸의 개수)를 인수를 받아서 퍼즐의 빈칸을 만든다.
# no_of_holes만큼 퍼즐보드의 빈칸의 개수를 만드는 함수
# 빈칸의 선택은 무작위로 하고, 빈칸은 0으로 채운다.
# 무작위로 빈칸을 넣은 퍼즐보드와 빈칸의 좌표 집합을 내준다.
def make_holes(board, no_of_holes):
holeset = set()
while no_of_holes > 0:
i = random.randint(0,3)
j = random.randint(0,3)
if int(board[i][j]) == 0:
continue
else:
board[i][j] = 0
holeset.add((i,j))
no_of_holes -= 1
return (board, holeset)
# 입력받은 퍼즐보드를 보여준다.
# 왼쪽에는 가로줄 번호를 1~4으로 붙이고 위쪽에는 세로줄 번호를 1~~4으로 붙인다.
# 퍼즐보드에서 0값을 가지고 있는 빈칸은 '.'으로 표시한다.
def show_board(board):
# 1번째 줄
for f in range(0,5):
if f == 0:
print('+ |', end=' ')
else:
print(str(f).rjust(2), end=' ')
print('\n----------------')
for i in range(1,5):
print(i, end=' ')
print('|', end=' ')
for j in range(0,4):
if int(board[i-1][j]) != 0:
print(str(board[i-1][j]).rjust(2), end=' ')
else:
print('.'.rjust(2), end=' ')
print('')
return 0
# 사용자로부터 수를 입력받아 내줌
def get_integer(comment, a, b):
integer = input(comment)
while integer not in {'1','2','3','4'}:
integer = input(comment)
return int(integer)
sudokmini() | true |
053a4325baf89ea2f908b96e6fe0bd220bcd6998 | Python | Bonen0209/Machine_Learning_Foundations | /HW1/8.py | UTF-8 | 1,530 | 2.8125 | 3 | [] | no_license | import argparse
import numpy as np
from concurrent.futures import ProcessPoolExecutor, as_completed
from helper import load_data, plot_hist
from perceptron_learning_algorithm import Perceptron_Learning_Algorithm
def main():
parser = argparse.ArgumentParser(description='Problem 8')
parser.add_argument('--train_file', default='./HW1/hw1_7_train.dat', help='path of train data')
parser.add_argument('--test_file', default='./HW1/hw1_7_test.dat', help='path of test data')
parser.add_argument('--repeat_times', default=1126, help='repeat times')
args = parser.parse_args()
X_train, Y_train = load_data(args.train_file)
X_test, Y_test = load_data(args.test_file)
PLA = Perceptron_Learning_Algorithm(X_train, Y_train)
total = 0
ws = []
errors = []
with ProcessPoolExecutor() as executor:
results = [executor.submit(PLA.run_train, False) for _ in range(args.repeat_times)]
for f in as_completed(results):
result = f.result()
ws.append(result)
with ProcessPoolExecutor() as executor:
results = [executor.submit(PLA.run_test, w, X_test, Y_test) for w in ws]
for f in as_completed(results):
result = f.result()
errors.append(result)
total = sum(errors)
avg = total / (args.repeat_times * X_test.shape[1])
print(avg)
errors = np.asarray(errors) / X_test.shape[0]
plot_hist(errors, 'Problem 8', 'error rate', 'frequency', 200)
if __name__ == '__main__':
main() | true |
8cafa0363f8f5c9e7425d1e31d9722f5897222b4 | Python | thiagofb84jp/python-exercises | /pythonCourseUdemu/algoritmosExercicios/basicos/exercicio26.py | UTF-8 | 318 | 4.03125 | 4 | [] | no_license | '''
26. Write a Python program to create a histogram from a
given list of integers
'''
def histogram(items):
for number in items:
output = ''
times = number
while (times > 0):
output += '*'
times -= 1
print(output)
histogram([2, 3, 6, 5, 10, 100])
| true |
8688a4e2f18118b9371bfa2ee8ce21dadddb975f | Python | FilipeAPrado/Python | /Paradigmas de linguagem em python/AulaDeClasses/account.py | UTF-8 | 637 | 3.734375 | 4 | [] | no_license | class Account:
def __init__(self, num):
self.num = num
self.balance = 0.0
def checkBalance(self):
return self.balance
def credit(self, value):
self.balance += value
def debit(self, value):
self.balance -= value
def transfer(self, account, value):
self.balance -= value
account.balance += value
# account1 = Account(1)
# account1.credit(10)
# account2 = Account(2)
# account2.credit(5)
# print(account1.checkBalance())
# print(account2.checkBalance())
# account1.transfer(account2,5)
# print(account1.checkBalance())
# print(account2.checkBalance())
| true |
568cd943de8a598b0391b5a2988d72544ceecd81 | Python | StefGalanis/Mixed-Search | /part2.py | UTF-8 | 5,843 | 3.09375 | 3 | [] | no_license | #Stefanos Galanis 2032
import sys
import time
import heapq
import numpy as np
def exportGridAsFile(grid,lenghtX,lengthY,minX,minY):
print(grid.shape)
exportedFile = open('gridFile.tsv','w')
header = '{}\t{}\n'.format(grid.shape[0],grid.shape[1])
exportedFile.write(header)
subHeader = '{}\t{}\t{}\t{}\n'.format(lenghtX,lengthY,minX,minY)
exportedFile.write(subHeader)
for i in range(grid.shape[0]):
for j in range(grid.shape[1]):
output = '{}\t{}\t{}\n'.format(i,j,grid[i][j])
exportedFile.write(output)
def spaSearchRaw(lowerX,upperX,lowerY,upperY):
restaurantFile = open('Restaurants_London_England.tsv')
numberOfResultsRaw = 0
resultList = []
startTime = time.time()
for line in restaurantFile:
lineValues = line.split('\t')
coordinates = lineValues[1]
coordinates = coordinates[9:len(coordinates)]
coordinates = coordinates.strip().split(',')
xCoordinate = float(coordinates[0])
yCoordinate = float(coordinates[1])
if xCoordinate >= lowerX and xCoordinate <= upperX and yCoordinate >= lowerY and yCoordinate <= upperY:
resultList.append(line.replace('\n',''))
numberOfResultsRaw += 1
endTime = time.time()
totalExecutionTime = endTime - startTime
print('spaSearchRaw: {} results, cost = {} seconds'.format(numberOfResultsRaw,totalExecutionTime))
for item in resultList:
print(item)
print('spaSearchRaw: {} results, cost = {} seconds'.format(numberOfResultsRaw,totalExecutionTime))
xCoordinateList = []
yCoordinateList = []
restaurantFile = open('Restaurants_London_England.tsv')
restaurantsList = []
for line in restaurantFile:
restaurantsList.append(line)
lineValues = line.split('\t')
coordinates = lineValues[1]
coordinates = coordinates[9:len(coordinates)]
coordinates = coordinates.strip().split(',')
#print(coordinates)
xCoordinateList.append(float(coordinates[0]))
yCoordinateList.append(float(coordinates[1]))
restaurantFile.close()
xCoordinateList.sort()
yCoordinateList.sort()
minX = xCoordinateList[0]
minY = yCoordinateList[0]
maxX = xCoordinateList[-1]
maxY = yCoordinateList[-1]
print('max X :{} min X :{} max Y :{} min Y :{} '.format(maxX,minX,maxY,minY))
print('bounds: {} {} {} {} '.format(maxX,minX,maxY,minY))
lenghtX = maxX - minX
lengthY = maxY - minY
print('widths: {} {}'.format(lenghtX,lengthY))
fragSizeX = lenghtX / 50
fragSizeY = lengthY / 50
print('fragment size on x(axis): {} fragment size on y(axis): {}'.format(fragSizeX,fragSizeY))
border1 = minX
border2 = minX
for i in range(0,50):
if i == 0 :
pass
else:
border1 += fragSizeX
border2 += fragSizeX
print('{} {}-{}'.format(i,border1,border2))
grid = np.empty(shape=(50,50),dtype=object)
numberOfLine = 0
restaurantFile = open('Restaurants_London_England.tsv')
for line in restaurantFile:
lineValues = line.split('\t')
coordinates = lineValues[1]
coordinates = coordinates[9:len(coordinates)]
coordinates = coordinates.strip().split(',')
locationX = float(coordinates[0])
locationY = float(coordinates[1])
distX = locationX - minX
distY = locationY - minY
distXinBlocks = int(distX/fragSizeX)
distYinBlocks = int(distY/fragSizeY)
if distXinBlocks == 50 :
distXinBlocks -= 1
if distYinBlocks == 50 :
distYinBlocks -= 1
if grid[distXinBlocks][distYinBlocks] == None:
grid[distXinBlocks][distYinBlocks] = [numberOfLine]
else:
grid[distXinBlocks][distYinBlocks].append(numberOfLine)
numberOfLine += 1
numberOfNonEmptyBlocks = 0
for i in range(0,50):
for j in range(0,50):
if grid[i][j] != None:
numberOfNonEmptyBlocks += 1
print('block[{}][{}]:{}'.format(i,j,len(grid[i][j])))#arithmo thelei
lowerX = float(sys.argv[1])
upperX = float(sys.argv[2])
lowerY = float(sys.argv[3])
upperY = float(sys.argv[4])
lowerBoundX = float(sys.argv[1]) - minX
upperBoundX = float(sys.argv[2]) - minX
lowerBoundY = float(sys.argv[3]) - minY
upperBoundY = float(sys.argv[4]) - minY
upperBoundX = int(upperBoundX/fragSizeX)
lowerBoundX = int(lowerBoundX/fragSizeX)
upperBoundY = int(upperBoundY/fragSizeY)
lowerBoundY = int(lowerBoundY/fragSizeY)
if upperBoundX == 50:
upperBoundX -= 1
if lowerBoundX == 50:
lowerBoundX -= 1
if upperBoundY == 50:
upperBoundY -= 1
if lowerBoundY == 50:
lowerBoundY -= 1
startTime = time.time()
restaurantsToRetrieve = []
additive = 0
print(lowerBoundX,upperBoundX,lowerBoundY,upperBoundY)
counter = 0
for i in range(lowerBoundX,upperBoundX+1):
for j in range(lowerBoundY,upperBoundY+1):
print(i,j)
if grid[i][j] != None:
restaurants = grid[i][j]
additive += len(restaurants)
for restaurantID in restaurants:
restaurantsToRetrieve.append(int(restaurantID))
resultListGrid = []
numberOfResultsGrid = 0
for restaurant in restaurantsToRetrieve:
line = restaurantsList[restaurant]
lineValues = line.split('\t')
coordinates = lineValues[1]
coordinates = coordinates[9:len(coordinates)]
coordinates = coordinates.strip().split(',')
xCoordinate = float(coordinates[0])
yCoordinate = float(coordinates[1])
if xCoordinate >= lowerX and xCoordinate <= upperX and yCoordinate >= lowerY and yCoordinate <= upperY:
resultListGrid.append(line.replace('\n',''))
endTime = time.time()
totalExecutionTime = endTime-startTime
spaSearchRaw(lowerX,upperX,lowerY,upperY)
print('spaSearchGrid: {} results, cost = {} seconds'.format(len(resultListGrid),float(totalExecutionTime)))
for restaurant in resultListGrid:
print(restaurant)
exportGridAsFile(grid,lenghtX,lengthY,minX,minY)
| true |
56cb213ffca915d0aa1a064dc4dbcb8085be2b25 | Python | msporkin/FASTLIFI | /Dated/Search.py | UTF-8 | 6,071 | 2.890625 | 3 | [] | no_license | #ECEN 404 - Michael Sporkin
#Imports custom libraries and threading
from CameraLibrary import *
from MotorLibrary import *
import threading
#initialize search variables
ledLit = False
offsetAngles = np.array([0,0,0])
global targetFound
targetFound = False
global sweeping
sweeping = True
statPi = StatPi() #initializes stationary pi class with GPIO designations
#sweep function - turns module a full 180 degrees
def sweep(ap1, an1, bp1, bn1, delay):
global targetFound
sequences = 0
while targetFound == False and sequences < 7000:
oneQuickRightTurn(ap1, an1, bp1, bn1, delay)
sequences = sequences + 1
if targetFound == True:
print('Hexagon spotted.')
global center #center of the hexagon
while abs(centerFrame[0]-center[0])>40 and sequences < 7000:
oneQuickRightTurn(ap1, an1, bp1, bn1, delay)
sequences = sequences + 1
global sweeping
sweeping = False
return
if targetFound == False:
print('Full 180 degree sweep. Target not found.')
return
#begins full sweep
threading.Thread(target=sweep, args = [statPi.ap1, statPi.an1,
statPi.bp1, statPi.bn1, delayS]).start()
printpos(offsetAngles)
while ledLit == False:
#read frame
ret, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) #converts BRG -> HSV image
mask = cv2.inRange(hsv, lb, ub) #masks all colors other than ideal green
#smooths image - chosen over Gaussian Blur for sharpness
#mask = cv2.bilateralFilter(mask, 3, 60,60, borderType=cv2.BORDER_REFLECT)
# Converting image to a binary image
_,threshold = cv2.threshold(mask, 3, 255, cv2.THRESH_BINARY)
#Set up detector to detect shapes with same colors
detector, _ = cv2.findContours(threshold, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# Searching through every region selected to find the required polygon.
for cnt in detector :
area = cv2.contourArea(cnt)
# Shortlisting the regions based on area.
if area > 120:
approx = cv2.approxPolyDP(cnt, 0.03 * cv2.arcLength(cnt, True), True)
# Checking if the no. of sides of the selected region is 7.
if (len(approx) == 6):
offsetAngles, center = hex_position(frame, cnt, approx)
targetFound = True
#tiltInfo = tilt(approx)
cv2.putText(frame, str(offsetAngles),(100,500),font,1,(0,0,0),2)
#cv2.putText(frame, tiltInfo,(100,550),font,1,(0,0,0),2)
# Showing the image along with outlined arrow.
cv2.imshow('Room Scan', cv2.resize(frame, (960,540)))
if sweeping == False:
print('Sweep complete. Beginning alignment.')
printpos(offsetAngles)
cv2.destroyWindow('Room Scan')
#Calibrate Motors
Calibrate(statPi.ap1, statPi.an1, statPi.bp1, statPi.bn1, statPi.ap2, statPi.an2,
statPi.bp2, statPi.bn2, delayC)
print('Calibration complete')
#Calculate new offset after calibration and align
#read frame
ret, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) #converts BRG -> HSV image
mask = cv2.inRange(hsv, lb, ub) #masks all colors other than ideal green
# Converting image to a binary image
_,threshold = cv2.threshold(mask, 3, 255, cv2.THRESH_BINARY)
#Set up detector to detect shapes with same colors
detector, _ = cv2.findContours(threshold, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# Searching through every region selected to find the required polygon.
for cnt in detector :
area = cv2.contourArea(cnt)
# Shortlisting the regions based on area.
if area > 120:
approx = cv2.approxPolyDP(cnt, 0.03 * cv2.arcLength(cnt, True), True)
# Checking if the no. of sides of the selected region is 7.
if (len(approx) == 6):
targetFound = True
offsetAngles, center = hex_position(frame, cnt, approx)
printpos(offsetAngles)
Align(offsetAngles, statPi.ap1, statPi.an1, statPi.bp1, statPi.bn1, statPi.ap2,
statPi.an2, statPi.bp2, statPi.bn2)
#Calculate and show new offset to confirm alignment
while (True):
#read frame
ret, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) #converts BRG -> HSV image
mask = cv2.inRange(hsv, lb, ub) #masks all colors other than ideal green
# Converting image to a binary image
_,threshold = cv2.threshold(mask, 3, 255, cv2.THRESH_BINARY)
#Set up detector to detect shapes with same colors
detector, _ = cv2.findContours(threshold, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# Searching through every region selected to find the required polygon.
for cnt in detector :
area = cv2.contourArea(cnt)
# Shortlisting the regions based on area.
if area > 120:
approx = cv2.approxPolyDP(cnt, 0.03 * cv2.arcLength(cnt, True), True)
# Checking if the no. of sides of the selected region is 7.
if (len(approx) == 6):
targetFound = True
offsetAngles, center = hex_position(frame, cnt, approx)
cv2.putText(frame, str(offsetAngles),(100,500),font,1,(0,0,0),2)
cv2.imshow('Target Aligned', cv2.resize(frame, (960,540)))
#leave the loop if triggered
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#leave the loop if triggered
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#Shuts it down
cap.release()
cv2.destroyAllWindows
| true |
29a28ab6c78b87cd56bfce477cf31400e9445c89 | Python | elOXXO/Tarea_03 | /Rendimientodeautos.py | UTF-8 | 2,859 | 4.03125 | 4 | [] | no_license | #Encoding: UTF-8
#Autor: Alberto López Reyes
'''Descripción: Este programa calcula e imprime el rendimiento de un auto en km/l, mi/l, y la cantidad de litros necesarios
al ser otorgado los km recorridos, los litros usados, y los km a recorrer.'''
#Se declaran las constantes universales, porque nunca deberían cambiar, de la conversión de litros a galones y
#km a millas.
fltLiTOGa = .264172051
fltKmTOMi = (1/1.609344)
#Esta función calcula el rendimiento del auto en km/l al recibir los km recorridos y litros usados.
def calcularRendimientoKmL(fltKmRecorridos, fltLitrosUsados):
fltRendimientoKmL = fltKmRecorridos / fltLitrosUsados
return fltRendimientoKmL
#Esta función calcula el rendimiento del auto en mi/l al recibir y multiplicar por sus conversiones respectivamente
#los km recorridos y litros usados.
def calcularRendimientoMiL(fltKmRecorridos, fltLitrosUsados):
global fltLiTOGa, fltKmTOMi
fltRendimientoMiL = (fltKmRecorridos * fltKmTOMi) / (fltLitrosUsados * fltLiTOGa)
return fltRendimientoMiL
#Esta función calcula los litros que se deben usar para recorrer los km a recorrer recibiendo esta cantidad junto
#los km recorridos y los litros usados previamente.
def calcularKilometrosARecorrer(fltKmRecorridos, fltLitrosUsados, fltKmRecorrer):
fltLiARecorrer = fltKmRecorrer * fltLitrosUsados / fltKmRecorridos
return fltLiARecorrer
#Esta función principal recibe los km recorridos, litros usados, y km a recorrer de un auto para otorgárselos a las
#funciones "calcularRendimientoKmL", "calcularRendimientoMiL", y "calcularKilometrosARecorrer". Estas tres funciones
#devolverán el rendimiento en km/l, el rendimiento en mi/l, y los litros que se necesitan respectivamente. Estas tres
#magnitudes después serán impresas.
def main():
strKmRecorridos = input("Teclea el número de km recorridos: ")
fltKmRecorridos = float(strKmRecorridos)
strLitrosUsados = input("Teclea el número de litros de gasolina usados: ")
fltLitrosUsados = float(strLitrosUsados)
fltRendimientoKmL = calcularRendimientoKmL(fltKmRecorridos, fltLitrosUsados)
fltRendimientoMiL = calcularRendimientoMiL(fltKmRecorridos, fltLitrosUsados)
print("""""")
print("Si recorres "+strKmRecorridos+" kms con "+strLitrosUsados+" litros de gasolina, el redimiento es: ")
print(format(fltRendimientoKmL, '.2f')+" km/l")
print(format(fltRendimientoMiL, '.2f')+" mi/gal")
print("""""")
strKmRecorrer = input("¿Cuántos kilómetros vas a recorrer? ")
fltKmRecorrer = float(strKmRecorrer)
fltLiARecorrer = calcularKilometrosARecorrer(fltKmRecorridos, fltLitrosUsados, fltKmRecorrer)
print("""""")
print("Para recorrer "+strKmRecorrer+" km. necesitas "+format(fltLiARecorrer, '.2f')+" litros de gasolina")
#Se acciona la función "main".
main()
| true |
86c8431473e7b9bf443f5adf4682e9e07ec4650e | Python | jvSanches/PI-7 | /Python_sender/GCode_parser.py | UTF-8 | 1,187 | 3.484375 | 3 | [] | no_license | """
Interpretador de Gcode simplificado
"""
import re
last_x = 2048
last_y = 2048
last_z = 1
# Quebra um programa em uma lista de strings
def refine(prog):
refined_prog = []
prog = prog.split("\n")
for line in prog:
no_comments = re.sub(r'\([^()]*\)', '', line).upper()
refined_prog.append(no_comments.split())
return refined_prog
# Obtém coordenadas a partir do GCode
def parse(prog):
global last_x
global last_y
global last_z
prog = refine(prog)
coords = []
for line in prog:
x = None
y = None
z = None
for instruction in line:
func = instruction[0]
value = int(float(instruction[1:])*10)
if func == 'M' and value == 30:
return coords
if func == 'X':
x = value + 2048
if func == 'Y':
y = value + 2048
if func == 'Z':
z = value
if x == None:
x = last_x
if y == None:
y = last_y
if z == None:
z = last_z
last_x, last_y, last_z = x, y, z
coords.append([x,y,z])
return coords
| true |
125882b86b5673235daed8200ef6913cba23b320 | Python | GucciGerm/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/5-filter_cities.py | UTF-8 | 753 | 3.125 | 3 | [] | no_license | #!/usr/bin/python3
"""
This script will take the name of a state as an argument
and we will list all the cities within that state with database hbtn_0e_4_usa
4 arguments passed:
- A MySQL username
- A MySQL password
- A database name
- A state name
"""
import MySQLdb
from sys import argv
if __name__ == "__main__":
database = MySQLdb.connect(user=argv[1], passwd=argv[2], db=argv[3])
cur = database.cursor()
cur.execute("SELECT cities.id, cities.name, states.name \
FROM cities INNER JOIN states ON cities.state_id = states.id WHERE\
states.name = %s ORDER BY cities.id ASC", (argv[4], ))
list = []
for row in cur.fetchall():
list.append(row[1])
print(", ".join(list))
cur.close()
database.close()
| true |
a691cc2da5f167e3f00ea37deab52820a6950182 | Python | edbeeching/AA_LCS_Project | /code_production/runtime_comparisons.py | UTF-8 | 1,289 | 3.140625 | 3 | [] | no_license | from __future__ import print_function
import random
import string
import time
import lcs_branch_and_bound
import lcs_recursive
def generate_random_list(length):
words = [None]*length
for i in range(length):
words[i] = (random.choice(string.ascii_uppercase))
return words
if __name__ == '__main__':
print("Runtime comparisons")
start = time.time()
print("hello")
end = time.time()
print(end - start)
time_dict_rec = {}
for i in range(0, 14):
time_dict_rec[i] = 0
for _ in range(0, 40):
list1 = generate_random_list(i)
list2 = generate_random_list(i)
start = time.time()
lcs = lcs_recursive.lcs_recursive(list1, list2)
time_dict_rec[i] += time.time() - start
for i in range(0, 14):
print(i, time_dict_rec.get(i))
time_dict = {}
print("-----------------------")
for i in range(0, 40):
time_dict[i] = 0
for _ in range(0, 40):
list1 = generate_random_list(i)
list2 = generate_random_list(i)
start = time.time()
lcs_branch_and_bound.branch_n_bound(list1, list2)
time_dict[i] += time.time() - start
for i in range(0, 40):
print(i, time_dict.get(i))
| true |
7966be684ab2d44bde1f3829a16e65ddfb25a102 | Python | bassem-debug/behave-training-ci | /features/steps/search_steps.py | UTF-8 | 683 | 2.609375 | 3 | [] | no_license | import time
from behave import then,given,when
from numpy.testing import assert_equal
from selenium import webdriver
from selenium.webdriver import ActionChains
@given(u'the user navigates to the PyPi Home page')
def step_impl(context):
context.browser.get("https://qavbox.github.io/demo/dragndrop/")
assert "DragnDrop" in context.browser.title
@when(u'he search for "behave"')
def step_impl(context):
time.sleep(2)
context.hp.drag_and_dop()
time.sleep(2)
@then(u'he see a search result "behave 1.2.5"')
def step_impl(context):
time.sleep(2)
print(context.hp.return_target_message())
assert_equal("Dropped!",context.hp.return_target_message())
| true |
6a19e801df9115814b7bbaf2cc2e53e7dc316276 | Python | JensPfeifle/adventofcode-2018 | /day11_chronalcharge.py | UTF-8 | 3,972 | 2.796875 | 3 | [] | no_license | import numpy as np
from numba import jit
from typing import Dict
def powerlevels(serial_number):
grid = np.zeros([300, 300], dtype=int)
for i in range(grid.shape[0]):
for j in range(grid.shape[1]):
rack_id = i + 10
power = rack_id * j
power = power + serial_number
power = power * rack_id
if len(str(power)) > 3:
power = int(str(power)[-3])
else:
power = 0
power -= 5
grid[i, j] = power
return grid
squares = {}
@jit(nopython=True, parallel=True)
def para_incr_sum(power_levels, prev_sum: int, size: int, row: int, col: int):
sum_power = prev_sum
i = row
j = col
for k in range(col, col+size):
sum_power += power_levels[k, col + size-1]
for l in range(row, row + size):
sum_power += power_levels[row+size-1, l]
return sum_power
@jit(nopython=True, parallel=True)
def para_sum_squares(power_levels, size=3):
sums = [] # square sums for this power level
for i in range(0, power_levels.shape[0] - size+1):
for j in range(0, power_levels.shape[1] - size+1):
sum_power = 0
for k in range(i, i+size):
for l in range(j, j+size):
sum_power += power_levels[k, l]
sums.append(sum_power)
return sums
def cached_para_sum_squares(power_levels, size):
print("size = {}".format(size))
for i in range(0, power_levels.shape[0] - size+1):
for j in range(0, power_levels.shape[1] - size+1):
if (i, j, size-1) in squares.keys():
# print("{},{} size {} found".format(i, j, size-1))
prev_sum = squares[(i, j, size-1)]
squares[(i, j, size)] = para_incr_sum(
power_levels, prev_sum, size, i, j)
else:
# print("{},{} size {} not found".format(i, j, size-1))
sum_power = 0
for k in range(i, i+size):
for l in range(j, j+size):
# print("+grid[{},{}]".format(k,l))
sum_power += power_levels[k, l]
squares[(i, j, size)] = sum_power
def sum_squares(power_levels, size=3):
print("size = {}".format(size))
for i in range(0, power_levels.shape[0] - size+1):
for j in range(0, power_levels.shape[1] - size+1):
if (i, j, size-1) in squares.keys():
# print("{},{} size {} found".format(i, j, size-1))
sum_power = (squares[(i, j, size-1)]
+ sum(power_levels[i+size-1, j:j+size])
+ sum(power_levels[i:i+size - 1, j + size-1]))
squares[(i, j, size)] = sum_power
else:
# print("{},{} size {} not found".format(i, j, size-1))
sum_power = 0
for k in range(i, i+size):
for l in range(j, j+size):
# print("+grid[{},{}]".format(k,l))
sum_power += power_levels[k, l]
squares[(i, j, size)] = sum_power
assert powerlevels(57)[122, 79] == -5.0
assert powerlevels(39)[217, 196] == 0.0
assert powerlevels(71)[101, 153] == 4.0
def maxpower(sqs):
return max([(sq, pw) for sq, pw in sqs.items()], key=lambda x: x[1])
##############
# Tests
##############
# squares = {}
# for s in range(1, 20):
# sum_squares(powerlevels(18), size=s)
# print(maxpower(squares)) # should be 90,269,16 with power 113
# squares = {}
# for s in range(1, 20):
# sum_squares(powerlevels(42), size=s)
# print(maxpower(squares)) # should be 232,251,12 with power 119
print("Part1")
squares = {}
sum_squares(powerlevels(3214), size=3)
print(maxpower(squares))
print("Part2")
for s in range(1, 300):
cached_para_sum_squares(powerlevels(3214), size=s)
print(maxpower(squares)) # should be 232,251,12 with power 119 | true |
4eaa54e568ad94dc39eef6acbe2945d78879034a | Python | yfhd/python_practice | /python2/tuples.py | UTF-8 | 165 | 3.078125 | 3 | [] | no_license | #!/usr/bin/python
tup = ('physics', 'chemistry', 1997, 2000)
print tup
del tup
print "After deleting tup: "
try:
print tup
except Exception as e:
print e
| true |
f8636209b2307cc73fb9a154efc945af2b7a302a | Python | HoChangSUNG/sparta_algorithm | /week_1/05_find_max_plus_or_multiple.py | UTF-8 | 322 | 3.5 | 4 | [] | no_license | input = [1, 3, 5, 6, 1, 2, 4]
def find_max_plus_or_multiply(array):
multiply_sum = 0
for number in array :
if number<=1 or multiply_sum <= 1 :
multiply_sum+=number
else :
multiply_sum*=number
return multiply_sum
result = find_max_plus_or_multiply(input)
print(result)
| true |
b0480f028394d501eb5e8d003632c464bf5a810b | Python | lebm/coursera-interactive-python-1 | /rspls/rspls.py | UTF-8 | 1,356 | 4.09375 | 4 | [] | no_license | import random
# dicts to simplify name_to_number and number_to_name
name_number = {"rock": 0, "Spock": 1, "paper": 2, "lizard": 3, "scissors": 4}
number_name = {0: "rock", 1: "Spock", 2: "paper", 3: "lizard", 4: "scissors"}
def name_to_number(name):
""" Maps name to its number
Well, I am not sure if we was supposed to use if/elif/else here,
so I decided to user dicts, it makes the code so much simpler
"""
return name_number[name]
def number_to_name(number):
""" Maps number to its name. See name_to_number comments above
"""
return number_name[number]
def rpsls(player_choice):
print
print "Player chooses " + player_choice
player_number = name_to_number(player_choice)
comp_number = random.randrange(0, 5)
comp_choice = number_to_name(comp_number)
print "Computer chooses " + comp_choice
comp2player_diff = (comp_number - player_number) % 5
if (comp2player_diff == 0):
print "Player and computer tie!"
elif ((comp2player_diff == 1) or (comp2player_diff == 2)):
print "Computer wins!"
else:
print "Player wins!"
# test your code - THESE CALLS MUST BE PRESENT IN YOUR SUBMITTED CODE
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
# always remember to check your completed program against the grading rubric
| true |
3d927274b8aae20174f8578545f03c7488ecfaa7 | Python | ahmedhamza47/Projects_for_Beginner | /password generator pro.py | UTF-8 | 808 | 3.484375 | 3 | [] | no_license | import random as rd
import secrets
import string
def password_gen(pass_length):
pass_source = string.ascii_letters + string.digits + string.punctuation
password = secrets.choice(string.ascii_lowercase)
password += secrets.choice(string.ascii_uppercase)
password += secrets.choice(string.digits)
password += secrets.choice(string.punctuation)
for i in range(0, pass_length-4):
password += secrets.choice(pass_source)
pass_list = list(password)
secrets.SystemRandom().choice(pass_list)
password = ''.join(pass_list)
return password
length = int(input('How long would you like your password to be:'))
# digit = int(input('Enter the number of digits you would like:'))
# alph = input('Enter the number of alphabet:')
pas = password_gen(length)
print(pas)
| true |
704fa10010d4628067e9a875369d5556b67b3149 | Python | meethu/LeetCode | /solutions/0141.linked-list-cycle/linked-list-cycle.py | UTF-8 | 1,006 | 3.78125 | 4 | [] | no_license | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hascycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
fast = slow = head
while fast and fast.next:
slow = slow.next # 每次走一步
fast = fast.next.next # 每次走两步
if slow == fast:
return True
return False
# 本质还是哈希法,只不过不需要额外空间
# def hasCycle(self, head):
# if not head:
# return False
# while head.next and head.val != None:
# head.val = None # 遍历的过程中将值置空
# head = head.next
# if not head.next: # 如果碰到空发现已经结束,则无环
# return False
# return True # 否则有环
head = [3, 2, 0, -4]
problems = Solution()
print(problems.hascycle(head))
| true |
bbc2a31f9f19f120bdeed806448f63262a4cae1e | Python | wasweisic/CryptoPredicted | /predictors/eval.py | UTF-8 | 4,737 | 2.734375 | 3 | [
"MIT"
] | permissive |
# evaluation function to determine accuracy
# many techniques were tried, including RMSE and similar; this one uses DTW algorithm.
# however this file should no longer be used, because it may no longer be compatible with the API.
# you can however refactor it if you wish to make it compatible again with our new data format and new API.
import json
import urllib.request
from datetime import datetime, timedelta
import sys
sys.path.insert(0, '/home/nevolin/public_html/cryptoproto/')
from mysettings import dtNow, createLogger
from collections import OrderedDict
from numpy import array, zeros, argmin, inf, equal, ndim
from scipy.spatial.distance import cdist
from sklearn.metrics.pairwise import manhattan_distances
def dtw(x, y, dist):
"""
Computes Dynamic Time Warping (DTW) of two sequences.
:param array x: N1*M array
:param array y: N2*M array
:param func dist: distance used as cost measure
Returns the minimum distance, the cost matrix, the accumulated cost matrix, and the wrap path.
"""
assert len(x)
assert len(y)
r, c = len(x), len(y)
D0 = zeros((r + 1, c + 1))
D0[0, 1:] = inf
D0[1:, 0] = inf
D1 = D0[1:, 1:] # view
for i in range(r):
for j in range(c):
D1[i, j] = dist(x[i], y[j])
C = D1.copy()
for i in range(r):
for j in range(c):
D1[i, j] += min(D0[i, j], D0[i, j+1], D0[i+1, j])
if len(x)==1:
path = zeros(len(y)), range(len(y))
elif len(y) == 1:
path = range(len(x)), zeros(len(x))
else:
path = _traceback(D0)
return D1[-1, -1] / sum(D1.shape), C, D1, path
def _traceback(D):
i, j = array(D.shape) - 2
p, q = [i], [j]
while ((i > 0) or (j > 0)):
tb = argmin((D[i, j], D[i, j+1], D[i+1, j]))
if (tb == 0):
i -= 1
j -= 1
elif (tb == 1):
i -= 1
else: # (tb == 2):
j -= 1
p.insert(0, i)
q.insert(0, j)
return array(p), array(q)
def eval(currentDateTime):
currentDateTime = currentDateTime.replace(minute=currentDateTime.minute-(currentDateTime.minute % interval))
currentDateTime_T = datetime.strftime(currentDateTime, '%Y-%m-%dT%H:%M')
print(str(currentDateTime_T))
url = "http://cryptopredicted.com/api.php?type=predictionChart3&coin="+coin+"&interval="+str(interval)+"&historymins=360¤tDateTime="+currentDateTime_T+"&featuresID=-1&batchsize=-1&neurons=-1&windowsize=-1&epochs=-1&hiddenlayers=-1&predicted_feature=price3"
print(url)
out = urllib.request.urlopen(url)
js = json.loads(out.read().decode(out.info().get_param('charset') or 'utf-8'), object_pairs_hook=OrderedDict)
arrA = list(js['history_extended'].values())[:8]
print(arrA)
buckets = {}
for uid, vals in js['predictions'].items():
it = 0
arrP = list(vals.values())[:8]
dist_fun = manhattan_distances
dist, cost, acc, path = dtw(arrA, arrP, dist_fun)
print(uid +"\t==>\t"+str(dist)) # the smaller the dist the better. dist==0 if both A and B are equal
if not uid in buckets: buckets[uid]=[]
buckets[uid].append(dist)
return buckets
import threading
class evalProcessor (threading.Thread):
def __init__(self, currentDateTime, evals):
threading.Thread.__init__(self)
self.currentDateTime = currentDateTime
self.evals = evals
def run(self):
bucket = eval(self.currentDateTime)
for uid, arr in bucket.items():
if uid not in self.evals:
self.evals[uid] = []
for a in arr:
self.evals[uid].append(a)
coin = "BTC"
interval=10
#currentDateTime = dtNow().replace(second=0,microsecond=0) - timedelta(minutes=interval*8)
dtstart = datetime.strptime('2018-02-20 00:00', '%Y-%m-%d %H:%M')
dtend = datetime.strptime('2018-02-28 23:50', '%Y-%m-%d %H:%M')
dtit = dtstart
evals = {}
threads = []
while(dtit <= dtend):
th = evalProcessor(dtit, evals)
th.start()
threads.append(th)
if len(threads) == 8:
for t in threads:
try:
t.join(timeout=30) # 30 sec per article
except Exception as ex:
print(ex)
threads=[]
dtit += timedelta(minutes=interval)
for t in threads:
try:
t.join(timeout=30) # 30 sec per article
except Exception as ex:
print(ex)
print("==================")
print("==================")
print(json.dumps(evals))
print("==================")
print("==================")
min_avg = None
min_uid = None
for uid, arr in evals.items():
avg = sum(arr)/len(arr)
print(uid +"\t==avg==>\t"+ str(avg))
if min_avg == None or avg < min_avg:
min_avg = avg
min_uid=uid
print("---")
print("min_avg = " + str(min_avg))
print("min_uid = " + min_uid)
| true |
17f97364d07b37219c50789650d14ffe11d23bee | Python | axeloh/hackerrank | /coin_change_problem.py | UTF-8 | 1,148 | 4.15625 | 4 | [] | no_license | """
Coin Change Problem from https://www.youtube.com/watch?v=HWW-jA6YjHk
"""
def num_coins(cents, coins):
num_coins = 0
# O(k)
for coin in coins:
num_coins += cents // coin
cents = cents % coin
if cents != 0:
return -1
return num_coins
def num_coins2(cents, coins):
# Solution that works also when missing coins
# For example not having nickels
# k: number of coins
# O(k^2)
# k + (k-1) + (k-2) + (k-3) = O(k^2)
min_coins = 1e8
for i in range(len(coins)-1):
c = cents
coins = coins[i:]
num_coins = 0
for coin in coins:
num_coins += c // coin
c = c % coin
if c != 0:
continue
if num_coins < min_coins:
min_coins = num_coins
if c != 0:
return -1
return min_coins
if __name__ == '__main__':
cents = 31
# quarter: 25, dime: 10, nickel: 5, pennies: 1
coins = [25, 10, 5, 1]
num_coins = num_coins(cents, coins)
print(f'Found min coins: {num_coins}')
print('-'*10)
num_coins = num_coins2(cents, coins)
print(f'Optimalnum_coins') | true |
57ebcd327ef932c7b79a38dc2086f70de3d26010 | Python | jonathanmarmor/jam | /jam/soxsynth.py | UTF-8 | 1,539 | 3.375 | 3 | [] | no_license | """A simple synthesizer for rhythmic unison parts using the sox utility.
install dependencies:
brew install sox
"""
import os
TEST_MUSIC = [
(0.16, ['Ab2', 'Ab4', 'B4', 'Eb4']),
(0.48, ['B2', 'B4', 'Eb4', 'Gb4']),
(0.16, ['B2', 'B4', 'Eb4', 'Gb4']),
(0.64, ['E2', 'E4', 'Ab4', 'B4']),
]
def play(music):
command = make_command(music)
print command
os.system(command)
def make_command(music):
"""
>>> make_command(TEST_MUSIC)
'play "| sox --volume 0.95 -n -p synth 0.16 pluck Ab2 pluck Ab4 pluck B4 pluck Eb4" "| sox --volume 0.95 -n -p synth 0.48 pluck B2 pluck B4 pluck Eb4 pluck Gb4" "| sox --volume 0.95 -n -p synth 0.16 pluck B2 pluck B4 pluck Eb4 pluck Gb4" "| sox --volume 0.95 -n -p synth 0.64 pluck E2 pluck E4 pluck Ab4 pluck B4";'
"""
note_commands = ' '.join(make_note_command(duration, pitches) for duration, pitches in music)
return 'play {};'.format(note_commands)
def make_note_command(duration, pitches, timbre='pluck'):
"""
>>> make_note_command(0.64, ['E2', 'E4', 'Ab4', 'B4'])
'"| sox --volume 0.95 -n -p synth 0.64 pluck E2 pluck E4 pluck Ab4 pluck B4"'
"""
pitch_format = '{timbre} {pitch}'
pitches_string = ' '.join(pitch_format.format(timbre=timbre, pitch=p) for p in pitches)
command = '"| sox --volume 0.95 -n -p synth {duration} {pitches_string}"'.format(
duration=duration,
pitches_string=pitches_string
)
return command
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
745a68090329048226a7521b675f3f10d44708ff | Python | offwhite/gerty | /face_recogniser.py | UTF-8 | 1,032 | 2.703125 | 3 | [] | no_license | import numpy as np
import os
class Recogniser:
def __init__(self, cv2, db):
self.cv2 = cv2
self.db = db
self.detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
self.recognizer = self.cv2.face.LBPHFaceRecognizer_create()
self.recognizer.read('trainer/trainer.yml')
def call(self, frame):
faces = []
grey = self.cv2.cvtColor(frame, self.cv2.COLOR_BGR2GRAY)
for (x, y, w, h) in self.detected_faces(grey):
self.cv2.rectangle(frame, (x-5, y-5), (x+w+5, y+h+5), (255, 255, 255), 1)
id, distance = self.recognizer.predict(grey[y:y+h,x:x+w])
confidence = format(round(100 - distance))
faces.append((x, y, w, h, id, confidence))
return faces
def detected_faces(self, grey):
return self.detector.detectMultiScale(
grey,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=self.cv2.CASCADE_SCALE_IMAGE
)
| true |
7ccdaaf03dda02c77434c1101105c1aeb3d80eb3 | Python | gehenriquez/MCOC2020-P1-2 | /Entrega 5/Entrega5.py | UTF-8 | 10,882 | 2.5625 | 3 | [] | no_license | import numpy as np
from scipy.integrate import odeint
from datetime import datetime
from leer_eof import leer_eof
from time import perf_counter
import matplotlib.pyplot as plt
t0 = perf_counter()
# Datos
hr = 3600
km = 1000
Radio = 6371*km
Mt = 5.972e24
G = 6.67408e-11
omega = -7.2921150e-5
HG = 700 * km
J2 = 1.75553e10 * (1000 ** 5) # km5⋅s−2
J3 = -2.61913e11 * (1000 ** 6) # km6⋅s−2
FgMax = G*Mt/Radio**2
zp = np.zeros(6)
def satelite(z, t):
c = np.cos(omega * t)
s = np.sin(omega * t)
R = np.array([[c, s, 0], [-s, c, 0], [0, 0, 1]])
Rp = omega * (np.array([[-s, c, 0], [-c, -s, 0], [0, 0, 0]]))
Rpp = (omega ** 2) * (np.array([[-c, -s, 0], [s, -c, 0], [0, 0, 0]]))
z1 = z[0:3]
z2 = z[3:6]
r2 = np.dot(z1, z1)
r = np.sqrt(r2)
Fg = (-G*Mt/r**2) * (R@(z1/r))
zp[0:3] = z2
zp[3:6] = R.T@(Fg - (2*(Rp@z2) + (Rpp@z1)))
return zp
def eulerint(zp, z0, t, Nsubdivisiones):
Nt = len(t)
Ndim = len(z0)
z = np.zeros((Nt, Ndim))
z[0, :] = z0
for i in range(1, Nt):
t_anterior = t[i-1]
dt = (t[i] - t[i-1])/Nsubdivisiones
z_temp = z[i-1, :].copy()
for k in range(Nsubdivisiones):
z_temp += dt*zp(z_temp, t_anterior + k*dt)
z[i, :] = z_temp
return z
fname = "S1A_OPER_AUX_POEORB_OPOD_20200820T121229_V20200730T225942_20200801T005942.EOF"
t, x, y, z, vx, vy, vz = leer_eof(fname)
sol_real = []
for i in range(len(t)):
sol_real.append([x[i], y[i], z[i], vx[i], vy[i], vz[i]])
np.array(sol_real)
# Condicion inicial (m)
xi = x[0]
yi = y[0]
zi = z[0]
vxi = vx[0]
vyi = vy[0]
vzi = vz[0]
# Condicion final
xf = x[-1]
yf = y[-1]
zf = z[-1]
vxf = vx[-1]
vyf = vy[-1]
vzf = vz[-1]
z0 = np.array([xi, yi, zi, vxi, vyi, vzi])
zf = np.array([xf, yf, zf, vxf, vyf, vzf])
t1 = perf_counter()
sol_odeint = odeint(satelite, z0, t)
t2 = perf_counter()
sol_eulerint = eulerint(satelite, z0, t, 1)
t3 = perf_counter()
# --Pregunta 1--#
plt.figure()
plt.subplot(3, 1, 1)
plt.title("Posición Real vs Odeint")
plt.plot(t, x, color="b", label="Real")
plt.plot(t, sol_odeint[:, 0], color="orange", label="Odeint")
plt.ylabel("x(t)")
plt.legend()
plt.subplot(3,1,2)
plt.plot(t, y, color="b", label="Real")
plt.plot(t, sol_odeint[:, 1], color="orange", label="Odeint")
plt.ylabel("y(t)")
plt.legend()
plt.subplot(3, 1, 3)
plt.plot(t, z, color="b", label="Real")
plt.plot(t, sol_odeint[:, 2], color="orange", label="Odeint")
plt.xlabel("t")
plt.ylabel("z(t)")
plt.legend()
plt.savefig("P1-grafico_posición(x,y,z)-RealvsOdeint.png")
plt.show() # sacar para entrega?
plt.figure()
plt.subplot(3, 1, 1)
plt.title("Posicion Real")
plt.plot(t, x, color="b", label="Real")
plt.ylabel("x(t)")
plt.subplot(3,1,2)
plt.plot(t, y, color="b", label="Real")
plt.ylabel("y(t)")
plt.subplot(3, 1, 3)
plt.plot(t, z, color="b", label="Real")
plt.xlabel("t")
plt.ylabel("z(t)")
plt.savefig("P1-grafico_posición(x,y,z)-Real.png")
plt.show() # sacar para entrega?
# ---Pregunta 2---#
tiempo_odeint = t2-t1
tiempo_euler = t3-t2
# ---Eulerint vs Odeint---#
deriva = []
for i in range(len(t)):
difx = sol_odeint[i][0] - sol_eulerint[i][0]
dify = sol_odeint[i][1] - sol_eulerint[i][1]
difz = sol_odeint[i][2] - sol_eulerint[i][2]
deriva.append(np.sqrt(np.dot(difx, difx) + np.dot(dify, dify) + np.dot(difz, difz)))
tx = t / 3600.
plt.figure()
plt.title(f"Diferencia Eulerint vs Odeint dmax = {round(max(deriva)/1000, 2)} KM")
plt.xlabel("Tiempo")
plt.ylabel("Deriva")
plt.plot(tx, np.array(deriva) / 1000)
plt.savefig("P2-EulerintvsOdeint.png")
plt.show()
# ---Real vs Eulerint---#
deriva1 = []
for i in range(len(t)):
difx = sol_real[i][0] - sol_eulerint[i][0]
dify = sol_real[i][1] - sol_eulerint[i][1]
difz = sol_real[i][2] - sol_eulerint[i][2]
deriva1.append(np.sqrt(np.dot(difx, difx) + np.dot(dify, dify) + np.dot(difz, difz)))
plt.figure()
plt.title(f"Diferencia Real vs Eulerint dmax = {round(max(deriva1)/1000, 2)} KM")
plt.xlabel("Tiempo")
plt.ylabel("Deriva")
plt.plot(tx, np.array(deriva1) / 1000)
plt.savefig("P2-RealvsEulerint.png")
plt.show()
# ---Real vs Odeint---#
deriva2 = []
for i in range(len(t)):
difx = sol_real[i][0] - sol_odeint[i][0]
dify = sol_real[i][1] - sol_odeint[i][1]
difz = sol_real[i][2] - sol_odeint[i][2]
deriva2.append(np.sqrt(np.dot(difx, difx) + np.dot(dify, dify) + np.dot(difz, difz)))
plt.figure()
plt.title(f"Diferencia Real vs Odeint dmax = {round(max(deriva2)/1000, 2)} KM")
plt.xlabel("Tiempo")
plt.ylabel("Deriva")
plt.plot(tx, np.array(deriva2) / 1000)
plt.savefig("P2-RealvsOdeint.png")
plt.show()
print(f"La solucion de eulerint demora {tiempo_euler} segundos")
print(f"La solucion de odeint demora {tiempo_odeint} segundos")
print(f"La solucion de odeint difiere en {round((deriva[-1])/1000, 2)} KM de la solucion eulerint al final del tiempo")
"""
# --- Pregunta 3 --- #
N=10000
error=100
while(error>=1):
N+=1
print(N)
t_eu0 = perf_counter()
sol_eulerint1 = eulerint(satelite, z0, t, N)
t_eu1 = perf_counter()
deriva3=[]
for i in range(len(t)):
difx = sol_real[i][0] - sol_eulerint1[i][0]
dify = sol_real[i][1] - sol_eulerint1[i][1]
difz = sol_real[i][2] - sol_eulerint1[i][2]
deriva3.append(np.sqrt(np.dot(difx, difx)+np.dot(dify, dify)+np.dot(difz, difz)))
errorx = (abs(difx)/sol_real[-1][0]) * 100
errory = (abs(dify)/sol_real[-1][1]) * 100
errorz = (abs(difz)/sol_real[-1][2]) * 100
error = (errorx + errory + errorz)/3
print(f"Eulerint con {N} subdivisiones presenta un error de {error} < al 1%")
plt.figure()
plt.title(f"Diferencia Real vs Eulerint con {N} subdivisiones dmax = {round(max(deriva3)/1000, 2)} KM")
plt.xlabel("Tiempo")
plt.ylabel("Deriva")
plt.plot(tx, np.array(deriva3) / 1000)
plt.savefig("P3.png")
plt.show()
"""
# --- Pregunta 4 --- #
def satelite_J2_J3(z, t):
c = np.cos(omega * t)
s = np.sin(omega * t)
R = np.array([[c, s, 0], [-s, c, 0], [0, 0, 1]])
Rp = omega * (np.array([[-s, c, 0], [-c, -s, 0], [0, 0, 0]]))
Rpp = (omega ** 2) * (np.array([[-c, -s, 0], [s, -c, 0], [0, 0, 0]]))
z1 = z[0:3]
z2 = z[3:6]
r2 = np.dot(z1, z1)
r = np.sqrt(r2)
FJ2 = np.zeros(3)
FJ2[0] = (J2 * z[0] / (r ** 7)) * (6 * z[2] ** 2 - (3 / 2) * (z[0] ** 2 + z[1] ** 2))
FJ2[1] = (J2 * z[1] / (r ** 7)) * (6 * z[2] ** 2 - (3 / 2) * (z[0] ** 2 + z[1] ** 2))
FJ2[2] = (J2 * z[2] / (r ** 7)) * (3 * z[2] ** 2 - (9 / 2) * (z[0] ** 2 + z[1] ** 2))
FJ3 = np.zeros(3)
FJ3[0] = (J3 * z[0] * z[2] / (r ** 9)) * (10 * z[2] ** 2 - (15 / 2) * (z[0] ** 2 + z[1] ** 2))
FJ3[1] = (J3 * z[1] * z[2] / (r ** 9)) * (10 * z[2] ** 2 - (15 / 2) * (z[0] ** 2 + z[1] ** 2))
FJ3[2] = (J3 / (r ** 9)) * (4 * z[2] ** 2 * (z[2] ** 2 - 3 * (z[0] ** 2 + z[1] ** 2) + (3 / 2) * (z[0] ** 2 + z[1] ** 2) ** 2))
zp[0:3] = z2
Fg = (-G * Mt / r ** 2) * (R @ (z1 / r))
zp[3:6] = R.T @ (Fg - (2 * Rp @ z2) + (Rpp @ z1)) + FJ2 + FJ3
return zp
p4_t1 = perf_counter()
p4_sol_odeint = odeint(satelite_J2_J3, z0, t)
p4_t2 = perf_counter()
p4_sol_eulerint = eulerint(satelite_J2_J3, z0, t, 1)
p4_t3 = perf_counter()
# --Pregunta 4 - parte 1--#
plt.figure()
plt.subplot(3, 1, 1)
plt.title("Posición Real vs Odeint_J2_J3")
plt.plot(t, x, color="b", label="Real")
plt.plot(t, p4_sol_odeint[:, 0], color="orange", label="Odeint_J2_J3")
plt.ylabel("x(t)")
plt.legend()
plt.subplot(3,1,2)
plt.plot(t, y, color="b", label="Real")
plt.plot(t, p4_sol_odeint[:, 1], color="orange", label="Odeint_J2_J3")
plt.ylabel("y(t)")
plt.legend()
plt.subplot(3, 1, 3)
plt.plot(t, z, color="b", label="Real")
plt.plot(t, p4_sol_odeint[:, 2], color="orange", label="Odeint_J2_J3")
plt.xlabel("t")
plt.ylabel("z(t)")
plt.legend()
plt.savefig("P4-grafico_posición(x,y,z)-RealvsOdeint_J2_J3.png")
plt.show() # sacar para entrega?
plt.figure()
plt.subplot(3, 1, 1)
plt.title("Posicion Real")
plt.plot(t, x, color="b", label="Real")
plt.ylabel("x(t)")
plt.subplot(3,1,2)
plt.plot(t, y, color="b", label="Real")
plt.ylabel("y(t)")
plt.subplot(3, 1, 3)
plt.plot(t, z, color="b", label="Real")
plt.xlabel("t")
plt.ylabel("z(t)")
plt.savefig("P4-grafico_posición(x,y,z)-Real.png")
plt.show() # sacar para entrega?
# ---Pregunta 4 - parte 2 ---#
p4_tiempo_odeint = p4_t2-p4_t1
p4_tiempo_euler = p4_t3-p4_t2
# ---Eulerint vs Odeint_J2_J3---#
p4_deriva = []
for i in range(len(t)):
difx = p4_sol_odeint[i][0] - p4_sol_eulerint[i][0]
dify = p4_sol_odeint[i][1] - p4_sol_eulerint[i][1]
difz = p4_sol_odeint[i][2] - p4_sol_eulerint[i][2]
p4_deriva.append(np.sqrt(np.dot(difx, difx) + np.dot(dify, dify) + np.dot(difz, difz)))
tx = t / 3600.
plt.figure()
plt.title(f"Diferencia Eulerint vs Odeint_J2_J3 dmax = {round(max(p4_deriva)/1000, 2)} KM")
plt.xlabel("Tiempo")
plt.ylabel("Deriva")
plt.plot(tx, np.array(p4_deriva) / 1000)
plt.savefig("P4-EulerintvsOdeint_J2_J3.png")
plt.show()
# ---Real vs Eulerint_J2_J3---#
p4_deriva1 = []
for i in range(len(t)):
difx = sol_real[i][0] - p4_sol_eulerint[i][0]
dify = sol_real[i][1] - p4_sol_eulerint[i][1]
difz = sol_real[i][2] - p4_sol_eulerint[i][2]
p4_deriva1.append(np.sqrt(np.dot(difx, difx) + np.dot(dify, dify) + np.dot(difz, difz)))
plt.figure()
plt.title(f"Diferencia Real vs Eulerint_J2_J3 dmax = {round(max(p4_deriva1)/1000, 2)} KM")
plt.xlabel("Tiempo")
plt.ylabel("Deriva")
plt.plot(tx, np.array(p4_deriva1) / 1000)
plt.savefig("P4-RealvsEulerint_J2_J3.png")
plt.show()
# ---Real vs Odeint_J2_J3---#
p4_deriva2 = []
for i in range(len(t)):
difx = sol_real[i][0] - p4_sol_odeint[i][0]
dify = sol_real[i][1] - p4_sol_odeint[i][1]
difz = sol_real[i][2] - p4_sol_odeint[i][2]
p4_deriva2.append(np.sqrt(np.dot(difx, difx) + np.dot(dify, dify) + np.dot(difz, difz)))
plt.figure()
plt.title(f"Diferencia Real vs Odeint_J2_J3 dmax = {round(max(p4_deriva2)/1000, 2)} KM")
plt.xlabel("Tiempo")
plt.ylabel("Deriva")
plt.plot(tx, np.array(p4_deriva2) / 1000)
plt.savefig("P4-RealvsOdeint_J2_J3.png")
plt.show()
p4_tf = perf_counter()
print(f"La solucion de eulerint_J2_J3 demora {p4_tiempo_euler} segundos")
print(f"La solucion de odeint_J2_J3 demora {p4_tiempo_odeint} segundos")
print(f"La solucion de odeint_J2_J3 difiere en {round((p4_deriva[-1])/1000, 2)} KM de la solucion eulerint al final del tiempo")
print(f"La Parte 4 demora {p4_tf-p4_t1} segundos en correr")
print(f"Todo el archivo demora {p4_tf-t0} segundos en correr (sin la parte 3)")
| true |
c3a8487bbecc417936016e18df339624909a1513 | Python | danxia0308/AIPractice | /tensorflow/tf_data.py | UTF-8 | 4,410 | 3.046875 | 3 | [] | no_license | '''
dataset = dataset.map(parse_function) //将dataset通过parse_function进行解析。
dataset = dataset.map(lambda filename, label:tuple(tf.py_func(_read_py_function, [filename,label], [tf.uint8,label.dtype]))) //使用tf.py_func来作用于非tf函数。
训练中使用dataset的顺序:
1. tf.data创建dataset。
2. dataset.map做预处理。
3. dataset.shuffle(buffer_size=1000) 乱序
4. dataset.batch(32)
5. dataset.repeat(num_epochs)
6. dataset.make_one_shot_iterator或者使用make_initializable_iterator并run其initializer。
7. 用iterator的get_next来获取下一个batch,直到出现OutOfRangeError。
'''
import tensorflow as tf
import numpy as np
from tensorflow.python.framework.errors_impl import OutOfRangeError
# 新版不能使用make_one_shot_iterator和make_initializable_iterator
# 2.X版本和3.X版本很不同啊
def ds_from_tensors():
dataset = tf.data.Dataset.from_tensor_slices(np.array([1.0,2.0,3.0,4.0,5.0,6.0]))
# dataset = tf.data.Dataset.from_tensor_slices(np.array(tf.constant(1.0, shape=[80])))
dataset = dataset.batch(3)
dataset = dataset.map(lambda x:[x,x])
print(list(dataset.as_numpy_iterator()))
for element in dataset.as_numpy_iterator():
print(element)
# with tf.compat.v1.Session() as sess:
# print(sess.run(next))
ds_from_tensors()
'''
tf.data.Dataset.from_tensor_slices 输入一个或多个tensor,可为数组或者dict。第一维表示数目,需要保持一致。
tf.data.make_one_shot_iterator 产生一次输出。
dataset.batch 产生batch数据
'''
def gen_data_and_use():
dataset=tf.data.Dataset.from_tensor_slices({'a':np.arange(10),'b':np.arange(10,20)});
dataset=tf.data.Dataset.from_tensor_slices((np.arange(10),np.arange(10,20)));
dataset=dataset.shuffle(10)
# 挨个读取
iter=tf.data.make_one_shot_iterator(dataset)
e1,e2=iter.get_next()
with tf.Session() as sess:
while True:
try:
print(sess.run([e1]))
print(sess.run([e2]))
except OutOfRangeError as e:
break
return
# batched_dataset = dataset.padded_batch(4, padded_shapes=[None])
# Batch读取
batched_dataset = dataset.batch(5)
iter_batch = batched_dataset.make_one_shot_iterator()
next_batch=iter_batch.get_next()
with tf.Session() as sess:
for i in range(2):
print(sess.run(next_batch))
init_iter = dataset.make_initializable_iterator()
next_element = init_iter.get_next()
with tf.Session() as sess:
sess.run(init_iter.initializer)
while True:
try:
print(sess.run(next_element))
except OutOfRangeError as e:
break
sess.run(init_iter.initializer)
while True:
try:
print(sess.run(next_element))
except OutOfRangeError as e:
break
# gen_data_and_use()
#TODO What's parse_single_example?
def __parse_function(example_proto):
features={'image':tf.FixedLenFeature((),tf.string, default_value=""),
'label':tf.FixedLenFeature((),tf.int64, default_value=0)}
parsed_features=tf.parse_single_example(example_proto,features)
return parsed_features['image'],parsed_features['label']
'''
注意dataset在map和batch之后,都需要返回并赋值给新的dataset。
'''
class Agent():
def __init__(self):
pass
def __parse(self, filename, label):
# image_string = tf.read_file(filename)
# image_decoded = tf.image.decode_jpeg(image_string)
# image_resized = tf.image.resize_images(image_decoded,(256,256))
# return image_resized, label
return filename, label
def run(self):
filenames=['1.jpg','2.jpg']
dataset=tf.data.Dataset.from_tensor_slices((filenames, filenames)).shuffle(buffer_size=len(filenames))
dataset = dataset.map(self.__parse,num_parallel_calls=8).batch(2)
iterator=dataset.make_initializable_iterator()
# dataset.batch(batch_size=2)
next_element=iterator.get_next()
with tf.Session() as sess:
# iterator=tf.data.make_one_shot_iterator(dataset)
sess.run(iterator.initializer)
for i in range(2):
print(sess.run(next_element))
# agent=Agent()
# agent.run()
| true |
a2e87dffe62e763daca2e4d7d633b895fb3f612f | Python | Andy-SKlee/Algorithm | /unit06.py | UTF-8 | 366 | 3.578125 | 4 | [] | no_license | def hanoi(n, from_bar, to_bar, aux_bar):
if n == 1:
print(from_bar, " -> ", to_bar)
return
hanoi(n - 1, from_bar, aux_bar, to_bar)
print(from_bar, " -> ", to_bar)
hanoi(n - 1, aux_bar, to_bar, from_bar)
print("n = 1")
hanoi(1, 1, 3, 2)
print("n = 2")
hanoi(2, 1, 3, 2)
print("n = 3")
hanoi(3, 1, 3, 2)
print("n = 4")
hanoi(4, 1, 3, 2) | true |
c10e51bd3576dc5cd023d278267237d4f0455c46 | Python | hjxu2016/somecode | /post_process/Train_Random.py | UTF-8 | 2,370 | 2.5625 | 3 | [] | no_license | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 20:26:44 2017
@author: hjxu
"""
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_curve, auc
import pickle
from sklearn import svm
HEATMAP_FEATURE_CSV_TRAIN = '/home/hjxu/breast_project/post_process/features/feature_train.csv'
model_save_pickle = '/home/hjxu/breast_project/post_process/tree/Random_model_90.pkl'
df_train = pd.read_csv(HEATMAP_FEATURE_CSV_TRAIN)
#df_validation = pd.read_csv(utils.HEATMAP_FEATURE_CSV_VALIDATION)
n_columns = len(df_train.columns)
feature_column_names = df_train.columns[1:n_columns - 1]#返回的是每个列表的第一行,对应的是特征的名字
#print feature_column_names
label_column_name = df_train.columns[n_columns - 1]
print label_column_name
train_x = df_train[feature_column_names]
train_y = df_train[label_column_name]
###############c测试文件##################3
df_test = pd.read_csv('/home/hjxu/breast_project/post_process/features/feature_test.csv')
df_testy = pd.read_csv('/home/hjxu/breast_project/Extract_Features_heatmap/GT_ground.csv')
test_x = df_test[feature_column_names]
test_y = df_testy['label']
###############c测试文件##################3
clf = svm.SVC()
#clf = RandomForestClassifier(n_estimators=500, n_jobs=2) #分类型决策树
s = clf.fit(train_x, train_y) # 训练模型
#with open(model_save_pickle, "wb") as f:
# pickle.dump(clf, f)
prob_predict_y_validation = clf.predict_proba(test_x)#给出带有概率值的结果,每个点所有label的概率和为1
predict = clf.predict(test_x)
#for i in range (130):
# print df_test['name'][i],prob_predict_y_validation[i],predict[i]
#######测试模型的准确率##########
#r = clf.score(test_x,test_y)
#print r
########测试模型的准确率##########3
#############画出roc曲线###################
#predictions_validation = prob_predict_y_validation[:, 1]
#fpr, tpr, _ = roc_curve(test_y, predictions_validation)
#
#roc_auc = auc(fpr, tpr)
#plt.title('ROC Validation')
#plt.plot(fpr, tpr, 'b', label='AUC = %0.2f' % roc_auc)
#plt.legend(loc='lower right')
#plt.plot([0, 1], [0, 1], 'r--')
#plt.xlim([0, 1])
#plt.ylim([0, 1])
#plt.ylabel('True Positive Rate')
#plt.xlabel('False Positive Rate')
#plt.show()
###################画roc曲线############## | true |
836cac9ff703916e1d2111d438a1feace5ffa595 | Python | bibopBob/streamlit_basic_text_charts | /simple.py | UTF-8 | 2,228 | 3.9375 | 4 | [] | no_license | import streamlit as st
import numpy as np
import pandas as pd
st.title('My first app')
st.write('Here\'s our first attempt at using data to create a table:')
st.write(pd.DataFrame({
'first column':[1,2,3,4],
'second column':[10,20,30,40]
}))
"""
## Second title
This is a second title with different method
"""
df = pd.DataFrame({
'first column':[1,2,3,4],
'second column':[10,20,30,40]
})
df
"""
## Lets add some more features
### Draw a line chart
"""
chart_data = pd.DataFrame(np.random.randn(20,3),columns=['a','b','c'])
st.line_chart(chart_data)
"""
### Plot a map
"""
map_data = pd.DataFrame(np.random.randn(1000,2) / [50,50] + [37.76,-122.4], columns=['lat','lon'])
st.map(map_data)
"""
## Add interativity
> https://docs.streamlit.io/en/stable/api.html
"""
"""
### Use checkboxes to show/hide data
"""
if st.checkbox('Show dataframe'):
chart_data = pd.DataFrame(np.random.randn(20,3),columns=['a','b','c'])
st.line_chart(chart_data)
"""
### Use a selectbox for options
"""
option = st.selectbox('Which number do you like best?',df['first column'])
'You selected: ', option
"""
### Lay out your app
For a cleaner look, you can move your widgets into a sidebar.
Most of the elements you can put into your app can also be put into a sidebar using this syntax: `st.sidebar.[element_name]()`
"""
option2 = st.sidebar.selectbox('Which number you like More?',df['first column'])
'You selected: ', option2
"""
### More widgets
Buttons & actions, collapsibles, multiple column rows
"""
left_column, right_column = st.beta_columns(2)
pressed = left_column.button('Press me?')
if pressed:
right_column.write("Woohoo!")
expander = st.beta_expander("FAQ")
expander.write("Here you could put in some really, really long explanations...")
"""
## Show progress
When adding long running computations to an app, you can use st.progress() to display status in real time.
"""
import time
'Starting a long computation...'
# Add a placeholder
latest_iteration = st.empty()
bar = st.progress(0)
for i in range(100):
# Update the progress bar with each iteration.
latest_iteration.text(f'Iteration {i+1}')
bar.progress(i + 1)
time.sleep(0.1)
'...and now we\'re done!'
#
| true |
c3d7035598ec023f8128a622a4157e7e31ff517b | Python | lccastro9/hkr-6 | /Point.py | UTF-8 | 533 | 3.375 | 3 | [] | no_license | class Point():
def __init__(self,x,y):
self.x=x
self.y=y
def move(self,x,y):
self.x1=x
self.y1=y
def reset(self):
self.x=0
self.y=0
def calculate_distance(self,otherPoint):
a=(otherPoint.x-self.x)**2 + (otherPoint.y-self.y)**2
distancia = a**0.5
return distancia
D=[]
for i in range((int(raw_input())/2)):
D.append(Point(*map(int,raw_input().split())).Distancia(Point(*map(int,raw_input().split()))))
for i in D:
print i
| true |
a6a875db61c83a8e4190bae5b0259ce6bef949bc | Python | sultann1997/Kase | /Kase parsing.py | UTF-8 | 4,384 | 2.65625 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
import csv
from urllib.request import urlopen
from zipfile import ZipFile
from io import BytesIO
import pandas as pd
import os
import pickle
import smtplib, ssl
df_test = pd.DataFrame() #creating Empty DataFrame
#Preparing email to automatically send notifications
from email.mime.text import MIMEText
import base64
from __future__ import print_function
import os.path
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/gmail.send'] #Scopes that will be allowed by the sender (in this case to send messages from my testing email)
#Creating functions to create and send an email
def create_message(sender, to, subject, message_text):
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
raw_message = base64.urlsafe_b64encode(message.as_string().encode("utf-8"))
return {
'raw': raw_message.decode("utf-8")
}
def send_message(service, user_id, message):
try:
message = service.users().messages().send(userId=user_id, body=message).execute()
print('Message Id: %s' % message['id'])
return message
except Exception as e:
print('An error occurred: %s' % e)
return None
# Check if the messaging works
# kase_update = send_message(service=build('gmail', 'v1', credentials=Credentials.from_authorized_user_file('token.json', SCOPES)),
# user_id='sultan.python.tests@gmail.com',
# message=create_message('sultan.python.tests@gmail.com', 'sultann1997@gmail.com', 'Kase Update', 'Kase DataFrame has been updated'))
URL = 'https://kase.kz/ru/documents/marketvaluation/'
if requests.get(URL).status_code == 200:
print('Connected')
else:
print("Could not connect into server")
soup = BeautifulSoup(requests.get(URL).text, features='html.parser')
items = soup.find_all('div', {'id':'a2021'})
#function to donwload and unzip files
def download_unzip(url, extract_to='.'):
http_response = urlopen(url)
zipfile = ZipFile(BytesIO(http_response.read()))
zipfile.extractall(path=extract_to)
for div in soup.find_all('div', {'id':'a2021'}):
for li in div.find_all('li'):
a = li.find('a')
#check if the file was already downloaded in the common directory
if a['href'].replace(r'/files/market_valuation/ru/2021/', '') in os.listdir(r'C:\Users\Sultan\Downloads\Big Data downloads\Kase zips check2'):
pass
else:
url_zip = 'https://kase.kz/' + a['href']
#create directories for each zipfile to be extracted in
current_dir = os.path.abspath(r'C:\Users\Sultan\Downloads\Big Data downloads\Kase zips check2'+'\\'+a['href'].replace(r'/files/market_valuation/ru/2021/', ''))
try: os.makedirs(current_dir)
except FileExistsError:
pass
download_unzip(url_zip, current_dir)
#zipfile contains txt and xlsx files, we take xlsx files
excel_file = [i for i in os.listdir(current_dir) if i.endswith('xlsx')]
try:
temp_df = pd.read_excel(current_dir +'\\'+ excel_file[0], engine='openpyxl')
#DataFrame automatically takes first row as headers, whereas our headers are on the third row
headers = temp_df.iloc[1]
temp_df = temp_df[3:]
temp_df.columns = headers
temp_df.drop(temp_df.columns[0], axis=1, inplace=True)
temp_df['File'] = excel_file[0]
df_test = df_test.append(temp_df)
df_test.reset_index(drop=True, inplace=True)
#sending email in case if the dataframe has been updated
send_message(service=build('gmail', 'v1',
credentials=Credentials.from_authorized_user_file('token.json', SCOPES)),
user_id='sultan.python.tests@gmail.com',
message=create_message('sultan.python.tests@gmail.com', 'sultann1997@gmail.com', 'Kase Update', 'Kase DataFrame has been updated'))
except (IndexError, AttributeError):
pass
#exporting file into excel
df_test.to_excel(r"C:\Users\Sultan\Downloads\Big Data downloads\my_excel.xls", engine='openpyxl') | true |
ebcf39d4fd3c76d9d5c180a3604cd8358d2ece5e | Python | corka149/pump_light | /src/pump_light/client.py | UTF-8 | 1,805 | 2.6875 | 3 | [] | no_license | """ Websocket and HTTP/S client for iot_server """
import logging
import pprint
import socket
import traceback
from aiohttp import ClientSession
from pump_light.infrastructure import config
from pump_light.model.exception import ExceptionSubmittal
_LOG = logging.getLogger(__name__)
class ExceptionReporter:
""" Async contextmanager that reports exceptions to the IoT server. """
async def __aenter__(self):
pass
async def __aexit__(self, exc_type, exc_val, exc_tb):
if exc_type and exc_val and exc_tb:
stack = traceback.format_stack()
exception_dto = ExceptionSubmittal(
hostname=socket.gethostname(),
clazz=str(exc_type),
message=str(exc_val),
stacktrace=''.join(stack)
)
_LOG.error(pprint.pformat(exception_dto.json()))
await send_exception(exception_dto)
# Exception was handled
return True
async def send_exception(exception_dto: ExceptionSubmittal) -> None:
""" Send a exception report to the iot server. """
url = config.get_config('iot_server.address') + '/exception'
async with ClientSession() as session:
async with session.post(url, data=exception_dto.json(), headers=config.basic_auth()) as response:
msg = await response.text()
_LOG.info('Response on error report: status=%s, message="%s"', response.status, msg)
async def check_existence() -> bool:
""" Checks if a device exists. """
async with ClientSession() as session:
async with session.get(config.build_device_url(), headers=config.basic_auth()) as response:
_LOG.info('Response of checking existence: status=%s', response.status)
return response.status == 200
| true |
8a0e4e161c178aaaf72d7682383566b37caad37f | Python | jamesdpearce/utils | /variable_importance.py | UTF-8 | 3,324 | 2.59375 | 3 | [] | no_license | import sys
import time
import numpy as np
from progress import ProgressBar
def gen_var_impact_scores(clf, X_train, y_train, X_test,
n_rounds=100, verbose=False, fit=True):
"""
Given classifier and training data, return variable importances on the
test data on a per-sample basis.
Impact scores represent the ability of a given variable
to influence the result (given the others are held constant).
"""
if fit:
clf.fit(X_train, y_train)
real_scores = clf.predict_proba(X_test)[:, 1]
impact_scores = np.zeros(X_test.shape)
if verbose:
pc = ProgressCounter()
for var in range(X_train.shape[1]):
single_var_scores = np.zeros([X_test.shape[0], n_rounds])
X_test_mod = np.copy(X_test)
for j in range(n_rounds):
if verbose:
pc.increment_progress()
X_test_mod[:, var] = np.random.choice(X_train[:, var], X_test.shape[0], replace=True)
single_var_scores[:, j] = clf.predict_proba(X_test_mod)[:, 1]
impact_scores[:, var] = np.std(single_var_scores, axis=1)
return impact_scores
def gen_var_result_scores(clf, X_train, X_test, y_train=None,
n_rounds=100, verbose=False, fit=True):
"""
Given classifier and training data, return variable importances on the
test data on a per-sample basis. UPDATED.
Result scores represent the difference between the observed score and
the mean score obtained if the specific variable is resampled from the
training data randomly.
"""
if fit:
if verbose:
print 'Training model...'
sys.stdout.flush()
t0 = time.time()
clf.fit(X_train, y_train)
if verbose:
t1 = time.time()
print 'Training took %.2f seconds' % (t1 - t0)
real_scores = clf.predict_proba(X_test)[:, 1]
result_scores = np.zeros(X_test.shape)
if verbose:
pb = ProgressBar()
progress = 0
for var in range(X_train.shape[1]):
single_var_scores = np.zeros([X_test.shape[0], n_rounds])
X_test_mod = np.copy(X_test)
for j in range(n_rounds):
if verbose:
progress += 1
pb.update_progress(progress / float(n_rounds * X_train.shape[1]))
X_test_mod[:, var] = np.random.choice(X_train[:, var], X_test.shape[0], replace=True)
single_var_scores[:, j] = clf.predict_proba(X_test_mod)[:, 1]
result_scores[:, var] = np.abs(real_scores - np.mean(single_var_scores, axis=1))
return result_scores
def _resampled_scores(clf, X_train, X_test, n_rounds=100, verbose=False):
scores = np.zeros([X_test.shape[0], n_rounds, X_test.shape[1]])
if verbose:
pc = ProgressCounter()
for var in range(X_train.shape[1]):
single_var_scores = np.zeros([X_test.shape[0], n_rounds])
X_test_mod = np.copy(X_test)
for j in range(n_rounds):
if verbose:
pc.increment_progress()
X_test_mod[:, var] = np.random.choice(X_train[:, var], X_test.shape[0], replace=True)
single_var_scores[:, j] = clf.predict_proba(X_test_mod)[:, 1]
scores[:, :, var] = single_var_scores
return scores
| true |
8fde96116f053050407e69d6424ab218e2b49c70 | Python | xmaimiao/hogwarts_venv | /testing/test_calcu.py | UTF-8 | 1,228 | 2.578125 | 3 | [] | no_license | import pytest
import yaml
from decimal import *
from testing.usual import usual
class TestAdd:
@pytest.mark.parametrize("data", yaml.safe_load(open("./data_add.yaml")),
ids=['1.int', '2.float', '3.int+float', '4.before=0', '5.after=0', '6.be/af=0'])
def test_add(self, data, calcu_m):
usual(data, '+')
@pytest.mark.parametrize("data", yaml.safe_load(open("./data_sub.yaml")),
ids=['1.int,be>af', '2.float,be>af', '3.float-int,be>af',
'4.int,be<af', '5.float,be<af', '6.float-int,be<af',
'7.int,be=af', '8.float,be=af',
'9.before=0', '10.after=0', '11.be/af=0'])
def test_sub(self, data):
usual(data, '-')
@pytest.mark.parametrize("data", yaml.safe_load(open("./data_mult.yaml")),
ids=['1.int', '2.float', '3.int*float', '4.before=0', '5.after=0', '6.be/af=0'])
def test_mult(self, data):
usual(data, '*')
@pytest.mark.parametrize("data", yaml.safe_load(open("./data_div.yaml")))
def test_div(self, data):
usual(data, '/')
if __name__ == '__main__':
pytest.main()
| true |
c40847b2270348c356dcadcf047ccdaac7b80aae | Python | rangertaha/celerity-challenge | /apps/demo/tests.py | UTF-8 | 963 | 3.234375 | 3 | [
"MIT"
] | permissive | # Third party imports
from django.test import TestCase
# Local imports
from .roman import RomanNumeral
class RomanNumeralTestCase(TestCase):
def setUp(self):
self.TEST_CASES = [
('', 0),
('VI', 6),
('IX', 9),
('XVIII', 18),
('XIX', 19),
('XXXVIII', 38),
('XXXIX', 39),
('XL', 40),
('XCVIII', 98),
('CCCLXXXVIII', 388),
('CDXCIX', 499),
('DCCCLXVII', 867),
('MCMXCVIII', 1998),
('MMMCMXCIX', 3999),
]
def test_int_to_rom(self):
"""Testing the conversion from int to roman numerals"""
for c, n in self.TEST_CASES:
self.assertEqual(RomanNumeral(n).rom, c)
def test_rom_to_int(self):
"""Testing the conversion from int to roman numerals"""
for c, n in self.TEST_CASES:
self.assertEqual(RomanNumeral(c).int, n)
| true |
e89fc52fe9ec939f1ef4f7141b9944e036deda1c | Python | xuxu001/spider | /hehe/spiders/ceshi.py | UTF-8 | 1,671 | 2.71875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import scrapy
import string
class CeshiSpider(scrapy.Spider):
name = 'ceshi'
allowed_domains = ['qiushibaike.com']
start_urls = ['https://www.qiushibaike.com/text/page/']
# header = {
# "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"}
# yield scrapy.Request(url=url, headers=header, callback=self.parse)
def parse(self, response):
content_list = response.xpath("//div[@id='content-left']/div")
print(content_list)
for con in content_list:
item ={}
item['body']=con.xpath(".//a/div/span/text()").extract_first()
item['stater']=con.xpath(".//div[1]/a[2]/h2/text()").extract_first()
yield item
last_url = response.xpath("//div[@id='content-left']/ul/li[8]/a/@href").extract_first()
if last_url !=None:
next_url = "https://www.qiushibaike.com" + last_url
yield scrapy.Request(
next_url,
callback=self.parse
)
# print(last_url)
# b = chr(last_url)
# print(type(b))
# # next_url=response.xpath('.//ur/li/a/text()').extract_first()[1:]
# # next_url = "https://www.qiushibaike.com" + next_url
# # yield scrapy.Request(
# # next_url,
# # callback=self.parse
# # )
# for a in range(1,b):
# next_url = "https://www.qiushibaike.com/text/page/" +a +'/'
#
# yield scrapy.Request(
# next_url,
# callback=self.parse
# )
| true |
bb98a51c0d1dca9683272ebaf2fdcf97bace0ede | Python | robmccoll/leap-projects | /drawing/drawing.py | UTF-8 | 4,802 | 2.640625 | 3 | [] | no_license | ################################################################################
# Copyright Rob and Mark McColl 2012
# This source code is available under the terms of the 3-part BSD Open Source
# license. http://opensource.org/licenses/BSD-3-Clause
################################################################################
import Leap, sys, wx
class ScaledVector(Leap.Vector):
def __init__(self, init, scale, in_min, in_max):
Leap.Vector.__init__(self, init)
self.scale = scale
self.in_min = in_min
self.in_max = in_max
self.in_range = in_max - in_min
def interpolate(self, val, scale, in_max, in_min, in_range):
if(val > max(in_max,in_min)):
return scale
elif(val < min(in_min,in_max)):
return 0
else:
return scale * ((val - in_min) / in_range)
def set(self, val):
self.x = self.interpolate(val.x, self.scale.x, self.in_max.x, self.in_min.x, self.in_range.x)
self.y = self.interpolate(val.y, self.scale.y, self.in_max.y, self.in_min.y, self.in_range.y)
self.z = self.interpolate(val.z, self.scale.z, self.in_max.z, self.in_min.z, self.in_range.z)
def copy_to_vec(self, vec):
vec.x = self.x
vec.y = self.y
vec.z = self.z
class OneFinger(Leap.Listener):
def __init__(self, location):
Leap.Listener.__init__(self)
self.location = location
def on_frame(self, controller):
frame = controller.frame()
if not frame.hands.empty and not frame.hands[0].fingers.empty:
fingers = frame.hands[0].fingers
two_hands = len(frame.hands) == 2
eight_fingers = two_hands and ((len(frame.hands[0].fingers) + len(frame.hands[1].fingers)) == 8)
self.location.set_location(fingers[0].tip_position, two_hands, eight_fingers)
class LocationPainter:
def __init__(self, panel, scaledvec):
self.loc = scaledvec
self.prev = Leap.Vector(scaledvec)
self.on = self.loc.scale.z * 0.5
self.bmp = wx.EmptyBitmap(self.loc.scale.x, self.loc.scale.y)
self.dc = wx.MemoryDC()
self.dc.SelectObject(self.bmp)
self.panel = panel
self.erase = True
self.full_erase = False
def set_location(self, new_loc, erase, full_erase):
self.loc.set(new_loc)
self.erase = erase
self.full_erase = full_erase
self.panel.Refresh()
def paint_location(self, event):
dc = wx.PaintDC(event.GetEventObject())
dc.Blit(0,0,self.loc.scale.x, self.loc.scale.y,self.dc,0,0,wx.COPY)
if(self.full_erase):
x = self.loc.scale.x
y = self.loc.scale.y
points = [wx.Point(0,0), wx.Point(x,0), wx.Point(x,y), wx.Point(0,y)]
self.dc.SetBrush(wx.Brush("BLACK"))
self.dc.SetPen(wx.Pen("BLACK", 10))
self.dc.DrawPolygon(points)
elif(self.loc.z > self.on):
dc.SetPen(wx.Pen("RED", self.loc.z - self.on + 10))
dc.DrawLine(self.loc.x,self.loc.y, self.loc.x, self.loc.y)
if(self.erase):
dc.SetPen(wx.Pen("WHITE", 10))
else:
dc.SetPen(wx.Pen("BLUE", 10))
dc.DrawLine(self.loc.x,self.loc.y, self.loc.x, self.loc.y)
elif(self.erase):
size = (self.on - self.loc.z) / 1.2 + 10
dc.SetPen(wx.Pen("WHITE", size))
dc.DrawLine(self.loc.x,self.loc.y, self.loc.x, self.loc.y)
self.dc.SetPen(wx.Pen("BLACK", size))
self.dc.DrawLine(self.prev.x,self.prev.y, self.loc.x, self.loc.y)
else:
self.dc.SetPen(wx.Pen("BLUE", 10))
self.dc.DrawLine(self.prev.x,self.prev.y, self.loc.x, self.loc.y)
self.loc.copy_to_vec(self.prev)
def main():
init_pos = Leap.Vector(500, 400, 100)
img_size = Leap.Vector(1000, 800, 100)
phys_min = Leap.Vector(-70, 360, -180)
phys_max = Leap.Vector(100, 130, 60)
scaled_vec = ScaledVector(init_pos, img_size, phys_min, phys_max)
# Create the wxApp and frame
app = wx.App(False)
frame = wx.Frame(None, title = "Drawing")
frame.SetSizeWH(img_size.x, img_size.y)
panel = wx.Panel(frame)
panel.SetDoubleBuffered(True)
loc = LocationPainter(panel, scaled_vec)
panel.Bind(wx.EVT_PAINT, loc.paint_location)
# Create a sample listener and controller
listener = OneFinger(loc)
controller = Leap.Controller()
# Have the sample listener receive events from the controller
controller.add_listener(listener)
# Display window and start main loop
frame.Show(True)
app.MainLoop()
# Remove the sample listener when done
controller.remove_listener(listener)
if __name__ == "__main__":
main()
| true |
9bacba16954cc9423525c6eddb0a33c259a0ccf2 | Python | code-goblin-for-jack/gzEstate | /data_wash.py | UTF-8 | 5,977 | 3 | 3 | [] | no_license | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import sqlite3
import logging
_DB_File = "./data/houses.db"
_Fields = [
"链家编号", "标题",
"总价", "首付", "税费",
"建筑年代", "配备电梯",
"梯户比例", "建筑结构", "建筑类型", "所在楼层",
"装修情况", "房屋朝向",
"行政区", "板块", "小区",
"建筑面积", "房本年限", "挂牌时间", "上次交易",
"产权所属", "房屋用途", "交易权属",
"室", "厅", "厨", "卫"
]
class NormalizeMap:
"""
归一化的映射表,支持正反向查询
"""
def __init__(self, dataset: pd.DataFrame):
"""
根据数据集建立每一列数据的归一化映射表
:param dataset: 待处理的数据集
"""
self._normalize_map = {
column: self.map_field2number(dataset[column])
for column in dataset.columns
if dataset[column].dtype.name == "object"
}
for column in dataset.columns:
if dataset[column].dtype.name != "object":
self._normalize_map[column] = \
(dataset[column].min(), dataset[column].max())
logging.debug("归一化映射表为: %s" % (self._normalize_map,))
def normalize(self, field:str, value):
"""
将field数据域的原始数据值value进行归一化计算后返回
:param field: dataset数据集中field数据域键名
:param value: 待归一化的数据
:return: float 归一化后的数据值
"""
table = self._normalize_map[field]
if(isinstance(table, tuple)):
min, max = table
return (float(value)-min)/(max-min)
else:
return table[value]
def de_normalize(self, field:str, value:float):
"""
将field数据域对应的归一化数据之value还原为原始数据值
:param field: dataset数据集中field数据域键名
:param value: 已归一化的数据
:return: 还原为原始数据后的值
"""
table = self._normalize_map[field]
if(isinstance(table, tuple)):
min, max = table
return min + value*(max-min)
else:
for k,v in table.items():
if abs(value-v) < 0.00001:
return k
@staticmethod
def map_field2number(series: pd.Series):
"""
根据一个序列,建立元素到归一化数值的映射表,
:param series: pandas.Series类型
:return: dict类型, 从元素到归一化数值的映射表
Example:
>>> HouseFrame.map_field2number(pd.Series(["1", "foo", "1", "bar"]))
{'1': 0.0, 'bar': 0.5, 'foo': 1.0}
>>> HouseFrame.map_field2number(pd.Series(["2", "foo", "foo"]))
{'2': 0.0, 'foo': 1.0}
"""
unique_values = series.sort_values().unique()
if len(unique_values) == 1:
return {unique_values[0]: 1}
step = 1.0/(len(unique_values)-1)
return {item: step*index
for index, item in enumerate(unique_values)}
class HouseFrame:
"""
处理房源列表
"""
def __init__(self, db_conn, table, fields):
"""
读取数据,并初始化HouseFrame
:param db_conn: 数据库链接,HouseFrame实例将从该链接读取数据
:param table: 数据库中存储目标数据的表
:param fields: table表中将要读取的数据域
"""
self._df = None
self._dataset = None
self._read_frame(db_conn, table, fields)
logging.debug(self.df)
self._normalize_map = NormalizeMap(self.df)
self._normalize()
def _read_frame(self, db_conn, table, fields):
query = " ".join(
["SELECT ",
", ".join(fields),
" FROM ",
table,
";"]
)
self._df = pd.io.sql.read_sql(query, db_conn)
def convert2number(x):
try:
return float(x)
except ValueError:
return np.NaN
self._df["梯户比例"] = self._df["梯户比例"].map(convert2number)
def _normalize(self):
self._df = self.df.fillna(-1)
for column in self.df.columns:
self.df[column] = self.df[column].map(
lambda x: self._normalize_map.normalize(column, x)
)
# self._df = self.df.dropna()
@property
def df(self):
"""
获取内部数据
:return: pandas.DataFrame对象实例
"""
return self._df
@property
def dataset(self):
"""
返回供机器学习使用的数据集
:return:
"""
if self._dataset is not None:
return self._dataset
else:
self._dataset = {
"input": pd.DataFrame(),
"target": pd.DataFrame()
}
target_columns = ("总价", "首付", "税费")
for column in target_columns:
self._dataset["target"][column] = self._df[column]
for column in self._df.columns:
if column not in target_columns:
self._dataset["input"][column] = self._df[column]
return self._dataset
def read_house_frame():
with sqlite3.connect(_DB_File) as db_conn:
house_frame = HouseFrame(db_conn, "houses", _Fields)
return house_frame.dataset
if __name__ == "__main__":
def _main():
logging.basicConfig(level=logging.DEBUG)
dataset = read_house_frame()
print("输入数据:")
print(dataset["input"])
fn = lambda lst : any(np.isnan(x) for x in lst)
na_df = dataset["input"].apply(fn)
print(na_df)
print("\n目标数据:")
print(dataset["target"])
_main()
| true |
dfdaab107f4940dd02f9021a2ebff95ff6d1ef47 | Python | muhammadsyamsudin/Python_Telepot_DigiwareProjects | /Raspberry-Pi/Smarthome_with_RPi_and_Telegram_Bot.py | UTF-8 | 2,419 | 2.734375 | 3 | [] | no_license | import sys
import time
import random
import datetime
import telepot
import RPi.GPIO as GPIO
def on(pin):
GPIO.output(pin,GPIO.LOW)
return
def off(pin):
GPIO.output(pin,GPIO.HIGH)
return
# Perintah untuk menggunakan pin board GPIO Raspberry Pi
GPIO.setmode(GPIO.BOARD)
# Pengaturan GPIO
GPIO.setup(37, GPIO.OUT)
GPIO.setup(38, GPIO.OUT)
GPIO.setup(40, GPIO.OUT)
GPIO.output(37, 1)
GPIO.output(38, 1)
GPIO.output(40, 1)
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
print 'Got command: %s' % command
# Menyalakan channel relay 1
if command == 'nyala1':
bot.sendMessage(chat_id, on(37))
# Menyalakan channel relay 2
elif command == 'nyala2':
bot.sendMessage(chat_id, on(38))
# Menyalakan channel relay 3
elif command == 'nyala3':
bot.sendMessage(chat_id, on(40))
# Memadamkan channel relay 1
elif command =='padam1':
bot.sendMessage(chat_id, off(37))
# Memadamkan channel relay 2
elif command =='padam2':
bot.sendMessage(chat_id, off(38))
# Memadamkan channel relay 3
elif command =='padam3':
bot.sendMessage(chat_id, off(40))
#Memadamkan semua channel
elif command =='allof':
bot.sendMessage(chat_id, off(40), off(38), off(37))
#Memadamkan semua channel
elif command =='allon':
bot.sendMessage(chat_id, on(40), on(38), on(37))
bot = telepot.Bot('Bot Token') # Ganti 'Bot Token' dengan kode token anda, misal bot = telepot.Bot('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9')
bot.message_loop(handle)
print '=================================================='
print 'Selamat datang di demo Smarthome Telegram DigiWare'
print '=================================================='
print ' '
print ' + kirim pesan nyala1 untuk mengaktifkan relay channel 1'
print ' + kirim pesan nyala2 untuk mengaktifkan relay channel 2'
print ' + kirim pesan nyala3 untuk mengaktifkan relay channel 3'
print ' + kirim pesan padam1 untuk menonaktifkan relay channel 1'
print ' + kirim pesan padam2 untuk menonaktifkan relay channel 2'
print ' + kirim pesan padam3 untuk menonaktifkan relay channel 3'
print ' + kirim pesan allon untuk mengaktifkan semua channel'
print ' + kirim pesan alloff untuk menonaktifkan semua channel'
print ' '
print 'Siap menerima pesan Anda...'
while 1:
time.sleep(10)
| true |
138e00452252df2a4a1609c534904dfa662dbd17 | Python | ofloveandhate/advent_of_code_2020 | /2/solution.py | UTF-8 | 639 | 3.703125 | 4 | [
"MIT"
] | permissive |
def read_data():
with open ('input.txt') as f:
data = f.readlines()
return data
def part1():
data = read_data()
count = 0
for d in data:
span,letter,password = d.split()
lower,upper = span.split('-')
letter = letter[0]
occ = password.count(letter)
if int(lower) <= occ and occ <= int(upper):
count = count+1
return count
def part2():
data = read_data()
count = 0
for d in data:
span,letter,password = d.split()
pos1,pos2 = span.split('-')
letter = letter[0]
if (password[int(pos1)-1]==letter) != (password[int(pos2)-1] == letter):
count = count+1
return count
print(part1())
print(part2()) | true |
e248d25c8afeff5a6ad480c4f39426dfdd2278da | Python | locqj/study | /python/python.py | UTF-8 | 3,041 | 3.328125 | 3 | [] | no_license | # -*- coding: UTF-8 -*-
import json, calendar, time, support, package # json 要导入才能用json
# 循环
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :'+'asd', fruits[index]
print "Good bye!"
# 多重循环
test = ['a', 'b', 'c']
test1 = [1, 2, 3]
new_list = []
for t in test:
for m in test1:
print '%s is a what, index equal %d' %(t, m)
new_list.append([t, m])
else:
print 'in for'
else:
print 'out for'
print new_list
# while 循环
''' i = 2
while(i < 20):
j=2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j):
print i, "是 素数"
i = i + 1
print "good bye!" '''
for m in 'Python':
if m == 'h':
pass
print 'this is block'
print m
i = 2
j = 2
q = cmp(i, j) # 大于 1 等于 0 小于 -1
print q
if(i == j):
print "eq"
else:
print ""
# 字符串
var1 = 'locqj'
locq = 'lo'
# print var1[0:3] # loc
# print var1[:3] # loc
''' if (locq in var1):
print 'in' '''
# 引用json
''' data = [{'a':"A",'b':(2,4),'c':3.0}]
print "DATA:",repr(data)
data_string = json.dumps(data)
print "JSON:",data_string '''
# Lists
''' L = ['span', 'test', 'asd']
Q = [1, 2, 3]
M = L + Q
print M '''
# 元组
''' tup1 = ('phys', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 111)
del tup1
tup1 = ()
tup3 = tup1 + tup2
print max(tup2) '''
# dictionary
dict = {'Aclie': 123, 'lcoqj': 1235}
del dict['Aclie']
print dict
# time
ticks = time.time() # 时间戳
localtime = time.localtime(time.time())
print localtime[0]
cal = calendar.month(2018, 1)
print cal
# 函数
def printme( string ):
val1 = "打印传入的字符串到标准显示设备上"
return string + val1
print printme("asdasd")
#可写函数说明
def printinfo( name, age=20 ):
"打印任何传入的字符串"
print "Name: ", name
print "Age ", age
#调用printinfo函数
printinfo("miki", 50)
printinfo(age=50, name="miki") #这样规定传入参数值,就不需要按照顺序写,只要知道参数名
printinfo(name="asdas") # 函数写了缺省就可以自定义函数个数
# 不定长参数
''' def testlength(name, *age):
print "output"
print name
for n in age:
print n
testlength('asdasdas', 1, 'asd', 'dasda') '''#除了第一个为固定参数,其他的参数以数组的形式赋值给*age, *就代表不定参数,可能是一个或者多个
# lambda 好处减少代码环境污染,减少无用代码,注意不能用print在lambda 匿名函数(闭包)
''' sum = lambda age1, age2: age1 + age2
print sum(120,123)
support.print_func("locqj") '''
Money = 2000
def AddMoney():
global Money #加上 global 就不会报错 -》全局变量, 不定义全局变量 函数外面识别不了Money
Money = Money + 1
print Money
AddMoney()
print Money
content = dir(package) # 输出import里面函数的名字
package.hellaa()
# I/O
str = raw_input("Enter your input: ")
print "Received :", str | true |
fbb864eb24d3d3e9477086c26d6fc5837e74b658 | Python | gabriellaec/desoft-analise-exercicios | /backup/user_225/ch22_2020_03_02_19_54_10_487593.py | UTF-8 | 194 | 2.96875 | 3 | [] | no_license | fuma_há_quanto_tempo = int (input("Há quantos anos fuma: "))
número_de_cigarros = int (input ("Número de cigarros por dia: "))
print ((fuma_há_quanto_tempo*365*24*60)*(número_de_cigarros)) | true |
114f0e4f2a57c11f3f5201984857635351284b0c | Python | allanliebold/python_refresh | /data_structures_tutorial.py | UTF-8 | 715 | 4.46875 | 4 | [
"MIT"
] | permissive | from math import sqrt
s = 'hello'
s.upper()
# To see a list of methods available, press tab after the .
#Big O Notation - Describes how quickly runtime will grow relative to the size of the input
def sumToN(n):
''' Take an input of n and return the sum of the numbers from 0 to n'''
sum = 0
for x in range(n+1):
sum += x
return sum
def sumToN2(n):
return (n*(n+1))/2
# O(1) - Constant
# log(n) - Logarithmic
# O(n) - Linear
# O(1)
def func_constant(values):
print values[0]
func_constant([1,2,3])
# 1
# Constant. Regardless of n number of inputs, the function always takes returns 1
# O(n)
def func_lin(lst):
for val in lst:
print val
# Linear. A list of n values will print n values
| true |
b914e87aa29ed684db1a141ceab0baee023cf90b | Python | mishik182/places | /place/management/commands/fill_tags_and_addr.py | UTF-8 | 999 | 2.53125 | 3 | [] | no_license | from django.core.management.base import BaseCommand, CommandError
from coolname import generate_slug
from faker import Faker
from place.models import Address
from tag.models import Tag
class Command(BaseCommand):
fake = Faker()
@classmethod
def delete_objects(cls, Model):
Model.objects.all().delete()
@classmethod
def create_tags(cls):
cls.delete_objects(Tag)
for i in range(20):
Tag.objects.create(
name=generate_slug(2)
)
@classmethod
def create_addresses(cls):
cls.delete_objects(Address)
for i in range(20):
Address.objects.create(
address=cls.fake.address()
)
def handle(self, *args, **options):
try:
self.create_tags()
self.create_addresses()
except Exception as e:
raise CommandError('Error while filling the database!', e)
self.stdout.write(self.style.SUCCESS('OK!'))
| true |
16a86ec1e736a57cd9cfcfef26787a4496f1656a | Python | ferhatelmas/algo | /codechef/practice/easy/dce03.py | UTF-8 | 181 | 3.234375 | 3 | [
"WTFPL"
] | permissive | catalans = [1]
for i in range(0, 1001):
catalans.append((2 * (2 * i + 1) * catalans[-1]) / (i + 2))
for _ in range(int(input())):
print(catalans[int(input()) - 1] % 10000)
| true |
44c5dea5d2795d74d769d3b9dea84f9ffb8296c1 | Python | kashyapvinay/leetcode-challenge | /python3/june/day_14_Cheapest Flights Within K Stops.py | UTF-8 | 1,033 | 2.984375 | 3 | [
"MIT"
] | permissive | class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
graph = [ [] for _ in range(n)]
for flight in flights:
u = flight[0]
v = flight[1]
cost = flight[2]
graph[u].append((v, cost,))
q = deque()
q.append((src, 0))
visited = [float('inf') for _ in range(n)]
ans = float('inf')
while (len(q) > 0 and K >= 0):
s = len(q)
for _ in range(s):
u, cost = q.popleft()
for j in range(len(graph[u])):
v = graph[u][j][0]
new_cost = cost + graph[u][j][1]
if dst == v:
ans = min(new_cost, ans)
if new_cost < visited[v]:
visited[v] = new_cost
q.append((v, new_cost))
K -= 1
return ans if ans != float('inf') else -1
| true |
51b284e3ce119936cbe4047558afecb091f44d50 | Python | kinghotelwelco/Instagram-follow-tracker-manager | /main.py | UTF-8 | 4,039 | 2.796875 | 3 | [] | no_license | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
username_css = '@name=\'username\''
password_css = 'name="password"'
username = ''
password = ''
count = 0
def login(driver):
driver.find_element_by_name("username").send_keys(username)
driver.find_element_by_name("password").send_keys(password)
driver.find_element_by_name("password").send_keys(u'\ue007')
def click_button_with_css(driver, css_selector):
element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, css_selector)))
element.click()
def navigate_to_followers(driver):
dropdown_css = '[alt*="' + username + '"]'
profile_css = "[href*=\"" + username + "\"]"
click_button_with_css(driver, dropdown_css)
click_button_with_css(driver, profile_css)
def __main__():
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://www.instagram.com/accounts/login/?source=auth_switcher')
time.sleep(1)
login(driver)
navigate_to_followers(driver)
try:
click_button_with_css(driver, "[href*=\"" + username + "/followers/\"]")
except:
print("auto opened this time")
followers = get_list_from_dialog(driver)
css_select_close = '[aria-label="Close"]'
click_button_with_css(driver, css_select_close)
click_button_with_css(driver, "[href*=\"" + username + "/following/\"]")
following = get_list_from_dialog(driver)
unfollow_list = no_followback(followers, following)
print("You follow the following people who do not follow you back:")
for i in range(len(unfollow_list)):
print(unfollow_list[i])
time.sleep(5)
for i in range(len(unfollow_list)):
driver.get('https://www.instagram.com/' + str(unfollow_list[i]) + '/')
css_select_following = '[aria-label="Following"]'
click_button_with_css(driver, css_select_following)
driver.find_element_by_xpath('//button[text()="Unfollow"]')\
.click()
time.sleep(2)
print("Unfollowed" + str(len(unfollow_list)) + " accounts that weren't following you back.")
def no_followback(followers, following):
followers.sort()
following.sort()
no_followback_list = []
for i in range(len(following)):
try:
followers.index(following[i])
except ValueError:
no_followback_list += [following[i]]
return no_followback_list
def get_list_from_dialog(driver):
list_xpath = "//div[@role='dialog']//li"
WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.XPATH, list_xpath)))
scroll_down(driver)
list_elems = driver.find_elements_by_xpath(list_xpath)
users = []
for i in range(len(list_elems)):
try:
row_text = list_elems[i].text
if ("Follow" in row_text):
username = row_text[:row_text.index("\n")]
users += [username]
except:
print("continue")
return users
def check_difference_in_count(driver):
global count
new_count = len(driver.find_elements_by_xpath("//div[@role='dialog']//li"))
if count != new_count:
count = new_count
return True
else:
return False
def scroll_down(driver):
global count
iter = 1
while 1:
scroll_top_num = str(iter * 2000)
iter += 1
# scroll down
driver.execute_script("document.querySelector('div[role=dialog] ul').parentNode.scrollTop=" + scroll_top_num)
try:
WebDriverWait(driver, 1).until(check_difference_in_count)
except:
count = 0
break
__main__()
| true |
6ae7353f4c67c04c5eb875affb3a8c8b3d076245 | Python | starrye/LeetCode | /all_topic/esay_topic/605. 种花问题.py | UTF-8 | 1,783 | 3.90625 | 4 | [] | no_license | #!/usr/local/bin/python3
# -*- coding:utf-8 -*-
"""
@author:
@file: 605. 种花问题.py
@time: 2020/5/10 14:59
@desc:
"""
from typing import List
"""
假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。
示例 1:
输入: flowerbed = [1,0,0,0,1], n = 1
输出: True
示例 2:
输入: flowerbed = [1,0,0,0,1], n = 2
输出: False
注意:
数组内已种好的花不会违反种植规则。
输入的数组长度范围为 [1, 20000]。
n 是非负整数,且不会超过输入数组的大小。
"""
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
if not n:
return True
i = 0
length = len(flowerbed) - 1
while i <= length:
if i == length:
if flowerbed[i] == 0:
n -= 1
break
if flowerbed[i] == flowerbed[i+1] == 0:
n -= 1
if n == 0:
return True
i += 2
continue
elif flowerbed[i] == 1:
i += 2
continue
elif flowerbed[i+1] == 1:
i += 3
continue
return n == 0
a = Solution().canPlaceFlowers([1,0,0,0,1,0,0],2)
b = Solution().canPlaceFlowers([1,0,0,0,1],1)
c = Solution().canPlaceFlowers([0,0,1,0,0],1)
e = Solution().canPlaceFlowers([1],1)
print(a)
print(b)
print(c)
print(e) | true |
c6db308777366aabc66beaad84e0f22aa0b23a50 | Python | hezy10/myproject | /PyCharm 2017.3.2/自动化测试/执行js.py | UTF-8 | 450 | 2.5625 | 3 | [] | no_license | from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path=r'E:\chromdriver\chromedriver.exe')
ret = driver.get('https://www.baidu.com')
# new_str = "alert('ok')"
# driver.execute_script(new_str)
#
driver.find_element_by_name('wd').send_keys('图片')
driver.find_element_by_id('su').click()
time.sleep(2)
js = 'window.scrollTo(100,400)'
driver.execute_script(js)
driver.save_screenshot('d.png')
time.sleep(1)
driver.quit() | true |
65f2750fe7f440138f5fdbaa2a8a784429b4dee3 | Python | dunhe001/mycodes | /学者信息采集与清理/get_item_in_data.py | UTF-8 | 12,277 | 3.34375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import re
import pandas as pd
def clean_n(d_list):
'''去除列表里面的\n 和空字符'''
return [x.strip() for x in d_list if x.strip() != '']
def clean_null_list(d_list):
'''去除里面的空列表'''
return [x for x in d_list if len(x) > 0]
def clean_blank(d_list):
'''去除\xa0'''
return [x.replace(r'\xa0','') for x in d_list]
def find(data,item):
'''返回找到的字段的下标'''
return data.find(item)
def get_name(data):
t_index = find(data,'姓名')
if t_index > -1:
txt = data[t_index+2: t_index+15]
m = re.search(r'([\u4E00-\u9FA5]+)',txt)
if m:
return m.group(1)
else:
#要是没有找到,则在开头进行查找
m = re.search(r'([\u4E00-\u9FA5]+)',data)
if m:
return m.group(1)
return ''
def get_gender(data):
t_index = find(data,'性别')
if t_index > -1:
txt = data[t_index+2: t_index+6]
m = re.search(r'([\u7537|\u5973])',txt)
if m:
return m.group(1)
index2 = find(data,'男')
index3 = find(data,'女')
if index2 > -1 and (data[index2 - 1] < u'\u4E00' or data[index2 + 1] > u'\u9FA5'):
return '男'
if index3 > -1 and (data[index3 - 1] < u'\u4E00' or data[index3 + 1] > u'\u9FA5'):
return '女'
return ''
def get_birth(data):
'''处理情况:
出生年月 xxxx/ xxx 出生 / xxx生 / 大牛(1950- —) / 出生日期:\nxxx
'''
r1 = r'出生年月[::][\s\d\u4E00-\u9FA5]+'
r2 = r'[\d\u4E00-\u9FA5]+出生'
r3 = r'[\d\u4E00-\u9FA5]+生于'
#r4 = r'(\d+[-—]+.*?)'
r5 = r'出生日期[::][\s\d\u4E00-\u9FA5]+'
m1 = re.findall(r1,data)
m2 = re.findall(r2,data)
m3 = re.findall(r3,data)
#m4 = re.findall(r4,data)
m5 = re.findall(r5,data.replace(r'\n',''))
def find_birth(text):
data = re.findall(r'\d+',text)
if len(data) > 0: #在符合条件的匹配中检索数字
year = data[0]
if len(year) != 4:
return ''
if len(data) > 1:
month = data[1]
birth = str(year[:4]) + '年' + str(month) + '月' #预防199608的情况
else:
birth = str(year) + '年'
return birth
return ''
if len(m1) > 0:
birth = find_birth(m1[0])
if len(birth) > 0:
return birth
if len(m2) > 0:
birth = find_birth(m2[0])
if len(birth) > 0:
return birth
if len(m3) > 0:
birth = find_birth(m3[0])
if len(birth) > 0:
return birth
if len(m5) > 0:
birth = find_birth(m5[0])
if len(birth) > 0:
return birth
return ''
# t_index = find(data,'出生年月')
# if t_index > -1:
return ''
def get_xueli(data):
index1 = find(data,'硕士研究生')
index2 = find(data,'博士研究生')
i3 = find(data,'博士')
i4 = find(data,'硕士')
if index2 > -1:
return '博士研究生'
if i3 > -1:
return '博士研究生'
if index1 > -1:
return '硕士研究生'
if i4 > -1:
return '硕士研究生'
return ''
def get_xuewei(data):
r1 = r'([\u4E00-\u9FA5]+学博士)'
r2 = r'([\u4E00-\u9FA5]+学硕士)'
m1 = re.findall(r1,data)
m2 = re.findall(r2,data)
i1 = find(data,'博士')
i2 = find(data,'硕士')
# text = ''
text = []
if len(m1) > 0:
for item in m1:
if find(item,'得') > -1: #去掉‘获得’ ‘获’
item = item[find(item,'得') + 1:]
if find(item,'获') > -1:
item = item[find(item,'获') + 1:]
text.append(item)
if len(m2) > 0:
for item in m2:
if find(item,'得') > -1: #去掉‘获得’ ‘获’
item = item[find(item,'得') + 1:]
if find(item,'获') > -1:
item = item[find(item,'获') + 1:]
text.append(item)
text = list(set(text)) #去重
if len(text) == 0 and i1 > -1:
return '博士'
elif len(text) == 0 and i2 > -1:
return '硕士'
return '||'.join(text).strip('|')
def get_schools(data):
return ''
def get_zhicheng(data):
if find(data,'教授') > -1 and find(data,'副教授') == -1:
return '教授'
if find(data,'副教授') > -1:
return '副教授'
if find(data,'讲师') > -1:
return '讲师'
def get_xiaonei_zhiwu(data):
text = []
i1 = find(data,'是否博导:是')
i4 = find(data,'是否博导: 是')
i2 = find(data,'博士生导师')
i3 = find(data,'博士研究生导师')
if i1 > -1 or i2 > -1 or i3 > -1 or i4 > -1:
text.append('博士生导师')
t1 = find(data,'是否硕导:是')
t4 = find(data,'是否硕导: 是')
t2 = find(data,'硕士生导师')
t3 = find(data,'硕士研究生导师')
if t1 > -1 or t2 > -1 or t3 > -1 or t4 > -1:
text.append('硕士生导师')
return '||'.join(text).strip('|')
# t_index = find(data,'职务')
# if t_index > -1:
# txt = data[t_index+2: t_index+20]
# m = re.search(r'([\u4E00-\u9FA5]+)',txt)
# if m:
# return m.group(1)
# return ''
def get_email(data):
# 邮箱、电子邮箱、email、Email、EMAIL
m = re.search( r"([-_\w\.]{0,64}@([-\w]{1,63}\.)*[-\w]{1,63})",data)
if m:
return m.group(1)
return ''
def get_phone(data):
lists = ['电话','手机']
for item in lists:
i1 = find(data,item)
if i1 > -1 :
text = data[i1 + 2 : i1 + 20]
m = re.search(r"(\d+)",text)
if m:
return m.group(1).strip('\'')
return ''
def get_web(data):
i1 = find(data,'网址:')
if i1 == -1:
return ''
return data[i1+3:].strip()
def get_qita_zhiwu(data):
'''获取职务'''
r0 = r'[\u4e00-\u9fa5]+'
the_list = ['书记','院长','顾问','理事','会长','主任','主席']
content = []
for item in the_list:
r1 = r0 + item
match = re.findall(r1,data)
for i in match:
if i.find('任') > -1:
i = i[i.find('任')+1:]
if i.find('为') > -1:
i = i[i.find('为')+1:] # 是否加入这个指标待定
content.append(i.strip('\' , ;。'))
#去重
content = list(set(content))
return '||'.join(content).strip('|')
def get_education(data):
'''获取教育背景'''
r0 = r'[\d\u4e00-\u9fa5]+'
the_list = ['学士','硕士','博士,','博士后','硕导','博导','硕士生导师','博士生导师','教授']
content = []
for item in the_list:
r1 = r0 + item
match = re.findall(r1,data)
for i in match:
if i.find('学') == -1: #过滤
continue
if i.find('得') > -1:
i = i[i.find('得')+1:]
if i.find('获') > -1:
i = i[i.find('获')+1:]
if i.find('为') > -1:
i = i[i.find('为')+1:]
content.append(i.strip('\' ;,。'))
#去重
content = list(set(content))
return '||'.join(content).strip('|')
def get_field(data):
'''获取研究方向
处理情况:主要研究方向:|| 主要研究方向为 || 研究方向 xx || 研究领域:
只接受中文和中文顿号 去掉最后的 等'''
temp_list = re.findall('研究方向:[:、\s\u4e00-\u9fa5]+',data)
if len(temp_list) > 0:
temp = re.sub(r'\s+','',temp_list[0][5:]) #去空格、去定位项
if temp[-1] == '等':
temp = temp[:-1]
content = temp.split('、')
content = list(set(content)) #去重
return '||'.join(content).strip('|')
temp_list = re.findall('研究方向为[:\s\u4e00-\u9fa5、]+',data)
if len(temp_list) > 0:
temp = re.sub(r'\s+','',temp_list[0][5:]) #去空格、去定位项
if temp[-1] == '等':
temp = temp[:-1]
content = temp.split('、')
content = list(set(content)) #去重
return '||'.join(content).strip('|')
temp_list = re.findall('研究领域:[\s\u4e00-\u9fa5、]+',data)
if len(temp_list) > 0:
temp = re.sub(r'\s+','',temp_list[0][5:]) #去空格、去定位项
if temp[-1] == '等':
temp = temp[:-1]
content = temp.split('、')
content = list(set(content)) #去重
return '||'.join(content).strip('|')
return ''
def get_chengguo(data):
'''获取科研成果
处理情况:主持xxx 直到句号、分号'''
temp_list = re.findall('主持.*?[。;]',data)
content = []
if len(temp_list) > 0:
for temp in temp_list:
content.append(temp.strip('。 ;:'))
content = list(set(content)) #去重
return '||'.join(content).strip('|')
return ''
def get_timeline(data):
'''获取时间轴(出生/学习/工作
xx年xxxx 去掉过短的'''
temp_list = re.findall('\d{4}年.*?[。;\s]',data)
content = []
my_filter = ['获','任','参加','在','入选','学习','毕业','访','为'] #用于过滤匹配结果
if len(temp_list) > 0:
for temp in temp_list:
flag = True #用于标志过滤器
if len(temp) < 9: #去掉过短
continue
for item in my_filter:
if temp.find(item) > -1:
flag = False
break
if flag: #如果数据中不包含过滤器中的值,则跳过
continue
content.append(temp.strip('。;: '))
content = list(set(content)) #去重
return '||'.join(content).strip('|')
return ''
def get_dir_filenames(path,ftype):
'''获取目录下所有指定格式的文件名'''
import os
names = []
for root, dirs, files in os.walk(path):
for file in files:
if ftype in file:
names.append(file)
return names
def final_cleaning():
'''对汇总的财税学者信息进行进一步提取'''
df = pd.read_excel('财税学者信息汇总1.0.xls',sheet_name='概览')
new_datas = pd.DataFrame(columns=['姓名','性别','出生年月','学历','学位','职称','校内职务','其他职务','电子邮件','工作单位(院校)','学院','网址','教育背景','研究方向','成果','时间轴','所有信息'])
for index,row in df.iterrows():
if type(row['姓名']) == float:
continue
name = row['姓名'].strip()
employer = row['工作单位(高校)'].strip() if type(row['工作单位(高校)']) == str else ''
college = row['所属学院'] if type(row['所属学院']) == str else ''
if type(row['个人简介']) == float:
print(name + ' 没有学者信息详情,请详细比对')
continue
data = row['个人简介'].replace('\xa0','')
data1 = data.replace(' ','')
gender = get_gender(data)
birth = get_birth(data)
xueli = get_xueli(data)
xuewei = get_xuewei(data)
zhicheng = get_zhicheng(data)
xiaonei_zhiwu = get_xiaonei_zhiwu(data)
email = get_email(data1)
web = get_web(data)
zhicheng = get_zhicheng(data)
qita_zhiwu = get_qita_zhiwu(data)
education = get_education(data)
field = get_field(data)
chengguo = get_chengguo(data)
timeline = get_timeline(data)
all_message = data
row = {'姓名':name,'性别':gender,'出生年月':birth,'学历':xueli,'学位':xuewei,'教育背景':education,'所属学院':college,'职称':zhicheng,'校内职务':xiaonei_zhiwu,'电子邮件':email,'工作单位(院校)':employer,'网址':web,'其他职务':qita_zhiwu,'研究方向':field,'成果':chengguo,'时间轴':timeline,'所有信息':all_message}
new_datas = new_datas.append(row,ignore_index=True)
new_datas.to_excel('财税学者信息深度.xlsx')
print('finish..')
#注意: 博士后、博士 信息会重叠
final_cleaning()
| true |
9a61022b6dfead01c8ba079bda89ffc15e0d2318 | Python | AlexBrin/HostsEditor | /hostseditor/log.py | UTF-8 | 430 | 2.8125 | 3 | [
"MIT"
] | permissive | import hostseditor.color as color
def error(text, separator=' + '):
print(color.RED + separator + "Error: " + color.NULL + text)
def info(text, separator=' + '):
print(color.BLUE + separator + color.NULL + text)
def warn(text, separator=' + '):
print(color.YELLOW + separator + "Error: " + color.NULL + text)
def success(text, separator=' + '):
print(color.RED + separator + "Error: " + color.NULL + text)
| true |
19dc27c6223d76e4721fa36c10250746bf0358af | Python | punitjha/CHEM_548_Project_2 | /feaux.py | UTF-8 | 163 | 2.671875 | 3 | [] | no_license | #!/usr/bin/python
import numpy as np
eigs1 = np.loadtxt('eigen1.txt')
eigs2 = np.loadtxt('eigen2.txt')
for i in range(len(eigs1)):
print(eigs2[i] - eigs1[0])
| true |
ed6e450eae82b7cdb58b42c578b3f7f95851f738 | Python | Soontrax/Programacion-Python | /Practica5/Ejercicio6.py | UTF-8 | 341 | 3.9375 | 4 | [] | no_license | a = input("Escribe un numero:")
b = input("Escribe un numero mayor que %d: \n" %a)
w = []
while b<=a:
b = input("Escribe un numero mayor que %d: \n" %a)
c = input("Escribe un numero entre" + str(a) + "y" + str(b) + ":")
while a<= c <=b:
w.append(c)
c = input("Escribe otro entre" + str(a) + "y" + str(b) + ":")
print w
| true |
ab99b3cc191d173b08bd9bf42e3e7280933943c2 | Python | dougtc1/algorithms1 | /Python/Laboratorio-3/Lab03Ejercicio1fail.py | UTF-8 | 1,726 | 4.125 | 4 | [] | no_license | #
# Lab03Ejercicio1.py
#
# Descripcion: Este programa permite al usuario escoger una opcion de un menu
# de tres opciones
# Autor: Douglas Torres
# Ultima modificacion: 29/04/2014
#
# Variables:
# seleccion : integer //
# resultado : float //
# largo : float //
# ancho : float //
# radio : string //
# n : boolean //
#
# Entrada de datos
resultado = 0
seleccion = int(input("Se le presentan 3 opciones: \n" \
"Opcion 1: Superficie de una habitacion \n" \
"Opcion 2: Area de una circunferencia \n" \
"opcion 3: Suma de cuadrados \n"))
if (seleccion == 1):
largo = float(input("Introduzca el largo de la habitacion: "))
ancho = float(input("Introduzca el ancho de la habitacion: "))
elif (seleccion == 2):
radio = float(input("Introduzca el radio de la circunferencia: "))
elif (seleccion == 3):
n = int(input("Introduzca un numero natural: "))
# Precondicion
try:
assert ((((seleccion == 1) and largo >= 0 and ancho >=0) or \
((seleccion == 2) and radio >= 0) or \
((seleccion == 3) and n > 0)))
except AssertionError:
print ("La Precondicion no se cumple")
# Calculo de datos
if (seleccion == 1):
resultado = largo*ancho
elif (seleccion == 2):
resultado = radio*radio*3,1416
elif (seleccion == 3):
resultado = sum(x**2 for x in range (1,n+1))
# Postcondicion
assert (((seleccion==1) and resultado==largo*ancho and resultado>=0) or \
((seleccion==2) and resultado==radio*radio*3,1416 and resultado>=0) or \
((seleccion == 3) and resultado==sum(x*x for x in range (1,n+1))))
# Salida de datos
print("El resultado de la opcion escogida es:",resultado)
| true |
2f743498897bfc609265ed8fe1e1343ed1578aa5 | Python | vinodrajendran001/nlp | /syllables.py | UTF-8 | 178 | 2.5625 | 3 | [] | no_license | from nltk.corpus import cmudict
d = cmudict.dict()
def max_syl(word):
if word not in d: return None
return max([len([y for y in x if y[-1].isdigit()]) for x in d[word]])
| true |
bcaef77b95b8ce10204a25abaf302c69a57742a6 | Python | yodeng/sw-algorithms | /pythonic/array_questions/circular_counter.py | UTF-8 | 801 | 4 | 4 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env python
# encoding: utf-8
"""
@author: swensun
@github:https://github.com/yunshuipiao
@software: python
@file: circular_counter.py
@desc: 约瑟夫环
@hint: 一般解法和动态规划
"""
# 简单方法:每次移除删除的元素并打印出来:O()
def circular_counter(n, m):
temp = [i for i in range(1, n + 1)]
i = 0
while len(temp) > 1:
i = (i + m - 1) % len(temp)
temp.pop(i)
print(temp[0])
# 动态规划:找状态转移方程
def circular_counter_two(n, m):
if n < 1 or m < 1:
return -1
win_index = [0] * (n + 1)
for i in range(2, n + 1): # [2: n]
win_index[i] = (win_index[i - 1] + m) % i
print(win_index[n] + 1)
if __name__ == '__main__':
circular_counter(9, 3)
circular_counter_two(9, 3) | true |
dc8dc23026fc3a8022a1e4fcfc7c446918c341b8 | Python | alexisdeveloper-oui/devoirDidi | /main.py | UTF-8 | 2,399 | 3.5625 | 4 | [] | no_license | from PIL import Image
import glob
i = 0
flag = False
list_of_pictures = glob.glob('pictures/*.jpg')
def resize(width, height) -> object:
"""
:param width: La largeur de la photo
:param height: La hauteur de la photo
:return: message de confirmation
"""
nouvelle_image = image.resize((width, height))
nouvelle_image.save("pictures/" + file.split('.')[0] + "(" + str(width) + "x" + str(height) + ").jpg")
return "Image recadrée"
if len(list_of_pictures) != 0: # Check if there's pictures in the folder
print("il y a " + str(len(list_of_pictures)) + " photos dans le dossier\n")
for picture in list_of_pictures:
image = Image.open(picture)
# The file format of the source file.
print(image.format) # Output: JPEG
file = image.filename.split('\\')[1]
print(file)
w, h = image.size
if w == h: # Check if the photo's resolution is square
print("la photo " + file + " est carrée et peut être recadrée")
flag = True
elif (h - h * .10) <= w <= (h + h * .10): # if it's not square, it will check if the width is within a 10%
# margin of the height
# im bad at explaining
print(
"La photo " + file + " n'est pas vraiment carrée, mais elle peut quand même être resize sans « effouarage »")
choix2 = int(input("Appuyez sur 1 pour oui, n'importe quel autre chiffre pour non\n")) # asking user
if choix2 == 1:
flag = True
else:
flag = False
print("Cette photo ne peut définitivement pas être recadrée")
if flag:
print("Choisissez l'une des trois options")
choix = int(input("1 : 200x200 et 800x800\n2 : 172x172 \n3: Résolution custom\n4: Ne rien faire\n\n"))
if choix == 1:
print(resize(200, 200))
print(resize(800, 800))
elif choix == 2:
print(resize(172, 172))
elif choix == 3:
res = int(input(("Entrez hauteur : ")))
print(resize(res, res))
else:
print("y faut rien recadrer")
print("\n\n")
else:
print("Veuillez créer un dossier pictures et ajouter des photos en jpg dedans. Le script ne détecte aucune photo "
"dans ce format")
| true |
d72e57279e399cdb8f14ce78702e57c1b5654321 | Python | kiba0510/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | UTF-8 | 519 | 3.703125 | 4 | [] | no_license | #!/usr/bin/python3
'''
Module defining function add_integer
'''
def add_integer(a, b=98):
"""
Function that sums 2 integers
a (int or float)
b (int or float)
"""
if not isinstance(a, int) and not isinstance(a, float):
raise TypeError("a must be an integer")
if not isinstance(b, int) and not isinstance(b, float):
raise TypeError("b must be an integer")
return int(a + b)
if __name__ == "__main__":
import doctest
doctest.testfile("tests/0-add_integer.txt")
| true |
ea29430eff02df01a81644622744a09806445d24 | Python | innovatorved/BasicPython | /Python Programs/13. series.py | UTF-8 | 194 | 3.875 | 4 | [] | no_license | #print the series from 1 to 10
def series(x):
i=0
while(i<=x):
print(i)
i=i+1
return
while(1):
a=int(input('Enter a number : '))
print(series(a))
| true |
71f3e3482762e8fdb4f8689a5a254100a9a832c7 | Python | degentech/magicbutton | /contracts/mockQPToken.py | UTF-8 | 3,786 | 2.578125 | 3 | [] | no_license | import smartpy as sp
class FA12_Error:
def make(s): return ("FA1.2_" + s)
NotAdmin = make("NotAdmin")
InsufficientBalance = make("InsufficientBalance")
UnsafeAllowanceChange = make("UnsafeAllowanceChange")
Paused = make("Paused")
NotAllowed = make("NotAllowed")
class FA12Mock(sp.Contract):
def __init__(self, **extra_storage):
self.init(
balances = sp.big_map(tvalue = sp.TRecord(approvals = sp.TMap(sp.TAddress, sp.TNat), balance = sp.TNat)),
totalSupply = 0,
**extra_storage
)
@sp.entry_point
def withdrawProfit(self, params):
sp.set_type(params, sp.TAddress)
sp.send(params, sp.balance)
@sp.entry_point
def default(self):
pass
@sp.entry_point
def transfer(self, params):
sp.set_type(params, sp.TRecord(from_ = sp.TAddress, to_ = sp.TAddress, value = sp.TNat).layout(("from_ as from", ("to_ as to", "value"))))
sp.verify((((params.from_ == sp.sender) |
(self.data.balances[params.from_].approvals[sp.sender] >= params.value))), FA12_Error.NotAllowed)
self.addAddressIfNecessary(params.from_)
self.addAddressIfNecessary(params.to_)
sp.verify(self.data.balances[params.from_].balance >= params.value, FA12_Error.InsufficientBalance)
self.data.balances[params.from_].balance = sp.as_nat(self.data.balances[params.from_].balance - params.value)
self.data.balances[params.to_].balance += params.value
sp.if (params.from_ != sp.sender):
self.data.balances[params.from_].approvals[sp.sender] = sp.as_nat(self.data.balances[params.from_].approvals[sp.sender] - params.value)
@sp.entry_point
def approve(self, params):
sp.set_type(params, sp.TRecord(spender = sp.TAddress, value = sp.TNat).layout(("spender", "value")))
self.addAddressIfNecessary(sp.sender)
alreadyApproved = self.data.balances[sp.sender].approvals.get(params.spender, 0)
self.data.balances[sp.sender].approvals[params.spender] = params.value
def addAddressIfNecessary(self, address):
sp.if ~ self.data.balances.contains(address):
self.data.balances[address] = sp.record(balance = 0, approvals = {})
@sp.utils.view(sp.TNat)
def getBalance(self, params):
sp.if self.data.balances.contains(params):
sp.result(self.data.balances[params].balance)
sp.else:
sp.result(sp.nat(0))
@sp.utils.view(sp.TNat)
def getAllowance(self, params):
sp.if self.data.balances.contains(params.owner):
sp.result(self.data.balances[params.owner].approvals.get(params.spender, 0))
sp.else:
sp.result(sp.nat(0))
@sp.utils.view(sp.TNat)
def getTotalSupply(self, params):
sp.set_type(params, sp.TUnit)
sp.result(self.data.totalSupply)
@sp.entry_point
def mint(self, params):
sp.set_type(params, sp.TRecord(address = sp.TAddress, value = sp.TNat))
self.addAddressIfNecessary(params.address)
self.data.balances[params.address].balance += params.value
self.data.totalSupply += params.value
@sp.entry_point
def burn(self, params):
sp.set_type(params, sp.TRecord(address = sp.TAddress, value = sp.TNat))
sp.verify(self.data.balances[params.address].balance >= params.value, FA12_Error.InsufficientBalance)
self.data.balances[params.address].balance = sp.as_nat(self.data.balances[params.address].balance - params.value)
self.data.totalSupply = sp.as_nat(self.data.totalSupply - params.value)
if __name__ == "__main__":
sp.add_compilation_target("FA12", FA12Mock())
| true |
0661f68e47a54f821e3e006b2cb8cb18a3d24843 | Python | QDylan/Learning- | /Leetcode/81. 搜索旋转排序数组 II.py | UTF-8 | 1,494 | 4.1875 | 4 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""
@Time : 2020/6/30 22:31
@Author : QDY
@FileName: 81. 搜索旋转排序数组 II.py
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] )。
编写一个函数来判断给定的目标值是否存在于数组中。若存在返回 true,否则返回 false。
示例 1:
输入: nums = [2,5,6,0,0,1,2], target = 0
输出: true
示例 2:
输入: nums = [2,5,6,0,0,1,2], target = 3
输出: false
进阶:
这是 搜索旋转排序数组 的延伸题目,本题中的 nums 可能包含重复元素。
这会影响到程序的时间复杂度吗?会有怎样的影响,为什么?
"""
class Solution:
def search(self, nums, target):
n = len(nums)
l, r = 0, n - 1
while l <= r:
m = l + (r - l) // 2
if nums[m] == target:
return True
if nums[m] == nums[l]:
l += 1
continue
if nums[m] > nums[l]: # 左边是有序的
if nums[m] > target and nums[l] <= target:
r = m - 1
else:
l = m + 1
elif nums[m] < nums[l]: # 右边是有序的
if nums[m] < target and nums[r] >= target:
l = m + 1
else:
r = m - 1
return False
| true |
c7f51414d0751d76c34136a6b3539fa558c31084 | Python | Saykon-k/pit | /4_semester/comp_grafic/labS/labS_pil/1_lab/solve/gistagram_roof.py | UTF-8 | 767 | 2.84375 | 3 | [] | no_license | from PIL import Image, ImageDraw
image = Image.open("../files/roof.JPG")
draw = ImageDraw.Draw(image)
width = image.size[0]
height = image.size[1]
pix = image.load()
green = 256*[0]
red = []
blue = []
for x in range(width):
for y in range(height):
a = pix[x, y][0]
b = pix[x, y][1]
c = pix[x, y][2]
green[b]+=1
red.append(a)
blue.append(c)
gr= height/(max(green)*2)
print(max(green),' ',gr,' ',height,' ',max(green)*gr)
for i in range(256):
green[i]=round(gr*green[i])
for x in range(256):
for y in range(height):
if y > height/2-green[x]:
if y < height/2:
draw.point((x,y),(0,255,0))
image.save("F:/pit/4 semestr/comp_grafic/lab_1/out//green_kom.jpg")
del draw
| true |
5a6462731d172fd92532d6569ecdb7c20ec5be10 | Python | johnrdowson/py-spectrum | /pyspectrum/attributes.py | UTF-8 | 1,831 | 2.578125 | 3 | [
"MIT"
] | permissive | from enum import IntEnum
def attr_name_to_id(attr_name: str) -> int:
"""
Attempts to lookup the attribute ID (hex) from the name. If no match is
found, the name is assumed to be a hexadecimal (as string), and is therefore
returned as an integer type. Otherwise, the lookup fails.
"""
try:
return SpectrumModelAttributes[attr_name.upper()].value
except KeyError:
try:
return int(str(attr_name), 0)
except ValueError:
raise ValueError(
f"'{attr_name}' is not a recognised Spectrum attribute name or "
f"valid ID."
)
def attr_id_to_name(attr_id: int) -> str:
"""
Attempts to match the attribute ID to the corresponding name. If no match
found, the ID is returned as a hexadecimal in string format.
"""
try:
return SpectrumModelAttributes(int(attr_id, 0)).name.lower()
except ValueError:
return hex(int(attr_id, 0))
class SpectrumModelAttributes(IntEnum):
""" Attribute name to ID mappings """
COLLECTIONS_MODEL_NAME_STRING = 0x12ADB
CONDITION = 0x1000A
DEVICE_TYPE = 0x23000E
IS_MANAGED = 0x1295D
LAST_SUCCESSFUL_POLL = 0x11620
MANUFACTURER = 0x10032
MDL_CREAT_TIME = 0x1102A
MODEL_CLASS = 0x11EE8
MODEL_HANDLE = 0x129FA
MODEL_NAME = 0x1006E
MODEL_TYPE_HANDLE = 0x10001
MODEL_TYPE_NAME = 0x10000
NCM_DEVICE_FAMILY_INDEX = 0x12BEF
NCM_POTENTIAL_COMM_MODES = 0x12BEB
NCM_SELECTED_COMM_MODE = 0x12BEC
NETWORK_ADDRESS = 0x12D7F
SERIAL_NUMBER = 0x10030
SYS_DESC = 0x10052
SYS_LOCATION = 0x1102E
TOPOLOGY_MODEL_NAME_STRING = 0x129E7
def __str__(self) -> str:
return hex(self.value)
def __repr__(self) -> str:
return f"{str(self.name).lower()}: {hex(self.value)}"
| true |
6afefcc3ed76f7c30367f66a1c72e051c3452c86 | Python | ChenliangLi205/LeetCode | /Q103BinaryTreeZigzagLevelOrderTraversal.py | UTF-8 | 1,169 | 3.15625 | 3 | [
"MIT"
] | permissive | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None:
return []
activeNodes = [root]
results = []
right2left = False
while True:
newActive = []
subResults = []
if not any(activeNodes):
break
for i in range(len(activeNodes)-1, -1, -1):
if activeNodes[i] is not None:
subResults.append(activeNodes[i].val)
if right2left:
newActive.append(activeNodes[i].right)
newActive.append(activeNodes[i].left)
else:
newActive.append(activeNodes[i].left)
newActive.append(activeNodes[i].right)
right2left = not right2left
results.append(subResults)
activeNodes = newActive
return results | true |
60854e8ae17338375cf8e32eb1111dda7357dfc8 | Python | gear106/leetcode | /13. Roman to Integer.py | UTF-8 | 711 | 3.609375 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 21:08:13 2018
@author: GEAR
"""
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
lookup = {
'M':1000,
'D':500,
'C':100,
'L':50,
'X':10,
'V':5,
'I':1
}
res = 0
for i in range(len(s)):
if i > 0 and lookup[s[i]] > lookup[s[i-1]]:
res = res + lookup[s[i]] - 2 * lookup[s[i-1]]
else:
res += lookup[s[i]]
return res
s = Solution()
string = 'IV'
print(s.romanToInt(string))
| true |
b72e4dc55017bf543bf91250b7eeeef5a1b2271c | Python | Nikotiin/kuvat-api | /kuvat_api/api.py | UTF-8 | 2,830 | 3.078125 | 3 | [
"MIT"
] | permissive | """
Raw JSON API of kuvat.fi
"""
from requests import Session, RequestException
from .exceptions import ConnectionException, AuthenticationException
class Api:
"""
Api encapsulates HTTP client
"""
def __init__(self, base_url):
"""
:param base_url: URL of kuvat.fi site
"""
self.base_url = base_url
self.http_client = Session()
def get_directories(self):
"""
Get all directories
:return: JSON object of directories
"""
params = {"type": "getFolderTree"}
data = {"folder": ""}
try:
response = self.http_client.post(self.base_url, params=params, data=data)
return response.json()
except RequestException as exception:
raise ConnectionException(str(exception))
def get_files(self, folder):
"""
Get all files from folder
:param folder: kuvat.fi folder
:return: JSON object of files
"""
params = {"type": "getFileListJSON"}
data = {"folder": folder}
try:
response = self.http_client.post(self.base_url, params=params, data=data)
return response.json()
except RequestException as exception:
raise ConnectionException(str(exception))
def authenticate(self, id_, password):
"""
Authenticate user
:param id_: ID of the directory
:param password: Password
:return: JSON object of result of authentication
"""
params = {"q": "folderpassword", "id": id_, "folderpassword": password}
try:
response = self.http_client.get(self.base_url, params=params)
return response.json()
except RequestException as exception:
raise ConnectionException(str(exception))
def get_bytes(self, path):
"""
Get file bytes
:param path: Path of the file
:return: Bytearray of file bytes
"""
response = self.__get_file(path)
return response.content
def save_file(self, path, savepath):
"""
Save file to disk
:param path: Path of the kuvat.fi file
:param savepath: Path, where file should be saved
"""
response = self.__get_file(path)
with open(savepath, 'wb') as file:
for chunk in response.iter_content():
file.write(chunk)
def __get_file(self, path):
params = {"img": "full"}
try:
response = self.http_client.get(self.base_url + path, params=params)
if response.status_code == 403:
raise AuthenticationException("403 Forbidden")
return response
except RequestException as exception:
raise ConnectionException(str(exception))
| true |
7e08540020a3ccd76010b33bfaadb776585be3f8 | Python | eomjinyoung/bigdata3 | /bit-python01/src08/ex02/test03.py | UTF-8 | 1,011 | 4.1875 | 4 | [] | no_license | # 함수 - call by value 와 call by reference II
# - immutable 값을 넘기면 call by value 가 된다.
# - mutable 값을 넘기면 call by reference 가 된다.
print("1-----------------------")
# call by reference
def f1(a):
a[0] = 100;
l1 = [1, 2, 3]
f1(l1) # 리스트의 주소가 넘어간다.
print(l1)
# 만약 리스트를 call by value 식으로 다루고 싶다면
# 복사본을 넘겨라
l2 = [1, 2, 3]
f1(l2[:])
print(l2)
t1 = (1, 2, 3)
# 튜플의 주소가 넘어간다.
# 그러나 튜플의 값을 변경할 수 없기 때문에
#f1(t1) # 오류 발생!
print("2-----------------------")
def f2(d):
d['tel'] = '1111-2222'
d1 = {
'name': '홍길동',
'age': 20,
'working': True,
}
f2(d1) # 딕셔너리의 주소를 넘긴다.
print(d1)
print("3-----------------------")
def f3():
return {'name': '홍길동', 'age': 20}
d2 = f3()
print(d2)
| true |
67e134ab6aeae4895c7a7ab346e8307f09007cbe | Python | K1ngfreak/functions_tryout | /hello_world.py | UTF-8 | 160 | 3.390625 | 3 | [] | no_license | def helloWorld(y):
x = 0
for i in range(0,y):
x = x + 1
print(str(x) + '. ' + 'Hello World!')
g = int(input('aantal: '))
helloWorld(g) | true |
64995794b185789e3dbe22aa84809705d524aee1 | Python | pianowow/various | /pythonchallenge.com/3.py | UTF-8 | 695 | 3.046875 | 3 | [] | no_license | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: CHRISTOPHER_IRWIN
#
# Created: 22/01/2013
import string, re
f = open('3.txt').read()
f = f.replace('\n','')
upper = string.ascii_uppercase
lower = string.ascii_lowercase
length = len(f)
sol = ''
for i,c in enumerate(f):
found = True
if i < length - 9:
test = f[i:i+9]
if test[4] in lower and test[0] in lower and test[8] in lower:
for x in test[1:4]+test[5:8]:
if x not in upper:
found = False
if found:
sol += test[4]
print(sol) | true |
aead43fa5228064dabe57bca51e5f2ed4adfa6e1 | Python | teletype3/ex_pe_codAby | /codeabbey/11.py | UTF-8 | 247 | 2.765625 | 3 | [] | no_license | b = 0
with open('data.txt', 'r') as data:
for i in data.readlines():
a = i.split(' ')
r = str(int(a[0])*int(a[1])+int(a[2]))
for x in r:
b += int(x)
print(b, end=' ')
b = 0 | true |
96b7bd08623db6077605d6df48d963c37d546b7c | Python | KrisAsante/Unit-8-01 | /car_program.py | UTF-8 | 458 | 3.5 | 4 | [] | no_license | # Created by: Chris Asante
# Created on: 3-April-2019
# Created for: ICS3U
# Unit 8-01
# This main program will create a car object
from car import *
#create a vehicle
car1 = Car()
car2 = Car()
print(car1.current_state())
car1.accelerate(100)
print(car1.current_state())
car1.brake(50)
print(car1.current_state())
print(car2.current_state())
car2.accelerate(50)
print(car2.current_state())
car2.accelerate(160)
print(car2.current_state()) | true |
88f6510f88b44bbd1e3664a4f212c1cb5a3d2c1b | Python | johnboscor/codingpractice | /test-test.py | UTF-8 | 741 | 3.265625 | 3 | [] | no_license | A = [ [1, 3, 5], [2, 6, 9], [3, 6, 9]]
C = [ list(i) for i in zip(*A)]
print(C)
from math import log
print(log(8,2))
A = [1, 2, 3, 4, 5]
A = "cat"
B = {"A":1, "B":2}
print(''.join(sorted(A)))
print(B["A"])
A=15
binary = bin(256)[2:].zfill(32)
print(binary)
A = [1, 2, 3, 4, 5]
A = A[4:] + A[:3]
print(A)
file1 = open("test-file",'w')
file1.write("hello123\n")
file1.close()
file1 = open("test-file",'r')
for line in file1.readlines():
print(line)
#num1 = 6, num2 = 3
def findGcd(num1, num2):
if num1 < num2:
num2, num1 = num1, num2
while num2 != 0:
temp = num2
num2 = num1%num2
num1 = temp
return num1
num1 = 10
num2 = 2
print(f'gcd of {num1} and {num2} is {findGcd(num1,num2)}')
| true |
8bc25cd29262dc0aff509f3f2abb0480fe7c3150 | Python | hankerbit/learning-based-RRT | /2link_NN/old/kNN_control_fulltraj.py | UTF-8 | 1,317 | 2.546875 | 3 | [
"MIT"
] | permissive | import sys
import numpy
from sklearn.neighbors import KNeighborsRegressor
from sklearn.externals import joblib
from sklearn.metrics import mean_squared_error
from numpy.random import seed
seed(1)
if len(sys.argv) == 4:
num_data = str(sys.argv[1])
type_data = str(sys.argv[2])
rep_parameter = str(sys.argv[3])
data = '../training_data/final_data/final_control_ft_2_' + num_data + 'k_' + type_data + '_' + rep_parameter
#load data
X_train,Y_train,X_validate,Y_validate,coeff = joblib.load(data)
#open file to save metrics
to_file = open('../trained_models/' + type_data + '_knn_control_' + num_data + '_' + rep_parameter + '.txt', 'a')
for num_neigh in range(5,10):
print 'no. of neighbours = ',num_neigh
#kNN training
knn = KNeighborsRegressor(n_neighbors=num_neigh)
knn.fit(X_train, Y_train)
#validate and compute the mean squared error
predictions = knn.predict(X_validate)
mse = mean_squared_error(Y_validate,predictions)
print "mse =", mse
to_file.write('%s %s \n' % (num_neigh, mse))
#save kNN
joblib.dump(knn, '../trained_models/knn/control/knn_control_ft_2_' + num_data + 'k_' + type_data + '_' + rep_parameter + '_' + str(num_neigh))
else:
print 'Incorrect no. of arguments'
| true |
03771bbbe577f1aeaa3ec1e043b8ff2741a09d20 | Python | naoland/nemlog-55579 | /flow.py | UTF-8 | 2,504 | 3.265625 | 3 | [
"CC0-1.0"
] | permissive | """
ZEMの最終価格をZaif取引所のAPIから取得して、その結果によって異なるフローチャートを生成します。
出力形式はPNGやJPG、SVG、PDFなどを指定できます。
"""
import sys
from graphviz import Digraph
from zaifapi import ZaifPublicApi, ZaifFuturesPublicApi, ZaifLeverageTradeApi
FILENAME: str = "dist/flow.dot"
DEBUG: bool = True
THRESHOLD: float = 40.0
def last_price(pair: str = "xem_jpy") -> float:
"""指定した通貨ペア(xem_jpyなど)の最終価格を取得して返します。"""
zaif = ZaifPublicApi()
result = zaif.last_price(pair)
# print(type(result["last_price"]))
if type(result["last_price"]) == float:
return result["last_price"]
else:
return float(result["last_price"])
def flow(price: float, format: str = "png", comment: str = "") -> None:
""" `price`の価格によって、異なるフローチャートを生成します。"""
dot = Digraph(format=format, comment=comment)
dot.node("start", "開始")
dot.node("step1", "NEM(XEM)の最終価格を取得します", shape="box")
if price >= THRESHOLD:
dot.node(
"step2",
str(f"取得結果:{price} JPY"),
shape="oval",
style="filled",
fillcolor="lightcyan",
)
else:
dot.node(
"step2",
str(f"取得結果:{price} JPY"),
shape="oval",
style="filled",
fillcolor="orange",
)
dot.node("step3", "40.0JPY以上ですか?", shape="diamond")
dot.node("end", "終了")
dot.edge("start", "step1")
dot.edge("step1", "step2")
dot.edge("step2", "step3")
if price >= THRESHOLD:
dot.node("step4-y", "売り時を待つ", shape="box")
dot.edge("step3", "step4-y", label=" YES")
dot.edge("step4-y", "end")
else:
dot.node("step4-n", "買い増しを検討する", shape="box")
dot.edge("step3", "step4-n", label=" NO")
dot.edge("step4-n", "end")
# view=Trueの場合はOSに指定されているデフォルトの画像ビューワーが起動します。
dot.render(FILENAME, view=False)
if __name__ == "__main__":
try:
price = last_price("xem_jpy")
message = f"XEM現在価格: {price} JPY"
if DEBUG:
print(message)
flow(price, format="png")
except:
print(f"エラーが発生しました: {sys.exc_info()}")
| true |
fa9687d1f66506d1da7820522dff82ab3371b17a | Python | pmarcol/Python-excercises | /Python - General/List/11-20/excercise11.py | UTF-8 | 434 | 4.125 | 4 | [] | no_license | """
Write a Python function that takes two lists and returns True if they have at least one common member.
"""
"""
SOLUTION:
"""
def haveCommon(list1, list2):
return bool( set(list1) & set(list2) )
myList1 = [1,2,3]
myList2 = [3,4,5]
myList3 = [5,6,7]
print(haveCommon(myList1, myList2)) # True
print(haveCommon(myList2, myList3)) # True
print(haveCommon(myList1, myList3)) # False
print(haveCommon([], myList1)) # False | true |
358d9857e04d6f9c50f7f8552121ca58202df64c | Python | SaideepGona/Thesis-Code---2016 | /Thesis_Sort.py | UTF-8 | 4,921 | 2.890625 | 3 | [] | no_license | import numpy as np
def initialize(input_matrix):
print(type(input_matrix))
def set_2_list(set_object):
new_list = []
for x in set_object:
new_list.append(x)
return new_list
def all_possible(input_matrix):
column_sets = []
for x in np.arange(len(input_matrix[0])):
column = []
for y in np.arange(len(input_matrix)):
column.append(input_matrix[y][x])
set_var = set(column)
unset_var = set_2_list(set_var)
column_sets.append(unset_var)
unset_column_sets = []
for set_val in column_sets:
unset_column_sets.append(set_val)
return unset_column_sets
def search_list(input_matrix, values_matrix):
def position_check(row_position, row_matrix, values_matrix):
check = 0
for y in values_matrix[row_position]:
print (y, row_matrix[row_position])
if y == row_matrix[row_position] or None:
check = 1
print ('hi')
return check
return check
gene_list = []
full_gene_list = []
full_list = []
for row in input_matrix:
for row_position in np.arange(len(row)):
#print(position_check(row_position, row, values_matrix))
if position_check(row_position, row, values_matrix) == 0:
break
gene_list.append(row[0])
full_gene_list.append(row[0])
full_list.append(row)
set_gene_list = set(gene_list)
unset_gene_list = set_2_list(set_gene_list)
return (unset_gene_list, full_gene_list, full_list)
#def create_set_or(input_matrix, values_matrix):
#
# gene_list = []
# full_gene_list = []
# stop = 0
#
# for w in np.arange(len(values_matrix)):
# if stop == 1:
# break
# for x in values_matrix[w]:
# for y in input_matrix:
# for z in y:
# if x != None:
# stop = 1
# post_w_values = values_matrix[w + 1: len(values_matrix)]
# print (post_w_values)
# if x == z:
# print ('hi')
# contains = 0
# for w_1 in post_w_values:
# for x_1 in w_1:
# if search(w_1,x):
# contains = 1
# if contains == 1:
# gene_list.append(x[y][0])
# full_gene_list.append(x[y][0])
#
# set_gene_list = set(gene_list)
# unset_gene_list = set_2_list(set_gene_list)
#
# return (unset_gene_list, full_gene_list)
# Cleanup removes a provided list of values from a provided list
def cleanup(gene_list, removal_list):
clean_gene_list = gene_list[:]
for x in removal_list:
for z in gene_list:
if x == z:
clean_gene_list.remove(z)
return clean_gene_list
# Counter counts the number of repeats for each gene based on the original gene list.
# Returns a dictionary with gene names as keys, and their counts as values
def counter(starting_matrix, clean_gene_list):
gene_counts = []
for x in clean_gene_list:
counter = 0
for y in starting_matrix:
if x == y:
counter = counter + 1
gene_counts.append(counter)
gene_count_dictionary = dict(zip(clean_gene_list, gene_counts))
return gene_count_dictionary
# Main Body
# Read in the data (Pre-processed Article_List)
starting_matrix = np.genfromtxt('Article_List.csv', dtype = ('U10','U10','U10','U10','U10','U10'), delimiter=',', skip_header = 1)
# List all possible values from the starting matrix
column_sets_list = all_possible(starting_matrix)
# Given a list of values, generates a list of all pertinent gene data
values = [[],[], ['S','M'],[],[],['T']] # Exposure Types
#values = ['M'] # Exposure Type: Metals
(set_thing, raw_gene_list, full_list) = search_list(starting_matrix, values)
# Given a list of genes, removes the genes from a given gene list
clean_set_thing = cleanup(set_thing, [ 'xa' , 'blank' ])
# Counts the number of gene repeats in the value-based
count_dict = counter(raw_gene_list, clean_set_thing)
print(count_dict, 'Values:', values)
print(len(count_dict))
| true |