当前位置: 首页>>代码示例>>Python>>正文


Python attrdict.AttrDict类代码示例

本文整理汇总了Python中attrdict.AttrDict的典型用法代码示例。如果您正苦于以下问题:Python AttrDict类的具体用法?Python AttrDict怎么用?Python AttrDict使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了AttrDict类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: BuildSurprise

def BuildSurprise(hist_times,t_before,base_rate,maxbin,surpmax,surpmin):
        
    # hist_times:         the array of spiketimes for each whisker and direction relative to stim
    # t_before & t_after: how long we want to compute the psths bins (all 1 msec)
    # base_rate:          rate of a 1ms bin of the blank psth
    # maxbin:             the number of binning sizes where we compute the surprise, from 1 to maxbin
    # blankw:             the blank whisker number (changes depending on the experiment)
    # surpmax:            up to what time we compute surprise (tipically 55ms)
    # nsizeth:            how many consecutive bins are required to be responsive (tipically 2)
    # surpmin:            is from the time we consider to look for a response (tipically over 5ms)
    
    # we save all in this variable as attr dictionary
    Surprise = dict()
    #-------------------------------------
    # here computing the surprise (from surpmin to surpmax in ms)
    SurpriseW = {}
   
    for w in np.arange(25):
        Surprisefixbin = {}  #here we store the 25 whiskers
        
        for binsize in np.arange(maxbin)+1:
            Surprisefixbin[binsize] = BuildSingleSurprise(hist_times[w],base_rate,binsize,surpmax,t_before)
        
        SurpriseW[w] = Surprisefixbin
            
    Surprise = AttrDict({'Data' : SurpriseW})
    Surprise.update({'logic_tree_data': '[whiskers][binsizes][direction][values] = 25x20x2x'+ str(surpmax-surpmin)})

    return Surprise    
开发者ID:matigoldin,项目名称:Expect_analysis,代码行数:29,代码来源:surp_functions.py

示例2: add_template_from_json

 def add_template_from_json(self, template, basename, version):
     new_tpl = AttrDict(template.copy())
     new_tpl.name = '{}_v{}'.format(basename, version)
     
     # copy old template directory
     tpl_dir = app.config['UPLOADED_TEMPLATES_DEST']
     src = os.path.join(tpl_dir, template.name)
     dst = os.path.join(tpl_dir, new_tpl.name)
     shutil.copytree(src, dst)
     #old_tpl = os.path.join(tpl_dir, 'template', 'template.xml')
     #if os.path.exists(old_tpl):
         #os.remove(old_tpl) # old xml is obsolete
     
     # genericize the template
     def visit(path, key, value):
         if key in set(['cr_date']):
             return False
         elif key in set(['id', 'template_id', 'type_id', 'attr_id']):
             return key, None            
         return key, value
     new_tpl = remap(dict(new_tpl), visit=visit)
     
     new_template = self.call('add_template', {'tmpl': new_tpl})
     
     return new_template
开发者ID:CentroDelAgua-Decisiones,项目名称:OpenAguaDSS,代码行数:25,代码来源:connection.py

示例3: search

    def search(self, title):
        log.debug("Searching IMDb for '{}'", title)
        results = self.imdb.search_for_title(title)

        print("Results:")
        for i, movie in enumerate(results):
            print("%s: %s (%s)" % (i, movie['title'], movie['year']))

        while True:
            choice = input('Select number or enter an alternate'
                           ' search term: [0-%s, 0 default] ' %
                           (len(results) - 1))
            try:
                choice = int(choice)
            except ValueError:
                if choice:
                    return self.search(choice)
                choice = 0

            try:
                result = results[choice]
            except IndexError:
                pass
            else:
                imdb_id = result['imdb_id']
                log.debug("Found IMDb item {}", imdb_id)
                movie = AttrDict(self.imdb.get_title(imdb_id))
                movie.credits = self.imdb.get_title_credits(imdb_id)['credits']
                movie.genres = self.imdb.get_title_genres(imdb_id)['genres']
                return ImdbResult(movie)
开发者ID:loveevelyn,项目名称:Pythonbits,代码行数:30,代码来源:imdb.py

示例4: parse_thread_page

def parse_thread_page(el: bs4.element.Tag) -> AttrDict:
    out = AttrDict()
    out.user = el.select('.postprofile dt')[0].text.strip()
    out.body_html = str(el.select('.content')[0]).strip()
    out.body_text = el.select('.content')[0].text.strip()
    out.date = el.select('.postbody .author')[0].text.strip()
    return out
开发者ID:davidgengenbach,项目名称:d120-forum-post-exporter,代码行数:7,代码来源:crawler.py

