Example #1
0
    def __init__(self):
        self._publish_arch_related = Gate().grants('gentoo', 'arch_related')
        self._publish_system_profile = Gate().grants('gentoo',
                                                     'system_profile')

        self._trivials = {}

        self._trivial_scalars = {}
        for upper in ('ARCH', 'CHOST'):
            value = portage.settings[upper].strip()
            lower = upper.lower()
            if self._publish_arch_related:
                self._trivial_scalars[lower] = value
            else:
                self._trivial_scalars[lower] = 'WITHHELD'
            self._trivials[lower] = self._trivial_scalars[lower]

        if self._publish_system_profile:
            system_profile = SystemProfile().get()
        else:
            system_profile = 'WITHHELD'
        self._trivial_scalars['system_profile'] = system_profile
        self._trivials['system_profile'] = self._trivial_scalars[
            'system_profile']

        self._trivial_vectors = {}
        self._trivial_vectors['accept_keywords'] = \
            self._accept_keywords()
        self._trivials['accept_keywords'] = \
            self._trivial_vectors['accept_keywords']
Example #2
0
    def __init__(self, debug=False):
        self._publish_mirrors_sync = Gate().grants('gentoo', 'mirrors_sync')
        self._publish_mirrors_distfiles = Gate().grants(
            'gentoo', 'mirrors_distfiles')

        if self._publish_mirrors_distfiles:
            all_urls = self._collect_used_mirror_urls()
            self._mirror_urls = [
                url for url in all_urls
                if _normalize_url(url) in self._collect_known_mirror_urls()
            ]
            if debug:
                private_mirrors = [
                    url for url in all_urls if _normalize_url(url) not in
                    self._collect_known_mirror_urls()
                ]
                for i in private_mirrors:
                    print '  distfiles mirror "%s" is private' % (i)

            self._mirrors_distfiles_count_non_private = len(self._mirror_urls)
            self._mirrors_distfiles_count_private = len(all_urls) - \
                    self._mirrors_distfiles_count_non_private
        else:
            self._mirror_urls = []
            self._mirrors_distfiles_count_non_private = 0
            self._mirrors_distfiles_count_private = 0

        if self._publish_mirrors_sync:
            self._sync_url = self._get_sync_url(debug=debug)
        else:
            self._sync_url = 'WITHHELD'
Example #3
0
    def modify_circuit(self, array):
        counter_insertion = 0
        for i in range(len(array)):
            if int(array[i]) == 1 or int(array[i]) == 2:
                gate_number = self.__find_available_gate_number(i)
                new_gate_inputs = ["I{0}".format(self.key_counter)]
                self.inputs_dicts[self.key_counter] = self.inputs_dicts_counter
                self.inputs_dicts_counter = self.inputs_dicts_counter + 1
                new_gate_inputs.append(str(self.__gates[i].id))
                self.key_counter += 1
                for this_gate in self.__gates:
                    for input_index in range(len(this_gate.input)):
                        if this_gate.input[input_index] == str(
                                self.__gates[i].id):
                            old_input = this_gate.input[input_index]
                            this_gate.input[input_index] = str(gate_number)

                if int(array[i]) == 1:
                    self.__gates.append(
                        Gate(gate_number, "type1_" + str(gate_number), "xor",
                             new_gate_inputs, 1, self.__gates[i].id + 1))
                    counter_insertion += 1
                if int(array[i]) == 2:
                    self.__gates.append(
                        Gate(gate_number, "type2_" + str(gate_number), "xnor",
                             new_gate_inputs, 1, self.__gates[i].id + 1))
                    counter_insertion += 1
                self.gates_dicts[gate_number] = self.gates_dicts_counter
                self.gates_dicts_counter = self.gates_dicts_counter + 1
        self.__gates.sort(key=lambda x: x.sorting)
        return counter_insertion
Example #4
0
def gate_factory(gate_names, is_output_node):
    # return a list of gates, generated from gate types based on a list of names
    if is_output_node == False:
        return [
            Gate(*GATE_TYPES.get(name) + ["default"]) for name in gate_names
        ]
    else:
        return [
            Gate(*GATE_TYPES.get(name) + ["output"]) for name in gate_names
        ]
