Пример #1
0
    def __init__(self,
                 output_dim,
                 batch_size=None,
                 input_dim=None,
                 act='linear',
                 batch_norm=False,
                 batch_norm_params={
                     'momentum': 0.9,
                     'epsilon': 1e-5,
                     'training': False,
                     'name': 'bn'
                 },
                 keep_prob=tf.constant(1.0),
                 weights_init=tf.truncated_normal_initializer(stddev=0.01),
                 bias_init=tf.constant_initializer(0.0),
                 name="linear"):
        self.name = name
        Module.__init__(self)

        self.input_dim = input_dim
        self.output_dim = output_dim
        self.batch_size = batch_size
        self.act = act
        self.batch_norm = batch_norm
        self.batch_norm_params = batch_norm_params

        self.keep_prob = keep_prob

        self.weights_init = weights_init
        self.bias_init = bias_init
Пример #2
0
    def __init__(self, dim, nNeurons, name=None, outputFullMap=False):
        if outputFullMap:
            outdim = nNeurons**2
        else:
            outdim = 2
        Module.__init__(self, dim, outdim, name)

        # switch modes
        self.outputFullMap = outputFullMap

        # create neurons
        self.neurons = random.random((nNeurons, nNeurons, dim))
        self.difference = zeros(self.neurons.shape)
        self.winner = zeros(2)
        self.nInput = dim
        self.nNeurons = nNeurons
        self.neighbours = nNeurons
        self.learningrate = 0.01
        self.neighbourdecay = 0.9999

        # distance matrix
        distx, disty = mgrid[0:self.nNeurons, 0:self.nNeurons]
        self.distmatrix = zeros((self.nNeurons, self.nNeurons, 2))
        self.distmatrix[:, :, 0] = distx
        self.distmatrix[:, :, 1] = disty
Пример #3
0
    def get(self):
        TAG = "Meters:"
        module = Module()
        start_time = time.time()
        database = Database()
        module = Module()

        current_user = get_jwt_identity()
        print(TAG, "current_user="******"username="******"sub"])
        username = current_user['sub']

        cmd = """SELECT machineID, machineName, department FROM Machines WHERE username='******' """ % (username)
        res = database.getData(cmd)

        # command = "show measurements"
        # res = module.getData(command)[0]["values"]
        # print(TAG, "res=", res)
        # meters = []
        # for meter in res:
        #     tmp_meter = {}
        #     # print(TAG, meter[0])
        #     tmp_meter["id"] = meter[0]
        #     meters.append(tmp_meter)

        elapsed_time = (time.time() - start_time) * 1000
        print(TAG, "times=", elapsed_time, "ms")

        return res
Пример #4
0
  def LoadEntered(self):
      name = self.e.get()
      self.loadPopup.destroy()
      tempDict = {}
      with open("./Patches/patches.json",'r') as json_file:
        patchDictionary = json.load(json_file)
        print "ALL MODULES"
        print self.AllModules
        while len(self.AllModules) != 0:
          m = self.AllModules.pop()
          print "DELETING" + str(m.name)
          m.delete()
        patch = patchDictionary[name]
        self.PureData.reset()

        #Load all modules 
        for n, module in patch['modules'].iteritems():
          newM = Module(self.canvas, module['Name'], module['x'] * scalar , module['y'] * scalar, self, self.osc)
          newM.setValues(module['Values'])
          tempDict[n] = newM
          self.AllModules.append(newM)

        #Load all connections
        for cable in patch['cables'].values():
          print cable
          inputModule = tempDict[cable[0]]
          inputJack = inputModule.InputJacks[cable[1]]
          outputModule = tempDict[cable[2]]
          outputJack = outputModule.OutputJacks[cable[3]]
          inputModule.connectCable(inputJack, outputJack)
Пример #5
0
    def __init__(self,
                 output_depth,
                 phase_train,
                 is_fullyConnected=False,
                 batch_size=None,
                 input_dim=None,
                 input_depth=None,
                 name="batchNorm",
                 param_dir=None):

        self.name = name
        #self.input_tensor = input_tensor
        Module.__init__(self)

        #comment (it's done in fwd pass)
        self.batch_size = batch_size
        self.input_dim = input_dim
        self.input_depth = input_depth

        #path to stored weights and biases
        self.param_dir = param_dir

        self.beta = tf.Variable(tf.constant(0.0, shape=[output_depth]),
                                name='beta',
                                trainable=True)
        self.gamma = tf.Variable(tf.constant(1.0, shape=[output_depth]),
                                 name='gamma',
                                 trainable=True)

        self.ema = tf.train.ExponentialMovingAverage(decay=0.5)

        self.phase_train = phase_train

        self.is_fullyConnected = is_fullyConnected
Пример #6
0
    def __init__(self, filtersize=(5, 5, 3, 32), stride=(2, 2)):
        '''
        Constructor for a Convolution layer.

        Parameters
        ----------

        filtersize : 4-tuple with values (h,w,d,n), where
            h = filter heigth
            w = filter width
            d = filter depth
            n = number of filters = number of outputs

        stride : 2-tuple (h,w), where
            h = step size for filter application in vertical direction
            w = step size in horizontal direction

        '''

        Module.__init__(self)

        self.fh, self.fw, self.fd, self.n = filtersize
        self.stride = stride

        self.W = np.random.normal(0, 1. / (self.fh * self.fw * self.fd)**.5,
                                  filtersize)
        self.B = np.zeros([self.n])
Пример #7
0
 def __init__(self, probability=0.5, scaled=False):
     assert probability < 1 and probability > 0, 'probability must be (0,1)'
     Module.__init__(self)
     self.prob = probability
     self.train = True
     self.scaled = scaled
     self.noise = torch.Tensor()