示例5: test_len

    def test_len(self):
        """
        Test that len works properly.
        """
        from attrdict import AttrDict

        # empty
        adict = AttrDict()
        self.assertEqual(len(adict), 0)

        # added via key
        adict['key'] = 1
        self.assertEqual(len(adict), 1)

        adict['key'] = 2
        self.assertEqual(len(adict), 1)

        # added via attribute
        adict.attribute = 3
        self.assertEqual(len(adict), 2)

        adict.key = 3
        self.assertEqual(len(adict), 2)

        # deleted
        del adict.key
        self.assertEqual(len(adict), 1)
开发者ID:donsignore,项目名称:AttrDict,代码行数:27,代码来源:tests.py

示例6: test_setattr

    def test_setattr(self):
        """
        Test that key-value pairs can be added/changes as attributes
        """
        from attrdict import AttrDict

        adict = AttrDict({'foo': 'bar'})

        adict.foo = 'baz'
        self.assertEqual(adict.foo, 'baz')
        self.assertEqual(adict['foo'], 'baz')

        adict.lorem = 'ipsum'
        self.assertEqual(adict.lorem, 'ipsum')
        self.assertEqual(adict['lorem'], 'ipsum')

        adict.alpha = {'beta': 1, 'bravo': 2}
        self.assertEqual(adict.alpha, {'beta': 1, 'bravo': 2})
        self.assertEqual(adict.alpha.beta, 1)
        self.assertEqual(adict['alpha'], {'beta': 1, 'bravo': 2})

        # with self.assertRaises(TypeError):
        try:
            adict._no = "Won't work"
        except TypeError:
            pass  # expected
        else:
            raise AssertionError("Exception not thrown")
开发者ID:donsignore,项目名称:AttrDict,代码行数:28,代码来源:tests.py

示例7: __init__

    def __init__(self, response):
        self.raw = response
        self.name = response["name"]
        self.version = response["version"]
        self.description = response["description"]
        self.preseeds = response["preseeds"]

        AttrDict.__init__(self)
开发者ID:vinodpanicker,项目名称:hubtools,代码行数:8,代码来源:appliances.py

示例8: test_pop_removes_attr

def test_pop_removes_attr():
    d = AttrDict(k=True)
    try:
        d.k
    except AttributeError:
        assert False, "AttributeError shouldn't be raised yet"
    d.pop('k')
    d.k
开发者ID:brainsik,项目名称:lab,代码行数:8,代码来源:tests.py

示例9: test_pop_removes_item

def test_pop_removes_item():
    d = AttrDict(k=True)
    try:
        d['k']
    except KeyError:
        assert False, "KeyError shouldn't be raised yet"
    d.pop('k')
    d['k']
开发者ID:brainsik,项目名称:lab,代码行数:8,代码来源:tests.py

示例10: BuildPSTH

def BuildPSTH(Stims, Spikes, sampling_freq, exp, meas):
    
    stimtimes = {}
    stim_samp = 1/.0009997575757
    # make an 'output dict'
    # the PSTH will be built on -tbefore:tafter
    PSTH_times = {}
    
    # Loop each neuron and get the spikes.
    for neuron in list(Spikes.keys()): 
        codename = 'exp'+ str(exp) + '_' + str(meas) + '_c' + str(neuron)
        psth = AttrDict({'clusnum': neuron,'exp' : int(exp) , 'meas': int(meas[1]) , 'shank': int(meas[3])})
        psth.update(AttrDict({'psth_counts': [] , 'psth_times': []}))
        
        histo= build_hist_dict()
        spikes = Spikes[neuron].spike_times*1000 #(want them in ms)
        
        #loop episodes and stims_per_episode, and populate the histograms
        for ep in np.arange(Stims.episodes)[:]:
            if ep<30:
                stims = 82
            else:
                stims = 28

            #print('Episode: ',ep)
            
            stims=8
            for se in np.arange(stims):#np.arange(Stims.stims_ep):
                #print('se     :',se)
                code = str(int(Stims.st_ctrl[ep][se]))
                c = str(Stims.st_logic.ctrl[code])
                                
                if code=='0':
                    t_after=500
                    start = Stims.st_times[ep][se]
                    if len(spikes[(start <= spikes) * (spikes <= start + t_after)])>0:
                        histo[c].extend(spikes[(start <= spikes) * (spikes <= start + t_after)]-start)
                        histo['Counts'][c] +=  len(spikes[(start <= spikes) * (spikes <= start + t_after)])
                else:
                    code = str(int(Stims.st_types[ep][se]))                                                
                    t = str(Stims.st_logic.types[code])
                
                    code = str(int(Stims.st_pad[ep][se]))
                    p = Stims.st_logic.pad[code]
                    
                    r = Stims.st_rep[ep][se]
                    i = Stims.st_isi[ep][se]
                    start = Stims.st_times[ep][se]
                              
                    t_after = 500*r
                    
                    if len(spikes[(start <= spikes) * (spikes <= start + t_after)])>0:
                        histo[c][t][p][r][i].extend(spikes[(start <= spikes) * (spikes <= start + t_after)]-start)
                        histo['Counts'][c][t][p][r][i]  += len((spikes[(start <= spikes) * (spikes <= start + t_after)]))
                                                       
        PSTH_times[codename] = histo
       
    return PSTH_times
