text stringlengths 81 112k |
|---|
Plot a 2-D histogram of samples.
Parameters
----------
x, y : array_like (nsamples,)
The samples.
levels : array_like
The contour levels to draw.
ax : matplotlib.Axes (optional)
A axes instance on which to add the 2-D histogram.
plot_datapoints : bool (optional)
... |
avg dist from one lamost point to nearest 10 training points
def calc_dist(lamost_point, training_points, coeffs):
""" avg dist from one lamost point to nearest 10 training points """
diff2 = (training_points - lamost_point)**2
dist = np.sqrt(np.sum(diff2*coeffs, axis=1))
return np.mean(dist[dist.argso... |
Entrenar un clasificador SVM sobre los textos cargados.
Crea un clasificador que se guarda en el objeto bajo el nombre `name`.
Args:
name (str): Nombre para el clasidicador.
ids (list): Se espera una lista de N ids de textos ya almacenados
en el TextClassifier.
... |
Reentrenar parcialmente un clasificador SVM.
Args:
name (str): Nombre para el clasidicador.
ids (list): Se espera una lista de N ids de textos ya almacenados
en el TextClassifier.
labels (list): Se espera una lista de N etiquetas. Una por cada id
... |
Usar un clasificador SVM para etiquetar textos nuevos.
Args:
classifier_name (str): Nombre del clasidicador a usar.
examples (list or str): Se espera un ejemplo o una lista de
ejemplos a clasificar en texto plano o en ids.
max_labels (int, optional): Cantidad... |
Funcion para generar los vectores tf-idf de una lista de textos.
Args:
examples (list or str): Se espera un ejemplo o una lista de:
o bien ids, o bien textos.
Returns:
textvec (sparse matrix): Devuelve una matriz sparse que contiene
los vectores T... |
Devuelve textos similares al ejemplo dentro de los textos entrenados.
Nota:
Usa la distancia de coseno del vector de features TF-IDF
Args:
example (str): Se espera un id de texto o un texto a partir del
cual se buscaran otros textos similares.
max_si... |
Calcula los vectores de terminos de textos y los almacena.
A diferencia de :func:`~TextClassifier.TextClassifier.store_text` esta
funcion borra cualquier informacion almacenada y comienza el conteo
desde cero. Se usa para redefinir el vocabulario sobre el que se
construyen los vectores.... |
A quick and simple autocomplete service that returns up to 20 name usages by
doing prefix matching against the scientific name. Results are ordered by relevance.
:param q: [str] Simple search parameter. The value for this parameter can be a
simple word or a phrase. Wildcards can be added to the simple word pa... |
Get details on a GBIF dataset.
:param uuid: [str] One or more dataset UUIDs. See examples.
References: http://www.gbif.org/developer/registry#datasetMetrics
Usage::
from pygbif import registry
registry.dataset_metrics(uuid='3f8a1297-3259-4700-91fc-acc4170b27ce')
registry.dataset_metrics(uuid='66dd0960-2... |
Search for datasets and dataset metadata.
:param data: [str] The type of data to get. Default: ``all``
:param type: [str] Type of dataset, options include ``OCCURRENCE``, etc.
:param uuid: [str] UUID of the data node provider. This must be specified if data
is anything other than ``all``.
:param query: [str] Qu... |
Search that returns up to 20 matching datasets. Results are ordered by relevance.
:param q: [str] Query term(s) for full text search. The value for this parameter can be a simple word or a phrase. Wildcards can be added to the simple word parameters only, e.g. ``q=*puma*``
:param type: [str] Type of dataset, optio... |
Full text search across all datasets. Results are ordered by relevance.
:param q: [str] Query term(s) for full text search. The value for this parameter
can be a simple word or a phrase. Wildcards can be added to the simple word
parameters only, e.g. ``q=*puma*``
:param type: [str] Type of dataset, options in... |
reverse WKT winding order
:param x: [str] WKT string
:param digits: [int] number of digits after decimal to use for the return string.
by default, we use the mean number of digits in your string.
:return: a string
Usage::
from pygbif import wkt_rewind
x = 'POLYGON((1... |
Lookup occurrence issue definitions and short codes
:param issue: Full name of issue, e.g, CONTINENT_COUNTRY_MISMATCH
:param code: an issue short code, e.g. ccm
Usage
pygbif.occ_issues_lookup(issue = 'CONTINENT_COUNTRY_MISMATCH')
pygbif.occ_issues_lookup(issue = 'MULTIMEDIA_DATE_INVALID')
pygb... |
Search GBIF occurrences
:param taxonKey: [int] A GBIF occurrence identifier
:param q: [str] Simple search parameter. The value for this parameter can be a simple word or a phrase.
:param spellCheck: [bool] If ``True`` ask GBIF to check your spelling of the value passed to the ``search`` parameter.
... |
Networks metadata.
Note: there's only 1 network now, so there's not a lot you can do with this method.
:param data: [str] The type of data to get. Default: ``all``
:param uuid: [str] UUID of the data network provider. This must be specified if data
is anything other than ``all``.
:param q: [str] Query ne... |
GBIF maps API
:param source: [str] Either ``density`` for fast, precalculated tiles,
or ``adhoc`` for any search
:param z: [str] zoom level
:param x: [str] longitude
:param y: [str] latitude
:param format: [str] format of returned data. One of:
- ``.mvt`` - vector tile
- ``@Hx.... |
Lookup details for specific names in all taxonomies in GBIF.
:param key: [fixnum] A GBIF key for a taxon
:param name: [str] Filters by a case insensitive, canonical namestring,
e.g. 'Puma concolor'
:param data: [str] The type of data to get. Default: ``all``. Options: ``all``,
``verbatim``, ``name``, ``parents... |
check if a variable is present in the environmental variables
def _check_environ(variable, value):
"""check if a variable is present in the environmental variables"""
if is_not_none(value):
return value
else:
value = os.environ.get(variable)
if is_none(value):
stop(''.jo... |
Spin up a download request for GBIF occurrence data.
:param queries: One or more of query arguments to kick of a download job.
See Details.
:type queries: str or list
:param pred_type: (character) One of ``equals`` (``=``), ``and`` (``&``),
`or`` (``|``), ``lessThan`` (``<``), ``lessThanOrE... |
Lists the downloads created by a user.
:param user: [str] A user name, look at env var ``GBIF_USER`` first
:param pwd: [str] Your password, look at env var ``GBIF_PWD`` first
:param limit: [int] Number of records to return. Default: ``20``
:param offset: [int] Record number to start at. Default: ``0``
... |
Get a download from GBIF.
:param key: [str] A key generated from a request, like that from ``download``
:param path: [str] Path to write zip file to. Default: ``"."``, with a ``.zip`` appended to the end.
:param **kwargs**: Further named arguments passed on to ``requests.get``
Downloads the zip file t... |
set main predicate combination type
:param value: (character) One of ``equals`` (``=``), ``and`` (``&``), ``or`` (``|``),
``lessThan`` (``<``), ``lessThanOrEquals`` (``<=``), ``greaterThan`` (``>``),
``greaterThanOrEquals`` (``>=``), ``in``, ``within``, ``not`` (``!``), ``like``
def main_pred_... |
add key, value, type combination of a predicate
:param key: query KEY parameter
:param value: the value used in the predicate
:param predicate_type: the type of predicate (e.g. ``equals``)
def add_predicate(self, key, value, predicate_type='equals'):
"""
add key, value, type co... |
extract values from either file or list
:param values_list: list or file name (str) with list of values
def _extract_values(values_list):
"""extract values from either file or list
:param values_list: list or file name (str) with list of values
"""
values = []
# check ... |
add an iterative predicate with a key and set of values
which it can be equal to in and or function.
The individual predicates are specified with the type ``equals`` and
combined with a type ``or``.
The main reason for this addition is the inability of using ``in`` as
predicate ... |
Gets details for a single, interpreted occurrence
:param key: [int] A GBIF occurrence key
:return: A dictionary, of results
Usage::
from pygbif import occurrences
occurrences.get(key = 1258202889)
occurrences.get(key = 1227768771)
occurrences.get(key = 1227769518)
def ge... |
Gets a verbatim occurrence record without any interpretation
:param key: [int] A GBIF occurrence key
:return: A dictionary, of results
Usage::
from pygbif import occurrences
occurrences.get_verbatim(key = 1258202889)
occurrences.get_verbatim(key = 1227768771)
occurrences.... |
Get a single occurrence fragment in its raw form (xml or json)
:param key: [int] A GBIF occurrence key
:return: A dictionary, of results
Usage::
from pygbif import occurrences
occurrences.get_fragment(key = 1052909293)
occurrences.get_fragment(key = 1227768771)
occurrence... |
Lookup names in the GBIF backbone taxonomy.
:param name: [str] Full scientific name potentially with authorship (required)
:param rank: [str] The rank given as our rank enum. (optional)
:param kingdom: [str] If provided default matching will also try to match against this
if no direct match is found for the... |
Parse taxon names using the GBIF name parser
:param name: [str] A character vector of scientific names. (required)
reference: http://www.gbif.org/developer/species#parser
Usage::
from pygbif import species
species.name_parser('x Agropogon littoralis')
species.name_parser(['Arrhenatherum elat... |
Lookup names in all taxonomies in GBIF.
This service uses fuzzy lookup so that you can put in partial names and
you should get back those things that match. See examples below.
:param q: [str] Query term(s) for full text search (optional)
:param rank: [str] ``CLASS``, ``CULTIVAR``, ``CULTIVAR_GROUP``, ``DOMAIN``,... |
Returns occurrence counts for a predefined set of dimensions
:param taxonKey: [int] A GBIF occurrence identifier
:param basisOfRecord: [str] A GBIF occurrence identifier
:param country: [str] A GBIF occurrence identifier
:param isGeoreferenced: [bool] A GBIF occurrence identifier
:param datasetKey:... |
Lists occurrence counts by year
:param year: [int] year range, e.g., ``1990,2000``. Does not support ranges like ``asterisk,2010``
:return: dict
Usage::
from pygbif import occurrences
occurrences.count_year(year = '1990,2000')
def count_year(year, **kwargs):
'''
Lists oc... |
Lists occurrence counts for datasets that cover a given taxon or country
:param taxonKey: [int] Taxon key
:param country: [str] A country, two letter code
:return: dict
Usage::
from pygbif import occurrences
occurrences.count_datasets(country = "DE")
def count_datasets(taxon... |
Lists occurrence counts for all countries covered by the data published by the given country
:param publishingCountry: [str] A two letter country code
:return: dict
Usage::
from pygbif import occurrences
occurrences.count_countries(publishingCountry = "DE")
def count_countries(p... |
Lists occurrence counts for all countries that publish data about the given country
:param country: [str] A country, two letter code
:return: dict
Usage::
from pygbif import occurrences
occurrences.count_publishingcountries(country = "DE")
def count_publishingcountries(country, ... |
Detect if code is running in a Jupyter Notebook.
This isn't 100% correct but seems good enough
Returns
-------
bool
True if it detects this is a notebook, otherwise False.
def _detect_notebook() -> bool:
"""Detect if code is running in a Jupyter Notebook.
This isn't 100% correct but ... |
Merge attributes from two layouts.
def _merge_layout(x: go.Layout, y: go.Layout) -> go.Layout:
"""Merge attributes from two layouts."""
xjson = x.to_plotly_json()
yjson = y.to_plotly_json()
if 'shapes' in yjson and 'shapes' in xjson:
xjson['shapes'] += yjson['shapes']
yjson.update(xjson)
... |
Try to convert to pandas objects to datetimes.
Plotly doesn't know how to handle them.
def _try_pydatetime(x):
"""Try to convert to pandas objects to datetimes.
Plotly doesn't know how to handle them.
"""
try:
# for datetimeindex
x = [y.isoformat() for y in x.to_pydatetime()]
... |
TODO: Docstring for spark.
Parameters
----------
points : array-like
shapes : array-like
fill : array-like, optional
Returns
-------
Chart
def spark_shape(points, shapes, fill=None, color='blue', width=5, yindex=0, heights=None):
"""TODO: Docstring for spark.
Parameters
-... |
Draws a vertical line from `ymin` to `ymax`.
Parameters
----------
xmin : int, optional
xmax : int, optional
color : str, optional
width : number, optional
Returns
-------
Chart
def vertical(x, ymin=0, ymax=1, color=None, width=None, dash=None, opacity=None):
"""Draws a vertic... |
Draws a horizontal line from `xmin` to `xmax`.
Parameters
----------
xmin : int, optional
xmax : int, optional
color : str, optional
width : number, optional
Returns
-------
Chart
def horizontal(y, xmin=0, xmax=1, color=None, width=None, dash=None, opacity=None):
"""Draws a ho... |
Draws connected dots.
Parameters
----------
x : array-like, optional
y : array-like, optional
label : array-like, optional
Returns
-------
Chart
def line(
x=None,
y=None,
label=None,
color=None,
width=None,
dash=None,
opacity=None,
mode='lines+markers',... |
Create a 3d line chart.
def line3d(
x, y, z, label=None, color=None, width=None, dash=None, opacity=None, mode='lines+markers'
):
"""Create a 3d line chart."""
x = np.atleast_1d(x)
y = np.atleast_1d(y)
z = np.atleast_1d(z)
assert x.shape == y.shape
assert y.shape == z.shape
lineattr = {... |
Draws dots.
Parameters
----------
x : array-like, optional
y : array-like, optional
label : array-like, optional
Returns
-------
Chart
def scatter(
x=None,
y=None,
label=None,
color=None,
width=None,
dash=None,
opacity=None,
markersize=6,
yaxis=1,
... |
Create a bar chart.
Parameters
----------
x : array-like, optional
y : TODO, optional
label : TODO, optional
mode : 'group' or 'stack', default 'group'
opacity : TODO, optional
Returns
-------
Chart
A Chart with bar graph data.
def bar(x=None, y=None, label=None, mode=... |
Create a heatmap.
Parameters
----------
z : TODO
x : TODO, optional
y : TODO, optional
colorscale : TODO, optional
Returns
-------
Chart
def heatmap(z, x=None, y=None, colorscale='Viridis'):
"""Create a heatmap.
Parameters
----------
z : TODO
x : TODO, optiona... |
Fill to zero.
Parameters
----------
x : array-like, optional
y : TODO, optional
label : TODO, optional
Returns
-------
Chart
def fill_zero(
x=None,
y=None,
label=None,
color=None,
width=None,
dash=None,
opacity=None,
mode='lines+markers',
**kargs
):... |
Fill between `ylow` and `yhigh`.
Parameters
----------
x : array-like, optional
ylow : TODO, optional
yhigh : TODO, optional
Returns
-------
Chart
def fill_between(
x=None,
ylow=None,
yhigh=None,
label=None,
color=None,
width=None,
dash=None,
opacity=No... |
Rug chart.
Parameters
----------
x : array-like, optional
label : TODO, optional
opacity : TODO, optional
Returns
-------
Chart
def rug(x, label=None, opacity=None):
"""Rug chart.
Parameters
----------
x : array-like, optional
label : TODO, optional
opacity : ... |
Surface plot.
Parameters
----------
x : array-like, optional
y : array-like, optional
z : array-like, optional
Returns
-------
Chart
def surface(x, y, z):
"""Surface plot.
Parameters
----------
x : array-like, optional
y : array-like, optional
z : array-like, ... |
Histogram.
Parameters
----------
x : array-like
mode : str, optional
label : TODO, optional
opacity : float, optional
horz : bool, optional
histnorm : None, "percent", "probability", "density", "probability density", optional
Specifies the type of normalization used for this his... |
2D Histogram.
Parameters
----------
x : array-like, optional
y : array-like, optional
label : TODO, optional
opacity : float, optional
Returns
-------
Chart
def hist2d(x, y, label=None, opacity=None):
"""2D Histogram.
Parameters
----------
x : array-like, optional... |
Set the angle of the y-axis tick labels.
Parameters
----------
value : int
Angle in degrees
index : int, optional
Y-axis index
Returns
-------
Chart
def ytickangle(self, angle, index=1):
"""Set the angle of the y-axis tick labels... |
Set the size of the label.
Parameters
----------
size : int
Returns
-------
Chart
def ylabelsize(self, size, index=1):
"""Set the size of the label.
Parameters
----------
size : int
Returns
-------
Chart
... |
Set the tick font size.
Parameters
----------
size : int
Returns
-------
Chart
def yticksize(self, size, index=1):
"""Set the tick font size.
Parameters
----------
size : int
Returns
-------
Chart
"""
... |
Set the tick values.
Parameters
----------
values : array-like
Returns
-------
Chart
def ytickvals(self, values, index=1):
"""Set the tick values.
Parameters
----------
values : array-like
Returns
-------
Chart
... |
Set the tick labels.
Parameters
----------
labels : array-like
Returns
-------
Chart
def yticktext(self, labels, index=1):
"""Set the tick labels.
Parameters
----------
labels : array-like
Returns
-------
Chart
... |
Set yaxis limits.
Parameters
----------
low : number
high : number
index : int, optional
Returns
-------
Chart
def ylim(self, low, high, index=1):
"""Set yaxis limits.
Parameters
----------
low : number
high : nu... |
Set the tick distance.
def ydtick(self, dtick, index=1):
"""Set the tick distance."""
self.layout['yaxis' + str(index)]['dtick'] = dtick
return self |
Set the number of ticks.
def ynticks(self, nticks, index=1):
"""Set the number of ticks."""
self.layout['yaxis' + str(index)]['nticks'] = nticks
return self |
Display the chart.
Parameters
----------
filename : str, optional
Save plot to this filename, otherwise it's saved to a temporary file.
show_link : bool, optional
Show link to plotly.
auto_open : bool, optional
Automatically open the plot (in ... |
Save the chart to an html file.
def save(
self,
filename: Optional[str] = None,
show_link: bool = True,
auto_open: bool = False,
output: str = 'file',
plotlyjs: bool = True,
) -> str:
"""Save the chart to an html file."""
if filename is None:
... |
**RegisterMethod**
RegisterMethod(f, library_path, alias=None, original_name=None, doc=None, wrapped=None, explanation="", method_type=utils.identity, explain=True)
`classmethod` for registering functions as methods of this class.
**Arguments**
* **f** : the particular function being registered as a method
* **... |
**RegisterAt**
RegisterAt(n, f, library_path, alias=None, original_name=None, doc=None, wrapped=None, explanation="", method_type=utils.identity, explain=True, _return_type=None)
Most of the time you don't want to register an method as such, that is, you don't care about the `self` builder object, instead you wan... |
This classmethod lets you easily patch all of functions/callables from a module or class as methods a Builder class.
**Arguments**
* **n** : the position the the object being piped will take in the arguments when the function being patched is applied. See `RegisterMethod` and `ThenAt`.
* **module** : a module or clas... |
Given a function, it returns a string that pretty much looks how the
function signature_ would be written in python.
:param method: a python method
:return: A string similar describing the pythong method signature_.
eg: "my_method(first_argArg, second_arg=42, third_arg='something')"
def get_method_sig... |
`Pipe` runs any `phi.dsl.Expression`. Its highly inspired by Elixir's [|> (pipe)](https://hexdocs.pm/elixir/Kernel.html#%7C%3E/2) operator.
**Arguments**
* ***sequence**: any variable amount of expressions. All expressions inside of `sequence` will be composed together using `phi.dsl.Expression.Seq`.
* ****kwargs**: ... |
`ThenAt` enables you to create a partially apply many arguments to a function, the returned partial expects a single arguments which will be applied at the `n`th position of the original function.
**Arguments**
* **n**: position at which the created partial will apply its awaited argument on the original function.
* ... |
`Then0(f, ...)` is equivalent to `ThenAt(0, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
def Then0(self, f, *args, **kwargs):
"""
`Then0(f, ...)` is equivalent to `ThenAt(0, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
"""
return self.ThenAt(0, ... |
`Then(f, ...)` is equivalent to `ThenAt(1, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
def Then(self, f, *args, **kwargs):
"""
`Then(f, ...)` is equivalent to `ThenAt(1, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
"""
return self.ThenAt(1, f, ... |
`Then2(f, ...)` is equivalent to `ThenAt(2, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
def Then2(self, f, arg1, *args, **kwargs):
"""
`Then2(f, ...)` is equivalent to `ThenAt(2, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
"""
args = (arg1,) +... |
`Then3(f, ...)` is equivalent to `ThenAt(3, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
def Then3(self, f, arg1, arg2, *args, **kwargs):
"""
`Then3(f, ...)` is equivalent to `ThenAt(3, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
"""
args = (ar... |
`Then4(f, ...)` is equivalent to `ThenAt(4, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
def Then4(self, f, arg1, arg2, arg3, *args, **kwargs):
"""
`Then4(f, ...)` is equivalent to `ThenAt(4, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
"""
args... |
`Then5(f, ...)` is equivalent to `ThenAt(5, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
def Then5(self, f, arg1, arg2, arg3, arg4, *args, **kwargs):
"""
`Then5(f, ...)` is equivalent to `ThenAt(5, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
"""
... |
While `Seq` is sequential, `phi.dsl.Expression.List` allows you to split the computation and get back a list with the result of each path. While the list literal should be the most incarnation of this expresion, it can actually be any iterable (implements `__iter__`) that is not a tuple and yields a valid expresion.
T... |
`Seq` is used to express function composition. The expression
Seq(f, g)
be equivalent to
lambda x: g(f(x))
As you see, its a little different from the mathematical definition. Excecution order flow from left to right, this makes reading and reasoning about code way more easy. This bahaviour is based upon th... |
**With**
def With(context_manager, *body):
**Arguments**
* **context_manager**: a [context manager](https://docs.python.org/2/reference/datamodel.html#context-managers) object or valid expression from the DSL that returns a context manager.
* ***body**: any valid expression of the DSL to be evaluated inside the ... |
Same as `phi.dsl.Expression.List` but any string argument `x` is translated to `Read(x)`.
def ReadList(self, *branches, **kwargs):
"""
Same as `phi.dsl.Expression.List` but any string argument `x` is translated to `Read(x)`.
"""
branches = map(lambda x: E.Read(x) if isinstance(x, str) else x, b... |
See `phi.dsl.Expression.Read`
def Write(self, *state_args, **state_dict):
"""See `phi.dsl.Expression.Read`"""
if len(state_dict) + len(state_args) < 1:
raise Exception("Please include at-least 1 state variable, got {0} and {1}".format(state_args, state_dict))
if len(state_dict) > 1... |
The expression
Val(a)
is equivalent to the constant function
lambda x: a
All expression in this module interprete values that are not functions as constant functions using `Val`, for example
Seq(1, P + 1)
is equivalent to
Seq(Val(1), P + 1)
The previous expression as a whole is a constant functi... |
**If**
If(Predicate, *Then)
Having conditionals expressions a necesity in every language, Phi includes the `If` expression for such a purpose.
**Arguments**
* **Predicate** : a predicate expression uses to determine if the `Then` or `Else` branches should be used.
* ***Then** : an expression to be excecuted if ... |
See `phi.dsl.Expression.If`
def Else(self, *Else, **kwargs):
"""See `phi.dsl.Expression.If`"""
root = self._root
ast = self._ast
next_else = E.Seq(*Else)._f
ast = _add_else(ast, next_else)
g = _compile_if(ast)
return root.__then__(g, **kwargs) |
Returns the number of graphemes in the string.
Note that this functions needs to traverse the full string to calculate the length,
unlike `len(string)` and it's time consumption is linear to the length of the string
(up to the `until` value).
Only counts up to the `until` argument, if given. This is u... |
Returns a substring of the given string, counting graphemes instead of codepoints.
Negative indices is currently not supported.
>>> string = "tamil நி (ni)"
>>> string[:7]
'tamil ந'
>>> grapheme.slice(string, end=7)
'tamil நி'
>>> string[7:]
'ி (ni)'
>>> grapheme.slice(string, 7)
... |
Returns true if the sequence of graphemes in substring is also present in string.
This differs from the normal python `in` operator, since the python operator will return
true if the sequence of codepoints are withing the other string without considering
grapheme boundaries.
Performance notes: Very fa... |
Like str.startswith, but also checks that the string starts with the given prefixes sequence of graphemes.
str.startswith may return true for a prefix that is not visually represented as a prefix if a grapheme cluster
is continued after the prefix ends.
>>> grapheme.startswith("✊🏾", "✊")
False
>>... |
Like str.endswith, but also checks that the string ends with the given prefixes sequence of graphemes.
str.endswith may return true for a suffix that is not visually represented as a suffix if a grapheme cluster
is initiated before the suffix starts.
>>> grapheme.endswith("🏳️🌈", "🌈")
False
>>>... |
Returns the highest index up to `max_len` at which the given string can be sliced, without breaking a grapheme.
This is useful for when you want to split or take a substring from a string, and don't really care about
the exact grapheme length, but don't want to risk breaking existing graphemes.
This funct... |
Read B1 logfile (*.log)
Inputs:
filename: the file name
Output: A dictionary.
def readB1logfile(filename):
"""Read B1 logfile (*.log)
Inputs:
filename: the file name
Output: A dictionary.
"""
dic = dict()
# try to open. If this fails, an exception is raised
with ... |
Write a header structure into a B1 logfile.
Inputs:
filename: name of the file.
data: header dictionary
Notes:
exceptions pass through to the caller.
def writeB1logfile(filename, data):
"""Write a header structure into a B1 logfile.
Inputs:
filename: name of the file.... |
Read beamline B1 (HASYLAB, Hamburg) header data
Input
-----
filename: string
the file name. If ends with ``.gz``, it is fed through a ``gunzip``
filter
Output
------
A header dictionary.
Examples
--------
read header data from 'ORG000123.DAT'::
header=read... |
Helper function to interpret lines in an EDF file header.
def _readedf_extractline(left, right):
"""Helper function to interpret lines in an EDF file header.
"""
functions = [int, float, lambda l:float(l.split(None, 1)[0]),
lambda l:int(l.split(None, 1)[0]),
dateutil.parse... |
Read EDF header (ESRF data format, as of beamline ID01 and ID02)
Input
-----
filename: string
the file name to load
Output
------
the EDF header structure in a dictionary
def readehf(filename):
"""Read EDF header (ESRF data format, as of beamline ID01 and ID02)
Input
----... |
Read header data from bdf/bhf file (Bessy Data Format v1)
Input:
filename: the name of the file
load_data: if the matrices are to be loaded
Output:
bdf: the BDF header structure
Adapted the bdf_read.m macro from Sylvio Haas.
def readbhfv1(filename, load_data=False, bdfext='.bdf',... |
Read a header from a MarResearch .image file.
def readmarheader(filename):
"""Read a header from a MarResearch .image file."""
with open(filename, 'rb') as f:
intheader = np.fromstring(f.read(10 * 4), np.int32)
floatheader = np.fromstring(f.read(15 * 4), '<f4')
strheader = f.read(24)
... |
Read a header from a SANS file (produced usually by BerSANS)
def readBerSANS(filename):
"""Read a header from a SANS file (produced usually by BerSANS)"""
hed = {'Comment': ''}
translate = {'Lambda': 'Wavelength',
'Title': 'Owner',
'SampleName': 'Title',
'... |
Sine function
Inputs:
-------
``x``: independent variable
``a``: amplitude
``omega``: circular frequency
``phi``: phase
``y0``: offset
Formula:
--------
``a*sin(x*omega + phi)+y0``
def Sine(x, a, omega, phi, y0):
"""Sine function
Inputs:
--... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.