Пример #8
0
    def __init__(self,
                 output_depth,
                 batch_size=None,
                 input_dim=None,
                 input_depth=None,
                 kernel_size=5,
                 stride_size=2,
                 act='linear',
                 keep_prob=1.0,
                 pad='SAME',
                 name="conv2d"):
        self.name = name
        #self.input_tensor = input_tensor
        Module.__init__(self)

        self.batch_size = batch_size
        self.input_dim = input_dim
        self.input_depth = input_depth

        self.output_depth = output_depth
        self.kernel_size = kernel_size
        self.stride_size = stride_size
        self.act = act
        self.keep_prob = keep_prob
        self.pad = pad
Пример #9
0
    def __init__(self, dim, peepholes = False, name = None):
        """
        :arg dim: number of cells
        :key peepholes: enable peephole connections (from state to gates)? """
        self.setArgs(dim = dim, peepholes = peepholes)

        # Internal buffers, created dynamically:
        self.bufferlist = [
            ('ingate', dim),
            ('outgate', dim),
            ('forgetgate', dim),
            ('ingatex', dim),
            ('outgatex', dim),
            ('forgetgatex', dim),
            ('state', dim),
            ('ingateError', dim),
            ('outgateError', dim),
            ('forgetgateError', dim),
            ('stateError', dim),
        ]

        Module.__init__(self, 4*dim, dim, name)
        if self.peepholes:
            ParameterContainer.__init__(self, dim*3)
            self._setParameters(self.params)
            self._setDerivatives(self.derivs)
Пример #10
0
    def __init__(self, dim, peepholes=False, name=None):
        """ 
        :arg dim: number of cells
        :key peepholes: enable peephole connections (from state to gates)? """
        self.setArgs(dim=dim, peepholes=peepholes)

        # Internal buffers, created dynamically:
        self.bufferlist = [
            ('ingate', dim),
            ('outgate', dim),
            ('forgetgate', dim),
            ('ingatex', dim),
            ('outgatex', dim),
            ('forgetgatex', dim),
            ('state', dim),
            ('ingateError', dim),
            ('outgateError', dim),
            ('forgetgateError', dim),
            ('stateError', dim),
        ]

        Module.__init__(self, 4 * dim, dim, name)
        if self.peepholes:
            ParameterContainer.__init__(self, dim * 3)
            self._setParameters(self.params)
            self._setDerivatives(self.derivs)
Пример #11
0
 def __init__(self,args):
     Module.__init__(self,args)
     self.log_request = args.log_request
     self.log_response = args.log_response
     self.log = args.log
     self.data = args.data
     self.headers = args.headers
Пример #12
0
 def configure(self, config):
     Module.configure(self, config)
     if not self.version:
         self.version = m.ReadModuleName()
     # Import appropriate the ADAM module (or package).
     module = 'mpx.ion.adam.adam' + self.version
     command = compile('import ' + module,
                       'mpx.ion.adam.unknown.configure()', 'exec')
     eval(command)
     # Get the module's factory and instanciate the "real" class.
     command = module + '.factory'
     adam_factory = eval(command, globals(), locals())
     self.instance = adam_factory()
     
     # Scary stuff.  Detach this ion from our parent, configure the real
     # instance (thus attaching it to the parent) and then morph this
     # instance to behave like the real instance (in case anyone has a
     # handle to this instance).
     try:
         self.parent._del_child(self.name)
         self.instance.configure(config)
         attributes = vars(self.instance.__class__)
         attributes.update(vars(self.instance))
         for attrribute in attributes:
             setattr(self, attrribute, getattr(self.instance, attrribute))
     except:
         msglog.exception()
         # The scary stuff failed, reattach to the parent.
         try:
             self.parent._del_child(self.instance.name)
         except:
             pass
         self.parent._add_child(self)
Пример #13
0
 def insertData(self, query_cmd):
     TAG = "Database:"
     start_time = time.time()
     # self.__init__()
     # establish mysql connection
     module = Module()
     # print(TAG, self.config)
     # print(TAG, "Loading data from mysql server")
     mydb = mysql.connector.connect(**self.config)
     # print(TAG, "Database is ready")
     mycursor = mydb.cursor()
     # print(TAG, "Cursor is ready")
     # execute the sql command
     try:
         # print(TAG, "trying to execute command")
         mycursor.execute(query_cmd)
     except Exception as err:
         # on error execute
         print(TAG, "error on execute command")
         print(TAG, err)
         mydb.close()
         return module.serveErrMsg()
     mydb.commit()
     mydb.close()
     # calculate elapset time
     elapsed_time = (time.time() - start_time) * 1000
     print(TAG, "times=", elapsed_time, "ms")
     return {
                'type': True,
                'message': "success",
                'error_message': None,
                'result': "Meter created",
                'elapsed_time_ms': elapsed_time
            }, 200
	def dropEvent(self, e):
		# Establecer el widget en una nueva posición
		# aqui tengo que separar entre modulos nuevos y ya existentes.
		# la cadena que transmito es "posx,posy" si es mover uno existe
		# posx y posy es la posicion relativa al modulo del cursor
		# los ya existentes, muevo el modulo que paso con el drag a
		# la posicion del click menos el punto (posx,posy)
		# los modulos nuevos, hago una copia de ese tipo de modulo
		# de una base que no se este mostrando, y lo muestro
		# y no solo eso, sino que ademas mantengo
		# la numeracion de cada tipo de modulos para generar siguientes

		# obtiene la posicion relativa de los datos mime (mimeData)
		if e.mimeData().hasText():
			x, y = map(int, e.mimeData().text().split(','))
			e.source().move(e.pos()-QtCore.QPoint(x, y))
			e.setDropAction(QtCore.Qt.MoveAction)
			for l in e.source().lines:
				l.repaint()
		else:
			name=self.newName(e.source().name)
			m = Module(name, e.source().code, self)
			m.move(e.pos()-QtCore.QPoint(100,50))
			m.show()
			self.addModule(m)
			if m.type == Module.Input:
				self.update_composite()
			e.setDropAction(QtCore.Qt.CopyAction)
		e.accept()