Example #5
0
 def fine_init(self):
   for i in range(24):
     self.vertices.append([])
     lic_empty_vertex = Gate(name = 'LIC', begin_time = i, day = self.day,
                             loc = [constants.LIC_LATITUDE, constants.LIC_LONGITUDE])
     skip_empty_vertex = Gate(name='GSkip', begin_time = i, day = self.day)
     self.vertices[i].append(lic_empty_vertex)
     self.vertices[i].append(skip_empty_vertex)
     
     if i != 0:
       # connect neighbors
       self.vertices[i-1][0].neighbors.append(lic_empty_vertex)
       self.vertices[i-1][0].neighbors.append(skip_empty_vertex)
       self.vertices[i-1][1].neighbors.append(lic_empty_vertex)
       self.vertices[i-1][1].neighbors.append(skip_empty_vertex)
       # add distances of 0
       self.vertices[i-1][0].edge_dist_tt.append(0)
       self.vertices[i-1][0].edge_dist_tt.append(0)
       self.vertices[i-1][1].edge_dist_tt.append(0)
       self.vertices[i-1][1].edge_dist_tt.append(0)
       # add distance priority
       self.vertices[i-1][0].dist_prio.append(0)
       self.vertices[i-1][0].dist_prio.append(0)
       self.vertices[i-1][1].dist_prio.append(0)
       self.vertices[i-1][1].dist_prio.append(0)
     else:
       self.empty_vertex.neighbors.append(lic_empty_vertex)
       self.empty_vertex.neighbors.append(skip_empty_vertex)
       self.empty_vertex.edge_dist_tt.append(0)
       self.empty_vertex.edge_dist_tt.append(0)
       self.empty_vertex.dist_prio.append(0)
       self.empty_vertex.dist_prio.append(0)
     if i == 23:
       # connect to layer 0 to form a circular graph
       self.vertices[i][0].neighbors.append(self.vertices[0][0])
       self.vertices[i][0].neighbors.append(self.vertices[0][1])
       self.vertices[i][1].neighbors.append(self.vertices[0][0])
       self.vertices[i][1].neighbors.append(self.vertices[0][1])
       # add distances of 0
       self.vertices[i][0].edge_dist_tt.append(0)
       self.vertices[i][0].edge_dist_tt.append(0)
       self.vertices[i][1].edge_dist_tt.append(0)
       self.vertices[i][1].edge_dist_tt.append(0)
       # add distance priority
       self.vertices[i][0].dist_prio.append(0)
       self.vertices[i][0].dist_prio.append(0)
       self.vertices[i][1].dist_prio.append(0)
       self.vertices[i][1].dist_prio.append(0)
Example #6
0
  def naive_init(self):
    for i in range(24):
      self.vertices.append([])
      skip_empty_vertexM = Gate(name = 'SkipM', begin_time = i, boro = 'M', day = self.day)
      skip_empty_vertexQ = Gate(name = 'SkipQ', begin_time = i, boro = 'Q', day = self.day)
      skip_empty_vertexBK = Gate(name = 'SkipBK', begin_time = i, boro = 'BK', day = self.day)
      skip_empty_vertexBX = Gate(name = 'SkipBX', begin_time = i, boro = 'BX', day = self.day)
      lic_empty_vertex = Gate(name = 'LIC', begin_time = i, day = self.day,
                              loc = [constants.LIC_LATITUDE, constants.LIC_LONGITUDE])
      self.vertices[i].append(lic_empty_vertex)
      self.vertices[i].append(skip_empty_vertexM)
      self.vertices[i].append(skip_empty_vertexQ)
      self.vertices[i].append(skip_empty_vertexBK)
      self.vertices[i].append(skip_empty_vertexBX)
      # [0 LIC, 1 M, 2 Q, 3 BK, 4 BX]
      # connect skipping vertices at current layer to that at next layer
      if i != 0:
        self.vertices[i-1][0].neighbors.append(skip_empty_vertexM)
        self.vertices[i-1][0].neighbors.append(skip_empty_vertexQ)
        self.vertices[i-1][0].neighbors.append(skip_empty_vertexBK)
        self.vertices[i-1][0].neighbors.append(skip_empty_vertexBX)

        for j in range(4):
          self.vertices[i-1][j+1].neighbors.append(lic_empty_vertex)
          self.vertices[i-1][j+1].neighbors.append(skip_empty_vertexM)
          self.vertices[i-1][j+1].neighbors.append(skip_empty_vertexQ)
          self.vertices[i-1][j+1].neighbors.append(skip_empty_vertexBK)
          self.vertices[i-1][j+1].neighbors.append(skip_empty_vertexBX)

        for j in range(4):
          # distance between lic to skipping vertices is 0
          self.vertices[i-1][0].edge_dist_tt.append(0)
          self.vertices[i-1][0].dist_prio.append(0)
          # distance between skipping vertices connecting each other is 0
          for k in range(5):
            self.vertices[i-1][j+1].edge_dist_tt.append(0)
            self.vertices[i-1][j+1].dist_prio.append(0)

      # connect starting empty vertices with skipping vertex at the first layer
      else:
        self.empty_vertex.neighbors.append(lic_empty_vertex) 
        self.empty_vertex.neighbors.append(skip_empty_vertexM) 
        self.empty_vertex.neighbors.append(skip_empty_vertexQ) 
        self.empty_vertex.neighbors.append(skip_empty_vertexBK) 
        self.empty_vertex.neighbors.append(skip_empty_vertexBX)
        for j in range(5):
          self.empty_vertex.edge_dist_tt.append(0)
          self.empty_vertex.dist_prio.append(0)
