def test_something_typeConversions(self): import math self.assertEqual(complex(1), complex(Something(1))) self.assertEqual(oct(1), oct(Something(1))) self.assertEqual(hex(16), hex(Something(16))) self.assertEqual(math.trunc(math.pi), math.trunc(maybe(math.pi)))
def muestraAccel(self): wiiuse.motion_sensing(self.wiimotes,self.nmotes) wiiuse.poll(self.wiimotes, self.nmotes) t = self.wm.gforce.x temp=0 try: temp = math.trunc(t) except: temp=0 if temp< (self.rotX-3) or temp> (self.rotX+3): self.rotX= temp self.window.emit(SIGNAL("AccelX"), self.rotX) t = self.wm.gforce.y temp=0 try: temp = math.trunc(t) except: temp=0 if temp < (self.rotY-3) or temp > (self.rotY+3): self.rotY= temp self.window.emit(SIGNAL("AccelY"), self.rotY) t = self.wm.gforce.z temp=0 try: temp = math.trunc(t) except: temp=0 if temp != self.rotZ: self.rotZ= temp self.window.emit(SIGNAL("AccelZ"), self.rotZ)
def mw_cdf(x_hist_vals, hist_vals, a_coeff, figs, plot=False): max_a = np.sum(hist_vals) area_a = np.ones(len(hist_vals)) for el in xrange(len(hist_vals)): area_a[el] = np.sum(hist_vals[0:el+1]) c_d_f = area_a/max_a interp = interp1d(c_d_f, x_hist_vals) a_best = interp(0.5) a_limits = interp(np.array([0.5 - 0.683/2.0, 0.5 + 0.683/2.0])) decim = [math.trunc(np.abs(np.log10(a_best - a_limits[0])))+2, math.trunc(np.abs(np.log10(a_limits[1] - a_best)))+2] uncertainties = np.array([round(a_best - a_limits[0], decim[0]), round(a_limits[1] - a_best, decim[1])]) if plot: plt.figure(figs) figs += 1 plt.clf() plt.scatter(x_hist_vals, c_d_f, marker='+') plt.plot((a_best, a_best), (( c_d_f.max(), 0)), 'g') plt.errorbar(a_best, 0.5, xerr=[[uncertainties[0]], [uncertainties[1]]], fmt='^', color='red') plt.ylabel('CDF ') plt.xlabel(r'a$_'+str(a_coeff)+'$ values') plt.title(r'Result: a$_'+str(a_coeff)+' = '+str(round(a_best, np.max(decim)))+'_{-'+str(uncertainties[1])+'}^{+'+str(uncertainties[0])+'}$') plt.show() #in most cases unnecessary return figs
def ejecutar(self, ts = None): if self.parametro2 != None: # 2 PARAMETROS nodoSyn1 = self.parametro1.ejecutar(ts) if isinstance(nodoSyn1 , ErrorReport): return nodoSyn1 nodoSyn2 = self.parametro2.ejecutar(ts) if isinstance(nodoSyn2 , ErrorReport): return nodoSyn2 if isinstance(nodoSyn1 , ExpresionNumero) and isinstance(nodoSyn2 , ExpresionNumero): if self.funcion == "ATAN2": rads = math.atan2(nodoSyn1.val,nodoSyn2.val) return ExpresionNumero(rads,self.getTipo(rads),self.linea) if self.funcion == "ATAN2D": rads = math.atan2(nodoSyn1.val,nodoSyn2.val) grados = (rads * 180/math.pi) return ExpresionNumero(grados,self.getTipo(grados),self.linea) if self.funcion == "DIV": izq = nodoSyn1.val der = nodoSyn2.val if der == 0: return ErrorReport('semantico', 'error DIVISION entre 0' ,self.linea) valor = izq/der return ExpresionNumero(valor,self.getTipo(valor),self.linea) if self.funcion =="GCD": valor = math.gcd(nodoSyn1.val , nodoSyn2.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) if self.funcion =="MOD": try: valor = (nodoSyn1.val % nodoSyn2.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) except: return ErrorReport('semantico', 'error en MODULO' ,self.linea) if self.funcion =="POWER": try: valor = (nodoSyn1.val ** nodoSyn2.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) except: return ErrorReport('semantico', 'error en MODULO' ,self.linea) if self.funcion =="ROUND": valor = round(nodoSyn1.val , nodoSyn2.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) if self.funcion == "TRUNC": if self.getTipo(nodoSyn2.val) != TIPO_DE_DATO.ENTERO: return ErrorReport('semantico', 'error en Metodo TRUNC el segundo parametro tiene que ser un entero' ,self.linea) cadenaInt = str(nodoSyn1.val) numero_truncado = '' indice = 0 decimalesAdjuntados = 0 for i in range(len(cadenaInt)): if cadenaInt[i] == '.': numero_truncado += cadenaInt[i] indice = i break else: numero_truncado += cadenaInt[i] indice+=1 while(decimalesAdjuntados < nodoSyn2.val): if indice < len(cadenaInt): numero_truncado += cadenaInt[indice] else: numero_truncado += '0' indice+=1 decimalesAdjuntados+=1 valor = float(numero_truncado) return ExpresionNumero(valor,self.getTipo(valor),self.linea) else: return ErrorReport('semantico', 'error de tipo, se esperaba un ENTERO O DECIMAL' ,self.linea) elif self.parametro1 != None: # 1 PARAMETRO if isinstance(self.parametro1,list): if self.funcion =="WIDTH_BUCKET": return self.metodo_width_bucket(self.parametro1,ts) nodoSyn1 = self.parametro1.ejecutar(ts) if isinstance(nodoSyn1 , ErrorReport): return nodoSyn1 if isinstance(nodoSyn1 , ExpresionNumero): # decimales y eneteros if self.funcion == "ACOS": # RADIANEES if nodoSyn1.val > 1 or nodoSyn1.val < 1: return ErrorReport('semantico', 'Error en ACOS ,el parametro debe estar entre -1 y 1' ,self.linea) return ExpresionNumero(math.acos(nodoSyn1.val),self.getTipo(nodoSyn1.val),self.linea) if self.funcion == "ACOSD": # GRADOS if nodoSyn1.val > 1 or nodoSyn1.val < 1: return ErrorReport('semantico', 'Error en ACOSD , el parametro debe estar entre -1 y 1' ,self.linea) rads = math.acos(nodoSyn1.val) grados = (rads * 180/math.pi) return ExpresionNumero(grados,self.getTipo(grados),self.linea) if self.funcion == "ASIN": if nodoSyn1.val > 1 or nodoSyn1.val < 1: return ErrorReport('semantico', 'Error en ASIN ,el parametro debe estar entre -1 y 1' ,self.linea) valor = math.asin(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) if self.funcion == "ASIND": if nodoSyn1.val > 1 or nodoSyn1.val < 1: return ErrorReport('semantico', 'Error en ASIND ,el parametro debe estar entre -1 y 1' ,self.linea) rads = math.asin(nodoSyn1.val) grados = (rads * 180/math.pi) return ExpresionNumero(grados,self.getTipo(grados),self.linea) if self.funcion == "ATAN": try: rads = math.atan(nodoSyn1.val) return ExpresionNumero(rads,self.getTipo(rads),self.linea) except: return ErrorReport('semantico', 'Error en ATAN por el valor del parametro ' ,self.linea) if self.funcion == "ATAND": try: rads = math.atan(nodoSyn1.val) grados = (rads * 180/math.pi) return ExpresionNumero(grados,self.getTipo(grados),self.linea) except: return ErrorReport('semantico', 'Error en ATAND por el valor del parametro ' ,self.linea) if self.funcion == "COS": valor = math.cos(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) if self.funcion == "COSD": rads = math.cos(nodoSyn1.val) grados = (rads * 180/math.pi) return ExpresionNumero(grados,self.getTipo(grados),self.linea) if self.funcion == "COT": tangente=math.tan(nodoSyn1.val) if tangente == 0: return ErrorReport('semantico', 'Error en COT por el valor del parametro ' ,self.linea) cot = 1 / tangente return ExpresionNumero(cot,self.getTipo(cot),self.linea) if self.funcion == "COTD": tangente=math.tan(nodoSyn1.val) if tangente == 0: return ErrorReport('semantico', 'Error en COTD por el valor del parametro ' ,self.linea) cot =math.degrees(1 / tangente) return ExpresionNumero(cot,self.getTipo(cot),self.linea) if self.funcion == "SIN": radianes=math.sin(nodoSyn1.val) return ExpresionNumero(radianes,self.getTipo(radianes),self.linea) if self.funcion == "SIND": grados=math.degrees(math.sin(nodoSyn1.val)) return ExpresionNumero(grados,self.getTipo(grados),self.linea) if self.funcion == "TAN": try: radianes=math.tan(nodoSyn1.val) return ExpresionNumero(radianes,self.getTipo(radianes),self.linea) except: return ErrorReport('semantico', 'Error en TAN por el valor del parametro ' ,self.linea) if self.funcion == "TAND": try: grados=math.degrees(math.tan(nodoSyn1.val)) return ExpresionNumero(grados,self.getTipo(grados),self.linea) except: return ErrorReport('semantico', 'Error en TAND por el valor del parametro ' ,self.linea) if self.funcion == "COSH": try: valor=math.cosh(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) except: return ErrorReport('semantico', 'Error en COSH por el valor del parametro ' ,self.linea) if self.funcion == "SINH": try: valor=math.sinh(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) except: return ErrorReport('semantico', 'Error en SINH por el valor del parametro ' ,self.linea) if self.funcion == "TANH": try: valor=math.tanh(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) except: return ErrorReport('semantico', 'Error en TANH por el valor del parametro ' ,self.linea) if self.funcion == "ACOSH": if nodoSyn1.val < 1: return ErrorReport('semantico', 'Error en ACOSH, el parametro debe de ser mayor o igual a 1 ' ,self.linea) valor=math.acosh(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) if self.funcion == "ASINH": valor=math.asinh(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) if self.funcion == "ATANH": if nodoSyn1.val > 0.99 or nodoSyn1.val < -0.99: return ErrorReport('semantico', 'Error en ATANH, el parametro debe estar entre 0.99 y -0.99 ' ,self.linea) valor=math.atanh(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) #_________________________________ fin de trigonometricas if self.funcion == "ABS": valor=math.fabs(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) if self.funcion == "CBRT": #RAIZ CUBICA SOLO PARA ENTREROS if (nodoSyn1.val) < 0 : return ErrorReport('semantico', 'error SQRT solo recibe enteros POSITIVOS :D' ,self.linea) if (nodoSyn1.val % 1) == 0: valor = nodoSyn1.val**(1/3) return ExpresionNumero(valor,self.getTipo(valor),self.linea) else: return ErrorReport('semantico', 'error CBRT solo recibe enteros, NO decimales' ,self.linea) if self.funcion =="CEIL" or self.funcion == "CEILING": valor = math.ceil(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) if self.funcion =="DEGREES": valor = math.degrees(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) if self.funcion =="FACTORIAL": valor = math.factorial(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) if self.funcion =="FLOOR":# POR SI VIENE EN UN INSERT valor = math.floor(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) if self.funcion =="LN": try: valor = math.log(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) except : return ErrorReport('semantico', 'error en el paramtro de LN' ,self.linea) if self.funcion =="LOG": try: valor = math.log10(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) except : return ErrorReport('semantico', 'error en el paramtro de LOG' ,self.linea) if self.funcion =="EXP": try: valor = math.exp(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) except : return ErrorReport('semantico', 'error en el paramtro de EXP' ,self.linea) if self.funcion =="RADIANS": valor = math.radians(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) if self.funcion =="ROUND": valor = round(nodoSyn1.val) return ExpresionNumero(valor,self.getTipo(valor),self.linea) if self.funcion =="SIGN": if nodoSyn1.val > 0: valor = 1 return ExpresionNumero(valor,TIPO_DE_DATO.ENTERO,self.linea) if nodoSyn1.val < 0: valor = -1 return ExpresionNumero(valor,TIPO_DE_DATO.ENTERO,self.linea) else: return ErrorReport('semantico', 'error en funcion SING , EL 0 no tiene signo ' ,self.linea) if self.funcion == "SQRT": if (nodoSyn1.val) < 0 : return ErrorReport('semantico', 'error SQRT solo recibe enteros POSITIVOS' ,self.linea) if (nodoSyn1.val % 1) == 0: valor = nodoSyn1.val**(1/2) return ExpresionNumero(valor,self.getTipo(valor),self.linea) else: return ErrorReport('semantico', 'error SQRT solo recibe enteros, NO decimales' ,self.linea) if self.funcion == "TRUNC": valor = math.trunc(nodoSyn1.val) return ExpresionNumero(valor,TIPO_DE_DATO.ENTERO,self.linea) else: return ErrorReport('semantico', 'error de tipo, se esperaba un ENTERO O DECIMAL' ,self.linea) else:# SIN PARAMETROS if self.funcion == 'PI': return ExpresionNumero(math.pi,TIPO_DE_DATO.DECIMAL,self.linea) elif self.funcion == "RANDOM": valor = random.choice((1,0)) return ExpresionNumero(valor,TIPO_DE_DATO.ENTERO,self.linea)
def test_basic(pair: AlternativeNativeFractionsPair) -> None: alternative, native = pair assert are_alternative_native_ints_equal(math.trunc(alternative), math.trunc(native))
def glClearColor(self, r, g, b): for i in range(self.height): for j in range(self.width): self.bmp.point( i, j, color(trunc(r * 255), trunc(g * 255), trunc(b * 255)))
import math # Acquisition and Control of the DATA entered by the USER number = input("Enter the NUMBER to add: ") numbers = [] while number != "": try: # Storing the entered number if "." not in number: numbers.append(int(number)) else: numbers.append(float(number)) # Displaying the CURRENT SUM current_sum = sum(numbers) if current_sum - math.trunc(current_sum) == 0: current_sum = int(current_sum) print("Current Sum = " + str(current_sum)) number = input("Enter the NUMBER to add: ") # Exception -> Value Error except ValueError: print("Warning, a NON-NUMERIC value has been entered.") number = input("Enter the NUMBER to add: ") # Displaying the RESULTS print("The SUM of the NUMBERS entered is {} ".format(current_sum)) print("NUMBERS entered -> ", end="") if len(numbers) == 0: print("NO ONE") else: for value in numbers:
def dc_journ(region): df_reg = df_new_regions[df_new_regions["regionName"] == region] dc_new_rolling = df_reg["incid_dc"].rolling(window=7).mean() range_x, name_fig, range_y = ["2020-03-29", last_day_plot], "dc_journ_"+region, [0, df_reg["incid_dc"].max()] title = "<b>Décès hospitaliers quotidiens</b> du Covid19 - <b>" + region + "</b>" fig = go.Figure() fig.add_trace(go.Scatter( x = df_reg["jour"], y = dc_new_rolling, name = "Nouveaux décès hosp.", marker_color='black', line_width=8, opacity=0.8, fill='tozeroy', fillcolor="rgba(0,0,0,0.3)", showlegend=False )) fig.add_trace(go.Scatter( x = [dates[-1]], y = [dc_new_rolling.values[-1]], name = "Nouveaux décès hosp.", mode="markers", marker_color='black', marker_size=15, opacity=1, showlegend=False )) # fig.add_trace(go.Scatter( x = df_reg["jour"], y = df_reg["incid_dc"], name = "Nouveaux décès hosp.", mode="markers", marker_color='black', line_width=3, opacity=0.4, showlegend=False )) ### fig.update_yaxes(zerolinecolor='Grey', range=range_y, tickfont=dict(size=18)) fig.update_xaxes(nticks=10, ticks='inside', tickangle=0, tickfont=dict(size=18)) # Here we modify the tickangle of the xaxis, resulting in rotated labels. fig.update_layout( margin=dict( l=50, r=0, b=50, t=70, pad=0 ), legend_orientation="h", barmode='group', title={ 'text': title, 'y':0.93, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'}, titlefont = dict( size=20), xaxis=dict( title='', tickformat='%d/%m'), annotations = [ dict( x=0, y=1, xref='paper', yref='paper', font=dict(size=15), text='{}. Données : Santé publique France. <b>@GuillaumeRozier - covidtracker.fr</b>'.format(datetime.strptime(max(dates), '%Y-%m-%d').strftime('%d %b')), showarrow = False ), ] ) fig['layout']['annotations'] += (dict( x = dates[-1], y = dc_new_rolling.values[-1], # annotation point xref='x1', yref='y1', text=" <b>{} {}".format('%d' % math.trunc(round(dc_new_rolling.values[-1], 2)), "décès quotidiens</b><br>en moyenne<br>du {} au {}.".format(datetime.strptime(dates[-7], '%Y-%m-%d').strftime('%d'), datetime.strptime(dates[-1], '%Y-%m-%d').strftime('%d %b'))), xshift=-2, yshift=0, xanchor="center", align='center', font=dict( color="black", size=20 ), bgcolor="rgba(255, 255, 255, 0.6)", opacity=0.8, ax=-250, ay=-90, arrowcolor="black", arrowsize=1.5, arrowwidth=1, arrowhead=0, showarrow=True ),) fig.write_image(PATH+"images/charts/france/regions_dashboards/{}.jpeg".format(name_fig), scale=1.2, width=900, height=600) print("> " + name_fig)
def render_hud(self, window): """Renders a Head-Up display on the active window.""" center = (75, s.DIMENSIONS[1] - 80) speedo_rect = (35, s.DIMENSIONS[1] - 120, 80, 80) orbit_pos = (self.speed / (self.settings["top_speed"] / 4.7)) + 2.35 start = self.__circular_orbit(center, -10, orbit_pos) finish = self.__circular_orbit(center, 36, orbit_pos) speed = round((self.speed / s.SEGMENT_HEIGHT) * 1.5, 1) font = pygame.font.Font(s.FONTS["retro_computer"], 16) st = self.special_text time_colour = s.COLOURS["text"] if self.time_left > 5 else s.COLOURS[ "red"] pygame.draw.circle(window, s.COLOURS["black"], center, 50, 2) pygame.draw.circle(window, s.COLOURS["black"], center, 4) pygame.draw.line(window, s.COLOURS["black"], start, finish, 3) pygame.draw.arc(window, s.COLOURS["black"], speedo_rect, 0.2, math.pi * 1.25, 5) pygame.draw.arc(window, s.COLOURS["red"], speedo_rect, -0.73, 0.2, 5) u.render_text("kmph", window, font, s.COLOURS["text"], (110, s.DIMENSIONS[1] - 24)) u.render_text(str(speed), window, font, s.COLOURS["text"], (10, s.DIMENSIONS[1] - 24)) u.render_text("Lap", window, font, s.COLOURS["text"], (s.DIMENSIONS[0] - 130, 10)) u.render_text("%s/%s" % (self.lap, self.total_laps), window, font, s.COLOURS["text"], (s.DIMENSIONS[0] - 58, 10)) u.render_text("Time", window, font, time_colour, (10, 10)) u.render_text(str(math.trunc(self.time_left)), window, font, time_colour, (90, 10)) # Render special text. if st: td = (datetime.datetime.now() - st[0]) if td.seconds > st[1]: self.special_text = None else: bonus_colour = "bonus_a" if (td.microseconds / 25000.0) % 10 > 5 else "bonus_b" u.render_text(st[2], window, font, s.COLOURS[bonus_colour], (10, 36)) # Points rendering needs more care because it grows so fast. p_val_text = font.render(str(math.trunc(self.points)), 1, s.COLOURS["text"]) p_name_text = font.render("Points", 1, s.COLOURS["text"]) p_val_x = s.DIMENSIONS[0] - p_val_text.get_width() - 10 window.blit(p_val_text, (p_val_x, s.DIMENSIONS[1] - 24)) window.blit(p_name_text, (p_val_x - 112, s.DIMENSIONS[1] - 24)) # Hit a point milestone. if self.points > self.next_milestone and self.status == self.ALIVE: milestone_sfx = pygame.mixer.Sound( os.path.join("lib", "excellent.ogg")) milestone_sfx.play() self.next_milestone += s.POINT_MILESTONE self.__set_special_text("Nice driving!", 2) # On the leaderboard! if self.high_score > 0 and self.points > self.high_score: high_score_sfx = pygame.mixer.Sound( os.path.join("lib", "excellent.ogg")) high_score_sfx.play() self.high_score = 0 self.__set_special_text("New High Score!", 2) if self.status == self.GAME_OVER: self.__game_over_overlay(window) elif self.status == self.LEVEL_OVER: self.__level_over_overlay(window) # Display lap difference (unless we've only done one lap). if self.lap_margin != 0 and self.lap > 2 and self.lap_percent < 20: diff = self.lap_margin if diff <= 0: colour = "red" sign = "+" else: colour = "green" sign = "-" u.render_text(sign + str(round(abs(diff), 1)), window, font, s.COLOURS[colour], (10, 40))
def main(): torch.manual_seed(42) device = "cpu" dataset = getBachDataset() #print(dataset) conv = [3, 4, 8, 16] fc = [32, 16, 2] shape = dataset["train"].shape PATH = "" enc = torch.load(PATH + "enchighest.pt") dec = torch.load(PATH + "dechighest.pt") disc = torch.load(PATH + "dischighest.pt") clsfr = torch.load(PATH + "clsfrhighest.pt") enc.eval() dec.eval() disc.eval() clsfr.eval() test_dl = torch.utils.data.DataLoader(dataset["eval"], batch_size=50) test_probs, test_preds, testy_labels = predict_dl(test_dl, enc, dec, clsfr) dict_save = { 'Expected': testy_labels, 'predictions': test_preds } # , 'dec_predictions' : dec_preds} # prediction = pd.DataFrame(dict_save, columns=['Expected','predictions']).to_csv('binary_new.csv') #print(testy_labels) #print(test_preds) #prediction = pd.DataFrame(test_preds, columns=['predictions']).to_csv('testpreds.csv') np.savetxt("test_labels.txt", np.hstack(testy_labels).astype(int), delimiter=',') np.savetxt("test_preds.txt", np.hstack(test_preds).astype(int), delimiter=',') arr = [] for i in range(len(testy_labels)): label = math.trunc(testy_labels[i]) pred_label = math.trunc(test_preds[i]) arr.append([label, pred_label]) np.savetxt("predictions.txt", arr, delimiter=',') lr_auc = roc_auc_score(testy_labels, test_probs) print('ROC AUC=%.3f' % (lr_auc)) # calculate roc curves lr_fpr, lr_tpr, _ = roc_curve(testy_labels, test_probs) # plot the roc curve for the model plt.plot(lr_fpr, lr_tpr, marker='.', label='Binary') # axis labels plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') # show the legend plt.legend() plt.savefig("ROC_new_bin") # show the plot plt.show()
def result(language=default_language): birth_date = request.args.get('birth_date') if not birth_date: abort(400) birth_date = datetime.strptime(birth_date, '%Y-%m-%d').date() gender = int(request.args.get('sex', '1')) if gender not in genders: abort(400) country_id = int(request.args.get('country', '181')) if country_id not in countries: abort(400) country = countries.get(country_id) life_exp = countries.get(country_id)['life_exp'] life_length_years = math.trunc(life_exp[gender]) life_length_months = round(12 * math.modf(life_exp[gender])[0]) life_length = relativedelta( years=life_length_years, months=life_length_months ) today_date = date.today() death_date = birth_date + life_length lived = relativedelta(birth_date, today_date) life_left = relativedelta(death_date, today_date) params = { 'birth_date': birth_date.strftime(config.DATE_FORMAT), 'today_date': today_date.strftime(config.DATE_FORMAT), 'lived': { 'years': abs(lived.years), 'months': abs(lived.months) }, 'life_length': { 'years': life_length_years, 'months': life_length_months }, 'death_date': death_date.strftime(config.DATE_FORMAT), 'life_left': { 'years': life_left.years, 'months': life_left.months, 'days': life_left.days }, 'sex': genders[gender][language]['name'], } params.update({ 'site_addr': f'{request.scheme}://{request.host}', 'languages': languages, 'language': language, 'country': country }) params.update({ 'translate': lt_lib.getTranslator(translations, language), 'dateFormate': lt_lib.getDateFormator(language=language) }) return render_template('pages/result.html', **params)
import math n = float(input("digite um number: ")) i = math.trunc(n) print("O inteiro do numero {} é {}".format(n, i))
def truncate(number, digits): stepper = 10.0**digits return math.trunc(stepper * number) / stepper
def jd_to_date(jd): """ Convert Julian Day to date. Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet', 4th ed., Duffet-Smith and Zwart, 2011. Parameters ---------- jd : float Julian Day Returns ------- year : int Year as integer. Years preceding 1 A.D. should be 0 or negative. The year before 1 A.D. is 0, 10 B.C. is year -9. month : int Month as integer, Jan = 1, Feb. = 2, etc. day : float Day, may contain fractional part. Examples -------- Convert Julian Day 2446113.75 to year, month, and day. >>> jd_to_date(2446113.75) (1985, 2, 17.25) """ jd = jd + 0.5 F, I = math.modf(jd) I = int(I) A = math.trunc((I - 1867216.25) / 36524.25) if I > 2299160: B = I + 1 + A - math.trunc(A / 4.) else: B = I C = B + 1524 D = math.trunc((C - 122.1) / 365.25) E = math.trunc(365.25 * D) G = math.trunc((C - E) / 30.6001) day = C - E + F - math.trunc(30.6001 * G) if G < 13.5: month = G - 1 else: month = G - 13 if month > 2.5: year = D - 4716 else: year = D - 4715 return year, month, day
from math import trunc num = float(input('Informe o numero: ')) print(trunc(num))
#y[BB]=0 plt.figure(num=1, dpi=100, facecolor='white') plt.plot(t, y, 'r') plt.xlim(0, 0.05) plt.xlabel('time($sec$)') plt.ylabel('y') plt.savefig("./test_figure1.png", dpi=300) # Calculate FFT .................... n = len(y) # Length of signal NFFT = n # ?? NFFT=2^nextpow2(length(y)) ?? k = np.arange(NFFT) f0 = k * Fs / NFFT # double sides frequency range f0 = f0[range(math.trunc(NFFT / 2))] # single sied frequency range Y = np.fft.fft(y) / NFFT # fft computing and normaliation Y = Y[range(math.trunc(NFFT / 2))] # single sied frequency range amplitude_Hz = 2 * abs(Y) phase_ang = np.angle(Y) * 180 / np.pi # figure 1 .................................. plt.figure(num=2, dpi=100, facecolor='white') plt.subplots_adjust(hspace=0.6, wspace=0.3) plt.subplot(3, 1, 1) plt.plot(t, y, 'r') plt.title('Signal FFT analysis') plt.xlabel('time($sec$)') plt.ylabel('y')
def findDistance(self, bounds, x, y, psi): if (psi >= (2 * math.pi)): # findDistance commands only likes psi within 0-2pi so only for this instance use relative psi psi = psi - math.trunc(psi / (2 * math.pi)) * 2 * math.pi # Generate bound segments m = zeros((bounds.shape[0], 1)) for index in range(0, bounds.shape[0]): m[index] = (bounds[index][1] - bounds[index - 1][1]) / ( bounds[index][0] - bounds[index - 1][0]) bound_segments = append(bounds, m, axis=1) # Uses point-slope form to find intersection of ray (fish heading) and the # bounds of the tank. Assumes psi is between 0 and 2pi # Create ray describing current heading if psi < 0: psi += 2 * math.pi m_ray = math.tan(psi) x_intersect_arr = array([]) y_intersect_arr = array([]) for index in range(0, bound_segments.shape[0]): # Loop through each boundary segment and find intersection point # Shortcut because we know the tank boundaries will always be either # vertical or horizontal. if abs(bound_segments[index][2]) == 0: # Horizontal line described by y = num y_intersect = bound_segments[index][ 1] # will intersect at this y value x_intersect = (y_intersect + m_ray * x - y) / m_ray # point-slope solved for x elif math.isinf(bound_segments[index][2]): # Vertical line described by x = num x_intersect = bound_segments[index][ 0] # will intersect this x value y_intersect = m_ray * (x_intersect - x) + y # point-slope solved for y # Save values in array x_intersect_arr = append(x_intersect_arr, x_intersect) y_intersect_arr = append(y_intersect_arr, y_intersect) # Use intersection points to find distance distances = sqrt( square(x_intersect_arr - x) + square(y_intersect_arr - y)) # Now we need to find the right quadrant of intersection point. quad_ray = math.floor(psi / (math.pi / 2)) + 1 if (psi == math.pi / 2 and x > 0) or (psi == math.pi and y > 0) or ( psi == 3 * math.pi / 2 and x < 0): # correct for weird instances where quadrant is iffy. Shouldn't ever occur # because it's very very unlikely yaw will be exactly pi, pi/2, etc. quad_ray -= 1 if (psi == 0 and y < 0): # see above, yes these are one-off solutions but again this shouldn't really occur # in practice. quad_ray = 4 intersect_angles = arctan2(y_intersect_arr - y, x_intersect_arr - x) for i in range(len(intersect_angles)): if intersect_angles[i] < 0: intersect_angles[i] += 2 * math.pi quad_intersections = floor(intersect_angles / (math.pi / 2)) + 1 flag = 0 for i in range(len(quad_intersections)): # not out of the fish bounds x_pt = x_intersect_arr[i] y_pt = y_intersect_arr[i] if ((quad_intersections[i] == quad_ray) and (abs(x_pt) <= (self.bound_X + 0.1)) and (abs(y_pt) <= (self.bound_Y / 2 + 0.1))): dw = distances[i] # x_intersect_actual = x_intersect_arr[i] # y_intersect_actual = y_intersect_arr[i] break else: dw = 0.1 # flag = 1 # if flag: # print(str(x)+"\t"+str(y)+"\t"+str(psi)) return dw
def updateStates(self, dt, Omega, U, x, y, zdot, psi, S, state=1, friendpos=None): if friendpos is not None: goal_angle = arctan2(friendpos[1] - self.y, friendpos[0] - self.x) - math.pi / 2 angle_error_1 = goal_angle + self.laps * 2 * math.pi - self.psi angle_error_2 = goal_angle + (self.laps - 1) * 2 * math.pi - self.psi if (abs(angle_error_2) <= abs(angle_error_1)): angle_error = angle_error_2 else: angle_error = angle_error_1 # rospy.logwarn("ptw thinks that friendpos is: "+str(friendpos)) # goal_angle=0 dist_error = -self.dfish + sqrt((self.x - friendpos[0])**2 + (self.y - friendpos[1])**2) # rospy.logwarn("dist error is "+str(dist_error)) if dist_error < 0: dist_error = 0 else: goal_angle = self.psi dist_error = 0 rospy.logwarn("friendpos is none") self.dt = dt Omegadot, Udot, zdoubledot, dw = self.calcDerivatives( Omega, U, x, y, zdot, psi, friendpos) # rospy.logwarn("angle error: "+str((goal_angle*self.laps*2*pi-self.psi)*self.yaw_K)) self.Omega += Omegadot * dt + (angle_error) * self.yaw_K * dt # if state == 1: # self.U += Udot*dt # else: # self.U = 0 rospy.logwarn("dist error: " + str(dist_error)) if dist_error > (2 * self.dfish): self.U += Udot * dt else: self.U += Udot * dt + self.dist_K * dist_error * dt self.zdot += zdoubledot * dt if (self.U < 0): ## print "U can't do that!" #self.U=0 pass # if dw <= 0.005: # self.U = 0 ##### Bound z by setting zdot = 0 when approaching boundaries ##### TOP - z = 0, anything less than 0 will stop it ##### BOTTOM - z = maxz anything more will stop it. ##### Recall that positive zdot is down if ((self.z <= 0.001) and (self.zdot < 0)): # If we're at the min depth (0) and going upwards (zdot < 0) self.zdot = 0 # elif((self.z>=(app.zmax-0.001)) and (self.zdot>0)): # in case bound_Z isn't updated for some reason.. pull zmax from Window class. elif ((self.z >= (self.bound_Z - 0.001)) and (self.zdot > 0)): self.zdot = 0 # Determine relative positions S, psi # self.S += self.U*dt ######## NOTE THIS IS JUST IN-PLANE PATH # in-plane path depth path self.S += math.sqrt((self.U * dt)**2 + (self.zdot * dt)**2) self.psi = psi + self.Omega * dt # laps can be found by dividing current psi by 2pi to find number of laps psi_sign = self.psi / abs( self.psi ) # if negative this will return negative, positive positive. self.laps = psi_sign * math.trunc(abs(self.psi) / (2 * math.pi)) # if abs(self.psi)>=2*math.pi: # # Keep yaw within 0 to 2pi # if self.psi < 0: # self.psi += 2*math.pi # if self.psi > 0: # self.psi -= 2*math.pi ################## SF WALL LIMITS ########################################### if ((self.x <= 0.01) or (self.x >= self.bound_X - 0.01)): # If the fish is outside left/right bounds if ((self.x <= 0.01) and (self.U * math.cos(self.psi) <= 0)): # If it's on the left wall and moving left self.x = self.x elif ((self.x <= 0.01) and (self.U * math.cos(self.psi) > 0)): self.x = self.x + self.U * math.cos(self.psi) * dt if ((self.x >= (self.bound_X - 0.01)) and (self.U * math.cos(self.psi) >= 0)): # If it's on the right wall and moving right self.x = self.x elif ((self.x >= (self.bound_X - 0.01)) and (self.U * math.cos(self.psi) < 0)): self.x = self.x + self.U * math.cos(self.psi) * dt else: self.x = self.x + self.U * math.cos(self.psi) * dt if ((self.y <= 0.01) or (self.y >= self.bound_Y - 0.01)): # If it's outside top/bottom bounds if ((self.y <= 0.01) and (self.U * math.sin(self.psi) <= 0)): # If it's at bottom wall and moving down self.y = self.y elif ((self.y <= 0.01) and (self.U * math.sin(self.psi) > 0)): self.y = self.y + self.U * math.sin(self.psi) * dt if ((self.y >= (self.bound_Y - 0.01)) and (self.U * math.sin(self.psi) >= 0)): # If it's at top wall and moving up self.y = self.y elif ((self.y >= (self.bound_Y - 0.01)) and (self.U * math.sin(self.psi) < 0)): self.y = self.y + self.U * math.sin(self.psi) * dt else: self.y = self.y + self.U * math.sin(self.psi) * dt ################### AAB WALL LIMITS ######################################### # if(self.x<.01): # if(self.U*cos(self.psi)<=0): # print"bounding x" # self.x=self.x # else: # self.x = x + self.U*math.cos(psi)*dt # else: # self.x = x + self.U*math.cos(psi)*dt # if(self.x>(self.bound_X-.01)): # if(self.U*cos(self.psi)>=0): # print "bounding x for bigbound" # self.x=self.x # else: # self.x = self.x + self.U*math.cos(psi)*dt # else: # self.x = self.x + self.U*math.cos(psi)*dt # if(self.y<.01): # if(self.U*sin(self.psi)<=0): # print "bounding y" # self.y=self.y # else: # self.y = self.y + self.U*math.sin(psi)*dt # else: # self.y = self.y + self.U*math.sin(psi)*dt # if(self.y>(self.bound_Y-.01)): # if(self.U*sin(self.psi)>=0): # self.y=self.y # print "bounding y for bigbound" # else: # self.y = self.y + self.U*math.sin(psi)*dt # else: # self.y = self.y + self.U*math.sin(psi)*dt ############################################################################ # # Use these to transform to local coordinates # if ((self.x<.01) or (self.x>(self.bound_X-.01))): # if(self.U*) # self.x = self.x # else: # self.x = x + self.U*math.cos(psi)*dt # if ( (self.y<.01) or (self.y>(self.bound_Y - .01))): # self.y = self.y # else: # self.y = self.y + self.U*math.sin(psi)*dt self.z = self.z + self.zdot * dt # self.y = y + self.U*math.sin(self.psi)*dt # self.x = x + self.U*math.cos(self.psi)*dt # tail+dt*self.Uuff # self.pitchnow = 0. if (self.Udot > 0): tailfreq_new = self.maxfreq * self.Udot / (self.mu_u) * 7.5 else: tailfreq_new = 0 if self.statusNow == "Inactive": tailfreq_new = 0 self.tailfreq = ( 1 - dt / self.tailfreq_tau ) * self.tailfreq + dt / self.tailfreq_tau * tailfreq_new self.tailtheta += self.tailfreq * dt self.tailangle = self.maxamp * sin( self.tailtheta) - 2 * self.maxamp * self.yawrate if (U > .01): pitchnew = -arctan2(self.zdot, self.U) else: pitchnew = 0 self.pitchnow = (1 - dt / self.pitchtau ) * self.pitchnow + dt / self.pitchtau * pitchnew # print self.pitchnow #print self.psi return self.x, self.y, self.psi, self.z, self.pitchnow, self.tailangle
(grid_nodes, grid_nodes, grid_nodes, 3)) #Reshape eigenvectors #'data' format reminder: (Pos)XYZ(Mpc/h), (Vel)VxVyVz(km/s), (Ang. Mom)JxJyJz((Msun/h)*(Mpc/h)*km/s), (Vir. Mass)Mvir(Msun/h) & (Vir. Rad)Rvir(kpc/h) #partcl_halo_flt=np.where((data[:,9]/(Mass_res))>=particles_filt)#filter for halos with <N particles partcl_halo_flt = np.where( data[:, 11] >= particles_filt) #filter for halos with <N particles data = data[partcl_halo_flt] #Filter out halos with <N particles #apend eigvecs on to data array and apend mask value to data array #create empty arrays and apend to data array color_cd = np.zeros((len(data), 1)) norm_eigvecs = np.zeros((len(data), 3)) data = np.hstack((data, color_cd, norm_eigvecs)) for i in range(len(data)): #Create index from halo coordinates grid_index_x = mth.trunc(data[i, 0] * Xc_mult - Xc_minus) grid_index_y = mth.trunc(data[i, 1] * Yc_mult - Yc_minus) grid_index_z = mth.trunc(data[i, 2] * Zc_mult - Zc_minus) data[i, 12] = mask[grid_index_x, grid_index_y, grid_index_z] data[i, 13:16] = recon_vecs[grid_index_x, grid_index_y, grid_index_z, :] del recon_vecs del mask #NEW 'data' format :(Pos)XYZ(Mpc/h), (Vel)VxVyVz(km/s), (Ang. Mom)JxJyJz((Msun/h)*(Mpc/h)*km/s), (Vir. Mass)Mvir(Msun/h), #(Vir. Rad)Rvir(kpc/h), mask(0,1,2,3) & eigvecs(ex,ey,ez) fil_filt = np.where(data[:, 12] == lss_type) #2-filament data = data[fil_filt] #At this point is where the methods will be different.================================================================================= def dpbins_hiho(data):
def process(input_path, output_prefix): makedirs(os.path.split(output_prefix)[0], exist_ok=True) df = pd.read_csv(input_path) hxl = df.ix[0] df = df.ix[1:] df["datetime"] = df.date.apply( lambda x: datetime.datetime.strptime(x, "%Y-%m-%d")) df["ym"] = df.datetime.apply(lambda x: x.year + (x.month - 1) / 12.0) df["price"] = df.price.apply(float) plots = [] for key, index in sorted( df.groupby(["cmname", "unit", "mktname"]).groups.items()): commodity, unit, market = key g = df.ix[index] plots.append( go.Scatter(x=g.date, y=g.price, mode='lines+markers', name='%(commodity)s (%(unit)s) - %(market)s' % locals())) plot(plots, show_link=False, filename=output_prefix + "_all.html", auto_open=False) plots = [] for key, index in sorted(df.groupby(["cmname", "unit"]).groups.items()): commodity, unit = key g = df.ix[index] gd = g.groupby(["date"]) x = gd.price.mean().index y = gd.price.mean() y_min = gd.price.min() y_max = gd.price.max() plots.append( go.Scatter(x=x, y=y, name='%(commodity)s (%(unit)s)' % locals(), error_y=dict(type='data', symmetric=False, array=y_max - y, arrayminus=y - y_min))) plot(plots, show_link=False, filename=output_prefix + "_band.html", auto_open=False) plots = [] for key, index in sorted(df.groupby(["cmname", "unit"]).groups.items()): commodity, unit = key g = df.ix[index] gd = g.groupby(["date"]) x = gd.price.median().index y = gd.price.median() plots.append( go.Scatter(x=x, y=y, name='%(commodity)s (%(unit)s)' % locals(), mode='lines+markers')) plot(plots, show_link=False, filename=output_prefix + "_median.html", auto_open=False) plots = [] for key, index in sorted(df.groupby(["cmname", "unit"]).groups.items()): commodity, unit = key g = df.ix[index] invmean = 100.0 / g.price.mean() quantity = math.pow(10, math.trunc(math.log10(invmean))) qlabel = quantity if quantity < 1: qlabel = "1/" + str(int(1 / quantity)) if qlabel == 1: qlabel = "" gd = g.groupby(["date"]) x = gd.price.median().index y = gd.price.median() * quantity plots.append( go.Scatter(x=x, y=y, name='%(commodity)s (%(qlabel)s %(unit)s)' % locals(), mode='lines+markers')) plot(plots, show_link=False, filename=output_prefix + "_scaledmedian.html", auto_open=False) plots = [] for key, index in sorted(df.groupby(["cmname", "unit"]).groups.items()): commodity, unit = key g = df.ix[index] invmean = 100.0 / g.price.mean() quantity = invmean qlabel = quantity gd = g.groupby(["date"]) x = gd.price.median().index y = gd.price.median() * quantity plots.append( go.Scatter(x=x, y=y, name='%(commodity)s (%(qlabel)s %(unit)s)' % locals(), mode='lines+markers')) plot(plots, show_link=False, filename=output_prefix + "_normmedian.html", auto_open=False) plots = [] for key, index in sorted(df.groupby(["cmname", "unit"]).groups.items()): commodity, unit = key g = df.ix[index] x = g.date y = g.price plots.append( go.Scatter(x=x, y=y, name='%(commodity)s (%(unit)s)' % locals(), mode='markers')) plot(plots, show_link=False, filename=output_prefix + "_allscat.html", auto_open=False)
from math import trunc real = float(input('Digite um número aleatório :')) inteiro = trunc(real) print('O número digita foi {} e quando transformado em inteiro se tornou {}!'. format(real, inteiro))
2.3 a와 b의 합집합을 구한다. a = ['FR', 'RA', 'AN', 'NC', 'CE'] b = ['FR', 'RE', 'EN', 'NC', 'CH'] union = set(a+b) print(union) 2.4 a와 b의 자카드 유사도를 구한다. (결과에 65536을 곱해서 출력) a = ['FR', 'RA', 'AN', 'NC', 'CE'] b = ['FR', 'RE', 'EN', 'NC', 'CH'] import math len_i = len(intersection) len_u = len(union) print ( math.trunc( len_i / len_u * 65536) ) 문제521. 지금까지의 코드를 함수로 만들어서 아래와 같이 실행되게하시오 print( Jaccard() ) 문자열을 입력해주세요. : FRANCE 문자열을 입력해주세요. : french 16384 import math def str_split(string): res =[] for i in range( len(string) -1 ):
def get_ratio_next(ratio): if ratio == float("inf"): return ratio else: return math.trunc(ratio) + 1
def validate(self): self.checkForAnalyzerErrors() # check we include some metadata in the summary self.assertGrep('loganalyzer_output/summary_status.generated-log-08.csv', expr='# metadata.*,analyzerVersion=,[0-9]') self.assertGrep('loganalyzer_output/summary_status.generated-log-08.json', expr='"analyzerVersion":.*"[0-9]') self.assertGrep('loganalyzer_output/summary_status.generated-log-08.json', literal=True, # check for ordering of key, and that the right things are present expr='{"statistic": "0% (start)", "local datetime": "2019-04-08 13:00:00.111", "epoch secs": 1554728400.111, "interval secs": 0.0, "line num": 1, ') self.assertGrep('loganalyzer_output/summary_status.generated-log-08.json', literal=True, # check it's represented as a float expr='"interval secs": 1.0') self.assertGrep('loganalyzer_output/summary_status.generated-log-08.json', expr='mynewstatus') self.assertGrep('loganalyzer_output/summary_status.generated-log-08.json', expr='somethingelse') with io.open(self.output+'/loganalyzer_output/summary_status.generated-log-08.json') as f: s = json.load(f)['status'] def findstat(statistic): for x in s: if x['statistic'] == statistic: return x assert False, 'Not found: %s'%statistic self.assertEval("{status0pc_linenum} == 1", status0pc_linenum=findstat('0% (start)')['line num']) self.assertEval("{status25pc_linenum} == 2", status25pc_linenum=findstat('25%')['line num']) self.assertEval("{status50pc_linenum} == 4", status50pc_linenum=findstat('50%')['line num']) self.assertEval("{status75pc_linenum} == 6", status75pc_linenum=findstat('75%')['line num']) self.assertEval("{status100pc_linenum} == 8", status100pc_linenum=findstat('100% (end)')['line num']) self.assertEval("{status0pc_rq} == 4", status0pc_rq=findstat('0% (start)')['rq=queued route']) self.assertEval("{status25pc_rq} == 4*10", status25pc_rq=findstat('25%')['rq=queued route']) self.assertEval("{status50pc_rq} == 4*1000", status50pc_rq=findstat('50%')['rq=queued route']) self.assertEval("{status75pc_rq} == 4*100000", status75pc_rq=findstat('75%')['rq=queued route']) self.assertEval("{status100pc_rq} == 4*10000000", status100pc_rq=findstat('100% (end)')['rq=queued route']) self.assertEval("{min_rq} == 4", min_rq=findstat('min')['rq=queued route']) self.assertEval("{max_rq} == 4*10000000", max_rq=findstat('max')['rq=queued route']) self.assertEval("{mean_rq} == {expected}", mean_rq=findstat('mean')['rq=queued route'], expected=math.trunc(sum([4*(10**n) for n in range(8)])/8.0)) self.assertEval("{min_swapping} == 0", min_swapping=findstat('min')['is swapping']) self.assertEval("{max_swapping} == 1", max_swapping=findstat('max')['is swapping']) self.assertEval("{mean_swapping} == 2/8.0", mean_swapping=findstat('mean')['is swapping']) self.assertEval("{min_mean_max_datetime} == ''", min_mean_max_datetime=findstat('min')['local datetime']+findstat('mean')['local datetime']+findstat('max')['local datetime']) # user-defined statuses self.assertEval("{min_mynewstatus} == 10", min_mynewstatus=findstat('min')['mynewstatus']) self.assertEval("{max_mynewstatus} == 100*1000*1000", max_mynewstatus=findstat('max')['mynewstatus']) self.assertEval("{mean_somethingelse} == 123", mean_somethingelse=findstat('mean')['somethingelse']) # special check for a key that is a floating point number and we special-case those self.assertEval("{min_pm} == 7", min_pm=findstat('min')['pm=resident MB']) self.assertEval("{max_pm} == 70*1000*1000", max_pm=findstat('max')['pm=resident MB']) self.assertEval("{mean_pm} == {expected}", mean_pm=findstat('mean')['pm=resident MB'], expected=sum([7*(10**n) for n in range(8)])/8.0) self.assertEval("{mean_pm_delta} == {expected}", mean_pm_delta=findstat('mean')['pm delta MB'], expected=math.trunc(sum([(70-7)*(10**(n-1)) for n in range(8)])/8.0)) # check CSV file has the annotated headinghs self.assertGrep('loganalyzer_output/status.generated-log-08.csv', expr=',rq=queued route,') # formatting of final JVM in CSV self.assertGrep('loganalyzer_output/status.generated-log-08.csv', expr='13:00:00,.*,7.00,') self.assertGrep('loganalyzer_output/summary_status.generated-log-08.csv', expr='13:00:00,.*,7.00,') self.assertGrep('loganalyzer_output/status.generated-log-08.csv', expr='13:00:07,.*"70,000,000"') self.assertGrep('loganalyzer_output/summary_status.generated-log-08.csv', expr='13:00:07,.*"70,000,000"') # sanity check that min<=mean<=max for k in findstat('min'): if isinstance(findstat('min')[k], str): continue if round(findstat('min')[k], 3) > round(findstat('mean')[k], 3): # allow a bit of rounding error self.addOutcome(FAILED, f"min ({findstat('min')[k]}) > mean ({findstat('mean')[k]}) for '{k}'") if findstat('mean')[k] > findstat('max')[k]: self.addOutcome(FAILED, f"mean ({findstat('mean')[k]}) > max ({findstat('max')[k]}) for '{k}'")
def get_level_percentage(level: float): # i wrote this months ago so idk but it's probably just math tho return round((level - math.trunc(level)) * 100, 2)
from math import trunc x = float(input('Digite um numero: ')) print('O numero {} tem a parte inteira {}'.format(x, trunc(x))) #print('O numero {} tem a parte inteira {:.0f}'.format(x, x//1))
def get_network_level(experience): # formula that i don't understand # thank you @littlemxantivirus return math.trunc(get_network_level_exact(experience))
def constrain_new_to_old(model_info, pars): """ Restrict parameter values to those that will match sasview. """ name = model_info.id # Note: update convert.revert_model to match if name in MODELS_WITHOUT_SCALE or model_info.structure_factor: pars['scale'] = 1 if name in MODELS_WITHOUT_BACKGROUND or model_info.structure_factor: pars['background'] = 0 # sasview multiplies background by structure factor if '*' in name: pars['background'] = 0 # Shut off magnetism when comparing non-magnetic sasview models if name not in MAGNETIC_SASVIEW_MODELS: suppress_magnetism = False for key in pars.keys(): if key.startswith("M0:"): suppress_magnetism = suppress_magnetism or (pars[key] != 0) pars[key] = 0 if suppress_magnetism: warnings.warn("suppressing magnetism for comparison with sasview") # Shut off theta polydispersity since algorithm has changed if 'theta_pd_n' in pars: if pars['theta_pd_n'] != 0: warnings.warn( "suppressing theta polydispersity for comparison with sasview") pars['theta_pd_n'] = 0 # If it is a product model P*S, then check the individual forms for special # cases. Note: despite the structure factor alone not having scale or # background, the product model does, so this is below the test for # models without scale or background. namelist = name.split('*') if '*' in name else [name] for name in namelist: if name in MODELS_WITHOUT_VOLFRACTION: pars['volfraction'] = 1 if name == 'core_multi_shell': pars['n'] = min(math.ceil(pars['n']), 4) elif name == 'gel_fit': pars['scale'] = 1 elif name == 'line': pars['scale'] = 1 pars['background'] = 0 elif name == 'mono_gauss_coil': pars['scale'] = 1 elif name == 'onion': pars['n_shells'] = math.ceil(pars['n_shells']) elif name == 'pearl_necklace': pars['string_thickness_pd_n'] = 0 pars['number_of_pearls_pd_n'] = 0 elif name == 'poly_gauss_coil': pars['scale'] = 1 elif name == 'rpa': pars['case_num'] = int(pars['case_num']) elif name == 'spherical_sld': pars['n_shells'] = math.ceil(pars['n_shells']) pars['n_steps'] = math.ceil(pars['n_steps']) for k in range(1, 11): pars['shape%d' % k] = math.trunc(pars['shape%d' % k] + 0.5) for k in range(2, 11): pars['thickness%d_pd_n' % k] = 0 pars['interface%d_pd_n' % k] = 0 elif name == 'teubner_strey': pars['scale'] = 1 if pars['volfraction_a'] > 0.5: pars['volfraction_a'] = 1.0 - pars['volfraction_a'] elif name == 'unified_power_Rg': pars['level'] = int(pars['level'])
from math import trunc #import math num = float(input('Digite um Valor: ')) print('O numero {}, tem a parte inteira {}'.format(num, trunc(num))) # print('O numero {}, tem a parte inteira {}'.format(num,math.trunc(num)))
def get_skywars_level(experience): return math.trunc(get_skywars_level_exact(experience))
def display_image(self, image_id, show_polys=True, show_bbox=True, show_labels=True, show_crowds=True, use_url=False): print('Image:') print('======') if image_id == 'random': image_id = random.choice(list(self.images.keys())) # Print the image info print(self.images) input("images") image = self.images[image_id] for key, val in image.items(): print(' {}: {}'.format(key, val)) # Open the image if use_url: image_path = image['coco_url'] response = requests.get(image_path) image = PILImage.open(BytesIO(response.content)) else: image_path = os.path.join(self.image_dir, image['file_name']) image = PILImage.open(image_path) buffered = BytesIO() image.save(buffered, format="PNG") img_str = "data:image/png;base64, " + base64.b64encode( buffered.getvalue()).decode() # Calculate the size and adjusted display size max_width = 900 image_width, image_height = image.size adjusted_width = min(image_width, max_width) adjusted_ratio = adjusted_width / image_width adjusted_height = adjusted_ratio * image_height # Create list of polygons to be drawn polygons = {} bbox_polygons = {} rle_regions = {} poly_colors = {} labels = {} print(' segmentations ({}):'.format(len( self.segmentations[image_id]))) for i, segm in enumerate(self.segmentations[image_id]): polygons_list = [] if segm['iscrowd'] != 0: # Gotta decode the RLE px = 0 x, y = 0, 0 rle_list = [] for j, counts in enumerate(segm['segmentation']['counts']): if j % 2 == 0: # Empty pixels px += counts else: # Need to draw on these pixels, since we are drawing in vector form, # we need to draw horizontal lines on the image x_start = trunc( trunc(px / image_height) * adjusted_ratio) y_start = trunc(px % image_height * adjusted_ratio) px += counts x_end = trunc( trunc(px / image_height) * adjusted_ratio) y_end = trunc(px % image_height * adjusted_ratio) if x_end == x_start: # This is only on one line rle_list.append({ 'x': x_start, 'y': y_start, 'width': 1, 'height': (y_end - y_start) }) if x_end > x_start: # This spans more than one line # Insert top line first rle_list.append({ 'x': x_start, 'y': y_start, 'width': 1, 'height': (image_height - y_start) }) # Insert middle lines if needed lines_spanned = x_end - x_start + 1 # total number of lines spanned full_lines_to_insert = lines_spanned - 2 if full_lines_to_insert > 0: full_lines_to_insert = trunc( full_lines_to_insert * adjusted_ratio) rle_list.append({ 'x': (x_start + 1), 'y': 0, 'width': full_lines_to_insert, 'height': image_height }) # Insert bottom line rle_list.append({ 'x': x_end, 'y': 0, 'width': 1, 'height': y_end }) if len(rle_list) > 0: rle_regions[segm['id']] = rle_list else: # Add the polygon segmentation for segmentation_points in segm['segmentation']: segmentation_points = np.multiply( segmentation_points, adjusted_ratio).astype(int) polygons_list.append( str(segmentation_points).lstrip('[').rstrip(']')) polygons[segm['id']] = polygons_list if i < len(self.colors): poly_colors[segm['id']] = self.colors[i] else: poly_colors[segm['id']] = 'white' bbox = segm['bbox'] bbox_points = [ bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3], bbox[0], bbox[1] + bbox[3], bbox[0], bbox[1] ] bbox_points = np.multiply(bbox_points, adjusted_ratio).astype(int) bbox_polygons[segm['id']] = str(bbox_points).lstrip('[').rstrip( ']') labels[segm['id']] = (self.categories[segm['category_id']]['name'], (bbox_points[0], bbox_points[1] - 4)) # Print details print(' {}:{}:{}'.format(segm['id'], poly_colors[segm['id']], self.categories[segm['category_id']])) # Draw segmentation polygons on image html = '<div class="container" style="position:relative;">' html += '<img src="{}" style="position:relative;top:0px;left:0px;width:{}px;">'.format( img_str, adjusted_width) html += '<div class="svgclass"><svg width="{}" height="{}">'.format( adjusted_width, adjusted_height) if show_polys: for seg_id, points_list in polygons.items(): fill_color = poly_colors[seg_id] stroke_color = poly_colors[seg_id] for points in points_list: html += '<polygon points="{}" style="fill:{}; stroke:{}; stroke-width:1; fill-opacity:0.5" />'.format( points, fill_color, stroke_color) if show_crowds: for seg_id, rect_list in rle_regions.items(): fill_color = poly_colors[seg_id] stroke_color = poly_colors[seg_id] for rect_def in rect_list: x, y = rect_def['x'], rect_def['y'] w, h = rect_def['width'], rect_def['height'] html += '<rect x="{}" y="{}" width="{}" height="{}" style="fill:{}; stroke:{}; stroke-width:1; fill-opacity:0.5; stroke-opacity:0.5" />'.format( x, y, w, h, fill_color, stroke_color) if show_bbox: for seg_id, points in bbox_polygons.items(): fill_color = poly_colors[seg_id] stroke_color = poly_colors[seg_id] html += '<polygon points="{}" style="fill:{}; stroke:{}; stroke-width:1; fill-opacity:0" />'.format( points, fill_color, stroke_color) if show_labels: for seg_id, label in labels.items(): color = poly_colors[seg_id] html += '<text x="{}" y="{}" style="fill:{}; font-size: 12pt;">{}</text>'.format( label[1][0], label[1][1], color, label[0]) html += '</svg></div>' html += '</div>' html += '<style>' html += '.svgclass { position:absolute; top:0px; left:0px;}' html += '</style>' return html
def get_guild_level(experience): return math.trunc(get_guild_level_exact(experience))
def get_bucket_number(hkey, shards_number): """Returns bucket (shard) number (int) for given hashed key (int).""" # We purposely do not use modulo (%) to keep global order across shards. # floor(key * shards_number / HKEYS_NUMBER), with HKEYS_NUMBER = 2**HKEY_SIZE. return math.trunc((hkey * shards_number)>>HKEY_SIZE)