Пример #15
0
    def __init__(self,
                 output_dim,
                 batch_size=None,
                 input_dim=None,
                 act='linear',
                 keep_prob=tf.constant(1.0),
                 weights_init=tf.truncated_normal_initializer(stddev=0.05),
                 bias_init=tf.constant_initializer(0.05),
                 name="linear",
                 param_dir=None,
                 use_dropout=False,
                 init_DH=False):
        self.name = name
        #Se crea un objeto Module de module.py, el que lleva el conteo de las capas presentes
        #y un preset a las variables usadas por LRP en cada capa
        Module.__init__(self)

        self.input_dim = input_dim
        self.output_dim = output_dim
        self.batch_size = batch_size
        self.act = act
        self.keep_prob = keep_prob
        self.use_dropout = use_dropout

        self.weights_init = weights_init
        self.bias_init = bias_init

        #path to stored weights and biases
        self.param_dir = param_dir
        self.init_DH = init_DH
Пример #16
0
    def __init__(self,
                 output_depth,
                 input_depth=None,
                 batch_size=None,
                 input_dim=None,
                 kernel_size=5,
                 stride_size=2,
                 act='linear',
                 keep_prob=1.0,
                 pad='SAME',
                 weights_init=tf.truncated_normal_initializer(stddev=0.01),
                 bias_init=tf.constant_initializer(0.0),
                 name="deconv2d"):
        self.name = name
        Module.__init__(self)

        self.input_depth = input_depth
        self.input_dim = input_dim
        #self.check_input_shape()
        self.batch_size = batch_size
        self.output_depth = output_depth
        self.kernel_size = kernel_size
        self.stride_size = stride_size
        self.keep_prob = keep_prob
        self.act = act
        self.pad = pad

        self.weights_init = weights_init
        self.bias_init = bias_init
Пример #17
0
def write_london(template, scf, molecule):
    printable = ''
    wave_function = scf.contains(template.wave_function.name)
    if wave_function:
        scf_submodule = wave_function.submodules.get(template.scf.name)
        if scf_submodule:
            atomst = scf_submodule.properties.pop(template.atomst.name)

    for module in scf.modules:
        if module.name != template.visual.name:
            printable += module.__str__()

    nmr = SubModule('*NMR')
    nmr.add_property(template, '.LONDON')
    nmr.add_property(template, '.DOEPRN')
    nmr.add_property(template, '.INTFLG', ['1 1 0'])#calculating just large-large large-small

    newModule = Module('**PROPERTIES')
    newModule.add_property(template, '.' + molecule.magnetic_field)
    newModule.submodules.update({'*NMR':nmr})

    printable += newModule.__str__()
    printable += '*END OF\n'

    if atomst:
        scf_submodule.properties.update({atomst.name:atomst})

    return printable
 def __init__(self, dim, nNeurons, name=None, outputFullMap=False):
     if outputFullMap: 
         outdim = nNeurons ** 2
     else: 
         outdim = 2
     Module.__init__(self, dim, outdim, name)
     
     # switch modes
     self.outputFullMap = outputFullMap
     
     # create neurons
     self.neurons = random.random((nNeurons, nNeurons, dim))
     self.difference = zeros(self.neurons.shape)
     self.winner = zeros(2)
     self.nInput = dim
     self.nNeurons = nNeurons
     self.neighbours = nNeurons 
     self.learningrate = 0.01
     self.neighbourdecay = 0.9999
     
     # distance matrix
     distx, disty = mgrid[0:self.nNeurons, 0:self.nNeurons]
     self.distmatrix = zeros((self.nNeurons, self.nNeurons, 2))
     self.distmatrix[:, :, 0] = distx
     self.distmatrix[:, :, 1] = disty
Пример #19
0
def write_london(template, scf, molecule):
    printable = ''
    wave_function = scf.contains(template.wave_function.name)
    if wave_function:
        scf_submodule = wave_function.submodules.get(template.scf.name)
        if scf_submodule:
            atomst = scf_submodule.properties.pop(template.atomst.name)

    for module in scf.modules:
        if module.name != template.visual.name:
            printable += module.__str__()

    nmr = SubModule('*NMR')
    nmr.add_property(template, '.LONDON')
    nmr.add_property(template, '.DOEPRN')
    nmr.add_property(template, '.INTFLG',
                     ['1 1 0'])  #calculating just large-large large-small

    newModule = Module('**PROPERTIES')
    newModule.add_property(template, '.' + molecule.magnetic_field)
    newModule.submodules.update({'*NMR': nmr})

    printable += newModule.__str__()
    printable += '*END OF\n'

    if atomst:
        scf_submodule.properties.update({atomst.name: atomst})

    return printable
Пример #20
0
    def __init__(self, library_path, assembly_path, enable_debug=False):
        self.is_windows = "win" in sys.platform

        print(library_path)
        self.module = Module(library_path)

        state = State(self)
        self.rpc = RPC(state)

        # Prepare delegates
        self.on_message = on_message_delegate(RPC.on_message)
        self.on_exit = on_exit_delegate(Bridge.on_exit)

        self._imp_common()
        self._imp_proxy()

        pluginDir = os.path.dirname(
            os.path.abspath(
                sys.modules['__main__'].__file__
            )
        )

        # Initialize AppDomain and call initialize from the plugin
        self.plugin_handle = self.module.clrInit(
            assembly_path, pluginDir,
            self.on_message,
            self.on_exit,
            enable_debug
        )
Пример #21
0
 def __init__(self, input_size, output_size):
     Module.__init__(self)
     self.weight = Tensor(output_size, input_size)
     self.bias = Tensor(output_size)
     self.grad_weight = Tensor(output_size, input_size)
     self.grad_bias = Tensor(output_size)
     self.reset()
