Skip to content

Instantly share code, notes, and snippets.

@hxer
hxer / isintersecion.py
Created February 21, 2016 07:55
判断两个集合是否有交集
def is_intersection(a, b):
'''
input:
a = [1, 2, 3]
b = [3, 6, 9]
output:
True
'''
return any(_ in a for _ in b)
@hxer
hxer / upgradepackage.py
Last active October 11, 2016 02:16
一键升级python 第三方包
# -*- coding: utf-8 -*-
# auto upgrade python package
# need root privilige
"""
import pip
from subprocess import call
for dist in pip.get_installed_distributions():
call("pip install --upgrade " + dist.project_name, shell=True)
@hxer
hxer / log.py
Last active September 18, 2021 14:37
python logging 将日志同时输出文件和屏幕
# 日志打印屏幕或文件
def setup_logger_2(logger_name, level=logging.INFO, handler='all', log_file=''):
"""
:param logger_name:
:param log_file:
:param level:
:param handler: file or stream or all
:return:
"""
log_setup = logging.getLogger(logger_name)
@hxer
hxer / factorial.py
Created March 1, 2016 01:58
python factorial
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
by hx, 2015.11.24
version:python2.7.x
"""
def factorial(x):
res = 1
@hxer
hxer / request_flask.py
Created March 2, 2016 04:45
Receiving and POSTing JSON with requests [Python and Flask]
import os
# Using Flask since Python doesn't have built-in session management
from flask import Flask, session, render_template
# Our target library
import requests
import json
app = Flask(__name__)
# Generate a secret random key for the session
@hxer
hxer / randomstring.py
Created March 3, 2016 02:43
python生成随机字符串
import os
def randomString(n):
return (''.join(map(lambda xx:(hex(ord(xx))[2:]),os.urandom(n))))[0:16]
print randomString(16)
"""
os.urandom(n) : 随机生成n个字节的串,一个字节是8位,我猜是这8位二进制数是随机的,所以这个字节也是随机的。所以没有指定的编码方案可以很好地把所有这个字符串显示转换成功,即有可能会乱码
@hxer
hxer / displayattrs.py
Created March 9, 2016 03:47
查看python所有属性及文档描述
import inspect
def displayattrs(objects):
attrs = inspect.getmembers(objects)
for attr in attrs:
attr = attr[0]
filters = ['_', '__']
if not any(map(attr.startswith, filters)):
doc = getattr(objects, attr).__doc__
if doc:
@hxer
hxer / md5file.py
Created March 10, 2016 03:10
计算文件md5值
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
@hxer
hxer / str_2_binstr.py
Created April 27, 2016 07:46
字符串转二进制字符串
''.join([ '{0:08b}'.format(ord(i)) for i in src ])
# -*- coding: utf-8 -*-
"""
"""
import functools
from flask import Flask, jsonify
from gevent.pywsgi import WSGIServer