Example #7
0
    def from_file_to_circuit(self, file_path):
        f = open(file_path, "r")
        system = f.read()
        system = system.split('.')
        self.name = system[0]
        self.inputs = self.create_node(system[1])
        self.outputs = self.create_node(system[2])
        self.nodes = self.outputs + self.inputs

        gates = system[3].split('\n')
        gates.remove('')

        self.gates = []
        for g in gates:
            txt = g.replace('[', '')
            txt = txt.replace(']', '')
            temp = txt.split(',')
            gate_type = temp[0]
            gate_name = temp[1]
            output_gate = temp[2]
            inputs_gate = []
            for i in temp[3:]:
                if i != "":
                    inputs_gate.append(self.find_nodes(i))
            output_node = self.find_nodes(output_gate)
            self.gates.append(
                Gate(gate_type, gate_name, output_node, inputs_gate))
        self.run_cnf_leq()
        self.run_cnf_gates()
    def __init__(self, master):
        """
		Start the GUI and the asynchronous threads. We are in the main
		(original) thread of the application, which will later be used by
		the GUI. We spawn a new thread for the worker.
		"""
        self.master = master
        self.running = 1
        self.dispensing_state = 0

        # Create the queue
        self.queue = queue.Queue()

        # Set up the GUI part
        self.gui = GuiPart(master, self.queue, self.onEndApplication,
                           self.onGUIEvent)

        self.gate = Gate(self.processOpeningChange)
        self.gate.start()
        self.gate.execute(["Z"])

        self.scales = Scales()
        self.scales.subscribe("WeightChanged", self)
        self.scales.start()
        self.scales.execute("T")
        self.scales.execute("Z")

        self.dispensingControl = DispensingControl(self.scales, self.gate)
        self.dispensingControl.subscribe("FlowChanged", self)

        self.loadDispensingRule()

        # Start the periodic call in the GUI to check if the queue contains
        # anything
        self.periodicCall()
Example #9
0
    def _init(self, section, metrics_key, privacy_filter):
        self._section = section
        self._metrics_key = metrics_key
        self._privacy_filter = privacy_filter

        self._publish = Gate().grants('gentoo', self._metrics_key)
        self._collect()
Example #10
0
 def __init__(self):
     self._publish = Gate().grants('gentoo', 'repositories')
     self._fill_overlays()
     tree_config = config()
     tree_config['PORTDIR_OVERLAY'] = ' '.join(self._get_active_paths())
     tree_config['PORTDIR'] = main_tree_dir()
     self._dbapi = portdbapi(main_tree_dir(), tree_config)
Example #11
0
    def _fill_features(self):
        def pre_evaluate_to_set(use_flags):
            # .. -foo .. foo .. --> foo
            # .. foo .. -foo .. --> -foo
            d = {}
            for i in [e.lstrip('+') for e in use_flags]:
                if i.startswith('-'):
                    enabled = False
                    flag = i.lstrip('-')
                else:
                    enabled = True
                    flag = i
                d[flag] = enabled
            return set((enabled and flag or '-' + flag)
                       for flag, enabled in d.items())

        def get_features(section):
            res = pre_evaluate_to_set(portage.settings.configdict[section].get(
                "FEATURES", "").split())
            return res

        publish_features = Gate().grants('gentoo', 'features')
        publish_system_profile = Gate().grants('gentoo', 'system_profile')

        self._features = {}
        for key in ('defaults', 'conf', 'env', 'globals'):
            self._features[key] = {}

        self._features['defaults']['publish'] = \
                publish_features and publish_system_profile
        self._features['conf']['publish'] = publish_features
        self._features['globals']['publish'] = publish_features
        self._features['env']['publish'] = \
                self._features['defaults']['publish'] and \
                self._features['globals']['publish'] and \
                self._features['conf']['publish']

        _all_features = {}
        for key in ('defaults', 'conf', 'env', 'globals'):
            if self._features[key]['publish']:
                _all_features[key] = get_features(key)
            else:
                _all_features[key] = []

        for key in ('defaults', 'conf', 'env', 'globals'):
            self._features[key]['entries'] = \
                    set(_all_features[key])