Пример #22
0
    def __init__(self, library_path, assembly, enable_debug=False):
        self.is_windows = "win" in sys.platform

        self.module = Module(library_path)

        #print("Init State: %s" % extra_vars)
        #state = State(**extra_vars)
        state = State(self)

        self.rpc = RPC(state)

        # Prepare delegates
        self.on_message = on_message_delegate(RPC.on_message)
        self.on_exit = on_exit_delegate(Bridge._on_exit)

        self._imp_common()
        # Initialize MonoHost on Unix
        if not self.is_windows:
            self._imp_monohost()

            self.module.setMainMethodName(str(assembly.entry))

            self.module.clrInit(assembly.path, self.on_message, self.on_exit)

        # Call initialize from the plugin
        self.module.Initialize(self.on_message, self.on_exit, enable_debug)
Пример #23
0
    def configure(self, config):
        Module.configure(self, config)
        if not self.version:
            self.version = m.ReadModuleName()
        # Import appropriate the ADAM module (or package).
        module = 'mpx.ion.adam.adam' + self.version
        command = compile('import ' + module,
                          'mpx.ion.adam.unknown.configure()', 'exec')
        eval(command)
        # Get the module's factory and instanciate the "real" class.
        command = module + '.factory'
        adam_factory = eval(command, globals(), locals())
        self.instance = adam_factory()

        # Scary stuff.  Detach this ion from our parent, configure the real
        # instance (thus attaching it to the parent) and then morph this
        # instance to behave like the real instance (in case anyone has a
        # handle to this instance).
        try:
            self.parent._del_child(self.name)
            self.instance.configure(config)
            attributes = vars(self.instance.__class__)
            attributes.update(vars(self.instance))
            for attrribute in attributes:
                setattr(self, attrribute, getattr(self.instance, attrribute))
        except:
            msglog.exception()
            # The scary stuff failed, reattach to the parent.
            try:
                self.parent._del_child(self.instance.name)
            except:
                pass
            self.parent._add_child(self)
Пример #24
0
 def GenerateBldMod(self):
     # ugly hack for create a module for the bld file
     bldMod = Module('bld_' + self.name, '** autogenerated **')
     bldMod.resolvedFiles.append(self.bldFile)
     bldMod.putInPkg = False
     self.buildSys.modules[bldMod.name] = bldMod
     if bldMod.name not in self.modules:
         self.modules.append(bldMod.name)
Пример #25
0
 def __deploy(self, type_name, *constraints):
     inner_modules = self.__deploy_inners(*constraints)
     module = Module(self, inner_modules, *constraints)
     module.dump()
     #logging.info('Completed to dump the module "%s"', module.id)
     Template.__deployed_counter += 1
     self.__print_deployment_status(module.id)
     return InnerModule(module)
Пример #26
0
class ModuleTestCase(TestCase):
    def setUp(self):
        print '-' * 200
        print 'testing Module'
        self.module = Module(1)
        self.module.fill('dcg', 'DCG', 1)
        obj = self.module.get_object()
        print obj
Пример #27
0
 def GenerateBldMod (self):
     # ugly hack for create a module for the bld file
     bldMod = Module('bld_' + self.name, '** autogenerated **')         
     bldMod.resolvedFiles.append(self.bldFile)
     bldMod.putInPkg = False
     self.buildSys.modules[bldMod.name] = bldMod
     if bldMod.name not in self.modules:
         self.modules.append(bldMod.name)
Пример #28
0
class Bridge(object):
    def __init__(self, library_path, assembly, enable_debug=False):
        self.is_windows = "win" in sys.platform

        self.module = Module(library_path)

        #print("Init State: %s" % extra_vars)
        #state = State(**extra_vars)
        state = State(self)

        self.rpc = RPC(state)

        # Prepare delegates
        self.on_message = on_message_delegate(RPC.on_message)
        self.on_exit = on_exit_delegate(Bridge._on_exit)

        self._imp_common()
        # Initialize MonoHost on Unix
        if not self.is_windows:
            self._imp_monohost()

            self.module.setMainMethodName(str(assembly.entry))

            self.module.clrInit(assembly.path, self.on_message, self.on_exit)

        # Call initialize from the plugin
        self.module.Initialize(self.on_message, self.on_exit, enable_debug)

    def run(self):
        g_closed.clear()

        self.module.PluginMain()

        # wait synchonously for C# to unblock us
        g_closed.wait()

    def _initialize(self):
        if not self.is_windows:
            self.module.clrInit()

    @staticmethod
    def _reaper():
        g_closed.set()

    @staticmethod
    def _on_exit():
        print("=> OnExit called")
        # Start a thread so C# can return from the exit call
        # while we unblock the RPC state
        rt = threading.Thread(target=Bridge._reaper)
        rt.start()
        pass

    def _imp_common(self):
        return self.module.import_methods(common_imports)

    def _imp_monohost(self):
        return self.module.import_methods(monohost_imports)
Пример #29
0
class Bridge(object):
    def __init__(self, library_path, assembly_path, enable_debug=False):
        self.is_windows = "win" in sys.platform

        print(library_path)
        self.module = Module(library_path)

        state = State(self)
        self.rpc = RPC(state)

        # Prepare delegates
        self.on_message = on_message_delegate(RPC.on_message)
        self.on_exit = on_exit_delegate(Bridge.on_exit)

        self._imp_common()
        self._imp_proxy()

        pluginDir = os.path.dirname(
            os.path.abspath(
                sys.modules['__main__'].__file__
            )
        )

        # Initialize AppDomain and call initialize from the plugin
        self.plugin_handle = self.module.clrInit(
            assembly_path, pluginDir,
            self.on_message,
            self.on_exit,
            enable_debug
        )

    def post_event(self, jsonString):
        self.module.PostEvent(self.plugin_handle, jsonString)

    def run(self):
        g_closed.clear()

        print("GOING TO CALL C# ENTRY")
        self.module.PluginMain(self.plugin_handle)

        print("RETURNED FROM C#")
        # wait for C# to unblock us
        g_closed.wait()

    '''
    C# Calls this method when it's done and handles control back to Python
    '''
    @staticmethod
    def on_exit():
        print("=> OnExit called")
        g_closed.set()
        pass

    def _imp_common(self):
        return self.module.import_methods(common_imports)

    def _imp_proxy(self):
        return self.module.import_methods(proxy_imports)
