text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConfirmarArribo(self, numero_carta_de_porte, numero_ctg, cuit_transportista, peso_neto_carga, consumo_propio, establecimiento=None, cuit_chofer=None, **kwargs): "Confirma arribo CTG" ret = self.client.confirmarArribo(request=dict( auth={ 'token': self.Token, 'sign': self.Sign, 'cuitRepresentado': self.Cuit, }, datosConfirmarArribo=dict( cartaPorte=numero_carta_de_porte, ctg=numero_ctg, cuitTransportista=cuit_transportista, cuitChofer=cuit_chofer, cantKilosCartaPorte=peso_neto_carga, consumoPropio=consumo_propio, establecimiento=establecimiento, )))['response'] self.__analizar_errores(ret) datos = ret.get('datosResponse') if datos: self.CartaPorte = str(datos['cartaPorte']) self.NumeroCTG = str(datos['ctg']) self.FechaHora = str(datos['fechaHora']) self.CodigoTransaccion = str(datos['codigoOperacion']) self.Observaciones = "" return self.CodigoTransaccion
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConfirmarDefinitivo(self, numero_carta_de_porte, numero_ctg, establecimiento=None, codigo_cosecha=None, peso_neto_carga=None, **kwargs): "Confirma arribo definitivo CTG" ret = self.client.confirmarDefinitivo(request=dict( auth={ 'token': self.Token, 'sign': self.Sign, 'cuitRepresentado': self.Cuit, }, datosConfirmarDefinitivo=dict( cartaPorte=numero_carta_de_porte, ctg=numero_ctg, establecimiento=establecimiento, codigoCosecha=codigo_cosecha, pesoNeto=peso_neto_carga, )))['response'] self.__analizar_errores(ret) datos = ret.get('datosResponse') if datos: self.CartaPorte = str(datos['cartaPorte']) self.NumeroCTG = str(datos['ctg']) self.FechaHora = str(datos['fechaHora']) self.CodigoTransaccion = str(datos.get('codigoOperacion', "")) self.Observaciones = "" return self.CodigoTransaccion
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def RegresarAOrigenCTGRechazado(self, numero_carta_de_porte, numero_ctg, km_a_recorrer=None, **kwargs): "Al consultar los CTGs rechazados se puede Regresar a Origen" ret = self.client.regresarAOrigenCTGRechazado(request=dict( auth={ 'token': self.Token, 'sign': self.Sign, 'cuitRepresentado': self.Cuit, }, datosRegresarAOrigenCTGRechazado=dict( cartaPorte=numero_carta_de_porte, ctg=numero_ctg, kmARecorrer=km_a_recorrer, )))['response'] self.__analizar_errores(ret) datos = ret.get('datosResponse') if datos: self.CartaPorte = str(datos['cartaPorte']) self.NumeroCTG = str(datos['ctg']) self.FechaHora = str(datos['fechaHora']) self.CodigoTransaccion = str(datos['codigoOperacion']) self.Observaciones = "" return self.CodigoTransaccion
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarCTGActivosPorPatente(self, patente="ZZZ999"): "Consulta de CTGs activos por patente" ret = self.client.consultarCTGActivosPorPatente(request=dict( auth={ 'token': self.Token, 'sign': self.Sign, 'cuitRepresentado': self.Cuit, }, patente=patente, ))['response'] self.__analizar_errores(ret) datos = ret.get('arrayConsultarCTGActivosPorPatenteResponse') if datos: self.DatosCTG = datos self.LeerDatosCTG(pop=False) return True else: self.DatosCTG = [] return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarLiquidacionesPorContrato(self, nro_contrato=None, cuit_comprador=None, cuit_vendedor=None, cuit_corredor=None, cod_grano=None, **kwargs): "Obtener los COE de liquidaciones relacionadas a un contrato" ret = self.client.liquidacionPorContratoConsultar( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, nroContrato=nro_contrato, cuitComprador=cuit_comprador, cuitVendedor=cuit_vendedor, cuitCorredor=cuit_corredor, codGrano=cod_grano, ) ret = ret['liqPorContratoCons'] self.__analizar_errores(ret) if 'coeRelacionados' in ret: # analizo la respuesta = [{'coe': "...."}] self.DatosLiquidacion = sorted(ret['coeRelacionados']) # establezco el primer COE self.LeerDatosLiquidacion() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarCertificacion(self, pto_emision=None, nro_orden=None, coe=None, pdf=None): "Consulta una certificacion por No de orden o COE" if coe: ret = self.client.cgConsultarXCoe( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, coe=coe, pdf='S' if pdf else 'N', ) else: ret = self.client.cgConsultarXNroOrden( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, ptoEmision=pto_emision, nroOrden=nro_orden, ) ret = ret['oReturn'] self.__analizar_errores(ret) if 'autorizacion' in ret: self.AnalizarAutorizarCertificadoResp(ret) # guardo el PDF si se indico archivo y vino en la respuesta: if pdf and 'pdf' in ret: open(pdf, "wb").write(ret['pdf']) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarTipoDeduccion(self, sep="||"): "Consulta de tipos de Deducciones" ret = self.client.tipoDeduccionConsultar( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, )['tipoDeduccionReturn'] self.__analizar_errores(ret) array = ret.get('tiposDeduccion', []) return [("%s %%s %s %%s %s" % (sep, sep, sep)) % (it['codigoDescripcion']['codigo'], it['codigoDescripcion']['descripcion']) for it in array]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarTipoRetencion(self, sep="||"): "Consulta de tipos de Retenciones." ret = self.client.tipoRetencionConsultar( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, )['tipoRetencionReturn'] self.__analizar_errores(ret) array = ret.get('tiposRetencion', []) return [("%s %%s %s %%s %s" % (sep, sep, sep)) % (it['codigoDescripcion']['codigo'], it['codigoDescripcion']['descripcion']) for it in array]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarPuerto(self, sep="||"): "Consulta de Puertos habilitados" ret = self.client.puertoConsultar( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, )['puertoReturn'] self.__analizar_errores(ret) array = ret.get('puertos', []) return [("%s %%s %s %%s %s" % (sep, sep, sep)) % (it['codigoDescripcion']['codigo'], it['codigoDescripcion']['descripcion']) for it in array]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarTipoActividad(self, sep="||"): "Consulta de Tipos de Actividad." ret = self.client.tipoActividadConsultar( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, )['tipoActividadReturn'] self.__analizar_errores(ret) array = ret.get('tiposActividad', []) return [("%s %%s %s %%s %s" % (sep, sep, sep)) % (it['codigoDescripcion']['codigo'], it['codigoDescripcion']['descripcion']) for it in array]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarTipoActividadRepresentado(self, sep="||"): "Consulta de Tipos de Actividad inscripta en el RUOCA." try: ret = self.client.tipoActividadRepresentadoConsultar( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, )['tipoActividadReturn'] self.__analizar_errores(ret) array = ret.get('tiposActividad', []) self.Excepcion = self.Traceback = "" return [("%s %%s %s %%s %s" % (sep, sep, sep)) % (it['codigoDescripcion']['codigo'], it['codigoDescripcion']['descripcion']) for it in array] except Exception: ex = utils.exception_info() self.Excepcion = ex['msg'] self.Traceback = ex['tb'] if sep: return ["ERROR"]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarProvincias(self, sep="||"): "Consulta las provincias habilitadas" ret = self.client.provinciasConsultar( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, )['provinciasReturn'] self.__analizar_errores(ret) array = ret.get('provincias', []) if sep is None: return dict([(int(it['codigoDescripcion']['codigo']), it['codigoDescripcion']['descripcion']) for it in array]) else: return [("%s %%s %s %%s %s" % (sep, sep, sep)) % (it['codigoDescripcion']['codigo'], it['codigoDescripcion']['descripcion']) for it in array]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def CargarFormatoPDF(self, archivo="liquidacion_form_c1116b_wslpg.csv"): "Cargo el formato de campos a generar desde una planilla CSV" # si no encuentro archivo, lo busco en el directorio predeterminado: if not os.path.exists(archivo): archivo = os.path.join(self.InstallDir, "plantillas", os.path.basename(archivo)) if DEBUG: print "abriendo archivo ", archivo # inicializo la lista de los elementos: self.elements = [] for lno, linea in enumerate(open(archivo.encode('latin1')).readlines()): if DEBUG: print "procesando linea ", lno, linea args = [] for i,v in enumerate(linea.split(";")): if not v.startswith("'"): v = v.replace(",",".") else: v = v#.decode('latin1') if v.strip()=='': v = None else: v = eval(v.strip()) args.append(v) # corrijo path relativo para las imágenes: if args[1] == 'I': if not os.path.exists(args[14]): args[14] = os.path.join(self.InstallDir, "plantillas", os.path.basename(args[14])) if DEBUG: print "NUEVO PATH:", args[14] self.AgregarCampoPDF(*args) self.AgregarCampoPDF("anulado", 'T', 150, 250, 0, 0, size=70, rotate=45, foreground=0x808080, priority=-1) if HOMO: self.AgregarCampoPDF("homo", 'T', 100, 250, 0, 0, size=70, rotate=45, foreground=0x808080, priority=-1) # cargo los elementos en la plantilla self.template.load_elements(self.elements) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def AgregarCampoPDF(self, nombre, tipo, x1, y1, x2, y2, font="Arial", size=12, bold=False, italic=False, underline=False, foreground= 0x000000, background=0xFFFFFF, align="L", text="", priority=0, **kwargs): "Agrego un campo a la plantilla" # convierto colores de string (en hexadecimal) if isinstance(foreground, basestring): foreground = int(foreground, 16) if isinstance(background, basestring): background = int(background, 16) if isinstance(text, unicode): text = text.encode("latin1") field = { 'name': nombre, 'type': tipo, 'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2, 'font': font, 'size': size, 'bold': bold, 'italic': italic, 'underline': underline, 'foreground': foreground, 'background': background, 'align': align, 'text': text, 'priority': priority} field.update(kwargs) self.elements.append(field) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def GenerarPDF(self, archivo="", dest="F"): "Generar archivo de salida en formato PDF" try: self.template.render(archivo, dest=dest) return True except Exception, e: self.Excepcion = str(e) return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarContribuyentes(self, fecha_desde, fecha_hasta, cuit_contribuyente): "Realiza la consulta remota a ARBA, estableciendo los resultados" self.limpiar() try: self.xml = SimpleXMLElement(XML_ENTRADA_BASE) self.xml.fechaDesde = fecha_desde self.xml.fechaHasta = fecha_hasta self.xml.contribuyentes.contribuyente.cuitContribuyente = cuit_contribuyente xml = self.xml.as_xml() self.CodigoHash = md5.md5(xml).hexdigest() nombre = "DFEServicioConsulta_%s.xml" % self.CodigoHash # guardo el xml en el archivo a enviar y luego lo re-abro: archivo = open(os.path.join(tempfile.gettempdir(), nombre), "w") archivo.write(xml) archivo.close() archivo = open(os.path.join(tempfile.gettempdir(), nombre), "r") if not self.testing: response = self.client(user=self.Usuario, password=self.Password, file=archivo) else: response = open(self.testing).read() self.XmlResponse = response self.xml = SimpleXMLElement(response) if 'tipoError' in self.xml: self.TipoError = str(self.xml.tipoError) self.CodigoError = str(self.xml.codigoError) self.MensajeError = str(self.xml.mensajeError).decode('latin1').encode("ascii", "replace") if 'numeroComprobante' in self.xml: self.NumeroComprobante = str(self.xml.numeroComprobante) self.CantidadContribuyentes = int(self.xml.cantidadContribuyentes) if 'contribuyentes' in self.xml: for contrib in self.xml.contribuyente: c = { 'CuitContribuytente': str(contrib.cuitContribuyente), 'AlicuotaPercepcion': str(contrib.alicuotaPercepcion), 'AlicuotaRetencion': str(contrib.alicuotaRetencion), 'GrupoPercepcion': str(contrib.grupoPercepcion), 'GrupoRetencion': str(contrib.grupoRetencion), 'Errores': [], } self.contribuyentes.append(c) # establecer valores del primer contrib (sin eliminarlo) self.LeerContribuyente(pop=False) return True except Exception, e: ex = traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback) self.Traceback = ''.join(ex) try: self.Excepcion = traceback.format_exception_only( sys.exc_type, sys.exc_value)[0] except: self.Excepcion = u"<no disponible>" return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def AgregarReceptor(self, cuit, iibb, nro_socio, nro_fet, **kwargs): "Agrego un receptor a la liq." rcpt = dict(cuit=cuit, iibb=iibb, nroSocio=nro_socio, nroFET=nro_fet) self.solicitud['receptor'] = rcpt return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def AgregarPrecioClase(self, clase_tabaco, precio, total_kilos=None, total_fardos=None, **kwargs): "Agrego un PrecioClase a la liq." precioclase = dict(claseTabaco=clase_tabaco, precio=precio, totalKilos=total_kilos, totalFardos=total_fardos) self.solicitud['precioClase'].append(precioclase) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarVariedadesClasesTabaco(self, sep="||"): "Retorna un listado de variedades y clases de tabaco" # El listado es una estructura anidada (varias clases por variedad) #import dbg; dbg.set_trace() ret = self.client.consultarVariedadesClasesTabaco( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, )['respuesta'] self.__analizar_errores(ret) self.XmlResponse = self.client.xml_response array = ret.get('variedad', []) if sep is None: # sin separador, devuelve un diccionario con clave cod_variadedad # y valor: {"descripcion": ds_variedad, "clases": lista_clases} # siendo lista_clases = [{'codigo': ..., 'descripcion': ...}] return dict([(it['codigo'], {'descripcion': it['descripcion'], 'clases': it['clase']}) for it in array]) else: # con separador, devuelve una lista de strings: # || cod.variedad || desc.variedad || desc.clase || cod.clase || ret = [] for it in array: for clase in it['clase']: ret.append( ("%s %%s %s %%s %s %%s %s %%s %s" % (sep, sep, sep, sep, sep)) % (it['codigo'], it['descripcion'], clase['descripcion'], clase['codigo']) ) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def exception_info(current_filename=None, index=-1): "Analizar el traceback y armar un dict con la info amigable user-friendly" # guardo el traceback original (por si hay una excepción): info = sys.exc_info() # exc_type, exc_value, exc_traceback # importante: no usar unpacking porque puede causar memory leak if not current_filename: # genero un call stack para ver quien me llamó y limitar la traza: # advertencia: esto es necesario ya que en py2exe no tengo __file__ try: raise ZeroDivisionError except ZeroDivisionError: f = sys.exc_info()[2].tb_frame.f_back current_filename = os.path.normpath(os.path.abspath(f.f_code.co_filename)) # extraer la última traza del archivo solicitado: # (útil para no alargar demasiado la traza con lineas de las librerías) ret = {'filename': "", 'lineno': 0, 'function_name': "", 'code': ""} try: for (filename, lineno, fn, text) in traceback.extract_tb(info[2]): if os.path.normpath(os.path.abspath(filename)) == current_filename: ret = {'filename': filename, 'lineno': lineno, 'function_name': fn, 'code': text} except Exception, e: pass # obtengo el mensaje de excepcion tal cual lo formatea python: # (para evitar errores de encoding) try: ret['msg'] = traceback.format_exception_only(*info[0:2])[0] except: ret['msg'] = '<no disponible>' # obtener el nombre de la excepcion (ej. "NameError") try: ret['name'] = info[0].__name__ except: ret['name'] = 'Exception' # obtener la traza formateada como string: try: tb = traceback.format_exception(*info) ret['tb'] = ''.join(tb) except: ret['tb'] = "" return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def leer(linea, formato, expandir_fechas=False): "Analiza una linea de texto dado un formato, devuelve un diccionario" dic = {} comienzo = 1 for fmt in formato: clave, longitud, tipo = fmt[0:3] dec = (len(fmt)>3 and isinstance(fmt[3], int)) and fmt[3] or 2 valor = linea[comienzo-1:comienzo-1+longitud].strip() try: if chr(8) in valor or chr(127) in valor or chr(255) in valor: valor = None # nulo elif tipo == N: if valor: valor = long(valor) else: valor = 0 elif tipo == I: if valor: try: if '.' in valor: valor = float(valor) else: valor = valor.strip(" ") if valor[0] == "-": sign = -1 valor = valor[1:] else: sign = +1 valor = sign * float(("%%s.%%0%sd" % dec) % (long(valor[:-dec] or '0'), int(valor[-dec:] or '0'))) except ValueError: raise ValueError("Campo invalido: %s = '%s'" % (clave, valor)) else: valor = 0.00 elif expandir_fechas and clave.lower().startswith("fec") and longitud <= 8: if valor: valor = "%s-%s-%s" % (valor[0:4], valor[4:6], valor[6:8]) else: valor = None else: valor = valor.decode("ascii","ignore") if not valor and clave in dic and len(linea) <= comienzo: pass # ignorar - compatibilidad hacia atrás (cambios tamaño) else: dic[clave] = valor comienzo += longitud except Exception, e: raise ValueError("Error al leer campo %s pos %s val '%s': %s" % ( clave, comienzo, valor, str(e))) return dic
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dar_nombre_campo_dbf(clave, claves): "Reducir nombre de campo a 10 caracteres, sin espacios ni _, sin repetir" # achico el nombre del campo para que quepa en la tabla: nombre = clave.replace("_","")[:10] # si el campo esta repetido, le agrego un número i = 0 while nombre in claves: i += 1 nombre = nombre[:9] + str(i) return nombre.lower()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def verifica(ver_list, res_dict, difs): "Verificar que dos diccionarios sean iguales, actualiza lista diferencias" for k, v in ver_list.items(): # normalizo a float para poder comparar numericamente: if isinstance(v, (Decimal, int, long)): v = float(v) if isinstance(res_dict.get(k), (Decimal, int, long)): res_dict[k] = float(res_dict[k]) if isinstance(v, list): # verifico que ambas listas tengan la misma cantidad de elementos: if v and not k in res_dict and v: difs.append("falta tag %s: %s %s" % (k, repr(v), repr(res_dict.get(k)))) elif len(res_dict.get(k, []))!=len(v or []): difs.append("tag %s len !=: %s %s" % (k, repr(v), repr(res_dict.get(k)))) else: # ordeno las listas para poder compararlas si vienen mezcladas rl = sorted(res_dict.get(k, [])) # comparo los elementos uno a uno: for i, vl in enumerate(sorted(v)): verifica(vl, rl[i], difs) elif isinstance(v, dict): # comparo recursivamente los elementos: verifica(v, res_dict.get(k, {}), difs) elif res_dict.get(k) is None or v is None: # alguno de los dos es nulo, verifico si ambos lo son o faltan if v=="": v = None r = res_dict.get(k) if r=="": r = None if not (r is None and v is None): difs.append("%s: nil %s!=%s" % (k, repr(v), repr(r))) elif type(res_dict.get(k)) == type(v): # tipos iguales, los comparo directamente if res_dict.get(k) != v: difs.append("%s: %s!=%s" % (k, repr(v), repr(res_dict.get(k)))) elif isinstance(v, float) or isinstance(res_dict.get(k), float): # comparar numericamente if float(res_dict.get(k)) != float(v): difs.append("%s: %s!=%s" % (k, repr(v), repr(res_dict.get(k)))) elif unicode(res_dict.get(k)) != unicode(v): # tipos diferentes, comparo la representación difs.append("%s: str %s!=%s" % (k, repr(v), repr(res_dict.get(k)))) else: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def norm(x, encoding="latin1"): "Convertir acentos codificados en ISO 8859-1 u otro, a ASCII regular" if not isinstance(x, basestring): x = unicode(x) elif isinstance(x, str): x = x.decode(encoding, 'ignore') return unicodedata.normalize('NFKD', x).encode('ASCII', 'ignore')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def SetTicketAcceso(self, ta_string): "Establecer el token y sign desde un ticket de acceso XML" if ta_string: ta = SimpleXMLElement(ta_string) self.Token = str(ta.credentials.token) self.Sign = str(ta.credentials.sign) return True else: raise RuntimeError("Ticket de Acceso vacio!")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def __analizar_observaciones(self, ret): "Comprueba y extrae observaciones si existen en la respuesta XML" self.Observaciones = [obs["codigoDescripcion"] for obs in ret.get('arrayObservaciones', [])] self.Obs = '\n'.join(["%(codigo)s: %(descripcion)s" % obs for obs in self.Observaciones])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def __analizar_evento(self, ret): "Comprueba y extrae el wvento informativo si existen en la respuesta XML" evt = ret.get('evento') if evt: self.Eventos = [evt] self.Evento = "%(codigo)s: %(descripcion)s" % evt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def CrearRemito(self, tipo_comprobante, punto_emision, tipo_movimiento, categoria_emisor, cuit_titular_mercaderia, cod_dom_origen, tipo_receptor, categoria_receptor=None, cuit_receptor=None, cuit_depositario=None, cod_dom_destino=None, cod_rem_redestinar=None, cod_remito=None, estado=None, **kwargs): "Inicializa internamente los datos de un remito para autorizar" self.remito = {'tipoComprobante': tipo_comprobante, 'puntoEmision': punto_emision, 'categoriaEmisor': categoria_emisor, 'cuitTitularMercaderia': cuit_titular_mercaderia, 'cuitDepositario': cuit_depositario, 'tipoReceptor': tipo_receptor, 'categoriaReceptor': categoria_receptor, 'cuitReceptor': cuit_receptor, 'codDomOrigen': cod_dom_origen, 'codDomDestino': cod_dom_destino, 'tipoMovimiento': tipo_movimiento, 'estado': estado, 'codRemito': cod_remito, 'codRemRedestinado': cod_rem_redestinar, 'arrayMercaderias': [], 'arrayContingencias': [], } return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def AnalizarRemito(self, ret, archivo=None): "Extrae el resultado del remito, si existen en la respuesta XML" if ret: self.CodRemito = ret.get("codRemito") self.TipoComprobante = ret.get("tipoComprobante") self.PuntoEmision = ret.get("puntoEmision") datos_aut = ret.get('datosAutorizacion') if datos_aut: self.NroRemito = datos_aut.get('nroRemito') self.CodAutorizacion = datos_aut.get('codAutorizacion') self.FechaEmision = datos_aut.get('fechaEmision') self.FechaVencimiento = datos_aut.get('fechaVencimiento') self.Estado = ret.get('estado') self.Resultado = ret.get('resultado') self.QR = ret.get('qr') or "" if archivo: qr = base64.b64decode(self.QR) f = open(archivo, "wb") f.write(qr) f.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def EmitirRemito(self, archivo="qr.png"): "Emitir Remitos que se encuentren en estado Pendiente de Emitir." response = self.client.emitirRemito( authRequest={'token': self.Token, 'sign': self.Sign, 'cuitRepresentada': self.Cuit}, codRemito=self.remito['codRemito'], viaje=self.remito.get('viaje')) ret = response.get("emitirRemitoReturn") if ret: self.__analizar_errores(ret) self.__analizar_observaciones(ret) self.__analizar_evento(ret) self.AnalizarRemito(ret, archivo) return bool(self.CodRemito)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarRemito(self, cod_remito=None, id_req=None, tipo_comprobante=None, punto_emision=None, nro_comprobante=None): "Obtener los datos de un remito generado" print(self.client.help("consultarRemito")) response = self.client.consultarRemito( authRequest={'token': self.Token, 'sign': self.Sign, 'cuitRepresentada': self.Cuit}, codRemito=cod_remito, idReq=id_req, tipoComprobante=tipo_comprobante, puntoEmision=punto_emision, nroComprobante=nro_comprobante) ret = response.get("consultarRemitoReturn", {}) id_req = ret.get("idReq", 0) self.remito = rec = ret.get("remito", {}) self.__analizar_errores(ret) self.__analizar_observaciones(ret) self.__analizar_evento(ret) self.AnalizarRemito(rec) return id_req
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def AgregarEmisor(self, tipo_cbte, pto_vta, nro_cbte, cod_caracter=None, fecha_inicio_act=None, iibb=None, nro_ruca=None, nro_renspa=None, cuit_autorizado=None, **kwargs): "Agrego los datos del emisor a la liq." # cod_caracter y fecha_inicio_act no es requerido para ajustes d = {'tipoComprobante': tipo_cbte, 'puntoVenta': pto_vta, 'nroComprobante': nro_cbte, 'codCaracter': cod_caracter, 'fechaInicioActividades': fecha_inicio_act, 'iibb': iibb, 'nroRUCA': nro_ruca, 'nroRenspa': nro_renspa, 'cuitAutorizado': cuit_autorizado} self.solicitud['emisor'].update(d) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def AgregarReceptor(self, cod_caracter, **kwargs): "Agrego los datos del receptor a la liq." d = {'codCaracter': cod_caracter} self.solicitud['receptor'].update(d) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def AgregarOperador(self, cuit, iibb=None, nro_ruca=None, nro_renspa=None, cuit_autorizado=None, **kwargs): "Agrego los datos del operador a la liq." d = {'cuit': cuit, 'iibb': iibb, 'nroRUCA': nro_ruca, 'nroRenspa': nro_renspa, 'cuitAutorizado': cuit_autorizado} self.solicitud['receptor']['operador'] = d return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def AgregarAjusteFisico(self, cantidad, cantidad_cabezas=None, cantidad_kg_vivo=None, **kwargs): "Agrega campos al detalle de item por un ajuste fisico" d = {'cantidad': cantidad, 'cantidadCabezas': cantidad_cabezas, 'cantidadKgVivo': cantidad_kg_vivo, } item_liq = self.solicitud['itemDetalleAjusteLiquidacion'][-1] item_liq['ajusteFisico'] = d return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def AgregarAjusteMonetario(self, precio_unitario, precio_recupero=None, **kwargs): "Agrega campos al detalle de item por un ajuste monetario" d = {'precioUnitario': precio_unitario, 'precioRecupero': precio_recupero, } item_liq = self.solicitud['itemDetalleAjusteLiquidacion'][-1] item_liq['ajusteMonetario'] = d return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarLocalidades(self, cod_provincia, sep="||"): "Consulta las localidades habilitadas" ret = self.client.consultarLocalidadesPorProvincia( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, solicitud={'codProvincia': cod_provincia}, )['respuesta'] self.__analizar_errores(ret) array = ret.get('localidad', []) if sep is None: return dict([(it['codigo'], it['descripcion']) for it in array]) else: return [("%s %%s %s %%s %s" % (sep, sep, sep)) % (it['codigo'], it['descripcion']) for it in array]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Descargar(self, url=URL, filename="padron.txt", proxy=None): "Descarga el archivo de AFIP, devuelve 200 o 304 si no fue modificado" proxies = {} if proxy: proxies['http'] = proxy proxies['https'] = proxy proxy_handler = urllib2.ProxyHandler(proxies) print "Abriendo URL %s ..." % url req = urllib2.Request(url) if os.path.exists(filename): http_date = formatdate(timeval=os.path.getmtime(filename), localtime=False, usegmt=True) req.add_header('If-Modified-Since', http_date) try: web = urllib2.urlopen(req) except urllib2.HTTPError, e: if e.code == 304: print "No modificado desde", http_date return 304 else: raise # leer info del request: meta = web.info() lenght = float(meta['Content-Length']) date = meta['Last-Modified'] tmp = open(filename + ".zip", "wb") print "Guardando" size = 0 p0 = None while True: p = int(size / lenght * 100) if p0 is None or p>p0: print "Leyendo ... %0d %%" % p p0 = p data = web.read(1024*100) size = size + len(data) if not data: print "Descarga Terminada!" break tmp.write(data) print "Abriendo ZIP..." tmp.close() web.close() uf = open(filename + ".zip", "rb") zf = zipfile.ZipFile(uf) for fn in zf.namelist(): print "descomprimiendo", fn tf = open(filename, "wb") tf.write(zf.read(fn)) tf.close() return 200
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Procesar(self, filename="padron.txt", borrar=False): "Analiza y crea la base de datos interna sqlite para consultas" f = open(filename, "r") keys = [k for k, l, t, d in FORMATO] # conversion a planilla csv (no usado) if False and not os.path.exists("padron.csv"): csvfile = open('padron.csv', 'wb') import csv wr = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for i, l in enumerate(f): if i % 100000 == 0: print "Progreso: %d registros" % i r = leer(l, FORMATO) row = [r[k] for k in keys] wr.writerow(row) csvfile.close() f.seek(0) if os.path.exists(self.db_path) and borrar: os.remove(self.db_path) if True: db = db = sqlite3.connect(self.db_path) c = db.cursor() c.execute("CREATE TABLE padron (" "nro_doc INTEGER, " "denominacion VARCHAR(30), " "imp_ganancias VARCHAR(2), " "imp_iva VARCHAR(2), " "monotributo VARCHAR(1), " "integrante_soc VARCHAR(1), " "empleador VARCHAR(1), " "actividad_monotributo VARCHAR(2), " "tipo_doc INTEGER, " "cat_iva INTEGER DEFAULT NULL, " "email VARCHAR(250), " "PRIMARY KEY (tipo_doc, nro_doc)" ");") c.execute("CREATE TABLE domicilio (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "tipo_doc INTEGER, " "nro_doc INTEGER, " "direccion TEXT, " "FOREIGN KEY (tipo_doc, nro_doc) REFERENCES padron " ");") # importar los datos a la base sqlite for i, l in enumerate(f): if i % 10000 == 0: print i l = l.strip("\x00") r = leer(l, FORMATO) params = [r[k] for k in keys] params[8] = 80 # agrego tipo_doc = CUIT params[9] = None # cat_iva no viene de AFIP placeholders = ", ".join(["?"] * len(params)) c.execute("INSERT INTO padron VALUES (%s)" % placeholders, params) db.commit() c.close() db.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Buscar(self, nro_doc, tipo_doc=80): "Devuelve True si fue encontrado y establece atributos con datos" # cuit: codigo único de identificación tributaria del contribuyente # (sin guiones) self.cursor.execute("SELECT * FROM padron WHERE " " tipo_doc=? AND nro_doc=?", [tipo_doc, nro_doc]) row = self.cursor.fetchone() for key in [k for k, l, t, d in FORMATO]: if row: val = row[key] if not isinstance(val, basestring): val = str(row[key]) setattr(self, key, val) else: setattr(self, key, '') if self.tipo_doc == 80: self.cuit = self.nro_doc elif self.tipo_doc == 96: self.dni = self.nro_doc # determinar categoría de IVA (tentativa) try: cat_iva = int(self.cat_iva) except ValueError: cat_iva = None if cat_iva: pass elif self.imp_iva in ('AC', 'S'): self.cat_iva = 1 # RI elif self.imp_iva == 'EX': self.cat_iva = 4 # EX elif self.monotributo: self.cat_iva = 6 # MT else: self.cat_iva = 5 # CF return True if row else False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarDomicilios(self, nro_doc, tipo_doc=80, cat_iva=None): "Busca los domicilios, devuelve la cantidad y establece la lista" self.cursor.execute("SELECT direccion FROM domicilio WHERE " " tipo_doc=? AND nro_doc=? ORDER BY id ", [tipo_doc, nro_doc]) filas = self.cursor.fetchall() self.domicilios = [fila['direccion'] for fila in filas] return len(filas)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Guardar(self, tipo_doc, nro_doc, denominacion, cat_iva, direccion, email, imp_ganancias='NI', imp_iva='NI', monotributo='NI', integrante_soc='N', empleador='N'): "Agregar o actualizar los datos del cliente" if self.Buscar(nro_doc, tipo_doc): sql = ("UPDATE padron SET denominacion=?, cat_iva=?, email=?, " "imp_ganancias=?, imp_iva=?, monotributo=?, " "integrante_soc=?, empleador=? " "WHERE tipo_doc=? AND nro_doc=?") params = [denominacion, cat_iva, email, imp_ganancias, imp_iva, monotributo, integrante_soc, empleador, tipo_doc, nro_doc] else: sql = ("INSERT INTO padron (tipo_doc, nro_doc, denominacion, " "cat_iva, email, imp_ganancias, imp_iva, monotributo, " "integrante_soc, empleador) " "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") params = [tipo_doc, nro_doc, denominacion, cat_iva, email, imp_ganancias, imp_iva, monotributo, integrante_soc, empleador] self.cursor.execute(sql, params) # agregar el domicilio solo si no existe: if direccion: self.cursor.execute("SELECT * FROM domicilio WHERE direccion=? " "AND tipo_doc=? AND nro_doc=?", [direccion, tipo_doc, nro_doc]) if self.cursor.rowcount < 0: sql = ("INSERT INTO domicilio (nro_doc, tipo_doc, direccion)" "VALUES (?, ?, ?)") self.cursor.execute(sql, [nro_doc, tipo_doc, direccion]) self.db.commit() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ConsultarPuntosVentas(self, sep="||"): "Retorna los puntos de ventas autorizados para la utilizacion de WS" ret = self.client.consultarPuntosVenta( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, )['respuesta'] self.__analizar_errores(ret) array = ret.get('puntoVenta', []) if sep is None: return dict([(it['codigo'], it['descripcion']) for it in array]) else: return [("%s %%s %s %%s %s" % (sep, sep, sep)) % (it['codigo'], it['descripcion']) for it in array]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_boards(self): """Return a list with all the supported boards"""
# Print table click.echo('\nSupported boards:\n') BOARDLIST_TPL = ('{board:25} {fpga:20} {type:<5} {size:<5} {pack:<10}') terminal_width, _ = click.get_terminal_size() click.echo('-' * terminal_width) click.echo(BOARDLIST_TPL.format( board=click.style('Board', fg='cyan'), fpga='FPGA', type='Type', size='Size', pack='Pack')) click.echo('-' * terminal_width) for board in self.boards: fpga = self.boards.get(board).get('fpga') click.echo(BOARDLIST_TPL.format( board=click.style(board, fg='cyan'), fpga=fpga, type=self.fpgas.get(fpga).get('type'), size=self.fpgas.get(fpga).get('size'), pack=self.fpgas.get(fpga).get('pack'))) click.secho(BOARDS_MSG, fg='green')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_fpgas(self): """Return a list with all the supported FPGAs"""
# Print table click.echo('\nSupported FPGAs:\n') FPGALIST_TPL = ('{fpga:30} {type:<5} {size:<5} {pack:<10}') terminal_width, _ = click.get_terminal_size() click.echo('-' * terminal_width) click.echo(FPGALIST_TPL.format( fpga=click.style('FPGA', fg='cyan'), type='Type', size='Size', pack='Pack')) click.echo('-' * terminal_width) for fpga in self.fpgas: click.echo(FPGALIST_TPL.format( fpga=click.style(fpga, fg='cyan'), type=self.fpgas.get(fpga).get('type'), size=self.fpgas.get(fpga).get('size'), pack=self.fpgas.get(fpga).get('pack')))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, lsftdi, lsusb, lsserial, info): """System tools.\n Install with `apio install system`"""
exit_code = 0 if lsftdi: exit_code = System().lsftdi() elif lsusb: exit_code = System().lsusb() elif lsserial: exit_code = System().lsserial() elif info: click.secho('Platform: ', nl=False) click.secho(get_systype(), fg='yellow') else: click.secho(ctx.get_help()) ctx.exit(exit_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, command, variables=[], board=None, packages=[]): """Executes scons for building"""
# -- Check for the SConstruct file if not isfile(util.safe_join(util.get_project_dir(), 'SConstruct')): variables += ['-f'] variables += [util.safe_join( util.get_folder('resources'), 'SConstruct')] else: click.secho('Info: use custom SConstruct file') # -- Resolve packages if self.profile.check_exe_default(): # Run on `default` config mode if not util.resolve_packages( packages, self.profile.packages, self.resources.distribution.get('packages') ): # Exit if a package is not installed raise Exception else: click.secho('Info: native config mode') # -- Execute scons return self._execute_scons(command, variables, board)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, board, fpga, pack, type, size, project_dir, verbose, verbose_yosys, verbose_arachne): """Bitstream timing analysis."""
# Run scons exit_code = SCons(project_dir).time({ 'board': board, 'fpga': fpga, 'size': size, 'type': type, 'pack': pack, 'verbose': { 'all': verbose, 'yosys': verbose_yosys, 'arachne': verbose_arachne } }) ctx.exit(exit_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, board, scons, project_dir, sayyes): """Manage apio projects."""
if scons: Project().create_sconstruct(project_dir, sayyes) elif board: Project().create_ini(board, project_dir, sayyes) else: click.secho(ctx.get_help())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, project_dir): """Clean the previous generated files."""
exit_code = SCons(project_dir).clean() ctx.exit(exit_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, all, top, nostyle, nowarn, warn, project_dir): """Lint the verilog code."""
exit_code = SCons(project_dir).lint({ 'all': all, 'top': top, 'nostyle': nostyle, 'nowarn': nowarn, 'warn': warn }) ctx.exit(exit_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_sconstruct(self, project_dir='', sayyes=False): """Creates a default SConstruct file"""
project_dir = util.check_dir(project_dir) sconstruct_name = 'SConstruct' sconstruct_path = util.safe_join(project_dir, sconstruct_name) local_sconstruct_path = util.safe_join( util.get_folder('resources'), sconstruct_name) if isfile(sconstruct_path): # -- If sayyes, skip the question if sayyes: self._copy_sconstruct_file(sconstruct_name, sconstruct_path, local_sconstruct_path) else: click.secho( 'Warning: {} file already exists'.format(sconstruct_name), fg='yellow') if click.confirm('Do you want to replace it?'): self._copy_sconstruct_file(sconstruct_name, sconstruct_path, local_sconstruct_path) else: click.secho('Abort!', fg='red') else: self._copy_sconstruct_file(sconstruct_name, sconstruct_path, local_sconstruct_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_ini(self, board, project_dir='', sayyes=False): """Creates a new apio project file"""
project_dir = util.check_dir(project_dir) ini_path = util.safe_join(project_dir, PROJECT_FILENAME) # Check board boards = Resources().boards if board not in boards.keys(): click.secho( 'Error: no such board \'{}\''.format(board), fg='red') sys.exit(1) if isfile(ini_path): # -- If sayyes, skip the question if sayyes: self._create_ini_file(board, ini_path, PROJECT_FILENAME) else: click.secho( 'Warning: {} file already exists'.format(PROJECT_FILENAME), fg='yellow') if click.confirm('Do you want to replace it?'): self._create_ini_file(board, ini_path, PROJECT_FILENAME) else: click.secho('Abort!', fg='red') else: self._create_ini_file(board, ini_path, PROJECT_FILENAME)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self): """Read the project config file"""
# -- If no project finel found, just return if not isfile(PROJECT_FILENAME): print('Info: No {} file'.format(PROJECT_FILENAME)) return # -- Read stored board board = self._read_board() # -- Update board self.board = board if not board: print('Error: invalid {} project file'.format( PROJECT_FILENAME)) print('No \'board\' field defined in project file') sys.exit(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, project_dir): """Verify the verilog code."""
exit_code = SCons(project_dir).verify() ctx.exit(exit_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, ftdi_enable, ftdi_disable, serial_enable, serial_disable): """Manage FPGA boards drivers."""
exit_code = 0 if ftdi_enable: # pragma: no cover exit_code = Drivers().ftdi_enable() elif ftdi_disable: # pragma: no cover exit_code = Drivers().ftdi_disable() elif serial_enable: # pragma: no cover exit_code = Drivers().serial_enable() elif serial_disable: # pragma: no cover exit_code = Drivers().serial_disable() else: click.secho(ctx.get_help()) ctx.exit(exit_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, list, fpga): """Manage FPGA boards."""
if list: Resources().list_boards() elif fpga: Resources().list_fpgas() else: click.secho(ctx.get_help())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, board, serial_port, ftdi_id, sram, project_dir, verbose, verbose_yosys, verbose_arachne): """Upload the bitstream to the FPGA."""
drivers = Drivers() drivers.pre_upload() # Run scons exit_code = SCons(project_dir).upload({ 'board': board, 'verbose': { 'all': verbose, 'yosys': verbose_yosys, 'arachne': verbose_arachne } }, serial_port, ftdi_id, sram) drivers.post_upload() ctx.exit(exit_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx): """Check the latest Apio version."""
current_version = get_distribution('apio').version latest_version = get_pypi_latest_version() if latest_version is None: ctx.exit(1) if latest_version == current_version: click.secho('You\'re up-to-date!\nApio {} is currently the ' 'newest version available.'.format(latest_version), fg='green') else: click.secho('You\'re not updated\nPlease execute ' '`pip install -U apio` to upgrade.', fg="yellow")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unicoder(p): """ Make sure a Unicode string is returned """
if isinstance(p, unicode): return p if isinstance(p, str): return decoder(p) else: return unicode(decoder(p))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_join(*paths): """ Join paths in a Unicode-safe way """
try: return join(*paths) except UnicodeDecodeError: npaths = () for path in paths: npaths += (unicoder(path),) return join(*npaths)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_apt_get(): """Check if apio can be installed through apt-get"""
check = False if 'TESTING' not in os.environ: result = exec_command(['dpkg', '-l', 'apio']) if result and result.get('returncode') == 0: match = re.findall('rc\s+apio', result.get('out')) + \ re.findall('ii\s+apio', result.get('out')) check = len(match) > 0 return check
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, cmd): """Execute commands using Apio packages."""
exit_code = util.call(cmd) ctx.exit(exit_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, list, verbose, exe): """Apio configuration."""
if list: # pragma: no cover profile = Profile() profile.list() elif verbose: # pragma: no cover profile = Profile() profile.add_config('verbose', verbose) elif exe: # pragma: no cover profile = Profile() profile.add_config('exe', exe) else: click.secho(ctx.get_help())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, packages, all, list, force, platform): """Install packages."""
if packages: for package in packages: Installer(package, platform, force).install() elif all: # pragma: no cover packages = Resources(platform).packages for package in packages: Installer(package, platform, force).install() elif list: Resources(platform).list_packages(installed=True, notinstalled=True) else: click.secho(ctx.get_help())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, list, dir, files, project_dir, sayno): """Manage verilog examples.\n Install with `apio install examples`"""
exit_code = 0 if list: exit_code = Examples().list_examples() elif dir: exit_code = Examples().copy_example_dir(dir, project_dir, sayno) elif files: exit_code = Examples().copy_example_files(files, project_dir, sayno) else: click.secho(ctx.get_help()) click.secho(Examples().examples_of_use_cad()) ctx.exit(exit_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, project_dir): """Launch the verilog simulation."""
exit_code = SCons(project_dir).sim() ctx.exit(exit_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, packages, all, list, platform): """Uninstall packages."""
if packages: _uninstall(packages, platform) elif all: # pragma: no cover packages = Resources(platform).packages _uninstall(packages, platform) elif list: Resources(platform).list_packages(installed=True, notinstalled=False) else: click.secho(ctx.get_help())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_index_fields(self): """ List of fields to use for index """
index_fields = self.get_meta_option('index', []) if index_fields: return index_fields model = getattr(self.model_serializer_meta, 'model', None) if model: pk_name = model._meta.pk.name if pk_name in self.child.get_fields(): return [pk_name] return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform_dataframe(self, dataframe): """ Unstack the dataframe so header fields are across the top. """
dataframe.columns.name = "" for i in range(len(self.get_header_fields())): dataframe = dataframe.unstack() # Remove blank rows / columns dataframe = dataframe.dropna( axis=0, how='all' ).dropna( axis=1, how='all' ) return dataframe
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform_dataframe(self, dataframe): """ Unstack the dataframe so header consists of a composite 'value' header plus any other header fields. """
coord_fields = self.get_coord_fields() header_fields = self.get_header_fields() # Remove any pairs that don't have data for both x & y for i in range(len(coord_fields)): dataframe = dataframe.unstack() dataframe = dataframe.dropna(axis=1, how='all') dataframe = dataframe.dropna(axis=0, how='any') # Unstack series header for i in range(len(header_fields)): dataframe = dataframe.unstack() # Compute new column headers columns = [] for i in range(len(header_fields) + 1): columns.append([]) for col in dataframe.columns: value_name = col[0] coord_names = list(col[1:len(coord_fields) + 1]) header_names = list(col[len(coord_fields) + 1:]) coord_name = '' for name in coord_names: if name != self.index_none_value: coord_name += name + '-' coord_name += value_name columns[0].append(coord_name) for i, header_name in enumerate(header_names): columns[1 + i].append(header_name) dataframe.columns = columns dataframe.columns.names = [''] + header_fields return dataframe
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_boxplot(self, series): """ Compute boxplot for given pandas Series. """
from matplotlib.cbook import boxplot_stats series = series[series.notnull()] if len(series.values) == 0: return {} elif not is_numeric_dtype(series): return self.non_numeric_stats(series) stats = boxplot_stats(list(series.values))[0] stats['count'] = len(series.values) stats['fliers'] = "|".join(map(str, stats['fliers'])) return stats
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_cls(cls_name): """Import class by its fully qualified name. In terms of current example it is just a small helper function. Please, don't use it in production approaches. """
path_components = cls_name.split('.') module = __import__('.'.join(path_components[:-1]), locals(), globals(), fromlist=path_components[-1:]) return getattr(module, path_components[-1])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(uid, password, photo, users_service, auth_service, photos_service): """Authenticate user and upload photo."""
user = users_service.get_user_by_id(uid) auth_service.authenticate(user, password) photos_service.upload_photo(user['uid'], photo)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, email): """Execute use case handling."""
print('Sign up user {0}'.format(email)) self.email_sender.send(email, 'Welcome, "{}"'.format(email))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user_by_id(self, uid): """Return user's data by identifier."""
self.logger.debug('User %s has been found in database', uid) return dict(uid=uid, password_hash='secret_hash')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(self, user, password): """Authenticate user."""
assert user['password_hash'] == '_'.join((password, 'hash')) self.logger.debug('User %s has been successfully authenticated', user['uid'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, email, body): """Send email."""
print('Connecting server {0}:{1} with {2}:{3}'.format( self._host, self._port, self._login, self._password)) print('Sending "{0}" to "{1}"'.format(body, email))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main_photo(self): """Return user's main photo."""
if not self._main_photo: self._main_photo = self.photos_factory() return self._main_photo
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_sqlite(movies_data, database): """Initialize sqlite3 movies database. :param movies_data: Data about movies :type movies_data: tuple[tuple] :param database: Connection to sqlite database with movies data :type database: sqlite3.Connection """
with database: database.execute('CREATE TABLE IF NOT EXISTS movies ' '(name text, year int, director text)') database.execute('DELETE FROM movies') database.executemany('INSERT INTO movies VALUES (?,?,?)', movies_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_csv(movies_data, csv_file_path, delimiter): """Initialize csv movies database. :param movies_data: Data about movies :type movies_data: tuple[tuple] :param csv_file_path: Path to csv file with movies data :type csv_file_path: str :param delimiter: Csv file's delimiter :type delimiter: str """
with open(csv_file_path, 'w') as csv_file: csv.writer(csv_file, delimiter=delimiter).writerows(movies_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def play(self): """Play game."""
print('{0} and {1} are playing {2}'.format( self.player1, self.player2, self.__class__.__name__.lower()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_user(self, name, password): """Create user with hashed password."""
hashed_password = self._password_hasher(password) return dict(name=name, password=hashed_password)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call(self, operation, data): """Make some network operations."""
print('API call [{0}:{1}], method - {2}, data - {3}'.format( self.host, self.api_key, operation, repr(data)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def movies_directed_by(self, director): """Return list of movies that were directed by certain person. :param director: Director's name :type director: str :rtype: list[movies.models.Movie] :return: List of movie instances. """
return [movie for movie in self._movie_finder.find_all() if movie.director == director]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def movies_released_in(self, year): """Return list of movies that were released in certain year. :param year: Release year :type year: int :rtype: list[movies.models.Movie] :return: List of movie instances. """
return [movie for movie in self._movie_finder.find_all() if movie.year == year]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_database(self): """Initialize database, if it has not been initialized yet."""
with contextlib.closing(self.database.cursor()) as cursor: cursor.execute(""" CREATE TABLE IF NOT EXISTS users( id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(32) ) """)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, name): """Create user with provided name and return his id."""
with contextlib.closing(self.database.cursor()) as cursor: cursor.execute('INSERT INTO users(name) VALUES (?)', (name,)) return cursor.lastrowid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_by_id(self, id): """Return user info by user id."""
with contextlib.closing(self.database.cursor()) as cursor: cursor.execute('SELECT id, name FROM users WHERE id=?', (id,)) return cursor.fetchone()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_top_headlines(self, q=None, sources=None, language='en', country=None, category=None, page_size=None, page=None): """ Returns live top and breaking headlines for a country, specific category in a country, single source, or multiple sources.. Optional parameters: (str) q - return headlines w/ specific keyword or phrase. For example: 'bitcoin', 'trump', 'tesla', 'ethereum', etc. (str) sources - return headlines of news sources! some Valid values are: 'bbc-news', 'the-verge', 'abc-news', 'crypto coins news', 'ary news','associated press','wired','aftenposten','australian financial review','axios', 'bbc news','bild','blasting news','bloomberg','business insider','engadget','google news', 'hacker news','info money,'recode','techcrunch','techradar','the next web','the verge' etc. (str) language - The 2-letter ISO-639-1 code of the language you want to get headlines for. Valid values are: 'ar','de','en','es','fr','he','it','nl','no','pt','ru','se','ud','zh' (str) country - The 2-letter ISO 3166-1 code of the country you want to get headlines! Valid values are: 'ae','ar','at','au','be','bg','br','ca','ch','cn','co','cu','cz','de','eg','fr','gb','gr', 'hk','hu','id','ie','il','in','it','jp','kr','lt','lv','ma','mx','my','ng','nl','no','nz', 'ph','pl','pt','ro','rs','ru','sa','se','sg','si','sk','th','tr','tw','ua','us' (str) category - The category you want to get headlines for! Valid values are: 'business','entertainment','general','health','science','sports','technology' (int) page_size - The number of results to return per page (request). 20 is the default, 100 is the maximum. (int) page - Use this to page through the results if the total results found is greater than the page size. """
# Define Payload payload = {} # Keyword/Phrase if q is not None: if type(q) == str: payload['q'] = q else: raise TypeError('keyword/phrase q param should be a of type str') # Sources if (sources is not None) and ((country is not None) or (category is not None)): raise ValueError('cannot mix country/category param with sources param.') # Sources if sources is not None: if type(sources) == str: payload['sources'] = sources else: raise TypeError('sources param should be of type str') # Language if language is not None: if type(language) == str: if language in const.languages: payload['language'] = language else: raise ValueError('invalid language') else: raise TypeError('language param should be of type str') # Country if country is not None: if type(country) == str: if country in const.countries: payload['country'] = country else: raise ValueError('invalid country') else: raise TypeError('country param should be of type str') # Category if category is not None: if type(category) == str: if category in const.categories: payload['category'] = category else: raise ValueError('invalid category') else: raise TypeError('category param should be of type str') # Page Size if page_size is not None: if type(page_size) == int: if 0 <= page_size <= 100: payload['pageSize'] = page_size else: raise ValueError('page_size param should be an int between 1 and 100') else: raise TypeError('page_size param should be an int') # Page if page is not None: if type(page) == int: if page > 0: payload['page'] = page else: raise ValueError('page param should be an int greater than 0') else: raise TypeError('page param should be an int') # Send Request r = requests.get(const.TOP_HEADLINES_URL, auth=self.auth, timeout=30, params=payload) # Check Status of Request if r.status_code != requests.codes.ok: raise NewsAPIException(r.json()) return r.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_sources(self, category=None, language=None, country=None): """ Optional parameters: (str) category - The category you want to get headlines for! Valid values are: 'business','entertainment','general','health','science','sports','technology' (str) language - The 2-letter ISO-639-1 code of the language you want to get headlines for. Valid values are: 'ar','de','en','es','fr','he','it','nl','no','pt','ru','se','ud','zh' (str) country - The 2-letter ISO 3166-1 code of the country you want to get headlines! Valid values are: 'ae','ar','at','au','be','bg','br','ca','ch','cn','co','cu','cz','de','eg','fr','gb','gr', 'hk','hu','id','ie','il','in','it','jp','kr','lt','lv','ma','mx','my','ng','nl','no','nz', 'ph','pl','pt','ro','rs','ru','sa','se','sg','si','sk','th','tr','tw','ua','us' (str) category - The category you want to get headlines for! Valid values are: 'business','entertainment','general','health','science','sports','technology' """
# Define Payload payload = {} # Language if language is not None: if type(language) == str: if language in const.languages: payload['language'] = language else: raise ValueError('invalid language') else: raise TypeError('language param should be of type str') # Country if country is not None: if type(country) == str: if country in const.countries: payload['country'] = country else: raise ValueError('invalid country') else: raise TypeError('country param should be of type str') # Category if category is not None: if type(category) == str: if category in const.categories: payload['category'] = category else: raise ValueError('invalid category') else: raise TypeError('category param should be of type str') # Send Request r = requests.get(const.SOURCES_URL, auth=self.auth, timeout=30, params=payload) # Check Status of Request if r.status_code != requests.codes.ok: raise NewsAPIException(r.json()) return r.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_logger(name=None, logfile=None, level=logging.DEBUG, formatter=None, maxBytes=0, backupCount=0, fileLoglevel=None, disableStderrLogger=False): """ Configures and returns a fully configured logger instance, no hassles. If a logger with the specified name already exists, it returns the existing instance, else creates a new one. If you set the ``logfile`` parameter with a filename, the logger will save the messages to the logfile, but does not rotate by default. If you want to enable log rotation, set both ``maxBytes`` and ``backupCount``. Usage: .. code-block:: python from logzero import setup_logger logger = setup_logger() logger.info("hello") :arg string name: Name of the `Logger object <https://docs.python.org/2/library/logging.html#logger-objects>`_. Multiple calls to ``setup_logger()`` with the same name will always return a reference to the same Logger object. (default: ``__name__``) :arg string logfile: If set, also write logs to the specified filename. :arg int level: Minimum `logging-level <https://docs.python.org/2/library/logging.html#logging-levels>`_ to display (default: ``logging.DEBUG``). :arg Formatter formatter: `Python logging Formatter object <https://docs.python.org/2/library/logging.html#formatter-objects>`_ (by default uses the internal LogFormatter). :arg int maxBytes: Size of the logfile when rollover should occur. Defaults to 0, rollover never occurs. :arg int backupCount: Number of backups to keep. Defaults to 0, rollover never occurs. :arg int fileLoglevel: Minimum `logging-level <https://docs.python.org/2/library/logging.html#logging-levels>`_ for the file logger (is not set, it will use the loglevel from the ``level`` argument) :arg bool disableStderrLogger: Should the default stderr logger be disabled. Defaults to False. :return: A fully configured Python logging `Logger object <https://docs.python.org/2/library/logging.html#logger-objects>`_ you can use with ``.debug("msg")``, etc. """
_logger = logging.getLogger(name or __name__) _logger.propagate = False _logger.setLevel(level) # Reconfigure existing handlers stderr_stream_handler = None for handler in list(_logger.handlers): if hasattr(handler, LOGZERO_INTERNAL_LOGGER_ATTR): if isinstance(handler, logging.FileHandler): # Internal FileHandler needs to be removed and re-setup to be able # to set a new logfile. _logger.removeHandler(handler) continue elif isinstance(handler, logging.StreamHandler): stderr_stream_handler = handler # reconfigure handler handler.setLevel(level) handler.setFormatter(formatter or LogFormatter()) # remove the stderr handler (stream_handler) if disabled if disableStderrLogger: if stderr_stream_handler is not None: _logger.removeHandler(stderr_stream_handler) elif stderr_stream_handler is None: stderr_stream_handler = logging.StreamHandler() setattr(stderr_stream_handler, LOGZERO_INTERNAL_LOGGER_ATTR, True) stderr_stream_handler.setLevel(level) stderr_stream_handler.setFormatter(formatter or LogFormatter()) _logger.addHandler(stderr_stream_handler) if logfile: rotating_filehandler = RotatingFileHandler(filename=logfile, maxBytes=maxBytes, backupCount=backupCount) setattr(rotating_filehandler, LOGZERO_INTERNAL_LOGGER_ATTR, True) rotating_filehandler.setLevel(fileLoglevel or level) rotating_filehandler.setFormatter(formatter or LogFormatter(color=False)) _logger.addHandler(rotating_filehandler) return _logger
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_unicode(value): """ Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8. """
if isinstance(value, _TO_UNICODE_TYPES): return value if not isinstance(value, bytes): raise TypeError( "Expected bytes, unicode, or None; got %r" % type(value)) return value.decode("utf-8")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_default_logger(): """ Resets the internal default logger to the initial configuration """
global logger global _loglevel global _logfile global _formatter _loglevel = logging.DEBUG _logfile = None _formatter = None logger = setup_logger(name=LOGZERO_DEFAULT_LOGGER, logfile=_logfile, level=_loglevel, formatter=_formatter)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slerp(R1, R2, t1, t2, t_out): """Spherical linear interpolation of rotors This function uses a simpler interface than the more fundamental `slerp_evaluate` and `slerp_vectorized` functions. The latter are fast, being implemented at the C level, but take input `tau` instead of time. This function adjusts the time accordingly. Parameters R1: quaternion Quaternion at beginning of interpolation R2: quaternion Quaternion at end of interpolation t1: float Time corresponding to R1 t2: float Time corresponding to R2 t_out: float or array of floats Times to which the rotors should be interpolated """
tau = (t_out-t1)/(t2-t1) return np.slerp_vectorized(R1, R2, tau)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def squad(R_in, t_in, t_out): """Spherical "quadrangular" interpolation of rotors with a cubic spline This is the best way to interpolate rotations. It uses the analog of a cubic spline, except that the interpolant is confined to the rotor manifold in a natural way. Alternative methods involving interpolation of other coordinates on the rotation group or normalization of interpolated values give bad results. The results from this method are as natural as any, and are continuous in first and second derivatives. The input `R_in` rotors are assumed to be reasonably continuous (no sign flips), and the input `t` arrays are assumed to be sorted. No checking is done for either case, and you may get silently bad results if these conditions are violated. This function simplifies the calling, compared to `squad_evaluate` (which takes a set of four quaternions forming the edges of the "quadrangle", and the normalized time `tau`) and `squad_vectorized` (which takes the same arguments, but in array form, and efficiently loops over them). Parameters R_in: array of quaternions A time-series of rotors (unit quaternions) to be interpolated t_in: array of float The times corresponding to R_in t_out: array of float The times to which R_in should be interpolated """
if R_in.size == 0 or t_out.size == 0: return np.array((), dtype=np.quaternion) # This list contains an index for each `t_out` such that # t_in[i-1] <= t_out < t_in[i] # Note that `side='right'` is much faster in my tests # i_in_for_out = t_in.searchsorted(t_out, side='left') # np.clip(i_in_for_out, 0, len(t_in) - 1, out=i_in_for_out) i_in_for_out = t_in.searchsorted(t_out, side='right')-1 # Now, for each index `i` in `i_in`, we need to compute the # interpolation "coefficients" (`A_i`, `B_ip1`). # # I previously tested an explicit version of the loops below, # comparing `stride_tricks.as_strided` with explicit # implementation via `roll` (as seen here). I found that the # `roll` was significantly more efficient for simple calculations, # though the difference is probably totally washed out here. In # any case, it might be useful to test again. # A = R_in * np.exp((- np.log((~R_in) * np.roll(R_in, -1)) + np.log((~np.roll(R_in, 1)) * R_in) * ((np.roll(t_in, -1) - t_in) / (t_in - np.roll(t_in, 1))) ) * 0.25) B = np.roll(R_in, -1) * np.exp((np.log((~np.roll(R_in, -1)) * np.roll(R_in, -2)) * ((np.roll(t_in, -1) - t_in) / (np.roll(t_in, -2) - np.roll(t_in, -1))) - np.log((~R_in) * np.roll(R_in, -1))) * -0.25) # Correct the first and last A time steps, and last two B time steps. We extend R_in with the following wrap-around # values: # R_in[0-1] = R_in[0]*(~R_in[1])*R_in[0] # R_in[n+0] = R_in[-1] * (~R_in[-2]) * R_in[-1] # R_in[n+1] = R_in[0] * (~R_in[-1]) * R_in[0] # = R_in[-1] * (~R_in[-2]) * R_in[-1] * (~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1] # = R_in[-1] * (~R_in[-2]) * R_in[-1] * (~R_in[-2]) * R_in[-1] # A[i] = R_in[i] * np.exp((- np.log((~R_in[i]) * R_in[i+1]) # + np.log((~R_in[i-1]) * R_in[i]) * ((t_in[i+1] - t_in[i]) / (t_in[i] - t_in[i-1])) # ) * 0.25) # A[0] = R_in[0] * np.exp((- np.log((~R_in[0]) * R_in[1]) + np.log((~R_in[0])*R_in[1]*(~R_in[0])) * R_in[0]) * 0.25) # = R_in[0] A[0] = R_in[0] # A[-1] = R_in[-1] * np.exp((- np.log((~R_in[-1]) * R_in[n+0]) # + np.log((~R_in[-2]) * R_in[-1]) * ((t_in[n+0] - t_in[-1]) / (t_in[-1] - t_in[-2])) # ) * 0.25) # = R_in[-1] * np.exp((- np.log((~R_in[-1]) * R_in[n+0]) + np.log((~R_in[-2]) * R_in[-1])) * 0.25) # = R_in[-1] * np.exp((- np.log((~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1]) # + np.log((~R_in[-2]) * R_in[-1])) * 0.25) # = R_in[-1] * np.exp((- np.log((~R_in[-2]) * R_in[-1]) + np.log((~R_in[-2]) * R_in[-1])) * 0.25) # = R_in[-1] A[-1] = R_in[-1] # B[i] = R_in[i+1] * np.exp((np.log((~R_in[i+1]) * R_in[i+2]) * ((t_in[i+1] - t_in[i]) / (t_in[i+2] - t_in[i+1])) # - np.log((~R_in[i]) * R_in[i+1])) * -0.25) # B[-2] = R_in[-1] * np.exp((np.log((~R_in[-1]) * R_in[0]) * ((t_in[-1] - t_in[-2]) / (t_in[0] - t_in[-1])) # - np.log((~R_in[-2]) * R_in[-1])) * -0.25) # = R_in[-1] * np.exp((np.log((~R_in[-1]) * R_in[0]) - np.log((~R_in[-2]) * R_in[-1])) * -0.25) # = R_in[-1] * np.exp((np.log((~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1]) # - np.log((~R_in[-2]) * R_in[-1])) * -0.25) # = R_in[-1] * np.exp((np.log((~R_in[-2]) * R_in[-1]) - np.log((~R_in[-2]) * R_in[-1])) * -0.25) # = R_in[-1] B[-2] = R_in[-1] # B[-1] = R_in[0] # B[-1] = R_in[0] * np.exp((np.log((~R_in[0]) * R_in[1]) - np.log((~R_in[-1]) * R_in[0])) * -0.25) # = R_in[-1] * (~R_in[-2]) * R_in[-1] # * np.exp((np.log((~(R_in[-1] * (~R_in[-2]) * R_in[-1])) * R_in[-1] * (~R_in[-2]) * R_in[-1] * (~R_in[-2]) * R_in[-1]) # - np.log((~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1])) * -0.25) # = R_in[-1] * (~R_in[-2]) * R_in[-1] # * np.exp((np.log(((~R_in[-1]) * R_in[-2] * (~R_in[-1])) * R_in[-1] * (~R_in[-2]) * R_in[-1] * (~R_in[-2]) * R_in[-1]) # - np.log((~R_in[-1]) * R_in[-1] * (~R_in[-2]) * R_in[-1])) * -0.25) # * np.exp((np.log((~R_in[-2]) * R_in[-1]) # - np.log((~R_in[-2]) * R_in[-1])) * -0.25) B[-1] = R_in[-1] * (~R_in[-2]) * R_in[-1] # Use the coefficients at the corresponding t_out indices to # compute the squad interpolant # R_ip1 = np.array(np.roll(R_in, -1)[i_in_for_out]) # R_ip1[-1] = R_in[-1]*(~R_in[-2])*R_in[-1] R_ip1 = np.roll(R_in, -1) R_ip1[-1] = R_in[-1]*(~R_in[-2])*R_in[-1] R_ip1 = np.array(R_ip1[i_in_for_out]) t_inp1 = np.roll(t_in, -1) t_inp1[-1] = t_in[-1] + (t_in[-1] - t_in[-2]) tau = (t_out - t_in[i_in_for_out]) / ((t_inp1 - t_in)[i_in_for_out]) # tau = (t_out - t_in[i_in_for_out]) / ((np.roll(t_in, -1) - t_in)[i_in_for_out]) R_out = np.squad_vectorized(tau, R_in[i_in_for_out], A[i_in_for_out], B[i_in_for_out], R_ip1) return R_out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def integrate_angular_velocity(Omega, t0, t1, R0=None, tolerance=1e-12): """Compute frame with given angular velocity Parameters ========== Omega: tuple or callable Angular velocity from which to compute frame. Can be 1) a 2-tuple of float arrays (t, v) giving the angular velocity vector at a series of times, 2) a function of time that returns the 3-vector angular velocity, or 3) a function of time and orientation (t, R) that returns the 3-vector angular velocity In case 1, the angular velocity will be interpolated to the required times. Note that accuracy is poor in case 1. t0: float Initial time t1: float Final time R0: quaternion, optional Initial frame orientation. Defaults to 1 (the identity orientation). tolerance: float, optional Absolute tolerance used in integration. Defaults to 1e-12. Returns ======= t: float array R: quaternion array """
import warnings from scipy.integrate import ode if R0 is None: R0 = quaternion.one input_is_tabulated = False try: t_Omega, v = Omega from scipy.interpolate import InterpolatedUnivariateSpline Omega_x = InterpolatedUnivariateSpline(t_Omega, v[:, 0]) Omega_y = InterpolatedUnivariateSpline(t_Omega, v[:, 1]) Omega_z = InterpolatedUnivariateSpline(t_Omega, v[:, 2]) def Omega_func(t, R): return [Omega_x(t), Omega_y(t), Omega_z(t)] Omega_func(t0, R0) input_is_tabulated = True except (TypeError, ValueError): def Omega_func(t, R): return Omega(t, R) try: Omega_func(t0, R0) except TypeError: def Omega_func(t, R): return Omega(t) Omega_func(t0, R0) def RHS(t, y): R = quaternion.quaternion(*y) return (0.5 * quaternion.quaternion(0.0, *Omega_func(t, R)) * R).components y0 = R0.components if input_is_tabulated: from scipy.integrate import solve_ivp t = t_Omega t_span = [t_Omega[0], t_Omega[-1]] solution = solve_ivp(RHS, t_span, y0, t_eval=t_Omega, atol=tolerance, rtol=100*np.finfo(float).eps) R = quaternion.from_float_array(solution.y.T) else: solver = ode(RHS) solver.set_initial_value(y0, t0) solver.set_integrator('dop853', nsteps=1, atol=tolerance, rtol=0.0) solver._integrator.iwork[2] = -1 # suppress Fortran-printed warning t = appending_array((int(t1-t0),)) t.append(solver.t) R = appending_array((int(t1-t0), 4)) R.append(solver.y) warnings.filterwarnings("ignore", category=UserWarning) t_last = solver.t while solver.t < t1: solver.integrate(t1, step=True) if solver.t > t_last: t.append(solver.t) R.append(solver.y) t_last = solver.t warnings.resetwarnings() t = t.a R = quaternion.as_quat_array(R.a) return t, R
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def minimal_rotation(R, t, iterations=2): """Adjust frame so that there is no rotation about z' axis The output of this function is a frame that rotates the z axis onto the same z' axis as the input frame, but with minimal rotation about that axis. This is done by pre-composing the input rotation with a rotation about the z axis through an angle gamma, where dgamma/dt = 2*(dR/dt * z * R.conjugate()).w This ensures that the angular velocity has no component along the z' axis. Note that this condition becomes easier to impose the closer the input rotation is to a minimally rotating frame, which means that repeated application of this function improves its accuracy. By default, this function is iterated twice, though a few more iterations may be called for. Parameters ========== R: quaternion array Time series describing rotation t: float array Corresponding times at which R is measured iterations: int [defaults to 2] Repeat the minimization to refine the result """
from scipy.interpolate import InterpolatedUnivariateSpline as spline if iterations == 0: return R R = quaternion.as_float_array(R) Rdot = np.empty_like(R) for i in range(4): Rdot[:, i] = spline(t, R[:, i]).derivative()(t) R = quaternion.from_float_array(R) Rdot = quaternion.from_float_array(Rdot) halfgammadot = quaternion.as_float_array(Rdot * quaternion.z * R.conjugate())[:, 0] halfgamma = spline(t, halfgammadot).antiderivative()(t) Rgamma = np.exp(quaternion.z * halfgamma) return minimal_rotation(R * Rgamma, t, iterations=iterations-1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mean_rotor_in_chordal_metric(R, t=None): """Return rotor that is closest to all R in the least-squares sense This can be done (quasi-)analytically because of the simplicity of the chordal metric function. The only approximation is the simple 2nd-order discrete formula for the definite integral of the input rotor function. Note that the `t` argument is optional. If it is present, the times are used to weight the corresponding integral. If it is not present, a simple sum is used instead (which may be slightly faster). """
if not t: return np.quaternion(*(np.sum(as_float_array(R)))).normalized() mean = np.empty((4,), dtype=float) definite_integral(as_float_array(R), t, mean) return np.quaternion(*mean).normalized()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_float_array(a): """View the quaternion array as an array of floats This function is fast (of order 1 microsecond) because no data is copied; the returned quantity is just a "view" of the original. The output view has one more dimension (of size 4) than the input array, but is otherwise the same shape. """
return np.asarray(a, dtype=np.quaternion).view((np.double, 4))