开发者ID:matigoldin,项目名称:Expect_analysis,代码行数:58,代码来源:stim_loading.py

示例11: test_valid_name

    def test_valid_name(self):
        """
        Test that valid_name works.
        """
        from attrdict import AttrDict

        self.assertTrue(AttrDict._valid_name('valid'))
        self.assertFalse(AttrDict._valid_name('_invalid'))
        self.assertFalse(AttrDict._valid_name('get'))
开发者ID:donsignore,项目名称:AttrDict,代码行数:9,代码来源:tests.py

示例12: test_build

    def test_build(self):
        """
        Test that build works.
        """
        from attrdict import AttrDict

        self.assertTrue(isinstance(AttrDict._build({}), AttrDict))
        self.assertTrue(isinstance(AttrDict._build([]), list))
        self.assertTrue(isinstance(AttrDict._build(AttrDict()), AttrDict))
        self.assertTrue(isinstance(AttrDict._build(1), int))
开发者ID:donsignore,项目名称:AttrDict,代码行数:10,代码来源:tests.py

示例13: __init__

 def __init__(self, id, parent):
   """ Inits a new widget.
   The constructor should never be called directly. To add a sub-widgegt use
   _add_widget. To create a root widget see report.py
   """
   self.id = id
   self.parent = parent
   self.unique_counter = 0
   self.widgets = AttrDict()
   self.values = AttrDict()
   self.value_name_to_cache_key = {}
开发者ID:ericjsolis,项目名称:danapeerlab,代码行数:11,代码来源:widget.py

示例14: test_delattr

    def test_delattr(self):
        """
        Test that key-value pairs can be deleted as attributes.
        """
        from attrdict import AttrDict

        adict = AttrDict({'foo': 'bar', '_set': 'shadows', 'get': 'shadows'})

        del adict.foo

        # with self.assertRaises(AttributeError):
        try:
            adict.foo
        except AttributeError:
            pass  # expected
        else:
            raise AssertionError("Exception not thrown")

        # with self.assertRaises(KeyError):
        try:
            adict['foo']
        except KeyError:
            pass  # expected
        else:
            raise AssertionError("Exception not thrown")

        # with self.assertRaises(TypeError):
        try:
            del adict.lorem
        except TypeError:
            pass  # expected
        else:
            raise AssertionError("Exception not thrown")

        # with self.assertRaises(TypeError):
        try:
            del adict._set
        except TypeError:
            pass  # expected
        else:
            raise AssertionError("Exception not thrown")

        # with self.assertRaises(TypeError):
        try:
            del adict.get
        except TypeError:
            pass  # expected
        else:
            raise AssertionError("Exception not thrown")

        # make sure things weren't deleted
        adict._set
        self.assertEqual(adict.get('get'), 'shadows')
        self.assertEqual(adict, {'_set': 'shadows', 'get': 'shadows'})
开发者ID:donsignore,项目名称:AttrDict,代码行数:54,代码来源:tests.py

示例15: __init__

    def __init__(self, env='prod'):

        self.env = os.environ.get('NETKI_ENV', env)

        config_file = ConfigManager.find_config_file(self.env)

        if not config_file or not os.path.isfile(config_file):
            raise Exception('Cannot Find Config File app.%s.config' % self.env)

        log.info('Loading Configuration [ENV: %s | FILE: %s]' % (self.env, config_file))

        with open(config_file,'r') as file:
            config = ConfigParser.ConfigParser()
            config.readfp(file)

            pre_transform_dict = AttrDict(config._sections)
            for k,v in pre_transform_dict.iteritems():
                if isinstance(v, dict):
                    is_changed = False
                    for key,value in v.items():

                        # Convert Bools
                        if value.strip().lower() == 'true':
                            v[key] = True
                            is_changed = True
                            continue

                        if value.strip().lower() == 'false':
                            v[key] = False
                            is_changed = True
                            continue

                        # Convert Floats
                        try:
                            if '.' in value:
                                v[key] = float(value)
                                is_changed = True
                                continue
                        except ValueError:
                            pass

                        # Convert Ints
                        try:
                            v[key] = int(value)
                            is_changed = True
                            continue
                        except ValueError:
                            pass

                    if is_changed:
                        pre_transform_dict.__setattr__(k,v)

            self.config_dict = pre_transform_dict
开发者ID:bankonme,项目名称:wns-api-server,代码行数:53,代码来源:config.py


注:本文中的attrdict.AttrDict类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。