Пример #30
0
 def getData(self, query_cmd):
     TAG = "Database:"
     start_time = time.time()
     # self.__init__()
     # establish mysql connection
     module = Module()
     # print(TAG, self.config)
     # print(TAG, "Loading data from mysql server")
     mydb = mysql.connector.connect(**self.config)
     # print(TAG, "Database is ready")
     mycursor = mydb.cursor()
     # print(TAG, "Cursor is ready")
     # execute the sql command
     try:
         # print(TAG, "trying to execute command")
         mycursor.execute(query_cmd)
     except Exception as err:
         # on error execute
         print(TAG, "error on execute command")
         print(TAG, err)
         mydb.close()
         return module.serveErrMsg()
     # get raw result
     myresult = mycursor.fetchall()
     # get columns name
     column_name = mycursor.column_names
     # print(TAG, "myresult=", myresult)
     # print(TAG, "columns name=", column_name)
     # convert raw result to json format
     result = []
     for row in myresult:
         tmp_res = {}
         for i in range(len(column_name)):
             if (isinstance(row[i], datetime.date)):
                 # print(TAG, "date found")
                 tmp_res[column_name[i]] = str(row[i])
             elif (isinstance(row[i], bytes)):
                 tmp_json = json.loads(row[i].decode())
                 tmp_res[column_name[i]] = tmp_json
             else:
                 # print(TAG, "type=", type(row[i]))
                 tmp_res[column_name[i]] = row[i]
         result.append(tmp_res)
     # close mysql connecttion
     mydb.close()
     # calculate elapset time
     elapsed_time = (time.time() - start_time) * 1000
     print(TAG, "times=", elapsed_time, "ms")
     # reture result to the client
     return {
                'type': True,
                'message': "success",
                'error_message': None,
                'len': len(result),
                'result': result,
                'elapsed_time_ms': elapsed_time
            }, 200
Пример #31
0
 def __init__(self, context):
     Module.__init__(self, context)
     self.monitor_is_on = True
     self.status_label = render.OutlinedTextImg(color="#8888ff", outlinesize=2, size=20)
     self.bluetooth_address = context.get_config("bluetooth")
     if len(self.bluetooth_address) == 0:
         self.bluetooth_address = None
     # -1=scan failed, 0=not scanned, 1=not found, 2=found
     self.bluetooth_status = 0
Пример #32
0
	def __init__(self, **conf):
		# super(RPCModule, self).__init__()
		Module.__init__(self)
		self.lua_scripts = {}
		self.conf = conf
		self.alive = True
		self.topic = config.RPC_TOPIC
		self.db = None
		self.app = None
Пример #33
0
 def __init__(self, pool_size=2, pool_stride=None, pad = 'SAME',name='avgpool'):
     self.name = name
     Module.__init__(self)
     self.pool_size = pool_size
     self.pool_kernel = [1]+[self.pool_size, self.pool_size]+[1]
     self.pool_stride = pool_stride
     if self.pool_stride is None:
         self.stride_size=self.pool_size
         self.pool_stride=[1, self.stride_size, self.stride_size, 1] 
     self.pad = pad
Пример #34
0
 def scan(self):
     for addr in range(0,0x100):
         try:
             m = Module()
             m.configure({'name':'adamXXXX', 'parent':self,
                          'line_handler':self, 'address':addr})
             print '0x%02X' % addr, '(%3d)' % addr, m.ReadModuleName()
         except EIOError:
             print "."
         del m
Пример #35
0
def poission_model():
    module = Module("poission process")
    module.addConstant(Constant('r', None))

    # variable definition
    v = Variable('n', 0, None, int, False)  # n: int init 0;
    module.addVariable(v)
    # command definition

    comm = Command('', lambda vs, cs: True,
                   lambda vs, cs: vs['n'].setValue(vs['n'].getValue() + 1),
                   module, module.getConstant("r"), CommandKind.NONE, None)
    module.addCommand(comm)

    # 增加label表示n>=4这个ap
    labels = dict()

    def nge4(vs, cs):
        return vs['n'] >= 4

    labels['nge4'] = nge4

    model = ModulesFile.ModulesFile(ModelType.CTMC,
                                    modules=[module],
                                    labels=labels)
    return model
Пример #36
0
    def prepare_and_absolute_diff_all_archs(self, old_lib, new_lib):
        old_modules = Module.get_test_modules_by_name(old_lib)
        new_modules = Module.get_test_modules_by_name(new_lib)
        self.assertEqual(len(old_modules), len(new_modules))

        for old_module, new_module in zip(old_modules, new_modules):
            self.assertEqual(old_module.arch, new_module.arch)
            old_ref_dump_path = self.get_or_create_ref_dump(old_module, False)
            new_ref_dump_path = self.get_or_create_ref_dump(new_module, True)
            self.assertEqual(read_output_content(old_ref_dump_path, AOSP_DIR),
                             read_output_content(new_ref_dump_path, AOSP_DIR))
Пример #37
0
    def __init__(self,modules):
        '''
        Constructor

        Parameters
        ----------
        modules : list, tuple, etc. enumerable.
            an enumerable collection of instances of class Module
        '''
        Module.__init__(self)
        self.modules = modules
Пример #38
0
def list_bin(args):
    """ 
    List the programs provided by the module.
    """

    db = ModuleDb()
    for moduleid in args.module:
        name,version = splitid(moduleid)
        try:
            Module.list_bin(db.lookup(name),version)
        except ModuleError as e:
            e.warn()
Пример #39
0
    def __init__(self, modules):
        '''
        Constructor

        Parameters
        ----------
        modules : list, tuple, etc. enumerable.
            an enumerable collection of instances of class Module
        '''
        Module.__init__(self)
        self.modules = modules
        self.name = '_'.join([x.layerName for x in modules])
