Beispiel #1
0
    def setUp(self):
        super(TestRedirectionToDeclaration, self).setUp()
        name = type(self).__name__

        private_h = Header("private.h")
        private_h.add_type(Structure("Private"))

        public_h = Header("public.h")
        public_h.add_types([
            Type["Private"].gen_forward_declaration(),
            Function("public_func")
        ])

        private_c = Source("private.c")
        public_func_impl = Type["public_func"].gen_definition()
        private_c.add_type(public_func_impl)

        src = Source(name.lower() + ".c").add_global_variable(
            # It must internally re-direct pointer from type "Private"
            # to "Private.declaration", its forward declaration.
            Pointer(Type["Private"])("handler"))
        src.add_type(Pointer(public_func_impl, name="cb_ptr"))

        src_content = """\
/* %s */

#include "public.h"

typedef void (*cb_ptr)(void);
Private *handler __attribute__((unused));

""" % (name.lower() + ".c")

        self.files = [(src, src_content)]
Beispiel #2
0
def run():
    """
    Create the objects source for Sirio, Vega and Proxima as well
    as the corresponding scanners and the satellite object of Gaia.
    Then scan the sources from Gaia and print the time.
    :return: gaia, sirio, scanSirio, vega, scanVega, proxima, scanProxima
    """
    start_time = time.time()
    sirio = Source("sirio", 101.28, -16.7161, 379.21, -546.05, -1223.14, -7.6)
    vega = Source("vega", 279.2333, 38.78, 128.91, 201.03, 286.23, -13.9)
    proxima = Source("proxima", 217.42, -62, 768.7, 3775.40, 769.33, 21.7)

    scanSirio = Scanner(np.radians(20), np.radians(2))
    scanVega = Scanner(np.radians(20), np.radians(2))
    scanProxima = Scanner(np.radians(20), np.radians(2))
    gaia = Satellite()
    print(time.time() - start_time)

    scanSirio.start(gaia, sirio)
    scanVega.start(gaia, vega)
    scanProxima.start(gaia, proxima)
    print(time.time() - start_time)

    seconds = time.time() - start_time
    print('Total seconds:', seconds)
    return gaia, sirio, scanSirio, vega, scanVega, proxima, scanProxima
Beispiel #3
0
 def test_handles_no_matches(self):
     p = Parser()
     m = Meme("all your * -base")
     s = [
         Source("", "foo", ""),
         Source("", "bar", ""),
         Source("", "baz", "")
     ]
     self.assertEqual(p.collate_words(m, s).get_list(), [])
Beispiel #4
0
 def test_collates_words(self):
     p = Parser()
     m = Meme("all your * -base")
     s = [
         Source("", "all your cake", ""),
         Source("", "all your cake", ""),
         Source("", "all your data", "")
     ]
     self.assertEqual(
         p.collate_words(m, s).get_list(), [("cake", 2), ("data", 1)])
Beispiel #5
0
def main(args):
    #print (args)
    result = {
        'is_success': True,
        'data': None,
        #'foo': '中文',
    }
    if args.action == 'upload-image' and args.db_file and args.resource_id:
        src = Source('database', name=args.db_file)
        res = src.upload_image(args.resource_id)
        result['data'] = res

    elif args.action == 'update-source-description' and args.db_file and args.resource_id and args.value:
        src = Source('database', name=args.db_file)
        res = src.update_description(args.resource_id, args.value)
        result['result'] = {
            'source_id': args.resource_id,
            'value': args.value,
            'text': 'update ok',
            'sql': res
        }
    elif args.action == 'poll-source-status' and args.db_file and args.resource_id:
        src = Source('database', name=args.db_file)
        res = src.poll_source_status(args.resource_id)
        result['data'] = res

    elif args.action == 'batch-upload' and args.resource_id and args.ini_file and args.db_file:
        src = Source('database', name=args.db_file)
        config = Config(args.ini_file)
        res = src.batch_upload(config.get_config(), args.resource_id)
        if res:
            result['data'] = res
        else:
            result['is_success'] = False

    elif args.action == 'get-config' or \
       (args.ini_file and not args.set_config_value):
        config = Config(args.ini_file)
        res = config.get_config()
        result['data'] = res

    elif args.action == 'set-config' or \
         (args.ini_file and args.set_config_value):
        if sov := args.set_conifg_value.split(':'):
            # check input value
            if len(sov) < 3 or sov[1] == '':
                result['error'] = 'section:option:value syntax error'
                return result
            else:
                config = Config(args.ini_file)
                res = config.set_config(sov[0], sov[1], sov[2])
                result['data'] = res
