code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
data = clips.data.DataObject(self._env)
if lib.EnvGetDefglobalValue(
self._env, self.name.encode(), data.byref) != 1:
raise CLIPSError(self._env)
return data.value | def value(self) | Global value. | 14.066885 | 11.374062 | 1.236751 |
return ffi.string(
lib.EnvGetDefglobalName(self._env, self._glb)).decode() | def name(self) | Global name. | 30.238077 | 19.306301 | 1.566228 |
modname = ffi.string(lib.EnvDefglobalModule(self._env, self._glb))
defmodule = lib.EnvFindDefmodule(self._env, modname)
return Module(self._env, defmodule) | def module(self) | The module in which the Global is defined.
Python equivalent of the CLIPS defglobal-module command. | 10.907097 | 6.834846 | 1.595807 |
lib.EnvSetDefglobalWatch(self._env, int(flag), self._glb) | def watch(self, flag) | Whether or not the Global is being watched. | 49.071358 | 31.816757 | 1.542312 |
if lib.EnvUndefglobal(self._env, self._glb) != 1:
raise CLIPSError(self._env)
self._env = None | def undefine(self) | Undefine the Global.
Python equivalent of the CLIPS undefglobal command.
The object becomes unusable after this method has been called. | 21.682037 | 13.683454 | 1.584544 |
return ffi.string(
lib.EnvGetDefmoduleName(self._env, self._mdl)).decode() | def name(self) | Global name. | 39.48716 | 28.780842 | 1.371995 |
deffunction = lib.EnvGetNextDeffunction(self._env, ffi.NULL)
while deffunction != ffi.NULL:
yield Function(self._env, deffunction)
deffunction = lib.EnvGetNextDeffunction(self._env, deffunction) | def functions(self) | Iterates over the defined Globals. | 4.217135 | 3.936982 | 1.071159 |
deffunction = lib.EnvFindDeffunction(self._env, name.encode())
if deffunction == ffi.NULL:
raise LookupError("Function '%s' not found" % name)
return Function(self._env, deffunction) | def find_function(self, name) | Find the Function by its name. | 4.190552 | 3.711089 | 1.129197 |
defgeneric = lib.EnvGetNextDefgeneric(self._env, ffi.NULL)
while defgeneric != ffi.NULL:
yield Generic(self._env, defgeneric)
defgeneric = lib.EnvGetNextDefgeneric(self._env, defgeneric) | def generics(self) | Iterates over the defined Generics. | 6.169922 | 4.801214 | 1.285076 |
defgeneric = lib.EnvFindDefgeneric(self._env, name.encode())
if defgeneric == ffi.NULL:
raise LookupError("Generic '%s' not found" % name)
return Generic(self._env, defgeneric) | def find_generic(self, name) | Find the Generic by its name. | 5.31523 | 4.607732 | 1.153546 |
return ffi.string(
lib.EnvGetDeffunctionName(self._env, self._fnc)).decode() | def name(self) | Function name. | 22.547785 | 14.719519 | 1.531829 |
modname = ffi.string(lib.EnvDeffunctionModule(self._env, self._fnc))
defmodule = lib.EnvFindDefmodule(self._env, modname)
return Module(self._env, defmodule) | def module(self) | The module in which the Function is defined.
Python equivalent of the CLIPS deffunction-module command. | 9.268104 | 6.372092 | 1.454484 |
lib.EnvSetDeffunctionWatch(self._env, int(flag), self._fnc) | def watch(self, flag) | Whether or not the Function is being watched. | 34.484779 | 22.083975 | 1.56153 |
if lib.EnvUndeffunction(self._env, self._fnc) != 1:
raise CLIPSError(self._env)
self._env = None | def undefine(self) | Undefine the Function.
Python equivalent of the CLIPS undeffunction command.
The object becomes unusable after this method has been called. | 15.429393 | 10.232152 | 1.507932 |
if lib.EnvUndefgeneric(self._env, self._gnc) != 1:
raise CLIPSError(self._env)
self._env = None | def undefine(self) | Undefine the Generic.
Python equivalent of the CLIPS undefgeneric command.
The object becomes unusable after this method has been called. | 22.145975 | 14.774216 | 1.498961 |
if lib.EnvUndefmethod(self._env, self._gnc, self._idx) != 1:
raise CLIPSError(self._env)
self._env = None | def undefine(self) | Undefine the Method.
Python equivalent of the CLIPS undefmethod command.
The object becomes unusable after this method has been called. | 20.066502 | 14.082079 | 1.424967 |
capped_series = np.minimum(
series, series.mean() + multiplier * series.std())
count = pd.value_counts(series != capped_series)
count = count[True] if True in count else 0
perc = self._percent(count / self.length)
return count, perc | def _get_deviation_of_mean(self, series, multiplier=3) | Returns count of values deviating of the mean, i.e. larger than `multiplier` * `std`.
:type series:
:param multiplier:
:return: | 5.499213 | 5.572425 | 0.986862 |
capped_series = np.minimum(
series, series.median() + multiplier * series.mad())
count = pd.value_counts(series != capped_series)
count = count[True] if True in count else 0
perc = self._percent(count / self.length)
return count, perc | def _get_median_absolute_deviation(self, series, multiplier=3) | Returns count of values larger than `multiplier` * `mad`
:type series:
:param multiplier:
:return (array): | 5.802502 | 6.023079 | 0.963378 |
columns_excluded = pd.Index([])
columns_included = df.columns
if usage == self.INCLUDE:
try:
columns_included = columns_included.intersection(pd.Index(columns))
except TypeError:
pass
elif usage == self.EXCLUDE:
... | def get_columns(self, df, usage, columns=None) | Returns a `data_frame.columns`.
:param df: dataframe to select columns from
:param usage: should be a value from [ALL, INCLUDE, EXCLUDE].
this value only makes sense if attr `columns` is also set.
otherwise, should be used with default value ALL.
... | 2.260909 | 2.272285 | 0.994994 |
# Plot fluorescence of beads populations
plt.plot(fl_rfi,
fl_mef,
'o',
label='Beads',
color=standard_curve_colors[0])
# Generate points in x axis to plot beads model and standard curve.
if xlim is None:
xlim = plt.xlim()
if xscale=='l... | def plot_standard_curve(fl_rfi,
fl_mef,
beads_model,
std_crv,
xscale='linear',
yscale='linear',
xlim=None,
ylim=(1.,1e8)) | Plot a standard curve with fluorescence of calibration beads.
Parameters
----------
fl_rfi : array_like
Fluorescence of the calibration beads' subpopulations, in RFI
units.
fl_mef : array_like
Fluorescence of the calibration beads' subpopulations, in MEF
units.
beads... | 1.946517 | 1.974378 | 0.985889 |
# Catch sheetname as list or None
if sheetname is None or \
(hasattr(sheetname, '__iter__') \
and not isinstance(sheetname, six.string_types)):
raise TypeError("sheetname should specify a single sheet")
# Load excel table using pandas
# Parameter specifying sheet na... | def read_table(filename, sheetname, index_col=None) | Return the contents of an Excel table as a pandas DataFrame.
Parameters
----------
filename : str
Name of the Excel file to read.
sheetname : str or int
Name or index of the sheet inside the Excel file to read.
index_col : str, optional
Column name or index to be used as row... | 3.490259 | 3.659248 | 0.953819 |
# Modify default header format
# Pandas' default header format is bold text with thin borders. Here we
# use bold text only, without borders.
# The header style structure is in pd.core.format in pandas<=0.18.0,
# pd.formats.format in 0.18.1<=pandas<0.20, and pd.io.formats.excel in
# pandas>... | def write_workbook(filename, table_list, column_width=None) | Write an Excel workbook from a list of tables.
Parameters
----------
filename : str
Name of the Excel file to write.
table_list : list of ``(str, DataFrame)`` tuples
Tables to be saved as individual sheets in the Excel table. Each
tuple contains two values: the name of the sheet... | 3.243129 | 3.231119 | 1.003717 |
# Extract channels that require stats histograms
headers = list(samples_table.columns)
hist_headers = [h for h in headers if re_units.match(h)]
hist_channels = [re_units.match(h).group(1) for h in hist_headers]
# The number of columns in the DataFrame has to be set to the maximum
# number ... | def generate_histograms_table(samples_table, samples, max_bins=1024) | Generate a table of histograms as a DataFrame.
Parameters
----------
samples_table : DataFrame
Table specifying samples to analyze. For more information about the
fields required in this table, please consult the module's
documentation.
samples : list
FCSData objects fro... | 3.408316 | 3.285875 | 1.037263 |
# Make keyword and value arrays
keywords = []
values = []
# FlowCal version
keywords.append('FlowCal version')
values.append(FlowCal.__version__)
# Analysis date and time
keywords.append('Date of analysis')
values.append(time.strftime("%Y/%m/%d"))
keywords.append('Time of an... | def generate_about_table(extra_info={}) | Make a table with information about FlowCal and the current analysis.
Parameters
----------
extra_info : dict, optional
Additional keyword:value pairs to include in the table.
Returns
-------
about_table : DataFrame
Table with information about FlowCal and the current analysis,... | 2.954134 | 2.357602 | 1.253025 |
# The following line is used to Tk's main window is not shown
Tk().withdraw()
# OSX ONLY: Call bash script to prevent file select window from sticking
# after use.
if platform.system() == 'Darwin':
subprocess.call("defaults write org.python.python " +
"ApplePersistenceI... | def show_open_file_dialog(filetypes) | Show an open file dialog and return the path of the file selected.
Parameters
----------
filetypes : list of tuples
Types of file to show on the dialog. Each tuple on the list must
have two elements associated with a filetype: the first element is
a description, and the second is th... | 6.736431 | 7.148593 | 0.942344 |
# Get arguments from ``sys.argv`` if necessary.
# ``sys.argv`` has the name of the script as its first element. We remove
# this element because it will break ``parser.parse_args()`` later. In fact,
# ``parser.parse_args()``, if provided with no arguments, will also use
# ``sys.argv`` after rem... | def run_command_line(args=None) | Entry point for the FlowCal and flowcal console scripts.
Parameters
----------
args: list of strings, optional
Command line arguments. If None or not specified, get arguments
from ``sys.argv``.
See Also
----------
FlowCal.excel_ui.run()
http://amir.rachum.com/blog/2017/07/... | 3.69515 | 3.355903 | 1.10109 |
fields = [
'version',
'text_begin',
'text_end',
'data_begin',
'data_end',
'analysis_begin',
'analysis_end']
FCSHeader = collections.namedtuple('FCSHeader', fields)
field_values = []
buf.seek(begin)
field_values.append(buf.read(10).decod... | def read_fcs_header_segment(buf, begin=0) | Read HEADER segment of FCS file.
Parameters
----------
buf : file-like object
Buffer containing data to interpret as HEADER segment.
begin : int
Offset (in bytes) to first byte of HEADER segment in `buf`.
Returns
-------
header : namedtuple
Version information and b... | 2.091989 | 1.973573 | 1.060001 |
# Get time channels indices
time_channel_idx = [idx
for idx, channel in enumerate(self.channels)
if channel.lower() == 'time']
if len(time_channel_idx) > 1:
raise KeyError("more than one time channel in data")
#... | def acquisition_time(self) | Acquisition time, in seconds.
The acquisition time is calculated using the 'time' channel by
default (channel name is case independent). If the 'time' channel
is not available, the acquisition_start_time and
acquisition_end_time, extracted from the $BTIM and $ETIM keyword
parame... | 3.115105 | 2.911875 | 1.069793 |
# Check default
if channels is None:
channels = self._channels
# Get numerical indices of channels
channels = self._name_to_index(channels)
# Get detector type of the specified channels
if hasattr(channels, '__iter__') \
and not isin... | def amplification_type(self, channels=None) | Get the amplification type used for the specified channel(s).
Each channel uses one of two amplification types: linear or
logarithmic. This function returns, for each channel, a tuple of
two numbers, in which the first number indicates the number of
decades covered by the logarithmic am... | 3.695888 | 4.207898 | 0.878322 |
# Check default
if channels is None:
channels = self._channels
# Get numerical indices of channels
channels = self._name_to_index(channels)
# Get detector type of the specified channels
if hasattr(channels, '__iter__') \
and not isin... | def detector_voltage(self, channels=None) | Get the detector voltage used for the specified channel(s).
The detector voltage for channel "n" is extracted from the $PnV
parameter, if available.
Parameters
----------
channels : int, str, list of int, list of str
Channel(s) for which to get the detector voltage.... | 3.834873 | 4.304756 | 0.890846 |
# Check default
if channels is None:
channels = self._channels
# Get numerical indices of channels
channels = self._name_to_index(channels)
# Get detector type of the specified channels
if hasattr(channels, '__iter__') \
and not isin... | def amplifier_gain(self, channels=None) | Get the amplifier gain used for the specified channel(s).
The amplifier gain for channel "n" is extracted from the $PnG
parameter, if available.
Parameters
----------
channels : int, str, list of int, list of str
Channel(s) for which to get the amplifier gain. If No... | 3.87161 | 4.28276 | 0.903999 |
# Check default
if channels is None:
channels = self._channels
# Get numerical indices of channels
channels = self._name_to_index(channels)
# Get the range of the specified channels
if hasattr(channels, '__iter__') \
and not isinstan... | def range(self, channels=None) | Get the range of the specified channel(s).
The range is a two-element list specifying the smallest and largest
values that an event in a channel should have. Note that with
floating point data, some events could have values outside the
range in either direction due to instrument compens... | 3.596635 | 3.671987 | 0.979479 |
# Check default
if channels is None:
channels = self._channels
# Get numerical indices of channels
channels = self._name_to_index(channels)
# Get resolution of the specified channels
if hasattr(channels, '__iter__') \
and not isinsta... | def resolution(self, channels=None) | Get the resolution of the specified channel(s).
The resolution specifies the number of different values that the
events can take. The resolution is directly obtained from the $PnR
parameter.
Parameters
----------
channels : int, str, list of int, list of str
... | 3.631719 | 3.754949 | 0.967182 |
# If input is None, return None
if time_str is None:
return None
time_l = time_str.split(':')
if len(time_l) == 3:
# Either 'hh:mm:ss' or 'hh:mm:ss.cc'
if '.' in time_l[2]:
# 'hh:mm:ss.cc' format
time_str = tim... | def _parse_time_string(time_str) | Get a datetime.time object from a string time representation.
The start and end of acquisition are stored in the optional keyword
parameters $BTIM and $ETIM. The following formats are used
according to the FCS standard:
- FCS 2.0: 'hh:mm:ss'
- FCS 3.0: 'hh:mm:ss[:tt]', w... | 2.078799 | 1.907951 | 1.089545 |
# If input is None, return None
if date_str is None:
return None
# Standard format for FCS2.0
try:
return datetime.datetime.strptime(date_str, '%d-%b-%y')
except ValueError:
pass
# Standard format for FCS3.0
try:
... | def _parse_date_string(date_str) | Get a datetime.date object from a string date representation.
The FCS standard includes an optional keyword parameter $DATE in
which the acquistion date is stored. In FCS 2.0, the date is saved
as 'dd-mmm-yy', whereas in FCS 3.0 and 3.1 the date is saved as
'dd-mmm-yyyy'.
This ... | 2.18511 | 1.87462 | 1.165629 |
# Check if list, then run recursively
if hasattr(channels, '__iter__') \
and not isinstance(channels, six.string_types):
return [self._name_to_index(ch) for ch in channels]
if isinstance(channels, six.string_types):
# channels is a string contain... | def _name_to_index(self, channels) | Return the channel indices for the specified channel names.
Integers contained in `channel` are returned unmodified, if they
are within the range of ``self.channels``.
Parameters
----------
channels : int or str or list of int or list of str
Name(s) of the channel(s... | 2.628853 | 2.726131 | 0.964316 |
with open(file_path, 'r') as f:
file_contents = f.read()
version_match = re.search(r"^__version__\s*=\s*['\"]([^'\"]*)['\"]",
file_contents, re.M)
if version_match:
return version_match.group(1)
else:
raise RuntimeError("unable to find version s... | def find_version(file_path) | Scrape version information from specified file path. | 1.65553 | 1.606786 | 1.030336 |
if num_start < 0:
num_start = 0
if num_end < 0:
num_end = 0
if data.shape[0] < (num_start + num_end):
raise ValueError('Number of events to discard greater than total' +
' number of events.')
mask = np.ones(shape=data.shape[0],dtype=bool)
mask[:num_st... | def start_end(data, num_start=250, num_end=100, full_output=False) | Gate out first and last events.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
num_start, num_end : int, optional
Number of events to gate out from beginning and end of... | 2.930763 | 2.402163 | 1.220052 |
# Extract channels in which to gate
if channels is None:
data_ch = data
else:
data_ch = data[:,channels]
if data_ch.ndim == 1:
data_ch = data_ch.reshape((-1,1))
# Default values for high and low
if high is None:
if hasattr(data_ch, 'range'):
... | def high_low(data, channels=None, high=None, low=None, full_output=False) | Gate out high and low values across all specified channels.
Gate out events in `data` with values in the specified channels which
are larger than or equal to `high` or less than or equal to `low`.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the nu... | 2.168142 | 2.003597 | 1.082124 |
# Extract channels in which to gate
if len(channels) != 2:
raise ValueError('2 channels should be specified.')
data_ch = data[:,channels].view(np.ndarray)
# Log if necessary
if log:
data_ch = np.log10(data_ch)
# Center
center = np.array(center)
data_centered = data... | def ellipse(data, channels,
center, a, b, theta=0,
log=False, full_output=False) | Gate that preserves events inside an ellipse-shaped region.
Events are kept if they satisfy the following relationship::
(x/a)**2 + (y/b)**2 <= 1
where `x` and `y` are the coordinates of the event list, after
substracting `center` and rotating by -`theta`. This is mathematically
equivalent to... | 2.714022 | 2.365336 | 1.147415 |
# Copy data array
data_t = data.copy().astype(np.float64)
# Default
if channels is None:
if def_channels is None:
channels = range(data_t.shape[1])
else:
channels = def_channels
# Convert channels to iterable
if not (hasattr(channels, '__iter__') \
... | def transform(data, channels, transform_fxn, def_channels = None) | Apply some transformation function to flow cytometry data.
This function is a template transformation function, intended to be
used by other specific transformation functions. It performs basic
checks on `channels` and `data`. It then applies `transform_fxn` to the
specified channels. Finally, it resca... | 2.686494 | 2.563261 | 1.048077 |
# Default sc_channels
if sc_channels is None:
if data.ndim == 1:
sc_channels = range(data.shape[0])
else:
sc_channels = range(data.shape[1])
# Check that sc_channels and sc_list have the same length
if len(sc_channels) != len(sc_list):
raise ValueErro... | def to_mef(data, channels, sc_list, sc_channels = None) | Transform flow cytometry data using a standard curve function.
This function accepts a list of standard curves (`sc_list`) and a list
of channels to which those standard curves should be applied
(`sc_channels`). `to_mef` automatically checks whether a standard curve
is available for each channel specif... | 2.333042 | 2.210673 | 1.055354 |
# Mask out-of-range values
if mask_out_of_range:
x_masked = np.ma.masked_where((x < self._xmin) | (x > self._xmax),
x)
else:
x_masked = x
# Calculate s and return
return np.interp(x_masked, self._x_range, ... | def transform_non_affine(self, x, mask_out_of_range=True) | Transform a Nx1 numpy array.
Parameters
----------
x : array
Data to be transformed.
mask_out_of_range : bool, optional
Whether to mask input values out of range.
Return
------
array or masked array
Transformed data. | 2.926005 | 3.301725 | 0.886205 |
T = self._T
M = self._M
W = self._W
p = self._p
# Calculate x
return T * 10**(-(M-W)) * (10**(s-W) - (p**2)*10**(-(s-W)/p) + p**2 - 1) | def transform_non_affine(self, s) | Apply transformation to a Nx1 numpy array.
Parameters
----------
s : array
Data to be transformed in display scale units.
Return
------
array or masked array
Transformed data, in data value units. | 7.684227 | 8.072868 | 0.951858 |
if numticks is not None:
self.numticks = numticks
if subs is not None:
self._subs = subs | def set_params(self, subs=None, numticks=None) | Set parameters within this locator.
Parameters
----------
subs : array, optional
Subtick values, as multiples of the main ticks.
numticks : array, optional
Number of ticks. | 2.457584 | 3.786777 | 0.648991 |
b = self._transform.base
if vmax < vmin:
vmin, vmax = vmax, vmin
if not matplotlib.ticker.is_decade(abs(vmin), b):
if vmin < 0:
vmin = -matplotlib.ticker.decade_up(-vmin, b)
else:
vmin = matplotlib.ticker.decade_down(v... | def view_limits(self, vmin, vmax) | Try to choose the view limits intelligently. | 1.884403 | 1.838111 | 1.025185 |
return _InterpolatedInverseTransform(transform=self._transform,
smin=0,
smax=self._transform._M) | def get_transform(self) | Get a new object to perform the scaling transformation. | 21.495564 | 18.700768 | 1.149448 |
axis.set_major_locator(_LogicleLocator(self._transform))
axis.set_minor_locator(_LogicleLocator(self._transform,
subs=np.arange(2.0, 10.)))
axis.set_major_formatter(matplotlib.ticker.LogFormatterSciNotation(
labelOnlyBase=True)) | def set_default_locators_and_formatters(self, axis) | Set up the locators and formatters for the scale.
Parameters
----------
axis: matplotlib.axis
Axis for which to set locators and formatters. | 3.505335 | 3.653873 | 0.959348 |
vmin_bound = self._transform.transform_non_affine(0)
vmax_bound = self._transform.transform_non_affine(self._transform.M)
vmin = max(vmin, vmin_bound)
vmax = min(vmax, vmax_bound)
return vmin, vmax | def limit_range_for_scale(self, vmin, vmax, minpos) | Return minimum and maximum bounds for the logicle axis.
Parameters
----------
vmin : float
Minimum data value.
vmax : float
Maximum data value.
minpos : float
Minimum positive value in the data. Ignored by this function.
Return
... | 2.83125 | 3.375638 | 0.83873 |
# Slice data to take statistics from
if channels is None:
data_stats = data
else:
data_stats = data[:, channels]
# Calculate and return statistic
return np.mean(data_stats, axis=0) | def mean(data, channels=None) | Calculate the mean of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optional
Chan... | 4.489032 | 6.018084 | 0.745924 |
# Slice data to take statistics from
if channels is None:
data_stats = data
else:
data_stats = data[:, channels]
# Calculate and return statistic
return scipy.stats.gmean(data_stats, axis=0) | def gmean(data, channels=None) | Calculate the geometric mean of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optional
... | 4.570107 | 5.566637 | 0.820982 |
# Slice data to take statistics from
if channels is None:
data_stats = data
else:
data_stats = data[:, channels]
# Calculate and return statistic
return np.median(data_stats, axis=0) | def median(data, channels=None) | Calculate the median of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optional
Ch... | 4.445992 | 6.019383 | 0.738613 |
# Slice data to take statistics from
if channels is None:
data_stats = data
else:
data_stats = data[:, channels]
# Calculate and return statistic
# scipy.stats.mode returns two outputs, the first of which is an array
# containing the modal values. This array has the same nu... | def mode(data, channels=None) | Calculate the mode of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optional
Chan... | 5.406348 | 6.00777 | 0.899893 |
# Slice data to take statistics from
if channels is None:
data_stats = data
else:
data_stats = data[:, channels]
# Calculate and return statistic
return np.std(data_stats, axis=0) | def std(data, channels=None) | Calculate the standard deviation of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optiona... | 4.539021 | 5.811913 | 0.780986 |
# Slice data to take statistics from
if channels is None:
data_stats = data
else:
data_stats = data[:, channels]
# Calculate and return statistic
return np.std(data_stats, axis=0) / np.mean(data_stats, axis=0) | def cv(data, channels=None) | Calculate the Coeff. of Variation of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, option... | 4.014305 | 4.259686 | 0.942394 |
# Slice data to take statistics from
if channels is None:
data_stats = data
else:
data_stats = data[:, channels]
# Calculate and return statistic
return np.exp(np.std(np.log(data_stats), axis=0)) | def gstd(data, channels=None) | Calculate the geometric std. dev. of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, option... | 4.617376 | 5.418686 | 0.852121 |
# Slice data to take statistics from
if channels is None:
data_stats = data
else:
data_stats = data[:, channels]
# Calculate and return statistic
return np.sqrt(np.exp(np.std(np.log(data_stats), axis=0)**2) - 1) | def gcv(data, channels=None) | Calculate the geometric CV of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optional
... | 4.659977 | 5.400321 | 0.862908 |
# Slice data to take statistics from
if channels is None:
data_stats = data
else:
data_stats = data[:, channels]
# Calculate and return statistic
q75, q25 = np.percentile(data_stats, [75 ,25], axis=0)
return q75 - q25 | def iqr(data, channels=None) | Calculate the Interquartile Range of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, option... | 3.480556 | 4.095978 | 0.84975 |
# Slice data to take statistics from
if channels is None:
data_stats = data
else:
data_stats = data[:, channels]
# Calculate and return statistic
q75, q25 = np.percentile(data_stats, [75 ,25], axis=0)
return (q75 - q25)/np.median(data_stats, axis=0) | def rcv(data, channels=None) | Calculate the RCV of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optional
Chann... | 3.850543 | 3.74756 | 1.02748 |
infCFe = cfe.getroot().find('./infCFe')
cnpjcpf_consumidor = infCFe.findtext('dest/CNPJ') or \
infCFe.findtext('dest/CPF') or ''
return '|'.join([
infCFe.attrib['Id'][3:], # remove prefixo "CFe"
'{}{}'.format(
infCFe.findtext('ide/dEmi'),
... | def dados_qrcode(cfe) | Compila os dados que compõem o QRCode do CF-e-SAT, conforme a
documentação técnica oficial **Guia para Geração do QRCode pelo Aplicativo
Comercial**, a partir de uma instância de ``ElementTree`` que represente a
árvore do XML do CF-e-SAT.
:param cfe: Instância de :py:mod:`xml.etree.ElementTree.ElementT... | 4.97704 | 4.915155 | 1.012591 |
assert 44 % num_partes == 0, 'O numero de partes nao produz um '\
'resultado inteiro (partes por 44 digitos): '\
'num_partes=%s' % num_partes
salto = 44 // num_partes
return [self._campos[n:(n + salto)] for n in range(0, 44, salto)] | def partes(self, num_partes=11) | Particiona a chave do CF-e-SAT em uma lista de *n* segmentos.
:param int num_partes: O número de segmentos (partes) em que os digitos
da chave do CF-e-SAT serão particionados. **Esse número deverá
resultar em uma divisão inteira por 44 (o comprimento da chave)**.
Se não for ... | 5.704041 | 5.42108 | 1.052196 |
texto = '{:n}'.format(valor)
if remover_zeros:
dp = locale.localeconv().get('decimal_point')
texto = texto.rstrip('0').rstrip(dp) if dp in texto else texto
return texto | def texto_decimal(valor, remover_zeros=True) | Converte um valor :py:class:`decimal.Decimal` para texto, com a opção de
remover os zeros à direita não significativos. A conversão para texto irá
considerar o :py:module:`locale` para converter o texto pronto para
apresentação.
:param decimal.Decimal valor: Valor a converter para texto.
:param boo... | 3.850396 | 5.412796 | 0.711351 |
pesos = '23456789' * ((len(base) // 8) + 1)
acumulado = sum([int(a) * int(b) for a, b in zip(base[::-1], pesos)])
digito = 11 - (acumulado % 11)
return 0 if digito >= 10 else digito | def modulo11(base) | Calcula o dígito verificador (DV) para o argumento usando "Módulo 11".
:param str base: String contendo os dígitos sobre os quais o DV será
calculado, assumindo que o DV não está incluído no argumento.
:return: O dígito verificador calculado.
:rtype: int | 2.732668 | 2.951121 | 0.925976 |
atributos = valor.as_tuple()
if not (minimo <= abs(atributos.exponent) <= maximo):
raise ValueError('Numero de casas decimais fora dos limites esperados '
'(valor={!r}, minimo={!r}, maximo={!r}): {!r}'.format(
valor, minimo, maximo, atributos)) | def validar_casas_decimais(valor, minimo=1, maximo=2) | Valida o número de casas decimais. Se o número de casas decimais não
estiver dentro do mínimo e máximo, será lançada uma exceção do tipo
:py:exc:`ValueError`.
:param valor: Um objeto :py:class:`~decimal.Decimal`.
:param minimo: Valor inteiro maior ou igual a zero indicando o número
mínimo de c... | 3.505343 | 3.579484 | 0.979287 |
if not sigla in [s for s, i, n, r in UNIDADES_FEDERACAO]:
raise UnidadeFederativaError('Estado (sigla) UF "%s" '
'inexistente' % sigla) | def uf(sigla) | Valida a sigla da Unidade Federativa. Se não for uma sigla de UF válida,
será lançada a exceção :exc:`UnidadeFederativaError`. | 7.462634 | 6.21608 | 1.200537 |
idx = [i for s, i, n, r in UNIDADES_FEDERACAO].index(codigo_ibge)
return UNIDADES_FEDERACAO[idx][_UF_SIGLA] | def uf_pelo_codigo(codigo_ibge) | Retorna a UF para o código do IBGE informado. | 7.234877 | 6.660296 | 1.08627 |
idx = [s for s, i, n, r in UNIDADES_FEDERACAO].index(sigla)
return UNIDADES_FEDERACAO[idx][_UF_CODIGO_IBGE] | def codigo_ibge_uf(sigla) | Retorna o código do IBGE para a UF informada. | 5.862553 | 5.594562 | 1.047902 |
_digitos = [int(c) for c in numero if c.isdigit()]
if len(_digitos) != 14 or len(numero) != 14:
raise NumeroCNPJError('Nao possui 14 digitos: {!r}'.format(numero))
if numero == numero[0] * 14:
raise NumeroCNPJError('Todos os digitos iguais: {!r}'.format(numero))
multiplicadores =... | def cnpj(numero) | Valida um número de CNPJ. O número deverá ser informado como uma string
contendo 14 dígitos numéricos. Se o número informado for inválido será
lançada a exceção :exc:`NumeroCNPJError`. Esta implementação da validação
foi delicadamente copiada de `python-sped <http://git.io/vfuGW>`. | 1.821371 | 1.761745 | 1.033845 |
try:
cnpj(digitos(numero) if not estrito else numero)
return True
except NumeroCNPJError:
pass
return False | def is_cnpj(numero, estrito=False) | Uma versão conveniente para usar em testes condicionais. Apenas retorna
verdadeiro ou falso, conforme o argumento é validado.
:param bool estrito: Padrão ``False``, indica se apenas os dígitos do
número deverão ser considerados. Se verdadeiro, potenciais caracteres
que formam a máscara serão re... | 5.114462 | 6.923688 | 0.73869 |
_num = digitos(numero)
if is_cnpj(_num):
return '{}.{}.{}/{}-{}'.format(
_num[:2], _num[2:5], _num[5:8], _num[8:12], _num[12:])
return numero | def as_cnpj(numero) | Formata um número de CNPJ. Se o número não for um CNPJ válido apenas
retorna o argumento sem qualquer modificação. | 2.60433 | 2.494881 | 1.043869 |
_digitos = [int(c) for c in numero if c.isdigit()]
if len(_digitos) != 11 or len(numero) != 11:
raise NumeroCPFError('Nao possui 11 digitos: {!r}'.format(numero))
if numero == numero[0] * 11:
raise NumeroCPFError('Todos os digitos iguais: {!r}'.format(numero))
multiplicadores = [... | def cpf(numero) | Valida um número de CPF. O número deverá ser informado como uma string
contendo 11 dígitos numéricos. Se o número informado for inválido será
lançada a exceção :exc:`NumeroCPFError`. Esta implementação da validação
foi delicadamente copiada de `python-sped <http://git.io/vfuGW>`. | 1.874791 | 1.809049 | 1.036341 |
try:
cpf(digitos(numero) if not estrito else numero)
return True
except NumeroCPFError:
pass
return False | def is_cpf(numero, estrito=False) | Uma versão conveniente para usar em testes condicionais. Apenas retorna
verdadeiro ou falso, conforme o argumento é validado.
:param bool estrito: Padrão ``False``, indica se apenas os dígitos do
número deverão ser considerados. Se verdadeiro, potenciais caracteres
que formam a máscara serão re... | 5.710249 | 7.698184 | 0.741766 |
_num = digitos(numero)
if is_cpf(_num):
return '{}.{}.{}-{}'.format(_num[:3], _num[3:6], _num[6:9], _num[9:])
return numero | def as_cpf(numero) | Formata um número de CPF. Se o número não for um CPF válido apenas
retorna o argumento sem qualquer modificação. | 3.126936 | 2.855118 | 1.095204 |
try:
cnpj(numero)
except NumeroCNPJError:
try:
cpf(numero)
except NumeroCPFError:
raise NumeroCNPJCPFError('numero "%s" nao valida como '
'CNPJ nem como CPF' % numero) | def cnpjcpf(numero) | Valida um número de CNPJ ou CPF. Veja :func:`cnpj` e/ou :func:`cpf`. | 4.327929 | 4.109443 | 1.053167 |
_numero = digitos(numero) if not estrito else numero
try:
cnpj(_numero)
return True
except NumeroCNPJError:
try:
cpf(_numero)
return True
except NumeroCPFError:
pass
return False | def is_cnpjcpf(numero, estrito=False) | Uma versão conveniente para usar em testes condicionais. Apenas retorna
verdadeiro ou falso, conforme o argumento é validado.
:param bool estrito: Padrão ``False``, indica se apenas os dígitos do
número deverão ser considerados. Se verdadeiro, potenciais caracteres
que formam a máscara serão re... | 3.675898 | 4.261965 | 0.862489 |
if is_cnpj(numero):
return as_cnpj(numero)
elif is_cpf(numero):
return as_cpf(numero)
return numero | def as_cnpjcpf(numero) | Formata um número de CNPJ ou CPF. Se o número não for um CNPJ ou CPF
válidos apenas retorna o argumento sem qualquer modificação. | 2.413321 | 2.508561 | 0.962034 |
_digitos = digitos(numero)
if len(_digitos) != 8 or len(numero) != 8:
raise NumeroCEPError('CEP "%s" nao possui 8 digitos' % numero)
elif _digitos[0] * 8 == _digitos:
raise NumeroCEPError('CEP "%s" considerado invalido' % numero) | def cep(numero) | Valida um número de CEP. O número deverá ser informado como uma string
contendo 8 dígitos numéricos. Se o número informado for inválido será
lançada a exceção :exc:`NumeroCEPError`.
.. warning::
Qualquer string que contenha 8 dígitos será considerada como um CEP
válido, desde que os dígito... | 4.217037 | 3.522371 | 1.197215 |
try:
cep(digitos(numero) if not estrito else numero)
return True
except NumeroCEPError:
pass
return False | def is_cep(numero, estrito=False) | Uma versão conveniente para usar em testes condicionais. Apenas retorna
verdadeiro ou falso, conforme o argumento é validado.
:param bool estrito: Padrão ``False``, indica se apenas os dígitos do
número deverão ser considerados. Se verdadeiro, potenciais caracteres
que formam a máscara serão re... | 7.467427 | 8.843053 | 0.84444 |
_numero = digitos(numero)
if is_cep(_numero):
return '{}-{}'.format(_numero[:5], _numero[5:])
return numero | def as_cep(numero) | Formata um número de CEP. Se o argumento não for um CEP válido apenas
retorna o argumento sem qualquer modificação. | 5.160287 | 4.491198 | 1.148978 |
ct = message.get_content_type()
cs = message.get_content_subtype()
if charset is None:
charset = get_charset_from_message_fragment(message)
if not message.is_multipart():
# we're on a leaf
converted = None
disposition = message.get('Content-Disposition', 'inline')
... | def convert_tree(message, config, indent=0, wrap_alternative=True, charset=None) | Recursively convert a potentially-multipart tree.
Returns a tuple of (the converted tree, whether any markdown was found) | 2.323485 | 2.300509 | 1.009988 |
if c.smtp_ssl:
klass = smtplib.SMTP_SSL
else:
klass = smtplib.SMTP
conn = klass(c.smtp_host, c.smtp_port, timeout=c.smtp_timeout)
if not c.smtp_ssl:
conn.ehlo()
conn.starttls()
conn.ehlo()
if c.smtp_username:
conn.login(c.smtp_username, c.smtp_pas... | def smtp_connection(c) | Create an SMTP connection from a Config object | 1.776195 | 1.710109 | 1.038644 |
issuers = self._get_property('issuers') or []
result = {
'_embedded': {
'issuers': issuers,
},
'count': len(issuers),
}
return List(result, Issuer) | def issuers(self) | Return the list of available issuers for this payment method. | 4.684786 | 4.046549 | 1.157724 |
if not payment_id or not payment_id.startswith(self.RESOURCE_ID_PREFIX):
raise IdentifierError(
"Invalid payment ID: '{id}'. A payment ID should start with '{prefix}'.".format(
id=payment_id, prefix=self.RESOURCE_ID_PREFIX)
)
result = ... | def delete(self, payment_id, data=None) | Cancel payment and return the payment object.
Deleting a payment causes the payment status to change to canceled.
The updated payment object is returned. | 3.256946 | 3.275284 | 0.994401 |
return self.client.customer_mandates.with_parent_id(self.customer_id).get(self.mandate_id) | def mandate(self) | Return the mandate for this payment. | 7.029842 | 5.220212 | 1.346658 |
return self.client.customer_subscriptions.with_parent_id(self.customer_id).get(self.subscription_id) | def subscription(self) | Return the subscription for this payment. | 6.102824 | 5.110013 | 1.194287 |
from ..resources.orders import Order
url = self._get_link('order')
if url:
resp = self.client.orders.perform_api_call(self.client.orders.REST_READ, url)
return Order(resp, self.client) | def order(self) | Return the order for this payment. | 7.272339 | 6.348135 | 1.145587 |
try:
version_file = open(os.path.join(ROOT_DIR, 'mollie', 'api', 'version.py'), encoding='utf=8')
except TypeError:
# support python 2
version_file = open(os.path.join(ROOT_DIR, 'mollie', 'api', 'version.py'))
contents = version_file.read()
match = re.search(r'VERSION = [\'"... | def get_version() | Read the version from a file (mollie/api/version.py) in the repository.
We can't import here since we might import from an installed version. | 2.670403 | 2.283023 | 1.169678 |
if data is None:
data = {'lines': []}
refund = OrderRefunds(self.client).on(self).create(data, **params)
return refund | def create_refund(self, data=None, **params) | Create a refund for the order. When no data arg is given, a refund for all order lines is assumed. | 6.240181 | 5.285131 | 1.180705 |
from ..resources.order_lines import OrderLines
if data is None:
data = {'lines': []}
canceled = OrderLines(self.client).on(self).delete(data)
return canceled | def cancel_lines(self, data=None) | Cancel the lines given. When no lines are given, cancel all the lines.
Canceling an order line causes the order line status to change to canceled.
An empty dictionary will be returned. | 8.113512 | 6.747589 | 1.202431 |
return OrderLines(self.client).on(self).update(resource_id, data) | def update_line(self, resource_id, data) | Update a line for an order. | 15.431857 | 9.50104 | 1.624228 |
if data is None:
data = {'lines': []}
return Shipments(self.client).on(self).create(data) | def create_shipment(self, data=None) | Create a shipment for an order. When no data arg is given, a shipment for all order lines is assumed. | 7.41896 | 5.553693 | 1.335861 |
return Shipments(self.client).on(self).get(resource_id) | def get_shipment(self, resource_id) | Retrieve a single shipment by a shipment's ID. | 13.268768 | 11.831061 | 1.12152 |
return Shipments(self.client).on(self).update(resource_id, data) | def update_shipment(self, resource_id, data) | Update the tracking information of a shipment. | 9.68917 | 10.136998 | 0.955822 |
return OrderPayments(self.client).on(self).create(data) | def create_payment(self, data) | Creates a new payment object for an order. | 18.920118 | 11.648121 | 1.624306 |
path = self.get_resource_name()
result = self.perform_api_call(self.REST_DELETE, path, data=data)
return result | def delete(self, data, *args) | Custom handling for deleting orderlines.
Orderlines are deleted by issuing a DELETE on the orders/*/lines endpoint,
with the orderline IDs and quantities in the request body. | 5.865684 | 6.730604 | 0.871494 |
path = self.get_resource_name() + '/' + str(resource_id)
result = self.perform_api_call(self.REST_UPDATE, path, data=data)
for line in result['lines']:
if line['id'] == resource_id:
return self.get_resource_object(line)
raise DataConsistencyError('Li... | def update(self, resource_id, data=None, **params) | Custom handling for updating orderlines.
The API returns an Order object. Since we are sending the request through an orderline object, it makes more
sense to convert the returned object to to the updated orderline object.
If you wish to retrieve the order object, you can do so by using the or... | 4.210009 | 4.035707 | 1.04319 |
url = self._get_link('next')
resource = self.object_type.get_resource_class(self.client)
resp = resource.perform_api_call(resource.REST_READ, url)
return List(resp, self.object_type, self.client) | def get_next(self) | Return the next set of objects in a list | 6.416053 | 6.308798 | 1.017001 |
if not subscription_id or not subscription_id.startswith(self.RESOURCE_ID_PREFIX):
raise IdentifierError(
"Invalid subscription ID: '{id}'. A subscription ID should start with '{prefix}'.".format(
id=subscription_id, prefix=self.RESOURCE_ID_PREFIX)
... | def delete(self, subscription_id, data=None) | Cancel subscription and return the subscription object.
Deleting a subscription causes the subscription status to changed to 'canceled'.
The updated subscription object is returned. | 3.325505 | 3.342787 | 0.99483 |
if not chargeback_id or not chargeback_id.startswith(self.RESOURCE_ID_PREFIX):
raise IdentifierError(
"Invalid chargeback ID: '{id}'. A chargeback ID should start with '{prefix}'.".format(
id=chargeback_id, prefix=self.RESOURCE_ID_PREFIX)
)
... | def get(self, chargeback_id, **params) | Verify the chargeback ID and retrieve the chargeback from the API. | 2.651923 | 2.68288 | 0.988461 |
if not params:
return None
parts = []
for param, value in sorted(params.items()):
if not isinstance(value, dict):
parts.append(urlencode({param: value}))
else:
# encode dictionary with square brackets
for key, sub_value in sorted(value.items()... | def generate_querystring(params) | Generate a querystring suitable for use in the v2 api.
The Requests library doesn't know how to generate querystrings that encode dictionaries using square brackets:
https://api.mollie.com/v2/methods?amount[value]=100.00&amount[currency]=USD
Note: we use `sorted()` to work around a difference in iteration... | 2.723418 | 2.543288 | 1.070825 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.