Пример #40
0
    def prepare_and_absolute_diff_all_archs(self, old_lib, new_lib):
        old_modules = Module.get_test_modules_by_name(old_lib)
        new_modules = Module.get_test_modules_by_name(new_lib)
        self.assertEqual(len(old_modules), len(new_modules))

        for old_module, new_module in zip(old_modules, new_modules):
            self.assertEqual(old_module.arch, new_module.arch)
            old_ref_dump_path = self.get_or_create_ref_dump(old_module, False)
            new_ref_dump_path = self.get_or_create_ref_dump(new_module, True)
            self.assertEqual(
                read_output_content(old_ref_dump_path, AOSP_DIR),
                read_output_content(new_ref_dump_path, AOSP_DIR))
Пример #41
0
    def __init__(self, output_dim, batch_size=None, input_dim = None, act = 'linear', keep_prob=tf.constant(1.0), weights_init= tf.truncated_normal_initializer(stddev=0.01), bias_init= tf.constant_initializer(0.0), name="linear"):
        self.name = name
        Module.__init__(self)

        self.input_dim = input_dim
        self.output_dim = output_dim
        self.batch_size = batch_size
        self.act = act
        self.keep_prob = keep_prob

        self.weights_init = weights_init
        self.bias_init = bias_init
Пример #42
0
 def __init__(self):
     self.root = Tk()
     self.module1 = Module()
     self.module1.FillData()
     self.NumHiddenLayer = StringVar()
     self.ListNumNeurons = StringVar()
     self.learning = StringVar()
     self.epoc = StringVar()
     self.bais = StringVar()
     self.listN = []
     self.sigmoid = StringVar()
     self.Hyper = StringVar()
Пример #43
0
 def __init__(self, context):
     Module.__init__(self, context)
     self.img = None
     self._next_index = 0
     self.img_rect = None
     self._files = []
     slideshow_dir = context.get_config("slideshow_dir")
     for filename in os.listdir(slideshow_dir):
         full_path = os.path.join(slideshow_dir, filename)
         if os.path.isfile(full_path):
             self._files.append(full_path)
     random.shuffle(self._files)
Пример #44
0
    def __init__(self, config, channel, x, y):
        """
        Constructor.
        :param config: the set of configs loaded by the simulator
        :param channel: the channel to which frames are sent
        :param x: x position
        :param y: y position
        """
        Module.__init__(self)

        #Number of slots in the contention window
        self.window_slots_count = config.get_param(Node.WINDOW_SIZE)
        #Duration in seconds of the channel listening period
        self.listening_duration = config.get_param(Node.LISTENING_TIME)
        #Duration in seconds of each slot
        self.slot_duration = self.listening_duration

        # load configuration parameters
        self.datarate = config.get_param(Node.DATARATE)
        self.queue_size = config.get_param(Node.QUEUE)
        self.interarrival = Distribution(config.get_param(Node.INTERARRIVAL))
        self.size = Distribution(config.get_param(Node.SIZE))

        self.proc_time = Distribution(config.get_param(Node.PROC_TIME))
        self.maxsize = config.get_param(Node.MAXSIZE)
        # queue of packets to be sent
        self.queue = []


        # current state
        self.state = None
        self.switch_state(Node.IDLE)

        # save position
        self.x = x
        self.y = y
        # save channel
        self.channel = channel

        #Number of packets being received
        self.packets_in_air = 0

        #Number of window slots we still have to wait before transmitting
        self.slot_countdown = 0

        #First packet in the current sequence of receiving packets
        self.rx_sequence_first_packet = None

        #Hook to events in the queue for future manipulation
        self.end_listenting_event_hook = None
        self.end_slot_event_hook = None
Пример #45
0
 def __init__ = (self, input_plane, output_plane, kw, kh, dw=1, dh=1, padding=0):
     Module.__init__(self)
     self.input_plane = input_plane
     self.output_plane = output_plane
     self.dw = dw
     self.dh = dh
     self.kw = kw
     self.kh = kh
     self.padding = padding
     self.weight = Tensor(output_plane, input_plane, kh, kw)
     self.bias = Tensor(output_plane)
     self.grad_weight = Tensor(output_plane, input_plane, kh, kw)
     self.grad_bias = Tensor(output_plane)
     self.reset()
Пример #46
0
 def run(self):
     if self.config.task == 1:
         self.g_theta_layers = [2048, 2048]
         self.f_phi_layers = [2048, 2048]
     elif self.config.task == 2:
         self.g_theta_layers = [1024, 1024]
         self.f_phi_layers = [1024, 1024]
     elif self.config.task == 3:
         self.g_theta_layers = [1024, 1024, 1024]
         self.f_phi_layers = [1024] * 3
     elif self.config.task == 4:
         self.g_theta_layers = [1024, 1024]
         self.f_phi_layers = [1024, 1024]
     elif self.config.task == 5:
         self.g_theta_layers = [4096, 4096]
         self.f_phi_layers = [4096, 4096]
     else:
         log.error("Task index error")
     self.g_theta_layers.append(
         1)  # attention should be ended with layer sized 1
     md = Module(self.config, self.g_theta_layers, self.f_phi_layers)
     if self.embedding == 'sum':
         embedded_c = md.contextSum(self.context, with_embed_matrix=True)
         embedded_q = md.questionSum(self.question, with_embed_matrix=True)
     elif self.embedding == 'concat':
         embedded_c = md.contextConcat(self.context, with_embed_matrix=True)
         embedded_q = md.questionConcat(self.question,
                                        with_embed_matrix=True)
     m, alphas = md.hop_1(embedded_c,
                          embedded_q,
                          phase=self.is_training,
                          activation=tf.nn.tanh)
     input_ = md.concat_with_q(m[-1], embedded_q)
     pred = md.f_phi(input_,
                     activation=tf.nn.relu,
                     reuse=False,
                     with_embed_matrix=True,
                     is_concat=True,
                     use_match=self.use_match,
                     phase=self.is_training)
     correct, accuracy, loss, sim_score, p, a = md.get_corr_acc_loss(
         pred,
         self.answer,
         self.answer_match,
         self.answer_idx,
         with_embed_matrix=True,
         is_concat=True,
         use_match=self.use_match,
         is_cosine_sim=True)
     return pred, correct, accuracy, loss, sim_score, p, a