Example #12
0
  def fine_add(self, vertex):

    self.fine_add_aux(vertex)
    task_empty_vertex = Gate(name = 'Skip_'+vertex.name, boro=vertex.boro,
                              loc = [vertex.loc[0], vertex.loc[1]], day = vertex.day,
                              booth_id = vertex.booth_id,
                              begin_time = (vertex.begin_time+1)%24)
    self.fine_add_aux(task_empty_vertex)
Example #13
0
 def getTrueGates(self):
     events = rospy.get_param("/uav/gate_names", "[]")
     inflation = rospy.get_param("/uav/inflation", 0.1)
     gates = []
     for e in events:
         loc = np.asarray(rospy.get_param("/uav/%s/location" % e, []))
         gates.append(Gate(e, loc, inflation))
     return gates
Example #14
0
class Lend:
    gate = Gate()

    def run(self):
        self.gate.getlendrecord()
        # while(1):

        print "Start : %s" % time.ctime()
        time.sleep(10)
        print "End : %s" % time.ctime()
Example #15
0
def main(args):
    rospy.init_node('Cameras', anonymous=True)
    cams = Cameras()
    gate = Gate()
    buoy = Buoy()
    loc = Localize()
    rate = rospy.Rate(30)

    lastTime = time() * 1000
    try:
        while True:
            if rospy.is_shutdown():
                rospy.logerr("F**K")
                break
            if (cams.cam0Ready
                    and (cams.cam1Ready or cams.cameraMap['down'] is None)):
                img_gate = np.copy(cams.getFrontFrame())
                img_buoy = np.copy(img_gate)
                if ((img_gate == np.copy(None)).any() or img_gate is None):
                    rospy.logwarn("none image recieved")
                    continue
                bars = gate.findBars(img_gate)
                loc.updateGate([bars[1], bars[2], bars[3]])

                buoys = buoy.mainImg(img_buoy)
                img_buoy = buoy.getResultImg()
                cams.buoyLinePrediction(
                    img_buoy,
                    loc.firstBuoyYaw.getPredictedState()[0])
                cams.buoyLinePrediction(
                    img_buoy,
                    loc.secondBuoyYaw.getPredictedState()[0],
                    green=False)
                loc.updateBuoy(buoys)

                try:
                    cams.buoyPub.publish(
                        cams.bridge.cv2_to_imgmsg(img_buoy, "bgr8"))
                    cams.gatePub.publish(
                        cams.bridge.cv2_to_imgmsg(img_gate, "bgr8"))
                except Exception as e:
                    rospy.logerr("EXCEPTION IN CAMERAS: ")
                    rospy.logerr(e)
                rospy.logwarn("LOOP TIME %d", time() * 1000 - lastTime)
                lastTime = time() * 1000

            else:
                pass
                #print("NOT READY")

    except KeyboardInterrupt:
        rospy.logerr("Shutting down")
    cv2.destroyAllWindows()
    rospy.logerr("KILL")
def main():
    try:
        server = Gate(serialName)
        server.openGate()
        message = Message()
        message.handshake()
        server.receiveMessage(10)

    except Exception as e:
        print("Um erro aconteceu:")
        print('Failed to upload to ftp: '+str(e))
 def parse_from_strings(self, content):
     content = filter(lambda line: not strip(line).startswith('$'), content)
     input = filter(lambda x: x is not None, map(self.get_inputs, content))
     output = filter(lambda x: x is not None, map(self.get_outputs,
                                                  content))
     connections = filter(
         lambda line: len(strip(line).split()) > 2 and 'primary' not in
         line, content)
     connections = map(lambda line: line.split(), connections)
     gates = map(lambda line: Gate(line[0], line[1], line[2:]), connections)
     return ParseResult(input, output, gates)
Example #18
0
 def __init__(self):
     self._publish = Gate().grants('gentoo', 'compile_flags')
     if self._publish:
         self._cflags = self._parse(portage.settings['CFLAGS'])
         self._cxxflags = self._parse(portage.settings['CXXFLAGS'])
         self._ldflags = self._parse(portage.settings['LDFLAGS'])
         self._makeopts = MakeOpts().serialize()
     else:
         self._cflags = []
         self._cxxflags = []
         self._ldflags = []
         self._makeopts = []
