_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q35100 | getIntervalLeadingPrecision | train | def getIntervalLeadingPrecision(data_type_oid, type_modifier):
"""
Returns the leading precision for an interval, which is the largest number
of digits that can fit in the leading field of the interval.
All Year/Month intervals are defined in terms of months, even if the
type_modifier forbids month... | python | {
"resource": ""
} |
q35101 | getPrecision | train | def getPrecision(data_type_oid, type_modifier):
"""
Returns the precision for the given Vertica type with consideration of
the type modifier.
For numerics, precision is the total number of digits (in base 10) that can
fit in the type.
For intervals, time and timestamps, precision is the number... | python | {
"resource": ""
} |
q35102 | getDisplaySize | train | def getDisplaySize(data_type_oid, type_modifier):
"""
Returns the column display size for the given Vertica type with
consideration of the type modifier.
The display size of a column is the maximum number of characters needed to
display data in character form.
"""
if data_type_oid == Verti... | python | {
"resource": ""
} |
q35103 | _get_classpath | train | def _get_classpath():
"""Extract CLASSPATH from system environment as JPype doesn't seem
to respect that variable.
"""
try:
orig_cp = os.environ['CLASSPATH']
except KeyError:
return []
expanded_cp = []
for i in orig_cp.split(os.path.pathsep):
expanded_cp.extend(_jar_g... | python | {
"resource": ""
} |
q35104 | Cursor._close_last | train | def _close_last(self):
"""Close the resultset and reset collected meta data.
"""
if self._rs:
self._rs.close()
self._rs = None
if self._prep:
self._prep.close()
self._prep = None
self._meta = None
self._description = None | python | {
"resource": ""
} |
q35105 | set_global_tracer | train | def set_global_tracer(value):
"""Sets the global tracer.
It is an error to pass ``None``.
:param value: the :class:`Tracer` used as global instance.
:type value: :class:`Tracer`
"""
if value is None:
raise ValueError('The global Tracer tracer cannot be None')
global tracer, is_trac... | python | {
"resource": ""
} |
q35106 | Tracer.inject | train | def inject(self, span_context, format, carrier):
"""Injects `span_context` into `carrier`.
The type of `carrier` is determined by `format`. See the
:class:`Format` class/namespace for the built-in OpenTracing formats.
Implementations *must* raise :exc:`UnsupportedFormatException` if
... | python | {
"resource": ""
} |
q35107 | WSCTG.__analizar_controles | train | def __analizar_controles(self, ret):
"Comprueba y extrae controles si existen en la respuesta XML"
if 'arrayControles' in ret:
controles = ret['arrayControles']
self.Controles = ["%(tipo)s: %(descripcion)s" % ctl['control']
for ctl in controles] | python | {
"resource": ""
} |
q35108 | WSCTG.Dummy | train | def Dummy(self):
"Obtener el estado de los servidores de la AFIP"
results = self.client.dummy()['response']
self.AppServerStatus = str(results['appserver'])
self.DbServerStatus = str(results['dbserver'])
self.AuthServerStatus = str(results['authserver']) | python | {
"resource": ""
} |
q35109 | WSCTG.SolicitarCTGInicial | train | def SolicitarCTGInicial(self, numero_carta_de_porte, codigo_especie,
cuit_canjeador, cuit_destino, cuit_destinatario, codigo_localidad_origen,
codigo_localidad_destino, codigo_cosecha, peso_neto_carga,
cant_horas=None, patente_vehiculo=None, cuit_transportista=None,
km_a_recorrer=None,... | python | {
"resource": ""
} |
q35110 | WSCTG.SolicitarCTGDatoPendiente | train | def SolicitarCTGDatoPendiente(self, numero_carta_de_porte, cant_horas,
patente_vehiculo, cuit_transportista, patente=None, turno=None):
"Solicitud que permite completar los datos faltantes de un Pre-CTG "
"generado anteriormente a través de la operación solicitarCTGInicial"
ret = self.c... | python | {
"resource": ""
} |
q35111 | WSCTG.ConfirmarArribo | train | 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=d... | python | {
"resource": ""
} |
q35112 | WSCTG.ConfirmarDefinitivo | train | 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(
... | python | {
"resource": ""
} |
q35113 | WSCTG.RegresarAOrigenCTGRechazado | train | 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(
... | python | {
"resource": ""
} |
q35114 | WSCTG.ConsultarCTGActivosPorPatente | train | 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... | python | {
"resource": ""
} |
q35115 | WSLPG.ConsultarLiquidacionesPorContrato | train | def ConsultarLiquidacionesPorContrato(self, nro_contrato=None,
cuit_comprador=None,
cuit_vendedor=None,
cuit_corredor=None,
co... | python | {
"resource": ""
} |
q35116 | WSLPG.ConsultarCertificacion | train | 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... | python | {
"resource": ""
} |
q35117 | WSLPG.ConsultarTipoDeduccion | train | def ConsultarTipoDeduccion(self, sep="||"):
"Consulta de tipos de Deducciones"
ret = self.client.tipoDeduccionConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['tip... | python | {
"resource": ""
} |
q35118 | WSLPG.ConsultarTipoRetencion | train | def ConsultarTipoRetencion(self, sep="||"):
"Consulta de tipos de Retenciones."
ret = self.client.tipoRetencionConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['ti... | python | {
"resource": ""
} |
q35119 | WSLPG.ConsultarPuerto | train | def ConsultarPuerto(self, sep="||"):
"Consulta de Puertos habilitados"
ret = self.client.puertoConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['puertoReturn']
... | python | {
"resource": ""
} |
q35120 | WSLPG.ConsultarTipoActividad | train | def ConsultarTipoActividad(self, sep="||"):
"Consulta de Tipos de Actividad."
ret = self.client.tipoActividadConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['tipo... | python | {
"resource": ""
} |
q35121 | WSLPG.ConsultarTipoActividadRepresentado | train | 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,
... | python | {
"resource": ""
} |
q35122 | WSLPG.ConsultarProvincias | train | def ConsultarProvincias(self, sep="||"):
"Consulta las provincias habilitadas"
ret = self.client.provinciasConsultar(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['provin... | python | {
"resource": ""
} |
q35123 | WSLPG.CargarFormatoPDF | train | 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, "planti... | python | {
"resource": ""
} |
q35124 | WSLPG.AgregarCampoPDF | train | 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):
... | python | {
"resource": ""
} |
q35125 | WSLPG.GenerarPDF | train | 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 | python | {
"resource": ""
} |
q35126 | IIBB.ConsultarContribuyentes | train | 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.fec... | python | {
"resource": ""
} |
q35127 | WSLTV.AgregarReceptor | train | 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 | python | {
"resource": ""
} |
q35128 | WSLTV.AgregarPrecioClase | train | 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['precioClas... | python | {
"resource": ""
} |
q35129 | WSLTV.ConsultarVariedadesClasesTabaco | train | 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={
... | python | {
"resource": ""
} |
q35130 | exception_info | train | 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 causa... | python | {
"resource": ""
} |
q35131 | leer | train | 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[comie... | python | {
"resource": ""
} |
q35132 | dar_nombre_campo_dbf | train | 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... | python | {
"resource": ""
} |
q35133 | verifica | train | 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.... | python | {
"resource": ""
} |
q35134 | norm | train | 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') | python | {
"resource": ""
} |
q35135 | BaseWS.SetTicketAcceso | train | 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:
... | python | {
"resource": ""
} |
q35136 | WSRemCarne.__analizar_observaciones | train | 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]) | python | {
"resource": ""
} |
q35137 | WSRemCarne.__analizar_evento | train | 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 | python | {
"resource": ""
} |
q35138 | WSRemCarne.CrearRemito | train | 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, es... | python | {
"resource": ""
} |
q35139 | WSRemCarne.AnalizarRemito | train | 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_... | python | {
"resource": ""
} |
q35140 | WSRemCarne.EmitirRemito | train | 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=... | python | {
"resource": ""
} |
q35141 | WSRemCarne.ConsultarRemito | train | 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(
... | python | {
"resource": ""
} |
q35142 | WSLSP.AgregarEmisor | train | 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 requerid... | python | {
"resource": ""
} |
q35143 | WSLSP.AgregarReceptor | train | 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 | python | {
"resource": ""
} |
q35144 | WSLSP.AgregarOperador | train | 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,
... | python | {
"resource": ""
} |
q35145 | WSLSP.AgregarAjusteFisico | train | 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_v... | python | {
"resource": ""
} |
q35146 | WSLSP.AgregarAjusteMonetario | train | 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.sol... | python | {
"resource": ""
} |
q35147 | WSLSP.ConsultarLocalidades | train | def ConsultarLocalidades(self, cod_provincia, sep="||"):
"Consulta las localidades habilitadas"
ret = self.client.consultarLocalidadesPorProvincia(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
... | python | {
"resource": ""
} |
q35148 | PadronAFIP.Descargar | train | 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)
... | python | {
"resource": ""
} |
q35149 | PadronAFIP.Procesar | train | 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"):
... | python | {
"resource": ""
} |
q35150 | PadronAFIP.Buscar | train | 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=? A... | python | {
"resource": ""
} |
q35151 | PadronAFIP.ConsultarDomicilios | train | 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, ... | python | {
"resource": ""
} |
q35152 | PadronAFIP.Guardar | train | 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... | python | {
"resource": ""
} |
q35153 | WSLUM.ConsultarPuntosVentas | train | 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, },
... | python | {
"resource": ""
} |
q35154 | Resources.list_boards | train | 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_wi... | python | {
"resource": ""
} |
q35155 | Resources.list_fpgas | train | 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)
cl... | python | {
"resource": ""
} |
q35156 | cli | train | 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:
... | python | {
"resource": ""
} |
q35157 | SCons.run | train | 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... | python | {
"resource": ""
} |
q35158 | cli | train | 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,
... | python | {
"resource": ""
} |
q35159 | cli | train | 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()) | python | {
"resource": ""
} |
q35160 | cli | train | def cli(ctx, project_dir):
"""Clean the previous generated files."""
exit_code = SCons(project_dir).clean()
ctx.exit(exit_code) | python | {
"resource": ""
} |
q35161 | cli | train | 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) | python | {
"resource": ""
} |
q35162 | Project.create_sconstruct | train | 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(
... | python | {
"resource": ""
} |
q35163 | Project.create_ini | train | 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():
... | python | {
"resource": ""
} |
q35164 | Project.read | train | 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()
# -- Upda... | python | {
"resource": ""
} |
q35165 | cli | train | def cli(ctx, project_dir):
"""Verify the verilog code."""
exit_code = SCons(project_dir).verify()
ctx.exit(exit_code) | python | {
"resource": ""
} |
q35166 | cli | train | 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_... | python | {
"resource": ""
} |
q35167 | cli | train | def cli(ctx, list, fpga):
"""Manage FPGA boards."""
if list:
Resources().list_boards()
elif fpga:
Resources().list_fpgas()
else:
click.secho(ctx.get_help()) | python | {
"resource": ""
} |
q35168 | cli | train | 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': {
... | python | {
"resource": ""
} |
q35169 | cli | train | 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 ... | python | {
"resource": ""
} |
q35170 | unicoder | train | 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)) | python | {
"resource": ""
} |
q35171 | safe_join | train | 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) | python | {
"resource": ""
} |
q35172 | _check_apt_get | train | 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')) + \
... | python | {
"resource": ""
} |
q35173 | cli | train | def cli(ctx, cmd):
"""Execute commands using Apio packages."""
exit_code = util.call(cmd)
ctx.exit(exit_code) | python | {
"resource": ""
} |
q35174 | cli | train | 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 = Profil... | python | {
"resource": ""
} |
q35175 | cli | train | 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:
Inst... | python | {
"resource": ""
} |
q35176 | cli | train | 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:
... | python | {
"resource": ""
} |
q35177 | cli | train | def cli(ctx, project_dir):
"""Launch the verilog simulation."""
exit_code = SCons(project_dir).sim()
ctx.exit(exit_code) | python | {
"resource": ""
} |
q35178 | cli | train | 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=... | python | {
"resource": ""
} |
q35179 | PandasSerializer.get_index_fields | train | 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.... | python | {
"resource": ""
} |
q35180 | PandasUnstackedSerializer.transform_dataframe | train | 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
data... | python | {
"resource": ""
} |
q35181 | PandasScatterSerializer.transform_dataframe | train | 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 ha... | python | {
"resource": ""
} |
q35182 | PandasBoxplotSerializer.compute_boxplot | train | 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... | python | {
"resource": ""
} |
q35183 | import_cls | train | 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]),
... | python | {
"resource": ""
} |
q35184 | main | train | 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) | python | {
"resource": ""
} |
q35185 | SignupUseCase.execute | train | def execute(self, email):
"""Execute use case handling."""
print('Sign up user {0}'.format(email))
self.email_sender.send(email, 'Welcome, "{}"'.format(email)) | python | {
"resource": ""
} |
q35186 | UsersService.get_user_by_id | train | 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') | python | {
"resource": ""
} |
q35187 | AuthService.authenticate | train | 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']) | python | {
"resource": ""
} |
q35188 | MailService.send | train | 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)) | python | {
"resource": ""
} |
q35189 | User.main_photo | train | def main_photo(self):
"""Return user's main photo."""
if not self._main_photo:
self._main_photo = self.photos_factory()
return self._main_photo | python | {
"resource": ""
} |
q35190 | init_sqlite | train | 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.execut... | python | {
"resource": ""
} |
q35191 | init_csv | train | 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 delim... | python | {
"resource": ""
} |
q35192 | Game.play | train | def play(self):
"""Play game."""
print('{0} and {1} are playing {2}'.format(
self.player1, self.player2, self.__class__.__name__.lower())) | python | {
"resource": ""
} |
q35193 | UsersService.create_user | train | def create_user(self, name, password):
"""Create user with hashed password."""
hashed_password = self._password_hasher(password)
return dict(name=name, password=hashed_password) | python | {
"resource": ""
} |
q35194 | ApiClient.call | train | 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))) | python | {
"resource": ""
} |
q35195 | MovieLister.movies_directed_by | train | 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._m... | python | {
"resource": ""
} |
q35196 | MovieLister.movies_released_in | train | 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_... | python | {
"resource": ""
} |
q35197 | UsersService.init_database | train | 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 VAR... | python | {
"resource": ""
} |
q35198 | UsersService.create | train | 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 | python | {
"resource": ""
} |
q35199 | UsersService.get_by_id | train | 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() | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.