Пример #47
0
    def update_module_data(self, module_data):
        """
        Updates module data
        :param module_data: Module data to update. It contains the module id, request origin address and parsed
        module data
        :return: (iot_error) a status indicating if the module data was updated or not
        """
        assert isinstance(module_data, dict)

        # status code
        status = iot_error.FAILED

        # get module name
        module_name = module_data.get("id")

        # module instance
        module = Module(name=module_name)

        # get module type
        module_type = module.get_module_type()

        # check if module is registered
        if self.check_module_registration(
                module).code == iot_error.SUCCESS.code:

            # check module support
            if self.check_module_support(
                    module).code == iot_error.SUCCESS.code:

                # check for ilm module
                if module_type == "ilm":
                    status = ilm_data_update.update(module_data)

                # check for acm module
                elif module_type == "acm":
                    status = acm_data_update.update(module_data)

                # check for fpm module
                elif module_type == "fpm":
                    status = fpm_data_update.update(module_data)

            # unsupported module
            else:
                status = iot_error.UNSUPPORTED_MODULE

        # module is not registered before
        else:
            status = iot_error.UNREGISTERED_MODULE

        return status
Пример #48
0
 def __init__(self, context):
     Module.__init__(self, context)
     self._gradient = render.Gradient(context.width, self.GRADIENT_SIZE, pygame.Color(0, 0, 0, 0),
                                      pygame.Color(0, 0, 0, 255))
     self.zip_code = context.get_config("zip_code")
     if len(self.zip_code) == 0:
         self.zip_code = self._get_geoip()
     self.api_key = context.get_config("api_key")
     self.temp_label = render.OutlinedTextImg(color="#ffffff", outlinesize=2, size=60)
     self.weather_label = render.OutlinedTextImg(color="#ffffff", outlinesize=2, size=60)
     self.updated_label = render.TextImg(color="#ffffff", size=20)
     self.sun_label = render.TextImg(color="#ffffff", size=20)
     self.temp_f = ""
     self._updated_time = None
     self._had_error = False
Пример #49
0
def load(args):
    """
    Load modules, unloading any versions that are already loaded.
    aliases: add switch swap
    """

    env = ModuleEnv()
    db = ModuleDb()
    for moduleid in args.module:
        name,version = splitid(moduleid)
        try:
            Module.load(db.lookup(name),env,version)
        except ModuleError as e:
            e.warn()
    env.dump()
Пример #50
0
def unload(args):
    """
    Unload modules, if the specified version is already loaded.
    aliases: rm remove
    """

    env = ModuleEnv()
    db = ModuleDb()
    for moduleid in args.module:
        name,version = splitid(moduleid)
        try:
            Module.unload(db.lookup(name),env,strict=True)
        except ModuleError as e:
            e.warn()
    env.dump()
Пример #51
0
	def __init__(self, frame):
		Module.__init__(self, frame, 'submod0')
		self.label = QtWidgets.QLabel()
		#self.label.setGeometry(10,10,100,200)

		grid = QtWidgets.QGridLayout()
		self.setLayout(grid)

		grid.addWidget(self.label, 0, 0, 1, 1)
		reader = QtGui.QImageReader("Mod2Line.png")
		image = reader.read()
		qpixmap = QtGui.QPixmap()
		qpixmap.convertFromImage(image)
		self.label.setPixmap(qpixmap)
		self.changeStateComplete()
Пример #52
0
def show(args):
    """
    Show the environment changes that will be made when loading the module.
    aliases: display
    """

    env = ModuleEnv()
    db = ModuleDb()
    for moduleid in args.module:
        name,version = splitid(moduleid)
        try:
            Module.show(db.lookup(name),env,version)
        except ModuleError as e:
            e.warn()
    env.dump(sys.stderr)
    def getModule(self):

        allModules = loadConf()
        allAlarms = loadAlarm()

        sortedModule = self.sortCfg(allModules)
        sortedAlarms = self.sortCfg(allAlarms)

        for moduleName in sorted(sortedModule.keys()):
            devices = sortedModule[moduleName]
            alarms = sortedAlarms[moduleName]
            module = Module(self, moduleName, devices)
            module.setAlarms(alarms)
            self.globalLayout.addWidget(module)
            self.moduleDict[moduleName] = module
            self.tabCsv[moduleName] = []
Пример #54
0
	def __init__(self, frame):
		Module.__init__(self, frame, 'submod4')
		
		self.init = 1
		self.background = QtWidgets.QLabel()
		#self.label.setGeometry(10,10,100,200)

		grid = QtWidgets.QGridLayout()
		self.setLayout(grid)

		grid.addWidget(self.background, 0, 0, 100, 100)
		reader = QtGui.QImageReader("pie.png")
		image = reader.read()
		qpixmap = QtGui.QPixmap()
		qpixmap.convertFromImage(image)
		self.label.setPixmap(qpixmap)
Пример #55
0
    def prepare_and_run_abi_diff_all_archs(self, old_lib, new_lib,
                                           expected_return_code, flags=[],
                                           create_old=False, create_new=True):
        old_modules = Module.get_test_modules_by_name(old_lib)
        new_modules = Module.get_test_modules_by_name(new_lib)
        self.assertEqual(len(old_modules), len(new_modules))

        for old_module, new_module in zip(old_modules, new_modules):
            self.assertEqual(old_module.arch, new_module.arch)
            old_ref_dump_path = self.get_or_create_ref_dump(old_module,
                                                            create_old)
            new_ref_dump_path = self.get_or_create_ref_dump(new_module,
                                                            create_new)
            self.prepare_and_run_abi_diff(
                old_ref_dump_path, new_ref_dump_path, new_module.arch,
                expected_return_code, flags)