Example #19
0
def main(argv):
    print("Starting run!")
    rospy.init_node('tartan_19_controller', anonymous=True)

    run_config = ConfigMap['Sub']
    sub_controller = SubController(run_config)

    print("Arming")
    sub_controller.armer.arm()

    print("#######################################")
    print("        R U N     G A T E S            ")
    print("#######################################")

    gate = Gate(sub_controller, run_config)
    #gate.execute("fancy")
    sub_controller.mover.dive(4, -0.3)
    sub_controller.mover.dive(1, -0.2)

    # sub_controller.mover.target_heading_relative(-0.2, timeout_s=10) # Right turn
    #sub_controller.mover.forward(5, 0.4)

    print("#######################################")
    print("        R U N     V A M P S            ")
    print("#######################################")
    vamp = VampVisualServoing(sub_controller, run_config)
    vamp.execute()

    print("#######################################")
    print("        R U N     M A R K E R          ")
    print("#######################################")
    # marker = Marker(sub_controller, run_config)
    # marker.execute()

    print("skipping..")
    #sub_controller.mover.target_heading_relative(0.3, 15) # Left turn

    print("#######################################")
    print("        R U N     O C T A G O N        ")
    print("#######################################")
    octagon = Octagon(sub_controller)
    octagon.execute()

    print("#######################################")
    print("        R U N     C O M P L E T E      ")
    print("#######################################")
    sub_controller.armer.disarm()
Example #20
0
  def __init__(self, day = constants.DAY[0], graph_type = constants.GRAPH_TYPE[0]):
    self.day = day
    self.empty_vertex = Gate(name = 'Root', begin_time = 0, day = self.day)
    self.graph_type = graph_type
    self.am_special_tasks = []
    self.pm_special_tasks = []
    self.availability_book = None

    #self.lic_vertex = Gate(name = 'LIC', begin_time = 0, day = self.day)

    # list of lists of tasks at all 24 hours
    self.vertices = []

    if self.graph_type == constants.GRAPH_TYPE[0]:
        self.naive_init()
    elif self.graph_type == constants.GRAPH_TYPE[1]:
        self.fine_init()
def decompose_Con_U(a, b, c, d):
    Gc = np.dot(Gate('S', b).to_matrix(), Gate('R', c).to_matrix())
    Ga = Gate('S', (d - b) / 2).to_matrix()
    Gb = np.dot(
        Gate('R', (-c)).to_matrix(),
        Gate('S', (b - d) / 2).to_matrix())
    Ge = Gate('E', a).to_matrix()

    Oper1 = np.kron(I, Gc)
    Oper2 = np.kron(I, Gb)
    Oper3 = np.kron(Ge, Ga)

    return Oper1.dot(cnot).dot(Oper2).dot(cnot).dot(Oper3)
Example #22
0
 def __get_gates_from_file(self, file):
     '''
         Get all the gates from the circuit file and store it in the circuit.
         Arguments:
         file -- Circuit file to read
     '''
     self.__gates = []
     self.inputs_dicts = {}
     self.inputs_dicts_counter = 0
     self.gates_dicts = {}
     self.gates_dicts_counter = 0
     self.key_counter = 8000
     file_content = read_file(file)
     file_content_lines = file_content.splitlines()
     for i in range(len(file_content_lines)):
         data = file_content_lines[i].split()
         data_fields = []
         gate_inputs = []
         for j in range(len(data)):
             if j == 0:
                 data_fields.append(int(data[j]))
             elif j > 2:
                 gate_inputs.append(data[j].upper())
             else:
                 data_fields.append(data[j].upper())
         data_fields.append(gate_inputs)
         score = 2
         for gate_input in gate_inputs:
             if gate_input.startswith("I"):
                 score -= 1
                 gate_input_row = self.__get_int_of_general_value(
                     gate_input)
                 if gate_input_row not in self.inputs_dicts:
                     self.inputs_dicts[
                         gate_input_row] = self.inputs_dicts_counter
                     self.inputs_dicts_counter = self.inputs_dicts_counter + 1
         self.gates_dicts[data_fields[0]] = self.gates_dicts_counter
         self.gates_dicts_counter = self.gates_dicts_counter + 1
         data_fields.append(score)
         self.__gates.append(
             Gate(data_fields[0], data_fields[1], data_fields[2],
                  data_fields[3], data_fields[4], data_fields[0]))
