def __get_size__(filename): """ Parses the filename to get the size of a file e.g. 128M+12, 110M-10 """ match = FILE_REGEX.search(filename) if match: size_str = match.group('size') si_unit = match.group('size_si') shift = __get_shift__(match) mul = 1 if si_unit == 'B': mul = 1 elif si_unit == 'K': mul = ONE_K elif si_unit == 'M': mul = pow(ONE_K, 2) elif si_unit == 'G': mul = pow(ONE_K, 3) elif si_unit == 'T': mul = pow(ONE_K, 4) size = int(size_str) size_in_bytes = (size * mul) + shift return size_in_bytes else: raise ValueError
def sim_pearson(prefs,p1,p2): # Get the list of mutually rated items si={} for item in prefs[p1]: if item in prefs[p2]: si[item]=1 # if they are no ratings in common, return 0 if len(si)==0: return 0 # Sum calculations n=len(si) # Sums of all the preferences sum1=sum([prefs[p1][it] for it in si]) sum2=sum([prefs[p2][it] for it in si]) # Sums of the squares sum1Sq=sum([pow(prefs[p1][it],2) for it in si]) sum2Sq=sum([pow(prefs[p2][it],2) for it in si]) # Sum of the products pSum=sum([prefs[p1][it]*prefs[p2][it] for it in si]) # Calculate r (Pearson score) num=pSum-(sum1*sum2/n) den=sqrt((sum1Sq-pow(sum1,2)/n)*(sum2Sq-pow(sum2,2)/n)) if den==0: return 0 r=num/den return r
def divide_arrays(self, num_array, num_array_error, den_array, den_array_error): ''' This function calculates the ratio of two arrays and calculate the respective error values ''' nbr_elements = np.shape(num_array)[0] # calculate the ratio array ratio_array = np.zeros(nbr_elements) for i in range(nbr_elements): if den_array[i] is 0: _tmp_ratio = 0 else: _tmp_ratio = num_array[i] / den_array[i] ratio_array[i] = _tmp_ratio # calculate the error of the ratio array ratio_error_array = np.zeros(nbr_elements) for i in range(nbr_elements): if (num_array[i] == 0) or (den_array[i] == 0): ratio_error_array[i] = 0 else: tmp1 = pow(num_array_error[i] / num_array[i],2) tmp2 = pow(den_array_error[i] / den_array[i],2) ratio_error_array[i] = math.sqrt(tmp1+tmp2)*(num_array[i]/den_array[i]) return [ratio_array, ratio_error_array]
def test_good_result(self): # Note: All of these cases use integers, and would fail if the float() casts # were to be remvoed from get_safe_feedrate. Try it. cases = [ [[1, 0, 0, 0, 0], # Single axis: Move under the max feedrate [10, 0, 0, 0, 0], 1, 1], [[11, 0, 0, 0, 0], # Single axis: Move at the max feedrate [2, 0, 0, 0, 0], 2, 2], [[-12,0, 0, 0, 0], # Single axis: Move in negative direction at the max feedrate [1, 0 ,0, 0, 0], 1, 1], [[13, 0, 0, 0, 0], # Single axis: Move faster than the max feedrate [1, 0, 0, 0, 0], 10, 1], [[1, -1, 1,-1, 1], # Multi axis: Move in negative direction at the max feedrate [1, 1, 1, 1, 1], pow(5,.5), pow(5,.5)], [[1, -2, 3,-4, 5], # Multi axis: Move faster than the max feedrate [1, 1, 1, 1, 1], 10, pow(55,.5)/5], ] for case in cases: self.assertEquals(case[3], makerbot_driver.Gcode.get_safe_feedrate(case[0], case[1], case[2]))
def weighted_mean(self, data_array, error_array, error_0): ''' weighted mean of an array ''' sz = len(data_array) # calculate the numerator of mean dataNum = 0; for i in range(sz): if (error_array[i] == 0): error_array[i] = error_0 tmpFactor = float(data_array[i]) / float((pow(error_array[i],2))) dataNum += tmpFactor # calculate denominator dataDen = 0; for i in range(sz): if (error_array[i] == 0): error_array[i] = error_0 tmpFactor = 1./float((pow(error_array[i],2))) dataDen += tmpFactor if dataDen == 0: data_mean = np.nan mean_error = np.nan else: data_mean = float(dataNum) / float(dataDen) mean_error = math.sqrt(1/dataDen) return [data_mean, mean_error]
def sim_pearson(prefs, persion1, persion2): """返回persion1和persion2的皮尔逊相关系数""" si = {} #找到两个人都评价过的电影 for item in prefs[persion1]: if item in prefs[persion2]: si[item] = 1 n = len(si) if n == 0: return 1 #对所有的偏好求和 sum1 = sum([prefs[persion1][it] for it in si]) sum2 = sum([prefs[persion2][it] for it in si]) #求平方和 sum1Sqre = sum([pow(prefs[persion1][it], 2) for it in si]) sum2Sqre = sum([pow(prefs[persion2][it], 2) for it in si]) #求乘积之和 persionSum = sum([prefs[persion1][it] * prefs[persion2][it] for it in si]) #计算皮尔逊相关系数 num = persionSum - (sum1 * sum2 / n) den = math.sqrt((sum1Sqre - pow(sum1, 2) / n) * (sum2Sqre - pow(sum2, 2) / n)) if den == 0: return 0 r = num / den return r
def __setXYZData(self, pixel, x, y): if(pixel[0] < 0.04045): r = pixel[0]/12.92 else: r = pow((pixel[0] + 0.055)/1.055, 2.4) if(pixel[1] < 0.04045): g = pixel[1]/12.92 else: g = pow((pixel[1] + 0.055)/1.055, 2.4) if(pixel[2] < 0.04045): b = pixel[2]/12.92 else: b = pow((pixel[2] + 0.055)/1.055, 2.4) X = 0.412453*r + 0.357580*g + 0.180423 *b Y = 0.212671*r + 0.715160*g + 0.072169 *b Z = 0.019334*r + 0.119193*g + 0.950227 *b new_pixel = [X, Y, Z] self.pixel_data[(x, y)] = new_pixel if(x == 0 and y == 0): print str(pixel[0]) + "," + str(pixel[1]) + "," + str(pixel[2]) print self.pixel_data[(x, y)] return new_pixel
def _guinier_porod(self, x): """ Guinier-Porod Model """ # parameters G = self.params['scale'] s = self.params['dim'] Rg = self.params['rg'] m = self.params['m'] bgd = self.params['background'] n = 3.0 - s qval = x # take care of the singular points if Rg <= 0.0: return bgd if (n-3.0+m) <= 0.0: return bgd #do the calculation and return the function value q1 = sqrt((n-3.0+m)*n/2.0)/Rg if qval < q1: F = (G/pow(qval,(3.0-n)))*exp((-qval*qval*Rg*Rg)/n) else: F = (G/pow(qval, m))*exp(-(n-3.0+m)/2.0)*pow(((n-3.0+m)*n/2.0), ((n-3.0+m)/2.0))/pow(Rg,(n-3.0+m)) inten = F + bgd return inten
def find_substep(target, source, value, step_size, error): # recursive end condition if step_size < 0.0001: # new_source = source[:] # substep_shift(new_source, value) # return new_source return value # check plus shift source_plus = source[:] substep_shift(source_plus, value + step_size) p_error = 0 for vals in zip(target, source_plus): p_error += pow(vals[0] - vals[1], 2) # check minus shift source_minus = source[:] substep_shift(source_minus, value - step_size) m_error = 0 for vals in zip(target, source_minus): m_error += pow(vals[0] - vals[1], 2) # take best out of plus shift, minus shift, and no shift if p_error < m_error: if p_error < error: return find_substep(target, source, value + step_size, step_size / 2, p_error) else: return find_substep(target, source, value, step_size / 2, error) else: if m_error < error: return find_substep(target, source, value - step_size, step_size / 2, m_error) else: return find_substep(target, source, value, step_size / 2, error)
def run(self): self.time_step += 1 self.beta1 *= self.lamb t = self.time_step learning_rate = self.alpha self.net.forward_pass(training_pass=True) self.net.backward_pass() gradient = self.net.buffer.gradients temp = self.net.handler.allocate(gradient.shape) temp_m0 = self.net.handler.allocate(self.m_0.shape) temp_v0 = self.net.handler.allocate(self.v_0.shape) # m_t <- beta_1*m_{t-1} + (1-beta1) *gradient self.net.handler.mult_st(self.beta1, self.m_0, out=self.m_0) self.net.handler.mult_add_st(1.0-self.beta1, gradient, out=self.m_0) # v_t <- beta_2*v_{t-1} + (1-beta2) *gradient^2 self.net.handler.mult_st(self.beta2, self.v_0, out=self.v_0) self.net.handler.mult_tt(gradient, gradient, temp) # gradient^2 self.net.handler.mult_add_st(1.0-self.beta2, temp, out=self.v_0) # m_hat_t <- m_t/(1-beta1^t) self.net.handler.mult_st(1.0/(1.0-pow(self.beta1, t)), self.m_0, out=temp_m0) # v_hat_t <- v_t/(1-beta2^t) self.net.handler.mult_st(1.0/(1.0-pow(self.beta2, t)), self.v_0, out=temp_v0) self.net.handler.sqrt_t(temp_v0, temp_v0) self.net.handler.add_st(self.epsilon, temp_v0, out=temp_v0) self.net.handler.mult_st(learning_rate, temp_m0, out=temp_m0) self.net.handler.divide_tt(temp_m0, temp_v0, temp) self.net.handler.subtract_tt(self.net.buffer.parameters, temp, out=self.net.buffer.parameters)
def prove_decryption(self, ciphertext): """ given g, y, alpha, beta/(encoded m), prove equality of discrete log with Chaum Pedersen, and that discrete log is x, the secret key. Prover sends a=g^w, b=alpha^w for random w Challenge c = sha1(a,b) with and b in decimal form Prover sends t = w + xc Verifier will check that g^t = a * y^c and alpha^t = b * beta/m ^ c """ m = (Utils.inverse(pow(ciphertext.alpha, self.x, self.pk.p), self.pk.p) * ciphertext.beta) % self.pk.p beta_over_m = (ciphertext.beta * Utils.inverse(m, self.pk.p)) % self.pk.p # pick a random w w = Utils.random_mpz_lt(self.pk.q) a = pow(self.pk.g, w, self.pk.p) b = pow(ciphertext.alpha, w, self.pk.p) c = int(sha.new(str(a) + "," + str(b)).hexdigest(),16) t = (w + self.x * c) % self.pk.q return m, { 'commitment' : {'A' : str(a), 'B': str(b)}, 'challenge' : str(c), 'response' : str(t) }
def miller_rabin_helper(a, d, s, n): print n base = pow(a, d, n) yield base == 1 for r in range(s): yield base == n - 1 base = pow(base, 2, n)
def _try_composite(a, d, n, s): if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2**i * d, n) == n-1: return False return True # n is definitely composite
def __init__(self, num_inputs, num_inners, num_outputs, learning_rate, activation_function=None): """Constructor.""" self._num_nodes = { INPUT: num_inputs, INNER: num_inners, OUTPUT: num_outputs } self._learning_rate = learning_rate # Sample weights from normal probability distribution centered around # zero, with a standard deviation related to the number of incoming # links into a node. self.weights = { ITH: numpy.random.normal( 0.0, pow(self._num_nodes[INNER], -0.5), (self._num_nodes[INNER], self._num_nodes[INPUT])), HTO: numpy.random.normal( 0.0, pow(self._num_nodes[OUTPUT], -0.5), (self._num_nodes[OUTPUT], self._num_nodes[INNER])) } # Sigmoid-esque activation function. self.activation_function = ( activation_function or (lambda x: scipy.special.expit(x))) # Score is initially set to 0. self._score = 0.0 # Default # training epochs. self._training_epochs = 7
def generate_detail(level,map): global iterations pow_max = pow(2,iterations) # 4 4 pow_size = pow(2,iterations-level) # 4 2 #diamond step for i in range(int(pow_max / pow_size)): # 0 , 0 1 for d in range(int(pow_max / pow_size)): # 0 , 0 1 h = 0 x = 0 y = 0 print("diamond") for u in range(2): for v in range(2): tx = int(i * pow_size + u*pow_size) ty = int(d * pow_size + v*pow_size) print(tx," ",ty) h += map[tx][ty] y += pow_size x += pow_size h = h / 4 + random.uniform(0.0,100.0/(level +1)) map[int(i*pow_size+pow_size/2)][int(d*pow_size+pow_size/2)] = h #square step #for i in range(int(pow_max / (pow_size/2))): # 2 , #return(map) print("==level" , level , "configuration==") render_map(map,0,0) print("==level", level,"configuration==") if(iterations == level + 1): return(map) else: return(generate_detail(level+1,map))
def __pow__(self, other): if isinstance(other, (WithUnit, Unit)) and not other.isDimensionless(): raise TypeError('Exponents must be dimensionless') if self.unit is None: return WithUnit(pow(self.value, float(other)), None) return WithUnit(pow(self.value, float(other)), pow(self.unit, other))
def prime(a, q, k, n): if pow(a, q, n) == 1: return True elif (n - 1) in [pow(a, q*(2**j), n) for j in range(k)]: return True else: return False
def runoff_pitt(precip, land_use): """ The Pitt Small Storm Hydrology method. The output is a runoff value in inches. """ c1 = +3.638858398e-2 c2 = -1.243464039e-1 c3 = +1.295682223e-1 c4 = +9.375868043e-1 c5 = -2.235170859e-2 c6 = +0.170228067e+0 c7 = -3.971810782e-1 c8 = +3.887275538e-1 c9 = -2.289321859e-2 p4 = pow(precip, 4) p3 = pow(precip, 3) p2 = pow(precip, 2) impervious = ((c1 * p3) + (c2 * p2) + (c3 * precip) + c4) * precip urb_grass = ((c5 * p4) + (c6 * p3) + (c7 * p2) + (c8 * precip) + c9) * precip # noqa runoff_vals = { 'open_water': impervious, 'developed_low': 0.20 * impervious + 0.80 * urb_grass, 'cluster_housing': 0.20 * impervious + 0.80 * urb_grass, 'developed_med': 0.65 * impervious + 0.35 * urb_grass, 'developed_high': 0.85 * impervious + 0.15 * urb_grass, 'developed_open': urb_grass } if land_use not in runoff_vals: raise Exception('Land use %s not a built-type.' % land_use) else: return min(runoff_vals[land_use], precip)
def pearson_similarity(film1_ratings, film2_ratings): """Produces a metric of similarity between movies, 1.0 means the movies are essentially identical, -1.0 means they are complete opposites on the scale. @film1_ratings -- A dictionary of movie ratings, of the format {"user_id": rating, "user_id2": rating2} @film2_ratings -- A dictionary of movie ratings, of the format {"user_id": rating, "user_id2": rating2} @returns -- float""" common_critics = [] for critic in film1_ratings: if critic in film2_ratings: common_critics.append(critic) if len(common_critics) == 0: return 0 film1_sum = sum(film1_critics[critic] for critic in common_critics) film2_sum = sum(film2_critics[critic] for critic in common_critics) film1_sum_square = sum([pow(film1_critics[critic], 2) for critic in common_critics]) film2_sum_square = sum([pow(film2_critics[critic], 2) for critic in common_critics]) product_sum = sum([film1_critics[critic] * film2_critics[critic] for critic in common_critics]) # Calculate the pearson score num_critics = len(common_critics) num = product_sum - ((film1_sum * film2_sum)/num_critics) den = sqrt((film1_sum_square - pow(film1_sum, 2) / num_critics) * (film2_sum_square - pow(film2_sum, 2)/num_critics)) if den == 0: return 0 return num/den
def update(self): date = datetime.utcnow() + timedelta(0, self.TimeIn.value * self.TimeScale.value) azimuth = get_azimuth(self.city, date) elevation = get_elevation(self.city, date) r = g = b = 0.0 if (elevation > 0): r = g = b = elevation / 90 r = pow(r, 0.3) * 1.3 g = pow(g, 0.4) * 1.2 b = pow(b, 0.5) * 1.6 self.SunColorOut.value = avango.gua.Color(r, g, b) self.MatrixOut.value = avango.gua.make_rot_mat( azimuth, 0, 1, 0) * avango.gua.make_rot_mat(-elevation, 1, 0, 0) direcion = self.MatrixOut.value * avango.gua.Vec3(0, 0, -1) self.DirectionOut.value = avango.gua.Vec3(direcion.x, direcion.y, direcion.z) self.BlendFactorOut.value = 0.0 if elevation / 90 < 0: self.BlendFactorOut.value = abs(elevation / 90) * 5 if direcion.y > 0: val = max(0.2 - direcion.y, 0) self.GroundColorOut.value = avango.gua.Color(val, val, val) else: self.GroundColorOut.value = avango.gua.Color(0.5, 0.5, 0.5)
def elemop(N=1000): r''' (Takes about 40ms on a first-generation Macbook Pro) ''' for i in range(N): assert a+b == 579 assert a-b == -333 assert b*a == a*b == 56088 assert b%a == 87 assert divmod(a, b) == (0, 123) assert divmod(b, a) == (3, 87) assert -a == -123 assert pow(a, 10) == 792594609605189126649 assert pow(a, 7, b) == 99 assert cmp(a, b) == -1 assert '7' in str(c) assert '0' not in str(c) assert a.sqrt() == 11 assert _g.lcm(a, b) == 18696 assert _g.fac(7) == 5040 assert _g.fib(17) == 1597 assert _g.divm(b, a, 20) == 12 assert _g.divm(4, 8, 20) == 3 assert _g.divm(4, 8, 20) == 3 assert _g.mpz(20) == 20 assert _g.mpz(8) == 8 assert _g.mpz(4) == 4 assert a.invert(100) == 87
def __init__(self, rp, t1, r1, t2, r2, t3, r3): t1 = t1 + 273.15 # low temperature (25C) r1 = r1 # resistance at low temperature t2 = t2 + 273.15 # middle temperature (150C) r2 = r2 # resistance at middle temperature t3 = t3 + 273.15 # high temperature (250C) r3 = r3 # resistance at high temperature self.rp = rp # pull-up resistance self.vadc = 5.0 # ADC reference self.vcc = 5.0 # supply voltage to potential divider a1 = log(r1) a2 = log(r2) a3 = log(r3) z = a1 - a2 y = a1 - a3 x = 1/t1 - 1/t2 w = 1/t1 - 1/t3 v = pow(a1,3) - pow(a2,3) u = pow(a1,3) - pow(a3,3) c3 = (x-z*w/y)/(v-z*u/y) c2 = (x-c3*v)/z c1 = 1/t1-c3*pow(a1,3)-c2*a1 self.c1 = c1 self.c2 = c2 self.c3 = c3
def computeDistance(m1,m2): r = numpy.dot(m1.transpose(),m2) #print r trace = r.trace() s = (trace-1.0)/2.0 if int(round(abs(s),7)) == 1: """ Either: (1) Vectors are the same , i.e. 0 degrees (2) Vectors are opposite, i.e. 180 degrees """ diff = numpy.sum(pow((m1-m2),2)) #apDisplay.printWarning("overflow return, diff="+str(diff)+" m1="+str(m1)+" m2="+str(m2)) if diff < 1.0e-6: return 0.0 return 180.0 else: #print "calculating" theta = math.acos(s) #print 'theta',theta t1 = abs(theta/(2*math.sin(theta))) #print 't1',t1 t2 = math.sqrt(pow(r[0,1]-r[1,0],2)+pow(r[0,2]-r[2,0],2)+pow(r[1,2]-r[2,1],2)) #print 't2',t2, t2*180/math.pi dist = t1 * t2 dist *= 180.0/math.pi #print 'dist=',dist return dist
def getProfile(self, r): P=0. if (r<self.rcut): P = pow(1. + (r/self.rcore)*(r/self.rcore),-0.5) - \ pow(1. + (self.rcut/self.rcore)*(self.rcut/self.rcore),-0.5) return P
def goExForceF3d(): sig,sig1,sig2=1,4,4 fx = readImage(fxfile) ws = zerofloat(n1,n2) gs = zerofloat(n1,n2,2) gvf = GradientVectorFlow() ed = gvf.applyForEdge(sig,sig1,sig2,fx) et = gvf.applyForGVX(sig,sig1,sig2,ed,gs,ws) #channel 1 #gvf.setScale(0.01) gvf.setScale(0.0) wp = pow(ed,1.0) ws = pow(ws,1.0) wm = pow(wp,1) wm = div(wm,max(wm)) wm = sub(1,wm) fs = gvf.applyForGVF(None,gs[0],gs[1],ws,wm) writeImage(edfile,ed) writeImage(f1file,fs[0]) writeImage(f2file,fs[1]) plot(fx) plot(wp) plot(ws) plot(wm) plotVectors(10,5,gs[0],gs[1],fx) plotVectors(100,5,fs[0],fs[1],fx)
def rd (tokeniser): try: value = tokeniser() separator = value.find(':') if separator > 0: prefix = value[:separator] suffix = int(value[separator+1:]) # XXX: FIXME: we need much more checks here instead that the blank try/except... if '.' in prefix: bytes = [chr(0),chr(1)] bytes.extend([chr(int(_)) for _ in prefix.split('.')]) bytes.extend([chr(suffix>>8),chr(suffix&0xFF)]) rd = ''.join(bytes) else: number = int(prefix) if number < pow(2,16) and suffix < pow(2,32): rd = chr(0) + chr(0) + pack('!H',number) + pack('!L',suffix) elif number < pow(2,32) and suffix < pow(2,16): rd = chr(0) + chr(2) + pack('!L',number) + pack('!H',suffix) else: raise ValueError('invalid route-distinguisher %s' % value) except ValueError: raise ValueError('invalid route-distinguisher %s' % value) return RouteDistinguisher(rd)
def sim_pearson(prefs, p1, p2): # Get the list of mutually rated items si = {} for item in prefs[p1]: if item in prefs[p2]: si[item] = 1 n = len(si) if 0==n: return 0 # Add up all the preferences sum1 = sum(prefs[p1][it] for it in si) sum2 = sum(prefs[p2][it] for it in si) # Sum up the squares sum1Sq = sum([pow(prefs[p1][it], 2) for it in si]) sum2Sq = sum([pow(prefs[p2][it], 2) for it in si]) pSum = sum([prefs[p1][it] * prefs[p2][it] for it in si]) num = pSum - (sum1*sum2/n) den = sqrt((sum1Sq-pow(sum1, 2)/n)*(sum2Sq-pow(sum2,2)/n)) if 0==den: return 0 r = num/den return r
def findMainObject(objectsCNT,shape,img=0): ''' znajduje obiekt najbardziej po srodku plaszczyzny (bo to nie beda krawedzie lustra) ''' #srodek obrazu yc0 = shape[0]/2 xc0 = (shape[1]/4)*3 min_index = -1 min_cost = shape[0]*shape[1] marker = False for n,c in enumerate(objectsCNT): moments = cv2.moments(c) # policzenie srodkow ciezkosci figur yc = int(moments['m01']/moments['m00']) xc = int(moments['m10']/moments['m00']) #odległosc od srodka dx = xc0-xc dy = yc0-yc cost = sqrt(pow(dx,2)+pow(dy,2)) if cost.real < min_cost: min_cost = cost.real min_index = n mainCNT = objectsCNT[min_index] return mainCNT
def try_composite(a): if pow(a, d, n) == 1: return False for i in xrange(s): if pow(a, 2**i * d, n) == n - 1: return False return True
def _insertStepsContinue(self): args = { '--o': '%s/relion' % self.ExtraDir, '--continue': self.optimiserFileName, '--iter': self.NumberOfIterations, '--tau2_fudge': self.RegularisationParamT,# should not be changed '--flatten_solvent': '',# use always #'--zero_mask': '',# use always. This is confussing since Sjors gui creates the command line # # with this option # # but then the program complains about it. '--oversampling': '1', '--norm': '', '--scale': '', } iover = 1 #TODO: check this DROP THIS # Sampling stuff args['--psi_step'] = self.InPlaneAngularSamplingDeg * pow(2, iover) args['--offset_range'] = self.OffsetSearchRangePix args['--offset_step'] = self.OffsetSearchStepPix * pow(2, iover) args['--j'] = self.NumberOfThreads # Join in a single line all key, value pairs of the args dict params = ' '.join(['%s %s' % (k, str(v)) for k, v in args.iteritems()]) params += ' ' + self.AdditionalArguments self.insertRunJobStep(self.program, params, self._getIterFiles(self.NumberOfIterations))
def modinv(n,p): return pow(n,p-2,p)
def transform(self, K): for i in range(0, K.shape[0]): for j in range(0, K.shape[1]): K[i, j] = pow(K[i, j], 1.0 / 10.0) return K
from Crypto.Util import number from itertools import permutations with open('flag') as fp: flag = fp.read() M = int(flag.encode('hex'), 16) p = number.getPrime(1024) q = number.getPrime(1024) N = p * q e = 65537 assert M < N print "N = %d" % N print "e = %d" % e for a in 'MNe': for b in 'MNe': for c in 'MNe': print "pow(%s,%s,%s) = %d" % (a, b, c, pow(eval(a), eval(b), eval(c)))
def createFile(self, filePath, fileName, size=0, randomData=True, umask="777", append=False): """ Create a file :param append: If True, the content will be appended to the existing file. If False, file will be overwritten or created :param filePath: :param fileName: :param size: Can be in Bytes or in the format of "1M", "5G" ...etc :param randomData: Boolean. To have random data or not in the file created. Random data takes a while to create. :param umask: :return: True/False """ if not fileName: autopsy_logger.error("FileName can't be empty or None") return False if not filePath: filePath = "~" if size == 0: self.execute("touch {0}/{1}".format(filePath, fileName)) return self.ssh_client.exit_status_last_command == 0 if randomData: inFile = "/dev/urandom" else: if self.getFileSystemType(filePath + "/") == 'ext4': self.execute("fallocate -l {0} {1}".format(size, filePath + "/" + fileName), sudo=True) if self.ssh_client.exit_status_last_command != 0: autopsy_logger.error("Error creating file {0}".format(filePath + "/" + fileName)) return False self.execute("chmod {0} {1}".format(umask, filePath + "/" + fileName), sudo=True, quiet=True) return True else: inFile = "/dev/zero" remainder = Utilities.convertToBytes(size) value = 2 bsValues = ["1M", "1K", "1"] isFirst = not append while remainder > 0 and value >= 0: quotient = remainder // (pow(1024, value)) remainder %= (pow(1024, value)) if quotient > 0: if isFirst: self.execute("dd if={0} bs={3} count={2} > {1}".format(inFile, filePath + "/" + fileName, quotient, bsValues[len(bsValues) - value - 1]), sudo=True, quiet=True, timeout=3600) if self.ssh_client.exit_status_last_command != 0: autopsy_logger.error( "Error doing dd command for file {0}: Exiting...".format(filePath + "/" + fileName)) return False isFirst = False else: self.execute("dd if={0} bs={3} count={2} >> {1}".format(inFile, filePath + "/" + fileName, quotient, bsValues[len(bsValues) - value - 1]), sudo=True, quiet=True, timeout=3600) if self.ssh_client.exit_status_last_command != 0: autopsy_logger.error( "Error doing dd command for file {0}: Exiting...".format(filePath + "/" + fileName)) return False value -= 1 return True
def stdev(numbers): avg = mean(numbers) variance = sum([pow(x - avg, 2) for x in numbers]) / float(len(numbers) - 1) return math.sqrt(variance)
def forward(self, G): """ The forward function which defines how the network is connected :param G: The input geometry (Since this is a forward network) :return: S: The 300 dimension spectra """ out = G # initialize the out # Monitor the gradient list # For the linear part for ind, (fc, bn) in enumerate(zip(self.linears, self.bn_linears)): #print(out.size()) if ind < len(self.linears) - 1: out = F.relu(bn(fc(out))) # ReLU + BN + Linear else: out = bn(fc(out)) # If use lorentzian layer, pass this output to the lorentzian layer if self.use_lorentz: out = torch.sigmoid( out) # Lets say w0, wp is in range (0,5) for now #out = F.relu(out) + 0.00001 # Get the out into (batch_size, num_lorentz, 3) and the last epsilon_inf baseline epsilon_inf = out[:, -1] out = out[:, 0:-1].view([-1, int(out.size(1) / 3), 3]) # Get the list of params for lorentz, also add one extra dimension at 3rd one to if self.fix_w0: w0 = self.w0.unsqueeze(0).unsqueeze(2) else: w0 = out[:, :, 0].unsqueeze(2) * 1.5 wp = out[:, :, 1].unsqueeze(2) * 5 g = out[:, :, 2].unsqueeze(2) * 0.05 # This is for debugging purpose (Very slow), recording the output tensors self.w0s = w0.data.cpu().numpy() self.wps = wp.data.cpu().numpy() self.gs = g.data.cpu().numpy() self.eps_inf = epsilon_inf.data.cpu().numpy() # Expand them to the make the parallelism, (batch_size, #Lor, #spec_point) w0 = w0.expand(out.size(0), self.num_lorentz, self.num_spec_point) wp = wp.expand_as(w0) g = g.expand_as(w0) w_expand = self.w.expand_as(g) """ Testing code #print("c1 size", self.c1.size()) #print("w0 size", w0.size()) End of testing module """ """ # This is version that easier to understand by human, but memory intensive # Therefore we implement the less memory aggressive one below, make sure you use only one # Get the powers first w02 = pow(w0, 2) wp2 = pow(wp, 2) w2 = pow(w_expand, 2) g2 = pow(g, 2) # Start calculating s1 = add(w02, -w2) s12= pow(s1, 2) n1 = mul(wp2, s1) n2 = mul(wp2, mul(w_expand, g)) denom = add(s12, mul(w2, g2)) e1 = div(n1, denom) e2 = div(n2, denom) """ # This is the version of more "machine" code that hard to understand but much more memory efficient e1 = div( mul(pow(wp, 2), add(pow(w0, 2), -pow(w_expand, 2))), add(pow(add(pow(w0, 2), -pow(w_expand, 2)), 2), mul(pow(w_expand, 2), pow(g, 2)))) e2 = div( mul(pow(wp, 2), mul(w_expand, pow(g, 2))), add(pow(add(pow(w0, 2), -pow(w_expand, 2)), 2), mul(pow(w_expand, 2), pow(g, 2)))) # End line for the 2 versions of code that do the same thing, 1 for memory efficient but ugly self.e2 = e2.data.cpu().numpy( ) # This is for plotting the imaginary part self.e1 = e1.data.cpu().numpy( ) # This is for plotting the imaginary part """ debugging purposes: 2019.12.10 Bens code for debugging the addition of epsilon_inf print("size of e1", e1.size()) print("size pf epsilon_inf", epsilon_inf.size()) """ """ # This is version that easier to understand by human, but memory intensive # Therefore we implement the less memory aggressive one below, make sure you use only one # the correct calculation should be adding up the es e1 = torch.sum(e1, 1) e2 = torch.sum(e2, 1) epsilon_inf = epsilon_inf.unsqueeze(1).expand_as(e1) #Change the shape of the epsilon_inf e1 += epsilon_inf # print("e1 size", e1.size()) # print("e2 size", e2.size()) e12 = pow(e1, 2) e22 = pow(e2, 2) n = sqrt(0.5 * add(sqrt(add(e12, e22)), e1)) k = sqrt(0.5 * add(sqrt(add(e12, e22)), -e1)) n_12 = pow(n+1, 2) k2 = pow(k, 2) T = div(4*n, add(n_12, k2)).float() """ # This is the memory efficient version of code n = sqrt(0.5 * add( sqrt(add(pow(torch.sum(e1, 1), 2), pow(torch.sum(e2, 1), 2))), torch.sum(e1, 1))) k = sqrt(0.5 * add( sqrt(add(pow(torch.sum(e1, 1), 2), pow(torch.sum(e2, 1), 2))), -torch.sum(e1, 1))) T = div(4 * n, add(pow(n + 1, 2), pow(k, 2))).float() # End line for 2 versions of code that do the same thing, 1 for memory efficient but ugly """ Debugging and plotting (This is very slow, comment to boost) """ self.T_each_lor = T.data.cpu().numpy( ) # This is for plotting the transmittion self.N = n.data.cpu().numpy( ) # This is for plotting the imaginary part self.K = k.data.cpu().numpy( ) # This is for plotting the imaginary part # print("T size",T.size()) # Last step, sum up except for the 0th dimension of batch_size (deprecated since we sum at e above) # T = torch.sum(T, 1).float() return T # The normal mode to train without Lorentz if self.use_conv: out = out.unsqueeze(1) # Add 1 dimension to get N,L_in, H # For the conv part for ind, conv in enumerate(self.convs): out = conv(out) # Final touch, because the input is normalized to [-1,1] # S = tanh(out.squeeze()) out = out.squeeze() return out
else: run_else = True assert not run_else run_else = False n=10 while n>5: n -= 1 else: run_else = True assert run_else # issue 135 assert pow(*(2,3)) == 8 assert pow(*(2,-3)) == 0.125 assert pow(*(-2,3)) == -8 assert pow(*(-2,-3)) == -0.125 # issue 137 assert int('-10') == -10 # issue 139 try: d = [] d[3] except (IndexError,TypeError) as err: pass # just check that there is no SyntaxError # issue 157 : check that the 2nd line doesn't raise a SyntaxError
#CalPiv2.py 蒙特卡罗方法求解圆周率 from random import random from time import perf_counter hits = 0.0 DARTS = 1000 * 1000 * 10 start = perf_counter() for dot in range(1, DARTS + 1): x, y = random(), random() dist = pow(x**2 + y**2, 0.5) if (dist < 1.0): hits += 1 end = perf_counter() pi = 4 * (hits / DARTS) print("计算运周率PI为:{}".format(pi)) print("运行时间为:{:.2f}".format(end - start))
def read_var_int(): pos[0] += 1 if ord(tx[pos[0]-1]) < 253: return ord(tx[pos[0]-1]) return read_as_int(pow(2, ord(tx[pos[0]-1]) - 252))
# python3 from Crypto.Util.number import * mm = bytes_to_long(b'12345678') l = len(bin(mm)) - 2 def genkey(): while 1: p = getPrime(128) q = getPrime(128) e = getPrime(32) n = p * q phi = (p - 1) * (q - 1) if GCD(e, phi) > 1: continue d = inverse(e, phi) return e, d, n e, d, n = genkey() cc = pow(mm, e, n) f = str(pow(cc, d, n) % 2) # oracle 一开始泄露的第一bit for i in range(1, l): e, d, n = genkey() cc = pow(mm, e, n) # oracle给出的密文 ss = inverse(2**i, n) cs = (cc * pow(ss, e, n)) % n # 把处理过后的密文cs发给oracle lb = pow(cs, d, n) % 2 # oracle返回新泄露的最后1bit bb = (lb - (int(f, 2) * ss % n)) % 2 # 恢复第 i bit f = str(bb) + f assert(((mm >> i) % 2) == bb) print(long_to_bytes(int(f, 2)))
def __preprocess_dataset(self, data_frame): if self.__preprocess_type == 'fft': for i in range(len(data_frame)): row_X = np.array(data_frame.iloc[i,:-1], dtype=np.float) row_y = np.array(data_frame.iloc[i,-1], dtype=np.float) row_X = self.__apply_window(row_X) transformed_X = np.abs(np.fft.rfft(row_X)) #Fourier transform on each sample decibels = [] if self.__decibels == True: #convert to decibels scale for j in range(len(transformed_X)): decibel = transformed_X[j] * pow(10,16) decibels.append(10 * np.log10(decibel)) transformed_X = np.array(decibels, dtype=np.float) processedRow = np.append(transformed_X, (row_y - self.__dataset_starts_at_label)) #Append y with X try: processed_dataset = np.vstack([processed_dataset,processedRow]) except: processed_dataset = np.array(processedRow,dtype=float) if i % 1000 == 0: print(i, "processed rows") processed_X = processed_dataset[:,0:-1] processed_y = processed_dataset[:,-1] path = os.path.abspath(__file__) dir_path = os.path.dirname(path) preprocessed_X_file = dir_path + '/dataset/' + 'preprocessedSamples_X_samples_nylonGuitar_1024_Mm7_R03.data' preprocessed_y_file = dir_path + '/dataset/' + 'preprocessedSamples_y_samples_nylonGuitar_1024_Mm7_R03.data' processed_X.dump(preprocessed_X_file) processed_y.dump(preprocessed_y_file) return processed_X, processed_y elif self.__preprocess_type == 'stft': X = np.array(data_frame.iloc[:,:-1], dtype=np.float) y = np.array(data_frame.iloc[:,-1], dtype=np.float) processed_X = np.zeros((len(X),12,80,1), dtype=np.float) processed_y = np.zeros(len(y), dtype=np.float) for i in range(len(X)): if self.__cut_freq_above is not None: sample = np.fft.rfft(X[i]) for ii in range(len(sample)): if ii < self.__cut_freq_above: #ignore frequencies greater than self.__cut_freq_above X_fft_new[ii] = sample[ii] X[i] = np.fft.ifft(X_fft_new) row_X = librosa.core.stft(y=X[i], n_fft=self.__n_fft, win_length=self.__win_length, window=self.__window, center=True, dtype=np.float32, pad_mode='reflect') row_X_3d = np.atleast_3d(row_X) processed_X[i] = row_X_3d processed_y[i] = y[i] if i % 400 == 0: print(i, "processed rows") return processed_X, processed_y elif self.__preprocess_type == 'chroma_stft': X = np.array(data_frame.iloc[:,:-1], dtype=np.float) y = np.array(data_frame.iloc[:,-1], dtype=np.float) processed_X = np.zeros((len(X),12,80,1), dtype=np.float) processed_y = np.zeros(len(y), dtype=np.float) X_fft_new = np.zeros(20480) for i in range(len(X)): if self.__cut_freq_above is not None: sample = np.fft.rfft(X[i]) for ii in range(len(sample)): if ii < self.__cut_freq_above: #ignore frequencies greater than self.__cut_freq_above X_fft_new[ii] = sample[ii] X[i] = np.fft.ifft(X_fft_new) row_X = librosa.feature.chroma_stft(y=X[i], sr=44100, n_fft=self.__n_fft, hop_length=self.__hop_lenght) row_X_3d = np.atleast_3d(row_X) processed_X[i] = row_X_3d processed_y[i] = y[i] if i % 400 == 0: print(i, "processed rows") return processed_X, processed_y
break # =========================== # Part 2 deck_size = 119315717514047 MOD = deck_size iterations = 101741582076661 pos = 2020 offset = 0 increment = 1 for i in instr: i = i.split(' ') if 'cut' in i: offset += increment * int(i[1]) offset %= MOD elif 'with' in i: increment *= pow(int(i[3]), MOD - 2, MOD) increment %= MOD elif 'into' in i: increment *= -1 increment %= MOD offset += increment offset %= MOD all_multi = pow(increment, iterations, MOD) all_addi = (offset * (1 - all_multi) * pow(1 - increment, MOD - 2, MOD)) % MOD res = (pos * all_multi + all_addi) % MOD print "Part 2: %d" % res
def V(self): """Method for calculation the volume of ball""" v = (4 / 3) * pi * pow(self.r, 3) return round(v, 2)
def raise_to_exp(x): print(locals()) return pow(x, exp)
def encrypt(m): return pow(m,2,n)
def f(x,args): global p return x+p*pow(2,-(x/1.5))
rel_error = abs(grad_numerical - grad_analytic) / ( abs(grad_numerical) + abs(grad_analytic) ) print(grad_numerical) print(grad_analytic) print(rel_error) assert_almost_equal(rel_error, 0, decimal=5) @pytest.mark.xfail @pytest.mark.parametrize( "method, y_d, domain", [ (np.positive, lambda x: 1, None), (np.negative, lambda x: -1, None), (np.exp, lambda x: pow(e, x), None), (np.exp2, lambda x: pow(2, x) * log(2), None), (np.log, lambda x: 1 / x, (0, None)), (np.log2, lambda x: 1 / (x * log(2)), (0, None)), (np.log10, lambda x: 1 / (x * log(10)), (0, None)), (np.sqrt, lambda x: 0.5 * pow(x, -0.5), (0, None)), (np.square, lambda x: 2 * x, None), ( np.cbrt, lambda x: 1 / 3 * pow(x, -2 / 3), (0, None), ), # Negative numbers cannot be raised to a fractional power (np.reciprocal, lambda x: -1 / pow(x, 2), (None, 0)), (np.sin, lambda x: cos(x), None), (np.cos, lambda x: -sin(x), None), (
def S(self): """Method for calculation the square of ball""" s = 4 * pi * pow(self.r, 2) return round(s, 2)
def main(): # Examples: # TRLYNOP11DE633DD31 church bells # TRWMWTX11DE6393849 a7 unt by lithops # TRMTWYL11DD5A1D829 valley hi by stereolab #a = audio.ExistingTrack("TRMTWYL11DD5A1D829").analysis a = audio.LocalAudioFile(sys.argv[1]).analysis midi = MidiOutFile('output.mid') midi.header() midi.start_of_track() midi.tempo( int(60000000.00 / 60.0) ) # 60 BPM, one Q per second, 96 ticks per Q, 96 ticks per second.) BOOST = 30 # Boost volumes if you want # Do you want the channels to be split by timbre or no? splitChannels = True for seg_index in xrange(len(a.segments)): s = a.segments[seg_index] if (splitChannels): # Figure out a channel to assign this segment to. Let PCA do the work here... we'll just take the sign of coeffs 1->5 as a 4-bit # bits = [0, 0, 0, 0] for i in xrange(4): # Can't use the first coeff because it's (always?) positive. if (s.timbre[i + 1] >= 0): bits[i] = 1 channel = bits[0] * 8 + bits[1] * 4 + bits[2] * 2 + bits[3] * 1 else: channel = 0 # Get the loudnesses in MIDI cc #7 vals for the start of the segment, the loudest part, and the start of the next segment. # db -> voltage ratio http://www.mogami.com/e/cad/db.html linearMaxVolume = int(pow(10.0, s.loudness_max / 20.0) * 127.0) + BOOST linearStartVolume = int( pow(10.0, s.loudness_begin / 20.0) * 127.0) + BOOST if (seg_index == len(a.segments) - 1): # if this is the last segment linearNextStartVolume = 0 else: linearNextStartVolume = int( pow(10.0, a.segments[seg_index + 1].loudness_begin / 20.0) * 127.0) + BOOST whenMaxVolume = s.time_loudness_max # Count the # of ticks I wait in doing the volume ramp so I can fix up rounding errors later. tt = 0 # take pitch vector and hit a note on for each pitch at its relative volume. That's 12 notes per segment. for note in xrange(12): volume = int(s.pitches[note] * 127.0) midi.update_time(0) midi.note_on(channel=channel, note=0x3C + note, velocity=volume) midi.update_time(0) # Set volume of this segment. Start at the start volume, ramp up to the max volume , then ramp back down to the next start volume. curVol = float(linearStartVolume) # Do the ramp up to max from start ticksToMaxLoudnessFromHere = int(96.0 * whenMaxVolume) if (ticksToMaxLoudnessFromHere > 0): howMuchVolumeToIncreasePerTick = float( linearMaxVolume - linearStartVolume) / float(ticksToMaxLoudnessFromHere) for ticks in xrange(ticksToMaxLoudnessFromHere): midi.continuous_controller(channel, 7, int(curVol)) curVol = curVol + howMuchVolumeToIncreasePerTick tt = tt + 1 midi.update_time(1) # Now ramp down from max to start of next seg ticksToNextSegmentFromHere = int(96.0 * (s.duration - whenMaxVolume)) if (ticksToNextSegmentFromHere > 0): howMuchVolumeToDecreasePerTick = float( linearMaxVolume - linearNextStartVolume) / float(ticksToNextSegmentFromHere) for ticks in xrange(ticksToNextSegmentFromHere): curVol = curVol - howMuchVolumeToDecreasePerTick if curVol < 0: curVol = 0 midi.continuous_controller(channel, 7, int(curVol)) tt = tt + 1 midi.update_time(1) # Account for rounding error if any midi.update_time(int(96.0 * s.duration) - tt) # Send the note off for note in xrange(12): midi.note_off(channel=channel, note=0x3C + note) midi.update_time(0) midi.update_time(0) midi.end_of_track() midi.eof()
def checkBlock(self, heightToCheck): #check content of the block for valid transactions block = self.tnc.getBlock(heightToCheck) for transaction in block['transactions']: targetAddress = self.tnc.checkTx(transaction) if targetAddress is not None: if targetAddress != "No attachment": if not (self.otc.validateAddress(targetAddress)): self.faultHandler(transaction, "txerror") else: targetAddress = self.otc.normalizeAddress( targetAddress) amount = transaction['amount'] / pow( 10, self.config['tn']['decimals']) if amount < self.config['main'][ 'min'] or amount > self.config['main']['max']: self.faultHandler(transaction, "senderror", e='outside amount ranges') else: try: txId = None self.db.insTunnel('sending', transaction['sender'], targetAddress) txId = self.otc.sendTx(targetAddress, amount) if not (str(txId.hex()).startswith('0x')): self.faultHandler(transaction, "senderror", e=txId.hex()) self.db.updTunnel("error", transaction['sender'], targetAddress, statusOld="sending") else: print("INFO: send tx: " + str(txId.hex())) self.db.insExecuted( transaction['sender'], targetAddress, txId.hex(), transaction['id'], amount, self.config['other']['fee']) print( 'INFO: send tokens from tn to erc20!') #self.db.delTunnel(transaction['sender'], targetAddress) self.db.updTunnel("verifying", transaction['sender'], targetAddress, statusOld='sending') except Exception as e: self.faultHandler(transaction, "txerror", e=e) continue if txId is None: if targetAddress != 'invalid address': self.db.insError( transaction['sender'], targetAddress, transaction['id'], '', amount, 'tx failed to send - manual intervention required' ) print( "ERROR: tx failed to send - manual intervention required" ) self.db.updTunnel("error", transaction['sender'], targetAddress, statusOld="sending") else: self.otc.verifyTx(txId, transaction['sender'], targetAddress) else: self.faultHandler(transaction, 'noattachment')
class BrukerParams(ExternalParams): format = 'Bruker' # how many directories to keep in file path for default DataUrl split keepDirectories = 4 def __init__(self, procs_file, **kw): # Accept procs directory or any file in it # Assume correct file is named 'procs' if there is such a file if os.path.isdir(procs_file): procs_file = os.path.join(procs_file, 'procs') else: dd, file = os.path.split(procs_file) if file != 'procs': ss = os.path.join(dd, 'procs') if os.path.isfile(ss): print 'Switching to input file: %s' % ss procs_file = ss self.procs_file = procs_file ExternalParams.__init__(self, **kw) # ExternalParams requires this to be defined def parseFile(self): # get processed file data try: help = BrukerParHelp('help') procParData = BrukerProcessingParData(self.procs_file, help.tags) procParData.get() except IOError, e: raise ApiError(str(e)) # get acquisition file data procDir = procParData.fileDir func = os.path.dirname acqDir = func(func(procDir)) files = set(os.listdir(acqDir)) nAxes = 1 while True: i = nAxes + 1 if ('acqu%ds' % i) in files: nAxes = i else: break numDim = procParData.numDim if nAxes < numDim: nAxes = numDim acqParData = None else: acqParData = BrukerAcqParData(os.path.join(acqDir, 'acqus'), nAxes, help.tags) acqParData.get() # check if we have a processed projection, a projection experiment or what if nAxes > numDim: extraDimHasPoints = [ x for x in acqParData.npts[numDim:nAxes] if x > 1 ] if extraDimHasPoints: # wb104: added the npts=1 check on 11 Mar 2011 # check if any dims have npts=1, in which case can eliminate onePointDims = [ i for i in range(nAxes) if acqParData.npts[i] == 1 ] if len(onePointDims) + numDim == nAxes: # can rescue this case # looks like don't use most of the below but what the heck, keep consistent for attr in ('baseFreq', 'npts', 'nuc', 'numPointsValid', 'refppm', 'refpt', 'sf', 'sw'): for n in reversed(onePointDims): try: del getattr(acqParData, attr)[n] except: # not sure should pass, perhaps should give up instead?? # but hopefully never in this situation pass else: # something is wrong here, # maybe we have e.g. a 2D projection of an original 3D spectrum # Anyway the acquisition parameters can not be trusted to match the # processing dimensions. print( 'WARNING, Spectrum is a computed, %sD projection or slice of a %sD Experiment' % (numDim, nAxes)) acqParData = None nAxes = numDim self.nAxes = nAxes # set data from proc files aPars = procParData.aPars aPars['nAxes'] = max(nAxes, numDim) aPars['scale'] = pow(2, aPars['brukerScale']) self.setAttrs(aPars) # add data from acqus files if acqParData is not None: self.acquisitionDim = 0 self.numScans = acqParData.numScans dateString = acqParData.dateString if dateString: self.date = dateString pulProgName = acqParData.pulProgName if pulProgName is not None: self.pulProgName = pulProgName self.pulProgType = 'bruker' # reset basefreq and sf to more accurate acqu values for tag in ('baseFreq', 'sf'): if hasattr(acqParData, tag): ll = getattr(acqParData, tag) getattr(self, tag)[:len(ll)] = ll if hasattr(acqParData, 'nuc'): nucs = self.nuc acqnucs = acqParData.nuc for ii, nuc in enumerate(nucs): #if nuc is None: # Added for TopSpin3.2: if nuc is 'off' also take from acqus if nuc in (None, 'off'): nucs[ii] = acqnucs[ii] # Add projection dimensions: # Assumes that first numDim acq dimensions are processed, and that # last nAxes-numDim dimensions are projection and add to last real dim # NB the test for projection experiment versus processed projection # has been done previously newInfoTags = ('sf', 'baseFreq', 'nuc', 'sw', 'refpt', 'refppm') if nAxes > numDim: # projection experiment (e.g. Prodecomp) for ss in newInfoTags: getattr(self, ss)[numDim:nAxes] = getattr(acqParData, ss)[numDim:nAxes] # add extra dimensions if extra displayNames present # (Prodecomp exps with pos/neg peaks Ca,Cb and possibly Ha,Hb) posNegCaCb = False displayNames = self.extraData.get('displayNames') if displayNames: if len(displayNames) > nAxes: if 'Ca' in displayNames and 'Cb' in displayNames: posNegCaCb = True indx = [ displayNames.index('Ca'), displayNames.index('Cb') ] indx.sort() for ss in dimParamDefs.keys(): ll = getattr(self, ss) if ll: ll.insert(indx[1], ll[indx[0]]) nAxes = self.nAxes = nAxes + 1 if len(displayNames) > nAxes: if 'Ha' in displayNames and 'Hb' in displayNames: indx = [ displayNames.index('Ha'), displayNames.index('Hb') ] indx.sort() for ss in dimParamDefs.keys(): ll = getattr(self, ss) if ll: ll.insert(indx[1], ll[indx[0]]) nAxes = self.nAxes = nAxes + 1 # reset carrier and reference from CNST for C, Cab, and Ca constants = acqParData.constants for ii, name in enumerate(displayNames): O1 = 1 if name == 'CO': O1 = constants.values[21] elif name == 'Cab' or (posNegCaCb and name in ('Ca', 'Cb')): O1 = constants.values[23] elif name == 'Ca': O1 = constants.values[22] if O1 == 1: continue baseFreq = self.baseFreq[ii] if baseFreq: self.sf[ii] = baseFreq + 1.0e-6 * O1 self.refpt[ii] = 1.0 self.refppm[ii] = O1 + 0.5 * self.sw[ii] / baseFreq
def run_operation(self): for engine in self.engine_objects: for _cache in self.cache: _index = "gr" _v_scale = self.scale _v_size = pow(2, _v_scale) _txsize = pow(2, _v_scale) self.initialize_property(engine.name) self.propertyFile.setInitCache(_cache[0]) self.propertyFile.setMaxCache(_cache[1]) navigate_profileName = "navigate.profile" now_string = self.db.now_string(True).replace(" ", "_") if self.tag_object: navigate_profileName = "navigate." + now_string + ".profile" pass f = file("ring_search.txt", "w") print >> f, "0,%d" % (pow(2, _v_scale) - 1) print >> f, "0,%d" % (pow(2, _v_scale) - 1) f.flush() f.close() self.ig_navigate(self.type, engine.name, self.propertyFile, _v_scale, 1, _txsize, navigate_profileName, "ring_search.txt") if self.case_object: f = file(navigate_profileName, "r") line = f.readline() data = eval(line) platform_object = self.db.create_unique_object( db_objects.model.platform, "name", data["os"]) index_object = self.db.create_unique_object( db_objects.model.index_type, "name", _index) case_data_object = self.db.create_object( db_objects.model.case_data, timestamp=self.db.now_string(True), case_id=self.case_object.id, tag_id=self.tag_object.id, engine_id=engine.id, size=data["size"], time=data["time"], memory_init=data["mem_init"], memory_used=data["mem_used"], memory_committed=data["mem_committed"], memory_max=data["mem_max"], op_size=data["opsize"], rate=data["rate"], page_size=_page_size, cache_init=self.propertyFile.getInitCache(), cache_max=self.propertyFile.getMaxCache(), tx_size=_txsize, platform_id=platform_object.id, threads=1, index_id=index_object.id, status=1) if self.diskmap: case_data_object.setDataValue("diskmap", self.diskmap) pass case_data_object.setDataValue("edge_factor", _e_factor) self.db.update(case_data_object) case_data_key = case_data_object.generateKey() case_data_stat_object = self.db.fetch_using_generic( db_objects.model.case_data_stat, key=case_data_key, case_id=self.case_object.id) if (len(case_data_stat_object) == 0): case_data_stat_object = self.db.create_unique_object( db_objects.model.case_data_stat, "key", case_data_key, case_id=self.case_object.id) else: case_data_stat_object = case_data_stat_object[0] pass case_data_stat_object.addCounter() case_data_stat_object.setRateStat(data["rate"]) case_data_stat_object.setTimeStat(data["time"]) case_data_stat_object.setMemInitStat(data["mem_init"]) case_data_stat_object.setMemUsedStat(data["mem_used"]) case_data_stat_object.setMemCommittedStat( data["mem_committed"]) case_data_stat_object.setMemMaxStat(data["mem_max"]) self.db.update(case_data_stat_object) f.close() os.remove(navigate_profileName) pass pass pass pass
def compound_interest(p, r , t): ci = p * (pow((1+ r/100), t)) print("Compund interst for years is", ci)
def computeDistance(self, point1, point2, length): distance = 0 for x in range(length): distance += pow((point1[x] - point2[x]), 2) return math.sqrt(distance)
def _skeleton_graph(project_id, skeleton_ids, confidence_threshold, bandwidth, expand, compute_risk, cable_spread, path_confluence, pre_rel='presynaptic_to', post_rel='postsynaptic_to') -> nx.DiGraph: """ Assumes all skeleton_ids belong to project_id. """ skeletons_string = ",".join(str(int(x)) for x in skeleton_ids) cursor = connection.cursor() # Fetch all treenodes of all skeletons cursor.execute(''' SELECT id, parent_id, confidence, skeleton_id, location_x, location_y, location_z FROM treenode WHERE skeleton_id IN (%s) ''' % skeletons_string) rows = tuple(cursor.fetchall()) # Each skeleton is represented with a DiGraph arbors: Union[DefaultDict[Any, nx.DiGraph], Dict[Any, nx.DiGraph]] = defaultdict(nx.DiGraph) # Get reviewers for the requested skeletons reviews = get_treenodes_to_reviews(skeleton_ids=skeleton_ids) # Create a DiGraph for every skeleton for row in rows: arbors[row[3]].add_node(row[0], **{'reviewer_ids': reviews.get(row[0], [])}) # Dictionary of skeleton IDs vs list of DiGraph instances arbors = split_by_confidence_and_add_edges(confidence_threshold, arbors, rows) # Fetch all synapses relations = get_relation_to_id_map(project_id, cursor=cursor) cursor.execute(''' SELECT connector_id, relation_id, treenode_id, skeleton_id FROM treenode_connector WHERE skeleton_id IN (%s) AND (relation_id = %s OR relation_id = %s) ''' % (skeletons_string, relations[pre_rel], relations[post_rel])) connectors: DefaultDict = defaultdict(partial(defaultdict, list)) skeleton_synapses: DefaultDict = defaultdict(partial(defaultdict, list)) for row in cursor.fetchall(): connectors[row[0]][row[1]].append((row[2], row[3])) skeleton_synapses[row[3]][row[1]].append(row[2]) # Cluster by synapses minis: DefaultDict[Any, List] = defaultdict( list) # skeleton_id vs list of minified graphs locations = None whole_arbors = arbors if expand and bandwidth > 0: locations = {row[0]: (row[4], row[5], row[6]) for row in rows} treenode_connector: DefaultDict[Any, List] = defaultdict(list) for connector_id, pp in connectors.items(): for treenode_id in chain.from_iterable(pp[relations[pre_rel]]): treenode_connector[treenode_id].append((connector_id, pre_rel)) for treenode_id in chain.from_iterable(pp[relations[post_rel]]): treenode_connector[treenode_id].append( (connector_id, post_rel)) arbors_to_expand = { skid: ls for skid, ls in arbors.items() if skid in expand } expanded_arbors, minis = split_by_synapse_domain( bandwidth, locations, arbors_to_expand, treenode_connector, minis) arbors.update(expanded_arbors) # Obtain neuron names cursor.execute(''' SELECT cici.class_instance_a, ci.name FROM class_instance ci, class_instance_class_instance cici WHERE cici.class_instance_a IN (%s) AND cici.class_instance_b = ci.id AND cici.relation_id = %s ''' % (skeletons_string, relations['model_of'])) names = dict(cursor.fetchall()) # A DiGraph representing the connections between the arbors (every node is an arbor) circuit = nx.DiGraph() for skid, digraphs in arbors.items(): base_label = names[skid] tag = len(digraphs) > 1 i = 0 for g in digraphs: if g.number_of_nodes() == 0: continue if tag: label = "%s [%s]" % (base_label, i + 1) else: label = base_label circuit.add_node( g, **{ 'id': "%s_%s" % (skid, i + 1), 'label': label, 'skeleton_id': skid, 'node_count': len(g), 'node_reviewed_count': sum( 1 for v in g.nodes.values() if 0 != len(v.get('reviewer_ids', [])) ), # TODO when bandwidth > 0, not all nodes are included. They will be included when the bandwidth is computed with an O(n) algorithm rather than the current O(n^2) 'branch': False, }) i += 1 # Define edges between arbors, with number of synapses as an edge property for c in connectors.values(): for pre_treenode, pre_skeleton in c[relations[pre_rel]]: for pre_arbor in arbors.get(pre_skeleton, ()): if pre_treenode in pre_arbor: # Found the DiGraph representing an arbor derived from the skeleton to which the presynaptic treenode belongs. for post_treenode, post_skeleton in c[relations[post_rel]]: for post_arbor in arbors.get(post_skeleton, ()): if post_treenode in post_arbor: # Found the DiGraph representing an arbor derived from the skeleton to which the postsynaptic treenode belongs. edge_props = circuit.get_edge_data( pre_arbor, post_arbor) if edge_props: edge_props['c'] += 1 edge_props['pre_treenodes'].append( pre_treenode) edge_props['post_treenodes'].append( post_treenode) else: circuit.add_edge( pre_arbor, post_arbor, **{ 'c': 1, 'pre_treenodes': [pre_treenode], 'post_treenodes': [post_treenode], 'arrow': 'triangle', 'directed': True, }) break break if compute_risk and bandwidth <= 0: # Compute synapse risk: # Compute synapse centrality of every node in every arbor that has synapses for skeleton_id, arbors in whole_arbors.items(): synapses = skeleton_synapses[skeleton_id] pre = synapses[relations[pre_rel]] post = synapses[relations[post_rel]] for arbor in arbors: # The subset of synapses that belong to the fraction of the original arbor pre_sub = tuple(treenodeID for treenodeID in pre if treenodeID in arbor) post_sub = tuple(treenodeID for treenodeID in post if treenodeID in arbor) totalInputs = len(pre_sub) totalOutputs = len(post_sub) tc = {treenodeID: Counts() for treenodeID in arbor} for treenodeID in pre_sub: tc[treenodeID].outputs += 1 for treenodeID in post_sub: tc[treenodeID].inputs += 1 # Update the nPossibleIOPaths field in the Counts instance of each treenode _node_centrality_by_synapse(arbor, tc, totalOutputs, totalInputs) arbor.treenode_synapse_counts = tc if not locations: locations = {row[0]: (row[4], row[5], row[6]) for row in rows} # Estimate the risk factor of the edge between two arbors, # as a function of the number of synapses and their location within the arbor. # Algorithm by Casey Schneider-Mizell # Implemented by Albert Cardona for pre_arbor, post_arbor, edge_props in circuit.edges(data=True): if pre_arbor == post_arbor: # Signal autapse edge_props['risk'] = -2 continue try: spanning = spanning_tree(post_arbor, edge_props['post_treenodes']) # for arbor in whole_arbors[circuit[post_arbor]['skeleton_id']]: # if post_arbor == arbor: # tc = arbor.treenode_synapse_counts tc = post_arbor.treenode_synapse_counts count = spanning.number_of_nodes() if count < 3: median_synapse_centrality = sum( tc[treenodeID].synapse_centrality for treenodeID in spanning.nodes) / count else: median_synapse_centrality = sorted( tc[treenodeID].synapse_centrality for treenodeID in spanning.nodes)[count / 2] cable = cable_length(spanning, locations) if -1 == median_synapse_centrality: # Signal not computable edge_props['risk'] = -1 else: edge_props['risk'] = 1.0 / sqrt( pow(cable / cable_spread, 2) + pow(median_synapse_centrality / path_confluence, 2) ) # NOTE: should subtract 1 from median_synapse_centrality, but not doing it here to avoid potential divisions by zero except Exception as e: logging.getLogger(__name__).error(e) # Signal error when computing edge_props['risk'] = -3 if expand and bandwidth > 0: # Add edges between circuit nodes that represent different domains of the same neuron for skeleton_id, list_mini in minis.items(): for mini in list_mini: for node in mini.nodes: g = mini.nodes[node]['g'] if 1 == len(g) and next( g.nodes(data=True))[1].get('branch'): # A branch node that was preserved in the minified arbor circuit.add_node( g, **{ 'id': '%s-%s' % (skeleton_id, node), 'skeleton_id': skeleton_id, 'label': "", # "%s [%s]" % (names[skeleton_id], node), 'node_count': 1, 'branch': True, }) for node1, node2 in mini.edges: g1 = mini.nodes[node1]['g'] g2 = mini.nodes[node2]['g'] circuit.add_edge( g1, g2, **{ 'c': 10, 'arrow': 'none', 'directed': False }) return circuit
def diff(x): return marketPrice - (1 + (c / x - 1) * (1 - pow((1 + x * dt), -(T / dt))))
_Scalars = int, float #: (INTERNAL) Scalar objects (C{tuple}) try: # _Seqs imported by .utily from collections import Sequence as _Seqs #: (INTERNAL) incl MutableSequence except ImportError: # PYCHOK no cover _Seqs = list, tuple, range # XXX also set? try: EPS = _float_info.epsilon #: System's epsilon (C{float}) MANTIS = _float_info.mant_dig #: System's mantissa bits (C{int}) MAX = _float_info.max #: System's float max (C{float}) MIN = _float_info.min #: System's float min (C{float}) except AttributeError: # PYCHOK no cover EPS = 2.220446049250313e-16 #: Epsilon (C{float}) 2**-52? MANTIS = 53 #: Mantissa bits ≈53 (C{int}) MAX = pow(2.0, 1023) * (2 - EPS) #: Float max (C{float}) ≈10**308, 2**1024? MIN = pow(2.0, -1021) # Float min (C{float}) ≈10**-308, 2**-1021? EPS_2 = EPS / 2 #: M{EPS / 2} ≈1.110223024625e-16 (C{float}) EPS1 = 1.0 - EPS #: M{1 - EPS} ≈0.9999999999999998 (C{float}) EPS1_2 = 1.0 - EPS_2 #: M{1 - EPS_2} ≈0.9999999999999999 (C{float}) # _1EPS = 1.0 + EPS #: M{1 + EPS} ≈1.0000000000000002 (C{float}) INF = float('inf') #: Infinity (C{float}), see C{isinf}, C{isfinite} NAN = float('nan') #: Not-A-Number (C{float}), see C{isnan} NEG0 = -0.0 #: Negative 0.0 (C{float}), see C{isneg0} _1_3rd = 1.0 / 3.0 #: (INTERNAL) One third (C{float}) _2_3rd = 2.0 / 3.0 #: (INTERNAL) Two thirds (C{float}) _3_2nd = 3.0 / 2.0 #: (INTERNAL) Three halfs (C{float})
from secret import flag from Crypto.Util.number import * assert flag.startswith('flag{') assert flag.endswith('}') pt = int(flag[5:-1].encode('hex'), 16) p = getPrime(30) q = getPrime(25) n = p * q e = 65537 assert pt < n print 'e:', e print 'n:', n print 'ct:', pow(pt, e, n)
def StandardDeviation(self, rss): average = self.MeanValue(rss) variance = sum([pow(RSSI-average,2) for RSSI in rss])/float(len(rss)-1) standarddev = math.sqrt(variance) return standarddev
# По данному целому числу N распечатайте все квадраты натуральных чисел, не превосходящие N, в порядке возрастания. # Например: # 50 1 4 9 16 25 36 49 # 10 1 4 9 # 9 1 4 9 # 4 1 4 # 1 1 # 100 1 4 9 16 25 36 49 64 81 100 # 99 1 4 9 16 25 36 49 64 81 inp = int(input('Введите число: ')) square = 1 a = 1 print ('Искомые квадраты: ', end = ' ') while square <= inp: # print ('a = ' + str(a)) # print ('square = ' + str(square)) a += 1 print((square), end = ' ') square = pow(a,2)