Beispiel #6
0
    def setUp(self):
        super(TestOptimizeInclusions, self).setUp()
        name = type(self).__name__

        src = Source(name.lower() + ".c")

        ah = Header("a.h")
        bh = Header("b.h")
        ch = Header("c.h")

        ah.add_type(Type("a"))
        bh.add_type(Type("b")).add_reference(Type["a"])
        ch.add_type(Type("c")).add_reference(Type["b"]).add_inclusion(ah)

        src.add_type(Pointer(Type["c"], "cpointer"))

        # c.h includes a.h but inclusion of a.h cannot be substituted with c.h
        # inclusion because it creating reference loop between inclusions of
        # c.h and b.h. This test checks inclusions optimization correctness and
        # ordering of chunks.

        src_content = """\
/* {} */

#include "a.h"
#include "b.h"
#include "c.h"

typedef c *cpointer;
""".format(src.path)

        self.files = [(src, src_content)]
Beispiel #7
0
    def sample(self):
        """
        Method to pick the sample satisfying the likelihood constraint using uniform sampling

        Returns
        -------
        new : object
            The evolved sample
        number : int
            Number of likelihood calculations after sampling

        """

        new = Source()

        x_l, x_u = self.getPrior_X()
        y_l, y_u = self.getPrior_Y()
        r_l, r_u = self.getPrior_R()
        a_l, a_u = self.getPrior_A()

        while (True):

            new.X = np.random.uniform(x_l, x_u)
            new.Y = np.random.uniform(y_l, y_u)
            new.A = np.random.uniform(a_l, a_u)
            new.R = np.random.uniform(r_l, r_u)
            new.logL = self.log_likelihood(new)
            self.number += 1

            if (new.logL > self.LC):
                break

        return new, self.number
Beispiel #8
0
 def __get_source(self):
     fname = self.__get_filename()
     if SourceMap.sources.has_key(fname):
         return SourceMap.sources[fname]
     else:
         SourceMap.sources[fname] = Source(fname)
         return SourceMap.sources[fname]
Beispiel #9
0
    def _recognition(self):
        # Colocando no banco de dados
        text = []

        # Para cada arquivo, um reconhecimento
        for i in range(self.count):
            # Informando qual reconhecimento está sendo realizado
            self.label_recognition.text = f'Reconhecimento {i+1} de {self.count}'

            # Lendo o arquivo de aúdio
            audio = self.recog.read_file(f'{self.filename}-{i}.wav')

            # Fazendo o STT
            text_recognition = self.recog.recognize_speech(audio)
            text.append(text_recognition)

            sleep(0.1)

        self.label_recognition.text = "Reconhecimento concluído, salvando o arquivos"
        organizator = Source()
        organizator.delete()

        # Definindo o meu dia atual
        now = datetime.now()
        dia_atual = f'{now.day}-{now.month}-{now.year}'

        # Definindo nome
        name = self.filename.replace('tmp/', '').replace(dia_atual ,'').replace('-', '')

        organizator.constructor(f'{dia_atual}-{str(now.hour)}-{str(now.minute)}', name, text)

        self.remove_widget(self.layout)
        self.add_widget(Initial())
Beispiel #10
0
    def setUp(self):
        super(TestSeparateCases, self).setUp()

        src = Source(type(self).__name__.lower() + ".c")

        i = Type["int"]("i")
        src.add_type(
            Function(name="func_a",
                     body=BodyTree()(Declare(OpDeclareAssign(i, 0)),
                                     BranchSwitch(i, separate_cases=True)(
                                         SwitchCase(1), SwitchCase(2)))))

        src_content = """\
/* {} */

void func_a(void)
{{
    int i = 0;
    switch (i) {{
    case 1:
        break;

    case 2:
        break;

    default:
        break;
    }}
}}

""".format(src.path)

        self.files = [(src, src_content)]
Beispiel #11
0
    def setUp(self):
        super(TestForwardDeclaration, self).setUp()
        name = type(self).__name__

        src = Source(name.lower() + ".c")

        a = Structure("A")
        a.append_field(Pointer(a)("next"))

        b = Structure("B")
        b.append_field(Pointer(a)("next"))

        src.add_types([a, b])

        src_content = """\
/* {} */

typedef struct A A;

struct A {{
    A *next;
}};

typedef struct B {{
    A *next;
}} B;

""".format(src.path)

        self.files = [(src, src_content)]