Example #23
0
    async def run(self):
        """
            Setting up Gate, routes and main socket
        """

        app = web.Application()
        app["api_gate"] = Gate()

        app.add_routes([
            web.get('/api/v1/{entity}', entry_points.api),
            ])

        runner = web.AppRunner(app)
        await runner.setup()

        sock = self.__make_socket()
        srv = web.SockSite(runner, sock)
        await srv.start()

        return srv, app, runner
    def __get_gates_from_file(self, file):
        """Get all the gates from the circuit file and store it in the circuit.

        Keyword arguments:
        file -- Circuit file to read
        """
        # Initialize a private list to hold logic gates.
        self.__gates = []

        # Read the .in file and get each line.
        file_content = read_file(file)
        file_content_lines = file_content.splitlines()

        # Parse each line for gate information.
        for i in range(len(file_content_lines)):
            # Get the gate information separated by whitespaces.
            data = file_content_lines[i].split()
            data_fields = []
            gate_inputs = []

            # Temporarily store each data field.
            for j in range(len(data)):
                # If j is 0, then store an int for the gate ID.
                if j == 0:
                    data_fields.append(int(data[j]))

                # Else if j is greater than 2, then store the gate inputs.
                elif j > 2:
                    gate_inputs.append(data[j].upper())

                # Otherwise, simply store either the name or type.
                else:
                    data_fields.append(data[j].upper())

            # Merge the gate inputs into the data fields list.
            data_fields.append(gate_inputs)

            # Create a new Gate object and store it.
            self.__gates.append(
                Gate(data_fields[0], data_fields[1], data_fields[2],
                     data_fields[3]))
Example #25
0
def read_failed_tasks(graph, file_name):
    tasks = pd.read_excel(file_name)
    for i in range(len(tasks)):
        sample_id = tasks.loc[i, 'sample_id']
        booth_id = tasks.loc[i, 'booth_id']
        station_name = tasks.loc[i, 'sta']
        loc_str = tasks.loc[i, 'loc']
        loc = loc_str[1:len(loc_str) - 1].split(',')
        loc = [float(i) for i in loc]
        day = tasks.loc[i, 'day']
        begin_time = int(tasks.loc[i, 'begin'] / 100)
        boro = tasks.loc[i, 'boro']
        routes_str = tasks.loc[i, 'routes']
        routes = routes_str.split(',')
        comments = tasks.loc[i, 'comments_for_checker']
        new_gate = Gate(name=station_name,
                        loc=loc,
                        day=day,
                        sample_id=sample_id,
                        begin_time=begin_time,
                        boro=boro,
                        routes=routes,
                        comments=comments,
                        booth_id=booth_id,
                        task_type=constants.TASK_TYPE[1])
        for g in graph:
            if g.day == day:
                daytype = constants.DAY.index(day)
                available_checkers = g.availability_book[daytype][
                    new_gate.begin_time]
                if available_checkers != 0:
                    new_gate.availability_priority_holder = 1 / available_checkers
                else:
                    new_gate.availability_priority_holder = 1
                if available_checkers == 1:
                    new_gate.availability_priority_holder = 2
                g.add_vertex(new_gate)
    for g in graph:
        g.normalize_distance_priority()
        g.normalize_availability_priority()
    def __init__(self):
        self.control = CommandInterfaces("strategy")

        self.control.publish_data("Waiting service name /vision/gate")
        rospy.wait_for_service('/vision/gate')

        self.rate = rospy.Rate(10)

        # Step setup mission gate
        #        try:
        #            gate_srv = rospy.ServiceProxy('/vision/gate', VisionGate)
        #        except rospy.ServiceException, e:
        #            print("Service call failed: %s" % e)
        #        self.mission_gate = Gate(gate_srv)
        self.mission_gate = Gate()

        # Step setup mission Path
        self.mission_path = Path(_CONSTANT_PATH_1_MOVEMENT_X_,
                                 _CONSTANT_PATH_1_MOVEMENT_Y_)
        self.vision_path = AnalysisPath()

        # Step setup mission buoy
        self.mission_buoy = Buoy()
        self.vision_buoy = AnalysisBuoy()

        self.current_play = False

        # Step setup service of strategy_mission
        self.service_service = rospy.Service('/mission/strategy', SendBool(),
                                             self.callback_service)

        self.control.publish_data("Waiting command to run mission")
        while (not rospy.is_shutdown()):
            if (self.current_play):
                self.main()
                self.current_play = False
                break
            self.rate.sleep()
