android 在运行时请求权限

参考 https://developer.android.google.cn/training/permissions/requesting.html?hl=zh-cn

 // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED) {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {
                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {

                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        0);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }

此处是获取读取sd卡内容的权限

python dataframe中元素替换

zip()可以将多个一维向量组合成元组列表

import numpy as np
a=[1,2,3]
b=[2,3,4]
z = zip(a,b)
print(list(z))
#输出  [(1, 2), (2, 3), (3, 4)]

于是当我们有一个dataframe

可以先利用zip创建一个dict

a=[1,2,3]
b=[2,3,4]
z = dict(zip(a,b))

再用过replace实现把1,2,3分别替换成,2,3,4

df.replace(z)

在现有多个共享键值表格的时候这样操作比较方便。

使用代理的爬虫小程序

import urllib.request
import os
import sys
import re

def testArgument(url):
        TP=TestProxy(url)

def tipUse():
    print('改程序只能输入一个参数,这个参数必须是可用的proxy')
    print('usage:python test Urllib2WithProxy.py http//1.2.3.4:5')
    print('usage:python test Urllib2WithProxy.py https//1.2.3.4:5')

class TestProxy(object):
    def __init__(self,proxy):
        self.proxy = proxy
        self.checkProxyFormat(self.proxy)
        self.url = 'http://www.baidu.com'
        self.timeout=5
        self.flagWord='百度'
        self.useProxy(self.proxy)

    def checkProxyFormat(self,proxy):
        try:
            proxyMatch = re.compile('http[s]?://[\d]{1,3}\.{\d}{1,3}\.[\d]{1,3}:[\d]{1,5}$')
            proxyMatch.match(proxy)
        except AttributeError:
            tipUse()
            exit()
        flag = 1
        proxy = proxy.replace('//','')
        try:
            protocol = proxy.split(':')[0]
            ip = proxy.split(':')[1]
            port = proxy.split(':')[2]
        except IndexError:
            print('下标出界')
            tipUse()
            exit()
        flag = flag and len(proxy.split(':')) and len(ip.split('.'))

        flag = ip.split('.')[0] in map(str,range(1,256)) and flag
        flag = ip.split('.')[1] in map(str,range(256)) and flag
        flag = ip.split('.')[2] in map(str,range(256)) and flag
        flag = ip.split('.')[3] in map(str,range(1,255)) and flag
        flag = protocol in ['http','https'] and flag
        flag = port in map(str,range(1,65535)) and flag
        if flag:
            print('输入的http代理服务器符合标准')
        else:
            tipUse()
            exit()
            
    def useProxy(self,proxy):
        protocol = proxy.split('//')[0].replace(':','')
        ip = proxy.split('//')[1]
        opener = urllib.request.build_opener(urllib.request.ProxyHandler({protocol:ip}))
        urllib.request.install_opener(opener)
        try:
            response = urllib.request.urlopen(self.url,timeout=self.timeout)
        except:
            print('连接错误,退出程序')
            exit()
        
        data = response.read()
        data = data.decode('UTF-8')
        print(data)

testArgument('https://117.135.250.134:80')

python异步IO的发展历程

python中异步IO发展分为三个发展阶段

1.使用yield和send

2.使用@asyncio.coroutine和yield from

3.使用async/await关键字

一、yield和send


def fib(n):
	res = [0]*n
	index = 0
	a = 0
	b = 1
	while index < n:
		res[index] = b
		a, b = b, a + b
		index += 1
	return res

for res in fib(20):
	print(res)

这是一段输出斐波那契数列的代码,需要经过数次迭代。这种方式的缺点是执行这种迭代运算需要占用大量内存,而我们最终的目的如果只是想得到某一个顺序位上的数字,该方法就不太合适了。


def fib(n):
	res = [0]*n
	index = 0
	a = 0
	b = 1
	while index < n:
		yield b
		a, b = b, a + b
		index += 1
	
for res in fib(20):
	print(res)

当我们使用yield 时,无须在函数内加入return,直接用for in,便可直接得到yield的值,即没运行一次,就会再执行一次next(fib(20)) (相当于执行下一次吧)。


import random
import time
def fib(n):
	index = 0
	a = 0
	b = 1
	while index < n:
		sleep_cnt = yield b
		print('delay {0} seconds'.format(sleep_cnt))
		time.sleep(sleep_cnt)
		a, b = b, a + b
		index += 1
		
N = 20
sfib = fib(N)
res = next(sfib)
while True:
	print(res)
	try:
		res = sfib.send(random.uniform(0, 0.5))
	except StopIteration:
		break