Beispiel #12
0
    def setUp(self):
        super(TestCrossDeclaration, self).setUp()

        src = Source(type(self).__name__.lower() + ".c")

        a = Structure("A")
        b = Structure("B")

        b.append_field(Pointer(a)("ref"))
        a.append_field(Pointer(b)("ref"))

        src.add_types([a, b])

        src_content = """\
/* {} */

typedef struct B B;

typedef struct A {{
    B *ref;
}} A;

struct B {{
    A *ref;
}};

""".format(src.path)

        self.files = [(src, src_content)]
 def addSource(self, x, y):
     self.state['sourceXIndices'].append(x)
     self.state['sourceYIndices'].append(y)
     self.state['sourcesPoints'].append((x, y))
     self.state['sources'].append(
         Source(self.canvas, (x + 1) * (self.width / 8),
                (y + 1) * (self.height / 8)))
Beispiel #14
0
    def setup_source(self,
                     x,
                     y,
                     source_image,
                     source_size,
                     to_intersection,
                     car_images,
                     car_size,
                     generative=True,
                     spawn_delay=4.0):
        ''' Sets up a Source, which is an Intersection. '''
        s = Sprite(source_image, source_size)
        s.move_to(x=x, y=self.height - y)

        source = Source(x,
                        y,
                        None,
                        None,
                        self,
                        car_images,
                        car_size,
                        spawn_delay=spawn_delay,
                        generative=generative)
        road = self.setup_road(source, to_intersection, 'road.bmp')
        source.road = road
        source.length_along_road = road.length
        self.source_set.add(source)
        self.window.add_sprite(s)
        return source
Beispiel #15
0
    def __init__(self, words, source, **kwargs):
            super().__init__(**kwargs)
            
            self.words = words.split(' ')
            self.src = source

            # Criando os componentes
            self.source = Source()
            self.layout = BoxLayout(orientation='vertical')
            self.clear_widgets()

            results = self.search()

            if results != []:
                for result in results:
                    title = Label(text=result['title'], font_size=30, size_hint_y=None, height=40)
                    time = Label(text=result['time'], font_size=20, size_hint_y=None, height=40)
                    phrarse = Label(text=result['phrarse'], font_size=15, size_hint_y=None, height=40)
                    separator = Label(text='-----------------------------------------------', font_size=60, size_hint_y=None, height=20)

                    
                    self.layout.add_widget(title)
                    self.layout.add_widget(time)
                    self.layout.add_widget(phrarse)
                    self.layout.add_widget(separator)
            
            self.add_widget(self.layout)
Beispiel #16
0
    def setUp(self):
        super(TestLabelAndGotoGeneration, self).setUp()
        name = type(self).__name__

        src = Source(name.lower() + ".c")

        lbl = Label("begin")
        i = Type["int"]("i")

        src.add_type(
            Function(name="main",
                     body=BodyTree()(Declare(i), lbl, OpAssign(i, OpAdd(i, 1)),
                                     Goto(lbl))))

        src_content = """\
/* {} */

void main(void)
{{
    int i;
begin:
    i = i + 1;
    goto begin;
}}

""".format(src.path)

        self.files = [(src, src_content)]
Beispiel #17
0
 def find_live():
     # TODO refactor this mess
     rm = visa.ResourceManager()
     for res in rm.list_resources():
         try:
             print(f'trying: {res}')
             inst = rm.open_resource(res)
             answer = inst.query('*IDN?')
             model = answer.split(',')[1].strip()
             print(model, self._generatorList)
             if model == 'E3648A':
                 # if model == 'E3631A':
                 self._source = Source(res, answer, inst)
                 print('>>> source')
             # elif 'N5183A' in answer:
             #     self._generator1 = Generator(res, answer, inst)
             elif model in self._generatorList:
                 if not self._generator1:
                     self._generator1 = Generator(res, answer, inst)
                     print('>>> gen1')
                 else:
                     self._generator2 = Generator(res, answer, inst)
                     print('>>> gen2')
             elif model == 'N9030A':
                 self._analyzer = Analyzer(res, answer, inst)
                 print('>>> analyzer')
         except Exception as ex:
             print(ex)
