def draw(self, screen): # draw roads for i in range(self.n_all): for j in range(i, self.n_all): if not self.nodes_distance[i, j] < float('inf'): continue pos_i = utils.lb2lt(tuple(self.nodes_position[i])) pos_j = utils.lb2lt(tuple(self.nodes_position[j])) color = utils.get_color() size = 2 if self.flags_main_road[i, j]: color = utils.get_color('RED') size = 3 draw.aaline(screen, color, pos_i, pos_j) # draw nodes for i in range(self.n_all): pos = utils.lb2lt(tuple(self.nodes_position[i])) if 'D' in self.i2c[i]: xdraw.filled_circle(screen, pos[0], pos[1], 8, utils.get_color('RED')) elif 'Z' in self.i2c[i]: xdraw.filled_circle(screen, pos[0], pos[1], 6, utils.get_color('BLUE')) elif 'J' in self.i2c[i]: xdraw.filled_circle(screen, pos[0], pos[1], 4, utils.get_color('BLACK')) elif 'F' in self.i2c[i]: xdraw.box(screen, (pos[0] - 4, pos[1] - 4, 8, 8), (139, 19, 69))
def install_dependency(self): unmet = self.dependency_set.get_unmet_list() if len(unmet)!=0: print utils.get_color("cyan") + "Installing : " + " ".join(unmet) + utils.reset_color() self.dependency_set.install_unmet() else: print utils.get_color("cyan") + "Nothing to install" + utils.reset_color()
def run_instance(self , o_str , instance, index): e_list = instance.outputStr.split("\n") if(e_list[0] == "?"): print "Showing output for " + instance.description print utils.get_color("yellow") if len(e_list)<=2 or e_list[2] != "false" : print "input : " print instance.inputStr print "output : " for i in range(int(e_list[1])): if index >= len(o_str): self.throw_eof(i , e_list[i],instance) print o_str[index] index = index + 1 print utils.reset_color() return index for i in range(len(e_list)): exp = e_list[i] if exp=="": continue if index >= len(o_str) : self.throw_eof(i , e_list[i],instance) if not instance.test(o_str[index] , exp): print utils.get_color("red") print instance.description + " failed at line#" + str(i) print "Expected : " + exp print "Got : " + o_str[index] print utils.reset_color() raise JarvisTestError("Mismatch") index = index + 1 return index
def warn_for_dependency(self): unmet = self.dependency_set.get_unmet_list() if len(unmet)!=0: print utils.get_color("red") + "The following dependencies for filter:'"+self.name+"' seem to be unmet. You better make sure these are installed before testing the project" + utils.reset_color() for dependency in unmet: print utils.get_color("yellow") + dependency + utils.reset_color() return False return True
def start_trigger(self,fd,trigger,arg): try: self.stdinFD = sys.stdin.fileno() sys.stdin = os.fdopen(fd) signal.signal(signal.SIGINT , self.child_handler) trigger(arg) except OSError: print utils.get_color("red") + "Trigger interrupted" + utils.reset_color()
def build(self , err=sys.stderr): self.warn_for_dependency() print utils.get_color("blue" , -1 , "b") + "Building Project...\n" + utils.reset_color() try: utils.run_script("scripts/" + self.buildfile , verbose = self.set_verbose , serr=err) except Exception as err: print err print utils.get_color("blue" , -1 , "b") + "Build Complete" + utils.reset_color()
def test(self): if "testCases" in sys.modules.keys(): del sys.modules["testCases"] self.tests = importlib.import_module("testCases").getTests() self.build() for i in range(len(self.tests)): print utils.get_color("blue") + "Running " + self.tests[i].description + utils.reset_color() self.examine(subprocess.check_output(["bash" , "scripts/testfile"] , stdin=open(self.tests[i].description.replace(" ","_"))) , self.tests[i]) print ""
def debug(self , iname=0 , oname=0): sin = self.get_file(iname , sys.stdin) sout= self.get_file(oname , sys.stdout , "w") print utils.get_color("blue" , -1 , "b") + "Debugging Project...\n" + utils.reset_color() try: utils.run_script("scripts/" + self.debugfile , True , sin , sout , verbose = self.set_verbose) except Exception as err: print err.args print utils.get_color("blue" , -1 , "b") + "Debug Complete\n" + utils.reset_color()
def run(self , iname=0 , oname=0 , err=sys.stderr): sin = self.get_file(iname , sys.stdin) sout= self.get_file(oname , sys.stdout , "w") print utils.get_color("blue" , -1 , "b") + "Running Project...\n" + utils.reset_color() try: utils.run_script("scripts/" + self.runfile , True , sin , sout , verbose = self.set_verbose , serr = err) except Exception as err: print err.args print utils.get_color("blue" , -1 , "b") + "Run Complete" + utils.reset_color()
def get_file(self , name , alter_stream , mode="r"): if(name!=0): try: sin=open(name , mode) except: print utils.get_color("red") + "Could not open " + name print "Using " + alter_stream.name + " instead" sin = alter_stream else: sin=alter_stream return sin
def deaths_area(deaths): threshold = 15 deaths_sorted = utils.sort_columns_on_row(deaths) deaths_upper = deaths_sorted[deaths_sorted.columns[0:threshold]] deaths_lower = deaths_sorted[deaths_sorted.columns[threshold:]].sum(axis=1) fig = go.Figure(layout=go.Layout( title=go.layout.Title(text=f'Total deaths due to COVID-19'), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font=dict(family="Lato, Helvetica", color="#333447"), yaxis=go.layout.YAxis( showgrid=True, gridwidth=1, gridcolor='rgb(220,220,220)', ), xaxis=go.layout.XAxis( showgrid=True, gridwidth=1, gridcolor='rgb(220,220,220)', nticks=5), legend_orientation="h", margin={ 'l': 0, 'r': 0, 'pad': 0 })) color, show = utils.get_color('Other', 1000, 1) fig.add_trace( go.Scatter( x=deaths_lower.index, y=deaths_lower.values, hoverinfo='none', hovertemplate='Total deaths: %{y}<br>Day: %{x}', mode='lines', name='Other', line=dict(width=0, color=color), stackgroup='one' # define stack group )) for i, column in enumerate(deaths_upper.columns): color, show = utils.get_color(column) fig.add_trace( go.Scatter( x=deaths_upper[column].index, y=deaths_upper[column].values, mode='lines', name=column, hoverinfo='none', hovertemplate='Total deaths: %{y}<br>Day: %{x}', line=dict(width=0, color=color), stackgroup='one' # define stack group )) return fig
def fill_board(loop_digest, digest_portion): if digest_portion == 4: # top left fill_square(0, height//2, width//2, width, get_color(str(loop_digest[0]))) # top right fill_square(0, height//2, 0, width//2, get_color(str(loop_digest[1]))) # bottom left fill_square(height//2, height, width//2, width, get_color(str(loop_digest[2]))) # bottom right fill_square(height//2, height, 0, width//2, get_color(str(loop_digest[3]))) if digest_portion == 1: fill_all(get_color(str(loop_digest[0])))
def create_input(self): for i in range(len(self.tests)): print utils.get_color("blue") + "Creating files for " + self.tests[i].description + utils.reset_color() inputStr = "" if self.tests[i].header!="": inputStr = inputStr + self.tests[i].header + "\n" if self.tests[i].print_count : inputStr= inputStr + str(len(self.tests[i].instances)) + "\n" for j in range( len( self.tests[i].instances ) ): inputStr = inputStr + self.tests[i].instances[j].getInput() + "\n" if self.tests[i].footer!="": inputStr = inputStr + self.tests[i].footer + "\n" f = open( self.tests[i].description.replace(" ","_") , "w+" ) f.write(inputStr) f.close() print utils.get_color("green") + "Files created" + utils.reset_color() + "\n"
def deaths_pie_chart(deaths): threshold = 10 deaths_sorted = utils.sort_columns_on_row(deaths) deaths_merged = deaths_sorted[deaths_sorted.columns[0:threshold]] deaths_merged['Other'] = deaths_sorted[ deaths_sorted.columns[threshold:]].sum(axis=1) deaths_merged = deaths_merged.iloc[-1].transpose() fig = go.Figure(layout=go.Layout( title=go.layout.Title(text=f'Distribution of deaths by country'), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font=dict(family="Lato, Helvetica", color="#333447"), legend_orientation="h", margin={ 'l': 0, 'r': 0, 'pad': 0 }), data=[ go.Pie(labels=deaths_merged.index, values=deaths_merged.values, hole=0.5, marker=dict(colors=[ utils.get_color(c)[0] for c in deaths_merged.index ])) ]) return fig
def get_hr_style_from_css(css): available_css_attrs = ('width', 'border-width', 'color', 'margin-top', 'margin-bottom', 'float', 'border-style') float_mapping = {'left': 'LEFT', 'right': 'RIGTH', 'none': 'CENTER'} attrs = {} for key, value in css.iteritems(): if key in available_css_attrs: if key == 'width': attrs['width'] = format_size(value) elif key == 'border-width': attrs['thickness'] = format_size(value) elif key == 'color': attrs['color'] = get_color(value) elif key == 'margin-top': attr_value = format_size(value) if attr_value is not None: attrs['spaceBefore'] = attr_value elif key == 'margin-bottom': attr_value = format_size(value) if attr_value is not None: attrs['spaceAfter'] = attr_value elif key == 'float': attrs['hAlign'] = float_mapping.get(value, 'CENTER') elif key == 'border-style': dash = None if value == 'solid': dash = None elif value == 'dashed': dash = [5, 5] elif value == 'dotted': dash = [2, 2] attrs['dash'] = dash return attrs
def annotate_and_save_per_class(annotations, d, image_file, model_name, precision_mode): base_image_file = image_file.replace('Results/seeds/annotations_trt', 'Data') img = Image.open(base_image_file) classes = train_model.get_classes() labels = load_labels(image_file) classes_image = [] for c in range(0,len(classes)): new_img = img.copy() draw = ImageDraw.Draw(new_img, mode='RGBA') for i in range(0,len(annotations)): color,predicted_class = utils.get_color_probs(annotations[i][0]) classes_image.append(predicted_class) if predicted_class==c: x,y = (annotations[i][1], annotations[i][2]) draw.rectangle((x-d/2, y-d/2, x+d/2, y+d/2), fill=color) for (c_name,x,y) in labels: solid_color = utils.get_color(classes.index(c_name),255) draw.ellipse((x-6, y-6, x+6, y+6), fill=solid_color) new_image_file = image_file.replace('.' + image_format, '_annotated_by_' + precision_mode + '_' + model_name + '_for_class_%s.jpg' % classes[c]) new_img.save(new_image_file) print("Saved %s" % new_image_file) return classes_image
def draw(self, draw_buffer): """ Called every cycle. About .1 seconds Parameters: draw_buffer The raw drawing array for the launchpad """ draw_buffer[self._draw_position] = get_color(self.red, self.green, flashing=True)
def fill_board(loop_digest, digest_portion): sq = int(math.sqrt(digest_portion)) for i in range(digest_portion): t_left = (i % sq) * width//sq t_right = ((i % sq) + 1) * width//sq b_left = (i//sq * height//sq) b_right = (i + sq)//sq * height//sq fill_square_standard_unicorn(t_left, t_right, b_left, b_right, \ get_color(str(loop_digest[i])))
def signature_file(request): image = Image.new(mode='RGB', size=(660, 125), color=get_color()) # image = Image.open(fp=r'image_path') image_draw = ImageDraw.Draw(image) image_font = ImageFont.truetype(font=str(settings.FONT_PATH), size=50) for k, v in request.META.items(): print(k, v) # print(request.M) ip = f'你的 IP:{request.META["REMOTE_ADDR"]}' browser = request.META["HTTP_USER_AGENT"] # user_name = f'你的電腦名稱: {request.META["USERNAME"]}' # image_draw.text(xy=(250, 0), text='hello', font=image_font, fill=get_color()) print(f'ip: {ip}') image_draw.text(xy=(100, 0), text=ip, font=image_font, fill=get_color()) # image_draw.text(xy=(100, 50), text=user_name, font=image_font, fill=get_color()) fp = BytesIO() image.save(fp=fp, format='png') return HttpResponse(fp.getvalue(), content_type='image/png')
def create_filtered_image(self): arrays = self.get_bands(self.mask.channels, shape=self.original_array.shape[:2]) types = self.mask.get_value(*tuple(arrays)) colors = get_color(types, self.colors) filtered_image_array = (self.original_array * 0.5 + colors * 0.5).astype('uint8') self.filtered_image = Image.fromarray(filtered_image_array, mode='RGB')
def draw_random(self, screen): if self.message == "paint random": temp_x = random.randint(10, self.width) temp_y = random.randint(75, self.height + 65) pos = (temp_x, temp_y) radius = random.randint(2, 10) self.list_of_circles.append([pos, utils.get_color(), radius]) elif self.message == "stop adding": pass self.paint(screen)
def _create_crafted_image(self, n): raster = self.rasters[n][:, ::-1] crafted_image_array = get_color(raster, self.colors) if n == 0: crafted_image_array = self.base_array else: mask = np.array([raster == 0] * 3).transpose([1, 2, 0]) crafted_image_array = crafted_image_array * ( 1 - mask) + self.base_array * mask self.crafted_image = Image.fromarray( crafted_image_array.astype('uint8').transpose(1, 0, 2))
def __run_drak__(self , filename): text_extract = self.__extract_text__(filename) if len(text_extract["immediate"]["suggestion"])!=0: print utils.get_color("blue") + "Immediately resolvable Issues detected" + utils.reset_color() for suggestion in text_extract["immediate"]["suggestion"]: print utils.get_color("yellow") + suggestion + utils.reset_color() if len(text_extract["web"]) + len(text_extract["immediate"]["keyword"])!=0: response = str(raw_input(utils.get_color("blue") + "Would you like to search online for better suggestions?[Y/N]" + utils.reset_color())).lower() if response == "y": app = DrakSuggestionFetcher() web_result = [] for keyword in text_extract["web"] + text_extract["immediate"]["keyword"]: web_result += app.get_suggestions(keyword, 10) ob = Inex() print utils.get_color("blue") + "Dr Drak Suggests : " + utils.reset_color() print utils.get_color("yellow") + ob.processInput(web_result , False) + utils.reset_color()
def child_handler(self , signum , frame): print utils.get_color("red") + "Keyboard interrrupt. Signal Number : " + str(signum) + utils.reset_color() print utils.get_color("white" , -1 , "b") + self.prompt + utils.reset_color() , print utils.get_color("red") + "Exiting worker thread" + utils.reset_color() sys.stdout.flush() sys.stdin = os.fdopen(self.stdinFD) os._exit(0)
def get_code(request): # 初始化畫布 image = Image.new(mode='RGB', size=(200, 100), color=get_color()) # 初始化畫筆 image_draw = ImageDraw.Draw(image, mode='RGB') # 字形 + 字體大小 image_font = ImageFont.truetype(font=str(settings.FONT_PATH), size=50, encoding="unic") # 取得驗證碼 verify_code = get_verify_code() # 存 session request.session['verify_code'] = verify_code # 畫字 image_draw.text(xy=(10, 25), text=verify_code, font=image_font, fill=get_color()) # 畫點 混淆 for i in range(2500): image_draw.point(xy=(random.randrange(220), random.randrange(100)), fill=get_color()) # 畫線 # image_draw.line(xy=((100, 50), (50, 0)), fill=get_color(), width=7) fp = BytesIO() image.save(fp=fp, format='png') return HttpResponse(fp.getvalue(), content_type='image/png')
def __getattr__(self, attribute): """ Get an attribute. This function is used to get the "stroke" attribute; if the attribute being requested isn't "stroke" None will be returned. @type attribute: string @param attribute: The name of the requested attribute. @rtype: string or None @return: The attribute's value or None. """ if attribute == "stroke": return get_color(self, SVGElement, "stroke", "stroke-opacity") else: return False
def __getattr__(self, attribute): """ Get an attribute. See L{SVGElement.__getattr__} for more information, as this function passes on unresolved attributes to it. @type attribute: string @param attribute: The attribute being requested. @rtype: string @return: The requested attribute. """ if attribute == "color": color = get_color(self, SVGElement, "stop-color", "stop-opacity") if color: return color return SVGElement.__getattr__(self, attribute)
def build(self): self.build_filters() self.create_input() print utils.get_color("blue") + "Creating test scripts" + utils.reset_color() string = "(" fptr = open("scripts/" + self.project.runfile) scripts = fptr.read().splitlines() fptr.close() for script in scripts: string = string + script + ";" string = string + ")" for fltr in self.filter_list: string = string + " | " + fltr.run_script fptr = open("scripts/testfile" , "w") fptr.write(string) fptr.close() print utils.get_color("green") + "Test scripts created" + utils.reset_color() + "\n"
def top_deaths_per_time(deaths, interval=7): threshold = 20 df_diff = utils.sort_columns_on_row(deaths).diff().iloc[1:] df_buckets = utils.bucket_values(df_diff, interval=interval, limit=threshold) deaths_sorted = utils.sort_columns_on_row(df_buckets) deaths_merged = deaths_sorted[deaths_sorted.columns[0:threshold]] deaths_merged['Other'] = deaths_sorted[ deaths_sorted.columns[threshold:]].sum(axis=1) deaths_merged = deaths_merged.iloc[-1].sort_values(ascending=False) fig = go.Figure(layout=go.Layout(title=go.layout.Title( text=f'Number of deaths by country - Last {interval} day(s)'), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font=dict(family="Lato, Helvetica", color="#333447"), legend_orientation="v", xaxis=go.layout.XAxis( showgrid=False, automargin=True, gridwidth=1, gridcolor='rgb(220,220,220)', ), yaxis=go.layout.YAxis( showgrid=True, automargin=True, gridwidth=1, gridcolor='rgb(220,220,220)', tickformat=',.0', side='right', range=[0, deaths_merged.max()]), margin={ 'l': 0, 'r': 0, 'pad': 0 }), ) text = zip( deaths_merged.values, [x for x in round(deaths_merged / deaths_merged.sum() * 1000) / 10], ) fig.add_trace( go.Bar(x=deaths_merged.index, y=deaths_merged, text=[f"{x[0]:.0f} ({str(x[1])}%)" for x in text], textposition='auto', marker=dict( color=[utils.get_color(c)[0] for c in deaths_merged.index]), orientation='v')) return fig
def run(self): self.add_files() readline.parse_and_bind("tab: complete") readline.set_completer(self.complete_type) cmd = str(raw_input(utils.get_color("white" , -1 , "b") + self.prompt + utils.reset_color())) cmd = cmd.split() if len(cmd)==0 : return try: if cmd[0] in self.trigger_list: if self.is_child_trigger[cmd[0]]: proc = multiprocessing.Process(name='worker:'+cmd[0], target=self.start_trigger,args=(self.stdinFD,self.triggers[cmd[0]],cmd[1:len(cmd)],)) proc.start() proc.join() else: self.triggers[cmd[0]](cmd[1:len(cmd)]) else: os.system(" ".join(cmd)) except SystemExit : sys.exit(0) except Exception: print utils.get_color("red") + "Error executing trigger" + utils.reset_color() traceback.print_exc(file=sys.stdout)
def warn_for_dependency(self): unmet = self.dependency_set.get_unmet_list() if len(unmet)!=0: print utils.get_color("red") + "The following dependencies seem to be unmet. You better make sure these are installed before building the project" + utils.reset_color() for dependency in unmet: print utils.get_color("yellow") + dependency + utils.reset_color() print utils.get_color("blue") + "Or you could simply use install_dependency command otherwise" + utils.reset_color() return False return True
def examine(self , o_str , test): print utils.get_color("blue") + "Examining Output" + utils.reset_color() o_list = o_str.split("\n") index = 0 try: for instance in test.instances: index = self.run_instance(o_list , instance , index) print utils.get_color("green") + test.description + " passed" + utils.reset_color() except JarvisTestError as err: print utils.get_color("red") + test.description + " falied due to : " , print err.msg + utils.reset_color()
def heal(): msg = request.form['text'] username = request.form['user_name'] user_id = request.form['user_id'] commands = msg.split(' ') target = commands[0].replace('@', '') amount = ' '.join(commands[1:]) character = get_character(target) contents = character.get_contents() contents['user_id'] = user_id hp = int(contents.get('hp', 0)) max_hp = int(contents.get('max_hp', 0)) titles, evaluated, results, score = parse_dice(amount) log.info(titles) log.info(evaluated) log.info(results) log.info(score) hp += sum(results) hp = min(hp, max_hp) contents['hp'] = hp set_and_commit(character, contents) fields = [] for i in range(len(titles)): if len(evaluated[i]) == 0: continue str_eval = map(str, evaluated[i]) field = { 'title': 'Rolls ({})'.format(titles[i]), 'value': ' '.join(str_eval), 'short': True } fields.append(field) field = {'title': 'Result', 'value': str(results[i]), 'short': True} fields.append(field) fields.append({ 'title': f'{target}\'s Current HP', 'value': f'{hp}/{max_hp}' }) return make_response(fields, f'{username} healed {target}({amount})', color=get_color(hp / max_hp))
async def prefix(self, ctx): """Show the current prefix.""" if ctx.guild is not None: prefix = await ctx.pool.fetchval( """ SELECT prefix FROM meta.guilds WHERE id = $1; """, ctx.guild.id) else: prefix = None embed = discord.Embed(title='Prefix', color=get_color(ctx)) if prefix is not None: embed.description = prefix embed.set_footer(text='(Mention not included)') else: embed.description = ctx.me.mention await ctx.send(embed=embed)
def confirmed_cases_over_threshold(confirmed): limit = 25 confirmed = confirmed.assign(EU=confirmed[[ 'Austria', 'Belgium', 'Bulgaria', 'Croatia', 'Cyprus', 'Czechia', 'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland', 'Italy', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', 'Romania', 'Slovakia', 'Slovenia', 'Spain', 'Sweden' ]].sum(axis=1)) confirmed_over_threshold = utils.sort_columns_on_row( confirmed).iloc[:, :limit] fig = go.Figure( layout=go.Layout(title=go.layout.Title( text=f'Positive cases of COVID-19 - Top {limit} countries'), paper_bgcolor=paper_bgcolor, plot_bgcolor=plot_bgcolor, font=dict(family="Lato, Helvetica", color="#333447"), yaxis=go.layout.YAxis(showgrid=True, automargin=True, gridwidth=1, nticks=5, gridcolor='rgb(220,220,220)'), xaxis=go.layout.XAxis( showgrid=True, automargin=True, gridwidth=1, gridcolor='rgb(220,220,220)', nticks=5, ), margin={ 'l': 0, 'r': 0, 'pad': 0 })) for i, column in enumerate(confirmed_over_threshold): color, show = utils.get_color(column, i, 8) fig.add_trace( go.Scatter(x=confirmed_over_threshold[column].index, y=confirmed_over_threshold[column].values, name=column, hoverinfo='none', hovertemplate='Positive cases: %{y}<br>Date: %{x}', marker_color=color, line=dict(width=1.5, dash='solid' if show else 'dot'))) return fig
def __init__(self): pygame.sprite.Sprite.__init__(self) self.cor = get_color() self.width,self.height = (40,40) self.x,self.y,self.dir = get_pos() self.imageMaster = pygame.Surface((self.width,self.height)) self.imageMaster.fill(self.cor) self.imageMaster.set_colorkey((255,255,255)) self.image = self.imageMaster pygame.draw.rect(self.image, self.cor, (self.x,self.y,self.width,self.height)) self.rect = self.image.get_rect() self.rect.x = self.x self.rect.y = self.y self.speed = random.randrange(1,10) self.dx = 0 self.dy = 0 self.colide = False
def daily_change(df, interval=1): limit = 10 df_diff = utils.sort_columns_on_row(df).diff().iloc[1:] df_buckets = utils.bucket_values(df_diff, limit=limit, interval=interval) fig = go.Figure( layout=go.Layout(title=go.layout.Title( text=f'Sum of new deaths every {interval} day due to COVID-19'), paper_bgcolor=paper_bgcolor, plot_bgcolor=plot_bgcolor, font=dict(family="Lato, Helvetica", color="#333447"), yaxis=go.layout.YAxis(showgrid=True, automargin=True, gridwidth=1, gridcolor='rgb(220,220,220)', nticks=5), xaxis=go.layout.XAxis( showgrid=False, automargin=True, gridwidth=1, gridcolor='rgb(220,220,220)', nticks=5, ), margin={ 'l': 0, 'r': 0, 'pad': 0 }, barmode='stack')) for i, column in enumerate(df_buckets): hovertemplate = 'New deaths: %{y}<br>Date: %{x}' if (interval > 1): hovertemplate = 'New deaths: %{y}<br>Date: %{x}+' + str(interval - 1) color, show = utils.get_color(column) fig.add_trace( go.Bar( x=df_buckets[column].index, y=df_buckets[column].values, name=column, hoverinfo='none', hovertemplate=hovertemplate, marker_color=color, )) return fig
def add_module(arg): fptr = open(os.getcwd() + "/project.json") j = json.load(fptr) tp = str(j["type"]) name= str(j["name"]) fptr.close() f=open(os.getenv("HOME")+"/Documents/jarvis/config.json") j=json.load(f) workspace = str(j["workspace"]) author = str(j["author"]) f.close() project_folder = os.getenv("HOME") + "/" + workspace + "/" + tp + "/" + name type_folder = os.getenv("HOME")+"/Documents/jarvis/templates/" + tp module_name = str(raw_input(utils.get_color("blue") + "Enter Module Name : " + utils.reset_color())) module_name = module_name.replace(" ","_") files = os.listdir(type_folder) ls = os.listdir(os.getcwd()) for fname in files: if fname.startswith("module"): fname = fname.replace("module",module_name) if fname in ls: print utils.get_color("red") + "Cannot add "+module_name+" : file " + fname + " already exists" + utils.reset_color() return cmt = str(raw_input(utils.get_color("blue") + "Comments : " + utils.reset_color())) for fname in files: if fname.startswith("module"): fptr = open(type_folder + "/" + fname) content = fptr.read() fptr.close() fname = fname.replace("module",module_name) print utils.get_color("blue") + "Creating " + fname + utils.reset_color() fptr = open(project_folder + "/" + fname , "w") fptr.write(utils.sanitise(content,{"name":name , "comments":cmt , "author":author,"module":module_name})) fptr.close() print utils.get_color("green") + "Module Added" + utils.reset_color()
def current_distribution(deaths): threshold = 15 deaths_sorted = utils.sort_columns_on_row(deaths) deaths_merged = deaths_sorted[deaths_sorted.columns[0:threshold]] deaths_merged['Other'] = deaths_sorted[ deaths_sorted.columns[threshold:]].sum(axis=1) deaths_merged = deaths_merged.iloc[-1].sort_values() fig = go.Figure(layout=go.Layout( title=go.layout.Title(text=f'Distribution of deaths by country'), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font=dict(family="Lato, Helvetica", color="#333447"), legend_orientation="h", yaxis=go.layout.YAxis(showgrid=False, automargin=True, gridwidth=1, gridcolor='rgb(220,220,220)', side='right'), xaxis=go.layout.XAxis( showgrid=True, automargin=True, gridwidth=1, gridcolor='rgb(220,220,220)', tickformat=',.0%', range=[0, deaths_merged.max() / deaths_merged.sum()]), margin={ 'l': 0, 'r': 0, 'pad': 0 }), ) fig.add_trace( go.Bar(y=deaths_merged.index, x=deaths_merged / deaths_merged.sum(), text=[ str(x) + '%' for x in round(deaths_merged / deaths_merged.sum() * 1000) / 10 ], textposition='auto', marker=dict( color=[utils.get_color(c)[0] for c in deaths_merged.index]), orientation='h')) return fig
def update(arg): os.system("mkdir -p .jarvis_update_repo") os.chdir(".jarvis_update_repo") print utils.get_color("blue") + "Cloning Repository in current directory" + utils.reset_color() os.system("git clone https://github.com/anant-pushkar/jarvis2.git") print utils.get_color("blue") + "Installing updates" + utils.reset_color() os.chdir("jarvis2") os.system("bash update.sh") print utils.get_color("blue") + "Cleaning Repository" + utils.reset_color() os.chdir("../..") os.system("rm -r .jarvis_update_repo")
def redraw(self, _ev=None): if self.polygon_or_mask_state == 'normal': img = self.map_image.filtered_image elif self.polygon_or_mask_state == 'polygon': img = self.canvas_image.crafted_image else: # self.polygon_or_mask_state == 'mask' map_mask = self.map_image.get_bands( ['_map_mask_'], shape=self.map_image.original_array.shape[:2])[0] map_mask = np.array(map_mask > self.mask_threshold_slider.get(), dtype=int) colors = get_color(map_mask, self.colors) filtered_image_array = (self.map_image.original_array * 0.5 + colors * 0.5).astype('uint8') img = Image.fromarray(filtered_image_array, mode='RGB') if img is not None: self.canvas_image.patch_image(img) else: self.on_shift(None)
def pair_plot(dataset, mask, sizex, sizey): first_feature = dataset.features[0] _, ax = plt.subplots(sizex, sizey) ax_index = 0 for i in range(len(first_feature)): if i in mask and float_try_parse(first_feature[i]): for j in range(len(first_feature)): if j in mask and float_try_parse(first_feature[j]): yval = [] xval = [] colors = [] for f in dataset.features: if float_try_parse(f[i]) and float_try_parse(f[j]): yval.append(float(f[i])) xval.append(float(f[j])) colors.append(get_color(f[0])) ax_tindex = (ax_index // sizex, ax_index % sizey) ax[ax_tindex].scatter(xval, yval, color=colors) ax_index += 1 plt.show()
def hough_method(image_path, isInvert, vis=False): image = utils.cv_imread(image_path) if isInvert: image = cv.flip(image, -1) w, h, c = image.shape circles = utils.get_hough_circle(image) circles = utils.get_bottom_valid_circles(circles[0]) all_rate = [] k = 'bottom' # bottom only white glue location_coord = get_location_coord(circles, k, w, h) quad = utils.bottom_cross_points2quad(location_coord) for idx_quad, _quad in enumerate(quad): line = [[_quad[i], _quad[i + 1]] for i in range(0, len(_quad), 2)] line = np.array([line]).astype(np.int64) crop_res = utils.crop_rectangle(image, line) crop_gray = cv.cvtColor(crop_res, cv.COLOR_BGR2GRAY) crop_w, crop_h = crop_gray.shape crop_bin = cv.inRange(crop_gray, param_bottom.segment[k]['minVal'], param_bottom.segment[k]['maxVal']) rate = np.sum(crop_bin) / 255 / (crop_w * crop_h) all_rate.append(rate) if vis: for idx_quad, _quad in enumerate(quad): line = [[_quad[i], _quad[i + 1]] for i in range(0, len(_quad), 2)] line = np.array([line]).astype(np.int64) cv.polylines(image, line, 1, utils.get_color(), thickness=5) cv.namedWindow('vis', 0) cv.imshow('vis', image) cv.waitKey() return all_rate
def dice(): msg = request.form['text'] username = request.form['user_name'] user_id = request.form['user_id'] commands = msg.split(' ') log.debug(commands) character = get_character(username) contents = character.get_contents() contents['user_id'] = user_id if 'user_id' not in contents: name = character.name else: name = f'<@{contents["user_id"]}|{character.name}>' try: titles, evaluated, results, score = parse_dice(msg) except: return process_unknown(username) color = get_color(score) roll_title = ' / '.join(titles) title = f'{name} rolled {roll_title}' fields = [] for i in range(len(titles)): if len(evaluated[i]) == 0: continue str_eval = map(str, evaluated[i]) field = { 'title': 'Rolls ({})'.format(titles[i]), 'value': ' '.join(str_eval), 'short': True } fields.append(field) field = {'title': 'Result', 'value': str(results[i]), 'short': True} fields.append(field) return make_response(fields, title, color=color)
def build_frame_style(context, style_css, inline_attributes=freeze({})): frame_attr = {} border = {} keys = style_css.keys() keys.sort() # revert keys to avoid css inheritance for key in keys: value = style_css[key] if key.startswith('border'): border.update(p_border_style(key, value)) if key in ('height', 'width'): frame_attr[key] = value elif key.startswith('padding'): frame_attr.update(frame_padding_style(key, value)) elif key.startswith('margin'): frame_attr.update(body_margin_style(key, value)) if border: sb = ShowBoundaryValue(get_color(border.get('borderColor', 'black')), border.get('borderWidth', 1)) frame_attr['showBoundary'] = sb return frame_attr
async def stats(self, ctx): """List bot-wide statistics.""" records = await self.bot.pool.fetch(""" SELECT command, count(*) FROM statistics.commands GROUP BY command ORDER BY count DESC; """) member_count = sum(guild.member_count for guild in self.bot.guilds) command_count = sum(record['count'] for record in records) embed = discord.Embed(title='Statistics', color=get_color(ctx)) embed.add_field(name='General', value='\n'.join([ f'Servers: **{len(self.bot.guilds)}**', f'Members: **{member_count}**', f'Commands Used: **{command_count}**' ])) embed.add_field( name='Top Commands', value='\n'.join( f"{i}. **{record['command']}** ({record['count']} uses)" for i, record in enumerate(records[:5], 1))) await ctx.send(embed=embed)
def countries_deaths_over_threshold(deaths): limit = 25 confirmed_over_threshold = utils.sort_columns_on_row( deaths).iloc[:, :limit] fig = go.Figure( layout=go.Layout(title=go.layout.Title( text=f'Deaths due to COVID-19 - Top {limit} countries'), paper_bgcolor=paper_bgcolor, plot_bgcolor=plot_bgcolor, font=dict(family="Lato, Helvetica", color="#333447"), yaxis=go.layout.YAxis(showgrid=True, automargin=True, gridwidth=1, gridcolor='rgb(220,220,220)'), xaxis=go.layout.XAxis(showgrid=True, automargin=True, gridwidth=1, gridcolor='rgb(220,220,220)', nticks=5), margin={ 'l': 0, 'r': 0, 'pad': 0 })) for i, column in enumerate(confirmed_over_threshold): color, show = utils.get_color(column, i, 8) fig.add_trace( go.Scatter(x=confirmed_over_threshold[column].index, y=confirmed_over_threshold[column].values, name=column, hoverinfo='none', hovertemplate='Total deaths: %{y}<br>Date: %{x}', marker_color=color, line=dict(width=1.5, dash='solid' if show else 'dot'))) return fig
def create_student_identification_table(student=None): ''' CREATE student_identification numbers table correspond to specific task on identifying numbers corresponds to crabs + jellyfish ### Methods FROM records WHERE dataset='numbers' and game matchs [crabs, jellyfish] GROUP BY student, subject, subject FILTER timespent != -1 CREATE timespents [timespent, timespent, ...] CREATE games unique[game, game, ...] CREATE tags unique [tag, tag, ...] SUM score, nb_records CALCULATE %CA, color(%CA) OUT student_identification ### Output ```json { "_id" : ObjectId("5df40a5898f28e7c4f6729ca"), "games" : [ "ants", "crabs", "jellyfish" ], "classroom": 30, "score" : 2589, "nb_records" : 2809, "student" : 3051, "subject" : "numbers", "dataset" : "numbers", "timespent" : 886.749968, "%CA" : 92.17, "color" : "green" } ``` ''' pipeline = [ { "$match": { "subject": "numbers", "game": {"$in": ["crabs", "jellyfish"]}, # "group": {"$ne": "guest"} } }, { "$group": { "_id": { "student":"$student", "subject": "$subject", "dataset": "$dataset", "classroom": "$classroom" }, "timespent": { "$push": { "$cond":[ {"$gt":["$elapsedTime", 0]}, "$elapsedTime", None ] } }, "games": {"$addToSet": "$game"}, # "tags": {"$addToSet": "$value"}, "score": {"$sum": "$score"}, "nb_records": {"$sum": 1}, } }, { "$project": { "_id": 0, "games": "$games", "score": "$score", # "tags": "$tags", "nb_records": "$nb_records", "student": "$_id.student", "classroom": "$_id.classroom", "subject": "$_id.subject", "dataset": "$_id.dataset", "timespent": {"$sum": "$timespent"}, "%CA": {"$round":[{"$multiply": [{"$divide": ["$score", "$nb_records"]}, 100]}, 2]} } }, { "$out": "student_identification" } ] if student is not None: pipeline[0] = { "$match": { "subject": "numbers", "game": {"$in": ["crabs", "jellyfish"]}, "student": int(student) # "group": {"$ne": "guest"} } } pipeline[-1] = {"$merge": "student_identification"} db = connect() if student is None: db.student_identification.drop() db.records.aggregate(pipeline, allowDiskUse=True) if student is None: for n in db.student_identification.find({}, {"_id":1, "%CA":1}): color = get_color(n["%CA"]) db.student_identification.update({"_id": n["_id"]}, {"$set": {"color": color}}) else: for n in db.student_identification.find({"student":int(student)}, {"_id":1, "%CA":1}): color = get_color(n["%CA"]) db.student_identification.update({"_id": n["_id"]}, {"$set": {"color": color}})
def run_loopback(x, t, dac, adc, display=False, debug_plot=False, main_channel=0): N = x.shape[0] x_st_int = (x * (1 << 24)).astype(numpy.int32) time_start = datetime.now() adc.start_recording(SLOT_ADC) # 4/4/2018 debug """ for i in range(10): adc.fifo_status(display=True) adc.stop_recording(SLOT_ADC) pdb.set_trace() """ samples_written = 0 samples_read = 0 do_record = True start_flag = False chunk_size = (1 << 13) rec_data = [] #print adc.get_dirchan() #print 'N = %d, sample shape = %s' % (N, x_st_int.shape) # TODO: Make this loop until DAC has read all of the samples we wrote. while samples_written < N: chunk = x_st_int[samples_written:samples_written + chunk_size] this_chunk_size = chunk.shape[0] """ dac.audio_write(SLOT_DAC, chunk.flatten()) samples_written += this_chunk_size if display: print 'Wrote %d samples' % samples_written if do_record: data = adc.audio_read(SLOT_ADC, chunk_size * NUM_CHANNELS_ADC, timeout=100) rec_data.append(data) samples_read += data.shape[0] if display: print 'samples_read = %d' % samples_read """ #""" # 11/18 - NO REALLY, YOU GET DROPOUTS IF YOU DON'T DO THIS # Delay first read so that we don't get a buffer underrun if start_flag: samples_to_read = chunk_size * NUM_CHANNELS_ADC else: samples_to_read = 0 # (self, slot_dac, slot_adc, data, timeout=100): data_read = adc.audio_read_write(SLOT_DAC, SLOT_ADC, chunk.flatten(), samples_to_read, timeout=1000) rec_data.append(data_read) # print 'Data size = %s' % data_read.shape samples_read += data_read.shape[0] samples_written += chunk.shape[0] if display: print 'samples_read = %d, samples_written = %d' % (samples_read, samples_written) if start_flag == False: start_flag = True #""" # Wait for DAC to flush its buffer time.sleep(chunk_size / F_s) adc.stop_recording(SLOT_ADC) # Get FIFO status and then retrieve any lingering samples status = adc.fifo_status(display=display) leftover_samples = status[4 + SLOT_ADC][0] - status[4 + SLOT_ADC][1] leftover_samples -= (leftover_samples % 2) if display: print 'Retrieving %d leftover samples' % leftover_samples rec_data.append( adc.audio_read(SLOT_ADC, leftover_samples, perform_update=True, timeout=1000)) time_elapsed = datetime.now() - time_start time_float = time_elapsed.seconds + 1e-6 * time_elapsed.microseconds # TODO: Save file data = numpy.concatenate(rec_data) Ns_trunc = data.shape[0] & 0xFFFFFFF8 data = data[:Ns_trunc] N = data.shape[0] / NUM_CHANNELS_ADC data = data.reshape((N, NUM_CHANNELS_ADC)) data[data > (1 << 23)] -= (1 << 24) data_float = data.astype(float) / (1 << 24) rms_level = 20 * numpy.log10(numpy.mean(data_float**2)**0.5) #scipy.io.wavfile.write(filename, F_s, data) #print 'Saved %d samples (%.3f sec) to %s. RMS level = %.2f dBFS' % (N, N / F_s, filename, rms_level) if display: print 'Runtime: %.3f sec to collect %.3f sec audio' % (time_float, N / F_s) # Do FFT of largest 2^N sized segment start_ind = 1 << 12 # 11/24/2017: Set to avoid any lag issues in sweeps m_fft = int(numpy.floor(numpy.log2(data.shape[0] - start_ind))) N_fft = 2**m_fft x1 = data[start_ind:start_ind + N_fft].astype(float) / (1 << 24) if display: print 'FFT size: %d' % N_fft t = numpy.linspace(-numpy.pi, numpy.pi, N_fft) t = numpy.expand_dims(t, 1).repeat(data.shape[1], axis=1) w = 0.5 * (1 + numpy.cos(t)) # Try not windowing. 11/21/2017 #X = scipy.fftpack.fft(x1, axis=0) X = scipy.fftpack.fft(x1 * w, axis=0) freq = numpy.linspace(0, F_s / 2, N_fft / 2 + 1) # Note: scaling for pos-only freq, and for +/- 0.5 (rather than 1.0) range ampl = numpy.abs(X[:(N_fft / 2 + 1)] / N_fft * 8) ampl_db = 20 * numpy.log10(ampl) if display: print 'Hz/bin: %f' % (44100. / N_fft) if display: print 'Noise floor RMS in dBFS' if display: print 20 * numpy.log10( numpy.sum(ampl[10:(N_fft / 2), :]**2, axis=0)**0.5) # Compute mask for SNDR calc. # Restrict noise bandwidth for SNDR to 20--20k Hz (in particular noise floor tends to go up at LF) sndr_dc_cutoff = int(20 * (N_fft / F_s)) sndr_hf_cutoff = int(20000 * (N_fft / F_s)) #sndr_hf_cutoff = N_fft / 2 # 11/24/2017: Don't limit BW for 96k tests sndr_mask = numpy.ones((N_fft / 2 + 1, )) sndr_mask[:sndr_dc_cutoff] = 0 sndr_mask[sndr_hf_cutoff:] = 0 freq_ind = numpy.argmax(ampl_db[sndr_dc_cutoff:sndr_hf_cutoff, main_channel]) + sndr_dc_cutoff sndr_masked_width = 15 sndr_sig_start = max(0, freq_ind - sndr_masked_width) sndr_sig_end = min(N_fft / 2 + 1, freq_ind + sndr_masked_width) sndr_mask[sndr_sig_start:sndr_sig_end] = 0 results_by_channel = {} # THD/SNR/SNDR analysis for channel in range(NUM_CHANNELS_ADC): try: ampl_rms = numpy.mean(x1[:, channel]**2)**0.5 if display: print '-- THD analysis for channel %d' % channel ampl_db_peak = numpy.max(ampl_db[:, channel]) freq_ind = numpy.argmax(ampl_db[:, channel]) if display: print 'THD: carrier (%.2f kHz) is %.2f dB, ind %d' % ( freq[freq_ind] / 1e3, ampl_db_peak, freq_ind) sum_of_squares = 0 sos_ho = 0 thd_rel_ampl = [] base_freq_ind = freq_ind harm_ind = 1 peak_search_dist = 5 while harm_ind < 10 and freq_ind < N_fft / 2: harm_ind += 1 freq_ind = harm_ind * base_freq_ind if freq_ind > N_fft / 2: break freq_ind += ( numpy.argmax(ampl_db[freq_ind - peak_search_dist:freq_ind + peak_search_dist, channel]) - peak_search_dist) ampl_thd = ampl_db[freq_ind, channel] ampl_rel = ampl_thd - ampl_db_peak if display: print 'THD: harmonic %d (%.2f kHz) is %.2f dB, ind %d - %.2f dB abs.' % ( harm_ind, freq[freq_ind] / 1e3, ampl_rel, freq_ind, ampl_thd) thd_rel_ampl.append(ampl_rel) sum_of_squares += (10**(ampl_rel / 10.)) if harm_ind > 3: sos_ho += (10**(ampl_rel / 10.)) hd_total = 10 * numpy.log10(sum_of_squares) hd_ho = 10 * numpy.log10(sos_ho) if display: print ' -> THD for channel %d is %.2f dB via sum of squares (%.2f dB high order)' % ( channel, hd_total, hd_ho) ampl_masked = ampl[:, channel] * sndr_mask rms_masked = numpy.sum(ampl_masked**2)**0.5 sndr_db = ampl_db_peak - 20 * numpy.log10(rms_masked) if display: print '-- SNDR for channel %d = %.2f dB' % (channel, sndr_db) results_by_channel[channel] = { 'ampl_rms': 20 * numpy.log10(ampl_rms * (2**1.5)), 'carrier_freq': freq[base_freq_ind], 'carrier_ampl': ampl_db_peak, 'total_hd_rel_ampl': hd_total, 'other_hd_rel_ampl': hd_ho, 'sndr': sndr_db, } if len(thd_rel_ampl) > 0: results_by_channel[channel]['hd2_rel_ampl'] = thd_rel_ampl[0] if len(thd_rel_ampl) > 1: results_by_channel[channel]['hd3_rel_ampl'] = thd_rel_ampl[1] except IndexError as e: raise except Exception as e: # Eh, whatever. if display: print 'Error processing THD/SNDR for channel %d: %s' % ( channel, str(e)) pass if debug_plot: # t_plot = numpy.linspace(0, x1.shape[0] / F_s, x1.shape[0]) t_plot = numpy.arange(x1.shape[0]) #""" pyplot.figure(figsize=(16, 12)) pyplot.hold(True) for i in range(data.shape[1]): pyplot.plot(t_plot, x1[:, i]) pyplot.xlabel('Time (samples)') pyplot.ylabel('Amplitude (a. u.)') pyplot.title('Waveform captured from DAC/ADC loopback') pyplot.grid(True) #""" pyplot.figure(figsize=(16, 12)) pyplot.hold(True) # temp debug pyplot.plot(freq, (sndr_mask - 1) * 150, 'k-') for i in range(data.shape[1]): pyplot.plot(freq, ampl_db[:, i], color=get_color(NUM_CHANNELS_ADC, i)) pyplot.xlabel('Frequency (Hz)') pyplot.ylabel('Amplitude (dBFS)') pyplot.title('Spectrum captured from DAC/ADC loopback') pyplot.xlim([0, 20500]) pyplot.xticks(numpy.arange(0, 21000, 1000)) #pyplot.xlim([0, 40000]) #pyplot.ylim([-150, -100]) pyplot.ylim([-170, 10]) pyplot.yticks(numpy.arange(-170, 20, 10)) pyplot.grid(True) labels = ['Ch %d' % i for i in range(1, NUM_CHANNELS_ADC + 1)] pyplot.legend(labels, loc='upper right') print 'Plotting; results = %s' % results_by_channel pyplot.show() return results_by_channel
def hp(): print(request.form) msg = request.form['text'] username = request.form['user_name'] user_id = request.form['user_id'] commands = msg.split(' ') log.debug(commands) character = get_character(username) contents = character.get_contents() contents['user_id'] = user_id if 'user_id' not in contents: name = character.name else: name = f'<@{contents["user_id"]}|{character.name}>' if len(commands[0]) == 0: hp = contents.get('hp', 0) max_hp = contents.get('max_hp', 0) fields = [{'value': f'{hp}/{max_hp}'}] score = hp / max_hp if max_hp > 0 else 0 return make_response(fields, f'{name}\'s Current HP', color=get_color(score)) if commands[0] == 'party' or commands[0] == 'all': characters = db.session.query(Character).all() ratios = [] fields = [] for character in characters: contents = character.get_contents() if 'hp' in contents: hp = str(contents['hp']) max_hp = str(contents.get('max_hp', hp)) name = character.name field = { 'title': name, 'value': '{}/{}'.format(hp, max_hp), 'short': True } score = int(hp) / int(max_hp) if int(max_hp) != 0 else 1.0 ratios.append(score) fields.append(field) score = sum(ratios) / len(ratios) if len(ratios) > 0 else 0 return make_response(fields, color=get_color(score)) if commands[0] in ('party_simple', 'simple', 'allsimple', 'all_simple'): characters = db.session.query(Character).all() msgs = [] for character in characters: contents = character.get_contents() if 'hp' in contents: hp = str(contents['hp']) max_hp = str(contents.get('max_hp', hp)) msgs.append(f'@{character.name} : {hp}/{max_hp}') msg = '\n'.join(msgs) return make_response(msg) if commands[0] == 'max': if len(commands) > 1: if commands[1][0] in ('+', '-') and 'max_hp' in contents: max_hp = get_int(commands[1], 0) + contents['max_hp'] else: max_hp = get_int(commands[1], 0) hp = contents.get('hp', max_hp) contents['max_hp'] = max_hp contents['hp'] = hp set_and_commit(character, contents) else: max_hp = contents.get('max_hp', 0) hp = contents.get('hp', max_hp) fields = [{'value': f'{hp}/{max_hp}'}] score = hp / max_hp if max_hp > 0 else 0 return make_response(fields, f'{name}\'s Current HP', color=get_color(score)) if commands[0] == 'full': max_hp = int(contents['max_hp']) hp = max_hp contents['hp'] = hp set_and_commit(character, contents) fields = [{'value': f'{hp}/{max_hp}'}] return make_response(fields, f'{name}\'s Current HP', color=get_color(hp / max_hp)) if commands[0] in ('REMOVE', 'CLEAR'): if len(commands) > 1: target = commands[1].replace('@', '') character = get_character(target) contents = character.get_contents() if 'max_hp' in contents: del (contents['max_hp']) if 'hp' in contents: del (contents['hp']) set_and_commit(character, contents) return make_response('HP removed') hp = get_int(commands[0], 0) current_hp = int(contents.get('hp', hp)) max_hp = contents.get('max_hp', current_hp) if commands[0].startswith('+') or commands[0].startswith('-'): current_hp += hp else: current_hp = hp #current_hp = min(current_hp, max_hp) #current_hp = max(-10, current_hp) contents['hp'] = current_hp contents['max_hp'] = max_hp set_and_commit(character, contents) score = current_hp / max_hp if max_hp != 0 else 1 color = get_color(score) fields = [{'value': f'{current_hp}/{max_hp}'}] return make_response(fields, 'Current HP', color=color)
def init(): print(request.form) msg = request.form['text'] username = request.form['user_name'] user_id = request.form['user_id'] team_id = request.form['team_id'] commands = msg.split(' ') character = get_character(username) contents = character.get_contents() contents['user_id'] = user_id if 'user_id' not in contents: name = character.name else: name = f'<@{contents["user_id"]}|{character.name}>' if len(commands[0]) == 0 or commands[0] == 'roll' or commands[0][0] in ( '+', '-'): if len(commands[0]) > 0 and commands[0][0] in ('+', '-'): init_mod = get_int(commands[0], 0) else: init_mod = int(contents.get('init_mod', 0)) title = '{} rolls 1d20 {}'.format(name, modifier(init_mod)) roll = random.randint(1, 20) last_init = roll + init_mod fields = [{ 'title': 'Rolls', 'value': f'{roll}', 'short': True }, { 'title': 'Result', 'value': f'{last_init}', 'short': True }] contents['last_init'] = last_init set_and_commit(character, contents) color = get_color(roll / 20) return make_response(fields, title, color=color) if len(commands) > 1 and commands[0] == 'mod': init_mod = get_int(commands[1], 0) contents['init_mod'] = init_mod set_and_commit(character, contents) fields = [{'value': signed(init_mod)}] return make_response(fields, f'{name}\'s Initiative modifier') if commands[0] == 'set': if len(commands) == 2: last_init = get_int(commands[1], 0) contents['last_init'] = last_init set_and_commit(character, contents) fields = [{'value': str(last_init)}] elif len(commands) > 2: team = db.session.query(Team).filter( Team.team_id == team_id).one_or_none() team = Team(team_id) if team is None else team team_contents = team.get_contents() tmp_inits = team_contents.get('tmp_inits', {}) last_init = get_int(commands[1], 0) target = ' '.join(commands[2:]) if target.startswith('@'): target = target[1:] name = character.name name = f'{target}({name})' tmp_inits[name] = last_init team_contents['tmp_inits'] = tmp_inits team.set_contents(team_contents) db.session.add(team) db.session.commit() fields = [{'value': str(last_init)}] return make_response(fields, f'{name}\'s Initiative value') if commands[0] in ('party', 'all'): characters = db.session.query(Character).all() team = db.session.query(Team).filter( Team.team_id == team_id).one_or_none() team = Team(team_id) if team is None else team team_contents = team.get_contents() tmp_inits = team_contents.get('tmp_inits', {}) log.info('tmp_inits: {}'.format(str(tmp_inits))) char_inits = [] for character in characters: contents = character.get_contents() if 'last_init' in contents: last_init = int(contents['last_init']) if 'user_id' not in contents: name = character.name else: name = f'<@{contents["user_id"]}|{character.name}>' char_inits.append((name, last_init)) for tmp_char in tmp_inits: char_inits.append((tmp_char, tmp_inits[tmp_char])) sorted_inits = sorted(char_inits, key=lambda tup: tup[1], reverse=True) merged_inits = [f'{name} ({init})' for name, init in sorted_inits] formatted_inits = ' > '.join(merged_inits) fields = [{'value': formatted_inits}] return make_response(fields, 'Round initiatives') if commands[0] in ('CLEAR', 'REMOVE'): if 'last_init' in contents: del (contents['last_init']) character.set_contents(contents) db.session.add(character) db.session.commit() return make_response('Your initiative is removed') if commands[0] in ('ALLCLEAR', 'ALLREMOVE', 'CLEARALL', 'REMOVEALL'): characters = db.session.query(Character).all() for character in characters: contents = character.get_contents() if 'last_init' in contents: del (contents['last_init']) character.set_contents(contents) db.session.add(character) db.session.commit() return make_response('All initiatives are removed') return process_unknown(username)
def throw_eof(self , i , line,instance): print utils.get_color("red") , print instance.description + " cannot read after line #" +str(i) + " :\n\t" + line print utils.reset_color() raise JarvisTestError("Unexpected End Of Input")
def exit_jarvis(arg): print utils.get_color("blue") + "Exiting Jarvis. Have a good day!!!" + utils.reset_color() self.__del__() self.status = False
def table_border_style(border, start, stop): width = border.get('borderWidth', None) if width is not None and width >= 0: color = get_color(border.get('borderColor', 'grey')) return [('GRID', start, stop, width, color)] return []
def table_bg_style(key, value, start, stop): style = [] if key == 'background-color': color = get_color(value) style.append(('BACKGROUND', start, stop, color)) return style
def create_student_counting_table(student=None): ''' CREATE student_counting numbers table correspond to specific task on counting numbers caterpillar ### Methods FROM records WHERE dataset='numbers' and game matchs [caterpillar] GROUP BY student, subject, subject FILTER timespent != -1 CREATE timespents [timespent, timespent, ...] CREATE games unique[game, game, ...] CREATE tags unique [tag, tag, ...] SUM score, nb_records CALCULATE %CA, color(%CA) OUT student_counting ### Output ```json { "_id" : ObjectId("5df40a7298f28e7c4f6730ba"), "games" : [ "caterpillar" ], "score" : 2308, "nb_records" : 2695, "student" : 3284, "subject" : "numbers", "dataset" : "numbers", "timespent" : 2489.583685, "%CA" : 85.64, "color" : "green" } ``` ''' pipeline = [ { "$match": { "subject": "numbers", "game": {"$in": ["caterpillar"]}, # "group": {"$ne": "guest"}, } }, { "$group": { "_id": { "student":"$student", "subject": "$subject", "dataset": "$dataset", "classroom": "$classroom" }, "timespent": { "$push": { "$cond":[ {"$gt":["$elapsedTime", 0]}, "$elapsedTime", None ] } }, "games": {"$addToSet": "$game"}, # "tags": {"$addToSet": "$value"}, "score": {"$sum": "$score"}, "nb_records": {"$sum": 1}, } }, { "$project": { "_id": 0, "games": "$games", "score": "$score", "nb_records": "$nb_records", "student": "$_id.student", "subject": "$_id.subject", "dataset": "$_id.dataset", "classroom": "$_id.classroom", "timespent": {"$sum": "$timespent"}, "%CA": {"$round":[{"$multiply": [{"$divide": ["$score", "$nb_records"]}, 100]}, 2]} } }, { "$out": "student_counting" } ] db = connect() if student is None: db.student_counting.drop() else: pipeline[0] = { "$match": { "student":int(student), "subject": "numbers", "game": {"$in": ["caterpillar"]}, # "group": {"$ne": "guest"}, } } pipeline[-1] = { "$merge": "student_counting" } db.records.aggregate(pipeline, allowDiskUse=True) if student is None: for n in db.student_counting.find({}, {"_id":1, "%CA":1}): color = get_color(n["%CA"]) db.student_counting.update({"_id": n["_id"]}, {"$set": {"color": color}}) else: for n in db.student_counting.find({"student":int(student)}, {"_id":1, "%CA":1}): color = get_color(n["%CA"]) db.student_counting.update({"_id": n["_id"]}, {"$set": {"color": color}})
def build_filters(self): print utils.get_color("blue") + "Building Filters..." + utils.reset_color() for fltr in self.filter_list: fltr.build() print utils.get_color("green") + fltr.name + " built successfully" print utils.reset_color()
def print_help(self,arg): for i in range(len(self.trigger_list)): if self.is_operation[self.trigger_list[i]]: print utils.get_color("cyan") + self.trigger_list[i] + utils.reset_color() print utils.get_color("yellow",attr="b") + self.trigger_helplist[i] + utils.reset_color() + "\n"