repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
astropy/pyregion | pyregion/core.py | open | python | def open(fname):
with _builtin_open(fname) as fh:
region_string = fh.read()
return parse(region_string) | Open, read and parse DS9 region file.
Parameters
----------
fname : str
Filename
Returns
-------
shapes : `ShapeList`
List of `~pyregion.Shape` | train | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/core.py#L245-L260 | [
"def parse(region_string):\n \"\"\"Parse DS9 region string into a ShapeList.\n\n Parameters\n ----------\n region_string : str\n Region string\n\n Returns\n -------\n shapes : `ShapeList`\n List of `~pyregion.Shape`\n \"\"\"\n rp = RegionParser()\n ss = rp.parse(region_st... | from itertools import cycle
from .ds9_region_parser import RegionParser
from .wcs_converter import check_wcs as _check_wcs
_builtin_open = open
class ShapeList(list):
"""A list of `~pyregion.Shape` objects.
Parameters
----------
shape_list : list
List of `pyregion.Shape` objects
comment... |
astropy/pyregion | pyregion/core.py | read_region | python | def read_region(s):
rp = RegionParser()
ss = rp.parse(s)
sss1 = rp.convert_attr(ss)
sss2 = _check_wcs(sss1)
shape_list = rp.filter_shape(sss2)
return ShapeList(shape_list) | Read region.
Parameters
----------
s : str
Region string
Returns
-------
shapes : `ShapeList`
List of `~pyregion.Shape` | train | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/core.py#L263-L282 | [
"def check_wcs(l):\n default_coord = \"physical\"\n\n for l1, c1 in l:\n if isinstance(l1, CoordCommand):\n default_coord = l1.text.lower()\n continue\n if isinstance(l1, Shape):\n if default_coord == \"galactic\":\n is_wcs, coord_list = check_wcs_... | from itertools import cycle
from .ds9_region_parser import RegionParser
from .wcs_converter import check_wcs as _check_wcs
_builtin_open = open
class ShapeList(list):
"""A list of `~pyregion.Shape` objects.
Parameters
----------
shape_list : list
List of `pyregion.Shape` objects
comment... |
astropy/pyregion | pyregion/core.py | read_region_as_imagecoord | python | def read_region_as_imagecoord(s, header):
rp = RegionParser()
ss = rp.parse(s)
sss1 = rp.convert_attr(ss)
sss2 = _check_wcs(sss1)
sss3 = rp.sky_to_image(sss2, header)
shape_list = rp.filter_shape(sss3)
return ShapeList(shape_list) | Read region as image coordinates.
Parameters
----------
s : str
Region string
header : `~astropy.io.fits.Header`
FITS header
Returns
-------
shapes : `~pyregion.ShapeList`
List of `~pyregion.Shape` | train | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/core.py#L285-L307 | [
"def check_wcs(l):\n default_coord = \"physical\"\n\n for l1, c1 in l:\n if isinstance(l1, CoordCommand):\n default_coord = l1.text.lower()\n continue\n if isinstance(l1, Shape):\n if default_coord == \"galactic\":\n is_wcs, coord_list = check_wcs_... | from itertools import cycle
from .ds9_region_parser import RegionParser
from .wcs_converter import check_wcs as _check_wcs
_builtin_open = open
class ShapeList(list):
"""A list of `~pyregion.Shape` objects.
Parameters
----------
shape_list : list
List of `pyregion.Shape` objects
comment... |
astropy/pyregion | pyregion/core.py | get_mask | python | def get_mask(region, hdu, origin=1):
from pyregion.region_to_filter import as_region_filter
data = hdu.data
region_filter = as_region_filter(region, origin=origin)
mask = region_filter.mask(data)
return mask | Get mask.
Parameters
----------
region : `~pyregion.ShapeList`
List of `~pyregion.Shape`
hdu : `~astropy.io.fits.ImageHDU`
FITS image HDU
origin : float
TODO: document me
Returns
-------
mask : `~numpy.array`
Boolean mask
Examples
--------
>... | train | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/core.py#L310-L341 | [
"def as_region_filter(shape_list, origin=1):\n \"\"\"\n Often, the regions files implicitly assume the lower-left corner\n of the image as a coordinate (1,1). However, the python convetion\n is that the array index starts from 0. By default (origin = 1),\n coordinates of the returned mpl artists have... | from itertools import cycle
from .ds9_region_parser import RegionParser
from .wcs_converter import check_wcs as _check_wcs
_builtin_open = open
class ShapeList(list):
"""A list of `~pyregion.Shape` objects.
Parameters
----------
shape_list : list
List of `pyregion.Shape` objects
comment... |
astropy/pyregion | pyregion/core.py | ShapeList.as_imagecoord | python | def as_imagecoord(self, header):
comment_list = self._comment_list
if comment_list is None:
comment_list = cycle([None])
r = RegionParser.sky_to_image(zip(self, comment_list),
header)
shape_list, comment_list = zip(*list(r))
ret... | New shape list in image coordinates.
Parameters
----------
header : `~astropy.io.fits.Header`
FITS header
Returns
-------
shape_list : `ShapeList`
New shape list, with coordinates of the each shape
converted to the image coordinate us... | train | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/core.py#L48-L71 | [
"def sky_to_image(shape_list, header):\n \"\"\"Converts a `ShapeList` into shapes with coordinates in image coordinates\n\n Parameters\n ----------\n shape_list : `pyregion.ShapeList`\n The ShapeList to convert\n header : `~astropy.io.fits.Header`\n Specifies what WCS transformations to... | class ShapeList(list):
"""A list of `~pyregion.Shape` objects.
Parameters
----------
shape_list : list
List of `pyregion.Shape` objects
comment_list : list, None
List of comment strings for each argument
"""
def __init__(self, shape_list, comment_list=None):
if comm... |
astropy/pyregion | pyregion/core.py | ShapeList.get_mpl_patches_texts | python | def get_mpl_patches_texts(self, properties_func=None,
text_offset=5.0,
origin=1):
from .mpl_helper import as_mpl_artists
patches, txts = as_mpl_artists(self, properties_func,
text_offset,
... | Often, the regions files implicitly assume the lower-left
corner of the image as a coordinate (1,1). However, the python
convetion is that the array index starts from 0. By default
(``origin=1``), coordinates of the returned mpl artists have
coordinate shifted by (1, 1). If you do not wa... | train | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/core.py#L73-L89 | [
"def as_mpl_artists(shape_list,\n properties_func=None,\n text_offset=5.0, origin=1):\n \"\"\"\n Converts a region list to a list of patches and a list of artists.\n\n\n Optional Keywords:\n [ text_offset ] - If there is text associated with the regions, add\n some... | class ShapeList(list):
"""A list of `~pyregion.Shape` objects.
Parameters
----------
shape_list : list
List of `pyregion.Shape` objects
comment_list : list, None
List of comment strings for each argument
"""
def __init__(self, shape_list, comment_list=None):
if comm... |
astropy/pyregion | pyregion/core.py | ShapeList.get_filter | python | def get_filter(self, header=None, origin=1):
from .region_to_filter import as_region_filter
if header is None:
if not self.check_imagecoord():
raise RuntimeError("the region has non-image coordinate. header is required.")
reg_in_imagecoord = self
else:
... | Get filter.
Often, the regions files implicitly assume the lower-left
corner of the image as a coordinate (1,1). However, the python
convetion is that the array index starts from 0. By default
(``origin=1``), coordinates of the returned mpl artists have
coordinate shifted by (1, ... | train | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/core.py#L91-L124 | [
"def as_region_filter(shape_list, origin=1):\n \"\"\"\n Often, the regions files implicitly assume the lower-left corner\n of the image as a coordinate (1,1). However, the python convetion\n is that the array index starts from 0. By default (origin = 1),\n coordinates of the returned mpl artists have... | class ShapeList(list):
"""A list of `~pyregion.Shape` objects.
Parameters
----------
shape_list : list
List of `pyregion.Shape` objects
comment_list : list, None
List of comment strings for each argument
"""
def __init__(self, shape_list, comment_list=None):
if comm... |
astropy/pyregion | pyregion/core.py | ShapeList.get_mask | python | def get_mask(self, hdu=None, header=None, shape=None):
if hdu and header is None:
header = hdu.header
if hdu and shape is None:
shape = hdu.data.shape
region_filter = self.get_filter(header=header)
mask = region_filter.mask(shape)
return mask | Create a 2-d mask.
Parameters
----------
hdu : `astropy.io.fits.ImageHDU`
FITS image HDU
header : `~astropy.io.fits.Header`
FITS header
shape : tuple
Image shape
Returns
-------
mask : `numpy.array`
Boolean... | train | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/core.py#L126-L158 | [
"def get_filter(self, header=None, origin=1):\n \"\"\"Get filter.\n Often, the regions files implicitly assume the lower-left\n corner of the image as a coordinate (1,1). However, the python\n convetion is that the array index starts from 0. By default\n (``origin=1``), coordinates of the returned mp... | class ShapeList(list):
"""A list of `~pyregion.Shape` objects.
Parameters
----------
shape_list : list
List of `pyregion.Shape` objects
comment_list : list, None
List of comment strings for each argument
"""
def __init__(self, shape_list, comment_list=None):
if comm... |
astropy/pyregion | pyregion/core.py | ShapeList.write | python | def write(self, outfile):
if len(self) < 1:
print("WARNING: The region list is empty. The region file "
"'{:s}' will be empty.".format(outfile))
try:
outf = _builtin_open(outfile, 'w')
outf.close()
return
excep... | Write this shape list to a region file.
Parameters
----------
outfile : str
File name | train | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/core.py#L160-L220 | null | class ShapeList(list):
"""A list of `~pyregion.Shape` objects.
Parameters
----------
shape_list : list
List of `pyregion.Shape` objects
comment_list : list, None
List of comment strings for each argument
"""
def __init__(self, shape_list, comment_list=None):
if comm... |
astropy/pyregion | pyregion/ds9_attr_parser.py | get_attr | python | def get_attr(attr_list, global_attrs):
local_attr = [], {}
for kv in attr_list:
keyword = kv[0]
if len(kv) == 1:
local_attr[0].append(keyword)
continue
elif len(kv) == 2:
value = kv[1]
elif len(kv) > 2:
value = kv[1:]
if ke... | Parameters
----------
attr_list : list
A list of (keyword, value) tuple pairs
global_attrs : tuple(list, dict)
Global attributes which update the local attributes | train | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/ds9_attr_parser.py#L75-L109 | null | import copy
from pyparsing import (Literal, CaselessKeyword, Word, Optional, Combine,
ZeroOrMore, nums, alphas, And, Or, quotedString,
QuotedString, White)
from .region_numbers import CoordOdd, CoordEven, Distance, Angle
from .parser_helper import wcs_shape, define_shape... |
astropy/pyregion | pyregion/ds9_region_parser.py | RegionParser.sky_to_image | python | def sky_to_image(shape_list, header):
for shape, comment in shape_list:
if isinstance(shape, Shape) and \
(shape.coord_format not in image_like_coordformats):
new_coords = convert_to_imagecoord(shape, header)
l1n = copy.copy(shape)
... | Converts a `ShapeList` into shapes with coordinates in image coordinates
Parameters
----------
shape_list : `pyregion.ShapeList`
The ShapeList to convert
header : `~astropy.io.fits.Header`
Specifies what WCS transformations to use.
Yields
-------... | train | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/ds9_region_parser.py#L162-L209 | [
"def convert_to_imagecoord(shape, header):\n \"\"\"Convert the coordlist of `shape` to image coordinates\n\n Parameters\n ----------\n shape : `pyregion.parser_helper.Shape`\n The `Shape` to convert coordinates\n\n header : `~astropy.io.fits.Header`\n Specifies what WCS transformations ... | class RegionParser(RegionPusher):
def __init__(self):
RegionPusher.__init__(self)
self.shape_definition = ds9_shape_defs
regionShape = define_shape_helper(self.shape_definition)
regionShape = regionShape.setParseAction(lambda s, l, tok: Shape(tok[0], tok[1:]))
regionExpr ... |
astropy/pyregion | pyregion/wcs_helper.py | _estimate_angle | python | def _estimate_angle(angle, reg_coordinate_frame, header):
y_axis_rot = _calculate_rotation_angle(reg_coordinate_frame, header)
return angle - y_axis_rot | Transform an angle into a different frame
Parameters
----------
angle : float, int
The number of degrees, measured from the Y axis in origin's frame
reg_coordinate_frame : str
Coordinate frame in which ``angle`` is defined
header : `~astropy.io.fits.Header` instance
Header... | train | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/wcs_helper.py#L7-L27 | [
"def _calculate_rotation_angle(reg_coordinate_frame, header):\n \"\"\"Calculates the rotation angle from the region to the header's frame\n\n This attempts to be compatible with the implementation used by SAOImage\n DS9. In particular, this measures the rotation of the north axis as\n measured at the ce... | import numpy as np
from astropy.coordinates import SkyCoord
from astropy.wcs import WCS
from astropy.wcs.utils import proj_plane_pixel_scales
def _calculate_rotation_angle(reg_coordinate_frame, header):
"""Calculates the rotation angle from the region to the header's frame
This attempts to be compatible wit... |
astropy/pyregion | pyregion/wcs_helper.py | _calculate_rotation_angle | python | def _calculate_rotation_angle(reg_coordinate_frame, header):
new_wcs = WCS(header)
region_frame = SkyCoord(
'0d 0d',
frame=reg_coordinate_frame,
obstime='J2000')
region_frame = SkyCoord(
'0d 0d',
frame=reg_coordinate_frame,
obstime='J2000',
equinox=reg... | Calculates the rotation angle from the region to the header's frame
This attempts to be compatible with the implementation used by SAOImage
DS9. In particular, this measures the rotation of the north axis as
measured at the center of the image, and therefore requires a
`~astropy.io.fits.Header` object ... | train | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/wcs_helper.py#L30-L89 | null | import numpy as np
from astropy.coordinates import SkyCoord
from astropy.wcs import WCS
from astropy.wcs.utils import proj_plane_pixel_scales
def _estimate_angle(angle, reg_coordinate_frame, header):
"""Transform an angle into a different frame
Parameters
----------
angle : float, int
The num... |
astropy/pyregion | pyregion/mpl_helper.py | as_mpl_artists | python | def as_mpl_artists(shape_list,
properties_func=None,
text_offset=5.0, origin=1):
patch_list = []
artist_list = []
if properties_func is None:
properties_func = properties_func_default
# properties for continued(? multiline?) regions
saved_attrs = None... | Converts a region list to a list of patches and a list of artists.
Optional Keywords:
[ text_offset ] - If there is text associated with the regions, add
some vertical offset (in pixels) to the text so that it doesn't overlap
with the regions.
Often, the regions files implicitly assume the lower-... | train | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/mpl_helper.py#L136-L388 | [
"def rotated_polygon(xy, ox, oy, angle):\n # angle in degree\n theta = angle / 180. * pi\n\n st = sin(theta)\n ct = cos(theta)\n\n xy = np.asarray(xy, dtype=\"d\")\n x, y = xy[:, 0], xy[:, 1]\n x1 = x - ox\n y1 = y - oy\n\n x2 = ct * x1 + -st * y1\n y2 = st * x1 + ct * y1\n\n xp = x... | import copy
import numpy as np
from math import cos, sin, pi, atan2
import warnings
import matplotlib.patches as mpatches
from matplotlib.path import Path
from matplotlib.lines import Line2D
from matplotlib.transforms import Affine2D, Bbox, IdentityTransform
from matplotlib.text import Annotation
def rotated_polygon(... |
biocore-ntnu/epic | epic/run/run_epic.py | multiple_files_count_reads_in_windows | python | def multiple_files_count_reads_in_windows(bed_files, args):
# type: (Iterable[str], Namespace) -> OrderedDict[str, List[pd.DataFrame]]
bed_windows = OrderedDict() # type: OrderedDict[str, List[pd.DataFrame]]
for bed_file in bed_files:
logging.info("Binning " + bed_file)
if ".bedpe" in bed_f... | Use count_reads on multiple files and store result in dict.
Untested since does the same thing as count reads. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/run/run_epic.py#L129-L144 | [
"def count_reads_in_windows(bed_file, args):\n # type: (str, Namespace) -> List[pd.DataFrame]\n\n chromosome_size_dict = args.chromosome_sizes\n chromosomes = natsorted(list(chromosome_size_dict.keys()))\n\n parallel_count_reads = partial(_count_reads_in_windows, bed_file, args)\n\n info(\"Binning ch... | from __future__ import print_function
"""Run whole epic pipeline."""
__author__ = "Endre Bakken Stovner https://github.com/endrebak/"
__license__ = "MIT"
from os.path import dirname, join, basename
from sys import stdout, argv, stderr
from itertools import chain
from collections import OrderedDict
from subprocess im... |
biocore-ntnu/epic | epic/run/run_epic.py | _merge_files | python | def _merge_files(windows, nb_cpu):
# type: (Iterable[pd.DataFrame], int) -> pd.DataFrame
# windows is a list of chromosome dfs per file
windows = iter(windows) # can iterate over because it is odict_values
merged = next(windows)
# if there is only one file, the merging is skipped since the window... | Merge lists of chromosome bin df chromosome-wise.
windows is an OrderedDict where the keys are files, the values are lists of
dfs, one per chromosome.
Returns a list of dataframes, one per chromosome, with the collective count
per bin for all files.
TODO: is it faster to merge all in one command? | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/run/run_epic.py#L147-L169 | [
"def merge_same_files(sample1_dfs, sample2_dfs, nb_cpu):\n # type: (List[pd.DataFrame], List[pd.DataFrame], int) -> List[pd.DataFrame]\n\n # if one list is missing a chromosome, we might pair up the wrong dataframes\n # therefore creating dicts beforehand to ensure they are paired up properly\n d1, d2 =... | from __future__ import print_function
"""Run whole epic pipeline."""
__author__ = "Endre Bakken Stovner https://github.com/endrebak/"
__license__ = "MIT"
from os.path import dirname, join, basename
from sys import stdout, argv, stderr
from itertools import chain
from collections import OrderedDict
from subprocess im... |
biocore-ntnu/epic | epic/statistics/generate_cumulative_distribution.py | generate_cumulative_dist | python | def generate_cumulative_dist(island_expectations_d, total_length):
# type: (Dict[int, float], int) -> float
cumulative = [0.0] * (total_length + 1)
partial_sum = 0.0
island_expectations = []
for i in range(len(cumulative)):
if i in island_expectations_d:
island_expectations.app... | Generate cumulative distribution: a list of tuples (bins, hist). | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/statistics/generate_cumulative_distribution.py#L5-L32 | null | from epic.config.constants import E_VALUE, BIN_SIZE
from typing import Sequence, List
|
biocore-ntnu/epic | epic/statistics/compute_values_needed_for_recurrence.py | compute_enriched_threshold | python | def compute_enriched_threshold(average_window_readcount):
# type: (float) -> int
current_threshold, survival_function = 0, 1
for current_threshold in count(start=0, step=1):
survival_function -= poisson.pmf(current_threshold,
average_window_readcount)
... | Computes the minimum number of tags required in window for an island to be enriched. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/statistics/compute_values_needed_for_recurrence.py#L7-L22 | null | from itertools import count
from scipy.stats import poisson
from epic.config.constants import WINDOW_P_VALUE
def compute_gap_factor(island_enriched_threshold,
gap_intervals_allowed, poisson_distribution_parameter):
# type: (int, int, float) -> float
max_gap_score = 1.0
gap_factor... |
biocore-ntnu/epic | epic/statistics/compute_poisson.py | _factln | python | def _factln(num):
# type: (int) -> float
if num < 20:
log_factorial = log(factorial(num))
else:
log_factorial = num * log(num) - num + log(num * (1 + 4 * num * (
1 + 2 * num))) / 6.0 + log(pi) / 2
return log_factorial | Computes logfactorial regularly for tractable numbers, uses Ramanujans approximation otherwise. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/statistics/compute_poisson.py#L6-L18 | null | from math import log, factorial, pi, exp
from epic.utils.helper_functions import lru_cache
@lru_cache()
@lru_cache()
def _poisson(i, average):
# type: (int, float) -> float
"""
"""
exponent = -average + i * log(average) - _factln(i)
return exp(exponent)
|
biocore-ntnu/epic | epic/merge/merge_helpers.py | add_new_enriched_bins_matrixes | python | def add_new_enriched_bins_matrixes(region_files, dfs, bin_size):
dfs = _remove_epic_enriched(dfs)
names = ["Enriched_" + os.path.basename(r) for r in region_files]
regions = region_files_to_bins(region_files, names, bin_size)
new_dfs = OrderedDict()
assert len(regions.columns) == len(dfs)
f... | Add enriched bins based on bed files.
There is no way to find the correspondence between region file and matrix
file, but it does not matter. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/merge/merge_helpers.py#L51-L75 | [
"def _remove_epic_enriched(dfs):\n\n new_dfs = OrderedDict()\n for n, df in dfs.items():\n bad_cols = [c for c in df.columns if \"Enriched_\" in c]\n df = df.drop(bad_cols, axis=1)\n new_dfs[n] = df\n\n return new_dfs\n",
"def region_files_to_bins(region_files, names, bin_size):\n\n ... | import os
from functools import reduce
import logging
from collections import OrderedDict
try: # py3
from math import gcd
except:
from fractions import gcd
import pandas as pd
from epic.merge.compute_bed_bins import compute_bins, merge_bed_bins
def compute_bin_size(dfs):
bin_sizes = []
for df in d... |
biocore-ntnu/epic | epic/windows/count/merge_chromosome_dfs.py | merge_chromosome_dfs | python | def merge_chromosome_dfs(df_tuple):
# type: (Tuple[pd.DataFrame, pd.DataFrame]) -> pd.DataFrame
plus_df, minus_df = df_tuple
index_cols = "Chromosome Bin".split()
count_column = plus_df.columns[0]
if plus_df.empty:
return return_other(minus_df, count_column, index_cols)
if minus_df.emp... | Merges data from the two strands into strand-agnostic counts. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/windows/count/merge_chromosome_dfs.py#L5-L32 | [
"def return_other(df, count_column, index_cols):\n # type: (pd.DataFrame, Any, Sequence[Any]) -> pd.DataFrame\n\n df[[count_column, \"Bin\"]] = df[[count_column, \"Bin\"]].astype(int32)\n df = df.groupby(index_cols).sum().reset_index()\n return df[[count_column, \"Chromosome\", \"Bin\"]]\n"
] | import pandas as pd
from numpy import int32
from typing import Any, Tuple, Sequence
def return_other(df, count_column, index_cols):
# type: (pd.DataFrame, Any, Sequence[Any]) -> pd.DataFrame
df[[count_column, "Bin"]] = df[[count_column, "Bin"]].astype(int32)
df = df.groupby(index_cols).sum().reset_index... |
biocore-ntnu/epic | epic/windows/count/remove_out_of_bounds_bins.py | remove_out_of_bounds_bins | python | def remove_out_of_bounds_bins(df, chromosome_size):
# type: (pd.DataFrame, int) -> pd.DataFrame
# The dataframe is empty and contains no bins out of bounds
if "Bin" not in df:
return df
df = df.drop(df[df.Bin > chromosome_size].index)
return df.drop(df[df.Bin < 0].index) | Remove all reads that were shifted outside of the genome endpoints. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/windows/count/remove_out_of_bounds_bins.py#L3-L13 | null | import pandas as pd
def remove_bins_with_ends_out_of_bounds(df, chromosome_size,
window_size):
# type: (pd.DataFrame, int, int) -> pd.DataFrame
"""Remove all reads that were shifted outside of the genome endpoints."""
# The dataframe is empty and contains no bins ... |
biocore-ntnu/epic | epic/windows/count/remove_out_of_bounds_bins.py | remove_bins_with_ends_out_of_bounds | python | def remove_bins_with_ends_out_of_bounds(df, chromosome_size,
window_size):
# type: (pd.DataFrame, int, int) -> pd.DataFrame
# The dataframe is empty and contains no bins out of bounds
# print(df.head(2))
# print(chromosome_size)
# print(window_size)
out_... | Remove all reads that were shifted outside of the genome endpoints. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/windows/count/remove_out_of_bounds_bins.py#L16-L31 | null | import pandas as pd
def remove_out_of_bounds_bins(df, chromosome_size):
# type: (pd.DataFrame, int) -> pd.DataFrame
"""Remove all reads that were shifted outside of the genome endpoints."""
# The dataframe is empty and contains no bins out of bounds
if "Bin" not in df:
return df
df = df.d... |
biocore-ntnu/epic | epic/bigwig/create_bigwigs.py | create_log2fc_bigwigs | python | def create_log2fc_bigwigs(matrix, outdir, args):
# type: (pd.DataFrame, str, Namespace) -> None
call("mkdir -p {}".format(outdir), shell=True)
genome_size_dict = args.chromosome_sizes
outpaths = []
for bed_file in matrix[args.treatment]:
outpath = join(outdir, splitext(basename(bed_file))[... | Create bigwigs from matrix. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/bigwig/create_bigwigs.py#L33-L47 | [
"def create_log2fc_data(matrix, args):\n\n input_columns = matrix[args.control]\n input_rpkm_sum = (1e6 * input_columns / input_columns.sum()).sum(axis=1) / len(args.control)\n input_rpkm_sum[input_rpkm_sum == 0] = 1\n\n data = []\n for bed_file in matrix[args.treatment]:\n bed_column = matrix... | import logging
import numpy as np
from os.path import join, basename, splitext, dirname
from subprocess import call
from argparse import Namespace
import pandas as pd
from typing import Any, Dict, Iterable, List
import pyBigWig
from joblib import Parallel, delayed
def create_log2fc_data(matrix, args):
input_c... |
biocore-ntnu/epic | epic/statistics/add_to_island_expectations.py | add_to_island_expectations_dict | python | def add_to_island_expectations_dict(average_window_readcount,
current_max_scaled_score,
island_eligibility_threshold,
island_expectations, gap_contribution):
# type: ( float, int, float, Dict[int, float], flo... | Can probably be heavily optimized.
Time required to run can be seen from logging info. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/statistics/add_to_island_expectations.py#L12-L41 | null | WINDOW_P_VALUE = 0.20
BIN_SIZE = 0.001
E_VALUE = 1000
E_VALUE_THRESHOLD = E_VALUE * .0000001
from typing import Sequence
from epic.statistics.compute_window_score import compute_window_score
from epic.statistics.compute_poisson import _poisson
|
biocore-ntnu/epic | epic/scripts/effective_genome_size.py | effective_genome_size | python | def effective_genome_size(fasta, read_length, nb_cores, tmpdir="/tmp"):
# type: (str, int, int, str) -> None
idx = Fasta(fasta)
genome_length = sum([len(c) for c in idx])
logging.info("Temporary directory: " + tmpdir)
logging.info("File analyzed: " + fasta)
logging.info("Genome length: " + st... | Compute effective genome size for genome. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/scripts/effective_genome_size.py#L15-L68 | null | from __future__ import print_function, division
import sys
import atexit
from subprocess import call, check_output
import os
from os.path import basename
import logging
from pyfaidx import Fasta
from epic.config import logging_settings
|
biocore-ntnu/epic | epic/matrixes/matrixes.py | create_matrixes | python | def create_matrixes(chip, input, df, args):
# type: (Iterable[pd.DataFrame], Iterable[pd.DataFrame], pd.DataFrame, Namespace) -> List[pd.DataFrame]
"Creates matrixes which can be written to file as is (matrix) or as bedGraph."
genome = args.chromosome_sizes
chip = put_dfs_in_chromosome_dict(chip)
... | Creates matrixes which can be written to file as is (matrix) or as bedGraph. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/matrixes/matrixes.py#L148-L168 | [
"def put_dfs_in_chromosome_dict(dfs):\n # type: (Iterable[pd.DataFrame]) -> Dict[str, pd.DataFrame]\n\n chromosome_dict = {} # type: Dict[str, pd.DataFrame]\n for df in dfs:\n\n if df.empty:\n continue\n\n chromosome = df.head(1).Chromosome.values[0]\n chromosome_dict... | import sys
import logging
from os.path import dirname, join, basename
from subprocess import call
from itertools import chain
from typing import Iterable, Sequence, Tuple
from argparse import Namespace
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from natsort import natsorted
from epi... |
biocore-ntnu/epic | epic/matrixes/matrixes.py | get_island_bins | python | def get_island_bins(df, window_size, genome, args):
# type: (pd.DataFrame, int, str, Namespace) -> Dict[str, Set[int]]
# need these chromos because the df might not have islands in all chromos
chromosomes = natsorted(list(args.chromosome_sizes))
chromosome_island_bins = {} # type: Dict[str, Set[int]]
... | Finds the enriched bins in a df. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/matrixes/matrixes.py#L184-L205 | null | import sys
import logging
from os.path import dirname, join, basename
from subprocess import call
from itertools import chain
from typing import Iterable, Sequence, Tuple
from argparse import Namespace
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from natsort import natsorted
from epi... |
biocore-ntnu/epic | epic/config/genomes.py | create_genome_size_dict | python | def create_genome_size_dict(genome):
# type: (str) -> Dict[str,int]
size_file = get_genome_size_file(genome)
size_lines = open(size_file).readlines()
size_dict = {}
for line in size_lines:
genome, length = line.split()
size_dict[genome] = int(length)
return size_dict | Creates genome size dict from string containing data. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/config/genomes.py#L29-L41 | [
"def get_genome_size_file(genome):\n # type: (str) -> str\n\n genome_names = pkg_resources.resource_listdir(\"epic\", \"scripts/chromsizes\")\n name_dict = {n.lower().replace(\".chromsizes\", \"\"): n for n in genome_names}\n\n # No try/except here, because get_egs would already have failed if genome\n ... | from natsort import natsorted
from collections import OrderedDict
import pkg_resources
import logging
from typing import Dict
from epic.config import logging_settings
from epic.utils.find_readlength import (find_readlength,
get_closest_readlength)
__author__ = "Endre Bakken Sto... |
biocore-ntnu/epic | epic/statistics/compute_score_threshold.py | compute_score_threshold | python | def compute_score_threshold(average_window_readcount,
island_enriched_threshold,
gap_contribution, boundary_contribution,
genome_length_in_bins):
# type: (float, int, float, float, float) -> float
required_p_value = poisson.pmf... | What does island_expectations do? | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/statistics/compute_score_threshold.py#L10-L67 | [
"def add_to_island_expectations_dict(average_window_readcount,\n current_max_scaled_score,\n island_eligibility_threshold,\n island_expectations, gap_contribution):\n # type: ( float, int, float, Dict[int, fl... | import logging
from scipy.stats import poisson
from numpy import log
from epic.config.constants import BIN_SIZE, E_VALUE_THRESHOLD
from epic.statistics.generate_cumulative_distribution import generate_cumulative_dist
from epic.statistics.add_to_island_expectations import add_to_island_expectations_dict
|
biocore-ntnu/epic | epic/utils/find_readlength.py | find_readlength | python | def find_readlength(args):
# type: (Namespace) -> int
try:
bed_file = args.treatment[0]
except AttributeError:
bed_file = args.infiles[0]
filereader = "cat "
if bed_file.endswith(".gz") and search("linux", platform, IGNORECASE):
filereader = "zcat "
elif bed_file.endswi... | Estimate length of reads based on 10000 first. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/utils/find_readlength.py#L16-L55 | null | import logging
from sys import platform
from re import search, IGNORECASE
from io import BytesIO
from subprocess import check_output
from argparse import Namespace
import pandas as pd
from epic.config import logging_settings
__author__ = "Endre Bakken Stovner https://github.com/endrebak/"
__license__ = "MIT"
def ... |
biocore-ntnu/epic | epic/utils/find_readlength.py | get_closest_readlength | python | def get_closest_readlength(estimated_readlength):
# type: (int) -> int
readlengths = [36, 50, 75, 100]
differences = [abs(r - estimated_readlength) for r in readlengths]
min_difference = min(differences)
index_of_min_difference = [i
for i, d in enumerate(differences)
... | Find the predefined readlength closest to the estimated readlength.
In the case of a tie, choose the shortest readlength. | train | https://github.com/biocore-ntnu/epic/blob/ed0024939ec6182a0a39d59d845ff14a4889a6ef/epic/utils/find_readlength.py#L58-L71 | null | import logging
from sys import platform
from re import search, IGNORECASE
from io import BytesIO
from subprocess import check_output
from argparse import Namespace
import pandas as pd
from epic.config import logging_settings
__author__ = "Endre Bakken Stovner https://github.com/endrebak/"
__license__ = "MIT"
def f... |
hthiery/python-fritzhome | pyfritzhome/cli.py | list_all | python | def list_all(fritz, args):
devices = fritz.get_devices()
for device in devices:
print('#' * 30)
print('name=%s' % device.name)
print(' ain=%s' % device.ain)
print(' id=%s' % device.identifier)
print(' productname=%s' % device.productname)
print(' manufacturer... | Command that prints all device information. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/cli.py#L18-L61 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import logging
import argparse
try:
from version import __version__
except ImportError:
__version__ = 'dev'
from pyfritzhome import Fritzhome
_LOGGER = logging.getLogger(__name__)
def device_name(fritz, args):
"""Comm... |
hthiery/python-fritzhome | pyfritzhome/cli.py | device_statistics | python | def device_statistics(fritz, args):
stats = fritz.get_device_statistics(args.ain)
print(stats) | Command that prints the device statistics. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/cli.py#L74-L77 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import logging
import argparse
try:
from version import __version__
except ImportError:
__version__ = 'dev'
from pyfritzhome import Fritzhome
_LOGGER = logging.getLogger(__name__)
def list_all(fritz, args):
"""Command ... |
hthiery/python-fritzhome | pyfritzhome/cli.py | main | python | def main(args=None):
parser = argparse.ArgumentParser(
description='Fritz!Box Smarthome CLI tool.')
parser.add_argument('-v', action='store_true', dest='verbose',
help='be more verbose')
parser.add_argument('-f', '--fritzbox', type=str, dest='host',
he... | The main function. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/cli.py#L100-L190 | [
"def login(self):\n \"\"\"Login and get a valid session ID.\"\"\"\n try:\n (sid, challenge) = self._login_request()\n if sid == '0000000000000000':\n secret = self._create_login_secret(challenge, self._password)\n (sid2, challenge) = self._login_request(username=self._user,... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import logging
import argparse
try:
from version import __version__
except ImportError:
__version__ = 'dev'
from pyfritzhome import Fritzhome
_LOGGER = logging.getLogger(__name__)
def list_all(fritz, args):
"""Command ... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | get_text | python | def get_text(nodelist):
value = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
value.append(node.data)
return ''.join(value) | Get the value from a text node. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L14-L20 | null | # -*- coding: utf-8 -*-
from __future__ import print_function
import hashlib
import logging
import xml.dom.minidom
from requests import Session
from .errors import (InvalidError, LoginError)
_LOGGER = logging.getLogger(__name__)
def get_node_value(node, name):
"""Get the value from a node."""
return get_t... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | Fritzhome._request | python | def _request(self, url, params=None, timeout=10):
rsp = self._session.get(url, params=params, timeout=timeout)
rsp.raise_for_status()
return rsp.text.strip() | Send a request with parameters. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L47-L51 | null | class Fritzhome(object):
"""Fritzhome object to communicate with the device."""
_sid = None
_session = None
def __init__(self, host, user, password):
self._host = host
self._user = user
self._password = password
self._session = Session()
def _login_request(self, u... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | Fritzhome._login_request | python | def _login_request(self, username=None, secret=None):
url = 'http://' + self._host + '/login_sid.lua'
params = {}
if username:
params['username'] = username
if secret:
params['response'] = secret
plain = self._request(url, params)
dom = xml.dom.mi... | Send a login request with paramerters. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L53-L68 | [
"def get_text(nodelist):\n \"\"\"Get the value from a text node.\"\"\"\n value = []\n for node in nodelist:\n if node.nodeType == node.TEXT_NODE:\n value.append(node.data)\n return ''.join(value)\n",
"def _request(self, url, params=None, timeout=10):\n \"\"\"Send a request with pa... | class Fritzhome(object):
"""Fritzhome object to communicate with the device."""
_sid = None
_session = None
def __init__(self, host, user, password):
self._host = host
self._user = user
self._password = password
self._session = Session()
def _request(self, url, par... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | Fritzhome._logout_request | python | def _logout_request(self):
_LOGGER.debug('logout')
url = 'http://' + self._host + '/login_sid.lua'
params = {
'security:command/logout': '1',
'sid': self._sid
}
self._request(url, params) | Send a logout request. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L70-L79 | [
"def _request(self, url, params=None, timeout=10):\n \"\"\"Send a request with parameters.\"\"\"\n rsp = self._session.get(url, params=params, timeout=timeout)\n rsp.raise_for_status()\n return rsp.text.strip()\n"
] | class Fritzhome(object):
"""Fritzhome object to communicate with the device."""
_sid = None
_session = None
def __init__(self, host, user, password):
self._host = host
self._user = user
self._password = password
self._session = Session()
def _request(self, url, par... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | Fritzhome._create_login_secret | python | def _create_login_secret(challenge, password):
to_hash = (challenge + '-' + password).encode('UTF-16LE')
hashed = hashlib.md5(to_hash).hexdigest()
return '{0}-{1}'.format(challenge, hashed) | Create a login secret. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L82-L86 | null | class Fritzhome(object):
"""Fritzhome object to communicate with the device."""
_sid = None
_session = None
def __init__(self, host, user, password):
self._host = host
self._user = user
self._password = password
self._session = Session()
def _request(self, url, par... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | Fritzhome._aha_request | python | def _aha_request(self, cmd, ain=None, param=None, rf=str):
url = 'http://' + self._host + '/webservices/homeautoswitch.lua'
params = {
'switchcmd': cmd,
'sid': self._sid
}
if param:
params['param'] = param
if ain:
params['ain'] = ai... | Send an AHA request. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L88-L106 | [
"def _request(self, url, params=None, timeout=10):\n \"\"\"Send a request with parameters.\"\"\"\n rsp = self._session.get(url, params=params, timeout=timeout)\n rsp.raise_for_status()\n return rsp.text.strip()\n"
] | class Fritzhome(object):
"""Fritzhome object to communicate with the device."""
_sid = None
_session = None
def __init__(self, host, user, password):
self._host = host
self._user = user
self._password = password
self._session = Session()
def _request(self, url, par... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | Fritzhome.login | python | def login(self):
try:
(sid, challenge) = self._login_request()
if sid == '0000000000000000':
secret = self._create_login_secret(challenge, self._password)
(sid2, challenge) = self._login_request(username=self._user,
... | Login and get a valid session ID. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L108-L121 | [
"def _login_request(self, username=None, secret=None):\n \"\"\"Send a login request with paramerters.\"\"\"\n url = 'http://' + self._host + '/login_sid.lua'\n params = {}\n if username:\n params['username'] = username\n if secret:\n params['response'] = secret\n\n plain = self._requ... | class Fritzhome(object):
"""Fritzhome object to communicate with the device."""
_sid = None
_session = None
def __init__(self, host, user, password):
self._host = host
self._user = user
self._password = password
self._session = Session()
def _request(self, url, par... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | Fritzhome.get_device_elements | python | def get_device_elements(self):
plain = self._aha_request('getdevicelistinfos')
dom = xml.dom.minidom.parseString(plain)
_LOGGER.debug(dom)
return dom.getElementsByTagName("device") | Get the DOM elements for the device list. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L128-L133 | [
"def _aha_request(self, cmd, ain=None, param=None, rf=str):\n \"\"\"Send an AHA request.\"\"\"\n url = 'http://' + self._host + '/webservices/homeautoswitch.lua'\n params = {\n 'switchcmd': cmd,\n 'sid': self._sid\n }\n if param:\n params['param'] = param\n if ain:\n pa... | class Fritzhome(object):
"""Fritzhome object to communicate with the device."""
_sid = None
_session = None
def __init__(self, host, user, password):
self._host = host
self._user = user
self._password = password
self._session = Session()
def _request(self, url, par... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | Fritzhome.get_device_element | python | def get_device_element(self, ain):
elements = self.get_device_elements()
for element in elements:
if element.getAttribute('identifier') == ain:
return element
return None | Get the DOM element for the specified device. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L135-L141 | [
"def get_device_elements(self):\n \"\"\"Get the DOM elements for the device list.\"\"\"\n plain = self._aha_request('getdevicelistinfos')\n dom = xml.dom.minidom.parseString(plain)\n _LOGGER.debug(dom)\n return dom.getElementsByTagName(\"device\")\n"
] | class Fritzhome(object):
"""Fritzhome object to communicate with the device."""
_sid = None
_session = None
def __init__(self, host, user, password):
self._host = host
self._user = user
self._password = password
self._session = Session()
def _request(self, url, par... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | Fritzhome.get_devices | python | def get_devices(self):
devices = []
for element in self.get_device_elements():
device = FritzhomeDevice(self, node=element)
devices.append(device)
return devices | Get the list of all known devices. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L143-L149 | [
"def get_device_elements(self):\n \"\"\"Get the DOM elements for the device list.\"\"\"\n plain = self._aha_request('getdevicelistinfos')\n dom = xml.dom.minidom.parseString(plain)\n _LOGGER.debug(dom)\n return dom.getElementsByTagName(\"device\")\n"
] | class Fritzhome(object):
"""Fritzhome object to communicate with the device."""
_sid = None
_session = None
def __init__(self, host, user, password):
self._host = host
self._user = user
self._password = password
self._session = Session()
def _request(self, url, par... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | Fritzhome.get_device_by_ain | python | def get_device_by_ain(self, ain):
devices = self.get_devices()
for device in devices:
if device.ain == ain:
return device | Returns a device specified by the AIN. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L151-L156 | [
"def get_devices(self):\n \"\"\"Get the list of all known devices.\"\"\"\n devices = []\n for element in self.get_device_elements():\n device = FritzhomeDevice(self, node=element)\n devices.append(device)\n return devices\n"
] | class Fritzhome(object):
"""Fritzhome object to communicate with the device."""
_sid = None
_session = None
def __init__(self, host, user, password):
self._host = host
self._user = user
self._password = password
self._session = Session()
def _request(self, url, par... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | Fritzhome.set_target_temperature | python | def set_target_temperature(self, ain, temperature):
param = 16 + ((float(temperature) - 8) * 2)
if param < min(range(16, 56)):
param = 253
elif param > max(range(16, 56)):
param = 254
self._aha_request('sethkrtsoll', ain=ain, param=int(param)) | Set the thermostate target temperature. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L202-L210 | [
"def _aha_request(self, cmd, ain=None, param=None, rf=str):\n \"\"\"Send an AHA request.\"\"\"\n url = 'http://' + self._host + '/webservices/homeautoswitch.lua'\n params = {\n 'switchcmd': cmd,\n 'sid': self._sid\n }\n if param:\n params['param'] = param\n if ain:\n pa... | class Fritzhome(object):
"""Fritzhome object to communicate with the device."""
_sid = None
_session = None
def __init__(self, host, user, password):
self._host = host
self._user = user
self._password = password
self._session = Session()
def _request(self, url, par... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | FritzhomeDevice.update | python | def update(self):
node = self._fritz.get_device_element(self.ain)
self._update_from_node(node) | Update the device values. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L409-L412 | [
"def _update_from_node(self, node):\n _LOGGER.debug(node.toprettyxml())\n self.ain = node.getAttribute(\"identifier\")\n self.identifier = node.getAttribute(\"id\")\n self._functionsbitmask = int(node.getAttribute(\"functionbitmask\"))\n self.fw_version = node.getAttribute(\"fwversion\")\n self.ma... | class FritzhomeDevice(object):
"""The Fritzhome Device class."""
ALARM_MASK = 0x010
UNKNOWN_MASK = 0x020
THERMOSTAT_MASK = 0x040
POWER_METER_MASK = 0x080
TEMPERATURE_MASK = 0x100
SWITCH_MASK = 0x200
DECT_REPEATER_MASK = 0x400
MICROPHONE_UNIT = 0x800
HANFUN_UNIT = 0x2000
ain ... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | FritzhomeDevice.get_hkr_state | python | def get_hkr_state(self):
self.update()
try:
return {
126.5: 'off',
127.0: 'on',
self.eco_temperature: 'eco',
self.comfort_temperature: 'comfort'
}[self.target_temperature]
except KeyError:
return ... | Get the thermostate state. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L492-L503 | [
"def update(self):\n \"\"\"Update the device values.\"\"\"\n node = self._fritz.get_device_element(self.ain)\n self._update_from_node(node)\n"
] | class FritzhomeDevice(object):
"""The Fritzhome Device class."""
ALARM_MASK = 0x010
UNKNOWN_MASK = 0x020
THERMOSTAT_MASK = 0x040
POWER_METER_MASK = 0x080
TEMPERATURE_MASK = 0x100
SWITCH_MASK = 0x200
DECT_REPEATER_MASK = 0x400
MICROPHONE_UNIT = 0x800
HANFUN_UNIT = 0x2000
ain ... |
hthiery/python-fritzhome | pyfritzhome/fritzhome.py | FritzhomeDevice.set_hkr_state | python | def set_hkr_state(self, state):
try:
value = {
'off': 0,
'on': 100,
'eco': self.eco_temperature,
'comfort': self.comfort_temperature
}[state]
except KeyError:
return
self.set_target_temperature(v... | Set the state of the thermostat.
Possible values for state are: 'on', 'off', 'comfort', 'eco'. | train | https://github.com/hthiery/python-fritzhome/blob/c74bd178d08a305028f316f7da35202da3526f61/pyfritzhome/fritzhome.py#L505-L520 | [
"def set_target_temperature(self, temperature):\n \"\"\"Set the thermostate target temperature.\"\"\"\n return self._fritz.set_target_temperature(self.ain, temperature)\n"
] | class FritzhomeDevice(object):
"""The Fritzhome Device class."""
ALARM_MASK = 0x010
UNKNOWN_MASK = 0x020
THERMOSTAT_MASK = 0x040
POWER_METER_MASK = 0x080
TEMPERATURE_MASK = 0x100
SWITCH_MASK = 0x200
DECT_REPEATER_MASK = 0x400
MICROPHONE_UNIT = 0x800
HANFUN_UNIT = 0x2000
ain ... |
ixc/python-edtf | edtf/fields.py | EDTFField.pre_save | python | def pre_save(self, instance, add):
if not self.natural_text_field or self.attname not in instance.__dict__:
return
edtf = getattr(instance, self.attname)
# Update EDTF field based on latest natural text value, if any
natural_text = getattr(instance, self.natural_text_field)... | Updates the edtf value from the value of the display_field.
If there's a valid edtf, then set the date values. | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/fields.py#L87-L138 | [
"def parse_edtf(str, parseAll=True, fail_silently=False):\n try:\n if not str:\n raise ParseException(\"You must supply some input text\")\n p = edtfParser.parseString(str.strip(), parseAll)\n if p:\n return p[0]\n except ParseException as e:\n if fail_silentl... | class EDTFField(models.CharField):
def __init__(
self,
verbose_name=None, name=None,
natural_text_field=None,
lower_strict_field=None,
upper_strict_field=None,
lower_fuzzy_field=None,
upper_fuzzy_field=None,
**kwargs
):
kwargs['max_length'... |
ixc/python-edtf | edtf/parser/parser_classes.py | apply_delta | python | def apply_delta(op, time_struct, delta):
if not delta:
return time_struct # No work to do
try:
dt_result = op(datetime(*time_struct[:6]), delta)
return dt_to_struct_time(dt_result)
except (OverflowError, ValueError):
# Year is not within supported 1 to 9999 AD range
... | Apply a `relativedelta` to a `struct_time` data structure.
`op` is an operator function, probably always `add` or `sub`tract to
correspond to `a_date + a_delta` and `a_date - a_delta`.
This function is required because we cannot use standard `datetime` module
objects for conversion when the date/time ... | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/parser/parser_classes.py#L47-L83 | [
"def dt_to_struct_time(dt):\n \"\"\"\n Convert a `datetime.date` or `datetime.datetime` to a `struct_time`\n representation *with zero values* for data fields that we cannot always\n rely on for ancient or far-future dates: tm_wday, tm_yday, tm_isdst\n\n NOTE: If it wasn't for the requirement that th... | import calendar
import re
from time import struct_time
from datetime import date, datetime
from operator import add, sub
from dateutil.relativedelta import relativedelta
from edtf import appsettings
from edtf.convert import dt_to_struct_time, trim_struct_time, \
TIME_EMPTY_TIME, TIME_EMPTY_EXTRAS
EARLIEST = 'ear... |
ixc/python-edtf | edtf/parser/parser_classes.py | Date._strict_date | python | def _strict_date(self, lean):
return struct_time(
(
self._precise_year(lean),
self._precise_month(lean),
self._precise_day(lean),
) + tuple(TIME_EMPTY_TIME) + tuple(TIME_EMPTY_EXTRAS)
) | Return a `time.struct_time` representation of the date. | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/parser/parser_classes.py#L290-L300 | null | class Date(EDTFObject):
def set_year(self, y):
if y is None:
raise AttributeError("Year must not be None")
self._year = y
def get_year(self):
return self._year
year = property(get_year, set_year)
def set_month(self, m):
self._month = m
if m == None:... |
ixc/python-edtf | edtf/parser/parser_classes.py | PartialUncertainOrApproximate._get_fuzzy_padding | python | def _get_fuzzy_padding(self, lean):
result = relativedelta(0)
if self.year_ua:
result += appsettings.PADDING_YEAR_PRECISION * self.year_ua._get_multiplier()
if self.month_ua:
result += appsettings.PADDING_MONTH_PRECISION * self.month_ua._get_multiplier()
if self.... | This is not a perfect interpretation as fuzziness is introduced for
redundant uncertainly modifiers e.g. (2006~)~ will get two sets of
fuzziness. | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/parser/parser_classes.py#L582-L620 | null | class PartialUncertainOrApproximate(Date):
def set_year(self, y): # Year can be None.
self._year = y
year = property(Date.get_year, set_year)
def __init__(
self, year=None, month=None, day=None,
year_ua=False, month_ua = False, day_ua = False,
year_month_ua = False, month_d... |
ixc/python-edtf | edtf/jdutil.py | date_to_jd | python | def date_to_jd(year,month,day):
if month == 1 or month == 2:
yearp = year - 1
monthp = month + 12
else:
yearp = year
monthp = month
# this checks where we are in relation to October 15, 1582, the beginning
# of the Gregorian calendar.
if ((year < 1582) or
(ye... | Convert a date to Julian Day.
Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet',
4th ed., Duffet-Smith and Zwart, 2011.
Parameters
----------
year : int
Year as integer. Years preceding 1 A.D. should be 0 or negative.
The year before 1 A.D. is 0, 10 B.C.... | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/jdutil.py#L57-L117 | null | # Source: https://gist.github.com/jiffyclub/1294443
"""
Functions for converting dates to/from JD and MJD. Assumes dates are historical
dates, including the transition from the Julian calendar to the Gregorian
calendar in 1582. No support for proleptic Gregorian/Julian calendars.
:Author: Matt Davis
:Website: http://g... |
ixc/python-edtf | edtf/jdutil.py | jd_to_date | python | def jd_to_date(jd):
jd = jd + 0.5
F, I = math.modf(jd)
I = int(I)
A = math.trunc((I - 1867216.25)/36524.25)
if I > 2299160:
B = I + 1 + A - math.trunc(A / 4.)
else:
B = I
C = B + 1524
D = math.trunc((C - 122.1) / 365.25)
E = math.trunc(365.25 * D)
G = math.... | Convert Julian Day to date.
Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet',
4th ed., Duffet-Smith and Zwart, 2011.
Parameters
----------
jd : float
Julian Day
Returns
-------
year : int
Year as integer. Years preceding 1 A.D. should be 0 ... | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/jdutil.py#L120-L184 | null | # Source: https://gist.github.com/jiffyclub/1294443
"""
Functions for converting dates to/from JD and MJD. Assumes dates are historical
dates, including the transition from the Julian calendar to the Gregorian
calendar in 1582. No support for proleptic Gregorian/Julian calendars.
:Author: Matt Davis
:Website: http://g... |
ixc/python-edtf | edtf/jdutil.py | hmsm_to_days | python | def hmsm_to_days(hour=0,min=0,sec=0,micro=0):
days = sec + (micro / 1.e6)
days = min + (days / 60.)
days = hour + (days / 60.)
return days / 24. | Convert hours, minutes, seconds, and microseconds to fractional days.
Parameters
----------
hour : int, optional
Hour number. Defaults to 0.
min : int, optional
Minute number. Defaults to 0.
sec : int, optional
Second number. Defaults to 0.
micro : int, optional
... | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/jdutil.py#L187-L222 | null | # Source: https://gist.github.com/jiffyclub/1294443
"""
Functions for converting dates to/from JD and MJD. Assumes dates are historical
dates, including the transition from the Julian calendar to the Gregorian
calendar in 1582. No support for proleptic Gregorian/Julian calendars.
:Author: Matt Davis
:Website: http://g... |
ixc/python-edtf | edtf/jdutil.py | days_to_hmsm | python | def days_to_hmsm(days):
hours = days * 24.
hours, hour = math.modf(hours)
mins = hours * 60.
mins, min = math.modf(mins)
secs = mins * 60.
secs, sec = math.modf(secs)
micro = round(secs * 1.e6)
return int(hour), int(min), int(sec), int(micro) | Convert fractional days to hours, minutes, seconds, and microseconds.
Precision beyond microseconds is rounded to the nearest microsecond.
Parameters
----------
days : float
A fractional number of days. Must be less than 1.
Returns
-------
hour : int
Hour number.
min :... | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/jdutil.py#L225-L271 | null | # Source: https://gist.github.com/jiffyclub/1294443
"""
Functions for converting dates to/from JD and MJD. Assumes dates are historical
dates, including the transition from the Julian calendar to the Gregorian
calendar in 1582. No support for proleptic Gregorian/Julian calendars.
:Author: Matt Davis
:Website: http://g... |
ixc/python-edtf | edtf/jdutil.py | datetime_to_jd | python | def datetime_to_jd(date):
days = date.day + hmsm_to_days(date.hour,date.minute,date.second,date.microsecond)
return date_to_jd(date.year,date.month,days) | Convert a `datetime.datetime` object to Julian Day.
Parameters
----------
date : `datetime.datetime` instance
Returns
-------
jd : float
Julian day.
Examples
--------
>>> d = datetime.datetime(1985,2,17,6)
>>> d
datetime.datetime(1985, 2, 17, 6, 0)
>>> jdutil... | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/jdutil.py#L274-L298 | [
"def hmsm_to_days(hour=0,min=0,sec=0,micro=0):\n \"\"\"\n Convert hours, minutes, seconds, and microseconds to fractional days.\n\n Parameters\n ----------\n hour : int, optional\n Hour number. Defaults to 0.\n\n min : int, optional\n Minute number. Defaults to 0.\n\n sec : int, o... | # Source: https://gist.github.com/jiffyclub/1294443
"""
Functions for converting dates to/from JD and MJD. Assumes dates are historical
dates, including the transition from the Julian calendar to the Gregorian
calendar in 1582. No support for proleptic Gregorian/Julian calendars.
:Author: Matt Davis
:Website: http://g... |
ixc/python-edtf | edtf/jdutil.py | jd_to_datetime | python | def jd_to_datetime(jd):
year, month, day = jd_to_date(jd)
frac_days,day = math.modf(day)
day = int(day)
hour,min,sec,micro = days_to_hmsm(frac_days)
return datetime(year,month,day,hour,min,sec,micro) | Convert a Julian Day to an `jdutil.datetime` object.
Parameters
----------
jd : float
Julian day.
Returns
-------
dt : `jdutil.datetime` object
`jdutil.datetime` equivalent of Julian day.
Examples
--------
>>> jd_to_datetime(2446113.75)
datetime(1985, 2, 17, 6,... | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/jdutil.py#L301-L328 | [
"def jd_to_date(jd):\n \"\"\"\n Convert Julian Day to date.\n\n Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet', \n 4th ed., Duffet-Smith and Zwart, 2011.\n\n Parameters\n ----------\n jd : float\n Julian Day\n\n Returns\n -------\n year : int\n ... | # Source: https://gist.github.com/jiffyclub/1294443
"""
Functions for converting dates to/from JD and MJD. Assumes dates are historical
dates, including the transition from the Julian calendar to the Gregorian
calendar in 1582. No support for proleptic Gregorian/Julian calendars.
:Author: Matt Davis
:Website: http://g... |
ixc/python-edtf | edtf/jdutil.py | timedelta_to_days | python | def timedelta_to_days(td):
seconds_in_day = 24. * 3600.
days = td.days + (td.seconds + (td.microseconds * 10.e6)) / seconds_in_day
return days | Convert a `datetime.timedelta` object to a total number of days.
Parameters
----------
td : `datetime.timedelta` instance
Returns
-------
days : float
Total number of days in the `datetime.timedelta` object.
Examples
--------
>>> td = datetime.timedelta(4.5)
>>> td
... | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/jdutil.py#L331-L357 | null | # Source: https://gist.github.com/jiffyclub/1294443
"""
Functions for converting dates to/from JD and MJD. Assumes dates are historical
dates, including the transition from the Julian calendar to the Gregorian
calendar in 1582. No support for proleptic Gregorian/Julian calendars.
:Author: Matt Davis
:Website: http://g... |
ixc/python-edtf | edtf/convert.py | dt_to_struct_time | python | def dt_to_struct_time(dt):
if isinstance(dt, datetime):
return struct_time(
[dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second] +
TIME_EMPTY_EXTRAS
)
elif isinstance(dt, date):
return struct_time(
[dt.year, dt.month, dt.day] + TIME_EMPTY_TIME + ... | Convert a `datetime.date` or `datetime.datetime` to a `struct_time`
representation *with zero values* for data fields that we cannot always
rely on for ancient or far-future dates: tm_wday, tm_yday, tm_isdst
NOTE: If it wasn't for the requirement that the extra fields are unset
we could use the `timetu... | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/convert.py#L11-L31 | null | from time import struct_time
from datetime import date, datetime
from edtf import jdutil
TIME_EMPTY_TIME = [0, 0, 0] # tm_hour, tm_min, tm_sec
TIME_EMPTY_EXTRAS = [0, 0, -1] # tm_wday, tm_yday, tm_isdst
def struct_time_to_date(st):
"""
Return a `datetime.date` representing the provided `struct_time.
... |
ixc/python-edtf | edtf/convert.py | trim_struct_time | python | def trim_struct_time(st, strip_time=False):
if strip_time:
return struct_time(list(st[:3]) + TIME_EMPTY_TIME + TIME_EMPTY_EXTRAS)
else:
return struct_time(list(st[:6]) + TIME_EMPTY_EXTRAS) | Return a `struct_time` based on the one provided but with the extra fields
`tm_wday`, `tm_yday`, and `tm_isdst` reset to default values.
If `strip_time` is set to true the time value are also set to zero:
`tm_hour`, `tm_min`, and `tm_sec`. | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/convert.py#L52-L63 | null | from time import struct_time
from datetime import date, datetime
from edtf import jdutil
TIME_EMPTY_TIME = [0, 0, 0] # tm_hour, tm_min, tm_sec
TIME_EMPTY_EXTRAS = [0, 0, -1] # tm_wday, tm_yday, tm_isdst
def dt_to_struct_time(dt):
"""
Convert a `datetime.date` or `datetime.datetime` to a `struct_time`
... |
ixc/python-edtf | edtf/convert.py | struct_time_to_jd | python | def struct_time_to_jd(st):
year, month, day = st[:3]
hours, minutes, seconds = st[3:6]
# Convert time of day to fraction of day
day += jdutil.hmsm_to_days(hours, minutes, seconds)
return jdutil.date_to_jd(year, month, day) | Return a float number representing the Julian Date for the given
`struct_time`.
NOTE: extra fields `tm_wday`, `tm_yday`, and `tm_isdst` are ignored. | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/convert.py#L66-L79 | [
"def hmsm_to_days(hour=0,min=0,sec=0,micro=0):\n \"\"\"\n Convert hours, minutes, seconds, and microseconds to fractional days.\n\n Parameters\n ----------\n hour : int, optional\n Hour number. Defaults to 0.\n\n min : int, optional\n Minute number. Defaults to 0.\n\n sec : int, o... | from time import struct_time
from datetime import date, datetime
from edtf import jdutil
TIME_EMPTY_TIME = [0, 0, 0] # tm_hour, tm_min, tm_sec
TIME_EMPTY_EXTRAS = [0, 0, -1] # tm_wday, tm_yday, tm_isdst
def dt_to_struct_time(dt):
"""
Convert a `datetime.date` or `datetime.datetime` to a `struct_time`
... |
ixc/python-edtf | edtf/convert.py | jd_to_struct_time | python | def jd_to_struct_time(jd):
year, month, day = jdutil.jd_to_date(jd)
# Convert time of day from fraction of day
day_fraction = day - int(day)
hour, minute, second, ms = jdutil.days_to_hmsm(day_fraction)
day = int(day)
# This conversion can return negative values for items we do not want to be
... | Return a `struct_time` converted from a Julian Date float number.
WARNING: Conversion to then from Julian Date value to `struct_time` can be
inaccurate and lose or gain time, especially for BC (negative) years.
NOTE: extra fields `tm_wday`, `tm_yday`, and `tm_isdst` are set to default
values, not real... | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/convert.py#L82-L106 | [
"def jd_to_date(jd):\n \"\"\"\n Convert Julian Day to date.\n\n Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet', \n 4th ed., Duffet-Smith and Zwart, 2011.\n\n Parameters\n ----------\n jd : float\n Julian Day\n\n Returns\n -------\n year : int\n ... | from time import struct_time
from datetime import date, datetime
from edtf import jdutil
TIME_EMPTY_TIME = [0, 0, 0] # tm_hour, tm_min, tm_sec
TIME_EMPTY_EXTRAS = [0, 0, -1] # tm_wday, tm_yday, tm_isdst
def dt_to_struct_time(dt):
"""
Convert a `datetime.date` or `datetime.datetime` to a `struct_time`
... |
ixc/python-edtf | edtf/convert.py | _roll_negative_time_fields | python | def _roll_negative_time_fields(year, month, day, hour, minute, second):
if second < 0:
minute += int(second / 60.0) # Adjust by whole minute in secs
minute -= 1 # Subtract 1 for negative second
second %= 60 # Convert negative second to positive remainder
if minute < 0:
hour +=... | Fix date/time fields which have nonsense negative values for any field
except for year by rolling the overall date/time value backwards, treating
negative values as relative offsets of the next higher unit.
For example minute=5, second=-63 becomes minute=3, second=57 (5 minutes
less 63 seconds)
Th... | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/convert.py#L109-L145 | null | from time import struct_time
from datetime import date, datetime
from edtf import jdutil
TIME_EMPTY_TIME = [0, 0, 0] # tm_hour, tm_min, tm_sec
TIME_EMPTY_EXTRAS = [0, 0, -1] # tm_wday, tm_yday, tm_isdst
def dt_to_struct_time(dt):
"""
Convert a `datetime.date` or `datetime.datetime` to a `struct_time`
... |
ixc/python-edtf | edtf/natlang/en.py | text_to_edtf | python | def text_to_edtf(text):
if not text:
return
t = text.lower()
# try parsing the whole thing
result = text_to_edtf_date(t)
if not result:
# split by list delims and move fwd with the first thing that returns a non-empty string.
# TODO: assemble multiple dates into a {} or []... | Generate EDTF string equivalent of a given natural language date string. | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/natlang/en.py#L27-L102 | [
"def text_to_edtf_date(text):\n \"\"\"\n Return EDTF string equivalent of a given natural language date string.\n\n The approach here is to parse the text twice, with different default\n dates. Then compare the results to see what differs - the parts that\n differ are undefined.\n \"\"\"\n if n... | """Utilities to derive an EDTF string from an (English) natural language string."""
from datetime import datetime
from dateutil.parser import parse
import re
from edtf import appsettings
from six.moves import xrange
# two dates where every digit of an ISO date representation is different,
# and one is in the past and... |
ixc/python-edtf | edtf/natlang/en.py | text_to_edtf_date | python | def text_to_edtf_date(text):
if not text:
return
t = text.lower()
result = ''
for reject_re in REJECT_RULES:
if re.match(reject_re, t):
return
# matches on '1800s'. Needs to happen before is_decade.
could_be_century = re.findall(r'(\d{2}00)s', t)
# matches on '... | Return EDTF string equivalent of a given natural language date string.
The approach here is to parse the text twice, with different default
dates. Then compare the results to see what differs - the parts that
differ are undefined. | train | https://github.com/ixc/python-edtf/blob/ec2124d3df75f8dd72571026380ce8dd16f3dd6b/edtf/natlang/en.py#L105-L275 | null | """Utilities to derive an EDTF string from an (English) natural language string."""
from datetime import datetime
from dateutil.parser import parse
import re
from edtf import appsettings
from six.moves import xrange
# two dates where every digit of an ISO date representation is different,
# and one is in the past and... |
cykl/infoqscraper | infoqscraper/cache.py | XDGCache.get_content | python | def get_content(self, url):
cache_path = self._url_to_path(url)
try:
with open(cache_path, 'rb') as f:
return f.read()
except IOError:
return None | Returns the content of a cached resource.
Args:
url: The url of the resource
Returns:
The content of the cached resource or None if not in the cache | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/cache.py#L56-L70 | [
"def _url_to_path(self, url):\n return os.path.join(self.dir, url)\n"
] | class XDGCache(object):
"""A disk cache for resources.
Remote resources can be cached to avoid to fetch them several times from the web server.
The resources are stored into the XDG_CACHE_HOME_DIR.
Attributes:
dir: Where to store the cached resources
"""
def __init__(self):
s... |
cykl/infoqscraper | infoqscraper/cache.py | XDGCache.get_path | python | def get_path(self, url):
cache_path = self._url_to_path(url)
if os.path.exists(cache_path):
return cache_path
return None | Returns the path of a cached resource.
Args:
url: The url of the resource
Returns:
The path to the cached resource or None if not in the cache | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/cache.py#L72-L85 | [
"def _url_to_path(self, url):\n return os.path.join(self.dir, url)\n"
] | class XDGCache(object):
"""A disk cache for resources.
Remote resources can be cached to avoid to fetch them several times from the web server.
The resources are stored into the XDG_CACHE_HOME_DIR.
Attributes:
dir: Where to store the cached resources
"""
def __init__(self):
s... |
cykl/infoqscraper | infoqscraper/cache.py | XDGCache.put_content | python | def put_content(self, url, content):
cache_path = self._url_to_path(url)
# Ensure that cache directories exist
try:
dir = os.path.dirname(cache_path)
os.makedirs(dir)
except OSError as e:
if e.errno != errno.EEXIST:
raise Error('Failed... | Stores the content of a resource into the disk cache.
Args:
url: The url of the resource
content: The content of the resource
Raises:
CacheError: If the content cannot be put in cache | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/cache.py#L87-L111 | [
"def _url_to_path(self, url):\n return os.path.join(self.dir, url)\n"
] | class XDGCache(object):
"""A disk cache for resources.
Remote resources can be cached to avoid to fetch them several times from the web server.
The resources are stored into the XDG_CACHE_HOME_DIR.
Attributes:
dir: Where to store the cached resources
"""
def __init__(self):
s... |
cykl/infoqscraper | infoqscraper/cache.py | XDGCache.put_path | python | def put_path(self, url, path):
cache_path = self._url_to_path(url)
# Ensure that cache directories exist
try:
dir = os.path.dirname(cache_path)
os.makedirs(dir)
except OSError as e:
if e.errno != errno.EEXIST:
raise Error('Failed to cr... | Puts a resource already on disk into the disk cache.
Args:
url: The original url of the resource
path: The resource already available on disk
Raises:
CacheError: If the file cannot be put in cache | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/cache.py#L113-L147 | [
"def _url_to_path(self, url):\n return os.path.join(self.dir, url)\n"
] | class XDGCache(object):
"""A disk cache for resources.
Remote resources can be cached to avoid to fetch them several times from the web server.
The resources are stored into the XDG_CACHE_HOME_DIR.
Attributes:
dir: Where to store the cached resources
"""
def __init__(self):
s... |
cykl/infoqscraper | infoqscraper/cache.py | XDGCache.size | python | def size(self):
total_size = 0
for dir_path, dir_names, filenames in os.walk(self.dir):
for f in filenames:
fp = os.path.join(dir_path, f)
total_size += os.path.getsize(fp)
return total_size | Returns the size of the cache in bytes. | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/cache.py#L158-L165 | null | class XDGCache(object):
"""A disk cache for resources.
Remote resources can be cached to avoid to fetch them several times from the web server.
The resources are stored into the XDG_CACHE_HOME_DIR.
Attributes:
dir: Where to store the cached resources
"""
def __init__(self):
s... |
cykl/infoqscraper | infoqscraper/scrap.py | get_summaries | python | def get_summaries(client, filter=None):
try:
index = 0
while True:
rb = _RightBarPage(client, index)
summaries = rb.summaries()
if filter is not None:
summaries = filter.filter(summaries)
for summary in summaries:
... | Generate presentation summaries in a reverse chronological order.
A filter class can be supplied to filter summaries or bound the fetching process. | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/scrap.py#L36-L55 | [
"def filter(self, presentation_summaries):\n if self.page_count >= self.max_pages:\n raise StopIteration\n\n self.page_count += 1\n return presentation_summaries\n",
"def summaries(self):\n \"\"\"Return a list of all the presentation summaries contained in this page\"\"\"\n def create_summar... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2014, Clément MATHIEU
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice... |
cykl/infoqscraper | infoqscraper/scrap.py | Presentation._fetch | python | def _fetch(self):
url = client.get_url("/presentations/" + self.id)
content = self.client.fetch_no_cache(url).decode('utf-8')
return bs4.BeautifulSoup(content, "html.parser") | Download the page and create the soup | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/scrap.py#L82-L86 | [
"def get_url(path, scheme=\"http\"):\n \"\"\" Return the full InfoQ URL \"\"\"\n return scheme + \"://www.infoq.com\" + path\n"
] | class Presentation(object):
""" An InfoQ presentation.
"""
def __init__(self, client, id):
self.client = client
self.id = id
self.soup = self._fetch()
@property
def metadata(self):
def get_title(pres_div):
return pres_div.find('h1', class_="general").di... |
cykl/infoqscraper | infoqscraper/scrap.py | _RightBarPage.soup | python | def soup(self):
try:
return self._soup
except AttributeError:
url = client.get_url("/presentations/%s" % self.index)
content = self.client.fetch_no_cache(url).decode('utf-8')
self._soup = bs4.BeautifulSoup(content, "html.parser")
return self._... | Download the page and create the soup | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/scrap.py#L203-L212 | [
"def get_url(path, scheme=\"http\"):\n \"\"\" Return the full InfoQ URL \"\"\"\n return scheme + \"://www.infoq.com\" + path\n"
] | class _RightBarPage(object):
"""A page returned by /rightbar.action
This page lists all available presentations with pagination.
"""
def __init__(self, client, index):
self.client = client
self.index = index
@property
def summaries(self):
"""Return a list of all the ... |
cykl/infoqscraper | infoqscraper/scrap.py | _RightBarPage.summaries | python | def summaries(self):
def create_summary(div):
def get_id(div):
return get_url(div).rsplit('/')[-1]
def get_url(div):
return client.get_url(div.find('h2', class_='itemtitle').a['href'])
def get_desc(div):
return div.p.get_text(... | Return a list of all the presentation summaries contained in this page | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/scrap.py#L214-L249 | null | class _RightBarPage(object):
"""A page returned by /rightbar.action
This page lists all available presentations with pagination.
"""
def __init__(self, client, index):
self.client = client
self.index = index
@property
def soup(self):
"""Download the page and create the... |
cykl/infoqscraper | infoqscraper/convert.py | swf2png | python | def swf2png(swf_path, png_path, swfrender_path="swfrender"):
# Currently rely on swftools
#
# Would be great to have a native python dependency to convert swf into png or jpg.
# However it seems that pyswf isn't flawless. Some graphical elements (like the text!) are lost during
# the export.
tr... | Convert SWF slides into a PNG image
Raises:
OSError is raised if swfrender is not available.
ConversionError is raised if image cannot be created. | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/convert.py#L340-L360 | null | # -*- coding: utf-8 -*-
#
# Copyright (c) 2012, Clément MATHIEU
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, thi... |
cykl/infoqscraper | infoqscraper/convert.py | Converter.create_presentation | python | def create_presentation(self):
# Avoid wasting time and bandwidth if we known that conversion will fail.
if not self.overwrite and os.path.exists(self.output):
raise ConversionError("File %s already exist and --overwrite not specified" % self.output)
video = self.download_video()
... | Create the presentation.
The audio track is mixed with the slides. The resulting file is saved as self.output
DownloadError is raised if some resources cannot be fetched.
ConversionError is raised if the final video cannot be created. | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/convert.py#L70-L90 | [
"def download_video(self):\n \"\"\"Downloads the video.\n\n If self.client.cache_enabled is True, then the disk cache is used.\n\n Returns:\n The path where the video has been saved.\n\n Raises:\n DownloadError: If the video cannot be downloaded.\n \"\"\"\n rvideo_path = self.present... | class Converter(object):
def __init__(self, presentation, output, **kwargs):
self.presentation = presentation
self.output = output
self.ffmpeg = kwargs['ffmpeg']
self.rtmpdump = kwargs['rtmpdump']
self.swfrender = kwargs['swfrender']
self.overwrite = kwargs['overwri... |
cykl/infoqscraper | infoqscraper/convert.py | Converter.download_video | python | def download_video(self):
rvideo_path = self.presentation.metadata['video_path']
if self.presentation.client.cache:
video_path = self.presentation.client.cache.get_path(rvideo_path)
if not video_path:
video_path = self.download_video_no_cache()
se... | Downloads the video.
If self.client.cache_enabled is True, then the disk cache is used.
Returns:
The path where the video has been saved.
Raises:
DownloadError: If the video cannot be downloaded. | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/convert.py#L92-L113 | [
"def download_video_no_cache(self):\n \"\"\"Downloads the video.\n\n Returns:\n The path where the video has been saved.\n\n Raises:\n DownloadError: If the video cannot be downloaded.\n \"\"\"\n video_url = self.presentation.metadata['video_url']\n video_path = self.presentation.met... | class Converter(object):
def __init__(self, presentation, output, **kwargs):
self.presentation = presentation
self.output = output
self.ffmpeg = kwargs['ffmpeg']
self.rtmpdump = kwargs['rtmpdump']
self.swfrender = kwargs['swfrender']
self.overwrite = kwargs['overwri... |
cykl/infoqscraper | infoqscraper/convert.py | Converter.download_video_no_cache | python | def download_video_no_cache(self):
video_url = self.presentation.metadata['video_url']
video_path = self.presentation.metadata['video_path']
# After a while, when downloading a long video (> 1h), the RTMP server seems to reset the connection (rtmpdump
# returns exit code 2). The only wa... | Downloads the video.
Returns:
The path where the video has been saved.
Raises:
DownloadError: If the video cannot be downloaded. | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/convert.py#L115-L145 | null | class Converter(object):
def __init__(self, presentation, output, **kwargs):
self.presentation = presentation
self.output = output
self.ffmpeg = kwargs['ffmpeg']
self.rtmpdump = kwargs['rtmpdump']
self.swfrender = kwargs['swfrender']
self.overwrite = kwargs['overwri... |
cykl/infoqscraper | infoqscraper/convert.py | Converter.download_slides | python | def download_slides(self):
return self.presentation.client.download_all(self.presentation.metadata['slides'], self.tmp_dir) | Download all SWF slides.
The location of the slides files are returned.
A DownloadError is raised if at least one of the slides cannot be download.. | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/convert.py#L147-L154 | null | class Converter(object):
def __init__(self, presentation, output, **kwargs):
self.presentation = presentation
self.output = output
self.ffmpeg = kwargs['ffmpeg']
self.rtmpdump = kwargs['rtmpdump']
self.swfrender = kwargs['swfrender']
self.overwrite = kwargs['overwri... |
cykl/infoqscraper | infoqscraper/client.py | InfoQ.login | python | def login(self, username, password):
url = get_url("/login.action", scheme="https")
params = {
'username': username,
'password': password,
'submit-login': '',
}
with contextlib.closing(self.opener.open(url, urllib.parse.urlencode(params))) as response:... | Log in.
AuthenticationFailedException exception is raised if authentication fails. | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/client.py#L62-L79 | [
"def get_url(path, scheme=\"http\"):\n \"\"\" Return the full InfoQ URL \"\"\"\n return scheme + \"://www.infoq.com\" + path\n"
] | class InfoQ(object):
""" InfoQ web client entry point
Attributes:
authenticated: If logged in or not
cache: None if caching is disable. A Cache object otherwise
"""
def __init__(self, cache_enabled=False):
self.authenticated = False
# InfoQ requires c... |
cykl/infoqscraper | infoqscraper/client.py | InfoQ.fetch_no_cache | python | def fetch_no_cache(self, url):
try:
with contextlib.closing(self.opener.open(url)) as response:
# InfoQ does not send a 404 but a 302 redirecting to a valid URL...
if response.code != 200 or response.url == INFOQ_404_URL:
raise DownloadError("%s n... | Fetch the resource specified and return its content.
DownloadError is raised if the resource cannot be fetched. | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/client.py#L92-L105 | null | class InfoQ(object):
""" InfoQ web client entry point
Attributes:
authenticated: If logged in or not
cache: None if caching is disable. A Cache object otherwise
"""
def __init__(self, cache_enabled=False):
self.authenticated = False
# InfoQ requires c... |
cykl/infoqscraper | infoqscraper/client.py | InfoQ.download | python | def download(self, url, dir_path, filename=None):
if not filename:
filename = url.rsplit('/', 1)[1]
path = os.path.join(dir_path, filename)
content = self.fetch(url)
with open(path, "wb") as f:
f.write(content)
return path | Download the resources specified by url into dir_path. The resulting
file path is returned.
DownloadError is raised the resources cannot be downloaded. | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/client.py#L107-L121 | [
"def fetch(self, url):\n if self.cache:\n content = self.cache.get_content(url)\n if not content:\n content = self.fetch_no_cache(url)\n self.cache.put_content(url, content)\n else:\n content = self.fetch_no_cache(url)\n\n return content\n"
] | class InfoQ(object):
""" InfoQ web client entry point
Attributes:
authenticated: If logged in or not
cache: None if caching is disable. A Cache object otherwise
"""
def __init__(self, cache_enabled=False):
self.authenticated = False
# InfoQ requires c... |
cykl/infoqscraper | infoqscraper/client.py | InfoQ.download_all | python | def download_all(self, urls, dir_path):
# TODO: Implement parallel download
filenames = []
try:
for url in urls:
filenames.append(self.download(url, dir_path))
except DownloadError as e:
for filename in filenames:
os.remove(filenam... | Download all the resources specified by urls into dir_path. The resulting
file paths is returned.
DownloadError is raised if at least one of the resources cannot be downloaded.
In the case already downloaded resources are erased. | train | https://github.com/cykl/infoqscraper/blob/4fc026b994f98a0a7fe8578e0c9a3a9664982b2e/infoqscraper/client.py#L123-L141 | [
"def download(self, url, dir_path, filename=None):\n \"\"\" Download the resources specified by url into dir_path. The resulting\n file path is returned.\n\n DownloadError is raised the resources cannot be downloaded.\n \"\"\"\n if not filename:\n filename = url.rsplit('/', 1)[1]\n ... | class InfoQ(object):
""" InfoQ web client entry point
Attributes:
authenticated: If logged in or not
cache: None if caching is disable. A Cache object otherwise
"""
def __init__(self, cache_enabled=False):
self.authenticated = False
# InfoQ requires c... |
klmitch/requiem | requiem/request.py | HTTPRequest.send | python | def send(self):
# Pre-process the request
try:
self.procstack.proc_request(self)
except exc.ShortCircuit, e:
self._debug("Request pre-processing short-circuited")
# Short-circuited; we have an (already processed) response
return e.response
... | Issue the request.
Uses httplib2.Http support for handling redirects. Returns an
httplib2.Response, which may be augmented by the
proc_response() method.
Note that the default implementation of proc_response() causes
an appropriate exception to be raised if the response code i... | train | https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/request.py#L76-L122 | [
"def proc_response(self, resp):\n \"\"\"Process response hook.\n\n Process non-redirect responses received by the send() method.\n May augment the response. The default implementation causes\n an exception to be raised if the response status code is >=\n 400.\n \"\"\"\n\n # Raise exceptions fo... | class HTTPRequest(object):
"""Represent and perform HTTP requests.
Implements the dictionary access protocol to modify headers
(headers can also be accessed directly at the 'headers' attribute)
and the stream protocol to build up the body. Handles
redirections under control of the class attribute ... |
klmitch/requiem | requiem/request.py | HTTPRequest.proc_response | python | def proc_response(self, resp):
# Raise exceptions for error responses
if resp.status >= 400:
e = exc.exception_map.get(resp.status, exc.HTTPException)
self._debug(" Response was a %d fault, raising %s",
resp.status, e.__name__)
raise e(resp) | Process response hook.
Process non-redirect responses received by the send() method.
May augment the response. The default implementation causes
an exception to be raised if the response status code is >=
400. | train | https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/request.py#L124-L138 | null | class HTTPRequest(object):
"""Represent and perform HTTP requests.
Implements the dictionary access protocol to modify headers
(headers can also be accessed directly at the 'headers' attribute)
and the stream protocol to build up the body. Handles
redirections under control of the class attribute ... |
klmitch/requiem | requiem/processor.py | _safe_call | python | def _safe_call(obj, methname, *args, **kwargs):
meth = getattr(obj, methname, None)
if meth is None or not callable(meth):
return
return meth(*args, **kwargs) | Safely calls the method with the given methname on the given
object. Remaining positional and keyword arguments are passed to
the method. The return value is None, if the method is not
available, or the return value of the method. | train | https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/processor.py#L57-L69 | null | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
klmitch/requiem | requiem/processor.py | ProcessorStack.proc_request | python | def proc_request(self, req):
for idx in range(len(self)):
resp = _safe_call(self[idx], 'proc_request', req)
# Do we have a response?
if resp is not None:
# Short-circuit
raise exc.ShortCircuit(self.proc_response(resp, idx - 1))
# Ret... | Pre-process a request through all processors in the stack, in
order. If any processor's proc_request() method returns a
value other than None, that value is treated as a response and
post-processed through the proc_response() methods of the
processors preceding that processor in the sta... | train | https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/processor.py#L79-L102 | [
"def _safe_call(obj, methname, *args, **kwargs):\n \"\"\"\n Safely calls the method with the given methname on the given\n object. Remaining positional and keyword arguments are passed to\n the method. The return value is None, if the method is not\n available, or the return value of the method.\n ... | class ProcessorStack(list):
"""
A list subclass for processor stacks, defining three
domain-specific methods: proc_request(), proc_response(), and
proc_exception().
"""
def proc_response(self, resp, startidx=None):
"""
Post-process a response through all processors in the stack... |
klmitch/requiem | requiem/processor.py | ProcessorStack.proc_response | python | def proc_response(self, resp, startidx=None):
# If we're empty, bail out early
if not self:
return resp
# Select appropriate starting index
if startidx is None:
startidx = len(self)
for idx in range(startidx, -1, -1):
_safe_call(self[idx], '... | Post-process a response through all processors in the stack,
in reverse order. For convenience, returns the response
passed to the method.
The startidx argument is an internal interface only used by
the proc_request() and proc_exception() methods to process a
response through a... | train | https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/processor.py#L104-L127 | [
"def _safe_call(obj, methname, *args, **kwargs):\n \"\"\"\n Safely calls the method with the given methname on the given\n object. Remaining positional and keyword arguments are passed to\n the method. The return value is None, if the method is not\n available, or the return value of the method.\n ... | class ProcessorStack(list):
"""
A list subclass for processor stacks, defining three
domain-specific methods: proc_request(), proc_response(), and
proc_exception().
"""
def proc_request(self, req):
"""
Pre-process a request through all processors in the stack, in
order. ... |
klmitch/requiem | requiem/processor.py | ProcessorStack.proc_exception | python | def proc_exception(self, exc_type, exc_value, traceback):
# If we're empty, bail out early
if not self:
return
for idx in range(len(self), -1, -1):
# First, process the response...
if hasattr(exc_value, 'response'):
_safe_call(self[idx], 'pro... | Post-process an exception through all processors in the stack,
in reverse order. The exception so post-processed is any
exception raised by the Request object's proc_response()
method; if the httplib2.Http raises an exception, that
exception will not be processed by this mechanism.
... | train | https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/processor.py#L129-L165 | [
"def _safe_call(obj, methname, *args, **kwargs):\n \"\"\"\n Safely calls the method with the given methname on the given\n object. Remaining positional and keyword arguments are passed to\n the method. The return value is None, if the method is not\n available, or the return value of the method.\n ... | class ProcessorStack(list):
"""
A list subclass for processor stacks, defining three
domain-specific methods: proc_request(), proc_response(), and
proc_exception().
"""
def proc_request(self, req):
"""
Pre-process a request through all processors in the stack, in
order. ... |
klmitch/requiem | requiem/jsclient.py | JSONRequest.proc_response | python | def proc_response(self, resp):
# Try to interpret any JSON
try:
resp.obj = json.loads(resp.body)
self._debug(" Received entity: %r", resp.obj)
except ValueError:
resp.obj = None
self._debug(" No received entity; body %r", resp.body)
# N... | Process JSON data found in the response. | train | https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/jsclient.py#L56-L68 | [
"def proc_response(self, resp):\n \"\"\"Process response hook.\n\n Process non-redirect responses received by the send() method.\n May augment the response. The default implementation causes\n an exception to be raised if the response status code is >=\n 400.\n \"\"\"\n\n # Raise exceptions fo... | class JSONRequest(request.HTTPRequest):
"""Variant of HTTPRequest to process JSON data in responses."""
|
klmitch/requiem | requiem/jsclient.py | JSONClient._attach_obj | python | def _attach_obj(self, req, obj):
# Attach the object to the request
json.dump(obj, req)
# Also set the content-type header
req['content-type'] = self._content_type | Helper method to attach obj to req as JSON data. | train | https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/jsclient.py#L92-L99 | null | class JSONClient(client.RESTClient):
"""Process JSON data in requests and responses.
Augments RESTClient to include the _attach_obj() helper method,
for attaching JSON objects to requests. Also uses JSONRequest in
preference to HTTPRequest, so that JSON data in responses is
processed.
"""
... |
klmitch/requiem | requiem/headers.py | HeaderDict.fromkeys | python | def fromkeys(cls, seq, v=None):
return super(HeaderDict, cls).fromkeys(cls,
[s.title() for s in seq], v) | Override dict.fromkeys() to title-case keys. | train | https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/headers.py#L57-L61 | null | class HeaderDict(dict):
"""Class for representing a dictionary where keys are header names."""
def __contains__(self, k):
"""Override dict.__contains__() to title-case keys."""
return super(HeaderDict, self).__contains__(k.title())
def __delitem__(self, k):
"""Override dict.__deli... |
klmitch/requiem | requiem/headers.py | HeaderDict.get | python | def get(self, k, d=None):
return super(HeaderDict, self).get(k.title(), d) | Override dict.get() to title-case keys. | train | https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/headers.py#L63-L66 | null | class HeaderDict(dict):
"""Class for representing a dictionary where keys are header names."""
def __contains__(self, k):
"""Override dict.__contains__() to title-case keys."""
return super(HeaderDict, self).__contains__(k.title())
def __delitem__(self, k):
"""Override dict.__deli... |
klmitch/requiem | requiem/headers.py | HeaderDict.setdefault | python | def setdefault(self, k, d=None):
return super(HeaderDict, self).setdefault(k.title(), d) | Override dict.setdefault() to title-case keys. | train | https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/headers.py#L73-L76 | null | class HeaderDict(dict):
"""Class for representing a dictionary where keys are header names."""
def __contains__(self, k):
"""Override dict.__contains__() to title-case keys."""
return super(HeaderDict, self).__contains__(k.title())
def __delitem__(self, k):
"""Override dict.__deli... |
klmitch/requiem | requiem/headers.py | HeaderDict.update | python | def update(self, e=None, **f):
# Handle e first
if e is not None:
if hasattr(e, 'keys'):
for k in e:
self[k.title()] = e[k]
else:
for (k, v) in e:
self[k.title()] = v
# Now handle f
if len(f... | Override dict.update() to title-case keys. | train | https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/headers.py#L78-L93 | null | class HeaderDict(dict):
"""Class for representing a dictionary where keys are header names."""
def __contains__(self, k):
"""Override dict.__contains__() to title-case keys."""
return super(HeaderDict, self).__contains__(k.title())
def __delitem__(self, k):
"""Override dict.__deli... |
klmitch/requiem | requiem/decorators.py | _getcallargs | python | def _getcallargs(func, positional, named):
args, varargs, varkw, defaults = inspect.getargspec(func)
f_name = func.__name__
arg2value = {}
# The following closures are basically because of tuple parameter
# unpacking.
assigned_tuple_params = []
def assign(arg, value):
if isinstanc... | Get the mapping of arguments to values.
Generates a dict, with keys being the function argument names
(including the names of the * and ** arguments, if any), and
values the respective bound values from 'positional' and 'named'.
A parameter for the request is injected. Returns a tuple of the
dict,... | train | https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/decorators.py#L40-L147 | [
"def assign(arg, value):\n if isinstance(arg, str):\n arg2value[arg] = value\n else:\n assigned_tuple_params.append(arg)\n value = iter(value)\n for i, subarg in enumerate(arg):\n try:\n subvalue = next(value)\n except StopIteration:\n ... | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
klmitch/requiem | requiem/decorators.py | _urljoin | python | def _urljoin(left, right):
# Handle the tricky case of right being a full URL
tmp = urlparse.urlparse(right)
if tmp.scheme or tmp.netloc:
# Go ahead and use urlparse.urljoin()
return urlparse.urljoin(left, right)
# Check for slashes
joincond = (left[-1:], right[:1])
if joincond... | Join two URLs.
Takes URLs specified by left and right and joins them into a
single URL. If right is an absolute URL, it is returned directly.
This differs from urlparse.urljoin() in that the latter always
chops off the left-most component of left unless it is trailed by
'/', which is not the behav... | train | https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/decorators.py#L150-L176 | null | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.