Beispiel #18
0
    def __init__(self,
                 name,
                 directory,
                 nic_num=0,
                 timer_num=0,
                 char_num=0,
                 block_num=0,
                 **qom_kw):
        super(QOMDevice, self).__init__(name, **qom_kw)

        self.directory = directory
        self.nic_num = nic_num
        self.timer_num = timer_num
        self.char_num = char_num
        self.block_num = block_num

        # Define header file
        header_path = join("hw", directory, self.qtn.for_header_name + ".h")
        try:
            self.header = Header.lookup(header_path)
        except Exception:
            self.header = Header(header_path)

        # Define source file
        source_path = join("hw", directory, self.qtn.for_header_name + ".c")
        self.source = Source(source_path)
def main():

    debug = Debugger()
    chrono = Chrono()
    universe = Universe(debug)
    source = Source(debug).get_source()
    bucket_chain = BucketChain(debug, chrono, universe, source)
    clusters = Clusters(debug, chrono, universe)
    algorithm = OnlineClustering(debug, universe, bucket_chain, clusters)

    while True:
        operation_time = time.time()
        if bucket_chain.is_updated():
            universe.compute_log_n_df()
            bucket_chain.compute_universal_counts()
            bucket_chain.compute_universal_tfidf()
            clusters.update_centroid_counts()
            clusters.update_centroid_tfidf()
            algorithm.pre_clustering_work()
            algorithm.online_clustering()
            clusters.remove_old_clusters()
            universe.prune_terms(clusters)
            debug.log("BUCKET FINISHED IN: " +
                      str(time.time() - operation_time))
            clusters.debug_active_clusters()
            clusters.save_active_clusters()
Beispiel #20
0
    def setUp(self):
        super(TestPointerReferences, self).setUp()
        name = type(self).__name__

        try:
            h = Header["type_a.h"]
        except:
            h = Header("type_a.h")
        h.add_type(Type("a", incomplete=False, base=False))

        src = Source(name.lower() + ".c").add_type(
            Structure("s",
                      Pointer(Type["a"])("next")))

        src_content = """\
/* {} */

#include "type_a.h"

typedef struct s {{
    a *next;
}} s;

""".format(src.path)

        self.files = [(src, src_content)]
Beispiel #21
0
 def setUp(self):
     t_init = 0  # 1/24/60
     t_end = t_init + 1 / 24 / 60  # 365*5
     my_dt = 1 / 24 / 60 / 10  # [days]
     spline_degree = 3
     gaia = Satellite(ti=t_init, tf=t_end, dt=my_dt, k=spline_degree)
     self.gaia = gaia
     my_times = np.linspace(t_init, t_end, num=100, endpoint=False)
     real_sources = []
     calc_sources = []
     for t in my_times:
         alpha, delta = af.generate_observation_wrt_attitude(
             gaia.func_attitude(t))
         real_src_tmp = Source(str(t), np.degrees(alpha), np.degrees(delta),
                               0, 0, 0, 0)
         calc_src_tmp = Calc_source('calc_' + str(t), [t],
                                    real_src_tmp.get_parameters()[0:5],
                                    real_src_tmp.get_parameters()[5])
         real_sources.append(real_src_tmp)
         calc_sources.append(calc_src_tmp)
     # test if source and calc source are equal (as they should be)
     np.testing.assert_array_almost_equal(
         np.array(real_sources[0].get_parameters()[0:5]),
         calc_sources[0].s_params)
     # create Solver
     self.Solver = Agis(
         gaia,
         calc_sources,
         real_sources,
         attitude_splines=[gaia.s_w, gaia.s_x, gaia.s_y, gaia.s_z],
         spline_degree=spline_degree,
         attitude_regularisation_factor=1e-3)
Beispiel #22
0
def _get_sources(items, limit):
    return {
        item.name:
        Source(item.prob,
               RandomPrices(item.seed, item.initial_price, item.sigma, limit),
               item.seed)
        for item in items
    }
Beispiel #23
0
    def test_reduce(self, numeric_dataset):
        """Test reduce"""

        flow = Flow().from_source(Source(fin=numeric_dataset.open())).map(
            lambda x: [float(_) for _ in x]
        ).map(lambda x: sum(x))

        assert flow.reduce(lambda a, b: a + b).eval() == [145]
Beispiel #24
0
 def run2(self):
     trace('start')
     source = Source()
     translator = Translator(source)
     sink = Sink(translator)
     #exit()
     sink.run()
     trace('end')
