func_code_string stringlengths 52 1.94M | func_documentation_string stringlengths 1 47.2k |
|---|---|
def get_parsed_context(context_arg):
if not context_arg:
logger.debug("pipeline invoked without context arg set. For "
"this keyvaluepairs parser you're looking for "
"something like: "
"pypyr pipelinename 'key1=value1,key2=value2'.")
... | Parse input context string and returns context as dictionary. |
def run_step(context):
logger.debug("started")
deprecated(context)
context.assert_key_has_value(key='fetchJson', caller=__name__)
fetch_json_input = context.get_formatted('fetchJson')
if isinstance(fetch_json_input, str):
file_path = fetch_json_input
destination_key_expression =... | Load a json file into the pypyr context.
json parsed from the file will be merged into the pypyr context. This will
overwrite existing values if the same keys are already in there.
I.e if file json has {'eggs' : 'boiled'} and context {'eggs': 'fried'}
already exists, returned context['eggs'] will be 'b... |
def deprecated(context):
if 'fetchJsonPath' in context:
context.assert_key_has_value(key='fetchJsonPath', caller=__name__)
context['fetchJson'] = {'path': context['fetchJsonPath']}
if 'fetchJsonKey' in context:
context['fetchJson']['key'] = context.get('fetchJsonKey', None)
... | Create new style in params from deprecated. |
def _ignore_request(self, path):
return any([
re.match(pattern, path) for pattern in QC_SETTINGS['IGNORE_REQUEST_PATTERNS']
]) | Check to see if we should ignore the request. |
def _ignore_sql(self, query):
return any([
re.search(pattern, query.get('sql')) for pattern in QC_SETTINGS['IGNORE_SQL_PATTERNS']
]) | Check to see if we should ignore the sql query. |
def _duplicate_queries(self, output):
if QC_SETTINGS['DISPLAY_DUPLICATES']:
for query, count in self.queries.most_common(QC_SETTINGS['DISPLAY_DUPLICATES']):
lines = ['\nRepeated {0} times.'.format(count)]
lines += wrap(query)
lines = "\n".join... | Appends the most common duplicate queries to the given output. |
def _calculate_num_queries(self):
request_totals = self._totals("request")
response_totals = self._totals("response")
return request_totals[2] + response_totals[2] | Calculate the total number of request and response queries.
Used for count header and count table. |
def _process_settings(**kwargs):
# If we are in this method due to a signal, only reload for our settings
setting_name = kwargs.get('setting', None)
if setting_name is not None and setting_name != 'QUERYCOUNT':
return
# Support the old-style settings
if getattr(settings, 'QUERYCOUNT_TH... | Apply user supplied settings. |
def login(password, phone=None, email=None, rememberLogin=True):
if (phone is None) and (email is None):
raise ParamsError()
if password is None:
raise ParamsError()
r = NCloudBot()
# r.username = phone or email
md5 = hashlib.md5()
md5.update(password)
password = md5.hex... | 登录接口,返回 :class:'Response' 对象
:param password: 网易云音乐的密码
:param phone: (optional) 手机登录
:param email: (optional) 邮箱登录
:param rememberLogin: (optional) 是否记住密码,默认 True |
def user_play_list(uid, offset=0, limit=1000):
if uid is None:
raise ParamsError()
r = NCloudBot()
r.method = 'USER_PLAY_LIST'
r.data = {'offset': offset, 'uid': uid, 'limit': limit, 'csrf_token': ''}
r.send()
return r.response | 获取用户歌单,包含收藏的歌单
:param uid: 用户的ID,可通过登录或者其他接口获取
:param offset: (optional) 分段起始位置,默认 0
:param limit: (optional) 数据上限多少行,默认 1000 |
def user_dj(uid, offset=0, limit=30):
if uid is None:
raise ParamsError()
r = NCloudBot()
r.method = 'USER_DJ'
r.data = {'offset': offset, 'limit': limit, "csrf_token": ""}
r.params = {'uid': uid}
r.send()
return r.response | 获取用户电台数据
:param uid: 用户的ID,可通过登录或者其他接口获取
:param offset: (optional) 分段起始位置,默认 0
:param limit: (optional) 数据上限多少行,默认 30 |
def search(keyword, type=1, offset=0, limit=30):
if keyword is None:
raise ParamsError()
r = NCloudBot()
r.method = 'SEARCH'
r.data = {
's': keyword,
'limit': str(limit),
'type': str(type),
'offset': str(offset)
}
r.send()
return r.response | 搜索歌曲,支持搜索歌曲、歌手、专辑等
:param keyword: 关键词
:param type: (optional) 搜索类型,1: 单曲, 100: 歌手, 1000: 歌单, 1002: 用户
:param offset: (optional) 分段起始位置,默认 0
:param limit: (optional) 数据上限多少行,默认 30 |
def user_follows(uid, offset='0', limit=30):
if uid is None:
raise ParamsError()
r = NCloudBot()
r.method = 'USER_FOLLOWS'
r.params = {'uid': uid}
r.data = {'offset': offset, 'limit': limit, 'order': True}
r.send()
return r.response | 获取用户关注列表
:param uid: 用户的ID,可通过登录或者其他接口获取
:param offset: (optional) 分段起始位置,默认 0
:param limit: (optional) 数据上限多少行,默认 30 |
def user_event(uid):
if uid is None:
raise ParamsError()
r = NCloudBot()
r.method = 'USER_EVENT'
r.params = {'uid': uid}
r.data = {'time': -1, 'getcounts': True, "csrf_token": ""}
r.send()
return r.response | 获取用户动态
:param uid: 用户的ID,可通过登录或者其他接口获取 |
def user_record(uid, type=0):
if uid is None:
raise ParamsError()
r = NCloudBot()
r.method = 'USER_RECORD'
r.data = {'type': type, 'uid': uid, "csrf_token": ""}
r.send()
return r.response | 获取用户的播放列表,必须登录
:param uid: 用户的ID,可通过登录或者其他接口获取
:param type: (optional) 数据类型,0:获取所有记录,1:获取 weekData |
def event():
r = NCloudBot()
r.method = 'EVENT'
r.data = {"csrf_token": ""}
r.send()
return r.response | 获取好友的动态,包括分享视频、音乐、动态等 |
def top_playlist_highquality(cat='全部', offset=0, limit=20):
r = NCloudBot()
r.method = 'TOP_PLAYLIST_HIGHQUALITY'
r.data = {'cat': cat, 'offset': offset, 'limit': limit}
r.send()
return r.response | 获取网易云音乐的精品歌单
:param cat: (optional) 歌单类型,默认 ‘全部’,比如 华语、欧美等
:param offset: (optional) 分段起始位置,默认 0
:param limit: (optional) 数据上限多少行,默认 20 |
def play_list_detail(id, limit=20):
if id is None:
raise ParamsError()
r = NCloudBot()
r.method = 'PLAY_LIST_DETAIL'
r.data = {'id': id, 'limit': limit, "csrf_token": ""}
r.send()
return r.response | 获取歌单中的所有音乐。由于获取精品中,只能看到歌单名字和 ID 并没有歌单的音乐,因此增加该接口传入歌单 ID
获取歌单中的所有音乐.
:param id: 歌单的ID
:param limit: (optional) 数据上限多少行,默认 20 |
def music_url(ids=[]):
if not isinstance(ids, list):
raise ParamsError()
r = NCloudBot()
r.method = 'MUSIC_URL'
r.data = {'ids': ids, 'br': 999000, "csrf_token": ""}
r.send()
return r.response | 通过歌曲 ID 获取歌曲下载地址
:param ids: 歌曲 ID 的 list |
def lyric(id):
if id is None:
raise ParamsError()
r = NCloudBot()
r.method = 'LYRIC'
r.params = {'id': id}
r.send()
return r.response | 通过歌曲 ID 获取歌曲歌词地址
:param id: 歌曲ID |
def music_comment(id, offset=0, limit=20):
if id is None:
raise ParamsError()
r = NCloudBot()
r.method = 'MUSIC_COMMENT'
r.params = {'id': id}
r.data = {'offset': offset, 'limit': limit, 'rid': id, "csrf_token": ""}
r.send()
return r.response | 获取歌曲的评论列表
:param id: 歌曲 ID
:param offset: (optional) 分段起始位置,默认 0
:param limit: (optional) 数据上限多少行,默认 20 |
def song_detail(ids):
if not isinstance(ids, list):
raise ParamsError()
c = []
for id in ids:
c.append({'id': id})
r = NCloudBot()
r.method = 'SONG_DETAIL'
r.data = {'c': json.dumps(c), 'ids': c, "csrf_token": ""}
r.send()
return r.response | 通过歌曲 ID 获取歌曲的详细信息
:param ids: 歌曲 ID 的 list |
def personal_fm():
r = NCloudBot()
r.method = 'PERSONAL_FM'
r.data = {"csrf_token": ""}
r.send()
return r.response | 个人的 FM ,必须在登录之后调用,即 login 之后调用 |
def _get_webapi_requests(self):
headers = {
'Accept':
'*/*',
'Accept-Language':
'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4',
'Connection':
'keep-alive',
'Content-Type':
'application/x-www-form-urlencoded',
... | Update headers of webapi for Requests. |
def _build_response(self, resp):
# rememberLogin
# if self.method is 'LOGIN' and resp.json().get('code') == 200:
# cookiesJar.save_cookies(resp, NCloudBot.username)
self.response.content = resp.content
self.response.status_code = resp.status_code
self.respons... | Build internal Response object from given response. |
def send(self):
success = False
if self.method is None:
raise ParamsError()
try:
if self.method == 'SEARCH':
req = self._get_requests()
_url = self.__NETEAST_HOST + self._METHODS[self.method]
resp = req.post(_url, d... | Sens the request. |
def json(self):
if not self.headers and len(self.content) > 3:
encoding = get_encoding_from_headers(self.headers)
if encoding is not None:
return json.loads(self.content.decode(encoding))
return json.loads(self.content) | Returns the json-encoded content of a response, if any. |
def set_option(name, value):
old = get_option(name)
globals()[name] = value
return old | Set plydata option
Parameters
----------
name : str
Name of the option
value : object
New value of the option
Returns
-------
old : object
Old value of the option
See also
--------
:class:`options` |
def _join(verb):
data = pd.merge(verb.x, verb.y, **verb.kwargs)
# Preserve x groups
if isinstance(verb.x, GroupedDataFrame):
data.plydata_groups = list(verb.x.plydata_groups)
return data | Join helper |
def groupby(self, by=None, **kwargs):
if by is None:
by = self.plydata_groups
# Turn off sorting by groups messes with some verbs
if 'sort' not in kwargs:
kwargs['sort'] = False
return super().groupby(by, **kwargs) | Group by and do not sort (unless specified)
For plydata use cases, there is no need to specify
group columns. |
def group_indices(self):
# No groups
if not self.plydata_groups:
return np.ones(len(self), dtype=int)
grouper = self.groupby()
indices = np.empty(len(self), dtype=int)
for i, (_, idx) in enumerate(sorted(grouper.indices.items())):
indices[idx] = i... | Return group indices |
def _make_verb_helper(verb_func, add_groups=False):
@wraps(verb_func)
def _verb_func(verb):
verb.expressions, new_columns = build_expressions(verb)
if add_groups:
verb.groups = new_columns
return verb_func(verb)
return _verb_func | Create function that prepares verb for the verb function
The functions created add expressions to be evaluated to
the verb, then call the core verb function
Parameters
----------
verb_func : function
Core verb function. This is the function called after
expressions created and adde... |
def _get_base_dataframe(df):
if isinstance(df, GroupedDataFrame):
base_df = GroupedDataFrame(
df.loc[:, df.plydata_groups], df.plydata_groups,
copy=True)
else:
base_df = pd.DataFrame(index=df.index)
return base_df | Remove all columns other than those grouped on |
def _add_group_columns(data, gdf):
n = len(data)
if isinstance(gdf, GroupedDataFrame):
for i, col in enumerate(gdf.plydata_groups):
if col not in data:
group_values = [gdf[col].iloc[0]] * n
# Need to be careful and maintain the dtypes
# of... | Add group columns to data with a value from the grouped dataframe
It is assumed that the grouped dataframe contains a single group
>>> data = pd.DataFrame({
... 'x': [5, 6, 7]})
>>> gdf = GroupedDataFrame({
... 'g': list('aaa'),
... 'x': range(3)}, groups=['g'])
>>> _add_group_... |
def _create_column(data, col, value):
with suppress(AttributeError):
# If the index of a series and the dataframe
# in which the series will be assigned to a
# column do not match, missing values/NaNs
# are created. We do not want that.
if not value.index.equals(data.ind... | Create column in dataframe
Helper method meant to deal with problematic
column values. e.g When the series index does
not match that of the data.
Parameters
----------
data : pandas.DataFrame
dataframe in which to insert value
col : column label
Column name
value : obje... |
def build_expressions(verb):
def partial(func, col, *args, **kwargs):
def new_func(gdf):
return func(gdf[col], *args, **kwargs)
return new_func
def make_statement(func, col):
if isinstance(func, str):
expr = '{}({})'.format(func, col)
... | Build expressions for helper verbs
Parameters
----------
verb : verb
A verb with a *functions* attribute.
Returns
-------
out : tuple
(List of Expressions, New columns). The expressions and the
new columns in which the results of those expressions will
be stored... |
def process(self):
# Short cut
if self._all_expressions_evaluated():
if self.drop:
# Drop extra columns. They do not correspond to
# any expressions.
columns = [expr.column for expr in self.expressions]
self.data = self... | Run the expressions
Returns
-------
out : pandas.DataFrame
Resulting data |
def _all_expressions_evaluated(self):
def present(expr):
return expr.stmt == expr.column and expr.column in self.data
return all(present(expr) for expr in self.expressions) | Return True all expressions match with the columns
Saves some processor cycles |
def _get_group_dataframes(self):
if isinstance(self.data, GroupedDataFrame):
grouper = self.data.groupby()
# groupby on categorical columns uses the categories
# even if they are not present in the data. This
# leads to empty groups. We exclude them.
... | Get group dataframes
Returns
-------
out : tuple or generator
Group dataframes |
def _evaluate_group_dataframe(self, gdf):
gdf._is_copy = None
result_index = gdf.index if self.keep_index else []
data = pd.DataFrame(index=result_index)
for expr in self.expressions:
value = expr.evaluate(gdf, self.env)
if isinstance(value, pd.DataFrame)... | Evaluate a single group dataframe
Parameters
----------
gdf : pandas.DataFrame
Input group dataframe
Returns
-------
out : pandas.DataFrame
Result data |
def _concat(self, egdfs):
egdfs = list(egdfs)
edata = pd.concat(egdfs, axis=0, ignore_index=False, copy=False)
# groupby can mixup the rows. We try to maintain the original
# order, but we can only do that if the result has a one to
# one relationship with the original
... | Concatenate evaluated group dataframes
Parameters
----------
egdfs : iterable
Evaluated dataframes
Returns
-------
edata : pandas.DataFrame
Evaluated data |
def _resolve_slices(data_columns, names):
def _get_slice_cols(sc):
# Just like pandas.DataFrame.loc the stop
# column is included
idx_start = data_columns.get_loc(sc.start)
idx_stop = data_columns.get_loc(sc.stop) + 1
return data_... | Convert any slices into column names
Parameters
----------
data_columns : pandas.Index
Dataframe columns
names : tuple
Names (including slices) of columns in the
dataframe.
Returns
-------
out : tuple
Names of colu... |
def select(cls, verb):
columns = verb.data.columns
contains = verb.contains
matches = verb.matches
groups = _get_groups(verb)
names = cls._resolve_slices(columns, verb.names)
names_set = set(names)
groups_set = set(groups)
lst = [[]]
if na... | Return selected columns for the select verb
Parameters
----------
verb : object
verb with the column selection attributes:
- names
- startswith
- endswith
- contains
- matches |
def _all(cls, verb):
groups = set(_get_groups(verb))
return [col for col in verb.data if col not in groups] | A verb |
def _at(cls, verb):
# Named (listed) columns are always included
columns = cls.select(verb)
final_columns_set = set(cls.select(verb))
groups_set = set(_get_groups(verb))
final_columns_set -= groups_set - set(verb.names)
def pred(col):
if col not in ve... | A verb with a select text match |
def _if(cls, verb):
pred = verb.predicate
data = verb.data
groups = set(_get_groups(verb))
# force predicate
if isinstance(pred, str):
if not pred.endswith('_dtype'):
pred = '{}_dtype'.format(pred)
pred = getattr(pdtypes, pred)
... | A verb with a predicate function |
def get_verb_function(data, verb):
try:
module = type_lookup[type(data)]
except KeyError:
# Some guess work for subclasses
for type_, mod in type_lookup.items():
if isinstance(data, type_):
module = mod
break
try:
return getatt... | Return function that implements the verb for given data type |
def Expression(*args, **kwargs):
# dispatch
if not hasattr(args[0], '_Expression'):
return BaseExpression(*args, *kwargs)
else:
return args[0]._Expression(*args, **kwargs) | Return an appropriate Expression given the arguments
Parameters
----------
args : tuple
Positional arguments passed to the Expression class
kwargs : dict
Keyword arguments passed to the Expression class |
def evaluate(self, data, env):
def n():
return len(data)
if isinstance(self.stmt, str):
# Add function n() that computes the
# size of the group data to the inner namespace.
if self._has_n_func:
namespace = dict(data, ... | Evaluate statement
Parameters
----------
data : pandas.DataFrame
Data in whose namespace the statement will be
evaluated. Typically, this is a group dataframe.
Returns
-------
out : object
Result of the evaluation.pandas.DataFrame |
def evaluate(self, data, env):
# For each predicate-value, we keep track of the positions
# that have been copied to the result, so that the later
# more general values do not overwrite the previous ones.
result = np.repeat(None, len(data))
copied = np.repeat(False, len(... | Evaluate the predicates and values |
def evaluate(self, data, env):
bool_idx = self.predicate_expr.evaluate(data, env)
true_value = self.true_value_expr.evaluate(data, env)
false_value = self.false_value_expr.evaluate(data, env)
true_idx = np.where(bool_idx)[0]
false_idx = np.where(~bool_idx)[0]
res... | Evaluate the predicates and values |
def with_outer_namespace(self, outer_namespace):
return self.__class__(self._namespaces + [outer_namespace],
self.flags) | Return a new EvalEnvironment with an extra namespace added.
This namespace will be used only for variables that are not found in
any existing namespace, i.e., it is "outside" them all. |
def eval(self, expr, source_name="<string>", inner_namespace={}):
code = compile(expr, source_name, "eval", self.flags, False)
return eval(code, {}, VarLookupDict([inner_namespace]
+ self._namespaces)) | Evaluate some Python code in the encapsulated environment.
:arg expr: A string containing a Python expression.
:arg source_name: A name for this string, for use in tracebacks.
:arg inner_namespace: A dict-like object that will be checked first
when `expr` attempts to access any variabl... |
def capture(cls, eval_env=0, reference=0):
if isinstance(eval_env, cls):
return eval_env
elif isinstance(eval_env, numbers.Integral):
depth = eval_env + reference
else:
raise TypeError("Parameter 'eval_env' must be either an integer "
... | Capture an execution environment from the stack.
If `eval_env` is already an :class:`EvalEnvironment`, it is returned
unchanged. Otherwise, we walk up the stack by ``eval_env + reference``
steps and capture that function's evaluation environment.
For ``eval_env=0`` and ``reference=0``, t... |
def subset(self, names):
vld = VarLookupDict(self._namespaces)
new_ns = dict((name, vld[name]) for name in names)
return EvalEnvironment([new_ns], self.flags) | Creates a new, flat EvalEnvironment that contains only
the variables specified. |
def temporary_key(d, key, value):
d[key] = value
try:
yield d
finally:
del d[key] | Context manager that removes key from dictionary on closing
The dictionary will hold the key for the duration of
the context.
Parameters
----------
d : dict-like
Dictionary in which to insert a temporary key.
key : hashable
Location at which to insert ``value``.
value : obj... |
def temporary_attr(obj, name, value):
setattr(obj, name, value)
try:
yield obj
finally:
delattr(obj, name) | Context manager that removes key from dictionary on closing
The dictionary will hold the key for the duration of
the context.
Parameters
----------
obj : object
Object onto which to add a temporary attribute.
name : str
Name of attribute to add to ``obj``.
value : object
... |
def Q(name):
env = EvalEnvironment.capture(1)
try:
return env.namespace[name]
except KeyError:
raise NameError("No data named {!r} found".format(name)) | Quote a variable name
A way to 'quote' variable names, especially ones that do not otherwise
meet Python's variable name rules.
Parameters
----------
name : str
Name of variable
Returns
-------
value : object
Value of variable
Examples
--------
>>> import ... |
def regular_index(*dfs):
original_index = [df.index for df in dfs]
have_bad_index = [not isinstance(df.index, pd.RangeIndex)
for df in dfs]
for df, bad in zip(dfs, have_bad_index):
if bad:
df.reset_index(drop=True, inplace=True)
try:
yield dfs
f... | Change & restore the indices of dataframes
Dataframe with duplicate values can be hard to work with.
When split and recombined, you cannot restore the row order.
This can be the case even if the index has unique but
irregular/unordered. This contextmanager resets the unordered
indices of any datafr... |
def unique(lst):
seen = set()
def make_seen(x):
seen.add(x)
return x
return [make_seen(x) for x in lst if x not in seen] | Return unique elements
:class:`pandas.unique` and :class:`numpy.unique` cast
mixed type lists to the same type. They are faster, but
some times we want to maintain the type.
Parameters
----------
lst : list-like
List of items
Returns
-------
out : list
Unique items... |
def _nth(arr, n):
try:
return arr.iloc[n]
except (KeyError, IndexError):
return np.nan | Return the nth value of array
If it is missing return NaN |
def make_time(h=0, m=0, s=0, ms=0, frames=None, fps=None):
if frames is None and fps is None:
return times_to_ms(h, m, s, ms)
elif frames is not None and fps is not None:
return frames_to_ms(frames, fps)
else:
raise ValueError("Both fps and frames must be specified") | Convert time to milliseconds.
See :func:`pysubs2.time.times_to_ms()`. When both frames and fps are specified,
:func:`pysubs2.time.frames_to_ms()` is called instead.
Raises:
ValueError: Invalid fps, or one of frames/fps is missing.
Example:
>>> make_time(s=1.5)
1500
>>>... |
def timestamp_to_ms(groups):
h, m, s, frac = map(int, groups)
ms = frac * 10**(3 - len(groups[-1]))
ms += s * 1000
ms += m * 60000
ms += h * 3600000
return ms | Convert groups from :data:`pysubs2.time.TIMESTAMP` match to milliseconds.
Example:
>>> timestamp_to_ms(TIMESTAMP.match("0:00:00.42").groups())
420 |
def times_to_ms(h=0, m=0, s=0, ms=0):
ms += s * 1000
ms += m * 60000
ms += h * 3600000
return int(round(ms)) | Convert hours, minutes, seconds to milliseconds.
Arguments may be positive or negative, int or float,
need not be normalized (``s=120`` is okay).
Returns:
Number of milliseconds (rounded to int). |
def frames_to_ms(frames, fps):
if fps <= 0:
raise ValueError("Framerate must be positive number (%f)." % fps)
return int(round(frames * (1000 / fps))) | Convert frame-based duration to milliseconds.
Arguments:
frames: Number of frames (should be int).
fps: Framerate (must be a positive number, eg. 23.976).
Returns:
Number of milliseconds (rounded to int).
Raises:
ValueError: fps was negative or zero. |
def ms_to_frames(ms, fps):
if fps <= 0:
raise ValueError("Framerate must be positive number (%f)." % fps)
return int(round((ms / 1000) * fps)) | Convert milliseconds to number of frames.
Arguments:
ms: Number of milliseconds (may be int, float or other numeric class).
fps: Framerate (must be a positive number, eg. 23.976).
Returns:
Number of frames (int).
Raises:
ValueError: fps was negative or zero... |
def ms_to_times(ms):
ms = int(round(ms))
h, ms = divmod(ms, 3600000)
m, ms = divmod(ms, 60000)
s, ms = divmod(ms, 1000)
return Times(h, m, s, ms) | Convert milliseconds to normalized tuple (h, m, s, ms).
Arguments:
ms: Number of milliseconds (may be int, float or other numeric class).
Should be non-negative.
Returns:
Named tuple (h, m, s, ms) of ints.
Invariants: ``ms in range(1000) and s in range(60) and m in ... |
def ms_to_str(ms, fractions=False):
sgn = "-" if ms < 0 else ""
h, m, s, ms = ms_to_times(abs(ms))
if fractions:
return sgn + "{:01d}:{:02d}:{:02d}.{:03d}".format(h, m, s, ms)
else:
return sgn + "{:01d}:{:02d}:{:02d}".format(h, m, s) | Prettyprint milliseconds to [-]H:MM:SS[.mmm]
Handles huge and/or negative times. Non-negative times with ``fractions=True``
are matched by :data:`pysubs2.time.TIMESTAMP`.
Arguments:
ms: Number of milliseconds (int, float or other numeric class).
fractions: Whether to print up to mi... |
def ms_to_timestamp(ms):
# XXX throw on overflow/underflow?
if ms < 0: ms = 0
if ms > MAX_REPRESENTABLE_TIME: ms = MAX_REPRESENTABLE_TIME
h, m, s, ms = ms_to_times(ms)
return "%01d:%02d:%02d.%02d" % (h, m, s, ms//10) | Convert ms to 'H:MM:SS.cc |
def parse_tags(text, style=SSAStyle.DEFAULT_STYLE, styles={}):
fragments = SSAEvent.OVERRIDE_SEQUENCE.split(text)
if len(fragments) == 1:
return [(text, style)]
def apply_overrides(all_overrides):
s = style.copy()
for tag in re.findall(r"\\[ibus][10]|\\r[a-zA-Z_0-9 ]*"... | Split text into fragments with computed SSAStyles.
Returns list of tuples (fragment, style), where fragment is a part of text
between two brace-delimited override sequences, and style is the computed
styling of the fragment, ie. the original style modified by all override
sequences before the fragm... |
def plaintext(self):
text = self.text
text = self.OVERRIDE_SEQUENCE.sub("", text)
text = text.replace(r"\h", " ")
text = text.replace(r"\n", "\n")
text = text.replace(r"\N", "\n")
return text | Subtitle text as multi-line string with no tags (read/write property).
Writing to this property replaces :attr:`SSAEvent.text` with given plain
text. Newlines are converted to ``\\N`` tags. |
def shift(self, h=0, m=0, s=0, ms=0, frames=None, fps=None):
delta = make_time(h=h, m=m, s=s, ms=ms, frames=frames, fps=fps)
self.start += delta
self.end += delta | Shift start and end times.
See :meth:`SSAFile.shift()` for full description. |
def equals(self, other):
if isinstance(other, SSAEvent):
return self.as_dict() == other.as_dict()
else:
raise TypeError("Cannot compare to non-SSAEvent object") | Field-based equality for SSAEvents. |
def load(cls, path, encoding="utf-8", format_=None, fps=None, **kwargs):
with open(path, encoding=encoding) as fp:
return cls.from_file(fp, format_, fps=fps, **kwargs) | Load subtitle file from given path.
Arguments:
path (str): Path to subtitle file.
encoding (str): Character encoding of input file.
Defaults to UTF-8, you may need to change this.
format_ (str): Optional, forces use of specific parser
(eg. `"s... |
def from_string(cls, string, format_=None, fps=None, **kwargs):
fp = io.StringIO(string)
return cls.from_file(fp, format_, fps=fps, **kwargs) | Load subtitle file from string.
See :meth:`SSAFile.load()` for full description.
Arguments:
string (str): Subtitle file in a string. Note that the string
must be Unicode (in Python 2).
Returns:
SSAFile
Example:
>>> text = '''
... |
def from_file(cls, fp, format_=None, fps=None, **kwargs):
if format_ is None:
# Autodetect subtitle format, then read again using correct parser.
# The file might be a pipe and we need to read it twice,
# so just buffer everything.
text = fp.read()
... | Read subtitle file from file object.
See :meth:`SSAFile.load()` for full description.
Note:
This is a low-level method. Usually, one of :meth:`SSAFile.load()`
or :meth:`SSAFile.from_string()` is preferable.
Arguments:
fp (file object): A file object, ie. :c... |
def save(self, path, encoding="utf-8", format_=None, fps=None, **kwargs):
if format_ is None:
ext = os.path.splitext(path)[1].lower()
format_ = get_format_identifier(ext)
with open(path, "w", encoding=encoding) as fp:
self.to_file(fp, format_, fps=fps, **kwar... | Save subtitle file to given path.
Arguments:
path (str): Path to subtitle file.
encoding (str): Character encoding of output file.
Defaults to UTF-8, which should be fine for most purposes.
format_ (str): Optional, specifies desired subtitle format
... |
def to_string(self, format_, fps=None, **kwargs):
fp = io.StringIO()
self.to_file(fp, format_, fps=fps, **kwargs)
return fp.getvalue() | Get subtitle file as a string.
See :meth:`SSAFile.save()` for full description.
Returns:
str |
def to_file(self, fp, format_, fps=None, **kwargs):
impl = get_format_class(format_)
impl.to_file(self, fp, format_, fps=fps, **kwargs) | Write subtitle file to file object.
See :meth:`SSAFile.save()` for full description.
Note:
This is a low-level method. Usually, one of :meth:`SSAFile.save()`
or :meth:`SSAFile.to_string()` is preferable.
Arguments:
fp (file object): A file object, ie. :clas... |
def transform_framerate(self, in_fps, out_fps):
if in_fps <= 0 or out_fps <= 0:
raise ValueError("Framerates must be positive, cannot transform %f -> %f" % (in_fps, out_fps))
ratio = in_fps / out_fps
for line in self:
line.start = int(round(line.start * ratio))
... | Rescale all timestamps by ratio of in_fps/out_fps.
Can be used to fix files converted from frame-based to time-based
with wrongly assumed framerate.
Arguments:
in_fps (float)
out_fps (float)
Raises:
ValueError: Non-positive framerate given. |
def rename_style(self, old_name, new_name):
if old_name not in self.styles:
raise KeyError("Style %r not found" % old_name)
if new_name in self.styles:
raise ValueError("There is already a style called %r" % new_name)
if not is_valid_field_content(new_name):
... | Rename a style, including references to it.
Arguments:
old_name (str): Style to be renamed.
new_name (str): New name for the style (must be unused).
Raises:
KeyError: No style named old_name.
ValueError: new_name is not a legal name (cannot use commas)
... |
def import_styles(self, subs, overwrite=True):
if not isinstance(subs, SSAFile):
raise TypeError("Must supply an SSAFile.")
for name, style in subs.styles.items():
if name not in self.styles or overwrite:
self.styles[name] = style | Merge in styles from other SSAFile.
Arguments:
subs (SSAFile): Subtitle file imported from.
overwrite (bool): On name conflict, use style from the other file
(default: True). |
def equals(self, other):
if isinstance(other, SSAFile):
for key in set(chain(self.info.keys(), other.info.keys())) - {"ScriptType"}:
sv, ov = self.info.get(key), other.info.get(key)
if sv is None:
logging.debug("%r missing in self.info", k... | Equality of two SSAFiles.
Compares :attr:`SSAFile.info`, :attr:`SSAFile.styles` and :attr:`SSAFile.events`.
Order of entries in OrderedDicts does not matter. "ScriptType" key in info is
considered an implementation detail and thus ignored.
Useful mostly in unit tests. Differences are l... |
def get_file_extension(format_):
if format_ not in FORMAT_IDENTIFIER_TO_FORMAT_CLASS:
raise UnknownFormatIdentifierError(format_)
for ext, f in FILE_EXTENSION_TO_FORMAT_IDENTIFIER.items():
if f == format_:
return ext
raise RuntimeError("No file extension for format %r" % for... | Format identifier -> file extension |
def autodetect_format(content):
formats = set()
for impl in FORMAT_IDENTIFIER_TO_FORMAT_CLASS.values():
guess = impl.guess_format(content)
if guess is not None:
formats.add(guess)
if len(formats) == 1:
return formats.pop()
elif not formats:
raise FormatAu... | Return format identifier for given fragment or raise FormatAutodetectionError. |
def modify_main_app(app, config: Config):
app._debug = True
dft_logger.debug('livereload enabled: %s', '✓' if config.livereload else '✖')
def get_host(request):
if config.infer_host:
return request.headers.get('host', 'localhost').split(':', 1)[0]
else:
return co... | Modify the app we're serving to make development easier, eg.
* modify responses to add the livereload snippet
* set ``static_root_url`` on the app
* setup the debug toolbar |
async def src_reload(app, path: str = None):
cli_count = len(app[WS])
if cli_count == 0:
return 0
is_html = None
if path:
path = str(Path(app['static_url']) / Path(path).relative_to(app['static_path']))
is_html = mimetypes.guess_type(path)[0] == 'text/html'
reloads = 0
... | prompt each connected browser to reload by sending websocket message.
:param path: if supplied this must be a path relative to app['static_path'],
eg. reload of a single file is only supported for static resources.
:return: number of sources reloaded |
def modify_request(self, request):
filename = URL.build(path=request.match_info['filename'], encoded=True).path
raw_path = self._directory.joinpath(filename)
try:
filepath = raw_path.resolve()
if not filepath.exists():
# simulate strict=True for p... | Apply common path conventions eg. / > /index.html, /foobar > /foobar.html |
def substitute_environ(self):
for attr_name in dir(self):
if attr_name.startswith('_') or attr_name.upper() != attr_name:
continue
orig_value = getattr(self, attr_name)
is_required = isinstance(orig_value, Required)
orig_type = orig_value.... | Substitute environment variables into settings. |
def prepare_database(delete_existing: bool) -> bool:
settings = Settings()
conn = psycopg2.connect(
password=settings.DB_PASSWORD,
host=settings.DB_HOST,
port=settings.DB_PORT,
user=settings.DB_USER,
)
conn.autocommit = True
cur = conn.cursor()
db_name = sett... | (Re)create a fresh database and run migrations.
:param delete_existing: whether or not to drop an existing database if it exists
:return: whether or not a database has been (re)created |
async def index(request):
# {% if database.is_none and example.is_message_board %}
# app.router allows us to generate urls based on their names,
# see http://aiohttp.readthedocs.io/en/stable/web.html#reverse-url-constructing-using-named-resources
message_url = request.app.router['messages'].url_for... | This is the view handler for the "/" url.
**Note: returning html without a template engine like jinja2 is ugly, no way around that.**
:param request: the request object see http://aiohttp.readthedocs.io/en/stable/web_reference.html#request
:return: aiohttp.web.Response object |
async def message_data(request):
messages = []
# {% if database.is_none %}
if request.app['settings'].MESSAGE_FILE.exists():
# read the message file, process it and populate the "messages" list
with request.app['settings'].MESSAGE_FILE.open() as msg_file:
for line in msg_fil... | As an example of aiohttp providing a non-html response, we load the actual messages for the "messages" view above
via ajax using this endpoint to get data. see static/message_display.js for details of rendering. |
def pg_dsn(settings: Settings) -> str:
return str(URL(
database=settings.DB_NAME,
password=settings.DB_PASSWORD,
host=settings.DB_HOST,
port=settings.DB_PORT,
username=settings.DB_USER,
drivername='postgres',
)) | :param settings: settings including connection settings
:return: DSN url suitable for sqlalchemy and aiopg. |
def serve(path, livereload, port, verbose):
setup_logging(verbose)
run_app(*serve_static(static_path=path, livereload=livereload, port=port)) | Serve static files from a directory. |
def runserver(**config):
active_config = {k: v for k, v in config.items() if v is not None}
setup_logging(config['verbose'])
try:
run_app(*_runserver(**active_config))
except AiohttpDevException as e:
if config['verbose']:
tb = click.style(traceback.format_exc().strip('\... | Run a development server for an aiohttp apps.
Takes one argument "app-path" which should be a path to either a directory containing a recognized default file
("app.py" or "main.py") or to a specific file. Defaults to the environment variable "AIO_APP_PATH" or ".".
The app path is run directly, see the "--... |
def start(*, path, name, verbose, **kwargs):
setup_logging(verbose)
try:
check_dir_clean(Path(path))
if name is None:
name = Path(path).name
for kwarg_name, choice_enum in DECISIONS:
docs = dedent(choice_enum.__doc__).split('\n')
title, *help_text... | Create a new aiohttp app. |
def import_app_factory(self):
rel_py_file = self.py_file.relative_to(self.python_path)
module_path = '.'.join(rel_py_file.with_suffix('').parts)
sys.path.append(str(self.python_path))
try:
module = import_module(module_path)
except ImportError as e:
... | Import attribute/class from from a python module. Raise AdevConfigError if the import failed.
:return: (attribute, Path object for directory of file) |
def runserver(**config_kwargs):
# force a full reload in sub processes so they load an updated version of code, this must be called only once
set_start_method('spawn')
config = Config(**config_kwargs)
config.import_app_factory()
loop = asyncio.get_event_loop()
loop.run_until_complete(check_... | Prepare app ready to run development server.
:param config_kwargs: see config.Config for more details
:return: tuple (auxiliary app, auxiliary app port, event loop) |
def log_config(verbose: bool) -> dict:
log_level = 'DEBUG' if verbose else 'INFO'
return {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format': '[%(asctime)s] %(message)s',
'datefmt': '%H:%M:%S',
... | Setup default config. for dictConfig.
:param verbose: level: DEBUG if True, INFO if False
:return: dict suitable for ``logging.config.dictConfig`` |
def scenario(weight=1, delay=0.0, name=None):
def _scenario(func, *args, **kw):
_check_coroutine(func)
if weight > 0:
sname = name or func.__name__
data = {'name': sname,
'weight': weight, 'delay': delay,
'func': func, 'args': args... | Decorator to register a function as a Molotov test.
Options:
- **weight** used by Molotov when the scenarii are randomly picked.
The functions with the highest values are more likely to be picked.
Integer, defaults to 1. This value is ignored when the
*scenario_picker* decorator is used.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.