Example #27
0
    def load_objects(self):
        for x, y in place_objects(CHECK):
            self.game_objects["check"].append(
                Checkpoint(x * 8, y * 8, self.plr))

        for x, y in place_objects(SWITCH):
            self.game_objects["switch"].append(Switch(x * 8, y * 8))

        for x, y in place_objects(BAD_ROBOT):
            self.game_objects["robot"].append(BadRobot(x * 8, y * 8, self.cam))

        for x, y in place_objects(BADDER_ROBOT):
            self.game_objects["robot"].append(
                BadRobot(x * 8, y * 8, self.cam, True))

        for x, y in place_objects(MOVING_PLATFORM):
            self.game_objects["platform"].append(MobilePlatform(x * 8, y * 8))

        for x, y in place_objects(MOVING_PLATFORM_OPPOSITE):
            self.game_objects["platform"].append(
                MobilePlatform(x * 8, y * 8, True))

        for x, y in place_objects(LASER):
            self.game_objects["laser"].append(
                Laser(x * 8, y * 8, self, self.cam, 3))

        for x, y in place_objects(FAST_LASER):
            self.game_objects["laser"].append(
                Laser(x * 8, y * 8, self, self.cam, 2))

        for x, y in place_objects(VERY_FAST_LASER):
            self.game_objects["laser"].append(
                Laser(x * 8, y * 8, self, self.cam, 1))

        for id in range(1, GATE_IDS + 1):
            for x, y in place_objects(GATE_START_ADDRESS + id):
                self.game_objects["gate"].append(Gate(x * 8, y * 8, id))
Example #28
0
def generate_iscas_faults(file, num_mutated_gates):

    net = Net(*SimpleParser(open(file)).parse())
    net.generate_random_inputs()
    net.calculate_outputs()
    original_outputs = dict(net.outputs)
    tries = 0
    while tries < 100:
        gates = random.sample(net.gates.values(), num_mutated_gates)
        mutated_gates = []
        tries += 1
        for g in gates:
            m = Gate(*g)
            m.type = GATE_MUTATION[m.type]
            mutated_gates.append(m)

        original_gates = net.mutate_net(mutated_gates)
        net.reset_outputs()
        net.calculate_outputs()
        net.mutate_net(original_gates)
        if net.outputs != original_outputs:
            return [file, net.input_values_compact(), mutated_gates]
    print "Failed to generate fault for " + file + " within 100 tries."
    net.finished()
