repo_name
stringclasses 400
values | branch_name
stringclasses 4
values | file_content
stringlengths 16
72.5k
| language
stringclasses 1
value | num_lines
int64 1
1.66k
| avg_line_length
float64 6
85
| max_line_length
int64 9
949
| path
stringlengths 5
103
| alphanum_fraction
float64 0.29
0.89
| alpha_fraction
float64 0.27
0.89
|
|---|---|---|---|---|---|---|---|---|---|
ChanJeunlam/eddy_wave
|
refs/heads/master
|
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
plt.ion()
f0 = 1e-4
u0 = 0.5
R0 = 40e3 # radius
vmax = 0.5 # m/s
def v1(rr):
v = -vmax*rr/R0*np.exp(-0.5*(rr/R0)**2)
# v = -vmax*np.tanh(rr/R0)/(np.cosh(rr/R0))**2/(np.tanh(1.0)/(np.cosh(1.0))**2)
return v
def dv1(rr):
v = -vmax/R0*np.exp(-0.5*(rr/R0)**2)*(1-(rr/R0)**2)
# v = -vmax*2/R0*np.tanh(rr/R0)/((np.cosh(rr/R0))**2)*(1/(np.cosh(rr/R0))**2 - (np.tanh(rr/R0))**2)/(np.tanh(1.0)/(np.cosh(1.0))**2)
return v
def f(r, t):
omega = np.sqrt((dv1(r)+v1(r)/r + f0)*(2*v1(r)/r + f0))
return u0*np.sin(omega*t)
si_r = 30
si_t = 100000
r0 = np.linspace(1,5*R0,si_r)
t = np.linspace(0, si_t/f0/1000, si_t)
ra = np.zeros((si_t,si_r))
for ni in range(0,si_r):
ra[:,ni] = integrate.odeint(f, r0[ni], t).squeeze()
plt.figure()
plt.plot(t*f0/(2*np.pi),ra/R0,'k',linewidth=1)
plt.xlabel('t*f/2pi')
plt.ylabel('r/R0')
|
Python
| 41
| 22.170732
| 133
|
/analysis/ode_wave.py
| 0.576842
| 0.489474
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
print('I will display the od number 1 through 9.')
for num in [1, 3, 5, 7, 9]:
print(num)
|
Python
| 5
| 27
| 50
|
/global/simple_loop2.py
| 0.571429
| 0.514286
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
total_seconds = float(input('Enter a number of seconds: '))
hours = total_seconds // 3600
minutes = (total_seconds // 60) % 60
seconds = total_seconds % 60
print('Here is the time in hours,minutes, and seconds:')
print('Hours:', hours)
print('minutes:', minutes)
print('seconds:', seconds)
|
Python
| 10
| 32.599998
| 59
|
/global/time_converter.py
| 0.669643
| 0.636905
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
from Crypto import Random
from binascii import b2a_hex, a2b_hex
__author__ = 'florije'
class prpcrypt():
def __init__(self, key):
self.key = key
self.mode = AES.MODE_CBC
# 加密函数,如果text不足16位就用空格补足为16位,
# 如果大于16当时不是16的倍数,那就补足为16的倍数。
def encrypt(self, text):
cryptor = AES.new(self.key, self.mode, b'0000000000000000')
# 这里密钥key 长度必须为16(AES-128),
# 24(AES-192),或者32 (AES-256)Bytes 长度
# 目前AES-128 足够目前使用
length = 16
count = len(text)
if count < length:
add = (length - count)
# \0 backspace
text = text + ('\0' * add)
elif count > length:
add = (length - (count % length))
text = text + ('\0' * add)
self.ciphertext = cryptor.encrypt(text)
# 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
# 所以这里统一把加密后的字符串转化为16进制字符串
return b2a_hex(self.ciphertext)
# 解密后,去掉补足的空格用strip() 去掉
def decrypt(self, text):
cryptor = AES.new(self.key, self.mode, b'0000000000000000')
plain_text = cryptor.decrypt(a2b_hex(text))
return plain_text.rstrip('\0')
if __name__ == '__main__':
# pc = prpcrypt('keyskeyskeyskeys')
# import sys
#
# e = pc.encrypt(sys.argv[1])
# d = pc.decrypt(e)
# print "加密:", e
# print "解密:", d
key = '0123456789abcdef'
mode = AES.MODE_CBC
iv = Random.new().read(AES.block_size)
encryptor = AES.new(key, mode, iv)
text = 'j' * 64
ciphertext = encryptor.encrypt(text)
print ciphertext
"""
上例中的key是16位, 还可以是24 或 32 位长度, 其对应为 AES-128, AES-196 和 AES-256.
解密则可以用以下代码进行:
"""
decryptor = AES.new(key, mode, iv)
plain = decryptor.decrypt(ciphertext)
print plain
|
Python
| 67
| 25.97015
| 67
|
/other/aes_demo.py
| 0.576646
| 0.526287
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
'''
'''
data = [1, 2, 3, 4]
# for i in data:
# for j in data:
# print('{a}{b}'.format(a=i, b=j), end=' ')
# 上下两种表达一样,都是生成两位数。
# for i in data:
# for j in data:
# print('%s%s' % (i, j), end=' ')
# 下面生成任意组合三位数。
# for i in data:
# for j in data:
# for k in data:
# print('{a}{b}{c}'.format(a=i, b=j, c=k), end=' ')
# 下面生成无重复数字的三位数。
count = 0
for i in data:
for j in data:
for k in data:
if i != j and j != k and i != k:
count += 1
print('{a}{b}{c}'.format(a=i, b=j, c=k), end=' ')
print('\n{count}'.format(count=count))
|
Python
| 33
| 19.424242
| 65
|
/21days/5_5.py
| 0.445104
| 0.434718
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
"""
输出所有的水仙花数,把谓水仙花数是指一个数3位数,其各各位数字立方和等于其本身,
例如: 153 = 1*1*1 + 3*3*3 + 5*5*5
"""
def get_flower():
for i in range(1, 10):
for j in range(10):
for k in range(10):
s = 100*i + 10*j + k
h = i**3 + j**3 + k**3
if s == h:
print(s)
if __name__ == '__main__':
get_flower()
|
Python
| 18
| 21.777779
| 40
|
/learn/004.py
| 0.413625
| 0.343066
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8-*-
__author__ = 'manman'
import sys
print('The command line arguments are:')
for i in sys.argv:
print i
print '\n\nThe PRTHONPATH is', sys.path, '\n'
|
Python
| 10
| 16.700001
| 45
|
/byte/chapter_9_1.py
| 0.616667
| 0.611111
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
import jpype
__author__ = 'florije'
lib_base_path = r'E:\fuboqing\files\company\po_upnp\libs'
jar_list = ['commons-codec-1.10.jar', 'log4j-1.2.17.jar', 'chinapaysecure.jar', 'bcprov-jdk15on-154.jar']
class_path = ';'.join(['%s\%s' % (lib_base_path, jar) for jar in jar_list])
jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % class_path)
secssUtil = jpype.JClass('com.chinapay.secss.PythonDelegate')()
prop = jpype.JClass('java.util.Properties')()
# jpype.java.lang.System.out.println("hello world")
configs_dict = {'sign.file.password': 'abcd1234', 'sign.cert.type': 'PKCS12', 'sign.invalid.fields': 'Signature,CertId',
'verify.file': 'E:\\fuboqing\\files\\company\\po_upnp\\pfx\\000001509184450.cer',
'sign.file': 'E:\\fuboqing\\files\\company\\po_upnp\\pfx\\000001509184450.pfx', 'log4j.name': 'cpLog',
'signature.field': 'Signature'}
for key, value in configs_dict.iteritems():
prop.setProperty(key, value)
try:
secssUtil.PyInit(prop)
if secssUtil.getErrCode() != '00':
print(secssUtil.getErrMsg())
except jpype.JavaException as e:
raise e
data = {'Version': '20140728', 'OrderAmt': str(1L), 'TranDate': '20160114', 'BusiType': '0001',
'MerBgUrl': 'http://182.48.115.36:8443/upnp/payNotify', 'MerPageUrl': 'http://182.48.115.35:20060/pay-success',
'MerOrderNo': '2016844500000009', 'TranTime': '170733', 'CurryNo': 'CNY', 'MerId': '000001509184450'}
data_map = jpype.JClass("java.util.HashMap")()
for key, value in data.iteritems():
data_map.put(key, value)
try:
secssUtil.PySign(data_map)
except jpype.JavaException as e:
print(e.message())
res = secssUtil.getSign()
print res
jpype.shutdownJVM()
|
Python
| 47
| 36.553192
| 122
|
/other/python_java/java_sign.py
| 0.65949
| 0.58187
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
for x in range(5):
print('Hello world')
|
Python
| 4
| 21.5
| 24
|
/global/simple_loop4.py
| 0.544444
| 0.522222
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
import requests
__author__ = 'florije'
res = requests.get('http://www.weather.com.cn/data/list3/city.xml', params={'level': 1}, headers={
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6',
'Content-Type': 'text/xml',
'Host': 'www.weather.com.cn',
})
if res.status_code == 200:
print res.content.decode('utf-8')
else:
pass
|
Python
| 16
| 25.5625
| 109
|
/other/requests_demo.py
| 0.617371
| 0.556338
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
class Meta(type):
def __call__(*args):
print("meta call", *args)
return None
class C(metaclass=Meta):
def __init__(*args):
print("C init not called", args)
if __name__ == '__main__':
c = C()
print(c)
|
Python
| 18
| 15.222222
| 40
|
/other/chap1key6.py
| 0.493151
| 0.489726
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
import time
import random
import requests
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager, Shell, Server
from flask_migrate import Migrate, MigrateCommand
__author__ = 'florije'
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///weather.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
manager = Manager(app)
manager.add_command("runserver", Server())
migrate = Migrate(app, db)
def make_shell_context():
# return dict(app=app, db=db, TaskModel=TodoModel)
return dict(app=app)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
MUNICIPALITIES = [u'北京', u'上海', u'天津', u'重庆']
def request_data(url):
"""
获取url地址的数据
:param url:
:return:
"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6',
'Content-Type': 'text/xml',
'Host': 'www.weather.com.cn',
}
res = requests.get(url, headers=headers)
if res.status_code == 200:
return res.content.decode('utf-8')
else:
raise Exception(res.status_code, res.reason)
class BaseModel(db.Model):
"""
Model基类
"""
__abstract__ = True
id = db.Column(db.Integer, primary_key=True)
create_time = db.Column(db.DateTime(), default=db.func.datetime('now', 'localtime')) # db.func.now()
update_time = db.Column(db.DateTime(), default=db.func.datetime('now', 'localtime'),
onupdate=db.func.datetime('now', 'localtime'))
class ModelMixin(object):
"""
Model拓展类
"""
def __repr__(self):
return unicode(self.__dict__)
class ProvinceModel(BaseModel, ModelMixin):
"""
Province Model
"""
__tablename__ = 'province'
uid = db.Column(db.String(6), unique=False, nullable=False)
province = db.Column(db.String(20), unique=False, nullable=False)
def __init__(self, uid, province):
self.uid = uid
self.province = province
# def __repr__(self):
# return '<Weather %r>' % self.province
class CityModel(BaseModel, ModelMixin):
"""
City Model
"""
__tablename__ = 'city'
uid = db.Column(db.String(6), unique=False, nullable=False)
province_uid = db.Column(db.String(6), unique=False, nullable=False)
city = db.Column(db.String(20), unique=False, nullable=False)
def __init__(self, uid, province_uid, city):
self.uid = uid
self.province_uid = province_uid
self.city = city
# def __repr__(self):
# return '<City %r>' % self.city
class DistrictModel(BaseModel, ModelMixin):
"""
District Model
"""
__tablename__ = 'district'
uid = db.Column(db.String(6), unique=False, nullable=False)
code = db.Column(db.String(20), unique=False, nullable=True)
province_uid = db.Column(db.String(6), unique=False, nullable=False)
city_uid = db.Column(db.String(6), unique=False, nullable=False)
district = db.Column(db.String(20), unique=False, nullable=False)
def __init__(self, uid, province_uid, city_uid, district):
self.uid = uid
self.province_uid = province_uid
self.city_uid = city_uid
self.district = district
# def __repr__(self):
# return '<District %r>' % self.district
def sleep(start, end):
"""
睡眠时间
:param start: 开始数字
:param end: 停止数字
:return:
"""
time.sleep(random.randint(start, end))
@manager.command
def create_db():
"""
创建数据库,暂未使用migrate
:return:
"""
db.create_all()
print "db ok."
@manager.command
def get_province():
"""
获取省份
:return:
"""
success = False
try:
res = request_data('http://www.weather.com.cn/data/list3/city.xml?level=1')
province_list = []
for item in res.split(','):
split_item = item.split('|')
if split_item:
province = ProvinceModel(uid=split_item[0], province=split_item[1])
province_list.append(province)
if province_list:
db.session.add_all(province_list)
db.session.commit()
success = True
except Exception as e:
print e.args, e.message
time.sleep(random.randint(2, 5))
while not success:
try:
res = request_data('http://www.weather.com.cn/data/list3/city.xml?level=1')
province_list = []
for item in res.split(','):
split_item = item.split('|')
if split_item:
province = ProvinceModel(uid=split_item[0], province=split_item[1])
province_list.append(province)
if province_list:
db.session.add_all(province_list)
db.session.commit()
success = True
except Exception as e:
print e.args, e.message
time.sleep(random.randint(2, 5))
print 'get province data ok.'
@manager.command
def get_city():
"""
获取城市
:return:
"""
province_list = ProvinceModel.query.all()
to_deal_provinces = []
for province in province_list:
sleep(1, 4)
print "in origin province %s" % province.province
try:
res = request_data('http://www.weather.com.cn/data/list3/city{code}.xml?level=2'.format(code=province.uid))
city_list = []
for item in res.split(','):
split_item = item.split('|')
city = CityModel(uid=split_item[0], city=split_item[1], province_uid=province.uid)
city_list.append(city)
if city_list:
db.session.add_all(city_list)
db.session.commit()
except Exception as e:
print e.args, e.message
to_deal_provinces.append(province)
sleep(3, 7)
while to_deal_provinces:
for province in to_deal_provinces[:]:
print "in to deal province %s" % province.province
sleep(1, 4)
try:
res = request_data(
'http://www.weather.com.cn/data/list3/city{code}.xml?level=2'.format(code=province.uid))
city_list = []
for item in res.split(','):
split_item = item.split('|')
city = CityModel(uid=split_item[0], city=split_item[1], province_uid=province.uid)
city_list.append(city)
if city_list:
db.session.add_all(city_list)
db.session.commit()
to_deal_provinces.remove(province)
except Exception as e:
print e.args, e.message
sleep(3, 7)
print 'get city data ok.'
@manager.command
def get_district():
"""
获取城区
:return:
"""
city_list = CityModel.query.all()
to_deal_cities = []
for city in city_list:
sleep(1, 4)
print "in origin city %s" % city.city
try:
res = request_data('http://www.weather.com.cn/data/list3/city{code}.xml?level=3'.format(code=city.uid))
district_list = []
for item in res.split(','):
split_item = item.split('|')
district = DistrictModel(uid=split_item[0], district=split_item[1], province_uid=city.province_uid,
city_uid=city.uid)
district_list.append(district)
if district_list:
db.session.add_all(district_list)
db.session.commit()
except Exception as e:
print e.args, e.message
to_deal_cities.append(city)
sleep(3, 7)
while to_deal_cities:
for city in to_deal_cities[:]:
print "in to deal city %s" % city.city
sleep(1, 4)
try:
res = request_data('http://www.weather.com.cn/data/list3/city{code}.xml?level=3'.format(code=city.uid))
district_list = []
for item in res.split(','):
split_item = item.split('|')
district = DistrictModel(uid=split_item[0], district=split_item[1], province_uid=city.province_uid,
city_uid=city.uid)
district_list.append(district)
if district_list:
db.session.add_all(district_list)
db.session.commit()
to_deal_cities.remove(city)
except Exception as e:
print e.args, e.message
sleep(3, 7)
print 'get district data ok.'
@manager.command
def get_weather_code():
"""
获取天气编码
:return:
"""
district_list = DistrictModel.query.all()
to_deal_districts = []
for district in district_list:
municipality_codes = [city.uid for city in CityModel.query.filter(CityModel.city.in_(MUNICIPALITIES)).all()]
if district.city_uid in municipality_codes:
sleep(1, 4)
print "in origin municipality district %s" % district.district
try:
res = request_data(
'http://www.weather.com.cn/data/list3/city{code}.xml?level=4'.format(code=district.uid))
district.code = res.split('|')[1] # if res.split('|') and len(res.split('|')) >= 2 else res
db.session.commit()
except Exception as e:
to_deal_districts.append(district)
print e.args, e.message
sleep(3, 7)
else:
# 直辖市的比较复杂直接获取,其他省市直接拼接.
print "in origin common district %s" % district.district
district.code = '101{code}'.format(code=district.uid)
db.session.commit()
while to_deal_districts:
for district in to_deal_districts[:]:
print "in to deal district %s" % district.district
sleep(1, 4)
try:
res = request_data(
'http://www.weather.com.cn/data/list3/city{code}.xml?level=4'.format(code=district.uid))
district.code = res.split('|')[1] # if res.split('|') and len(res.split('|')) >= 2 else res
to_deal_districts.remove(district)
db.session.commit()
except Exception as e:
print e.args, e.message
sleep(3, 7)
@manager.command
def get_weather():
"""
获取天气
:return:
"""
code = request.args.get('code', '')
res = request_data('http://weather.com.cn/adat/cityinfo/{code}.html'.format(code=code))
return res
@app.route("/")
def hello():
"""
index
:return:
"""
return "Hello, World!"
if __name__ == '__main__':
# app.run(debug=True, host='127.0.0.1', port=8020)
manager.run()
|
Python
| 355
| 29.909859
| 119
|
/other/weather_data.py
| 0.553723
| 0.543607
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
from lxml import etree
__author__ = 'florije'
tree = etree.parse('citylist.xml')
root = tree.getroot()
for subroot in root:
for field in subroot:
print 'number:', field.get('d1'), 'name_cn:', field.get('d2'), 'name_en:', field.get(
'd3'), 'prov_name:', field.get('d4')
|
Python
| 12
| 25.666666
| 93
|
/other/lxml_demo.py
| 0.58125
| 0.565625
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
monthly_pay = 5000.0
annual_pay = monthly_pay * 12
print('Your annual pay is $', \
format(annual_pay, ',.2f'), \
sep='')
|
Python
| 7
| 24.571428
| 35
|
/global/dollar_display.py
| 0.547486
| 0.497207
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
'''
总科目状态:1,未通过,2,补考,3,通过
1.输入两门成绩
2.第一门成绩大于60分即通过,不及格则未通过
3.第一门成绩及格而第二门成绩不及格,则显示‘补考’。
'''
'''
x = int(input('输入第一门课程成绩:'))
y = int(input('输入第二门课程成绩:'))
status = 0 # 总科目状态,0定义为未知。
if x >= 60:
if y < 60:
status = 2
else:
status = 3
else:
status = 1
if status == 1:
print('未通过')
elif status == 2:
print('补考')
elif status == 3:
print('通过')
'''
x = int(input('输入第一门课程成绩:'))
y = int(input('输入第二门课程成绩:'))
if x >= 60:
if y >= 60:
print('通过')
else:
print('补考')
else:
print('未通过')
|
Python
| 39
| 14.153846
| 28
|
/21days/4_3.py
| 0.521959
| 0.47973
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
num1 = 127.899
num2 = 3465.148
num3 = 3.776
num4 = 264.821
num5 = 88.081
num6 = 799.999
print(format(num1, '7.2f'))
print(format(num2, '7.2f'))
print(format(num3, '7.2f'))
print(format(num4, '7.2f'))
print(format(num5, '7.2f'))
print(format(num6, '7.2f'))
|
Python
| 15
| 19.200001
| 27
|
/global/columns.py
| 0.620462
| 0.425743
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
amount_due = 5000.0
monthly_payment = amount_due / 12
# \可加可不加
print('The monthly payment is ' +\
format(monthly_payment, '.2f'))
|
Python
| 7
| 25.142857
| 37
|
/global/formatting.py
| 0.612022
| 0.562842
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
from crypto_py import Cryptor
import binascii
iv, encrypted = Cryptor.encrypt('fuboqing', Cryptor.KEY)
print "iv : %s" % iv
# => iv 6aa60df8ff95955ec605d5689036ee88
print "encrypted : %s" % binascii.b2a_base64(encrypted).rstrip()
# => encrypted r19YcF8gc8bgk5NNui6I3w==
# encrypted_str = "U2FsdGVkX18Qr0xuqggzVgHwDkxBHLLJiPLppAFoAjQsybTv9jj96gSK4CIQyZb3Ead1k3yMSRx0UOH11hyzbvksA2au/JSoo9rd79Dd/a/bpxMXPh4ot3gd6kSgWaPMbr6LxsD0lhUdKF+qR9u+e3hvmSrGRBKuhCNUJUm+419pdt4DMyRw4eJ0TFEhPDzj9GHYJCDXvI58ORA3uOIHJU5ITMfzse2zYCC9is46OlAuli+FKuQ9g966xNjhQb4rakllujU547VdXTOeZAIVtcZXY7XTBtJDGt72+JPNEMQeaC9pkfgyfbp6fcoYwlvOKT6iJspJE2nVclKA+yPnvDCaDVjJxf2lACVOeJGBx20Bd3YvbkYCTvFftmfTrz4rmBvOQw1/68+kFTT4cRsN3DQrLM29wsHL8sRynSzxNMnck4BQ6Ds0InW8z639Luh/+9kodyScbx69gXdtlFqrRZ2CZhei/eMKJDgZbG1BZMBOz5H9VQ45j8kZW5Wzog19FZWSg5ZD8KOt9i0PHCJHo8rM6geHj/UZ2Zv6S+PV/Y7mQa7ik4jBsotqifxGLA1uG8HKp+3XeJPllngsX/LHkMlT9FXDwvO8QPHWutO36O01QGzx70VbgWq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ypted = Cryptor.decrypt(encrypted_str, Cryptor.KEY, iv)
print "decrypted : %s" % decrypted
# => decrypted : fisproject
|
Python
| 19
| 26.789474
| 64
|
/other/aes_js_py/aes.py
| 0.712121
| 0.645833
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
"""
用户输入两个数字,程序计算出这两个数字的最小公倍数。
百度关键字:辗转相除法
"""
"""
1.定义函数,引出俩数x,y
2.大数除以小数得一余数不为零时,小数继续除以该余数,直至余数为零停止
3.最小公倍数 = (x*y)/余数
"""
from fractions import gcd
def arb(x, y):
while y != 0:
x, y = y, x % y
return x
if __name__ == '__main__':
x = int(input('Please input x value:'))
y = int(input('Please input y value:'))
print(x * y / arb(x, y))
'''
def arb(x, y):
print(x, y)
for i in range(x * y, x + 1, -1):
if i % x == 0 and i % y == 0:
c = i
print(c)
if __name__ == '__main__':
x = int(input("请输入数字:"))
y = int(input("请输入数字:"))
arb(x, y)
'''
|
Python
| 40
| 15.8
| 43
|
/learn/006.py
| 0.483631
| 0.470238
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
aint = int(input('please input a int:'))
bint = int(input('please input a int:'))
cint = int(input('please input a int:'))
dint = int(input('please input a int:'))
fint = int(input('please input a int:'))
alst = [aint, bint, cint, dint, fint]
print(alst[1:4:2])
print(alst[3:0:-2])
|
Python
| 11
| 28.90909
| 40
|
/21days/3_2.py
| 0.625
| 0.603659
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
'''输入3个整数,列表,求最小值'''
aint = int(input('please input a int:'))
bint = int(input('please input a int:'))
cint = int(input('please input a int:'))
alst = [aint, bint,cint]
print(min(alst))
|
Python
| 9
| 24.888889
| 40
|
/21days/3_1.py
| 0.611111
| 0.602564
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
for name in ['Winken', 'Blinken', 'Nod']:
print(name)
|
Python
| 4
| 25
| 41
|
/global/simple_loop3.py
| 0.538462
| 0.528846
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8-*-
__author__ = 'manman'
class Person:
pass
p = Person
print(p)
|
Python
| 10
| 8.2
| 22
|
/byte/chapter_12_1.py
| 0.543478
| 0.532609
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
from Crypto.Cipher import AES
# Encryption
encryption_suite = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
cipher_text = encryption_suite.encrypt("The answer is no")
print cipher_text['ciphertext']
# Decryption
decryption_suite = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
plain_text = decryption_suite.decrypt(cipher_text)
print plain_text
|
Python
| 13
| 31.76923
| 80
|
/other/aes_js_py/new/002.py
| 0.720657
| 0.690141
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
high_score = 95
test1 = int(input('Enter the score for test 1:'))
test2 = int(input('Enter the score for test 2:'))
test3 = int(input('Enter the score for test 3:'))
average = (test1 + test2 + test3) / 3
print('The average score is', average)
if average >= high_score:
print('Congratulations!')
print('That is a great average!')
|
Python
| 11
| 33.81818
| 49
|
/global/test_average.py
| 0.650131
| 0.616188
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
for i in range(3):
for j in range(i, 3):
print('+', end='')
print()
print('women')
print('doushi', end='')
print('haohaizi.', end='\n')
|
Python
| 11
| 17.181818
| 28
|
/21days/4_2.py
| 0.505
| 0.49
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
first_name = 'Kathryn'
last_name = 'Marino'
print(first_name, last_name)
print(first_name, last_name)
|
Python
| 7
| 20.285715
| 28
|
/global/string_variable.py
| 0.64
| 0.633333
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
import urllib, json
import urllib.parse, urllib.request
query_args = {'pass': 'b6ce159334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KrmLqjPl75KOUN/jldj5o3R4xstbi64/90CCKTKc6WPjgUt68PCKpnUPtjjArDF5y26KagNrZ529PBdwpTfxdL7k/bd8KBPHUCNng4P6aOItMMOhN8PFyzI+7GEwZ9y5l7rK/38n+Sab19WHtoGX8Hi1utFhPOy4gYAgikJEbyWoiFHgT9hteYUHWIZ3RkfvG7jX8nrd/nymy9Bb1hboxEfM8/qnh1mnMt6atttUkNzJ3qLMXYMgLrGGvzgfoNUmx1/Mg+DewH1zvjQufjE2UHLQpLcPuAk/rFfVXngqTGxka7UtQFpLk+7xEMWYF/5T0O6bpXEHFM8UkY7uxay8x7p/aJrh1BqPCaKnjW96Q/bQ=='}
encoded_args = urllib.parse.urlencode(query_args)
print('Encoded:', encoded_args)
url = 'http://45.56.64.124:3000/aes/?' + encoded_args
res = urllib.request.urlopen(url).read()
for item in json.loads(res.decode('utf-8', )):
print(item['album'], item['artist'], item['mp3'])
|
Python
| 15
| 29.466667
| 53
|
/other/aes_js_py/urls.py
| 0.643326
| 0.584245
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
first_name = input('Enter your first name: ')
last_name = input('Enter your last name: ')
print('Hello', first_name, last_name)
|
Python
| 6
| 28.166666
| 45
|
/global/string_input.py
| 0.627119
| 0.621469
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
"""
去除重复关键字,
'[a:1,b:2,c:3]','[a:7,c:2,m:7,r:4]','[a:3,b:2,c:7,o:5]'
"""
myseq = """[a:1,b:2,c:3]
[a:3,b:3,c:8]
[a:7,c:2,m:7,r:4]
[a:2,c:4,m:6,r:4]
[a:3,b:2,c:7,o:5]"""
res_keys, res_strs = [], []
for item in myseq.split('\n'):
# 获取key
item_keys = [raw_item.split(':')[0] for raw_item in item[1: len(item) - 1].split(',')]
# 判断是否有key的列表,然后决定是否放进去。
for key_list in res_keys: # 已存['a', 'b', 'c']
list_r = [a for a in item_keys if a in key_list]
long_len = len(item_keys) if len(item_keys) >= len(key_list) else len(key_list)
if len(list_r) >= long_len:
break
else:
res_keys.append(item_keys)
res_strs.append(item)
print(', '.join(res_strs))
|
Python
| 30
| 24.466667
| 90
|
/other/problem01.py
| 0.515707
| 0.472513
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8-*-
__author__ = 'manman'
def say(message, times=1):
print(message * times)
say('Hello')
say('World', 5)
def say(message, times=2):
print(message * times)
say('Hello', 2)
say('World', 4)
def say(message, times=1):
print(message * times)
say('Hate')
say('You', 1314)
|
Python
| 26
| 10.884615
| 26
|
/byte/func_default.py
| 0.588997
| 0.553398
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
print('''one
two
three''')
print('''one two three''')
print('''one, two, three''')
print('''one,
two,
three''')
print("one\n"
"two\n"
"three")
|
Python
| 17
| 11.058824
| 28
|
/global/display_quote.py
| 0.504854
| 0.5
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
import json
import urllib.request
"""
读取1.json文件内容,然后解析出来把mp3下载地址找到,然后下载mp3文件。
"""
# import os
#
# for r, ds, fs in os.walk("/home/test"):
# for f in fs:
# fn = os.path.join(r, f)
# if f == "A":
# print(os.path.abspath(fn))
#
#
# def file_hdl(name='1.json'):
# f = open(name)
# for line in f:
# print(line)
def read_content(filename):
"""
从filename读取数据
:param filename:
:return:
"""
result = ''
f = open(filename)
for line in f:
result += line
f.close()
return result
def find_mp3_link(content):
"""
从content里面找到mp3链接
:param content:
:return:
"""
json_data = json.loads(content)
print(json_data)
res = []
for item in json_data:
res.append(item['mp3'])
return res # http://luoo-mp3.kssws.ks-cdn.com/low/luoo/radio1/1.mp3
def store_mp3(mp3_links):
"""
根据mp3链接下载mp3文件,然后存储到本地
:param mp3_link:
:return:
"""
for link in mp3_links:
res = urllib.request.urlopen(link).read()
f = open(link.split('/')[-1], 'wb')
f.write(res)
f.close()
print('{mp3} download success.'.format(mp3=link.split('/')[-1]))
if __name__ == '__main__':
content = read_content('1.json')
mp3_links = find_mp3_link(content)
store_mp3(mp3_links)
|
Python
| 72
| 18.263889
| 72
|
/learn/010.py
| 0.545782
| 0.526316
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
"""
2.1 设计程序流程
设计程序-写代码-更正语法错误-测试程序-更正逻辑错误-继续循环
流程图的概念,稍后搜索学习。
"""
|
Python
| 9
| 11.888889
| 32
|
/start/2_1/2_1.py
| 0.59322
| 0.567797
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
amount_due = 5000.0
monthly_payment = amount_due / 12.0
print('The monthly payment is', monthly_payment)
|
Python
| 5
| 29.200001
| 48
|
/global/no_formatting.py
| 0.662252
| 0.602649
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8-*-
__author__ = 'manman'
# Filename: mymodule_demo.py
import mymodule
mymodule.say_hi()
print('Version', mymodule.__version__)
|
Python
| 9
| 15.777778
| 38
|
/byte/mymodule_demo.py
| 0.640523
| 0.633987
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
test1 = float(input('Enter the first test score: '))
test2 = float(input('Enter the second test score: '))
test3 = float(input('Enter the third test score: '))
average = (test1 + test2 + test3) / 3.0
print('The average score is', average)
|
Python
| 7
| 39.714287
| 53
|
/global/test_score_average.py
| 0.65614
| 0.624561
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8-*-
__author__ = 'manman'
def func(a, b=5, c=10):
print 'a is', a, 'b is', b, 'c is', c
func(3, 7)
func(25, c=24)
func(c=50, a=100)
func(a=3)
def show_info(name, age=20, *args, **kwargs):
"""
show student's info
:param name: student's name
:param age: student's age
:param score: student's score
:return: nothing
"""
print name,
print age,
print args,
print kwargs
if __name__ == '__main__':
show_info('zhuzai')
print '-' * 40
show_info('zhuzai', 10)
print '-' * 40
show_info('zhuzai', age=11)
print '-' * 40
show_info('zhuzai', 12, 13, 14)
print '-' * 40
show_info('zhuzai', 15, *(16, 17), score=100)
print '-' * 40
show_info('zhuzai', 18, *(19, ), **{'score': 20})
|
Python
| 40
| 18.65
| 53
|
/byte/func_key.py
| 0.520966
| 0.453621
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
def pydanny_selected_numbers():
# If you multiple 9 by any other number you can easily play with
# numbers to get back to 9.
# Ex: 2 * 9 = 18. 1 + 8 = 9
# Ex: 15 * 9 = 135. 1 + 3 + 5 = 9
# See https://en.wikipedia.org/wiki/Digital_root
yield 9
# A pretty prime.
yield 31
# What's 6 * 7?
yield 42
# The string representation of my first date with Audrey Roy
yield "2010/02/20"
if __name__ == '__main__':
for item in pydanny_selected_numbers():
print item
|
Python
| 25
| 21.879999
| 68
|
/other/yields/yielding.py
| 0.561189
| 0.5
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
# Program 2-1 练习单引号使用
print('Kate Austen')
print('123 Full Circle Drive')
print('Asheville, NC 28899')
|
Python
| 7
| 19.857143
| 30
|
/start/2_2/output.py
| 0.630137
| 0.554795
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
max_temp = 102.5
temperature = float(input("Enter the substance's Celsius temperature: "))
while temperature > max_temp:
print('The temperature is too high.')
print('Turn the thermostat down and wait')
print('5 minutes.Then take the temperature')
print('again and enter it.')
temperature = float(input('Enter the new Celsius temperature:'))
print('The temperature is acceptable.')
print('Check it again in 15 minutes.')
|
Python
| 12
| 39.5
| 73
|
/global/temperature.py
| 0.695473
| 0.679012
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
"""
http://www.cnblogs.com/xiongqiangcs/p/3416072.html
"""
unitArab = (2, 3, 4, 5, 9)
unitStr = u'十百千万亿'
unitStr = u'拾佰仟万亿'
# 单位字典unitDic,例如(2,'十')表示给定的字符是两位数,那么返回的结果里面定会包含'十'.3,4,5,9以此类推.
unitDic = dict(zip(unitArab, unitStr))
numArab = u'0123456789'
numStr = u'零一二三四五六七八九'
numStr = u'零壹贰叁肆伍陆柒捌玖'
# 数值字典numDic,和阿拉伯数字是简单的一一对应关系
numDic = dict(zip(numArab, numStr))
def chn_number(s):
def wrapper(v):
"""
针对多位连续0的简写规则设计的函数
例如"壹佰零零"会变为"壹佰","壹仟零零壹"会变为"壹仟零壹"
"""
if u'零零' in v:
return wrapper(v.replace(u'零零', u'零'))
return v[:-1] if v[-1] == u'零' else v
def recur(s, bit):
"""
此函数接收2个参数:
1.纯数字字符串
2.此字符串的长度,相当于位数
"""
# 如果是一位数,则直接按numDic返回对应汉字
if bit == 1:
return numDic[s]
# 否则,且第一个字符是0,那么省略"单位"字符,返回"零"和剩余字符的递归字符串
if s[0] == u'0':
return wrapper(u'%s%s' % (u'零', recur(s[1:], bit - 1)))
# 否则,如果是2,3,4,5,9位数,那么返回最高位数的字符串"数值"+"单位"+"剩余字符的递归字符串"
if bit < 6 or bit == 9:
return wrapper(u'%s%s%s' % (numDic[s[0]], unitDic[bit], recur(s[1:], bit - 1)))
# 否则,如果是6,7,8位数,那么用"万"将字符串从万位数划分为2个部分.
# 例如123456就变成:12+"万"+3456,再对两个部分进行递归.
if bit < 9:
return u'%s%s%s' % (recur(s[:-4], bit - 4), u"万", recur(s[-4:], 4))
# 否则(即10位数及以上),用"亿"仿照上面的做法进行划分.
if bit > 9:
return u'%s%s%s' % (recur(s[:-8], bit - 8), u"亿", recur(s[-8:], 8))
return recur(s, len(s))
if __name__ == '__main__':
for i in range(18):
v1 = '9' + '0' * (i + 1)
v2 = '9' + '0' * i + '9'
v3 = '1' * (i + 2)
print ('%s->%s\n%s->%s\n%s->%s' % (v1, chn_number(v1), v2, chn_number(v2), v3, chn_number(v3)))
|
Python
| 62
| 28.032259
| 103
|
/other/alabo.py
| 0.504444
| 0.450556
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
min_salary = 30000.0
min_years = 2
salary = float(input('Enter your annual salary:'))
years_on_job = int(input('Enter the number of ' +
'years employed:'))
if salary >= min_salary and years_on_job >= min_years:
print('You qualify for the loan.')
else:
print('You do not qualify for this loan.')
|
Python
| 12
| 30.25
| 54
|
/global/loan_qualifier2.py
| 0.608
| 0.586667
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8-*-
__author__ = 'manman'
for i in range(1, 5, 2):
print(i)
else:
print('The for loop is over')
for i in range(1, 5):
print(i)
else:
print('The for loop is over')
|
Python
| 12
| 15.666667
| 33
|
/byte/for..in.py
| 0.555
| 0.525
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
"""
编写程序,判断给定的某个年份是否是闰年。
闰年的判断规则如下:
(1)若某个年份能被4整除但不能被100整除,则是闰年。
(2)若某个年份能被400整除,则也是闰年。
"""
def leap_year(year):
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print('{year} year is leap year!'.format(year=year))
else:
print('{year} year is not leap year!'.format(year=year))
if __name__ == '__main__':
year = int(input("Please input some years: "))
leap_year(year)
|
Python
| 21
| 20.857143
| 64
|
/learn/001.py
| 0.588235
| 0.544662
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
"""
<script type="text/javascript">var fish=1734+473;var frog=435+2716^fish;var seal=168+8742^frog;var chick=7275+2941^seal;var snake=3820+4023^chick;</script>
以上script脚本提取变量为字典。
"""
|
Python
| 7
| 32
| 155
|
/learn/012.py
| 0.69697
| 0.532468
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
import urllib
from lxml import etree
__author__ = 'florije'
def get_html(url):
page = urllib.urlopen(url)
html = page.read()
return html
def get_key(html):
page = etree.HTML(html.lower().decode('gb2312'))
trs = page.xpath(u"//td[@valign='top']/font[@size='2']//table[contains(@width,'100%')]/tr")
i = 1
size = len(trs)
while (i < size):
ip = trs[i].xpath("./td[2]/text()")[0]
port = trs[i].xpath("./td[3]/text()")[0]
i = i + 1
print ip + " " + port
if __name__ == '__main__':
i = 1
total_page = 12
while i < total_page:
addr = "http://www.proxy.com.ru/list_" + str(i) + ".html"
html = get_html(addr)
key = get_key(html)
i += 1
|
Python
| 34
| 21.647058
| 95
|
/other/proxy.py
| 0.505195
| 0.480519
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
# this program displays a person's name and address
print('Kate')
print('123 Full circle Drive')
print('Asheville, NC 28899')
|
Python
| 7
| 23.714285
| 51
|
/global/comment1.py
| 0.67052
| 0.618497
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
start_speed = 60 # Starting speed
end_speed = 131 # Ending speed
increment = 10 # Speed increment
conversion_factor = 0.6214 # Conversation factor
print('KPH\tMPH')
print('--------')
for kph in range(start_speed, end_speed, increment):
mph = kph * conversion_factor
print(kph, '\t', format(mph, '.1f'))
|
Python
| 12
| 29.166666
| 52
|
/global/speed_converter.py
| 0.640884
| 0.60221
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
a = [1, 2, 3]
b = [item for item in a]
tmp = []
for item in a:
tmp.append(item)
print b, tmp
|
Python
| 9
| 15.111111
| 24
|
/other/for.py
| 0.531034
| 0.503448
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
from Crypto.Hash import SHA512
import cgi, base64
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
h = SHA512.new()
h.update(b'Hello')
print h.hexdigest()
"""
先生成rsa的公私钥:
打开控制台,输入 openssl
再输入 genrsa -out private.pem 1024 来生成私钥
接着输入 rsa -in private.pem -pubout -out public.pem 来生成公钥
"""
# 私钥文件
priKey = """-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQD4c1uYjQfxsxD/RWLWYPKUN1QPWIp1Vu/K3Do6DF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''*RSA签名
* data待签名数据
* 签名用商户私钥,必须是没有经过pkcs8转换的私钥
* 最后的签名,需要用base64编码
* return Sign签名
'''
def sign(data):
key = RSA.importKey(priKey)
h = SHA.new(data)
signer = PKCS1_v1_5.new(key)
signature = signer.sign(h)
return base64.b64encode(signature)
'''*RSA验签
* data待签名数据
* signature需要验签的签名
* 验签用支付宝公钥
* return 验签是否通过 bool值
'''
def verify(data, signature):
key = RSA.importKey(pubKey)
h = SHA.new(data)
verifier = PKCS1_v1_5.new(key)
if verifier.verify(h, base64.b64decode(signature)):
return True
return False
raw_data = 'partner="2088701924089318"&seller="774653@qq.com"&out_trade_no="123000"&subject="123456"&body="2010新款NIKE 耐克902第三代板鞋 耐克男女鞋 386201 白红"&total_fee="0.01"¬ify_url="http://notify.java.jpxx.org/index.jsp"'
sign_data = sign(raw_data)
print "sign_data: ", sign_data
print verify(raw_data, sign_data)
|
Python
| 68
| 18.852942
| 205
|
/other/crys.py
| 0.679259
| 0.622222
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
"""
1.判断用户输入的年月日,然后判断这一天是当年的第几天。
2.随机生成20个10以内的数字,放入数组中,然后去掉重复的数字。然后打印数组。
"""
# 根据出生年先判断是平年还是闰年,得出2月份天数,各月份天数相加即可。
# year = int(input("请输入年份: "))
# march = int(input("请输入月份: "))
# days = int(input("请输入日子: "))
# def feb_days():
# for i in range():
# if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
# xadct.valus({'feb': 28})
# days = days + xadct.valus()
# return(days)
# else:
# return(days + 1)
def is_leap(year):
"""
判断是否是瑞年
:param year:
:return:
"""
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
return True
else:
return False
def print_days_of_year(year, month, day):
"""
打印当前天是这一年的第几天
:param year:
:param month:
:param day:
:return:
"""
month_days = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
if is_leap(year):
month_days[2] = 29
full_month_day_count = 0
for i in range(1, month):
full_month_day_count += month_days[i]
total_days = full_month_day_count + day
print(total_days)
if __name__ == '__main__':
year = int(input('Please input year:'))
month = int(input('Please input month:'))
day = int(input('Please input day:'))
print_days_of_year(year, month, day)
|
Python
| 61
| 21.721312
| 104
|
/learn/008.py
| 0.52886
| 0.474747
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8-*-
__author__ = 'manman'
def total(initial=5, *numbers, **keywords):
count = initial
for number in numbers:
count += number
for key in keywords:
count += keywords[key]
return count
print(total(10, 1, 2, 3, vegetables=50, fruits=100))
def add(a, b, c):
if a == 1:
return a + b + c
else:
return a * b * c
print add(2, 2, 4)
|
Python
| 24
| 15.916667
| 52
|
/byte/VarArgs.py
| 0.539409
| 0.5
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
user_infos = [{'name': 'john', 'password': '2354kdd', 'usertype': 1},
{'name': 'kate', 'password': '3574kdd', 'usertype': 2}]
def login(name, password):
"""
用户登录
:param name:
:param password:
:return:
"""
for user in user_infos:
if user['name'] == name and user['password'] == password:
return user['usertype']
else:
return None
if __name__ == '__main__':
name = input("Please input your name: ")
password = input("Please input your password: ")
res = login(name, password)
if not res:
print("You have not registered in the system")
else:
print("Welcome, your user type is %d" % res)
|
Python
| 30
| 24.333334
| 72
|
/21days/5_4.py
| 0.536842
| 0.532895
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
min_salary = 30000.0
min_years = 2
salary = float(input('Enter your annual salary:'))
years_on_job = int(input('Enter the number of' +
'years employed:'))
if salary >= min_salary:
if years_on_job >= min_years:
print('You quality for the loan.')
else:
print('You must have been employed', \
'for at least', min_years, \
'years to qualify.')
else:
print('You must earn at least $', \
format(min_salary, ',.2f'), \
' per year to qualify.', sep='')
|
Python
| 18
| 31.055555
| 50
|
/global/loan_qualifier.py
| 0.55286
| 0.537262
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
"""
求 2/1+3/2+5/3+8/5+13/8.....前20项之和?
"""
a = 1.0
b = 2.0
sum = 0
c = 0
for i in range(0, 20):
sum = sum + b/a
c = a + b
a = b
b = c
print(sum)
|
Python
| 17
| 11.529411
| 34
|
/learn/005.py
| 0.415888
| 0.308411
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
first_name = 'ww'
last_name = 'rr'
print('I am a teacher', \
first_name, \
last_name)
print('a', 'b', 'c', end=';')
print('a', 'b', 'c', sep='**')
print(1, 2, 3, 4, sep='')
print('****\n*\n****\n* *\n****')
print('****')
print('*')
print('* *')
print('* *')
print('你好'.encode())
# print('你好'.decode())
test_dict = {'a': 3}
abc = test_dict.get('b')
print('~~~~~~~~')
print(abc)
|
Python
| 26
| 16.115385
| 34
|
/21days/2_1.py
| 0.455157
| 0.441704
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
"""
练习双引号使用
"""
print("Kate Austen")
print("123 Full Circle Drive")
print("Asheville, NC 28899")
|
Python
| 10
| 13.1
| 30
|
/start/2_2/double_quotes.py
| 0.588652
| 0.524823
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8-*-
__author__ = 'manman'
print 'Simple Assignment'
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist
del shoplist[0]
print 'shoplist is', shoplist, id(shoplist)
print 'mylist is', mylist, id(mylist)
print 'Copy by making a full slice'
mylist = shoplist[:]
del mylist[0]
print 'shoplist is', shoplist, id(shoplist)
print 'mylist is', mylist, id(mylist)
|
Python
| 20
| 18.85
| 49
|
/byte/chapter_10_5.py
| 0.680101
| 0.672544
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8-*-
__author__ = 'manman'
# !/usr/bin/python
# Filename: str_format.py
age = 25
name = 'Swaroop'
print (' {0} is {1} years old'.format(name, age))
print('Why is {0} playing with that python?'.format(name))
print('{:3}'.format('hello'))
print('{:<11}'.format('hello'))
print('{:>11}'.format('hello'))
print('{:>15}'.format('huaibizai'))
print('{:^11}'.format('hello'))
print('{:^11}'.format('bizi'))
print ('{:_>11}'.format('hello'))
|
Python
| 17
| 25.705883
| 58
|
/byte/format.py
| 0.592511
| 0.550661
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
import re
import json
import time
import random
import requests
import datetime
import requesocks
from bs4 import BeautifulSoup
def test_url_available(url):
proxies = {
'http': 'http://{url}'.format(url=url),
# 'http': 'http://222.88.142.51:8000',
}
try:
res = requests.get('http://www.luoo.net/', proxies=proxies)
except Exception as e:
return False
return res.status_code == 200
available_url = 'http://pachong.org/test/single/id/{id}'
proxies = {
"http": "socks5://127.0.0.1:1080",
"https": "socks5://127.0.0.1:1080"
}
user_agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"
headers = {
"User-Agent": user_agent,
"Host": "pachong.org",
"Referer": "http://pachong.org/"
}
def get_var_list(page_content):
# res = 'var chick=958+2894;var bee=6981+6600^chick;var cock=8243+890^bee;var calf=8872+4397^cock;var fish=3571+2760^calf;'
# var dog=7544+4134;var worm=3554+5240^dog;var goat=1408+5265^worm;var cat=1981+8542^goat;var fish=7827+5906^cat;
# print page_content
pattern = re.compile(r'var \w+=\S+;var \w+=\S+;var \w+=\S+;var \w+=\S+;var \w+=\S+;')
match = pattern.search(page_content)
if match:
print match.group()
content = match.group()[:-1]
var_list = content.split(';') # ['var chick=958+2894']
map_dict = {}
# one
raw_one = var_list[0] # 'var chick=958+2894'
left_raw_one, right_raw_one = raw_one.split('=')[0], raw_one.split('=')[1]
ont_var = left_raw_one.split(' ')[1]
one_value = sum([int(value) for value in right_raw_one.split('+')])
print ont_var, one_value
map_dict[ont_var] = one_value
# two
raw_two = var_list[1] # 'var bee=6981+6600^chick'
left_raw_two, right_raw_two = raw_two.split('=')[0], raw_two.split('=')[1]
two_var = left_raw_two.split(' ')[1]
two_value = int(right_raw_two.split('+')[0]) + int(right_raw_two.split('+')[1].split('^')[0]) ^ map_dict.get(right_raw_two.split('+')[1].split('^')[1])
print two_var, two_value
map_dict[two_var] = two_value
# three
raw_three = var_list[2] # 'var cock=8243+890^bee'
left_raw_three, right_raw_three = raw_three.split('=')[0], raw_three.split('=')[1]
three_var = left_raw_three.split(' ')[1]
three_value = int(right_raw_three.split('+')[0]) + int(right_raw_three.split('+')[1].split('^')[0]) ^ map_dict.get(right_raw_three.split('+')[1].split('^')[1])
print three_var, three_value
map_dict[three_var] = three_value
# four
raw_four = var_list[3] # var calf=8872+4397^cock;
left_raw_four, right_raw_four = raw_four.split('=')[0], raw_four.split('=')[1]
four_var = left_raw_four.split(' ')[1]
four_value = int(right_raw_four.split('+')[0]) + int(right_raw_four.split('+')[1].split('^')[0]) ^ map_dict.get(right_raw_four.split('^')[1])
print four_var, four_value
map_dict[four_var] = four_value
# five
raw_five = var_list[4] # 'var fish=3571+2760^calf'
left_raw_five, right_raw_five = raw_five.split('=')[0], raw_five.split('=')[1]
five_var = left_raw_five.split(' ')[1]
five_value = int(right_raw_five.split('+')[0]) + int(right_raw_five.split('+')[1].split('^')[0]) ^ map_dict.get(right_raw_five.split('^')[1])
print five_var, five_value
map_dict[five_var] = five_value
return map_dict
def get_urls():
session = requesocks.Session(headers=headers, proxies=proxies)
page_content = session.get('http://pachong.org/').content
# print(page_content.content)
soup = BeautifulSoup(page_content)
# print soup.find("table", {"class": "tb"})
# var chick=958+2894;var bee=6981+6600^chick;var cock=8243+890^bee;var calf=8872+4397^cock;var fish=3571+2760^calf;
map_dict = get_var_list(page_content)
table = soup.find('table', attrs={'class': 'tb'})
table_body = table.find('tbody')
rows = table_body.find_all('tr')
data = []
for row in rows:
cols = row.find_all('td')
# url_res = session.get(available_url.format(id=cols[6].find('a').get('name'))).content
# json_url_res = json.loads(url_res)
json_url_res = {'ret': 0, 'data': {'all': 0}}
if json_url_res.get('ret') == 0:
raw_port = cols[2].text.strip() # document.write((11476^fish)+298);
port = raw_port[raw_port.index('(') + 1: raw_port.index(';') - 1] # (11476^fish)+298
port = (int(port.split('^')[0][1:]) ^ map_dict.get(port[port.index('^') + 1: port.index(')')])) + int(port.split('+')[1])
tmp = {'id': cols[0].text.strip(), 'ip': cols[1].text.strip(), 'port': port,
'url_id': cols[6].find('a').get('name'), 'con_time': json_url_res.get('data').get('all'), 'region': cols[3].text.strip()}
data.append(tmp)
print(tmp)
# time.sleep(random.randint(3, 7))
# cols = [ele.text.strip() for ele in row.find_all('td')]
# data.append([ele for ele in cols if ele])
return data
def save_data(json_data):
with open('data_{date}.json'.format(date=datetime.datetime.now().strftime('%Y%m%d%H%M%S')), mode='w') as f:
f.write(json_data)
if __name__ == '__main__':
res = get_urls()
data = []
for item in res:
if u'调试' not in item.get('region'):
if test_url_available('{ip}:{port}'.format(ip=item.get('ip'), port=item.get('port'))):
data.append(item)
save_data(json.dumps(data))
|
Python
| 147
| 36.707481
| 163
|
/other/jiandan/proxy.py
| 0.586686
| 0.533285
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
# Create two variables: top_speed and distance.
top_speed = 160
distance = 300
# Display the values referenced by the variables.
print('The top speed is')
print(top_speed)
print('The distance traveled is')
print(distance)
|
Python
| 12
| 21.5
| 49
|
/global/variable_demo2.py
| 0.707407
| 0.681481
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
myseq = """[a:1, b:2, c:3]
[a:3, b:3, c:8]
[a:7, c:2, m:7, r:4]
[a:2, c:4, m:6, r:4]
[a:3, b:2, c:7, o:5]"""
res_keys = []
res_strs = []
# res = [item[1: len(item) - 1].split(',') for item in myseq.split('\n')]
# print res
for item in myseq.split('\n'):
# item_list = item[1: len(item) - 1].split(',')
# print item_list
# 获取key
item_keys = [raw_item.split(':')[0] for raw_item in item[1: len(item) - 1].split(',')]
# print item_keys
# 判断是否有key的列表,然后决定是否放进去。
for key_list in res_keys: # 已存['a', 'b', 'c']
# ['a', 'b', 'c'] 比较 ['a', 'b', 'c']是否相等。
# if key_list == item_keys:
# break
list_r = [a for a in item_keys if a in key_list]
long_len = len(item_keys) if len(item_keys) >= len(key_list) else len(key_list)
if len(list_r) >= long_len:
break
else:
res_keys.append(item_keys)
res_strs.append(item)
print(', '.join(res_strs))
|
Python
| 35
| 27.285715
| 90
|
/21days/4_5.py
| 0.500502
| 0.474423
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
#.adct = {'a': 1, 'b': 2, 'c': 3}
#.print(adct)
# adct = {'a': 1, 'b': 2}
# adct.update({'c': 3})
# print(adct)
# d1,d2,d3是三种不同的表达形式,
d1 = dict((['a', 1], ['b', 2],['c', 3]))
d2 = dict(a=1, b=2,c=3)
d3 = {'a': 1, 'b': 2, 'c': 3}
print(d1)
print(d2)
print(d3)
|
Python
| 17
| 17.117647
| 40
|
/21days/3_3.py
| 0.448387
| 0.367742
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
"""
壹、贰、叁、肆、伍、陆、柒、捌、玖、拾、佰、仟、万
11111
壹万壹仟壹佰壹拾壹
"""
map_value_dict = {'0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆', '5': '伍', '6': '陆', '7': '柒', '8': '捌',
'9': '玖'}
map_unit_dict = {2: '拾', 3: '佰', 4: '仟', 5: '万'}
result = []
def convert_num_str(num):
str_value = str(num)
print(str_value)
if len(str_value) > 5:
raise Exception('Too long value!!!')
if 5 >= len(str_value) > 4:
pop_value = str_value[0:1]
if int(pop_value) == 0:
pass
else:
result.append(map_value_dict[pop_value])
result.append(map_unit_dict[len(str_value)])
str_value = str_value[1:]
if 4 >= len(str_value) > 3:
pop_value = str_value[0:1]
if int(pop_value) == 0:
result.append('零')
else:
result.append(map_value_dict[pop_value])
result.append(map_unit_dict[len(str_value)])
str_value = str_value[1:]
if 3 >= len(str_value) > 2:
pop_value = str_value[0:1]
if int(pop_value) == 0:
if not result[-1] == '零':
result.append('零')
else:
result.append(map_value_dict[pop_value])
result.append(map_unit_dict[len(str_value)])
str_value = str_value[1:]
if 2 >= len(str_value) > 1:
pop_value = str_value[0:1]
if int(pop_value) == 0:
if not result[-1] == '零':
result.append('零')
else:
result.append(map_value_dict[pop_value])
result.append(map_unit_dict[len(str_value)])
str_value = str_value[1:]
if 1 >= len(str_value):
pop_value = str_value[0:1]
if int(pop_value) == 0:
# result.append('零')
pass
else:
result.append(map_value_dict[pop_value])
# result.append(map_unit_dict[len(str_value)])
if __name__ == '__main__':
value = 9099
convert_num_str(value)
print(''.join(result))
|
Python
| 70
| 28.085714
| 107
|
/global/0.0shuzizhuanhuan.py
| 0.481845
| 0.454858
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
function_class = (lambda x: x).__class__
print(function_class)
def foo():
print("hello world.")
def myprint(*args, **kwargs):
print("this is my print.")
print(*args, **kwargs)
newfunc1 = function_class(foo.__code__, {'print': myprint})
newfunc1()
newfunc2 = function_class(compile("print('asdf')", "filename", "single"), {'print': print})
newfunc2()
|
Python
| 20
| 19.75
| 91
|
/other/functions.py
| 0.619277
| 0.607229
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
original_price = float(input("Enter the item's original price: "))
discount = original_price * 0.2
sale_price = original_price - discount
print('The sale price is', sale_price)
|
Python
| 7
| 31
| 66
|
/global/sale_price.py
| 0.678571
| 0.665179
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8-*-
__author__ = 'manman'
class Person:
def __init__(self, name):
self.name = name
def say_hi(self):
print 'Hello, my name is', self.name
p = Person('Swaroop')
p.say_hi()
|
Python
| 14
| 14.642858
| 44
|
/byte/chapter_12_3.py
| 0.538813
| 0.534247
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
room =1002
print('I am staying in room number')
print(room)
room = 503
print('I am staying in room number', room)
|
Python
| 9
| 17
| 42
|
/global/variable_demo3.py
| 0.638037
| 0.588957
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
aint = int(input('please input a int:'))
bint = int(input('please input a int:'))
cint = int(input('please input a int:'))
dint = int(input('please input a int:'))
fint = int(input('please input a int:'))
gint = int(input('please input a int:'))
hint = int(input('please input a int:'))
lint = int(input('please input a int:'))
mint = int(input('please input a int:'))
nint = int(input('please input a int:'))
alst = [aint, bint, cint, dint, fint, gint, hint, lint, mint, nint]
print(sum(alst))
print(len(alst))
print(sum(alst)/len(alst))
|
Python
| 19
| 29.947369
| 67
|
/21days/3_4.py
| 0.643463
| 0.641766
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
import base64
from Crypto.Cipher import AES
from pkcs7 import PKCS7Encoder
# 使用256位的AES,Python会根据传入的Key长度自动选择,长度为16时使用128位的AES
key = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
mode = AES.MODE_CBC
iv = '1234567812345678' # AES的CBC模式使用IV
encoder = PKCS7Encoder()
text = "This is for test."
def encrypt(data):
encryptor = AES.new(key, AES.MODE_CBC, iv)
padded_text = encoder.encode(data)
encrypted_data = encryptor.encrypt(padded_text)
return base64.b64encode(encrypted_data)
def decrypt(data):
cipher = base64.b64decode(data)
decryptor = AES.new(key, AES.MODE_CBC, iv)
plain = decryptor.decrypt(cipher)
return encoder.decode(plain)
encrypted_text = encrypt(text)
clean_text = decrypt(encrypted_text)
print "encrypted_text:", encrypted_text
print "clean_text: ", clean_text
|
Python
| 35
| 22.6
| 51
|
/other/aes_js_py/encrypt.py
| 0.717576
| 0.671515
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
'''
1.输入20个数
2.收入一个列表
3.按正负数分入两个列表
'''
source_list = []
positive_list = []
negative_list = []
for i in range(20):
num = int(input('Please input the number:'))
print(num)
source_list.append(num)
print('source list data is:')
print(source_list)
for item in source_list:
if item >= 0:
positive_list.append(item)
else:
negative_list.append(item)
print('positive data is:')
print(positive_list)
print('negative data is:')
print(negative_list)
|
Python
| 31
| 15.967742
| 48
|
/21days/4_4.py
| 0.634981
| 0.617871
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
import time
import requests
from bs4 import BeautifulSoup
def sign_daily(username, password):
username = username # username
password = password # password
singin_url = 'https://v2ex.com/signin'
home_page = 'https://www.v2ex.com'
daily_url = 'https://www.v2ex.com/mission/daily'
user_agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"
headers = {
"User-Agent": user_agent,
"Host": "www.v2ex.com",
"Referer": "https://www.v2ex.com/signin",
"Origin": "https://www.v2ex.com"
}
v2ex_session = requests.Session()
def make_soup(url, tag, name):
page = v2ex_session.get(url, headers=headers, verify=True).text
soup = BeautifulSoup(page)
soup_result = soup.find(attrs={tag: name})
return soup_result
once_vaule = make_soup(singin_url, 'name', 'once')['value']
print(once_vaule) # will show you the once
post_info = {
'u': username,
'p': password,
'once': once_vaule,
'next': '/'
}
resp = v2ex_session.post(singin_url, data=post_info, headers=headers, verify=True)
short_url = make_soup(daily_url, 'class', 'super normal button')['onclick']
first_quote = short_url.find("'")
last_quote = short_url.find("'", first_quote + 1)
final_url = home_page + short_url[first_quote + 1:last_quote]
page = v2ex_session.get(final_url, headers=headers, verify=True).content
suceessful = make_soup(daily_url, 'class', 'fa fa-ok-sign')
if suceessful:
print ("Sucessful.")
else:
print ("Something wrong.")
if __name__ == '__main__':
user_list = [{'username': 'florije', 'password': 'fuboqing'}, {'username': 'vob636', 'password': 'fuboqing1988'},
{'username': 'moioutoi@163.com', 'password': '19931221'}]
for user in user_list:
sign_daily(user.get('username'), user.get('password'))
time.sleep(60)
|
Python
| 65
| 30.4
| 120
|
/other/signvto.py
| 0.598236
| 0.577658
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
salary = 2500.0
bonus = 1200.0
pay = salary + bonus
print('Your pay is', pay)
|
Python
| 7
| 16.857143
| 25
|
/global/simple_math.py
| 0.592
| 0.504
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8-*-
__author__ = 'manman'
def say_hi():
print('Hi,this is mymodule speaking.')
__version__ = '0.1'
|
Python
| 9
| 13
| 42
|
/byte/mymodule.py
| 0.53125
| 0.507813
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
something = raw_input("Enter input: ")
if is_palindrome(something):
print "Yes,it is a palindrome"
else:
print"No,it is not a palindrome"
|
Python
| 17
| 16.529411
| 38
|
/byte/chapter_13_1.py
| 0.637584
| 0.630872
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
hours = int(input('Enter the hours worked this week: '))
pay_rate = float(input('Enter the hourly pay rate: '))
gross_pay = hours * pay_rate
print('Gross pay: $', format(gross_pay, ',.2f'))
|
Python
| 6
| 38.333332
| 56
|
/global/gross_pay.py
| 0.631356
| 0.622881
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
# This program demonstrates a variable.
room = 503
print('I am staying in room number.')
print(room)
|
Python
| 7
| 20.142857
| 39
|
/global/variable_demo.py
| 0.655405
| 0.628378
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
"""
根据用户输入打印正三角,比如用户输入3打印如下:
*
*
* *
*
* *
* * *
打印菱形
"""
# 1. 三角形
# def show_triangle(num):
# """
# print triangle
# :param num:
# :return:
# """
# for i in range(num):
# # print('i%s' % i)
# print(' ' * (num - i - 1), end='')
# for j in range(i + 1):
# print('*', end=' ')
# print()
#
# if __name__ == '__main__':
# num = int(input('Please input the number:'))
# show_triangle(num)
# 2. 菱形
def show_diamond(num):
"""
print diamond
:param num:
:return:
"""
# 菱形的上半部分
for i in range(num):
print(' ' * (num - i) + '*' * (2 * i + 1))
# 菱形的正中
print('*' * (2 * num + 1))
# 菱形的下半部分
for i in range(num):
print(' ' * (i + 1) + '*' * (2 * (num - i - 1) + 1))
if __name__ == '__main__':
num = int(input('Please input the number:'))
show_diamond(num)
|
Python
| 61
| 14.557377
| 60
|
/learn/007.py
| 0.419389
| 0.404636
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
"""
1,定义函数get_blank_count
2,该函数获取字符串空格
3,测试该方法
"""
def get_blank_count(strs):
"""
获取字符串中空格数目
:param strs: 传入原始字符串
:return: 返回字符串中空格数目
"""
count = 0
for item in strs:
if item == ' ':
count += 1
return count
if __name__ == '__main__':
test_str = "women doushi haohaizi."
blank_count = get_blank_count(test_str)
print(blank_count)
|
Python
| 26
| 16
| 43
|
/21days/5_2.py
| 0.547511
| 0.533937
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
'''
1,写一个function
2,这个函数是排序列表使用
3,写调用function
'''
# alist = [8, 4, 7, 12, 10, 9, 16]
# alist.sort() # 默认按升序排列
# print(alist)
# alist.sort(reverse=True) # 按降序排列
# print(alist)
#
# alist = [(3, 'ab'), (13, 'd'), (2, 'ss'), (101, 'c')]
# alist.sort()
# print(alist)
def sort_list(data):
data.sort()
if __name__ == '__main__':
raw_list = [1, 3, 2]
sort_list(raw_list)
print(raw_list)
|
Python
| 28
| 15.071428
| 55
|
/21days/5_1.py
| 0.535556
| 0.482222
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
print('I will display the number 1 through 5.')
for num in [1, 2, 3, 4, 5]:
print(num)
|
Python
| 5
| 26.4
| 47
|
/global/simple_loop1.py
| 0.557143
| 0.5
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8-*-
__author__ = 'manman'
def func_outer():
x = 2
print('x is', x)
def func_inner():
nonlocal x # zhe li bu dui ya. bu dong.
x = 5
func_inner()
print('Changed local x to', x)
func_outer()
|
Python
| 18
| 13.388889
| 48
|
/byte/func_nonlocal.py
| 0.482625
| 0.471042
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
"""
2.2 输入,执行,输出
"""
print('Hello world')
|
Python
| 9
| 9.222222
| 23
|
/start/2_2/2_2.py
| 0.5
| 0.467391
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
"""
1,给定字符串,带分行,然后split(分裂)为list
2,分析list每个元素,判断是否有href关键字,保存有关键字的数据
3,提取剩余元素里面的href=开头的部分
"""
def get_hrefs(str_data):
"""
获取str_data里面所有超链接
:param str_data:
:return:
"""
# split str_data to list
str_list = str_data.split('\n') # 分析原始数据看到有回车换行
href_list = []
for line in str_list:
if 'href=' in line:
line = line.strip() # 看到有的行有空格,就去掉
line = line[4: -5] # href带其他标签,规则去掉
line = line[0: line.find('>') + 1] # 看规则去掉字符串尾部的汉字
href_list.append(line)
#
return href_list # [href sre[0:href str.find('>') + 1] for href str in[line.strip()[4: -5]for]
if __name__ == '__main__':
str_data = """
<h3>联系我们</h3>
<p>联系人:王经理</p>
<p>电话:021-87017800</p>
<div>
<ul>
<li><a class="nav-first" href="/"首 页</li>
<li><a href="/lista.php">吸粮机</a></li>
<li><a href="/listb.php">灌包机</a></li>
<li><a href="/listc.php">汽油吸粮机</a></li>
<li><a href="/order/setorder.php">我要订购</a></li>
<li><a href="/about.php">关于我们</a></li>
</ul>
</div>
"""
res = get_hrefs(str_data)
for item in res:
print(item)
|
Python
| 47
| 26.553192
| 100
|
/21days/5_3.py
| 0.485339
| 0.466049
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8-*-
__author__ = 'manman'
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split non a line."
backslash_cat = "I'm \\ a \\cat."
|
Python
| 6
| 23.833334
| 37
|
/hard/ex10.py
| 0.56
| 0.553333
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
"""
遍历文件夹jsons,获取所有文件内容,并保存文件title到一个list里面并打印。
"""
import os
import json
base_path = '{base_path}\\jsons'.format(base_path=os.getcwd())
def get_content(filename):
"""
从filename读取数据
:param filename:
:return:
"""
result = ''
with open(filename) as f:
for line in f:
result += line
return result
def get_json_data():
"""
获取json数据的title的list
:param content:
:return: res_list
"""
res_list = []
for item in os.listdir(base_path): # '.\\jsons'
res = get_content('{base_path}\\{filename}'.format(base_path=base_path, filename=item))
json_res = json.loads(res)
res_list.extend(data.get('title') for data in json_res)
return res_list
def print_data(res_list):
"""
:param res_list:
:return:
"""
for title in res_list:
print(title)
if __name__ == '__main__':
res_list = get_json_data()
print_data(res_list)
|
Python
| 53
| 17.943396
| 95
|
/learn/011.py
| 0.570717
| 0.569721
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'florije'
import binascii
import StringIO
from Crypto.Cipher import AES
KEY = 'ce975de9294067470d1684442555767fcb007c5a3b89927714e449c3f66cb2a4'
IV = '9AAECFCF7E82ABB8118D8E567D42EE86'
PLAIN_TEXT = "ciao"
class PKCS7Padder(object):
'''
RFC 2315: PKCS#7 page 21
Some content-encryption algorithms assume the
input length is a multiple of k octets, where k > 1, and
let the application define a method for handling inputs
whose lengths are not a multiple of k octets. For such
algorithms, the method shall be to pad the input at the
trailing end with k - (l mod k) octets all having value k -
(l mod k), where l is the length of the input. In other
words, the input is padded at the trailing end with one of
the following strings:
01 -- if l mod k = k-1
02 02 -- if l mod k = k-2
.
.
.
k k ... k k -- if l mod k = 0
The padding can be removed unambiguously since all input is
padded and no padding string is a suffix of another. This
padding method is well-defined if and only if k < 256;
methods for larger k are an open issue for further study.
'''
def __init__(self, k=16):
self.k = k
## @param text: The padded text for which the padding is to be removed.
# @exception ValueError Raised when the input padding is missing or corrupt.
def decode(self, text):
'''
Remove the PKCS#7 padding from a text string
'''
nl = len(text)
val = int(binascii.hexlify(text[-1]), 16)
if val > self.k:
raise ValueError('Input is not padded or padding is corrupt')
l = nl - val
return text[:l]
## @param text: The text to encode.
def encode(self, text):
'''
Pad an input string according to PKCS#7
'''
l = len(text)
output = StringIO.StringIO()
val = self.k - (l % self.k)
for _ in xrange(val):
output.write('%02x' % val)
return text + binascii.unhexlify(output.getvalue())
def encrypt(my_key=KEY, my_iv=IV, my_plain_text=PLAIN_TEXT):
"""
Expected result if called without parameters:
PLAIN 'ciao'
KEY 'ce975de9294067470d1684442555767fcb007c5a3b89927714e449c3f66cb2a4'
IV '9aaecfcf7e82abb8118d8e567d42ee86'
ENCRYPTED '62e6f521d533b26701f78864c541173d'
"""
key = binascii.unhexlify(my_key)
iv = binascii.unhexlify(my_iv)
padder = PKCS7Padder()
padded_text = padder.encode(my_plain_text)
encryptor = AES.new(key, AES.MODE_CFB, iv, segment_size=128) # Initialize encryptor
result = encryptor.encrypt(padded_text)
return {
"plain": my_plain_text,
"key": binascii.hexlify(key),
"iv": binascii.hexlify(iv),
"ciphertext": result
}
if __name__ == '__main__':
result = encrypt()
print "PLAIN %r" % result['plain']
print "KEY %r" % result['key']
print "IV %r" % result['iv']
print "ENCRYPTED %r" % binascii.hexlify(result['ciphertext'])
|
Python
| 98
| 30.775511
| 88
|
/other/cryptojs_aes.py
| 0.610469
| 0.558767
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
print('This program displays a list of number')
print('and their squares.')
start = int(input('Enter the starting number: '))
end = int(input('How high should I go?'))
print()
print('Number\tSquare')
print('--------------')
for number in range(start, end + 1):
square = number ** 2
print(number, '\t', square)
|
Python
| 12
| 29.333334
| 49
|
/global/user_squares1.py
| 0.618132
| 0.60989
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
dollars = 2.75
print('I have', dollars, 'in my account.')
dollars =99.95
print('But now I have', dollars, 'in my account!')
|
Python
| 7
| 23.428572
| 50
|
/global/variable_demo4.py
| 0.606936
| 0.560694
|
florije1988/manman
|
refs/heads/master
|
# -*- coding: utf-8 -*-
__author__ = 'manman'
"""
编写程序求 1+3+5+7+……+99 的和值。
"""
'''
1.定义一组数列
2.求和
'''
def get_res():
source = range(1, 100, 2)
sum = 0
for i in source:
print(i)
sum += i
return sum
if __name__ == '__main__':
res = get_res()
print(res)
|
Python
| 23
| 11.782609
| 29
|
/learn/002.py
| 0.452381
| 0.401361
|
dronperminov/Word2VecCodeNames
|
refs/heads/master
|
import json
import os
from math import sqrt
import re
def norm(vec):
dot = 0
for v in vec:
dot += v*v
return sqrt(dot)
def main():
filename = 'embedding.txt'
embedding = dict()
with open(filename, encoding='utf-8') as f:
args = f.readline().strip('\n').split(' ')
embedding['size'] = int(args[1])
embedding['embedding'] = dict()
for line in f:
word, *vector = line.strip().split(' ')
if not re.fullmatch(r'[а-яА-Я\-]+', word) or len(word) < 3:
continue
assert(len(vector) == embedding['size'])
vector = [float(v) for v in vector]
length = norm(vector)
vector = [v / length for v in vector]
embedding['embedding'][word] = vector
with open(filename + '.js', 'w', encoding='utf-8') as f:
f.write('const EMBEDDING = ' + json.dumps(embedding))
if __name__ == '__main__':
main()
|
Python
| 42
| 22
| 71
|
/scripts/convert.py
| 0.524845
| 0.519669
|
justincohler/opioid-epidemic-study
|
refs/heads/master
|
import pandas as pd
import json
def write_county_json():
tsv = pd.read_csv("../data/county_fips.tsv", sep='\t')
tsv = tsv[["FIPS", "Name"]]
print(tsv.head())
county_json = json.loads(tsv.to_json())
print(county_json)
with open('county_fips.json', 'w') as outfile:
json.dump(county_json, outfile)
def write_od_distribution_json():
csv = pd.read_csv("../data/county_health_rankings.csv")
csv = csv[["FIPS", "Drug Overdose Mortality Rate"]]
max_od = csv["Drug Overdose Mortality Rate"].max()
print(max_od)
csv["pctile"] = (csv["Drug Overdose Mortality Rate"] / max_od * 100)
csv["pctile"] = pd.to_numeric(csv["pctile"], downcast="unsigned")
print(csv.tail())
if __name__ == "__main__":
write_od_distribution_json()
|
Python
| 25
| 30.440001
| 72
|
/choropleth/scripts/convert_fips.py
| 0.616561
| 0.612739
|
jeffcheung2015/gallery_django_reactjs
|
refs/heads/master
|
"""backend URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
# from customers import views
from django.conf.urls import url
from gallery import views
from rest_framework_simplejwt import views as jwt_views
from django.conf import settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('admin/', admin.site.urls),
path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
path('api/token/verify/', jwt_views.TokenVerifyView.as_view(), name='token_verify'),
url(r'^getuser$', views.get_user),
url(r'^signup$', views.user_signup),
url(r'^login$', views.user_login),
url(r'^logout$', views.user_logout),
path('getimage/', views.get_image),
# path('getuserimage/<int:user_id>', views.get_imgs_owned_by_user),
path('gettags/', views.get_tags),
path('api/upsert', views.upsert_image),
path('api/updateuser', views.update_user),
path('api/updateavatar', views.update_avatar),
] + staticfiles_urlpatterns() + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# url(r'^api/customers/$', views.customers_list),
# url(r'^api/customers/(?P<pk>[0-9]+)$', views.customers_detail),
# url(r'^api/gallery/(?P<pageNo>[0-9]+)$', views.image_page),
|
Python
| 50
| 38.119999
| 93
|
/backend/backend/urls.py
| 0.706033
| 0.699898
|
jeffcheung2015/gallery_django_reactjs
|
refs/heads/master
|
from django import forms
from .models import Image, Profile
from django.contrib.auth.models import User
from django.db import models
class UpsertImageForm(forms.ModelForm):
class Meta:
model = Image
fields = ["image_name", "image_desc", "image_file", "user", "tags"]
class UpdateUserForm(forms.ModelForm):
class Meta:
model = User
fields = ["email", "password"]
class UpdateAvatarForm(forms.ModelForm):
class Meta:
model = Profile
fields = ["avatar", "last_edit"]
|
Python
| 20
| 25.4
| 75
|
/backend/gallery/forms.py
| 0.662879
| 0.662879
|
LeeHanYeong/CI-Test
|
refs/heads/master
|
from django.test import TestCase
class SampleTest(TestCase):
def test_fail(self):
self.assertEqual(2, 1)
|
Python
| 6
| 18.833334
| 32
|
/app/ft/tests.py
| 0.697479
| 0.680672
|
ajhoward7/Machine_Learning
|
refs/heads/master
|
from .imports import *
from .torch_imports import *
from .core import *
import IPython, graphviz
from concurrent.futures import ProcessPoolExecutor
import sklearn_pandas, sklearn, warnings
from sklearn_pandas import DataFrameMapper
from sklearn.preprocessing import LabelEncoder, Imputer, StandardScaler
from pandas.api.types import is_string_dtype, is_numeric_dtype
from sklearn.ensemble import forest
from sklearn.tree import export_graphviz
def set_plot_sizes(sml, med, big):
plt.rc('font', size=sml) # controls default text sizes
plt.rc('axes', titlesize=sml) # fontsize of the axes title
plt.rc('axes', labelsize=med) # fontsize of the x and y labels
plt.rc('xtick', labelsize=sml) # fontsize of the tick labels
plt.rc('ytick', labelsize=sml) # fontsize of the tick labels
plt.rc('legend', fontsize=sml) # legend fontsize
plt.rc('figure', titlesize=big) # fontsize of the figure title
def parallel_trees(m, fn, n_jobs=8):
return list(ProcessPoolExecutor(n_jobs).map(fn, m.estimators_))
def draw_tree(t, df, size=10, ratio=0.6, precision=0):
s=export_graphviz(t, out_file=None, feature_names=df.columns, filled=True,
special_characters=True, rotate=True, precision=precision)
IPython.display.display(graphviz.Source(re.sub('Tree {',
f'Tree {{ size={size}; ratio={ratio}', s)))
def combine_date(years, months=1, days=1, weeks=None, hours=None, minutes=None,
seconds=None, milliseconds=None, microseconds=None, nanoseconds=None):
years = np.asarray(years) - 1970
months = np.asarray(months) - 1
days = np.asarray(days) - 1
types = ('<M8[Y]', '<m8[M]', '<m8[D]', '<m8[W]', '<m8[h]',
'<m8[m]', '<m8[s]', '<m8[ms]', '<m8[us]', '<m8[ns]')
vals = (years, months, days, weeks, hours, minutes, seconds,
milliseconds, microseconds, nanoseconds)
return sum(np.asarray(v, dtype=t) for t, v in zip(types, vals)
if v is not None)
def get_nn_mappers(df, cat_vars, contin_vars):
# Replace nulls with 0 for continuous, "" for categorical.
for v in contin_vars: df[v] = df[v].fillna(df[v].max()+100,)
for v in cat_vars: df[v].fillna('#NA#', inplace=True)
# list of tuples, containing variable and instance of a transformer for that variable
# for categoricals, use LabelEncoder to map to integers. For continuous, standardize
cat_maps = [(o, LabelEncoder()) for o in cat_vars]
contin_maps = [([o], StandardScaler()) for o in contin_vars]
return DataFrameMapper(cat_maps).fit(df), DataFrameMapper(contin_maps).fit(df)
def get_sample(df,n):
idxs = sorted(np.random.permutation(len(df)))
return df.iloc[idxs[:n]].copy()
def add_datepart(df, fldname):
fld = df[fldname]
targ_pre = re.sub('[Dd]ate$', '', fldname)
for n in ('Year', 'Month', 'Week', 'Day', 'Dayofweek', 'Dayofyear',
'Is_month_end', 'Is_month_start', 'Is_quarter_end', 'Is_quarter_start', 'Is_year_end', 'Is_year_start'):
df[targ_pre+n] = getattr(fld.dt,n.lower())
df[targ_pre+'Elapsed'] = fld.astype(np.int64) // 10**9
df.drop(fldname, axis=1, inplace=True)
def is_date(x): return np.issubdtype(x.dtype, np.datetime64)
def train_cats(df):
for n,c in df.items():
if is_string_dtype(c): df[n] = c.astype('category').cat.as_ordered()
def apply_cats(df, trn):
for n,c in df.items():
if trn[n].dtype.name=='category':
df[n] = pd.Categorical(c, categories=trn[n].cat.categories, ordered=True)
def fix_missing(df, col, name, na_dict):
if is_numeric_dtype(col):
if pd.isnull(col).sum() or (name in na_dict):
df[name+'_na'] = pd.isnull(col)
filler = na_dict[name] if name in na_dict else col.median()
df[name] = col.fillna(filler)
na_dict[name] = filler
return na_dict
def numericalize(df, col, name, max_n_cat):
if not is_numeric_dtype(col) and ( max_n_cat is None or col.nunique()>max_n_cat):
df[name] = col.cat.codes+1
def scale_vars(df):
warnings.filterwarnings('ignore', category=sklearn.exceptions.DataConversionWarning)
map_f = [([n],StandardScaler()) for n in df.columns if is_numeric_dtype(df[n])]
mapper = DataFrameMapper(map_f).fit(df)
df[mapper.transformed_names_] = mapper.transform(df)
return mapper
def proc_df(df, y_fld, skip_flds=None, do_scale=False, na_dict=None,
preproc_fn=None, max_n_cat=None, subset=None):
if not skip_flds: skip_flds=[]
if subset: df = get_sample(df,subset)
df = df.copy()
if preproc_fn: preproc_fn(df)
y = df[y_fld].values
df.drop(skip_flds+[y_fld], axis=1, inplace=True)
if na_dict is None: na_dict = {}
for n,c in df.items(): na_dict = fix_missing(df, c, n, na_dict)
if do_scale: mapper = scale_vars(df)
for n,c in df.items(): numericalize(df, c, n, max_n_cat)
res = [pd.get_dummies(df, dummy_na=True), y, na_dict]
if do_scale: res = res + [mapper]
return res
def rf_feat_importance(m, df):
return pd.DataFrame({'cols':df.columns, 'imp':m.feature_importances_}
).sort_values('imp', ascending=False)
def set_rf_samples(n):
forest._generate_sample_indices = (lambda rs, n_samples:
forest.check_random_state(rs).randint(0, n_samples, n))
def reset_rf_samples():
forest._generate_sample_indices = (lambda rs, n_samples:
forest.check_random_state(rs).randint(0, n_samples, n_samples))
|
Python
| 129
| 41.550388
| 116
|
/ML/fastai/structured.py
| 0.645537
| 0.638251
|
olof98johansson/SentimentAnalysisNLP
|
refs/heads/main
|
import train
import preprocessing
def run():
'''
Training function to run the training process after specifying parameters
'''
preprocessing.config.paths = ['./training_data/depressive1.json',
'./training_data/depressive2.json',
'./training_data/depressive3.json',
'./training_data/depressive4.json',
'./training_data/depressive5.json',
'./training_data/depressive6.json',
'./training_data/non-depressive1.json',
'./training_data/non-depressive2.json',
'./training_data/non-depressive3.json',
'./training_data/non-depressive4.json',
'./training_data/non-depressive5.json',
'./training_data/non-depressive6.json']
preprocessing.config.save_path = './training_data/all_training_data.csv'
preprocessing.config.labels = ['depressive', 'depressive', 'depressive', 'depressive', 'depressive', 'depressive',
'not-depressive', 'not-depressive', 'not-depressive', 'not-depressive',
'not-depressive', 'not-depressive']
preprocessing.config.keywords = ['depressed', 'lonely', 'sad', 'depression', 'tired', 'anxious',
'happy', 'joy', 'thankful', 'health', 'hopeful', 'glad']
preprocessing.config.nr_of_tweets = [1000, 1000, 1000, 1000, 1000, 1000,
1000, 1000, 1000, 1000, 1000, 1000]
history, early_stop_check = train.train_rnn(save_path='./weights/lstm_model_2.pth', collect=True) # Collect=False if already collected data
train.show_progress(history=history, save_name='./plots/training_progress.png')
train.animate_progress(history=history, save_path='./plots/training_animation_progress_REAL.gif',
early_stop_check=early_stop_check)
run()
|
Python
| 43
| 48.674419
| 143
|
/main.py
| 0.534612
| 0.50608
|
olof98johansson/SentimentAnalysisNLP
|
refs/heads/main
|
import torch
import torch.nn as nn
import models
import preprocessing
from collections import defaultdict
import time
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('darkgrid')
from celluloid import Camera
def Logger(elapsed_time, epoch, epochs, tr_loss, tr_acc, val_loss, val_acc):
'''
Logger function to track training progress
Input: elapsed_time - the current elapsed training time
epoch - current epoch
epochs - total number of epochs
tr_loss/val_loss - current training/validation loss
tr_acc/val_acc - current training/validation accuracy
'''
tim = 'sec'
if elapsed_time > 60 and elapsed_time <= 3600:
elapsed_time /= 60
tim = 'min'
elif elapsed_time > 3600:
elapsed_time /= 3600
tim = 'hrs'
elapsed_time = format(elapsed_time, '.2f')
print(f'Elapsed time: {elapsed_time} {tim} Epoch: {epoch}/{epochs} ',
f'Train Loss: {tr_loss:.4f} Val Loss: {val_loss:.4f} ',
f'Train Acc: {tr_acc:.2f}% Val Acc: {val_acc:.2f}%')
class EarlyStopping(object):
'''
Stops the training progress if the performance has not improved for
a number of epochs to avoid overfitting
'''
def __init__(self, patience):
super().__init__()
self.best_loss = 1e5
self.patience = patience
self.nr_no_improved = 0
def update(self, curr_loss):
if curr_loss < self.best_loss:
self.best_loss = curr_loss
self.nr_no_improved = 0
return False
else:
self.nr_no_improved+=1
if self.nr_no_improved >= self.patience:
print(f'Early stopping! Model did not improve for last {self.nr_no_improved} epochs')
return True
else:
return False
class rnn_params:
'''
Configuration to store and tune RNN specific hyperparameters
'''
rnn_type = 'lstm'
emb_dim = 64
rnn_size = 64
nr_layers = 1
dropout = 0.5
lr = 1e-3
batch_size = 64
n_epochs = 30
decay = 1e-5
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
patience = 5
def train_rnn(save_path = None, collect=True):
'''
Training function for the rnn model that trains and validates the models performance
Input: save_path - path and file name to where to save the trained weights (type: string)
collect - specify if to collect data or not (type: boolean)
Output: history - history of the models training progression (type: defaultdict of lists)
early_stop_check - if early stopping has been executed or not (type: boolean)
'''
dataloaders, vocab_size, n_classes = preprocessing.preprocess(rnn_params.batch_size, collect=collect)
train_loader, val_loader = dataloaders
model = models.RNNModel(rnn_type=rnn_params.rnn_type, nr_layers=rnn_params.nr_layers,
voc_size=vocab_size, emb_dim=rnn_params.emb_dim, rnn_size=rnn_params.rnn_size,
dropout=rnn_params.dropout, n_classes=n_classes)
loss_fn = nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=rnn_params.lr, weight_decay=rnn_params.decay)
model.to(rnn_params.device)
history = defaultdict(list)
init_training_time = time.time()
early_stopping = EarlyStopping(patience=rnn_params.patience)
for epoch in range(1, rnn_params.n_epochs):
model.train()
h = model.init_hidden(rnn_params.batch_size, device=rnn_params.device)
n_correct, n_instances, total_loss = 0,0,0
for inputs, labels in train_loader:
model.zero_grad()
inputs = inputs.to(rnn_params.device)
labels = labels.to(rnn_params.device)
h = tuple([each.data for each in h])
outputs, h = model(inputs, h)
loss = loss_fn(outputs.squeeze(), labels.float())
total_loss+=loss.item()
n_instances+=labels.shape[0]
predictions = torch.round(outputs.squeeze())
n_correct += (torch.sum(predictions == labels.float())).item()
optimizer.zero_grad()
loss.backward()
optimizer.step()
epoch_loss = total_loss / (len(train_loader))
epoch_acc = n_correct / n_instances
n_correct_val, n_instances_val, total_loss_val = 0, 0, 0
model.eval()
val_h = model.init_hidden(rnn_params.batch_size, device=rnn_params.device)
for val_inp, val_lab in val_loader:
val_inp = val_inp.to(rnn_params.device)
val_lab = val_lab.to(rnn_params.device)
val_h = tuple([each.data for each in val_h])
val_out, val_h = model(val_inp, val_h)
val_loss = loss_fn(val_out.squeeze(), val_lab.float())
total_loss_val += val_loss.item()
n_instances_val += val_lab.shape[0]
val_preds = torch.round(val_out.squeeze())
n_correct_val += (torch.sum(val_preds == val_lab.float())).item()
epoch_val_loss = total_loss_val / len(val_loader)
epoch_val_acc = n_correct_val / n_instances_val
curr_time = time.time()
Logger(curr_time-init_training_time, epoch, rnn_params.n_epochs, epoch_loss,
epoch_acc, epoch_val_loss, epoch_val_acc)
history['training loss'].append(epoch_loss)
history['training acc'].append(epoch_acc)
history['validation loss'].append(epoch_val_loss)
history['validation acc'].append(epoch_val_acc)
early_stop_check = early_stopping.update(epoch_val_loss)
if early_stop_check:
models.ModelUtils.save_model(save_path=save_path, model=model)
return history, early_stop_check
if save_path:
root, ext = os.path.splitext(save_path)
save_path = root + '.pth'
models.ModelUtils.save_model(save_path=save_path, model=model)
return history, early_stop_check
def show_progress(history, save_name = None):
fig, axes = plt.subplots(1, 2, figsize=(21, 7))
fig.suptitle('Training progression', fontsize=18)
axes[0].plot(history['training loss'], linewidth=2, color='#99ccff', alpha=0.9, label='Training')
axes[0].plot(history['validation loss'], linewidth=2, color='#cc99ff', alpha=0.9, label='Validation')
axes[0].set_xlabel(xlabel='Epochs', fontsize=12)
axes[0].set_ylabel(ylabel=r'$\mathcal{L}(\hat{y}, y)$', fontsize=12)
axes[0].set_title(label='Losses', fontsize=14)
axes[1].plot(history['training acc'], linewidth=2, color='#99ccff', alpha=0.9, label='Training')
axes[1].plot(history['validation acc'], linewidth=2, color='#cc99ff', alpha=0.9, label='Validation')
axes[1].set_xlabel(xlabel='Epochs', fontsize=12)
axes[1].set_ylabel(ylabel=r'%', fontsize=12)
axes[1].set_title(label='Accuracies', fontsize=14)
axes[0].legend()
axes[1].legend()
if save_name:
plt.savefig(save_name, bbox_inches='tight')
plt.show()
def animate_progress(history, save_path, early_stop_check):
root, ext = os.path.splitext(save_path)
save_path = root + '.gif'
fig, axes = plt.subplots(1, 2, figsize=(15, 6))
camera = Camera(fig)
fig.suptitle('Training progression', fontsize=18)
axes[0].set_xlabel(xlabel='Epochs', fontsize=12)
axes[0].set_ylabel(ylabel=r'$\mathcal{L}(\hat{y}, y)$', fontsize=12)
axes[0].set_title(label='Losses', fontsize=14)
axes[1].set_xlabel(xlabel='Epochs', fontsize=12)
axes[1].set_ylabel(ylabel=r'%', fontsize=12)
axes[1].set_title(label='Accuracies', fontsize=14)
epochs = np.arange(len(history['training loss']))
for e in epochs:
axes[0].plot(epochs[:e], history['training loss'][:e], linewidth=2, color='#99ccff')
axes[0].plot(epochs[:e], history['validation loss'][:e], linewidth=2, color='#cc99ff')
axes[1].plot(epochs[:e], history['training acc'][:e], linewidth=2, color='#99ccff')
axes[1].plot(epochs[:e], history['validation acc'][:e], linewidth=2, color='#cc99ff')
axes[0].legend(['Training', 'Validation'])
axes[1].legend(['Training', 'Validation'])
camera.snap()
for i in range(10):
axes[0].plot(epochs, history['training loss'], linewidth=2, color='#99ccff')
axes[0].plot(epochs, history['validation loss'], linewidth=2, color='#cc99ff')
axes[1].plot(epochs, history['training acc'], linewidth=2, color='#99ccff')
axes[1].plot(epochs, history['validation acc'], linewidth=2, color='#cc99ff')
axes[0].legend(['Training', 'Validation'])
axes[1].legend(['Training', 'Validation'])
camera.snap()
animation = camera.animate()
animation.save(save_path, writer='imagemagick')
|
Python
| 234
| 36.901711
| 106
|
/train.py
| 0.618002
| 0.599414
|
olof98johansson/SentimentAnalysisNLP
|
refs/heads/main
|
# NOTE: TWINT NEEDS TO BE INSTALLEED BY THE FOLLOWING COMMAND:
# pip install --user --upgrade git+https://github.com/twintproject/twint.git@origin/master#egg=twint
# OTHERWISE IT WON'T WORK
import twint
import nest_asyncio
nest_asyncio.apply()
from dateutil import rrule
from datetime import datetime, timedelta
def get_weeks(start_date, end_date):
'''
Finds collection of weeks chronologically from a starting date to a final date
Input: start_date - date of which to start collecting with format [year, month, day] (type: list of ints)
end_date - date of which to stop collecting with format [year, month, day] (type: list of ints)
Output: weeks - list containing the lists of starting and ending date for each week with format
"%Y-%m-%d %h-%m-%s" (type: list of lists of strings)
'''
start_year, start_month, start_day = start_date
final_year, final_month, final_day = end_date
start = datetime(start_year, start_month, start_day)
end = datetime(final_year, final_month, final_day)
dates = rrule.rrule(rrule.WEEKLY, dtstart=start, until=end)
nr_weeks = 0
for _ in dates:
nr_weeks+=1
weeks = []
for idx, dt in enumerate(dates):
if idx < nr_weeks-1:
week = [dates[idx].date().strftime('%Y-%m-%d %H:%M:%S'),
dates[idx+1].date().strftime('%Y-%m-%d %H:%M:%S')]
weeks.append(week)
return weeks
def collect_tweets(keywords = None, nr_tweets = None,
output_file=None, coord=None, timespan=[None, None]):
'''
Collectiing tweets using twint based on different attributes and save to json file
Input: keywords - keywords that the tweet should contain (type: string)
nr_tweets - number of tweets to collect (type: int)
output_file - path and name to where the file should be saved (type: string, extension: .json)
near - location or city of which the tweets were tweeted (type: string)
timespan - timespan of when the tweet was tweeted in format "%Y-%m-%d %h-%m-%s" (type: string)
Output: Returns twint object
'''
# configuration
config = twint.Config()
# Search keyword
config.Search = keywords
# Language
config.Lang = "en"
# Number of tweets
config.Limit = nr_tweets
#Dates
config.Since = timespan[0]
config.Until = timespan[1]
# Output file format (alternatives: json, csv, SQLite)
config.Store_json = True
# Name of output file with format extension (i.e NAME.json, NAME.csv etc)
config.Output = output_file
config.Geo = coord
# running search
twint.run.Search(config)
return twint
# EXAMPLE
def test():
config = twint.Config()
config.Search = None
config.Near = "london"
config.Lang = "en"
config.Limit = 10
config.Since = "2016-10-29 00:00:00"
config.Until = "2016-11-29 12:15:19"
config.Store_json = True
config.Output = "test2.json"
#running search
twint.run.Search(config)
#test()
|
Python
| 93
| 31.838709
| 109
|
/twint_scraping.py
| 0.644728
| 0.632613
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.