function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
list
def test_plot_fcc23(): assert os.path.exists("output/fcc23.png")
ghislainv/deforestprob
[ 97, 21, 97, 8, 1480589112 ]
def test_dataset(gstart): assert gstart["dataset"].iloc[0, 0] == 30.0
ghislainv/deforestprob
[ 97, 21, 97, 8, 1480589112 ]
def test_model_binomial_iCAR(gstart): p = np.array([0.34388896, 0.29002158, 0.51594223, 0.48436339, 0.60838453, 0.61257058, 0.55034979, 0.58819568, 0.51087469, 0.58819568, 0.64149789, 0.57400436, 0.59570952, 0.63212285, 0.566676, 0.62562204, 0.55379459, 0.15644965, 0.61284327, 0.36638686, 0.55439297, 0.57325744, 0.62562204, 0.17995823, 0.4930868, 0.54641479, 0.59782004, 0.48159526, 0.62882886, 0.59831051, 0.76245777, 0.74576097, 0.77356767, 0.73863295, 0.78188891, 0.75056545, 0.60775752, 0.64978574, 0.74654465, 0.77378323, 0.53994416, 0.75852715, 0.77754366, 0.60053684, 0.71543739, 0.74565542, 0.7555028, 0.44598923, 0.76401273, 0.75953027, 0.49027142, 0.69610182, 0.75679461, 0.78543649, 0.76863321, 0.6209473, 0.77653139, 0.76182804, 0.78169681, 0.58816002, 0.50453473, 0.77980428, 0.76084413, 0.73054832, 0.78289747, 0.71858934, 0.78362842, 0.74702923, 0.67357571, 0.78940242, 0.75358937, 0.66791346, 0.75602843, 0.42494845, 0.77653139, 0.60509306, 0.60846943, 0.76187008, 0.73278992, 0.72792572, 0.47661681, 0.59456417, 0.71894598, 0.6731302, 0.74964489, 0.77247818, 0.78289747, 0.74200682, 0.78940242, 0.78508877, 0.73153419, 0.65636031, 0.78607775, 0.59738545, 0.72596162, 0.78216462, 0.75078253, 0.77527468, 0.69907386, 0.71991522]) assert np.allclose(gstart["pred_icar"][0:100], p)
ghislainv/deforestprob
[ 97, 21, 97, 8, 1480589112 ]
def test_interpolate_rho(): assert os.path.exists("output/rho.tif")
ghislainv/deforestprob
[ 97, 21, 97, 8, 1480589112 ]
def test_countpix(gstart): assert gstart["fc"] == [83999.25, 79015.5]
ghislainv/deforestprob
[ 97, 21, 97, 8, 1480589112 ]
def test_plot_fcc123(): assert os.path.exists("output/fcc123.png")
ghislainv/deforestprob
[ 97, 21, 97, 8, 1480589112 ]
def test_plot_prob(): assert os.path.exists("output/prob.png")
ghislainv/deforestprob
[ 97, 21, 97, 8, 1480589112 ]
def __init__(self, name, identifier, oLeftToken, oRightToken, iLines): length.Rule.__init__(self, name=name, identifier=identifier) self.length = iLines self.oLeftToken = oLeftToken self.oRightToken = oRightToken
jeremiah-c-leary/vhdl-style-guide
[ 129, 31, 129, 57, 1499106283 ]
def is_periodic(bcs): "Check if boundary conditions are periodic" return all(isinstance(bc, PeriodicBC) for bc in bcs)
Juanlu001/CBC.Solve
[ 1, 7, 1, 1, 1427993651 ]
def timestep_range(T, dt): """Return a matching time step range for given end time and time step. Note that the time step may be adjusted so that it matches the given end time."""
Juanlu001/CBC.Solve
[ 1, 7, 1, 1, 1427993651 ]
def timestep_range_cfl(problem, mesh): """Return a sensible default time step and time step range based on an approximate CFL condition."""
Juanlu001/CBC.Solve
[ 1, 7, 1, 1, 1427993651 ]
def __init__(self, config): self.printer = config.get_printer() self.reactor = self.printer.get_reactor() self.default_prefix = config.getchoice('default_type', respond_types, 'echo') self.default_prefix = config.get('default_prefix', self.default_prefix) gcode = self.printer.lookup_object('gcode') gcode.register_command('M118', self.cmd_M118, True) gcode.register_command('RESPOND', self.cmd_RESPOND, True, desc=self.cmd_RESPOND_help)
KevinOConnor/klipper
[ 6307, 4329, 6307, 57, 1464190926 ]
def cmd_RESPOND(self, gcmd): respond_type = gcmd.get('TYPE', None) prefix = self.default_prefix if(respond_type != None): respond_type = respond_type.lower() if(respond_type in respond_types): prefix = respond_types[respond_type] else: raise gcmd.error( "RESPOND TYPE '%s' is invalid. Must be one" " of 'echo', 'command', or 'error'" % (respond_type,)) prefix = gcmd.get('PREFIX', prefix) msg = gcmd.get('MSG', '') gcmd.respond_raw("%s %s" % (prefix, msg))
KevinOConnor/klipper
[ 6307, 4329, 6307, 57, 1464190926 ]
def __init__(self, cpu_factory, registers): for group, register_list in registers.iteritems(): registers[group] = [Register(x) for x in register_list] super(GenericCpu, self).__init__(cpu_factory, registers)
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def architecture(cls): return Architecture.Generic
dholm/voidwalker
[ 129, 15, 129, 1, 1351059142 ]
def compute(files, output_filename, thresholds, n_samples=1024): thresholds = thresholds.astype(float) data_stream = event_stream(files) # data_stream = trigger.fill_event_type(data_stream, flag=8) data_stream = filters.filter_event_types(data_stream, flags=CameraEventType.INTERNAL) data_stream = baseline.fill_baseline_r0(data_stream, n_bins=n_samples) data_stream = filters.filter_missing_baseline(data_stream) data_stream = trigger.fill_trigger_patch(data_stream) data_stream = trigger.fill_trigger_input_7(data_stream) data_stream = trigger.fill_trigger_input_19(data_stream) output = compute_bias_curve( data_stream, thresholds=thresholds, ) rate, rate_error, cluster_rate, cluster_rate_error, thresholds, \ start_event_id, end_event_id, start_event_time, end_event_time = output with fitsio.FITS(output_filename, mode='rw', clobber=True) as f: f.write([np.array([start_event_id, end_event_id]), np.array([start_event_time, end_event_time])], extname='meta', names=['event_id', 'time']) f.write(thresholds, extname='threshold', compress='gzip') f.write([rate, rate_error], extname='camera', names=['rate', 'error'], compress='gzip') f.write([cluster_rate, cluster_rate_error], names=['rate', 'error'], extname='cluster', compress='gzip') return output
calispac/digicampipe
[ 3, 3, 3, 38, 1504526984 ]
def clean(self): """ Check for instances with null values in unique_together fields. """ from django.core.exceptions import ValidationError super(BaseModel, self).clean() for field_tuple in self._meta.unique_together[:]: unique_filter = {} unique_fields = [] null_found = False for field_name in field_tuple: field_value = getattr(self, field_name) if getattr(self, field_name) is None: unique_filter['%s__isnull' % field_name] = True null_found = True else: unique_filter['%s' % field_name] = field_value unique_fields.append(field_name) if null_found: unique_queryset = self.__class__.objects.filter( **unique_filter) if self.pk: unique_queryset = unique_queryset.exclude(pk=self.pk) if unique_queryset.exists(): msg = self.unique_error_message( self.__class__, tuple(unique_fields)) raise ValidationError(msg)
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def __str__(self): return self.nome
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def parents(self): if not self.parent: return [] parents = self.parent.parents + [self.parent, ] return parents
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def __str__(self): return self.descricao
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def __str__(self): if self.content_object: assert hasattr(self.content_object, 'epigrafe'), _( 'Modelos integrados aos Textos Articulados devem possuir a ' 'property "epigrafe"') return str(self.content_object.epigrafe) else: numero = self.numero if numero.isnumeric(): numero = '{0:,}'.format(int(self.numero)).replace(',', '.') return _('%(tipo)s nº %(numero)s, de %(data)s') % { 'tipo': self.tipo_ta, 'numero': numero, 'data': defaultfilters.date(self.data, "d \d\e F \d\e Y").lower()}
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def can_use_dynamic_editing(self, user): return not self.editing_locked and\ (not self.editable_only_by_owners and user.has_perm( 'compilacao.change_dispositivo_edicao_dinamica') or self.editable_only_by_owners and user in self.owners.all() and user.has_perm( 'compilacao.change_your_dispositivo_edicao_dinamica'))
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def has_edit_permission(self, request): if self.privacidade == STATUS_TA_PRIVATE: if request.user not in self.owners.all(): raise Http404() if not self.can_use_dynamic_editing(request.user): messages.error(request, _( 'Usuário sem permissão para edição.')) return False else: return True if self.privacidade == STATUS_TA_IMMUTABLE_RESTRICT: messages.error(request, _( 'A edição deste Texto Articulado está bloqueada. ' 'Este documento é imutável e de acesso é restrito.')) return False if self.privacidade == STATUS_TA_IMMUTABLE_PUBLIC: messages.error(request, _( 'A edição deste Texto Articulado está bloqueada. ' 'Este documento é imutável.')) return False if self.editing_locked and\ self.privacidade in (STATUS_TA_PUBLIC, STATUS_TA_EDITION) and\ not request.user.has_perm( 'compilacao.lock_unlock_textoarticulado'): messages.error(request, _( 'A edição deste Texto Articulado está bloqueada. ' 'É necessário acessar com usuário que possui ' 'permissão de desbloqueio.')) return False if not request.user.has_perm( 'compilacao.change_dispositivo_edicao_dinamica'): messages.error(request, _( 'Usuário sem permissão para edição.')) return False if self.editable_only_by_owners and\ request.user not in self.owners.all(): messages.error(request, _( 'Apenas usuários donos do Texto Articulado podem editá-lo.')) return False return True
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def update_or_create(cls, view_integracao, obj): map_fields = view_integracao.map_fields ta_values = getattr(view_integracao, 'ta_values', {}) related_object_type = ContentType.objects.get_for_model(obj) ta = TextoArticulado.objects.filter( object_id=obj.pk, content_type=related_object_type) ta_exists = bool(ta.exists()) if not ta_exists: tipo_ta = TipoTextoArticulado.objects.filter( content_type=related_object_type).first() ta = TextoArticulado() ta.tipo_ta = tipo_ta ta.content_object = obj ta.privacidade = ta_values.get('privacidade', STATUS_TA_EDITION) ta.editing_locked = ta_values.get('editing_locked', False) ta.editable_only_by_owners = ta_values.get( 'editable_only_by_owners', False) else: ta = ta[0] if not ta.data: ta.data = getattr(obj, map_fields['data'] if map_fields['data'] else 'xxx', timezone.now()) if not ta.data: ta.data = timezone.now() ta.ementa = getattr( obj, map_fields['ementa'] if map_fields['ementa'] else 'xxx', _( 'Integração com %s sem ementa.') % obj) ta.observacao = getattr( obj, map_fields['observacao'] if map_fields['observacao'] else 'xxx', '') now = timezone.now() ta.numero = getattr( obj, map_fields['numero'] if map_fields['numero'] else 'xxx', int('%s%s%s' % ( int(now.year), int(now.month), int(now.day)))) ta.ano = getattr(obj, map_fields['ano'] if map_fields['ano'] else 'xxx', now.year) ta.save() return ta
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def reagrupar_ordem_de_dispositivos(self): dpts = Dispositivo.objects.filter(ta=self) if not dpts.exists(): return ordem_max = dpts.last().ordem dpts.update(ordem=F('ordem') + ordem_max) dpts = Dispositivo.objects.filter( ta=self).values_list('pk', flat=True).order_by('ordem') count = 0 for d in dpts: count += Dispositivo.INTERVALO_ORDEM Dispositivo.objects.filter(pk=d).update(ordem=count)
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def update(dpk): Dispositivo.objects.filter(pk=dpk).update(ordem=count[0]) count[0] = count[0] + Dispositivo.INTERVALO_ORDEM filhos = Dispositivo.objects.filter( dispositivo_pai_id=dpk).values_list( 'pk', flat=True).order_by('ordem') for dpk in filhos: update(dpk)
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def __str__(self): return '%s: %s' % (self.sigla, self.nome)
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def __str__(self): return '%s: %s' % (self.sigla, self.nome)
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def __str__(self): return self.nome
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def permitido_variacao(self, base, perfil_pk=None): perfil = PerfilEstruturalTextoArticulado.objects.all() if not perfil_pk: perfil = perfil.filter(padrao=True) else: perfil = perfil.filter(pk=perfil_pk) if not perfil.exists(): return False perfil = perfil[0] while perfil: pp = self.possiveis_pais.filter(pai=base, perfil=perfil) if pp.exists(): if pp[0].permitir_variacao: return True perfil = perfil.parent return False
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def __str__(self): return '%s - %s' % ( self.pai.nome, self.filho_permitido.nome if self.filho_permitido else '')
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def __str__(self): return self.nome
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def __str__(self): return '%s: %s' % (self.sigla, self.nome)
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def __str__(self): return _('%s realizada em %s \n <small>%s</small>') % ( self.tipo_publicacao, defaultfilters.date(self.data, "d \d\e F \d\e Y"), self.ta)
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def ws_sync(self): return self.ta and self.ta.privacidade in ( STATUS_TA_IMMUTABLE_PUBLIC, STATUS_TA_PUBLIC)
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def save(self, force_insert=False, force_update=False, using=None, update_fields=None, clean=True): self.dispositivo_raiz = self.get_raiz() if self.dispositivo_raiz == self: self.dispositivo_raiz = None self.contagem_continua = self.tipo_dispositivo.contagem_continua """try: if self.texto: self.texto = self.texto.replace('\xa0', '') self.texto = str(BeautifulSoup(self.texto, "html.parser")) if self.texto_atualizador: self.texto_atualizador = str(BeautifulSoup( self.texto_atualizador, "html.parser")) except: pass""" return super().save( force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields, clean=clean)
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def get_raiz(self): dp = self while dp.dispositivo_pai is not None: dp = dp.dispositivo_pai return dp
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def get_profundidade(self): numero = self.get_numero_completo() for i in range(len(numero)): if numero[i] != 0 or i == 0: continue return i - 1 return i
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def transform_in_prior(self, profundidade=-1): numero = self.get_numero_completo() numero.reverse() if profundidade != -1: profundidade = len(numero) - profundidade - 1 for i in range(len(numero)): if not numero[i]: continue if i < profundidade: continue numero[i] -= 1 break numero.reverse() self.set_numero_completo(numero)
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def get_numero_completo(self): return [ self.dispositivo0, self.dispositivo1, self.dispositivo2, self.dispositivo3, self.dispositivo4, self.dispositivo5]
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def criar_espaco(self, espaco_a_criar, local=None): if local == 'json_add_next': proximo_bloco = Dispositivo.objects.filter( ordem__gt=self.ordem, nivel__lte=self.nivel, ta_id=self.ta_id).first() elif local == 'json_add_in': proximo_bloco = Dispositivo.objects.filter( ordem__gt=self.ordem, nivel__lte=self.nivel + 1, ta_id=self.ta_id).exclude(auto_inserido=True).first() elif local == 'json_add_in_with_auto': proximo_bloco = Dispositivo.objects.filter( ordem__gt=self.ordem, nivel__lte=self.nivel + 1, ta_id=self.ta_id).first() else: proximo_bloco = Dispositivo.objects.filter( ordem__gte=self.ordem, ta_id=self.ta_id).first() if proximo_bloco: ordem = proximo_bloco.ordem proximo_bloco = Dispositivo.objects.order_by('-ordem').filter( ordem__gte=ordem, ta_id=self.ta_id) proximo_bloco.update(ordem=F('ordem') + 1) proximo_bloco.update( ordem=F('ordem') + ( Dispositivo.INTERVALO_ORDEM * espaco_a_criar - 1)) else: # inserção no fim do ta ordem_max = Dispositivo.objects.order_by( 'ordem').filter( ta_id=self.ta_id).aggregate( Max('ordem')) if ordem_max['ordem__max'] is None: raise Exception( _('Não existem registros base neste Texto Articulado')) ordem = ordem_max['ordem__max'] + Dispositivo.INTERVALO_ORDEM return ordem
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def get_parents(self, ordem='desc'): dp = self p = [] while dp.dispositivo_pai: dp = dp.dispositivo_pai if ordem == 'desc': p.append(dp) else: p.insert(0, dp) return p
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def incrementar_irmaos(self, variacao=0, tipoadd=[], force=True): if not self.tipo_dispositivo.contagem_continua: irmaos = list(Dispositivo.objects.filter( Q(ordem__gt=self.ordem) | Q(dispositivo0=0), dispositivo_pai_id=self.dispositivo_pai_id, tipo_dispositivo_id=self.tipo_dispositivo.pk)) elif self.dispositivo_pai is None: irmaos = list(Dispositivo.objects.filter( ordem__gt=self.ordem, ta_id=self.ta_id, tipo_dispositivo_id=self.tipo_dispositivo.pk)) else: # contagem continua restrita a articulacao proxima_articulacao = self.select_next_root() if proxima_articulacao is None: irmaos = list(Dispositivo.objects.filter( ordem__gt=self.ordem, ta_id=self.ta_id, tipo_dispositivo_id=self.tipo_dispositivo.pk)) else: irmaos = list(Dispositivo.objects.filter( Q(ordem__gt=self.ordem) & Q(ordem__lt=proxima_articulacao.ordem), ta_id=self.ta_id, tipo_dispositivo_id=self.tipo_dispositivo.pk)) dp_profundidade = self.get_profundidade() if (not force and not variacao and len(irmaos) > 0 and irmaos[0].get_numero_completo() > self.get_numero_completo()): return irmaos_a_salvar = [] ultimo_irmao = None for irmao in irmaos: if irmao.ordem <= self.ordem or irmao.dispositivo0 == 0: irmaos_a_salvar.append(irmao) continue irmao_profundidade = irmao.get_profundidade() if irmao_profundidade < dp_profundidade: break if irmao.get_numero_completo() < self.get_numero_completo(): if irmao_profundidade > dp_profundidade: if ultimo_irmao is None: irmao.transform_in_next( dp_profundidade - irmao_profundidade) irmao.transform_in_next( irmao_profundidade - dp_profundidade) else: irmao.set_numero_completo( ultimo_irmao.get_numero_completo()) irmao.transform_in_next( irmao_profundidade - ultimo_irmao.get_profundidade()) ultimo_irmao = irmao else: irmao.transform_in_next() irmao.rotulo = irmao.rotulo_padrao() irmaos_a_salvar.append(irmao) elif irmao.get_numero_completo() == self.get_numero_completo(): irmao_numero = irmao.get_numero_completo() irmao_numero[dp_profundidade] += 1 irmao.set_numero_completo(irmao_numero) irmao.rotulo = irmao.rotulo_padrao() irmaos_a_salvar.append(irmao) else: if dp_profundidade < irmao_profundidade and \ dp_profundidade > 0 and \ self.get_numero_completo()[:dp_profundidade] >= \ irmao.get_numero_completo()[:dp_profundidade] and\ ultimo_irmao is None: break else: ultimo_irmao = irmao irmao_numero = irmao.get_numero_completo() irmao_numero[dp_profundidade] += 1 irmao.set_numero_completo(irmao_numero) irmao.rotulo = irmao.rotulo_padrao() irmaos_a_salvar.append(irmao) irmaos_a_salvar.reverse() for irmao in irmaos_a_salvar: if (irmao.dispositivo0 == 0 and irmao.ordem <= self.ordem) and variacao == 0: irmao.dispositivo0 = 1 irmao.rotulo = irmao.rotulo_padrao() self.dispositivo0 = 2 self.rotulo = self.rotulo_padrao() elif (irmao.dispositivo0 == 0 and irmao.ordem > self.ordem) and variacao == 0: irmao.dispositivo0 = 2 irmao.rotulo = irmao.rotulo_padrao() self.dispositivo0 = 1 self.rotulo = self.rotulo_padrao() irmao.clean() irmao.save()
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def select_next_root(self): return self.select_roots().filter(ordem__gt=self.ordem).first()
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def is_relative_auto_insert__obsoleto(self, perfil_pk=None): if self.dispositivo_pai is not None: # pp possiveis_pais if not perfil_pk: perfis = PerfilEstruturalTextoArticulado.objects.filter( padrao=True)[:1] if perfis.exists(): perfil_pk = perfis[0].pk pp = self.tipo_dispositivo.possiveis_pais.filter( pai=self.dispositivo_pai.tipo_dispositivo, perfil_id=perfil_pk) if pp.exists(): if pp[0].filho_de_insercao_automatica: return True return False
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def new_instance_based_on(dispositivo_base, tipo_base, base_alteracao=None): dp = Dispositivo() dp.tipo_dispositivo = tipo_base dp.set_numero_completo( dispositivo_base.get_numero_completo()) dp.nivel = dispositivo_base.nivel dp.texto = '' dp.visibilidade = True # dp.auto_inserido = dispositivo_base.auto_inserido dp.ta = dispositivo_base.ta dp.dispositivo_pai = dispositivo_base.dispositivo_pai dp.publicacao = dispositivo_base.publicacao b = base_alteracao if base_alteracao else dispositivo_base # teste de criação inversa de itens alterados por mesmo bloco dp.ta_publicado = b.ta_publicado dp.dispositivo_atualizador = b.dispositivo_atualizador if dp.ta_publicado: dp.ordem_bloco_atualizador = b.ordem_bloco_atualizador + \ Dispositivo.INTERVALO_ORDEM dp.dispositivo_vigencia = dispositivo_base.dispositivo_vigencia if dp.dispositivo_vigencia: dp.inicio_eficacia = dp.dispositivo_vigencia.inicio_eficacia dp.inicio_vigencia = dp.dispositivo_vigencia.inicio_vigencia dp.fim_eficacia = dp.dispositivo_vigencia.fim_eficacia dp.fim_vigencia = dp.dispositivo_vigencia.fim_vigencia else: dp.inicio_eficacia = dispositivo_base.inicio_eficacia dp.inicio_vigencia = dispositivo_base.inicio_vigencia dp.fim_eficacia = dispositivo_base.fim_eficacia dp.fim_vigencia = dispositivo_base.fim_vigencia dp.ordem = dispositivo_base.ordem return dp
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def set_numero_for_add_in(dispositivo_base, dispositivo, tipo_base): if tipo_base.contagem_continua: raiz = dispositivo_base.get_raiz() disps = Dispositivo.objects.order_by('-ordem').filter( tipo_dispositivo_id=tipo_base.pk, ordem__lte=dispositivo_base.ordem, ordem__gt=raiz.ordem, ta_id=dispositivo_base.ta_id)[:1] if disps.exists(): dispositivo.set_numero_completo( disps[0].get_numero_completo()) # dispositivo.transform_in_next() else: dispositivo.set_numero_completo([0, 0, 0, 0, 0, 0, ]) else: if ';' in tipo_base.rotulo_prefixo_texto: if dispositivo != dispositivo_base: irmaos_mesmo_tipo = Dispositivo.objects.filter( tipo_dispositivo=tipo_base, dispositivo_pai=dispositivo_base) dispositivo.set_numero_completo([ 1 if irmaos_mesmo_tipo.exists() else 0, 0, 0, 0, 0, 0, ]) else: dispositivo.set_numero_completo([0, 0, 0, 0, 0, 0, ]) else: dispositivo.set_numero_completo([1, 0, 0, 0, 0, 0, ])
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def __str__(self): return _('Vide %s') % self.texto
interlegis/sapl
[ 74, 74, 74, 294, 1435330918 ]
def ftrace(func): """Decorator used for marking the beginning and end of function calls. Automatically indents nested calls. """ def w(*args, **kargs): global __ftraceDepth pfx = " " * __ftraceDepth print(pfx + func.__name__ + " start") __ftraceDepth += 1 try: rv = func(*args, **kargs) finally: __ftraceDepth -= 1 print(pfx + func.__name__ + " done") return rv return w
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def __init__(self): self.count = 0 self.stack = []
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def stop(self): sys.settrace(None)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def frameInfo(self, fr): filename = fr.f_code.co_filename funcname = fr.f_code.co_name lineno = fr.f_lineno callfr = sys._getframe(3) callline = "%s %d" % (callfr.f_code.co_name, callfr.f_lineno) args, _, _, value_dict = inspect.getargvalues(fr) if len(args) and args[0] == 'self': instance = value_dict.get('self', None) if instance is not None: cls = getattr(instance, '__class__', None) if cls is not None: funcname = cls.__name__ + "." + funcname return "%s: %s %s: %s" % (callline, filename, lineno, funcname)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def w(*args, **kwds): try: func(*args, **kwds) except: printExc('Ignored exception:')
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def getExc(indent=4, prefix='| ', skip=1): lines = formatException(*sys.exc_info(), skip=skip) lines2 = [] for l in lines: lines2.extend(l.strip('\n').split('\n')) lines3 = [" "*indent + prefix + l for l in lines2] return '\n'.join(lines3)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def printTrace(msg='', indent=4, prefix='|'): """Print an error message followed by an indented stack trace""" trace = backtrace(1) #exc = getExc(indent, prefix + ' ') print("[%s] %s\n" % (time.strftime("%H:%M:%S"), msg)) print(" "*indent + prefix + '='*30 + '>>') for line in trace.split('\n'): print(" "*indent + prefix + " " + line) print(" "*indent + prefix + '='*30 + '<<')
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def backtrace(skip=0): return ''.join(traceback.format_stack()[:-(skip+1)])
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def printException(exctype, value, traceback): """Print an exception with its full traceback.
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def listObjs(regex='Q', typ=None): """List all objects managed by python gc with class name matching regex. Finds 'Q...' classes by default.""" if typ is not None: return [x for x in gc.get_objects() if isinstance(x, typ)] else: return [x for x in gc.get_objects() if re.match(regex, type(x).__name__)]
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def findRefPath(startObj, endObj, maxLen=8, restart=True, seen={}, path=None, ignore=None): """Determine all paths of object references from startObj to endObj""" refs = [] if path is None: path = [endObj] if ignore is None: ignore = {} ignore[id(sys._getframe())] = None ignore[id(path)] = None ignore[id(seen)] = None prefix = " "*(8-maxLen) #print prefix + str(map(type, path)) prefix += " " if restart: #gc.collect() seen.clear() gc.collect() newRefs = [r for r in gc.get_referrers(endObj) if id(r) not in ignore] ignore[id(newRefs)] = None #fo = allFrameObjs() #newRefs = [] #for r in gc.get_referrers(endObj): #try: #if r not in fo: #newRefs.append(r) #except: #newRefs.append(r)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def objString(obj): """Return a short but descriptive string for any object""" try: if type(obj) in [int, float]: return str(obj) elif isinstance(obj, dict): if len(obj) > 5: return "<dict {%s,...}>" % (",".join(list(obj.keys())[:5])) else: return "<dict {%s}>" % (",".join(list(obj.keys()))) elif isinstance(obj, str): if len(obj) > 50: return '"%s..."' % obj[:50] else: return obj[:] elif isinstance(obj, ndarray): return "<ndarray %s %s>" % (str(obj.dtype), str(obj.shape)) elif hasattr(obj, '__len__'): if len(obj) > 5: return "<%s [%s,...]>" % (type(obj).__name__, ",".join([type(o).__name__ for o in obj[:5]])) else: return "<%s [%s]>" % (type(obj).__name__, ",".join([type(o).__name__ for o in obj])) else: return "<%s %s>" % (type(obj).__name__, obj.__class__.__name__) except: return str(type(obj))
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def objectSize(obj, ignore=None, verbose=False, depth=0, recursive=False): """Guess how much memory an object is using""" ignoreTypes = ['MethodType', 'UnboundMethodType', 'BuiltinMethodType', 'FunctionType', 'BuiltinFunctionType'] ignoreTypes = [getattr(types, key) for key in ignoreTypes if hasattr(types, key)] ignoreRegex = re.compile('(method-wrapper|Flag|ItemChange|Option|Mode)')
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def __init__(self): self.objs = weakref.WeakValueDictionary() self.allNames = []
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def add(self, obj, name): self.objs[name] = obj self.allNames.append(name)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def __setitem__(self, name, obj): self.add(obj, name)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def check(self): """Print a list of all watched objects and whether they have been collected.""" gc.collect() dead = self.allNames[:] alive = [] for k in self.objs: dead.remove(k) alive.append(k) print("Deleted objects:", dead) print("Live objects:", alive)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def __getitem__(self, item): return self.objs[item]
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def function(...): profiler = Profiler() ... do stuff ... profiler('did stuff') ... do other stuff ... profiler('did other stuff') # profiler is garbage-collected and flushed at function end
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def __init__(self, *args, **kwds): pass
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def finish(self): pass
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def __new__(cls, msg=None, disabled='env', delayed=True): """Optionally create a new profiler based on caller's qualname. """ if disabled is True or (disabled == 'env' and len(cls._profilers) == 0): return cls._disabledProfiler
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def __call__(self, msg=None): """Register or print a new message with timing information. """ if self.disable: return if msg is None: msg = str(self._markCount) self._markCount += 1 newTime = ptime.time() self._newMsg(" %s: %0.4f ms", msg, (newTime - self._lastTime) * 1000) self._lastTime = newTime
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def mark(self, msg=None): self(msg)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def __del__(self): self.finish()
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def finish(self, msg=None): """Add a final message; flush the message list if no parent profiler. """ if self._finished or self.disable: return self._finished = True if msg is not None: self(msg) self._newMsg("< Exiting %s, total time: %0.4f ms", self._name, (ptime.time() - self._firstTime) * 1000) type(self)._depth -= 1 if self._depth < 1: self.flush()
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def flush(self): if self._msgs: print("\n".join([m[0]%m[1] for m in self._msgs])) type(self)._msgs = []
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def _getr(slist, olist, first=True): i = 0 for e in slist:
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def get_all_objects(): """Return a list of all live Python objects (excluding int and long), not including the list itself.""" gc.collect() gcl = gc.get_objects() olist = {} _getr(gcl, olist)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def lookup(oid, objects=None): """Return an object given its ID, if it exists.""" if objects is None: objects = get_all_objects() return objects[oid]
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def __init__(self): self.startRefs = {} ## list of objects that exist when the tracker is initialized {oid: weakref} ## (If it is not possible to weakref the object, then the value is None) self.startCount = {} self.newRefs = {} ## list of objects that have been created since initialization self.persistentRefs = {} ## list of objects considered 'persistent' when the last diff() was called self.objTypes = {}
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def findNew(self, regex): """Return all objects matching regex that were considered 'new' when the last diff() was run.""" return self.findTypes(self.newRefs, regex)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def findPersistent(self, regex): """Return all objects matching regex that were considered 'persistent' when the last diff() was run.""" return self.findTypes(self.persistentRefs, regex)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def start(self): """ Remember the current set of objects as the comparison for all future calls to diff() Called automatically on init, but can be called manually as well. """ refs, count, objs = self.collect() for r in self.startRefs: self.forgetRef(self.startRefs[r]) self.startRefs.clear() self.startRefs.update(refs) for r in refs: self.rememberRef(r) self.startCount.clear() self.startCount.update(count) #self.newRefs.clear() #self.newRefs.update(refs)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def __del__(self): self.startRefs.clear() self.startCount.clear() self.newRefs.clear() self.persistentRefs.clear()
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def isObjVar(cls, o): return type(o) is cls or id(o) in cls.allObjs
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def collect(self): print("Collecting list of all objects...") gc.collect() objs = get_all_objects() frame = sys._getframe() del objs[id(frame)] ## ignore the current frame del objs[id(frame.f_code)]
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def forgetRef(self, ref): if ref is not None: del ObjTracker.allObjs[id(ref)]
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def rememberRef(self, ref): ## Record the address of the weakref object so it is not included in future object counts. if ref is not None: ObjTracker.allObjs[id(ref)] = None
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def lookup(self, oid, ref, objs=None): if ref is None or ref() is None: try: obj = lookup(oid, objects=objs) except: obj = None else: obj = ref() return obj
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def report(self, refs, allobjs=None, showIDs=False): if allobjs is None: allobjs = get_all_objects()
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def findTypes(self, refs, regex): allObjs = get_all_objects() ids = {} objs = [] r = re.compile(regex) for k in refs: if r.search(self.objTypes[k]): objs.append(self.lookup(k, refs[k], allObjs)) return objs
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def describeObj(obj, depth=4, path=None, ignore=None): """ Trace all reference paths backward, printing a list of different ways this object can be accessed. Attempts to answer the question "who has a reference to this object" """ if path is None: path = [obj] if ignore is None: ignore = {} ## holds IDs of objects used within the function. ignore[id(sys._getframe())] = None ignore[id(path)] = None gc.collect() refs = gc.get_referrers(obj) ignore[id(refs)] = None printed=False for ref in refs: if id(ref) in ignore: continue if id(ref) in list(map(id, path)): print("Cyclic reference: " + refPathString([ref]+path)) printed = True continue newPath = [ref]+path if len(newPath) >= depth: refStr = refPathString(newPath) if '[_]' not in refStr: ## ignore '_' references generated by the interactive shell print(refStr) printed = True else: describeObj(ref, depth, newPath, ignore) printed = True if not printed: print("Dead end: " + refPathString(path))
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def typeStr(obj): """Create a more useful type string by making <instance> types report their class.""" typ = type(obj) if typ == getattr(types, 'InstanceType', None): return "<instance of %s>" % obj.__class__.__name__ else: return str(typ)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def searchRefs(obj, *args): """Pseudo-interactive function for tracing references backward. **Arguments:**
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def slen(o): if hasattr(o, '__len__'): return len(o) else: return None
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def allFrameObjs(): """Return list of frame objects in current stack. Useful if you want to ignore these objects in refernece searches""" f = sys._getframe() objs = [] while f is not None: objs.append(f) objs.append(f.f_code) #objs.append(f.f_locals) #objs.append(f.f_globals) #objs.append(f.f_builtins) f = f.f_back return objs
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def findObj(regex): """Return a list of objects whose typeStr matches regex""" allObjs = get_all_objects() objs = [] r = re.compile(regex) for i in allObjs: obj = allObjs[i] if r.search(typeStr(obj)): objs.append(obj) return objs
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def listRedundantModules(): """List modules that have been imported more than once via different paths.""" mods = {} for name, mod in sys.modules.items(): if not hasattr(mod, '__file__'): continue mfile = os.path.abspath(mod.__file__) if mfile[-1] == 'c': mfile = mfile[:-1] if mfile in mods: print("module at %s has 2 names: %s, %s" % (mfile, name, mods[mfile])) else: mods[mfile] = name
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def walkQObjectTree(obj, counts=None, verbose=False, depth=0): """ Walk through a tree of QObjects, doing nothing to them. The purpose of this function is to find dead objects and generate a crash immediately rather than stumbling upon them later. Prints a count of the objects encountered, for fun. (or is it?) """
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def qObjectReport(verbose=False): """Generate a report counting all QObjects and their types""" global qObjCache count = {} for obj in findObj('PyQt'): if isinstance(obj, QtCore.QObject): oid = id(obj) if oid not in QObjCache: QObjCache[oid] = typeStr(obj) + " " + obj.objectName() try: QObjCache[oid] += " " + obj.parent().objectName() QObjCache[oid] += " " + obj.text() except: pass print("check obj", oid, str(QObjCache[oid])) if obj.parent() is None: walkQObjectTree(obj, count, verbose)
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]
def __init__(self): self.stdout = sys.stdout sys.stdout = self
ArteliaTelemac/PostTelemac
[ 16, 7, 16, 6, 1450199695 ]