Пример #56
0
def main():
    patt = re.compile(
        '^.*\\.(?:' +
        '|'.join('(?:' + re.escape(ext) + ')' for ext in FILE_EXTENSIONS) +
        ')$')
    input_dir_prefix_len = len(INPUT_DIR) + 1
    for base, dirnames, filenames in os.walk(INPUT_DIR):
        for filename in filenames:
            if not patt.match(filename):
                print('ignore:', filename)
                continue

            input_path = os.path.join(base, filename)
            input_rel_path = input_path[input_dir_prefix_len:]
            output_path = os.path.join(EXPECTED_DIR, input_rel_path)

            print('generating', output_path, '...')
            output_content = run_header_abi_dumper(input_path)

            os.makedirs(os.path.dirname(output_path), exist_ok=True)
            with open(output_path, 'w') as f:
                f.write(output_content)
    modules = Module.get_test_modules()
    for module in modules:
        print('Created abi dump at', make_and_copy_reference_dumps(module))

    return 0
Пример #57
0
    def __init__(self,args):
        Module.__init__(self,args)
        if args.bytes:
            self.corrupt = corrupt_bytes
        else:
            self.corrupt = corrupt_bits

        self.number = args.number
        self.percentage = args.percentage

        self.corrupt_request = args.both or args.request
        self.corrupt_response = args.both or args.response

        # To be reproductible
        if not args.seed is None:
            random.seed(args.seed)
Пример #58
0
	def __init__(self, frame):
		Module.__init__(self, frame, 'submod3')
		
		self.stage = 0
		self.init = 1
		self.posState2 = 0
		self.posState1 = 0
		self.selectedButton = 1
		self.background = QtWidgets.QLabel()
		self.background1 = QtWidgets.QLabel()
		self.button1 = QtWidgets.QPushButton()
		self.button2 = QtWidgets.QPushButton()
		self.button3 = QtWidgets.QPushButton()
		self.displayNum = QtWidgets.QLabel()
		self.select1 = QtWidgets.QLabel()
		self.select2 = QtWidgets.QLabel()
		self.select3 = QtWidgets.QLabel()

		self.stageLabel = QtWidgets.QLabel()
		grid = QtWidgets.QGridLayout()
		self.setLayout(grid)
		'''
		self.background = QtWidgets.QLabel()

		'''
		grid.addWidget(self.background, 0, 0, 0, 1)
		grid.addWidget(self.background1, 0, 0, 1, 0)
		grid.addWidget(self.button3, 2, 3)
		grid.addWidget(self.button2, 2, 2)
		grid.addWidget(self.button1, 2, 1)
		grid.addWidget(self.select3, 3, 3)
		grid.addWidget(self.select2, 3, 2)
		grid.addWidget(self.select1, 3, 1)
		grid.addWidget(self.displayNum, 1, 1, 1, 2)
		grid.addWidget(self.stageLabel, 1, 3, 1, 1)

		reader = QtGui.QImageReader("Mod3Line1.png")
		image = reader.read()
		qpixmap = QtGui.QPixmap()
		qpixmap.convertFromImage(image)
		self.background.setPixmap(qpixmap)

		reader = QtGui.QImageReader("Mod3Line2.png")
		image = reader.read()
		qpixmap = QtGui.QPixmap()
		qpixmap.convertFromImage(image)
		self.background1.setPixmap(qpixmap)
Пример #59
0
    def new_module(self, parent, url, source, fetchto, process_manifest=True):
        """Add new module to the pool.

        This is the only way to add new modules to the pool. Thanks to it the pool can easily
        control its content
        """
        from module import Module
        self._deps_solved = False
        if source != fetch.LOCAL:
            clean_url, branch, revision = path_mod.url_parse(url)
        else:
            clean_url, branch, revision = url, None, None
        if url in [m.raw_url for m in self
                   ]:  # check if module is not already in the pool
            # same_url_mod = [m for m in self if m.raw_url == url][0]
            # if branch != same_url_mod.branch:
            #     logging.error("Requested the same module, but different branches."
            #                   "URL: %s\n" % clean_url +
            #                   "branches: %s and %s\n" % (branch, same_url_mod.branch))
            #     sys.exit("\nExiting")
            # if revision != same_url_mod.revision:
            #     logging.error("Requested the same module, but different revisions."
            #                   "URL: %s\n" % clean_url +
            #                   "revisions: %s (from %s)\n and \n%s (from %s)\n" % (revision,
            #                                                                       parent.path,
            #                                                                       same_url_mod.revision,
            #                                                                       same_url_mod.parent.path))
            #     sys.exit("\nExiting")
            return [m for m in self if m.raw_url == url][0]
        else:
            if self.global_fetch:  # if there is global fetch parameter (HDLMAKE_COREDIR env variable)
                fetchto = self.global_fetch  # screw module's particular fetchto

            new_module = Module(
                parent=parent,
                url=url,
                source=source,
                fetchto=fetchto,
                pool=self)
            self._add(new_module)
            if not self.top_module:
                global_mod.top_module = new_module
                self.top_module = new_module
                new_module.parse_manifest()
                if process_manifest is True:
                    new_module.process_manifest()
            return new_module
Пример #60
0
    def new_module(self, parent, url, source, fetchto):
        from module import Module
        if url in [m.url for m in self]:
            return [m for m in self if m.url == url][0]
        else:
            if self.global_fetch:            # if there is global fetch parameter (HDLMAKE_COREDIR env variable)
                fetchto  = self.global_fetch # screw module's particular fetchto
            elif global_mod.top_module:
                fetchto = global_mod.top_module.fetchto

            new_module = Module(parent=parent, url=url, source=source, fetchto=fetchto, pool=self)
            self._add(new_module)
            if not self.top_module:
                global_mod.top_module = new_module
                self.top_module = new_module
                new_module.parse_manifest()
            return new_module