Example #29
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--point-permute", help="enable the point-and-permute optimization", action='store_true')
    parser.add_argument("--free-xor", help="enable the free-XOR optimization", action='store_true')
    parser.add_argument("--grr3", help="enable the GRR3 optimization", action='store_true')
    args = parser.parse_args()

    if args.grr3 and not args.point_permute:
        print("The GRR3 optimization requires the point-and-permute optimization to be enabled")
        exit(0)

    if args.free_xor:
        config.USE_FREE_XOR = True
        print("Optimization enabled: free-XOR")

    if args.point_permute:
        config.USE_POINT_PERMUTE = True
        print("Optimization enabled: point-and-permute")

    if args.grr3:
        config.USE_GRR3 = True
        print("Optimization enabled: GRR3")

    alice = Alice()
    bob = Bob()

    # In this implementation we store wires as strings, whose values are those supplied by the user. 
    # These strings uniquely identify the corresponding wire. Not to be confused with labels, for which there are 
    # two for every unique wire!
    print(
        "Welcome! Please define your circuit by entering a sequence of logic gate specifications of the form \"z = x "
        "OP y\", where:")
    print(" - x and y are identifiers that uniquely specify the gate's two input wires, ")
    print(" - z is an identifier that uniquely specifies the gate's output wire")
    print(" - OP is the gate operation, which is one of \"and\", \"or\", \"xor\"")
    print(
        "Please enter one logic gate per line. When you are finished defining gates and are ready to proceed, "
        "please enter a blank line.")
    wires = dict()
    out_wires = []
    in_wires = []
    while True:
        gate_info = input()
        if not gate_info:
            break
        gate_info = gate_info.split()
        gate = Gate()
        if gate_info[3] == "and":
            gate.op = 'AND'
        elif gate_info[3] == "or":
            gate.op = 'OR'
        elif gate_info[3] == "xor":
            gate.op = 'XOR'
        else:
            raise ValueError("Operation must be one of \"and\", \"or\", \"xor\"")

        gate.in1 = gate_info[2]
        gate.in2 = gate_info[4]
        gate.out = gate_info[0]

        gates[gate.out] = gate

        wires[gate.in1] = ""
        wires[gate.in2] = ""
        wires[gate.out] = ""

        in_wires.append(gate.in1)
        in_wires.append(gate.in2)
        out_wires.append(gate.out)

        wires[gate_info[0]] = ""
        wires[gate_info[2]] = ""
        wires[gate_info[4]] = ""

    input_wires = []
    output_wires = []

    for w in wires:  # select the wires that are ONLY input and ONLY output
        if w in in_wires and w not in out_wires:
            input_wires.append(w)
        if w in out_wires and w not in in_wires:
            output_wires.append(w)

    print("Detected the following INPUT wires:  " + str(input_wires))
    print("Detected the following OUTPUT wires: " + str(output_wires))

    alice_wires = []
    alice_wire_values = []
    bob_wires = []
    bob_wire_values = []

    print("Among the input wires " + str(
        input_wires) + ", which are supplied by Alice, the garbler? Please enter the wire identifiers seperated by commas.")
    alice_wires = input().split(",")

    if len(alice_wires) > 0:  # Alice has at least one input
        print(
            "What are Alice's boolean input values? Please enter a sequence of 0s and 1s corresponding to her input wires, separated by commas.")
        alice_wire_values = list(map(int, input().split(",")))

        # ...therefore, the remaining inputs must be owned by Bob
        for w in input_wires:
            if w not in alice_wires:
                bob_wires.append(w)

        if len(bob_wires) > 0:
            print("The remaining input wires, " + str(bob_wires),
                  " must be supplied by Bob. Please enter a sequence of 0s and 1s corresponding to his input wires, separated by commas.")
            bob_wire_values = list(map(int, input().split(",")))
        else:
            print("Assuming all inputs are supplied by Alice, and Bob only evaluates.")

    else:  # Alice has no inputs; all inputs must be owned by Bob
        print(
            "Assuming all inputs are supplied by Bob, the evaluator. What are Bob's boolean input values? Please enter a sequence of 0s and 1s corresponding to his input wires, separated by commas.")
        bob_input_values = input().split(",")

    # TODO Instead of exiting, handle bad user input gracefully.
    assert (len(alice_wires) == len(alice_wire_values))
    assert (len(bob_wire_values) == len(bob_wire_values))

    alice.input_wires = dict(zip(alice_wires, alice_wire_values))
    bob.input_wires = dict(zip(bob_wires, bob_wire_values))

    print()
    print("Successfully generated the following circuit: ")
    circuit = Circuit()
    # at the moment, we only support one output wire; hence output_wires[0]
    # but the infrastructure is in place to change this, if we so desire
    # to do this, we would likely have to represent the circuit as a digraph instead of a tree
    # and reimplement our construction and evaluation algorithms accordingly 
    circuit.build(output_wires[0], gates)
    circuit.tree.show()

    # Give the circuit to Alice to garble
    alice.circuit = circuit

    # Instruct Alice to generate labels and garble garble gates using the generated labels
    print()
    print("Alice generates labels for the circuit, and garbles gates accordingly:")
    alice.garble_gates()

    # Instruct Alice to permute the garbled tables
    print()
    print("Alice permutes the entries in each garbled gate's garbled truth table:")
    alice.permute_entries()

    # Transfer the circuit to Bob
    print()
    print("Alice transfers the circuit to Bob.")
    bob.circuit = alice.circuit

    for wire in alice.input_wires:
        # Transfer the labels corresponding to Alice's input to Bob
        bob.known_labels[wire] = alice.wire_labels[wire][alice.input_wires[wire]]

    # Simulate OT between Alice and Bob so that Bob can acquire labels corresponding to his input
    print()
    print("Bob uses OT to request from Alice labels corresponding to his input bits:")
    bob.request_labels(alice)

    # Instruct Bob to evaluate the circuit
    print()
    print("Bob proceeds to evaluate the circuit:")
    result = bob.evaluate()

    print()
    print("Alice reveals the value of the label that Bob computed as the circuit's output:")
    # Instruct Alice to reveal the result of Bob's computation
    alice.reveal_result(result)
Example #30
0
def assemble_gate(circuit, output_wire, a, gate_type, b):
    part_a = assemble_input(circuit, a)
    part_b = assemble_input(circuit, b)

    gate = Gate(gate_type, part_a, part_b, output_wire)
    output_wire.set_input(gate)