code
stringlengths
1
18.2k
def enviar_dados_venda(self, dados_venda): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.enviar_dados_venda`. :return: Uma resposta SAT especializada em ``EnviarDadosVenda``. :rtype: satcfe.resposta.enviardadosvenda.RespostaEnviarDadosVenda """ resp = self._http_post('enviardadosvenda', dados_venda=dados_venda.documento()...
def cancelar_ultima_venda(self, chave_cfe, dados_cancelamento): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.cancelar_ultima_venda`. :return: Uma resposta SAT especializada em ``CancelarUltimaVenda``. :rtype: satcfe.resposta.cancelarultimavenda.RespostaCancelarUltimaVenda """ resp = self._http_post('cancelarultimavenda',...
def consultar_sat(self): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_sat`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT """ resp = self._http_post('consultarsat') conteudo = resp.json() return RespostaSAT.consultar_sat(conteudo.get('retorno'))
def consultar_status_operacional(self): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_status_operacional`. :return: Uma resposta SAT especializada em ``ConsultarStatusOperacional``. :rtype: satcfe.resposta.consultarstatusoperacional.RespostaConsultarStatusOperacional """ resp = self._http_post('consultarstatusop...
def consultar_numero_sessao(self, numero_sessao): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_numero_sessao`. :return: Uma resposta SAT que irá depender da sessão consultada. :rtype: satcfe.resposta.padrao.RespostaSAT """ resp = self._http_post('consultarnumerosessao', numero_sessao=numero_sessao) conteudo = r...
def configurar_interface_de_rede(self, configuracao): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.configurar_interface_de_rede`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT """ resp = self._http_post('configurarinterfacederede', configuracao=configuracao.documento()) conteudo = resp.json...
def associar_assinatura(self, sequencia_cnpj, assinatura_ac): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.associar_assinatura`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT """ resp = self._http_post('associarassinatura', sequencia_cnpj=sequencia_cnpj, assinatura_ac=assinatura_ac) # (!) r...
def atualizar_software_sat(self): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.atualizar_software_sat`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT """ resp = self._http_post('atualizarsoftwaresat') conteudo = resp.json() return RespostaSAT.atualizar_software_sat(conteudo.get('retorno'))
def extrair_logs(self): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.extrair_logs`. :return: Uma resposta SAT especializada em ``ExtrairLogs``. :rtype: satcfe.resposta.extrairlogs.RespostaExtrairLogs """ resp = self._http_post('extrairlogs') conteudo = resp.json() return RespostaExtrairLogs.analisar(conteudo.get('retorno...
def bloquear_sat(self): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.bloquear_sat`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT """ resp = self._http_post('bloquearsat') conteudo = resp.json() return RespostaSAT.bloquear_sat(conteudo.get('retorno'))
def desbloquear_sat(self): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.desbloquear_sat`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT """ resp = self._http_post('desbloquearsat') conteudo = resp.json() return RespostaSAT.desbloquear_sat(conteudo.get('retorno'))
def trocar_codigo_de_ativacao(self, novo_codigo_ativacao, opcao=constantes.CODIGO_ATIVACAO_REGULAR, codigo_emergencia=None): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT """ resp = self._http_post('trocarcodigodeativa...
def bounds(self) -> typing.Tuple[typing.Tuple[float, float], typing.Tuple[float, float]]: """Return the bounds property in relative coordinates. Bounds is a tuple ((top, left), (height, width))""" ...
def end(self, value: typing.Union[float, typing.Tuple[float, float]]) -> None: """Set the end property in relative coordinates. End may be a float when graphic is an Interval or a tuple (y, x) when graphic is a Line.""" ...
def start(self, value: typing.Union[float, typing.Tuple[float, float]]) -> None: """Set the end property in relative coordinates. End may be a float when graphic is an Interval or a tuple (y, x) when graphic is a Line.""" ...
def vector(self) -> typing.Tuple[typing.Tuple[float, float], typing.Tuple[float, float]]: """Return the vector property in relative coordinates. Vector will be a tuple of tuples ((y_start, x_start), (y_end, x_end)).""" ...
def get_data_item_for_hardware_source(self, hardware_source, channel_id: str=None, processor_id: str=None, create_if_needed: bool=False, large_format: bool=False) -> DataItem: """Get the data item associated with hardware source and (optional) channel id and processor_id. Optionally create if missing. :param hardware_s...
The associated data item. May be None. .. versionadded:: 1.0 Status: Provisional Scriptable: Yes """ ...
def get_data_item_for_reference_key(self, data_item_reference_key: str=None, create_if_needed: bool=False, large_format: bool=False) -> DataItem: """Get the data item associated with data item reference key. Optionally create if missing. :param data_item_reference_key: The data item reference key. :param create_if_need...
def show_get_string_message_box(self, caption: str, text: str, accepted_fn, rejected_fn=None, accepted_text: str=None, rejected_text: str=None) -> None: """Show a dialog box and ask for a string. Caption describes the user prompt. Text is the initial/default string. Accepted function must be a function taking one argum...
Rejected function can be a function taking no arguments, called if the user clicks Cancel. .. versionadded:: 1.0 Scriptable: No """ ...
def create_calibration(self, offset: float=None, scale: float=None, units: str=None) -> Calibration.Calibration: """Create a calibration object with offset, scale, and units. :param offset: The offset of the calibration. :param scale: The scale of the calibration. :param units: The units of the calibration as a string....
+ value * scale` """ ...
def create_data_and_metadata(self, data: numpy.ndarray, intensity_calibration: Calibration.Calibration=None, dimensional_calibrations: typing.List[Calibration.Calibration]=None, metadata: dict=None, timestamp: str=None, data_descriptor: DataAndMetadata.DataDescriptor=None) -> DataAndMetadata.DataAndMetadata: """Create ...
Scriptable: Yes """ ...
def create_data_and_metadata_from_data(self, data: numpy.ndarray, intensity_calibration: Calibration.Calibration=None, dimensional_calibrations: typing.List[Calibration.Calibration]=None, metadata: dict=None, timestamp: str=None) -> DataAndMetadata.DataAndMetadata: """Create a data_and_metadata object from data. .. ver...
def create_data_descriptor(self, is_sequence: bool, collection_dimension_count: int, datum_dimension_count: int) -> DataAndMetadata.DataDescriptor: """Create a data descriptor. :param is_sequence: whether the descriptor describes a sequence of data. :param collection_dimension_count: the number of collection dimensions...
def make_calibration_row_widget(ui, calibration_observable, label: str=None): """Called when an item (calibration_observable) is inserted into the list widget. Returns a widget.""" calibration_row = ui.create_row_widget() row_label = ui.create_label_widget(label, properties={"width": 60}) row_label.widget_id = "label" ...
the binding of calibration_index below. calibration_row.add(row_label) calibration_row.add_spacing(12) calibration_row.add(offset_field) calibration_row.add_spacing(12) calibration_row.add(scale_field) calibration_row.add_spacing(12) calibration_row.add(units_field) calibration_row.add_stretch() return calibration_row
def add_widget_to_content(self, widget): """Subclasses should call this to add content in the section's top level column.""" self.__section_content_column.add_spacing(4) self.__section_content_column.add(widget)
def __create_list_item_widget(self, ui, calibration_observable): """Called when an item (calibration_observable) is inserted into the list widget. Returns a widget.""" calibration_row = make_calibration_row_widget(ui, calibration_observable) column = ui.create_column_widget() column.add_spacing(4) column.add(calibratio...
def _repaint(self, drawing_context): """Repaint the canvas item. This will occur on a thread.""" # canvas size canvas_width = self.canvas_size[1] canvas_height = self.canvas_size[0] left = self.display_limits[0] right = self.display_limits[1] # draw left display limit if left > 0.0: with drawing_context.saver(): drawin...
with drawing_context.saver(): drawing_context.begin_path() drawing_context.move_to(right * canvas_width, 1) drawing_context.line_to(right * canvas_width, canvas_height-1) drawing_context.line_width = 2 drawing_context.stroke_style = "#FFF" drawing_context.stroke() # draw border with drawing_context.saver(): drawing_con...
def _repaint(self, drawing_context): """Repaint the canvas item. This will occur on a thread.""" # canvas size canvas_width = self.canvas_size[1] canvas_height = self.canvas_size[0] # draw background if self.background_color: with drawing_context.saver(): drawing_context.begin_path() drawing_context.move_to(0,0) drawin...
Image.rebin_1d(self.data, int(canvas_width), self.__retained_rebin_1d) if int(canvas_width) != self.data.shape[0] else self.data for i in range(canvas_width): drawing_context.move_to(i, canvas_height) drawing_context.line_to(i, canvas_height * (1 - binned_data[i])) drawing_context.line_width = 1 drawing_context.stroke_...
def color_map_data(self, data: numpy.ndarray) -> None: """Set the data and mark the canvas item for updating. Data should be an ndarray of shape (256, 3) with type uint8 """ self.__color_map_data = data self.update()
def _repaint(self, drawing_context: DrawingContext.DrawingContext): """Repaint the canvas item. This will occur on a thread.""" # canvas size canvas_width = self.canvas_size.width canvas_height = self.canvas_size.height with drawing_context.saver(): if self.__color_map_data is not None: rgba_image = numpy.empty((4,) + ...
def get_params(self): "Parameters used to initialize the class" import inspect a = inspect.getargspec(self.__init__)[0] out = dict() for key in a[1:]: value = getattr(self, "_%s" % key, None) out[key] = value return out
def signature(self): "Instance file name" kw = self.get_params() keys = sorted(kw.keys()) l = [] for k in keys: n = k[0] + k[-1] v = kw[k] if k == 'function_set': v = "_".join([x.__name__[0] + x.__name__[-1] + str(x.nargs) for x in kw[k]]) elif k == 'population_class': v = kw[k].__name__ else: v = str(v) l.append('{0}_...
def population(self): "Class containing the population and all the individuals generated" try: return self._p except AttributeError: self._p = self._population_class(base=self, tournament_size=self._tournament_size, classifier=self.classifier, labels=self._labels, es_extra_test=self.es_extra_test, popsize=self._popsize...
def random_leaf(self): "Returns a random variable with the associated weight" for i in range(self._number_tries_feasible_ind): var = np.random.randint(self.nvar) v = self._random_leaf(var) if v is None: continue return v raise RuntimeError("Could not find a suitable random leaf")
def random_offspring(self): "Returns an offspring with the associated weight(s)" function_set = self.function_set function_selection = self._function_selection_ins function_selection.density = self.population.density function_selection.unfeasible_functions.clear() for i in range(self._number_tries_feasible_ind): if sel...
f raise RuntimeError("Could not find a suitable random offpsring")
def stopping_criteria(self): "Test whether the stopping criteria has been achieved." if self.stopping_criteria_tl(): return True if self.generations < np.inf: inds = self.popsize * self.generations flag = inds <= len(self.population.hist) else: flag = False if flag: return True est = self.population.estopping if self._...
not None and est is not None: position = self.population.estopping.position if position < self.init_popsize: position = self.init_popsize return (len(self.population.hist) + self._unfeasible_counter - position) > esr return flag
def nclasses(self, v): "Number of classes of v, also sets the labes" if not self.classifier: return 0 if isinstance(v, list): self._labels = np.arange(len(v)) return if not isinstance(v, np.ndarray): v = tonparray(v) self._labels = np.unique(v) return self._labels.shape[0]
def fit(self, X, y, test_set=None): """Evolutive process""" self._init_time = time.time() self.X = X if self._popsize == "nvar": self._popsize = self.nvar + len(self._input_functions) if isinstance(test_set, str) and test_set == 'shuffle': test_set = self.shuffle_tr2ts() nclasses = self.nclasses(y) if self.classifier a...
for _ in range(self._number_tries_feasible_ind): self._logger.info("Starting evolution") try: self.create_population() if self.stopping_criteria_tl(): break except RuntimeError as err: self._logger.info("Done evolution (RuntimeError (%s), hist: %s)" % (err, len(self.population.hist))) return self self._logger.info("Pop...
in range(self.nvar): self._X[x] = None while not self.stopping_criteria(): try: a = self.random_offspring() except RuntimeError as err: self._logger.info("Done evolution (RuntimeError (%s), hist: %s)" % (err, len(self.population.hist))) return self self.replace(a) self._logger.info("Done evolution (hist: %s)" % len(sel...
def decision_function(self, v=None, X=None): "Decision function i.e. the raw data of the prediction" m = self.model(v=v) return m.decision_function(X)
def predict(self, v=None, X=None): """In classification this returns the classes, in regression it is equivalent to the decision function""" if X is None: X = v v = None m = self.model(v=v) return m.predict(X)
def serve(application, host='127.0.0.1', port=8080): """Gevent-based WSGI-HTTP server.""" # Instantiate the server with a host/port configuration and our application. WSGIServer((host, int(port)), application).serve_forever()
def get_subscribers(obj): """ Returns the subscribers for a given object. :param obj: Any object. """ ctype = ContentType.objects.get_for_model(obj) return Subscription.objects.filter(content_type=ctype, object_id=obj.pk)
def is_subscribed(user, obj): """ Returns ``True`` if the user is subscribed to the given object. :param user: A ``User`` instance. :param obj: Any object. """ if not user.is_authenticated(): return False ctype = ContentType.objects.get_for_model(obj) try: Subscription.objects.get( user=user, content_type=ctype, object...
def _promote(self, name, instantiate=True): """Create a new subclass of Context which incorporates instance attributes and new descriptors. This promotes an instance and its instance attributes up to being a class with class attributes, then returns an instance of that class. """ metaclass = type(self.__class__) conten...
def run_individual(sim_var, reference, neuroml_file, nml_doc, still_included, generate_dir, target, sim_time, dt, simulator, cleanup = True, show=False): """ Run an individual simulation. The candidate data has been flattened into the sim_var dict. The sim_var dict contains parameter:value key value pairs, which are ap...
id1 = words[0].split(':') if ':' in words[1]: variable, id2 = words[1].split(':') else: variable = words[1] id2 = None units = words[2] value = sim_var[var_name] pyneuroml.pynml.print_comment_v(' Changing value of %s (%s) in %s (%s) to: %s %s'%(variable, id2, type, id1, value, units)) if type == 'channel': channel = nm...
not find channel with id %s from expression: %s'%(id1, individual_var_name)) exit() elif type == 'cell': cell = None for c in nml_doc.cells: if c.id == id1: cell = c if variable == 'channelDensity': chanDens = None for cd in cell.biophysical_properties.membrane_properties.channel_densities + cell.biophysical_properties...
cell.biophysical_properties.membrane_properties.channel_density_v_shifts: if cd.id == id2: chanDens = cd chanDens.v_shift = '%s %s'%(value, units) elif variable == 'channelDensityNernst': chanDens = None for cd in cell.biophysical_properties.membrane_properties.channel_density_nernsts: if cd.id == id2: chanDens = cd ch...
== id2: chanDens = cd chanDens.erev = '%s %s'%(value, units) elif variable == 'erev_ion': # change all values of erev in channelDensity elements with this ion chanDens = None for cd in cell.biophysical_properties.membrane_properties.channel_densities + cell.biophysical_properties.membrane_properties.channel_density_v_s...
== 'all') or sc.segment_groups == id2 : specCap = sc specCap.value = '%s %s'%(value, units) elif variable == 'resistivity': resistivity = None for rs in cell.biophysical_properties.intracellular_properties.resistivities: if (rs.segment_groups == None and id2 == 'all') or rs.segment_groups == id2 : resistivity = rs resi...
for c in nml_doc.izhikevich2007_cells: if c.id == id1: izhcell = c izhcell.__setattr__(variable, '%s %s'%(value, units)) else: pyneuroml.pynml.print_comment_v('Unknown type (%s) in variable expression: %s'%(type, individual_var_name)) new_neuroml_file = '%s/%s'%(generate_dir,os.path.basename(neuroml_file)) if new_neuro...
file %s to %s (%s) beside %s"%(inc_loc, generate_dir,os.path.abspath(generate_dir), new_neuroml_file)) shutil.copy(inc_loc, generate_dir) from pyneuroml.tune.NeuroMLSimulation import NeuroMLSimulation sim = NeuroMLSimulation(reference, neuroml_file = new_neuroml_file, target = target, sim_time = sim_time, dt = dt, simu...
def run(self,candidates,parameters): """ Run simulation for each candidate This run method will loop through each candidate and run the simulation corresponding to its parameter values. It will populate an array called traces with the resulting voltage traces for the simulation and return it. """ traces = [] start_time...
pyneuroml.pynml.print_comment_v('\n\n - RUN %i (%i/%i); variables: %s\n'%(self.count,candidate_i+1,len(candidates),sim_var)) self.count+=1 t,v = self.run_individual(sim_var) traces.append([t,v]) else: import pp ppservers = () job_server = pp.Server(self.num_parallel_evaluations, ppservers=ppservers) pyneuroml.pynml.pri...
self.ref, self.neuroml_file, self.nml_doc, self.still_included, cand_dir, self.target, self.sim_time, self.dt, self.simulator) job = job_server.submit(run_individual, vars, (), ("pyneuroml.pynml",'pyneuroml.tune.NeuroMLSimulation','shutil','neuroml')) jobs.append(job) for job_i in range(len(jobs)): job = jobs[job_i] py...
def prepare(self, context): """Executed prior to processing a request.""" if __debug__: log.debug("Assigning thread local request context.") self.local.context = context
def register(self, kind, handler): """Register a handler for a given type, class, interface, or abstract base class. View registration should happen within the `start` callback of an extension. For example, to register the previous `json` view example: class JSONExtension: def start(self, context): context.view.registe...
it, however there is another approach. Using named handlers registered as discrete plugins (via the `entry_point` argument in `setup.py`) allows the extension to easily ask "what's my handler?" class JSONExtension: def start(self, context): context.view.register( tuple, context.view.json ) Otherwise unknown attributes ...
completely skipped, regardless of logging level. if py3 and not pypy: # Where possible, we shorten things to just the cannonical name. log.debug("Registering view handler.", extra=dict(type=name(kind), handler=name(handler))) else: # Canonical name lookup is not entirely reliable on some combinations. log.debug("Regist...
self._map.add(kind, handler) return handler
def static(base, mapping=None, far=('js', 'css', 'gif', 'jpg', 'jpeg', 'png', 'ttf', 'woff')): """Serve files from disk. This utility endpoint factory is meant primarily for use in development environments; in production environments it is better (more efficient, secure, etc.) to serve your static content using a front...
below the attachment point for the generated endpoint will combine this base path with the remaining path elements to determine the file to serve. The second argument is an optional dictionary mapping filename extensions to template engines, for cooperation with the TemplateExtension. (See: https://github.com/marrow/te...
`.html` files as Mako templates, you would attach something like the following: class Root: page = static('/path/to/static/pages', dict(html='mako')) By default the "usual culprits" are served with far-futures cache expiry headers. If you wish to change the extensions searched just assign a new `far` iterable. To disab...
__debug__: log.debug("Attempting to serve static file.", extra=dict( request = id(context), base = base, path = path )) if not path.startswith(base): # Ensure we only serve files from the allowed path. raise HTTPForbidden("Cowardly refusing to violate base path policy." if __debug__ else None) if not exists(path): # Do...
normal files; no UNIX domain sockets, FIFOs, etc., etc. raise HTTPForbidden("Cowardly refusing to open a non-file." if __debug__ else None) if far and path.rpartition('.')[2] in far: context.response.cache_expires = 60*60*24*365 if mapping: # Handle the mapping of filename extensions to 2-tuples. 'Cause why not? _, _, ...
def serve(application, host='127.0.0.1', port=8080): """Diesel-based (greenlet) WSGI-HTTP server. As a minor note, this is crazy. Diesel includes Flask, too. """ # Instantiate the server with a host/port configuration and our application. WSGIApplication(application, port=int(port), iface=host).run()
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser(description="A script for plotting files containing spike time data") parser.add_argument('spiketimeFiles', type=str, metavar='<spiketime file>', help='List of text file containing spike times', nargs='+') parser.add_argument('-f...
HDF5 file containing spike times') parser.add_argument('-rates', action='store_true', default=DEFAULTS['rates'], help='Show a plot of rates') parser.add_argument('-showPlotsAlready', action='store_true', default=DEFAULTS['show_plots_already'], help='Show plots once generated') parser.add_argument('-saveSpikePlotTo', ty...
def simple(application, host='127.0.0.1', port=8080): """Python-standard WSGI-HTTP server for testing purposes. The additional work performed here is to match the default startup output of "waitress". This is not a production quality interface and will be have badly under load. """ # Try to be handy as many terminals a...
operation. make_server(host, int(port), application).serve_forever()
def iiscgi(application): """A specialized version of the reference WSGI-CGI server to adapt to Microsoft IIS quirks. This is not a production quality interface and will behave badly under load. """ try: from wsgiref.handlers import IISCGIHandler except ImportError: print("Python 3.2 or newer is required.") if not __deb...
def serve(application, host='127.0.0.1', port=8080, socket=None, **options): """Basic FastCGI support via flup. This web server has many, many options. Please see the Flup project documentation for details. """ # Allow either on-disk socket (recommended) or TCP/IP socket use. if not socket: bindAddress = (host, int(por...
def _get_method_kwargs(self): """ Helper method. Returns kwargs needed to filter the correct object. Can also be used to create the correct object. """ method_kwargs = { 'user': self.user, 'content_type': self.ctype, 'object_id': self.content_object.pk, } return method_kwargs
def save(self, *args, **kwargs): """Adds a subscription for the given user to the given object.""" method_kwargs = self._get_method_kwargs() try: subscription = Subscription.objects.get(**method_kwargs) except Subscription.DoesNotExist: subscription = Subscription.objects.create(**method_kwargs) return subscription
def prepare(self, context): """Add the usual suspects to the context. This adds `request`, `response`, and `path` to the `RequestContext` instance. """ if __debug__: log.debug("Preparing request context.", extra=dict(request=id(context))) # Bridge in WebOb `Request` and `Response` objects. # Extensions shouldn't rely o...
server bridged to us. context.environ['web.base'] = context.request.script_name # Track the remaining (unprocessed) path elements. context.request.remainder = context.request.path_info.split('/') if context.request.remainder and not context.request.remainder[0]: del context.request.remainder[0] # Track the "breadcrumb ...
def dispatch(self, context, consumed, handler, is_endpoint): """Called as dispatch descends into a tier. The base extension uses this to maintain the "current url". """ request = context.request if __debug__: log.debug("Handling dispatch event.", extra=dict( request = id(context), consumed = consumed, handler = safe_na...
= [''] nConsumed = 0 if consumed: # Migrate path elements consumed from the `PATH_INFO` to `SCRIPT_NAME` WSGI environment variables. if not isinstance(consumed, (list, tuple)): consumed = consumed.split('/') for element in consumed: if element == context.request.path_info_peek(): context.request.path_info_pop() nConsum...
def render_none(self, context, result): """Render empty responses.""" context.response.body = b'' del context.response.content_length return True
def render_binary(self, context, result): """Return binary responses unmodified.""" context.response.app_iter = iter((result, )) # This wraps the binary string in a WSGI body iterable. return True
def render_file(self, context, result): """Perform appropriate metadata wrangling for returned open file handles.""" if __debug__: log.debug("Processing file-like object.", extra=dict(request=id(context), result=repr(result))) response = context.response response.conditional_response = True modified = mktime(gmtime(get...
# Seek back to the start of the file. response.body_file = result return True
def render_generator(self, context, result): """Attempt to serve generator responses through stream encoding. This allows for direct use of cinje template functions, which are generators, as returned views. """ context.response.encoding = 'utf8' context.response.app_iter = ( (i.encode('utf8') if isinstance(i, unicode) ...
def serve(application, host='127.0.0.1', port=8080): """CherryPy-based WSGI-HTTP server.""" # Instantiate the server with our configuration and application. server = CherryPyWSGIServer((host, int(port)), application, server_name=host) # Try to be handy as many terminals allow clicking links. print("serving on http://{0...
def colorize(self, string, rgb=None, ansi=None, bg=None, ansi_bg=None): '''Returns the colored string''' if not isinstance(string, str): string = str(string) if rgb is None and ansi is None: raise TerminalColorMapException( 'colorize: must specify one named parameter: rgb or ansi') if rgb is not None and ansi is not No...
and ansi_bg is not None: raise TerminalColorMapException( 'colorize: must specify only one named parameter: bg or ansi_bg') if rgb is not None: (closestAnsi, closestRgb) = self.convert(rgb) elif ansi is not None: (closestAnsi, closestRgb) = (ansi, self.colors[ansi]) if bg is None and ansi_bg is None: return "\033[38;5;...
(ansi_bg, self.colors[ansi_bg]) return "\033[38;5;{ansiCode:d}m\033[48;5;{bf:d}m{string:s}\033[0m".format(ansiCode=closestAnsi, bf=closestBgAnsi, string=string)
def render_serialization(self, context, result): """Render serialized responses.""" resp = context.response serial = context.serialize match = context.request.accept.best_match(serial.types, default_match=self.default) result = serial[match](result) if isinstance(result, str): result = result.decode('utf-8') resp.chars...
def serve(application, host='127.0.0.1', port=8080): """Eventlet-based WSGI-HTTP server. For a more fully-featured Eventlet-capable interface, see also [Spawning](http://pypi.python.org/pypi/Spawning/). """ # Instantiate the server with a bound port and with our application. server(listen(host, int(port)), application)