def _image(self, node): import urllib from reportlab.lib.utils import ImageReader u = urllib.urlopen(str(node.getAttribute("file"))) s = StringIO.StringIO() s.write(u.read()) s.seek(0) img = ImageReader(s) (sx, sy) = img.getSize() args = {} for tag in ("width", "height", "x", "y"): if node.hasAttribute(tag): args[tag] = utils.unit_get(node.getAttribute(tag)) if ("width" in args) and (not "height" in args): args["height"] = sy * args["width"] / sx elif ("height" in args) and (not "width" in args): args["width"] = sx * args["height"] / sy elif ("width" in args) and ("height" in args): if (float(args["width"]) / args["height"]) > (float(sx) > sy): args["width"] = sx * args["height"] / sy else: args["height"] = sy * args["width"] / sx self.canvas.drawImage(img, **args)
def calc_pr(bigccmat, numnodes, pprloc=-99): """ function calc_pr calculates PageRank based on the input transition matrix """ # convert to transition matrix rowsum = bigccmat.sum(axis=1) for ii in range(numnodes): if rowsum[ii, 0] != 0: bigccmat[ii, :] = bigccmat[ii, :] / rowsum[ii, 0] else: # case with no outgoing links bigccmat[ii, ii] = 1.0 # convert sparse matrix format sp_transmat_first = scisp.csr_matrix(bigccmat) oldprvec = np.matrix(np.ones((numnodes, 1))) / float(numnodes) convergevec = [1000] # some large value if pprloc > 0: onevec = np.matrix(np.zeros((numnodes, 1))) onevec[pprloc, 0] = 0.15 else: onevec = (0.15 / float(numnodes)) * np.matrix(np.ones((numnodes, 1))) ii = 0 while convergevec[-1] > 1e-5: newprvec = 0.85 * (sp_transmat_first.T * oldprvec) newprvec = newprvec + onevec newnorm = np.linalg.norm(newprvec, 1) convergevec.append(sum(abs(newprvec - oldprvec))[0, 0]) oldprvec = newprvec ii = ii + 1 print "Norm of PR vector:", newnorm print "Number of iterations for convergence:", ii convergevec.remove(1000) return (newprvec, convergevec)
def do_padding(img, padding): if not padding: return img try: padding = float(padding)*2.0 if padding > .9: padding = .9 if padding <= 0.0: return img except ValueError: return iw, ih = img.size img.thumbnail( ( int( round( float(img.size[0]) * (1.0 - padding) ) ), int( round( float(img.size[1]) * (1.0 - padding) ) ) ), pil.ANTIALIAS ) img = do_fill(img, "ffffff00", iw, ih) return img
def from_pmml(self, pmml): """Returns a model with the intercept and coefficients represented in PMML file.""" model = self() # Reads the input PMML file with BeautifulSoup. with open(pmml, "r") as f: lm_soup = BeautifulSoup(f, "xml") if not lm_soup.RegressionTable: raise ValueError("RegressionTable not found in the input PMML file.") else: ##### DO I WANT TO PULL THIS OUT AS ITS OWN FUNCTION? ##### # Pulls out intercept from the PMML file and assigns it to the # model. If the intercept does not exist, assign it to zero. intercept = 0 if "intercept" in lm_soup.RegressionTable.attrs: intercept = lm_soup.RegressionTable['intercept'] model.intercept_ = float(intercept) # Pulls out coefficients from the PMML file, and assigns them # to the model. if not lm_soup.find_all('NumericPredictor'): raise ValueError("NumericPredictor not found in the input PMML file.") else: coefs = [] numeric_predictors = lm_soup.find_all('NumericPredictor') for i in numeric_predictors: i_coef = float(i['coefficient']) coefs.append(i_coef) model.coef_ = numpy.array(coefs) return model
def find_info(test): #do the match match = regex.match(test) if match is not None: return (match.group(1),float(match.group(2)),float(match.group(3)),float(match.group(4))) else: return ("",0,0,0)
def getCraftedGcode(self, fileName, repository, svgText): "Parse svgText and store the scale svgText." svgReader = SVGReader() svgReader.parseSVG('', svgText) if svgReader.sliceDictionary == None: print('Warning, nothing will be done because the sliceDictionary could not be found getCraftedGcode in preface.') return '' xyPlaneScale = repository.xyPlaneScale.value zAxisScale = repository.zAxisScale.value decimalPlacesCarried = int(svgReader.sliceDictionary['decimalPlacesCarried']) layerHeight = zAxisScale * float(svgReader.sliceDictionary['layerHeight']) edgeWidth = float(svgReader.sliceDictionary['edgeWidth']) loopLayers = svgReader.loopLayers for loopLayer in loopLayers: setLoopLayerScale(loopLayer, xyPlaneScale, zAxisScale) cornerMaximum = Vector3(-912345678.0, -912345678.0, -912345678.0) cornerMinimum = Vector3(912345678.0, 912345678.0, 912345678.0) svg_writer.setSVGCarvingCorners(cornerMaximum, cornerMinimum, layerHeight, loopLayers) svgWriter = svg_writer.SVGWriter( True, cornerMaximum, cornerMinimum, decimalPlacesCarried, layerHeight, edgeWidth) commentElement = svg_writer.getCommentElement(svgReader.documentElement) procedureNameString = svgReader.sliceDictionary['procedureName'] + ',scale' return svgWriter.getReplacedSVGTemplate(fileName, loopLayers, procedureNameString, commentElement)
def set_value(self, value): if(self._parameter_to_map_to != None): if(self._parameter_to_map_to.is_enabled): newval = float(float(float(value)/127) * (self._parameter_to_map_to.max - self._parameter_to_map_to.min)) + self._parameter_to_map_to.min self._parameter_to_map_to.value = newval else: self.receive_value(int(value))
def __init__(self): rospy.init_node('actuators_handler') rospy.loginfo(rospy.get_caller_id() + 'Initializing actuators_handler node') self.timelast = 0 #Get all parameters from config (rosparam) name = 'engine' engine_output_pin = int(rospy.get_param('actuators/' + name + '/output_pin', 1)) engine_board_pin = int(rospy.get_param('actuators/' + name + '/board_pin', 60)) engine_period_us = int(1e6 / float(rospy.get_param('actuators/' + name + '/frequency', 60))) name = 'steering' steering_output_pin = int(rospy.get_param('actuators/' + name + '/output_pin', 1)) steering_board_pin = int(rospy.get_param('actuators/' + name + '/board_pin', 62)) steering_period_us = int(1e6 / float(rospy.get_param('actuators/' + name + '/frequency', 60))) #Initialize PWM self.dev1 = mraa.Pwm(engine_board_pin) self.dev1.period_us(engine_period_us) self.dev1.enable(True) self.dev1.pulsewidth_us(1500) self.dev2 = mraa.Pwm(steering_board_pin) self.dev2.period_us(steering_period_us) self.dev2.enable(True) self.dev2.pulsewidth_us(1500)
def parse_rho(m1, m2, config): """Parse the rho data and convert to numpy array.""" f = open(in_name(m1, m2, config), 'r') # Skip to the mixed rho correlator section. # This assumes it is the first RHO* entry. !! x = f.readline() while x: if re.match('correlator:\s+RHO', x): break x = f.readline() # Throw away header. print x for i in range(5): print f.readline().strip() result = [] for i in range(64): t, r, im = f.readline().strip().split('\t') result.append(complex(float(r), float(im))) f.close() return np.array(result)
def legIK(self, X, Y, Z, resolution): """ Compute leg servo positions. """ ans = [0,0,0,0] # (coxa, femur, tibia) try: # first, make this a 2DOF problem... by solving coxa ans[0] = radToServo(atan2(X,Y), resolution) trueX = int(sqrt(sq(X)+sq(Y))) - self.L_COXA im = int(sqrt(sq(trueX)+sq(Z))) # length of imaginary leg # get femur angle above horizon... q1 = -atan2(Z,trueX) d1 = sq(self.L_FEMUR)-sq(self.L_TIBIA)+sq(im) d2 = 2*self.L_FEMUR*im q2 = acos(d1/float(d2)) ans[1] = radToServo(q1+q2, resolution) # and tibia angle from femur... d1 = sq(self.L_FEMUR)-sq(im)+sq(self.L_TIBIA) d2 = 2*self.L_TIBIA*self.L_FEMUR; ans[2] = radToServo(acos(d1/float(d2))-1.57, resolution) except: if self.debug: "LegIK FAILED" return [1024,1024,1024,0] if self.debug: print "LegIK:",ans return ans
def extract_features(data): ''' Perform feature extraction for variables that can be extracted the same way for both training and test data sets. The input "data" is the pandas dataframe for the training or test sets. ''' token_pattern = re.compile(r"(?u)\b\w+\b") data["query_tokens_in_title"] = 0.0 data["query_tokens_in_description"] = 0.0 data["percent_query_tokens_in_description"] = 0.0 data["percent_query_tokens_in_title"] = 0.0 for i, row in data.iterrows(): query = set(x.lower() for x in token_pattern.findall(row["search_term"])) title = set(x.lower() for x in token_pattern.findall(row["product_title"])) description = set(x.lower() for x in token_pattern.findall(row["product_description"])) if len(title) > 0: data.set_value(i, "query_tokens_in_title", float(len(query.intersection(title)))/float(len(title))) data.set_value(i, "percent_query_tokens_in_title", float(len(query.intersection(title)))/float(len(query))) if len(description) > 0: data.set_value(i, "query_tokens_in_description", float(len(query.intersection(description)))/float(len(description))) data.set_value(i, "percent_query_tokens_in_description", float(len(query.intersection(description)))/float(len(query))) data.set_value(i, "query_length", len(query)) data.set_value(i, "description_length", len(description)) data.set_value(i, "title_length", len(title)) two_grams_in_query = set(get_n_grams(row["search_term"], 2)) two_grams_in_title = set(get_n_grams(row["product_title"], 2)) two_grams_in_description = set(get_n_grams(row["product_description"], 2)) data.set_value(i, "two_grams_in_q_and_t", len(two_grams_in_query.intersection(two_grams_in_title))) data.set_value(i, "two_grams_in_q_and_d", len(two_grams_in_query.intersection(two_grams_in_description)))
def _render_on_subplot(self, subplot): """ Render this arrow in a subplot. This is the key function that defines how this arrow graphics primitive is rendered in matplotlib's library. EXAMPLES:: This function implicitly ends up rendering this arrow on a matplotlib subplot: sage: arrow(path=[[(0,1), (2,-1), (4,5)]]) """ options = self.options() width = float(options['width']) head = options.pop('head') if head == 0: style = '<|-' elif head == 1: style = '-|>' elif head == 2: style = '<|-|>' else: raise KeyError('head parameter must be one of 0 (start), 1 (end) or 2 (both).') arrowsize = float(options.get('arrowsize',5)) head_width=arrowsize head_length=arrowsize*2.0 color = to_mpl_color(options['rgbcolor']) from matplotlib.patches import FancyArrowPatch from matplotlib.path import Path bpath = Path(self.vertices, self.codes) p = FancyArrowPatch(path=bpath, lw=width, arrowstyle='%s,head_width=%s,head_length=%s'%(style,head_width, head_length), fc=color, ec=color, linestyle=options['linestyle']) p.set_zorder(options['zorder']) p.set_label(options['legend_label']) subplot.add_patch(p) return p
def send_file_with_oob_tcp(s, filename): sending_file = open(filename, 'rb') filesize = os.stat(filename).st_size oob_sent = 0 try: bytes_sent = int(s.recv(Constants.FILE_CHUNK_SIZE)) print "Already sent {0} / {1}".format(bytes_sent, filesize) except: print 'Lost Connection' return 0 sending_file.seek(int(bytes_sent), 0) while True: chunk = sending_file.read(Constants.FILE_CHUNK_SIZE) if not chunk: break try: s.settimeout(Constants.DEFAULT_TIMEOUT) s.send(chunk) except socket.error: print 'Transfer fail' return 0 bytes_sent += Constants.FILE_CHUNK_SIZE percent = int(float(bytes_sent) * 100 / float(filesize)) print "{0} / {1} Kb sent ({2}%)".format(Utils.to_kilobytes(bytes_sent), Utils.to_kilobytes(filesize), percent) sys.stdout.write('\033M') if (percent % 10 == 0) & (oob_sent != percent) & (percent < 91): oob_sent = percent sys.stdout.write('\033D') print '\033[37;1;41m Urgent flag sent at {0}% \033[0m'.format(percent) s.send(b'{}'.format(percent / 10), socket.MSG_OOB) sending_file.close()
def send_file_multicast(s, filename): connections = {} filesize = os.stat(filename).st_size try: while True: readable, _, _ = select.select([s], [], []) for rd in readable: bytes_sent = 0 package, client_address = s.recvfrom(Constants.FILE_CHUNK_SIZE) unpacked_package = Utils.unpack_package(package) if not connections.has_key(client_address) or connections[client_address] is None: connections[client_address] = open(filename, 'rb') if unpacked_package['command'] == Constants.INIT_TRANSMIT: bytes_sent = int(unpacked_package['payload']) connections[client_address].seek(bytes_sent) data = connections[client_address].read(Constants.FILE_CHUNK_SIZE) if not data: rd.sendto(Utils.pack_package(Constants.FIN, ''), client_address) connections[client_address].close() connections[client_address] = None else: rd.sendto(Utils.pack_package(Constants.ACK, data), client_address) bytes_sent += len(data) percent = int(float(bytes_sent) * 100 / float(filesize)) print "{0} / {1} Kb sent to client {2}({3}%)".format(Utils.to_kilobytes(bytes_sent), Utils.to_kilobytes(filesize), client_address, percent) sys.stdout.write('\033M') except socket.error, value: print value
def send_file_udp(s, filename): bytes_sent = 0 sending_file = open(filename, 'rb') filesize = os.stat(filename).st_size while True: package, client_address = s.recvfrom(Constants.FILE_CHUNK_SIZE) unpacked_package = Utils.unpack_package(package) if unpacked_package['command'] == Constants.INIT_TRANSMIT: bytes_sent = int(unpacked_package['payload']) sending_file.seek(bytes_sent) data = sending_file.read(Constants.FILE_CHUNK_SIZE) if not data: s.sendto(Utils.pack_package(Constants.FIN, ''), client_address) sending_file.close() break else: s.sendto(Utils.pack_package(Constants.ACK, data), client_address) package, client_address = s.recvfrom(Constants.FILE_CHUNK_SIZE) unpacked_package = Utils.unpack_package(package) if unpacked_package['command'] == Constants.ACK: bytes_sent += len(data) percent = int(float(bytes_sent) * 100 / float(filesize)) print "{0} / {1} Kb sent ({2}%)".format(Utils.to_kilobytes(bytes_sent), Utils.to_kilobytes(filesize), percent)
def init(): global theMesh, theLight, theCamera, \ theScreen, resolution initializeVAO() glEnable(GL_CULL_FACE) glEnable(GL_DEPTH_TEST) # Add our object # LIGHT theLight = N.array((-0.577, 0.577, 0.577, 0.0),dtype=N.float32) # OBJECT phongshader = makeShader("phongshader.vert","phongshader.frag") verts, elements = readOBJ("suzanne.obj") suzanneVerts = getArrayBuffer(verts) suzanneElements = getElementBuffer(elements) suzanneNum = len(elements) theMesh = coloredMesh(N.array((1.0, 0.5, 1.0, 1.0), dtype=N.float32), suzanneVerts, suzanneElements, suzanneNum, phongshader) # CAMERA width,height = theScreen.get_size() aspectRatio = float(width)/float(height) near = 0.01 far = 100.0 lens = 4.0 # "longer" lenses mean more telephoto theCamera = Camera(lens, near, far, aspectRatio) theCamera.moveBack(6)
def parse(self, attributes): def getValues(string): return numpy.array(list(map(float, string.split(" ")))) self.color.ident = self.demangled() if "shininess" in attributes.keys(): self.color.shininess = float(attributes["shininess"]) if "transparency" in attributes.keys(): self.color.transparency = float(attributes["transparency"]) if "diffuseColor" in attributes.keys(): self.color.diffuse = getValues(attributes["diffuseColor"]) if "emissiveColor" in attributes.keys(): self.color.emissive = getValues(attributes["emissiveColor"]) if "specularColor" in attributes.keys(): self.color.specular = getValues(attributes["specularColor"]) if "ambientIntensity" in attributes.keys(): self.color.ambient = self.color.diffuse * float(attributes["ambientIntensity"]) debug("%sMaterial properties:" % (' ' * self.level)) debug("%sShininess: %f" % (' ' * (self.level + 1), self.color.shininess)) debug("%sTransparency: %f" % (' ' * (self.level + 1), self.color.transparency)) debug("%sDiffuse Color: %f, %f, %f" % (' ' * (self.level + 1), self.color.diffuse[0], self.color.diffuse[1], self.color.diffuse[2])) debug("%sEmissive Color: %f, %f, %f" % (' ' * (self.level + 1), self.color.emissive[0], self.color.emissive[1], self.color.emissive[2])) debug("%sSpecular Color: %f, %f, %f" % (' ' * (self.level + 1), self.color.specular[0], self.color.specular[1], self.color.specular[2])) debug("%sAmbient Color: %f, %f, %f" % (' ' * (self.level + 1), self.color.ambient[0], self.color.ambient[1], self.color.ambient[2]))
def __init__(self,name,ambient=0.2,diffuse=0.2,specular=0.9,emission=0.1,shininess=2.0): self.name = str(name) self.ambient = float(ambient) self.diffuse = float(diffuse) self.specular = float(specular) self.emission = float(emission) self.shininess = float(shininess)
def shoot(temp, lux): with picamera.PiCamera() as camera: camera.resolution = (1024, 768) camera.start_preview() time.sleep(3) #fix camera values camera.shutter_speed = camera.exposure_speed camera.exposure_mode = 'off' g = camera.awb_gains camera.awb_mode = 'off' camera.awb_gains = g #camera.iso = 100-200 daytime, 400-800 low light if float(lux) >= 250: iso = 100 + (float(lux) - 250)/(1000 - 250)*(200-100) else: iso = 400 - (float(lux) - 250)/(250)*(800-400) camera.iso = int(iso) #set iso value #add date time to the image camera.annotate_text = strftime('%d-%m-%Y %H:%M:%S', localtime()) #camera.annotate_text = temp camera.capture('image.jpg') camera.stop_preview()
def testcaserun_setstatus(request, testcaserun_id): testcaserun = TestCaseRun.objects.get(pk=testcaserun_id) testcaserun_status_form = forms.TestCaseRunStatus(request.POST, instance=testcaserun) if testcaserun_status_form.is_valid(): testcaserun = testcaserun_status_form.save() log = history.History(request.user, testcaserun.parent) log.add_form(testcaserun_status_form, capture=["status"], prefix=True) log.save() # TODO: move this to testrun? method. Chec also templatetags passrate_ratio = [] testrun = testcaserun.parent testcaseruns_count = testrun.testcases.count() statuses = TestCaseRunStatus.objects.filter(testcaserun__parent=testrun).annotate(count=Count('testcaserun')) for status in statuses: passrate_ratio.append({ "ratio": float(status.count) / float(testcaseruns_count) * 100, "name": status.name, "color": status.color, }) return success(message=testcaserun.status.name, data=dict(id=testcaserun.pk, name=testcaserun.status.name, color=testcaserun.status.color, passrate=testcaserun.parent.passrate, passrate_ratio=passrate_ratio)) else: return failed(message=testcaserun.status.name, data=testcaserun_status_form.errors_list())
def get_temperature(): res = subprocess.check_output('sensors',shell=True) a = res.decode('utf-8') diva = a.split('\n') cpu1 = diva[2].split(' ')[4][1:5] cpu2 = diva[2].split(' ')[4][1:5] return (float(cpu1)+float(cpu2))/2
def main(): args = args_parse() out1 = open("%s.TE.fa"%str(args.fasta).split(".")[0],"w") out2 = open("%s.CON.fa"%str(args.fasta).split(".")[0],"w") seqslen = get_len(args.fasta) seqs = get_seqs(args.fasta) TE = get_TE_ids(args.TE) pfam_ids = get_pfam(args.infile) TE_ids = [] for line in open(args.infile,"r"): if "#" not in line and len(line.strip().split()) == 15 : ids = line.strip().split()[0] start = int(line.strip().split()[1]) end = int(line.strip().split()[2]) hmm = line.strip().split()[5] if hmm.split(".")[0] in TE: per = (float(end)-float(start)+float(1))/float(seqslen.get(ids)) if per >= float(0.3): TE_ids.append(ids) out1.write(">%s\t%f\n%s\n"%(ids,per,seqs.get(ids))) set1 = set(TE_ids) set2 = set(seqs.keys()) for retain_ids in set2 - set1: try: out2.write(">%s\t%s\n%s\n"%(retain_ids,pfam_ids[retain_ids],seqs.get(retain_ids))) except KeyError: out2.write(">%s\tNon-domains\n%s\n"%(retain_ids,seqs.get(retain_ids)))
def __init__(self, nscans=nscans_d, nt_scan=nt_scan_d, nf=nf_d, nra=nra_d, ndec=ndec_d, scan_size=scan_size_d, map_size=map_size_d, thermal=0, correlated_noise=None, random_mean=0, random_slope=0, add_ground=False, freq_mode_noise=None, universal_over_f=None): # Store parameters. self.nscans = nscans self.nt_scan = nt_scan self.nf = nf self.nra = nra self.ndec = ndec self.scan_size = float(scan_size) self.map_size = float(map_size) self.add_ground = add_ground # Noise parameters. self.thermal = thermal self.correlated_noise = correlated_noise self.freq_mode_noise = freq_mode_noise self.random_mean = random_mean self.random_slope = random_slope self.universal_over_f = universal_over_f # Initialize a counter. self.data_set_number = 0 self.nt = nt_scan * nscans self.dt = dt_d
def _getxview(self): # Horizontal dimension. clipperWidth = self._hclipper.winfo_width() frameWidth = self._hsframe.winfo_reqwidth() if frameWidth <= clipperWidth: # The scrolled frame is smaller than the clipping window. self.startX = 0 endScrollX = 1.0 if self['horizflex'] in ('expand', 'elastic'): relwidth = 1 else: relwidth = '' else: # The scrolled frame is larger than the clipping window. if self['horizflex'] in ('shrink', 'elastic'): self.startX = 0 endScrollX = 1.0 relwidth = 1 else: if self.startX + clipperWidth > frameWidth: self.startX = frameWidth - clipperWidth endScrollX = 1.0 else: if self.startX < 0: self.startX = 0 endScrollX = (self.startX + clipperWidth) / float(frameWidth) relwidth = '' # Position frame relative to clipper. self._hsframe.place(x = -self.startX, relwidth = relwidth) return (self.startX / float(frameWidth), endScrollX)
def createOrbPos(self, feraw): orbpos = feraw.get("orbital_position") if orbpos > 1800: return str((float(3600 - orbpos)) / 10.0) + "\xc2\xb0 W" elif orbpos > 0: return str((float(orbpos)) / 10.0) + "\xc2\xb0 E" return ""
def _getyview(self): # Vertical dimension. clipperHeight = self._vclipper.winfo_height() frameHeight = self._vsframe.winfo_reqheight() if frameHeight <= clipperHeight: # The scrolled frame is smaller than the clipping window. self.startY = 0 endScrollY = 1.0 if self['vertflex'] in ('expand', 'elastic'): relheight = 1 else: relheight = '' else: # The scrolled frame is larger than the clipping window. if self['vertflex'] in ('shrink', 'elastic'): self.startY = 0 endScrollY = 1.0 relheight = 1 else: if self.startY + clipperHeight > frameHeight: self.startY = frameHeight - clipperHeight endScrollY = 1.0 else: if self.startY < 0: self.startY = 0 endScrollY = (self.startY + clipperHeight) / float(frameHeight) relheight = '' # Position frame relative to clipper. self._vsframe.place(y = -self.startY, relheight = relheight) return (self.startY / float(frameHeight), endScrollY)
def get_user_details(self, username): contents = re.split('([+/])', username) assert len(contents) % 2 == 1 user, contents2 = contents[0], contents[1:] desired_pseudoshare_target = None desired_share_target = None for symbol, parameter in zip(contents2[::2], contents2[1::2]): if symbol == '+': try: desired_pseudoshare_target = bitcoin_data.difficulty_to_target(float(parameter)) except: if p2pool.DEBUG: log.err() elif symbol == '/': try: desired_share_target = bitcoin_data.difficulty_to_target(float(parameter)) except: if p2pool.DEBUG: log.err() if random.uniform(0, 100) < self.worker_fee: pubkey_hash = self.my_pubkey_hash else: try: pubkey_hash = bitcoin_data.address_to_pubkey_hash(user, self.node.net.PARENT) except: # XXX blah pubkey_hash = self.my_pubkey_hash return user, pubkey_hash, desired_share_target, desired_pseudoshare_target
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 __parse_positions(self, var): listPattern = re.compile("\[[^\[]+?\]") tagPattern = re.compile("<.+?>") betweenTagPattern = re.compile(">(.+?)<") numberPattern = re.compile("-?\d+\.?\d*") stringPattern = re.compile('".*?[^\\\\]"') positions = [] columns = ("pid", "date", "stock", "percentage", "shares", "notes") for text in listPattern.findall(var): data = stringPattern.findall(text[1:-1]) stock = betweenTagPattern.findall(data[0])[0] if self.user == list_user: percentage = shares = "NULL" notes = tagPattern.sub(" ", data[-1][1:-1]) else: comments = tagPattern.split(data[-1][1:-1]) try: percentage = float(numberPattern.findall(comments[0])[0]) except: percentage = 0 try: shares = float(numberPattern.findall(comments[1])[0]) except: shares = 0 try: notes = comments[2] except: notes = "" positions.append( dict(zip(columns, (self.id, self.now, stock, percentage, shares, notes.encode("ascii", "ignore")))) ) return positions
def readXml10811(item): global X_10811,LIGHT_SMALL_BIG,DATA_BIG,DATA_SMALL tablelist = item.getElementsByTagName('table') table_1 = tablelist[0] datalist = table_1.getElementsByTagName('td') #获取光源及小像大像位置 data_x = (float(datalist[2].firstChild.nodeValue),float(datalist[3].firstChild.nodeValue), float(datalist[4].firstChild.nodeValue)) LIGHT_SMALL_BIG = (float(datalist[2].firstChild.nodeValue),float(datalist[3].firstChild.nodeValue),float(datalist[4].firstChild.nodeValue)) table_2 = tablelist[1] datalist = table_2.getElementsByTagName('td') #获取大像位置 data_b2 = (float(datalist[0].firstChild.nodeValue), float(datalist[1].firstChild.nodeValue),float(datalist[2].firstChild.nodeValue), float(datalist[3].firstChild.nodeValue)) for b in data_b2: DATA_BIG.append(b) #获取小像位置 data_b1 = (float(datalist[4].firstChild.nodeValue),float(datalist[5].firstChild.nodeValue),float(datalist[6].firstChild.nodeValue),float(datalist[7].firstChild.nodeValue)) for b in data_b1: DATA_SMALL.append(b) table_3 = tablelist[2] datalist = table_3.getElementsByTagName('td') #获取条纹位置 data_X = [] for i in range(len(datalist)): data_X.append(float(datalist[i].firstChild.nodeValue)) X_10811.append(float(datalist[i].firstChild.nodeValue)) return data_b1, data_b2, data_x, data_X