Beispiel #25
0
 def __init__(self, source_qty, time_limits):
     self.create_csv_dir()
     self.boundaries = CityGenerator().get_general_boundaries()
     self.time_limits = time_limits
     self.init_tuples()
     for i in range(source_qty):
         util.display_loading("Création du graphe", i / source_qty)
         Source(self)
    def buildSourceList(self, titles, verbose=True):
        def wikiLink(link):
            try:
                page = wiki_api.page(link)
                if page.exists():
                    return {
                        'page': link,
                        'text': page.text,
                        'link': page.fullurl,
                        'categories': list(page.categories.keys())
                    }
            except:
                return None

        for current_title in titles:
            if not self.checkPageAdded(current_title):
                wiki_api = wikipediaapi.Wikipedia(
                    language='en',
                    extract_format=wikipediaapi.ExtractFormat.WIKI)
                page_name = wiki_api.page(current_title)
                if not page_name.exists():
                    print('Page {} does not exist.'.format(page_name))
                    return

                page_links = list(page_name.links.keys())
                print_description = "Links Scraped for page '{}'".format(
                    current_title)
                progress = tqdm(desc=print_description,
                                unit='',
                                total=len(page_links)) if verbose else None
                current_source = Source(page_name.title, page_name.text,
                                        page_name.fullurl,
                                        list(page_name.categories.keys()),
                                        page_name)

                # Parallelize the scraping, to speed it up (?)
                with concurrent.futures.ThreadPoolExecutor(
                        max_workers=4) as executor:
                    future_link = {
                        executor.submit(wikiLink, link): link
                        for link in page_links
                    }
                    for future in concurrent.futures.as_completed(future_link):
                        data = future.result()
                        current_source.append(data) if data else None
                        progress.update(1) if verbose else None
                progress.close() if verbose else None

                namespaces = ('Wikipedia', 'Special', 'Talk', 'LyricWiki', 'File', 'MediaWiki', 'Template', 'Help', 'User', \
                    'Category talk', 'Portal talk')
                current_source = current_source[
                    (len(current_source['text']) > 20)
                    & ~(current_source['page'].str.startswith(namespaces,
                                                              na=True))]
                current_source['categories'] = current_source.categories.apply(
                    lambda x: [y[9:] for y in x])
                current_source['topic'] = page_name
                print('Wikipedia pages scraped so far:', len(current_source))
Beispiel #27
0
    def setUp(self):
        super(TestHeaderInclusion, self).setUp()
        name = type(self).__name__

        f = Function(name="test_f")
        f_def = f.gen_definition()

        hdr = Header(name.lower() + ".h").add_type(f)
        hdr_content = """\
/* {path} */
#ifndef INCLUDE_{fname_upper}_H
#define INCLUDE_{fname_upper}_H

void test_f(void);
#endif /* INCLUDE_{fname_upper}_H */
""".format(path=hdr.path, fname_upper=name.upper())

        src1 = Source(name.lower() + ".c").add_type(f_def)
        src1_content = """\
/* {} */

void test_f(void) {{}}

""".format(src1.path)

        src2 = Source(name.lower() + "2.c").add_type(
            Function(
                name="func_a",
                body=BodyTree()(
                    Call(f_def)  # use function definition to Call
                )))
        src2_content = """\
/* {} */

#include "{}"

void func_a(void)
{{
    test_f();
}}

""".format(src2.path, hdr.path)

        self.files = [(hdr, hdr_content), (src1, src1_content),
                      (src2, src2_content)]
Beispiel #28
0
    def test_filter(self, string_dataset):
        """Test filter registering"""

        flow = Flow().from_source(Source(fin=string_dataset.open())).filter(
            lambda x: 'line' not in x
        )

        assert flow.chain[0].type == 'FLOW::FILTER'
        assert flow.batch(1)[0] == ['0', '1', '2', '3', '4']
Beispiel #29
0
 def setUp(self):
     self.absoluteTolerance = 1e-5
     self.relativeTolerance = 1e-4
     wavelength = 0.02
     theta = 60 * deg
     phi = 30 * deg
     pTEM = 1 / sqrt(2) * complexArray([1, 1j])
     reflectionLayer = Layer(er=2, ur=1)
     self.source = Source(wavelength, theta, phi, pTEM, reflectionLayer)
Beispiel #30
0
    def test_reload(self, numeric_dataset):
        """Test reloading"""

        flow = Flow().from_source(Source(fin=numeric_dataset.open())).map(
            lambda x: 1
        )

        assert flow.reduce(lambda a, b: a + b).eval() == [10]
        assert flow.reload().reduce(lambda a, b: a + b).eval() == [10]