def test(): import numpy as np oracle = lambda x: x.T oracle = transpose3 ex_set = [] example = np.array([[1, 2], [1, 2]]) # TODO: to add more than one formal parameter make sure to make first element of tuple a list ex_set.append((example, oracle(example))) input_shape = example.shape components = Components( { 'transpose': 1, 'eye_like': 1, 'ones_like': 0, 'multiply': 0, 'add': 0, 'matmul': 0 }, input_shape) f = Formulate(ex_set, components.get_list()) model = f.synthesize() f.Lval2Prog(model, components)
def __init__(self): self.nets = list() self.components = Components() self.component_instances = list() self.design_attributes = DesignAttributes() self.version = dict() self.set_version("0.1.0", "Upverter converter")
def __init__(self): self.server = Flask(__name__) self.app = dash.Dash( name="dashboard", server=self.server, external_stylesheets=[dbc.themes.BOOTSTRAP], routes_pathname_prefix="/somethingsomethin/", suppress_callback_exceptions=True, ) #makes sure that the login is required for data vis for view_func in self.server.view_functions: if view_func.startswith("/dashboard/"): print(view_func) self.server.view_functions[view_func] = login_required( self.server.view_functions[view_func]) self.comp = Components() # self.pi = Pi_Control() self.data = {} self.latLng = {} self.prev_data = {} self.default_plant_img = "https://ichef.bbci.co.uk/news/976/cpsprodpb/10ECF/production/_107772396_treesmall.jpg" self.water_button_counter = 0 self.suggestions = None #ending variables #basic layout for the dash app dashboard self.app.layout = html.Div([ self.comp.navbar, ])
class Design: """ The Design class represents the whole schematic, which is also the top level of the output format. The internal structure of this class closely matches the JSON output.""" def __init__(self): self.nets = list() self.components = Components() self.component_instances = list() self.design_attributes = DesignAttributes() self.version = dict() self.set_version("0.1.0", "Upverter converter") def bounds(self): """ Return the min and max point of a design """ bounds = [net.bounds() for net in self.nets] offset_bounds = lambda (x1, y1, x2, y2), (xo, yo): (x1 + xo, y1 + yo, x2 + xo, y2 + yo) for comp in self.component_instances: offsets = [(att.x, att.y) for att in comp.symbol_attributes] lib_comp = self.components.components[comp.library_id] bbounds = [ b.bounds() for b in lib_comp.symbols[comp.symbol_index].bodies ] bounds.extend( [offset_bounds(b, o) for b, o in zip(bbounds, offsets)]) xs = sum([list(b[0::2]) for b in bounds], []) ys = sum([list(b[1::2]) for b in bounds], []) return [Point(min(xs), min(ys)), Point(max(xs), max(ys))] def set_version(self, file_version, exporter): """ Set the file version and exporter """ self.version['file_version'] = file_version self.version['exporter'] = exporter def add_component_instance(self, component_instance): """ Add an instance """ self.component_instances.append(component_instance) def add_component(self, library_id, component): """ Add a library part """ self.components.add_component(library_id, component) def add_net(self, net): """ Add a net """ self.nets.append(net) def set_design_attributes(self, design_attributes): """ Add design level attributes """ self.design_attributes = design_attributes def json(self): """ Return a design as JSON """ return { "version": self.version, "nets": [n.json() for n in self.nets], "components": self.components.json(), "component_instances": [i.json() for i in self.component_instances], "design_attributes": self.design_attributes.json() }
def start_level(self, level): self.components = Components(self, level) self.route = self.calculate_route() self.components.new_runner(self) self.level_name = f'Level {level[5:]}' self.wealth = 100 self.score = 0 self.start_time = datetime.datetime.now()
def bridge(G, v, u): G[v][u] = 0 G[u][v] = 0 components = Components() [comp, nr] = components.find_components(G) G[v][u] = 1 G[u][v] = 1 if comp[v] != comp[u]: return True else: return False
def test_find_comp(): print("\nTask 3: Connected components:\n") G = [[0, 0, 1, 0, 0, 1], [0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0]] components = Components() [comp, nr] = components.find_components(G) comp_lists = [[] for x in range(nr)] for v in range(len(G)): comp_lists[comp[v] - 1].append(v) for count, item in enumerate(comp_lists): print(count + 1, item) print("Biggest connected component: " + str(components.max_component)) print("has " + str(components.max_count) + " vertices")
def test_synthesize(): oracle = lambda x: x + x ogis(oracle) return ex_set = [] example = np.array([1, 2, 3, 4]).reshape((2, 2)) example = np.array([[1]]) ex_set.append((example, oracle(example))) input_shape = example.shape components = Components( { 'transpose': 0, 'eye_like': 0, 'ones_like': 0, 'multiply': 0, 'add': 1, 'matmul': 0 }, input_shape).get_list() program = synthesize(ex_set, components) print(program)
def __init__(self): self.nets = list() self.components = Components() self.component_instances = list() self.design_attributes = DesignAttributes() self.version = dict() self.set_version("0.0.1","Upverter converter")
def choose_biggest_comp(self): adjacency = self.adj.tolist() components = Components() [comp, nr] = components.find_components(adjacency) for v in range(self.n): if comp[v] == components.max_component: self.biggest_comp.append(v) for i in reversed(range(self.n)): if i not in self.biggest_comp: adjacency.pop(i) else: for j in reversed(range(self.n)): if j not in self.biggest_comp: adjacency[i].pop(j) self.n -= (self.n - len(self.biggest_comp)) self.adj = np.array(adjacency)
class Design: """ The Design class represents the whole schematic, which is also the top level of the output format. The internal structure of this class closely matches the JSON output.""" def __init__(self): self.nets = list() self.components = Components() self.component_instances = list() self.design_attributes = DesignAttributes() self.version = dict() self.set_version("0.0.1","Upverter converter") def set_version(self, file_version, exporter): self.version['file_version'] = file_version self.version['exporter'] = exporter def add_component_instance(self, component_instance): self.component_instances.append(component_instance) def add_component(self, library_id, component): self.components.add_component(library_id,component) def add_net(self, net): self.nets.append(net) def set_design_attributes(self, design_attributes): self.design_attributes = design_attributes def json(self): return { "version" : self.version, "nets" : [n.json() for n in self.nets], "components" : self.components.json(), "component_instances" : [i.json() for i in self.component_instances], "design_attributes" : self.design_attributes.json() }
def ogis(oracle): ex_set = [] ishape = (2, 2) components = Components( { 'transpose': 0, 'eye_like': 1, 'ones_like': 0, 'multiply': 0, 'add': 1, 'matmul': 0 }, ishape) ex_set.append((np.ones((2, 2)), oracle(np.ones((2, 2))))) example = np.eye(ishape[0]) program_candidate = None while example is not None: ex_set.append((example, oracle(example))) f = Formulate(ex_set, components.get_list()) satisfying_constraints = f.Behave_E() s = z3.Solver() s.add(satisfying_constraints) if (s.check() == z3.sat): I, unique_constraints = f.dist_constraint() s2 = z3.Solver() s2.add(unique_constraints) if (s2.check() == z3.sat): print("nonunique; getting new example") model = s2.model() example = np.array([[model.evaluate(i) for i in il] for il in I]) else: print("unsat") #done program_candidate = f.Lval2Prog(s.model(), components) break else: print("No valid program candidate found") return False return program_candidate
def choose_biggest_comp(G): biggest_comp = [] components = Components() [comp, nr] = components.find_components(G.adjacency) adj = G.adjacency.tolist() for v in range(G.size): if comp[v] == components.max_component: biggest_comp.append(v) for i in reversed(range(G.size)): if i not in biggest_comp: adj.pop(i) else: for j in reversed(range(G.size)): if j not in biggest_comp: adj[i].pop(j) G.size -= (G.size - len(biggest_comp)) G.adjacency = np.array(adj)
def rotated_components(components, angle): ''' ... Args: components: angle: Returns: ''' img = components.img stencil = components.get_stencil() rotated_stencil = rotate(stencil, angle*180/np.pi, order=0) rotated_image = np.clip(rotate(img, angle*180/np.pi, order=2), 0, 1) boxes = get_bboxes(rotated_stencil) return Components(boxes, rotated_image, stencil=rotated_stencil)
def __init__(self): self._module_info = Components(MODULE_INFO) self._components = set() self._rolled_up_components = {} self._rollup_counters = {} self.set_version('min')
class YUILoader: def __init__(self): self._module_info = Components(MODULE_INFO) self._components = set() self._rolled_up_components = {} self._rollup_counters = {} self.set_version('min') def set_version(self, version): self._version = VERSIONS[version] def add_component(self, new_component_name): if not self._has_component(new_component_name): self._add_requirements(new_component_name) self._count_in_rollups(new_component_name) rollup_name = self._get_satisfied_rollup(new_component_name) if rollup_name: self.add_component(rollup_name) else: self._components.add(new_component_name) self._roll_up_superseded(new_component_name) def add_module(self, module_def): module_data = {} lexer = shlex(module_def, posix=True) def expect(*patterns): token = lexer.get_token() if token not in patterns: raise ValueError, '%s expected instead of %s' % \ (' or '.join(repr(s) for s in patterns), token and repr(token) or 'end of data') return token str_attrs = 'name', 'type', 'path', 'fullpath', 'varName' list_attrs = 'requires', 'optional', 'after' state = 'ATTR' expect('{') while state != 'STOP': if state == 'ATTR': token = expect(*str_attrs+list_attrs) expect(':') if token in str_attrs: module_data[token] = lexer.get_token() if module_data[token] is None: raise ValueError, \ 'string expected instead of end of data' state = 'DELIM' elif token in list_attrs: expect('[') lst = module_data[token] = [] state = 'LIST' elif state == 'LIST': lst.append(lexer.get_token()) if re.search(r'\W', lst[-1]): raise ValueError, 'invalid component name %r' % token if expect(',', ']') == ']': state = 'DELIM' elif state == 'DELIM': if expect(',', '}') == '}': expect(None) state = 'STOP' else: state = 'ATTR' if 'type' not in module_data: raise ValueError, 'type missing in %r' % module_def self._module_info.add(module_data['name'], module_data) return module_data def render(self): return '\n'.join(self._render_component(component) for component in self._sort_components()) def _has_component(self, component_name): return component_name in self._components \ or component_name in self._rolled_up_components def _get_satisfied_rollup(self, component_name): if self._version == '-min': for rollup_name in self._module_info.get_rollups(component_name): rollup_status = self._rollup_counters.get(rollup_name, set()) if len(rollup_status) >= self._module_info[rollup_name].rollup: return rollup_name def _count_in_rollups(self, component_name): for rollup_name in self._module_info.get_rollups(component_name): rolled_up = self._rollup_counters.setdefault(rollup_name, set()) rolled_up.add(component_name) for superseded in self._module_info[component_name].supersedes: self._count_in_rollups(superseded) def _roll_up_superseded(self, component_name): for superseded in self._module_info[component_name].supersedes: self._rolled_up_components[superseded] = component_name if superseded in self._components: self._components.remove(superseded) def _add_requirements(self, component_name): component = self._module_info[component_name] for requirement in component.requires: self.add_component(requirement) if component.skinnable: self.add_component(SKIN['defaultSkin']) def _render_component(self, component_name): component = self._module_info[component_name] path = component.fullpath or YUI_BASE + component.path if component.type == 'js': if self._version != '-min' and path.endswith('-min.js'): path = path[:-7] + self._version + '.js' elif component.type == 'css': if self._version == '' and path.endswith('-min.css'): path = path[:-8] + '.css' return TAGS[component.type] % path def _sort_components(self, component_names=None): if component_names is None: comps = self._components.copy() else: comps = component_names while comps: component_name = comps.pop() component = self._module_info[component_name] direct_deps = component.requires + component.after indirect_deps = [ self._rolled_up_components[r] for r in direct_deps if r in self._rolled_up_components] all_deps = set(direct_deps).union(set(indirect_deps)) deps_left = comps.intersection(all_deps) for r in self._sort_components(deps_left): yield r comps.remove(r) yield component_name
def before_all(context): context.config = TestConfig() context.config.driver = None context.config.components = Components()
class Design: """ The Design class represents the whole schematic, which is also the top level of the output format. The internal structure of this class closely matches the JSON output.""" def __init__(self): self.nets = list() self.components = Components() self.component_instances = list() self.design_attributes = DesignAttributes() self.version = dict() self.set_version("0.1.0","Upverter converter") def bounds(self): """ Return the min and max point of a design """ bounds = [net.bounds() for net in self.nets] offset_bounds = lambda (x1, y1, x2, y2), (xo, yo): (x1+xo, y1+yo, x2+xo, y2+yo) for comp in self.component_instances: offsets = [(att.x, att.y) for att in comp.symbol_attributes] lib_comp = self.components.components[comp.library_id] bbounds = [b.bounds() for b in lib_comp.symbols[comp.symbol_index].bodies] bounds.extend([offset_bounds(b, o) for b, o in zip(bbounds, offsets)]) xs = sum([list(b[0::2]) for b in bounds], []) ys = sum([list(b[1::2]) for b in bounds], []) return [Point(min(xs), min(ys)), Point(max(xs), max(ys))] def set_version(self, file_version, exporter): """ Set the file version and exporter """ self.version['file_version'] = file_version self.version['exporter'] = exporter def add_component_instance(self, component_instance): """ Add an instance """ self.component_instances.append(component_instance) def add_component(self, library_id, component): """ Add a library part """ self.components.add_component(library_id, component) def add_net(self, net): """ Add a net """ self.nets.append(net) def set_design_attributes(self, design_attributes): """ Add design level attributes """ self.design_attributes = design_attributes def json(self): """ Return a design as JSON """ return { "version" : self.version, "nets" : [n.json() for n in self.nets], "components" : self.components.json(), "component_instances" : [i.json() for i in self.component_instances], "design_attributes" : self.design_attributes.json() }
class DashApp: def __init__(self): self.server = Flask(__name__) self.app = dash.Dash( name="dashboard", server=self.server, external_stylesheets=[dbc.themes.BOOTSTRAP], routes_pathname_prefix="/somethingsomethin/", suppress_callback_exceptions=True, ) #makes sure that the login is required for data vis for view_func in self.server.view_functions: if view_func.startswith("/dashboard/"): print(view_func) self.server.view_functions[view_func] = login_required( self.server.view_functions[view_func]) self.comp = Components() # self.pi = Pi_Control() self.data = {} self.latLng = {} self.prev_data = {} self.default_plant_img = "https://ichef.bbci.co.uk/news/976/cpsprodpb/10ECF/production/_107772396_treesmall.jpg" self.water_button_counter = 0 self.suggestions = None #ending variables #basic layout for the dash app dashboard self.app.layout = html.Div([ self.comp.navbar, ]) #end of layout #call back for in the input value def output_text(self, value): if value != None: return "Your Input: " + str(value) else: "What are you waiting for..." #Funtion that displays the current date and time def update_time(self, n): style = {"padding": "12px", "fontsize": "25px"} return html.Span( datetime.datetime.now().strftime("%m/%d/%Y %I:%M:%S %p"), style=style) #Funtion that updates the map url when an address is entered def update_map_img(self, _, address): self.latLng = {} self.data = {'time': [], 'temperature': []} self.prev_data = {} if address != None and address != "": geoman = GeolocationManager(address) geolocation_str = geoman.__str__() print(geolocation_str) geolocation_dict = eval(geoman.__str__()) self.latLng['lat'], self.latLng['lng'] = geolocation_dict[ 'lat'], geolocation_dict['lng'] return (html.Img(src=geolocation_dict['img_url'], style={"width": "100%"}), self.comp.graph_output(address)) else: return "Please enter a valid address", html.Div() #Funtion to update the graph based on the active tab and the n_interval def updateGraph(self, n, active_tab): print(n) active_tab = active_tab.split("-")[0] lat, lng = self.latLng['lat'], self.latLng['lng'] print(self.data) time.sleep(1) df = pd.DataFrame.from_dict(self.data, orient="index") df = df.transpose() fig = px.area(df, x='time', y=active_tab, template="plotly_white") return fig def updateData(self, n): weatherman = WeatherManager(self.latLng['lat'], self.latLng['lng']) weatherman_data = eval(weatherman.__str__()) self.data = weatherman_data['data'] #Uses cutting edge computer vision research to classify plants and give suggestions based on a picture of that plant def updateImg(self, contents): print("in update image") if contents == None or not contents[0:10] == "data:image": card = self.comp.initializePlantCard(self.default_plant_img, []) print(card) return card self.plantRecognizer = Recognizer(contents) request_id = self.plantRecognizer.identify() suggestions = self.plantRecognizer.get_suggestions(request_id) suggestions = [ elem for elem in suggestions if not elem['plant']['common_name'] == "" ] print(suggestions) self.suggestions = suggestions return self.comp.initializePlantCard( contents, html.Div([ html.H6(suggestions[0]['plant']['common_name'], id="plant_name", style={ "text-align": "center", "font-size": "13px" }), dbc.Button("Confirm", id="confirm", color="success", className="mr-1", style={"width": "30%"}), dbc.Button("Reject", id="reject", color="danger", className="mr-1", style={"width": "30%"}), ], style={"text-align": "center"})) #Confirms the suggestion and returns the name of the plant def confirmSuggestion(self): print(self.suggestions[0]['id']) self.plantRecognizer.confirm_suggestion(self.suggestions[0]['id']) print("Thank you for confirming my suggestion") return html.H6(self.suggestions[0]['plant']['common_name'], id="plant_name", style={ "text-align": "center", "font-size": 13 }) def rejectSuggestion(self): print("Ok we are rejecting the suggestion") print(self.suggestions[0]['id']) self.plantRecognizer.reject_suggestion(self.suggestions[0]['id']) if len(self.suggestions) > 1: self.suggestions.pop(0) print(self.suggestions) return html.Div([ html.H6(self.suggestions[0]['plant']['common_name'], id="plant_name", style={ "text-align": "center", "font-size": "13px" }), dbc.Button("Confirm", id="confirm", color="success", className="mr-1", style={"width": "30%"}), dbc.Button("Reject", id="reject", color="danger", className="mr-1", style={"width": "30%"}), ], style={"text-align": "center"}) if len(self.suggestions) == 1: self.suggestions.pop(0) print("Suggestions length == 1", self.suggestions) #return a div with an input field and a button to submit the plant name return dbc.Row([ dbc.Col( dbc.Input(id="plant_input", placeholder="Plant Name", type="text"), width=9, ), dbc.Col( dbc.Button("Submit", id="submit_plant_name", color="dark", className="mr-1"), width=3, ) ], no_gutters=True, id="plant_stuff") #alter this code once you get the pi back working def toggleWater(self, _): if self.water_button_counter % 2 == 0: self.water_button_counter += 1 # Code to turn raspberry pi off with the solenoid config self.pi.off() return dbc.Button("Water On", color="primary", className="mr-1", id="pi") self.water_button_counter += 1 #Code to turn the water counter on with the soleniod config self.pi.on() return dbc.Button("Water Off", color="danger", className="mr-1", id="pi") #alteration for pi code ends here def update_layout(self, current_user): print(current_user.username) WATER_BENDER_LOGO = "https://raw.githubusercontent.com/csmjoshi/WaterBender/master/waterbender.png" ef = dbc.ButtonGroup([ dbc.DropdownMenu( [ dbc.DropdownMenuItem("Add Community", href="/add_community", external_link=True), dbc.DropdownMenuItem( "Add Plant", href="/add_plant", external_link=True) ], group=True, right=True, label="+", in_navbar=True, color="primary", ), dbc.DropdownMenu([ dbc.DropdownMenuItem( "My Profile", href="/my_profile", external_link=True), dbc.DropdownMenuItem("My Communities", href="/my_communities", external_link=True), dbc.DropdownMenuItem( "My Plants", href="/my_plants", external_link=True), dbc.DropdownMenuItem( "Sign Out", href="/logout", external_link=True) ], group=True, right=True, label=current_user.username, in_navbar=True, color="primary"), ], className="ml-auto flex-nowrap mt-3 mt-md-0") navbar = dbc.Navbar( [ html.A( dbc.Row( [ dbc.Col( html.Img(src=WATER_BENDER_LOGO, height="30px")), dbc.Col( dbc.NavbarBrand("Water Bender", className="ml-2")), ], align="center", no_gutters=True, ), href="/#", ), ef ], color="dark", dark=True, ) self.app.layout = html.Div([ navbar, html.P(id="live_time_updates", style={"margin-left": "10px"}), dcc.Interval(id="time_interval", interval=1000, n_intervals=0), dbc.Row([ dbc.Col( html.Div([ self.comp.plantCard, self.comp.imgUpload.uploads, self.comp.location_input, html.P(id="output_da_input"), html.Div(id="render_map") ]), width=3, style={"padding-top": "10px"}, ), dbc.Col(id="grapher", width=9) ]), ])
from tkinter import * from components import Components app = Tk() app.title("Faça Login") app.minsize("300", "400") app.maxsize("500", "400") app.geometry("500x400") app.configure(background="#393939") Components().render_components(app) app.mainloop()
def main(): parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-s', '--sequence', action='store_true', help='''Check if given sequence is graphic. Sequence consisting of ints separated by spaces''') group.add_argument( '-r', '--randomize', action='store_true', help='''Randomize edges n times where n(int) is first parameter after -r/--randomize flag in graph given by the graphical sequence(ints separated by spaces)''') group.add_argument('-c', '--components', action='store_true', help='''Find all connected components in graph given by the graphical sequence(ints separated by spaces) and mark the greatest''') group.add_argument( '-e', '--euler', action='store_true', help='''Make random Euler's graph with given n(int) nodes or with random number of them if not specified''') group.add_argument( '-kr', '--regular', action='store_true', help='''Make k-regular graph with n nodes where n(int) is first parameter and k(int) the second one''') group.add_argument( '-H', '--hamilton', action='store_true', help='''Check Hamilton's cycle exists in graph given by the graphical sequence(ints separated by spaces) and prints it''' ) arg = parser.parse_known_args() if arg[0].sequence: parser2 = argparse.ArgumentParser() parser2.add_argument('seq', type=int, nargs='+') args = parser2.parse_args(arg[1]) try: g = Graph.from_sequence(np.array(args.seq)) g.show() except NotGraphicSequenceException: print(f"Sequence:\n{args.seq}\nis not a graphic sequence") return return if arg[0].randomize: parser2 = argparse.ArgumentParser() parser2.add_argument('n', type=int) parser2.add_argument('seq', type=int, nargs='+') args = parser2.parse_args(arg[1]) if args.n < 0: print('Number of randomization n must be positive integer ') return try: g = Graph.from_sequence(np.array(args.seq)) except NotGraphicSequenceException: print(f"Sequence:\n{args.seq}\nis not a graphic sequence") return print("Randomized edges:") for i in range(0, args.n): p1, p2 = g.randomize_edges() print(f"{p1}, {p2} => ({p1[0]}, {p2[1]}), ({p1[1]}, {p2[0]})") print() g.show() return if arg[0].components: parser2 = argparse.ArgumentParser() parser2.add_argument('seq', type=int, nargs='+') args = parser2.parse_args(arg[1]) try: g = Graph.from_sequence(np.array(args.seq)) except NotGraphicSequenceException: print(f"Sequence:\n{args.seq}\nis not a graphic sequence") return G = g.adjacency components = Components() [comp, nr] = components.find_components(G) comp_lists = [[] for x in range(nr)] for v in range(len(G)): comp_lists[comp[v] - 1].append(v) for count, item in enumerate(comp_lists): print(count + 1, item) print("Biggest connected component: " + str(components.max_component)) print("has " + str(components.max_count) + " vertices") return if arg[0].euler: parser2 = argparse.ArgumentParser() parser2.add_argument('n', type=int, nargs='?', default=random.randint(4, 30)) args = parser2.parse_args(arg[1]) find_euler_random(args.n) return if arg[0].regular: print(5) parser2 = argparse.ArgumentParser() parser2.add_argument('n', type=int) parser2.add_argument('k', type=int) args = parser2.parse_args(arg[1]) gen_k_regular(args.n, args.k) return if arg[0].hamilton: parser2 = argparse.ArgumentParser() parser2.add_argument('seq', type=int, nargs='+') args = parser2.parse_args(arg[1]) try: g = Graph.from_sequence(np.array(args.seq)) except NotGraphicSequenceException: print(f"Sequence:\n{args.seq}\nis not a graphic sequence") return adj_list = convert_matrix_to_adj_list(g.adjacency) print(adj_list) check_hamilton_cycle(adj_list) return
# sort tuples by priority sorted_list = sorted(command_potential, key=lambda t: t[1]) # get final command priority_command = sorted_list[0][0] self.message_object.message_warp(target_type,priority_command) self.output_message_to_topic(report_control_data) def find_all_index(self, array_list, item): return [i for i, a in enumerate(array_list) if a == item] def find_all_index(array_list, item): return [i for i,a in enumerate(array_list) if a == item] if __name__ == '__main__': master = Components.Master() AI = AI(master) data = [100, 5] msg = [0, 3, data, "A"] print AI.generate_command(msg) types = [34, 31] p = [1,1] # AI.sort_and_output_commands(data, types, p) kkk = ["arm_command", "wheel_command", "cloud_deck_command", "voice_command", "light_command"] for i in range(len(kkk)-1,0,-1): print kkk[i] index = kkk.index("arm_command")
from json import load as json_load from utime import sleep from components import Components from network_wrapper import NetworkWrapper with open('config.json') as json_data: config = json_load(json_data) nw = NetworkWrapper(wifi_config=config['wifi'], ubidots_config=config['ubidots']) components = Components(config) bottle_capacity = config['bottle']['bottle_capacity_ml'] while True: sensors_data = components.measure_from_periodic_sensors() sensors_data['bottle-capacity'] = bottle_capacity nw.try_sending_sensors_data(sensors_data) sleep(config['behavior']['measurements_interval_sec'])
class YUILoader: def __init__(self): self._module_info = Components(MODULE_INFO) self._components = set() self._rolled_up_components = {} self._rollup_counters = {} self.set_version("min") def set_version(self, version): self._version = VERSIONS[version] def add_component(self, new_component_name): if not self._has_component(new_component_name): self._add_requirements(new_component_name) self._count_in_rollups(new_component_name) rollup_name = self._get_satisfied_rollup(new_component_name) if rollup_name: self.add_component(rollup_name) else: self._components.add(new_component_name) self._roll_up_superseded(new_component_name) def add_module(self, module_def): module_data = {} lexer = shlex(module_def, posix=True) def expect(*patterns): token = lexer.get_token() if token not in patterns: raise ValueError, "%s expected instead of %s" % ( " or ".join(repr(s) for s in patterns), token and repr(token) or "end of data", ) return token str_attrs = "name", "type", "path", "fullpath", "varName" list_attrs = "requires", "optional", "after" state = "ATTR" expect("{") while state != "STOP": if state == "ATTR": token = expect(*str_attrs + list_attrs) expect(":") if token in str_attrs: module_data[token] = lexer.get_token() if module_data[token] is None: raise ValueError, "string expected instead of end of data" state = "DELIM" elif token in list_attrs: expect("[") lst = module_data[token] = [] state = "LIST" elif state == "LIST": lst.append(lexer.get_token()) if re.search(r"\W", lst[-1]): raise ValueError, "invalid component name %r" % token if expect(",", "]") == "]": state = "DELIM" elif state == "DELIM": if expect(",", "}") == "}": expect(None) state = "STOP" else: state = "ATTR" if "type" not in module_data: raise ValueError, "type missing in %r" % module_def self._module_info.add(module_data["name"], module_data) return module_data def render(self): return "\n".join(self._render_component(component) for component in self._sort_components()) def _has_component(self, component_name): return component_name in self._components or component_name in self._rolled_up_components def _get_satisfied_rollup(self, component_name): if self._version == "-min": for rollup_name in self._module_info.get_rollups(component_name): rollup_status = self._rollup_counters.get(rollup_name, set()) if len(rollup_status) >= self._module_info[rollup_name].rollup: return rollup_name def _count_in_rollups(self, component_name): for rollup_name in self._module_info.get_rollups(component_name): rolled_up = self._rollup_counters.setdefault(rollup_name, set()) rolled_up.add(component_name) for superseded in self._module_info[component_name].supersedes: self._count_in_rollups(superseded) def _roll_up_superseded(self, component_name): for superseded in self._module_info[component_name].supersedes: self._rolled_up_components[superseded] = component_name if superseded in self._components: self._components.remove(superseded) def _add_requirements(self, component_name): component = self._module_info[component_name] for requirement in component.requires: self.add_component(requirement) if component.skinnable: self.add_component(SKIN["defaultSkin"]) def _render_component(self, component_name): component = self._module_info[component_name] path = component.fullpath or YUI_BASE + component.path if component.type == "js": if self._version != "-min" and path.endswith("-min.js"): path = path[:-7] + self._version + ".js" elif component.type == "css": if self._version == "" and path.endswith("-min.css"): path = path[:-8] + ".css" return TAGS[component.type] % path def _sort_components(self, component_names=None): if component_names is None: comps = self._components.copy() else: comps = component_names while comps: component_name = comps.pop() component = self._module_info[component_name] direct_deps = component.requires + component.after indirect_deps = [self._rolled_up_components[r] for r in direct_deps if r in self._rolled_up_components] all_deps = set(direct_deps).union(set(indirect_deps)) deps_left = comps.intersection(all_deps) for r in self._sort_components(deps_left): yield r comps.remove(r) yield component_name
def find_blobs(raw_img, args): '''function performing two dimensional connected component analysis on an image. Args: img (ndarray): original image to be analyzed args (Arguments instance): defined the threshold value to binarze the image Returns: an instance of the Components class, a stencil containing the final labels of components, and a stencil containing the labels before eliminating equivalences ''' # dimensions height = raw_img.shape[0] width = raw_img.shape[1] img = processing.threshold(raw_img, args) # adding column of zeros to prevent left and right most blob # form being mistaken as one zeros = np.zeros((height, 1)) img = np.concatenate((img, zeros), axis=1) width += 1 size = height * width img = img.reshape(size) stencil = np.zeros(size, dtype=int) labels = DisjointSet(n_labels=1) # first pass for i in range(size): if img[i] != 0: # if a neighboring pixel is labeled the investigated pixel is given the same label # Note: when iterating from top left to bottom right indices to the right bottom of investigated # pixel cannot be labeled before this pixel for j in [i - 1, i - width, i - width - 1, i - width + 1]: if j < 0 or j >= size: continue if stencil[j] != 0 and stencil[i] == 0: # connection stencil[i] = stencil[j] elif stencil[j] != 0 and stencil[j] != stencil[i]: # conflict labels.unite(stencil[i], stencil[j]) else: # no connection nor conflict continue # if no neighboring pixel is labeled the investigated pixel is give a new label if stencil[i] == 0: new_label = labels.next() stencil[i] = new_label labels.add(new_label) # uncomment to print show labels after first pass # first_pass = deepcopy(stencil.reshape((height, width))) # second pass to eliminate equivalences eq = labels.get_equivalents() for label in eq.keys(): stencil[stencil == label] = eq[label] # reshaping stencil stencil = stencil.reshape((height, width)) # SCIPY VARIANT #stencil = measure.label(img, background=0) # count pixels in blobs, calculate median to filter blobs final_labels = np.arange(1, np.max(stencil) + 1) pixel_counts = [] for label in final_labels: pixel_counts.append(np.sum(stencil == label)) pixel_counts = np.array(pixel_counts) min_allowed_pixels = np.median( pixel_counts[pixel_counts > 0]) / 5 # arbitrary; seems to work well # filter final lables and stencil final_labels = np.array(final_labels)[pixel_counts >= min_allowed_pixels] new_stencil = np.zeros_like(stencil) for i, label in enumerate(final_labels): new_stencil[stencil == label] = i + 1 stencil = new_stencil # construct boxes around letters bounding_boxes = get_bboxes(stencil) # chars = get_chars_from_boxes(raw, bounding_boxes) # extract characters from image in correct order #chars = [] #bounding_boxes = [] #while boxes: # box = heappop(boxes) # chars.append(raw[box[2]:box[3], box[0]:box[1]]) # bounding_boxes.append(box) return Components(boxes=bounding_boxes, img=raw_img, stencil=stencil)
class Game: def __init__(self, canvas): self.canvas = canvas self.font = pygame.font.SysFont('Arial', 48) self.components = None self.route = None self.wealth = 100 self.score = 0 self.start_time = None self.level_name = '' self.levels = ['level01', 'level02', 'level03'] self.start_level(self.levels[0]) def next_level(self): del self.levels[0] self.start_level(self.levels[0]) def score_point(self): self.score += 1 if self.score >= Settings.target_score: self.draw() time.sleep(2) self.next_level() def start_level(self, level): self.components = Components(self, level) self.route = self.calculate_route() self.components.new_runner(self) self.level_name = f'Level {level[5:]}' self.wealth = 100 self.score = 0 self.start_time = datetime.datetime.now() @property def time(self): duration = datetime.datetime.now() - self.start_time minutes, seconds = divmod(duration.seconds, 60) return f'{minutes}:{seconds:02}' @property def runners(self): return self.components.runners def handle_mouse_event(self, event): self.components.handle_mouse_event(event) def show_wealth(self): self.canvas.blit( self.font.render(f'{self.wealth}', True, pygame.Color('yellow')), utils.cell_to_isometric(Settings.wealth_location).as_int_list ) def show_score(self): self.canvas.blit( self.font.render(f'{self.score}/{Settings.target_score}', True, pygame.Color('white')), utils.cell_to_isometric(Settings.score_location).as_int_list ) def show_time(self): time = self.time self.canvas.blit( self.font.render(time, True, pygame.Color('white')), utils.cell_to_isometric(Settings.time_location).as_int_list ) def show_level_name(self): self.canvas.blit( self.font.render(self.level_name, True, pygame.Color('white')), utils.cell_to_isometric(Settings.level_name_location).as_int_list ) def draw(self): # TODO: Create background image self.canvas.fill((0, 0, 0)) self.components.draw() self.show_wealth() self.show_score() self.show_time() self.show_level_name() pygame.display.flip() def find_start_tile(self): for tile in self.components.filter(type=StaticTile): if tile.abstract_tile.is_start: return tile def neighbours(self, x, y): for i, j in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]: if 0 <= i < self.grid_size[0] and 0 <= j < self.grid_size[1]: yield i, j def find_neighbour_tile_on_path(self, tile): for tile in self.components.filter(type=StaticTile, neighbour=tile): if tile.abstract_tile.is_path: return tile def find_next_step(self, step): if step.tile.abstract_tile.is_end: return None delta = { 'E': Vector(1, 0), 'S': Vector(0, 1), 'W': Vector(-1, 0), 'N': Vector(0, -1) }[step.exit_side] next_location = step.grid_location + delta next_tile = self.components.filter(type=StaticTile, grid_location=next_location)[0] assert next_tile.is_path next_entry_side = { 'E': 'W', 'W': 'E', 'N': 'S', 'S': 'N' }[step.exit_side] if next_tile.direction in ['EW', 'NS']: # Can move in a straight line next_exit_side = step.exit_side else: # Take code (consisting in entry + exit side, but may be in wrong order) # remove the entry side, to be left with the exit side next_exit_side = [c for c in next_tile.direction if c is not next_entry_side][0] return Step(next_location, next_entry_side, next_exit_side, next_tile) def calculate_route(self): route = [] start_tile = self.find_start_tile() next_tile = self.find_neighbour_tile_on_path(start_tile) delta_to_next = next_tile.grid_location -start_tile.grid_location exit_side = { (1, 0): 'E', (0, 1): 'S', (-1, 0): 'W', (0, -1): 'N' }[delta_to_next.as_tuple] step = Step(grid_location=start_tile.grid_location, entry_side=None, exit_side=exit_side, tile=start_tile) while step is not None: route.append(step) step = self.find_next_step(step) return route def tick(self): if random.randint(1, 100) == 1: self.components.new_runner(self) for runner in self.runners: runner.take_a_step() for tile in self.components.filter(type=TowerTile): tile.support_runners()
def __init__(self): self._module_info = Components(MODULE_INFO) self._components = set() self._rolled_up_components = {} self._rollup_counters = {} self.set_version("min")
data.bufferKanjiSimData(kanjisim_url1, kanjisim_url2, kanjissim_file_name) data.get(kanjis_url, kanjis_file_name) fetched = True except Exception as e: print("- retry") print(e) time.sleep(60) print("Printing similarity") sdot = Similarity.graph(data) sdisplay = random.random() < 0.7 sdot.render('D:\Japanese\jap_anki\graphs\similarity', view=sdisplay) print("Printing composition") cdot = Composition.graph(data) cdisplay = random.random() < 0.7 cdot.render('D:\Japanese\jap_anki\graphs\composition', view=cdisplay) print("Printing ORoots") odot = ORoots.graph(data) odisplay = random.random() < 0.5 odot.render('D:\Japanese\jap_anki\graphs\oroots', view=odisplay) print("Printing components") rdot = Components.graph(data) rdisplay = (not (sdisplay or cdisplay or odisplay)) or (random.random() < 0.4) rdot.render('D:\Japanese\jap_anki\graphs\components', view=(random.random() < 0.4)) print("All done")
#-*- coding: UTF-8 -*- from pymatgen import MPRester from pymatgen.analysis.phase_diagram import PhaseDiagram, PDPlotter import collections import sys, os import time from components import Components Comps = Components() os.system('rm -rf structure; mkdir structure') ChemicalSymbols = [ 'H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr' ] #M = ['Sc', 'Ti', 'V', 'Cr', 'Mn', # 'Zr', 'Nb', 'Mo', # 'Hf', 'Ta', 'W'] #A = ['Al', 'Si', 'P', 'S', # 'Ga', 'Ge', 'As', # 'Cd', 'In', 'Sn', # 'Ti', 'Pb'] M = ['Sc'] A = ['Al']
return (True, False, False) # Hot - Red light elif external_temperature + external_temperature_allowed_offset < temperature_range[ 'min']: return (False, False, True) # Cold - Blue light else: return (False, True, False) # Good - Green light with open('config.json') as json_data: config = json_load(json_data) nw = NetworkWrapper(wifi_config=config['wifi'], ubidots_config=config['ubidots']) time_utils.sync_ntp(nw) components = Components() components.rgb_led.set_colors(False, False, False) last_notification_timestamp_sec = 0 while True: sensors_data = nw.get_sensors_data() # Color-by-temperature LED r, g, b = calculate_temperature_color( float(sensors_data['internal-temperature']), float(sensors_data['external-temperature'])) components.rgb_led.set_colors(r, g, b) # Water level display components.seven_segment.number(int(sensors_data['water-level']))