_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q30500 | nsdiffs | train | def nsdiffs(x, m, max_D=2, test='ocsb', **kwargs):
"""Estimate the seasonal differencing term, ``D``.
Perform a test of seasonality for different levels of ``D`` to
estimate the number of seasonal differences required to make a given time
series stationary. Will select the maximum value of ``D`` for wh... | python | {
"resource": ""
} |
q30501 | ndiffs | train | def ndiffs(x, alpha=0.05, test='kpss', max_d=2, **kwargs):
"""Estimate ARIMA differencing term, ``d``.
Perform a test of stationarity for different levels of ``d`` to
estimate the number of differences required to make a given time
series stationary. Will select the maximum value of ``d`` for which
... | python | {
"resource": ""
} |
q30502 | bind_df_model | train | def bind_df_model(model_fit, arima_results):
"""Set model degrees of freedom.
Older versions of statsmodels don't handle this issue. Sets the
model degrees of freedom in place if not already present.
Parameters
----------
model_fit : ARMA, ARIMA or SARIMAX
The fitted model.
arima_... | python | {
"resource": ""
} |
q30503 | get_compatible_pyplot | train | def get_compatible_pyplot(backend=None, debug=True):
"""Make the backend of MPL compatible.
In Travis Mac distributions, python is not installed as a framework. This
means that using the TkAgg backend is the best solution (so it doesn't
try to use the mac OS backend by default).
Parameters
---... | python | {
"resource": ""
} |
q30504 | _return_wrapper | train | def _return_wrapper(fits, return_all, start, trace):
"""If the user wants to get all of the models back, this will
return a list of the ARIMA models, otherwise it will just return
the model. If this is called from the end of the function, ``fits``
will already be a list.
We *know* that if a functio... | python | {
"resource": ""
} |
q30505 | AutoARIMA.fit | train | def fit(self, y, exogenous=None, **fit_args):
"""Fit the auto-arima estimator
Fit an AutoARIMA to a vector, ``y``, of observations with an
optional matrix of ``exogenous`` variables.
Parameters
----------
y : array-like or iterable, shape=(n_samples,)
The ti... | python | {
"resource": ""
} |
q30506 | autocorr_plot | train | def autocorr_plot(series, show=True):
"""Plot a series' auto-correlation.
A wrapper method for the Pandas ``autocorrelation_plot`` method.
Parameters
----------
series : array-like, shape=(n_samples,)
The series or numpy array for which to plot an auto-correlation.
show : bool, option... | python | {
"resource": ""
} |
q30507 | plot_acf | train | def plot_acf(series, ax=None, lags=None, alpha=None, use_vlines=True,
unbiased=False, fft=True, title='Autocorrelation',
zero=True, vlines_kwargs=None, show=True, **kwargs):
"""Plot a series' auto-correlation as a line plot.
A wrapper method for the statsmodels ``plot_acf`` method.
... | python | {
"resource": ""
} |
q30508 | plot_pacf | train | def plot_pacf(series, ax=None, lags=None, alpha=None, method='yw',
use_vlines=True, title='Partial Autocorrelation', zero=True,
vlines_kwargs=None, show=True, **kwargs):
"""Plot a series' partial auto-correlation as a line plot.
A wrapper method for the statsmodels ``plot_pacf`` met... | python | {
"resource": ""
} |
q30509 | load_airpassengers | train | def load_airpassengers(as_series=False):
"""Monthly airline passengers.
The classic Box & Jenkins airline data. Monthly totals of international
airline passengers, 1949 to 1960.
Parameters
----------
as_series : bool, optional (default=False)
Whether to return a Pandas series. If False... | python | {
"resource": ""
} |
q30510 | if_has_delegate | train | def if_has_delegate(delegate):
"""Wrap a delegated instance attribute function.
Creates a decorator for methods that are delegated in the presence of a
results wrapper. This enables duck-typing by ``hasattr`` returning True
according to the sub-estimator.
This function was adapted from scikit-lear... | python | {
"resource": ""
} |
q30511 | load_heartrate | train | def load_heartrate(as_series=False):
"""Uniform heart-rate data.
A sample of heartrate data borrowed from an
`MIT database <http://ecg.mit.edu/time-series/>`_. The sample consists
of 150 evenly spaced (0.5 seconds) heartrate measurements.
Parameters
----------
as_series : bool, optional (d... | python | {
"resource": ""
} |
q30512 | benchmark_is_constant | train | def benchmark_is_constant():
"""This benchmarks the "is_constant" function from ``pmdarima.arima.utils``
This was added in 0.6.2.
"""
# WINNER!
def is_const1(x):
"""This is the version in Pyramid 0.6.2.
Parameters
----------
x : np.ndarray
This is the arr... | python | {
"resource": ""
} |
q30513 | load_woolyrnq | train | def load_woolyrnq(as_series=False):
"""Quarterly production of woollen yarn in Australia.
This time-series records the quarterly production (in tonnes) of woollen
yarn in Australia between Mar 1965 and Sep 1994.
Parameters
----------
as_series : bool, optional (default=False)
Whether t... | python | {
"resource": ""
} |
q30514 | as_series | train | def as_series(x):
"""Cast as pandas Series.
Cast an iterable to a Pandas Series object. Note that the index
will simply be a positional ``arange`` and cannot be set in this
function.
Parameters
----------
x : array-like, shape=(n_samples,)
The 1d array on which to compute the auto ... | python | {
"resource": ""
} |
q30515 | c | train | def c(*args):
r"""Imitates the ``c`` function from R.
Since this whole library is aimed at re-creating in
Python what R has already done so well, the ``c`` function was created to
wrap ``numpy.concatenate`` and mimic the R functionality. Similar to R,
this works with scalars, iterables, and any mix... | python | {
"resource": ""
} |
q30516 | diff | train | def diff(x, lag=1, differences=1):
"""Difference an array.
A python implementation of the R ``diff`` function [1]. This computes lag
differences from an array given a ``lag`` and ``differencing`` term.
If ``x`` is a vector of length :math:`n`, ``lag=1`` and ``differences=1``,
then the computed res... | python | {
"resource": ""
} |
q30517 | _aicc | train | def _aicc(model_results, nobs):
"""Compute the corrected Akaike Information Criterion"""
aic = model_results.aic
df_model = model_results.df_model + 1 | python | {
"resource": ""
} |
q30518 | _append_to_endog | train | def _append_to_endog(endog, new_y):
"""Append to the endogenous array
Parameters
----------
endog : np.ndarray, shape=(n_samples, [1])
The existing endogenous array | python | {
"resource": ""
} |
q30519 | ARIMA.fit | train | def fit(self, y, exogenous=None, **fit_args):
"""Fit an ARIMA to a vector, ``y``, of observations with an
optional matrix of ``exogenous`` variables.
Parameters
----------
y : array-like or iterable, shape=(n_samples,)
The time-series to which to fit the ``ARIMA`` es... | python | {
"resource": ""
} |
q30520 | ARIMA.predict_in_sample | train | def predict_in_sample(self, exogenous=None, start=None,
end=None, dynamic=False):
"""Generate in-sample predictions from the fit ARIMA model. This can
be useful when wanting to visualize the fit, and qualitatively inspect
the efficacy of the model, or when wanting to co... | python | {
"resource": ""
} |
q30521 | ARIMA.predict | train | def predict(self, n_periods=10, exogenous=None,
return_conf_int=False, alpha=0.05):
"""Forecast future values
Generate predictions (forecasts) ``n_periods`` in the future.
Note that if ``exogenous`` variables were used in the model fit, they
will be expected for the pred... | python | {
"resource": ""
} |
q30522 | ARIMA.conf_int | train | def conf_int(self, alpha=0.05, **kwargs):
r"""Returns the confidence interval of the fitted parameters.
Returns
-------
alpha : float, optional (default=0.05)
The significance level for the confidence interval. ie.,
the default alpha = .05 returns a 95% confidenc... | python | {
"resource": ""
} |
q30523 | ARIMA.to_dict | train | def to_dict(self):
"""Get the ARIMA model as a dictionary
Return the dictionary representation of the ARIMA model
Returns
-------
res : dictionary
The ARIMA model as a dictionary.
"""
return {
'pvalues': self.pvalues(),
'resid... | python | {
"resource": ""
} |
q30524 | ARIMA.plot_diagnostics | train | def plot_diagnostics(self, variable=0, lags=10, fig=None, figsize=None):
"""Plot an ARIMA's diagnostics.
Diagnostic plots for standardized residuals of one endogenous variable
Parameters
----------
variable : integer, optional
Index of the endogenous variable for wh... | python | {
"resource": ""
} |
q30525 | BoxCoxEndogTransformer.transform | train | def transform(self, y, exogenous=None, **_):
"""Transform the new array
Apply the Box-Cox transformation to the array after learning the
lambda parameter.
Parameters
----------
y : array-like or None, shape=(n_samples,)
The endogenous (time-series) array.
... | python | {
"resource": ""
} |
q30526 | BoxCoxEndogTransformer.inverse_transform | train | def inverse_transform(self, y, exogenous=None):
"""Inverse transform a transformed array
Inverse the Box-Cox transformation on the transformed array. Note that
if truncation happened in the ``transform`` method, invertibility will
not be preserved, and the transformed array may not be p... | python | {
"resource": ""
} |
q30527 | _regularize | train | def _regularize(x, y, ties):
"""Regularize the values, make them ordered and remove duplicates.
If the ``ties`` parameter is explicitly set to 'ordered' then order
is already assumed. Otherwise, the removal process will happen.
Parameters
----------
x : array-like, shape=(n_samples,)
Th... | python | {
"resource": ""
} |
q30528 | approx | train | def approx(x, y, xout, method='linear', rule=1, f=0, yleft=None,
yright=None, ties='mean'):
"""Linearly interpolate points.
Return a list of points which (linearly) interpolate given data points,
or a function performing the linear (or constant) interpolation.
Parameters
----------
... | python | {
"resource": ""
} |
q30529 | BaseTransformer.fit_transform | train | def fit_transform(self, y, exogenous=None, **transform_kwargs):
"""Fit and transform the arrays
Parameters
----------
y : array-like or None, shape=(n_samples,)
The endogenous (time-series) array.
exogenous : array-like or None, shape=(n_samples, n_features), option... | python | {
"resource": ""
} |
q30530 | Pipeline.fit | train | def fit(self, y, exogenous=None, **fit_kwargs):
"""Fit the pipeline of transformers and the ARIMA model
Chain the time-series and exogenous arrays through a series of
transformations, fitting each stage along the way, finally fitting an
ARIMA or AutoARIMA model.
Parameters
... | python | {
"resource": ""
} |
q30531 | Pipeline.update | train | def update(self, y, exogenous=None, maxiter=None, **kwargs):
"""Update an ARIMA or auto-ARIMA as well as any necessary transformers
Passes the newly observed values through the appropriate endog
transformations, and the exogenous array through the exog transformers
(updating where neces... | python | {
"resource": ""
} |
q30532 | load_wineind | train | def load_wineind(as_series=False):
"""Australian total wine sales by wine makers in bottles <= 1 litre.
This time-series records wine sales by Australian wine makers between
Jan 1980 -- Aug 1994. This dataset is found in the R ``forecast`` package.
Parameters
----------
as_series : bool, optio... | python | {
"resource": ""
} |
q30533 | FourierFeaturizer.transform | train | def transform(self, y, exogenous=None, n_periods=0, **_):
"""Create Fourier term features
When an ARIMA is fit with an exogenous array, it must be forecasted
with one also. Since at ``predict`` time in a pipeline we won't have
``y`` (and we may not yet have an ``exog`` array), we have t... | python | {
"resource": ""
} |
q30534 | FourierFeaturizer.update_and_transform | train | def update_and_transform(self, y, exogenous, **kwargs):
"""Update the params and return the transformed arrays
Since no parameters really get updated in the Fourier featurizer, all
we do is compose forecasts for ``n_periods=len(y)`` and then update
``n_``.
Parameters
--... | python | {
"resource": ""
} |
q30535 | BaseARIMA.fit_predict | train | def fit_predict(self, y, exogenous=None, n_periods=10, **fit_args):
"""Fit an ARIMA to a vector, ``y``, of observations with an
optional matrix of ``exogenous`` variables, and then generate
predictions.
Parameters
----------
y : array-like or iterable, shape=(n_samples,)... | python | {
"resource": ""
} |
q30536 | inheritdoc | train | def inheritdoc(parent):
"""Inherit documentation from a parent
Parameters
----------
parent : callable
The parent function or class that contains the sought-after
docstring. If it doesn't have a docstring, this might behave
in unexpected ways.
Examples
--------
... | python | {
"resource": ""
} |
q30537 | load_austres | train | def load_austres(as_series=False):
"""Quarterly residential data.
Numbers (in thousands) of Australian residents measured quarterly from
March 1971 to March 1994.
Parameters
----------
as_series : bool, optional (default=False)
Whether to return a Pandas series. If False, will return a... | python | {
"resource": ""
} |
q30538 | SparkJobProgressMonitorOutput.display_with_id | train | def display_with_id(self, obj, display_id, update=False):
"""Create a new display with an id"""
ip = get_ipython()
if hasattr(ip, "kernel"):
data, md = ip.display_formatter.format(obj)
content = {
'data': data,
'metadata': md,
... | python | {
"resource": ""
} |
q30539 | get_caller_text | train | def get_caller_text(frame):
"""
Return the expression that calls the frame
"""
def find_match_node(node):
"Find a candidate ast node"
match_node = None
for chd in ast.iter_child_nodes(node):
if getattr(chd, "lineno", 0) > frame.f_back.f_lineno:
| python | {
"resource": ""
} |
q30540 | get_matches_lineno | train | def get_matches_lineno(code, fn_name):
"Return a list of line number corresponding to the definition of function with the name fn_name"
class Walker(ast.NodeVisitor):
def __init__(self):
self._hits = set()
#pylint: disable=E0213,E1102
def onvisit(fn):
def wra... | python | {
"resource": ""
} |
q30541 | tts_langs | train | def tts_langs():
"""Languages Google Text-to-Speech supports.
Returns:
dict: A dictionnary of the type `{ '<lang>': '<name>'}`
Where `<lang>` is an IETF language tag such as `en` or `pt-br`,
and `<name>` is the full English name of the language, such as
`English` or `Portuguese... | python | {
"resource": ""
} |
q30542 | tone_marks | train | def tone_marks(text):
"""Add a space after tone-modifying punctuation.
Because the `tone_marks` tokenizer case will split after a tone-modidfying
| python | {
"resource": ""
} |
q30543 | end_of_line | train | def end_of_line(text):
"""Re-form words cut by end-of-line hyphens.
Remove "<hyphen><newline>".
"""
return PreProcessorRegex(
| python | {
"resource": ""
} |
q30544 | abbreviations | train | def abbreviations(text):
"""Remove periods after an abbreviation from a list of known
abbrevations that can be spoken the same without that period. This
prevents having to handle tokenization of that period.
Note:
Could potentially remove the ending period of a sentence.
Note:
Abbr... | python | {
"resource": ""
} |
q30545 | tone_marks | train | def tone_marks():
"""Keep tone-modifying punctuation by matching following character.
Assumes the `tone_marks` pre-processor was run for cases where there might
not be any space after a tone-modifying punctuation mark.
| python | {
"resource": ""
} |
q30546 | period_comma | train | def period_comma():
"""Period and comma case.
Match if not preceded by ".<letter>" and only if followed by space.
Won't cut in the middle/after dotted abbreviations; won't cut numbers.
Note:
Won't match if a dotted abbreviation ends a sentence.
Note:
| python | {
"resource": ""
} |
q30547 | colon | train | def colon():
"""Colon case.
Match a colon ":" only if not preceeded by a digit.
Mainly to prevent a cut in the middle of time notations e.g. 10:01
"""
| python | {
"resource": ""
} |
q30548 | other_punctuation | train | def other_punctuation():
"""Match other punctuation.
Match other punctuation to split on; punctuation that naturally
inserts a break in speech.
"""
punc = ''.join(
set(symbols.ALL_PUNC) -
set(symbols.TONE_MARKS) -
set(symbols.PERIOD_COMMA) -
| python | {
"resource": ""
} |
q30549 | legacy_all_punctuation | train | def legacy_all_punctuation(): # pragma: no cover b/c tested but Coveralls: ¯\_(ツ)_/¯
"""Match all punctuation.
Use as only tokenizer case to mimic gTTS 1.x tokenization.
"""
punc = | python | {
"resource": ""
} |
q30550 | gTTS.write_to_fp | train | def write_to_fp(self, fp):
"""Do the TTS API request and write bytes to a file-like object.
Args:
fp (file object): Any file-like object to write the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request.
TypeError: When ``fp`` i... | python | {
"resource": ""
} |
q30551 | gTTS.save | train | def save(self, savefile):
"""Do the TTS API request and write result to file.
Args:
savefile (string): The path and file name to save the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request.
| python | {
"resource": ""
} |
q30552 | _minimize | train | def _minimize(the_string, delim, max_size):
"""Recursively split a string in the largest chunks
possible from the highest position of a delimiter all the way
to a maximum size
Args:
the_string (string): The string to split.
delim (string): The delimiter to split on.
max_size (in... | python | {
"resource": ""
} |
q30553 | PreProcessorRegex.run | train | def run(self, text):
"""Run each regex substitution on ``text``.
Args:
text (string): the input text.
Returns:
string: text after all substitutions have been sequentially
applied.
| python | {
"resource": ""
} |
q30554 | PreProcessorSub.run | train | def run(self, text):
"""Run each substitution on ``text``.
Args:
text (string): the input text.
Returns:
| python | {
"resource": ""
} |
q30555 | Stemmer.vowel_in_stem | train | def vowel_in_stem(self):
""" True iff 0...j contains vowel """
for i in range(0, self.j+1):
| python | {
"resource": ""
} |
q30556 | Stemmer.doublec | train | def doublec(self, j):
""" True iff j, j-1 contains double consonant """ | python | {
"resource": ""
} |
q30557 | Stemmer.ends | train | def ends(self, s):
length = len(s)
""" True iff 0...k ends with string s """
res = (self.b[self.k-length+1:self.k+1] == s)
| python | {
"resource": ""
} |
q30558 | Stemmer.setto | train | def setto(self, s):
""" set j+1...k to string s, readjusting k """
length = len(s)
| python | {
"resource": ""
} |
q30559 | Stemmer.step1c | train | def step1c(self):
""" turn terminal y into i if there's a vowel in stem """
| python | {
"resource": ""
} |
q30560 | Board.setup_layout | train | def setup_layout(self, board_layout):
"""
Setup the Pin instances based on the given board layout.
"""
# Create pin instances based on board layout
self.analog = []
for i in board_layout['analog']:
self.analog.append(Pin(self, i))
self.digital = []
... | python | {
"resource": ""
} |
q30561 | Board.auto_setup | train | def auto_setup(self):
"""
Automatic setup based on Firmata's "Capability Query"
"""
self.add_cmd_handler(CAPABILITY_RESPONSE, self._handle_report_capability_response)
self.send_sysex(CAPABILITY_QUERY, [])
self.pass_time(0.1) # Serial SYNC
while self.bytes_availa... | python | {
"resource": ""
} |
q30562 | Board.add_cmd_handler | train | def add_cmd_handler(self, cmd, func):
"""Adds a command handler for a command."""
len_args = len(inspect.getargspec(func)[0])
def add_meta(f):
def decorator(*args, **kwargs):
f(*args, **kwargs)
decorator.bytes_needed = len_args - | python | {
"resource": ""
} |
q30563 | Board.get_pin | train | def get_pin(self, pin_def):
"""
Returns the activated pin given by the pin definition.
May raise an ``InvalidPinDefError`` or a ``PinAlreadyTakenError``.
:arg pin_def: Pin definition as described below,
but without the arduino name. So for example ``a:1:i``.
'a' ana... | python | {
"resource": ""
} |
q30564 | Board.pass_time | train | def pass_time(self, t):
"""Non-blocking time-out for ``t`` seconds."""
cont = time.time() + t
| python | {
"resource": ""
} |
q30565 | Board.send_sysex | train | def send_sysex(self, sysex_cmd, data):
"""
Sends a SysEx msg.
:arg sysex_cmd: A sysex command byte
: arg data: a bytearray of 7-bit bytes of arbitrary data
| python | {
"resource": ""
} |
q30566 | Board.servo_config | train | def servo_config(self, pin, min_pulse=544, max_pulse=2400, angle=0):
"""
Configure a pin as servo with min_pulse, max_pulse and first angle.
``min_pulse`` and ``max_pulse`` default to the arduino defaults.
"""
if pin > len(self.digital) or self.digital[pin].mode == UNAVAILABLE:
| python | {
"resource": ""
} |
q30567 | Board.exit | train | def exit(self):
"""Call this to exit cleanly."""
# First detach all servo's, otherwise it somehow doesn't want to close...
if hasattr(self, 'digital'):
for pin in self.digital:
| python | {
"resource": ""
} |
q30568 | Board._handle_digital_message | train | def _handle_digital_message(self, port_nr, lsb, msb):
"""
Digital messages always go by the whole port. This means we have a
bitmask which we update the port.
"""
mask = (msb << 7) | python | {
"resource": ""
} |
q30569 | Port.enable_reporting | train | def enable_reporting(self):
"""Enable reporting of values for the whole port."""
self.reporting = True
msg = bytearray([REPORT_DIGITAL + self.port_number, 1])
self.board.sp.write(msg)
| python | {
"resource": ""
} |
q30570 | Port.disable_reporting | train | def disable_reporting(self):
"""Disable the reporting of the port."""
| python | {
"resource": ""
} |
q30571 | Port.write | train | def write(self):
"""Set the output pins of the port to the correct state."""
mask = 0
for pin in self.pins:
if pin.mode == OUTPUT:
if pin.value == 1:
pin_nr = pin.pin_number - self.port_number * 8
mask |= 1 << int(pin_nr)
# | python | {
"resource": ""
} |
q30572 | Port._update | train | def _update(self, mask):
"""Update the values for the pins marked as input with the mask."""
if self.reporting:
for pin in self.pins:
if pin.mode is INPUT:
| python | {
"resource": ""
} |
q30573 | Pin.enable_reporting | train | def enable_reporting(self):
"""Set an input pin to report values."""
if self.mode is not INPUT:
raise IOError("{0} is not an input and can therefore not report".format(self))
if self.type == ANALOG:
self.reporting = True
| python | {
"resource": ""
} |
q30574 | Pin.disable_reporting | train | def disable_reporting(self):
"""Disable the reporting of an input pin."""
if self.type == ANALOG:
self.reporting = False
| python | {
"resource": ""
} |
q30575 | Pin.write | train | def write(self, value):
"""
Output a voltage from the pin
:arg value: Uses value as a boolean if the pin is in output mode, or
expects a float from 0 to 1 if the pin is in PWM mode. If the pin
is in SERVO the value should be in degrees.
"""
if self.mode ... | python | {
"resource": ""
} |
q30576 | get_the_board | train | def get_the_board(
layout=BOARDS["arduino"], base_dir="/dev/", identifier="tty.usbserial"
):
"""
Helper function to get the one and only board connected to the computer
running this. It assumes a normal arduino layout, but this can be
overriden by passing a different layout dict as the ``layout`` pa... | python | {
"resource": ""
} |
q30577 | from_two_bytes | train | def from_two_bytes(bytes):
"""
Return an integer from two 7 bit bytes.
"""
lsb, msb = bytes
try:
# Usually bytes have been converted to integers with ord already
return msb << 7 | lsb
| python | {
"resource": ""
} |
q30578 | two_byte_iter_to_str | train | def two_byte_iter_to_str(bytes):
"""
Return a string made from a list of two byte chars.
"""
bytes = list(bytes)
chars = bytearray()
while bytes:
lsb = bytes.pop(0)
try:
| python | {
"resource": ""
} |
q30579 | str_to_two_byte_iter | train | def str_to_two_byte_iter(string):
"""
Return a iter consisting of two byte chars from a string.
"""
bstring = string.encode()
bytes = | python | {
"resource": ""
} |
q30580 | MockupSerial.write | train | def write(self, value):
"""
Appends bytes flat to the deque. So iterables will be unpacked.
"""
if hasattr(value, '__iter__'):
bytearray(value)
| python | {
"resource": ""
} |
q30581 | get_profile | train | def get_profile(name=None, **kwargs):
"""Get the profile by name; if no name is given, return the
default profile.
"""
if isinstance(name, Profile):
| python | {
"resource": ""
} |
q30582 | get_profile_class | train | def get_profile_class(name):
"""For the given profile name, load the data from the external
database, then generate dynamically a class.
"""
if name not in CLASS_CACHE:
profile_data = PROFILES[name]
profile_name = clean(name)
class_name = '{}{}Profile'.format(
| python | {
"resource": ""
} |
q30583 | BaseProfile.get_font | train | def get_font(self, font):
"""Return the escpos index for `font`. Makes sure that
the requested `font` is valid.
"""
font = | python | {
"resource": ""
} |
q30584 | BaseProfile.get_columns | train | def get_columns(self, font):
""" Return the number of columns for the given font.
"""
| python | {
"resource": ""
} |
q30585 | Config._reset_config | train | def _reset_config(self):
""" Clear the loaded configuration.
If we are loading a changed config, we don't want to have leftover
data.
"""
self._has_loaded = False
| python | {
"resource": ""
} |
q30586 | Config.load | train | def load(self, config_path=None):
""" Load and parse the configuration file using pyyaml
:param config_path: An optional file path, file handle, or byte string
for the configuration file.
"""
self._reset_config()
if not config_path:
config_path = os.pa... | python | {
"resource": ""
} |
q30587 | Config.printer | train | def printer(self):
""" Returns a printer that was defined in the config, or throws an
exception.
This method loads the default config if one hasn't beeen already loaded.
"""
if not self._has_loaded:
self.load()
if not self._printer_name:
raise e... | python | {
"resource": ""
} |
q30588 | Usb.open | train | def open(self, usb_args):
""" Search device on USB tree and set it as escpos device.
:param usb_args: USB arguments
"""
self.device = usb.core.find(**usb_args)
if self.device is None:
raise USBNotFoundError("Device not found or cable not plugged in.")
self.i... | python | {
"resource": ""
} |
q30589 | Usb.close | train | def close(self):
""" Release USB interface """
if self.device:
| python | {
"resource": ""
} |
q30590 | Serial.close | train | def close(self):
""" Close Serial interface """
if self.device is | python | {
"resource": ""
} |
q30591 | Network.open | train | def open(self):
""" Open TCP socket with ``socket``-library and set it as escpos device """
self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.device.settimeout(self.timeout)
| python | {
"resource": ""
} |
q30592 | File.open | train | def open(self):
""" Open system file """
self.device = open(self.devfile, "wb")
if self.device is None:
| python | {
"resource": ""
} |
q30593 | encode_katakana | train | def encode_katakana(text):
"""I don't think this quite works yet."""
encoded = []
for char in text:
if jaconv:
# try to convert japanese text to half-katakanas
char = jaconv.z2h(jaconv.hira2kata(char))
# TODO: "the conversion may result in multiple characters"
... | python | {
"resource": ""
} |
q30594 | EscposImage.to_column_format | train | def to_column_format(self, high_density_vertical=True):
"""
Extract slices of an image as equal-sized blobs of column-format data.
:param high_density_vertical: Printed line height in dots
"""
im = self._im.transpose(Image.ROTATE_270).transpose(Image.FLIP_LEFT_RIGHT)
lin... | python | {
"resource": ""
} |
q30595 | EscposImage.split | train | def split(self, fragment_height):
"""
Split an image into multiple fragments after fragment_height pixels
:param fragment_height: height of fragment
:return: list of PIL objects
"""
passes = int(math.ceil(self.height/fragment_height))
fragments = []
for n... | python | {
"resource": ""
} |
q30596 | EscposImage.center | train | def center(self, max_width):
"""In-place image centering
:param: Maximum width in order to deduce x offset for centering
:return: None
"""
old_width, height = self._im.size
new_size = (max_width, height)
new_im = | python | {
"resource": ""
} |
q30597 | demo | train | def demo(printer, **kwargs):
"""
Prints specificed demos. Called when CLI is passed `demo`. This function
uses the DEMO_FUNCTIONS dictionary.
:param printer: A printer from escpos.printer
:param kwargs: A dict with a key for each function you want to test. It's
in this format since it usual... | python | {
"resource": ""
} |
q30598 | Encoder.get_encoding_name | train | def get_encoding_name(self, encoding):
"""Given an encoding provided by the user, will return a
canonical encoding name; and also validate that the encoding
is supported.
TODO: Support encoding aliases: pc437 instead of cp437.
| python | {
"resource": ""
} |
q30599 | Encoder._get_codepage_char_list | train | def _get_codepage_char_list(encoding):
"""Get codepage character list
Gets characters 128-255 for a given code page, as an array.
:param encoding: The name of the encoding. This must appear in the CodePage list
"""
codepage = CodePages.get_encoding(encoding)
if 'data' i... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.