当我们想往线程中发送数据时,可以用到send函数,此处使用time库,虚拟一下io的延迟。

二、@asyncio.coroutine和yield from


def fibAgain(n):
	print('I am copy from fib')
	yield from fib(n)
	print('Copy end')
	
for res in fibAgain(20):
	print(res)
以上代码承接上文,由此可见,yield from相当于重构之前的yield的代码,重新来一次刷新。

import asyncio

@asyncio.coroutine
def wget(host):
    print('wget %s...' % host)
    connect = asyncio.open_connection(host, 80)
    reader, writer = yield from connect
    header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
    writer.write(header.encode('utf-8'))
    yield from writer.drain()
    while True:
        line = yield from reader.readline()
        if line == b'\r\n':
            break
        print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
    # Ignore the body, close the socket
    writer.close()

loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

以上是一个连接网站的一个例子,我们使用yield挂起需要异步IO的代码,在函数前加入@asyncio.coroutine关键字,再使用实现线程的并发。

三、async/await关键字


async def smart_fib(n):
	index = 0
	a = 0
	b = 1
	while index < n:
		sleep_secs = random.uniform(0, 0.2)
		await asyncio.sleep(sleep_secs)
		print('Smart one think {} secs to get {}'.format(sleep_secs, b))
		a, b = b, a + b
		index += 1
 
async def stupid_fib(n):
	index = 0
	a = 0
	b = 1
	while index < n:
		sleep_secs = random.uniform(0, 0.4)
		await asyncio.sleep(sleep_secs)
		print('Stupid one think {} secs to get {}'.format(sleep_secs, b))
		a, b = b, a + b
		index += 1
 
if __name__ == '__main__':
	loop = asyncio.get_event_loop()
	tasks = [
		smart_fib(10)),
		stupid_fib(10))
	]
	loop.run_until_complete(asyncio.wait(tasks))
	print('All fib finished.')
	loop.close()

理解了yield from之后,async/await关键字就很好理解了,其实就是对yield from的简化。

pandas 数据处理

pandas中数据可以分为series,dataframe,panel分别表示一维至三维数据。

其中在构造时,index表示行名,columns表示列名

series:

构造方式 

 s = pd.Series(data, index=index)
s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])

或者以字典的形式

In [7]: d = {'a' : 0., 'b' : 1., 'c' : 2.}

In [8]: pd.Series(d)
Out[8]: 
a    0.0
b    1.0
c    2.0
dtype: float64

In [9]: pd.Series(d, index=['b', 'c', 'd', 'a'])
Out[9]: 
b    1.0
c    2.0
d    NaN
a    0.0
dtype: float64

series的提取方式

In [11]: s[0]  #提取一个
Out[11]: 0.46911229990718628

In [12]: s[:3]    #提起开始至第三行
Out[12]:
a    0.4691
b   -0.2829
c   -1.5091
dtype: float64

In [13]: s[s > s.median()]   #按要求提取
Out[13]:
a    0.4691
e    1.2121
dtype: float64

In [14]: s[[4, 3, 1]]
Out[14]:
e    1.2121
d   -1.1356
b   -0.2829
dtype: float64

In [15]: np.exp(s)
Out[15]:
a    1.5986
b    0.7536
c    0.2211
d    0.3212
e    3.3606
dtype: float64

dataframe:

构造方式 

In [32]: d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
   ....:      'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
   ....: 

In [33]: df = pd.DataFrame(d)

In [34]: df
Out[34]: 
   one  two
a  1.0  1.0
b  2.0  2.0
c  3.0  3.0
d  NaN  4.0

In [35]: pd.DataFrame(d, index=['d', 'b', 'a'])
Out[35]: 
   one  two
d  NaN  4.0
b  2.0  2.0
a  1.0  1.0

In [36]: pd.DataFrame(d, index=['d', 'b', 'a'], columns=['two', 'three'])
Out[36]: 
   two three
d  4.0   NaN
b  2.0   NaN
a  1.0   NaN

提取或按要求添加字段

In [56]: df['one']
Out[56]: 
a    1.0
b    2.0
c    3.0
d    NaN
Name: one, dtype: float64

In [57]: df['three'] = df['one'] * df['two']

In [58]: df['flag'] = df['one'] > 2

In [59]: df
Out[59]: 
   one  two  three   flag
a  1.0  1.0    1.0  False
b  2.0  2.0    4.0  False
c  3.0  3.0    9.0   True
d  NaN  4.0    NaN  False