blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
281
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
6
116
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
313 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
18.2k
668M
star_events_count
int64
0
102k
fork_events_count
int64
0
38.2k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
107 values
src_encoding
stringclasses
20 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
4
6.02M
extension
stringclasses
78 values
content
stringlengths
2
6.02M
authors
listlengths
1
1
author
stringlengths
0
175
c84672dce8dcc55f0b56317afaca39ca97c9f8e9
5caea19ef73c546b7c53b87fe701129dc98f8327
/interaction_analysis/main_text_scenario1/main_figures.py
5142dc7b518ebcc15eeac29ed74eefa2d6678379
[]
no_license
ShotaSHIBASAKI/Switching_Environment
8fa9a8007f49022e821eaf6741abe1e744cc0576
004ac7cf02b97bc997706ac1eb037c13e5e48f9a
refs/heads/master
2023-08-10T16:21:32.163682
2021-09-21T08:02:58
2021-09-21T08:02:58
290,143,823
1
0
null
null
null
null
UTF-8
Python
false
false
16,647
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 25 11:54:38 2020 Plot Figs.2 and 3 in the main text """ import os import numpy as np import matplotlib.pyplot as plt import scipy as sp from scipy import stats import pymc3 as pm from scipy.stats import dirichlet def SmaplingDIr(obs, index): """ Estimating 95% Heighest posterior deinsty (HDP) in Dirichlet distribution. Although observed data follows a multinomial-distribution, we can also use the cases when the data are binary (in such cases,DIrichlet is Beta dist) Parameters ---------- obs : 1D array number of obseraving each event. index : int event to analyze its occuring probability. Returns ------- 95% HPD of occuring event index """ a=np.ones(np.size(obs)) # prior is uniform a+=obs # posterior after observing data #posterior = dirichlet(a) sample=dirichlet.rvs(a, size=10000)#sampleing parameter values from posterior distirbution sample_index=sample[:, index] # focus on parameter[index] alone """ plt.hist(sample_index) plt.xlim(0,1) plt.show() """ # calculate 95% HDI return pm.stats.hpd(sample_index) #-------------------------------------------------------------- #Fig.3A: different in extinction probabilities from mono- to co-cultures #Fig.3B: some exaples from Fig2A def Fig3AB (model, val=0): # model: scenario of environmental switching: 1,2,or 3 # val; which species 2 to comp@ete with: in the main text, choose 0. # You can also chose val =1,..., 4 for more sloer grower typ=1 """ plotting the probabilities of diff in extinction """ d_array=np.linspace(0.1, 1.0, 10) # toxin sensitivity nu_array=np.linspace(-5, 3, 9) # log scale in 3d is problematic in matplot # extinction prob at nu=10^-5(->0),10^-4, 10^-3, 10^-2, 10^-1, 10^0, 10^1, 10^2, 10^3(->infty) one_ext=np.zeros([np.size(d_array), np.size(nu_array)]) # extinction prob in absence of sepcies 2 two_ext=np.zeros([np.size(d_array), np.size(nu_array)]) # extinction prob in presence of species 2 diff=np.zeros([np.size(d_array), np.size(nu_array)]) for i in range(np.size(d_array)): death=d_array[i] # In absence of species 2 path=str('./death%.1f/OneConsumer' %(death)) os.chdir(path) data=np.loadtxt(str('OneConsumer_Extinction_model%d.csv'%(model)), delimiter=',', skiprows=1) one_ext[i, :]=data os.chdir('../TwoConsumer') # Extinction prob in presence of species 2 data=np.loadtxt(str('TwoConsumer_Extinction_model%d_competitor%d.csv'%(model, typ)), delimiter=',', skiprows=1) two_ext[i, :]=data[val,:] diff[i, :]=one_ext[i,:]- two_ext[i, :] os.chdir('../../') #plot figures #plot Fig.2A ax1 = plt.subplot(111) heatmap1=ax1.pcolor(diff, cmap='Blues_r') #heatmap=ax.pcolor(comp_array, cmap=plt.cm.bwr,vmin=0) ax1.xaxis.tick_bottom() plt.xlabel('$\log_{10}$ switching rate', fontsize=20) plt.ylabel('toxin sensitivity', fontsize=20) plt.title('diff. in extinction prob', fontsize=20) plt.xticks([0.5, 2.5, 4.5, 6.5, 8.5],['-5', '-3', '-1', '1','3'], fontsize=16) plt.yticks([1.5, 3.5, 5.5, 7.5, 9.5],['0.2', '0.4', '0.6', '0.8', '1.0'], fontsize=16) cb1=plt.colorbar(heatmap1, ticks=[-0.15, -0.1, -0.05, 0]) cb1.ax.tick_params(labelsize=14) plt.savefig('DiffExtinction_Heatmap_'+str('_Model%d.pdf'%(model)), bbox_inches='tight', pad_inches=0.05) plt.show() #plot Fig.3B rate=np.linspace(-5, 3, 9) col_list=['#8dd3c7', '#fb8072', '#bebada', '#80b1d3'] lab_list=['sensitivity 0.1', 'sensitivity 0.2', 'sensitivity 0.4', 'sensitivity 0.6'] example=[0,1,3,5] for i in range(len(example)): plt.plot(rate, diff[example[i], :], color=col_list[i], label=lab_list[i], marker='D', linewidth=2) #Calculate 95% HDP for each dot using Dirichlet (or beta) distribution #As we have 10**5 data, 95% HDP are unobservable in the figure for j in range(np.size(rate)): ext1=one_ext[example[i],j] # probs of extinction and persistence obs1=np.array([ext1, 1-ext1])*10**5 # total observation is 10**5 times ext2=two_ext[example[i],j] obs2=np.array([ext2,1-ext2])*10**5 #estimate 95%HDI sample1=dirichlet.rvs(obs1+1, size=10000) sample2=dirichlet.rvs(obs2+1, size=10000) sample_diff=sample1[:,0]-sample2[:, 0] hdp_l, hdp_h=pm.stats.hpd(sample_diff) plt.vlines(rate[j],hdp_l, hdp_h, color=col_list[i]) plt.xlabel('$\log_{10}$'+'switching rate',fontsize=20) plt.ylabel('diff. in extinction prob',fontsize=20) plt.xticks(fontsize=16, ticks=[-4, -2, 0, 2]) plt.yticks(fontsize=16, ticks=[0, -0.05, -0.1, -0.15, -0.2]) plt.legend(loc='lower center', bbox_to_anchor=(.5,1.05), ncol=2, fontsize=16) plt.savefig('DiffExtinction_examples.pdf',bbox_inches='tight',pad_inches=0.05) plt.show() #-------------------------------------------------------------- #Fig.3C: probabilities of exclusion of species #Fig.3D: some exaples from Fig.2C def Fig3CD (model, val=0): # model: scenario of environmental switching: 1,2,or 3 # val; which species 2 to comp@ete with: in the main text, choose 0. # You can also chose val =1,..., 4 for more sloer grower typ=1 """ plotting the probabilities of diff in extinction """ d_array=np.linspace(0.1, 1.0, 10) # toxin sensitivity nu_array=np.linspace(-5, 3, 9) # log scale in 3d is problematic in matplot # extinction prob at nu=10^-5(->0),10^-4, 10^-3, 10^-2, 10^-1, 10^0, 10^1, 10^2, 10^3(->infty) comp_exc=np.zeros([np.size(d_array),np.size(nu_array)]) # prob of competitive exclusion for i in range(np.size(d_array)): death=d_array[i] # In absence of species 2 path=str('./death%.1f/TwoConsumer' %(death)) os.chdir(path) #Competitive exclusion data=np.loadtxt(str('TwoConsumer_CompetitiveExclusion_model%d_competitor%d.csv'%(model, typ)), delimiter=',', skiprows=1) comp_exc[i, :]=data[val,:] os.chdir('../../') #plot figures #plot Fig.3C ax1 = plt.subplot(111) heatmap1=ax1.pcolor(comp_exc, cmap='Blues',vmin=0) #heatmap=ax.pcolor(comp_array, cmap=plt.cm.bwr,vmin=0) ax1.xaxis.tick_bottom() plt.xlabel('$\log_{10}$ switching rate', fontsize=20) plt.ylabel('toxin sensitivity', fontsize=20) plt.title('prob. of exclusion of fittest', fontsize=20) plt.xticks([0.5, 2.5, 4.5, 6.5, 8.5],['-5', '-3', '-1', '1','3'], fontsize=16) plt.yticks([1.5, 3.5, 5.5, 7.5, 9.5],['0.2', '0.4', '0.6', '0.8', '1.0'], fontsize=16) cb1=plt.colorbar(heatmap1, ticks=[0,0.05, 0.1, 0.15]) cb1.ax.tick_params(labelsize=14) plt.savefig('CompetitiveExclusion_Heatmap_'+str('_Model%d.pdf'%(model)), bbox_inches='tight', pad_inches=0.05) plt.show() #plot Fig.3D toxin=np.linspace(0.1, 1.0, 10) Data=np.zeros([3, 10]) Data[0, :]= comp_exc[:, 0] # nu=10^-5 Data[1, :]= comp_exc[:, 4] # nu =0.1 Data[2, :]= comp_exc[:, -1] # nu=10^3 #plot the data #col_list=['#8dd3c7', '#fb8072', '#80b1d3'] col_list=['grey', 'slategrey', 'black'] line_list=['dotted', 'dashed', 'solid'] lab_list=['slow', 'intermediate', 'fast'] for i in range(np.size(Data, 0)): plt.plot(toxin, Data[i, :], color=col_list[i], label=lab_list[i], linestyle=line_list[i], marker='D', linewidth=2) """ Plot 95% HDP. Again, HDPs are too samll to see in the plot For simplicity, we use beta distribution to see the probability that competitive exclusion of sp1 by sp2 happens. We may also use Dirichlet distribution instead by considering 1. both species extinction 2. both species persistnce 3. competitive exclusion of sp1 by sp2 and 4. competitive exclusion of sp2 by sp1 """ for j in range(np.size(toxin)): comp=Data[i,j] a=np.array([comp, 1-comp])*10**5 # total number of simulations is 10**5 sample=dirichlet.rvs(a+1, size=10000) hdp_l, hdp_h=pm.stats.hpd(sample[:,0]) plt.vlines(toxin[j],hdp_l, hdp_h, color=col_list[i]) plt.xlabel('toxin sensitivity',fontsize=20) plt.ylabel('prob. of exclusion of fittest',fontsize=20) plt.xticks(fontsize=16) plt.yticks(fontsize=16) plt.legend(loc='best', fontsize=16) plt.savefig('CompetitiveExclusion_furthest.pdf',bbox_inches='tight',pad_inches=0.05) plt.show() #------------------------------------------- def Fig4(): # plot the sample dynamics where exclusion of fittest happens fname_list=['./TimeSeries_switching10^-3_delta0.1_trial2.csv', './TimeSeries_switching10^-1_delta0.2_trial0.csv', './TimeSeries_switching10^1_delta0.4_trial18.csv'] for i in range(len(fname_list)): df=pd.read_csv(fname_list[i]) df=df.rename(columns={' resource': 'resource',' consumer1': 'species1', ' consumer2': 'species2',' toxin': 'toxin', ' environment': 'environment'}) df_good=df[df.environment==1] df_bad=df[df.environment==-1] plt.plot(df.time, df.resource, label='resource', color='#fdb462') plt.plot(df.time, df.toxin, label='toxin', color='#80b1d3') plt.plot(df.time, df.species1, label='species 1', color='#8dd3c7') plt.plot(df.time, df.species2, label='species 2',color='#b3de69') plt.legend(bbox_to_anchor=(0.5, 1.15), loc='center', ncol=2, fontsize=18) plt.scatter(df_bad.time, 0*df_bad.time, color='k', marker='s', s=30) plt.scatter(df_good.time, 0*df_good.time, color='w', marker='s', s=30) plt.xlabel('time', fontsize=20) plt.xticks(fontsize=16) plt.ylabel('amount or abundances', fontsize=20) plt.xlim(0, 205) plt.ylim(0, 160) plt.yticks(fontsize=16) plt.text( x=25,y=145, s=str("nu = 10^%d, delta=%.1f" %(-1, 0.2)),fontsize=20) gname=str('Ex_exclusion%d.pdf' %(i)) plt.savefig(gname, bbox_inches='tight',pad_inches=0.05) plt.show() #-------------------------------- #Fig.5A-C: both extinction and exclusion of fittest without EFs def Fig5AC(): os.chdir('../appendix/Appendix3_constant_env/scenario1') CompExcl=np.loadtxt('CompetitiveExclusion_model1.csv', delimiter=',', skiprows=1) BothExtinct=np.loadtxt('BothExtinction_model1.csv', delimiter=',', skiprows=1) death=np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) col_list=['#8dd3c7', '#fb8072', '#80b1d3'] lab_list=['scarce', 'mean', 'abundant'] width=0.05 for i in range(len(lab_list)): plt.bar(death, CompExcl[:, i], color=col_list[i], width=width, align='center', hatch='..', label='exclusion of fittest') plt.bar(death, BothExtinct[:, i], color=col_list[i], label='both extinction', width=width, align='center', bottom=CompExcl[:, i]) plt.xticks(fontsize=16) plt.ylabel('probability',fontsize=20) plt.yticks(fontsize=16) plt.ylim(0, 1) plt.xlabel('toxin sensitivity',fontsize=20) plt.legend(loc='lower center', bbox_to_anchor=(.5,1.05), ncol=2, fontsize=16) plt.plot(death, CompExcl[:, i], color='k', label=lab_list[i], linewidth=3) plt.text(x=0.05, y=0.9, s=lab_list[i], fontsize=20) for j in range(np.size(death)): comp=CompExcl[j,i] a=np.array([comp, 1-comp])*10**5 # total number of simulations is 10**5 sample=dirichlet.rvs(a+1, size=10000) hdp_l, hdp_h=pm.stats.hpd(sample[:,0]) plt.vlines(death[j],hdp_l, hdp_h, color=col_list[i]) plt.savefig('ConstantEnv_ver2' + lab_list[i] + '.pdf' ,bbox_inches='tight',pad_inches=0.05) plt.show() #------------------------------------------------ #Fig.A14: Correlation of non-monotonicity and distances between critical toxin sensitivities # This figure was previously shown in the main text but now in the appendix def NonMonotonicity(data): sign_prev=0 for i in range(np.size(data)-1): if data[i+1]-data[i]<-0.01: sign_curr=-1 # increasing elif data[i+1]-data[i]>0.01: sign_curr=1 #decreasing else: sign_curr=sign_prev if sign_prev*sign_curr<-0.1: # non-monotonicity return 1 else: sign_prev=sign_curr #monotnic return 0 def Number_NonMonotonic(start, end, Data): counter=0 for j in range(int(start)-1, int(end)): counter+=NonMonotonicity(Data[j, :]) return counter def FigA14(peak_harsh, peak_mean, peak_mild): """ This figure was preivously shown in the main text, but in the latest, they are showin in Appendix. Need the following three one-dim array that contains critical toxin sensitivities in each scenario without enviornmental scenario ---------- peak_harsh peak_mean peak_mild ---------- In the main text, the above arrays are np.array([0.1, 0.3, 0.1, 0.1, 0.3, 0.1, 0.1]), np.array([0.4, 0.4, 0.4, 0.9, 0.5, 0.2, 0.3]), np.array([0.8, 1.1, 1.3, 1.2, 0.8, 0.3, 0.8]) Plot the distance of peaks and the range of death rate with non-monotonic effect of environmental siwthcing rate Ex. three switching scenarios + four chaging resource supply """ Non_Monotonic=np.zeros([3, 7]) # 1st dim: mean-harsh, mild-mean, mild-harsh #2nd dim: each scenario #calculate non-monotonicity in each switchingscenario model_array=np.array([1,2,3]) os.chdir('./Correlation') for i in range(np.size(model_array)): # non-monotonicity check fname=str('DiffExtinction1_Heatmap_Model%d.csv'%(model_array[i])) Data=np.loadtxt(fname, delimiter=',', skiprows=0) Non_Monotonic[0, i]=Number_NonMonotonic(peak_harsh[i]*10, peak_mean[i]*10, Data) Non_Monotonic[1, i]=Number_NonMonotonic(peak_mean[i]*10, min(peak_mild[i]*10,10), Data) Non_Monotonic[2, i]=Number_NonMonotonic(peak_harsh[i]*10, min(peak_mild[i]*10, 10), Data) tail_list=['large_xmax', 'large_xmin', 'small_xmax', 'small_xmin'] for j in range(np.size(tail_list)): fname1='DiffExtinction1_Heatmap_Model1_'+tail_list[j]+'.csv' Data=np.loadtxt(fname1, delimiter=',', skiprows=0) Non_Monotonic[0, j+3]=Number_NonMonotonic(peak_harsh[j+3]*10, peak_mean[j+3]*10, Data) Non_Monotonic[1, j+3]=Number_NonMonotonic(peak_mean[j+3]*10, peak_mild[j+3]*10, Data) Non_Monotonic[2, j+3]=Number_NonMonotonic(peak_harsh[j+3]*10, peak_mild[j+3]*10, Data) # scatter plot and correlation corr, p_val=sp.stats.spearmanr(peak_mean-peak_harsh, Non_Monotonic[0, :]) plt.scatter(peak_mean-peak_harsh, Non_Monotonic[0, :], s=200, marker='o', color='black', label='harsh - mean') print(corr, p_val) corr, p_val=sp.stats.spearmanr(peak_mild-peak_mean, Non_Monotonic[1, :]) plt.scatter(peak_mild-peak_mean, Non_Monotonic[1, :], s=100, marker='D', color='dimgray', label='mean - mild') print(corr, p_val) corr, p_val=sp.stats.spearmanr(peak_mild-peak_harsh, Non_Monotonic[2, :]) plt.scatter(peak_mild-peak_harsh, Non_Monotonic[2, :], s=100, marker='x', color='grey', label='harsh - mild') print(corr, p_val) # add arrow to show the result in the main text plt.annotate(text="", xy=[0.35, 2.5], xytext=[0.45, 3.5], arrowprops=dict(width=2, facecolor='k', edgecolor='k')) plt.xlabel('distance between critical values', fontsize=20) plt.ylabel('non-monotonicity', fontsize=20) plt.xticks(fontsize=16) plt.yticks(fontsize=16) plt.legend(loc='lower center', bbox_to_anchor=(.5, 1.1), ncol=3, fontsize=20) plt.savefig('DistancePeak_Non_monotonicity_ver2.pdf',bbox_inches='tight',pad_inches=0.05) plt.show() print(peak_mean-peak_harsh, Non_Monotonic[0, :]) print(peak_mild-peak_mean, Non_Monotonic[1, :]) print(peak_mild-peak_harsh, Non_Monotonic[2, :])
[ "noreply@github.com" ]
noreply@github.com
e08245275924da51311b4f504a375d9583df3853
0473c6c0f5cd034757a7ec6bef5617a77db340b1
/python/ccxt/xex.py
b421e17cb97c94ea740f7e713864b065139f269b
[ "MIT" ]
permissive
yufengwei/ccxt
be1800d921d4e751ec07f6760e9bae836f649783
c50206354641a3752b1015c1247cc1d73614bba1
refs/heads/master
2021-10-08T00:26:55.661027
2018-12-06T06:41:13
2018-12-06T06:41:13
154,766,455
0
1
null
2018-10-26T02:35:03
2018-10-26T02:35:03
null
UTF-8
Python
false
false
13,652
py
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: from ccxt.base.exchange import Exchange from ccxt.base.errors import ExchangeError class xex (Exchange): def describe(self): return self.deep_extend(super(xex, self).describe(), { 'id': 'xex', 'name': 'XEX', 'countries': ['JP'], 'comment': 'Xex API', 'has': { 'fetchTicker': True, 'fetchOHLCV': True, 'fetchOrderBook': True, 'fetchTrades': True, 'fetchMyTrades': True, 'fetchOrderBooks': True, 'fetchOpenOrders': True, 'fetchOrder': True, 'createOrder': True, 'cancelOrder': True, 'fetchBalance': True, }, 'timeframes': { '1m': '1MIN', '5m': '5MIN', '15m': '15MIN', '30m': '30MIN', '1h': '1H', '2h': '2H', '4h': '4H', '6h': '6H', '12h': '12H', '1d': 'D', '2d': '2D', '1w': 'W', 'month': 'MONTH', }, 'urls': { 'logo': 'https://www.crossexchange.io/images/logo_icon.png', 'api': 'https://api.crossexchange.io', 'www': 'https://www.crossexchange.io/cross/home', 'doc': 'https://support.crossexchange.io/hc/en-us/categories/360001030591?flash_digest=4496738595f09128fc199486ac8f0fcee028b0ab', }, 'api': { 'public': { 'get': [ 'GET/v1/api/ticker', 'GET/v1/api/kline', 'GET/v1/api/depth', 'GET/v1/api/trades', ], }, 'private': { 'get': [ 'GET/v1/api/orderdetail', 'GET/v1/api/auth/wallet', 'GET/v1/api/mineLimit', ], 'post': [ 'POST/v1/api/trades', 'POST/v1/api/orders', 'POST/v1/api/auth/orders', 'POST/v1/api/cancelOrder', 'POST/v1/api/placeOrder', ], }, }, }) def fetch_markets(self): return [ { 'id': 'BTC_USDT', 'symbol': 'BTC_USDT', 'base': 'USDT', 'quote': 'BTC' }, { 'id': 'ETH_USDT', 'symbol': 'ETH_USDT', 'base': 'USDT', 'quote': 'ETH' }, { 'id': 'LTC_USDT', 'symbol': 'LTC_USDT', 'base': 'USDT', 'quote': 'LTC' }, { 'id': 'BCH_USDT', 'symbol': 'BCH_USDT', 'base': 'USDT', 'quote': 'BCH' }, { 'id': 'XRP_USDT', 'symbol': 'XRP_USDT', 'base': 'USDT', 'quote': 'XRP' }, { 'id': 'XEX_USDT', 'symbol': 'XEX_USDT', 'base': 'USDT', 'quote': 'XEX' }, { 'id': 'ETH_BTC', 'symbol': 'ETH_BTC', 'base': 'BTC', 'quote': 'ETH' }, { 'id': 'LTC_BTC', 'symbol': 'LTC_BTC', 'base': 'BTC', 'quote': 'LTC' }, { 'id': 'XRP_BTC', 'symbol': 'XRP_BTC', 'base': 'BTC', 'quote': 'XRP' }, { 'id': 'ADA_BTC', 'symbol': 'ADA_BTC', 'base': 'BTC', 'quote': 'ADA' }, { 'id': 'XEX_BTC', 'symbol': 'XEX_BTC', 'base': 'BTC', 'quote': 'XEX' }, { 'id': 'XEX_ETH', 'symbol': 'XEX_ETH', 'base': 'ETH', 'quote': 'XEX' }, ] def fetch_balance(self, params={}): response = self.privateGetGETV1ApiAuthWallet() result = {'info': response} balance = response['data'] free = balance['free'] freezed = balance['freezed'] coins = list(free.keys()) for i in range(0, len(coins)): currency = coins[i] account = self.account() account['free'] = float(free[currency]) account['used'] = float(freezed[currency]) account['total'] = self.sum(account['free'], account['used']) result[currency] = account return self.parse_balance(result) def fetch_order_book(self, symbol, limit=None, params={}): self.load_markets() response = self.publicGetGETV1ApiDepth(self.extend({ 'pair': self.market_id(symbol), }, params)) return self.parse_order_book(response['data'], response['data']['timestamp']) def fetch_ticker(self, symbol, params={}): self.load_markets() response = self.publicGetGETV1ApiTicker(self.extend({ 'pair': self.market_id(symbol), }, params)) ticker = response['data'] last = self.safe_float(ticker, 'last') return { 'symbol': symbol, 'timestamp': ticker['timestamp'], 'datetime': None, 'high': self.safe_float(ticker, 'high'), 'low': self.safe_float(ticker, 'low'), 'bid': self.safe_float(ticker, 'bid'), 'bidVolume': None, 'ask': None, 'askVolume': None, 'vwap': None, 'open': None, 'close': last, 'last': last, 'previousClose': None, 'change': self.safe_float(ticker, 'dchange'), 'percentage': self.safe_float(ticker, 'dchangepec'), 'average': None, 'baseVolume': None, 'quoteVolume': self.safe_float(ticker, 'vol'), 'info': ticker, } def fetch_ohlcv(self, symbol, timeframe='1d', since=None, limit=None, params={}): self.load_markets() market = self.market(symbol) response = self.publicGetGETV1ApiKline(self.extend({ 'pair': market['id'], 'type': self.timeframes[timeframe], }, params)) ohlcvs = response['data'] return self.parse_ohlcvs(ohlcvs, market, timeframe, since, limit) def parse_trade(self, trade, market): side_flag = 'sell' price = float(trade[1]) if price > 0.00000000000000000001: side_flag = 'buy' timestamp = trade[3] fee_num = None if len(trade) >= 7: fee_num = float(trade[6]) return { 'id': trade[0], 'info': trade, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'symbol': trade[5], 'order': None, 'type': trade[4], 'side': side_flag, 'price': price, 'amount': float(trade[2]), 'fee': fee_num, } def fetch_trades(self, symbol, since=None, limit=None, params={}): self.load_markets() market = self.market(symbol) response = self.publicGetGETV1ApiTrades(self.extend({ 'pair': market['id'], }, params)) trades = response['data'] newTrades = [] for i in range(0, len(trades)): oneTrade = [] for k in range(0, len(trades[i])): oneTrade.append(trades[i][k]) oneTrade.append(symbol) newTrades.append(oneTrade) return self.parse_trades(newTrades, market, since, limit) def fetch_my_trades(self, symbol, since=None, limit=None, params={}): self.load_markets() response = self.privatePostPOSTV1ApiTrades(params) trades = response['data'] newTrades = [] for i in range(0, len(trades)): oneTrade = [] oneTrade.append(trades[i][0]) oneTrade.append(trades[i][3]) oneTrade.append(trades[i][4]) oneTrade.append(trades[i][2]) oneTrade.append(trades[i][6]) oneTrade.append(trades[i][1]) oneTrade.append(trades[i][8]) newTrades.append(oneTrade) return self.parse_trades(newTrades, None, since, limit) def parse_order_status(self, status): statuses = { '0': 'Start', '1': 'Partially Executed', # partially filled '2': 'Executed', '3': 'Cancelled', } if status in statuses: return statuses[status] return status def fetch_order(self, id, symbol=None, params={}): self.load_markets() request = { 'order_id': id, } response = self.privateGetGETV1ApiOrderdetail(self.extend(request, params)) order = response['data'] timestamp = order[2] status = self.parse_order_status(order[9]) side = self.safe_string(order, 'flag') total = float(order[4]) completed = float(order[3]) remain = total - completed sidex = 'sell' price = float(order[5]) if price > 0.0000000000001: sidex = 'buy' result = { 'info': order, 'id': id, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'lastTradeTimestamp': None, 'symbol': order[1], 'type': order[7], 'side': sidex, 'price': price, 'cost': None, 'average': order[6], 'amount': total, 'filled': completed, 'remaining': remain, 'status': status, 'fee': None, 'stop_price': order[8], } return result def parse_order(self, order, market=None): id = order[0] timestamp = order[2] symbol = order[1] filled = float(order[3]) amount = float(order[4]) side = 'sell' price = float(order[5]) if price > 0.00000000000001: side = 'buy' remaining = amount - filled tradePrice = float(order[6]) cost = filled * tradePrice type = order[7] stopPrice = float(order[8]) status = self.parse_order_status(order[9]) result = { 'info': order, 'id': id, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'lastTradeTimestamp': None, 'symbol': symbol, 'type': type, 'side': side, 'price': price, 'cost': cost, 'average': None, 'amount': amount, 'filled': filled, 'remaining': remaining, 'status': status, 'fee': None, 'stop_price':stopPrice, } return result def fetch_orders_books(self, symbol=None, params={}): self.load_markets() response = self.privatePostPOSTV1ApiOrders(params) if 'data' in response: return self.parse_orders(response['data'], None, None, None) return [] def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}): self.load_markets() response = self.privatePostPOSTV1ApiAuthOrders() if 'data' in response: return self.parse_orders(response['data'], None, since, limit) return [] def create_order(self, symbol, type, side, amount, price=None, params={}): self.load_markets() order = { 'isbid': side, 'order_type': type, 'pair': self.market_id(symbol), 'amount': amount, } if type == 'STOP-LIMIT': order['stop_price'] = price else: order['stop_price'] = 0 result = self.privatePostPOSTV1ApiPlaceOrder(self.extend(order, params)) return { 'info': result, 'id': result['data']['orderId'], } def cancel_order(self, id, symbol=None, params={}): if symbol == None: raise ExchangeError(self.id + ' cancelOrder() requires a symbol argument') self.load_markets() return self.privatePostPOSTV1ApiCancelOrder(self.extend({ 'order_id': id, 'pair': self.market_id(symbol), }, params)) def nonce(self): return self.milliseconds() def sign(self, path, api='public', method='GET', params={}, headers=None, body=None): if self.id == 'cryptocapital': raise ExchangeError(self.id + ' is an abstract base API for xex') url = self.urls['api'] + '/' + path if api == 'public': if params: url += '?' + self.urlencode(params) else: self.check_required_credentials() time = self.nonce() query = self.keysort(self.extend({ 'api_key': self.apiKey, 'auth_nonce': time, }, params)) temp_str = '' for key in query: temp_str += str(query[key]) signed = self.hash(self.encode(temp_str + self.secret)) if method == 'GET': signed = self.hash(self.encode(self.apiKey + str(time) + self.secret)) query_str = self.urlencode(query) url += '?' + query_str + '&auth_sign=' + signed; headers = {'Content-Type': 'application/json'} return {'url': url, 'method': method, 'body': body, 'headers': headers} def request(self, path, api='public', method='GET', params={}, headers=None, body=None): response = self.fetch2(path, api, method, params, headers, body) if 'msg' in response: errors = response['msg'] raise ExchangeError(self.id + ' ' + errors) return response
[ "noreply@github.com" ]
noreply@github.com
7f80c2fc21926cef97f59322600076deab21b4ed
41b9fb1a3d50da08b2b9cf5b2e48161c07f7227a
/utils.py
5239c0c84c0da90df507db0cd80827042e0259b1
[]
no_license
Jasmina991/Image-recognition---beautif.ai
a9356390c462d7efe4606b05b24ff2606ec9fe3a
a2ba3708f288224deecc03d7c45c9d696594d8e5
refs/heads/main
2023-04-27T09:13:56.477229
2021-05-04T17:16:29
2021-05-04T17:16:29
354,949,699
0
2
null
null
null
null
UTF-8
Python
false
false
3,827
py
# Import libraries from google.colab import drive import os import pickle import numpy as np import pandas as pd from scipy import interp from itertools import cycle import math import cv2 import matplotlib.pyplot as plt import seaborn as sns import time import urllib.request def concat_dataset(path, img_size = 224): ''' Resize imgs and concatanete imgs from all the categories into one dataset. Parameters ---------- path : string Path to dataset folder. img_size : int Size of image after resizing. Default is 224. Returns ------- X : numpy array Contains all the data from different categories. y : numpy array Containts labels for the data. ''' X = [] y = [] if os.path.isdir(path): # check if directory exist and get all filenames for foldername in os.listdir(path): dirname = path + foldername print(dirname) if os.path.isdir(dirname): for filename in os.listdir(dirname): filedir = dirname + "/" + filename print(filedir) img = cv2.imread(filedir) img_resized = img_to_array(array_to_img(img, scale = False).resize((img_size, img_size))) # default is linear interpolation img_color = cv2.cvtColor(img_resized, cv2.COLOR_BGR2RGB) # convert image to RGB color space X.append(img_color) y.append(int(foldername)) # label is contained in folder name return np.asarray(X), np.asarray(y) def load_data(path, filename): ''' Loads data from a pickle file. Parameters ---------- data: numpy array path : string Path to folder containing the data. filename : string Name the file to be saved under. Returns ------- data : numpy array ''' with open(path + filename, 'rb') as output: data = pickle.load(output) return data def save_data(data, path, filename): ''' Saves data to a pickle file. Parameters ---------- data : numpy array Data to be saved. path : string Path to folder. filename : string Name the file to be saved under. Returns ------- None ''' with open(path + filename, 'wb') as output: pickle.dump(data, output) def get_prediction(image, model, class_names): ''' Predicts image class. Parameters ---------- image : image object model : deep learning model Returns ------- class_names : list Predicted class. ''' image = np.expand_dims(image, axis=0) prediction = model.predict(image) predicted_class = np.argmax(prediction) return class_names[predicted_class] def url_to_image(url): ''' Reads image from url and performs preprocessing. Parameters ---------- url: string Url to image. Returns ------- image_resized: image Preprocessed image. image : image Original image. ''' resp = urllib.request.urlopen(url) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_resized = cv2.resize(image, (224,224)) image_resized = image_resized/255.0 return image_resized, image def predict_url(url, model, class_names): ''' Shows image and predicted class. Parameters ---------- url: string Url to image. model : deep learning model class_names : list Returns ------- None ''' image_resized, image = url_to_image(url) predicted_class = get_prediction(image_resized, model, class_names) plt.imshow(image_resized) plt.title("Predicted label : " + predicted_class)
[ "noreply@github.com" ]
noreply@github.com
994f946068805b301a961f53fe581483cfb0ebe3
cfcc212a8f9da735122167a8e8abca41dd56022a
/rqt_mypkg/rqt_example_py/resource/ParamTab.py
2356ce0d0727a582990d0cbcc06926fdce03c652
[]
no_license
zhexxian/SUTD-S03-DSO-Indoor-Drone
3d5b8a126fedbf0eb24f626fb76786736fb634b0
6a56f357de24e9948b02f091fb63ad7481336cad
refs/heads/master
2021-03-16T10:17:26.103007
2017-07-28T13:31:26
2017-07-28T13:31:26
77,600,900
1
0
null
null
null
null
UTF-8
Python
false
false
8,839
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 2011-2013 Bitcraze AB # # Crazyflie Nano Quadcopter Client # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ Shows all the parameters available in the Crazyflie and also gives the ability to edit them. """ import logging from PyQt4 import uic from PyQt4.QtCore import Qt, pyqtSignal from PyQt4.QtCore import QAbstractItemModel, QModelIndex from PyQt4.QtGui import QBrush, QColor import cfclient from cfclient.ui.tab import Tab __author__ = 'Bitcraze AB' __all__ = ['ParamTab'] param_tab_class = uic.loadUiType( cfclient.module_path + "/resource/MyPlugin.ui")[0] logger = logging.getLogger(__name__) class ParamChildItem(object): """Represents a leaf-node in the tree-view (one parameter)""" def __init__(self, parent, name, crazyflie): """Initialize the node""" self.parent = parent self.name = name self.ctype = None self.access = None self.value = "" self._cf = crazyflie self.is_updating = True def updated(self, name, value): """Callback from the param layer when a parameter has been updated""" self.value = value self.is_updating = False self.parent.model.refresh() def set_value(self, value): """Send the update value to the Crazyflie. It will automatically be read again after sending and then the updated callback will be called""" complete_name = "%s.%s" % (self.parent.name, self.name) self._cf.param.set_value(complete_name, value) self.is_updating = True def child_count(self): """Return the number of children this node has""" return 0 class ParamGroupItem(object): """Represents a parameter group in the tree-view""" def __init__(self, name, model): """Initialize the parent node""" super(ParamGroupItem, self).__init__() self.parent = None self.children = [] self.name = name self.model = model def child_count(self): """Return the number of children this node has""" return len(self.children) class ParamBlockModel(QAbstractItemModel): """Model for handling the parameters in the tree-view""" def __init__(self, parent): """Create the empty model""" super(ParamBlockModel, self).__init__(parent) self._nodes = [] self._column_headers = ['Name', 'Type', 'Access', 'Value'] self._red_brush = QBrush(QColor("red")) def set_toc(self, toc, crazyflie): """Populate the model with data from the param TOC""" # No luck using proxy sorting, so do it here instead... for group in sorted(toc.keys()): new_group = ParamGroupItem(group, self) for param in sorted(toc[group].keys()): new_param = ParamChildItem(new_group, param, crazyflie) new_param.ctype = toc[group][param].ctype new_param.access = toc[group][param].get_readable_access() crazyflie.param.add_update_callback( group=group, name=param, cb=new_param.updated) new_group.children.append(new_param) self._nodes.append(new_group) self.layoutChanged.emit() def refresh(self): """Force a refresh of the view though the model""" self.layoutChanged.emit() def parent(self, index): """Re-implemented method to get the parent of the given index""" if not index.isValid(): return QModelIndex() node = index.internalPointer() if node.parent is None: return QModelIndex() else: return self.createIndex(self._nodes.index(node.parent), 0, node.parent) def columnCount(self, parent): """Re-implemented method to get the number of columns""" return len(self._column_headers) def headerData(self, section, orientation, role): """Re-implemented method to get the headers""" if role == Qt.DisplayRole: return self._column_headers[section] def rowCount(self, parent): """Re-implemented method to get the number of rows for a given index""" parent_item = parent.internalPointer() if parent.isValid(): parent_item = parent.internalPointer() return parent_item.child_count() else: return len(self._nodes) def index(self, row, column, parent): """Re-implemented method to get the index for a specified row/column/parent combination""" if not self._nodes: return QModelIndex() node = parent.internalPointer() if not node: index = self.createIndex(row, column, self._nodes[row]) self._nodes[row].index = index return index else: return self.createIndex(row, column, node.children[row]) def data(self, index, role): """Re-implemented method to get the data for a given index and role""" node = index.internalPointer() parent = node.parent if not parent: if role == Qt.DisplayRole and index.column() == 0: return node.name elif role == Qt.DisplayRole: if index.column() == 0: return node.name if index.column() == 1: return node.ctype if index.column() == 2: return node.access if index.column() == 3: return node.value elif role == Qt.EditRole and index.column() == 3: return node.value elif (role == Qt.BackgroundRole and index.column() == 3 and node.is_updating): return self._red_brush return None def setData(self, index, value, role): """Re-implemented function called when a value has been edited""" node = index.internalPointer() if role == Qt.EditRole: new_val = str(value) # This will not update the value, only trigger a setting and # reading of the parameter from the Crazyflie node.set_value(new_val) return True return False def flags(self, index): """Re-implemented function for getting the flags for a certain index""" flag = super(ParamBlockModel, self).flags(index) node = index.internalPointer() if index.column() == 3 and node.parent and node.access == "RW": flag |= Qt.ItemIsEditable return flag def reset(self): """Reset the model""" self._nodes = [] super(ParamBlockModel, self).reset() self.layoutChanged.emit() class ParamTab(Tab, param_tab_class): """ Show all the parameters in the TOC and give the user the ability to edit them """ _expand_all_signal = pyqtSignal() _connected_signal = pyqtSignal(str) _disconnected_signal = pyqtSignal(str) def __init__(self, tabWidget, helper, *args): """Create the parameter tab""" super(ParamTab, self).__init__(*args) self.setupUi(self) self.tabName = "Parameters" self.menuName = "Parameters" self.helper = helper self.tabWidget = tabWidget self.cf = helper.cf self.cf.connected.add_callback(self._connected_signal.emit) self._connected_signal.connect(self._connected) self.cf.disconnected.add_callback(self._disconnected_signal.emit) self._disconnected_signal.connect(self._disconnected) self._model = ParamBlockModel(None) self.paramTree.setModel(self._model) def _connected(self, link_uri): self._model.set_toc(self.cf.param.toc.toc, self.helper.cf) self.paramTree.expandAll() def _disconnected(self, link_uri): self._model.reset()
[ "noreply@github.com" ]
noreply@github.com
9b52f8728284f014f32195d6f50595415bcec9bb
cf54adda6874a4256401e9e4eb28f353b28ae74b
/python-modules/python_call_django_view.py
f56832338684b861081db955189ae868d9eae874
[]
no_license
oraant/study
c0ea4f1a7a8c3558c0eac4b4108bc681a54e8ebf
7bce20f2ea191d904b4e932c8d0abe1b70a54f7e
refs/heads/master
2020-09-23T02:08:07.279705
2016-11-21T06:30:26
2016-11-21T06:30:26
66,995,585
0
0
null
null
null
null
UTF-8
Python
false
false
656
py
# coding:utf-8 # # tree /home/oraant/test/django_celery/|grep -v .pyc # /home/oraant/test/django_celery/ # ├── django_celery # │   ├── __init__.py # │   ├── settings.py # │   ├── urls.py # │   ├── wsgi.py # ├── manage.py # └── myapp # ├── admin.py # ├── apps.py # ├── __init__.py # ├── migrations # │   ├── __init__.py # ├── models.py # ├── tests.py # └── views.py # # 3 directories, 25 files import sys sys.path.append('/home/oraant/test/django_celery/') from myapp.views import test_add print test_add(1, 2)
[ "oraant777@gmail.com" ]
oraant777@gmail.com
df4bc3c52cb2cc13ff6155431b8a111077115ef7
da6d44b06f631387739d04471920037e8541d6c0
/problems/014.py
8753c9f24c8c00abf2eddba5325e948652a085c7
[ "MIT" ]
permissive
JoshKarpel/euler-python
f6d5d5551a0d77565c852e3eb1e89522675824ec
9c4a89cfe4b0114d84a82e2b2894c7b8af815e93
refs/heads/master
2021-09-01T09:07:46.378352
2017-12-26T05:39:35
2017-12-26T05:39:35
64,712,642
2
0
null
null
null
null
UTF-8
Python
false
false
413
py
from problems import mymath, utils @utils.memoize def collatz_length(n): if n == 1: return 1 if n % 2 == 0: return 1 + collatz_length(n / 2) else: return 1 + collatz_length((3 * n) + 1) def solve(): collatz_lengths = {x: collatz_length(x) for x in range(1, 1000001)} return mymath.key_of_max_value(collatz_lengths) if __name__ == '__main__': print(solve())
[ "josh.karpel@gmail.com" ]
josh.karpel@gmail.com
f42ee53ee830d9587b5a82912dbf2299d14c6e20
ceef7327e18aebb652179d7799c509d598bdaee7
/alt/muenzelwuerfezehnmal.py
44a97b9b988297330c93d4a7bb27570e2f03d777
[]
no_license
cnrgrl/PYTHON-1
71d8e9baa5a24c14901909171aeb5b8ac3fbb1bc
63b1ee2667cb7f3d446541625e89b7e23ff966a0
refs/heads/master
2022-11-26T19:37:28.936978
2020-08-03T20:24:39
2020-08-03T20:24:39
279,966,797
0
0
null
null
null
null
UTF-8
Python
false
false
884
py
import random einsatz = 5 gewinn = 25 fail = 0 flip_n = 0 tage = 0 gewin_tage = 0 for i in range(1, 10001): while fail < einsatz < gewinn: wurfen = random.choice([True, False]) if wurfen == False: einsatz -= 1 else: einsatz += 1 flip_n +=1 hintereinander=0 while hintereinander<10: if einsatz == gewinn: tage += 1 gewin_tage += 1 hintereinander+=1 elif einsatz == fail: tage += 1 hintereinander=0 einsatz = 5 '''if einsatz == gewinn: print("WOOOOw DU HAST GEWON!!") elif einsatz == fail: print("Sorry sie mussen RAUS!!")''' print("#######################") print("Wurf zahl: ",flip_n) print(tage) print(gewin_tage) prozent=float(gewin_tage/tage) print(prozent) print(hintereinander)
[ "ugrl.cnr@gmail.com" ]
ugrl.cnr@gmail.com
12bad314b0ee825c5876eba56bb48592163b37c8
83037ddfb0a73d538902a64998b922e6c4116a38
/lib/config/default.py
d140fe3ffb3c4e1ec3c7553a90ab8d1702f23adb
[ "BSD-3-Clause", "MIT" ]
permissive
TotalVariation/Flattenet
bbff8782a334c836b424d45b051ac73709a718f6
828d1f95f6f77dd0b681318f2a544e84cf4be834
refs/heads/master
2021-08-28T11:23:59.947746
2021-08-19T13:23:56
2021-08-19T13:23:56
237,473,882
10
1
null
null
null
null
UTF-8
Python
false
false
2,575
py
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Written by Ke Sun (sunk@mail.ustc.edu.cn) # ------------------------------------------------------------------------------ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from yacs.config import CfgNode as CN _C = CN() _C.OUTPUT_DIR = '../output' _C.LOG_DIR = '../log' _C.GPUS = (0,) _C.WORKERS = 4 _C.PRINT_FREQ = 20 _C.AUTO_RESUME = False _C.PIN_MEMORY = True _C.RANK = 0 # Cudnn related params _C.CUDNN = CN() _C.CUDNN.BENCHMARK = True _C.CUDNN.DETERMINISTIC = False _C.CUDNN.ENABLED = True # common params for NETWORK _C.MODEL = CN() _C.MODEL.NAME = 'segnet' _C.MODEL.PRETRAINED = '' _C.MODEL.EXTRA = CN(new_allowed=True) _C.LOSS = CN() _C.LOSS.USE_OHEM = False _C.LOSS.OHEMTHRESH = 0.7 _C.LOSS.OHEMKEEP = 100000 _C.LOSS.CLASS_BALANCE = False _C.LOSS.TYPE = 'ce' # DATASET related params _C.DATASET = CN() _C.DATASET.ROOT = '../data' _C.DATASET.DATASET = 'pascal_ctx' _C.DATASET.NUM_CLASSES = 59 _C.DATASET.TRAIN_SET = 'train' _C.DATASET.TEST_SET = 'val' # training _C.TRAIN = CN() _C.TRAIN.IMAGE_SIZE = [512, 512] # [height, width] _C.TRAIN.AMSGRAD = False _C.TRAIN.BASE_SIZE = 512 _C.TRAIN.FLIP = True _C.TRAIN.MULTI_SCALE = True _C.TRAIN.SCALE_FACTOR = 16 _C.TRAIN.LR_FACTOR = 0.1 _C.TRAIN.LR_STEP = [90, 120] _C.TRAIN.LR = 0.001 _C.TRAIN.LR_SCHEDULER = 'cos' _C.TRAIN.OPTIMIZER = 'sgd' _C.TRAIN.MOMENTUM = 0.9 _C.TRAIN.WD = 0.0001 _C.TRAIN.NESTEROV = False _C.TRAIN.IGNORE_LABEL = -1 _C.TRAIN.BEGIN_EPOCH = 0 _C.TRAIN.END_EPOCH = 80 _C.TRAIN.EXTRA_EPOCH = 0 _C.TRAIN.RESUME = False _C.TRAIN.BATCH_SIZE_PER_GPU = 8 _C.TRAIN.SHUFFLE = True # only using some training samples _C.TRAIN.NUM_SAMPLES = 0 # testing _C.TEST = CN() _C.TEST.IMAGE_SIZE = [512, 512] # width * height _C.TEST.BASE_SIZE = 512 _C.TEST.BATCH_SIZE_PER_GPU = 8 # only testing some samples _C.TEST.NUM_SAMPLES = 0 _C.TEST.MODEL_FILE = '' _C.TEST.FLIP_TEST = False _C.TEST.MULTI_SCALE = False _C.TEST.SCALE_LIST = [1] # debug _C.DEBUG = CN() _C.DEBUG.DEBUG = False _C.DEBUG.SAVE_BATCH_IMAGES_GT = False _C.DEBUG.SAVE_BATCH_IMAGES_PRED = False _C.DEBUG.SAVE_HEATMAPS_GT = False _C.DEBUG.SAVE_HEATMAPS_PRED = False def update_config(cfg, args): cfg.defrost() cfg.merge_from_file(args.cfg) cfg.merge_from_list(args.opts) cfg.freeze() if __name__ == '__main__': import sys with open(sys.argv[1], 'w') as f: print(_C, file=f)
[ "511608332@qq.com" ]
511608332@qq.com
5567298ebb7978b48d392a67d3eb54b950aaa0f8
1f93f6540452af25ebe1e3a4fd4d1b1fc2151c18
/personal/urls.py
b2e1836fd943775fcc90887ab6b7c19c023bced7
[]
no_license
UdAyPaLRedDy/mysite1
51e80b3838e9e8aaa6f8e046aa6bf7ec5ad6fbc0
4c04caf715dbff0e6df91a8e9f7e099dce2dcd92
refs/heads/master
2021-01-19T12:00:24.745090
2017-04-12T05:42:36
2017-04-12T05:42:36
85,436,020
0
0
null
null
null
null
UTF-8
Python
false
false
181
py
from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index, name= 'index'), url(r'^contact/$', views.contact, name= 'contact'), ]
[ "udayreddy993@gmail.com" ]
udayreddy993@gmail.com
2d503aba7195bc7d6af601fb19d8e21dd724b07c
d82cd565ce0aaec97716a624d9ede0a27e34b660
/run.py
253d8fa51219e8dfa7ed2c10499663f6383fa9a8
[]
no_license
NanyiJiang/glados
d19fcf2a6010c8aedc04b226b54dd6cb78a6fc41
04fcbbe0c7c50bdf8585280b86427661bbf26035
refs/heads/master
2020-12-31T06:22:01.639747
2016-04-19T05:43:45
2016-04-19T05:43:45
55,537,640
0
0
null
2016-04-05T19:06:04
2016-04-05T19:06:04
null
UTF-8
Python
false
false
691
py
#!/usr/bin/env python import sys from client import GladosClient def main(): try: token_file = open('.slack-token') token = token_file.read().strip() except FileNotFoundError: print('Could not find slack token file .slack-token') sys.exit(1) debug = False if len(sys.argv) > 1: if len(sys.argv) == 2 and sys.argv[1] == '--debug': debug = True else: print('Usage: {} [--debug]'.format(sys.argv[0])) gclient = GladosClient(token, debug=debug) try: gclient.run() # if it gets past here it's crashed finally: gclient.close() if __name__ == '__main__': main()
[ "patrickwhite.256@gmail.com" ]
patrickwhite.256@gmail.com
5fa942cb659bf118cc2641d8efd9e84d123cea48
ceb7e3c876484200569e934c90b18d059f465657
/tools.py
53df081df42e0ae9e3f5619fe807fc84a14d4554
[]
no_license
jason91403/bot_DC
20e93927f76b094989b5715c6590025e93ba19d2
15cd5e98539960f7bbab40659b1b9e272c133ee1
refs/heads/master
2021-01-25T06:56:48.710785
2017-10-05T14:51:22
2017-10-05T14:51:22
93,633,218
0
0
null
null
null
null
UTF-8
Python
false
false
2,178
py
import collections import math class Tools(object): def __init__(self): pass @staticmethod def get_distance(x_position, y_position): return math.sqrt(math.pow((x_position[0] - y_position[0]), 2) + math.pow((x_position[1] - y_position[1]), 2)) @staticmethod def record_map_to_local_file(file_name, map_dic): """ To record the memory of a bot for map to the local txt file. :param file_name: :param map_dic: :return: """ test_file = open(file_name, 'w') line_dic = {} # [[y_position, line_detail_list],...] line_dic_p = {} x_min = 0 map_dic = collections.OrderedDict(sorted(map_dic.items())) for position, data_list in map_dic.items(): x_position = position[0] if x_position < x_min: x_min = x_position y_position = position[1] if y_position not in line_dic: line_dic[y_position] = [[x_position, data_list[0]]] else: line_dic[y_position].append([x_position, data_list[0]]) # Sort by line_dic = collections.OrderedDict(sorted(line_dic.items())) for y_position, data_list in line_dic.items(): data_list = sorted(data_list, key=lambda x: x[0]) # Sort by x_position # First x_position from a line # print "x_min: " + str(x_min) # print "data_list[0][0]: " + str(data_list[0][0]) while data_list[0][0] > x_min: data_list.insert(0, [data_list[0][0] - 1, " "]) data_list = sorted(data_list, key=lambda x: x[0]) # Sort by x_position for position_with_value_list in data_list: if y_position not in line_dic_p: line_dic_p[y_position] = position_with_value_list[1] else: line_dic_p[y_position] = line_dic_p[y_position] + position_with_value_list[1] line_dic_p = collections.OrderedDict(sorted(line_dic_p.items())) for line_num, line in line_dic_p.items(): test_file.write(line + "\n") test_file.close()
[ "j91403@gmail.com" ]
j91403@gmail.com
2adb8260f01517312ffc1b26f404f21fed669e76
9df0d99e15ef01bf310e310e383594e817030a50
/mainapp/admin.py
38e40daa2d4457adc8f9614033b3274df613ce34
[]
no_license
lalinaloginoval/geekshop-server
255a0fe22b97d71f210f1c6dee73527eab2e85d0
fb12b3ec5fb8edcd246a1c5ffdd2895399d08b08
refs/heads/master
2023-06-21T04:08:54.956510
2021-07-20T15:56:31
2021-07-20T15:56:31
359,889,410
0
0
null
null
null
null
UTF-8
Python
false
false
347
py
from django.contrib import admin from mainapp.models import ProductCategory, Product admin.site.register(ProductCategory) @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'quantity',) fields = ('name', 'image', 'description', 'price', 'quantity', 'category') search_fields = ('name',)
[ "alina.login30@gmail.com" ]
alina.login30@gmail.com
33a26a9eff1d85003c886ec1259d2874765ba03b
a2b6bc9bdd2bdbe5871edb613065dd2397175cb3
/中等/旋转图像.py
239a028395365d7e1f8543fcf746f87fc6437301
[]
no_license
Asunqingwen/LeetCode
ed8d2043a31f86e9e256123439388d7d223269be
b7c59c826bcd17cb1333571eb9f13f5c2b89b4ee
refs/heads/master
2022-09-26T01:46:59.790316
2022-09-01T08:20:37
2022-09-01T08:20:37
95,668,066
0
0
null
null
null
null
UTF-8
Python
false
false
1,224
py
''' 给定一个 n × n 的二维矩阵表示一个图像。 将图像顺时针旋转 90 度。 说明: 你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。 示例 1: 给定 matrix = [ [1,2,3], [4,5,6], [7,8,9] ], 原地旋转输入矩阵,使其变为: [ [7,4,1], [8,5,2], [9,6,3] ] 示例 2: 给定 matrix = [ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16] ], 原地旋转输入矩阵,使其变为: [ [15,13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7,10,11] ] ''' from typing import List class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ row = len(matrix) for i in range(row // 2): matrix[i][:], matrix[row - i - 1][:] = matrix[row - i - 1][:], matrix[i][:] for i in range(row): for j in range(i): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] if __name__ == '__main__': matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] sol = Solution() sol.rotate(matrix)
[ "sqw123az@sina.com" ]
sqw123az@sina.com
f08e7a8b8c0afb4f06cd501c4310cd9d053f667b
67667742f5bd8f1dc9340aae26493cb78b88d8e1
/traderrl/env/state_over_time.py
edb15d88c3adbe463d244b8663e443ad112b9461
[]
no_license
q-learning-trader/trader-rl
ae6e4ed51a0c5e769b3dcf01d0d147b95d909df5
f070f7fe29af828c258530721f2ac484d9ccb0ac
refs/heads/master
2021-04-23T22:17:21.269099
2019-08-26T05:12:41
2019-08-26T05:12:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,678
py
import numpy as np def candle_maker(self, state): new_state = [] highs = [] lows = [] new_state.append(state[-1][0]) for i in range(len(state)): highs.append(state[i][1]) for i in range(len(state)): lows.append(state[i][2]) new_state.append(max(highs)) new_state.append(min(lows)) new_state.append(state[0][3]) return new_state def state_over_time_m1(self, state): new_state = [] cl = state[-1][0] hi = state[-1][1] lo = state[-1][2] op =state[-1][3] v = state[-1][4] day = state[-1][5] hour = state[-1][6] minute = state[-1][7] cl2 = state[-2][0] hi2 = state[-2][1] lo2 = state[-2][2] op2 =state[-2][3] v2 = state[-2][4] day2 = state[-2][5] hour2 = state[-2][6] minute2 = state[-2][7] cl3 = state[-3][0] hi3 = state[-3][1] lo3 = state[-3][2] op3 =state[-3][3] v3 = state[-3][4] day3 = state[-3][5] hour3 = state[-3][6] minute3 = state[-3][7] cl4 = state[-4][0] hi4 = state[-4][1] lo4 = state[-4][2] op4 =state[-4][3] v4 = state[-4][4] day4 = state[-4][5] hour4 = state[-4][6] minute4 = state[-4][7] cl5 = state[-5][0] hi5 = state[-5][1] lo5 = state[-5][2] op5 =state[-5][3] v5 = state[-5][4] day5 = state[-5][5] hour5 = state[-5][6] minute5 = state[-5][7] cl6 = state[-6][0] hi6 = state[-6][1] lo6 = state[-6][2] op6 =state[-6][3] v6 = state[-6][4] day6 = state[-6][5] hour6 = state[-6][6] minute6 = state[-6][7] cl7 = state[-7][0] hi7 = state[-7][1] lo7 = state[-7][2] op7 =state[-7][3] v7 = state[-7][4] day7 = state[-7][5] hour7 = state[-7][6] minute7 = state[-7][7] cl8 = state[-8][0] hi8 = state[-8][1] lo8 = state[-8][2] op8 =state[-8][3] v8 = state[-8][4] day8 = state[-8][5] hour8 = state[-8][6] minute8 = state[-8][7] cl9 = state[-9][0] hi9 = state[-9][1] lo9 = state[-9][2] op9 =state[-9][3] v9 = state[-9][4] day9 = state[-9][5] hour9 = state[-9][6] minute9 = state[-9][7] cl10 = state[-10][0] hi10 = state[-10][1] lo10 = state[-10][2] op10 =state[-10][3] v10 = state[-10][4] day10 = state[-10][5] hour10 = state[-10][6] minute10 = state[-10][7] #cl5 = state[-5][0] #cl15 = state[-15][0] cl5 = cl - state[-5][3] cl15 = cl - state[-15][3] cl30 = cl - state[-30][3] cl1h = cl - state[-60][3] cl2h = cl - state[-120][3] cl4h = cl - state[-240][3] cl8h = cl - state[-480][3] cl16h = cl - state[-960][3] clday = cl - state[-1440][3] clnow = cl - op hinow = hi - op lonow = lo - op state5 = state[-5:] state15 = state[-15:] state30 = state[-30:] state1h = state[-60:] state2h = state[-120:] state4h = state[-240:] state8h = state[-480:] state16h = state[-960:] stateday = state[-1440:] statediff = self.difference2(state) state5diff = self.difference2(state5) state15diff = self.difference2(state15) state30diff = self.difference2(state30) state1hdiff = self.difference2(state1h) state2hdiff = self.difference2(state2h) state4hdiff = self.difference2(state4h) state8hdiff = self.difference2(state8h) state16hdiff = self.difference2(state16h) statedaydiff = self.difference2(stateday) av = self.average_diff(statediff) av5 = self.average_diff(state30diff) av15 = self.average_diff(state30diff) av30 = self.average_diff(state30diff) av1h = self.average_diff(state1hdiff) av2h = self.average_diff(state2hdiff) av4h = self.average_diff(state4hdiff) av8h = self.average_diff(state8hdiff) av16h = self.average_diff(state16hdiff) avday = self.average_diff(statedaydiff) md5 = self.median_diff(state5diff) md15 = self.median_diff(state15diff) md30 = self.median_diff(state30diff) md1h = self.median_diff(state1hdiff) md2h = self.median_diff(state2hdiff) md4h = self.median_diff(state4hdiff) md8h = self.median_diff(state8hdiff) md16h = self.median_diff(state16hdiff) mdday = self.median_diff(statedaydiff) atr = self.atr(state) atr5 = self.atr(state5) atr15 = self.atr(state15) atr30 = self.atr(state30) atr1h = self.atr(state1h) atr2h = self.atr(state2h) atr4h = self.atr(state4h) atr8h = self.atr(state8h) atr16h = self.atr(state16h) atrday = self.atr(stateday) aavol = self.average_vol(state) aavol5 = self.average_vol(state5) aavol15 = self.average_vol(state15) aavol30 = self.average_vol(state30) aavol1h = self.average_vol(state1h) aavol2h = self.average_vol(state2h) aavol4h = self.average_vol(state4h) aavol8h = self.average_vol(state8h) aavol16h = selfnew_state = [].average_vol(state16h) aavolday = selfnew_state = [].average_vol(stateday) #candle1 = selfnew_state = [].candle_maker(state[-1:]) #candle5 = self.new_state = []candle_maker(state[-5:]) candle15 = self.candle_maker(state[-15:]) candle30 = self.candle_maker(state[-30:]) candle1h = self.candle_maker(state[-60:]) candle2h = self.candle_maker(state[-120:]) candle4h = self.candle_maker(state[-240:]) candle8h = self.candle_maker(state[-480:]) candle16h = self.candle_maker(state[-960:]) candleday = self.candle_maker(state[-1440:]) #so = self.stocastic_oscillator(candle1) so5 = self.stocastic_oscillator(candle5) #print(so5) so15 = self.stocastic_oscillator(candle15) so30 = self.stocastic_oscillator(candle30) so1h = self.stocastic_oscillator(candle1h) so2h = self.stocastic_oscillator(candle2h) so4h = self.stocastic_oscillator(candle4h) so8h = self.stocastic_oscillator(candle8h) so16h = self.stocastic_oscillator(candle16h) soday = self.stocastic_oscillator(candleday) #new_state.append([cl, hi, lo, op, v, day, hour, minute, cl2, hi2, lo2, op2, v2, day2, hour2, minute2, cl3, hi3, lo3, op3, v3, day3, hour3, minute3, cl4, hi4, lo4, op4, v4, day4, hour4, minute4, cl5, hi5, lo5, op5, v5, day5, hour5, minute5, cl6, hi6, lo6, op6, v6, day6, hour6, minute6, cl7, hi7, lo7, op7, v7, day7, hour7, minute7, cl8, hi8, lo8, op8, v8, day8, hour8, minute8, cl9, hi9, lo9, op9, v9, day9, hour9, minute9, cl10, hi10, lo10, op10, v10, day10, hour10, minute10, clnow, hinow, lonow, cl30, cl1h, cl2h, cl4h, cl8h, cl16h, clday, atr14, atr30, atr1h, atr2h, atr4h, atr8h, atr16h, atrday, av30, av1h, av2h, av4h, av8h, av16h, avday, md30, md1h, md2h, md4h, md8h, md16h, mdday]) #new_state.append([cl, hi, lo, op, v, day, hour, minute, clnow, hinow, lonow, cl30, cl1h, cl2h, cl4h, cl8h, cl16h, clday, atr15, atr30, atr1h, atr2h, atr4h, atr8h, atr16h, atrday, av30, av1h, av2h, av4h, av8h, av16h, avday, md30, md1h, md2h, md4h, md8h, md16h, mdday]) new_state.append([cl, hi, lo, op, v, day, hour, minute, clnow, hinow, lonow, cl5, cl15, cl30, cl1h, cl2h, cl4h, cl8h, cl16h, clday, atr, atr5, atr15, atr30, atr1h, atr2h, atr4h, atr8h, atr16h, atrday, av5, av15, av30, av1h, av2h, av4h, av8h, av16h, avday, md5, md15, md30, md1h, md2h, md4h, md8h, md16h, mdday, aavol, aavol5, aavol15, aavol30, aavol1h, aavol2h, aavol4h, aavol8h, aavol16h, aavolday, so1h, so2h, so4h, so8h, so16h, soday]) def state_over_time_day(self, state): new_state = [] so = self.stocastic_oscillator_fixed(state) new_state.append([so, state[-1][0],state[-1][1], state[-1][2], state[-1][3], state[-1][4], state[-1][5], state[-1][6], state[-2][0],state[-2][1], state[-2][2], state[-2][3], state[-2][4], state[-2][5], state[-2][6], state[-3][0],state[-3][1], state[-3][2], state[-3][3], state[-3][4], state[-3][5], state[-3][6], state[-4][0],state[-4][1], state[-4][2], state[-4][3], state[-4][4], state[-4][5], state[-4][6], state[-5][0],state[-5][1], state[-5][2], state[-5][3], state[-5][4], state[-5][5], state[-5][6], state[-6][0],state[-6][1], state[-6][2], state[-6][3], state[-6][4], state[-6][5], state[-6][6], state[-7][0],state[-7][1], state[-7][2], state[-7][3], state[-7][4], state[-7][5], state[-7][6], state[-8][0],state[-8][1], state[-8][2], state[-8][3], state[-8][4], state[-8][5], state[-8][6], state[-9][0],state[-9][1], state[-9][2], state[-9][3], state[-9][4], state[-9][5], state[-9][6] ,state[-10][0],state[-10][1], state[-10][2], state[-10][3], state[-10][4], state[-10][5], state[-10][6] ,state[-11][0],state[-11][1], state[-11][2], state[-11][3], state[-11][4], state[-11][5], state[-11][6], state[-12][0], state[-12][1], state[-12][2], state[-12][3], state[-12][4], state[-12][5], state[-12][6], state[-13][0], state[-13][1], state[-13][2], state[-13][3], state[-13][4], state[-13][5], state[-13][6], state[-14][0], state[-14][1], state[-14][2], state[-14][3], state[-14][4], state[-14][5], state[-14][6]]) return new_state
[ "willie@adaptation.io" ]
willie@adaptation.io
a5ae296b4881fee18f5d49e648859f792efa4b90
44eab5a177b580df2c4d71df8bbf106b9d9cdb6d
/project/Q-sigma-lambda/main_gridworld_2.py
14864a0044b294103c5943e239ce9d44d7284df8
[]
no_license
abnan/TD-error-as-a-Q-learning-heuristic
9ebca47b5dba4da7db163a0569b84ab86cb20872
e905c00f8e6d1a112105505ac820a155c9b1144f
refs/heads/master
2020-11-28T12:35:36.038480
2020-01-04T19:31:35
2020-01-04T19:31:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,721
py
#Exponential decay import numpy as np import random from windy_gridworld2 import WindyGridworldEnv, StochasticWindyGridworldEnv import itertools import matplotlib.pyplot as plt import csv np.random.seed(198) env = StochasticWindyGridworldEnv() episodes = 100 num_run = 10000 # epsilon = 0.1 lr = 0.8 gamma = 1 lmbda = 0.6 def clamp(n, minn, maxn): if n < minn: return minn elif n > maxn: return maxn else: return n def getSelectionProb(state, epsilon): maxProbAction = np.argmax(Q[state]) selectionProb = np.repeat(epsilon/len(Q[state]), len(Q[state])) selectionProb[maxProbAction] += 1 - epsilon return selectionProb def getEpsilonGreedyAction(state, epsilon): selectionProb = getSelectionProb(state, epsilon) finalSelectedAction = np.random.choice(np.arange(len(Q[state])), p = selectionProb) return finalSelectedAction # f = open("results_exp1.csv", "w") colours = ['r-','b-','g-','c-','y-','k-'] colour_index = 0 #write header avg_reward_list = list() stats_episode_length = list() epi_avg_list = list() overall_per_episode_reward_list = list() for run in range(num_run): print(run) Q=np.zeros((env.observation_space.n, env.action_space.n)) stats_episode_reward = list() sigma = 1 for epi_num in range(episodes): z=np.zeros((env.observation_space.n, env.action_space.n)) s = env.reset() a = getEpsilonGreedyAction(s, epsilon=0.1) episode_reward = 0 td_error_list_this_episode = [] sigm_list_this_epiosed=[] for epi_len in itertools.count(): # env.render() # print(epi_num, s, a) s_n, reward, done, _ = env.step(a) episode_reward += reward a_n = getEpsilonGreedyAction(s_n, epsilon=0.1) td_target = reward + gamma * (sigma * Q[s_n, a_n] + (1-sigma) * np.dot(Q[s_n], getSelectionProb(s_n, epsilon=0))) td_error = td_target - Q[s, a] td_error_list_this_episode.append(abs(td_error)) z[s, a] += 1 Q += lr * td_error * z z = gamma * lmbda * z * (sigma + (1 - sigma) * getSelectionProb(s_n, epsilon=0)[a_n]) s = s_n a = a_n if(epi_num>0): sigma=clamp(abs(td_error/td_max), 0, 1) sigm_list_this_epiosed.append(sigma) # print(sigma) if(epi_len>4000): done=True if done: td_max = np.max(td_error_list_this_episode) stats_episode_reward.append(episode_reward) break overall_per_episode_reward_list.append(stats_episode_reward) epi_avg_list.append(np.sum(episode_reward)) overall_per_episode_reward_list = np.array(overall_per_episode_reward_list) avg_overall_per_episode_reward_list = np.mean(overall_per_episode_reward_list, axis=0) print(str(list(avg_overall_per_episode_reward_list))) std_error = np.std(overall_per_episode_reward_list, axis = 0)/np.sqrt(num_run) print("Std Error = ", str(list(std_error))) print("Average = ", np.mean(avg_overall_per_episode_reward_list)) print("Average last few = ", np.mean(avg_overall_per_episode_reward_list[-100:])) print("Average again =",epi_avg_list) temp_sum = np.sum(overall_per_episode_reward_list, axis=1) print("Average over entire return = ", np.mean(temp_sum)) print("SE over entire return = ", np.std(temp_sum)/np.sqrt(num_run)) #Plot all different lr for a fixed sigma avg_overall_per_episode_reward_list=avg_overall_per_episode_reward_list plt.plot(np.arange(len(avg_overall_per_episode_reward_list)), avg_overall_per_episode_reward_list, colours[0], label = "TD Error Sigma") plt.legend() plt.show()
[ "abhisheknan1993@gmail.com" ]
abhisheknan1993@gmail.com
8a7fcd602ce6c36bfe796131b87836fae4d82507
04ebcbce9e6ba1329a080f6a970c92fa38bfd3ad
/wxVTKRenderWindowInteractor.py
b082593f5eab958cc247a4efb72b0cbd38ccb342
[]
no_license
Garyfallidis/trn
a9400dfa6cf38887e8ba33a03bfdbc65222a82f6
558086a2c0c360dba9c204be35e9e206750fda5d
refs/heads/master
2020-03-26T17:03:38.476085
2013-02-01T03:19:34
2013-02-01T03:19:34
2,917,853
1
0
null
null
null
null
UTF-8
Python
false
false
25,333
py
""" A VTK RenderWindowInteractor widget for wxPython. Find wxPython info at http://wxPython.org Created by Prabhu Ramachandran, April 2002 Based on wxVTKRenderWindow.py Fixes and updates by Charl P. Botha 2003-2008 Updated to new wx namespace and some cleaning up by Andrea Gavana, December 2006 """ """ Please see the example at the end of this file. ---------------------------------------- Creation: wxVTKRenderWindowInteractor(parent, ID, stereo=0, [wx keywords]): You should create a wx.PySimpleApp() or some other wx**App before creating the window. Behaviour: Uses __getattr__ to make the wxVTKRenderWindowInteractor behave just like a vtkGenericRenderWindowInteractor. ---------------------------------------- """ # import usual libraries import math, os, sys import wx import vtk # wxPython 2.4.0.4 and newer prefers the use of True and False, standard # booleans in Python 2.2 but not earlier. Here we define these values if # they don't exist so that we can use True and False in the rest of the # code. At the time of this writing, that happens exactly ONCE in # CreateTimer() try: True except NameError: True = 1 False = 0 # a few configuration items, see what works best on your system # Use GLCanvas as base class instead of wx.Window. # This is sometimes necessary under wxGTK or the image is blank. # (in wxWindows 2.3.1 and earlier, the GLCanvas had scroll bars) baseClass = wx.Window if wx.Platform == "__WXGTK__": import wx.glcanvas baseClass = wx.glcanvas.GLCanvas # Keep capturing mouse after mouse is dragged out of window # (in wxGTK 2.3.2 there is a bug that keeps this from working, # but it is only relevant in wxGTK if there are multiple windows) _useCapture = (wx.Platform == "__WXMSW__") # end of configuration items class EventTimer(wx.Timer): """Simple wx.Timer class. """ def __init__(self, iren): """Default class constructor. @param iren: current render window """ wx.Timer.__init__(self) self.iren = iren def Notify(self): """ The timer has expired. """ self.iren.TimerEvent() class wxVTKRenderWindowInteractor(baseClass): """ A wxRenderWindow for wxPython. Use GetRenderWindow() to get the vtkRenderWindow. Create with the keyword stereo=1 in order to generate a stereo-capable window. """ # class variable that can also be used to request instances that use # stereo; this is overridden by the stereo=1/0 parameter. If you set # it to True, the NEXT instantiated object will attempt to allocate a # stereo visual. E.g.: # wxVTKRenderWindowInteractor.USE_STEREO = True # myRWI = wxVTKRenderWindowInteractor(parent, -1) USE_STEREO = False def __init__(self, parent, ID, *args, **kw): """Default class constructor. @param parent: parent window @param ID: window id @param **kw: wxPython keywords (position, size, style) plus the 'stereo' keyword """ # private attributes self.__RenderWhenDisabled = 0 # First do special handling of some keywords: # stereo, position, size, style stereo = 0 if kw.has_key('stereo'): if kw['stereo']: stereo = 1 del kw['stereo'] elif self.USE_STEREO: stereo = 1 position, size = wx.DefaultPosition, wx.DefaultSize if kw.has_key('position'): position = kw['position'] del kw['position'] if kw.has_key('size'): size = kw['size'] del kw['size'] # wx.WANTS_CHARS says to give us e.g. TAB # wx.NO_FULL_REPAINT_ON_RESIZE cuts down resize flicker under GTK style = wx.WANTS_CHARS | wx.NO_FULL_REPAINT_ON_RESIZE if kw.has_key('style'): style = style | kw['style'] del kw['style'] # the enclosing frame must be shown under GTK or the windows # don't connect together properly if wx.Platform != '__WXMSW__': l = [] p = parent while p: # make a list of all parents l.append(p) p = p.GetParent() l.reverse() # sort list into descending order for p in l: p.Show(1) # code added by cpbotha to enable stereo correctly where the user # requests this; remember that the glXContext in this case is NOT # allocated by VTK, but by WX, hence all of this. if stereo and baseClass.__name__ == 'GLCanvas': # initialize GLCanvas with correct attriblist for stereo attribList = [wx.glcanvas.WX_GL_RGBA, wx.glcanvas.WX_GL_MIN_RED, 1, wx.glcanvas.WX_GL_MIN_GREEN, 1, wx.glcanvas.WX_GL_MIN_BLUE, 1, wx.glcanvas.WX_GL_DEPTH_SIZE, 1, wx.glcanvas.WX_GL_DOUBLEBUFFER, wx.glcanvas.WX_GL_STEREO] try: baseClass.__init__(self, parent, ID, position, size, style, attribList=attribList) except wx.PyAssertionError: # stereo visual couldn't be allocated, so we go back to default baseClass.__init__(self, parent, ID, position, size, style) # and make sure everyone knows about it stereo = 0 else: baseClass.__init__(self, parent, ID, position, size, style) # create the RenderWindow and initialize it self._Iren = vtk.vtkGenericRenderWindowInteractor() self._Iren.SetRenderWindow( vtk.vtkRenderWindow() ) self._Iren.AddObserver('CreateTimerEvent', self.CreateTimer) self._Iren.AddObserver('DestroyTimerEvent', self.DestroyTimer) self._Iren.GetRenderWindow().AddObserver('CursorChangedEvent', self.CursorChangedEvent) try: self._Iren.GetRenderWindow().SetSize(size.width, size.height) except AttributeError: self._Iren.GetRenderWindow().SetSize(size[0], size[1]) if stereo: self._Iren.GetRenderWindow().StereoCapableWindowOn() self._Iren.GetRenderWindow().SetStereoTypeToCrystalEyes() self.__handle = None self.BindEvents() # with this, we can make sure that the reparenting logic in # Render() isn't called before the first OnPaint() has # successfully been run (and set up the VTK/WX display links) self.__has_painted = False # set when we have captured the mouse. self._own_mouse = False # used to store WHICH mouse button led to mouse capture self._mouse_capture_button = 0 # A mapping for cursor changes. self._cursor_map = {0: wx.CURSOR_ARROW, # VTK_CURSOR_DEFAULT 1: wx.CURSOR_ARROW, # VTK_CURSOR_ARROW 2: wx.CURSOR_SIZENESW, # VTK_CURSOR_SIZENE 3: wx.CURSOR_SIZENWSE, # VTK_CURSOR_SIZENWSE 4: wx.CURSOR_SIZENESW, # VTK_CURSOR_SIZESW 5: wx.CURSOR_SIZENWSE, # VTK_CURSOR_SIZESE 6: wx.CURSOR_SIZENS, # VTK_CURSOR_SIZENS 7: wx.CURSOR_SIZEWE, # VTK_CURSOR_SIZEWE 8: wx.CURSOR_SIZING, # VTK_CURSOR_SIZEALL 9: wx.CURSOR_HAND, # VTK_CURSOR_HAND 10: wx.CURSOR_CROSS, # VTK_CURSOR_CROSSHAIR } def BindEvents(self): """Binds all the necessary events for navigation, sizing, drawing. """ # refresh window by doing a Render self.Bind(wx.EVT_PAINT, self.OnPaint) # turn off background erase to reduce flicker self.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None) # Bind the events to the event converters self.Bind(wx.EVT_RIGHT_DOWN, self.OnButtonDown) self.Bind(wx.EVT_LEFT_DOWN, self.OnButtonDown) self.Bind(wx.EVT_MIDDLE_DOWN, self.OnButtonDown) self.Bind(wx.EVT_RIGHT_UP, self.OnButtonUp) self.Bind(wx.EVT_LEFT_UP, self.OnButtonUp) self.Bind(wx.EVT_MIDDLE_UP, self.OnButtonUp) self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel) self.Bind(wx.EVT_MOTION, self.OnMotion) self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnter) self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave) # If we use EVT_KEY_DOWN instead of EVT_CHAR, capital versions # of all characters are always returned. EVT_CHAR also performs # other necessary keyboard-dependent translations. self.Bind(wx.EVT_CHAR, self.OnKeyDown) self.Bind(wx.EVT_KEY_UP, self.OnKeyUp) self.Bind(wx.EVT_SIZE, self.OnSize) # the wx 2.8.7.1 documentation states that you HAVE to handle # this event if you make use of CaptureMouse, which we do. if _useCapture and hasattr(wx, 'EVT_MOUSE_CAPTURE_LOST'): self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self.OnMouseCaptureLost) def __getattr__(self, attr): """Makes the object behave like a vtkGenericRenderWindowInteractor. """ if attr == '__vtk__': return lambda t=self._Iren: t elif hasattr(self._Iren, attr): return getattr(self._Iren, attr) else: raise AttributeError, self.__class__.__name__ + \ " has no attribute named " + attr def CreateTimer(self, obj, evt): """ Creates a timer. """ self._timer = EventTimer(self) self._timer.Start(10, True) def DestroyTimer(self, obj, evt): """The timer is a one shot timer so will expire automatically. """ return 1 def _CursorChangedEvent(self, obj, evt): """Change the wx cursor if the renderwindow's cursor was changed. """ cur = self._cursor_map[obj.GetCurrentCursor()] c = wx.StockCursor(cur) self.SetCursor(c) def CursorChangedEvent(self, obj, evt): """Called when the CursorChangedEvent fires on the render window.""" # This indirection is needed since when the event fires, the # current cursor is not yet set so we defer this by which time # the current cursor should have been set. wx.CallAfter(self._CursorChangedEvent, obj, evt) def HideCursor(self): """Hides the cursor.""" c = wx.StockCursor(wx.CURSOR_BLANK) self.SetCursor(c) def ShowCursor(self): """Shows the cursor.""" rw = self._Iren.GetRenderWindow() cur = self._cursor_map[rw.GetCurrentCursor()] c = wx.StockCursor(cur) self.SetCursor(c) def GetDisplayId(self): """Function to get X11 Display ID from WX and return it in a format that can be used by VTK Python. We query the X11 Display with a new call that was added in wxPython 2.6.0.1. The call returns a SWIG object which we can query for the address and subsequently turn into an old-style SWIG-mangled string representation to pass to VTK. """ d = None try: d = wx.GetXDisplay() except NameError: # wx.GetXDisplay was added by Robin Dunn in wxPython 2.6.0.1 # if it's not available, we can't pass it. In general, # things will still work; on some setups, it'll break. pass else: # wx returns None on platforms where wx.GetXDisplay is not relevant if d: d = hex(d) # On wxPython-2.6.3.2 and above there is no leading '0x'. if not d.startswith('0x'): d = '0x' + d # we now have 0xdeadbeef # VTK wants it as: _deadbeef_void_p (pre-SWIG-1.3 style) d = '_%s_%s' % (d[2:], 'void_p') return d def OnMouseCaptureLost(self, event): """This is signalled when we lose mouse capture due to an external event, such as when a dialog box is shown. See the wx documentation. """ # the documentation seems to imply that by this time we've # already lost capture. I have to assume that we don't need # to call ReleaseMouse ourselves. if _useCapture and self._own_mouse: self._own_mouse = False def OnPaint(self,event): """Handles the wx.EVT_PAINT event for wxVTKRenderWindowInteractor. """ # wx should continue event processing after this handler. # We call this BEFORE Render(), so that if Render() raises # an exception, wx doesn't re-call OnPaint repeatedly. event.Skip() dc = wx.PaintDC(self) # make sure the RenderWindow is sized correctly self._Iren.GetRenderWindow().SetSize(self.GetSizeTuple()) # Tell the RenderWindow to render inside the wx.Window. if not self.__handle: # on relevant platforms, set the X11 Display ID d = self.GetDisplayId() if d: self._Iren.GetRenderWindow().SetDisplayId(d) # store the handle self.__handle = self.GetHandle() # and give it to VTK self._Iren.GetRenderWindow().SetWindowInfo(str(self.__handle)) # now that we've painted once, the Render() reparenting logic # is safe self.__has_painted = True self.Render() def OnSize(self,event): """Handles the wx.EVT_SIZE event for wxVTKRenderWindowInteractor. """ # event processing should continue (we call this before the # Render(), in case it raises an exception) event.Skip() try: width, height = event.GetSize() except: width = event.GetSize().width height = event.GetSize().height self._Iren.SetSize(width, height) self._Iren.ConfigureEvent() # this will check for __handle self.Render() def OnMotion(self,event): """Handles the wx.EVT_MOTION event for wxVTKRenderWindowInteractor. """ # event processing should continue # we call this early in case any of the VTK code raises an # exception. event.Skip() self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(), event.ControlDown(), event.ShiftDown(), chr(0), 0, None) self._Iren.MouseMoveEvent() def OnEnter(self,event): """Handles the wx.EVT_ENTER_WINDOW event for wxVTKRenderWindowInteractor. """ # event processing should continue event.Skip() self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(), event.ControlDown(), event.ShiftDown(), chr(0), 0, None) self._Iren.EnterEvent() def OnLeave(self,event): """Handles the wx.EVT_LEAVE_WINDOW event for wxVTKRenderWindowInteractor. """ # event processing should continue event.Skip() self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(), event.ControlDown(), event.ShiftDown(), chr(0), 0, None) self._Iren.LeaveEvent() def OnButtonDown(self,event): """Handles the wx.EVT_LEFT/RIGHT/MIDDLE_DOWN events for wxVTKRenderWindowInteractor. """ # allow wx event processing to continue # on wxPython 2.6.0.1, omitting this will cause problems with # the initial focus, resulting in the wxVTKRWI ignoring keypresses # until we focus elsewhere and then refocus the wxVTKRWI frame # we do it this early in case any of the following VTK code # raises an exception. event.Skip() ctrl, shift = event.ControlDown(), event.ShiftDown() self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(), ctrl, shift, chr(0), 0, None) button = 0 if event.RightDown(): self._Iren.RightButtonPressEvent() button = 'Right' elif event.LeftDown(): self._Iren.LeftButtonPressEvent() button = 'Left' elif event.MiddleDown(): self._Iren.MiddleButtonPressEvent() button = 'Middle' # save the button and capture mouse until the button is released # we only capture the mouse if it hasn't already been captured if _useCapture and not self._own_mouse: self._own_mouse = True self._mouse_capture_button = button self.CaptureMouse() def OnButtonUp(self,event): """Handles the wx.EVT_LEFT/RIGHT/MIDDLE_UP events for wxVTKRenderWindowInteractor. """ # event processing should continue event.Skip() button = 0 if event.RightUp(): button = 'Right' elif event.LeftUp(): button = 'Left' elif event.MiddleUp(): button = 'Middle' # if the same button is released that captured the mouse, and # we have the mouse, release it. # (we need to get rid of this as soon as possible; if we don't # and one of the event handlers raises an exception, mouse # is never released.) if _useCapture and self._own_mouse and \ button==self._mouse_capture_button: self.ReleaseMouse() self._own_mouse = False ctrl, shift = event.ControlDown(), event.ShiftDown() self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(), ctrl, shift, chr(0), 0, None) if button == 'Right': self._Iren.RightButtonReleaseEvent() elif button == 'Left': self._Iren.LeftButtonReleaseEvent() elif button == 'Middle': self._Iren.MiddleButtonReleaseEvent() def OnMouseWheel(self,event): """Handles the wx.EVT_MOUSEWHEEL event for wxVTKRenderWindowInteractor. """ # event processing should continue event.Skip() ctrl, shift = event.ControlDown(), event.ShiftDown() self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(), ctrl, shift, chr(0), 0, None) if event.GetWheelRotation() > 0: self._Iren.MouseWheelForwardEvent() else: self._Iren.MouseWheelBackwardEvent() def OnKeyDown(self,event): """Handles the wx.EVT_KEY_DOWN event for wxVTKRenderWindowInteractor. """ # event processing should continue event.Skip() ctrl, shift = event.ControlDown(), event.ShiftDown() keycode, keysym = event.GetKeyCode(), None if keycode == wx.WXK_LEFT: print('Left') if keycode == wx.WXK_RIGHT: print('Right') if keycode == wx.WXK_UP: print('Up') if keycode == wx.WXK_DOWN: print('Down') key = chr(0) if keycode < 256: key = chr(keycode) print(key) # wxPython 2.6.0.1 does not return a valid event.Get{X,Y}() # for this event, so we use the cached position. (x,y)= self._Iren.GetEventPosition() self._Iren.SetEventInformation(x, y, ctrl, shift, key, 0, keysym) self._Iren.KeyPressEvent() self._Iren.CharEvent() def OnKeyUp(self,event): """Handles the wx.EVT_KEY_UP event for wxVTKRenderWindowInteractor. """ # event processing should continue event.Skip() ctrl, shift = event.ControlDown(), event.ShiftDown() keycode, keysym = event.GetKeyCode(), None key = chr(0) if keycode < 256: key = chr(keycode) self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(), ctrl, shift, key, 0, keysym) self._Iren.KeyReleaseEvent() def GetRenderWindow(self): """Returns the render window (vtkRenderWindow). """ return self._Iren.GetRenderWindow() def Render(self): """Actually renders the VTK scene on screen. """ RenderAllowed = 1 ''' if not self.__RenderWhenDisabled: # the user doesn't want us to render when the toplevel frame # is disabled - first find the top level parent topParent = wx.GetTopLevelParent(self) if topParent: # if it exists, check whether it's enabled # if it's not enabeld, RenderAllowed will be false RenderAllowed = topParent.IsEnabled() ''' if RenderAllowed: if self.__handle and self.__handle == self.GetHandle(): self._Iren.GetRenderWindow().Render() elif self.GetHandle() and self.__has_painted: # this means the user has reparented us; let's adapt to the # new situation by doing the WindowRemap dance self._Iren.GetRenderWindow().SetNextWindowInfo( str(self.GetHandle())) # make sure the DisplayId is also set correctly d = self.GetDisplayId() if d: self._Iren.GetRenderWindow().SetDisplayId(d) # do the actual remap with the new parent information self._Iren.GetRenderWindow().WindowRemap() # store the new situation self.__handle = self.GetHandle() self._Iren.GetRenderWindow().Render() def SetRenderWhenDisabled(self, newValue): """Change value of __RenderWhenDisabled ivar. If __RenderWhenDisabled is false (the default), this widget will not call Render() on the RenderWindow if the top level frame (i.e. the containing frame) has been disabled. This prevents recursive rendering during wx.SafeYield() calls. wx.SafeYield() can be called during the ProgressMethod() callback of a VTK object to have progress bars and other GUI elements updated - it does this by disabling all windows (disallowing user-input to prevent re-entrancy of code) and then handling all outstanding GUI events. However, this often triggers an OnPaint() method for wxVTKRWIs, resulting in a Render(), resulting in Update() being called whilst still in progress. """ self.__RenderWhenDisabled = bool(newValue) #-------------------------------------------------------------------- def wxVTKRenderWindowInteractorConeExample(): """Like it says, just a simple example """ # every wx app needs an app app = wx.PySimpleApp() # create the top-level frame, sizer and wxVTKRWI frame = wx.Frame(None, -1, "wxVTKRenderWindowInteractor", size=(600,400)) widget = wxVTKRenderWindowInteractor(frame, -1) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(widget, 1, wx.EXPAND) frame.SetSizer(sizer) frame.Layout() # It would be more correct (API-wise) to call widget.Initialize() and # widget.Start() here, but Initialize() calls RenderWindow.Render(). # That Render() call will get through before we can setup the # RenderWindow() to render via the wxWidgets-created context; this # causes flashing on some platforms and downright breaks things on # other platforms. Instead, we call widget.Enable(). This means # that the RWI::Initialized ivar is not set, but in THIS SPECIFIC CASE, # that doesn't matter. widget.Enable(1) widget.AddObserver("ExitEvent", lambda o,e,f=frame: f.Close()) #widget.AddObserver("ExitEvent2", lambda o,e,f=frame: f.Close()) ren = vtk.vtkRenderer() widget.GetRenderWindow().AddRenderer(ren) cone = vtk.vtkConeSource() cone.SetResolution(8) coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInput(cone.GetOutput()) coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # show the window frame.Show() app.MainLoop() if __name__ == "__main__": wxVTKRenderWindowInteractorConeExample()
[ "garyfallidis@gmail.com" ]
garyfallidis@gmail.com
1e655ce6a6ae00b4bf3508a48cb7d6afd4ed5643
c2d461873c891869e6a082fa4f8f4a5855af89b9
/worldmeter.py
42629910133754d6982acae2046c77423ccb665f
[]
no_license
aimclee/vn-corona-server
b28b58a652debf4b577d4c94b4195af60fe2a525
d7aacbd0e1d88c151581d642f7b328a2c3aad8c7
refs/heads/master
2021-04-23T17:28:23.978053
2021-03-24T14:30:15
2021-03-24T14:30:15
249,946,930
1
0
null
2020-03-25T10:19:17
2020-03-25T10:19:17
null
UTF-8
Python
false
false
1,412
py
from bs4 import BeautifulSoup import requests def coronaParsing(): url = 'https://www.worldometers.info/coronavirus/' response = requests.get(url) data = response.text soup = BeautifulSoup(data, 'html.parser') url_corona = soup.find_all('div', {'class': 'maincounter-number'}) ### title = [] # title[0], title[1], title[2] -> world confirmed case # world confirmed Case # for text in range(len(url_corona)): # title.append(url_corona[text].find('span').text) # vietnam corona case viet = [] chart = soup.find('table', attrs={'id': "main_table_countries_today"}) chart_body = chart.find('tbody') rows = chart_body.find_all('tr') for row in rows: cols = row.find_all('td') cols = [ele.text for ele in cols] viet.append([ele for ele in cols if ele]) for vietnam in viet: if vietnam[0] == 'Vietnam': title.append(vietnam[vietnam.index('Vietnam') + 1]) # 전체 감염자 수 if vietnam[vietnam.index('Vietnam') + 2] == ' ': title.append('0') else: title.append(vietnam[vietnam.index('Vietnam') + 2]) # 사망자 수 title.append(vietnam[vietnam.index('Vietnam') + 3]) # 회복자 수 title.append(vietnam[vietnam.index('Vietnam') + 4]) # 신규 감염자수 return title a = coronaParsing() print(a)
[ "equuse3144@gmail.com" ]
equuse3144@gmail.com
9433a497451577e9a7e9d2d285c3dcda6726b8e9
6bedc9b6041525679bb3605df94c7e7d726ab220
/priv/jun_pandas.py
16c76c4f57986101130849f79e4d58fa3b6eb566
[ "MIT" ]
permissive
zgbjgg/jun
ff2f189763c541eec9db208e45128ff3db22dcb5
8a877d4a9c56efb6c9a2e13d25109e9da8dde5de
refs/heads/master
2021-06-21T22:05:30.692476
2020-10-01T03:51:08
2020-10-01T03:51:08
97,057,283
24
5
MIT
2020-10-01T03:51:09
2017-07-12T22:32:04
Erlang
UTF-8
Python
false
false
14,227
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import scipy as sp import numpy as np import matplotlib as mpl import pandas as pd import sklearn as skl import operator as opt import pyodbc as pyodbc from io import StringIO from dateutil.parser import parse mpl.use('Agg') opers = {'<': opt.lt, '>': opt.gt, '<=': opt.le, '>=': opt.ge, '==': opt.eq, '!=': opt.ne} sql = [ 'dsn', 'username', 'password', 'database'] # simple return sys version def version(): return sys.version # descriptive stats over a dataframe # this is used with a dynamical assignment since # data frame will hold by erlang process and the # syntax to apply functions over data will be complex def jun_dataframe(df, fn, args, axis='None', keywords=[]): if ( isinstance(df, pd.core.frame.DataFrame) | isinstance(df, pd.core.groupby.DataFrameGroupBy) ): args = [ islambda_from_erl(arg) for arg in args ] if axis != 'None': fun = getattr(df[axis], fn) else: fun = getattr(df, fn) # make dict from keywords even if empty! kwargs = dict([ (k, isexpression_from_erl(v)) for (k, v) in keywords ]) # explicity execute the fun if len(args) == 0: value = fun(**kwargs) else: value = fun(*args, **kwargs) # check for instance of int64 and return as scalar if isinstance(value, np.int64): return np.asscalar(value) elif isinstance(value, np.float64): return np.asscalar(value) elif isinstance(value, pd.core.frame.DataFrame): return ('pandas.core.frame.DataFrame', value) elif isinstance(value, pd.core.groupby.DataFrameGroupBy): return ('pandas.core.groupby.DataFrameGroupBy', value) elif isinstance(value, pd.core.frame.Series): return ('pandas.core.frame.Series', value) elif isinstance(value, np.ndarray): return ','.join(_fix(v) for v in value) elif value is None: # commonly when fun applies over callable object return ('pandas.core.frame.DataFrame', df) elif pd.isnull(value): return np.nan_to_num(value) else: return value else: return 'error_format_data_frame_invalid' # a common function to decode the pandas dataframe into # a readable erlang term def to_erl(value): if isinstance(value, pd.core.frame.DataFrame): # fill NaN as default since term cannot back to py jundataframe = value.fillna('NaN').values.tolist() columns = list(value) return ('pandas.core.frame.DataFrame', columns, jundataframe) else: return 'error_formar_data_frame_invalid' # working with columns are a important feature, but the main # function cannot deal with that, so just add a specific fn to that # When using multiIndex ensure index names! def columns(df): if isinstance(df, pd.core.frame.DataFrame): if isinstance(df.index, pd.core.index.MultiIndex): columns = list(df) + list(df.index.names) else: columns = list(df) columns_as_str = ','.join(columns) return columns_as_str else: return 'error_format_data_frame_invalid' # len columns helper def len_columns(df): if isinstance(df, pd.core.frame.DataFrame): return len(df.columns) else: return 'error_format_data_frame_invalid' # len index helper def len_index(df): if isinstance(df, pd.core.frame.DataFrame): return len(df.index) else: return 'error_format_data_frame_invalid' # memory usage helper def memory_usage(df): if isinstance(df, pd.core.frame.DataFrame): num = df.memory_usage(index=True, deep=True).sum() return _sizeof_fmt(num) else: return 'error_format_data_frame_invalid' # columns description (in a csv format) helper def info_columns(df): if isinstance(df, pd.core.frame.DataFrame): lines = "" counts = df.count() # for non-null values for i, column in enumerate(df.columns): dtype = df.dtypes.iloc[i] nonnull = counts.iloc[i] lines = lines + "%s,%s,%s\n" % (column, dtype, nonnull) return lines else: return 'error_format_data_frame_invalid' # size into human readable, taken from: # https://github.com/pandas-dev/pandas/blob/master/pandas/core/frame.py def _sizeof_fmt(num): # returns size in human readable format for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.1f%s %s" % (num, '+', x) num /= 1024.0 return "%3.1f%s %s" % (num, '+', 'PB') # common helper for plotting functions, wrapped over # erlang, declare if outputs goes to a path (image) or # only holds into memory as a single py dtype def jun_dataframe_plot(df, save='None', keywords=[]): if ( isinstance(df, pd.core.frame.DataFrame) ): # make dict from keywords even if empty! kwargs = dict([ (k, isexpression_from_erl(v)) for (k, v) in keywords ]) # IMPORTANT: check if columns has the x and y, otherwise remove to plot x = kwargs.get('x', 'None') y = kwargs.get('y', 'None') columns = list(df) if x not in columns and x != 'None': del kwargs['x'] if y not in columns and y != 'None': del kwargs['y'] # explicity execute the fun plot = df.plot(**kwargs) if save != 'None': fig = plot.get_figure() fig.savefig(save, bbox_inches='tight') # save contains path return 'matplotlib.AxesSubplot' else: return ('matplotlib.AxesSubplot', plot) # this is correct? because can be confusing with opaque df else: return 'error_format_data_frame_invalid' # common selection of columns (slicing) # this can be acomplished using loc but it's better # using a single syntax such as accesing data from dataframe def selection(df, columns): if ( isinstance(df, pd.core.frame.DataFrame) ): return ('pandas.core.frame.DataFrame', df[list(columns)]) else: return 'error_format_data_frame_invalid' # since query function cannot evaluate columns # with spaces in it (or even values) just use the legacy query # as a single filter, check for strings comparison as contains def legacy_query(df, column, operand, value): if ( isinstance(df, pd.core.frame.DataFrame) | isinstance(df, pd.core.groupby.DataFrameGroupBy) ): operation = opers[operand] if isinstance(value, str): try: parse(value, False) newdf = df[operation(df[column], value)] except ValueError: if operand == '!=': newdf = df[~df[column].str.contains(value, na=False)] elif operand == '==': newdf = df[df[column].str.contains(value, na=False)] # since str cannot be evaluated with '==' else: return 'error_string_operand_invalid' else: newdf = df[operation(df[column], value)] if isinstance(newdf, pd.core.frame.DataFrame): return ('pandas.core.frame.DataFrame', newdf) elif isinstance(newdf, pd.core.groupby.DataFrameGroupBy): return ('pandas.core.groupby.DataFrameGroupBy', newdf) else: return newdf else: return 'error_format_data_frame_invalid' # simple receiver for a lambda in string mode and pass # back to opaque term, it means a valid evaluated lambda # into py environment def islambda_from_erl(fn): try: fn0 = eval(fn) if ( callable(fn0) and fn0.__name__ == '<lambda>' ): return fn0 else: raise Exception('err.invalid.jun.Lambda', 'not a lambda valid function from erl instance') except: return fn # return fn safetly, same as passed # simple assignment for a serie to a dataframe as column or # even other assignments, but do it from here since cannot be evaluated # outside due to py syntax def legacy_assignment(df, column, value): if ( isinstance(df, pd.core.frame.DataFrame) | isinstance(df, pd.core.groupby.DataFrameGroupBy) ): df[column] = value if isinstance(df, pd.core.frame.DataFrame): return ('pandas.core.frame.DataFrame', df) elif isinstance(df, pd.core.groupby.DataFrameGroupBy): return ('pandas.core.groupby.DataFrameGroupBy', df) else: return df else: return 'error_format_data_frame_invalid' # descriptive stats over a series # this is used with a dynamical assignment since # series will hold by erlang process and the # syntax to apply functions over data will be complex def jun_series(series, fn, args, axis='None', keywords=[]): if ( isinstance(series, pd.core.frame.Series) ): args = [ islambda_from_erl(arg) for arg in args ] keywords = [ (k, islambda_from_erl(v)) for (k, v) in keywords ] # for complete integration also check for keywords with lambdas # keywords = [ islambda_from_erl(keyword) for keyword in keywords ] if axis != 'None': fun = getattr(series[axis], fn) else: fun = getattr(series, fn) # make dict from keywords even if empty! kwargs = dict([ (k, isexpression_from_erl(v)) for (k, v) in keywords ]) # explicity execute the fun if len(args) == 0: value = fun(**kwargs) else: value = fun(*args, **kwargs) # check for instance of int64 and return as scalar if isinstance(value, np.int64): return np.asscalar(value) elif isinstance(value, np.float64): return np.asscalar(value) elif isinstance(value, pd.core.frame.Series): return ('pandas.core.frame.Series', value) elif isinstance(value, np.ndarray): return ','.join(_fix(v) for v in value) elif pd.isnull(value): return np.nan_to_num(value) else: return value else: return 'error_format_series_invalid' # in keywords we cannot assing so easily the data comming from # erlang, since protocol buffers keep keywords as single strings # in key and value, eval each value so we can check if some of them # must be evaluated as an expression def isexpression_from_erl(expression): try: return eval(expression) except: return expression # return fn safetly, same as passed # this is used to apply functions to a # single dataframe but instead of getting functions to apply # based on the DataFrame class, use directly pandas implementation def jun_pandas(fn, args, keywords=[]): args = [ islambda_from_erl(arg) for arg in args ] fun = getattr(pd, fn) # we need to check the conn if using `read_sql` since conn # cannot be pickled :-( if fn == 'read_sql': keywords.extend([('con', conn(keywords, sql))]) # make dict from keywords even if empty! kwargs = dict([ (k, isexpression_from_erl(v)) for (k, v) in keywords if not k in sql]) # explicity execute the fun if len(args) == 0: value = fun(**kwargs) else: value = fun(*args, **kwargs) # check for instance of int64 and return as scalar if isinstance(value, np.int64): return np.asscalar(value) elif isinstance(value, np.float64): return np.asscalar(value) elif isinstance(value, pd.core.frame.DataFrame): return ('pandas.core.frame.DataFrame', value) elif isinstance(value, pd.core.groupby.DataFrameGroupBy): return ('pandas.core.groupby.DataFrameGroupBy', value) elif isinstance(value, pd.core.frame.Series): return ('pandas.core.frame.Series', value) elif isinstance(value, np.ndarray): return ','.join(_fix(v) for v in value) elif pd.isnull(value): return np.nan_to_num(value) else: return value # single selection of a column, return a series data # since this are now supported by jun core def single_selection(df, column): if ( isinstance(df, pd.core.frame.DataFrame) ): return ('pandas.core.frame.Series', df[column]) else: return 'error_format_data_frame_invalid' # timedelta operations def jun_timedelta(series, fn, axis='None', keywords=[]): if isinstance(series, pd.core.frame.Series): fun = getattr(series, 'dt') value = getattr(fun, fn) if isinstance(value, pd.core.frame.Series): return ('pandas.core.frame.Series', value) else: return value else: return 'error_format_data_frame_or_serie_invalid' # make a valid connection for sql using # pyodbc, this will return an opaque connection # to erlang, but the jun_pandas module will use that # to use related functions using such connection. def conn(keywords, sql): # ensure that ini file exists to generate the connection for (k, v) in keywords: if k in sql: if k == 'dsn': dsn = 'DSN=' + v elif k == 'username': username = 'UID=' + v elif k == 'password': password = 'PWD=' + v elif k == 'database': database = 'DATABASE=' + v setup_conn = ( dsn, username, password, database ) conn = pyodbc.connect(';'.join(str(arg) for arg in setup_conn)) return conn # custom fun to treat string as a new dataframe # this from python is a custom code so JUN implements directly from # its API def read_string(string, keywords): try: string = string.decode('utf-8') except: string = string args = [StringIO(string)] fun = getattr(pd, 'read_csv') kwargs = dict(keywords) # explicity execute the fun value = fun(*args, **kwargs) return ('pandas.core.frame.DataFrame', value) def _fix(v): if pd.isnull(v): return 'nan' elif isinstance(v, str): return v else: try: if isinstance(v, unicode): return v.encode('utf-8') else: return v except: return str(v)
[ "zgbjgg@gmail.com" ]
zgbjgg@gmail.com
d1494b6c3b9f0dd61bac4207e1580625cf158dac
ed8de41b5bd5c9b630047b2b558e5ed447561812
/mbm/test_app/migrations/0021_emailrequest.py
c657d411673ed50adbf7d51426cd6229d0e8f133
[]
no_license
rreubenreyes/mbm-photo
0ce6b490444655ac325ae6d689911f638091cc83
508a8b18ec96977bbd06f35faea398da1ff91d10
refs/heads/master
2021-06-21T10:32:22.712387
2017-07-21T02:44:42
2017-07-21T02:44:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
708
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-07-17 01:45 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('test_app', '0020_auto_20170717_0036'), ] operations = [ migrations.CreateModel( name='EmailRequest', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('sender', models.EmailField(max_length=254)), ('sub', models.CharField(max_length=100)), ('msg', models.TextField(max_length=1000)), ], ), ]
[ "reuben.a.reyes@gmail.com" ]
reuben.a.reyes@gmail.com
c68040c95d47cb1dbdc67e5ffca73df49529010b
dec108426231384227c39fd83adbd196f9149329
/forge/ethyr/io/__init__.py
53417336b1d41cf6bd2eb3f817ada3db9621aa51
[ "MIT" ]
permissive
Justin-Yuan/neural-mmo
591495d32e20142f8156e09aa725dd124285fd9e
cde2c666225d1382abb33243735f60e37113a267
refs/heads/master
2020-09-06T19:55:26.249578
2019-11-09T17:49:18
2019-11-09T17:49:18
220,532,021
0
0
null
null
null
null
UTF-8
Python
false
false
104
py
from .stimulus import Stimulus from .action import Action from .serial import Serial from .io import IO
[ "sealsuarez@gmail.com" ]
sealsuarez@gmail.com
fc0dfd542cb1fc87198d882b23f32e2a923cb059
8822149855c27522b54b05f796e292c1c63dbdf6
/mnist.py
105022e5d79ea5317478d7612e35b04793373105
[]
no_license
jaythaceo/TensorFlow-Tutorial
3c33844b473e67c63bfa9992c124e22ac2a394c3
b4eca4f3f25eeedd868ee2a0645eb617c1b3208a
refs/heads/master
2021-06-27T01:38:49.942255
2017-02-04T23:09:51
2017-02-04T23:09:51
59,586,904
0
0
null
null
null
null
UTF-8
Python
false
false
4,675
py
# Copyright 2016 Jason "jaythaceo" Brooks. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Builds the MNIST network Implements the inference/loss/training pattern for model building. 1. inference() - Builds the model as far as is required for running the network forward to make predictions. 2. loss() - Added to the inference model the layers required to generate loss. 3. training() - Adds to the loss model the Ops required to generate and apply gradiants. This file is used by the various "fully_connected_*.py" files and not meant to be run. """ import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data batch_size = 128 test_size = 256 def init_weights(shape): return tf.Variable(tf.random_normal(shape, stddev=0.01)) def model(X, w, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden): l1a = tf.nn.relu(tf.nn.conv2d(X, w, # l1a shape=(?, 28, 28, 32) strides=[1, 1, 1, 1], padding='SAME')) l1 = tf.nn.max_pool(l1a, ksize=[1, 2, 2, 1], # l1 shape=(?, 14, 14, 32) strides=[1, 2, 2, 1], padding='SAME') l1 = tf.nn.dropout(l1, p_keep_conv) l2a = tf.nn.relu(tf.nn.conv2d(l1, w2, # l2a shape=(?, 14, 14, 64) strides=[1, 1, 1, 1], padding='SAME')) l2 = tf.nn.max_pool(l2a, ksize=[1, 2, 2, 1], # l2 shape=(?, 7, 7, 64) strides=[1, 2, 2, 1], padding='SAME') l2 = tf.nn.dropout(l2, p_keep_conv) l3a = tf.nn.relu(tf.nn.conv2d(l2, w3, # l3a shape=(?, 7, 7, 128) strides=[1, 1, 1, 1], padding='SAME')) l3 = tf.nn.max_pool(l3a, ksize=[1, 2, 2, 1], # l3 shape=(?, 4, 4, 128) strides=[1, 2, 2, 1], padding='SAME') l3 = tf.reshape(l3, [-1, w4.get_shape().as_list()[0]]) # reshape to (?, 2048) l3 = tf.nn.dropout(l3, p_keep_conv) l4 = tf.nn.relu(tf.matmul(l3, w4)) l4 = tf.nn.dropout(l4, p_keep_hidden) pyx = tf.matmul(l4, w_o) return pyx mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels trX = trX.reshape(-1, 28, 28, 1) # 28x28x1 input img teX = teX.reshape(-1, 28, 28, 1) # 28x28x1 input img X = tf.placeholder("float", [None, 28, 28, 1]) Y = tf.placeholder("float", [None, 10]) w = init_weights([3, 3, 1, 32]) # 3x3x1 conv, 32 outputs w2 = init_weights([3, 3, 32, 64]) # 3x3x32 conv, 64 outputs w3 = init_weights([3, 3, 64, 128]) # 3x3x32 conv, 128 outputs w4 = init_weights([128 * 4 * 4, 625]) # FC 128 * 4 * 4 inputs, 625 outputs w_o = init_weights([625, 10]) # FC 625 inputs, 10 outputs (labels) p_keep_conv = tf.placeholder("float") p_keep_hidden = tf.placeholder("float") py_x = model(X, w, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost) predict_op = tf.argmax(py_x, 1) # Launch the graph in a session with tf.Session() as sess: # you need to initialize all variables tf.global_variables_initializer().run() for i in range(100): training_batch = zip(range(0, len(trX), batch_size), range(batch_size, len(trX)+1, batch_size)) for start, end in training_batch: sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end], p_keep_conv: 0.8, p_keep_hidden: 0.5}) test_indices = np.arange(len(teX)) # Get A Test Batch np.random.shuffle(test_indices) test_indices = test_indices[0:test_size] print(i, np.mean(np.argmax(teY[test_indices], axis=1) == sess.run(predict_op, feed_dict={X: teX[test_indices], p_keep_conv: 1.0, p_keep_hidden: 1.0})))
[ "jaythaceo@gmail.com" ]
jaythaceo@gmail.com
e130f466ce72a531a6005ed0b98ff6f888c5fdee
f52f778295b037017d957535d51784d76ccaa3ac
/applications/tensorflow/cnns/training/Models/squeezenet.py
b1b129c2b5ef9aa592f766d1b803f58b3567ee77
[ "MIT" ]
permissive
dkuo123/examples
7cbf79bc93727cb3bf6971389b7867930bfdbdf6
51cda4c15641ee2b4b035a2c0dcfd7ddbf2eb7ff
refs/heads/master
2022-12-27T14:18:49.863747
2020-10-16T17:57:14
2020-10-16T17:57:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,353
py
# Copyright 2019 Graphcore Ltd. """ SqueezeNet A Convolutional Neural Network with relatively few parameters (~1.25M) but equivalent accuracy to AlexNet. Architecture originally described in Caffe. Implemented here in TensorFlow for the IPU. SQUEEZENET: ALEXNET-LEVEL ACCURACY WITH 50X FEWER PARAMETERS AND <0.5MB MODEL SIZE https://arxiv.org/pdf/1602.07360.pdf SqueezeNet was originally implemented using a polynomial decay learnng rate. To use this, run with --lr-schedule polynomial_decay_lr. This will set a default rate of linear decay of the learning rate. You can change this rate with the parameters --poly-lr-decay-steps, --poly-lr-initial-lr, --poly-lr-decay-power and --poly-lr-end-lr. Unlike the original implementation, this version does not use quantization or compression. Additionally, unlike the original, this model trains in fp16 as default, but can be run in fp32 with --precision 32.32. In this case, you will need to run over two IPUs. """ import tensorflow as tf class SqueezeNet: def __init__(self, opts, is_training=True): self.is_training = is_training # Apply dataset specific changes if opts["dataset"] == "imagenet": self.num_classes = 1000 elif opts["dataset"] == "cifar-10": self.num_classes = 10 elif opts["dataset"] == "cifar-100": self.num_classes = 100 else: raise ValueError("Unknown Dataset {}".format(opts["dataset"])) self.use_bypass = opts.get("use_bypass") def _build_graph(self, image, use_bypass): """Classifies a batch of ImageNet images Returns: A logits Tensor with shape [<batch_size>, self.num_classes] """ pool_size, strides = (3, 2) image = _conv1(image, name="initialconv") x = tf.compat.v1.layers.max_pooling2d(image, pool_size=pool_size, strides=strides) x = _fire(x, 16, 64, name="fire2") x = _fire(x, 16, 64, name="fire3", use_bypass=use_bypass) x = _fire(x, 32, 128, name="fire4") # maxpool4 x = tf.compat.v1.layers.max_pooling2d(x, pool_size=pool_size, strides=strides) x = _fire(x, 32, 128, name="fire5", use_bypass=use_bypass) x = _fire(x, 48, 192, name="fire6") x = _fire(x, 48, 192, name="fire7", use_bypass=use_bypass) x = _fire(x, 64, 256, name="fire8") # maxpool8 x = tf.compat.v1.layers.max_pooling2d(x, pool_size=pool_size, strides=strides) x = _fire(x, 64, 256, name="fire9", use_bypass=use_bypass) x = tf.nn.dropout( x, rate=0.5 if self.is_training else 0.0, name="drop9") if self.num_classes == 1000: x = _conv10(x, name="finalconv", num_classes=self.num_classes) x = tf.layers.average_pooling2d( x, pool_size=13, strides=1, name="final_pool") x = tf.layers.flatten(x) else: x = tf.layers.flatten(x) x = tf.layers.dense(units=self.num_classes*2, inputs=x, activation=tf.nn.relu) return x def __call__(self, x): shape = x.get_shape().as_list() if len(shape) != 4: raise ValueError("Input size must be [batch,height,width,channels]") return self._build_graph(x, self.use_bypass) def Model(opts, training, image): return SqueezeNet(opts, training)(image) ########################################### # SqueezeNet block definitions ########################################### def _conv1(inputs, name): """The first layer of squeezenet Convolution name: a string name for the tensor output of the block layer. Returns: The output tensor of the block. """ with tf.variable_scope(name): inputs = conv(inputs, ksize=7, stride=2, filters_out=96, kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(), bias=False) return inputs def _conv10(inputs, name, num_classes): """The first layer of squeezenet Convolution then average pooling name: a string name for the tensor output of the block layer. Returns: The output tensor of the block. """ with tf.variable_scope(name): init = tf.initializers.truncated_normal(mean=0.0, stddev=0.01) inputs = conv(inputs, ksize=1, stride=1, filters_out=num_classes, kernel_initializer=init, bias=False) return inputs def _fire(inputs, squeeze, expand, name, use_bypass=False): """Fire module: A 'squeeze' convolution layer, which has only 1x1 filters, feeding into an 'expand' layer, that has a mix of 1x1 and 3x3 filters. squeeze: The number of 1x1 filters in the squeeze layer expand: The number of 1x1 and 3x3 filters in the expand layer name: a string name for the tensor output of the block layer. """ with tf.variable_scope(name): # squeeze layer with tf.variable_scope(name+"s_1"): x = conv(inputs, ksize=1, stride=1, filters_out=squeeze, kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(), bias=False) s1_out = tf.nn.relu(x) # expand layer with tf.variable_scope(name+"e_1"): e1_out = conv(s1_out, ksize=1, stride=1, filters_out=expand, kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(), bias=False) e1_out = tf.nn.relu(e1_out) # expand layer with tf.variable_scope(name+"e_3"): e3_out = conv(s1_out, ksize=3, stride=1, filters_out=expand, kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(), bias=False) e3_out = tf.nn.relu(e3_out) x = tf.concat([e1_out, e3_out], axis=3, name='concat') if use_bypass: x = inputs + x return x ########################################### # Layer definitions ########################################### def conv(x, ksize, stride, filters_out, kernel_initializer, bias=True): with tf.variable_scope('conv', use_resource=True): return tf.layers.conv2d( inputs=x, filters=filters_out, kernel_size=ksize, strides=stride, padding='same', use_bias=bias, kernel_initializer=kernel_initializer, bias_initializer=tf.zeros_initializer(), kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=0.0002), activation=tf.nn.relu, data_format='channels_last') def add_arguments(parser): group = parser.add_argument_group('SqueezeNet') group.add_argument('--use-bypass', action='store_true', help="Use bypass in the fire module.") return parser def set_defaults(opts): opts['summary_str'] += "SqueezeNet\n" if not opts.get("lr_schedule"): opts['lr_schedule'] = 'polynomial_decay_lr' # set ImageNet specific defaults if opts["dataset"] == "imagenet": if not opts.get("weight_decay"): # value taken from tf_official_resnet - may not be appropriate for # small batch sizes opts["weight_decay"] = 1e-4 if not opts.get("base_learning_rate"): if opts["optimiser"] == "SGD": opts["base_learning_rate"] = -8 elif opts["optimiser"] == "momentum": opts["base_learning_rate"] = -11 if not opts.get("learning_rate_schedule"): opts["learning_rate_schedule"] = [0.3, 0.6, 0.8, 0.9] if not opts.get("learning_rate_decay"): opts["learning_rate_decay"] = [1.0, 0.1, 0.01, 0.001, 1e-4] if opts.get("warmup") is None: # warmup on by default for ImageNet opts["warmup"] = True if not opts.get("batch_size"): opts['batch_size'] = 2 # exclude beta and gamma from weight decay calculation opts["wd_exclude"] = ["beta", "gamma"] # set CIFAR specific defaults elif "cifar" in opts["dataset"]: if not opts.get("weight_decay"): # based on sweep with CIFAR-10 opts["weight_decay"] = 1e-6 if not opts.get("base_learning_rate"): opts["base_learning_rate"] = -10 if not opts.get("epochs") and not opts.get("iterations"): opts["epochs"] = 160 if not opts.get("learning_rate_schedule"): opts["learning_rate_schedule"] = [0.5, 0.75] if not opts.get("learning_rate_decay"): opts["learning_rate_decay"] = [1.0, 0.1, 0.01] if not opts.get("batch_size"): opts['batch_size'] = 128 if not opts.get('epochs') and not opts.get('iterations'): opts['epochs'] = 100 if (opts['precision'] == '32.32') and not opts.get("shards"): opts['shards'] = 2 opts['name'] = "SN_bs{}".format(opts['batch_size']) if opts.get('replicas') > 1: opts['name'] += "x{}r".format(opts['replicas']) if opts['pipeline_depth'] > 1: opts['name'] += "x{}p".format(opts['pipeline_depth']) elif opts.get('gradients_to_accumulate') > 1: opts['name'] += "x{}a".format(opts['gradients_to_accumulate']) opts['name'] += '_{}{}'.format(opts['precision'], '_noSR' if opts['no_stochastic_rounding'] else '')
[ "dave.lacey@graphcore.ai" ]
dave.lacey@graphcore.ai
66466494386c8a107ff4f40e407535ade7080eb0
e171f26598e7c134f7384b63e8bfbb3f51be6478
/migrations/versions/2feafb94b028_.py
c0cbdd7c157b139faf3c182a7fddf9b49ac6af65
[ "Apache-2.0" ]
permissive
matteobaldelli/tesi-api
de5811f611b65bfdd24fcc24e8da5a88d07be6fc
0b1caacec4ce7e633a69aaf4d6666c08f18248ca
refs/heads/master
2020-03-30T23:10:55.493190
2018-12-19T14:40:20
2018-12-19T14:40:20
151,692,881
0
0
null
2018-12-07T16:56:00
2018-10-05T08:36:52
Python
UTF-8
Python
false
false
648
py
"""empty message Revision ID: 2feafb94b028 Revises: 528a88a08c26 Create Date: 2018-10-15 10:59:54.796906 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '2feafb94b028' down_revision = '528a88a08c26' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('users', sa.Column('admin', sa.Boolean(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'admin') # ### end Alembic commands ###
[ "baldelli.matteo2@gmail.com" ]
baldelli.matteo2@gmail.com
74fdcfd69840950e1b3e336b45fef12d98d7d355
91ff6fdf7b2ccc58869d6ad41842f230644952c1
/requirements/venky_task/String/7.py
4f1a8999bfbb7bfa6d11aac952ba9d77b5cfcd61
[]
no_license
KONASANI-0143/Dev
dd4564f54117f54ccfa003d1fcec4220e6cbe1f9
23d31fbeddcd303a7dc90ac9cfbe2c762d61c61e
refs/heads/master
2023-08-14T15:59:59.012414
2021-10-13T14:54:49
2021-10-13T15:10:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
183
py
def venky(s): n=s.find("not") m=s.find("poor") for i in s.split(): if i=="not": c=s.replace(i,"poor") print(s[n:]+str(c)) n=input("enter a string :") venky(n)
[ "harinadhareddypython@gmail.com" ]
harinadhareddypython@gmail.com
8fb3fd4c442c10f7729994c9eb4b72ccd3b904b4
c4e08dea65628a880920b3289d41e06ee80532f6
/HW3_submission/63_submission/hw3.py
44ff40311375d9f285681ede88eefe92a370eb2c
[]
no_license
AlexTuisov/HW3
e9c53a80c07f316d4d467089a44b9059d29a8ca6
2f660cbcb5110c8b7aa1eccafb77b62b29979e48
refs/heads/master
2023-03-25T10:04:15.691570
2021-03-02T16:06:10
2021-03-02T16:06:10
326,445,840
0
0
null
null
null
null
UTF-8
Python
false
false
11,961
py
import random from copy import deepcopy import operator ids = ['318483906', '316051903'] class Agent: def __init__(self, initial_state, zone_of_control, order): self.zoc = zone_of_control self.state = initial_state self.order = order self.out_of_zone = self.outer_zone(self.zoc) def outer_zone(self, zoc): out_of_zone = [] for i in range(0, 10): for j in range(0, 10): if (i, j) not in zoc: out_of_zone.append((i, j)) return out_of_zone def neighbor_h_in_zone(self, zoc, state, i, j): counter = 0 if i + 1 <= 9: if (i + 1, j) in zoc: if state[i + 1][j] == 'H': counter = counter + 1 if i - 1 >= 0: if (i - 1, j) in zoc: if state[i - 1][j] == 'H': counter = counter + 1 if j + 1 <= 9: if (i, j + 1) in zoc: if state[i][j + 1] == 'H': counter = counter + 1 if j - 1 >= 0: if (i, j - 1) in zoc: if state[i][j - 1] == 'H': counter = counter + 1 return counter def neighbor_I_in_zone(self, zoc, state, i, j): counter = 0 if i + 1 <= 9: if (i + 1, j) in zoc: if state[i + 1][j] == 'I': counter = counter + 1 if i - 1 >= 0: if (i - 1, j) in zoc: if state[i - 1][j] == 'I': counter = counter + 1 if j + 1 <= 9: if (i, j + 1) in zoc: if state[i][j + 1] == 'I': counter = counter + 1 if j - 1 >= 0: if (i, j - 1) in zoc: if state[i][j - 1] == 'I': counter = counter + 1 return counter def neighbor_S_in_zone(self, zoc, state, i, j): counter = 0 if i + 1 <= 9: if (i + 1, j) in zoc: if state[i + 1][j] == 'S': counter = counter + 1 if i - 1 >= 0: if (i - 1, j) in zoc: if state[i - 1][j] == 'S': counter = counter + 1 if j + 1 <= 9: if (i, j + 1) in zoc: if state[i][j + 1] == 'S': counter = counter + 1 if j - 1 >= 0: if (i, j - 1) in zoc: if state[i][j - 1] == 'S': counter = counter + 1 return counter def neighbor_U_in_zone(self, zoc, state, i, j): counter = 0 if i + 1 <= 9: if (i + 1, j) in zoc: if state[i + 1][j] == 'U': counter = counter + 1 if i - 1 >= 0: if (i - 1, j) in zoc: if state[i - 1][j] == 'U': counter = counter + 1 if j + 1 <= 9: if (i, j + 1) in zoc: if state[i][j + 1] == 'U': counter = counter + 1 if j - 1 >= 0: if (i, j - 1) in zoc: if state[i][j - 1] == 'U': counter = counter + 1 return counter def neighbor_h_out_of_zone(self, zoc, state, i, j): counter = 0 if i + 1 <= 9: if (i + 1, j) not in zoc: if state[i + 1][j] == 'H': counter = counter + 1 if i - 1 >= 0: if (i - 1, j) not in zoc: if state[i - 1][j] == 'H': counter = counter + 1 if j + 1 <= 9: if (i, j + 1) not in zoc: if state[i][j + 1] == 'H': counter = counter + 1 if j - 1 >= 0: if (i, j - 1) not in zoc: if state[i][j - 1] == 'H': counter = counter + 1 return counter def S_weight(self, S): s_weight = {} zoc = self.zoc state =self.state for s in S: i = s[0] j = s[1] s_weight[s] = self.neighbor_h_in_zone(zoc, state, i, j) \ - self.neighbor_h_out_of_zone(zoc, state, i, j) \ - self.neighbor_I_in_zone(zoc, state, i, j) \ - self.neighbor_S_in_zone(zoc, state, i, j) \ - self.neighbor_U_in_zone(zoc, state, i, j) sorted_s = dict(sorted(s_weight.items(), key=operator.itemgetter(1), reverse=True)) return sorted_s def H_weight(self, H): h_weight = {} zoc = self.zoc state = self.state for h in H: i = h[0] j = h[1] h_weight[h] = self.H_in_danger(i, j) + self.neighbor_h_in_zone(zoc, state, i, j) \ - self.neighbor_h_out_of_zone(zoc, state, i, j) \ - self.neighbor_I_in_zone(zoc, state, i, j) \ - self.neighbor_U_in_zone(zoc, state, i, j) sorted_h = dict(sorted(h_weight.items(), key=operator.itemgetter(1), reverse=True)) return sorted_h def H_in_danger(self, i, j): flag = False if i + 1 <= 9: if self.state[i + 1][j] == 'S': flag = True if i - 1 >= 0: if self.state[i - 1][j] == 'S': flag = True if j + 1 <= 9: if self.state[i][j + 1] == 'S': flag = True if j - 1 >= 0: if self.state[i][j - 1] == 'S': flag = True return flag def act(self, state): zoc = self.zoc out_of_zone = self.out_of_zone action = self.minimax(state, 4, True, zoc, out_of_zone)[1] return action def moves(self, state): healthy = set() sick = set() h_IN_dang = set() for (i, j) in self.zoc: if 'H' in state[i][j]: healthy.add((i, j)) if 'S' in state[i][j]: sick.add((i, j)) weighted_s = self.S_weight(sick) for h in healthy: if self.H_in_danger(h[0], h[1]): h_IN_dang.add(h) if len(h_IN_dang) == 0: weighted_h = self.H_weight(healthy) else: weighted_h = self.H_weight(h_IN_dang) i = 1 flag1 = False flag2 = False for Q_act in weighted_s: if len(weighted_s) > 0: if i == 1: max_weight = weighted_s[Q_act] x1, y1 = Q_act[0], Q_act[1] i = i + 1 flag1 = True if len(weighted_s) > 1: if i == 2: if weighted_s[Q_act] > max_weight: max2_weight = max_weight x2, y2 = x1, y1 max_weight = weighted_s[Q_act] x1, y1 = Q_act[0], Q_act[1] else: max2_weight = weighted_s[Q_act] x2, y2 = Q_act[0], Q_act[1] flag2 = True i = i + 1 elif i > 2: if weighted_s[Q_act] > max_weight: max2_weight = max_weight x2, y2 = x1, y1 max_weight = weighted_s[Q_act] x1, y1 = Q_act[0], Q_act[1] elif weighted_s[Q_act] > max2_weight: max2_weight = weighted_s[Q_act] x2, y2 = Q_act[0], Q_act[1] list_Q = [] if flag2 == True: list_Q = list(( (x1,y1),(x2,y2))) elif flag1 == True: list_Q = list((x1, y1)) i = 1 flag3 = False for I_act in weighted_h: if len(weighted_h) > 0: flag3 = True if i == 1: max_weight = weighted_h[I_act] x, y = I_act[0], I_act[1] else: if weighted_h[I_act] > max_weight: max_weight = weighted_h[I_act] x, y = I_act[0], I_act[1] list_I = [] if flag3 == True: list_I.append((x, y)) all_moves1 = [] all_moves2 = [] all_1 = [] all_4 = [] all_5 = [] all_7 = [] if flag2 == True : if flag3 == True: all_1 = [(('quarantine', (x1, y1)), ('quarantine', (x2, y2)), ('vaccinate', (x, y)))] all_7 = [(('quarantine', (x2, y2)), ('vaccinate', (x, y)))] all_2 = [(('quarantine', (x1, y1)), ('quarantine', (x2, y2)))] all_3 = [(('quarantine', (x2, y2)),)] all_moves1 = all_1 + all_2 + all_3 + all_7 if flag1 == True: if flag3 ==True: all_4 = [(('quarantine', (x1, y1)), ('vaccinate', (x, y)))] all_5 = [(('vaccinate', (x, y)),)] all_6 = [(('quarantine', (x1, y1)),)] all_moves2 = all_4 + all_5 + all_6 no_combinations = tuple() all_moves = all_moves1 + all_moves2 all_moves.append(no_combinations) return all_moves def game_over(self, state): flag = True for (i, j) in self.zoc: if state[i][j] == 'S': flag = False for (i, j) in self.out_of_zone: if state[i][j] == 'S': flag = False return flag def update_heristic_scores(self, state, player, control_zone): score = [0, 0] for (i, j) in control_zone: if 'H' in state[i][j]: score[player] += 2 if 'I' in state[i][j]: score[player] += 5 if 'S' in state[i][j]: score[player] -= -1 if 'Q' in state[i][j]: score[player] += 3 return score[player] def evaluate(self, state,max_player, zoc, out_of_zone): if max_player: eval = self.update_heristic_scores(state, 0, zoc) - self.update_heristic_scores(state, 1, out_of_zone) else: eval = self.update_heristic_scores(state, 1, zoc) - self.update_heristic_scores(state, 0, out_of_zone) return eval def apply_action(self, action, state): new_state = deepcopy(state) for act in action: if act == (): return new_state x = act[1][0] y = act[1][1] if act[0] == 'vaccinate': new_state[x][y] = "I" elif act[0] == 'quarantine': new_state[x][y] = "Q" return new_state def minimax(self, state, depth, max_player, zoc, out_of_zone): if depth == 0 or self.game_over(state): return self.evaluate(state, max_player, zoc, out_of_zone), None actions = self.moves(state) if max_player: maxEval = float('-inf') best_action = None for act in actions: new_state = self.apply_action(act, state) evaluation = self.minimax(new_state, depth - 1, False, out_of_zone, zoc)[0] maxEval = max(maxEval, evaluation) if maxEval == evaluation: best_action = act return maxEval, best_action else: minEval = float('inf') best_action = None for act in actions: new_state = self.apply_action(act, state) evaluation = self.minimax(new_state, depth - 1, True, zoc, out_of_zone)[0] minEval = min(minEval, evaluation) if minEval == evaluation: best_action = act return minEval, best_action
[ "queldelan@gmail.com" ]
queldelan@gmail.com
ad8df248427f7098d6463b39e0c10612baf026cc
807305b8aefbd7aac4f44c67deed06c059ca02d9
/src/stk/molecular/topology_graphs/polymer/linear/vertices.py
95e4ae66c4c80eab25400a4a05c7c5504fb3b81f
[ "MIT" ]
permissive
supramolecular-toolkit/stk
c40103b4820c67d110cbddc7be30d9b58d85f7af
46f70cd000890ca7c2312cc0fdbab306565f1400
refs/heads/master
2022-11-27T18:22:25.187588
2022-11-16T13:23:11
2022-11-16T13:23:11
129,884,045
22
5
MIT
2019-08-19T18:16:41
2018-04-17T09:58:28
Python
UTF-8
Python
false
false
6,060
py
""" Linear Polymer Vertices ======================= """ import logging from ...topology_graph import Vertex logger = logging.getLogger(__name__) class LinearVertex(Vertex): """ Represents a vertex in the middle of a linear polymer chain. """ def __init__(self, id, position, flip): """ Initialize a :class:`.LinearVertex` instance. Parameters ---------- id : :class:`int` The id of the vertex. position : :class:`numpy.ndarray` The position of the vertex. flip : :class:`bool` If ``True`` any building block placed by the vertex will have its orientation along the chain flipped. """ super().__init__(id, position) self._flip = flip def get_flip(self): """ Return ``True`` if the vertex flips building blocks it places. Returns ------- :class:`bool` ``True`` if the vertex flips building blocks it places. """ return self._flip def clone(self): clone = super().clone() clone._flip = self._flip return clone def place_building_block(self, building_block, edges): assert building_block.get_num_functional_groups() == 2, ( f"{building_block} needs to have exactly 2 functional " "groups but has " f"{building_block.get_num_functional_groups()}." ) building_block = building_block.with_centroid( position=self._position, atom_ids=building_block.get_placer_ids(), ) fg1, fg2 = building_block.get_functional_groups() fg1_position = building_block.get_centroid( atom_ids=fg1.get_placer_ids(), ) fg2_position = building_block.get_centroid( atom_ids=fg2.get_placer_ids(), ) return building_block.with_rotation_between_vectors( start=fg2_position - fg1_position, target=[-1 if self._flip else 1, 0, 0], origin=self._position, ).get_position_matrix() def map_functional_groups_to_edges(self, building_block, edges): fg1_id, fg2_id = self._sort_functional_groups(building_block) edge1_id, edge2_id = self._sort_edges(edges) return { fg1_id: edge1_id, fg2_id: edge2_id, } @staticmethod def _sort_functional_groups(building_block): fg1, fg2 = building_block.get_functional_groups() x1, y1, z1 = building_block.get_centroid( atom_ids=fg1.get_placer_ids(), ) x2, y2, z2 = building_block.get_centroid( atom_ids=fg2.get_placer_ids(), ) return (0, 1) if x1 < x2 else (1, 0) @staticmethod def _sort_edges(edges): edge1, edge2 = edges x1, y1, z1 = edge1.get_position() x2, y2, z2 = edge2.get_position() if x1 < x2: return edge1.get_id(), edge2.get_id() else: return edge2.get_id(), edge1.get_id() def __str__(self): return ( f"Vertex(id={self._id}, " f"position={self._position.tolist()}, " f"flip={self._flip})" ) class TerminalVertex(LinearVertex): """ Represents a vertex at the end of a polymer chain. Do not instantiate this class directly, use :class:`.HeadVertex` or :class:`.TailVertex` instead. """ def place_building_block(self, building_block, edges): if ( building_block.get_num_functional_groups() != 1 and building_block.get_num_placers() > 1 ): return super().place_building_block(building_block, edges) building_block = building_block.with_centroid( position=self._position, atom_ids=building_block.get_placer_ids(), ) fg, *_ = building_block.get_functional_groups() fg_centroid = building_block.get_centroid( atom_ids=fg.get_placer_ids(), ) core_centroid = building_block.get_centroid( atom_ids=building_block.get_core_atom_ids(), ) return building_block.with_rotation_between_vectors( start=fg_centroid - core_centroid, # _cap_direction is defined by a subclass. target=[self._cap_direction, 0, 0], origin=self._position, ).get_position_matrix() def map_functional_groups_to_edges(self, building_block, edges): if building_block.get_num_functional_groups() == 2: functional_groups = self._sort_functional_groups( building_block=building_block, ) index = 1 if self._cap_direction == 1 else 0 return {functional_groups[index]: edges[0].get_id()} elif building_block.get_num_functional_groups() == 1: return {0: edges[0].get_id()} else: raise ValueError( "The building block of a polymer " "must have 1 or 2 functional groups." ) class HeadVertex(TerminalVertex): """ Represents a vertex at the head of a polymer chain. """ # The direction to use if the building block placed on the # vertex only has 1 FunctionalGroup. _cap_direction = 1 class TailVertex(TerminalVertex): """ Represents a vertex at the tail of a polymer chain. """ # The direction to use if the building block placed on the # vertex only has 1 FunctionalGroup. _cap_direction = -1 class UnaligningVertex(LinearVertex): """ Just places a building block, does not align. """ def place_building_block(self, building_block, edges): return building_block.with_centroid( position=self._position, atom_ids=building_block.get_placer_ids(), ).get_position_matrix() def map_functional_groups_to_edges(self, building_block, edges): return { fg_id: edge.get_id() for fg_id, edge in enumerate(edges) }
[ "noreply@github.com" ]
noreply@github.com
61a317af4960d6afc294524a644e313c38ba24ec
fadae8c730ada52c05a5e081f686b7619b7c8675
/job/urls.py
30d99d1ba83ef5304f88963822e6b3c268e5508f
[]
no_license
amar-jondhalekar/online-job-portal2019-20
b609361166f2721a31384f008920f1cabba45689
41495bf54cfbfe22a76b1e9025741bccdf2d2ed0
refs/heads/master
2022-12-24T10:42:26.925801
2020-10-05T13:19:19
2020-10-05T13:19:19
301,413,792
0
0
null
null
null
null
UTF-8
Python
false
false
1,943
py
"""unicareer 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 . import views urlpatterns = [ path('', views.index, name='home'), path('home', views.index,name='home'), path('login/', views.login,name='login'), path('logout/', views.logout, name='logout'), path('register/', views.register,name='register'), path('login/forgot-password', views.frpass, name='frpass'), path('about/', views.about,name='about'), path('contact/', views.contact,name='contact'), path('post_job/', views.post_job,name='post_job'), path('login/register', views.register, name='register'), path('login/login', views.login, name='login'), path('browse_job', views.browse_job, name='browse_job'), path('add-resume', views.add_resume, name='add_resume'), path('job-details', views.job_details, name='job-details'), path('job-details/<int:id>', views.job_details, name='job-details_id'), path('search', views.search_job, name='search_job'), path('faq', views.faq,name='faq'), path('blog', views.blog, name='blog'), path('job-details/home', views.jobindex, name='jobhome'), path('about/home', views.reindex,name='redirecthome'), path('contact/home', views.reindex,name='redirecthome'), path('post_job/home', views.reindex,name='redirecthome'), ]
[ "amarjondhalekar221297@gmail.com" ]
amarjondhalekar221297@gmail.com
5e247276b561d0ca5b33c8a67c740600b365f044
812ec66111f3f71acbc6ca98a557edee419e3e76
/utils/functions.py
0c9a24313c848469ac5b9405b260740ee33e620f
[ "MIT" ]
permissive
AlanSavio25/AVSR-Dataset-Pipeline
7a35d922607901f0fa70593d1e34b89f3276e993
6e6d44eca6133c2e0223e9be8d011be0b68c73d1
refs/heads/main
2023-07-07T00:01:28.025308
2021-08-11T16:47:27
2021-08-11T16:47:27
389,610,550
6
0
null
null
null
null
UTF-8
Python
false
false
4,003
py
import torch import numpy as np import time, glob, shutil, datetime import xml.etree.ElementTree as ET from facetrack import * from syncnet import * import logging logging.basicConfig(format='[%(levelname)s] %(message)s', level=logging.INFO) def cut_into_utterances(filename, output_dir, genre, xmldir, source_dir=None): xmlfile = os.path.join(xmldir, filename+'.xml') tree = ET.parse(xmlfile) root = tree.getroot() utterance_items = [] paths = glob.glob(f"/afs/inf.ed.ac.uk/group/project/nst/bbcdata/ptn*/**/{filename}*.ts") \ + glob.glob(f"/afs/inf.ed.ac.uk/group/project/nst/bbcdata/raw/{filename}*.ts") if source_dir: paths += glob.glob(f"{source_dir}/*{filename}*webm") # (paths[0]) if len(paths)==0: raise Exception(f"Could not find {filename} in any of the source directories") inputVideo = paths[0] command_elems = ["ffmpeg -loglevel quiet -y -i " + inputVideo] for item in root.findall('./body/segments/segment'): if (item.attrib['id'].split('_')[-1]=='human'): if (float(item.attrib['endtime']) - float(item.attrib['starttime'])<2): continue location = output_dir + item.attrib['id'] ready_to_crop = prepare_output_directory(location) if ready_to_crop: utterance_items.append(item) data = item.attrib start = datetime.timedelta(seconds=float(data['starttime'])) end = datetime.timedelta(seconds=float(data['endtime'])) output = os.path.join(location, 'pyavi', 'video.avi') command_elems.append(" -ss " + str(start) + " -to " + str(end) + " -c copy " + output) # -c:a mp3 -c:v mpeg4 create_transcript_from_XML(location, item, genre) s = time.time() if len(command_elems) == 1: logging.warning("No utterances found.") logging.warning(f"The available segments are: {list(root.findall('./body/segments'))}") else: command = "".join(command_elems) result = subprocess.run(command, shell=True, stdout=None) if result.returncode != 0: logging.error(f"ERROR: ffmpeg failed to trim video: {filename}") logging.error(f"result: {result}") t = time.time() - s logging.info(f"Took {t} seconds to trim {len(command_elems)-1} utterances") return utterance_items def get_genre(filename): xmldir = "/afs/inf.ed.ac.uk/group/cstr/datawww/asru/MGB1/data/xml/" xmlfile = os.path.join(xmldir, filename+'.xml') tree = ET.parse(xmlfile) root = tree.getroot() head = root.find('./head/recording') genre = head.attrib["genre"] return genre def prepare_output_directory(location): ready = True incomplete_directory_exists = os.path.isdir(location) and not os.path.exists(f"{location}/0*.txt") if(incomplete_directory_exists): shutil.rmtree(location) elif(os.path.isdir(location)): ready = False return ready # This utterance has been processed already. else: pass subprocess.run("mkdir -p " + location + "/pyavi/", stdout=subprocess.DEVNULL, shell=True) if not os.path.isdir(location): return False return ready def create_transcript_from_XML(location, item, genre): utterance = "" for child in item: if child.text: utterance+=child.text + " " data = item.attrib data.update({"utterance": utterance}) data.update({"genre": genre}) with open(location + '/transcript.txt', 'w') as outfile: outfile.write(str(data)) def cleanup(dataset_dir): for utterance in os.listdir(dataset_dir): source = os.path.join(dataset_dir, utterance, 'pycrop') dest = os.path.join(dataset_dir, utterance) for f in os.listdir(source): new_path = shutil.move(f"{source}/{f}", f"{dest}/{f}") for f in glob.glob(f"{dest}/py*"): shutil.rmtree(f)
[ "s1768177@hessdalen.inf.ed.ac.uk" ]
s1768177@hessdalen.inf.ed.ac.uk
2ba31e7a90badb5fed8c2e13245185b77c8e19da
91bd3f2e5d318bbfb69994fb0018d6be20be1e13
/load_replay.py
bb9e31a88b12f08f686955c63aa1f918516d0612
[]
no_license
jesterswilde/dlgo
9aebd87a49de5c750284f8e58eb824421c4f3a98
a67a8c4674ec56058f7a7f48bcf5cda8a711606c
refs/heads/master
2020-09-12T06:43:02.414401
2019-11-27T00:41:55
2019-11-27T00:41:55
222,344,495
0
0
null
null
null
null
UTF-8
Python
false
false
671
py
from dlgo.gosgf import Sgf_game from dlgo.goboard import GameState, Move from dlgo.gotypes import Point from dlgo.utils import print_board from time import sleep sgf_example = "(;GM[1]FF[4]SZ[9];W[ef];B[ff];W[df];B[fe];W[fc];B[ec];W[gd];B[fb])" sgf_game = Sgf_game.from_string(sgf_example) game_state = GameState.new_game(19) for item in sgf_game.main_sequence_iter(): color, move_tuple = item.get_move() if color is not None and move_tuple is not None: row, col = move_tuple point = Point(row+1, col+1) move = Move.play(point) game_state = game_state.apply_move(move) print_board(game_state.board) sleep(0.3)
[ "jesterswilde@gmail.com" ]
jesterswilde@gmail.com
1f8c10416376d98fd9647224d5f6e4826a12517b
cd0cf1c75c715a67502ff7f164bb070da78956de
/calculation/migrations/0046_auto_20160310_0927.py
2a0fc34d174875b0400e1f1c7e5a69becb00158e
[]
no_license
nustarnuclear/orient_linux
9792fb4319007708861d619dac081fa32206d3f6
95082ea56a0dfc248024f9bf54897a017985ccdf
refs/heads/master
2020-03-28T03:17:02.629719
2017-01-04T08:38:16
2017-01-04T08:38:16
43,117,046
0
0
null
null
null
null
UTF-8
Python
false
false
1,065
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import calculation.models class Migration(migrations.Migration): dependencies = [ ('calculation', '0045_server_queue'), ] operations = [ migrations.RemoveField( model_name='server', name='status', ), migrations.AddField( model_name='robintask', name='log_file', field=models.FileField(upload_to=calculation.models.get_robintask_upload_path, blank=True, null=True), ), migrations.AddField( model_name='robintask', name='output_file', field=models.FileField(upload_to=calculation.models.get_robintask_upload_path, blank=True, null=True), ), migrations.AlterField( model_name='prerobintask', name='server', field=models.ForeignKey(to='calculation.Server', default=calculation.models.server_default, related_name='pre_robin_inputs'), ), ]
[ "hengzhang@nustarnuclear.com" ]
hengzhang@nustarnuclear.com
e4857470aea4908288af4a85deb4bb7996268d41
ab8a40b20c2330a514121f85a4fbd4400cb8136e
/Yj3b.py
f4bcba134e4e92d687d0a1c16a8856f5107ef2fd
[]
no_license
transit2019x/techgym_python
331fd7f725f21ca32d30409d0c4366cfb9af1547
42d0819bb20de0730c95b4dade9a69fa9b9d1fe7
refs/heads/master
2020-06-03T21:35:19.274144
2019-06-11T17:05:28
2019-06-11T17:05:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,037
py
import random class Player: def __init__(self, name, coin): self.name = name self.coin = coin def info(self): print(self.name + ':' + str(self.coin)) def set_bet_coin(self, bet_coin): self.bet_coin = bet_coin self.coin -= bet_coin class Human(Player): def __init__(self, name, coin): super().__init__(name, coin) def bet(self): bet_message = '何枚BETしますか?:(1-99)' bet_coin = input(bet_message) while not self.enable_bet_coin(bet_coin): bet_coin = input(bet_message) super().set_bet_coin(int(bet_coin)) print(bet_coin) def enable_bet_coin(self, string): if string.isdigit(): number = int(string) if number >= 1 and number <= 99: return True else: return False else: return False def play(): print('デバッグログ:play()') human = Human('MY', 500) human.info() human.bet() human.info() class Computer(Player): def __init__(self, name, coin): super().__init__(name, coin) play()
[ "noreply@github.com" ]
noreply@github.com
dfad275dde294c663c5a57d8a8191d0dd9174ac4
9b7ff4be461a619bd7fe4e02d285c4375a0df297
/src/create_config.py
bf8c01829f7dfa11afaf33f7aadac8cdb8b19f7c
[ "Apache-2.0" ]
permissive
PTA84/google_assistant_vietnamese_speaking
1f59bbf33f359e919f649022f78fb31ae3ceef12
938376c3bb80a78d8b8c3c714363550f3c9ea7b6
refs/heads/main
2023-06-26T12:59:31.796526
2021-07-15T06:01:56
2021-07-15T06:01:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,642
py
import json data = {} data['mic'] = [] data['mic'].append({ 'type': 'None Respeaker Mic', 'is_active': True }) data['mic'].append({ 'type': 'ReSpeaker 2/4-Mics Pi HAT', 'is_active': False }) data['mic'].append({ 'type': 'ReSpeaker Mic Array v2.0', 'is_active': False }) data['mic'].append({ 'type': 'ReSpeaker Core v2.0', 'is_active': False }) data['volume'] = [] data['volume'].append({ 'value': 50, 'type': 'speak' }) data['volume'].append({ 'value': 50, 'type': 'event' }) data['hotword'] = [] data['hotword'].append({ 'name': 'hey siri', 'keyword_path': 'hey siri_raspberry-pi.ppn', 'sensitive': 0.3, 'is_active': True }) data['hotword'].append({ 'name': 'americano', 'keyword_path': 'americano_raspberry-pi.ppn', 'sensitive': 0.3, 'is_active': True }) data['hotword'].append({ 'name': 'blueberry', 'keyword_path': 'blueberry_raspberry-pi.ppn', 'sensitive': 0.3, 'is_active': True }) data['hotword'].append({ 'name': 'terminator', 'keyword_path': 'terminator_raspberry-pi.ppn', 'sensitive': 0.3, 'is_active': False }) data['hotword'].append({ 'name': 'ok google', 'keyword_path': 'ok google_raspberry-pi.ppn', 'sensitive': 0.3, 'is_active': True }) data['hotword'].append({ 'name': 'hey google', 'keyword_path': 'hey google_raspberry-pi.ppn', 'sensitive': 0.3, 'is_active': True }) with open('config.json', 'w') as outfile: json.dump(data, outfile)
[ "noreply@github.com" ]
noreply@github.com
5faf40bbcb2caaa7edd850c568952b71d9a6de70
05c22017cde07bb9fdff2c7f03f2602b1cd15323
/src/textual/widget.py
e43372e6a165b2ec0153e5c91c32e700bf39cf10
[ "MIT" ]
permissive
ramiro/textual
00b0a7fc6fea95d327455c8328248cd926f3eaff
a6a912ab2713b0e1cb668224f7a38f31b1c9939c
refs/heads/main
2023-06-14T01:22:40.975706
2021-07-05T14:06:16
2021-07-05T14:06:16
383,201,815
0
0
MIT
2021-07-05T16:25:54
2021-07-05T16:25:53
null
UTF-8
Python
false
false
6,353
py
from __future__ import annotations from logging import getLogger from typing import ( Callable, cast, ClassVar, Generic, Iterable, NewType, TypeVar, TYPE_CHECKING, ) from rich.align import Align from rich.console import Console, RenderableType from rich.pretty import Pretty from rich.panel import Panel import rich.repr from rich.segment import Segment from rich.style import Style from . import events from ._animator import BoundAnimator from ._context import active_app from ._loop import loop_last from ._line_cache import LineCache from .message import Message from .messages import UpdateMessage, LayoutMessage from .message_pump import MessagePump from .geometry import Point, Dimensions from .reactive import Reactive if TYPE_CHECKING: from .app import App from .view import View WidgetID = NewType("WidgetID", int) log = getLogger("rich") @rich.repr.auto class Widget(MessagePump): _id: ClassVar[int] = 0 _counts: ClassVar[dict[str, int]] = {} can_focus: bool = False def __init__(self, name: str | None = None) -> None: class_name = self.__class__.__name__ Widget._counts.setdefault(class_name, 0) Widget._counts[class_name] += 1 _count = self._counts[class_name] self.id: WidgetID = cast(WidgetID, Widget._id) Widget._id += 1 self.name = name or f"{class_name}#{_count}" self.size = Dimensions(0, 0) self.size_changed = False self._repaint_required = False self._layout_required = False self._animate: BoundAnimator | None = None super().__init__() visible: Reactive[bool] = Reactive(True, layout=True) layout_size: Reactive[int | None] = Reactive(None) layout_fraction: Reactive[int] = Reactive(1) layout_minimim_size: Reactive[int] = Reactive(1) layout_offset_x: Reactive[float] = Reactive(0, layout=True) layout_offset_y: Reactive[float] = Reactive(0, layout=True) def __init_subclass__(cls, can_focus: bool = True) -> None: super().__init_subclass__() cls.can_focus = can_focus def __rich_repr__(self) -> rich.repr.RichReprResult: yield "name", self.name def __rich__(self) -> RenderableType: return self.render() @property def is_visual(self) -> bool: return True @property def app(self) -> "App": """Get the current app.""" return active_app.get() @property def console(self) -> Console: """Get the current console.""" return active_app.get().console @property def root_view(self) -> "View": """Return the top-most view.""" return active_app.get().view @property def animate(self) -> BoundAnimator: if self._animate is None: self._animate = self.app.animator.bind(self) assert self._animate is not None return self._animate @property def layout_offset(self) -> tuple[int, int]: """Get the layout offset as a tuple.""" return (round(self.layout_offset_x), round(self.layout_offset_y)) def require_repaint(self) -> None: """Mark widget as requiring a repaint. Actual repaint is done by parent on idle. """ self._repaint_required = True self.post_message_no_wait(events.Null(self)) def require_layout(self) -> None: self._layout_required = True self.post_message_no_wait(events.Null(self)) def check_repaint(self) -> bool: return self._repaint_required def check_layout(self) -> bool: return self._layout_required def reset_check_repaint(self) -> None: self._repaint_required = False def reset_check_layout(self) -> None: self._layout_required = False def get_style_at(self, x: int, y: int) -> Style: offset_x, offset_y = self.root_view.get_offset(self) return self.root_view.get_style_at(x + offset_x, y + offset_y) async def forward_event(self, event: events.Event) -> None: await self.post_message(event) async def refresh(self) -> None: """Re-render the window and repaint it.""" self.require_repaint() await self.repaint() async def repaint(self) -> None: """Instructs parent to repaint this widget.""" await self.emit(UpdateMessage(self, self)) async def update_layout(self) -> None: await self.emit(LayoutMessage(self)) def render(self) -> RenderableType: """Get renderable for widget. Returns: RenderableType: Any renderable """ return Panel( Align.center(Pretty(self), vertical="middle"), title=self.__class__.__name__ ) async def action(self, action: str, *params) -> None: await self.app.action(action, self) async def post_message(self, message: Message) -> bool: if not self.check_message_enabled(message): return True return await super().post_message(message) async def on_event(self, event: events.Event) -> None: if isinstance(event, events.Resize): new_size = Dimensions(event.width, event.height) if self.size != new_size: self.size = new_size self.require_repaint() await super().on_event(event) async def on_idle(self, event: events.Idle) -> None: if self.check_layout(): self.reset_check_repaint() self.reset_check_layout() await self.update_layout() elif self.check_repaint(): self.reset_check_repaint() self.reset_check_layout() await self.repaint() async def focus(self) -> None: await self.app.set_focus(self) async def capture_mouse(self, capture: bool = True) -> None: await self.app.capture_mouse(self if capture else None) async def on_mouse_move(self, event: events.MouseMove) -> None: style_under_cursor = self.get_style_at(event.x, event.y) log.debug("%r", style_under_cursor) async def on_mouse_up(self, event: events.MouseUp) -> None: style = self.get_style_at(event.x, event.y) if "@click" in style.meta: log.debug(style._link_id) await self.app.action(style.meta["@click"], default_namespace=self)
[ "willmcgugan@gmail.com" ]
willmcgugan@gmail.com
9afca773cc3e575a5e99270fc96821846e41becd
1eb7fa8b1745d4e51cefb4eceb44621862516aa6
/Company Interview/FB/BiggestKValuesInBST.py
fd6ddc0d98fe0ee5e2f7a5090dd8918d9e3db922
[]
no_license
geniousisme/CodingInterview
bd93961d728f1fe266ad5edf91adc5d024e5ca48
a64bca9c07a7be8d4060c4b96e89d8d429a7f1a3
refs/heads/master
2021-01-10T11:15:31.305787
2017-03-06T00:03:13
2017-03-06T00:03:13
43,990,453
0
1
null
null
null
null
UTF-8
Python
false
false
1,292
py
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution1(object): def biggestKthValues(self, root): res = []; stack = [] while root or stack: if root: stack.append(root) root = root.right else: top = stack.pop() res.append(top.val) root = top.left return res class Solution(object): # iterative def biggestKthValues(self, root, k): res = count = 0; stack = []; while root or stack: if root: stack.append(root) root = root.right else: top = stack.pop() if count == k - 1: return top.val else: count += 1 root = top.left return res if __name__ == "__main__": s = Solution() t9 = TreeNode(9) t1 = TreeNode(1) t5 = TreeNode(5) t7 = TreeNode(7) t13 = TreeNode(13) t11 = TreeNode(11) t15 = TreeNode(15) t9.left = t5 t9.right = t13 t5.left = t1 t5.right = t7 t13.left = t11 t13.right = t15 print s.biggestKthValues(t9, 3)
[ "chia-hao.hsu@aiesec.net" ]
chia-hao.hsu@aiesec.net
cb73ffe58893ed5b0a38623bfbfb1ef7cfc50f50
eac0a13fea8acd3ee5d8c6bd72b97f39102c6337
/Math/209poll_2019/functions.py
a382915f3c2973ddad0a4505997f8e3d8ab1ed16
[]
no_license
Jean-MichelGRONDIN/EPITECH_Tek2_Projects
ddb022cc6dafd9c3d8d1e8b17bad8de108a0cd2c
eb4621bb747b1f2cca3edfe993fefef4b564835f
refs/heads/master
2023-01-04T13:12:21.670186
2020-10-23T06:16:50
2020-10-23T06:16:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,381
py
## ## EPITECH PROJECT, 2020 ## 209poll_2019 ## File description: ## functions ## from math import sqrt def displayGivenVals(pSize, sSize, p): print("Population size: {}".format(pSize)) print("Sample size: {}".format(sSize)) print("Voting intentions: {:.2f}%".format(p)) def displayCalcsRes(variance, confiNineFive, confiNineNine): print("Variance: {:.6f}".format(variance)) print("95% confidence interval: [{:.2f}%; {:.2f}%]".format(confiNineFive[0] * 100, confiNineFive[1] * 100)) print("99% confidence interval: [{:.2f}%; {:.2f}%]".format(confiNineNine[0] * 100, confiNineNine[1] * 100)) def calcConfidenceInterval(pF, constVal, variance): tmp = [pF - (constVal * sqrt(variance)), pF + (constVal * sqrt(variance))] res = [] for val in tmp: if val < 0: val = 0 if val > 1: val = 1 res.append(val) return (res) def poll(pSize, sSize, p): try: pF = p / 100 endPop = (pSize - sSize) / (pSize - 1) variance = (pF * (1 - pF) * endPop) / sSize confiNineFive = calcConfidenceInterval(pF, 1.96, variance) confiNineNine = calcConfidenceInterval(pF, 2.58, variance) except: return (84) displayGivenVals(pSize, sSize, p) displayCalcsRes(variance, confiNineFive, confiNineNine) return (0)
[ "jean-michel@pop-os.localdomain" ]
jean-michel@pop-os.localdomain
f38ec7a4034c85010ec09729cea5e0713e174bab
97cd48c71d5a08ec5e2d61689a077b55e543e4f0
/projecteuler/012_highly_divisible_triangular_number.py
3e779b22304b99a27b249bb6a622639426a30c50
[ "MIT" ]
permissive
vikasmunshi/euler
001eb1c5b35ff873a0c2f526a4bb2d439152fb04
da4a7916b24e2d2b902ffdd1094991416eb74034
refs/heads/master
2020-09-05T09:41:28.306357
2020-04-13T08:26:33
2020-04-13T08:26:33
220,060,629
0
0
null
null
null
null
UTF-8
Python
false
false
1,215
py
#!/usr/bin/env python3.8 # -*- coding: utf-8 -*- """ https://projecteuler.net/problem=12 The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? Answer: 76576500 """ def num_factors(n: int) -> int: return 1 + 2 * sum([1 for i in range(2, int(n ** 0.5) + 1) if n % i == 0]) - (1 if n % int(n ** 0.5) == 0 else 0) def highly_divisible_triangle_number(num_divisors: int) -> int: i, triangle_number = 1, 1 while num_divisors > num_factors(triangle_number): i += 1 triangle_number = i * (i + 1) // 2 return triangle_number if __name__ == '__main__': from .evaluate import Watchdog with Watchdog() as wd: result = wd.evaluate_range(highly_divisible_triangle_number, answers={5: 28, 500: 76576500})
[ "vikas.munshi@ing.com" ]
vikas.munshi@ing.com
0fe19b24e222e8c4a1415ff3ce8417790c631ad4
33614ce5ac1850d7ac3f8a5d156506dd560fee66
/TFIDF_Keywords_2_JH_forLIRA.py
9d56d910eea011e8bf136dbe23c18083a9cdb7c0
[ "Unlicense" ]
permissive
william-letton/ASSIST
80917299e6fc168ca489056532ea403ebe97975c
b1b998de257a38f02206bccc8a1465bbd908b4f3
refs/heads/master
2022-09-02T10:46:29.157563
2020-05-20T07:54:52
2020-05-20T07:54:52
265,490,891
0
0
null
null
null
null
UTF-8
Python
false
false
9,303
py
import time import csv import math from Screening.models import Article,Project from Screening.ScreeningCeleryTasks import ReconcileTidyAsynch ## Define a character list of the punctuations to be removed during processing. punctuations = "•™©!£$€/\%^&*+±=()≥[]|0123456789'=.,:;?%<>ÿòñœ~#@-—–{}úøîæ÷ó¬åய§"+'"“”' def SuggestTagsMain(project,request): ## Note start time for testing. start = time.time() print("start: ",time.time()) #Get the correct abstracts - Pooled tags or individual or gold standard choice abstracts,screening_codes= GetDataForSuggester(project,request) #Get count count_all_abstracts=len(abstracts) print("number of abstracts: ",count_all_abstracts) #Make abstracts lower all_abstracts_lower = GetAbstractsInLower(abstracts) ## Create a list of screening codes without repetition. screening_codes_key = list() for code in project.allowedTags.all(): screening_codes_key.append(code.Tag) ## Split abstracts into words and put into vocabulary list. vocabulary = GetOurVocabulary(all_abstracts_lower,count_all_abstracts) vocabulary_length=len(vocabulary) print("length of vocabulary: ", vocabulary_length) ## Calculating TF values.Create a dictionary to store the total number of words for each screening code. print("start calculating TF values: ",time.time()) SCabstractsWordsNum, TFdict = GetTFDictSCabsts(all_abstracts_lower, count_all_abstracts, screening_codes_key, vocabulary,screening_codes) ## For each word in each screening code, divide the number of occurances by the total number of words for that screening code. TFdict = GetTFDictFinal(TFdict,SCabstractsWordsNum) ## Calculate IDF values. print("start calculating IDF values: ",time.time()) IDFdict = Pop0IDFDict(vocabulary) #Log scale IDFDict IDFdict = LogScaleIDFdict(IDFdict, all_abstracts_lower, count_all_abstracts, vocabulary) ## Calculate TF-IDF values. print("start calculating TF-IDF values: ",time.time()) ## Create a dictionary to store the results. TFIDFdict = GetTFIDFdict(IDFdict, TFdict, screening_codes_key, vocabulary) ## Print keyWord for code in TFIDFdict: l=list() for key,val in TFIDFdict[code].items(): l.append((val,key)) l.sort(reverse=True) print("\n",code) for key,value in l[0:15]: print(value) print("End: ",time.time()) print("Program took",time.time()-start,"seconds to run.") #returns our abstracts in a list (Full article object) def GetDataForSuggester(project,request): starsugg = time.time() AbstractsList = list() screening_codes = list() Type = request.POST["PoolType"] #Gold standard - Only reconciled if Type == "GoldStan": ReconcileTidyAsynch(project.UniqueID,False) goldsubset = project.assignedarticles.exclude(finalResult = None) for article in goldsubset.all(): #Get our content AbstractsList.append(article.content) #Get our tag screening_codes.append(article.finalResult.screeningTag.Tag) #All abstracts and screening codes if Type == "AllTag": allsubset = project.assignedarticles.exclude(screeningResults = None) for article in allsubset.all(): priortags = list() for tag in article.screeningResults.all(): #No point in adding multiple times if tag.screeningTag.Tag in priortags: continue AbstractsList.append(article.content) screening_codes.append(tag.screeningTag.Tag) priortags.append(tag.screeningTag.Tag) #User's codes if Type == "MyTag": userssubset = project.assignedarticles.filter(screeningResults__personScreening__pk = request.user.pk) for article in userssubset.all(): #Get our content AbstractsList.append(article.content) #Get our tags for code in article.screeningResults.all(): if code.personScreening == request.user: screening_codes.append(code.screeningTag.Tag) print("Getting Data took : " , time.time()-starsugg) #return what we have found return AbstractsList,screening_codes def GetAbstractsInLower(abstracts): ## Process the list of abstracts to remove punctuation and make lowercase all_abstracts_nopunct=[] #Add all of our characters bar punctuatuion for abstract in abstracts: no_punct="" for character in abstract: if character not in punctuations: no_punct= no_punct+character all_abstracts_nopunct.append(no_punct) #print("abstracts after no punctutation: ",all_abstracts_nopunct) #Get to lowercase all_abstracts_lower=[] for abstract in all_abstracts_nopunct: all_abstracts_lower.append(abstract.lower()) #print("abstracts after lowercase: ",all_abstracts_lower) #Return our result return all_abstracts_lower def GetOurVocabulary(all_abstracts_lower,count_all_abstracts): vocabulary=dict() for abstract in all_abstracts_lower: split=abstract.split() for word in split: vocabulary[word]=vocabulary.get(word,0)+1 #print("vocabulary: ",vocabulary) print("vocabulary length before processing: ",len(vocabulary)) # Take rare words out of vocabulary (to decrease run time later on). exWords=list() lowThreshold=1+((count_all_abstracts/200)**1.5) print("word count threshold for vocabulary inclusion: ",lowThreshold) for word in vocabulary: if vocabulary[word]<lowThreshold: exWords.append(str(word)) for word in exWords: del vocabulary[word] print("vocabulary length after processing: ",len(vocabulary)) vocabulary=list(set(vocabulary)) return vocabulary def GetTFDictSCabsts(all_abstracts_lower, count_all_abstracts, screening_codes_key, vocabulary,screening_codes): SCabstractsWordsNum=dict() ## Create a dictionary to store the TF values. TFdict=dict() for code in screening_codes_key: TFdict[code]={} SCabstractsWordsNum[code]=0 ## Insert all the words from the vocabulary into each screening code ## subdictionary, so that all subdictionaries have the same number of entries for i in TFdict: for j in vocabulary: TFdict[i][j]=0 ## Create a concatenated string of all of the abstracts of that screening code. for i in TFdict: ## Create an empty vector for boolean values bool=[] ## Create an empty list for abstracts text abstracts_text=[] # Compare the code to the screening_codes list to produce a list of true/false for j in screening_codes: if i==j: #print("True") bool.append(True) else: #print("False") bool.append(False) for l in range(0,count_all_abstracts): #print(l) if bool[l]==True: split=all_abstracts_lower[l].split() for word in split: if word in vocabulary: TFdict[i][word]=TFdict[i][word]+1 SCabstractsWordsNum[i]=SCabstractsWordsNum[i]+1 #print("TFdict after counting words in abstracts: ",TFdict) #print("SCabstractsWordsNum after counting words in abstracts: ",SCabstractsWordsNum) return SCabstractsWordsNum, TFdict def Pop0IDFDict(vocabulary): IDFdict=dict() for word in vocabulary: IDFdict[word]=0 print("done setting 0 values: ",time.time()) #print("IDFdict before population: ",IDFdict) return IDFdict def GetTFDictFinal(TFdict,SCabstractsWordsNum): for code in TFdict: for word in TFdict[code]: TFdict[code][word]=TFdict[code][word]/SCabstractsWordsNum[code] #print("TFdict final: ",TFdict) return TFdict def LogScaleIDFdict(IDFdict, all_abstracts_lower, count_all_abstracts, vocabulary): for word in vocabulary: for abstract in all_abstracts_lower: split=abstract.split() if word in split: IDFdict[word]=IDFdict[word]+1 IDFdict[word]=math.log(count_all_abstracts/IDFdict[word],10) #print("IDFdict after log-scaled inverse : ",IDFdict) return IDFdict def GetTFIDFdict(IDFdict, TFdict, screening_codes_key, vocabulary): TFIDFdict=dict() for code in screening_codes_key: TFIDFdict[code]={} #print("TFIDFdict unpopulated: ",TFIDFdict) ##for each screening code for each vocabulary word, multiply TF and IDF into TFIDFdict for code in TFIDFdict: for word in vocabulary: TFIDFdict[code][word]=TFdict[code][word]*IDFdict[word] #print("TFIDFdict populated: ",TFIDFdict) print("start sorting keyword by value and printing: ",time.time()) return TFIDFdict
[ "noreply@github.com" ]
noreply@github.com
8870db0404c7f85534265c7cf642790aa62039d2
c006f2d7f523bdc9407dd9d203b1967ba8bb0bfd
/State_wise_data_csv.py
fd6b762e250e0d3d9e7c53872160c6b3594ee972
[]
no_license
sagarRawatUK/coronaUpdate-Python-Deprecated
ccaf737bfbfa6a6407558e6208bd6d130a5c016e
dbd06c8b12046354ce16596bc77bdc6ab9553201
refs/heads/master
2023-01-31T08:45:01.058110
2020-12-18T13:12:21
2020-12-18T13:12:21
273,838,666
0
0
null
null
null
null
UTF-8
Python
false
false
1,157
py
import requests; import csv; from bs4 import BeautifulSoup; fields = ['Sr.no.','State', 'Total Cases', 'Cured ','Deaths','COnfirmed Cases']; filename = "State_corona_update.csv"; def get_html_data(url): data = requests.get(url); return data; def get_corona_detail(): details = []; url = "https://www.mohfw.gov.in/"; try: html_data = get_html_data(url); except Exception as e: print("Failed to connect to Internet"); exit(); soup = BeautifulSoup(html_data.text,"html.parser"); container = soup.find("table",class_="table").find("tbody").findAll("td"); with open(filename,'a') as csvfile: csvwriter = csv.writer(csvfile); csvwriter.writerow(fields); for i in range(0,6*32,6): num = container[0+i]; state = container[1+i]; total = container[2+i]; cured = container[3+i]; deaths = container[4+i]; confirm = container[5+i]; rows = [num.text,state.text,total.text,cured.text,deaths.text,confirm.text]; csvwriter.writerows([rows]); def main(): get_corona_detail(); main();
[ "sagarrawatuk@gmail.com" ]
sagarrawatuk@gmail.com
3a31fa232550234e8b13ac86c47c014b0d9286a5
41b4e362819e38239afa1cd79692e587c351bd6e
/gym_qiskit-game/envs/qiskit-game_env.py
d33842d336d2955a5675f2518a6b599f407f7bfd
[ "MIT" ]
permissive
PabloAMC/gym-qiskit-game
4e52e4066aa353b3717a2502c20e9eff682da3be
e7723db11f4286a74814220aa9d5ade018f371aa
refs/heads/master
2020-09-05T04:14:56.432331
2019-12-04T17:20:38
2019-12-04T17:20:38
219,979,801
2
0
null
null
null
null
UTF-8
Python
false
false
2,745
py
import gym from qiskit import * %matplotlib inline from gym import error, spaces, utils . #Probably my own space from gym.utils import seeding import numpy as np import math from qiskit import( QuantumCircuit, execute, Aer) class QiskitGameEnv(gym.Env): ''' The game starts in state |+>|->|+>|->|+>|-> and the objective of each player is to measure as many 0 or 1 as possible ''' metadata = {'render.modes': ['human']} def __init__(self): self.max_turns = 10 self.qubits = 6 self.turn = True self.objective = 1 #Assume 1 means that we want to measure 1 self.adversary_objective = -self.objective self.gates = ['H','X','Z','CX',CZ','M'] ''' ACTIONS = { 'H': 000, 'M': 100, 'X': 200, 'Z': 300, 'CX': 400, 'CZ': 500, } ''' self.simulator = Aer.get_backend('qasm_simulator') self.circuit = QuantumCircuit(self.qubits,self.qubits) #self.qubit qubits and self.qubit bits to store the result self.viewer = None self.action_space = [self.gates, spaces.Discrete(self.qubits), spaces.Discrete(self.qubits)] #first we indicate the gate, then the first qubit to which it applies, and latter the second qubit it is applied to. self.seed() def step(self, action): self.step_count += 1 if action[0] not in self.gates: raise Exception('Not valid gate!') if action[0] = 'H': self.circuit.h(action[1]) #apply Hadamard to qubit action[1] elif action[0] = 'M': self.circuit.measure(action[1],action[1]) #measures qubit in action[1] and saves the result to bit action[1] elif action[0] = 'X': self.circuit.x(action[1]) #apply X to qubit action[1] elif action[0] = 'Z': self.circuit.z(action[1]) #apply Z to qubit action[1] elif action[0] = 'CX': self.circuit.cx(action[1],action[2]) #apply X to qubit action[1] elif action[0] = 'CZ': self.circuit.cz(action[1],action[2]) #apply Z to qubit action[1] def reset(self): self.ste_count = 0 self.circuit = QuantumCircuit(self.qubits,self.qubits) for qubit in self.qubits: if qubit % 2 == 1: self.circuit.x(qubit) #Apply X on the odd qubits self.circuit.h(qubit) #Apply H on all qubits return self.circuit # The initial state is |+>|->|+>|->|+>|-> def render(self, mode='human'): return self.circuit.draw() def close(self):
[ "noreply@github.com" ]
noreply@github.com
111acd50db497fe5df938c6ec57e4343c713232a
b31689675d059f216161d74cd83331b77b475384
/archive/day_13/databindingeditor.py
aed41fd25c8612433e5871ead9964603fff9b640
[ "MIT" ]
permissive
tazjel/MicroScada
0e513aa993f7c63d4211c1ab0e6c6ded70c8ca1f
c4022d22ba02d19a973b64aeef63a9508068269c
refs/heads/master
2021-01-21T18:05:57.622724
2014-05-15T21:04:17
2014-05-15T21:04:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,695
py
from kivy.uix.dropdown import DropDown from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.floatlayout import FloatLayout from kivy.uix.textinput import TextInput from datamgr import variables class DataBindingEditor(FloatLayout): def __init__(self, widget, **kwargs): super(DataBindingEditor, self).__init__(**kwargs) dropdown = DropDown() for variable in variables: # when adding widgets, we need to specify the height manually (disabling # the size_hint_y) so the dropdown can calculate the area it needs. btn = Button(text='%s' % variable, size_hint_y=None, height=40) # for each button, attach a callback that will call the select() method # on the dropdown. We'll pass the text of the button as the data of the # selection. btn.bind(on_release=lambda btn: dropdown.select(btn.text)) # then add the button inside the dropdown dropdown.add_widget(btn) # create a big main button mainbutton = Button(text=widget.variable.name, size_hint=(None, None), pos_hint={'center_x': 0.5, 'center_y': 0.5}) # show the dropdown menu when the main button is released # note: all the bind() calls pass the instance of the caller (here, the # mainbutton instance) as the first argument of the callback (here, # dropdown.open.). mainbutton.bind(on_release=dropdown.open) # one last thing, listen for the selection in the dropdown list and # assign the data to the button text. dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x)) dropdown.bind(on_select=lambda instance, x: widget.set_var(x)) self.add_widget(mainbutton)
[ "victor-rene.dev@outlook.com" ]
victor-rene.dev@outlook.com
5f66a0c463969362e29987067f027b785455f16f
6ef428137a089bade01b8f0397f3ab01f2204cab
/Python_basics/31-40/36.py
400c357e209ce127b4acf96790f7fa33b5aba855
[]
no_license
epangar/python-w3.exercises
0db4415b916c41489e6d56b057a12cb54de8e2f1
479c27f39aa0df0a9df7d4a92c66f6d6e7c535fb
refs/heads/master
2023-01-24T10:14:59.654738
2020-12-08T23:37:48
2020-12-08T23:37:48
272,045,785
0
0
null
null
null
null
UTF-8
Python
false
false
176
py
""" 36. Write a Python program to add two objects if both objects are an integer type. """ def sum(a, b): if isinstance(a, int) and isinstance(b, int): return a + b
[ "e.pan.gar@gmail.com" ]
e.pan.gar@gmail.com
5f52fdc03f0db7fb339060a70be115388bb1d11a
ed2d96ead522dd4dbd1dfdf4a6a776617f7dbcaf
/tutorial/settings.py
2ab243e3f117195473def28fa8017680ee721604
[]
no_license
Alexmhack/django_rest_quickstart
ff83f435b09f6e279d17c87ea53ad5719276d1f9
b44be0cb8fd07d00ac8715934b1fe480e833e344
refs/heads/master
2020-04-01T06:45:04.591779
2018-10-14T12:22:00
2018-10-14T12:22:00
152,962,441
1
0
null
null
null
null
UTF-8
Python
false
false
3,417
py
""" Django settings for tutorial project. Generated by 'django-admin startproject' using Django 2.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config("PROJECT_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # django app 'quickstart', # dependencies 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'tutorial.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'tutorial.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # REST FRAMEWORK REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = False # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/'
[ "alexmohack@gmail.com" ]
alexmohack@gmail.com
34b3c726d80e09b43b8cb2178f207b8d3560ac42
e9685436ce494cf80fca4d1fd0cb7bc5185c8b30
/evolution_analysis/code/HGT_analysis/HGT_from_non_fungi/code/s5_alien_index.py
f49c42f6e15c0eef2e7045a801684c3df38d84d5
[ "MIT" ]
permissive
BoWangXJTU/Multi_scale_evolution
335573bfb09ef69ff70250f2371ac27be731acf6
b5f28ead733872519bc0758df034a076224c4253
refs/heads/master
2023-03-10T10:51:30.812635
2021-02-28T12:56:46
2021-02-28T12:56:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
503
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Step3: calculating the alien index score to predict HGT events. import math e_minus = 1e-200 alienindex_min = math.log(7e-48+e_minus, math.e)-math.log(4e-95+e_minus, math.e) alienindex_max = math.log(1+e_minus, math.e)-math.log(0+e_minus, math.e) alienindex2 = math.log(1e-10000+e_minus, 10) - math.log(1+e_minus, 10) minus = math.log(e_minus, 10) print(alienindex_min) print(alienindex_max) # Results: # -460.51701859880916 # 460.51701859880916
[ "55198637+le-yuan@users.noreply.github.com" ]
55198637+le-yuan@users.noreply.github.com
ac33b3bfb3be04e7d29210ae214a11952f05eb26
54852674f052f0cb8347ea9b67fd6d33d53cc367
/mmdet/models/dense_heads/atss_rank_head.py
7c84b466f1ff8482a3439b015031fb3746f12cf7
[ "Apache-2.0" ]
permissive
ap-cv-research/mmdetection
8c62888960ad8fff49eccc2783467a00fae83c62
6116474edce9efdb32987ebcd8003f9ce2b47b24
refs/heads/master
2023-02-22T16:57:40.102771
2021-01-25T19:40:41
2021-01-25T19:40:41
324,004,383
0
0
Apache-2.0
2021-01-25T19:40:42
2020-12-23T21:23:54
Python
UTF-8
Python
false
false
12,317
py
from mmcv.runner import force_fp32 from mmdet.core import (multi_apply, reduce_mean, build_assigner, build_sampler) import torch from .atss_head import ATSSHead from ..builder import HEADS, build_loss EPS = 1e-12 @HEADS.register_module() class ATSSRankHead(ATSSHead): _n_anchors: int def __init__(self, num_classes, in_channels, stacked_convs=4, conv_cfg=None, norm_cfg=dict(type='GN', num_groups=32, requires_grad=True), loss_centerness=dict(type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_rank=dict(type='RankingLoss', strategy='all', metric='cosine'), n_anchors=256, **kwargs): self.stacked_convs = stacked_convs self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self._n_anchors = n_anchors super(ATSSRankHead, self).__init__(num_classes, in_channels, **kwargs) self.sampling = False if self.train_cfg: self.assigner = build_assigner(self.train_cfg.assigner) # SSD sampling=False so use PseudoSampler sampler_cfg = dict(type='PseudoSampler') self.sampler = build_sampler(sampler_cfg, context=self) self.loss_centerness = build_loss(loss_centerness) self.loss_rank = build_loss(loss_rank) def loss_single(self, anchors, cls_score, bbox_pred, centerness, latent_vectors, labels, label_weights, bbox_targets, num_total_samples): """Compute loss of a single scale level. Args: cls_score (Tensor): Box scores for each scale level Has shape (N, num_anchors * num_classes, H, W). bbox_pred (Tensor): Box energies / deltas for each scale level with shape (N, num_anchors * 4, H, W). anchors (Tensor): Box reference for each scale level with shape (N, num_total_anchors, 4). latent_vectors (Tensor): Latent vectors for each scale level with shape (N, C, H, W) labels (Tensor): Labels of each anchors with shape (N, num_total_anchors). label_weights (Tensor): Label weights of each anchor with shape (N, num_total_anchors) bbox_targets (Tensor): BBox regression targets of each anchor wight shape (N, num_total_anchors, 4). num_total_samples (int): Number os positive samples that is reduced over all GPUs. Returns: dict[str, Tensor]: A dictionary of loss components. """ anchors = anchors.reshape(-1, 4) cls_score = cls_score.permute(0, 2, 3, 1).reshape( -1, self.cls_out_channels).contiguous() bbox_pred = bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4) centerness = centerness.permute(0, 2, 3, 1).reshape(-1) bbox_targets = bbox_targets.reshape(-1, 4) labels = labels.reshape(-1) label_weights = label_weights.reshape(-1) n_latent_feat = latent_vectors.shape[1] latent_vectors = latent_vectors.permute(0, 2, 3, 1).reshape(-1, n_latent_feat) # classification loss loss_cls = self.loss_cls( cls_score, labels, label_weights, avg_factor=num_total_samples ) # Rank Loss calculation is very space intensive. # Therefore, it is important to minimize the number of anchors used. # Set the number of anchors at double of num_total_samples to account for background if len(centerness)>self._n_anchors: _, topk_idx = centerness.topk(self._n_anchors) _latent_vectors, _labels, _label_weights = latent_vectors[topk_idx], labels[topk_idx], label_weights[topk_idx] else: _latent_vectors, _labels, _label_weights = latent_vectors, labels, label_weights loss_rank = self.loss_rank(_latent_vectors, _labels, _label_weights, avg_factor=num_total_samples) # FG cat_id: [0, num_classes -1], BG cat_id: num_classes bg_class_ind = self.num_classes pos_inds = ((labels >= 0) & (labels < bg_class_ind)).nonzero().squeeze(1) if len(pos_inds) > 0: pos_bbox_targets = bbox_targets[pos_inds] pos_bbox_pred = bbox_pred[pos_inds] pos_anchors = anchors[pos_inds] pos_centerness = centerness[pos_inds] centerness_targets = self.centerness_target( pos_anchors, pos_bbox_targets) pos_decode_bbox_pred = self.bbox_coder.decode( pos_anchors, pos_bbox_pred) pos_decode_bbox_targets = self.bbox_coder.decode( pos_anchors, pos_bbox_targets) # regression loss loss_bbox = self.loss_bbox( pos_decode_bbox_pred, pos_decode_bbox_targets, weight=centerness_targets, avg_factor=1.0) # centerness loss loss_centerness = self.loss_centerness( pos_centerness, centerness_targets, avg_factor=num_total_samples) else: loss_bbox = bbox_pred.sum() * 0 loss_centerness = centerness.sum() * 0 centerness_targets = bbox_targets.new_tensor(0.) return loss_cls, loss_bbox, loss_centerness, centerness_targets.sum(), loss_rank @force_fp32(apply_to=('cls_scores', 'bbox_preds', 'centernesses')) def loss(self, cls_scores, bbox_preds, centernesses, latent_vectors, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore=None): """Compute losses of the head. Args: cls_scores (list[Tensor]): Box scores for each scale level Has shape (N, num_anchors * num_classes, H, W) bbox_preds (list[Tensor]): Box energies / deltas for each scale level with shape (N, num_anchors * 4, H, W) centernesses (list[Tensor]): Centerness for each scale level with shape (N, num_anchors * 1, H, W) latent_vectors (list[Tensor]): Latent vectors for each scale level with shape (N, C, H, W) gt_bboxes (list[Tensor]): Ground truth bboxes for each image with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format. gt_labels (list[Tensor]): class indices corresponding to each box img_metas (list[dict]): Meta information of each image, e.g., image size, scaling factor, etc. gt_bboxes_ignore (list[Tensor] | None): specify which bounding boxes can be ignored when computing the loss. Returns: dict[str, Tensor]: A dictionary of loss components. """ featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores] assert len(featmap_sizes) == self.anchor_generator.num_levels device = cls_scores[0].device anchor_list, valid_flag_list = self.get_anchors( featmap_sizes, img_metas, device=device) label_channels = self.cls_out_channels if self.use_sigmoid_cls else 1 cls_reg_targets = self.get_targets( anchor_list, valid_flag_list, gt_bboxes, img_metas, gt_bboxes_ignore_list=gt_bboxes_ignore, gt_labels_list=gt_labels, label_channels=label_channels) if cls_reg_targets is None: return None (anchor_list, labels_list, label_weights_list, bbox_targets_list, bbox_weights_list, num_total_pos, num_total_neg) = cls_reg_targets num_total_samples = reduce_mean( torch.tensor(num_total_pos).cuda()).item() num_total_samples = max(num_total_samples, 1.0) losses_cls, losses_bbox, loss_centerness,\ bbox_avg_factor, losses_rank = multi_apply( self.loss_single, anchor_list, cls_scores, bbox_preds, centernesses, latent_vectors, labels_list, label_weights_list, bbox_targets_list, num_total_samples=num_total_samples) bbox_avg_factor = sum(bbox_avg_factor) bbox_avg_factor = reduce_mean(bbox_avg_factor).item() if bbox_avg_factor < EPS: bbox_avg_factor = 1 losses_bbox = list(map(lambda x: x / bbox_avg_factor, losses_bbox)) return dict( loss_cls=losses_cls, loss_bbox=losses_bbox, loss_centerness=loss_centerness, loss_rank=losses_rank) @force_fp32(apply_to=('cls_scores', 'bbox_preds', 'centernesses')) def get_bboxes(self, cls_scores, bbox_preds, centernesses, latent_vectors, img_metas, cfg=None, rescale=False, with_nms=True): """Transform network output for a batch into bbox predictions. Args: cls_scores (list[Tensor]): Box scores for each scale level with shape (N, num_anchors * num_classes, H, W). bbox_preds (list[Tensor]): Box energies / deltas for each scale level with shape (N, num_anchors * 4, H, W). centernesses (list[Tensor]): Centerness for each scale level with shape (N, num_anchors * 1, H, W). latent_vectors (list[Tensor]): Latent vectors for each scale level with shape (N, C, H, W) img_metas (list[dict]): Meta information of each image, e.g., image size, scaling factor, etc. cfg (mmcv.Config | None): Test / postprocessing configuration, if None, test_cfg would be used. Default: None. rescale (bool): If True, return boxes in original image space. Default: False. with_nms (bool): If True, do nms before return boxes. Default: True. Returns: list[tuple[Tensor, Tensor]]: Each item in result_list is 2-tuple. The first item is an (n, 5) tensor, where the first 4 columns are bounding box positions (tl_x, tl_y, br_x, br_y) and the 5-th column is a score between 0 and 1. The second item is a (n,) tensor where each item is the predicted class label of the corresponding box. """ return super(ATSSRankHead, self).get_bboxes( cls_scores, bbox_preds, centernesses, img_metas, cfg=cfg, rescale=rescale, with_nms=with_nms ) def forward_single(self, x, scale): """Forward feature of a single scale level. Args: x (Tensor): Features of a single scale level. scale (:obj: `mmcv.cnn.Scale`): Learnable scale module to resize the bbox prediction. Returns: tuple: cls_score (Tensor): Cls scores for a single scale level the channels number is num_anchors * num_classes. bbox_pred (Tensor): Box energies / deltas for a single scale level, the channels number is num_anchors * 4. centerness (Tensor): Centerness for a single scale level, the channel number is (N, num_anchors * 1, H, W). features (Tensor): Latent features for a single scale level, the channel number is (N, num_anchors * 1, H, W). """ cls_feat = x reg_feat = x for cls_conv in self.cls_convs: cls_feat = cls_conv(cls_feat) for reg_conv in self.reg_convs: reg_feat = reg_conv(reg_feat) cls_score = self.atss_cls(cls_feat) # we just follow atss, not apply exp in bbox_pred bbox_pred = scale(self.atss_reg(reg_feat)).float() centerness = self.atss_centerness(reg_feat) return cls_score, bbox_pred, centerness, x
[ "aponamarev@artisight.com" ]
aponamarev@artisight.com
36d27674e1d2c014c27a9c2cc9a551fe8e52cd19
e336f863debdc81e6fd9a847790f292c54ee8370
/code/remote_pkg/scripts/listener.py
e1993d2569ec58829cba8ce2198ffc77bbba2fe8
[]
no_license
xdnian/Self-positioning-Remote-Control-Car
f81e0342f361219d41186212a854e531aed2b0a9
1e05d9b6bbc1b6fbe359a908e06620b799462b9f
refs/heads/master
2020-04-06T10:35:57.282121
2018-11-13T13:47:02
2018-11-13T13:47:02
157,385,324
0
0
null
null
null
null
UTF-8
Python
false
false
2,405
py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ ## Simple talker demo that listens to std_msgs/Strings published ## to the 'chatter' topic import rospy from std_msgs.msg import String def callback(data): rospy.loginfo(rospy.get_caller_id() + 'I heard %s', data.data) def listener(): # In ROS, nodes are uniquely named. If two nodes with the same # name are launched, the previous one is kicked off. The # anonymous=True flag means that rospy will choose a unique # name for our 'listener' node so that multiple listeners can # run simultaneously. rospy.init_node('listener', anonymous=True) rospy.Subscriber('remote', String, callback) # spin() simply keeps python from exiting until this node is stopped rospy.spin() if __name__ == '__main__': listener()
[ "xiaodong0601@qq.com" ]
xiaodong0601@qq.com
1d803ef9b328061175dc929664d4498660153ef4
ac2f43c8e0d9649a7f063c59b3dffdfed9fd7ed7
/tools/verified-boot/signing/gen-op-cert.py
44f970940d9dbbd127253a9616fb4ac0335aa2bd
[]
no_license
facebook/openbmc
bef10604ced226288600f55248b7f1be9945aea4
32777c66a8410d767eae15baabf71c61a0bef13c
refs/heads/helium
2023-08-17T03:13:54.729494
2023-08-16T23:24:18
2023-08-16T23:24:18
31,917,712
684
331
null
2023-07-25T21:19:08
2015-03-09T19:18:35
C
UTF-8
Python
false
false
8,662
py
#!/usr/bin/env python3 # Copyright (c) 2023-present, META, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. import argparse import io import mmap import os import shutil import subprocess import sys import tempfile import time import traceback from typing import Optional from image_meta import FBOBMCImageMeta from measure_func import get_uboot_hash_algo_and_size from pyfdt import pyfdt from sh import cpp, dtc GEN_OP_CERT_VERSION = 1 EC_SUCCESS = 0 EC_EXCEPT = 255 OP_CERT_DTS = """ /dts-v1/; #define OP_CERT_DTS #include "op-cert-binding.h" / {{ timestamp = <{gen_time}>; no-fallback; PROP_CERT_VER = <{cert_ver}>; PROP_GIU_MODE = <{giu_mode}>; PROP_UBOOT_HASH = [{uboot_hash}]; PROP_UBOOT_HASH_LEN = <{uboot_hash_len}>; }}; """ def save_tmp_src_file(fn_tmp: str, mid_ext: str) -> None: if not args.debug: return dst_dir = os.path.dirname(args.output) dst_base_name = os.path.basename(args.output).split(".")[0] dst = os.path.join(dst_dir, f"{dst_base_name}.{mid_ext}.tmp") shutil.copy2(fn_tmp, dst) def extract_uboot_hash(fn_img: str) -> bytearray: image_meta = FBOBMCImageMeta(fn_img) fit = image_meta.get_part_info("u-boot-fit") uboot_hash, uboot_hash_algo, _ = get_uboot_hash_algo_and_size( image_meta.image, fit["offset"], 0x4000 ) return bytearray(uboot_hash) def create_cert_dtb(fn_img: str, giu_mode: str, injerr: Optional[str] = None) -> str: uboot_hash = extract_uboot_hash(fn_img) if injerr == "hash": uboot_hash[0] ^= 1 with tempfile.NamedTemporaryFile() as tmp_cert_dts_raw, \ tempfile.NamedTemporaryFile() as tmp_cert_dts, \ tempfile.NamedTemporaryFile(delete=False) as tmp_cert_dtb: # fmt:skip cert_dts = OP_CERT_DTS.format( gen_time=hex(int(time.time())), cert_ver=( "VBOOT_OP_CERT_VER" if injerr != "ver" else "VBOOT_OP_CERT_UNSUPPORT_VER" ), giu_mode=(giu_mode if injerr != "mode" else 0xEE), uboot_hash=bytes(uboot_hash).hex(), uboot_hash_len=len(uboot_hash), ) tmp_cert_dts_raw.write(cert_dts.encode("utf-8")) tmp_cert_dts_raw.flush() save_tmp_src_file(tmp_cert_dts_raw.name, "raw") cpp( "-nostdinc", "-undef", "-x", "assembler-with-cpp", "-I", os.path.dirname(os.path.realpath(__file__)), tmp_cert_dts_raw.name, tmp_cert_dts.name, ) save_tmp_src_file(tmp_cert_dts.name, "cpp") dtc( "-I", "dts", "-O", "dtb", "-o", tmp_cert_dtb.name, tmp_cert_dts.name, ) return tmp_cert_dtb.name OP_CERT_ITS = """ /dts-v1/; / {{ description = "vboot op-cert file"; images {{ fdt@1 {{ description = "vboot operation certificate"; data = /incbin/("{cert_dtb}"); hash@1 {{ algo = "{hash_algo}"; }}; signature@1 {{ algo = "sha256,rsa4096"; key-name-hint = "{key_name}"; }}; }}; }}; configurations {{ default = "conf@1"; conf@1 {{ firmware = "fdt@1"; }}; }}; }}; """ CERT_SIGN_PATH = "/images/fdt@1/signature@1/value" def create_cert_itb( mkimage: str, hsmkey: Optional[str], keyfile: Optional[str], hash_algo: str, tmp_cert_dtb_name: str, fn_cert: str, ) -> None: if hsmkey: requested_key_name = os.path.basename(hsmkey) keydir = os.path.dirname(hsmkey) else: keybase, keyext = os.path.splitext(keyfile) if keyext != ".key": raise ValueError(f"private key file {keyfile} must be .key ext") requested_key_name = os.path.basename(keybase) keydir = os.path.dirname(os.path.abspath(keyfile)) with tempfile.NamedTemporaryFile() as tmp_cert_its: cert_its = OP_CERT_ITS.format( cert_dtb=tmp_cert_dtb_name, hash_algo=hash_algo, key_name=requested_key_name, ) print(cert_its) tmp_cert_its.write(cert_its.encode("utf-8")) tmp_cert_its.flush() save_tmp_src_file(tmp_cert_its.name, "its") cmd = [ mkimage, "-f", tmp_cert_its.name, "-k", keydir, "-r", fn_cert, ] if hsmkey: cmd += ["-N", "FB-HSM"] print(" ".join(cmd)) subprocess.run(cmd, check=True) def decompile_dtb_file(fn_dtb: str, fn_src: str) -> None: dtc("-I", "dtb", "-O", "dts", "-o", fn_src, fn_dtb) def get_cert_sign(fn_cert: str) -> bytes: with open(fn_cert, "rb") as fh: cert_io = io.BytesIO(fh.read()) cert_fdt = pyfdt.FdtBlobParse(cert_io).to_fdt() return cert_fdt.resolve_path(CERT_SIGN_PATH).to_raw() class CertSignatureNotFind(Exception): pass def flip_bit_of_sign(fn_cert: str) -> None: cert_sig = get_cert_sign(fn_cert) with open(fn_cert, "r+b") as fh: with mmap.mmap(fh.fileno(), 0) as mm: sig_idx = mm.find(cert_sig) if sig_idx < 0: raise CertSignatureNotFind mm[sig_idx] ^= 1 mm.flush() def main(args: argparse.Namespace) -> int: # Create the certificate data from OP_CERT_DTS tmp_cert_dtb_name = None try: tmp_cert_dtb_name = create_cert_dtb(args.image, args.giu_mode, args.injerr) create_cert_itb( args.mkimage, args.hsmkey, args.keyfile, args.hash_algo, tmp_cert_dtb_name, args.output, ) dump_dir = os.path.dirname(args.output) dump_base_name = os.path.basename(args.output).split(".")[0] dump_base_path = os.path.join(dump_dir, dump_base_name) if args.injerr == "sig": if args.debug: shutil.copy2(args.output, f"{dump_base_path}.orig.itb") decompile_dtb_file(args.output, f"{dump_base_path}.orig.its") flip_bit_of_sign(args.output) if args.debug: decompile_dtb_file(tmp_cert_dtb_name, f"{dump_base_path}.dts") decompile_dtb_file(args.output, f"{dump_base_path}.its") finally: if tmp_cert_dtb_name: os.unlink(tmp_cert_dtb_name) return EC_SUCCESS if __name__ == "__main__": parser = argparse.ArgumentParser( description="Generate a vboot operation certificate file." ) parser.add_argument( "--version", action="version", version="%(prog)s-v{}".format(GEN_OP_CERT_VERSION), ) parser.add_argument( "--mkimage", required=True, metavar="MKIMAGE", help="Required path to mkimage, use openbmc built mkimage for HSM sign", ) parser.add_argument( "-i", "--image", required=True, help="Required openbmc image the certifate bound to", ) parser.add_argument( "output", metavar="CERT_FILE", help="Output path of signed certificate file", ) parser.add_argument( "-m", "--giu-mode", default="GIU_CERT", choices=["GIU_NONE", "GIU_CERT", "GIU_OPEN"], help="Golden image mode", ) parser.add_argument( "--hash-algo", default="sha256", help="Specify hashing algorithm, default(sha256)", ) parser.add_argument( "-d", "--debug", action="store_true", help="save dts and its in same dir of output cert with same basename", ) parser.add_argument( "--injerr", choices=["sig", "mode", "ver", "hash"], help="generate bad certificate with errors for testing", ) pkey = parser.add_mutually_exclusive_group(required=True) pkey.add_argument( "--keyfile", help="certificate signing private key file must with .key ext", ) pkey.add_argument( "--hsmkey", help="Use HSM based key to sign", ) args = parser.parse_args() # sanity check and normalize the input keydir try: sys.exit(main(args)) except Exception as e: print("Exception: %s" % (str(e))) traceback.print_exc() sys.exit(EC_EXCEPT)
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
2adb5dfa09418d7c569c7c8a6bebcfa114e65261
4652840c8fa0d701aaca8de426bf64c340a5e831
/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py
3649c2d42293998faef2f42ce2b30daf3f057f7c
[ "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft" ]
permissive
remzert/BraveBrowser
de5ab71293832a5396fa3e35690ebd37e8bb3113
aef440e3d759cb825815ae12bd42f33d71227865
refs/heads/master
2022-11-07T03:06:32.579337
2017-02-28T23:02:29
2017-02-28T23:02:29
84,563,445
1
5
BSD-3-Clause
2022-10-26T06:28:58
2017-03-10T13:38:48
null
UTF-8
Python
false
false
20,758
py
# Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials # provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. """This script imports a directory of W3C tests into Blink. This script takes a source repository directory, which it searches for files, then converts and copies files over to a destination directory. Rules for importing: * By default, only reference tests and JS tests are imported, (because pixel tests take longer to run). This can be overridden with the --all flag. * By default, if test files by the same name already exist in the destination directory, they are overwritten. This is because this script is used to refresh files periodically. This can be overridden with the --no-overwrite flag. * All files are converted to work in Blink: 1. All CSS properties requiring the -webkit- vendor prefix are prefixed (the list of what needs prefixes is read from Source/core/css/CSSProperties.in). 2. Each reftest has its own copy of its reference file following the naming conventions new-run-webkit-tests expects. 3. If a reference files lives outside the directory of the test that uses it, it is checked for paths to support files as it will be imported into a different relative position to the test file (in the same directory). 4. Any tags with the class "instructions" have style="display:none" added to them. Some w3c tests contain instructions to manual testers which we want to strip out (the test result parser only recognizes pure testharness.js output and not those instructions). * Upon completion, script outputs the total number tests imported, broken down by test type. * Also upon completion, if we are not importing the files in place, each directory where files are imported will have a w3c-import.log file written with a timestamp, the list of CSS properties used that require prefixes, the list of imported files, and guidance for future test modification and maintenance. On subsequent imports, this file is read to determine if files have been removed in the newer changesets. The script removes these files accordingly. """ import logging import mimetypes import optparse import os import sys from webkitpy.common.host import Host from webkitpy.common.webkit_finder import WebKitFinder from webkitpy.layout_tests.models.test_expectations import TestExpectationParser from webkitpy.w3c.test_parser import TestParser from webkitpy.w3c.test_converter import convert_for_webkit # Maximum length of import path starting from top of source repository. # This limit is here because the Windows builders cannot create paths that are # longer than the Windows max path length (260). See http://crbug.com/609871. MAX_PATH_LENGTH = 125 _log = logging.getLogger(__name__) def main(_argv, _stdout, _stderr): options, args = parse_args() host = Host() source_repo_path = host.filesystem.normpath(os.path.abspath(args[0])) if not host.filesystem.exists(source_repo_path): sys.exit('Repository directory %s not found!' % source_repo_path) configure_logging() test_importer = TestImporter(host, source_repo_path, options) test_importer.do_import() def configure_logging(): class LogHandler(logging.StreamHandler): def format(self, record): if record.levelno > logging.INFO: return "%s: %s" % (record.levelname, record.getMessage()) return record.getMessage() logger = logging.getLogger() logger.setLevel(logging.INFO) handler = LogHandler() handler.setLevel(logging.INFO) logger.addHandler(handler) return handler def parse_args(): parser = optparse.OptionParser(usage='usage: %prog [options] source_repo_path') parser.add_option('-n', '--no-overwrite', dest='overwrite', action='store_false', default=True, help=('Flag to prevent duplicate test files from overwriting existing tests. ' 'By default, they will be overwritten.')) parser.add_option('-a', '--all', action='store_true', default=False, help=('Import all tests including reftests, JS tests, and manual/pixel tests. ' 'By default, only reftests and JS tests are imported.')) parser.add_option('-d', '--dest-dir', dest='destination', default='w3c', help=('Import into a specified directory relative to the LayoutTests root. ' 'By default, files are imported under LayoutTests/w3c.')) parser.add_option('--ignore-expectations', action='store_true', default=False, help='Ignore the W3CImportExpectations file and import everything.') parser.add_option('--dry-run', action='store_true', default=False, help='Dryrun only (don\'t actually write any results).') options, args = parser.parse_args() if len(args) != 1: parser.error('Incorrect number of arguments; source repo path is required.') return options, args class TestImporter(object): def __init__(self, host, source_repo_path, options): self.host = host self.source_repo_path = source_repo_path self.options = options self.filesystem = self.host.filesystem self.webkit_finder = WebKitFinder(self.filesystem) self._webkit_root = self.webkit_finder.webkit_base() self.layout_tests_dir = self.webkit_finder.path_from_webkit_base('LayoutTests') self.destination_directory = self.filesystem.normpath( self.filesystem.join( self.layout_tests_dir, options.destination, self.filesystem.basename(self.source_repo_path))) self.import_in_place = (self.source_repo_path == self.destination_directory) self.dir_above_repo = self.filesystem.dirname(self.source_repo_path) self.import_list = [] def do_import(self): _log.info("Importing %s into %s", self.source_repo_path, self.destination_directory) self.find_importable_tests() self.import_tests() def find_importable_tests(self): """Walks through the source directory to find what tests should be imported. This function sets self.import_list, which contains information about how many tests are being imported, and their source and destination paths. """ paths_to_skip = self.find_paths_to_skip() for root, dirs, files in self.filesystem.walk(self.source_repo_path): cur_dir = root.replace(self.dir_above_repo + '/', '') + '/' _log.info(' scanning ' + cur_dir + '...') total_tests = 0 reftests = 0 jstests = 0 # Files in 'tools' are not for browser testing, so we skip them. # See: http://testthewebforward.org/docs/test-format-guidelines.html#tools DIRS_TO_SKIP = ('.git', 'test-plan', 'tools') # We copy all files in 'support', including HTML without metadata. # See: http://testthewebforward.org/docs/test-format-guidelines.html#support-files DIRS_TO_INCLUDE = ('resources', 'support') if dirs: for d in DIRS_TO_SKIP: if d in dirs: dirs.remove(d) for path in paths_to_skip: path_base = path.replace(self.options.destination + '/', '') path_base = path_base.replace(cur_dir, '') path_full = self.filesystem.join(root, path_base) if path_base in dirs: dirs.remove(path_base) if not self.options.dry_run and self.import_in_place: _log.info(" pruning %s", path_base) self.filesystem.rmtree(path_full) else: _log.info(" skipping %s", path_base) copy_list = [] for filename in files: path_full = self.filesystem.join(root, filename) path_base = path_full.replace(self.source_repo_path + '/', '') path_base = self.destination_directory.replace(self.layout_tests_dir + '/', '') + '/' + path_base if path_base in paths_to_skip: if not self.options.dry_run and self.import_in_place: _log.info(" pruning %s", path_base) self.filesystem.remove(path_full) continue else: continue # FIXME: This block should really be a separate function, but the early-continues make that difficult. if filename.startswith('.') or filename.endswith('.pl'): # The w3cs repos may contain perl scripts, which we don't care about. continue if filename == 'OWNERS' or filename == 'reftest.list': # These files fail our presubmits. # See http://crbug.com/584660 and http://crbug.com/582838. continue fullpath = self.filesystem.join(root, filename) mimetype = mimetypes.guess_type(fullpath) if ('html' not in str(mimetype[0]) and 'application/xhtml+xml' not in str(mimetype[0]) and 'application/xml' not in str(mimetype[0])): copy_list.append({'src': fullpath, 'dest': filename}) continue if self.filesystem.basename(root) in DIRS_TO_INCLUDE: copy_list.append({'src': fullpath, 'dest': filename}) continue test_parser = TestParser(fullpath, self.host) test_info = test_parser.analyze_test() if test_info is None: copy_list.append({'src': fullpath, 'dest': filename}) continue if self.path_too_long(path_full): _log.warning('%s skipped due to long path. ' 'Max length from repo base %d chars; see http://crbug.com/609871.', path_full, MAX_PATH_LENGTH) continue if 'reference' in test_info.keys(): test_basename = self.filesystem.basename(test_info['test']) # Add the ref file, following WebKit style. # FIXME: Ideally we'd support reading the metadata # directly rather than relying on a naming convention. # Using a naming convention creates duplicate copies of the # reference files (http://crrev.com/268729). ref_file = self.filesystem.splitext(test_basename)[0] + '-expected' # Make sure to use the extension from the *reference*, not # from the test, because at least flexbox tests use XHTML # references but HTML tests. ref_file += self.filesystem.splitext(test_info['reference'])[1] if not self.filesystem.exists(test_info['reference']): _log.warning('%s skipped because ref file %s was not found.', path_full, ref_file) continue if self.path_too_long(path_full.replace(filename, ref_file)): _log.warning('%s skipped because path of ref file %s would be too long. ' 'Max length from repo base %d chars; see http://crbug.com/609871.', path_full, ref_file, MAX_PATH_LENGTH) continue reftests += 1 total_tests += 1 copy_list.append({'src': test_info['reference'], 'dest': ref_file, 'reference_support_info': test_info['reference_support_info']}) copy_list.append({'src': test_info['test'], 'dest': filename}) elif 'jstest' in test_info.keys(): jstests += 1 total_tests += 1 copy_list.append({'src': fullpath, 'dest': filename, 'is_jstest': True}) elif self.options.all: total_tests += 1 copy_list.append({'src': fullpath, 'dest': filename}) if copy_list: # Only add this directory to the list if there's something to import self.import_list.append({'dirname': root, 'copy_list': copy_list, 'reftests': reftests, 'jstests': jstests, 'total_tests': total_tests}) def find_paths_to_skip(self): if self.options.ignore_expectations: return set() paths_to_skip = set() port = self.host.port_factory.get() w3c_import_expectations_path = self.webkit_finder.path_from_webkit_base('LayoutTests', 'W3CImportExpectations') w3c_import_expectations = self.filesystem.read_text_file(w3c_import_expectations_path) parser = TestExpectationParser(port, all_tests=(), is_lint_mode=False) expectation_lines = parser.parse(w3c_import_expectations_path, w3c_import_expectations) for line in expectation_lines: if 'SKIP' in line.expectations: if line.specifiers: _log.warning("W3CImportExpectations:%s should not have any specifiers", line.line_numbers) continue paths_to_skip.add(line.name) return paths_to_skip def import_tests(self): """Reads |self.import_list|, and converts and copies files to their destination.""" total_imported_tests = 0 total_imported_reftests = 0 total_imported_jstests = 0 total_prefixed_properties = {} for dir_to_copy in self.import_list: total_imported_tests += dir_to_copy['total_tests'] total_imported_reftests += dir_to_copy['reftests'] total_imported_jstests += dir_to_copy['jstests'] prefixed_properties = [] if not dir_to_copy['copy_list']: continue orig_path = dir_to_copy['dirname'] subpath = self.filesystem.relpath(orig_path, self.source_repo_path) new_path = self.filesystem.join(self.destination_directory, subpath) if not self.filesystem.exists(new_path): self.filesystem.maybe_make_directory(new_path) copied_files = [] for file_to_copy in dir_to_copy['copy_list']: # FIXME: Split this block into a separate function. orig_filepath = self.filesystem.normpath(file_to_copy['src']) if self.filesystem.isdir(orig_filepath): # FIXME: Figure out what is triggering this and what to do about it. _log.error('%s refers to a directory', orig_filepath) continue if not self.filesystem.exists(orig_filepath): _log.error('%s not found. Possible error in the test.', orig_filepath) continue new_filepath = self.filesystem.join(new_path, file_to_copy['dest']) if 'reference_support_info' in file_to_copy.keys() and file_to_copy['reference_support_info'] != {}: reference_support_info = file_to_copy['reference_support_info'] else: reference_support_info = None if not self.filesystem.exists(self.filesystem.dirname(new_filepath)): if not self.import_in_place and not self.options.dry_run: self.filesystem.maybe_make_directory(self.filesystem.dirname(new_filepath)) relpath = self.filesystem.relpath(new_filepath, self.layout_tests_dir) if not self.options.overwrite and self.filesystem.exists(new_filepath): _log.info(' skipping %s', relpath) else: # FIXME: Maybe doing a file diff is in order here for existing files? # In other words, there's no sense in overwriting identical files, but # there's no harm in copying the identical thing. _log.info(' %s', relpath) # Only HTML, XML, or CSS should be converted. # FIXME: Eventually, so should JS when support is added for this type of conversion. mimetype = mimetypes.guess_type(orig_filepath) if 'is_jstest' not in file_to_copy and ( 'html' in str(mimetype[0]) or 'xml' in str(mimetype[0]) or 'css' in str(mimetype[0])): converted_file = convert_for_webkit( new_path, filename=orig_filepath, reference_support_info=reference_support_info, host=self.host) if not converted_file: if not self.import_in_place and not self.options.dry_run: self.filesystem.copyfile(orig_filepath, new_filepath) # The file was unmodified. else: for prefixed_property in converted_file[0]: total_prefixed_properties.setdefault(prefixed_property, 0) total_prefixed_properties[prefixed_property] += 1 prefixed_properties.extend(set(converted_file[0]) - set(prefixed_properties)) if not self.options.dry_run: self.filesystem.write_text_file(new_filepath, converted_file[1]) else: if not self.import_in_place and not self.options.dry_run: self.filesystem.copyfile(orig_filepath, new_filepath) if self.filesystem.read_binary_file(orig_filepath)[:2] == '#!': self.filesystem.make_executable(new_filepath) copied_files.append(new_filepath.replace(self._webkit_root, '')) _log.info('') _log.info('Import complete') _log.info('') _log.info('IMPORTED %d TOTAL TESTS', total_imported_tests) _log.info('Imported %d reftests', total_imported_reftests) _log.info('Imported %d JS tests', total_imported_jstests) _log.info('Imported %d pixel/manual tests', total_imported_tests - total_imported_jstests - total_imported_reftests) _log.info('') if total_prefixed_properties: _log.info('Properties needing prefixes (by count):') for prefixed_property in sorted(total_prefixed_properties, key=lambda p: total_prefixed_properties[p]): _log.info(' %s: %s', prefixed_property, total_prefixed_properties[prefixed_property]) def path_too_long(self, source_path): """Checks whether a source path is too long to import. Args: Absolute path of file to be imported. Returns: True if the path is too long to import, False if it's OK. """ path_from_repo_base = os.path.relpath(source_path, self.source_repo_path) return len(path_from_repo_base) > MAX_PATH_LENGTH
[ "serg.zhukovsky@gmail.com" ]
serg.zhukovsky@gmail.com
70520ae32fa7fe2286ee988660ac8f214d4d19a0
0d65cd7eaaeacd8ccbb2f6cf4a451857387b5648
/app/config.py
7a1a3234dfd71fc42c42293a32efd59c2083fb18
[ "MIT" ]
permissive
Ndarko1/family_device_inventory
561827c78353ef285fdcff95e536077493bbb277
031caaef6ef5c44164de8dc7587f774beb4c2aff
refs/heads/main
2023-07-21T10:19:18.224726
2021-09-05T21:51:16
2021-09-05T21:51:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,205
py
""" This file holds configuration options. The Development config is default and spins up the application inside a Docker container. Production config allows the app to be run on Heroku. """ import os class Config: """ Base Configuration """ USER = os.environ.get('POSTGRES_USER') PASSWORD = os.environ.get('POSTGRES_PASSWORD') HOST = os.environ.get('POSTGRES_HOST') DATABASE = os.environ.get('POSTGRES_DB') PORT = os.environ.get('POSTGRES_PORT') SECRET_KEY = os.environ.get('SECRET_KEY') DATABASE_URL = f"postgres+psycopg2://{USER}:{PASSWORD}@{HOST}:{PORT}/{DATABASE}" SQLALCHEMY_TRACK_MODIFICATIONS = False class DevelopmentConfig(Config): """ Development Configuration - default config Requires the environment variable `FLASK_ENV=dev` """ SQLALCHEMY_DATABASE_URI = Config.DATABASE_URL DEBUG = True class ProductionConfig(Config): """ Production Configuration Requires the environment variable `FLASK_ENV=prod` """ SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL") DEBUG = False # map the value of `FLASK_ENV` to a configuration config = {"dev": DevelopmentConfig, "prod": ProductionConfig}
[ "fiifi.krampah@gmail.com" ]
fiifi.krampah@gmail.com
79bc5ae5c5a43defded6e9e852d8f2299777611c
ac4f675fbd6c98651707bac27db43dcf592564fc
/kalkulator.py
4c1774ad1408b82b6065d08e6215bea7ff5025de
[]
no_license
IzabelaR20/kalkulator_zaoczni2019
705e1aab51475c58cf464c5717760bb983adcda3
160e8dc434006050c9f6b5c86b54ed0e16a0d5ca
refs/heads/master
2020-05-30T12:03:17.562454
2019-06-05T17:48:17
2019-06-05T17:48:17
189,722,062
0
0
null
null
null
null
UTF-8
Python
false
false
1,171
py
#https://www.programiz.com/python-programming/examples/calculator?fbclid=IwAR0ezxxAzOk5aM1Q32dqj3QdPZtbP4-4D_ZaRAq05d_mgstDLCoE3NBZwZY # Program make a simple calculator that can add, subtract, multiply and divide using functions # This function adds two numbers def add(x, y): return x + y # This function subtracts two numbers def subtract(x, y): return x - y # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x / y def newfinction(x): return x / 100 def newfinction2(x): return x / 200 print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") # Take input from the user choice = input("Enter choice(1/2/3/4):") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print("Invalid input")
[ "email@gmail.com" ]
email@gmail.com
c422911d66d3c472a423daa9aae44836f52b2fba
7add1f8fc31b09bb79efd2b25cc15e23666c1d1d
/tfx/orchestration/portable/tfx_runner.py
c431cf3f36a66e468fcc48190bbaac4331fed4f7
[ "Apache-2.0" ]
permissive
twitter-forks/tfx
b867e9fee9533029ca799c4a4c5d1c5430ba05fe
cb3561224c54a5dad4d5679165d5b3bafc8b451b
refs/heads/master
2021-11-19T18:45:09.157744
2021-10-19T00:02:34
2021-10-19T00:02:34
205,426,993
2
1
Apache-2.0
2021-10-18T21:03:50
2019-08-30T17:21:03
Python
UTF-8
Python
false
false
1,333
py
# Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Definition of TFX runner base class.""" import abc from typing import Any, Optional, Union from tfx.orchestration import pipeline as pipeline_py from tfx.proto.orchestration import pipeline_pb2 class TfxRunner(metaclass=abc.ABCMeta): """Base runner class for TFX. This is the base class for every TFX runner. """ @abc.abstractmethod def run( self, pipeline: Union[pipeline_pb2.Pipeline, pipeline_py.Pipeline]) -> Optional[Any]: """Runs a TFX pipeline on a specific platform. Args: pipeline: a pipeline_pb2.Pipeline message or pipeline.Pipeline instance representing a pipeline definition. Returns: Optional platform-specific object. """ pass
[ "tensorflow-extended-nonhuman@googlegroups.com" ]
tensorflow-extended-nonhuman@googlegroups.com
70bc0f58d1a7260e8aa0c009c423467c33acd8a0
e6611443e946d1129985a95bc2dd2afc610f8292
/CMS/apps/task_status/migrations/0003_taskstatus_category.py
53b4aaa95708f0d4641fb077232356c169f2ceb3
[]
no_license
Indus-Action/Campaign-Management-System
a761dd9bbc7967f8302bb3283230f87ccc2bd2a6
9c6f1193ff897b8cc53f2a1c3bca8d70a890e70f
refs/heads/master
2020-03-12T19:49:19.329764
2018-05-15T06:37:41
2018-05-15T06:37:41
130,792,314
1
1
null
null
null
null
UTF-8
Python
false
false
694
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-09-28 06:19 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('task_status_categories', '0001_initial'), ('task_status', '0002_taskstatus_desc'), ] operations = [ migrations.AddField( model_name='taskstatus', name='category', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='task_status', to='task_status_categories.TaskStatusCategory', null=True), preserve_default=False, ), ]
[ "madhav.malhotra3089@gmail.com" ]
madhav.malhotra3089@gmail.com
bc63b92a278bd74e73e798b1ee3820187c9ed3e1
bedafa1ac84be4c2a31ac21d4e9f43cbf0e33c84
/WORK I/ex3 Variables.py
6fb17a838755b76280a22ee57583ecc575d9e623
[]
no_license
armsiwadol69/Python_ss2
abf9b9478fe7108b46e5cbef11fd5db28b239a68
563fa63f5506a9ad99274edfd4e1f8cef55d6051
refs/heads/master
2022-12-19T03:06:54.651746
2020-09-28T10:30:28
2020-09-28T10:30:28
281,633,024
0
0
null
null
null
null
UTF-8
Python
false
false
79
py
x = 100 y = str(112) z = "Gitano" print(type(x)) print(type(y)) print(type(z))
[ "armsiwadol2543@gmail.com" ]
armsiwadol2543@gmail.com
5a258fdbb9f2361d11447550c4970b8641a49990
a9adcb5efb4492094ecd9e45741b409afca56f53
/democratizing_weather_data/streaming/sample_code/seatgeek_query.py
9887303e6f4c8842dde2e27ce4c4ffdc162341c4
[]
no_license
LeoSalemann/democratizing_weather_data
0792a4419a67799f8f5b60585a6ec32aab72c4c6
55d84e8bc3748b0df166d5f2c999bd7906cff1f5
refs/heads/master
2021-05-05T10:03:39.234295
2017-09-19T01:58:41
2017-09-19T01:58:41
104,013,673
0
0
null
2017-09-19T02:05:05
2017-09-19T02:05:05
null
UTF-8
Python
false
false
931
py
import os # can probably ignore/comment this out. import datetime # can probably ignore/comment this out. import json import urllib import pandas as pd from pandas.io.json import json_normalize def seatgeek_query(key, secret, argument_dict={}): argument_dict.update({'client_id': key, 'client_secret': secret}) query = urllib.urlencode(argument_dict) endpoint = 'http://api.seatgeek.com/2/events?' url = endpoint+query url_object = urllib.urlopen(url) sg = {'defaultKey': 'defaultValue'} try: sg = json.load(url_object) except ValueError: print 'Invalid url_object returned for url:' + url return sg #key = 'your key here' #secret = 'your secret here' sg = seatgeek_query(key, secret, {'postal_code': 98122, 'per_page': 100}) if 'events' in sg.keys(): sg_df = json_normalize(sg['events']) sg_df.to_csv('seatgeek_query.csv', sep=',')
[ "leo.salemann@me.com" ]
leo.salemann@me.com
829abf4b2c1d0666fc4e2e737564e685026f32d5
52d734065cc158d45989077217e918d5515fecb6
/hyperglass_bird/configuration.py
d7687b7fcd6fa757f61c61605eb4884e8d55dc3f
[ "BSD-3-Clause-Clear" ]
permissive
thatmattlove/hyperglass-bird
1d2281c1e999fcb67b415f148b7328190d73942a
21c6ea911c475eb3d2bf985d6466939c5beb67e3
refs/heads/master
2022-11-16T05:38:36.037403
2020-07-06T17:07:13
2020-07-06T17:07:13
193,296,332
1
0
null
null
null
null
UTF-8
Python
false
false
5,895
py
""" Exports constructed commands and API variables from configuration file based \ on input query """ # Standard Imports import os import re import logging # Module Imports import toml import logzero from logzero import logger # Project Directories this_directory = os.path.dirname(os.path.abspath(__file__)) # TOML Imports conf = toml.load(os.path.join(this_directory, "configuration.toml")) def debug_state(): """Returns string for logzero log level""" state = conf.get("debug", False) return state # Logzero Configuration if debug_state(): logzero.loglevel(logging.DEBUG) else: logzero.loglevel(logging.INFO) def api(): """Imports & exports configured API parameters from configuration file""" api_dict = { "listen_addr": conf["api"].get("listen_addr", "*"), "port": conf["api"].get("port", 8080), "key": conf["api"].get("key", 0), } return api_dict def bird_version(): """Get BIRD version from command line, convert version to float for comparision""" import subprocess from math import fsum # Get BIRD version, convert output to UTF-8 string ver_string = str( subprocess.check_output(["bird", "--version"], stderr=subprocess.STDOUT), "utf8" ) # Extract numbers from string as list of numbers verlist_string = re.findall(r"\d+", ver_string) # Convert last 2 numbers in list to decimals verlist_string_dec = [ verlist_string[0], "." + verlist_string[1], "." + verlist_string[2], ] # Convert number strings to floats, add together to produce whole number as version number version_sum = fsum([float(number) for number in verlist_string_dec]) return version_sum class BirdConvert: """Converts traditional/standard commands to BIRD formatted commands""" def __init__(self, target): self.target = target def bgp_aspath(self): """Takes traditional AS_PATH regexp pattern and converts it to an accpetable birdc format""" _open = r"[= " _close = r" =]" # Strip out regex characters stripped = re.sub(r"[\^\$\(\)\.\+]", "", self.target) # Replace regex _ with wildcard * replaced = re.sub(r"\_", r"*", stripped) # Remove extra * as they are not needed with wildcards replaced_dedup = re.sub(r"\*+", r"*", replaced) # Pad ASNs & wildcard operators with whitespaces for sub in ((r"(\d+)", r" \1 "), (r"(\*)", r" \1 ")): subbed = re.sub(*sub, replaced_dedup) # Construct bgp_path pattern for birdc pattern = f"{_open}{subbed}{_close}" # Remove extra whitespaces from constructed pattern pattern_dedup = re.sub(r"\s+", " ", pattern) return pattern_dedup def bgp_community(self): """Takes traditional BGP Community format and converts it to an acceptable birdc format""" # Replace : with , subbed = re.sub(r"\:", r",", self.target) # Wrap in parentheses pattern = f"({subbed})" return pattern class Command: """Imports & exports configured command syntax from configuration file""" def __init__(self, query): self.query_type = query.get("query_type") self.afi = query.get("afi") self.source = query.get("source") self.target = query.get("target", 0) logger.debug( f"""Command class initialized with paramaters:\nQuery Type: {self.query_type}\nAFI: \ {self.afi}\nSource: {self.source}\nTarget: {self.target}""" ) def is_split(self): """Returns bash command as a list of arguments""" command_string = ( conf["commands"][self.afi] .get(self.query_type) .format(source=self.source, target=self.target) ) command_split = command_string.split(" ") logger.debug(f"Constructed bash command as list: {command_split}") return command_split def birdc(self): """Returns bash command as a list of arguments, with the birdc commands as separate list \ elements""" _bird_version = bird_version() birdc_pre = ["birdc", "-r"] birdc6_pre = ["birdc6", "-r"] to_run = None if _bird_version < 2 and self.afi == "dual": fmt_target = getattr(BirdConvert(self.target), self.query_type)() cmd4 = birdc_pre + [ conf["commands"][self.afi] .get(self.query_type) .format(target=fmt_target) ] cmd6 = birdc6_pre + [ conf["commands"][self.afi] .get(self.query_type) .format(target=fmt_target) ] to_run = (cmd4, cmd6) elif _bird_version >= 2 and self.afi == "dual": fmt_target = getattr(BirdConvert(self.target), self.query_type)() to_run = birdc_pre + [ conf["commands"][self.afi] .get(self.query_type) .format(target=fmt_target) ] elif _bird_version < 2 and self.afi == "ipv6": to_run = birdc6_pre + [ conf["commands"][self.afi] .get(self.query_type) .format(target=self.target) ] elif _bird_version >= 2 and self.afi == "ipv6": to_run = birdc_pre + [ conf["commands"][self.afi] .get(self.query_type) .format(target=self.target) ] elif self.afi == "ipv4": to_run = birdc_pre + [ conf["commands"][self.afi] .get(self.query_type) .format(target=self.target) ] logger.debug(f"Constructed Command: {to_run}") if not to_run: raise RuntimeError("Error constructing birdc commands") return to_run
[ "mtt.lov@gmail.com" ]
mtt.lov@gmail.com
fcdc3c6425304d12927eedb5366284da5f8f22cc
67b04bf2bdfdfc8de4189a52fe431aa482c375ac
/example/app.py
531fdcb75688c64a06ec95e82a0c65b0fe75b7d9
[ "MIT" ]
permissive
d0ugal/aioauth-client
2de6eeb25fd6582a34c8b144fff066d817b011db
6fce61642c974ede8d800e476a4a5661778a180d
refs/heads/develop
2023-04-10T03:59:04.766587
2020-01-22T19:46:26
2020-01-22T19:46:26
235,654,658
1
0
MIT
2023-04-04T01:21:32
2020-01-22T19:55:56
Python
UTF-8
Python
false
false
5,114
py
""" Aioauth-client example. """ import asyncio from aiohttp import web import html from pprint import pformat from aioauth_client import ( BitbucketClient, FacebookClient, GithubClient, GoogleClient, OAuth1Client, TwitterClient, YandexClient, ) app = web.Application() clients = { 'twitter': { 'class': TwitterClient, 'init': { 'consumer_key': 'oUXo1M7q1rlsPXm4ER3dWnMt8', 'consumer_secret': 'YWzEvXZJO9PI6f9w2FtwUJenMvy9SPLrHOvnNkVkc5LdYjKKup', }, }, 'github': { 'class': GithubClient, 'init': { 'client_id': 'b6281b6fe88fa4c313e6', 'client_secret': '21ff23d9f1cad775daee6a38d230e1ee05b04f7c', }, }, 'google': { 'class': GoogleClient, 'init': { 'client_id': '150775235058-9fmas709maee5nn053knv1heov12sh4n.apps.googleusercontent.com', # noqa 'client_secret': 'df3JwpfRf8RIBz-9avNW8Gx7', 'scope': 'email profile', }, }, 'yandex': { 'class': YandexClient, 'init': { 'client_id': 'e19388a76a824b3385f38beec67f98f1', 'client_secret': '1d2e6fdcc23b45849def6a34b43ac2d8', }, }, 'facebook': { 'class': FacebookClient, 'init': { 'client_id': '384739235070641', 'client_secret': '8e3374a4e1e91a2bd5b830a46208c15a', 'scope': 'email' }, }, 'bitbucket': { 'class': BitbucketClient, 'init': { 'consumer_key': '4DKzbyW8JSbnkFyRS5', 'consumer_secret': 'AvzZhtvRJhrEJMsGAMsPEuHTRWdMPX9z', }, }, } @asyncio.coroutine def index(request): return web.Response(text=""" <ul> <li><a href="/oauth/bitbucket">Login with Bitbucket</a></li> <li><a href="/oauth/facebook">Login with Facebook</a></li> <li><a href="/oauth/github">Login with Github</a></li> <li><a href="/oauth/google">Login with Google</a></li> <li><a href="/oauth/twitter">Login with Twitter</a></li> </ul> """, content_type="text/html") # Simple Github (OAuth2) example (not connected to app) @asyncio.coroutine def github(request): github = GithubClient( client_id='b6281b6fe88fa4c313e6', client_secret='21ff23d9f1cad775daee6a38d230e1ee05b04f7c', ) if 'code' not in request.query: return web.HTTPFound(github.get_authorize_url(scope='user:email')) # Get access token code = request.query['code'] token, _ = yield from github.get_access_token(code) assert token # Get a resource `https://api.github.com/user` response = yield from github.request('GET', 'user') body = yield from response.read() return web.Response(body=body, content_type='application/json') @asyncio.coroutine def oauth(request): provider = request.match_info.get('provider') if provider not in clients: raise web.HTTPNotFound(reason='Unknown provider') # Create OAuth1/2 client Client = clients[provider]['class'] params = clients[provider]['init'] client = Client(**params) client.params['oauth_callback' if issubclass(Client, OAuth1Client) else 'redirect_uri'] = \ 'http://%s%s' % (request.host, request.path) # Check if is not redirect from provider if client.shared_key not in request.query: # For oauth1 we need more work if isinstance(client, OAuth1Client): token, secret, _ = yield from client.get_request_token() # Dirty save a token_secret # Dont do it in production request.app.secret = secret request.app.token = token # Redirect client to provider return web.HTTPFound(client.get_authorize_url(access_type='offline')) # For oauth1 we need more work if isinstance(client, OAuth1Client): client.oauth_token_secret = request.app.secret client.oauth_token = request.app.token _, meta = yield from client.get_access_token(request.query) user, info = yield from client.user_info() text = ( "<a href='/'>back</a><br/><br/>" "<ul>" "<li>ID: {u.id}</li>" "<li>Username: {u.username}</li>" "<li>First, last name: {u.first_name}, {u.last_name}</li>" "<li>Gender: {u.gender}</li>" "<li>Email: {u.email}</li>" "<li>Link: {u.link}</li>" "<li>Picture: {u.picture}</li>" "<li>Country, city: {u.country}, {u.city}</li>" "</ul>" ).format(u=user) text += "<pre>%s</pre>" % html.escape(pformat(info)) text += "<pre>%s</pre>" % html.escape(pformat(meta)) return web.Response(text=text, content_type='text/html') app.router.add_route('GET', '/', index) app.router.add_route('GET', '/oauth/{provider}', oauth) loop = asyncio.get_event_loop() f = loop.create_server(app.make_handler(), '127.0.0.1', 5000) srv = loop.run_until_complete(f) print('serving on', srv.sockets[0].getsockname()) try: loop.run_forever() except KeyboardInterrupt: pass # pylama:ignore=D
[ "horneds@gmail.com" ]
horneds@gmail.com
c288e58b3545412b2843d13e32d82e5f94b23a6f
f4aa2101b67950e311e7be786aea332699227cd1
/shop/migrations/0008_auto_20190712_1958.py
6210c6b50d489f60336baf1f5ae3100bd218e09b
[]
no_license
PuneetPilania/LazzizCart
36382cc86053778b2fbbe70c14f6f0ad9060bca2
2c15eb5a767127540f87162eb41ddb8bbcd6f49b
refs/heads/master
2022-01-05T19:16:01.030686
2019-07-22T07:15:53
2019-07-22T07:15:53
196,684,831
0
0
null
null
null
null
UTF-8
Python
false
false
377
py
# Generated by Django 2.2.3 on 2019-07-12 14:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0007_orders_amount'), ] operations = [ migrations.AlterField( model_name='orders', name='amount', field=models.IntegerField(default=0), ), ]
[ "puneetpilania13@gmail.com" ]
puneetpilania13@gmail.com
1c43a180f86552189722c30e4df73d91a444fad5
27ba8f995043efe169cefe2d21e2f1ebdd30def4
/game_stats.py
3907be469f8adf39439004d0491ff9f445ca46df
[]
no_license
haojunnan/pygame_hit_aliens
94ef13f39fdc63f983e5359b5a90c084a6cb0c95
b025e5499ec033f67fe180917ac7041453b40e03
refs/heads/master
2021-09-07T21:24:22.313189
2018-03-01T09:44:57
2018-03-01T09:44:57
null
0
0
null
null
null
null
GB18030
Python
false
false
426
py
#coding:gb2312 class GameStats(): """跟踪游戏的统计信息""" def __init__(self,al_settings): """初始化统计信息""" self.al_settings = al_settings self.reset_stats() self.game_active = False self.high_score = 0 def reset_stats(self): """初始化在游戏运行期间可能变化的统计信息""" self.flys_left = self.al_settings.fly_limit self.score = 0 self.alien_level = 1
[ "noreply@github.com" ]
noreply@github.com
fb0b97eafee884d5d07ed6dd977d8d9483163db6
f0122dda64598ea437490645187cc680da915d58
/pages/urls.py
a54d0b5b960ec8310b2fd6062a795997aa6753b8
[]
no_license
DarkoTrpevski/DjangoBostonRealEstate
f95ab9c789fa541245be55495b2d8595ad4c6a99
2b87bd352301765e310361d0b059c42103fc6916
refs/heads/master
2022-04-18T11:16:45.410641
2020-04-20T19:37:11
2020-04-20T19:37:11
257,258,730
0
0
null
null
null
null
UTF-8
Python
false
false
399
py
from django.urls import path from . import views # First parameter is the URL Path. # Second parameter is the method we want to connect this to the view # Third parameter is the name # What ( path('') ) means, is that we don't want anything in the URL Path(meaning this will be our home page) urlpatterns = [ path('', views.index, name='index'), path('about', views.about, name='about') ]
[ "darko_trpevski@yahoo.com" ]
darko_trpevski@yahoo.com
f180ab018656525fd2a3a2e6f419270586db4dd0
947e71b34d21f3c9f5c0a197d91a880f346afa6c
/ambari-server/src/test/python/stacks/2.0.6/HDFS/test_alert_datanode_unmounted_data_dir.py
3bdec79c1f636e892ef6b9ed0a639903073d5fc8
[ "MIT", "Apache-2.0", "GPL-1.0-or-later", "GPL-2.0-or-later", "OFL-1.1", "MS-PL", "AFL-2.1", "GPL-2.0-only", "Python-2.0", "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-free-unknown" ]
permissive
liuwenru/Apache-Ambari-ZH
4bc432d4ea7087bb353a6dd97ffda0a85cb0fef0
7879810067f1981209b658ceb675ac76e951b07b
refs/heads/master
2023-01-14T14:43:06.639598
2020-07-28T12:06:25
2020-07-28T12:06:25
223,551,095
38
44
Apache-2.0
2023-01-02T21:55:10
2019-11-23T07:43:49
Java
UTF-8
Python
false
false
10,468
py
#!/usr/bin/env python ''' Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' # System imports import os import sys import logging from mock.mock import patch # Local imports from stacks.utils.RMFTestCase import * import resource_management.libraries.functions.file_system COMMON_SERVICES_ALERTS_DIR = "HDFS/2.1.0.2.0/package/alerts" DATA_DIR_MOUNT_HIST_FILE_PATH = "/var/lib/ambari-agent/data/datanode/dfs_data_dir_mount.hist" file_path = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(file_path))))) file_path = os.path.join(file_path, "main", "resources", "common-services", COMMON_SERVICES_ALERTS_DIR) RESULT_STATE_OK = "OK" RESULT_STATE_WARNING = "WARNING" RESULT_STATE_CRITICAL = "CRITICAL" RESULT_STATE_UNKNOWN = "UNKNOWN" class TestAlertDataNodeUnmountedDataDir(RMFTestCase): def setUp(self): """ Import the class under test. Because the class is present in a different folder, append its dir to the system path. Also, shorten the import name and make it a global so the test functions can access it. :return: """ self.logger = logging.getLogger() sys.path.append(file_path) global alert import alert_datanode_unmounted_data_dir as alert @patch("resource_management.libraries.functions.file_system.get_and_cache_mount_points") def test_missing_configs(self, get_and_cache_mount_points_mock): """ Check that the status is UNKNOWN when configs are missing. """ configs = {} [status, messages] = alert.execute(configurations=configs) self.assertEqual(status, RESULT_STATE_UNKNOWN) self.assertTrue(messages is not None and len(messages) == 1) self.assertTrue('is a required parameter for the script' in messages[0]) configs = { "{{hdfs-site/dfs.datanode.data.dir}}": "" } [status, messages] = alert.execute(configurations=configs) self.assertNotEqual(status, RESULT_STATE_UNKNOWN) @patch("resource_management.libraries.functions.file_system.get_and_cache_mount_points") @patch("resource_management.libraries.functions.file_system.get_mount_point_for_dir") @patch("os.path.exists") @patch("os.path.isdir") def test_mount_history_file_does_not_exist(self, is_dir_mock, exists_mock, get_mount_mock, get_and_cache_mount_points_mock): """ Test that the status is WARNING when the data dirs are mounted on root, but the mount history file does not exist. """ configs = { "{{hdfs-site/dfs.datanode.data.dir}}": "/grid/0/data" } # Mock calls exists_mock.return_value = False is_dir_mock.return_value = True get_mount_mock.return_value = "/" [status, messages] = alert.execute(configurations=configs) self.assertEqual(status, RESULT_STATE_WARNING) self.assertTrue(messages is not None and len(messages) == 1) self.assertTrue("{0} was not found".format(DATA_DIR_MOUNT_HIST_FILE_PATH) in messages[0]) @patch("resource_management.libraries.functions.file_system.get_and_cache_mount_points") @patch("resource_management.libraries.functions.mounted_dirs_helper.get_dir_to_mount_from_file") @patch("resource_management.libraries.functions.file_system.get_mount_point_for_dir") @patch("os.path.exists") @patch("os.path.isdir") def test_all_dirs_on_root(self, is_dir_mock, exists_mock, get_mount_mock, get_data_dir_to_mount_from_file_mock, get_and_cache_mount_points_mock): """ Test that the status is OK when all drives are mounted on the root partition and this coincides with the expected values. """ configs = { "{{hdfs-site/dfs.datanode.data.dir}}": "/grid/0/data,/grid/1/data,/grid/2/data" } # Mock calls exists_mock.return_value = True is_dir_mock.return_value = True get_mount_mock.return_value = "/" get_data_dir_to_mount_from_file_mock.return_value = {"/grid/0/data": "/", "/grid/1/data": "/", "/grid/2/data": "/"} [status, messages] = alert.execute(configurations=configs) self.assertEqual(status, RESULT_STATE_OK) self.assertTrue(messages is not None and len(messages) == 1) self.assertTrue("The following data dir(s) are valid" in messages[0]) @patch("resource_management.libraries.functions.file_system.get_and_cache_mount_points") @patch("resource_management.libraries.functions.mounted_dirs_helper.get_dir_to_mount_from_file") @patch("resource_management.libraries.functions.file_system.get_mount_point_for_dir") @patch("os.path.exists") @patch("os.path.isdir") def test_match_expected(self, is_dir_mock, exists_mock, get_mount_mock, get_data_dir_to_mount_from_file_mock, get_and_cache_mount_points_mock): """ Test that the status is OK when the mount points match the expected values. """ configs = { "{{hdfs-site/dfs.datanode.data.dir}}": "/grid/0/data,/grid/1/data,/grid/2/data" } # Mock calls exists_mock.return_value = True is_dir_mock.return_value = True get_mount_mock.side_effect = ["/device1", "/device2", "/"] get_data_dir_to_mount_from_file_mock.return_value = {"/grid/0/data": "/device1", "/grid/1/data": "/device2", "/grid/2/data": "/"} [status, messages] = alert.execute(configurations=configs) self.assertEqual(status, RESULT_STATE_OK) self.assertTrue(messages is not None and len(messages) == 1) self.assertTrue("The following data dir(s) are valid" in messages[0]) @patch("resource_management.libraries.functions.file_system.get_and_cache_mount_points") @patch("resource_management.libraries.functions.mounted_dirs_helper.get_dir_to_mount_from_file") @patch("resource_management.libraries.functions.file_system.get_mount_point_for_dir") @patch("os.path.exists") @patch("os.path.isdir") def test_critical_one_root_one_mounted(self, is_dir_mock, exists_mock, get_mount_mock, get_data_dir_to_mount_from_file_mock, get_and_cache_mount_points_mock): """ Test that the status is CRITICAL when the history file is missing and at least one data dir is on a mount and at least one data dir is on the root partition. """ configs = { "{{hdfs-site/dfs.datanode.data.dir}}": "/grid/0/data,/grid/1/data,/grid/2/data,/grid/3/data" } # Mock calls exists_mock.return_value = False is_dir_mock.return_value = True # The first 2 data dirs will report an error. get_mount_mock.side_effect = ["/", "/", "/device1", "/device2"] [status, messages] = alert.execute(configurations=configs) self.assertEqual(status, RESULT_STATE_CRITICAL) self.assertTrue(messages is not None and len(messages) == 1) self.assertTrue("Detected at least one data dir on a mount point, but these are writing to the root partition:\n/grid/0/data\n/grid/1/data" in messages[0]) @patch("resource_management.libraries.functions.file_system.get_and_cache_mount_points") @patch("resource_management.libraries.functions.mounted_dirs_helper.get_dir_to_mount_from_file") @patch("resource_management.libraries.functions.file_system.get_mount_point_for_dir") @patch("os.path.exists") @patch("os.path.isdir") def test_critical_unmounted(self, is_dir_mock, exists_mock, get_mount_mock, get_data_dir_to_mount_from_file_mock, get_and_cache_mount_points_mock): """ Test that the status is CRITICAL when the history file exists and one of the dirs became unmounted. """ configs = { "{{hdfs-site/dfs.datanode.data.dir}}": "/grid/0/data,/grid/1/data,/grid/2/data,/grid/3/data" } # Mock calls exists_mock.return_value = True is_dir_mock.return_value = True get_mount_mock.side_effect = ["/", "/", "/device3", "/device4"] get_data_dir_to_mount_from_file_mock.return_value = {"/grid/0/data": "/", # remained on / "/grid/1/data": "/device2", # became unmounted "/grid/2/data": "/", # became mounted "/grid/3/data": "/device4"} # remained mounted [status, messages] = alert.execute(configurations=configs) self.assertEqual(status, RESULT_STATE_CRITICAL) self.assertTrue(messages is not None and len(messages) == 1) self.assertTrue("Detected data dir(s) that became unmounted and are now writing to the root partition:\n/grid/1/data" in messages[0]) @patch("resource_management.libraries.functions.file_system.get_and_cache_mount_points") @patch("resource_management.libraries.functions.mounted_dirs_helper.get_dir_to_mount_from_file") @patch("resource_management.libraries.functions.file_system.get_mount_point_for_dir") @patch("os.path.exists") @patch("os.path.isdir") def test_file_uri_and_meta_tags(self, is_dir_mock, exists_mock, get_mount_mock, get_data_dir_to_mount_from_file_mock, get_and_cache_mount_points_mock): """ Test that the status is OK when the locations include file:// schemes and meta tags. """ configs = { "{{hdfs-site/dfs.datanode.data.dir}}":"[SSD]file:///grid/0/data" } # Mock calls exists_mock.return_value = True is_dir_mock.return_value = True get_mount_mock.return_value = "/" get_data_dir_to_mount_from_file_mock.return_value = {"/grid/0/data":"/"} [status, messages] = alert.execute(configurations = configs) self.assertEqual(status, RESULT_STATE_OK) self.assertTrue(messages is not None and len(messages) == 1) self.assertEqual("The following data dir(s) are valid:\n/grid/0/data", messages[0])
[ "ijarvis@sina.com" ]
ijarvis@sina.com
1dc0356232f83b9f82596add14362a858c4e3774
1678abd4c1efb74993745b55bf5a5536c2205417
/forum/migrations/0010_auto_20200414_2322.py
59d3916c979c2e05ef688ccf22bdbfbb16dbbdc9
[]
no_license
samosky123/Django-Forum
7b8868338d09d4a02b61717454adb2297cafc44e
c1ee3c9261479ebf8039c3a6fc9a3aba06d2c870
refs/heads/master
2023-07-29T09:45:19.810265
2020-11-13T16:05:42
2020-11-13T16:05:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
503
py
# Generated by Django 2.2 on 2020-04-14 17:22 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('forum', '0009_auto_20200414_2313'), ] operations = [ migrations.RenameField( model_name='answer', old_name='downvote', new_name='downvotes', ), migrations.RenameField( model_name='answer', old_name='upvote', new_name='upvotes', ), ]
[ "shout.mahmud@gmail.com" ]
shout.mahmud@gmail.com
67ef1fdd93e25e5a03aaa5b79601c167d78b9795
6ccbb74a59880aaee47e20861e6ac08ef31180ab
/mysecp.py
bcca6ddb33c946311e1622acf76ef3149160cf7c
[]
no_license
msebilly/cmp_ecdsa_mpc_poc
f56c288e258461dcf69f199c0105a8ef6565ea6e
d3528f6bf8763495306c6ee7a317de5549d83544
refs/heads/master
2023-09-02T03:43:18.349591
2021-11-21T19:03:15
2021-11-21T19:03:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
210
py
from ecpy.curves import Curve,Point ec = Curve.get_curve('secp256k1') def __repr__(self): return self.__str__() setattr(Point, '__repr__', __repr__) def point(x,y): return Point(x,y,ec) gen = ec.generator
[ "udi0peled@gmail.com" ]
udi0peled@gmail.com
ac8aa5968bcb2e2e1e965bf0ae23a8924c315724
4cb0b3c4acf4e30dda0f814fab8232bf13617422
/Python/Django/loginregistration/apps/log_reg/views.py
f5c5678e5092853e7e606b60f4ced6e339fbc84e
[]
no_license
h0oper/DojoAssignments
d60336b3e67021be0e6a43c1f3693193f83b22d9
28472e7907a18725d702fc9617f27619fcc4fcfc
refs/heads/master
2020-05-09T23:38:27.916674
2018-10-06T20:46:02
2018-10-06T20:46:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,790
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, redirect from .models import * from django.contrib import messages # Create your views here. def index(request): return render(request, 'log_reg/index.html') def register(request): if request.method == 'POST': password = request.POST['password'] cpassword = request.POST['cpassword'] errors = User.objects.basic_validator(request.POST) if 'userreg' in errors: request.session['id'] = errors['userreg'].id request.session['record'] = "registered!" return redirect('/success') else: for tag, error in errors.iteritems(): messages.error(request, error, extra_tags=tag) return redirect('/') def login(request): if request.method == 'POST': errors = User.objects.login_validator(request.POST) if 'userlog' in errors: request.session['id'] = errors['userlog'].id request.session['record'] = "logged in!" return redirect('/success') else: for tag, error in errors.iteritems(): messages.error(request, error, extra_tags=tag) return redirect('/') def success(request): if not 'id' in request.session: return redirect('/') data = { #get users name that connects with session id 'name': User.objects.get(id=request.session['id']), #filters items where user_id matches session id 'item': Item.objects.filter(users=request.session['id']), #opposite of 'item' 'allitem': Item.objects.exclude(users=request.session['id']), 'user': User.objects.all() } return render(request, 'log_reg/success.html', data) def delete(request,id): z = Item.objects.get(id=id) z.delete() return redirect('/success') def newitem(request): if request.method == 'POST': errors = User.objects.item_validator(request.POST) if len(errors): for tag, error in errors.iteritems(): messages.error(request, error, extra_tags=tag) return redirect('/add') else: item = Item.objects.create(itemname=request.POST['itemname'], added_by_id=request.session['id']) user = User.objects.get(id=request.session['id']) user.items.add(item) return redirect('/success') def add(request): return render(request, 'log_reg/add.html') def addto(request, id): item = Item.objects.get(id=id) user = User.objects.get(id=request.session['id']) user.items.add(item) return redirect('/success') def removefrom(request, id): item = Item.objects.get(id=id) user = User.objects.get(id=request.session['id']) user.items.remove(item) return redirect('/success') def show(request, id): data = { 'item': Item.objects.get(id=id), 'user': User.objects.filter(items=id) } return render(request, 'log_reg/show.html', data) def logout(request): request.session.clear() return redirect('/')
[ "ccasil@ucsc.edu" ]
ccasil@ucsc.edu
2e3544a7e767373aceccc7c0435e2ee8b5cb0722
d0671fb7738ff53d16ea28174eddc8252a0519e6
/PulseGenerator.py
60cfc854edd41a7a8e2d58fdf8ffbe6456332ae9
[ "BSD-2-Clause" ]
permissive
clavigne/feedback-control-retinal
cb0ca8bca3bbbd26a3b860cb9e90d4164349551c
5b2349961ae5fe09a21ddfb35e64ee958bc0a7aa
refs/heads/master
2022-11-11T22:39:51.763030
2020-06-19T20:21:32
2020-06-19T20:21:32
273,573,324
1
0
null
null
null
null
UTF-8
Python
false
false
3,401
py
import scipy.special as sps import scipy.linalg as spl import numpy as np from scipy.interpolate import interp1d def e2t(N,dE): return 2 * np.pi * np.fft.fftfreq(N,dE) def gaussian_fun(fwhm): prefac = np.sqrt(2 * np.sqrt(np.log(2))/(np.sqrt(np.pi) * fwhm)) alpha = 4.0 * np.log(2)/fwhm**2.0 def g(x): return np.exp(- alpha * x**2.0) return g def convert_fwhm(fwhm): return 8.0 * np.log(2)/fwhm def thisfft(y): return np.fft.fft(y, n=len(y)) def ithisfft(y): return np.fft.ifft(y, n=len(y)) class Pulse: def __init__(self, start, dbin, amps, fwhm_tl, fwhm_len, npts=2000, ebounds=None, grid=None, w0=5.0): if grid is None: end = start + (len(amps)-1) * dbin self.ebins = np.array([start - dbin/2.0] + [start + i * dbin for i in range(len(amps))] + [end + dbin/2.0]) self.amplitudes = np.array([amps[0]] + list(amps) + [amps[-1]]) else: start =np.min(grid) end = np.max(grid) self.ebins = grid self.amplitudes = amps if ebounds is None: low = start - 5.0/fwhm_tl * 2 *np.pi high = end + 5.0/fwhm_tl * 2 *np.pi else: low = ebounds[0] high = ebounds[1] self.e = np.linspace(low, high, npts) self.amp = np.zeros(len(self.e),dtype=np.complex) indm = np.argmin(abs(self.e - self.ebins[0])) for i in range(1,len(self.ebins)): indp = np.argmin(abs(self.e - self.ebins[i])) self.amp[indm:indp] = self.amplitudes[i] indm = indp x = self.e - w0 # The root 2 is for intensity as opposed to amplitude tl = gaussian_fun(convert_fwhm(fwhm_tl * np.sqrt(2))) total = gaussian_fun(convert_fwhm(fwhm_len * np.sqrt(2))) self.filt_tl = tl(x) self.filt_len = total(x) self.amp = np.convolve(self.amp * self.filt_tl,self.filt_len, 'same') self.dx = x[1] - x[0] self.w0 = w0 self.t = np.fft.fftshift(e2t(len(x), self.dx)) self.amp = np.convolve(self.amp * self.filt_tl,self.filt_len, 'same') self.w0 = w0 def get_grid(self, times): self.pt = np.fft.fftshift(thisfft(self.amp)) grid = np.zeros((len(self.e),len(times)), dtype=np.complex) for i in range(len(times)): newp = self.pt.copy() newp[self.t>times[i]] = 0.0 grid[:,i] = ithisfft(np.fft.ifftshift(newp)) return grid def get_preps(self,times, e): preps = np.zeros((len(e),len(times)), dtype=np.complex) grid = self.get_grid(times) for i in range(len(times)): f = interp1d(self.e, grid[:,i], fill_value=0.0,bounds_error=False, kind='nearest') preps[:,i] = f(e) return preps def chirp(self, delay=0.0, GDD=0.0, TOD=0.0): # apply a chirp to the pulse planck = 4.13566751691e-15 # ev s hbarfs = planck * 1e15 / (2 * np.pi) #ev fs # in fs cent = self.w0 phi_mat = (delay/hbarfs) * (self.e-cent) +\ (GDD/hbarfs**2.0) * (self.e -cent)**2.0/2.0 +\ (TOD/hbarfs**3.0) * (self.e -cent)**3.0/6.0 self.amp *= np.exp(1j*phi_mat)
[ "cyrille.lavigne@mail.utoronto.ca" ]
cyrille.lavigne@mail.utoronto.ca
c7d662afa44ad261f39eeb6758f41d4ae94730e7
9d4abe0bf6944f57302cbf0af89ab9f069a13d2d
/venv/lib/python2.7/sre.py
2d8e8ede2eda383dcb75c81f10f541f8d627442f
[]
no_license
calbooth/pycbc
de622ad45ef21af1ce7c9e8a855b8f565f97f38f
9f642fe732460a4863f488c7f8714b1bd17f44af
refs/heads/master
2021-01-22T09:10:06.089093
2017-02-14T12:20:12
2017-02-14T12:20:12
81,934,308
0
0
null
null
null
null
UTF-8
Python
false
false
96
py
/software/physics/ligo/spack/000/linux-redhat6-x86_64/gcc-5.4.0/ldg/pickxdy/lib/python2.7/sre.py
[ "c1320229@raven14.bullx" ]
c1320229@raven14.bullx
5c10902d7fce6fbab404b621f1c96d3526e596b1
76a2567b8de17bca7879ed8dc4485a9234b09cb2
/academy_manager.py
1f52dad9c1e0ce12f64d486397f1b740ad785e26
[]
no_license
Iron-Cow/Python02_Inheritance
86369082dae9acb8b556e1c246b6fede5aab7ca7
352c14da8a5fe8db8cd853b55f82828d1aeda245
refs/heads/master
2022-12-27T12:39:18.684066
2020-09-28T18:59:29
2020-09-28T18:59:29
299,404,273
0
0
null
null
null
null
UTF-8
Python
false
false
1,062
py
from models import * class AcademyManager(object): def test_academy(self): person = Person(16, 'Yura') print(person) print(person.get_name()) print(person.get_age()) student1 = Student(17, 'Ivan', 'Python666') print(student1) print(student1.get_group()) student1.set_group('Python_02') print(student1.get_group()) student1.add_mark(12) student1.add_mark(11) student1.add_mark(11) student1.add_mark(11) student1.add_mark(12) print(student1.get_marks()) new_emp = Employee(55, 'Borys', 'Teacher', 100500) print(new_emp) print(new_emp.get_salary()) print(new_emp.get_name()) print(new_emp.get_position()) new_emp.set_salary(5000) print(new_emp.get_salary()) teacher1 = Teacher(55, 'Oleg', 6000) print(teacher1) print(teacher1.get_salary()) teacher1.set_marks(student1, 7) print(student1.get_marks()) print(teacher1.__repr__())
[ "rudyk.iurii@gmail.com" ]
rudyk.iurii@gmail.com
86435a579cbe8e4726de5777274b1aa271d93341
1a72fbe5f21b72f35697af6e37e5adc6073da7ec
/data/combine_data_softIrIMU.py
f3d6363b3e33a24a06cb8a52df6e97a204ab1d68
[ "MIT" ]
permissive
DARYL-GWZ/SmartWalker
c50790460b431a96adf84b90387e584e27a4d9f0
f810d5f60e619362beacab026b897847c895112f
refs/heads/master
2023-07-16T20:03:02.721898
2021-08-25T11:06:00
2021-08-25T11:06:00
401,217,746
1
0
null
null
null
null
UTF-8
Python
false
false
10,861
py
import sys, os # import time import numpy as np import math import matplotlib.pyplot as pyplot import cv2 as cv pwd = os.path.abspath(os.path.abspath(__file__)) father_path = os.path.abspath(os.path.dirname(pwd)) # sys.path.append(father_path) # print(father_path) def get_data(direction): # 原始信息获取 file = open(direction) list_ir_data = file.readlines() lists = [] for lines in list_ir_data: lines = lines.strip("\n") lines = lines.strip('[') lines = lines.strip(']') lines = lines.split(", ") lists.append(lines) file.close() array_data = np.array(lists) rows_data = array_data.shape[0] columns_data = array_data.shape[1] data = np.zeros((rows_data, columns_data)) for i in range(rows_data): for j in range(columns_data): data[i][j] = float(array_data[i][j]) return data """load the data""" direction_ir_data = os.path.abspath(father_path + os.path.sep + "ir_data.txt") ir_data = get_data(direction_ir_data) print("ir",ir_data.shape) # direction_softskin = "./Record_data/data/softskin.txt" # softskin_data = get_data(direction_softskin) # print(softskin_data.shape) direction_IMU_walker = os.path.abspath(father_path + os.path.sep + "IMU.txt") walker_IMU_data = get_data(direction_IMU_walker) print("IMU",walker_IMU_data.shape) direction_driver = os.path.abspath(father_path + os.path.sep + "driver.txt") driver_data = get_data(direction_driver) print("driver",driver_data.shape) direction_leg = os.path.abspath(father_path + os.path.sep + "leg.txt") leg_data = get_data(direction_leg) print("leg",leg_data.shape) """以最低更新频率的irdata为基准,用时间帧对准其它数据""" def select_data(ir_data, target_data): remain_data = np.zeros((ir_data.shape[0],target_data.shape[1]-1)) j = 0 for i in range(ir_data.shape[0]): time_error = 100 while abs(ir_data[i,0] - target_data[j,0]) < time_error: time_error = abs(ir_data[i,0] - target_data[j,0]) j += 1 if j >= target_data.shape[0]: j -= 1 break # print(time_error,i,j) remain_data[i, :] = target_data[j,1:target_data.shape[1]] return remain_data """合并两个数据集""" def combine_data_from_two_dataset(data1,data2): row_1, col_1 = data1.shape row_2, col_2 = data2.shape data_combine = np.zeros((row_1,col_1+col_2-1)) data_combine[:,0:col_1] = data1 data_combine[:,col_1:col_1+col_2-1] = select_data(data1,data2) return data_combine data_combine = combine_data_from_two_dataset(ir_data,walker_IMU_data) data_combine = combine_data_from_two_dataset(data_combine,leg_data) data_combine = combine_data_from_two_dataset(data_combine,driver_data) # print(data_combine.shape) """Labeling""" """Load the combined data""" data_combine_cp = np.copy(data_combine) ir_data = data_combine_cp[:, 1:769] walker_IMU = data_combine_cp[:, 769:778] leg = data_combine_cp[:, 778:782] # leg[:,1] = leg[:,0] / 40 # leg[:,3] = leg[:,2] / 40 # leg[:,0] = (leg[:,1] + 20) / 65 # leg[:,2] = (leg[:,2] + 20) / 65 driver = data_combine[:,782:791] left_wheel = driver[:,3] right_wheel = driver[:,4] walker_orientation = walker_IMU[:,-1] def binarization(img): """according to an average value of the image to decide the threshold""" new_img = np.copy(img) if len(new_img.shape) != 0: threshold = max(new_img.mean() + 1.4, 23) new_img[new_img < threshold] = 0 new_img[new_img >= threshold] = 1 return new_img def filter(img): img_new = np.copy(img) img_new = img_new.reshape((24,32)) filter_kernel = np.ones((2, 2)) / 4 """other filters""" # filter_kernel = np.array([[1,1,1],[1,1,1],[1,1,1]])/10 # filter_kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]) for j in range(1): img_new = cv.filter2D(img_new, -1, filter_kernel) img_new = img_new.flatten() return img_new for i in range(ir_data.shape[0]): ir_data[i,0:ir_data.shape[1]] = filter(binarization(ir_data[i,0:ir_data.shape[1]])) """Adjust the orientation: 所有角度减去最初的角度,这样后面所有的角度都是相对起点的角度而不是地磁角度""" def adjust_orientation(orientation): average_len = 5 average_orientation = sum(orientation[0:average_len])/average_len # print(average_orientation) orientation = orientation - average_orientation for i in range(orientation.shape[0]): if orientation[i] < -180: orientation[i] += 360 if orientation[i] > 180: orientation[i] -= 360 return orientation walker_orientation = adjust_orientation(walker_orientation) """计算每个采样点前后角度变化,而不是同时刻两者的角度差""" def get_orientation_gradient(orientation): gradient = np.zeros((orientation.shape)) for i in range(gradient.shape[0]): if i == 0: continue elif i < gradient.shape[0] - 1: gradient[i] = orientation[i] - orientation[i-1] if gradient[i] <= -180: gradient[i] += 360 if gradient[i] >= 180: gradient[i] -= 360 else: gradient[i] = gradient[i-1] return gradient walker_gradient = get_orientation_gradient(walker_orientation) def create_label(gradient, walker_omega, omega_flag, positive_gradient_flag, negative_gradient_flag, left_wheel, right_wheel): label = np.copy(gradient) for i in range(gradient.shape[0]): # 原地 if abs(max(walker_omega[i,:])) <= omega_flag: label[i] = 0 # 左转 elif gradient[i] > positive_gradient_flag: if left_wheel[i] * right_wheel[i] >= 0: # 前行左转 label[i] = 2 else: # 原地左转 label[i] = 4 # 右转 elif gradient[i] < negative_gradient_flag: if left_wheel[i] * right_wheel[i] >= 0: # 前行右转 label[i] = 3 else: # 原地右转 label[i] = 5 else: if left_wheel[i] < 0 and right_wheel[i] < 0: # 前行 label[i] = 1 else: # 后退 label[i] = 6 return label walker_omega = walker_IMU[:,3:6] label_gradient = create_label(walker_gradient, walker_omega, omega_flag=0.2, positive_gradient_flag=1.8, negative_gradient_flag=-1.8, left_wheel=left_wheel, right_wheel=right_wheel) """去除某些突变值""" def filter_label(label,width): filtered_label = np.copy(label) for i in range(width,filtered_label.shape[0]-width): if label[i-width] == label[i+width]: filtered_label[i] = label[i-width] return filtered_label label_gradient = filter_label(label_gradient,1) label_gradient = filter_label(label_gradient,2) """Calculate the number/proportion of different movements""" number = np.zeros((2,7)) for i in range(label_gradient.shape[0]): number[0,int(label_gradient[i])] += 1 data_num = sum(number[0,:]) for i in range(7): number[1,i] = number[0,i]/data_num*100 print("Still: %d, Forward: %d, Left: %d, Right: %d, Left_Still: %d, Right_Still: %d, Backward: %d" % (number[0,0],number[0,1], number[0,2], number[0,3], number[0,4], number[0,5], number[0,6])) print("Still: %.2f, Forward: %.2f, Left: %.2f, Right: %.2f, Left_Still: %.2f, Right_Still: %.2f, Backward: %.2f" % (number[1,0],number[1,1], number[1,2], number[1,3], number[1,4], number[1,5], number[1,6])) """Generate the training data with label""" data_with_label_gradient = np.c_[label_gradient, ir_data, leg] """拼接相邻数据生成时间序列数据""" train_data = np.copy(data_with_label_gradient) original_label = train_data[:, 0] original_data = train_data[:, 1:train_data.shape[1]] ir_data_width = 768 leg_data_width = 4 # softskin_width = 32 softskin_width = leg_data_width # max_ir = original_data[:,0:768].max() # max_sk = original_data[:,768:800].max() """计算合并后的尺寸,用作确定LSTM的数据量""" """win_width确定模型的帧数""" win_width = 10 step_length = 1 data_num = int((train_data.shape[0] - win_width) / step_length + 1) concatenate_data = np.zeros((data_num, original_data.shape[1] * win_width)) for i in range(data_num): for j in range(win_width): concatenate_data[i, j * ir_data_width:(j + 1) * ir_data_width] = original_data[i + j, 0:ir_data_width] softskin_start_position = win_width * ir_data_width concatenate_data[i, softskin_start_position + j * softskin_width: softskin_start_position + ( j + 1) * softskin_width] = original_data[i + j, ir_data_width:ir_data_width + softskin_width] # max_ir = concatenate_data[:,0:win_width*ir_data_width].max() max_ir = 55 min_ir = 10 # max_sk = concatenate_data[:, win_width * ir_data_width:concatenate_data.shape[1]].max() # print(max_sk) max_sk = 100 # concatenate_data[:, 0:win_width * ir_data_width] = (concatenate_data[:, 0:win_width * ir_data_width]-min_ir) / (max_ir-min_ir) # threshold = 23 # preset_irdata = concatenate_data[:, 0:win_width * ir_data_width] # idx_low = preset_irdata < threshold # preset_irdata[idx_low] = 0 # idx_high = preset_irdata >= threshold # preset_irdata[idx_high] = 1 # concatenate_data[:, 0:win_width * ir_data_width] = preset_irdata """normalize with skin max pressure""" # concatenate_data[:, win_width * ir_data_width:concatenate_data.shape[1]] = concatenate_data[:, # win_width * ir_data_width: # concatenate_data.shape[1]] / max_sk """把softskin的数据置0,表示手离开""" concatenate_data[:, win_width * ir_data_width:concatenate_data.shape[1]] = (concatenate_data[:, win_width * ir_data_width:concatenate_data.shape[1]])/40+0.4 print(concatenate_data[:, win_width * ir_data_width:concatenate_data.shape[1]].max()) print(concatenate_data[:, win_width * ir_data_width:concatenate_data.shape[1]].min()) """打上label""" concatenate_label = np.zeros((concatenate_data.shape[0], 1)) for i in range(concatenate_label.shape[0]): concatenate_label[i, 0] = original_label[i + win_width - 3] concatenate_data_path = os.path.abspath(father_path + os.path.sep + str(concatenate_data.shape[0])+"data.txt") np.savetxt(concatenate_data_path,concatenate_data,fmt="%.3f") concatenate_label_path = os.path.abspath(father_path + os.path.sep + str(concatenate_data.shape[0])+"label.txt") np.savetxt(concatenate_label_path,concatenate_label,fmt="%d") print("data shape:",concatenate_data.shape) print("label shape:",concatenate_label.shape)
[ "522653608@qq.com" ]
522653608@qq.com
677694b3b52605164f56c811d4e8e9a603820803
d314a17646924dbb58b717ad23e0c2e5fb9e1b65
/DummyPlayer/const.py
7ee89b7afa93b868a9abf0d5818c7ad818317daf
[ "MIT" ]
permissive
waps101/PiSquare
072671bce6067ad478daed411ffeb5edd10c4b54
ee1bff51c7ee86fd80c9d805502525a63e548396
refs/heads/master
2021-01-10T01:37:05.222051
2015-11-26T15:04:23
2015-11-26T15:04:23
46,272,133
2
1
null
null
null
null
UTF-8
Python
false
false
869
py
UNCAPTURED = 0 UNPLAYED = 0 PLAYED = 1 PLAYER1 = 1 PLAYER2 = 2 ############################################################ ## ## Constants used for the client/server functionalities ## ############################################################ # Constant containing the IP address of the server GAME_SERVER_ADDR = '' #meaning the server is on the local host. Comment if server is elsewhere and provide # an address like the one below # GAME_SERVER_ADDR = '10.240.74.225' # Port used for the socket communication. You must ensure the same port is used by the client & the server # Note: another port number could be used GAME_SERVER_PORT = 12345 # Constant used in the communication to acknowledge a received message # Typically this constant is used to synchronise the clients and the server ACKNOWLEDGED = 'ACK'
[ "william.smith@york.ac.uk" ]
william.smith@york.ac.uk
682e6e9bf096cd8bc9cecd1f5476499372f6c040
61dcd9b485bc5e6d07c4adf14f138eabaa9a23b5
/Own practice/2.2-2.10/2.8.py
a4281af24752c551736fa11d1a5726365e91a315
[]
no_license
bong1915016/Introduction-to-Programming-Using-Python
d442d2252d13b731f6cd9c6356032e8b90aba9a1
f23e19963183aba83d96d9d8a9af5690771b62c2
refs/heads/master
2020-09-25T03:09:34.384693
2019-11-28T17:33:28
2019-11-28T17:33:28
225,904,132
1
0
null
2019-12-04T15:56:55
2019-12-04T15:56:54
null
UTF-8
Python
false
false
872
py
""" 程式設計練習題 2.2-2.10 2.8 計算能量. 請撰寫一程式,計算從起始溫度到最後溫度時熱水所需的能量。程式提示使用者數入多少公斤的水、起始溫度 及最後溫度。計算能量的公式如下: Q = M * (finalTemperature - initialTemperature) * 4184 此處的M逝水的公斤數,溫度是攝氏溫度,而Q是以焦耳(joules)來衡量的能量。 以下是範例輸出的樣本: ``` Enter the amount of water in kilograms: 55.5 Enter the initial temperature: 3.5 Enter the final Temperature:10.5 The energy needed is 1625484.0 ``` """ M = eval(input("Enter the amount of water in kilograms:")) initialTemperature = eval(input("Enter the initial temperature:")) finalTemperature = eval(input("Enter the final Temperature:")) Q = M * (finalTemperature - initialTemperature) * 4184 print("The energy needed is", Q)
[ "38396747+timmy61109@users.noreply.github.com" ]
38396747+timmy61109@users.noreply.github.com
dafc4576de9519d696cffadfb845b9e7b1470503
3134533e7bb1312ad7554e8ad4a4e59b58bdbfcf
/Webserver/apps.py
c034d2672f77b63b14f1dc3e206ecd75ad3a4e3d
[]
no_license
lingxitai/interface_web
be9e45d5c2fe53cc15af666845c9bd03be844d35
5a2c8b64745ba7a8048a910a8c27f230ff5e0be0
refs/heads/master
2020-06-25T00:52:17.747655
2019-08-06T10:21:12
2019-08-06T10:21:12
199,145,587
0
0
null
null
null
null
UTF-8
Python
false
false
93
py
from django.apps import AppConfig class WebserverConfig(AppConfig): name = 'Webserver'
[ "512654175@qq.com" ]
512654175@qq.com
1386a4e032f23d5569411ff1b79271220d0c1c9f
1d2d8048709ee1574b88e2255fed0700573d6365
/newblog/blog/migrations/0001_initial.py
a6a9da2f9b653c122743abee28d66df84608814d
[]
no_license
Misengkang/mysite
0973a147f17a70636ae1adc949913d431784926a
c0fb9c9a31752fd92b997d02b8c17c05fa25ca75
refs/heads/master
2022-12-11T16:57:54.627319
2018-03-24T12:14:24
2018-03-24T12:14:24
102,927,018
0
0
null
2022-12-08T00:36:16
2017-09-09T04:33:29
CSS
UTF-8
Python
false
false
1,880
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-08 03:07 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=70)), ('body', models.TextField()), ('create_time', models.DateTimeField()), ('modified_time', models.DateTimeField()), ('excerpt', models.CharField(blank=True, max_length=200)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='blog.Category')), ], ), migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ], ), migrations.AddField( model_name='post', name='tags', field=models.ManyToManyField(blank=True, to='blog.Tag'), ), ]
[ "hkk4641908@163.com" ]
hkk4641908@163.com
c205c5dc6573dba6cae2e742aa251ec672e6a4d4
1b5234024f6b3df18d1fef18ca1ce8419d12396a
/toDoTasks/models.py
ffead0228614f297b80b7bab398e2a72002d4de8
[]
no_license
RubiRS29/To-Do-List
cb8a34c66ad3d356612f1801a6251b288a8a2339
660115f3887ceb755f6ae74ac1005dd303d6c71a
refs/heads/main
2023-06-14T11:05:01.601959
2021-07-01T05:22:14
2021-07-01T05:22:14
376,641,334
1
0
null
null
null
null
UTF-8
Python
false
false
585
py
from django.db import models from user.models import User from formLists.models import List class Task(models.Model): user = models.ForeignKey(User , on_delete=models.CASCADE) title = models.CharField( max_length=150 ) date = models.DateField() listAdd = models.ForeignKey(List , verbose_name=("Lists") , on_delete=models.CASCADE , null=True , default=None ) create_at = models.DateField( auto_now_add=True ) class Meta: verbose_name = ("Task") verbose_name_plural = ("Tasks") def __str__(self): return self.title
[ "ramirezsantiagorubi@gmail.com" ]
ramirezsantiagorubi@gmail.com
dafa619dcaebac6988f802cb91ebce751697a7cc
8d6423ebb8933b9d92ffef4feb5ece20cf80dae4
/client.py
bcaa68add2239266b7ae93a25657d1bb8ebe3be7
[ "MIT" ]
permissive
G33kDude/dpirc
6059d422ee1e2d4a6444178c0b80a86168d886c7
7ae3f9a9117fa6d658f39d12d469a2bd16efcffc
refs/heads/master
2021-01-10T17:31:10.459109
2016-03-21T03:57:34
2016-03-21T03:57:34
54,342,040
1
0
null
null
null
null
UTF-8
Python
false
false
6,359
py
#! /usr/bin/env python3 import json import re import socket import sys import threading import time import tkinter as tk from datetime import datetime IRCRE = ('^(?::(\S+?)(?:!(\S+?))?(?:@(\S+?))? )?' # Nick!User@Host + '(\S+)(?: (?!:)(.+?))?(?: :(.+))?$') # CMD Params Params :Message class IRC(object): def connect(self, server, port, nick, user=None, name=None): self.nick = nick self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(260) # TODO: Settings self.sock.connect((server, port)) self.send('NICK {}'.format(nick)) self.send('USER {} 0 * :{}'.format(user or nick, name or nick)) self.channels = {} def send(self, text): # TODO: Make sure not longer than 512 self.sock.send((text + '\r\n').encode('UTF-8')) self.log('>{}'.format(text), raw=True) return text def sendcmd(self, cmd, params=[], msg=None): if len(params): cmd += ' ' + ' '.join(params) if msg is not None: cmd += ' :' + msg return self.send(cmd) def mainloop(self): buffer = b'' while True: try: buffer += self.sock.recv(2048) except socket.timeout: pass # should reconnect lines = buffer.split(b'\r\n') buffer = lines.pop() for line in lines: line = line.decode('utf-8', 'replace') # TODO: Encoding settings self.log('<{}'.format(line), raw=True) self.handle_message(line) def handle_message(self, message): matched = re.match(IRCRE, message) nick, user, host, cmd, params, msg = matched.groups() if hasattr(self, 'on'+cmd): handler = getattr(self,'on'+cmd) handler(nick, user, host, cmd, (params or '').split(' '), msg) def onPING(self, nick, user, host, cmd, params, msg): self.sendcmd('PONG', msg=msg) class Client(IRC): def __init__(self, server, port, nick, user=None, name=None): self.nick = nick self.master = tk.Tk() self.rawlog = tk.Text(self.master, state=tk.DISABLED) self.rawlog.pack(fill=tk.BOTH, expand=1) self.chanbox = tk.Listbox(self.master) self.chanbox.pack(fill=tk.Y, side=tk.LEFT) self.chanbox.bind('<<ListboxSelect>>', self.chanboxclick) self.nickbox = tk.Listbox(self.master) self.nickbox.pack(fill=tk.Y, side=tk.RIGHT) self.chatlog = tk.Text(self.master, state=tk.DISABLED) self.chatlog.pack(fill=tk.BOTH, expand=1) self.activechan = tk.Label(self.master, text=name) self.activechan.pack(side=tk.LEFT) self.chatbox = tk.Entry(self.master) self.chatbox.pack(fill=tk.X, side=tk.BOTTOM) self.chatbox.focus_set() self.master.bind('<Return>', self.chatboxsend) self.cur_chan = self.nick self.connect(server, port, nick, user, name) def chanboxclick(self, event): sel = self.chanbox.curselection() self.set_chan(sorted(self.channels)[sel[0]]) def chatboxsend(self, event): msg = self.chatbox.get() self.chatbox.delete(0, tk.END) if not msg.startswith('/'): self.log('{} <{}> {}'.format(self.cur_chan, self.nick, msg)) self.sendcmd('PRIVMSG', [self.cur_chan], msg) return split = msg[1:].split(' ', 2) command = split[0].lower() if command in ('join', 'j'): self.sendcmd('JOIN', [split[1]]) elif command in ('part', 'p', 'leave'): chan = self.cur_chan if len(split) < 2 else split[1] self.sendcmd('PART', [chan]) elif command in ('msg', 'pm'): self.sendcmd('PRIVMSG', [split[1]], split[2]) elif command in ('quit', 'q', 'exit'): self.sendcmd('QUIT') sys.exit() elif command in ('raw', 'quote'): self.send(msg[1:].split(' ',1)[1]) elif command in ('names', 'nicks', 'users'): self.log(', '.join(self.channels[self.cur_chan])) elif command in ('chan', 'channel', 'chans', 'channels', 'listchans'): if len(split) < 2: self.log(', '.join(self.channels)) self.log('Type /chan #channel to switch active channels') elif split[1] in self.channels: self.set_chan(split[1]) else: self.log('') else: self.log("UNKNOWN COMMAND: {}".format(command)) def log(self, text, raw=False): log = self.rawlog if raw else self.chatlog log.config(state=tk.NORMAL) log.insert(tk.END, datetime.now().strftime('[%H:%M] ') + text + '\n') log.config(state=tk.DISABLED) log.see(tk.END) def onPRIVMSG(self, nick, user, host, cmd, params, msg): self.log('{} <{}> {}'.format(params[0], nick, msg)) def onJOIN(self, nick, user, host, cmd, params, msg): channel = params[0] self.log('{} has joined {} ({}@{})'.format(nick, channel, user, host)) if nick == self.nick: self.channels[channel] = [] self.update_chans() self.set_chan(channel) if nick not in self.channels[channel]: self.channels[channel].append(nick) if channel == self.cur_chan: self.update_nicks() def onPART(self, nick, user, host, cmd, params, msg): channel = params[0] self.log('{} has parted {} ({}@{})'.format(nick, channel, user, host)) if nick == self.nick: self.channels.pop(channel) print(sorted(self.channels)) if channel == self.cur_chan: self.set_chan(sorted(self.channels)[0]) self.update_chans() else: self.channels[channel].remove(nick) if channel == self.cur_chan: self.update_nicks() def onQUIT(self, nick, user, host, cmd, params, msg): for channel in self.channels: if nick not in self.channels[channel]: continue self.channels[channel].remove(nick) if channel == self.cur_chan: self.update_nicks() def on353(self, nick, user, host, cmd, params, msg): for nick in msg.split(' '): nick = nick.lstrip('@+') # TODO: Pull from server meta if nick not in self.channels[params[2]]: self.channels[params[2]].append(nick) def on366(self, nick, user, host, cmd, params, msg): self.update_nicks() def set_chan(self, channel): self.cur_chan = channel self.activechan.config(text=self.cur_chan) self.update_nicks() def update_nicks(self): self.nickbox.delete(0, tk.END) for nick in sorted(self.channels[self.cur_chan]): self.nickbox.insert(tk.END, nick) def update_chans(self): self.chanbox.delete(0, tk.END) for channel in sorted(self.channels): self.chanbox.insert(tk.END, channel) def main(): with open('config.json', 'r') as f: config = json.loads(f.read()) client = Client(config['serv'], config['port'], config['nick'], config['user'], config['name']) client.sendcmd('JOIN', [config['chan']]) x = threading.Thread(target=client.mainloop) x.daemon = True x.start() client.master.mainloop() if __name__ == '__main__': main()
[ "GeekDudeAHK@Gmail.com" ]
GeekDudeAHK@Gmail.com
cfb60fa0a36ee354fb1d53624d1c999265bd40ad
cd93fdfe7a1594cfa1880074edd71200d5471a11
/core/config.py
9936725e7faa08282e1a15a8a6e003c119610ddd
[ "MIT" ]
permissive
earthmanET/SecretHunter
78d026d444e3ee37814ad8f27e2595325f173740
46561960851594e7d1f97c42c05b3b762ceaa826
refs/heads/main
2023-07-13T08:11:42.680848
2021-08-21T12:34:47
2021-08-21T12:34:47
398,521,311
0
0
null
null
null
null
UTF-8
Python
false
false
460
py
import yaml class Config: def __init__(self,yaml_path): self.yaml_path=yaml_path self.config=self.init_config() def init_config(self): yaml_path=self.yaml_path config_file = open(yaml_path,'r',encoding='utf-8') cont = config_file.read() config = yaml.load(cont,Loader=yaml.FullLoader) return config def get_target(self): target_list=self.config['target'] return target_list
[ "jsdsj13@yeah.net" ]
jsdsj13@yeah.net
11c92abeadba8a8d0063c99a18afbfba898fcbc3
94a0457c7266ab7748b7d2eeddca63c359771653
/Goldtimes5/var_data/TRMMsize_3hr_data.py
b2b306813439a93271838533fd5076f9a5aacee3
[]
no_license
HuangJin-De/cldenv_2020
30ea687ec801509827ca25f18b70f47e0b0357b7
a376b964493dfec8fe0eeb3e382f813e325272a8
refs/heads/master
2022-11-05T04:28:38.919641
2020-06-19T16:53:44
2020-06-19T16:53:44
273,133,793
0
0
null
null
null
null
UTF-8
Python
false
false
1,124
py
import csv import numpy as np from netCDF4 import Dataset import pickle import matplotlib.pyplot as plt years= np.arange(2006,2016) TRMM_path= '/data/dadm1/obs/TRMM/TRMM3B42size/' #TRMMsize_3hrs_2001.nc # lon: 0-360, lat: -49-49 #=== load lat lon TRMM TRMM_temp= '/data/dadm1/obs/TRMM/TRMM3B42/3B42.2004.3hr.nc' with Dataset(TRMM_temp,'r') as D: data= D.variables['latitude'][:] Tlat_full= np.array(data) data= D.variables['longitude'][:] Tlon_full= np.array(data) Tlat_mask= ( (Tlat_full > 0) & (Tlat_full <29.8) ) Tlon_mask= ( (Tlon_full > 100) & (Tlon_full <239.77) ) Tlat= Tlat_full[Tlat_mask] Tlon= Tlon_full[Tlon_mask] for year in years: print('Year ',year) # TRMM file TRMM_file= TRMM_path+ 'TRMMsize_3hrs_'+str(year)+'.nc' with Dataset(TRMM_file,'r') as D: TRMM= D.variables['objsize'][:,Tlat_mask,Tlon_mask] # correspond to t, Tlat, Tlon if year==years[0]: TRMM_all= TRMM else: TRMM_all = np.append(TRMM_all,TRMM,axis=0) data= TRMM_all with open('/data/cloud/Goldtimes5/data/TRMM3b42size.pk', 'wb') as fs: pickle.dump(data, fs, protocol = 4)
[ "r07229001@ntu.edu.tw" ]
r07229001@ntu.edu.tw
6281867ba787ea99bcdeed4afa68a182f5835bc6
6da7b3a425718c3eb6b980a67d50553115ce1bcb
/core/paginations.py
16e51a1f9504e27416401d9dee58556cc29fa7ad
[]
no_license
robertoggarcia/school_vanilla
9b267467813442b07dbb424a1976e73367ade686
a0f83ef8832c9ee3b7906493d0219b11ca48d09c
refs/heads/master
2022-12-02T13:56:00.899094
2020-08-21T01:58:25
2020-08-21T01:58:25
287,159,829
0
1
null
null
null
null
UTF-8
Python
false
false
338
py
from rest_framework.pagination import PageNumberPagination class LargeResultsSetPagination(PageNumberPagination): page_size = 50 page_size_query_param = 'page_size' max_page_size = 100 class SmallResultsSetPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 20
[ "robertojesusgarcia@gmail.com" ]
robertojesusgarcia@gmail.com
ebe477ad1740c02577cba55d514dba42d82725d7
20a692f84090c097c89d7f4da090c8fbe7a4a29a
/tests/test_null.py
22db265aa22a5c42c216520afccec4f93fdda067
[ "BSD-3-Clause" ]
permissive
bcaller/python-fastjsonschema
be18feb66f857e509ecdb35ee351f10de4e8b12e
5a26a8a4631a80949b1b3fd35bcabbab1cf390b9
refs/heads/master
2020-04-02T22:38:54.635757
2018-10-22T13:15:14
2018-10-22T13:15:14
154,839,989
1
0
BSD-3-Clause
2018-10-26T13:36:43
2018-10-26T13:36:43
null
UTF-8
Python
false
false
348
py
import pytest from fastjsonschema import JsonSchemaException exc = JsonSchemaException('data must be null') @pytest.mark.parametrize('value, expected', [ (0, exc), (None, None), (True, exc), ('abc', exc), ([], exc), ({}, exc), ]) def test_null(asserter, value, expected): asserter({'type': 'null'}, value, expected)
[ "michal.horejsek@firma.seznam.cz" ]
michal.horejsek@firma.seznam.cz
2a303dc18d18c13f63090a76aa45171b4d873903
a8e33ba2d2c4140a3d7601ca9aba195308539167
/Day_033/ISSOverheadNotifier/smtpHandler.py
5d920668198a6917e354f7abd42cb541b4c81398
[]
no_license
N-bred/100-days-of-code
815d3a8773a864eda2d4d3fc30e7df1903d3e79d
47ae3f9c0a040ec175b6e042a43fada647bbe96a
refs/heads/main
2023-04-02T20:00:09.469129
2021-04-08T22:06:04
2021-04-08T22:06:04
336,051,852
0
0
null
null
null
null
UTF-8
Python
false
false
659
py
import smtplib class SmtpHandler: def __init__(self, host, port, user, password): self.host = host self.port = port self.user = user self.password = password self.connection = None def start_connection(self): self.connection = smtplib.SMTP(self.host, self.port) self.smtp.starttls() self.connection.login(self.user, self.password) def send_message(self, message, to_addrs): self.start_connection() self.smtp.send_message(message, from_addr=self.user, to_addrs=to_addrs) self.end_connection() def end_connection(self): self.connection.close()
[ "thehardyboiz1@gmail.com" ]
thehardyboiz1@gmail.com
184dfa8d4c01be21a8ef6511122086221083f101
f541ffba346178741c65738035be6299f85059f9
/problem/abc148/a/main.py
41bb9b5a16c7a13713f046fd407bad6ed87cbf69
[]
no_license
TaigoKuriyama/atcoder
ccf1014615003744170626fac98c903e80538319
16e4f911db46d92186ddd99992c63baa324286de
refs/heads/master
2021-07-19T07:24:23.964803
2020-07-05T23:13:19
2020-07-05T23:13:19
189,786,665
0
0
null
null
null
null
UTF-8
Python
false
false
74
py
#!/usr/bin/env python3 a = int(input()) b = int(input()) print(6 - a - b)
[ "t.lorinza@gmail.com" ]
t.lorinza@gmail.com
722f6cccafabb3e43a45d23835ec7dc65f373228
f54e2067a0eb04540a925b4a22db1c341a964dac
/src/pyiem/nws/gini.py
4bdc3f0357741772a951ee1a8f5f6c92de1a3761
[ "MIT" ]
permissive
xoxo143/pyIEM
4b4000acadce17720ccbe4ecf9cd8c54e0775b8d
0dcf8ee65ac4b1acc11d7be61c62df815e3854f0
refs/heads/master
2023-01-24T11:17:32.450242
2020-12-02T04:06:09
2020-12-02T04:06:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
13,239
py
""" Processing of GINI formatted data found on NOAAPORT """ import struct import math import zlib from datetime import timezone, datetime import os import pyproj import numpy as np from pyiem.util import LOG DATADIR = os.sep.join([os.path.dirname(__file__), "../data"]) M_PI_2 = 1.57079632679489661923 M_PI = 3.14159265358979323846 RE_METERS = 6371200.0 ENTITIES = [ "UNK", "UNK", "MISC", "JERS", "ERS", "POES", "COMP", "DMSP", "GMS", "METEOSAT", "GOES7", "GOES8", "GOES9", "GOES10", "GOES11", "GOES12", "GOES13", "GOES14", "GOES15", ] LABELS = [ "UNK", "UNK", "MISC", "JERS", "ERS", "POES", "COMP", "DMSP", "GMS", "METEOSAT", "GOES", "GOES", "GOES", "GOES", "GOES", "GOES", "GOES", "GOES", "GOES", ] CHANNELS = [ "", "VIS", "3.9", "WV", "IR", "12", "13.3", "1.3", "U8", "U9", "U10", "U11", "U12", "LI", "PW", "SKIN", "CAPE", "TSURF", "WINDEX", ] for _u in range(22, 100): CHANNELS.append(f"U{_u}") SECTORS = [ "NHCOMP", "EAST", "WEST", "AK", "AKNAT", "HI", "HINAT", "PR", "PRNAT", "SUPER", "NHCOMP", "CCONUS", "EFLOAT", "WFLOAT", "CFLOAT", "PFLOAT", ] AWIPS_GRID_GUESS = { "A": 207, "B": 203, "E": 211, "F": 0, "H": 208, "I": 204, "N": 0, "P": 210, "Q": 205, "W": 211, } AWIPS_GRID = { "TIGB": 203, "TIGE": 211, "TIGW": 211, "TIGH": 208, "TIGP": 210, "TIGA": 207, "TIGI": 204, "TIGQ": 205, "TICF": 201, } def uint24(data): """convert three byte data that represents an unsigned int""" u = int(struct.unpack(">B", data[0:1])[0]) << 16 u += int(struct.unpack(">B", data[1:2])[0]) << 8 u += int(struct.unpack(">B", data[2:3])[0]) return u def int24(data): """Convert to int.""" u = int(struct.unpack(">B", data[0:1])[0] & 127) << 16 u += int(struct.unpack(">B", data[1:2])[0]) << 8 u += int(struct.unpack(">B", data[2:3])[0]) if (struct.unpack(">B", data[0:1])[0] & 128) != 0: u *= -1 return u def get_ir_ramp(): """ Return a np 256x3 array of colors to use for IR """ fn = "%s/gini_ir_ramp.txt" % (DATADIR,) data = np.zeros((256, 3), np.uint8) for i, line in enumerate(open(fn)): tokens = line.split() data[i, :] = [int(tokens[0]), int(tokens[1]), int(tokens[2])] return data class GINIZFile: """ Deal with compressed GINI files, which are the standard on NOAAPORT """ def __init__(self, fobj): """Create a GNIFile instance with a compressed file object Args: fobj (file): A fileobject """ fobj.seek(0) # WMO HEADER self.wmo = (fobj.read(21)).strip().decode("utf-8") d = zlib.decompressobj() hdata = d.decompress(fobj.read()) self.metadata = self.read_header(hdata[21:]) self.init_projection() totsz = len(d.unused_data) # 5120 value chunks, so we need to be careful! sdata = b"" chunk = b"x\xda" i = 0 for part in d.unused_data.split(b"x\xda"): if part == b"" and i == 0: continue chunk += part try: sdata += zlib.decompress(chunk) i += 1 totsz -= len(chunk) chunk = b"x\xda" except Exception: chunk += b"x\xda" if totsz != 0: LOG.info("Totalsize left: %s", totsz) self.data = np.reshape( np.fromstring(sdata, np.int8), (self.metadata["numlines"] + 1, self.metadata["linesize"]), ) def __str__(self): """return a string representation""" text = "%s Line Size: %s Num Lines: %s" % ( self.wmo, self.metadata["linesize"], self.metadata["numlines"], ) return text def awips_grid(self): """ Return the awips grid number based on the WMO header """ try1 = AWIPS_GRID.get(self.wmo[:4], None) if try1: return try1 return AWIPS_GRID_GUESS.get(self.wmo[3], None) def current_filename(self): """ Return a filename for this product, we'll use the format {SOURCE}_{SECTOR}_{CHANNEL}_{VALID}.png """ return "%s_%s_%s.png" % ( LABELS[self.metadata["creating_entity"]], SECTORS[self.metadata["sector"]], CHANNELS[self.metadata["channel"]], ) def get_bird(self): """ Return a string label for this satellite """ return ENTITIES[self.metadata["creating_entity"]] def get_sector(self): """Return the sector.""" return SECTORS[self.metadata["sector"]] def get_channel(self): """Return the channel.""" return CHANNELS[self.metadata["channel"]] def archive_filename(self): """ Return a filename for this product, we'll use the format {SOURCE}_{SECTOR}_{CHANNEL}_{VALID}.png """ return ("%s_%s_%s_%s.png") % ( LABELS[self.metadata["creating_entity"]], SECTORS[self.metadata["sector"]], CHANNELS[self.metadata["channel"]], self.metadata["valid"].strftime("%Y%m%d%H%M"), ) def init_llc(self): """ Initialize Lambert Conic Comformal """ self.metadata["proj"] = pyproj.Proj( proj="lcc", lat_0=self.metadata["latin"], lat_1=self.metadata["latin"], lat_2=self.metadata["latin"], lon_0=self.metadata["lov"], a=6371200.0, b=6371200.0, ) # s = 1.0 # if self.metadata['proj_center_flag'] != 0: # s = -1.0 psi = M_PI_2 - abs(math.radians(self.metadata["latin"])) cos_psi = math.cos(psi) # r_E = RE_METERS / cos_psi alpha = math.pow(math.tan(psi / 2.0), cos_psi) / math.sin(psi) x0, y0 = self.metadata["proj"]( self.metadata["lon1"], self.metadata["lat1"] ) self.metadata["x0"] = x0 self.metadata["y0"] = y0 # self.metadata['dx'] *= alpha # self.metadata['dy'] *= alpha self.metadata["y1"] = y0 + (self.metadata["dy"] * self.metadata["ny"]) (self.metadata["lon_ul"], self.metadata["lat_ul"]) = self.metadata[ "proj" ](self.metadata["x0"], self.metadata["y1"], inverse=True) LOG.info( ( "lat1: %.5f y0: %5.f y1: %.5f lat_ul: %.3f " "lat_ur: %.3f lon_ur: %.3f alpha: %.5f dy: %.3f" ), self.metadata["lat1"], y0, self.metadata["y1"], self.metadata["lat_ul"], self.metadata["lat_ur"], self.metadata["lon_ur"], alpha, self.metadata["dy"], ) def init_mercator(self): """ Compute mercator projection stuff """ self.metadata["proj"] = pyproj.Proj( proj="merc", lat_ts=self.metadata["latin"], x_0=0, y_0=0, a=6371200.0, b=6371200.0, ) x0, y0 = self.metadata["proj"]( self.metadata["lon1"], self.metadata["lat1"] ) self.metadata["x0"] = x0 self.metadata["y0"] = y0 x1, y1 = self.metadata["proj"]( self.metadata["lon2"], self.metadata["lat2"] ) self.metadata["x1"] = x1 self.metadata["y1"] = y1 self.metadata["dx"] = (x1 - x0) / self.metadata["nx"] self.metadata["dy"] = (y1 - y0) / self.metadata["ny"] (self.metadata["lon_ul"], self.metadata["lat_ul"]) = self.metadata[ "proj" ](self.metadata["x0"], self.metadata["y1"], inverse=True) LOG.info( ( "latin: %.2f lat_ul: %.3f lon_ul: %.3f " "y0: %5.f y1: %.5f dx: %.3f dy: %.3f" ), self.metadata["latin"], self.metadata["lat_ul"], self.metadata["lon_ul"], y0, y1, self.metadata["dx"], self.metadata["dy"], ) def init_stereo(self): """ Compute Polar Stereographic """ self.metadata["proj"] = pyproj.Proj( proj="stere", lat_ts=60, lat_0=90, lon_0=self.metadata["lov"], x_0=0, y_0=0, a=6371200.0, b=6371200.0, ) # First point! x0, y0 = self.metadata["proj"]( self.metadata["lon1"], self.metadata["lat1"] ) self.metadata["x0"] = x0 self.metadata["y0"] = y0 self.metadata["y1"] = y0 + (self.metadata["dy"] * self.metadata["ny"]) (self.metadata["lon_ul"], self.metadata["lat_ul"]) = self.metadata[ "proj" ](x0, self.metadata["y1"], inverse=True) LOG.info( ( "lon_ul: %.2f lat_ul: %.2f " "lon_ll: %.2f lat_ll: %.2f " " lov: %.2f latin: %.2f lat1: %.2f lat2: %.2f " "y0: %5.f y1: %.5f dx: %.3f dy: %.3f" ), self.metadata["lon_ul"], self.metadata["lat_ul"], self.metadata["lon1"], self.metadata["lat1"], self.metadata["lov"], self.metadata["latin"], self.metadata["lat1"], self.metadata["lat2"], y0, self.metadata["y1"], self.metadata["dx"], self.metadata["dy"], ) def init_projection(self): """ Setup Grid and projection details """ if self.metadata["map_projection"] == 3: self.init_llc() elif self.metadata["map_projection"] == 1: self.init_mercator() elif self.metadata["map_projection"] == 5: self.init_stereo() else: LOG.info("Unknown Projection: %s", self.metadata["map_projection"]) def read_header(self, hdata): """read the header!""" meta = {} meta["source"] = struct.unpack("> B", hdata[0:1])[0] meta["creating_entity"] = struct.unpack("> B", hdata[1:2])[0] meta["sector"] = struct.unpack("> B", hdata[2:3])[0] meta["channel"] = struct.unpack("> B", hdata[3:4])[0] meta["numlines"] = struct.unpack(">H", hdata[4:6])[0] meta["linesize"] = struct.unpack(">H", hdata[6:8])[0] yr = 1900 + struct.unpack("> B", hdata[8:9])[0] mo = struct.unpack("> B", hdata[9:10])[0] dy = struct.unpack("> B", hdata[10:11])[0] hh = struct.unpack("> B", hdata[11:12])[0] mi = struct.unpack("> B", hdata[12:13])[0] ss = struct.unpack("> B", hdata[13:14])[0] # hs = struct.unpack("> B", hdata[14:15] )[0] meta["valid"] = datetime(yr, mo, dy, hh, mi, ss).replace( tzinfo=timezone.utc ) meta["map_projection"] = struct.unpack("> B", hdata[15:16])[0] meta["proj_center_flag"] = struct.unpack("> B", hdata[36:37])[0] >> 7 meta["scan_mode"] = struct.unpack("> B", hdata[37:38])[0] meta["nx"] = struct.unpack(">H", hdata[16:18])[0] meta["ny"] = struct.unpack(">H", hdata[18:20])[0] meta["res"] = struct.unpack(">B", hdata[41:42])[0] # Is Calibration Info included? # http://www.nws.noaa.gov/noaaport/document/ICD%20CH5-2005-1.pdf # page24 # Mercator if meta["map_projection"] == 1: meta["lat1"] = int24(hdata[20:23]) meta["lon1"] = int24(hdata[23:26]) meta["lov"] = 0 meta["dx"] = struct.unpack(">H", hdata[33:35])[0] meta["dy"] = struct.unpack(">H", hdata[35:37])[0] meta["latin"] = int24(hdata[38:41]) meta["lat2"] = int24(hdata[27:30]) meta["lon2"] = int24(hdata[30:33]) meta["lat_ur"] = int24(hdata[55:58]) meta["lon_ur"] = int24(hdata[58:61]) # lambert == 3, polar == 5 else: meta["lat1"] = int24(hdata[20:23]) meta["lon1"] = int24(hdata[23:26]) meta["lov"] = int24(hdata[27:30]) meta["dx"] = uint24(hdata[30:33]) meta["dy"] = uint24(hdata[33:36]) meta["latin"] = int24(hdata[38:41]) meta["lat2"] = 0 meta["lon2"] = 0 meta["lat_ur"] = int24(hdata[55:58]) meta["lon_ur"] = int24(hdata[58:61]) meta["dx"] = meta["dx"] / 10.0 meta["dy"] = meta["dy"] / 10.0 meta["lat1"] = meta["lat1"] / 10000.0 meta["lon1"] = meta["lon1"] / 10000.0 meta["lov"] = meta["lov"] / 10000.0 meta["latin"] = meta["latin"] / 10000.0 meta["lat2"] = meta["lat2"] / 10000.0 meta["lon2"] = meta["lon2"] / 10000.0 meta["lat_ur"] = meta["lat_ur"] / 10000.0 meta["lon_ur"] = meta["lon_ur"] / 10000.0 return meta
[ "akrherz@iastate.edu" ]
akrherz@iastate.edu
4b4722dc364c71697c33815091831aec2badb373
0115cfe0ca89264d3e25616943c3437d24ac0497
/pyx/finance/finance.py
56f41561431419e6dbb05819a4c64021703e836c
[]
no_license
shakfu/polylab
9024918681fe4807b4e5e2da4bba04453566bae1
9dce4d30120981e34bbbbc6f2caaff6e16a6cfbd
refs/heads/master
2023-08-18T05:41:01.786936
2023-07-30T22:36:52
2023-07-30T22:36:52
62,841,098
3
0
null
2022-04-21T22:25:43
2016-07-07T22:08:47
C
UTF-8
Python
false
false
4,309
py
#!/usr/bin/env python ''' A set of functions for quick financial analysis of an investment opportunity and a series of projected cashflows. For further details and pros/cons of each function please refer to the respective wikipedia page: payback_period http://en.wikipedia.org/wiki/Payback_period net present value http://en.wikipedia.org/wiki/Net_present_value internal rate of return http://en.wikipedia.org/wiki/Internal_rate_of_return ''' import sys def payback_of_investment(investment, cashflows): """The payback period refers to the length of time required for an investment to have its initial cost recovered. >>> payback_of_investment(200.0, [60.0, 60.0, 70.0, 90.0]) 3.1111111111111112 """ total, years, cumulative = 0.0, 0, [] if not cashflows or (sum(cashflows) < investment): raise Exception("insufficient cashflows") for cashflow in cashflows: total += cashflow if total < investment: years += 1 cumulative.append(total) A = years B = investment - cumulative[years-1] C = cumulative[years] - cumulative[years-1] return A + (B/C) def payback(cashflows): """The payback period refers to the length of time required for an investment to have its initial cost recovered. (This version accepts a list of cashflows) >>> payback([-200.0, 60.0, 60.0, 70.0, 90.0]) 3.1111111111111112 """ investment, cashflows = cashflows[0], cashflows[1:] if investment < 0 : investment = -investment return payback_of_investment(investment, cashflows) def npv(rate, cashflows): """The total present value of a time series of cash flows. >>> npv(0.1, [-100.0, 60.0, 60.0, 60.0]) 49.211119459053322 """ total = 0.0 for i, cashflow in enumerate(cashflows): total += cashflow / (1 + rate)**i return total def irr(cashflows, iterations=100): """The IRR or Internal Rate of Return is the annualized effective compounded return rate which can be earned on the invested capital, i.e., the yield on the investment. >>> irr([-100.0, 60.0, 60.0, 60.0]) 0.36309653947517645 """ rate = 1.0 investment = cashflows[0] for i in range(1, iterations+1): rate *= (1 - npv(rate, cashflows) / investment) return rate def investment_analysis(discount_rate, cashflows): """Provides summary investment analysis on a list of cashflows and a discount_rate. Assumes that the first element of the list (i.e. at period 0) is the initial investment with a negative float value. """ _npv = npv(discount_rate, cashflows) ts = [('year', 'cashflow')] + [(str(x), str(y)) for (x,y) in zip( range(len(cashflows)), cashflows)] print "-" * 70 for y,c in ts: print y + (len(c) - len(y) + 1)*' ', print for y,c in ts: print c + ' ', print print print "Discount Rate: %.1f%%" % (discount_rate * 100) print print "Payback: %.2f years" % payback(cashflows) print " IRR: %.2f%%" % (irr(cashflows) * 100) print " NPV: %s" % _npv print print "==> %s investment of %s" % ( ("Approve" if _npv > 0 else "Do Not Approve"), str(-cashflows[0])) print "-" * 70 def main(inputs): """commandline entry point """ usage = '''Provides analysis of an investment and a series of cashflows. usage: invest discount_rate [cashflow0, cashflow1, ..., cashflowN] where discount_rate is the rate used to discount future cashflows to their present values cashflow0 is the investment amount (always a negative value) cashflow1 .. cashflowN values can be positive (net inflows) or negative (net outflows) for example: invest 0.05 -10000 6000 6000 6000 ''' try: rate, cashflows = inputs[0], inputs[1:] investment_analysis(float(rate), [float(c) for c in cashflows]) except IndexError: print usage sys.exit() main(sys.argv[1:])
[ "shakeeb.alireza@rezayat.net" ]
shakeeb.alireza@rezayat.net
0dc2a7265e351ceb503d8a6530d0a973c1c43a8f
4d56bd81412f762527064cdcdfeedceddfaa81c2
/venv/Scripts/django-admin.py
0eae46c8d41ff97a7107d41815e332da6b45ea5b
[]
no_license
sharonmalio/agencyperfomance
e23ed91d44a3d834587d1fee6b846f2deda4a830
abd74dc39b3937e751f251c503e661d2e856d6f6
refs/heads/master
2023-04-30T02:27:18.286695
2019-08-22T05:33:55
2019-08-22T05:33:55
203,717,423
0
1
null
2023-04-21T20:35:59
2019-08-22T04:58:36
Python
UTF-8
Python
false
false
188
py
#!C:\Users\sharon.malio\PycharmProjects\agencyperformance\venv\Scripts\python.exe from django.core import management if __name__ == "__main__": management.execute_from_command_line()
[ "kaninimalio@gmail.com" ]
kaninimalio@gmail.com
4d42d8db4679452819492958ff7feb7d0d4d412d
27a34f86c149ef4116c98d56c6827d7b643ffb07
/embed.py
c66019be46b47764493b3cf73e6e222fe93be703
[]
no_license
Zaltofairo1/embed
bbe6bc20f952e1e9c70070cbfb98f5ba9de4af58
ea3383160c88becee5b617ed4e114f1b7e258056
refs/heads/master
2023-06-03T04:35:36.892610
2021-06-21T17:22:04
2021-06-21T17:22:04
376,920,049
0
0
null
null
null
null
UTF-8
Python
false
false
1,545
py
from re import search import re import aiohttp from attr import dataclass import discord from discord import channel from discord import message from discord.flags import Intents from dotenv import load_dotenv import os import os.path import random as rnd from discord.ext import commands from yarl import URL bot = commands.Bot(command_prefix='€') load_dotenv() TOKEN = os.getenv("TOKEN_DS") GUILD = int(os.getenv("GUILD_DS")) api_key = os.getenv("GIPHY_API_KEY") async def random_gif(tag): api_giphy = ( f"https://api.giphy.com/v1/gifs/random?api_key=2GDNydq1IMOCd86RihgZ15AQnl78nz31&tag={tag}&rating=g") async with aiohttp.ClientSession() as session: async with session.get(api_giphy) as response: if response.status == 200: js = await response.json() return js["data"] return None @bot.command() async def random(ctx , tag : str = ""): data = await random_gif(tag) await ctx.send(data["images"]["downsized"]["url"]) @bot.command() async def embed(ctx , tag : str = ""): data = await random_gif(tag) embed = discord.Embed() embed.set_image(url=data["images"]["downsized"]["url"]) embed.add_field (name="bit.ly URL", value=data["bitly_url"], inline=True) description = f"@{ctx.author.name} requested this {tag if tag!='' else 'random'} gif" url = (data["url"]) title = (data["username"]) embed.description = description embed.url = url embed.title = title await ctx.send(embed=embed) bot.run(TOKEN)
[ "paragithubtesla@gmail.com" ]
paragithubtesla@gmail.com
183b750342285cfeea308e6f5d22a4cbe7bdc70d
c5acde6af3cfd1b14c73469d26de53171edb9547
/sunsoong/MachineLearining/Chap4.NaiveBayes/NaiveBys.py
bc7c461fc0d1d779842bc1bb42acd02217ef3eb6
[]
no_license
SunSoong/learnMachine
180dcfa60058e3fe12a7be268308385e53fa2f93
fcea3e6671955cb7e6472d7dae58ece04e815c23
refs/heads/master
2020-08-02T17:45:10.786108
2019-10-14T05:59:31
2019-10-14T05:59:31
211,451,674
0
0
null
null
null
null
UTF-8
Python
false
false
3,602
py
""" 总结: 一般来说,如果样本特征的分布大部分是连续性,使用GaussianNB 如果样本也正的分布大部分是多元离散值,使用MultinomialNB 如果是二元离散值或者很稀疏的多元离散值,使用BernoulliNB 手写GaussianNB对鸢尾花数据集进行分类 """ # 1.导入数据集 import numpy as np import pandas as pd import random dataSet = pd.read_csv("iris.txt", header=None) # print(dataSet.head()) # 2.切分训练集和测试集 def randSplit(dataSet, rate): """ 随机对数据集切分为训练集和测试集 :param dataSet: 输入的原始书记 :param rate: 训练集所占的比例 :return: 切分好的数据集和训练集 """ l = list(dataSet.index) # 提取索引 random.shuffle(l) # 随机打乱索引 只打乱索引 不改变运行方式 dataSet.index = l # 将打乱后的索引重新复制给原始数据 n = dataSet.shape[0] # 总行数 m = int(n * rate) # 训练集的行数 train = dataSet.loc[range(m), :] # 提取前m个记录作为训练集 test = dataSet.loc[range(m, n), :] # 剩下的作为测试集 dataSet.index = range(dataSet.shape[0]) # 更新原始数据集的索引 test.index = range(test.shape[0]) # 更新原始测试集的索引 return train, test def gnb_classify(train, test): # 提取训练集的标签种类 .value_counts 用于计数键值对中每个值得个数 返回列表 .index求列表中的键 即去重后的train的值 # 得到鸢尾花的三种类型 labels = train.iloc[:, -1].value_counts().index # 运用正态分布求当前测试样本属于哪一类的概率 需要用到均值和方差 mean = [] # 存放每个类别的均值 std = [] # 存放每个类别的方差 result = [] # 存放测试集的预测结果 for i in labels: # print(labels) item = train.loc[train.iloc[:, -1] == i, :] # 对train进行遍历 找到每一个标签等于i的行 提取出来 一共三个标签 四列 m = item.iloc[:, :-1].mean() # 求标签的平均值 四个特征 三个标签 一共12个数据 s = np.sum((item.iloc[:, :-1] - m) ** 2) / (item.shape[0]) # 当前类别的方差 mean.append(m) # 将当前类别的平均值追加至列表 std.append(s) # 将当前类别的方差追加至列表 means = pd.DataFrame(mean, index=labels) # 变为DF格式,索引为类标签 stds = pd.DataFrame(std, index=labels) # 变为DF格式 索引为类标签 print(means) print(stds) for j in range(test.shape[0]): # 遍历所有测试集 iset = test.iloc[j, :-1].tolist() # 当前测试实例 去除labels后的数据集 # 正态分布公式 测试目标属于每一种标签的概率 iprob = np.exp(-1 * (iset - means) ** 2 / (stds * 2)) / (np.sqrt(2 * np.pi * stds)) prob = 1 # 初始化当前实例总概率 # 朴素贝叶斯的想法:求出4个特征的概率,然后乘积 得到总概率 (test.shape[1]-1)=4 for k in range(test.shape[1] - 1): # 遍历每个特征 prob *= iprob[k] # 特征概率之积 为当前实例总概率 cla = prob.index[np.argmax(prob.values)] # 返回最大概率的类别 argmax返回最大值索引的值,结果为标签 result.append(cla) print(result) test["predict"] = result acc = (test.iloc[:, -1] == test.iloc[:, -2]).mean() # 计算预测准确率 # print(f"模型预测准确率为{acc}") return test train, test = randSplit(dataSet, 0.8) gnb_classify(train, test)
[ "sunsoong@qq.com" ]
sunsoong@qq.com
abfc8df4fc11d1e5b3a60d1ced77a125a34ecf59
cc5931ce51063e1ed34e3b6ae8965ffd88c8691d
/accounts/models.py
7a29ae7ebbabbd4472f9bf4b2b421c73c0d2b73d
[]
no_license
Chetan45s/Django-Custom-User-Boilerplate
c94368bbf76bc0600152aeda9eb7659c41899e80
ad332f35826d47075f9d20e332975d2dbbf3713d
refs/heads/main
2023-07-13T22:55:48.219369
2021-08-16T10:24:15
2021-08-16T10:24:15
385,047,445
1
0
null
null
null
null
UTF-8
Python
false
false
2,628
py
from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser) from django.contrib.auth.models import UserManager class UserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser # notice the absence of a "Password field", that is built in. objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # Email & Password are required by default. def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their email address return self.email def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" return self.staff @property def is_admin(self): "Is the user a admin member?" return self.admin
[ "chetansalmotra45@gmail.com" ]
chetansalmotra45@gmail.com
632e9c11e7738adbf13a23ce1089a58665d06d0a
6f83d9e8be5bc31c271497ac6c6423afdb0209a3
/script/static-checks/utils.py
548b64eaa8eaf4061d403a79c3c47324b3b422b0
[ "BSD-3-Clause", "BSD-2-Clause-Views" ]
permissive
suihkulokki/tf-m-ci-scripts
5a59e32af997ad169dbc05da7e5a88ef0e18329c
4c72bd89c54db913ae27eaf6c4857ccc23e64292
refs/heads/main
2023-05-13T01:48:27.545258
2021-06-02T09:04:31
2021-06-02T09:04:46
373,103,512
0
0
null
null
null
null
UTF-8
Python
false
false
2,707
py
#!/usr/bin/env python3 # # Copyright (c) 2019-2020, Arm Limited. All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # import os import subprocess import sys import textwrap def dir_is_ignored(relative_path, ignored_folders): '''Checks if a directory is on the ignore list or inside one of the ignored directories. relative_path mustn't end in "/".''' # Check if directory is in ignore list if relative_path in ignored_folders: return True # Check if directory is a subdirectory of one in ignore list return (relative_path + '/').startswith(ignored_folders) def file_is_ignored(relative_path, valid_file_extensions, ignored_files, ignored_folders): '''Checks if a file is ignored based on its folder, name and extension.''' if not relative_path.endswith(valid_file_extensions): return True if relative_path in ignored_files: return True return dir_is_ignored(os.path.dirname(relative_path), ignored_folders) def print_exception_info(): '''Print some information about the cause of an exception.''' print("ERROR: Exception:") print(textwrap.indent(str(sys.exc_info()[0])," ")) print(textwrap.indent(str(sys.exc_info()[1])," ")) def decode_string(string, encoding='utf-8'): '''Tries to decode a binary string. It gives an error if it finds invalid characters, but it will return the string converted anyway, ignoring these characters.''' try: string = string.decode(encoding) except UnicodeDecodeError: # Capture exceptions caused by invalid characters. print("ERROR:Non-{} characters detected.".format(encoding.upper())) print_exception_info() string = string.decode(encoding, "ignore") return string def shell_command(cmd_line): '''Executes a shell command. Returns (returncode, stdout, stderr), where stdout and stderr are strings.''' try: p = subprocess.Popen(cmd_line, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() # No need for p.wait(), p.communicate() does it by default. except: print("ERROR: Shell command: ", end="") print(cmd_line) print_exception_info() return (1, None, None) stdout = decode_string(stdout) stderr = decode_string(stderr) if p.returncode != 0: print("ERROR: Shell command failed:") print(textwrap.indent(str(cmd_line)," ")) print("ERROR: stdout:") print(textwrap.indent(stdout," ")) print("ERROR: stderr:") print(textwrap.indent(stderr," ")) return (p.returncode, stdout, stderr)
[ "karl.zhang@arm.com" ]
karl.zhang@arm.com
dd09e236278b87057704fa1510b85af4e1dbf687
fde242cc818c93ef23bcc7fddcdeab5505405185
/requests_/xpath.py
33b805475ef173a969fbb6bc3b15578aefd3b567
[]
no_license
sonchenone/login_OPPEIN
d565c7226f93a37c57c52cff305af4f2e7b5209a
2ee235bac917138f47a06f4dc090d850416550d7
refs/heads/master
2022-11-15T00:29:26.358261
2020-07-10T16:39:44
2020-07-10T16:39:44
276,142,467
0
0
null
null
null
null
UTF-8
Python
false
false
223,292
py
from scrapy import Selector html=""" <html><head> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <link rel="icon" href="/favicon.ico" type="image/x-icon"> <meta http-equiv="Content-Type" content="text/html; charset=gbk"> <title>【上海,python招聘,求职】-前程无忧</title> <meta name="description" content="前程无忧为您提供最新最全的上海,python招聘,求职信息。网聚全国各城市的人才信息,找好工作,找好员工,上前程无忧。"> <meta name="keywords" content="找工作,求职,人才,招聘"> <meta name="mobile-agent" content="format=html5; url=https://m.51job.com/search/joblist.php?jobarea=020000&amp;keyword=python&amp;partner=webmeta"> <meta name="mobile-agent" content="format=xhtml; url=https://m.51job.com/search/joblist.php?jobarea=020000&amp;keyword=python&amp;partner=webmeta"> <meta name="robots" content="all"> <meta http-equiv="Expires" content="0"> <meta http-equiv="Cache-Control" content="no-cache"> <meta http-equiv="Pragma" content="no-cache"> <link rel="dns-prefetch" href="//js.51jobcdn.com"> <link rel="dns-prefetch" href="//img01.51jobcdn.com"> <link rel="dns-prefetch" href="//img02.51jobcdn.com"> <link rel="dns-prefetch" href="//img03.51jobcdn.com"> <link rel="dns-prefetch" href="//img04.51jobcdn.com"> <link rel="dns-prefetch" href="//img05.51jobcdn.com"> <link rel="dns-prefetch" href="//img06.51jobcdn.com"> <script language="javascript" src="//js.51jobcdn.com/in/js/2016/jquery.js?20180319"></script> <script language="javascript"> var _tkd = _tkd || []; //点击量统计用 var lang = []; var supporthttps = 1; //浏览器是否支持https var currenthttps = (window.location.protocol === 'https:') ? '1' : '0'; //当前是否为https var systemtime = 1593948210031; var d_system_client_time = systemtime - new Date().getTime(); var trackConfig = { 'guid': 'd4c820d7e7291331733ed54e2248c47b', 'ip': '113.100.36.170', 'accountid': '', 'refpage': '', 'refdomain': '', 'domain': 'search.51job.com', 'pageName': 'index.php', 'partner': '', 'islanding': '0', }; window.cfg = { lang:'c', domain : { my : 'http://my.51job.com', login : 'https://login.51job.com', search : 'https://search.51job.com', www : '//www.51job.com', jobs : 'https://jobs.51job.com', jianli : 'https://jianli.51job.com', company : '//company.51job.com', i : '//i.51job.com', jc : '//jc.51job.com', map : 'https://map.51job.com', m : 'https://m.51job.com', cdn : '//js.51jobcdn.com', help : 'https://help.51job.com', img : '//img06.51jobcdn.com', dj : '//dj.51job.com', mdj : '//mdj.51job.com', mq : '//mq.51job.com', mmq : '//mmq.51job.com', kbc : 'https://kbc.51job.com', mtr : 'https://medu.51job.com', tr : 'https://edu.51job.com', } }; window.cfg.lang = 'c'; window.cfg.fullLang = 'Chinese'; window.cfg.url = { root : 'https://search.51job.com', image : '//img04.51jobcdn.com/im/2009', image_search : '//img01.51jobcdn.com/im/2009/search', i : '//i.51job.com' } window.cfg.fileName = 'index.php'; window.cfg.root = 'https://search.51job.com'; window.cfg.root_userset_ajax = '//i.51job.com/userset/ajax'; window.cfg.isSearchDomain = '1'; window.cfg.langs = { sqzwml : 'applyjob', qzzwqdg : '请在要选择的职位前打勾!', myml : 'my', ts_qxjzw : '请选择职位', queren : '确认', guanbi : '关闭', nzdnxj : '您最多能选择', xiang : '项', xzdq : '选择地区', xj_xg : '选择/修改', zycs : '主要城市', sysf : '所有省份', tspd : '特殊频道', buxian : '不限', qingxj : '请选择', yixuan : '已选', znlb : '职能类别', hylb : '行业类别', gzdd : '工作地点', quanbu : '全部', zhineng : '职能', hangye : '行业', didian : '地点', qsrgjz : '请输入关键字', srpcgjz : '输入排除关键字' } window.cfg.stype = '1'; window.cfg.isJobview = '1'; </script> <script type="text/javascript" src="//js.51jobcdn.com/in/js/2016/pointtrack.js?20180605"></script> <script language="javascript" src="//js.51jobcdn.com/in/js/2016/login/jquery.placeholder.min.js"></script> <link href="//js.51jobcdn.com/in/resource/css/2020/search/common.848e2ce1.css" rel="stylesheet"> <link href="//js.51jobcdn.com/in/resource/css/2020/search/searchResult.4bd31223.css" rel="stylesheet"> <script type="text/javascript" src="https://js.51jobcdn.com/in/js/2016/trace/trackData.js?20180206"></script></head> <body> <div class="header"> <!-- bar start --> <div class="bar"> <div class="in"> <div class="language"> <ul id="languagelist"> <li class="tle"><span class="list">简</span></li><li><a href="http://big5.51job.com/gate/big5/www.51job.com/" rel="external nofollow">繁</a></li><li class="last"><a href="//www.51job.com/default-e.php" rel="external nofollow">EN</a></li> <script language="javascript"> if(location.hostname == "big5.51job.com") { $('#languagelist li span').html("繁"); $('#languagelist li:nth-child(2) a').html("简"); $('#languagelist li:nth-child(2) a').attr('href','javascript:void(0)'); $('#languagelist li:nth-child(2) a').click(function(){location.href=window.cfg.domain.www}); $('#languagelist li:nth-child(3) a').attr('href','javascript:void(0)'); $('#languagelist li:nth-child(3) a').click(function(){location.href=window.cfg.domain.www+"/default-e.php"}); } </script> </ul> </div> <span class="l">&nbsp;</span> <div class="app"> <ul> <li><em class="e_icon"></em><a href="http://app.51job.com/index.html">APP下载</a></li> <li> <img width="80" height="80" src="//img02.51jobcdn.com/im/2016/code/new_app.png" alt="app download"> <p><a href="http://app.51job.com/index.html">APP下载</a></p> </li> </ul> </div> <div class="uer"> <p class="op"> <a href="https://login.51job.com/login.php?lang=c&amp;url=http%3A%2F%2Fsearch.51job.com%2Flist%2F020000%2C000000%2C0000%2C00%2C9%2C99%2Cpython%2C2%2C1.html%3Flang%3Dc%26stype%3D%26postchannel%3D0000%26workyear%3D99%26cotype%3D99%26degreefrom%3D99%26jobterm%3D99%26companysize%3D99%26providesalary%3D99%26lonlat%3D0%252C0%26radius%3D-1%26ord_field%3D0%26confirmdate%3D9%26fromType%3D%26dibiaoid%3D0%26address%3D%26line%3D%26specialarea%3D00%26from%3D%26welfare%3D%2520%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%2520%25E7%2589%2588%25E6%259D%2583%25E5%25A3%25B0%25E6%2598%258E%25EF%25BC%259A%25E6%259C%25AC%25E6%2596%2587%25E4%25B8%25BACSDN%25E5%258D%259A%25E4%25B8%25BB%25E3%2580%258C%25E5%25BC%25A0%25E6%25B6%25A6%25E7%25BA%25A2%25E3%2580%258D%25E7%259A%2584%25E5%258E%259F%25E5%2588%259B%25E6%2596%2587%25E7%25AB%25A0%25EF%25BC%258C%25E9%2581%25B5%25E5%25BE%25AACC%25204.0%2520BY-SA%25E7%2589%2588%25E6%259D%2583%25E5%258D%258F%25E8%25AE%25AE%25EF%25BC%258C%25E8%25BD%25AC%25E8%25BD%25BD%25E8%25AF%25B7%25E9%2599%2584%25E4%25B8%258A%25E5%258E%259F%25E6%2596%2587%25E5%2587%25BA%25E5%25A4%2584%25E9%2593%25BE%25E6%258E%25A5%25E5%258F%258A%25E6%259C%25AC%25E5%25A3%25B0%25E6%2598%258E%25E3%2580%2582%2520%25E5%258E%259F%25E6%2596%2587%25E9%2593%25BE%25E6%258E%25A5%25EF%25BC%259Ahttps%3A%2F%2Fblog.csdn.net%2FZhangrunhong%2Farticle%2Fdetails%2F103054281" rel="external nofollow">登录</a> / <a href="https://login.51job.com/register.php?lang=c&amp;url=http%3A%2F%2Fsearch.51job.com%2Flist%2F020000%2C000000%2C0000%2C00%2C9%2C99%2Cpython%2C2%2C1.html%3Flang%3Dc%26stype%3D%26postchannel%3D0000%26workyear%3D99%26cotype%3D99%26degreefrom%3D99%26jobterm%3D99%26companysize%3D99%26providesalary%3D99%26lonlat%3D0%252C0%26radius%3D-1%26ord_field%3D0%26confirmdate%3D9%26fromType%3D%26dibiaoid%3D0%26address%3D%26line%3D%26specialarea%3D00%26from%3D%26welfare%3D%2520%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%25E2%2580%2594%2520%25E7%2589%2588%25E6%259D%2583%25E5%25A3%25B0%25E6%2598%258E%25EF%25BC%259A%25E6%259C%25AC%25E6%2596%2587%25E4%25B8%25BACSDN%25E5%258D%259A%25E4%25B8%25BB%25E3%2580%258C%25E5%25BC%25A0%25E6%25B6%25A6%25E7%25BA%25A2%25E3%2580%258D%25E7%259A%2584%25E5%258E%259F%25E5%2588%259B%25E6%2596%2587%25E7%25AB%25A0%25EF%25BC%258C%25E9%2581%25B5%25E5%25BE%25AACC%25204.0%2520BY-SA%25E7%2589%2588%25E6%259D%2583%25E5%258D%258F%25E8%25AE%25AE%25EF%25BC%258C%25E8%25BD%25AC%25E8%25BD%25BD%25E8%25AF%25B7%25E9%2599%2584%25E4%25B8%258A%25E5%258E%259F%25E6%2596%2587%25E5%2587%25BA%25E5%25A4%2584%25E9%2593%25BE%25E6%258E%25A5%25E5%258F%258A%25E6%259C%25AC%25E5%25A3%25B0%25E6%2598%258E%25E3%2580%2582%2520%25E5%258E%259F%25E6%2596%2587%25E9%2593%25BE%25E6%258E%25A5%25EF%25BC%259Ahttps%3A%2F%2Fblog.csdn.net%2FZhangrunhong%2Farticle%2Fdetails%2F103054281" rel="external nofollow">注册</a> </p> </div> <p class="rlk"> <a href="//baike.51job.com" target="_blank">职场百科</a> <span class="lb">&nbsp;</span> <a href="//wenku.51job.com" target="_blank">职场文库</a> <span class="lb">&nbsp;</span> <a href="https://jobs.51job.com" target="_blank">招聘信息</a> <span class="lb">&nbsp;</span> <a href="https://ehire.51job.com" target="_blank">企业服务</a> </p> </div> </div> <!-- top end --> <!-- 英文版为body添加class --> <script> </script> <!-- nag start --> <div class="pop-city" style="display:none;position: absolute; z-index: 1000;" id="area_channel_layer"> <div class="tle"> 地区选择 <em class="close" onclick="jvascript:$('#area_channel_layer,#area_channel_layer_backdrop').hide();"></em> </div> <div class="pcon"> <div class="ht"> <label>热门城市</label><a href="//www.51job.com/beijing/">北京</a><a href="//www.51job.com/shanghai/">上海</a><a href="//www.51job.com/guangzhou/">广州</a><a href="//www.51job.com/shenzhen/">深圳</a><a href="//www.51job.com/wuhan/">武汉</a><a href="//www.51job.com/xian/">西安</a><a href="//www.51job.com/hangzhou/">杭州</a><a href="//www.51job.com/nanjing/">南京</a><a href="//www.51job.com/chengdu/">成都</a><a href="//www.51job.com/chongqing/">重庆</a> </div> <div class="cbox"> <ul id="area_channel_layer_list"> <li class="on" onclick="areaChannelChangeTab('abc', this)">A B C</li> <li onclick="areaChannelChangeTab('def', this)">D E F</li> <li onclick="areaChannelChangeTab('gh', this)">G H</li> <li onclick="areaChannelChangeTab('jkl', this)">J K L</li> <li onclick="areaChannelChangeTab('mnp', this)">M N P</li> <li onclick="areaChannelChangeTab('qrs', this)">Q R S</li> <li onclick="areaChannelChangeTab('twx', this)">T W X</li> <li onclick="areaChannelChangeTab('yz', this)">Y Z</li> </ul> <div class="clst" id="area_channel_layer_all"> <div class="e" name="area_channel_div_abc"> <span><a href="//www.51job.com/anshan/">鞍山</a></span> <span><a href="//www.51job.com/anqing/">安庆</a></span> <span><a href="//www.51job.com/anyang/">安阳</a></span> <span><a href="//www.51job.com/beijing/">北京</a></span> <span><a href="//www.51job.com/baotou/">包头</a></span> <span><a href="//www.51job.com/baoding/">保定</a></span> <span><a href="//www.51job.com/bengbu/">蚌埠</a></span> <span><a href="//www.51job.com/baoji/">宝鸡</a></span> <span><a href="//www.51job.com/binzhou/">滨州</a></span> <span><a href="//www.51job.com/changchun/">长春</a></span> <span><a href="//www.51job.com/changsha/">长沙</a></span> <span><a href="//www.51job.com/chengdu/">成都</a></span> <span><a href="//www.51job.com/chongqing/">重庆</a></span> <span><a href="//www.51job.com/changzhou/">常州</a></span> <span><a href="//www.51job.com/changde/">常德</a></span> <span><a href="//www.51job.com/changshu/">常熟</a></span> <span><a href="//www.51job.com/cangzhou/">沧州</a></span> <span><a href="//www.51job.com/chaozhou/">潮州</a></span> <span><a href="//www.51job.com/chenzhou/">郴州</a></span> <span><a href="//www.51job.com/chifeng/">赤峰</a></span> <span><a href="//www.51job.com/chuzhou/">滁州</a></span> <span><a href="//www.51job.com/changzhi/">长治</a></span> </div> <div class="e" name="area_channel_div_def" style="display:none"> <span><a href="//www.51job.com/dalian/">大连</a></span> <span><a href="//www.51job.com/dongguan/">东莞</a></span> <span><a href="//www.51job.com/dandong/">丹东</a></span> <span><a href="//www.51job.com/daqing/">大庆</a></span> <span><a href="//www.51job.com/dazhou/">达州</a></span> <span><a href="//www.51job.com/datong/">大同</a></span> <span><a href="//www.51job.com/deyang/">德阳</a></span> <span><a href="//www.51job.com/dezhou/">德州</a></span> <span><a href="//www.51job.com/dongying/">东营</a></span> <span><a href="//www.51job.com/errduosi/">鄂尔多斯</a></span> <span><a href="//www.51job.com/ezhou/">鄂州</a></span> <span><a href="//www.51job.com/fuzhou/">福州</a></span> <span><a href="//www.51job.com/foshan/">佛山</a></span> <span><a href="//www.51job.com/fushun/">抚顺</a></span> <span><a href="//www.51job.com/fuzhoue/">抚州</a></span> <span><a href="//www.51job.com/fuyang/">阜阳</a></span> </div> <div class="e" name="area_channel_div_gh" style="display:none"> <span><a href="//www.51job.com/guangzhou/">广州</a></span> <span><a href="//www.51job.com/guiyang/">贵阳</a></span> <span><a href="//www.51job.com/ganzhou/">赣州</a></span> <span><a href="//www.51job.com/guangan/">广安</a></span> <span><a href="//www.51job.com/guangyuan/">广元</a></span> <span><a href="//www.51job.com/guigang/">贵港</a></span> <span><a href="//www.51job.com/guilin/">桂林</a></span> <span><a href="//www.51job.com/harbin/">哈尔滨</a></span> <span><a href="//www.51job.com/hangzhou/">杭州</a></span> <span><a href="//www.51job.com/hefei/">合肥</a></span> <span><a href="//www.51job.com/haikou/">海口</a></span> <span><a href="//www.51job.com/huhhot/">呼和浩特</a></span> <span><a href="//www.51job.com/huizhou/">惠州</a></span> <span><a href="//www.51job.com/hengyang/">衡阳</a></span> <span><a href="//www.51job.com/huaian/">淮安</a></span> <span><a href="//www.51job.com/huzhou/">湖州</a></span> <span><a href="//www.51job.com/handan/">邯郸</a></span> <span><a href="//www.51job.com/hanzhong/">汉中</a></span> <span><a href="//www.51job.com/heyuan/">河源</a></span> <span><a href="//www.51job.com/heze/">菏泽</a></span> <span><a href="//www.51job.com/hengshui/">衡水</a></span> <span><a href="//www.51job.com/huaihua/">怀化</a></span> <span><a href="//www.51job.com/huaibei/">淮北</a></span> <span><a href="//www.51job.com/huainan/">淮南</a></span> <span><a href="//www.51job.com/huanggang/">黄冈</a></span> <span><a href="//www.51job.com/huangshi/">黄石</a></span> </div> <div class="e" name="area_channel_div_jkl" style="display:none"> <span><a href="//www.51job.com/jinan/">济南</a></span> <span><a href="//www.51job.com/jiaxing/">嘉兴</a></span> <span><a href="//www.51job.com/jinhua/">金华</a></span> <span><a href="//www.51job.com/jilin/">吉林</a></span> <span><a href="//www.51job.com/jiangmen/">江门</a></span> <span><a href="//www.51job.com/jingzhou/">荆州</a></span> <span><a href="//www.51job.com/jining/">济宁</a></span> <span><a href="//www.51job.com/jiujiang/">九江</a></span> <span><a href="//www.51job.com/jian/">吉安</a></span> <span><a href="//www.51job.com/jiaozuo/">焦作</a></span> <span><a href="//www.51job.com/jieyang/">揭阳</a></span> <span><a href="//www.51job.com/jinzhou/">锦州</a></span> <span><a href="//www.51job.com/jinzhong/">晋中</a></span> <span><a href="//www.51job.com/jingmen/">荆门</a></span> <span><a href="//www.51job.com/kunming/">昆明</a></span> <span><a href="//www.51job.com/kunshan/">昆山</a></span> <span><a href="//www.51job.com/kaifeng/">开封</a></span> <span><a href="//www.51job.com/lanzhou/">兰州</a></span> <span><a href="//www.51job.com/langfang/">廊坊</a></span> <span><a href="//www.51job.com/linyi/">临沂</a></span> <span><a href="//www.51job.com/luoyang/">洛阳</a></span> <span><a href="//www.51job.com/lianyungang/">连云港</a></span> <span><a href="//www.51job.com/liuzhou/">柳州</a></span> <span><a href="//www.51job.com/leshan/">乐山</a></span> <span><a href="//www.51job.com/liaocheng/">聊城</a></span> <span><a href="//www.51job.com/linfen/">临汾</a></span> <span><a href="//www.51job.com/luan/">六安</a></span> <span><a href="//www.51job.com/loudi/">娄底</a></span> <span><a href="//www.51job.com/luzhou/">泸州</a></span> <span><a href="//www.51job.com/luohe/">漯河</a></span> </div> <div class="e" name="area_channel_div_mnp" style="display:none"> <span><a href="//www.51job.com/mianyang/">绵阳</a></span> <span><a href="//www.51job.com/maanshan/">马鞍山</a></span> <span><a href="//www.51job.com/maoming/">茂名</a></span> <span><a href="//www.51job.com/meishan/">眉山</a></span> <span><a href="//www.51job.com/meizhou/">梅州</a></span> <span><a href="//www.51job.com/nanjing/">南京</a></span> <span><a href="//www.51job.com/ningbo/">宁波</a></span> <span><a href="//www.51job.com/nanchang/">南昌</a></span> <span><a href="//www.51job.com/nantong/">南通</a></span> <span><a href="//www.51job.com/nanning/">南宁</a></span> <span><a href="//www.51job.com/nanchong/">南充</a></span> <span><a href="//www.51job.com/nanyang/">南阳</a></span> <span><a href="//www.51job.com/neijiang/">内江</a></span> <span><a href="//www.51job.com/ningde/">宁德</a></span> <span><a href="//www.51job.com/pingdingshan/">平顶山</a></span> <span><a href="//www.51job.com/putian/">莆田</a></span> <span><a href="//www.51job.com/puyang/">濮阳</a></span> </div> <div class="e" name="area_channel_div_qrs" style="display:none"> <span><a href="//www.51job.com/qingdao/">青岛</a></span> <span><a href="//www.51job.com/quanzhou/">泉州</a></span> <span><a href="//www.51job.com/qinhuangdao/">秦皇岛</a></span> <span><a href="//www.51job.com/qingyuan/">清远</a></span> <span><a href="//www.51job.com/qiqihaer/">齐齐哈尔</a></span> <span><a href="//www.51job.com/quzhou/">衢州</a></span> <span><a href="//www.51job.com/qujing/">曲靖</a></span> <span><a href="//www.51job.com/rizhao/">日照</a></span> <span><a href="//www.51job.com/shanghai/">上海</a></span> <span><a href="//www.51job.com/shenzhen/">深圳</a></span> <span><a href="//www.51job.com/shenyang/">沈阳</a></span> <span><a href="//www.51job.com/shijiazhuang/">石家庄</a></span> <span><a href="//www.51job.com/suzhou/">苏州</a></span> <span><a href="//www.51job.com/sanya/">三亚</a></span> <span><a href="//www.51job.com/shaoxing/">绍兴</a></span> <span><a href="//www.51job.com/shantou/">汕头</a></span> <span><a href="//www.51job.com/shanwei/">汕尾</a></span> <span><a href="//www.51job.com/shangqiu/">商丘</a></span> <span><a href="//www.51job.com/shangrao/">上饶</a></span> <span><a href="//www.51job.com/shaoguan/">韶关</a></span> <span><a href="//www.51job.com/shaoyang/">邵阳</a></span> <span><a href="//www.51job.com/shiyan/">十堰</a></span> <span><a href="//www.51job.com/suizhou/">随州</a></span> <span><a href="//www.51job.com/suining/">遂宁</a></span> <span><a href="//www.51job.com/suqian/">宿迁</a></span> <span><a href="//www.51job.com/suzhoue/">宿州</a></span> </div> <div class="e" name="area_channel_div_twx" style="display:none"> <span><a href="//www.51job.com/tianjin/">天津</a></span> <span><a href="//www.51job.com/taiyuan/">太原</a></span> <span><a href="//www.51job.com/taizhoue/">台州</a></span> <span><a href="//www.51job.com/tangshan/">唐山</a></span> <span><a href="//www.51job.com/taizhou/">泰州</a></span> <span><a href="//www.51job.com/tieling/">铁岭</a></span> <span><a href="//www.51job.com/taian/">泰安</a></span> <span><a href="//www.51job.com/wuhan/">武汉</a></span> <span><a href="//www.51job.com/wuxi/">无锡</a></span> <span><a href="//www.51job.com/wenzhou/">温州</a></span> <span><a href="//www.51job.com/urumqi/">乌鲁木齐</a></span> <span><a href="//www.51job.com/wuhu/">芜湖</a></span> <span><a href="//www.51job.com/weifang/">潍坊</a></span> <span><a href="//www.51job.com/weihai/">威海</a></span> <span><a href="//www.51job.com/weinan/">渭南</a></span> <span><a href="//www.51job.com/xian/">西安</a></span> <span><a href="//www.51job.com/xiamen/">厦门</a></span> <span><a href="//www.51job.com/xuzhou/">徐州</a></span> <span><a href="//www.51job.com/xiangyang/">襄阳</a></span> <span><a href="//www.51job.com/xiangtan/">湘潭</a></span> <span><a href="//www.51job.com/xianyang/">咸阳</a></span> <span><a href="//www.51job.com/xining/">西宁</a></span> <span><a href="//www.51job.com/xianning/">咸宁</a></span> <span><a href="//www.51job.com/xiaogan/">孝感</a></span> <span><a href="//www.51job.com/xinxiang/">新乡</a></span> <span><a href="//www.51job.com/xinyang/">信阳</a></span> <span><a href="//www.51job.com/xingtai/">邢台</a></span> <span><a href="//www.51job.com/xuchang/">许昌</a></span> <span><a href="//www.51job.com/xuancheng/">宣城</a></span> </div> <div class="e" name="area_channel_div_yz" style="display:none"> <span><a href="//www.51job.com/yantai/">烟台</a></span> <span><a href="//www.51job.com/yangzhou/">扬州</a></span> <span><a href="//www.51job.com/yichang/">宜昌</a></span> <span><a href="//www.51job.com/yancheng/">盐城</a></span> <span><a href="//www.51job.com/yiwu/">义乌</a></span> <span><a href="//www.51job.com/yingkou/">营口</a></span> <span><a href="//www.51job.com/yinchuan/">银川</a></span> <span><a href="//www.51job.com/yangjiang/">阳江</a></span> <span><a href="//www.51job.com/yibin/">宜宾</a></span> <span><a href="//www.51job.com/yichune/">宜春</a></span> <span><a href="//www.51job.com/yiyang/">益阳</a></span> <span><a href="//www.51job.com/yongzhou/">永州</a></span> <span><a href="//www.51job.com/yulin/">玉林</a></span> <span><a href="//www.51job.com/yueyang/">岳阳</a></span> <span><a href="//www.51job.com/yuncheng/">运城</a></span> <span><a href="//www.51job.com/zhangzhou/">漳州</a></span> <span><a href="//www.51job.com/zhengzhou/">郑州</a></span> <span><a href="//www.51job.com/zhongshan/">中山</a></span> <span><a href="//www.51job.com/zhuhai/">珠海</a></span> <span><a href="//www.51job.com/zhenjiang/">镇江</a></span> <span><a href="//www.51job.com/zhuzhou/">株洲</a></span> <span><a href="//www.51job.com/zhanjiang/">湛江</a></span> <span><a href="//www.51job.com/zhaoqing/">肇庆</a></span> <span><a href="//www.51job.com/zhangjiagang/">张家港</a></span> <span><a href="//www.51job.com/zibo/">淄博</a></span> <span><a href="//www.51job.com/zaozhuang/">枣庄</a></span> <span><a href="//www.51job.com/zhangjiakou/">张家口</a></span> <span><a href="//www.51job.com/zhoukou/">周口</a></span> <span><a href="//www.51job.com/zhumadian/">驻马店</a></span> <span><a href="//www.51job.com/zunyi/">遵义</a></span> </div> </div> <div class="clear"></div> </div> </div> </div> <div id="area_channel_layer_backdrop" class="layer_back_drop_class" style="z-index:999;position:absolute;z-index:999;left:0;top:0;display:none"></div> <script> $(document).ready(function(){ $(window).resize(function(){ if(!$("#area_channel_layer").is(":hidden")) { setLayerPosition(); } }); }); window.areaChannelChangeTab = function(sName, oEvent) { $("#area_channel_layer_all").children().hide(); $("#area_channel_layer_list").children().removeClass("on"); $(oEvent).addClass("on"); $("#area_channel_layer_all").children("div[name='area_channel_div_" + sName + "']").show(); $("#area_channel_layer_backdrop").show(); }; window.openAreaChannelLayer = function() { setLayerPosition(); $("#area_channel_layer,#area_channel_layer_backdrop").show(); }; window.setLayerPosition = function() { var dl = $(document).scrollLeft(); var dt = $(document).scrollTop(); var ww = $(document).width(); var dwh = $(document).height(); var wwh = $(window).height(); var ow = $("#area_channel_layer").width(); var oh = $("#area_channel_layer").height(); var fLeft = (ww - ow) / 2 + dl; var fTop = (wwh - oh) * 382 / 1000 + dt;//黄金比例 $("#area_channel_layer").css({'left': Math.max(parseInt(fLeft), dl), 'top': Math.max(parseInt(fTop), dt)}); $("#area_channel_layer_backdrop").css({'width': ww + 'px', 'height': dwh + 'px'}); } </script> <div class="nag" id="topIndex"> <div class="in"> <a href="//www.51job.com"><img class="logo" id="logo" width="90" height="40" src="//img06.51jobcdn.com/im/2016/logo/logo_blue.png" alt="前程无忧"></a> <img class="slogen" id="slogen" width="162" height="17" src="//img01.51jobcdn.com/im/2016/header/slogen.png?1544426366"> <!-- Jobs频道使用 start --> <!-- Jobs频道使用 end --> <p class="nlink"> <a class="" href="//www.51job.com/">首页</a> <a class="on" href="https://search.51job.com">职位搜索</a> <a class="" href="javascript:openAreaChannelLayer();">地区频道</a> <a class="" href="https://mkt.51job.com/careerpost/default_res.php">职场资讯</a> <a class="" href="https://xy.51job.com/default-xs.php">校园招聘</a> <a href="http://my.51job.com/my/gojingying.php?direct=https%3A%2F%2Fwww.51jingying.com%2Fcommon%2Fsearchcase.php%3F5CC4CE%3D1008" target="_blank">无忧精英</a> </p> </div> </div> <!-- nag end --> </div><script> </script> <div class="dw_wp"> <a name="search"></a> <input type="hidden" id="pageCode" value="10101"> <input type="hidden" id="refdomain" value="search.51job.com"> <input type="hidden" id="refpagecode" value="01"> <form name="searchForm" method="post" action="" autocomplete="off"> <input type="hidden" name="lang" value="c"> <input type="hidden" name="postchannel" value="0000"> <input type="hidden" name="line" value=""> <input id="confirmdate" type="hidden" name="confirmdate" value="9"> <input name="keywordtype" id="keywordtype" type="hidden" value="2"> <!--搜索条件--> <div class="dw_search clearfix Fm"> <div class="dw_search_in"> <!-- 全文及相关关键字 --> <div class="el on el_q"> <ul id="kwdTypeSelUl"><li>全文</li><li><a href="javascript:void(0);" onclick="kwdtypeChangeResult(1);">搜公司</a></li></ul> <p class="ipt"> <input type="text" maxlength="200" id="kwdselectid" placeholder="搜索全文/职位名" autocomplete="off" vindex="-1" name="keyword" value="python" class="mytxt at" preval=""> </p> <div class="ul" id="KwdSearchResult" style="display:none;"> </div> <!--搜索历史 --> <div class="ul" id="searchHistory" style="display:none;z-index: 4;"> <span class="tl off"><span class="bg b_his">历史记录</span></span> <span class="li" onclick="javascript:window.location.href='https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare='" title="python(全文)+上海">python(全文)+上海</span> </div> </div> <!--地点 --> <div class="txt pointer" id="work_position_click"> <p class="hdl">地点</p> <input autocomplete="off" id="work_position_input" readonly="readonly" type="text" class="ef" placeholder="选择地点" value="上海"> <input name="jobarea" id="jobarea" type="hidden" value="020000"> </div> <!-- 行业类别 --> <div class="txt pointer long" id="indtype_click"> <p class="hdl">行业</p> <input autocomplete="off" id="indtype_input" readonly="readonly" type="text" class="ef" placeholder="选择行业" value=""> <input name="industrytype" type="hidden" id="indtype_code" value=""> </div> <!-- 职能类别 --> <div class="txt pointer long brn" id="funtype_click"> <p class="hdl">职能</p> <input autocomplete="off" id="funtype_input" readonly="readonly" type="text" class="ef" placeholder="选择职能" value=""> <input name="funtype" type="hidden" id="funtype_code" value=""> </div> <!-- 搜索按钮 --> <button class="p_but" type="button" onclick="search($('#kwdselectid').val(),1)">搜&nbsp;索</button> </div> <!--搜索条件 END--> <!--关键字推荐--> <div class="dw_recommend"> <span class="title">猜你喜欢:</span> <p> <a href="https://search.51job.com/list/020000,000000,0000,00,9,99,Python%2B%25E5%25BC%2580%25E5%258F%2591,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=" track-type="searchTrackButtonClick" event-type="1" onclick="_tkd.push(['_trackEvent','1511593948209931d4c820d7e7291331733ed54e2248c47b113.100.36.1701pythonPython 开发,Python 高级,Python Web,Python 后端,Python 前端,Python 运维,Python 实习,Python 服务器,Python 爬虫,开发工程师Python 开发']);">Python 开发</a> <a href="https://search.51job.com/list/020000,000000,0000,00,9,99,Python%2B%25E9%25AB%2598%25E7%25BA%25A7,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=" track-type="searchTrackButtonClick" event-type="1" onclick="_tkd.push(['_trackEvent','1511593948209932d4c820d7e7291331733ed54e2248c47b113.100.36.1701pythonPython 开发,Python 高级,Python Web,Python 后端,Python 前端,Python 运维,Python 实习,Python 服务器,Python 爬虫,开发工程师Python 高级']);">Python 高级</a> <a href="https://search.51job.com/list/020000,000000,0000,00,9,99,Python%2BWeb,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=" track-type="searchTrackButtonClick" event-type="1" onclick="_tkd.push(['_trackEvent','1511593948209932d4c820d7e7291331733ed54e2248c47b113.100.36.1701pythonPython 开发,Python 高级,Python Web,Python 后端,Python 前端,Python 运维,Python 实习,Python 服务器,Python 爬虫,开发工程师Python Web']);">Python Web</a> <a href="https://search.51job.com/list/020000,000000,0000,00,9,99,Python%2B%25E5%2590%258E%25E7%25AB%25AF,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=" track-type="searchTrackButtonClick" event-type="1" onclick="_tkd.push(['_trackEvent','1511593948209932d4c820d7e7291331733ed54e2248c47b113.100.36.1701pythonPython 开发,Python 高级,Python Web,Python 后端,Python 前端,Python 运维,Python 实习,Python 服务器,Python 爬虫,开发工程师Python 后端']);">Python 后端</a> <a href="https://search.51job.com/list/020000,000000,0000,00,9,99,Python%2B%25E5%2589%258D%25E7%25AB%25AF,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=" track-type="searchTrackButtonClick" event-type="1" onclick="_tkd.push(['_trackEvent','1511593948209932d4c820d7e7291331733ed54e2248c47b113.100.36.1701pythonPython 开发,Python 高级,Python Web,Python 后端,Python 前端,Python 运维,Python 实习,Python 服务器,Python 爬虫,开发工程师Python 前端']);">Python 前端</a> <a href="https://search.51job.com/list/020000,000000,0000,00,9,99,Python%2B%25E8%25BF%2590%25E7%25BB%25B4,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=" track-type="searchTrackButtonClick" event-type="1" onclick="_tkd.push(['_trackEvent','1511593948209932d4c820d7e7291331733ed54e2248c47b113.100.36.1701pythonPython 开发,Python 高级,Python Web,Python 后端,Python 前端,Python 运维,Python 实习,Python 服务器,Python 爬虫,开发工程师Python 运维']);">Python 运维</a> <a href="https://search.51job.com/list/020000,000000,0000,00,9,99,Python%2B%25E5%25AE%259E%25E4%25B9%25A0,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=" track-type="searchTrackButtonClick" event-type="1" onclick="_tkd.push(['_trackEvent','1511593948209932d4c820d7e7291331733ed54e2248c47b113.100.36.1701pythonPython 开发,Python 高级,Python Web,Python 后端,Python 前端,Python 运维,Python 实习,Python 服务器,Python 爬虫,开发工程师Python 实习']);">Python 实习</a> <a href="https://search.51job.com/list/020000,000000,0000,00,9,99,Python%2B%25E6%259C%258D%25E5%258A%25A1%25E5%2599%25A8,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=" track-type="searchTrackButtonClick" event-type="1" onclick="_tkd.push(['_trackEvent','1511593948209932d4c820d7e7291331733ed54e2248c47b113.100.36.1701pythonPython 开发,Python 高级,Python Web,Python 后端,Python 前端,Python 运维,Python 实习,Python 服务器,Python 爬虫,开发工程师Python 服务器']);">Python 服务器</a> <a href="https://search.51job.com/list/020000,000000,0000,00,9,99,Python%2B%25E7%2588%25AC%25E8%2599%25AB,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=" track-type="searchTrackButtonClick" event-type="1" onclick="_tkd.push(['_trackEvent','1511593948209932d4c820d7e7291331733ed54e2248c47b113.100.36.1701pythonPython 开发,Python 高级,Python Web,Python 后端,Python 前端,Python 运维,Python 实习,Python 服务器,Python 爬虫,开发工程师Python 爬虫']);">Python 爬虫</a> <a href="https://search.51job.com/list/020000,000000,0000,00,9,99,%25E5%25BC%2580%25E5%258F%2591%25E5%25B7%25A5%25E7%25A8%258B%25E5%25B8%2588,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=" track-type="searchTrackButtonClick" event-type="1" onclick="_tkd.push(['_trackEvent','1511593948209932d4c820d7e7291331733ed54e2248c47b113.100.36.1701pythonPython 开发,Python 高级,Python Web,Python 后端,Python 前端,Python 运维,Python 实习,Python 服务器,Python 爬虫,开发工程师开发工程师']);">开发工程师</a> </p> </div> <!--关键字推荐 END--> </div></form> <!--根据关键字和城市展示的广告--> <!--过滤条件--> <div class="dw_filter "> <div class="el mk" id="filter_issuedate"> <span class="title">发布日期:</span> <ul> <li><a track-type="searchConditionTrackButtonClick" event-type="" class="dw_c_orange" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">所有</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="" class="" href="https://search.51job.com/list/020000,000000,0000,00,0,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">24小时内</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="" class="" href="https://search.51job.com/list/020000,000000,0000,00,1,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">近三天</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="" class="" href="https://search.51job.com/list/020000,000000,0000,00,2,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">近一周</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="" class="" href="https://search.51job.com/list/020000,000000,0000,00,3,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">近一月</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="" class="" href="https://search.51job.com/list/020000,000000,0000,00,4,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">其他</a></li> </ul> <div class="clear"></div> </div> <div class="el on" id="multichoices_issuedate" style="display:none"> <span class="title">发布日期:</span> <ul><li data-value="9" class="on" onclick="checkMultipleChoice(this, 'issuedate')" name="defaultmultichoices"><a href="javascript:void(0)"><em class="check"></em>所有</a></li><li data-value="0" onclick="checkMultipleChoice(this, 'issuedate')"><a href="javascript:void(0)"><em class="check"></em>24小时内</a></li><li data-value="1" onclick="checkMultipleChoice(this, 'issuedate')"><a href="javascript:void(0)"><em class="check"></em>近三天</a></li><li data-value="2" onclick="checkMultipleChoice(this, 'issuedate')"><a href="javascript:void(0)"><em class="check"></em>近一周</a></li><li data-value="3" onclick="checkMultipleChoice(this, 'issuedate')"><a href="javascript:void(0)"><em class="check"></em>近一月</a></li><li data-value="4" onclick="checkMultipleChoice(this, 'issuedate')"><a href="javascript:void(0)"><em class="check"></em>其他</a></li></ul> <div class="clear"></div> <div class="err" style="display:none">最多只能选择5项</div> <div class="btnbox"> <span class="p_but" track-type="searchTrackButtonClick" event-type="" id="submit_issuedate" onclick="submitMultiChoices('issuedate')">确定</span><span class="p_but gray" onclick="multipleChoiceShow('issuedate', false)">取消</span> </div> </div> <div class="el mk" id="filter_providesalary"> <span class="title">月薪范围:</span> <span class="more dicon Dm">更多</span> <span class="dx dicon Dm" onclick="multipleChoiceShow('providesalary', true);">多选</span> <ul> <li><a track-type="searchConditionTrackButtonClick" event-type="20" class="dw_c_orange" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">所有</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="20" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,01,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">2千以下</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="20" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,02,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">2-3千</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="20" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,03,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">3-4.5千</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="20" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,04,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">4.5-6千</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="20" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,05,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">6-8千</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="20" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,06,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">0.8-1万</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="20" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,07,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">1-1.5万</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="20" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,08,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">1.5-2万</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="20" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,09,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">2-3万</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="20" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,10,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">3-4万</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="20" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,11,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">4-5万</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="20" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,12,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">5万以上</a></li> </ul> <div class="clear"></div> </div> <div class="el on" id="multichoices_providesalary" style="display:none"> <span class="title">月薪范围:</span> <ul><li data-value="99" class="on" onclick="checkMultipleChoice(this, 'providesalary')" name="defaultmultichoices"><a href="javascript:void(0)"><em class="check"></em>所有</a></li><li data-value="01" onclick="checkMultipleChoice(this, 'providesalary')"><a href="javascript:void(0)"><em class="check"></em>2千以下</a></li><li data-value="02" onclick="checkMultipleChoice(this, 'providesalary')"><a href="javascript:void(0)"><em class="check"></em>2-3千</a></li><li data-value="03" onclick="checkMultipleChoice(this, 'providesalary')"><a href="javascript:void(0)"><em class="check"></em>3-4.5千</a></li><li data-value="04" onclick="checkMultipleChoice(this, 'providesalary')"><a href="javascript:void(0)"><em class="check"></em>4.5-6千</a></li><li data-value="05" onclick="checkMultipleChoice(this, 'providesalary')"><a href="javascript:void(0)"><em class="check"></em>6-8千</a></li><li data-value="06" onclick="checkMultipleChoice(this, 'providesalary')"><a href="javascript:void(0)"><em class="check"></em>0.8-1万</a></li><li data-value="07" onclick="checkMultipleChoice(this, 'providesalary')"><a href="javascript:void(0)"><em class="check"></em>1-1.5万</a></li><li data-value="08" onclick="checkMultipleChoice(this, 'providesalary')"><a href="javascript:void(0)"><em class="check"></em>1.5-2万</a></li><li data-value="09" onclick="checkMultipleChoice(this, 'providesalary')"><a href="javascript:void(0)"><em class="check"></em>2-3万</a></li><li data-value="10" onclick="checkMultipleChoice(this, 'providesalary')"><a href="javascript:void(0)"><em class="check"></em>3-4万</a></li><li data-value="11" onclick="checkMultipleChoice(this, 'providesalary')"><a href="javascript:void(0)"><em class="check"></em>4-5万</a></li><li data-value="12" onclick="checkMultipleChoice(this, 'providesalary')"><a href="javascript:void(0)"><em class="check"></em>5万以上</a></li></ul> <div class="clear"></div> <div class="err" style="display:none">最多只能选择5项</div> <div class="btnbox"> <span class="p_but" track-type="searchTrackButtonClick" event-type="20" id="submit_providesalary" onclick="submitMultiChoices('providesalary')">确定</span><span class="p_but gray" onclick="multipleChoiceShow('providesalary', false)">取消</span> </div> </div> <div class="el" id="filter_cotype"> <span class="title">公司性质:</span> <span class="more dicon Dm">更多</span> <span class="dx dicon Dm" onclick="multipleChoiceShow('cotype', true);">多选</span> <ul> <li><a track-type="searchConditionTrackButtonClick" event-type="21" class="dw_c_orange" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">所有</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="21" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=04&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">国企</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="21" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=01&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">外资(欧美)</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="21" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=02&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">外资(非欧美)</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="21" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=10&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">上市公司</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="21" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=03&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">合资</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="21" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=05&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">民营公司</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="21" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=06&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">外企代表处</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="21" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=07&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">政府机关</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="21" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=08&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">事业单位</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="21" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=09&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">非营利组织</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="21" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=11&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">创业公司</a></li> </ul> <div class="clear"></div> </div> <div class="el on" id="multichoices_cotype" style="display:none"> <span class="title">公司性质:</span> <ul><li data-value="99" class="on" onclick="checkMultipleChoice(this, 'cotype')" name="defaultmultichoices"><a href="javascript:void(0)"><em class="check"></em>所有</a></li><li data-value="04" onclick="checkMultipleChoice(this, 'cotype')"><a href="javascript:void(0)"><em class="check"></em>国企</a></li><li data-value="01" onclick="checkMultipleChoice(this, 'cotype')"><a href="javascript:void(0)"><em class="check"></em>外资(欧美)</a></li><li data-value="02" onclick="checkMultipleChoice(this, 'cotype')"><a href="javascript:void(0)"><em class="check"></em>外资(非欧美)</a></li><li data-value="10" onclick="checkMultipleChoice(this, 'cotype')"><a href="javascript:void(0)"><em class="check"></em>上市公司</a></li><li data-value="03" onclick="checkMultipleChoice(this, 'cotype')"><a href="javascript:void(0)"><em class="check"></em>合资</a></li><li data-value="05" onclick="checkMultipleChoice(this, 'cotype')"><a href="javascript:void(0)"><em class="check"></em>民营公司</a></li><li data-value="06" onclick="checkMultipleChoice(this, 'cotype')"><a href="javascript:void(0)"><em class="check"></em>外企代表处</a></li><li data-value="07" onclick="checkMultipleChoice(this, 'cotype')"><a href="javascript:void(0)"><em class="check"></em>政府机关</a></li><li data-value="08" onclick="checkMultipleChoice(this, 'cotype')"><a href="javascript:void(0)"><em class="check"></em>事业单位</a></li><li data-value="09" onclick="checkMultipleChoice(this, 'cotype')"><a href="javascript:void(0)"><em class="check"></em>非营利组织</a></li><li data-value="11" onclick="checkMultipleChoice(this, 'cotype')"><a href="javascript:void(0)"><em class="check"></em>创业公司</a></li></ul> <div class="clear"></div> <div class="err" style="display:none">最多只能选择5项</div> <div class="btnbox"> <span class="p_but" track-type="searchTrackButtonClick" event-type="21" id="submit_cotype" onclick="submitMultiChoices('cotype')">确定</span><span class="p_but gray" onclick="multipleChoiceShow('cotype', false)">取消</span> </div> </div> <div class="el" id="filter_workyear"> <span class="title">工作年限:</span> <span class="dx dicon Dm" onclick="multipleChoiceShow('workyear', true);">多选</span> <ul> <li><a track-type="searchConditionTrackButtonClick" event-type="22" class="dw_c_orange" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">所有</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="22" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=01&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">在校生/应届生</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="22" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=02&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">1-3年</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="22" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=03&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">3-5年</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="22" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=04&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">5-10年</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="22" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=05&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">10年以上</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="22" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=06&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">无需经验</a></li> </ul> <div class="clear"></div> </div> <div class="el on" id="multichoices_workyear" style="display:none"> <span class="title">工作年限:</span> <ul><li data-value="99" class="on" onclick="checkMultipleChoice(this, 'workyear')" name="defaultmultichoices"><a href="javascript:void(0)"><em class="check"></em>所有</a></li><li data-value="01" onclick="checkMultipleChoice(this, 'workyear')"><a href="javascript:void(0)"><em class="check"></em>在校生/应届生</a></li><li data-value="02" onclick="checkMultipleChoice(this, 'workyear')"><a href="javascript:void(0)"><em class="check"></em>1-3年</a></li><li data-value="03" onclick="checkMultipleChoice(this, 'workyear')"><a href="javascript:void(0)"><em class="check"></em>3-5年</a></li><li data-value="04" onclick="checkMultipleChoice(this, 'workyear')"><a href="javascript:void(0)"><em class="check"></em>5-10年</a></li><li data-value="05" onclick="checkMultipleChoice(this, 'workyear')"><a href="javascript:void(0)"><em class="check"></em>10年以上</a></li><li data-value="06" onclick="checkMultipleChoice(this, 'workyear')"><a href="javascript:void(0)"><em class="check"></em>无需经验</a></li></ul> <div class="clear"></div> <div class="err" style="display:none">最多只能选择5项</div> <div class="btnbox"> <span class="p_but" track-type="searchTrackButtonClick" event-type="22" id="submit_workyear" onclick="submitMultiChoices('workyear')">确定</span><span class="p_but gray" onclick="multipleChoiceShow('workyear', false)">取消</span> </div> </div> <div class="el" id="filter_degreefrom"> <span class="title">学历要求:</span> <span class="dx dicon Dm" onclick="multipleChoiceShow('degreefrom', true);">多选</span> <ul> <li><a track-type="searchConditionTrackButtonClick" event-type="23" class="dw_c_orange" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">所有</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="23" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=01&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">初中及以下</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="23" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=02&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">高中/中技/中专</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="23" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=03&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">大专</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="23" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=04&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">本科</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="23" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=05&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">硕士</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="23" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=06&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">博士</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="23" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=07&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">无学历要求</a></li> </ul> <div class="clear"></div> </div> <div class="el on" id="multichoices_degreefrom" style="display:none"> <span class="title">学历要求:</span> <ul><li data-value="99" class="on" onclick="checkMultipleChoice(this, 'degreefrom')" name="defaultmultichoices"><a href="javascript:void(0)"><em class="check"></em>所有</a></li><li data-value="01" onclick="checkMultipleChoice(this, 'degreefrom')"><a href="javascript:void(0)"><em class="check"></em>初中及以下</a></li><li data-value="02" onclick="checkMultipleChoice(this, 'degreefrom')"><a href="javascript:void(0)"><em class="check"></em>高中/中技/中专</a></li><li data-value="03" onclick="checkMultipleChoice(this, 'degreefrom')"><a href="javascript:void(0)"><em class="check"></em>大专</a></li><li data-value="04" onclick="checkMultipleChoice(this, 'degreefrom')"><a href="javascript:void(0)"><em class="check"></em>本科</a></li><li data-value="05" onclick="checkMultipleChoice(this, 'degreefrom')"><a href="javascript:void(0)"><em class="check"></em>硕士</a></li><li data-value="06" onclick="checkMultipleChoice(this, 'degreefrom')"><a href="javascript:void(0)"><em class="check"></em>博士</a></li><li data-value="07" onclick="checkMultipleChoice(this, 'degreefrom')"><a href="javascript:void(0)"><em class="check"></em>无学历要求</a></li></ul> <div class="clear"></div> <div class="err" style="display:none">最多只能选择5项</div> <div class="btnbox"> <span class="p_but" track-type="searchTrackButtonClick" event-type="23" id="submit_degreefrom" onclick="submitMultiChoices('degreefrom')">确定</span><span class="p_but gray" onclick="multipleChoiceShow('degreefrom', false)">取消</span> </div> </div> <div class="el" id="filter_companysize"> <span class="title">公司规模:</span> <span class="dx dicon Dm" onclick="multipleChoiceShow('companysize', true);">多选</span> <ul> <li><a track-type="searchConditionTrackButtonClick" event-type="24" class="dw_c_orange" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">所有</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="24" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=01&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">少于50人</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="24" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=02&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">50-150人</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="24" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=03&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">150-500人</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="24" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=04&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">500-1000人</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="24" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=05&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">1000-5000人</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="24" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=06&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">5000-10000人</a></li> <li><a track-type="searchConditionTrackButtonClick" event-type="24" class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=07&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">10000人以上</a></li> </ul> <div class="clear"></div> </div> <div class="el on" id="multichoices_companysize" style="display:none"> <span class="title">公司规模:</span> <ul><li data-value="99" class="on" onclick="checkMultipleChoice(this, 'companysize')" name="defaultmultichoices"><a href="javascript:void(0)"><em class="check"></em>所有</a></li><li data-value="01" onclick="checkMultipleChoice(this, 'companysize')"><a href="javascript:void(0)"><em class="check"></em>少于50人</a></li><li data-value="02" onclick="checkMultipleChoice(this, 'companysize')"><a href="javascript:void(0)"><em class="check"></em>50-150人</a></li><li data-value="03" onclick="checkMultipleChoice(this, 'companysize')"><a href="javascript:void(0)"><em class="check"></em>150-500人</a></li><li data-value="04" onclick="checkMultipleChoice(this, 'companysize')"><a href="javascript:void(0)"><em class="check"></em>500-1000人</a></li><li data-value="05" onclick="checkMultipleChoice(this, 'companysize')"><a href="javascript:void(0)"><em class="check"></em>1000-5000人</a></li><li data-value="06" onclick="checkMultipleChoice(this, 'companysize')"><a href="javascript:void(0)"><em class="check"></em>5000-10000人</a></li><li data-value="07" onclick="checkMultipleChoice(this, 'companysize')"><a href="javascript:void(0)"><em class="check"></em>10000人以上</a></li></ul> <div class="clear"></div> <div class="err" style="display:none">最多只能选择5项</div> <div class="btnbox"> <span class="p_but" track-type="searchTrackButtonClick" event-type="24" id="submit_companysize" onclick="submitMultiChoices('companysize')">确定</span><span class="p_but gray" onclick="multipleChoiceShow('companysize', false)">取消</span> </div> </div> <div class="el e2 show"> <span class="title">其他筛选:</span> <ul class="ote" id="otherFilter"> <li track-type="searchTrackButtonClick" event-type="" onclick="showFilterOther('filter_p_keyword', this);"> <span>薪资福利</span> </li> <li track-type="searchTrackButtonClick" event-type="" onclick="showFilterOther('filter_p_jobterm', this);"> <span>工作类型</span> </li> <li track-type="searchTrackButtonClick" event-type="" onclick="showFilterOther('filter_p_jobarea', this);"> <span>地区地标</span> </li> <li track-type="searchTrackButtonClick" event-type="" onclick="showFilterOther('filter_p_line', this);"> <span>地铁沿线</span> </li> </ul> <div class="clear"></div> </div> <div class="kel" style="display:none;"> <p id="filter_p_keyword" class="" style="display:none;"> <a class="dw_c_orange" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">所有</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=01">五险一金</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=02">带薪年假</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=03">节日福利</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=04">周末双休</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=05">绩效奖金</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=06">员工旅游</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=07">立即上岗</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=08">专业培训</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=09">全勤奖</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=10">年终双薪</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=11">定期体检</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=12">交通补贴</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=13">通讯补贴</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=14">出差补贴</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=15">包住</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=16">人才推荐奖</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=17">高温补贴</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=18">包吃包住</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=19">弹性工作</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=20">补充医疗保险</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=21">年终分红</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=22">免费班车</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=23">出国机会</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=24">住房补贴</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=25">包吃</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=26">股票期权</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=27">采暖补贴</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=28">做一休一</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=29">加班补贴</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=30">餐饮补贴</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=31">补充公积金</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=32">补充养老保险</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=33">年终奖金</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=34">季度奖金</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=35">团队聚餐</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=36">每年多次调薪</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=37">落户办理</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=38">免息房贷</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=39">全员持股</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=40">子女教育津贴</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=41">子女保险</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=42">家人免费体检</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=43">家属免费医疗</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=44">外派津贴</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=45">电脑补助</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=46">油费补贴</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=47">职位津贴</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=48">配车</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=49">不加班</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=50">科研奖励</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=51">在职研究生培养</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=52">健身俱乐部</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=53">探亲假</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=54">母婴室</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=55">做五休二</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=56">做六休一</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=57">无试用期</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=58">工作服</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=59">夫妻房</a> </p> <p id="filter_p_jobterm" class="" style="display:none;"> <a class="dw_c_orange" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">所有</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=01&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">全职</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=02&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">兼职</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=03&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">实习全职</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=04&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">实习兼职</a> </p> <p id="filter_p_jobarea" class="" style="display:none;"> <a class="dw_c_orange" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=" onclick="">所有</a> <a class="" href="javascript:void(0)" onclick="showHotdibiaoid(this);return false;">热门地标</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '020100', '', this);return false;">黄浦区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '020300', '', this);return false;">徐汇区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '020400', '', this);return false;">长宁区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '020500', '', this);return false;">静安区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '020600', '', this);return false;">普陀区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '020800', '', this);return false;">虹口区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '020900', '', this);return false;">杨浦区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '021000', '', this);return false;">浦东新区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '021100', '', this);return false;">闵行区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '021200', '', this);return false;">宝山区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '021300', '', this);return false;">嘉定区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '021400', '', this);return false;">金山区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '021500', '', this);return false;">松江区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '021600', '', this);return false;">青浦区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '021800', '', this);return false;">奉贤区</a> <a class="" href="javascript:void(0)" onclick="showDibiaoV('https://search.51job.com', '021900', '', this);return false;">崇明区</a> </p> <p id="filter_p_dibiaoid" class="nk" style="display:none;"> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=56&amp;line=&amp;welfare=">人民广场</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=66&amp;line=&amp;welfare=">徐家汇</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=64&amp;line=&amp;welfare=">五角场</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=69&amp;line=&amp;welfare=">莘庄</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=57&amp;line=&amp;welfare=">上海火车站</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=53&amp;line=&amp;welfare=">陆家嘴</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=40&amp;line=&amp;welfare=">八佰伴</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=68&amp;line=&amp;welfare=">中山公园</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=45&amp;line=&amp;welfare=">虹口体育场</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=65&amp;line=&amp;welfare=">新天地</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=51&amp;line=&amp;welfare=">静安寺</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=67&amp;line=&amp;welfare=">张江</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=62&amp;line=&amp;welfare=">外高桥</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=50&amp;line=&amp;welfare=">金桥</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=46&amp;line=&amp;welfare=">虹桥</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=59&amp;line=&amp;welfare=">上海体育场</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=71&amp;line=&amp;welfare=">漕河泾</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=60&amp;line=&amp;welfare=">世纪公园</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=41&amp;line=&amp;welfare=">百盛淮海店</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=44&amp;line=&amp;welfare=">古北新区</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=70&amp;line=&amp;welfare=">闵行经济技术开发区</a> <a class="" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=52&amp;line=&amp;welfare=">临港新城工业区</a> </p> <p id="filter_p_line" class="" style="display:none;"> <a class="dw_c_orange" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=" onclick="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">所有</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200000100', this);return false;">地铁1号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200000200', this);return false;">地铁2号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200000300', this);return false;">地铁3号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200000400', this);return false;">地铁4号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200000500', this);return false;">地铁5号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200000600', this);return false;">地铁6号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200000700', this);return false;">地铁7号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200000800', this);return false;">地铁8号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200000900', this);return false;">地铁9号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200001000', this);return false;">地铁10号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200001100', this);return false;">地铁11号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200001200', this);return false;">地铁12号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200001300', this);return false;">地铁13号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200001400', this);return false;">地铁16号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200001500', this);return false;">地铁17号线</a> <a class="" href="javascript:void(0)" onclick="showLineV('https://search.51job.com', '0200001600', this);return false;">地铁浦江线</a> </p> </div> <!--排除关键字 --> <div class="el elp" id=""> <form name="excludeForm" method="post" action=""> <span class="title">排除关键字:</span> <div class="getr"> <input type="text" name="excludekeyword" placeholder="在结果中排除关键字" maxlength="100" onkeydown="if(event.keyCode==13){return false;}"> <a href="javascript:void(0);" onclick="excludeword()" track-type="searchTrackButtonClick" event-type="17"><em></em>确定</a> </div> </form> </div> <div class="op" onclick="collapseExpansionSearch('https://search.51job.com', 'dw_filter', this);"> <span>展开选项(公司性质、公司规模、工作年限等)<em class="dicon Dm"></em></span> </div> </div> <!--过滤条件 END--> <!--已选条件--> <div id="dw_choice_mk"></div> <div class="dw_choice"> <div class="in"> <span class="title">已选条件:</span> <p>python(全文)+上海</p> <a class="og_but" href="#search">修改</a> </div> </div> <!--已选条件 END--> <!--列表表格--> <div class="dw_table" id="resultList"> <!-- 关键字广告 start --> <!-- 关键字广告 end --> <div id="dw_tlc_mk"></div> <div class="dw_tlc"> <div class="chall"> <span> <em class="check" onclick="selectAllJobs(this, 'delivery_em')" value="" name="select_all" id="top_select_all_jobs_checkbox"></em> </span> 全选 </div> <div class="op"> <span track-type="searchTrackButtonClick" event-type="13" onclick="delivery('delivery_jobid', '2', '//i.51job.com', 'c', 'https://search.51job.com', '01', '01', '//img03.51jobcdn.com');" class="but_sq uck"><i class="dicon Dm"></i>申请职位</span><span track-type="searchTrackButtonClick" event-type="14" onclick="saveCollection('');" class="but_sc uck"><i class="dicon Dm"></i>收藏职位</span> </div> <div class="sbox"> <label>已选:</label> <p class="cod at" title="python(全文)+上海">python(全文)+上海</p> </div> <div class="rt"> 共6793条职位 </div> <div class="rt"> <span id="rtPrev" class="dicon Dm"></span> <span class="dw_c_orange">1</span>&nbsp;/&nbsp;136 <a href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,2.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=" id="rtNext" class="dicon Dm on"></a> </div> <div class="rt order_time"> <em class="dicon Dm "></em><a track-type="searchTrackButtonClick" event-type="16" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=1&amp;dibiaoid=0&amp;line=&amp;welfare=">发布时间</a> </div> <div class="rt order_auto dw_c_orange"> <em class="dicon Dm on"></em><a track-type="searchTrackButtonClick" event-type="15" href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,1.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">智能排序</a> </div> </div> <!--列表表格 start--> <div class="el title"> <span class="t1">职位名</span> <span class="t2">公司名</span> <span class="t3">工作地点</span> <span class="t4">薪资</span> <span class="t5">发布时间</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="121857920" jt="6" style="display:none"> <span> <a target="_blank" title="数据挖掘工程师" href="https://51rz.51job.com/job.html?jobid=121857920" onmousedown="jobview('121857920');"> 数据挖掘工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="“前程无忧”51job.com(上海)" href="https://51rz.51job.com/job.html?jobid=71752221&amp;coid=1249">“前程无忧”51job.com(上海)</a></span> <span class="t3">上海-浦东新区</span> <span class="t4"></span> <span class="t5">07-03</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="123035549" jt="0" style="display:none"> <span> <a target="_blank" title="中级Python开发工程师" href="https://jobs.51job.com/shanghai-mhq/123035549.html?s=01&amp;t=0" onmousedown=""> 中级Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海犇众信息技术有限公司" href="https://jobs.51job.com/all/co3488486.html">上海犇众信息技术有限公司</a></span> <span class="t3">上海-闵行区</span> <span class="t4">1-1.5万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="122805348" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-cnq/122805348.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海凭安征信服务有限公司" href="https://jobs.51job.com/all/co2869172.html">上海凭安征信服务有限公司</a></span> <span class="t3">上海-长宁区</span> <span class="t4">1.2-2.5万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="122765287" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-pdxq/122765287.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海毅朝信息科技有限公司" href="https://jobs.51job.com/all/co2564534.html">上海毅朝信息科技有限公司</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">0.8-1.2万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="122496691" jt="0" style="display:none"> <span> <a target="_blank" title="Python 软件开发初级工程师" href="https://jobs.51job.com/shanghai/122496691.html?s=01&amp;t=0" onmousedown=""> Python 软件开发初级工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海东软载波微电子有限公司" href="https://jobs.51job.com/all/co129603.html">上海东软载波微电子有限公司</a></span> <span class="t3">上海</span> <span class="t4"></span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="121503435" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发/深度学习" href="https://jobs.51job.com/shanghai-pdxq/121503435.html?s=01&amp;t=0" onmousedown=""> Python开发/深度学习 </a> </span> </p> <span class="t2"><a target="_blank" title="上海乐野网络科技有限公司" href="https://jobs.51job.com/all/co3947757.html">上海乐野网络科技有限公司</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">1-2万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="114897348" jt="0" style="display:none"> <span> <a target="_blank" title="Python/PHP后端程序员" href="https://jobs.51job.com/shanghai-xhq/114897348.html?s=01&amp;t=0" onmousedown=""> Python/PHP后端程序员 </a> </span> </p> <span class="t2"><a target="_blank" title="上海萌果信息科技有限公司" href="https://jobs.51job.com/all/co3087314.html">上海萌果信息科技有限公司</a></span> <span class="t3">上海-徐汇区</span> <span class="t4">1-1.5万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="111232230" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-pdxq/111232230.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="深圳兴融联科技股份有限公司上海分公司" href="https://jobs.51job.com/all/co2759674.html">深圳兴融联科技股份有限公司上海分...</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">1-1.5万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="123369773" jt="0" style="display:none"> <span> <a target="_blank" title="高级python开发工程师" href="https://jobs.51job.com/shanghai-jdq/123369773.html?s=01&amp;t=0" onmousedown=""> 高级python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="天津新智视讯技术股份有限公司" href="https://jobs.51job.com/all/co3632501.html">天津新智视讯技术股份有限公司</a></span> <span class="t3">上海-嘉定区</span> <span class="t4">1.8-2.5万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="123358525" jt="0" style="display:none"> <span> <a target="_blank" title="资深Python开发工程师" href="https://jobs.51job.com/shanghai-jdq/123358525.html?s=01&amp;t=0" onmousedown=""> 资深Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海傲觉网络科技有限公司" href="https://jobs.51job.com/all/co5497967.html">上海傲觉网络科技有限公司</a></span> <span class="t3">上海-嘉定区</span> <span class="t4">2-3.5万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="123344319" jt="0" style="display:none"> <span> <a target="_blank" title="中高级Python开发工程师" href="https://jobs.51job.com/shanghai/123344319.html?s=01&amp;t=0" onmousedown=""> 中高级Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="北京汉克时代科技有限公司" href="https://jobs.51job.com/all/co2844997.html">北京汉克时代科技有限公司</a></span> <span class="t3">上海</span> <span class="t4">1.4-2万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="122842363" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-mhq/122842363.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海名质网络科技有限公司" href="https://jobs.51job.com/all/co4943688.html">上海名质网络科技有限公司</a></span> <span class="t3">上海-闵行区</span> <span class="t4">1-2万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="122232383" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-xhq/122232383.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="深圳市网新新思软件有限公司" href="https://jobs.51job.com/all/co3749227.html">深圳市网新新思软件有限公司</a></span> <span class="t3">上海-徐汇区</span> <span class="t4">1-1.5万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="117355255" jt="0" style="display:none"> <span> <a target="_blank" title="高级Python算法工程师" href="https://jobs.51job.com/shanghai-jaq/117355255.html?s=01&amp;t=0" onmousedown=""> 高级Python算法工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="亿翰智库" href="https://jobs.51job.com/all/co3062290.html">亿翰智库</a></span> <span class="t3">上海-静安区</span> <span class="t4">2-2.5万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="123179770" jt="0" style="display:none"> <span> <a target="_blank" title="Python Engineer" href="https://jobs.51job.com/shanghai/123179770.html?s=01&amp;t=0" onmousedown=""> Python Engineer </a> </span> </p> <span class="t2"><a target="_blank" title="大连华钦软件技术有限公司" href="https://jobs.51job.com/all/co5400670.html">大连华钦软件技术有限公司</a></span> <span class="t3">上海</span> <span class="t4">1.5-3万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="105294644" jt="0" style="display:none"> <span> <a target="_blank" title="高级Python开发工程师" href="https://jobs.51job.com/shanghai/105294644.html?s=01&amp;t=0" onmousedown=""> 高级Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="字节跳动" href="https://jobs.51job.com/all/co2758227.html">字节跳动</a></span> <span class="t3">上海</span> <span class="t4">2.5-5万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="122874039" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-pdxq/122874039.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海柯华软件有限公司" href="https://jobs.51job.com/all/co125474.html">上海柯华软件有限公司</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">8-9.5千/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="120963511" jt="0" style="display:none"> <span> <a target="_blank" title="上市医药公司 Python开发工程师" href="https://jobs.51job.com/shanghai-pdxq/120963511.html?s=01&amp;t=0" onmousedown=""> 上市医药公司 Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="万宝盛华企业管理咨询(上海)有限公司" href="https://jobs.51job.com/all/co5761023.html">万宝盛华企业管理咨询(上海)有限...</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">12-18万/年</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="112471902" jt="0" style="display:none"> <span> <a target="_blank" title="python数据分析师" href="https://jobs.51job.com/shanghai-pdxq/112471902.html?s=01&amp;t=0" onmousedown=""> python数据分析师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海澳马信息技术服务有限公司" href="https://jobs.51job.com/all/co1436401.html">上海澳马信息技术服务有限公司</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">1-2万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="118924590" jt="0" style="display:none"> <span> <a target="_blank" title="python开发" href="https://jobs.51job.com/shanghai-pdxq/118924590.html?s=01&amp;t=0" onmousedown=""> python开发 </a> </span> </p> <span class="t2"><a target="_blank" title="上海煜暖实业有限公司" href="https://jobs.51job.com/all/co5643775.html">上海煜暖实业有限公司</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">6-8千/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="123307453" jt="0" style="display:none"> <span> <a target="_blank" title="python数据开发工程师" href="https://jobs.51job.com/shanghai-hkq/123307453.html?s=01&amp;t=0" onmousedown=""> python数据开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海锐赢信息技术有限公司" href="https://jobs.51job.com/all/co3260759.html">上海锐赢信息技术有限公司</a></span> <span class="t3">上海-虹口区</span> <span class="t4">1-1.5万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="121701741" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai/121701741.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海森松制药设备工程有限公司" href="https://jobs.51job.com/all/co2550408.html">上海森松制药设备工程有限公司</a></span> <span class="t3">上海</span> <span class="t4">15-20万/年</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="123112955" jt="0" style="display:none"> <span> <a target="_blank" title="1131BX-python开发工程师" href="https://jobs.51job.com/shanghai-pdxq/123112955.html?s=01&amp;t=0" onmousedown=""> 1131BX-python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="平安科技(深圳)有限公司" href="https://jobs.51job.com/all/co2155678.html">平安科技(深圳)有限公司</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">2-2.5万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="120097999" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-xhq/120097999.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="中国太平洋保险(集团)股份有限公司" href="https://jobs.51job.com/all/co5419606.html">中国太平洋保险(集团)股份有限公...</a></span> <span class="t3">上海-徐汇区</span> <span class="t4">15-25万/年</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="123329863" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-pdxq/123329863.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="巴乐兔-快乐租房" href="https://jobs.51job.com/all/co3545280.html">巴乐兔-快乐租房</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">1-2万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="123316215" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-xhq/123316215.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海舟恩信息技术有限公司" href="https://jobs.51job.com/all/co3400101.html">上海舟恩信息技术有限公司</a></span> <span class="t3">上海-徐汇区</span> <span class="t4">1.2-1.6万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="123138868" jt="0" style="display:none"> <span> <a target="_blank" title="测试开发工程师(python)" href="https://jobs.51job.com/shanghai-xhq/123138868.html?s=01&amp;t=0" onmousedown=""> 测试开发工程师(python) </a> </span> </p> <span class="t2"><a target="_blank" title="杉德支付网络服务发展有限公司" href="https://jobs.51job.com/all/co2598882.html">杉德支付网络服务发展有限公司</a></span> <span class="t3">上海-徐汇区</span> <span class="t4">1-1.5万/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="120436621" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-xhq/120436621.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海牵翼网络科技有限公司" href="https://jobs.51job.com/all/co3698602.html">上海牵翼网络科技有限公司</a></span> <span class="t3">上海-徐汇区</span> <span class="t4">7-8千/月</span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="115980776" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://51rz.51job.com/job.html?jobid=115980776" onmousedown="jobview('115980776');"> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="“前程无忧”51job.com(上海)" href="https://51rz.51job.com/job.html?jobid=71752221&amp;coid=1249">“前程无忧”51job.com(上海)</a></span> <span class="t3">上海</span> <span class="t4"></span> <span class="t5">07-05</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="114088822" jt="0" style="display:none"> <span> <a target="_blank" title="python算法开发" href="https://jobs.51job.com/shanghai-pdxq/114088822.html?s=01&amp;t=0" onmousedown=""> python算法开发 </a> </span> </p> <span class="t2"><a target="_blank" title="上海慧度至明信息科技有限公司" href="https://jobs.51job.com/all/co5518781.html">上海慧度至明信息科技有限公司</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">1-1.5万/月</span> <span class="t5">07-04</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="120694247" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师(***)" href="https://jobs.51job.com/shanghai/120694247.html?s=01&amp;t=0" onmousedown=""> Python开发工程师(***) </a> </span> </p> <span class="t2"><a target="_blank" title="上海铠卡医疗器械贸易有限公司" href="https://jobs.51job.com/all/co3962749.html">上海铠卡医疗器械贸易有限公司</a></span> <span class="t3">上海</span> <span class="t4">1000元/天</span> <span class="t5">07-04</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="120029449" jt="0" style="display:none"> <span> <a target="_blank" title="Python 高级开发工程师或开发经理" href="https://jobs.51job.com/shanghai/120029449.html?s=01&amp;t=0" onmousedown=""> Python 高级开发工程师或开发经理 </a> </span> </p> <span class="t2"><a target="_blank" title="常州汉器信息技术有限公司" href="https://jobs.51job.com/all/co4230517.html">常州汉器信息技术有限公司</a></span> <span class="t3">上海</span> <span class="t4">1-3万/月</span> <span class="t5">07-04</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="122730082" jt="0" style="display:none"> <span> <a target="_blank" title="Python高级讲师" href="https://jobs.51job.com/shanghai-pdxq/122730082.html?s=01&amp;t=0" onmousedown=""> Python高级讲师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海尚学堂智能科技有限公司" href="https://jobs.51job.com/all/co5187327.html">上海尚学堂智能科技有限公司</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">1-2万/月</span> <span class="t5">07-04</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="115310459" jt="0" style="display:none"> <span> <a target="_blank" title="python开发" href="https://jobs.51job.com/shanghai-xhq/115310459.html?s=01&amp;t=0" onmousedown=""> python开发 </a> </span> </p> <span class="t2"><a target="_blank" title="上海坤雷实业有限公司" href="https://jobs.51job.com/all/co5110995.html">上海坤雷实业有限公司</a></span> <span class="t3">上海-徐汇区</span> <span class="t4">6-8千/月</span> <span class="t5">07-04</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="121936358" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-cnq/121936358.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海沪万智能科技有限公司" href="https://jobs.51job.com/all/co3899562.html">上海沪万智能科技有限公司</a></span> <span class="t3">上海-长宁区</span> <span class="t4">0.7-1.5万/月</span> <span class="t5">07-04</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="122647046" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-xhq/122647046.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海悦米信息技术有限公司" href="https://jobs.51job.com/all/co3951454.html">上海悦米信息技术有限公司</a></span> <span class="t3">上海-徐汇区</span> <span class="t4">1.5-2万/月</span> <span class="t5">07-04</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="121371720" jt="0" style="display:none"> <span> <a target="_blank" title="Python/Django开发" href="https://jobs.51job.com/shanghai-jaq/121371720.html?s=01&amp;t=0" onmousedown=""> Python/Django开发 </a> </span> </p> <span class="t2"><a target="_blank" title="上海锐成信息科技有限公司" href="https://jobs.51job.com/all/co2812972.html">上海锐成信息科技有限公司</a></span> <span class="t3">上海-静安区</span> <span class="t4">0.8-1.2万/月</span> <span class="t5">07-04</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="123279346" jt="0" style="display:none"> <span> <a target="_blank" title="python后端开发工程师" href="https://jobs.51job.com/shanghai-mhq/123279346.html?s=01&amp;t=0" onmousedown=""> python后端开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海非夕机器人科技有限公司" href="https://jobs.51job.com/all/co4671974.html">上海非夕机器人科技有限公司</a></span> <span class="t3">上海-闵行区</span> <span class="t4">1.5-3万/月</span> <span class="t5">07-04</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="123277415" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-xhq/123277415.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="广州嘉为科技有限公司" href="https://jobs.51job.com/all/co2287694.html">广州嘉为科技有限公司</a></span> <span class="t3">上海-徐汇区</span> <span class="t4">1-1.5万/月</span> <span class="t5">07-04</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="121583766" jt="0" style="display:none"> <span> <a target="_blank" title="python架构师" href="https://jobs.51job.com/shanghai-pdxq/121583766.html?s=01&amp;t=0" onmousedown=""> python架构师 </a> </span> </p> <span class="t2"><a target="_blank" title="新环康安(深圳)发展有限公司" href="https://jobs.51job.com/all/co4865175.html">新环康安(深圳)发展有限公司</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">1.4-4万/月</span> <span class="t5">07-03</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="121502945" jt="0" style="display:none"> <span> <a target="_blank" title="数据管理工程师(vector SQL python)" href="https://jobs.51job.com/shanghai/121502945.html?s=01&amp;t=0" onmousedown=""> 数据管理工程师(vector SQL python) </a> </span> </p> <span class="t2"><a target="_blank" title="高蓓珥派珀管理咨询(上海)有限公司" href="https://jobs.51job.com/all/co3463936.html">高蓓珥派珀管理咨询(上海)有限公...</a></span> <span class="t3">上海</span> <span class="t4">2-3万/月</span> <span class="t5">07-03</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="122575049" jt="0" style="display:none"> <span> <a target="_blank" title="Python技术经理" href="https://jobs.51job.com/shanghai-mhq/122575049.html?s=01&amp;t=0" onmousedown=""> Python技术经理 </a> </span> </p> <span class="t2"><a target="_blank" title="聚时科技(上海)有限公司" href="https://jobs.51job.com/all/co5194824.html">聚时科技(上海)有限公司</a></span> <span class="t3">上海-闵行区</span> <span class="t4">40-50万/年</span> <span class="t5">07-03</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="122129651" jt="0" style="display:none"> <span> <a target="_blank" title="Java爬虫/python爬虫开发工程师" href="https://jobs.51job.com/shanghai-pdxq/122129651.html?s=01&amp;t=0" onmousedown=""> Java爬虫/python爬虫开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海新致软件股份有限公司" href="https://jobs.51job.com/all/co156132.html">上海新致软件股份有限公司</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">2-2.5万/月</span> <span class="t5">07-03</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="115319723" jt="0" style="display:none"> <span> <a target="_blank" title="Python高级开发工程师" href="https://jobs.51job.com/shanghai/115319723.html?s=01&amp;t=0" onmousedown=""> Python高级开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海百趣生物医学科技有限公司" href="https://jobs.51job.com/all/co5333373.html">上海百趣生物医学科技有限公司</a></span> <span class="t3">上海</span> <span class="t4">1-2.5万/月</span> <span class="t5">07-03</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="120957115" jt="0" style="display:none"> <span> <a target="_blank" title="Python高级开发工程师" href="https://jobs.51job.com/shanghai-pdxq/120957115.html?s=01&amp;t=0" onmousedown=""> Python高级开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="达观数据" href="https://jobs.51job.com/all/co4133721.html">达观数据</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">1.6-2.5万/月</span> <span class="t5">07-03</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="120532783" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai/120532783.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海占域实业有限公司" href="https://jobs.51job.com/all/co4477690.html">上海占域实业有限公司</a></span> <span class="t3">上海</span> <span class="t4">6-8千/月</span> <span class="t5">07-03</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="117622468" jt="0" style="display:none"> <span> <a target="_blank" title="python开发" href="https://jobs.51job.com/shanghai-hkq/117622468.html?s=01&amp;t=0" onmousedown=""> python开发 </a> </span> </p> <span class="t2"><a target="_blank" title="深圳市若昕科技有限公司" href="https://jobs.51job.com/all/co5613542.html">深圳市若昕科技有限公司</a></span> <span class="t3">上海-虹口区</span> <span class="t4">2-3万/月</span> <span class="t5">07-03</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="121944519" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-pdxq/121944519.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="HCL Technologies (Shanghai) Limited" href="https://jobs.51job.com/all/co2137128.html">HCL Technologies (Shanghai) Lim...</a></span> <span class="t3">上海-浦东新区</span> <span class="t4">1.6-2万/月</span> <span class="t5">07-03</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="117307986" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师" href="https://jobs.51job.com/shanghai-mhq/117307986.html?s=01&amp;t=0" onmousedown=""> Python开发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="上海图灵医疗科技有限公司" href="https://jobs.51job.com/all/co2919838.html">上海图灵医疗科技有限公司</a></span> <span class="t3">上海-闵行区</span> <span class="t4">0.8-1万/月</span> <span class="t5">07-03</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="123022767" jt="0" style="display:none"> <span> <a target="_blank" title="Python开发工程师(英文)" href="https://jobs.51job.com/shanghai-xhq/123022767.html?s=01&amp;t=0" onmousedown=""> Python开发工程师(英文) </a> </span> </p> <span class="t2"><a target="_blank" title="上海伊库伊库网络科技有限公司" href="https://jobs.51job.com/all/co5872598.html">上海伊库伊库网络科技有限公司</a></span> <span class="t3">上海-徐汇区</span> <span class="t4">1.8-3万/月</span> <span class="t5">07-03</span> </div> <div class="el"> <p class="t1 "> <em class="check" name="delivery_em" onclick="checkboxClick(this)"></em> <input class="checkbox" type="checkbox" name="delivery_jobid" value="122999465" jt="0" style="display:none"> <span> <a target="_blank" title="高级Python研发工程师" href="https://jobs.51job.com/shanghai-cnq/122999465.html?s=01&amp;t=0" onmousedown=""> 高级Python研发工程师 </a> </span> </p> <span class="t2"><a target="_blank" title="繁翰信息技术(上海)有限公司" href="https://jobs.51job.com/all/co5367238.html">繁翰信息技术(上海)有限公司</a></span> <span class="t3">上海-长宁区</span> <span class="t4">2-3万/月</span> <span class="t5">07-03</span> </div> <!--列表表格 END--> <div class="dw_line"></div> <!--分页--> <div class="dw_page"> <div class="p_box"> <div class="p_wp"> <div class="p_in"> <ul> <li class="bk"><span>上一页</span></li> <li class="on">1</li> <li><a href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,2.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">2</a></li> <li><a href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,3.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">3</a></li> <li><a href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,4.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">4</a></li> <li><a href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,5.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">5</a></li> <li><a href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,6.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">6</a></li> <li class="bk"><a href="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,2.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare=">下一页</a></li> </ul> <input type="hidden" id="hidTotalPage" value="136"> <span class="td">共136页,到第</span><input id="jump_page" class="mytxt" type="text" value="1"><span class="td">页</span><span class="og_but" onclick="jumpPage('136');">确定</span> </div> </div> </div> </div> <!--分页 END--> <div class="clear"></div> <a href="#top" id="goTop" style="display: none;">回到<br>顶部</a> <a href="//i.51job.com/userset/advice.php?from=search" target="_blank" class="dw_fb"></a> <!-- BANNER 广告 --> <div class="mainleft s_search search_btm0"> <table border="0" cellspacing="0" cellpadding="4"><tbody><tr> <td><a adid="33591245" onmousedown="return AdsClick(33591245)" href="https://companyadc.51job.com/companyads/ads/34/33592/33591223/index.htm" title="上海亿通国际股份有限公司" target="_blank" onfocus="blur()"><img src="//img05.51jobcdn.com/im/images/ads/34/33592/33591245/aa.gif" border="0" width="150" height="60"></a></td> <td><a adid="33778137" onmousedown="return AdsClick(33778137)" href="https://companyadc.51job.com/companyads/ads/34/33779/33778078/index.htm" title="苏州柯瑞机械有限公司" target="_blank" onfocus="blur()"><img src="//img05.51jobcdn.com/im/images/ads/34/33779/33778137/kraa.gif" border="0" width="150" height="60"></a></td> <td><a adid="33683731" onmousedown="return AdsClick(33683731)" href="https://companyadc.51job.com/companyads/ads/34/33684/33683660/index.htm" title="深圳波洛斯科技有限公司" target="_blank" onfocus="blur()"><img src="//img05.51jobcdn.com/im/images/ads/34/33684/33683731/bs.gif" border="0" width="150" height="60"></a></td> <td><a adid="33929151" onmousedown="return AdsClick(33929151)" href="https://companyadc.51job.com/companyads/ads/34/33930/33929151/index.htm" title="古驰(中国)贸易有限公司" target="_blank" onfocus="blur()"><img src="//img05.51jobcdn.com/im/images/ads/34/33930/33929155/gc60.gif" border="0" width="150" height="60"></a></td> <td><a adid="33873757" onmousedown="return AdsClick(33873757)" href="https://companyadc.51job.com/companyads/ads/34/33874/33873757/index.htm" title="广州点聚信息科技有限公司" target="_blank" onfocus="blur()"><img src="//img05.51jobcdn.com/im/images/ads/34/33874/33873757/dj.gif" border="0" width="150" height="60"></a></td> <td><a adid="33728677" onmousedown="return AdsClick(33728677)" href="https://companyadc.51job.com/companyads/ads/34/33704/33703724/index.htm" title="深圳市美而佳科技有限公司" target="_blank" onfocus="blur()"><img src="//img05.51jobcdn.com/im/images/ads/34/33729/33728677/mer.gif" border="0" width="150" height="60"></a></td> </tr> </tbody></table> </div> <!-- 广告 end --> <div class="tResult_bottom_roll tResult_bottom_roll_w "> <!--地区招聘 start --> <div class="rollBox"> <div id="announcement"> <div id="announcementbody"> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/baotou">包头招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shijiazhuang">石家庄招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/tianjin">天津招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/taiyuan">太原招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/huhhot">呼和浩特招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/baoding">保定招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/langfang">廊坊招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/qinhuangdao">秦皇岛招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/tangshan">唐山招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/handan">邯郸招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/errduosi">鄂尔多斯招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changchun">长春招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/dalian">大连招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shenyang">沈阳招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/harbin">哈尔滨招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jilin">吉林招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/anshan">鞍山招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yingkou">营口招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/fushun">抚顺招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/dandong">丹东招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/tieling">铁岭招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/daqing">大庆招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nanjing">南京招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nanchang">南昌招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/ningbo">宁波招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nantong">南通招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changzhou">常州招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/qingdao">青岛招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/quanzhou">泉州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/suzhou">苏州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shaoxing">绍兴招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/fuzhou">福州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/taizhoue">台州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/wuxi">无锡招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/wenzhou">温州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/hangzhou">杭州招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/hefei">合肥招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xiamen">厦门招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xuzhou">徐州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jinan">济南招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jiaxing">嘉兴招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jinhua">金华招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yantai">烟台招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yangzhou">扬州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/kunshan">昆山招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/changshu">常熟招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhangjiagang">张家港招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yancheng">盐城招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/lianyungang">连云港招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/huaian">淮安招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/taizhou">泰州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhangzhou">漳州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhenjiang">镇江招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/linyi">临沂招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/wuhu">芜湖招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/weifang">潍坊招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/weihai">威海招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/huzhou">湖州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yiwu">义乌招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zibo">淄博招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jining">济宁招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nanning">南宁招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changsha">长沙招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/dongguan">东莞招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/sanya">三亚招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/wuhan">武汉招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhengzhou">郑州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhongshan">中山招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhuhai">珠海招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/haikou">海口招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/foshan">佛山招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/huizhou">惠州招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/jiangmen">江门招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shantou">汕头招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhanjiang">湛江招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/qingyuan">清远招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/luoyang">洛阳招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yichang">宜昌招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xiangyang">襄阳招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jingzhou">荆州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhuzhou">株洲招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/hengyang">衡阳招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xiangtan">湘潭招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changde">常德招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/liuzhou">柳州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/chengdu">成都招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/chongqing">重庆招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/guiyang">贵阳招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/kunming">昆明招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/mianyang">绵阳招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/urumqi">乌鲁木齐招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xian">西安招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/lanzhou">兰州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xianyang">咸阳招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yinchuan">银川招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/baotou">包头人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shijiazhuang">石家庄人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/tianjin">天津人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/taiyuan">太原人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/huhhot">呼和浩特人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/baoding">保定人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/langfang">廊坊人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/qinhuangdao">秦皇岛人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/tangshan">唐山人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/handan">邯郸人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/errduosi">鄂尔多斯人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changchun">长春人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/dalian">大连人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shenyang">沈阳人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/harbin">哈尔滨人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jilin">吉林人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/anshan">鞍山人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yingkou">营口人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/fushun">抚顺人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/dandong">丹东人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/tieling">铁岭人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/daqing">大庆人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nanjing">南京人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nanchang">南昌人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/ningbo">宁波人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nantong">南通人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changzhou">常州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/qingdao">青岛人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/quanzhou">泉州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/suzhou">苏州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shaoxing">绍兴人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/fuzhou">福州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/taizhoue">台州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/wuxi">无锡人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/wenzhou">温州人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/hangzhou">杭州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/hefei">合肥人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xiamen">厦门人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xuzhou">徐州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jinan">济南人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jiaxing">嘉兴人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jinhua">金华人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/yantai">烟台人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yangzhou">扬州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/kunshan">昆山人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changshu">常熟人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhangjiagang">张家港人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yancheng">盐城人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/lianyungang">连云港人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/huaian">淮安人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/taizhou">泰州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhangzhou">漳州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhenjiang">镇江人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/linyi">临沂人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/wuhu">芜湖人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/weifang">潍坊人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/weihai">威海人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/huzhou">湖州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yiwu">义乌人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zibo">淄博人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jining">济宁人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nanning">南宁人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changsha">长沙人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/dongguan">东莞人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/sanya">三亚人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/wuhan">武汉人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhengzhou">郑州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhongshan">中山人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhuhai">珠海人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/haikou">海口人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/foshan">佛山人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/huizhou">惠州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jiangmen">江门人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shantou">汕头人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhanjiang">湛江人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/qingyuan">清远人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/luoyang">洛阳人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/yichang">宜昌人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xiangyang">襄阳人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jingzhou">荆州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhuzhou">株洲人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/hengyang">衡阳人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xiangtan">湘潭人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changde">常德人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/liuzhou">柳州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/chengdu">成都人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/chongqing">重庆人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/guiyang">贵阳人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/kunming">昆明人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/mianyang">绵阳人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/urumqi">乌鲁木齐人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/xian">西安人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/lanzhou">兰州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xianyang">咸阳人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yinchuan">银川人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/baotou">包头招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shijiazhuang">石家庄招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/tianjin">天津招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/taiyuan">太原招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/huhhot">呼和浩特招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/baoding">保定招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/langfang">廊坊招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/qinhuangdao">秦皇岛招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/tangshan">唐山招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/handan">邯郸招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/errduosi">鄂尔多斯招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changchun">长春招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/dalian">大连招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shenyang">沈阳招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/harbin">哈尔滨招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jilin">吉林招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/anshan">鞍山招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yingkou">营口招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/fushun">抚顺招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/dandong">丹东招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/tieling">铁岭招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/daqing">大庆招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nanjing">南京招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nanchang">南昌招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/ningbo">宁波招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nantong">南通招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changzhou">常州招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/qingdao">青岛招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/quanzhou">泉州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/suzhou">苏州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shaoxing">绍兴招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/fuzhou">福州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/taizhoue">台州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/wuxi">无锡招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/wenzhou">温州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/hangzhou">杭州招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/hefei">合肥招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xiamen">厦门招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xuzhou">徐州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jinan">济南招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jiaxing">嘉兴招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jinhua">金华招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yantai">烟台招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yangzhou">扬州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/kunshan">昆山招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/changshu">常熟招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhangjiagang">张家港招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yancheng">盐城招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/lianyungang">连云港招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/huaian">淮安招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/taizhou">泰州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhangzhou">漳州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhenjiang">镇江招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/linyi">临沂招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/wuhu">芜湖招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/weifang">潍坊招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/weihai">威海招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/huzhou">湖州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yiwu">义乌招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zibo">淄博招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jining">济宁招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nanning">南宁招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changsha">长沙招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/dongguan">东莞招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/sanya">三亚招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/wuhan">武汉招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhengzhou">郑州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhongshan">中山招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhuhai">珠海招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/haikou">海口招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/foshan">佛山招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/huizhou">惠州招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/jiangmen">江门招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shantou">汕头招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhanjiang">湛江招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/qingyuan">清远招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/luoyang">洛阳招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yichang">宜昌招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xiangyang">襄阳招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jingzhou">荆州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhuzhou">株洲招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/hengyang">衡阳招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xiangtan">湘潭招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changde">常德招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/liuzhou">柳州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/chengdu">成都招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/chongqing">重庆招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/guiyang">贵阳招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/kunming">昆明招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/mianyang">绵阳招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/urumqi">乌鲁木齐招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xian">西安招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/lanzhou">兰州招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xianyang">咸阳招聘</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yinchuan">银川招聘</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/baotou">包头人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shijiazhuang">石家庄人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/tianjin">天津人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/taiyuan">太原人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/huhhot">呼和浩特人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/baoding">保定人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/langfang">廊坊人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/qinhuangdao">秦皇岛人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/tangshan">唐山人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/handan">邯郸人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/errduosi">鄂尔多斯人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changchun">长春人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/dalian">大连人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shenyang">沈阳人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/harbin">哈尔滨人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jilin">吉林人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/anshan">鞍山人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yingkou">营口人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/fushun">抚顺人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/dandong">丹东人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/tieling">铁岭人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/daqing">大庆人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nanjing">南京人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nanchang">南昌人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/ningbo">宁波人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nantong">南通人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changzhou">常州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/qingdao">青岛人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/quanzhou">泉州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/suzhou">苏州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shaoxing">绍兴人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/fuzhou">福州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/taizhoue">台州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/wuxi">无锡人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/wenzhou">温州人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/hangzhou">杭州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/hefei">合肥人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xiamen">厦门人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xuzhou">徐州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jinan">济南人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jiaxing">嘉兴人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jinhua">金华人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/yantai">烟台人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yangzhou">扬州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/kunshan">昆山人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changshu">常熟人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhangjiagang">张家港人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yancheng">盐城人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/lianyungang">连云港人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/huaian">淮安人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/taizhou">泰州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhangzhou">漳州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhenjiang">镇江人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/linyi">临沂人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/wuhu">芜湖人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/weifang">潍坊人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/weihai">威海人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/huzhou">湖州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yiwu">义乌人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zibo">淄博人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jining">济宁人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/nanning">南宁人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changsha">长沙人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/dongguan">东莞人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/sanya">三亚人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/wuhan">武汉人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhengzhou">郑州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhongshan">中山人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhuhai">珠海人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/haikou">海口人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/foshan">佛山人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/huizhou">惠州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jiangmen">江门人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/shantou">汕头人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhanjiang">湛江人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/qingyuan">清远人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/luoyang">洛阳人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/yichang">宜昌人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xiangyang">襄阳人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/jingzhou">荆州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/zhuzhou">株洲人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/hengyang">衡阳人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xiangtan">湘潭人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/changde">常德人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/liuzhou">柳州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/chengdu">成都人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/chongqing">重庆人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/guiyang">贵阳人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/kunming">昆明人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/mianyang">绵阳人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/urumqi">乌鲁木齐人才网</a></li> </ul> <ul><li style="font-size:14px;color:#666;">地区人才网招聘</li> <li class="st_one"><a target="_blank" href="//www.51job.com/xian">西安人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/lanzhou">兰州人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/xianyang">咸阳人才网</a></li><li class="st_one"><a target="_blank" href="//www.51job.com/yinchuan">银川人才网</a></li> </ul> </div> </div> </div> <!--地区招聘 end--> <div class="rollBox"> <h3>个人简历模版-简历指导</h3> <div class="rollBox_twoRow f14"> <div id="resumeGuideTopicsBody"><div id="marqueeBox" style="overflow:hidden;height:48px"><div><ul class="resumeGuide"><li><a target="_blank" href="//jianli.51job.com/biaoge/" title="个人简历表格"><strong>个人简历表格</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/biaoge/1323.html" title="电子商务专业本科毕业生个人简历表格">电子商务专业...</a></li><li><a target="_blank" href="//jianli.51job.com/xiaohui/" title="高校校徽下载"><strong>高校校徽下载</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/xiaohui/346.html" title="上海理工大学">上海理工大学</a></li><li><a target="_blank" href="//jianli.51job.com/fengmian/" title="简历封面"><strong>简历封面</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/fengmian/9801.html" title="[简历封面下载]激情">[简历封面下载]激...</a></li><li><a target="_blank" href="//jianli.51job.com/gaoxiao/" title="高校简历模板"><strong>高校简历模板</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/gaoxiao/211.html" title="杭州师范大学高校简历模版">杭州师范大学...</a></li><li><a target="_blank" href="//jianli.51job.com/zhuanye/" title="专业简历模板"><strong>专业简历模板</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/zhuanye/187.html" title="经营管理专业">经营管理专业</a></li><li><a target="_blank" href="//jianli.51job.com/jianliyangben/" title="简历样本"><strong>简历样本</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/jianliyangben/104.html" title="人力资源总监简历样本">人力资源总监简历...</a></li><li><a target="_blank" href="//jianli.51job.com/jianlifanwen/" title="简历范文"><strong>简历范文</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/jianlifanwen/14356.html" title="商务总监简历范文">商务总监简历范文</a></li><li><a target="_blank" href="//jianli.51job.com/zhuanye/" title="专业简历模板"><strong>专业简历模板</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/zhuanye/192.html" title="广播电视新闻专业">广播电视新闻...</a></li></ul></div><div><ul class="resumeGuide"><li><a target="_blank" href="//jianli.51job.com/biaoge/" title="个人简历表格"><strong>个人简历表格</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/biaoge/1271.html" title="应届毕业生个人简历表格">应届毕业生个...</a></li><li><a target="_blank" href="//jianli.51job.com/gaoxiao/" title="高校简历模板"><strong>高校简历模板</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/gaoxiao/128.html" title="同济大学高校简历模版">同济大学高校...</a></li></ul></div></div></div> <div id="resumeGuideTopics" style="display:none"> <div><ul class="resumeGuide"><li><a target="_blank" href="//jianli.51job.com/fengmian/" title="简历封面"><strong>简历封面</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/fengmian/9795.html" title="[简历封面下载]机会">[简历封面下载]机...</a></li><li><a target="_blank" href="//jianli.51job.com/jianlifanwen/" title="简历范文"><strong>简历范文</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/jianlifanwen/14367.html" title="图书编目加工部主管简历范文">图书编目加工部主...</a></li><li><a target="_blank" href="//jianli.51job.com/biaoge/" title="个人简历表格"><strong>个人简历表格</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/biaoge/1329.html" title="互联网开发个人简历表格">互联网开发个...</a></li><li><a target="_blank" href="//jianli.51job.com/jianliyangben/" title="简历样本"><strong>简历样本</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/jianliyangben/128.html" title="中国现当代文学简历样本">中国现当代文学简...</a></li><li><a target="_blank" href="//jianli.51job.com/gaoxiao/" title="高校简历模板"><strong>高校简历模板</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/gaoxiao/193.html" title="南昌航空大学高校简历模版">南昌航空大学...</a></li><li><a target="_blank" href="//jianli.51job.com/zhuanye/" title="专业简历模板"><strong>专业简历模板</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/zhuanye/196.html" title="冶金工程专业">冶金工程专业</a></li><li><a target="_blank" href="//jianli.51job.com/xiaohui/" title="高校校徽下载"><strong>高校校徽下载</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/xiaohui/347.html" title="深圳大学">深圳大学</a></li><li><a target="_blank" href="//jianli.51job.com/jianliyangben/" title="简历样本"><strong>简历样本</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/jianliyangben/126.html" title="业务员简历样本">业务员简历样本</a></li></ul></div><div><ul class="resumeGuide"><li><a target="_blank" href="//jianli.51job.com/biaoge/" title="个人简历表格"><strong>个人简历表格</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/biaoge/1323.html" title="电子商务专业本科毕业生个人简历表格">电子商务专业...</a></li><li><a target="_blank" href="//jianli.51job.com/xiaohui/" title="高校校徽下载"><strong>高校校徽下载</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/xiaohui/346.html" title="上海理工大学">上海理工大学</a></li><li><a target="_blank" href="//jianli.51job.com/fengmian/" title="简历封面"><strong>简历封面</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/fengmian/9801.html" title="[简历封面下载]激情">[简历封面下载]激...</a></li><li><a target="_blank" href="//jianli.51job.com/gaoxiao/" title="高校简历模板"><strong>高校简历模板</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/gaoxiao/211.html" title="杭州师范大学高校简历模版">杭州师范大学...</a></li><li><a target="_blank" href="//jianli.51job.com/zhuanye/" title="专业简历模板"><strong>专业简历模板</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/zhuanye/187.html" title="经营管理专业">经营管理专业</a></li><li><a target="_blank" href="//jianli.51job.com/jianliyangben/" title="简历样本"><strong>简历样本</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/jianliyangben/104.html" title="人力资源总监简历样本">人力资源总监简历...</a></li><li><a target="_blank" href="//jianli.51job.com/jianlifanwen/" title="简历范文"><strong>简历范文</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/jianlifanwen/14356.html" title="商务总监简历范文">商务总监简历范文</a></li><li><a target="_blank" href="//jianli.51job.com/zhuanye/" title="专业简历模板"><strong>专业简历模板</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/zhuanye/192.html" title="广播电视新闻专业">广播电视新闻...</a></li></ul></div><div><ul class="resumeGuide"><li><a target="_blank" href="//jianli.51job.com/biaoge/" title="个人简历表格"><strong>个人简历表格</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/biaoge/1271.html" title="应届毕业生个人简历表格">应届毕业生个...</a></li><li><a target="_blank" href="//jianli.51job.com/gaoxiao/" title="高校简历模板"><strong>高校简历模板</strong></a><span style="color:#266EBA"> | </span><a target="_blank" href="//jianli.51job.com/gaoxiao/128.html" title="同济大学高校简历模版">同济大学高校...</a></li></ul></div> </div> </div> </div> </div> <!-- getPageFormHtml start --> <form name="pageForm" action="" method="post" style="display:none"> <input type="hidden" name="postchannel" value="0000"> <input type="hidden" name="jobarea" value="020000"> <input type="hidden" name="district" value="000000"> <input type="hidden" name="funtype" value="0000"> <input type="hidden" name="industrytype" value="00"> <input type="hidden" name="issuedate" value="9"> <input type="hidden" name="keywordtype" value="2"> <input type="hidden" name="keyword" value="python"> <input type="hidden" name="curr_page" value="1"> <input type="hidden" name="dibiaoid" value="0"> <input type="hidden" name="line" value=""> <input type="hidden" name="jobterm" value="99"> <input type="hidden" name="welfare" value=""> <input type="hidden" name="workyear" value="99" id="workyear"> <input type="hidden" name="providesalary" value="99" id="providesalary"> <input type="hidden" name="cotype" value="99" id="cotype"> <input type="hidden" name="degreefrom" value="99" id="degreefrom"> <input type="hidden" name="companysize" value="99" id="companysize"> <!-- 多选 start --> <input type="hidden" name="cotype_tmp" value="99" id="cotype_tmp"> <input type="hidden" name="workyear_tmp" value="99" id="workyear_tmp"> <input type="hidden" name="degreefrom_tmp" value="99" id="degreefrom_tmp"> <input type="hidden" name="companysize_tmp" value="99" id="companysize_tmp"> <input type="hidden" name="providesalary_tmp" value="99" id="providesalary_tmp"> <!-- 多选 end --> <input type="hidden" name="ord_field" value="0"> <!-- 由于JS中需要获取该值, 因此给出默认值, 之后全部升级完成, 再从JS中整体的删除 start --> <input type="hidden" name="address" value="" id="address"> <input type="hidden" name="radius" value="-1" id="radius"> <!-- end --> <!-- search start --> <input type="hidden" name="jobid_count" value="6793"> <!-- search end --> <input type="hidden" name="pagejump" value="https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,<<pagecode>>.html?lang=c&amp;postchannel=0000&amp;workyear=99&amp;cotype=99&amp;degreefrom=99&amp;jobterm=99&amp;companysize=99&amp;ord_field=0&amp;dibiaoid=0&amp;line=&amp;welfare="> </form> <!-- getPageFormHtml end --> <script> $(function(){//返回顶部 var stop=''; $(window).scroll(function(){ $('#goTop').hide(); stop=$(this).scrollTop(); if(stop>0){ $('#goTop').show(); }else{ $('#goTop').hide(); } }); }) </script> </div> </div> <!--引用js--> <script type="text/javascript" src="//js.51jobcdn.com/in/resource/js/2020/search/common.a8c323f7.js"></script> <script type="text/javascript" src="//js.51jobcdn.com/in/resource/js/2020/search/searchResult.6a55edcf.js"></script> <div class="footer"> <div class="in"> <div class="nag"> <div class="e e_first"> <label>销售热线:</label>400-886-0051&nbsp;&nbsp;027-87810888<br> <label>客服热线:</label>400-620-5100<br> <label>Email:</label><a href="mailto:club@51job.com" rel="external nofollow">club@51job.com</a>(个人)<br> <a href="mailto:hr@51job.com" rel="external nofollow">hr@51job.com</a>(公司) </div> <div class="e"> <strong>简介</strong><br> <a href="//www.51job.com/bo/AboutUs.php" target="_blank">关于我们</a><br> <a href="//www.51job.com/bo/service.php" target="_blank">服务声明</a><br> <a href="https://media.51job.com/media.php" target="_blank">媒体报道</a><br> <a href="https://ir.51job.com/ir/IRMain.php" target="_blank">Investor Relations</a> </div> <div class="e"> <strong>合作</strong><br> <a href="//www.51job.com/bo/jobs/new_joinus.php" target="_blank">加入我们</a><br> <a href="//www.51job.com/bo/contact.php" target="_blank">联系我们</a><br> <a href="//www.51job.com/link.php" target="_blank">友情链接</a> </div> <div class="e"> <strong>帮助</strong><br> <a href="https://help.51job.com/home.html" target="_blank">帮助中心</a><br> <a href="https://help.51job.com/qa.html?from=b" target="_blank">常见问题</a><br> <a href="https://help.51job.com/guide.html?from=d" target="_blank">新手引导</a> </div> <div class="e"> <strong>导航</strong><br> <a href="//www.51job.com/sitemap/site_Navigate.php" target="_blank">网站地图</a><br> <a href="https://search.51job.com" target="_blank">职位搜索</a><br> <a href="//i.51job.com/resume/resume_center.php?lang=c">简历中心</a><br> <a href="//company.51job.com" target="_blank">企业名录</a> </div> <div class="code c_first"> <img width="80" height="80" src="//img02.51jobcdn.com/im/2016/code/new_app.png" alt="APP下载"> <span><a href="http://app.51job.com/index.html">APP下载</a></span> </div> <div class="code"> <img width="80" height="80" src="//img01.51jobcdn.com/im/2016/code/web_fuwuhao_bottom.png" alt="微信服务号"> <span>微信服务号</span> </div> <div class="clear"></div> </div> <p class="note nag"> <span>未经51Job同意,不得转载本网站之所有招聘信息及作品 | 无忧工作网版权所有©1999-2020</span> </p> </div> </div> </body></html> """ from scrapy import Selector sel=Selector(text=html) tag=sel.xpath("//*[@id='resultList']/div[4]/p/span/a/text()").extract() pass
[ "852060542@qq.com" ]
852060542@qq.com
2493121819f4293cfba205ebc383c3a318856a5b
28f17a8860e878c0d5dc0f8079c7bd4275c9570a
/scripts/GetOrfs.py
842e80593c80a149518e2a1e4245d14dacc9015c
[]
no_license
ymx0723/TRACR_RNA
fb35e834d59eb6ee9ddfa572f456b166014ea2b6
249ec97f3d50c20e46758923caaaab78ef151b3b
refs/heads/master
2023-04-26T16:09:53.902993
2021-06-02T20:44:53
2021-06-02T20:44:53
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,224
py
#Cock et al 2009. Biopython: freely available Python tools for computational #molecular biology and bioinformatics. Bioinformatics 25(11) 1422-3. import sys import re try: from Bio.Alphabet import generic_dna from Bio.Seq import Seq, reverse_complement, translate from Bio.SeqRecord import SeqRecord from Bio.SeqFeature import SeqFeature, FeatureLocation from Bio import SeqIO from Bio.Data import CodonTable except ImportError: sys.exit("Missing Biopython library") class GetORFs: table_obj = CodonTable.ambiguous_generic_by_id[1] seq_format = "fasta" starts = sorted(table_obj.start_codons) re_starts = re.compile("|".join(starts)) stops = sorted(table_obj.stop_codons) re_stops = re.compile("|".join(stops)) def __init__(self, inputfile, outputfile=None, cutoff=50,writeOutPut=True): self.inputFile = inputfile self.records = {} self.cutoff = cutoff self.outputFile = outputfile self.Seqlist = [] self.parseRecs() if writeOutPut: self.write() #self.data = [] def start_chop_and_trans(s, strict=True): """Returns offset, trimmed nuc, protein.""" if strict: assert s[-3:] in stops, s assert len(s) % 3 == 0 for match in re_starts.finditer(s): # Must check the start is in frame start = match.start() if start % 3 == 0: n = s[start:] assert len(n) % 3 == 0, "%s is len %i" % (n, len(n)) if strict: t = translate(n, 1, cds=True) else: t = "M" + translate(n[3:], 1, to_stop=True) # Use when missing stop codon, return start, n, t return None, None, None def break_up_frame(self, s): """Returns offset, nuc, protein.""" start = 0 for match in GetORFs.re_stops.finditer(s): index = match.start() + 3 if index % 3 != 0: continue n = s[start:index] offset = 0 t = translate(n, 1, to_stop=True) if n and len(t) >= 8: yield start + offset, n, t start = index if "open" == "open": # No stop codon, Biopython's strict CDS translate will fail n = s[start:] # Ensure we have whole codons # TODO - Try appending N instead? # TODO - Do the next four lines more elegantly if len(n) % 3: n = n[:-1] if len(n) % 3: n = n[:-1] offset = 0 t = translate(n, 1, to_stop=True) if n and len(t) >= 8: yield start + offset, n, t def get_all_peptides(self, nuc_seq): """Returns start, end, strand, nucleotides, protein. Co-ordinates are Python style zero-based. """ # TODO - Refactor to use a generator function (in start order) # rather than making a list and sorting? answer = [] full_len = len(nuc_seq) for frame in range(0, 3): for offset, n, t in self.break_up_frame(nuc_seq[frame:]): start = frame + offset # zero based answer.append((start, start + len(n), +1, n, t)) rc = reverse_complement(nuc_seq) for frame in range(0, 3): for offset, n, t in self.break_up_frame(rc[frame:]): start = full_len - frame - offset # zero based answer.append((start - len(n), start, -1, n, t)) answer.sort() return answer def parseRecs(self): in_count = 0 out_count = 0 for record in SeqIO.parse(self.inputFile, GetORFs.seq_format, generic_dna): self.records[record.id] = record for i, (f_start, f_end, f_strand, n, t) in enumerate(self.get_all_peptides(str(record.seq).upper())): if len(t) < self.cutoff:continue out_count += 1 if f_strand == +1: loc = "%i..%i" % (f_start + 1, f_end) else: loc = "complement(%i..%i)" % (f_start + 1, f_end) descr = "length %i aa, %i bp, from %s of %s" % (len(t), len(n), loc, record.description) fid = record.id + "_%s%i" % ("ORF", i + 1) t = SeqRecord(Seq(t), id=fid, name="", description=descr) ORF_Feature = SeqFeature(FeatureLocation(f_start + 1, f_end), type="CDS", strand=f_strand) ORF_Feature.qualifiers['label'] = [fid] self.records[record.id].features.append(ORF_Feature) self.Seqlist.append(t) in_count += 1 # print "Found %i %ss in %i sequences" % (out_count, "ORF", in_count) def write(self): with open(self.outputFile,"w") as fh: SeqIO.write(self.Seqlist,fh,"fasta") if __name__ == "__main__": fileName = sys.argv[1] outFile = sys.argv[2] cutoff = int(sys.argv[3]) GetORFs(fileName, outFile, cutoff) #print ("Hello world")
[ "dooley@iastate.edu" ]
dooley@iastate.edu
8744dbe0208ec7873af18b980f3728650adca7b0
10690bb92fdfca4607aa211568d288910028ffee
/py/travis-ci/u_boot_boardenv_evb-ast2500_qemu.py
f4b6b2728b319e1f246df1ebcb995958d9554c3e
[]
no_license
swarren/uboot-test-hooks
c792c8c55dcc635de958952a90e976e5d77ec37d
cf979fcf372c2483fb972fcc6486b8dfcf47dece
refs/heads/master
2021-04-15T12:23:24.659131
2020-09-22T18:27:34
2020-09-22T18:31:36
47,702,435
8
19
null
2020-08-12T22:24:08
2015-12-09T16:07:07
Python
UTF-8
Python
false
false
133
py
import travis_tftp env__spl_skipped = True env__net_dhcp_server = True env__net_tftp_readable_file = travis_tftp.file2env('u-boot')
[ "swarren@nvidia.com" ]
swarren@nvidia.com
7f0c40889719ed4363271fcadbb617d93f84cd8a
96a0184da0699b7f6188722245784696190fc7e9
/fennel/logging.py
d51cc59c70d8e87e0a74fee8a95798acf733bf0a
[ "MIT" ]
permissive
mjwestcott/fennel
a600bb1d1636c5138c7f748c1f0a5d8d94d04b61
f196ca8c43a1c6e319b413627d9771b957638e01
refs/heads/master
2022-12-09T07:44:24.939650
2020-08-20T22:35:52
2020-08-20T22:35:52
212,467,048
36
3
MIT
2022-12-08T10:54:38
2019-10-03T00:20:41
Python
UTF-8
Python
false
false
3,577
py
import datetime import logging import logging.config import os from io import StringIO from typing import Any, Dict import colorama import structlog def init_logging(level="debug", format="console"): level = level.upper() logging.config.dictConfig({ "version": 1, "disable_existing_loggers": True, "formatters": { "standard": { "format": "%(message)s", } }, "handlers": { "fennel.client": { "level": level, "formatter": "standard", "class": "logging.StreamHandler", "stream": "ext://sys.stderr", } }, "loggers": { "fennel.client": { "handlers": ["fennel.client"], "level": level, "propagate": False, }, "fennel.worker": { # To be used with a custom QueueHandler to prevent interleaving # among the multiple processes. "level": level, "propagate": False, }, }, }) structlog.configure( logger_factory=logging.getLogger, processors=[ _add_meta, structlog.stdlib.filter_by_level, structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, structlog.processors.UnicodeDecoder(), structlog.processors.JSONRenderer() if format == "json" else _renderer, ], ) def _add_meta(logger: str, method_name: str, event_dict: Dict) -> Dict: event_dict = { "event": event_dict.pop("event"), "exc_info": event_dict.pop("exc_info", None), "extra": event_dict, } if not event_dict["extra"]: event_dict.pop("extra") event_dict["timestamp"] = datetime.datetime.utcnow().isoformat() + "Z" event_dict["level"] = method_name.upper() event_dict["pid"] = os.getpid() return event_dict def _renderer(logger: str, method_name: str, event_dict: Dict) -> str: reset = colorama.Style.RESET_ALL bright = colorama.Style.BRIGHT dim = colorama.Style.DIM red = colorama.Fore.RED yellow = colorama.Fore.YELLOW blue = colorama.Fore.BLUE green = colorama.Fore.GREEN colours = { "CRITICAL": red + bright, "EXCEPTION": red + bright, "ERROR": red + bright, "WARNING": yellow + bright, "INFO": green + bright, "DEBUG": blue + bright, } s = StringIO() ts = event_dict.pop("timestamp", None) if ts: s.write(f"{reset}{dim}{str(ts)}{reset} ") level = event_dict.pop("level", None) if level: s.write(f"{colours[level]}{level:>9}{reset} ") event = event_dict.pop("event") s.write(f"{bright}{event:<17}{reset} ") pid = event_dict.pop("pid", None) if pid: s.write(f"{blue}pid{reset}={pid} ") def _format_extra(key: str, value: Any) -> None: s.write(f"{blue}{key}{reset}={value}{reset} ") extra = event_dict.pop("extra", {}) job = extra.pop("job", None) if job: for k, v in job.items(): _format_extra(k, v) for key, value in extra.items(): _format_extra(key, value) stack = event_dict.pop("stack", None) exc = event_dict.pop("exception", None) if stack is not None: s.write("\n" + stack) if exc is not None: s.write("\n\n" + "=" * 88 + "\n") if exc is not None: s.write("\n" + exc) return s.getvalue()
[ "m.westcott@gmail.com" ]
m.westcott@gmail.com
ec63b954fd448cd482cec2bfb15b88afbea89cc4
c3ff891e0e23c5f9488508d30349259cc6b64b4d
/python练习/基础代码/Demo33.py
20ad574ee408810bd6658c854a8dd2e8ce4e4a44
[]
no_license
JacksonMike/python_exercise
2af2b8913ec8aded8a17a98aaa0fc9c6ccd7ba53
7698f8ce260439abb3cbdf478586fa1888791a61
refs/heads/master
2020-07-14T18:16:39.265372
2019-08-30T11:56:29
2019-08-30T11:56:29
205,370,953
0
0
null
null
null
null
UTF-8
Python
false
false
157
py
infor = {"name":"Jim"} infor["age"] = 19#添加 infor["QQ"] = 10086 infor["QQ"] = 10085#修改 del infor["QQ"] #删除 print(infor.get("name"))#查询 a = {}
[ "2101706902@qq.com" ]
2101706902@qq.com
6de8613a89c8db45ba9ad5e574921df00b84f51e
0de3304ae3c6bd0a410fe0e9a392312918e8affd
/py_eyetracker_v1.0/utils/histogram/lsh_equalization.py
600c0d7bc640973e302c24ab6e88867b0337c3d7
[ "MIT" ]
permissive
michele-mada/cv-eyetracking-project-2017
66b5e5814480b49090dd9330c1902994d42498e7
605cff57307e7c9abdd7fe0a40a710fdd4bca0ad
refs/heads/master
2021-01-11T16:40:29.028013
2017-09-13T18:49:24
2017-09-13T18:49:24
80,136,774
1
3
null
null
null
null
UTF-8
Python
false
false
382
py
from utils.histogram.lsh import locality_sensitive_histogram_cl as locality_sensitive_histogram from utils.histogram.iif import illumination_invariant_features_cl as illumination_invariant_features def lsh_equalization(picture_float): histogram = locality_sensitive_histogram(picture_float) iif = illumination_invariant_features(picture_float, histogram) return iif
[ "michele.mm1234@gmail.com" ]
michele.mm1234@gmail.com
08281919e1db3db834e6f24964ad38bf0bd73d30
8c3b05b508007a44c2e7e141ad52dd573b318976
/log.py
5303edc8541fe04f8ed7f9a70d3bc0f2a72b45c7
[]
no_license
wang-ironman/SSA-and-VRG-for-pedestrian-detection
f282d3eedcffc442d0613752952dbeec7b0d4433
66b9b308392f8dc91b024593b8282c9fa884b4b1
refs/heads/master
2023-03-02T20:02:28.941903
2021-02-13T14:42:33
2021-02-13T14:42:33
232,329,239
6
0
null
null
null
null
UTF-8
Python
false
false
1,308
py
import logging import time,os,sys from utils.mkdir import mkdir if sys.version_info.major==3: import configparser as cfg else: import ConfigParser as cfg class log(object): # root logger setting mkdir("/home/neuiva2/wangironman/SSD-change/pytorch-ssd-ad/experments/1_141_640_480_512baseline/logs/") save_path = "/home/neuiva2/wangironman/SSD-change/pytorch-ssd-ad/experments/1_141_640_480_512baseline/logs/" + time.strftime("%m_%d_%H_%M") + '.log' l = logging.getLogger() l.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') # clear handler streams for it in l.handlers: l.removeHandler(it) # file handler setting config = cfg.RawConfigParser() config.read('util.config') save_dir = config.get('general', 'log_path') if not os.path.exists(save_dir): os.makedirs(save_dir) save_path = os.path.join(save_dir, save_path) f_handler = logging.FileHandler(save_path) f_handler.setLevel(logging.DEBUG) f_handler.setFormatter(formatter) # console handler c_handler = logging.StreamHandler() c_handler.setLevel(logging.INFO) c_handler.setFormatter(formatter) l.addHandler(f_handler) l.addHandler(c_handler) # print(l.handlers[0].__dict__)
[ "noreply@github.com" ]
noreply@github.com
90df94c5e229fdd296228d82f72d8224423d82ae
a024eb30d51fd73d1366def184b91f2b4159f3d1
/python/TQC+/707.py
ee9afb3c51eba427016428518f5fcc65fe411f44
[]
no_license
ooxx2500/python-sql-for-test
e4e084719374157cc8bd87e0f62fb2f5d71eb397
66f6ce9f500d2a5eeac162bfc5de321b305c0114
refs/heads/master
2023-02-19T08:19:10.541402
2021-01-18T17:04:16
2021-01-18T17:04:16
266,665,158
0
1
null
null
null
null
UTF-8
Python
false
false
1,659
py
# -*- coding: utf-8 -*- """ Created on Thu May 28 20:44:29 2020 @author: 莫再提 """ ''' 設計說明: 請撰寫一程式,輸入X組和Y組各自的科目至集合中,以字串"end"作為結束點(集合中不包含字串"end")。請依序分行顯示(1) X組和Y組的所有科目、(2)X組和Y組的共同科目、(3)Y組有但X組沒有的科目,以及(4) X組和Y組彼此沒有的科目(不包含相同科目)。 提示:科目須參考範例輸出樣本,依字母由小至大進行排序。 3. 輸入輸出: 輸入說明 輸入X組和Y組各自的科目至集合,直至end結束輸入 輸出說明 X組和Y組的所有科目 X組和Y組的共同科目 Y組有但X組沒有的科目 X組和Y組彼此沒有的科目(不包含相同科目) 輸入輸出範例 輸入與輸出會交雜如下,輸出的部份以粗體字表示 Enter group X's subjects: Math Literature English History Geography end Enter group Y's subjects: Math Literature Chinese Physical Chemistry end ['Chemistry', 'Chinese', 'English', 'Geography', 'History', 'Literature', 'Math', 'Physical'] ['Literature', 'Math'] ['Chemistry', 'Chinese', 'Physical'] ['Chemistry', 'Chinese', 'English', 'Geography', 'History', 'Physical'] ''' s1=set() s2=set() print("Enter group X's subjects:") # TODO x = input() while x != 'end': s1.add(x) x = input() print("Enter group Y's subjects:") # TODO y = input() while y != 'end': s2.add(y) y = input() a = s1|s2 b =s1&s2 c = s2-s1 d =s1^s2 a1=list(a) b1=list(b) c1=list(c) d1=list(d) a1.sort() b1.sort() c1.sort() d1.sort() print(a1) print(b1) print(c1) print(d1)
[ "ooxx2500@gmail.com" ]
ooxx2500@gmail.com
30232aaafb908dc8c053eeb85976b9724e225dcf
df8220610a79ffddf26d81d6b9f64e09ea65ef17
/kdsg_sac/o1SAC.py
b0f4137a3a9343bdc860702b004030b9e347a344
[ "MIT" ]
permissive
fenildf/anki_addons-1
c43f40f488674ad0050cbd2c2ec5aec4f470b74c
352f5230cb52f07aaabd2bbc76d583f585deffb7
refs/heads/master
2020-05-22T05:47:07.183625
2018-03-14T13:04:32
2018-03-14T13:04:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,102
py
# -*- coding: utf-8 -*- # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from kdsgSAC import * def splitShuffle(expr, t): expr = stripHTML(expr).strip() if t == SGJ: from rakutenma import RakutenMA rma = RakutenMA(phi=1024, c=0.007812) tD, tF = os.path.split(__file__) jSon = os.path.join(tD, 'model_ja.min.json') rma.load(jSon) resultl = rma.tokenize(expr) result = [r for r, s in resultl] elif t in SGC: import jieba result = jieba.cut(expr, cut_all=False) elif t == JSS: result = expr.split(' ') elif t in WRAPL: result = list(expr) newResult, glosses = getResult(result, t) jn = u'' full = jn.join(newResult) random.shuffle(newResult) strResult = u''.join(newResult) return strResult, full, glosses def sentGloss(res, t): """ Fall back to reading-based Japanese lookup if headword lookup fails. Chinese lookup multi-pronged by default. """ if t == SGJ: from cjklib.dictionary import EDICT d = EDICT() dtrans = d.getForHeadword(res) elif t == SGC or t == SGCW: from cjklib.dictionary import CEDICT d = CEDICT() if res in cedict.all: dtrans = d.getFor(res) else: return '' entries = [] entry = '' for e in dtrans: for f in e._fields: if getattr(e, f) != None: entry = unicode(getattr(e, f)) + u'\t' entries.append(entry) if len(entries) == 0: for e in d.getForReading(res): for f in e._fields: if getattr(e, f) != None: entry = unicode(getattr(e, f)) + u'\t' entries.append(entry) return u'\t'.join(entries) def getResult(result, t): """ Use random to ensure uniqueness of IDs, just in case. """ glosses = [] random.seed(2) count = random.random() newResult = [] blacklist = [u' ', u' ', u'\xa0', u'?', u'!', u'。', u'、', u'.', u'!', u'?', u','] if 'Chinese' in t: l = 'zh' elif 'Japanese' in t: l = 'ja' else: l = 'sp' for res in result: trans = '' if res not in blacklist: if t == JSS or t == JSW: for p in blacklist: res = res.replace(p, "") count += 1.0 id = '%sUnshuffle' % (l) + str(count) if t != JSS and t != JSW: if t in WRAPL: from kanRen import glossKanji resk = u''.join(re.findall('[%s]' % hanzi.characters, res, re.UNICODE)) if resk: if t == SGCW and resk in cedict.all: trans = sentGloss(resk, t) elif t != SGCW: trans = glossKanji(resk, t) else: trans = sentGloss(res, t) if trans: glosses.append(u'• ' + trans) newResult.append('''<div class="copyt" onclick="copyrem( document.getElementById('%s').innerText, document.getElementById('%s') );" id="%s" style="padding: 1px; margin: 2px; box-shadow: 0px 0px 0px 1px rgba(0,0,0,0.3); cursor: pointer; border-radius: 5px; display: inline-block;" title="%s">%s</div>''' % (id, id, id, trans, res)) glosses = u'<br>'.join(glosses) return newResult, glosses
[ "aardodd@users.noreply.github.com" ]
aardodd@users.noreply.github.com
0da77f014cb0ab5fa330e78eb0ad3805875541f6
c65ea2fb10fc26d41d802d50e7d29b4d9f28dfe6
/honshu/geoclaw/pacific/.svn/text-base/setplot.py.svn-base
c1309d2c0632c0fae2f5b66c46f0edac1030886c
[]
no_license
jsvarkovitzky/ccTsunami
a48b6b86ac67ffb8fa430b1e38f45adfe4afb66d
47caa6f0c559f3060209d571d1d64a6186072deb
refs/heads/master
2021-01-15T22:29:21.968088
2011-08-04T05:34:32
2011-08-04T05:34:32
2,067,563
0
0
null
null
null
null
UTF-8
Python
false
false
9,135
""" Set up the plot figures, axes, and items to be done for each frame. This module is imported by the plotting routines and then the function setplot is called to set the plot parameters. """ from pyclaw.geotools import topotools from pyclaw.data import Data import pylab import glob if 0: dartdata = {} #for gaugeno in [21401, 21413, 21414, 21415, 21418, 21419, 51407, 52402]: for gaugeno in [21413, 21418, 52402]: files = glob.glob('../../DART/%s*_notide.txt' % gaugeno) if len(files) != 1: raise Exception("*** found %s files for gauge number %s" \ % (len(files),gaugeno) ) fname = files[0] dartdata[gaugeno] = pylab.loadtxt(fname) tlimits = {} tlimits[21401] = [0,28800] tlimits[21413] = [0,28800] tlimits[21414] = [8000,28800] tlimits[21415] = [7200,28800] tlimits[21416] = [0,14400] tlimits[21418] = [0,28800] tlimits[21419] = [0,28800] tlimits[51407] = [8000,28800] tlimits[52402] = [8000,28800] #-------------------------- def setplot(plotdata): #-------------------------- """ Specify what is to be plotted at each frame. Input: plotdata, an instance of pyclaw.plotters.data.ClawPlotData. Output: a modified version of plotdata. """ from pyclaw.plotters import colormaps, geoplot from numpy import linspace plotdata.clearfigures() # clear any old figures,axes,items data # To plot gauge locations on imshow or contour plot, use this as # an afteraxis function: def addgauges(current_data): from pyclaw.plotters import gaugetools gaugetools.plot_gauge_locations(current_data.plotdata, \ gaugenos='all', format_string='ko', add_labels=True) #----------------------------------------- # Figure for imshow plot #----------------------------------------- plotfigure = plotdata.new_plotfigure(name='full domain', figno=0) plotfigure.kwargs = {'figsize':[16,8]} # Set up for axes in this figure: plotaxes = plotfigure.new_plotaxes('imshow') plotaxes.title = 'Surface' plotaxes.scaled = True def fixup(current_data): import pylab t = current_data.t t = t / 3600. # hours pylab.title('Surface at %4.2f hours' % t, fontsize=20) pylab.xticks(fontsize=15) pylab.yticks(fontsize=15) #pylab.plot([139.7],[35.6],'wo',markersize=5) #pylab.text(130,38,'Tokyo',color='w',fontsize=15) pylab.plot([140.8847],[38.2547],'ko',markersize=5) pylab.text(130,38,'Sendai',color='k',fontsize=15) pylab.plot([205],[19.7],'wo',markersize=4) #pylab.text(205,22,'Hawaii',color='k',fontsize=15) pylab.text(195,18,'Hawaii',color='k',fontsize=15) pylab.plot([235.81],[41.75],'wo',markersize=5) pylab.text(237.0,42,'Crescent City',color='w',fontsize=15) pylab.plot([237.67],[47.61],'wo',markersize=5) pylab.text(238.5,47.85,'Seattle',color='w',fontsize=15) addgauges(current_data) pylab.xlabel('degrees longitude', fontsize=15) pylab.ylabel('degrees latitude', fontsize=15) plotaxes.afteraxes = fixup # Water plotitem = plotaxes.new_plotitem(plot_type='2d_imshow') #plotitem.plot_var = geoplot.surface plotitem.plot_var = geoplot.surface_or_depth plotitem.imshow_cmap = geoplot.tsunami_colormap plotitem.imshow_cmin = -0.09 plotitem.imshow_cmax = 0.09 plotitem.add_colorbar = False plotitem.amr_gridlines_show = [0,0,0] plotitem.gridedges_show = 0 plotitem.gridedges_color = 'y' # Land plotitem = plotaxes.new_plotitem(plot_type='2d_imshow') plotitem.plot_var = geoplot.land plotitem.imshow_cmap = geoplot.land_colors plotitem.imshow_cmin = 0.0 plotitem.imshow_cmax = 100.0 plotitem.add_colorbar = False plotitem.amr_gridlines_show = [0,0,0] plotitem.gridedges_show = 0 plotaxes.xlimits = [120,280] plotaxes.ylimits = [-20,60] # add contour lines of bathy if desired: plotitem = plotaxes.new_plotitem(plot_type='2d_contour') plotitem.show = False plotitem.plot_var = geoplot.topo plotitem.contour_levels = linspace(-5000,-100,6) plotitem.amr_contour_colors = ['y'] # color on each level plotitem.kwargs = {'linestyles':'solid','linewidths':2} plotitem.amr_contour_show = [1,0,0] plotitem.gridlines_show = 0 plotitem.gridedges_show = 0 #----------------------------------------- # Figure for zoom plot #----------------------------------------- plotfigure = plotdata.new_plotfigure(name='Zoom', figno=1) plotfigure.show = False # Set up for axes in this figure: plotaxes = plotfigure.new_plotaxes('pcolor') plotaxes.title = 'Surface' plotaxes.scaled = True plotaxes.xlimits = [235.7,235.9] plotaxes.ylimits = [41.65,41.85] def fixup(current_data): import pylab addgauges(current_data) t = current_data.t t = t / 3600. # hours pylab.title('Surface at %4.2f hours' % t, fontsize=20) # pylab.plot([139.7],[35.6],'wo',markersize=10) # pylab.text(138.2,35.9,'Tokyo',color='w',fontsize=25) plotaxes.afteraxes = fixup # Water plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor') #plotitem.plot_var = geoplot.surface plotitem.plot_var = geoplot.surface_or_depth plotitem.pcolor_cmap = geoplot.tsunami_colormap plotitem.pcolor_cmin = -0.5 plotitem.pcolor_cmax = 0.5 plotitem.add_colorbar = True plotitem.amr_gridlines_show = [0,0,0] ##Levels of refinement plotitem.gridedges_show = 1 # Land plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor') plotitem.plot_var = geoplot.land plotitem.pcolor_cmap = geoplot.land_colors plotitem.pcolor_cmin = 0.0 plotitem.pcolor_cmax = 100.0 plotitem.add_colorbar = False plotitem.amr_gridlines_show = [0,0,0] plotitem.gridedges_show = 1 # add contour lines of bathy if desired: plotitem = plotaxes.new_plotitem(plot_type='2d_contour') plotitem.show = False plotitem.plot_var = geoplot.topo plotitem.contour_levels = linspace(-3000,-3000,1) plotitem.amr_contour_colors = ['y'] # color on each level plotitem.kwargs = {'linestyles':'solid','linewidths':2} plotitem.amr_contour_show = [1,0,0] plotitem.gridlines_show = 0 plotitem.gridedges_show = 0 #----------------------------------------- # Figures for gauges #----------------------------------------- plotfigure = plotdata.new_plotfigure(name='Surface & topo', figno=300, \ type='each_gauge') plotfigure.clf_each_gauge = True # Set up for axes in this figure: plotaxes = plotfigure.new_plotaxes() plotaxes.xlimits = 'auto' plotaxes.ylimits = 'auto' plotaxes.title = 'Surface' # Plot surface as blue curve: plotitem = plotaxes.new_plotitem(plot_type='1d_plot') plotitem.plot_var = 3 plotitem.plotstyle = 'b-' plotitem.kwargs = {'linewidth':2} # Plot topo as green curve: plotitem = plotaxes.new_plotitem(plot_type='1d_plot') plotitem.show = False def gaugetopo(current_data): q = current_data.q h = q[:,0] eta = q[:,3] topo = eta - h return topo plotitem.plot_var = gaugetopo plotitem.plotstyle = 'g-' def add_zeroline(current_data): from pylab import plot, legend, xticks, floor t = current_data.t #legend(('surface','topography'),loc='lower left') #plot([0,10800],[0,0],'k') n = floor(t.max()/3600.) + 2 xticks([3600*i for i in range(n)]) def plot_dart(current_data): import pylab gaugeno = current_data.gaugeno try: dart = dartdata[gaugeno] pylab.plot(dart[:,0],dart[:,1],'k') pylab.legend(['GeoClaw','DART data']) except: pylab.legend(['GeoClaw']) add_zeroline(current_data) try: pylab.xlim(tlimits[gaugeno]) except: pass #plotaxes.afteraxes = plot_dart #----------------------------------------- # Parameters used only when creating html and/or latex hardcopy # e.g., via pyclaw.plotters.frametools.printframes: plotdata.printfigs = True # print figures plotdata.print_format = 'png' # file format plotdata.print_framenos = 'all' # list of frames to print plotdata.print_gaugenos = 'all' # list of gauges to print plotdata.print_fignos = 'all' # list of figures to print plotdata.html = True # create html files of plots? plotdata.html_homelink = '../README.html' # pointer for top of index plotdata.latex = True # create latex file of plots? plotdata.latex_figsperline = 2 # layout of plots plotdata.latex_framesperline = 1 # layout of plots plotdata.latex_makepdf = False # also run pdflatex? return plotdata
[ "vark@uw.edu" ]
vark@uw.edu
2406803ffeac1ba5f649de2438c85c6177e2f414
a461925cccddab803593377f4b558f671d43d432
/Rooms/migrations/0031_remove_deepclean_date.py
6cd5cb3fddab2d3674681f434ef3b0d565143139
[]
no_license
fenilpatel1710/Housekeeping
82a7f69d02b91f4ecb38dbce9319b0b6922873ff
f6dce8b98633ea3a01c2942ff0a84c512d9dffe1
refs/heads/master
2022-12-03T10:49:36.036539
2020-08-20T04:45:29
2020-08-20T04:45:29
288,914,377
0
0
null
null
null
null
UTF-8
Python
false
false
323
py
# Generated by Django 3.0.5 on 2020-07-31 02:22 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('Rooms', '0030_deepclean_date'), ] operations = [ migrations.RemoveField( model_name='deepclean', name='date', ), ]
[ "fenilpatel1710@gmail.com" ]
fenilpatel1710@gmail.com
ff3f2fe7c0ff1a24311692a70eb60866a57560e6
4607c3869cfcef24518e817a6e31d29b01eb4fee
/project/users/migrations/0001_initial.py
ef0de3a8007ea75c3d2fd331f41ae77c76017c42
[]
no_license
fa8chai/ClickTime
916902336d552498d2fedf41df08fc6304a82e81
18992f858a2354cdce6f6f38fccd7cfc9db0d912
refs/heads/master
2023-06-03T22:53:34.009319
2021-06-11T23:46:52
2021-06-11T23:46:52
280,895,226
0
0
null
2020-07-22T14:27:34
2020-07-19T15:33:03
Python
UTF-8
Python
false
false
2,448
py
# Generated by Django 3.0.5 on 2020-05-26 15:07 from django.db import migrations, models import django.utils.timezone import users.models class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.CreateModel( name='CustomUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('email', models.EmailField(max_length=254, unique=True)), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'verbose_name': 'user', 'verbose_name_plural': 'users', 'abstract': False, }, managers=[ ('objects', users.models.CustomUserManager()), ], ), ]
[ "anne.wi.sw@gmail.com" ]
anne.wi.sw@gmail.com
b221c3c9d0e06b9ff21be85f36bd5ec1b7182e06
d912ad85ecc9b444e7ae60640664b2af22693bcf
/characters/character.py
ae91f5da20767a85aedadf5dd968b2e7558b526a
[]
no_license
rockerway/godfink
ded01b80b2a1af39a5862a28b90ee31eb89584ed
e8c41d367ba7234998b01dd86950dd97fd8b07c2
refs/heads/master
2020-03-25T10:12:54.512114
2018-09-20T05:13:36
2018-09-20T05:13:36
143,687,392
2
0
null
null
null
null
UTF-8
Python
false
false
1,724
py
import tkinter import configparser from entities.displacement import Displacement from actions.actable import Actable config = configparser.ConfigParser() config.read('config.ini') width = int(config['window']['width']) height = int(config['window']['height']) class Character(Actable): def __init__(self, characterInfo): self.canvases = [] self.effect = None self.effectImage = tkinter.PhotoImage( file='resources/effects/breath.gif') self.id = characterInfo.id self.name = characterInfo.name self.role = characterInfo.role self.imageName = characterInfo.imageName self.image = tkinter.PhotoImage( file='resources/roles/' + characterInfo.imageName + '.gif') self.level = characterInfo.level self.x = characterInfo.xRatio * width self.y = characterInfo.yRatio * height self.events = [] self.action = characterInfo.action self.mantra = characterInfo.mantra self.displacement = Displacement() def getDisplacement(self): displacement = self.displacement self.displacement = Displacement() return displacement def transfer(self, canvas): for canvas in self.canvases: canvas.delete(self.canvas) def transferEnd(self, callback): callback() def move(self, displacement, width, height): nextX = self.x + displacement.dx nextY = self.y + displacement.dy if 0 < nextX and nextX < width: self.displacement.dx += displacement.dx self.x = nextX if 0 < nextY and nextY < height: self.displacement.dy += displacement.dy self.y = nextY
[ "tod.shen@todshen.local" ]
tod.shen@todshen.local
3baa5490caeaee6f4b3444ff8bdbe2023f78f045
8dcd3ee098b4f5b80879c37a62292f42f6b2ae17
/venv/Lib/site-packages/pandas/core/internals/blocks.py
8cd8524762a8f465d7b25de9b5374adb5fbcf3d3
[]
no_license
GregVargas1999/InfinityAreaInfo
53fdfefc11c4af8f5d2b8f511f7461d11a3f7533
2e4a7c6a2424514ca0ec58c9153eb08dc8e09a4a
refs/heads/master
2022-12-01T20:26:05.388878
2020-08-11T18:37:05
2020-08-11T18:37:05
286,821,452
0
0
null
null
null
null
UTF-8
Python
false
false
104,426
py
import functools import inspect import re import warnings from datetime import datetime, timedelta from typing import Any, List import numpy as np import pandas._libs.internals as libinternals import pandas.core.algorithms as algos import pandas.core.common as com import pandas.core.missing as missing from pandas._libs import NaT, Timestamp, algos as libalgos, lib, tslib, writers from pandas._libs.index import convert_scalar from pandas._libs.tslibs import Timedelta, conversion from pandas._libs.tslibs.timezones import tz_compare from pandas.core.arrays import ( Categorical, DatetimeArray, ExtensionArray, PandasArray, PandasDtype, TimedeltaArray, ) from pandas.core.base import PandasObject from pandas.core.construction import extract_array from pandas.core.dtypes.cast import ( astype_nansafe, find_common_type, infer_dtype_from, infer_dtype_from_scalar, maybe_downcast_numeric, maybe_downcast_to_dtype, maybe_infer_dtype_type, maybe_promote, maybe_upcast, soft_convert_objects, ) from pandas.core.dtypes.common import ( _NS_DTYPE, _TD_DTYPE, ensure_platform_int, is_bool_dtype, is_categorical, is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype, is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_integer, is_integer_dtype, is_interval_dtype, is_list_like, is_object_dtype, is_period_dtype, is_re, is_re_compilable, is_sparse, is_timedelta64_dtype, pandas_dtype, ) from pandas.core.dtypes.concat import concat_categorical, concat_datetime from pandas.core.dtypes.dtypes import CategoricalDtype, ExtensionDtype from pandas.core.dtypes.generic import ( ABCDataFrame, ABCExtensionArray, ABCPandasArray, ABCSeries, ) from pandas.core.dtypes.missing import ( _isna_compat, array_equivalent, is_valid_nat_for_dtype, isna, ) from pandas.core.indexers import ( check_setitem_lengths, is_empty_indexer, is_scalar_indexer, ) from pandas.core.nanops import nanpercentile from pandas.io.formats.printing import pprint_thing from pandas.util._validators import validate_bool_kwarg class Block(PandasObject): """ Canonical n-dimensional unit of homogeneous dtype contained in a pandas data structure Index-ignorant; let the container take care of that """ __slots__ = ["_mgr_locs", "values", "ndim"] is_numeric = False is_float = False is_integer = False is_complex = False is_datetime = False is_datetimetz = False is_timedelta = False is_bool = False is_object = False is_categorical = False is_extension = False _can_hold_na = False _can_consolidate = True _verify_integrity = True _validate_ndim = True _ftype = "dense" _concatenator = staticmethod(np.concatenate) def __init__(self, values, placement, ndim=None): self.ndim = self._check_ndim(values, ndim) self.mgr_locs = placement self.values = values if self._validate_ndim and self.ndim and len(self.mgr_locs) != len(self.values): raise ValueError( f"Wrong number of items passed {len(self.values)}, " f"placement implies {len(self.mgr_locs)}" ) def _check_ndim(self, values, ndim): """ ndim inference and validation. Infers ndim from 'values' if not provided to __init__. Validates that values.ndim and ndim are consistent if and only if the class variable '_validate_ndim' is True. Parameters ---------- values : array-like ndim : int or None Returns ------- ndim : int Raises ------ ValueError : the number of dimensions do not match """ if ndim is None: ndim = values.ndim if self._validate_ndim and values.ndim != ndim: raise ValueError( "Wrong number of dimensions. " f"values.ndim != ndim [{values.ndim} != {ndim}]" ) return ndim @property def _holder(self): """The array-like that can hold the underlying values. None for 'Block', overridden by subclasses that don't use an ndarray. """ return None @property def _consolidate_key(self): return (self._can_consolidate, self.dtype.name) @property def _is_single_block(self): return self.ndim == 1 @property def is_view(self): """ return a boolean if I am possibly a view """ return self.values.base is not None @property def is_datelike(self): """ return True if I am a non-datelike """ return self.is_datetime or self.is_timedelta def is_categorical_astype(self, dtype): """ validate that we have a astypeable to categorical, returns a boolean if we are a categorical """ if dtype is Categorical or dtype is CategoricalDtype: # this is a pd.Categorical, but is not # a valid type for astypeing raise TypeError(f"invalid type {dtype} for astype") elif is_categorical_dtype(dtype): return True return False def external_values(self, dtype=None): """ The array that Series.values returns (public attribute). This has some historical constraints, and is overridden in block subclasses to return the correct array (e.g. period returns object ndarray and datetimetz a datetime64[ns] ndarray instead of proper extension array). """ return self.values def internal_values(self, dtype=None): """ return an internal format, currently just the ndarray this should be the pure internal API format """ return self.values def array_values(self) -> ExtensionArray: """ The array that Series.array returns. Always an ExtensionArray. """ return PandasArray(self.values) def get_values(self, dtype=None): """ return an internal format, currently just the ndarray this is often overridden to handle to_dense like operations """ if is_object_dtype(dtype): return self.values.astype(object) return self.values def get_block_values(self, dtype=None): """ This is used in the JSON C code """ return self.get_values(dtype=dtype) def to_dense(self): return self.values.view() @property def fill_value(self): return np.nan @property def mgr_locs(self): return self._mgr_locs @mgr_locs.setter def mgr_locs(self, new_mgr_locs): if not isinstance(new_mgr_locs, libinternals.BlockPlacement): new_mgr_locs = libinternals.BlockPlacement(new_mgr_locs) self._mgr_locs = new_mgr_locs @property def array_dtype(self): """ the dtype to return if I want to construct this block as an array """ return self.dtype def make_block(self, values, placement=None) -> "Block": """ Create a new block, with type inference propagate any values that are not specified """ if placement is None: placement = self.mgr_locs return make_block(values, placement=placement, ndim=self.ndim) def make_block_same_class(self, values, placement=None, ndim=None): """ Wrap given values in a block of same type as self. """ if placement is None: placement = self.mgr_locs if ndim is None: ndim = self.ndim return make_block(values, placement=placement, ndim=ndim, klass=type(self)) def __repr__(self) -> str: # don't want to print out all of the items here name = type(self).__name__ if self._is_single_block: result = f"{name}: {len(self)} dtype: {self.dtype}" else: shape = " x ".join(pprint_thing(s) for s in self.shape) result = ( f"{name}: {pprint_thing(self.mgr_locs.indexer)}, " f"{shape}, dtype: {self.dtype}" ) return result def __len__(self) -> int: return len(self.values) def __getstate__(self): return self.mgr_locs.indexer, self.values def __setstate__(self, state): self.mgr_locs = libinternals.BlockPlacement(state[0]) self.values = state[1] self.ndim = self.values.ndim def _slice(self, slicer): """ return a slice of my values """ return self.values[slicer] def getitem_block(self, slicer, new_mgr_locs=None): """ Perform __getitem__-like, return result as block. As of now, only supports slices that preserve dimensionality. """ if new_mgr_locs is None: if isinstance(slicer, tuple): axis0_slicer = slicer[0] else: axis0_slicer = slicer new_mgr_locs = self.mgr_locs[axis0_slicer] new_values = self._slice(slicer) if self._validate_ndim and new_values.ndim != self.ndim: raise ValueError("Only same dim slicing is allowed") return self.make_block_same_class(new_values, new_mgr_locs) @property def shape(self): return self.values.shape @property def dtype(self): return self.values.dtype @property def ftype(self): if getattr(self.values, "_pandas_ftype", False): dtype = self.dtype.subtype else: dtype = self.dtype return f"{dtype}:{self._ftype}" def merge(self, other): return _merge_blocks([self, other]) def concat_same_type(self, to_concat, placement=None): """ Concatenate list of single blocks of the same type. """ values = self._concatenator( [blk.values for blk in to_concat], axis=self.ndim - 1 ) return self.make_block_same_class( values, placement=placement or slice(0, len(values), 1) ) def iget(self, i): return self.values[i] def set(self, locs, values): """ Modify Block in-place with new item value Returns ------- None """ self.values[locs] = values def delete(self, loc): """ Delete given loc(-s) from block in-place. """ self.values = np.delete(self.values, loc, 0) self.mgr_locs = self.mgr_locs.delete(loc) def apply(self, func, **kwargs): """ apply the function to my values; return a block if we are not one """ with np.errstate(all="ignore"): result = func(self.values, **kwargs) if is_extension_array_dtype(result) and result.ndim > 1: # if we get a 2D ExtensionArray, we need to split it into 1D pieces nbs = [] for i, loc in enumerate(self.mgr_locs): vals = result[i] nv = _block_shape(vals, ndim=self.ndim) block = self.make_block(values=nv, placement=[loc]) nbs.append(block) return nbs if not isinstance(result, Block): result = self.make_block(values=_block_shape(result, ndim=self.ndim)) return result def fillna(self, value, limit=None, inplace=False, downcast=None): """ fillna on the block with the value. If we fail, then convert to ObjectBlock and try again """ inplace = validate_bool_kwarg(inplace, "inplace") mask = isna(self.values) if limit is not None: limit = libalgos._validate_limit(None, limit=limit) mask[mask.cumsum(self.ndim - 1) > limit] = False if not self._can_hold_na: if inplace: return self else: return self.copy() if self._can_hold_element(value): # equivalent: _try_coerce_args(value) would not raise blocks = self.putmask(mask, value, inplace=inplace) return self._maybe_downcast(blocks, downcast) # we can't process the value, but nothing to do if not mask.any(): return self if inplace else self.copy() # operate column-by-column def f(mask, val, idx): block = self.coerce_to_target_dtype(value) # slice out our block if idx is not None: # i.e. self.ndim == 2 block = block.getitem_block(slice(idx, idx + 1)) return block.fillna(value, limit=limit, inplace=inplace, downcast=None) return self.split_and_operate(None, f, inplace) def split_and_operate(self, mask, f, inplace: bool): """ split the block per-column, and apply the callable f per-column, return a new block for each. Handle masking which will not change a block unless needed. Parameters ---------- mask : 2-d boolean mask f : callable accepting (1d-mask, 1d values, indexer) inplace : boolean Returns ------- list of blocks """ if mask is None: mask = np.broadcast_to(True, shape=self.shape) new_values = self.values def make_a_block(nv, ref_loc): if isinstance(nv, list): assert len(nv) == 1, nv assert isinstance(nv[0], Block) block = nv[0] else: # Put back the dimension that was taken from it and make # a block out of the result. nv = _block_shape(nv, ndim=self.ndim) block = self.make_block(values=nv, placement=ref_loc) return block # ndim == 1 if self.ndim == 1: if mask.any(): nv = f(mask, new_values, None) else: nv = new_values if inplace else new_values.copy() block = make_a_block(nv, self.mgr_locs) return [block] # ndim > 1 new_blocks = [] for i, ref_loc in enumerate(self.mgr_locs): m = mask[i] v = new_values[i] # need a new block if m.any(): nv = f(m, v, i) else: nv = v if inplace else v.copy() block = make_a_block(nv, [ref_loc]) new_blocks.append(block) return new_blocks def _maybe_downcast(self, blocks: List["Block"], downcast=None) -> List["Block"]: # no need to downcast our float # unless indicated if downcast is None and ( self.is_float or self.is_timedelta or self.is_datetime ): return blocks return _extend_blocks([b.downcast(downcast) for b in blocks]) def downcast(self, dtypes=None): """ try to downcast each item to the dict of dtypes if present """ # turn it off completely if dtypes is False: return self values = self.values # single block handling if self._is_single_block: # try to cast all non-floats here if dtypes is None: dtypes = "infer" nv = maybe_downcast_to_dtype(values, dtypes) return self.make_block(nv) # ndim > 1 if dtypes is None: return self if not (dtypes == "infer" or isinstance(dtypes, dict)): raise ValueError( "downcast must have a dictionary or 'infer' as its argument" ) elif dtypes != "infer": raise AssertionError("dtypes as dict is not supported yet") # operate column-by-column # this is expensive as it splits the blocks items-by-item def f(mask, val, idx): val = maybe_downcast_to_dtype(val, dtype="infer") return val return self.split_and_operate(None, f, False) def astype(self, dtype, copy: bool = False, errors: str = "raise"): """ Coerce to the new dtype. Parameters ---------- dtype : str, dtype convertible copy : bool, default False copy if indicated errors : str, {'raise', 'ignore'}, default 'ignore' - ``raise`` : allow exceptions to be raised - ``ignore`` : suppress exceptions. On error return original object Returns ------- Block """ errors_legal_values = ("raise", "ignore") if errors not in errors_legal_values: invalid_arg = ( "Expected value of kwarg 'errors' to be one of " f"{list(errors_legal_values)}. Supplied value is '{errors}'" ) raise ValueError(invalid_arg) if inspect.isclass(dtype) and issubclass(dtype, ExtensionDtype): msg = ( f"Expected an instance of {dtype.__name__}, " "but got the class instead. Try instantiating 'dtype'." ) raise TypeError(msg) # may need to convert to categorical if self.is_categorical_astype(dtype): if is_categorical_dtype(self.values): # GH 10696/18593: update an existing categorical efficiently return self.make_block(self.values.astype(dtype, copy=copy)) return self.make_block(Categorical(self.values, dtype=dtype)) dtype = pandas_dtype(dtype) # astype processing if is_dtype_equal(self.dtype, dtype): if copy: return self.copy() return self # force the copy here if self.is_extension: # TODO: Should we try/except this astype? values = self.values.astype(dtype) else: if issubclass(dtype.type, str): # use native type formatting for datetime/tz/timedelta if self.is_datelike: values = self.to_native_types() # astype formatting else: values = self.get_values() else: values = self.get_values(dtype=dtype) # _astype_nansafe works fine with 1-d only vals1d = values.ravel() try: values = astype_nansafe(vals1d, dtype, copy=True) except (ValueError, TypeError): # e.g. astype_nansafe can fail on object-dtype of strings # trying to convert to float if errors == "raise": raise newb = self.copy() if copy else self return newb # TODO(extension) # should we make this attribute? if isinstance(values, np.ndarray): values = values.reshape(self.shape) newb = make_block(values, placement=self.mgr_locs, ndim=self.ndim) if newb.is_numeric and self.is_numeric: if newb.shape != self.shape: raise TypeError( f"cannot set astype for copy = [{copy}] for dtype " f"({self.dtype.name} [{self.shape}]) to different shape " f"({newb.dtype.name} [{newb.shape}])" ) return newb def convert( self, copy: bool = True, datetime: bool = True, numeric: bool = True, timedelta: bool = True, coerce: bool = False, ): """ attempt to coerce any object types to better types return a copy of the block (if copy = True) by definition we are not an ObjectBlock here! """ return self.copy() if copy else self def _can_hold_element(self, element: Any) -> bool: """ require the same dtype as ourselves """ dtype = self.values.dtype.type tipo = maybe_infer_dtype_type(element) if tipo is not None: return issubclass(tipo.type, dtype) return isinstance(element, dtype) def to_native_types(self, slicer=None, na_rep="nan", quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.get_values() if slicer is not None: values = values[:, slicer] mask = isna(values) itemsize = writers.word_len(na_rep) if not self.is_object and not quoting and itemsize: values = values.astype(str) if values.dtype.itemsize / np.dtype("U1").itemsize < itemsize: # enlarge for the na_rep values = values.astype(f"<U{itemsize}") else: values = np.array(values, dtype="object") values[mask] = na_rep return values # block actions # def copy(self, deep=True): """ copy constructor """ values = self.values if deep: values = values.copy() return self.make_block_same_class(values, ndim=self.ndim) def replace( self, to_replace, value, inplace=False, filter=None, regex=False, convert=True ): """replace the to_replace value with value, possible to create new blocks here this is just a call to putmask. regex is not used here. It is used in ObjectBlocks. It is here for API compatibility. """ inplace = validate_bool_kwarg(inplace, "inplace") original_to_replace = to_replace # If we cannot replace with own dtype, convert to ObjectBlock and # retry if not self._can_hold_element(to_replace): if not isinstance(to_replace, list): if inplace: return [self] return [self.copy()] to_replace = [x for x in to_replace if self._can_hold_element(x)] if not len(to_replace): # GH#28084 avoid costly checks since we can infer # that there is nothing to replace in this block if inplace: return [self] return [self.copy()] if len(to_replace) == 1: # _can_hold_element checks have reduced this back to the # scalar case and we can avoid a costly object cast return self.replace( to_replace[0], value, inplace=inplace, filter=filter, regex=regex, convert=convert, ) # GH 22083, TypeError or ValueError occurred within error handling # causes infinite loop. Cast and retry only if not objectblock. if is_object_dtype(self): raise AssertionError # try again with a compatible block block = self.astype(object) return block.replace( to_replace=to_replace, value=value, inplace=inplace, filter=filter, regex=regex, convert=convert, ) values = self.values if lib.is_scalar(to_replace) and isinstance(values, np.ndarray): # The only non-DatetimeLike class that also has a non-trivial # try_coerce_args is ObjectBlock, but that overrides replace, # so does not get here. to_replace = convert_scalar(values, to_replace) mask = missing.mask_missing(values, to_replace) if filter is not None: filtered_out = ~self.mgr_locs.isin(filter) mask[filtered_out.nonzero()[0]] = False try: blocks = self.putmask(mask, value, inplace=inplace) # Note: it is _not_ the case that self._can_hold_element(value) # is always true at this point. In particular, that can fail # for: # "2u" with bool-dtype, float-dtype # 0.5 with int64-dtype # np.nan with int64-dtype except (TypeError, ValueError): # GH 22083, TypeError or ValueError occurred within error handling # causes infinite loop. Cast and retry only if not objectblock. if is_object_dtype(self): raise if not self.is_extension: # TODO: https://github.com/pandas-dev/pandas/issues/32586 # Need an ExtensionArray._can_hold_element to indicate whether # a scalar value can be placed in the array. assert not self._can_hold_element(value), value # try again with a compatible block block = self.astype(object) return block.replace( to_replace=original_to_replace, value=value, inplace=inplace, filter=filter, regex=regex, convert=convert, ) if convert: blocks = [b.convert(numeric=False, copy=not inplace) for b in blocks] return blocks def _replace_single(self, *args, **kwargs): """ no-op on a non-ObjectBlock """ return self if kwargs["inplace"] else self.copy() def setitem(self, indexer, value): """ Set the value inplace, returning a a maybe different typed block. Parameters ---------- indexer : tuple, list-like, array-like, slice The subset of self.values to set value : object The value being set Returns ------- Block Notes ----- `indexer` is a direct slice/positional indexer. `value` must be a compatible shape. """ transpose = self.ndim == 2 # coerce None values, if appropriate if value is None: if self.is_numeric: value = np.nan # coerce if block dtype can store value values = self.values if self._can_hold_element(value): # We only get here for non-Extension Blocks, so _try_coerce_args # is only relevant for DatetimeBlock and TimedeltaBlock if lib.is_scalar(value): value = convert_scalar(values, value) else: # current dtype cannot store value, coerce to common dtype find_dtype = False if hasattr(value, "dtype"): dtype = value.dtype find_dtype = True elif lib.is_scalar(value) and not isna(value): dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True) find_dtype = True if find_dtype: dtype = find_common_type([values.dtype, dtype]) if not is_dtype_equal(self.dtype, dtype): b = self.astype(dtype) return b.setitem(indexer, value) # value must be storeable at this moment if is_extension_array_dtype(getattr(value, "dtype", None)): # We need to be careful not to allow through strings that # can be parsed to EADtypes is_ea_value = True arr_value = value else: is_ea_value = False arr_value = np.array(value) # cast the values to a type that can hold nan (if necessary) if not self._can_hold_element(value): dtype, _ = maybe_promote(arr_value.dtype) values = values.astype(dtype) if transpose: values = values.T # length checking check_setitem_lengths(indexer, value, values) exact_match = ( len(arr_value.shape) and arr_value.shape[0] == values.shape[0] and arr_value.size == values.size ) if is_empty_indexer(indexer, arr_value): # GH#8669 empty indexers pass elif is_scalar_indexer(indexer, arr_value): # setting a single element for each dim and with a rhs that could # be e.g. a list; see GH#6043 values[indexer] = value elif ( exact_match and is_categorical_dtype(arr_value.dtype) and not is_categorical_dtype(values) ): # GH25495 - If the current dtype is not categorical, # we need to create a new categorical block values[indexer] = value return self.make_block(Categorical(self.values, dtype=arr_value.dtype)) elif exact_match and is_ea_value: # GH#32395 if we're going to replace the values entirely, just # substitute in the new array return self.make_block(arr_value) # if we are an exact match (ex-broadcasting), # then use the resultant dtype elif exact_match: values[indexer] = value try: values = values.astype(arr_value.dtype) except ValueError: pass # set else: values[indexer] = value if transpose: values = values.T block = self.make_block(values) return block def putmask(self, mask, new, align=True, inplace=False, axis=0, transpose=False): """ putmask the data to the block; it is possible that we may create a new dtype of block return the resulting block(s) Parameters ---------- mask : the condition to respect new : a ndarray/object align : boolean, perform alignment on other/cond, default is True inplace : perform inplace modification, default is False axis : int transpose : boolean Set to True if self is stored with axes reversed Returns ------- a list of new blocks, the result of the putmask """ new_values = self.values if inplace else self.values.copy() new = getattr(new, "values", new) mask = getattr(mask, "values", mask) # if we are passed a scalar None, convert it here if not is_list_like(new) and isna(new) and not self.is_object: # FIXME: make sure we have compatible NA new = self.fill_value if self._can_hold_element(new): # We only get here for non-Extension Blocks, so _try_coerce_args # is only relevant for DatetimeBlock and TimedeltaBlock if lib.is_scalar(new): new = convert_scalar(new_values, new) if transpose: new_values = new_values.T # If the default repeat behavior in np.putmask would go in the # wrong direction, then explicitly repeat and reshape new instead if getattr(new, "ndim", 0) >= 1: if self.ndim - 1 == new.ndim and axis == 1: new = np.repeat(new, new_values.shape[-1]).reshape(self.shape) new = new.astype(new_values.dtype) # we require exact matches between the len of the # values we are setting (or is compat). np.putmask # doesn't check this and will simply truncate / pad # the output, but we want sane error messages # # TODO: this prob needs some better checking # for 2D cases if ( is_list_like(new) and np.any(mask[mask]) and getattr(new, "ndim", 1) == 1 ): if mask[mask].shape[-1] == len(new): # GH 30567 # If length of ``new`` is less than the length of ``new_values``, # `np.putmask` would first repeat the ``new`` array and then # assign the masked values hence produces incorrect result. # `np.place` on the other hand uses the ``new`` values at it is # to place in the masked locations of ``new_values`` np.place(new_values, mask, new) elif mask.shape[-1] == len(new) or len(new) == 1: np.putmask(new_values, mask, new) else: raise ValueError("cannot assign mismatch length to masked array") else: np.putmask(new_values, mask, new) # maybe upcast me elif mask.any(): if transpose: mask = mask.T if isinstance(new, np.ndarray): new = new.T axis = new_values.ndim - axis - 1 # Pseudo-broadcast if getattr(new, "ndim", 0) >= 1: if self.ndim - 1 == new.ndim: new_shape = list(new.shape) new_shape.insert(axis, 1) new = new.reshape(tuple(new_shape)) # operate column-by-column def f(mask, val, idx): if idx is None: # ndim==1 case. n = new else: if isinstance(new, np.ndarray): n = np.squeeze(new[idx % new.shape[0]]) else: n = np.array(new) # type of the new block dtype, _ = maybe_promote(n.dtype) # we need to explicitly astype here to make a copy n = n.astype(dtype) nv = _putmask_smart(val, mask, n) return nv new_blocks = self.split_and_operate(mask, f, inplace) return new_blocks if inplace: return [self] if transpose: new_values = new_values.T return [self.make_block(new_values)] def coerce_to_target_dtype(self, other): """ coerce the current block to a dtype compat for other we will return a block, possibly object, and not raise we can also safely try to coerce to the same dtype and will receive the same block """ # if we cannot then coerce to object dtype, _ = infer_dtype_from(other, pandas_dtype=True) if is_dtype_equal(self.dtype, dtype): return self if self.is_bool or is_object_dtype(dtype) or is_bool_dtype(dtype): # we don't upcast to bool return self.astype(object) elif (self.is_float or self.is_complex) and ( is_integer_dtype(dtype) or is_float_dtype(dtype) ): # don't coerce float/complex to int return self elif ( self.is_datetime or is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype) ): # not a datetime if not ( (is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype)) and self.is_datetime ): return self.astype(object) # don't upcast timezone with different timezone or no timezone mytz = getattr(self.dtype, "tz", None) othertz = getattr(dtype, "tz", None) if not tz_compare(mytz, othertz): return self.astype(object) raise AssertionError( f"possible recursion in coerce_to_target_dtype: {self} {other}" ) elif self.is_timedelta or is_timedelta64_dtype(dtype): # not a timedelta if not (is_timedelta64_dtype(dtype) and self.is_timedelta): return self.astype(object) raise AssertionError( f"possible recursion in coerce_to_target_dtype: {self} {other}" ) try: return self.astype(dtype) except (ValueError, TypeError, OverflowError): return self.astype(object) def interpolate( self, method="pad", axis=0, index=None, values=None, inplace=False, limit=None, limit_direction="forward", limit_area=None, fill_value=None, coerce=False, downcast=None, **kwargs, ): inplace = validate_bool_kwarg(inplace, "inplace") def check_int_bool(self, inplace): # Only FloatBlocks will contain NaNs. # timedelta subclasses IntBlock if (self.is_bool or self.is_integer) and not self.is_timedelta: if inplace: return self else: return self.copy() # a fill na type method try: m = missing.clean_fill_method(method) except ValueError: m = None if m is not None: r = check_int_bool(self, inplace) if r is not None: return r return self._interpolate_with_fill( method=m, axis=axis, inplace=inplace, limit=limit, fill_value=fill_value, coerce=coerce, downcast=downcast, ) # validate the interp method m = missing.clean_interp_method(method, **kwargs) r = check_int_bool(self, inplace) if r is not None: return r return self._interpolate( method=m, index=index, values=values, axis=axis, limit=limit, limit_direction=limit_direction, limit_area=limit_area, fill_value=fill_value, inplace=inplace, downcast=downcast, **kwargs, ) def _interpolate_with_fill( self, method="pad", axis=0, inplace=False, limit=None, fill_value=None, coerce=False, downcast=None, ): """ fillna but using the interpolate machinery """ inplace = validate_bool_kwarg(inplace, "inplace") # if we are coercing, then don't force the conversion # if the block can't hold the type if coerce: if not self._can_hold_na: if inplace: return [self] else: return [self.copy()] values = self.values if inplace else self.values.copy() # We only get here for non-ExtensionBlock fill_value = convert_scalar(self.values, fill_value) values = missing.interpolate_2d( values, method=method, axis=axis, limit=limit, fill_value=fill_value, dtype=self.dtype, ) blocks = [self.make_block_same_class(values, ndim=self.ndim)] return self._maybe_downcast(blocks, downcast) def _interpolate( self, method=None, index=None, values=None, fill_value=None, axis=0, limit=None, limit_direction="forward", limit_area=None, inplace=False, downcast=None, **kwargs, ): """ interpolate using scipy wrappers """ inplace = validate_bool_kwarg(inplace, "inplace") data = self.values if inplace else self.values.copy() # only deal with floats if not self.is_float: if not self.is_integer: return self data = data.astype(np.float64) if fill_value is None: fill_value = self.fill_value if method in ("krogh", "piecewise_polynomial", "pchip"): if not index.is_monotonic: raise ValueError( f"{method} interpolation requires that the index be monotonic." ) # process 1-d slices in the axis direction def func(x): # process a 1-d slice, returning it # should the axis argument be handled below in apply_along_axis? # i.e. not an arg to missing.interpolate_1d return missing.interpolate_1d( index, x, method=method, limit=limit, limit_direction=limit_direction, limit_area=limit_area, fill_value=fill_value, bounds_error=False, **kwargs, ) # interp each column independently interp_values = np.apply_along_axis(func, axis, data) blocks = [self.make_block_same_class(interp_values)] return self._maybe_downcast(blocks, downcast) def take_nd(self, indexer, axis, new_mgr_locs=None, fill_tuple=None): """ Take values according to indexer and return them as a block.bb """ # algos.take_nd dispatches for DatetimeTZBlock, CategoricalBlock # so need to preserve types # sparse is treated like an ndarray, but needs .get_values() shaping values = self.values if fill_tuple is None: fill_value = self.fill_value allow_fill = False else: fill_value = fill_tuple[0] allow_fill = True new_values = algos.take_nd( values, indexer, axis=axis, allow_fill=allow_fill, fill_value=fill_value ) # Called from three places in managers, all of which satisfy # this assertion assert not (axis == 0 and new_mgr_locs is None) if new_mgr_locs is None: new_mgr_locs = self.mgr_locs if not is_dtype_equal(new_values.dtype, self.dtype): return self.make_block(new_values, new_mgr_locs) else: return self.make_block_same_class(new_values, new_mgr_locs) def diff(self, n: int, axis: int = 1) -> List["Block"]: """ return block for the diff of the values """ new_values = algos.diff(self.values, n, axis=axis, stacklevel=7) # We use block_shape for ExtensionBlock subclasses, which may call here # via a super. new_values = _block_shape(new_values, ndim=self.ndim) return [self.make_block(values=new_values)] def shift(self, periods, axis=0, fill_value=None): """ shift the block by periods, possibly upcast """ # convert integer to float if necessary. need to do a lot more than # that, handle boolean etc also new_values, fill_value = maybe_upcast(self.values, fill_value) # make sure array sent to np.roll is c_contiguous f_ordered = new_values.flags.f_contiguous if f_ordered: new_values = new_values.T axis = new_values.ndim - axis - 1 if np.prod(new_values.shape): new_values = np.roll(new_values, ensure_platform_int(periods), axis=axis) axis_indexer = [slice(None)] * self.ndim if periods > 0: axis_indexer[axis] = slice(None, periods) else: axis_indexer[axis] = slice(periods, None) new_values[tuple(axis_indexer)] = fill_value # restore original order if f_ordered: new_values = new_values.T return [self.make_block(new_values)] def where( self, other, cond, align=True, errors="raise", try_cast: bool = False, axis: int = 0, ) -> List["Block"]: """ evaluate the block; return result block(s) from the result Parameters ---------- other : a ndarray/object cond : the condition to respect align : boolean, perform alignment on other/cond errors : str, {'raise', 'ignore'}, default 'raise' - ``raise`` : allow exceptions to be raised - ``ignore`` : suppress exceptions. On error return original object axis : int Returns ------- a new block(s), the result of the func """ import pandas.core.computation.expressions as expressions assert errors in ["raise", "ignore"] transpose = self.ndim == 2 values = self.values orig_other = other if transpose: values = values.T other = getattr(other, "_values", getattr(other, "values", other)) cond = getattr(cond, "values", cond) # If the default broadcasting would go in the wrong direction, then # explicitly reshape other instead if getattr(other, "ndim", 0) >= 1: if values.ndim - 1 == other.ndim and axis == 1: other = other.reshape(tuple(other.shape + (1,))) elif transpose and values.ndim == self.ndim - 1: cond = cond.T if not hasattr(cond, "shape"): raise ValueError("where must have a condition that is ndarray like") # our where function def func(cond, values, other): if not ( (self.is_integer or self.is_bool) and lib.is_float(other) and np.isnan(other) ): # np.where will cast integer array to floats in this case if not self._can_hold_element(other): raise TypeError if lib.is_scalar(other) and isinstance(values, np.ndarray): other = convert_scalar(values, other) fastres = expressions.where(cond, values, other) return fastres if cond.ravel().all(): result = values else: # see if we can operate on the entire block, or need item-by-item # or if we are a single block (ndim == 1) try: result = func(cond, values, other) except TypeError: # we cannot coerce, return a compat dtype # we are explicitly ignoring errors block = self.coerce_to_target_dtype(other) blocks = block.where( orig_other, cond, align=align, errors=errors, try_cast=try_cast, axis=axis, ) return self._maybe_downcast(blocks, "infer") if self._can_hold_na or self.ndim == 1: if transpose: result = result.T return [self.make_block(result)] # might need to separate out blocks axis = cond.ndim - 1 cond = cond.swapaxes(axis, 0) mask = np.array([cond[i].all() for i in range(cond.shape[0])], dtype=bool) result_blocks = [] for m in [mask, ~mask]: if m.any(): taken = result.take(m.nonzero()[0], axis=axis) r = maybe_downcast_numeric(taken, self.dtype) nb = self.make_block(r.T, placement=self.mgr_locs[m]) result_blocks.append(nb) return result_blocks def equals(self, other) -> bool: if self.dtype != other.dtype or self.shape != other.shape: return False return array_equivalent(self.values, other.values) def _unstack(self, unstacker_func, new_columns, n_rows, fill_value): """Return a list of unstacked blocks of self Parameters ---------- unstacker_func : callable Partially applied unstacker. new_columns : Index All columns of the unstacked BlockManager. n_rows : int Only used in ExtensionBlock._unstack fill_value : int Only used in ExtensionBlock._unstack Returns ------- blocks : list of Block New blocks of unstacked values. mask : array_like of bool The mask of columns of `blocks` we should keep. """ unstacker = unstacker_func(self.values.T) new_items = unstacker.get_new_columns() new_placement = new_columns.get_indexer(new_items) new_values, mask = unstacker.get_new_values() mask = mask.any(0) new_values = new_values.T[mask] new_placement = new_placement[mask] blocks = [make_block(new_values, placement=new_placement)] return blocks, mask def quantile(self, qs, interpolation="linear", axis=0): """ compute the quantiles of the Parameters ---------- qs: a scalar or list of the quantiles to be computed interpolation: type of interpolation, default 'linear' axis: axis to compute, default 0 Returns ------- Block """ # We should always have ndim == 2 because Series dispatches to DataFrame assert self.ndim == 2 values = self.get_values() is_empty = values.shape[axis] == 0 orig_scalar = not is_list_like(qs) if orig_scalar: # make list-like, unpack later qs = [qs] if is_empty: # create the array of na_values # 2d len(values) * len(qs) result = np.repeat( np.array([self.fill_value] * len(qs)), len(values) ).reshape(len(values), len(qs)) else: # asarray needed for Sparse, see GH#24600 mask = np.asarray(isna(values)) result = nanpercentile( values, np.array(qs) * 100, axis=axis, na_value=self.fill_value, mask=mask, ndim=values.ndim, interpolation=interpolation, ) result = np.array(result, copy=False) result = result.T if orig_scalar and not lib.is_scalar(result): # result could be scalar in case with is_empty and self.ndim == 1 assert result.shape[-1] == 1, result.shape result = result[..., 0] result = lib.item_from_zerodim(result) ndim = np.ndim(result) return make_block(result, placement=np.arange(len(result)), ndim=ndim) def _replace_coerce( self, to_replace, value, inplace=True, regex=False, convert=False, mask=None ): """ Replace value corresponding to the given boolean array with another value. Parameters ---------- to_replace : object or pattern Scalar to replace or regular expression to match. value : object Replacement object. inplace : bool, default False Perform inplace modification. regex : bool, default False If true, perform regular expression substitution. convert : bool, default True If true, try to coerce any object types to better types. mask : array-like of bool, optional True indicate corresponding element is ignored. Returns ------- A new block if there is anything to replace or the original block. """ if mask.any(): if not regex: self = self.coerce_to_target_dtype(value) return self.putmask(mask, value, inplace=inplace) else: return self._replace_single( to_replace, value, inplace=inplace, regex=regex, convert=convert, mask=mask, ) return self class NonConsolidatableMixIn: """ hold methods for the nonconsolidatable blocks """ _can_consolidate = False _verify_integrity = False _validate_ndim = False def __init__(self, values, placement, ndim=None): """Initialize a non-consolidatable block. 'ndim' may be inferred from 'placement'. This will call continue to call __init__ for the other base classes mixed in with this Mixin. """ # Placement must be converted to BlockPlacement so that we can check # its length if not isinstance(placement, libinternals.BlockPlacement): placement = libinternals.BlockPlacement(placement) # Maybe infer ndim from placement if ndim is None: if len(placement) != 1: ndim = 1 else: ndim = 2 super().__init__(values, placement, ndim=ndim) @property def shape(self): if self.ndim == 1: return ((len(self.values)),) return (len(self.mgr_locs), len(self.values)) def iget(self, col): if self.ndim == 2 and isinstance(col, tuple): col, loc = col if not com.is_null_slice(col) and col != 0: raise IndexError(f"{self} only contains one item") elif isinstance(col, slice): if col != slice(None): raise NotImplementedError(col) return self.values[[loc]] return self.values[loc] else: if col != 0: raise IndexError(f"{self} only contains one item") return self.values def should_store(self, value): return isinstance(value, self._holder) def set(self, locs, values, check=False): assert locs.tolist() == [0] self.values = values def putmask(self, mask, new, align=True, inplace=False, axis=0, transpose=False): """ putmask the data to the block; we must be a single block and not generate other blocks return the resulting block Parameters ---------- mask : the condition to respect new : a ndarray/object align : boolean, perform alignment on other/cond, default is True inplace : perform inplace modification, default is False Returns ------- a new block, the result of the putmask """ inplace = validate_bool_kwarg(inplace, "inplace") # use block's copy logic. # .values may be an Index which does shallow copy by default new_values = self.values if inplace else self.copy().values if isinstance(new, np.ndarray) and len(new) == len(mask): new = new[mask] mask = _safe_reshape(mask, new_values.shape) new_values[mask] = new return [self.make_block(values=new_values)] def _get_unstack_items(self, unstacker, new_columns): """ Get the placement, values, and mask for a Block unstack. This is shared between ObjectBlock and ExtensionBlock. They differ in that ObjectBlock passes the values, while ExtensionBlock passes the dummy ndarray of positions to be used by a take later. Parameters ---------- unstacker : pandas.core.reshape.reshape._Unstacker new_columns : Index All columns of the unstacked BlockManager. Returns ------- new_placement : ndarray[int] The placement of the new columns in `new_columns`. new_values : Union[ndarray, ExtensionArray] The first return value from _Unstacker.get_new_values. mask : ndarray[bool] The second return value from _Unstacker.get_new_values. """ # shared with ExtensionBlock new_items = unstacker.get_new_columns() new_placement = new_columns.get_indexer(new_items) new_values, mask = unstacker.get_new_values() mask = mask.any(0) return new_placement, new_values, mask class ExtensionBlock(NonConsolidatableMixIn, Block): """Block for holding extension types. Notes ----- This holds all 3rd-party extension array types. It's also the immediate parent class for our internal extension types' blocks, CategoricalBlock. ExtensionArrays are limited to 1-D. """ is_extension = True def __init__(self, values, placement, ndim=None): values = self._maybe_coerce_values(values) super().__init__(values, placement, ndim) def _maybe_coerce_values(self, values): """ Unbox to an extension array. This will unbox an ExtensionArray stored in an Index or Series. ExtensionArrays pass through. No dtype coercion is done. Parameters ---------- values : Index, Series, ExtensionArray Returns ------- ExtensionArray """ return extract_array(values) @property def _holder(self): # For extension blocks, the holder is values-dependent. return type(self.values) @property def fill_value(self): # Used in reindex_indexer return self.values.dtype.na_value @property def _can_hold_na(self): # The default ExtensionArray._can_hold_na is True return self._holder._can_hold_na @property def is_view(self): """Extension arrays are never treated as views.""" return False @property def is_numeric(self): return self.values.dtype._is_numeric def setitem(self, indexer, value): """Set the value inplace, returning a same-typed block. This differs from Block.setitem by not allowing setitem to change the dtype of the Block. Parameters ---------- indexer : tuple, list-like, array-like, slice The subset of self.values to set value : object The value being set Returns ------- Block Notes ----- `indexer` is a direct slice/positional indexer. `value` must be a compatible shape. """ if isinstance(indexer, tuple): # we are always 1-D indexer = indexer[0] check_setitem_lengths(indexer, value, self.values) self.values[indexer] = value return self def get_values(self, dtype=None): # ExtensionArrays must be iterable, so this works. values = np.asarray(self.values) if values.ndim == self.ndim - 1: values = values.reshape((1,) + values.shape) return values def array_values(self) -> ExtensionArray: return self.values def to_dense(self): return np.asarray(self.values) def to_native_types(self, slicer=None, na_rep="nan", quoting=None, **kwargs): """override to use ExtensionArray astype for the conversion""" values = self.values if slicer is not None: values = values[slicer] mask = isna(values) values = np.asarray(values.astype(object)) values[mask] = na_rep # we are expected to return a 2-d ndarray return values.reshape(1, len(values)) def take_nd(self, indexer, axis=0, new_mgr_locs=None, fill_tuple=None): """ Take values according to indexer and return them as a block. """ if fill_tuple is None: fill_value = None else: fill_value = fill_tuple[0] # axis doesn't matter; we are really a single-dim object # but are passed the axis depending on the calling routing # if its REALLY axis 0, then this will be a reindex and not a take new_values = self.values.take(indexer, fill_value=fill_value, allow_fill=True) # Called from three places in managers, all of which satisfy # this assertion assert not (self.ndim == 1 and new_mgr_locs is None) if new_mgr_locs is None: new_mgr_locs = self.mgr_locs return self.make_block_same_class(new_values, new_mgr_locs) def _can_hold_element(self, element: Any) -> bool: # XXX: We may need to think about pushing this onto the array. # We're doing the same as CategoricalBlock here. return True def _slice(self, slicer): """ return a slice of my values """ # slice the category # return same dims as we currently have if isinstance(slicer, tuple) and len(slicer) == 2: if not com.is_null_slice(slicer[0]): raise AssertionError("invalid slicing for a 1-ndim categorical") slicer = slicer[1] return self.values[slicer] def concat_same_type(self, to_concat, placement=None): """ Concatenate list of single blocks of the same type. """ values = self._holder._concat_same_type([blk.values for blk in to_concat]) placement = placement or slice(0, len(values), 1) return self.make_block_same_class(values, ndim=self.ndim, placement=placement) def fillna(self, value, limit=None, inplace=False, downcast=None): values = self.values if inplace else self.values.copy() values = values.fillna(value=value, limit=limit) return [ self.make_block_same_class( values=values, placement=self.mgr_locs, ndim=self.ndim ) ] def interpolate( self, method="pad", axis=0, inplace=False, limit=None, fill_value=None, **kwargs ): values = self.values if inplace else self.values.copy() return self.make_block_same_class( values=values.fillna(value=fill_value, method=method, limit=limit), placement=self.mgr_locs, ) def diff(self, n: int, axis: int = 1) -> List["Block"]: if axis == 1: # we are by definition 1D. axis = 0 return super().diff(n, axis) def shift( self, periods: int, axis: int = 0, fill_value: Any = None, ) -> List["ExtensionBlock"]: """ Shift the block by `periods`. Dispatches to underlying ExtensionArray and re-boxes in an ExtensionBlock. """ return [ self.make_block_same_class( self.values.shift(periods=periods, fill_value=fill_value), placement=self.mgr_locs, ndim=self.ndim, ) ] def where( self, other, cond, align=True, errors="raise", try_cast: bool = False, axis: int = 0, ) -> List["Block"]: if isinstance(other, ABCDataFrame): # ExtensionArrays are 1-D, so if we get here then # `other` should be a DataFrame with a single column. assert other.shape[1] == 1 other = other.iloc[:, 0] other = extract_array(other, extract_numpy=True) if isinstance(cond, ABCDataFrame): assert cond.shape[1] == 1 cond = cond.iloc[:, 0] cond = extract_array(cond, extract_numpy=True) if lib.is_scalar(other) and isna(other): # The default `other` for Series / Frame is np.nan # we want to replace that with the correct NA value # for the type other = self.dtype.na_value if is_sparse(self.values): # TODO(SparseArray.__setitem__): remove this if condition # We need to re-infer the type of the data after doing the # where, for cases where the subtypes don't match dtype = None else: dtype = self.dtype result = self.values.copy() icond = ~cond if lib.is_scalar(other): set_other = other else: set_other = other[icond] try: result[icond] = set_other except (NotImplementedError, TypeError): # NotImplementedError for class not implementing `__setitem__` # TypeError for SparseArray, which implements just to raise # a TypeError result = self._holder._from_sequence( np.where(cond, self.values, other), dtype=dtype ) return [self.make_block_same_class(result, placement=self.mgr_locs)] @property def _ftype(self): return getattr(self.values, "_pandas_ftype", Block._ftype) def _unstack(self, unstacker_func, new_columns, n_rows, fill_value): # ExtensionArray-safe unstack. # We override ObjectBlock._unstack, which unstacks directly on the # values of the array. For EA-backed blocks, this would require # converting to a 2-D ndarray of objects. # Instead, we unstack an ndarray of integer positions, followed by # a `take` on the actual values. dummy_arr = np.arange(n_rows) dummy_unstacker = functools.partial(unstacker_func, fill_value=-1) unstacker = dummy_unstacker(dummy_arr) new_placement, new_values, mask = self._get_unstack_items( unstacker, new_columns ) blocks = [ self.make_block_same_class( self.values.take(indices, allow_fill=True, fill_value=fill_value), [place], ) for indices, place in zip(new_values.T, new_placement) ] return blocks, mask class ObjectValuesExtensionBlock(ExtensionBlock): """ Block providing backwards-compatibility for `.values`. Used by PeriodArray and IntervalArray to ensure that Series[T].values is an ndarray of objects. """ def external_values(self, dtype=None): return self.values.astype(object) class NumericBlock(Block): __slots__ = () is_numeric = True _can_hold_na = True class FloatOrComplexBlock(NumericBlock): __slots__ = () def equals(self, other) -> bool: if self.dtype != other.dtype or self.shape != other.shape: return False left, right = self.values, other.values return ((left == right) | (np.isnan(left) & np.isnan(right))).all() class FloatBlock(FloatOrComplexBlock): __slots__ = () is_float = True def _can_hold_element(self, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) if tipo is not None: return issubclass(tipo.type, (np.floating, np.integer)) and not issubclass( tipo.type, (np.datetime64, np.timedelta64) ) return isinstance( element, (float, int, np.floating, np.int_) ) and not isinstance( element, (bool, np.bool_, datetime, timedelta, np.datetime64, np.timedelta64), ) def to_native_types( self, slicer=None, na_rep="", float_format=None, decimal=".", quoting=None, **kwargs, ): """ convert to our native types format, slicing if desired """ values = self.values if slicer is not None: values = values[:, slicer] # see gh-13418: no special formatting is desired at the # output (important for appropriate 'quoting' behaviour), # so do not pass it through the FloatArrayFormatter if float_format is None and decimal == ".": mask = isna(values) if not quoting: values = values.astype(str) else: values = np.array(values, dtype="object") values[mask] = na_rep return values from pandas.io.formats.format import FloatArrayFormatter formatter = FloatArrayFormatter( values, na_rep=na_rep, float_format=float_format, decimal=decimal, quoting=quoting, fixed_width=False, ) return formatter.get_result_as_array() def should_store(self, value): # when inserting a column should not coerce integers to floats # unnecessarily return issubclass(value.dtype.type, np.floating) and value.dtype == self.dtype class ComplexBlock(FloatOrComplexBlock): __slots__ = () is_complex = True def _can_hold_element(self, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) if tipo is not None: return issubclass(tipo.type, (np.floating, np.integer, np.complexfloating)) return isinstance( element, (float, int, complex, np.float_, np.int_) ) and not isinstance(element, (bool, np.bool_)) def should_store(self, value): return issubclass(value.dtype.type, np.complexfloating) class IntBlock(NumericBlock): __slots__ = () is_integer = True _can_hold_na = False def _can_hold_element(self, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) if tipo is not None: return ( issubclass(tipo.type, np.integer) and not issubclass(tipo.type, (np.datetime64, np.timedelta64)) and self.dtype.itemsize >= tipo.itemsize ) return is_integer(element) def should_store(self, value): return is_integer_dtype(value) and value.dtype == self.dtype class DatetimeLikeBlockMixin: """Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock.""" @property def _holder(self): return DatetimeArray @property def fill_value(self): return np.datetime64("NaT", "ns") def get_values(self, dtype=None): """ return object dtype as boxed values, such as Timestamps/Timedelta """ if is_object_dtype(dtype): values = self.values.ravel() result = self._holder(values).astype(object) return result.reshape(self.values.shape) return self.values def iget(self, key): # GH#31649 we need to wrap scalars in Timestamp/Timedelta # TODO(EA2D): this can be removed if we ever have 2D EA result = super().iget(key) if isinstance(result, np.datetime64): result = Timestamp(result) elif isinstance(result, np.timedelta64): result = Timedelta(result) return result def shift(self, periods, axis=0, fill_value=None): # TODO(EA2D) this is unnecessary if these blocks are backed by 2D EAs values = self.array_values() new_values = values.shift(periods, fill_value=fill_value, axis=axis) return self.make_block_same_class(new_values) class DatetimeBlock(DatetimeLikeBlockMixin, Block): __slots__ = () is_datetime = True def __init__(self, values, placement, ndim=None): values = self._maybe_coerce_values(values) super().__init__(values, placement=placement, ndim=ndim) @property def _can_hold_na(self): return True def _maybe_coerce_values(self, values): """ Input validation for values passed to __init__. Ensure that we have datetime64ns, coercing if necessary. Parameters ---------- values : array-like Must be convertible to datetime64 Returns ------- values : ndarray[datetime64ns] Overridden by DatetimeTZBlock. """ if values.dtype != _NS_DTYPE: values = conversion.ensure_datetime64ns(values) if isinstance(values, DatetimeArray): values = values._data assert isinstance(values, np.ndarray), type(values) return values def astype(self, dtype, copy: bool = False, errors: str = "raise"): """ these automatically copy, so copy=True has no effect raise on an except if raise == True """ dtype = pandas_dtype(dtype) # if we are passed a datetime64[ns, tz] if is_datetime64tz_dtype(dtype): values = self.values if copy: # this should be the only copy values = values.copy() if getattr(values, "tz", None) is None: values = DatetimeArray(values).tz_localize("UTC") values = values.tz_convert(dtype.tz) return self.make_block(values) # delegate return super().astype(dtype=dtype, copy=copy, errors=errors) def _can_hold_element(self, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) if tipo is not None: if self.is_datetimetz: # require exact match, since non-nano does not exist return is_dtype_equal(tipo, self.dtype) or is_valid_nat_for_dtype( element, self.dtype ) # GH#27419 if we get a non-nano datetime64 object return is_datetime64_dtype(tipo) elif element is NaT: return True elif isinstance(element, datetime): if self.is_datetimetz: return tz_compare(element.tzinfo, self.dtype.tz) return element.tzinfo is None return is_valid_nat_for_dtype(element, self.dtype) def to_native_types( self, slicer=None, na_rep=None, date_format=None, quoting=None, **kwargs ): """ convert to our native types format, slicing if desired """ values = self.values i8values = self.values.view("i8") if slicer is not None: values = values[..., slicer] i8values = i8values[..., slicer] from pandas.io.formats.format import _get_format_datetime64_from_values fmt = _get_format_datetime64_from_values(values, date_format) result = tslib.format_array_from_datetime( i8values.ravel(), tz=getattr(self.values, "tz", None), format=fmt, na_rep=na_rep, ).reshape(i8values.shape) return np.atleast_2d(result) def should_store(self, value): return ( issubclass(value.dtype.type, np.datetime64) and not is_datetime64tz_dtype(value) and not is_extension_array_dtype(value) ) def set(self, locs, values): """ Modify Block in-place with new item value Returns ------- None """ values = conversion.ensure_datetime64ns(values, copy=False) self.values[locs] = values def external_values(self): return np.asarray(self.values.astype("datetime64[ns]", copy=False)) def array_values(self) -> ExtensionArray: return DatetimeArray._simple_new(self.values) class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): """ implement a datetime64 block with a tz attribute """ __slots__ = () is_datetimetz = True is_extension = True _can_hold_element = DatetimeBlock._can_hold_element to_native_types = DatetimeBlock.to_native_types fill_value = np.datetime64("NaT", "ns") @property def _holder(self): return DatetimeArray def _maybe_coerce_values(self, values): """Input validation for values passed to __init__. Ensure that we have datetime64TZ, coercing if necessary. Parameters ---------- values : array-like Must be convertible to datetime64 Returns ------- values : DatetimeArray """ if not isinstance(values, self._holder): values = self._holder(values) if values.tz is None: raise ValueError("cannot create a DatetimeTZBlock without a tz") return values @property def is_view(self): """ return a boolean if I am possibly a view """ # check the ndarray values of the DatetimeIndex values return self.values._data.base is not None def get_values(self, dtype=None): """ Returns an ndarray of values. Parameters ---------- dtype : np.dtype Only `object`-like dtypes are respected here (not sure why). Returns ------- values : ndarray When ``dtype=object``, then and object-dtype ndarray of boxed values is returned. Otherwise, an M8[ns] ndarray is returned. DatetimeArray is always 1-d. ``get_values`` will reshape the return value to be the same dimensionality as the block. """ values = self.values if is_object_dtype(dtype): values = values.astype(object) values = np.asarray(values) if self.ndim == 2: # Ensure that our shape is correct for DataFrame. # ExtensionArrays are always 1-D, even in a DataFrame when # the analogous NumPy-backed column would be a 2-D ndarray. values = values.reshape(1, -1) return values def to_dense(self): # we request M8[ns] dtype here, even though it discards tzinfo, # as lots of code (e.g. anything using values_from_object) # expects that behavior. return np.asarray(self.values, dtype=_NS_DTYPE) def _slice(self, slicer): """ return a slice of my values """ if isinstance(slicer, tuple): col, loc = slicer if not com.is_null_slice(col) and col != 0: raise IndexError(f"{self} only contains one item") return self.values[loc] return self.values[slicer] def diff(self, n: int, axis: int = 0) -> List["Block"]: """ 1st discrete difference. Parameters ---------- n : int Number of periods to diff. axis : int, default 0 Axis to diff upon. Returns ------- A list with a new TimeDeltaBlock. Notes ----- The arguments here are mimicking shift so they are called correctly by apply. """ if axis == 0: # Cannot currently calculate diff across multiple blocks since this # function is invoked via apply raise NotImplementedError new_values = (self.values - self.shift(n, axis=axis)[0].values).asi8 # Reshape the new_values like how algos.diff does for timedelta data new_values = new_values.reshape(1, len(new_values)) new_values = new_values.astype("timedelta64[ns]") return [TimeDeltaBlock(new_values, placement=self.mgr_locs.indexer)] def concat_same_type(self, to_concat, placement=None): # need to handle concat([tz1, tz2]) here, since DatetimeArray # only handles cases where all the tzs are the same. # Instead of placing the condition here, it could also go into the # is_uniform_join_units check, but I'm not sure what is better. if len({x.dtype for x in to_concat}) > 1: values = concat_datetime([x.values for x in to_concat]) placement = placement or slice(0, len(values), 1) if self.ndim > 1: values = np.atleast_2d(values) return ObjectBlock(values, ndim=self.ndim, placement=placement) return super().concat_same_type(to_concat, placement) def fillna(self, value, limit=None, inplace=False, downcast=None): # We support filling a DatetimeTZ with a `value` whose timezone # is different by coercing to object. if self._can_hold_element(value): return super().fillna(value, limit, inplace, downcast) # different timezones, or a non-tz return self.astype(object).fillna( value, limit=limit, inplace=inplace, downcast=downcast ) def setitem(self, indexer, value): # https://github.com/pandas-dev/pandas/issues/24020 # Need a dedicated setitem until #24020 (type promotion in setitem # for extension arrays) is designed and implemented. if self._can_hold_element(value) or ( isinstance(indexer, np.ndarray) and indexer.size == 0 ): return super().setitem(indexer, value) obj_vals = self.values.astype(object) newb = make_block( obj_vals, placement=self.mgr_locs, klass=ObjectBlock, ndim=self.ndim ) return newb.setitem(indexer, value) def equals(self, other) -> bool: # override for significant performance improvement if self.dtype != other.dtype or self.shape != other.shape: return False return (self.values.view("i8") == other.values.view("i8")).all() def quantile(self, qs, interpolation="linear", axis=0): naive = self.values.view("M8[ns]") # kludge for 2D block with 1D values naive = naive.reshape(self.shape) blk = self.make_block(naive) res_blk = blk.quantile(qs, interpolation=interpolation, axis=axis) # ravel is kludge for 2D block with 1D values, assumes column-like aware = self._holder(res_blk.values.ravel(), dtype=self.dtype) return self.make_block_same_class(aware, ndim=res_blk.ndim) class TimeDeltaBlock(DatetimeLikeBlockMixin, IntBlock): __slots__ = () is_timedelta = True _can_hold_na = True is_numeric = False fill_value = np.timedelta64("NaT", "ns") def __init__(self, values, placement, ndim=None): if values.dtype != _TD_DTYPE: values = conversion.ensure_timedelta64ns(values) if isinstance(values, TimedeltaArray): values = values._data assert isinstance(values, np.ndarray), type(values) super().__init__(values, placement=placement, ndim=ndim) @property def _holder(self): return TimedeltaArray def _can_hold_element(self, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) if tipo is not None: return issubclass(tipo.type, np.timedelta64) elif element is NaT: return True elif isinstance(element, (timedelta, np.timedelta64)): return True return is_valid_nat_for_dtype(element, self.dtype) def fillna(self, value, **kwargs): # allow filling with integers to be # interpreted as nanoseconds if is_integer(value): # Deprecation GH#24694, GH#19233 raise TypeError( "Passing integers to fillna for timedelta64[ns] dtype is no " "longer supported. To obtain the old behavior, pass " "`pd.Timedelta(seconds=n)` instead." ) return super().fillna(value, **kwargs) def should_store(self, value): return issubclass( value.dtype.type, np.timedelta64 ) and not is_extension_array_dtype(value) def to_native_types(self, slicer=None, na_rep=None, quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values if slicer is not None: values = values[:, slicer] mask = isna(values) rvalues = np.empty(values.shape, dtype=object) if na_rep is None: na_rep = "NaT" rvalues[mask] = na_rep imask = (~mask).ravel() # FIXME: # should use the formats.format.Timedelta64Formatter here # to figure what format to pass to the Timedelta # e.g. to not show the decimals say rvalues.flat[imask] = np.array( [Timedelta(val)._repr_base(format="all") for val in values.ravel()[imask]], dtype=object, ) return rvalues def external_values(self, dtype=None): return np.asarray(self.values.astype("timedelta64[ns]", copy=False)) def array_values(self) -> ExtensionArray: return TimedeltaArray._simple_new(self.values) class BoolBlock(NumericBlock): __slots__ = () is_bool = True _can_hold_na = False def _can_hold_element(self, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) if tipo is not None: return issubclass(tipo.type, np.bool_) return isinstance(element, (bool, np.bool_)) def should_store(self, value): return issubclass(value.dtype.type, np.bool_) and not is_extension_array_dtype( value ) def replace( self, to_replace, value, inplace=False, filter=None, regex=False, convert=True ): inplace = validate_bool_kwarg(inplace, "inplace") to_replace_values = np.atleast_1d(to_replace) if not np.can_cast(to_replace_values, bool): return self return super().replace( to_replace, value, inplace=inplace, filter=filter, regex=regex, convert=convert, ) class ObjectBlock(Block): __slots__ = () is_object = True _can_hold_na = True def __init__(self, values, placement=None, ndim=2): if issubclass(values.dtype.type, str): values = np.array(values, dtype=object) super().__init__(values, ndim=ndim, placement=placement) @property def is_bool(self): """ we can be a bool if we have only bool values but are of type object """ return lib.is_bool_array(self.values.ravel()) def convert( self, copy: bool = True, datetime: bool = True, numeric: bool = True, timedelta: bool = True, coerce: bool = False, ): """ attempt to coerce any object types to better types return a copy of the block (if copy = True) by definition we ARE an ObjectBlock!!!!! can return multiple blocks! """ # operate column-by-column def f(mask, val, idx): shape = val.shape values = soft_convert_objects( val.ravel(), datetime=datetime, numeric=numeric, timedelta=timedelta, coerce=coerce, copy=copy, ) if isinstance(values, np.ndarray): # TODO: allow EA once reshape is supported values = values.reshape(shape) values = _block_shape(values, ndim=self.ndim) return values if self.ndim == 2: blocks = self.split_and_operate(None, f, False) else: values = f(None, self.values.ravel(), None) blocks = [make_block(values, ndim=self.ndim, placement=self.mgr_locs)] return blocks def _maybe_downcast(self, blocks: List["Block"], downcast=None) -> List["Block"]: if downcast is not None: return blocks # split and convert the blocks return _extend_blocks([b.convert(datetime=True, numeric=False) for b in blocks]) def _can_hold_element(self, element: Any) -> bool: return True def should_store(self, value): return not ( issubclass( value.dtype.type, (np.integer, np.floating, np.complexfloating, np.datetime64, np.bool_), ) or is_extension_array_dtype(value) ) def replace( self, to_replace, value, inplace=False, filter=None, regex=False, convert=True ): to_rep_is_list = is_list_like(to_replace) value_is_list = is_list_like(value) both_lists = to_rep_is_list and value_is_list either_list = to_rep_is_list or value_is_list result_blocks = [] blocks = [self] if not either_list and is_re(to_replace): return self._replace_single( to_replace, value, inplace=inplace, filter=filter, regex=True, convert=convert, ) elif not (either_list or regex): return super().replace( to_replace, value, inplace=inplace, filter=filter, regex=regex, convert=convert, ) elif both_lists: for to_rep, v in zip(to_replace, value): result_blocks = [] for b in blocks: result = b._replace_single( to_rep, v, inplace=inplace, filter=filter, regex=regex, convert=convert, ) result_blocks = _extend_blocks(result, result_blocks) blocks = result_blocks return result_blocks elif to_rep_is_list and regex: for to_rep in to_replace: result_blocks = [] for b in blocks: result = b._replace_single( to_rep, value, inplace=inplace, filter=filter, regex=regex, convert=convert, ) result_blocks = _extend_blocks(result, result_blocks) blocks = result_blocks return result_blocks return self._replace_single( to_replace, value, inplace=inplace, filter=filter, convert=convert, regex=regex, ) def _replace_single( self, to_replace, value, inplace=False, filter=None, regex=False, convert=True, mask=None, ): """ Replace elements by the given value. Parameters ---------- to_replace : object or pattern Scalar to replace or regular expression to match. value : object Replacement object. inplace : bool, default False Perform inplace modification. filter : list, optional regex : bool, default False If true, perform regular expression substitution. convert : bool, default True If true, try to coerce any object types to better types. mask : array-like of bool, optional True indicate corresponding element is ignored. Returns ------- a new block, the result after replacing """ inplace = validate_bool_kwarg(inplace, "inplace") # to_replace is regex compilable to_rep_re = regex and is_re_compilable(to_replace) # regex is regex compilable regex_re = is_re_compilable(regex) # only one will survive if to_rep_re and regex_re: raise AssertionError( "only one of to_replace and regex can be regex compilable" ) # if regex was passed as something that can be a regex (rather than a # boolean) if regex_re: to_replace = regex regex = regex_re or to_rep_re # try to get the pattern attribute (compiled re) or it's a string if is_re(to_replace): pattern = to_replace.pattern else: pattern = to_replace # if the pattern is not empty and to_replace is either a string or a # regex if regex and pattern: rx = re.compile(to_replace) else: # if the thing to replace is not a string or compiled regex call # the superclass method -> to_replace is some kind of object return super().replace( to_replace, value, inplace=inplace, filter=filter, regex=regex ) new_values = self.values if inplace else self.values.copy() # deal with replacing values with objects (strings) that match but # whose replacement is not a string (numeric, nan, object) if isna(value) or not isinstance(value, str): def re_replacer(s): if is_re(rx) and isinstance(s, str): return value if rx.search(s) is not None else s else: return s else: # value is guaranteed to be a string here, s can be either a string # or null if it's null it gets returned def re_replacer(s): if is_re(rx) and isinstance(s, str): return rx.sub(value, s) else: return s f = np.vectorize(re_replacer, otypes=[self.dtype]) if filter is None: filt = slice(None) else: filt = self.mgr_locs.isin(filter).nonzero()[0] if mask is None: new_values[filt] = f(new_values[filt]) else: new_values[filt][mask] = f(new_values[filt][mask]) # convert block = self.make_block(new_values) if convert: block = block.convert(numeric=False) return block def _replace_coerce( self, to_replace, value, inplace=True, regex=False, convert=False, mask=None ): """ Replace value corresponding to the given boolean array with another value. Parameters ---------- to_replace : object or pattern Scalar to replace or regular expression to match. value : object Replacement object. inplace : bool, default False Perform inplace modification. regex : bool, default False If true, perform regular expression substitution. convert : bool, default True If true, try to coerce any object types to better types. mask : array-like of bool, optional True indicate corresponding element is ignored. Returns ------- A new block if there is anything to replace or the original block. """ if mask.any(): block = super()._replace_coerce( to_replace=to_replace, value=value, inplace=inplace, regex=regex, convert=convert, mask=mask, ) if convert: block = [b.convert(numeric=False, copy=True) for b in block] return block if convert: return [self.convert(numeric=False, copy=True)] return self class CategoricalBlock(ExtensionBlock): __slots__ = () is_categorical = True _verify_integrity = True _can_hold_na = True _concatenator = staticmethod(concat_categorical) def __init__(self, values, placement, ndim=None): # coerce to categorical if we can values = extract_array(values) assert isinstance(values, Categorical), type(values) super().__init__(values, placement=placement, ndim=ndim) @property def _holder(self): return Categorical @property def array_dtype(self): """ the dtype to return if I want to construct this block as an array """ return np.object_ def to_dense(self): # Categorical.get_values returns a DatetimeIndex for datetime # categories, so we can't simply use `np.asarray(self.values)` like # other types. return self.values._internal_get_values() def to_native_types(self, slicer=None, na_rep="", quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values if slicer is not None: # Categorical is always one dimension values = values[slicer] mask = isna(values) values = np.array(values, dtype="object") values[mask] = na_rep # we are expected to return a 2-d ndarray return values.reshape(1, len(values)) def concat_same_type(self, to_concat, placement=None): """ Concatenate list of single blocks of the same type. Note that this CategoricalBlock._concat_same_type *may* not return a CategoricalBlock. When the categories in `to_concat` differ, this will return an object ndarray. If / when we decide we don't like that behavior: 1. Change Categorical._concat_same_type to use union_categoricals 2. Delete this method. """ values = self._concatenator( [blk.values for blk in to_concat], axis=self.ndim - 1 ) # not using self.make_block_same_class as values can be object dtype return make_block( values, placement=placement or slice(0, len(values), 1), ndim=self.ndim ) def replace( self, to_replace, value, inplace: bool = False, filter=None, regex: bool = False, convert: bool = True, ): inplace = validate_bool_kwarg(inplace, "inplace") result = self if inplace else self.copy() if filter is None: # replace was called on a series result.values.replace(to_replace, value, inplace=True) if convert: return result.convert(numeric=False, copy=not inplace) else: return result else: # replace was called on a DataFrame if not isna(value): result.values.add_categories(value, inplace=True) return super(CategoricalBlock, result).replace( to_replace, value, inplace, filter, regex, convert ) # ----------------------------------------------------------------- # Constructor Helpers def get_block_type(values, dtype=None): """ Find the appropriate Block subclass to use for the given values and dtype. Parameters ---------- values : ndarray-like dtype : numpy or pandas dtype Returns ------- cls : class, subclass of Block """ dtype = dtype or values.dtype vtype = dtype.type if is_sparse(dtype): # Need this first(ish) so that Sparse[datetime] is sparse cls = ExtensionBlock elif is_categorical(values): cls = CategoricalBlock elif issubclass(vtype, np.datetime64): assert not is_datetime64tz_dtype(values) cls = DatetimeBlock elif is_datetime64tz_dtype(values): cls = DatetimeTZBlock elif is_interval_dtype(dtype) or is_period_dtype(dtype): cls = ObjectValuesExtensionBlock elif is_extension_array_dtype(values): cls = ExtensionBlock elif issubclass(vtype, np.floating): cls = FloatBlock elif issubclass(vtype, np.timedelta64): assert issubclass(vtype, np.integer) cls = TimeDeltaBlock elif issubclass(vtype, np.complexfloating): cls = ComplexBlock elif issubclass(vtype, np.integer): cls = IntBlock elif dtype == np.bool_: cls = BoolBlock else: cls = ObjectBlock return cls def make_block(values, placement, klass=None, ndim=None, dtype=None): # Ensure that we don't allow PandasArray / PandasDtype in internals. # For now, blocks should be backed by ndarrays when possible. if isinstance(values, ABCPandasArray): values = values.to_numpy() if ndim and ndim > 1: values = np.atleast_2d(values) if isinstance(dtype, PandasDtype): dtype = dtype.numpy_dtype if klass is None: dtype = dtype or values.dtype klass = get_block_type(values, dtype) elif klass is DatetimeTZBlock and not is_datetime64tz_dtype(values): # TODO: This is no longer hit internally; does it need to be retained # for e.g. pyarrow? values = DatetimeArray._simple_new(values, dtype=dtype) return klass(values, ndim=ndim, placement=placement) # ----------------------------------------------------------------- def _extend_blocks(result, blocks=None): """ return a new extended blocks, given the result """ from pandas.core.internals import BlockManager if blocks is None: blocks = [] if isinstance(result, list): for r in result: if isinstance(r, list): blocks.extend(r) else: blocks.append(r) elif isinstance(result, BlockManager): blocks.extend(result.blocks) else: blocks.append(result) return blocks def _block_shape(values, ndim=1, shape=None): """ guarantee the shape of the values to be at least 1 d """ if values.ndim < ndim: if shape is None: shape = values.shape if not is_extension_array_dtype(values): # TODO: https://github.com/pandas-dev/pandas/issues/23023 # block.shape is incorrect for "2D" ExtensionArrays # We can't, and don't need to, reshape. values = values.reshape(tuple((1,) + shape)) return values def _merge_blocks(blocks, dtype=None, _can_consolidate=True): if len(blocks) == 1: return blocks[0] if _can_consolidate: if dtype is None: if len({b.dtype for b in blocks}) != 1: raise AssertionError("_merge_blocks are invalid!") # FIXME: optimization potential in case all mgrs contain slices and # combination of those slices is a slice, too. new_mgr_locs = np.concatenate([b.mgr_locs.as_array for b in blocks]) new_values = np.vstack([b.values for b in blocks]) argsort = np.argsort(new_mgr_locs) new_values = new_values[argsort] new_mgr_locs = new_mgr_locs[argsort] return make_block(new_values, placement=new_mgr_locs) # no merge return blocks def _safe_reshape(arr, new_shape): """ If possible, reshape `arr` to have shape `new_shape`, with a couple of exceptions (see gh-13012): 1) If `arr` is a ExtensionArray or Index, `arr` will be returned as is. 2) If `arr` is a Series, the `_values` attribute will be reshaped and returned. Parameters ---------- arr : array-like, object to be reshaped new_shape : int or tuple of ints, the new shape """ if isinstance(arr, ABCSeries): arr = arr._values if not isinstance(arr, ABCExtensionArray): arr = arr.reshape(new_shape) return arr def _putmask_smart(v, mask, n): """ Return a new ndarray, try to preserve dtype if possible. Parameters ---------- v : `values`, updated in-place (array like) mask : np.ndarray Applies to both sides (array like). n : `new values` either scalar or an array like aligned with `values` Returns ------- values : ndarray with updated values this *may* be a copy of the original See Also -------- ndarray.putmask """ # we cannot use np.asarray() here as we cannot have conversions # that numpy does when numeric are mixed with strings # n should be the length of the mask or a scalar here if not is_list_like(n): n = np.repeat(n, len(mask)) # see if we are only masking values that if putted # will work in the current dtype try: nn = n[mask] except TypeError: # TypeError: only integer scalar arrays can be converted to a scalar index pass else: # make sure that we have a nullable type # if we have nulls if not _isna_compat(v, nn[0]): pass elif not (is_float_dtype(nn.dtype) or is_integer_dtype(nn.dtype)): # only compare integers/floats pass elif not (is_float_dtype(v.dtype) or is_integer_dtype(v.dtype)): # only compare integers/floats pass else: # we ignore ComplexWarning here with warnings.catch_warnings(record=True): warnings.simplefilter("ignore", np.ComplexWarning) nn_at = nn.astype(v.dtype) comp = nn == nn_at if is_list_like(comp) and comp.all(): nv = v.copy() nv[mask] = nn_at return nv n = np.asarray(n) def _putmask_preserve(nv, n): try: nv[mask] = n[mask] except (IndexError, ValueError): nv[mask] = n return nv # preserves dtype if possible if v.dtype.kind == n.dtype.kind: return _putmask_preserve(v, n) # change the dtype if needed dtype, _ = maybe_promote(n.dtype) if is_extension_array_dtype(v.dtype) and is_object_dtype(dtype): v = v._internal_get_values(dtype) else: v = v.astype(dtype) return _putmask_preserve(v, n)
[ "44142880+GregVargas1999@users.noreply.github.com" ]
44142880+GregVargas1999@users.noreply.github.com
40b189e2c7cf87e2f9c04dc040bffae8b304ffa8
36908b333699e76e7ca065795bdb3fddabbee9a7
/scribble_root/scribble/views.py
b79c90fad6d836cb2d2fbbcfcbbe16dc437dab18
[]
no_license
caseymccullough/scribble
606511fd38d25d2ab148690a3ff0d3b3e9dbb407
179277fe324b8cea3fa5b05896c027f2427a7c0f
refs/heads/main
2023-04-03T01:59:20.628177
2021-04-20T12:56:20
2021-04-20T12:56:20
359,178,333
0
0
null
null
null
null
UTF-8
Python
false
false
3,459
py
from django.shortcuts import render, redirect from .models import Post, Comment from .forms import PostForm, CommentForm # Index # New # Destroy # Update # Create # Edit # Show #Index Posts def post_list(request): posts = Post.objects.all() return render(request, 'scribble/post_list.html', {'posts': posts}) # posts: posts is a key value pair #Index Comments def comment_list(request): comments = Comment.objects.all() return render (request, 'scribble/comment_list.html', {'comments': comments}) #New Post def post_create(request): if request.method == "POST": #create a form instance and populate with data form = PostForm(request.POST) #check whether it's valid if form.is_valid(): #Save new post and redirect to show page post = form.save() return redirect('post_detail', pk = post.pk) else: form = PostForm() return render(request, 'scribble/post_form.html', {'form': form}) #New Comment def comment_create(request): if request.method == "POST": #create a comment instance and populate with data form = CommentForm(request.POST) #check whether it's valid if form.is_valid(): #Save new post and redirect to show page comment = form.save() # there is no comment detail, so go to associated post. # !! valid syntax? return redirect('post_detail', pk = comment.post.pk) else: form = CommentForm() return render(request, 'scribble/comment_form.html', {'form': form}) # Destroy a Post def post_delete(request, pk): Post.objects.get(id=pk).delete() # back to post list page return redirect('post_list') # Destroy a Comment def comment_delete(request, pk): post_pk = Comment.objects.get(id=pk).post.id Comment.objects.get(id=pk).delete() # back to post list page ## !! change to current post? return redirect('post_detail', pk = post_pk) # Update / Edit Post def post_edit (request, pk): post = Post.objects.get(pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save() # data now from form prev from db return redirect('post_detail', pk=post.pk) else: # they are requesting to get the form form = PostForm(instance = post) # populate with current data return render(request, 'scribble/post_form.html', {'form': form}) # Update / Edit Comment def comment_edit (request, pk): comment = Comment.objects.get(pk=pk) if request.method == "POST": # populate form with current data form = CommentForm(request.POST, instance=comment) if form.is_valid(): comment = form.save() # data now from form prev from db return redirect('post_detail', pk=comment.post.pk) else: # they are requesting to get the form form = CommentForm(instance = comment) # populate with current data return render(request, 'scribble/comment_form.html', {'form': form}) # Show individual post w/ associated comments def post_detail(request, pk): post = Post.objects.get(id=pk) return render(request, 'scribble/post_detail.html', {'post': post}) # Show individual comment def comment_detail(request, pk): comment = Comment.objects.get(id=pk) return render(request, 'scribble/comment_detail.html', {'comment': comment})
[ "kcmccullough@gmail.com" ]
kcmccullough@gmail.com