def load_font(font_file, font_size): """ Returns the font as a texture and a mapping of its values. """ image = Image(font_file).texture tex_w, tex_h = image.size font_w, font_h = font_size uvmap = {} char_ord = 0 range_x = range(0, tex_w, font_w) range_y = range(0, tex_h, font_h) for y0, x0 in itertools.product(range_y, range_x): x1, y1 = x0 + font_w, y0 + font_h uvmap[char_ord] = UVMapping( x0 / tex_w, y0 / tex_h, x1 / tex_w, y1 / tex_h, font_w * 0.5, font_h * 0.5, ) char_ord += 1 return image, uvmap
def main(): t=int(input()) for _ in range(t): n=int(input()) p=list(map(int,input().split())) m=-1 p1=[] curr=0 s=[] for i in range(n): if(p[i]>m): m=p[i] p1.append(s) s=[] s.append(p[i]) else: s.append(p[i]) p1.append(s) p1=p1[1:] p1.sort(reverse=True) for i in range(len(p1)): for j in p1[i]: print(j,end=" ") print()
def main(): t=int(input()) for _ in range(t): n,U,R,D,L=map(int,input().split()) ll=[U,R,D,L] perm = [] for i in range(4): perm.append(ll[i+1:]+ll[:i+1]) ff=True print(perm) for i in list(perm): u,r,d,l=i[0],i[1],i[2],i[3] if(r==n or l==n): ff=False if(u==0): if(d==0 and (r==n-1 or l==n-1)): ff=False elif(d==1 and (r==n-1 and l==n-1)): ff=False if(u==1): if((r==n or l==n)): if(ff): print("YES") else: print("NO")
def main(): t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) c = [0, 0, 0] for i in range(n): if (a[i] % 3 == 0): c[0] += 1 elif (a[i] % 3 == 1): c[1] += 1 else: c[2] += 1 target = n // 3 count = 0 while (check(c)): i = c.index(max(c)) while (c[i] != target and c[i] > target): c[i] -= 1 c[(i + 1) % 3] += 1 count += 1 print(count)
def main(): t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) d = Counter(a) cs = set() l = [] s = 0 for i in d: l.append(d[i]) cs.add(d[i]) s += d[i] cs = sorted(list(cs)) prefix = Counter() dd = Counter(l) prefix[cs[0]] = cs[0] * dd[cs[0]] for c in range(1, len(cs)): prefix[cs[c]] += (prefix[cs[c - 1]] + cs[c] * dd[cs[c]]) ans = 0 for x in range(1, len(cs)): ans += ((cs[x] - cs[0]) * dd[cs[x]]) for c in range(1, len(cs)): s = prefix[cs[c - 1]] for x in range(c + 1, len(cs)): s += ((cs[x] - cs[c]) * dd[cs[x]]) ans = min(ans, s) print(ans)
def GetGains_Cosmics(amplist): histmin = 0 histmax = 100 nbins = 50 fitmin = 12 fitmax = 60 mpvs, mpvs_errors, chisqrs = [], [], [] for amp in range(N_AMPS): c3 = TCanvas( 'canvas', 'canvas', 500, 200, 700, 500 ) #create canvas landau_hist = TH1F('dE/dx', 'Muon energy spectrum - Amp ' + str(amp),nbins,histmin,histmax) for i, stat in enumerate(amplist[amp]): # if i % 4 == 0: landau_hist.Fill(stat.de_dx) landau_hist.Fill(stat.de_dx) landau_hist.Draw() landau_hist.GetXaxis().SetTitle('dE/dx (ADU/#mum)') landau_hist.GetYaxis().SetTitle('Frequency') langaus_func, chisqr = LanGausFit(landau_hist, fitmin,fitmax) langaus_func.SetNpx(1000) langaus_func.Draw("same") # langaus_func = LandauFit(landau_hist, fitmin,fitmax) # langaus_func.SetNpx(1000) # langaus_func.Draw("same") # chisqr = 0 mpvs.append(langaus_func.GetParameter(1)) mpvs_errors.append(langaus_func.GetParError(1)) chisqrs.append(chisqr) legend = TPaveText(0.65,0.68,0.99,0.93,"NDC") legend.SetTextAlign(12) legend.SetFillColor(0) legend.AddText("MPV = " + str(round(mpvs[amp],2)) + " #pm " + str(round(mpvs_errors[amp],2)) + " ADU") legend.AddText("Entries = " + str(landau_hist.GetEntries())) legend.AddText("#chi^{2}_{red} = " + str(round(chisqr,2))) legend.Draw("same") c3.SaveAs(OUTPUT_PATH + "amp" + str(zfill(str(amp),2)) +"dedx_hist" + FILE_TYPE) del c3 del landau_hist tot_chi_sq = 0 for i in range(N_AMPS): print "Amp " + str(i) + " ChiSq = \t" + str(chisqrs[i]) tot_chi_sq += chisqrs[i] avg_chi_sq = tot_chi_sq/len(chisqrs) print "Avg ChiSq = " + str(avg_chi_sq) + "\n" GLOBAL_OUT.append("Avg ChiSq = " + str(avg_chi_sq)) for i in range(N_AMPS): print "Amp " + str(i) + " MPV = \t" + str(mpvs[i]) # print "Worst cosmic fit has Chisq_red of %.2f" %chisqrs.sort[0] # chisqrs.sort(cmp=None, key=None, reverse=False) return mpvs, mpvs_errors, chisqrs
def visualize_grid(Xs, ubound=255.0, padding=1): """ Reshape a 4D tensor of image data to a grid for easy visualization. Inputs: - Xs: Data of shape (N, H, W, C) - ubound: Output grid will have values scaled to the range [0, ubound] - padding: The number of blank pixels between elements of the grid """ (N, H, W, C) = Xs.shape grid_size = int(ceil(sqrt(N))) grid_height = H * grid_size + padding * (grid_size - 1) grid_width = W * grid_size + padding * (grid_size - 1) grid = np.zeros((grid_height, grid_width, C)) next_idx = 0 y0, y1 = 0, H for y in range(grid_size): x0, x1 = 0, W for x in range(grid_size): if next_idx < N: img = Xs[next_idx] low, high = np.min(img), np.max(img) grid[y0:y1, x0:x1] = ubound * (img - low) / (high - low) # grid[y0:y1, x0:x1] = Xs[next_idx] next_idx += 1 x0 += W + padding x1 += W + padding y0 += H + padding y1 += H + padding # grid_max = np.max(grid) # grid_min = np.min(grid) # grid = ubound * (grid - grid_min) / (grid_max - grid_min) return grid
def main(): n = int(input()) arr = list(map(int, input().split())) q = int(input()) dict1 = {} max1 = [] for i in range(q): temp = list(map(int, input().split())) if (len(temp) == 2): max1.append(temp[1]) else: dict1[temp[1]] = [temp[2], i] max1.append(-1) maxVal = max1[-1] for i in range(q - 2, -1, -1): if (max1[i] > maxVal): maxVal = max1[i] elif (max1[i] < maxVal): max1[i] = maxVal for i in range(n): if ((i + 1) in dict1): arr[i] = max(dict1[i + 1][0], max1[dict1[i + 1][1]]) else: arr[i] = max(arr[i], max1[0]) for x in arr: print(x, end=" ") print()
def showDsweep(): k_s_sweep = [10**(x-5) for x in range(10)] sl_div_diam_sweep = [5.0*(x+1)/1000 for x in range(20)] vol_ratio_sweep = [5.0*(x+1)/100 for x in range(10)] Dmsd = numpy.load(data_dir + "/D_numpy.npy") kDa = 1.660538921e-30; mass = 40.0*kDa; viscosity = 8.9e-4; diameter = 5e-9; T = 300.0; Dbase = k_b*T/(3.0*numpy.pi*viscosity*diameter); Dmsd = Dmsd/Dbase mlab.figure(1, size=(800, 800), fgcolor=(1, 1, 1), bgcolor=(0.5, 0.5, 0.5)) mlab.clf() contours = numpy.arange(0.01,2,0.2).tolist() obj = mlab.contour3d(Dmsd,contours=contours,transparent=True,vmin=contours[0],vmax=contours[-1]) outline = mlab.outline(color=(.7, .7, .7),extent=(0,10,0,20,0,10)) axes = mlab.axes(outline, color=(.7, .7, .7), nb_labels = 5, ranges=(k_s_sweep[0], k_s_sweep[-1], sl_div_diam_sweep[0], sl_div_diam_sweep[-1], vol_ratio_sweep[0], vol_ratio_sweep[-1]), xlabel='spring stiffness', ylabel='step length', zlabel='volume ratio') mlab.colorbar(obj,title='D',nb_labels=5) mlab.show()
def max_pool_forward_naive(x, pool_param): """ A naive implementation of the forward pass for a max pooling layer. Inputs: - x: Input data, of shape (N, C, H, W) - pool_param: dictionary with the following keys: - 'pool_height': The height of each pooling region - 'pool_width': The width of each pooling region - 'stride': The distance between adjacent pooling regions Returns a tuple of: - out: Output data - cache: (x, pool_param) """ out = None ########################################################################### # TODO: Implement the max pooling forward pass # ########################################################################### pass pool_height, pool_width, stride = pool_param['pool_height'], pool_param['pool_width'], pool_param['stride'] N, C, H, W = x.shape H_t = H/pool_height W_t = W/pool_width out = np.zeros((N,C,H_t, W_t)) for i in range(H_t): for j in range(W_t): out[:,:,i,j] = np.max(x[:,:,i*stride:i*stride+pool_height,j*stride:j*stride+pool_width], axis = (2,3)) ########################################################################### # END OF YOUR CODE # ########################################################################### cache = (x, pool_param) return out, cache
def max_pool_backward_naive(dout, cache): """ A naive implementation of the backward pass for a max pooling layer. Inputs: - dout: Upstream derivatives - cache: A tuple of (x, pool_param) as in the forward pass. Returns: - dx: Gradient with respect to x """ dx = None ########################################################################### # TODO: Implement the max pooling backward pass # ########################################################################### pass x, pool_param = cache pool_height, pool_width, stride = pool_param['pool_height'], pool_param['pool_width'], pool_param['stride'] N, C, H, W = x.shape H_t = H/pool_height W_t = W/pool_width dx = np.zeros_like(x) for i in range(H_t): for j in range(W_t): x_sub = x[:,:,i*stride:i*stride+pool_height,j*stride:j*stride+pool_width] dx[:,:,i*stride:i*stride+pool_height,j*stride:j*stride+pool_width] += np.reshape(dout[:,:,i,j],(N,C,1,1))*(x_sub == np.max(x_sub,axis =(2,3),keepdims=True)) ########################################################################### # END OF YOUR CODE # ########################################################################### return dx
def main(): n, q = tuple(map(int, input().split())) a = list(map(int, input().split())) log = 0 while (1 << log) < n: log += 1 size = 1 << log segtree = [id_node() for i in range(2 * size)] for i in range(n): segtree[size + i] = Node(a[i], a[i], 1, 1, 1, 1) for i in range(size - 1, 0, -1): segtree[i] = combine(segtree[i << 1], segtree[i << 1 | 1]) for _ in range(q): t, l, r = tuple(map(int, input().split())) l -= 1 if t == 1: l += size segtree[l] = Node(r, r, 1, 1, 1, 1) while l > 1: l >>= 1 segtree[l] = combine(segtree[l << 1], segtree[l << 1 | 1]) else: l += size r += size sml, smr = id_node(), id_node() while l < r: if l & 1: sml = combine(sml, segtree[l]) l += 1 if r & 1: r -= 1 smr = combine(segtree[r], smr) l >>= 1 r >>= 1 print(combine(sml, smr).ans)
def calculate_object_code_byte(token): operand = token.operands[0] code = 0 left = 0 right = 0 length = 0 if operand[0] == 'C': left = 2 right = len(operand) - 2 length = right - left + 1 for i in range(left, right + 1): c = ord(operand[i]) code += c << (8 * abs(i - right)) elif operand[0] == 'X': left = 2 right = 3 length = 1 for i in range(left, right + 1): c = ord(operand[i]) tmp = 0 if c > ord('9'): tmp = c - ord('A') + 10 else: tmp = c - ord('0') code += tmp << (4 * abs(i - right)) return length, code
def main(): t = 1 for _ in range(t): n, m = map(int, input().split()) s = input() t = input() si = 0 tj = 0 min1 = [] while (si < len(s) and tj < len(t)): if (s[si] == t[tj]): min1.append(si) tj += 1 si += 1 max1 = [] si = len(s) - 1 tj = len(t) - 1 while (si >= 0 and tj >= 0): if (s[si] == t[tj]): max1.append(si) tj -= 1 si -= 1 max1 = max1[::-1] ans = -1 for i in range(1, m): if (ans < (max1[i] - min1[i - 1])): ans = (max1[i] - min1[i - 1]) print(ans)
def main(): t=int(input()) for _ in range(t): n=int(input()) a=list(map(int,input().split())) maxs=0 for i in range(n): for j in range(i+1,n): if(i!=j): if(a[i]+a[j]>maxs): maxs=a[i]+a[j] a.sort() maxans=0 for i in range(1,maxs): ans=0 xi=0 xj=n-1 while(xi<xj): s=a[xi]+a[xj] if(s>i): xj-=1 elif(s<i): xi+=1 else: ans+=1 xi+=1 xj-=1 if(ans>maxans): maxans=ans print(maxans)
def main(): t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) x = a[0] f = 0 for i in range(1, n): if (a[i] != x): f = 1 break if (f == 0): print("NO") else: l = [] for i in range(1, n): if (a[i] != a[i - 1]): l.append((i - 1, i)) else: for j in range(n): if (a[j] != a[i]): l.append((j, i)) break print("YES") for i in l: print(i[0] + 1, i[1] + 1)
def fit(songs): con = connect() user = str(songs.pop('user', )) playlists = int(songs.pop('playlists', '0')) song_ids = list() for i in songs: song_ids.append(int(i)) res = con.execute("select * from features where song_id in " + str(tuple(song_ids))) x = np.zeros((len(songs), 45)) y = np.zeros((len(songs), playlists), dtype=int) i = 0 obj = {"0": [], "1": [], "2": [], "3": [], "4": [], "5": []} for row in res: y[i] = np.asarray(songs[str(row['song_id'])]['playlists']) for j in range(playlists): if (y[i][j] == 1): obj[str(j)].append(str(row['song_id'])) for j in range(1, 46): x[i][j - 1] = row[j] i += 1 with open("playlists", "w") as datafile: json.dump(obj, datafile) count = playlists * 2 size = int(math.ceil(playlists / 2)) base_classifier = RandomForestClassifier(n_estimators=75, n_jobs=-1) problem_transform_classifier = LabelPowerset(classifier=base_classifier) classifier = Rakel(classifier=problem_transform_classifier, model_count=count, labelset_size=size) classifier.fit(sparse.csr_matrix(x), sparse.csr_matrix(y)) with open("users/" + user, "w") as binfile: pickle.dump(classifier, binfile)
def predict(songs): con = connect() user = str(songs.pop('user', )) playlists = int(songs.pop('playlists', '0')) song_ids = list() for i in songs: song_ids.append(int(i)) if (len(song_ids) == 1): res = con.execute("select * from features where song_id = " + str(song_ids[0])) else: res = con.execute("select * from features where song_id in " + str(tuple(song_ids))) x = np.zeros((len(songs), 45)) song_ids = list() i = 0 for row in res: song_ids.append(row[0]) for j in range(1, 46): x[i][j - 1] = row[j] i += 1 with open("users/" + user) as binfile: classifier = pickle.load(binfile) pred = classifier.predict(sparse.csr_matrix(x)).toarray() prediction = {} for i in range(len(song_ids)): prediction[song_ids[i]] = [int(item) for item in pred[i].tolist()] return prediction
def main(): t = int(input()) for _ in range(t): n, x, y = map(int, input().split()) d = Divisors(y - x) rs, rd, re = 0, 0, 0 #print(d) mmax = 1000000000 for i in range(len(d)): elements = (y - x) // d[i] + 1 start = x end = y while elements < n and start - d[i] >= 1: elements += 1 start -= d[i] while elements < n: elements += 1 end += d[i] if (elements == n and end < mmax): mmax = end rs = start re = end rd = d[i] for i in range(rs, re + 1, rd): print(i, end=" ") print()
def main(): # NTFS: galen_colin from collections import defaultdict for _ in range(int(input())): n, k = map(int, input().split()) a = input() b = input() dica = defaultdict(int) dicb = defaultdict(int) for char in a: dica[ord(char) - 96] += 1 for char in b: dicb[ord(char) - 96] += 1 for i in range(26): # If there are not enough chars in a to convert to b # or # their diff is not multiple of k (seems obvious) diff = (dica[i] - dicb[i]) if diff < 0 or diff % k: print("No") break # dica[i] -= diff Not needed dica[i + 1] += diff else: print("Yes")
def main(): n, m, k = map(int, input().split()) arr = list(map(int, input().split()))[:n] l = [0] * (m) r = [0] * (m) d = [0] * (m) incrA = [0] * (100002) dInA = [0] * (100002) for i in range(m): l[i], r[i], d[i] = map(int, input().split()) for i in range(k): x, y = map(int, input().split()) x -= 1 incrA[x] += 1 incrA[y] -= 1 c = 0 for i in range(0, m): c += incrA[i] newD = c * (d[i]) dInA[l[i] - 1] += newD dInA[r[i]] -= newD c = 0 for i in range(0, n): c += dInA[i] print(c + arr[i], end=" ")
def main(): t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) ta = min(a) tb = min(b) m = 0 for i in range(n): if (a[i] > ta and b[i] > tb): m += min(a[i] - ta, b[i] - tb) if (min(a[i] - ta, b[i] - tb) == a[i] - ta): b[i] = b[i] - (a[i] - ta) a[i] = ta else: a[i] = a[i] - (b[i] - tb) b[i] = tb if (a[i] > ta): m += (a[i] - ta) a[i] = ta if (b[i] > tb): m += (b[i] - tb) b[i] = tb print(m)
def main(): t = 1 for i in range(t): n, m = map(int, input().split()) a = list(map(int, input().split())) p = [] x = 1 ans = 0 vis = Counter() for i in a: vis[i] = 1 while (m > 0): for j in range(n): if (vis[a[j] + x] == 0): ans += x p.append(a[j] + x) vis[a[j] + x] = 1 m -= 1 if (m <= 0): break if (vis[a[j] - x] == 0): ans += x p.append(a[j] - x) vis[a[j] - x] = 1 m -= 1 if (m <= 0): break x += 1 print(ans) for i in p: print(i, end=' ')
def generate_literals(): literals = [] generate_target_position = [] control_section_num = 0 num_of_ltorg = 0 for i in range(0, len(source_tokens)): token = source_tokens[i] if token.operator == 'START' or token.operator == 'CSECT': control_section_num += 1 generate_target_position.append((i, False)) continue if token.operator == 'LTORG': generate_target_position.append((i - num_of_ltorg, True)) continue if len(token.operands) == 0: continue operand1 = token.operands[0] if operand1[0] == '=': is_found = False for tp in literals: if tp[0] == operand1: is_found = True if not is_found: literals.append((operand1, i)) generate_target_position.append((len(source_tokens) - 1, False)) generated = 0 last = 0 for target_index in generate_target_position: new_tokens = [] for i in range(last, len(literals)): pair = literals[i] if pair[1] < target_index[0]: literal = pair[0] if literal[1] == 'X' or literal[1] == 'C': new_token = SourceToken('', 'BYTE') else: new_token = SourceToken('', 'WORD') new_token.label = literal new_token.generated_by_ltorg = target_index[1] new_token.operands.append(literal[1:]) new_tokens.append(new_token) generated += 1 last = i + 1 index = target_index[0] + generated - len(new_tokens) source_tokens[index:index] = new_tokens for token in source_tokens: if token.operator == 'LTORG': source_tokens.remove(token)
def _maya_animate_model(f, camera, pg, cam, model, yup, unit_scale_factor): frames = tde4.getCameraNoFrames(cam) mesh_name = validName(tde4.get3DModelName(pg, model)) for frame in builtin.range(1, frames + 1): nvert = tde4.get3DModelNoVertices(pg, model) for vertex_index in builtin.range(0, nvert): p3d = tde4.get3DModelVertex(pg, model, vertex_index, cam, frame) p3d = convertZup(p3d, yup, unit_scale_factor) _maya_animate_vertex(f, mesh_name, vertex_index, frame, p3d)
def main(): t = int(input()) for _ in range(t): n = int(input()) for i in range(1, n + 1): print(random.randint(501, 1000), end=" ") print()
def main(): # region fastio t=int(input()) for i in range(t): n,k=map(int,input().split()) l=list(map(int,input().split())) c=0 for i in range(n):
def GetGains_Fe55(amplist): from root_functions import GetLeftRightBinsAtPercentOfMax histmin = 200 histmax = 700 nbins = 200 fit_threshold_in_percent = 0.5 K_Alphas = [] K_Alpha_errors = [] K_Alphas_widths = [] K_Betas = [] K_Betas_widths = [] chisqrs = [] for amp in range(N_AMPS): c3 = TCanvas( 'canvas', 'canvas', CANVAS_WIDTH, CANVAS_HEIGHT) #create canvas hist = TH1F('hist', '^{55}Fe Spectrum - Amp ' + str(amp),nbins,histmin,histmax) for flux in amplist[amp]: hist.Fill(flux) hist.Draw() hist.GetXaxis().SetTitle('Charge (ADU)') hist.GetYaxis().SetTitle('Frequency') fitmin, fitmax = GetLeftRightBinsAtPercentOfMax(hist,fit_threshold_in_percent) fitfunc, chisqr = DoubleGausFit(hist, fitmin, fitmax) fitfunc.Draw("same") K_Alphas.append(fitfunc.GetParameter(0)) K_Alpha_errors.append(fitfunc.GetParError(0)) K_Alphas_widths.append(fitfunc.GetParameter(1)) K_Betas.append(fitfunc.GetParameter(3)) K_Betas_widths.append(fitfunc.GetParameter(4)) chisqrs.append(chisqr) legend = TPaveText(0.65,0.68,0.99,0.93,"NDC") legend.SetTextAlign(12) legend.SetFillColor(0) legend.AddText("K_{#alpha} peak = " + str(round(K_Alphas[amp],2)) + " #pm " + str(round(K_Alpha_errors[amp],2)) + " ADU") legend.AddText("Entries = " + str(len(amplist[amp]))) legend.AddText("#chi^{2}_{red} = " + str(round(chisqrs[amp],2))) legend.Draw("same") c3.SaveAs(OUTPUT_PATH + "fe55_amp_" + str(zfill(str(amp),2)) +"sprectrum" + FILE_TYPE) c3.SetLogy() c3.SaveAs(OUTPUT_PATH + "fe55_amp_" + str(zfill(str(amp),2)) +"sprectrum_logy" + FILE_TYPE) del c3 del hist print "amp \t K_a \t K_a_width \t K_b \t K_b_width \t K_a_error" for amp in range(N_AMPS): print "%s\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f" %(amp,K_Alphas[amp], K_Alphas_widths[amp], K_Betas[amp], K_Betas_widths[amp], K_Alpha_errors[amp]) return K_Alphas, K_Alpha_errors, chisqrs
def do_step2(costMatrix, coveredCol, coveredRow, primed, stared): L = len (costMatrix) unCoveredZero = False # print coveredCol # print coveredRow # print primed # print stared # for row in costMatrix: nrow = [] for c in row: if c == 0 : nrow.append(0) else: nrow.append(1) # print nrow for i in range(0, L): for j in range(0, L): if abs(costMatrix[i][j]) <= epsilon: if not(j in coveredCol) and not(i in coveredRow): unCoveredZero = True prime(primed, i, j) isStared = isRowStared(stared, i) if isStared[0] == False: # step 3 return [3, [i,j]] else: cover(coveredRow, i) unCover(coveredCol, j) return [2] #print unCoveredZero if not unCoveredZero: # find smallest un covered goto step 4 eMin = [] for i in range(0, L): if i in coveredRow: continue for j in range(0, L): if j in coveredCol: continue # print i, j, costMatrix[i][j] # print eMin if len(eMin) == 0: eMin = [costMatrix[i][j]] elif eMin[0] > costMatrix[i][j]: eMin = [costMatrix[i][j]] # print eMin return [4, eMin]
def main(): # region fastio t = int(input()) for i in range(t): n, k = map(int, input().split()) print(*solve(n - (k - 3), k), end=" ") for i in range(k - 3): print(1, end=' ') print()
def main(): t = int(input()) for _ in range(t): n = int(input()) f = 1 for i in range(1, int(pow(n, 1 / 3)) + 1): if (d[n - (i * i * i)] == 1): print("YES") f = 0 break if (f == 1): print("NO")
def main(): # region fastio t = int(input()) for i in range(t): n, m = map(int, input().split()) a = list(map(int, input().split())) for i in range(len(a)): a[i] = a[i] % m d = Counter(a) ans = 0 if (d[0] == n): print(1) else: for i in range(1, m // 2 + 1): #print("i",i) if (d[i] == d[m - i]): if (d[i] > 0 and d[m - i] > 0): ans += 1 d[i] = 0 d[m - i] = 0 else: if (d[i] < d[m - i]): if (d[i] > 0): ans += 1 d[m - i] -= (d[i] + 1) d[i] = 0 if (d[m - i] > 0): ans += d[m - i] d[m - i] = 0 else: d[m - i] = 0 else: if (d[m - i] > 0): ans += 1 d[i] -= (d[m - i] + 1) d[m - i] = 0 if (d[i] > 0): ans += d[i] d[i] = 0 else: d[i] = 0 #print(d) #print(d) if (d[0] > 0): print(ans + 1) else: print(ans)
def main(): t = int(input()) for _ in range(t): n = int(input()) xa = [] ya = [] for i in range(n): x, y = map(int, input().split()) xa.append(x) ya.append(y) xa.sort() ya.sort() print((xa[(n + 2) // 2 - 1] - xa[(n + 1) // 2 - 1] + 1) * (ya[(n + 2) // 2 - 1] - ya[(n + 1) // 2 - 1] + 1))
def main(): t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) maxi = 0 d = Counter() for i in range(n): d[i] = a[i] for i in range(n - 1, -1, -1): if (i + a[i] < n): d[i] += d[i + a[i]] maxi = max(d[i], maxi) print(maxi)
def getBoundingArea3(): fr = open(settings.dataFile) # skip first line fr.readline() nTripInCenter = 0 nTotalTrip = 0 max_longitude = -73.914941 min_longitude = -74.040039 max_latitude = 40.817171 min_latitude = 40.690645 delta_longitude = (max_longitude - min_longitude) / 210 delta_latitude = (max_latitude - min_latitude) / 280 A = numpy.zeros((210, 280)) X = [] Y = [] for line in fr: #line = fr.readline() array = line.split(',') pickup_longitude = float(array[10]) pickup_latitude = float(array[11]) #dropoff_longitude = float(array[12]) #dropoff_latitude = float(array[13]) if (pickup_longitude > min_longitude and pickup_longitude < max_longitude and pickup_latitude > min_latitude and pickup_latitude < max_latitude): x = int( math.floor( (pickup_longitude - min_longitude) / delta_longitude)) y = int( math.floor((pickup_latitude - min_latitude) / delta_latitude)) A[x][y] += 1 for x in range(210): for y in range(280): if A[x][y] > 20: X.append(x) Y.append(y) # print bounding area fr.close() return (X, Y)
def conv_forward_naive(x, w, b, conv_param): """ A naive implementation of the forward pass for a convolutional layer. The input consists of N data points, each with C channels, height H and width W. We convolve each input with F different filters, where each filter spans all C channels and has height HH and width HH. Input: - x: Input data of shape (N, C, H, W) - w: Filter weights of shape (F, C, HH, WW) - b: Biases, of shape (F,) - conv_param: A dictionary with the following keys: - 'stride': The number of pixels between adjacent receptive fields in the horizontal and vertical directions. - 'pad': The number of pixels that will be used to zero-pad the input. Returns a tuple of: - out: Output data, of shape (N, F, H', W') where H' and W' are given by H' = 1 + (H + 2 * pad - HH) / stride W' = 1 + (W + 2 * pad - WW) / stride - cache: (x, w, b, conv_param) """ out = None ########################################################################### # TODO: Implement the convolutional forward pass. # # Hint: you can use the function np.pad for padding. # ########################################################################### pass N,C,H,W = x.shape F,C,HH,WW = w.shape stride = conv_param['stride'] pad = conv_param['pad'] H_t = 1 + (H + 2 * pad - HH) / stride W_t = 1 + (W + 2 * pad - WW) / stride out = np.zeros((N,F,H_t,W_t)) x_pad = np.pad(x,((0,),(0,),(pad,),(pad,)),'constant') for i in range(N): for j in range(F): for k in range(H_t): for l in range(W_t): out[i,j,k,l] = np.sum(x_pad[i,:,k*stride:k*stride+HH,l*stride:l*stride+WW]*w[j,:,:,:]) out = out + np.reshape(b,(1,F,1,1)) ########################################################################### # END OF YOUR CODE # ########################################################################### cache = (x, w, b, conv_param) return out, cache
def do_step4(costMatrix, coveredCol, coveredRow, primed, stared, eMin): L = len(costMatrix) for i in coveredRow: for j in range(0, L): costMatrix[i][j] += eMin[0] for j in range(0, L): if j in coveredCol: continue for i in range(0, L): costMatrix[i][j] -= eMin[0] return 2
def _connect(self): # Establish an SSL connection _logger.debug("%s APNS connection establishing..." % self.__class__.__name__) # Fallback for socket timeout. for i in range(0, 3): try: self._socket = socket(AF_INET, SOCK_STREAM) self._socket.settimeout(self.timeout) self._socket.connect((self.server, self.port)) break except timeout: pass except: raise if self.enhanced: self._last_activity_time = time.time() self._socket.setblocking(False) self._ssl = wrap_socket(self._socket, self.key_file, self.cert_file, do_handshake_on_connect=False) while True: try: self._ssl.do_handshake() break except ssl.SSLError as err: if ssl.SSL_ERROR_WANT_READ == err.args[0]: select.select([self._ssl], [], []) elif ssl.SSL_ERROR_WANT_WRITE == err.args[0]: select.select([], [self._ssl], []) else: raise else: # Fallback for 'SSLError: _ssl.c:489: The handshake operation timed out' for i in range(0, 3): try: self._ssl = wrap_socket(self._socket, self.key_file, self.cert_file) break except SSLError as ex: if ex.args[0] == SSL_ERROR_WANT_READ: sys.exc_clear() elif ex.args[0] == SSL_ERROR_WANT_WRITE: sys.exc_clear() else: raise self.connection_alive = True _logger.debug("%s APNS connection established" % self.__class__.__name__)
def send_notification(self, token_hex, payload, identifier=0, expiry=0): """ in enhanced mode, send_notification may return error response from APNs if any """ if self.enhanced: self._last_activity_time = time.time() message = self._get_enhanced_notification(token_hex, payload, identifier, expiry) for i in range(0, WRITE_RETRY): try: with self._send_lock: self._make_sure_error_response_handler_worker_alive() self.write(message) self._sent_notifications.append(dict({"id": identifier, "message": message})) break except socket_error as e: delay = 10 + (i * 2) _logger.exception( "sending notification with id:" + str(identifier) + " to APNS failed: " + str(type(e)) + ": " + str(e) + " in " + str(i + 1) + "th attempt, will wait " + str(delay) + " secs for next action" ) time.sleep(delay) # wait potential error-response to be read else: self.write(self._get_notification(token_hex, payload))
def base58_encode(a,version='',postfix=''): """ Base58 encode input Mostly ripped from: https://github.com/jgarzik/python-bitcoinlib/blob/master/bitcoin/base58.py """ try: a = hexlify(unhexlify(a)) version = hexlify(unhexlify(version)) postfix = hexlify(unhexlify(postfix)) except: raise Exception('base58_encode() Invalid input') a, version, postfix = hex_to_hexstr(a), hex_to_hexstr(version), hex_to_hexstr(postfix) b = version + a + postfix b58_digits = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' n1 = int(b,16) res = [] while n1 > 0: n1, r = divmod(n1,58) res.append(b58_digits[r]) res = ''.join(res[::-1]) pad = 0 for i in range(len(b) // 2): j = int(2*i) teststr = str(b[j] + b[j+1]) if teststr == '00': pad += 1 else: break return str(b58_digits[0] * pad + res)
def get_credentials(create=False): """ We use this to ask the user for his credentials in case we have no valid token. If create is true, the user is asked twice for the password, to make sure, that no typing error occurred. This is done three times after that a PasswordsDontMatchException is thrown. """ email = raw_input('Email : ') password = None for i in range(3): #noinspection PyArgumentEqualDefault password = getpass.getpass('Password: '******'Password (again): ') if password != password2: print messages['PasswordsDontMatch'] if i == 2: #noinspection PyExceptionInherit raise PasswordsDontMatchException() else: break else: break return email, password
def construct_multi_label(topic, lang_model): arbitrary_tweet = topic.groups[0].head tokens = arbitrary_tweet['toks'] ranges = [] for label in topic.label_set: index = kmp.indexSubsequence(label, tokens) #print "%s in %s at %s" % (label, tokens, index) if index > -1: ranges.append(__builtin__.range(index, index + len(label))) indices = set() for rng in ranges: indices.update(rng) indices = list(indices) indices.sort() labels = [] last_index = indices[0] - 1 for index in indices: if index != last_index + 1: labels.append(None) labels.append(tokens[index]) last_index = index labels = [ tuple(g) for k, g in itertools.groupby(labels, lambda it: it is not None) if k ] multi_label = choose_multi_label(labels, lang_model) if isinstance(multi_label[0], list): multi_label = tuple(tuple(x) for x in multi_label) # if len(labels) > 1: # print "LABELS ",labels # print "MULTI", multi_label return multi_label, " / ".join([ " ".join(label) for label in multi_label])
def increase_location_counter_by_token(token): if token.operator == 'RESB': return int(token.operands[0]) elif token.operator == 'RESW': return int(token.operands[0]) * SIZE_OF_WORD elif token.operator == 'BYTE': operand = token.operands[0] if operand[0] == 'C': return len(operand) - 3 else: return (len(operand) - 3) / 2 elif token.operator == 'WORD': return SIZE_OF_WORD if token.operator[0] == '+': return 4 if token.operator not in instruction_table: return 0 instruction_data = instruction_table[token.operator] for i in range(1, 4): if str(i) in instruction_data[1]: return i return 0
def writeAnalyseResult(self): for i in range(0, self.mRawConfigLines.__len__()): if not self.mRawConfigLines[i].__contains__(',#'): self.mTotalInputCount += 1 analyseFile = open(ANALYSE_FILE_PATH, 'w') target = ['1. 输入case总数: ' + str(self.mTotalInputCount) + '\n', '2. 运行case总数: ' + str(self.mTotalRanCount) + '\n', '3. 首选: ' + '\n', '\t3.1 首选命中总权重: ' + str(self.mFirstHitWeight) + '\n' , '\t3.2 首选命中数: ' + str(self.mFirstHitCount) + '\n', '\t3.3 首选命中率(带权重): ' + str((self.mFirstHitWeight * 1.000) / self.mTotalWeight) + '\n', '\t3.4 首选命中率: ' + str((self.mFirstHitCount * 1.000) / self.mTotalRanCount) + '\n', '4. 首屏: ' + '\n', '\t4.1 首屏命中总权重: ' + str((self.mHitNotFirstWeight + self.mFirstHitWeight)) + '\n', '\t4.2 首屏命中数: ' + str(self.mTotalRanCount - self.mMissCount) + '\n', '\t4.3 首屏命中率(带权重): ' + str(((self.mHitNotFirstWeight + self.mFirstHitWeight) * 1.000) / self.mTotalWeight) + '\n', '\t4.4 首屏命中率: ' + str(((self.mTotalRanCount - self.mMissCount) * 1.000) / self.mTotalRanCount) + '\n', '5. 输入法信息: ' + '\n', '\t5.1 输入法名称: ' + self.imeInfo.PackageName + '\n', '\t5.2 输入法Version Name: ' + self.imeInfo.VersionName + '\n', '\t5.3 输入法Version Code: ' + self.imeInfo.VersionCode + '\n', '6. 结果校验: ' + '\n', '\t6.1 Log文件校验结果: ' + ('权重值校验正确, case个数校验正确!' if self.mIsCorrect else '错误') + '\n', '\t6.2 没有运行的Case: ' + '\n\n' + self.mMissedRunCase + '\n', '\t6.3 没有在首位的case: ' + '\n\n' + self.mNotFirstCase + '\n'] analyseFile.writelines(target) return
def is_offscreen(self): """Return a Boolean indicating whether all of the Options in this list are outside of the game window's viewable drawing region. """ if self.animation == ListAnimation.HIDE: for i in range(0, len(self.options), 2): if self.options[i].get_right_edge() > 0: return False for i in range(1, len(self.options), 2): if self.options[i].rect.x < SCREEN_SIZE[0]: return False return True else: return False
def calc_average_rdf(k_s, sl_div_diam, vol_ratio): subdir = str(k_s)+"_"+str(sl_div_diam)+"_"+str(vol_ratio) dir = data_dir + "/" + subdir print "reducing dir ",dir data = numpy.zeros((100,2,400)) for i in range(100,500): data[:,:,i-100] = numpy.loadtxt(dir+ "/rdf%05d.csv"%i, delimiter=',', usecols = (0,1)) return numpy.average(data, 2)
def plots(): k_s_sweep = [10**(x-5) for x in range(10)] sl_div_diam_sweep = [5.0*(x+1)/1000 for x in range(20)] sl_div_diam_sweep.reverse() vol_ratio = 0.3 plt.figure(figsize=(6,4.5)) for k_s,i in zip(k_s_sweep,range(10)): plt.clf() for sl_div_diam,j in zip(sl_div_diam_sweep,range(20)): subdir = str(k_s)+"_"+str(sl_div_diam)+"_"+str(vol_ratio) dir = data_dir + "/" + subdir rdf = numpy.loadtxt(dir+ "/rdf_average.csv", delimiter=',', usecols = (0,1)) plt.plot(rdf[:,0],rdf[:,1],label="step = %f"%(sl_div_diam),color=(1-j/20.0, 1-j/20.0, 1.0)) plt.xlabel('$r$') plt.ylabel('RDF') print "saving file /rdf_%f.pdf"%(k_s) plt.savefig(data_dir + "/rdf_%f.pdf"%(k_s))
def _make_sure_error_response_handler_worker_alive(self): if not self._error_response_handler_worker or not self._error_response_handler_worker.is_alive(): self._init_error_response_handler_worker() TIMEOUT_SEC = 10 for _ in range(0, TIMEOUT_SEC): if self._error_response_handler_worker.is_alive(): _logger.debug("error response handler worker is running") return time.sleep(1) _logger.warning("error response handler worker is not started after %s secs" % TIMEOUT_SEC)
def __init__(self, startnames): self.startnames = startnames from sets import Set possibleusernames = [] name = "" llist = self.startnames.split("-") for x in llist: if name == "": name = name + x else: name = name + " " + x if " " in name: parts = name.split() possibleusernames.append(parts[0]) possibleusernames.append(parts[0]+"."+parts[1]) possibleusernames.append(parts[0]+parts[1]) possibleusernames.append(parts[0]+"."+parts[1][0]) possibleusernames.append(parts[0][0]+"."+parts[1]) possibleusernames.append(parts[0]+parts[1][0]) possibleusernames.append(parts[0][0]+parts[1]) str1="" str2="" str3="" str4="" for i in __builtin__.range(0,len(parts)-1): str1=str1+parts[i]+"." str2=str2+parts[i] str3=str3+parts[i][0]+"." str4=str4+parts[i][0] str5=str1+parts[-1] str6=str2+parts[-1] str7=str4+parts[-1] str8=str3+parts[-1] str9=str2+parts[-1][0] str10=str4+parts[-1][0] possibleusernames.append(str5) possibleusernames.append(str6) possibleusernames.append(str7) possibleusernames.append(str8) possibleusernames.append(str9) possibleusernames.append(str10) possibleusernames.append(parts[-1]) possibleusernames.append(parts[0]+"."+parts[-1]) possibleusernames.append(parts[0]+parts[-1]) possibleusernames.append(parts[0]+"."+parts[-1][0]) possibleusernames.append(parts[0][0]+"."+parts[-1]) possibleusernames.append(parts[0]+parts[-1][0]) possibleusernames.append(parts[0][0]+parts[-1]) else: possibleusernames.append(name) self.creatednames=possibleusernames self.__count=len(possibleusernames)
def range(n): """ Returns the sequence of integers from 0 to n-1. >>> range(5) [0, 1, 2, 3, 4] >>> range(0) [] """ return __builtin__.range(n)
def ExcelImportLink(path,project): book = xlrd.open_workbook(path) sheet = book.sheets()[0] for r in range(1, sheet.nrows): num = sheet.cell(r,0).value #学生学号 link = RankLinks.objects.get(pk = linkid) student = Students.objects.get(pk = num) newlink = RankLinks(student = student,rtype= link.rtype,rum = link.rnum,status = '通过') newlink.save() return True
def minCol(listMatrix, colIndex): L = len(listMatrix) if L < 1: return 0 m = listMatrix[0][colIndex] for i in range(1, L): if m > listMatrix[i][colIndex]: m = listMatrix[i][colIndex] return m
def simple_aes_decrypt(msg,key): assert len(msg) == 16 assert len(key) == 32 cipher = AES.new(key) msg = hexstrlify(cipher.decrypt(msg)) while msg[-2:] == '7b': # Can't use rstrip for multiple chars msg = msg[:-2] for i in range((32 - len(msg))//2): msg = msg + '7b' assert len(msg) == 32 return unhexlify(msg)
def getImeInfo(self): resultFile = open(LOCAL_RESULT_FILE, 'r') for i in range(0, 10): line = resultFile.readline() if line.__contains__('IMEName'): self.imeInfo.PackageName = line[line.index(':') + 1:line.__len__() - 1] elif line.__contains__('IMEVersionName'): self.imeInfo.VersionName = line[line.index(':') + 1:line.__len__() - 1] elif line.__contains__('IMEVersionCode'): self.imeInfo.VersionCode = line[line.index(':') + 1:line.__len__() - 1] return
def physical_size(imageOrFilter) : """Return the physical size of an image, or of the output image of a filter This method take care of updating the needed informations """ from __builtin__ import range # required because range is overladed in this module spacing_ = spacing(imageOrFilter) size_ = size(imageOrFilter) result = [] for i in range(0, spacing_.Size()): result.append( spacing_.GetElement(i) * size_.GetElement(i) ) return result
def intervals(_min, _max=None, size=1): """ RETURN (min, max) PAIRS OF GIVEN SIZE, WHICH COVER THE _min, _max RANGE THE LAST PAIR MAY BE SMALLER """ if _max == None: _max = _min _min = 0 _max = int(Math.ceiling(_max)) output = ((x, min(x + size, _max)) for x in __builtin__.range(_min, _max, size)) return output
def minRow(listMatrix, rowIndex): L = len(listMatrix) if L < 1: return 0 m = listMatrix[rowIndex][0] for i in range(1, L): if m > listMatrix[rowIndex][i]: m = listMatrix[rowIndex][i] return m
def ll(ap='.',stime=True,type='',t='',d=False,dir=False,f=False,file=False): '''return {file : [size,atime,mtime,ctime,st_mode]} linux struct stat: http://pubs.opengroup.org/onlinepubs/009695399/basedefs/sys/stat.h.html''' dr={} for i in ls(ap,type=type,t=t,d=d,dir=dir,f=f,file=file): s=_os.stat(i) dr[i]=[size(i),s.st_atime,s.st_mtime,s.st_ctime,s.st_mode] if stime: # import U for j in py.range(len(dr[i])): if py.type(dr[i][j]) is py.float:dr[i][j]=U.stime(time=dr[i][j]) return dr
def run_sweep(): k_s_sweep = [10**(x-5) for x in range(10)] print "k_s = ",k_s_sweep sl_div_diam_sweep = [5.0*(x+1)/1000 for x in range(20)] print "sl_div_diam = ",sl_div_diam_sweep vol_ratio_sweep = [5.0*(x+1)/100 for x in range(10)] print "vol_ratio = ",vol_ratio_sweep params = [] for k_s in k_s_sweep: for sl_div_diam in sl_div_diam_sweep: for vol_ratio in vol_ratio_sweep: params.append((k_s,sl_div_diam,vol_ratio)) n_cpu = 4 num_its = int(len(params)/n_cpu) for i in range(num_its): threads = [threading.Thread(target = run, args = params[i*n_cpu+j]) for j in range(n_cpu)] for thread in threads: thread.start() for thread in threads: thread.join()
def ec_multiply(xs,ys,scalar): """Multiply a point by an integer scalar.""" if scalar == 0 or scalar >= N_ORDER: raise Exception('ec_multiply() Invalid Scalar/Private Key') scalar_bin = str(bin(scalar)).lstrip('0b') Qx,Qy=xs,ys for i in range (1, len(scalar_bin)): Qx, Qy = ec_double(Qx,Qy) if scalar_bin[i] == '1': Qx,Qy=ec_add(Qx,Qy,xs,ys) return Qx, Qy