repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_silva_2008.py
AbrahamsonSilva2008._get_stddevs
def _get_stddevs(self, C, C_PGA, pga1100, rup, sites, stddev_types): """ Return standard deviations as described in paragraph 'Equations for standard deviation', page 81. """ std_intra = self._compute_intra_event_std(C, C_PGA, pga1100, rup.mag, ...
python
def _get_stddevs(self, C, C_PGA, pga1100, rup, sites, stddev_types): """ Return standard deviations as described in paragraph 'Equations for standard deviation', page 81. """ std_intra = self._compute_intra_event_std(C, C_PGA, pga1100, rup.mag, ...
[ "def", "_get_stddevs", "(", "self", ",", "C", ",", "C_PGA", ",", "pga1100", ",", "rup", ",", "sites", ",", "stddev_types", ")", ":", "std_intra", "=", "self", ".", "_compute_intra_event_std", "(", "C", ",", "C_PGA", ",", "pga1100", ",", "rup", ".", "ma...
Return standard deviations as described in paragraph 'Equations for standard deviation', page 81.
[ "Return", "standard", "deviations", "as", "described", "in", "paragraph", "Equations", "for", "standard", "deviation", "page", "81", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L277-L296
train
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_silva_2008.py
AbrahamsonSilva2008._compute_inter_event_std
def _compute_inter_event_std(self, C, C_PGA, pga1100, mag, vs30): """ Compute inter event standard deviation, equation 25, page 82. """ tau_0 = self._compute_std_0(C['s3'], C['s4'], mag) tau_b_pga = self._compute_std_0(C_PGA['s3'], C_PGA['s4'], mag) delta_amp = self._comp...
python
def _compute_inter_event_std(self, C, C_PGA, pga1100, mag, vs30): """ Compute inter event standard deviation, equation 25, page 82. """ tau_0 = self._compute_std_0(C['s3'], C['s4'], mag) tau_b_pga = self._compute_std_0(C_PGA['s3'], C_PGA['s4'], mag) delta_amp = self._comp...
[ "def", "_compute_inter_event_std", "(", "self", ",", "C", ",", "C_PGA", ",", "pga1100", ",", "mag", ",", "vs30", ")", ":", "tau_0", "=", "self", ".", "_compute_std_0", "(", "C", "[", "'s3'", "]", ",", "C", "[", "'s4'", "]", ",", "mag", ")", "tau_b_...
Compute inter event standard deviation, equation 25, page 82.
[ "Compute", "inter", "event", "standard", "deviation", "equation", "25", "page", "82", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L314-L325
train
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_silva_2008.py
AbrahamsonSilva2008._compute_sigma_b
def _compute_sigma_b(self, C, mag, vs30measured): """ Equation 23, page 81. """ sigma_0 = self._compute_sigma_0(C, mag, vs30measured) sigma_amp = self.CONSTS['sigma_amp'] return np.sqrt(sigma_0 ** 2 - sigma_amp ** 2)
python
def _compute_sigma_b(self, C, mag, vs30measured): """ Equation 23, page 81. """ sigma_0 = self._compute_sigma_0(C, mag, vs30measured) sigma_amp = self.CONSTS['sigma_amp'] return np.sqrt(sigma_0 ** 2 - sigma_amp ** 2)
[ "def", "_compute_sigma_b", "(", "self", ",", "C", ",", "mag", ",", "vs30measured", ")", ":", "sigma_0", "=", "self", ".", "_compute_sigma_0", "(", "C", ",", "mag", ",", "vs30measured", ")", "sigma_amp", "=", "self", ".", "CONSTS", "[", "'sigma_amp'", "]"...
Equation 23, page 81.
[ "Equation", "23", "page", "81", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L327-L334
train
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_silva_2008.py
AbrahamsonSilva2008._compute_sigma_0
def _compute_sigma_0(self, C, mag, vs30measured): """ Equation 27, page 82. """ s1 = np.zeros_like(vs30measured, dtype=float) s2 = np.zeros_like(vs30measured, dtype=float) idx = vs30measured == 1 s1[idx] = C['s1mea'] s2[idx] = C['s2mea'] idx = vs...
python
def _compute_sigma_0(self, C, mag, vs30measured): """ Equation 27, page 82. """ s1 = np.zeros_like(vs30measured, dtype=float) s2 = np.zeros_like(vs30measured, dtype=float) idx = vs30measured == 1 s1[idx] = C['s1mea'] s2[idx] = C['s2mea'] idx = vs...
[ "def", "_compute_sigma_0", "(", "self", ",", "C", ",", "mag", ",", "vs30measured", ")", ":", "s1", "=", "np", ".", "zeros_like", "(", "vs30measured", ",", "dtype", "=", "float", ")", "s2", "=", "np", ".", "zeros_like", "(", "vs30measured", ",", "dtype"...
Equation 27, page 82.
[ "Equation", "27", "page", "82", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L336-L351
train
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_silva_2008.py
AbrahamsonSilva2008._compute_std_0
def _compute_std_0(self, c1, c2, mag): """ Common part of equations 27 and 28, pag 82. """ if mag < 5: return c1 elif mag >= 5 and mag <= 7: return c1 + (c2 - c1) * (mag - 5) / 2 else: return c2
python
def _compute_std_0(self, c1, c2, mag): """ Common part of equations 27 and 28, pag 82. """ if mag < 5: return c1 elif mag >= 5 and mag <= 7: return c1 + (c2 - c1) * (mag - 5) / 2 else: return c2
[ "def", "_compute_std_0", "(", "self", ",", "c1", ",", "c2", ",", "mag", ")", ":", "if", "mag", "<", "5", ":", "return", "c1", "elif", "mag", ">=", "5", "and", "mag", "<=", "7", ":", "return", "c1", "+", "(", "c2", "-", "c1", ")", "*", "(", ...
Common part of equations 27 and 28, pag 82.
[ "Common", "part", "of", "equations", "27", "and", "28", "pag", "82", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L353-L362
train
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_silva_2008.py
AbrahamsonSilva2008._compute_a21_factor
def _compute_a21_factor(self, C, imt, z1pt0, vs30): """ Compute and return a21 factor, equation 18, page 80. """ e2 = self._compute_e2_factor(imt, vs30) a21 = e2.copy() vs30_star, v1 = self._compute_vs30_star_factor(imt, vs30) median_z1pt0 = self._compute_median_...
python
def _compute_a21_factor(self, C, imt, z1pt0, vs30): """ Compute and return a21 factor, equation 18, page 80. """ e2 = self._compute_e2_factor(imt, vs30) a21 = e2.copy() vs30_star, v1 = self._compute_vs30_star_factor(imt, vs30) median_z1pt0 = self._compute_median_...
[ "def", "_compute_a21_factor", "(", "self", ",", "C", ",", "imt", ",", "z1pt0", ",", "vs30", ")", ":", "e2", "=", "self", ".", "_compute_e2_factor", "(", "imt", ",", "vs30", ")", "a21", "=", "e2", ".", "copy", "(", ")", "vs30_star", ",", "v1", "=", ...
Compute and return a21 factor, equation 18, page 80.
[ "Compute", "and", "return", "a21", "factor", "equation", "18", "page", "80", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L383-L404
train
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_silva_2008.py
AbrahamsonSilva2008._compute_vs30_star_factor
def _compute_vs30_star_factor(self, imt, vs30): """ Compute and return vs30 star factor, equation 5, page 77. """ v1 = self._compute_v1_factor(imt) vs30_star = vs30.copy() vs30_star[vs30_star >= v1] = v1 return vs30_star, v1
python
def _compute_vs30_star_factor(self, imt, vs30): """ Compute and return vs30 star factor, equation 5, page 77. """ v1 = self._compute_v1_factor(imt) vs30_star = vs30.copy() vs30_star[vs30_star >= v1] = v1 return vs30_star, v1
[ "def", "_compute_vs30_star_factor", "(", "self", ",", "imt", ",", "vs30", ")", ":", "v1", "=", "self", ".", "_compute_v1_factor", "(", "imt", ")", "vs30_star", "=", "vs30", ".", "copy", "(", ")", "vs30_star", "[", "vs30_star", ">=", "v1", "]", "=", "v1...
Compute and return vs30 star factor, equation 5, page 77.
[ "Compute", "and", "return", "vs30", "star", "factor", "equation", "5", "page", "77", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L406-L414
train
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_silva_2008.py
AbrahamsonSilva2008._compute_v1_factor
def _compute_v1_factor(self, imt): """ Compute and return v1 factor, equation 6, page 77. """ if imt.name == "SA": t = imt.period if t <= 0.50: v1 = 1500.0 elif t > 0.50 and t <= 1.0: v1 = np.exp(8.0 - 0.795 * np.log(t /...
python
def _compute_v1_factor(self, imt): """ Compute and return v1 factor, equation 6, page 77. """ if imt.name == "SA": t = imt.period if t <= 0.50: v1 = 1500.0 elif t > 0.50 and t <= 1.0: v1 = np.exp(8.0 - 0.795 * np.log(t /...
[ "def", "_compute_v1_factor", "(", "self", ",", "imt", ")", ":", "if", "imt", ".", "name", "==", "\"SA\"", ":", "t", "=", "imt", ".", "period", "if", "t", "<=", "0.50", ":", "v1", "=", "1500.0", "elif", "t", ">", "0.50", "and", "t", "<=", "1.0", ...
Compute and return v1 factor, equation 6, page 77.
[ "Compute", "and", "return", "v1", "factor", "equation", "6", "page", "77", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L416-L436
train
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_silva_2008.py
AbrahamsonSilva2008._compute_e2_factor
def _compute_e2_factor(self, imt, vs30): """ Compute and return e2 factor, equation 19, page 80. """ e2 = np.zeros_like(vs30) if imt.name == "PGV": period = 1 elif imt.name == "PGA": period = 0 else: period = imt.period ...
python
def _compute_e2_factor(self, imt, vs30): """ Compute and return e2 factor, equation 19, page 80. """ e2 = np.zeros_like(vs30) if imt.name == "PGV": period = 1 elif imt.name == "PGA": period = 0 else: period = imt.period ...
[ "def", "_compute_e2_factor", "(", "self", ",", "imt", ",", "vs30", ")", ":", "e2", "=", "np", ".", "zeros_like", "(", "vs30", ")", "if", "imt", ".", "name", "==", "\"PGV\"", ":", "period", "=", "1", "elif", "imt", ".", "name", "==", "\"PGA\"", ":",...
Compute and return e2 factor, equation 19, page 80.
[ "Compute", "and", "return", "e2", "factor", "equation", "19", "page", "80", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L438-L461
train
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_silva_2008.py
AbrahamsonSilva2008._compute_a22_factor
def _compute_a22_factor(self, imt): """ Compute and return the a22 factor, equation 20, page 80. """ if imt.name == 'PGV': return 0.0 period = imt.period if period < 2.0: return 0.0 else: return 0.0625 * (period - 2.0)
python
def _compute_a22_factor(self, imt): """ Compute and return the a22 factor, equation 20, page 80. """ if imt.name == 'PGV': return 0.0 period = imt.period if period < 2.0: return 0.0 else: return 0.0625 * (period - 2.0)
[ "def", "_compute_a22_factor", "(", "self", ",", "imt", ")", ":", "if", "imt", ".", "name", "==", "'PGV'", ":", "return", "0.0", "period", "=", "imt", ".", "period", "if", "period", "<", "2.0", ":", "return", "0.0", "else", ":", "return", "0.0625", "*...
Compute and return the a22 factor, equation 20, page 80.
[ "Compute", "and", "return", "the", "a22", "factor", "equation", "20", "page", "80", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L477-L487
train
gem/oq-engine
openquake/hazardlib/gsim/youngs_1997.py
YoungsEtAl1997SInter._compute_mean
def _compute_mean(self, C, A1, A2, A3, A4, A5, A6, mag, hypo_depth, rrup, mean, idx): """ Compute mean for subduction interface events, as explained in table 2, page 67. """ mean[idx] = (A1 + A2 * mag + C['C1'] + C['C2'] * (A3 - mag) ** 3 + ...
python
def _compute_mean(self, C, A1, A2, A3, A4, A5, A6, mag, hypo_depth, rrup, mean, idx): """ Compute mean for subduction interface events, as explained in table 2, page 67. """ mean[idx] = (A1 + A2 * mag + C['C1'] + C['C2'] * (A3 - mag) ** 3 + ...
[ "def", "_compute_mean", "(", "self", ",", "C", ",", "A1", ",", "A2", ",", "A3", ",", "A4", ",", "A5", ",", "A6", ",", "mag", ",", "hypo_depth", ",", "rrup", ",", "mean", ",", "idx", ")", ":", "mean", "[", "idx", "]", "=", "(", "A1", "+", "A...
Compute mean for subduction interface events, as explained in table 2, page 67.
[ "Compute", "mean", "for", "subduction", "interface", "events", "as", "explained", "in", "table", "2", "page", "67", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/youngs_1997.py#L121-L129
train
gem/oq-engine
openquake/hazardlib/gsim/youngs_1997.py
YoungsEtAl1997SInter._compute_std
def _compute_std(self, C, mag, stddevs, idx): """ Compute total standard deviation, as explained in table 2, page 67. """ if mag > 8.0: mag = 8.0 for stddev in stddevs: stddev[idx] += C['C4'] + C['C5'] * mag
python
def _compute_std(self, C, mag, stddevs, idx): """ Compute total standard deviation, as explained in table 2, page 67. """ if mag > 8.0: mag = 8.0 for stddev in stddevs: stddev[idx] += C['C4'] + C['C5'] * mag
[ "def", "_compute_std", "(", "self", ",", "C", ",", "mag", ",", "stddevs", ",", "idx", ")", ":", "if", "mag", ">", "8.0", ":", "mag", "=", "8.0", "for", "stddev", "in", "stddevs", ":", "stddev", "[", "idx", "]", "+=", "C", "[", "'C4'", "]", "+",...
Compute total standard deviation, as explained in table 2, page 67.
[ "Compute", "total", "standard", "deviation", "as", "explained", "in", "table", "2", "page", "67", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/youngs_1997.py#L131-L139
train
gem/oq-engine
openquake/hmtk/plotting/mapping.py
HMTKBaseMap._build_basemap
def _build_basemap(self): ''' Creates the map according to the input configuration ''' if self.config['min_lon'] >= self.config['max_lon']: raise ValueError('Upper limit of long is smaller than lower limit') if self.config['min_lon'] >= self.config['max_lon']: ...
python
def _build_basemap(self): ''' Creates the map according to the input configuration ''' if self.config['min_lon'] >= self.config['max_lon']: raise ValueError('Upper limit of long is smaller than lower limit') if self.config['min_lon'] >= self.config['max_lon']: ...
[ "def", "_build_basemap", "(", "self", ")", ":", "if", "self", ".", "config", "[", "'min_lon'", "]", ">=", "self", ".", "config", "[", "'max_lon'", "]", ":", "raise", "ValueError", "(", "'Upper limit of long is smaller than lower limit'", ")", "if", "self", "."...
Creates the map according to the input configuration
[ "Creates", "the", "map", "according", "to", "the", "input", "configuration" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/mapping.py#L124-L175
train
gem/oq-engine
openquake/hmtk/plotting/mapping.py
HMTKBaseMap.savemap
def savemap(self, filename, filetype='png', papertype="a4"): """ Save the figure """ self.fig.savefig(filename, dpi=self.dpi, format=filetype, papertype=papertype)
python
def savemap(self, filename, filetype='png', papertype="a4"): """ Save the figure """ self.fig.savefig(filename, dpi=self.dpi, format=filetype, papertype=papertype)
[ "def", "savemap", "(", "self", ",", "filename", ",", "filetype", "=", "'png'", ",", "papertype", "=", "\"a4\"", ")", ":", "self", ".", "fig", ".", "savefig", "(", "filename", ",", "dpi", "=", "self", ".", "dpi", ",", "format", "=", "filetype", ",", ...
Save the figure
[ "Save", "the", "figure" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/mapping.py#L177-L184
train
gem/oq-engine
openquake/hmtk/plotting/mapping.py
HMTKBaseMap.add_source_model
def add_source_model( self, model, area_border='k-', border_width=1.0, point_marker='ks', point_size=2.0, overlay=False, min_depth=0., max_depth=None, alpha=1.0): """ Adds a source model to the map :param model: Source model of mixed typologies as...
python
def add_source_model( self, model, area_border='k-', border_width=1.0, point_marker='ks', point_size=2.0, overlay=False, min_depth=0., max_depth=None, alpha=1.0): """ Adds a source model to the map :param model: Source model of mixed typologies as...
[ "def", "add_source_model", "(", "self", ",", "model", ",", "area_border", "=", "'k-'", ",", "border_width", "=", "1.0", ",", "point_marker", "=", "'ks'", ",", "point_size", "=", "2.0", ",", "overlay", "=", "False", ",", "min_depth", "=", "0.", ",", "max_...
Adds a source model to the map :param model: Source model of mixed typologies as instance of :class: openquake.hmtk.sources.source_model.mtkSourceModel
[ "Adds", "a", "source", "model", "to", "the", "map" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/mapping.py#L337-L361
train
gem/oq-engine
openquake/hmtk/plotting/mapping.py
HMTKBaseMap.add_colour_scaled_points
def add_colour_scaled_points(self, longitude, latitude, data, shape='s', alpha=1.0, size=20, norm=None, overlay=False): """ Overlays a set of points on a map with a fixed size but colour scaled according to the data :param np.ndarray longitude: ...
python
def add_colour_scaled_points(self, longitude, latitude, data, shape='s', alpha=1.0, size=20, norm=None, overlay=False): """ Overlays a set of points on a map with a fixed size but colour scaled according to the data :param np.ndarray longitude: ...
[ "def", "add_colour_scaled_points", "(", "self", ",", "longitude", ",", "latitude", ",", "data", ",", "shape", "=", "'s'", ",", "alpha", "=", "1.0", ",", "size", "=", "20", ",", "norm", "=", "None", ",", "overlay", "=", "False", ")", ":", "if", "not",...
Overlays a set of points on a map with a fixed size but colour scaled according to the data :param np.ndarray longitude: Longitude :param np.ndarray latitude: Latitude :param np.ndarray data: Data for plotting :param str shape: Mar...
[ "Overlays", "a", "set", "of", "points", "on", "a", "map", "with", "a", "fixed", "size", "but", "colour", "scaled", "according", "to", "the", "data" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/mapping.py#L363-L397
train
gem/oq-engine
openquake/hmtk/plotting/mapping.py
HMTKBaseMap.add_size_scaled_points
def add_size_scaled_points( self, longitude, latitude, data, shape='o', logplot=False, alpha=1.0, colour='b', smin=2.0, sscale=2.0, overlay=False): """ Plots a set of points with size scaled according to the data :param bool logplot: Choose to sca...
python
def add_size_scaled_points( self, longitude, latitude, data, shape='o', logplot=False, alpha=1.0, colour='b', smin=2.0, sscale=2.0, overlay=False): """ Plots a set of points with size scaled according to the data :param bool logplot: Choose to sca...
[ "def", "add_size_scaled_points", "(", "self", ",", "longitude", ",", "latitude", ",", "data", ",", "shape", "=", "'o'", ",", "logplot", "=", "False", ",", "alpha", "=", "1.0", ",", "colour", "=", "'b'", ",", "smin", "=", "2.0", ",", "sscale", "=", "2...
Plots a set of points with size scaled according to the data :param bool logplot: Choose to scale according to the logarithm (base 10) of the data :param float smin: Minimum scale size :param float sscale: Scaling factor
[ "Plots", "a", "set", "of", "points", "with", "size", "scaled", "according", "to", "the", "data" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/mapping.py#L399-L424
train
gem/oq-engine
openquake/hmtk/plotting/mapping.py
HMTKBaseMap.add_catalogue_cluster
def add_catalogue_cluster(self, catalogue, vcl, flagvector, cluster_id=None, overlay=True): """ Creates a plot of a catalogue showing where particular clusters exist """ # Create simple magnitude scaled point basemap self.add_size_scaled_points(catal...
python
def add_catalogue_cluster(self, catalogue, vcl, flagvector, cluster_id=None, overlay=True): """ Creates a plot of a catalogue showing where particular clusters exist """ # Create simple magnitude scaled point basemap self.add_size_scaled_points(catal...
[ "def", "add_catalogue_cluster", "(", "self", ",", "catalogue", ",", "vcl", ",", "flagvector", ",", "cluster_id", "=", "None", ",", "overlay", "=", "True", ")", ":", "# Create simple magnitude scaled point basemap", "self", ".", "add_size_scaled_points", "(", "catalo...
Creates a plot of a catalogue showing where particular clusters exist
[ "Creates", "a", "plot", "of", "a", "catalogue", "showing", "where", "particular", "clusters", "exist" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/mapping.py#L480-L524
train
gem/oq-engine
openquake/hazardlib/gsim/campbell_bozorgnia_2003.py
CampbellBozorgnia2003NSHMP2007._get_stddevs
def _get_stddevs(self, C, mag, stddev_types, num_sites): """ Return standard deviation as defined in eq.11 page 319. """ std = C['c16'] + np.zeros(num_sites) if mag < 7.4: std -= 0.07 * mag else: std -= 0.518 # only the 'total' standard d...
python
def _get_stddevs(self, C, mag, stddev_types, num_sites): """ Return standard deviation as defined in eq.11 page 319. """ std = C['c16'] + np.zeros(num_sites) if mag < 7.4: std -= 0.07 * mag else: std -= 0.518 # only the 'total' standard d...
[ "def", "_get_stddevs", "(", "self", ",", "C", ",", "mag", ",", "stddev_types", ",", "num_sites", ")", ":", "std", "=", "C", "[", "'c16'", "]", "+", "np", ".", "zeros", "(", "num_sites", ")", "if", "mag", "<", "7.4", ":", "std", "-=", "0.07", "*",...
Return standard deviation as defined in eq.11 page 319.
[ "Return", "standard", "deviation", "as", "defined", "in", "eq", ".", "11", "page", "319", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2003.py#L112-L127
train
gem/oq-engine
openquake/baselib/general.py
distinct
def distinct(keys): """ Return the distinct keys in order. """ known = set() outlist = [] for key in keys: if key not in known: outlist.append(key) known.add(key) return outlist
python
def distinct(keys): """ Return the distinct keys in order. """ known = set() outlist = [] for key in keys: if key not in known: outlist.append(key) known.add(key) return outlist
[ "def", "distinct", "(", "keys", ")", ":", "known", "=", "set", "(", ")", "outlist", "=", "[", "]", "for", "key", "in", "keys", ":", "if", "key", "not", "in", "known", ":", "outlist", ".", "append", "(", "key", ")", "known", ".", "add", "(", "ke...
Return the distinct keys in order.
[ "Return", "the", "distinct", "keys", "in", "order", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L171-L181
train
gem/oq-engine
openquake/baselib/general.py
split_in_blocks
def split_in_blocks(sequence, hint, weight=lambda item: 1, key=nokey): """ Split the `sequence` in a number of WeightedSequences close to `hint`. :param sequence: a finite sequence of items :param hint: an integer suggesting the number of subsequences to generate :param weight: a function returning...
python
def split_in_blocks(sequence, hint, weight=lambda item: 1, key=nokey): """ Split the `sequence` in a number of WeightedSequences close to `hint`. :param sequence: a finite sequence of items :param hint: an integer suggesting the number of subsequences to generate :param weight: a function returning...
[ "def", "split_in_blocks", "(", "sequence", ",", "hint", ",", "weight", "=", "lambda", "item", ":", "1", ",", "key", "=", "nokey", ")", ":", "if", "isinstance", "(", "sequence", ",", "int", ")", ":", "return", "split_in_slices", "(", "sequence", ",", "h...
Split the `sequence` in a number of WeightedSequences close to `hint`. :param sequence: a finite sequence of items :param hint: an integer suggesting the number of subsequences to generate :param weight: a function returning the weigth of a given item :param key: a function returning the key of a given...
[ "Split", "the", "sequence", "in", "a", "number", "of", "WeightedSequences", "close", "to", "hint", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L274-L304
train
gem/oq-engine
openquake/baselib/general.py
gettemp
def gettemp(content=None, dir=None, prefix="tmp", suffix="tmp"): """Create temporary file with the given content. Please note: the temporary file must be deleted by the caller. :param string content: the content to write to the temporary file. :param string dir: directory where the file should be crea...
python
def gettemp(content=None, dir=None, prefix="tmp", suffix="tmp"): """Create temporary file with the given content. Please note: the temporary file must be deleted by the caller. :param string content: the content to write to the temporary file. :param string dir: directory where the file should be crea...
[ "def", "gettemp", "(", "content", "=", "None", ",", "dir", "=", "None", ",", "prefix", "=", "\"tmp\"", ",", "suffix", "=", "\"tmp\"", ")", ":", "if", "dir", "is", "not", "None", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dir", ")",...
Create temporary file with the given content. Please note: the temporary file must be deleted by the caller. :param string content: the content to write to the temporary file. :param string dir: directory where the file should be created :param string prefix: file name prefix :param string suffix:...
[ "Create", "temporary", "file", "with", "the", "given", "content", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L356-L378
train
gem/oq-engine
openquake/baselib/general.py
removetmp
def removetmp(): """ Remove the temporary files created by gettemp """ for path in _tmp_paths: if os.path.exists(path): # not removed yet try: os.remove(path) except PermissionError: pass
python
def removetmp(): """ Remove the temporary files created by gettemp """ for path in _tmp_paths: if os.path.exists(path): # not removed yet try: os.remove(path) except PermissionError: pass
[ "def", "removetmp", "(", ")", ":", "for", "path", "in", "_tmp_paths", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "# not removed yet", "try", ":", "os", ".", "remove", "(", "path", ")", "except", "PermissionError", ":", "pass" ]
Remove the temporary files created by gettemp
[ "Remove", "the", "temporary", "files", "created", "by", "gettemp" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L382-L391
train
gem/oq-engine
openquake/baselib/general.py
run_in_process
def run_in_process(code, *args): """ Run in an external process the given Python code and return the output as a Python object. If there are arguments, then code is taken as a template and traditional string interpolation is performed. :param code: string or template describing Python code :par...
python
def run_in_process(code, *args): """ Run in an external process the given Python code and return the output as a Python object. If there are arguments, then code is taken as a template and traditional string interpolation is performed. :param code: string or template describing Python code :par...
[ "def", "run_in_process", "(", "code", ",", "*", "args", ")", ":", "if", "args", ":", "code", "%=", "args", "try", ":", "out", "=", "subprocess", ".", "check_output", "(", "[", "sys", ".", "executable", ",", "'-c'", ",", "code", "]", ")", "except", ...
Run in an external process the given Python code and return the output as a Python object. If there are arguments, then code is taken as a template and traditional string interpolation is performed. :param code: string or template describing Python code :param args: arguments to be used for interpolati...
[ "Run", "in", "an", "external", "process", "the", "given", "Python", "code", "and", "return", "the", "output", "as", "a", "Python", "object", ".", "If", "there", "are", "arguments", "then", "code", "is", "taken", "as", "a", "template", "and", "traditional",...
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L422-L440
train
gem/oq-engine
openquake/baselib/general.py
import_all
def import_all(module_or_package): """ If `module_or_package` is a module, just import it; if it is a package, recursively imports all the modules it contains. Returns the names of the modules that were imported as a set. The set can be empty if the modules were already in sys.modules. """ a...
python
def import_all(module_or_package): """ If `module_or_package` is a module, just import it; if it is a package, recursively imports all the modules it contains. Returns the names of the modules that were imported as a set. The set can be empty if the modules were already in sys.modules. """ a...
[ "def", "import_all", "(", "module_or_package", ")", ":", "already_imported", "=", "set", "(", "sys", ".", "modules", ")", "mod_or_pkg", "=", "importlib", ".", "import_module", "(", "module_or_package", ")", "if", "not", "hasattr", "(", "mod_or_pkg", ",", "'__p...
If `module_or_package` is a module, just import it; if it is a package, recursively imports all the modules it contains. Returns the names of the modules that were imported as a set. The set can be empty if the modules were already in sys.modules.
[ "If", "module_or_package", "is", "a", "module", "just", "import", "it", ";", "if", "it", "is", "a", "package", "recursively", "imports", "all", "the", "modules", "it", "contains", ".", "Returns", "the", "names", "of", "the", "modules", "that", "were", "imp...
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L447-L472
train
gem/oq-engine
openquake/baselib/general.py
get_array
def get_array(array, **kw): """ Extract a subarray by filtering on the given keyword arguments """ for name, value in kw.items(): array = array[array[name] == value] return array
python
def get_array(array, **kw): """ Extract a subarray by filtering on the given keyword arguments """ for name, value in kw.items(): array = array[array[name] == value] return array
[ "def", "get_array", "(", "array", ",", "*", "*", "kw", ")", ":", "for", "name", ",", "value", "in", "kw", ".", "items", "(", ")", ":", "array", "=", "array", "[", "array", "[", "name", "]", "==", "value", "]", "return", "array" ]
Extract a subarray by filtering on the given keyword arguments
[ "Extract", "a", "subarray", "by", "filtering", "on", "the", "given", "keyword", "arguments" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L890-L896
train
gem/oq-engine
openquake/baselib/general.py
not_equal
def not_equal(array_or_none1, array_or_none2): """ Compare two arrays that can also be None or have diffent shapes and returns a boolean. >>> a1 = numpy.array([1]) >>> a2 = numpy.array([2]) >>> a3 = numpy.array([2, 3]) >>> not_equal(a1, a2) True >>> not_equal(a1, a3) True >>...
python
def not_equal(array_or_none1, array_or_none2): """ Compare two arrays that can also be None or have diffent shapes and returns a boolean. >>> a1 = numpy.array([1]) >>> a2 = numpy.array([2]) >>> a3 = numpy.array([2, 3]) >>> not_equal(a1, a2) True >>> not_equal(a1, a3) True >>...
[ "def", "not_equal", "(", "array_or_none1", ",", "array_or_none2", ")", ":", "if", "array_or_none1", "is", "None", "and", "array_or_none2", "is", "None", ":", "return", "False", "elif", "array_or_none1", "is", "None", "and", "array_or_none2", "is", "not", "None",...
Compare two arrays that can also be None or have diffent shapes and returns a boolean. >>> a1 = numpy.array([1]) >>> a2 = numpy.array([2]) >>> a3 = numpy.array([2, 3]) >>> not_equal(a1, a2) True >>> not_equal(a1, a3) True >>> not_equal(a1, None) True
[ "Compare", "two", "arrays", "that", "can", "also", "be", "None", "or", "have", "diffent", "shapes", "and", "returns", "a", "boolean", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L899-L922
train
gem/oq-engine
openquake/baselib/general.py
humansize
def humansize(nbytes, suffixes=('B', 'KB', 'MB', 'GB', 'TB', 'PB')): """ Return file size in a human-friendly format """ if nbytes == 0: return '0 B' i = 0 while nbytes >= 1024 and i < len(suffixes) - 1: nbytes /= 1024. i += 1 f = ('%.2f' % nbytes).rstrip('0').rstrip(...
python
def humansize(nbytes, suffixes=('B', 'KB', 'MB', 'GB', 'TB', 'PB')): """ Return file size in a human-friendly format """ if nbytes == 0: return '0 B' i = 0 while nbytes >= 1024 and i < len(suffixes) - 1: nbytes /= 1024. i += 1 f = ('%.2f' % nbytes).rstrip('0').rstrip(...
[ "def", "humansize", "(", "nbytes", ",", "suffixes", "=", "(", "'B'", ",", "'KB'", ",", "'MB'", ",", "'GB'", ",", "'TB'", ",", "'PB'", ")", ")", ":", "if", "nbytes", "==", "0", ":", "return", "'0 B'", "i", "=", "0", "while", "nbytes", ">=", "1024"...
Return file size in a human-friendly format
[ "Return", "file", "size", "in", "a", "human", "-", "friendly", "format" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L925-L936
train
gem/oq-engine
openquake/baselib/general.py
deprecated
def deprecated(func, msg='', *args, **kw): """ A family of decorators to mark deprecated functions. :param msg: the message to print the first time the deprecated function is used. Here is an example of usage: >>> @deprecated(msg='Use new_function instead') ... def old_functio...
python
def deprecated(func, msg='', *args, **kw): """ A family of decorators to mark deprecated functions. :param msg: the message to print the first time the deprecated function is used. Here is an example of usage: >>> @deprecated(msg='Use new_function instead') ... def old_functio...
[ "def", "deprecated", "(", "func", ",", "msg", "=", "''", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "msg", "=", "'%s.%s has been deprecated. %s'", "%", "(", "func", ".", "__module__", ",", "func", ".", "__name__", ",", "msg", ")", "if", "not", ...
A family of decorators to mark deprecated functions. :param msg: the message to print the first time the deprecated function is used. Here is an example of usage: >>> @deprecated(msg='Use new_function instead') ... def old_function(): ... 'Do something' Notice that if the...
[ "A", "family", "of", "decorators", "to", "mark", "deprecated", "functions", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L947-L970
train
gem/oq-engine
openquake/baselib/general.py
random_histogram
def random_histogram(counts, nbins, seed): """ Distribute a total number of counts on a set of bins homogenously. >>> random_histogram(1, 2, 42) array([1, 0]) >>> random_histogram(100, 5, 42) array([28, 18, 17, 19, 18]) >>> random_histogram(10000, 5, 42) array([2043, 2015, 2050, 1930, 1...
python
def random_histogram(counts, nbins, seed): """ Distribute a total number of counts on a set of bins homogenously. >>> random_histogram(1, 2, 42) array([1, 0]) >>> random_histogram(100, 5, 42) array([28, 18, 17, 19, 18]) >>> random_histogram(10000, 5, 42) array([2043, 2015, 2050, 1930, 1...
[ "def", "random_histogram", "(", "counts", ",", "nbins", ",", "seed", ")", ":", "numpy", ".", "random", ".", "seed", "(", "seed", ")", "return", "numpy", ".", "histogram", "(", "numpy", ".", "random", ".", "random", "(", "counts", ")", ",", "nbins", "...
Distribute a total number of counts on a set of bins homogenously. >>> random_histogram(1, 2, 42) array([1, 0]) >>> random_histogram(100, 5, 42) array([28, 18, 17, 19, 18]) >>> random_histogram(10000, 5, 42) array([2043, 2015, 2050, 1930, 1962])
[ "Distribute", "a", "total", "number", "of", "counts", "on", "a", "set", "of", "bins", "homogenously", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L988-L1000
train
gem/oq-engine
openquake/baselib/general.py
safeprint
def safeprint(*args, **kwargs): """ Convert and print characters using the proper encoding """ new_args = [] # when stdout is redirected to a file, python 2 uses ascii for the writer; # python 3 uses what is configured in the system (i.e. 'utf-8') # if sys.stdout is replaced by a StringIO in...
python
def safeprint(*args, **kwargs): """ Convert and print characters using the proper encoding """ new_args = [] # when stdout is redirected to a file, python 2 uses ascii for the writer; # python 3 uses what is configured in the system (i.e. 'utf-8') # if sys.stdout is replaced by a StringIO in...
[ "def", "safeprint", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "new_args", "=", "[", "]", "# when stdout is redirected to a file, python 2 uses ascii for the writer;", "# python 3 uses what is configured in the system (i.e. 'utf-8')", "# if sys.stdout is replaced by a Str...
Convert and print characters using the proper encoding
[ "Convert", "and", "print", "characters", "using", "the", "proper", "encoding" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L1020-L1033
train
gem/oq-engine
openquake/baselib/general.py
zipfiles
def zipfiles(fnames, archive, mode='w', log=lambda msg: None, cleanup=False): """ Build a zip archive from the given file names. :param fnames: list of path names :param archive: path of the archive """ prefix = len(os.path.commonprefix([os.path.dirname(f) for f in fnames])) with zipfile.Zi...
python
def zipfiles(fnames, archive, mode='w', log=lambda msg: None, cleanup=False): """ Build a zip archive from the given file names. :param fnames: list of path names :param archive: path of the archive """ prefix = len(os.path.commonprefix([os.path.dirname(f) for f in fnames])) with zipfile.Zi...
[ "def", "zipfiles", "(", "fnames", ",", "archive", ",", "mode", "=", "'w'", ",", "log", "=", "lambda", "msg", ":", "None", ",", "cleanup", "=", "False", ")", ":", "prefix", "=", "len", "(", "os", ".", "path", ".", "commonprefix", "(", "[", "os", "...
Build a zip archive from the given file names. :param fnames: list of path names :param archive: path of the archive
[ "Build", "a", "zip", "archive", "from", "the", "given", "file", "names", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L1073-L1089
train
gem/oq-engine
openquake/baselib/general.py
println
def println(msg): """ Convenience function to print messages on a single line in the terminal """ sys.stdout.write(msg) sys.stdout.flush() sys.stdout.write('\x08' * len(msg)) sys.stdout.flush()
python
def println(msg): """ Convenience function to print messages on a single line in the terminal """ sys.stdout.write(msg) sys.stdout.flush() sys.stdout.write('\x08' * len(msg)) sys.stdout.flush()
[ "def", "println", "(", "msg", ")", ":", "sys", ".", "stdout", ".", "write", "(", "msg", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stdout", ".", "write", "(", "'\\x08'", "*", "len", "(", "msg", ")", ")", "sys", ".", "stdout...
Convenience function to print messages on a single line in the terminal
[ "Convenience", "function", "to", "print", "messages", "on", "a", "single", "line", "in", "the", "terminal" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L1108-L1115
train
gem/oq-engine
openquake/baselib/general.py
warn
def warn(msg, *args): """ Print a warning on stderr """ if not args: sys.stderr.write('WARNING: ' + msg) else: sys.stderr.write('WARNING: ' + msg % args)
python
def warn(msg, *args): """ Print a warning on stderr """ if not args: sys.stderr.write('WARNING: ' + msg) else: sys.stderr.write('WARNING: ' + msg % args)
[ "def", "warn", "(", "msg", ",", "*", "args", ")", ":", "if", "not", "args", ":", "sys", ".", "stderr", ".", "write", "(", "'WARNING: '", "+", "msg", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "'WARNING: '", "+", "msg", "%", "args"...
Print a warning on stderr
[ "Print", "a", "warning", "on", "stderr" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L1131-L1138
train
gem/oq-engine
openquake/baselib/general.py
WeightedSequence.insert
def insert(self, i, item_weight): """ Insert an item with the given weight in the sequence """ item, weight = item_weight self._seq.insert(i, item) self.weight += weight
python
def insert(self, i, item_weight): """ Insert an item with the given weight in the sequence """ item, weight = item_weight self._seq.insert(i, item) self.weight += weight
[ "def", "insert", "(", "self", ",", "i", ",", "item_weight", ")", ":", "item", ",", "weight", "=", "item_weight", "self", ".", "_seq", ".", "insert", "(", "i", ",", "item", ")", "self", ".", "weight", "+=", "weight" ]
Insert an item with the given weight in the sequence
[ "Insert", "an", "item", "with", "the", "given", "weight", "in", "the", "sequence" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L143-L149
train
gem/oq-engine
openquake/baselib/general.py
CallableDict.add
def add(self, *keys): """ Return a decorator registering a new implementation for the CallableDict for the given keys. """ def decorator(func): for key in keys: self[key] = func return func return decorator
python
def add(self, *keys): """ Return a decorator registering a new implementation for the CallableDict for the given keys. """ def decorator(func): for key in keys: self[key] = func return func return decorator
[ "def", "add", "(", "self", ",", "*", "keys", ")", ":", "def", "decorator", "(", "func", ")", ":", "for", "key", "in", "keys", ":", "self", "[", "key", "]", "=", "func", "return", "func", "return", "decorator" ]
Return a decorator registering a new implementation for the CallableDict for the given keys.
[ "Return", "a", "decorator", "registering", "a", "new", "implementation", "for", "the", "CallableDict", "for", "the", "given", "keys", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/general.py#L542-L551
train
gem/oq-engine
openquake/hazardlib/gsim/bindi_2014.py
BindiEtAl2014Rjb._get_magnitude_scaling_term
def _get_magnitude_scaling_term(self, C, mag): """ Returns the magnitude scaling term of the GMPE described in equation 3 """ dmag = mag - self.CONSTS["Mh"] if mag < self.CONSTS["Mh"]: return C["e1"] + (C["b1"] * dmag) + (C["b2"] * (dmag ** 2.0)) else:...
python
def _get_magnitude_scaling_term(self, C, mag): """ Returns the magnitude scaling term of the GMPE described in equation 3 """ dmag = mag - self.CONSTS["Mh"] if mag < self.CONSTS["Mh"]: return C["e1"] + (C["b1"] * dmag) + (C["b2"] * (dmag ** 2.0)) else:...
[ "def", "_get_magnitude_scaling_term", "(", "self", ",", "C", ",", "mag", ")", ":", "dmag", "=", "mag", "-", "self", ".", "CONSTS", "[", "\"Mh\"", "]", "if", "mag", "<", "self", ".", "CONSTS", "[", "\"Mh\"", "]", ":", "return", "C", "[", "\"e1\"", "...
Returns the magnitude scaling term of the GMPE described in equation 3
[ "Returns", "the", "magnitude", "scaling", "term", "of", "the", "GMPE", "described", "in", "equation", "3" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bindi_2014.py#L125-L134
train
gem/oq-engine
openquake/hazardlib/gsim/bindi_2014.py
BindiEtAl2014Rjb._get_distance_scaling_term
def _get_distance_scaling_term(self, C, rval, mag): """ Returns the distance scaling term of the GMPE described in equation 2 """ r_adj = np.sqrt(rval ** 2.0 + C["h"] ** 2.0) return ( (C["c1"] + C["c2"] * (mag - self.CONSTS["Mref"])) * np.log10(r_adj / sel...
python
def _get_distance_scaling_term(self, C, rval, mag): """ Returns the distance scaling term of the GMPE described in equation 2 """ r_adj = np.sqrt(rval ** 2.0 + C["h"] ** 2.0) return ( (C["c1"] + C["c2"] * (mag - self.CONSTS["Mref"])) * np.log10(r_adj / sel...
[ "def", "_get_distance_scaling_term", "(", "self", ",", "C", ",", "rval", ",", "mag", ")", ":", "r_adj", "=", "np", ".", "sqrt", "(", "rval", "**", "2.0", "+", "C", "[", "\"h\"", "]", "**", "2.0", ")", "return", "(", "(", "C", "[", "\"c1\"", "]", ...
Returns the distance scaling term of the GMPE described in equation 2
[ "Returns", "the", "distance", "scaling", "term", "of", "the", "GMPE", "described", "in", "equation", "2" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bindi_2014.py#L136-L144
train
gem/oq-engine
openquake/hazardlib/gsim/bindi_2014.py
BindiEtAl2014Rjb._get_site_amplification_term
def _get_site_amplification_term(self, C, vs30): """ Returns the site amplification term for the case in which Vs30 is used directly """ return C["gamma"] * np.log10(vs30 / self.CONSTS["Vref"])
python
def _get_site_amplification_term(self, C, vs30): """ Returns the site amplification term for the case in which Vs30 is used directly """ return C["gamma"] * np.log10(vs30 / self.CONSTS["Vref"])
[ "def", "_get_site_amplification_term", "(", "self", ",", "C", ",", "vs30", ")", ":", "return", "C", "[", "\"gamma\"", "]", "*", "np", ".", "log10", "(", "vs30", "/", "self", ".", "CONSTS", "[", "\"Vref\"", "]", ")" ]
Returns the site amplification term for the case in which Vs30 is used directly
[ "Returns", "the", "site", "amplification", "term", "for", "the", "case", "in", "which", "Vs30", "is", "used", "directly" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bindi_2014.py#L169-L174
train
gem/oq-engine
openquake/hazardlib/gsim/bindi_2014.py
BindiEtAl2014RjbEC8._get_site_amplification_term
def _get_site_amplification_term(self, C, vs30): """ Returns the site amplification given Eurocode 8 site classification """ f_s = np.zeros_like(vs30) # Site class B idx = np.logical_and(vs30 < 800.0, vs30 >= 360.0) f_s[idx] = C["eB"] # Site Class C ...
python
def _get_site_amplification_term(self, C, vs30): """ Returns the site amplification given Eurocode 8 site classification """ f_s = np.zeros_like(vs30) # Site class B idx = np.logical_and(vs30 < 800.0, vs30 >= 360.0) f_s[idx] = C["eB"] # Site Class C ...
[ "def", "_get_site_amplification_term", "(", "self", ",", "C", ",", "vs30", ")", ":", "f_s", "=", "np", ".", "zeros_like", "(", "vs30", ")", "# Site class B", "idx", "=", "np", ".", "logical_and", "(", "vs30", "<", "800.0", ",", "vs30", ">=", "360.0", "...
Returns the site amplification given Eurocode 8 site classification
[ "Returns", "the", "site", "amplification", "given", "Eurocode", "8", "site", "classification" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bindi_2014.py#L234-L248
train
gem/oq-engine
openquake/hazardlib/gsim/bindi_2014.py
BindiEtAl2014RjbEC8NoSOF._get_mean
def _get_mean(self, C, rup, dists, sites): """ Returns the mean value of ground motion - noting that in this case the style-of-faulting term is neglected """ return (self._get_magnitude_scaling_term(C, rup.mag) + self._get_distance_scaling_term(C, dists.rjb, rup.m...
python
def _get_mean(self, C, rup, dists, sites): """ Returns the mean value of ground motion - noting that in this case the style-of-faulting term is neglected """ return (self._get_magnitude_scaling_term(C, rup.mag) + self._get_distance_scaling_term(C, dists.rjb, rup.m...
[ "def", "_get_mean", "(", "self", ",", "C", ",", "rup", ",", "dists", ",", "sites", ")", ":", "return", "(", "self", ".", "_get_magnitude_scaling_term", "(", "C", ",", "rup", ".", "mag", ")", "+", "self", ".", "_get_distance_scaling_term", "(", "C", ","...
Returns the mean value of ground motion - noting that in this case the style-of-faulting term is neglected
[ "Returns", "the", "mean", "value", "of", "ground", "motion", "-", "noting", "that", "in", "this", "case", "the", "style", "-", "of", "-", "faulting", "term", "is", "neglected" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bindi_2014.py#L290-L297
train
gem/oq-engine
openquake/calculators/event_based_risk.py
build_loss_tables
def build_loss_tables(dstore): """ Compute the total losses by rupture and losses by rlzi. """ oq = dstore['oqparam'] L = len(oq.loss_dt().names) R = dstore['csm_info'].get_num_rlzs() serials = dstore['ruptures']['serial'] idx_by_ser = dict(zip(serials, range(len(serials)))) tbl = nu...
python
def build_loss_tables(dstore): """ Compute the total losses by rupture and losses by rlzi. """ oq = dstore['oqparam'] L = len(oq.loss_dt().names) R = dstore['csm_info'].get_num_rlzs() serials = dstore['ruptures']['serial'] idx_by_ser = dict(zip(serials, range(len(serials)))) tbl = nu...
[ "def", "build_loss_tables", "(", "dstore", ")", ":", "oq", "=", "dstore", "[", "'oqparam'", "]", "L", "=", "len", "(", "oq", ".", "loss_dt", "(", ")", ".", "names", ")", "R", "=", "dstore", "[", "'csm_info'", "]", ".", "get_num_rlzs", "(", ")", "se...
Compute the total losses by rupture and losses by rlzi.
[ "Compute", "the", "total", "losses", "by", "rupture", "and", "losses", "by", "rlzi", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/event_based_risk.py#L39-L54
train
gem/oq-engine
openquake/engine/tools/make_html_report.py
html
def html(header_rows): """ Convert a list of tuples describing a table into a HTML string """ name = 'table%d' % next(tablecounter) return HtmlTable([map(str, row) for row in header_rows], name).render()
python
def html(header_rows): """ Convert a list of tuples describing a table into a HTML string """ name = 'table%d' % next(tablecounter) return HtmlTable([map(str, row) for row in header_rows], name).render()
[ "def", "html", "(", "header_rows", ")", ":", "name", "=", "'table%d'", "%", "next", "(", "tablecounter", ")", "return", "HtmlTable", "(", "[", "map", "(", "str", ",", "row", ")", "for", "row", "in", "header_rows", "]", ",", "name", ")", ".", "render"...
Convert a list of tuples describing a table into a HTML string
[ "Convert", "a", "list", "of", "tuples", "describing", "a", "table", "into", "a", "HTML", "string" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/tools/make_html_report.py#L34-L39
train
gem/oq-engine
openquake/engine/tools/make_html_report.py
make_tabs
def make_tabs(tag_ids, tag_status, tag_contents): """ Return a HTML string containing all the tabs we want to display """ templ = ''' <div id="tabs"> <ul> %s </ul> %s </div>''' lis = [] contents = [] for i, (tag_id, status, tag_content) in enumerate( zip(tag_ids, tag_status, tag_...
python
def make_tabs(tag_ids, tag_status, tag_contents): """ Return a HTML string containing all the tabs we want to display """ templ = ''' <div id="tabs"> <ul> %s </ul> %s </div>''' lis = [] contents = [] for i, (tag_id, status, tag_content) in enumerate( zip(tag_ids, tag_status, tag_...
[ "def", "make_tabs", "(", "tag_ids", ",", "tag_status", ",", "tag_contents", ")", ":", "templ", "=", "'''\n<div id=\"tabs\">\n<ul>\n%s\n</ul>\n%s\n</div>'''", "lis", "=", "[", "]", "contents", "=", "[", "]", "for", "i", ",", "(", "tag_id", ",", "status", ",", ...
Return a HTML string containing all the tabs we want to display
[ "Return", "a", "HTML", "string", "containing", "all", "the", "tabs", "we", "want", "to", "display" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/tools/make_html_report.py#L125-L144
train
gem/oq-engine
openquake/engine/tools/make_html_report.py
make_report
def make_report(isodate='today'): """ Build a HTML report with the computations performed at the given isodate. Return the name of the report, which is saved in the current directory. """ if isodate == 'today': isodate = date.today() else: isodate = date(*time.strptime(isodate, '...
python
def make_report(isodate='today'): """ Build a HTML report with the computations performed at the given isodate. Return the name of the report, which is saved in the current directory. """ if isodate == 'today': isodate = date.today() else: isodate = date(*time.strptime(isodate, '...
[ "def", "make_report", "(", "isodate", "=", "'today'", ")", ":", "if", "isodate", "==", "'today'", ":", "isodate", "=", "date", ".", "today", "(", ")", "else", ":", "isodate", "=", "date", "(", "*", "time", ".", "strptime", "(", "isodate", ",", "'%Y-%...
Build a HTML report with the computations performed at the given isodate. Return the name of the report, which is saved in the current directory.
[ "Build", "a", "HTML", "report", "with", "the", "computations", "performed", "at", "the", "given", "isodate", ".", "Return", "the", "name", "of", "the", "report", "which", "is", "saved", "in", "the", "current", "directory", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/tools/make_html_report.py#L147-L191
train
gem/oq-engine
openquake/calculators/scenario_risk.py
scenario_risk
def scenario_risk(riskinputs, riskmodel, param, monitor): """ Core function for a scenario computation. :param riskinput: a of :class:`openquake.risklib.riskinput.RiskInput` object :param riskmodel: a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance :param param: ...
python
def scenario_risk(riskinputs, riskmodel, param, monitor): """ Core function for a scenario computation. :param riskinput: a of :class:`openquake.risklib.riskinput.RiskInput` object :param riskmodel: a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance :param param: ...
[ "def", "scenario_risk", "(", "riskinputs", ",", "riskmodel", ",", "param", ",", "monitor", ")", ":", "E", "=", "param", "[", "'E'", "]", "L", "=", "len", "(", "riskmodel", ".", "loss_types", ")", "result", "=", "dict", "(", "agg", "=", "numpy", ".", ...
Core function for a scenario computation. :param riskinput: a of :class:`openquake.risklib.riskinput.RiskInput` object :param riskmodel: a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance :param param: dictionary of extra parameters :param monitor: :class...
[ "Core", "function", "for", "a", "scenario", "computation", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/scenario_risk.py#L38-L82
train
gem/oq-engine
openquake/hmtk/seismicity/selector.py
_check_depth_limits
def _check_depth_limits(input_dict): '''Returns the default upper and lower depth values if not in dictionary :param input_dict: Dictionary corresponding to the kwargs dictionary of calling function :returns: 'upper_depth': Upper seismogenic depth (float) 'lower_depth': Lower seism...
python
def _check_depth_limits(input_dict): '''Returns the default upper and lower depth values if not in dictionary :param input_dict: Dictionary corresponding to the kwargs dictionary of calling function :returns: 'upper_depth': Upper seismogenic depth (float) 'lower_depth': Lower seism...
[ "def", "_check_depth_limits", "(", "input_dict", ")", ":", "if", "(", "'upper_depth'", "in", "input_dict", ".", "keys", "(", ")", ")", "and", "input_dict", "[", "'upper_depth'", "]", ":", "if", "input_dict", "[", "'upper_depth'", "]", "<", "0.", ":", "rais...
Returns the default upper and lower depth values if not in dictionary :param input_dict: Dictionary corresponding to the kwargs dictionary of calling function :returns: 'upper_depth': Upper seismogenic depth (float) 'lower_depth': Lower seismogenic depth (float)
[ "Returns", "the", "default", "upper", "and", "lower", "depth", "values", "if", "not", "in", "dictionary" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L63-L89
train
gem/oq-engine
openquake/hmtk/seismicity/selector.py
_get_decimal_from_datetime
def _get_decimal_from_datetime(time): ''' As the decimal time function requires inputs in the form of numpy arrays need to convert each value in the datetime object to a single numpy array ''' # Get decimal seconds from seconds + microseconds temp_seconds = np.float(time.second) + (np.floa...
python
def _get_decimal_from_datetime(time): ''' As the decimal time function requires inputs in the form of numpy arrays need to convert each value in the datetime object to a single numpy array ''' # Get decimal seconds from seconds + microseconds temp_seconds = np.float(time.second) + (np.floa...
[ "def", "_get_decimal_from_datetime", "(", "time", ")", ":", "# Get decimal seconds from seconds + microseconds", "temp_seconds", "=", "np", ".", "float", "(", "time", ".", "second", ")", "+", "(", "np", ".", "float", "(", "time", ".", "microsecond", ")", "/", ...
As the decimal time function requires inputs in the form of numpy arrays need to convert each value in the datetime object to a single numpy array
[ "As", "the", "decimal", "time", "function", "requires", "inputs", "in", "the", "form", "of", "numpy", "arrays", "need", "to", "convert", "each", "value", "in", "the", "datetime", "object", "to", "a", "single", "numpy", "array" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L92-L106
train
gem/oq-engine
openquake/hmtk/seismicity/selector.py
CatalogueSelector.select_catalogue
def select_catalogue(self, valid_id): ''' Method to post-process the catalogue based on the selection options :param numpy.ndarray valid_id: Boolean vector indicating whether each event is selected (True) or not (False) :returns: Catalogue of selecte...
python
def select_catalogue(self, valid_id): ''' Method to post-process the catalogue based on the selection options :param numpy.ndarray valid_id: Boolean vector indicating whether each event is selected (True) or not (False) :returns: Catalogue of selecte...
[ "def", "select_catalogue", "(", "self", ",", "valid_id", ")", ":", "if", "not", "np", ".", "any", "(", "valid_id", ")", ":", "# No events selected - create clean instance of class", "output", "=", "Catalogue", "(", ")", "output", ".", "processes", "=", "self", ...
Method to post-process the catalogue based on the selection options :param numpy.ndarray valid_id: Boolean vector indicating whether each event is selected (True) or not (False) :returns: Catalogue of selected events as instance of openquake.hmtk.seismic...
[ "Method", "to", "post", "-", "process", "the", "catalogue", "based", "on", "the", "selection", "options" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L133-L161
train
gem/oq-engine
openquake/hmtk/seismicity/selector.py
CatalogueSelector.within_polygon
def within_polygon(self, polygon, distance=None, **kwargs): ''' Select earthquakes within polygon :param polygon: Centre point as instance of nhlib.geo.polygon.Polygon class :param float distance: Buffer distance (km) (can take negative values) :returns...
python
def within_polygon(self, polygon, distance=None, **kwargs): ''' Select earthquakes within polygon :param polygon: Centre point as instance of nhlib.geo.polygon.Polygon class :param float distance: Buffer distance (km) (can take negative values) :returns...
[ "def", "within_polygon", "(", "self", ",", "polygon", ",", "distance", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "distance", ":", "# If a distance is specified then dilate the polyon by distance", "zone_polygon", "=", "polygon", ".", "dilate", "(", "di...
Select earthquakes within polygon :param polygon: Centre point as instance of nhlib.geo.polygon.Polygon class :param float distance: Buffer distance (km) (can take negative values) :returns: Instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue`...
[ "Select", "earthquakes", "within", "polygon" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L163-L197
train
gem/oq-engine
openquake/hmtk/seismicity/selector.py
CatalogueSelector.circular_distance_from_point
def circular_distance_from_point(self, point, distance, **kwargs): ''' Select earthquakes within a distance from a Point :param point: Centre point as instance of nhlib.geo.point.Point class :param float distance: Distance (km) :returns: Ins...
python
def circular_distance_from_point(self, point, distance, **kwargs): ''' Select earthquakes within a distance from a Point :param point: Centre point as instance of nhlib.geo.point.Point class :param float distance: Distance (km) :returns: Ins...
[ "def", "circular_distance_from_point", "(", "self", ",", "point", ",", "distance", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", "[", "'distance_type'", "]", "is", "'epicentral'", ":", "locations", "=", "Mesh", "(", "self", ".", "catalogue", ".", "dat...
Select earthquakes within a distance from a Point :param point: Centre point as instance of nhlib.geo.point.Point class :param float distance: Distance (km) :returns: Instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue` containing ...
[ "Select", "earthquakes", "within", "a", "distance", "from", "a", "Point" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L199-L225
train
gem/oq-engine
openquake/hmtk/seismicity/selector.py
CatalogueSelector.cartesian_square_centred_on_point
def cartesian_square_centred_on_point(self, point, distance, **kwargs): ''' Select earthquakes from within a square centered on a point :param point: Centre point as instance of nhlib.geo.point.Point class :param distance: Distance (km) :returns: ...
python
def cartesian_square_centred_on_point(self, point, distance, **kwargs): ''' Select earthquakes from within a square centered on a point :param point: Centre point as instance of nhlib.geo.point.Point class :param distance: Distance (km) :returns: ...
[ "def", "cartesian_square_centred_on_point", "(", "self", ",", "point", ",", "distance", ",", "*", "*", "kwargs", ")", ":", "point_surface", "=", "Point", "(", "point", ".", "longitude", ",", "point", ".", "latitude", ",", "0.", ")", "# As distance is", "nort...
Select earthquakes from within a square centered on a point :param point: Centre point as instance of nhlib.geo.point.Point class :param distance: Distance (km) :returns: Instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue` class c...
[ "Select", "earthquakes", "from", "within", "a", "square", "centered", "on", "a", "point" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L227-L261
train
gem/oq-engine
openquake/hmtk/seismicity/selector.py
CatalogueSelector.within_joyner_boore_distance
def within_joyner_boore_distance(self, surface, distance, **kwargs): ''' Select events within a Joyner-Boore distance of a fault :param surface: Fault surface as instance of nhlib.geo.surface.base.SimpleFaultSurface or as instance of nhlib.geo.surface.Comple...
python
def within_joyner_boore_distance(self, surface, distance, **kwargs): ''' Select events within a Joyner-Boore distance of a fault :param surface: Fault surface as instance of nhlib.geo.surface.base.SimpleFaultSurface or as instance of nhlib.geo.surface.Comple...
[ "def", "within_joyner_boore_distance", "(", "self", ",", "surface", ",", "distance", ",", "*", "*", "kwargs", ")", ":", "upper_depth", ",", "lower_depth", "=", "_check_depth_limits", "(", "kwargs", ")", "rjb", "=", "surface", ".", "get_joyner_boore_distance", "(...
Select events within a Joyner-Boore distance of a fault :param surface: Fault surface as instance of nhlib.geo.surface.base.SimpleFaultSurface or as instance of nhlib.geo.surface.ComplexFaultSurface :param float distance: Rupture distance (km) ...
[ "Select", "events", "within", "a", "Joyner", "-", "Boore", "distance", "of", "a", "fault" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L263-L288
train
gem/oq-engine
openquake/hmtk/seismicity/selector.py
CatalogueSelector.within_rupture_distance
def within_rupture_distance(self, surface, distance, **kwargs): ''' Select events within a rupture distance from a fault surface :param surface: Fault surface as instance of nhlib.geo.surface.base.BaseSurface :param float distance: Rupture distance (km) ...
python
def within_rupture_distance(self, surface, distance, **kwargs): ''' Select events within a rupture distance from a fault surface :param surface: Fault surface as instance of nhlib.geo.surface.base.BaseSurface :param float distance: Rupture distance (km) ...
[ "def", "within_rupture_distance", "(", "self", ",", "surface", ",", "distance", ",", "*", "*", "kwargs", ")", ":", "# Check for upper and lower depths", "upper_depth", ",", "lower_depth", "=", "_check_depth_limits", "(", "kwargs", ")", "rrupt", "=", "surface", "."...
Select events within a rupture distance from a fault surface :param surface: Fault surface as instance of nhlib.geo.surface.base.BaseSurface :param float distance: Rupture distance (km) :returns: Instance of :class:`openquake.hmtk.seismicity.catalogue.Catal...
[ "Select", "events", "within", "a", "rupture", "distance", "from", "a", "fault", "surface" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L290-L313
train
gem/oq-engine
openquake/hmtk/seismicity/selector.py
CatalogueSelector.within_time_period
def within_time_period(self, start_time=None, end_time=None): ''' Select earthquakes occurring within a given time period :param start_time: Earliest time (as datetime.datetime object) :param end_time: Latest time (as datetime.datetime object) :returns:...
python
def within_time_period(self, start_time=None, end_time=None): ''' Select earthquakes occurring within a given time period :param start_time: Earliest time (as datetime.datetime object) :param end_time: Latest time (as datetime.datetime object) :returns:...
[ "def", "within_time_period", "(", "self", ",", "start_time", "=", "None", ",", "end_time", "=", "None", ")", ":", "time_value", "=", "self", ".", "catalogue", ".", "get_decimal_time", "(", ")", "if", "not", "start_time", ":", "if", "not", "end_time", ":", ...
Select earthquakes occurring within a given time period :param start_time: Earliest time (as datetime.datetime object) :param end_time: Latest time (as datetime.datetime object) :returns: Instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue` ...
[ "Select", "earthquakes", "occurring", "within", "a", "given", "time", "period" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L315-L350
train
gem/oq-engine
openquake/hmtk/seismicity/selector.py
CatalogueSelector.within_depth_range
def within_depth_range(self, lower_depth=None, upper_depth=None): ''' Selects events within a specified depth range :param float lower_depth: Lower depth for consideration :param float upper_depth: Upper depth for consideration :returns: Ins...
python
def within_depth_range(self, lower_depth=None, upper_depth=None): ''' Selects events within a specified depth range :param float lower_depth: Lower depth for consideration :param float upper_depth: Upper depth for consideration :returns: Ins...
[ "def", "within_depth_range", "(", "self", ",", "lower_depth", "=", "None", ",", "upper_depth", "=", "None", ")", ":", "if", "not", "lower_depth", ":", "if", "not", "upper_depth", ":", "# No limiting depths defined - so return entire catalogue!", "return", "self", "....
Selects events within a specified depth range :param float lower_depth: Lower depth for consideration :param float upper_depth: Upper depth for consideration :returns: Instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue` containing...
[ "Selects", "events", "within", "a", "specified", "depth", "range" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L352-L378
train
gem/oq-engine
openquake/hmtk/seismicity/selector.py
CatalogueSelector.create_cluster_set
def create_cluster_set(self, vcl): """ For a given catalogue and list of cluster IDs this function splits the catalogue into a dictionary containing an individual catalogue of events within each cluster :param numpy.ndarray vcl: Cluster ID list :returns: ...
python
def create_cluster_set(self, vcl): """ For a given catalogue and list of cluster IDs this function splits the catalogue into a dictionary containing an individual catalogue of events within each cluster :param numpy.ndarray vcl: Cluster ID list :returns: ...
[ "def", "create_cluster_set", "(", "self", ",", "vcl", ")", ":", "num_clust", "=", "np", ".", "max", "(", "vcl", ")", "cluster_set", "=", "[", "]", "for", "clid", "in", "range", "(", "0", ",", "num_clust", "+", "1", ")", ":", "idx", "=", "np", "."...
For a given catalogue and list of cluster IDs this function splits the catalogue into a dictionary containing an individual catalogue of events within each cluster :param numpy.ndarray vcl: Cluster ID list :returns: Dictionary of instances of the :class: ...
[ "For", "a", "given", "catalogue", "and", "list", "of", "cluster", "IDs", "this", "function", "splits", "the", "catalogue", "into", "a", "dictionary", "containing", "an", "individual", "catalogue", "of", "events", "within", "each", "cluster" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L408-L428
train
gem/oq-engine
openquake/hmtk/seismicity/selector.py
CatalogueSelector.within_bounding_box
def within_bounding_box(self, limits): """ Selects the earthquakes within a bounding box. :parameter limits: A list or a numpy array with four elements in the following order: - min x (longitude) - min y (latitude) - max x (longitude) ...
python
def within_bounding_box(self, limits): """ Selects the earthquakes within a bounding box. :parameter limits: A list or a numpy array with four elements in the following order: - min x (longitude) - min y (latitude) - max x (longitude) ...
[ "def", "within_bounding_box", "(", "self", ",", "limits", ")", ":", "is_valid", "=", "np", ".", "logical_and", "(", "self", ".", "catalogue", ".", "data", "[", "'longitude'", "]", ">=", "limits", "[", "0", "]", ",", "np", ".", "logical_and", "(", "self...
Selects the earthquakes within a bounding box. :parameter limits: A list or a numpy array with four elements in the following order: - min x (longitude) - min y (latitude) - max x (longitude) - max y (latitude) :returns: ...
[ "Selects", "the", "earthquakes", "within", "a", "bounding", "box", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L430-L449
train
gem/oq-engine
openquake/baselib/datastore.py
get_calc_ids
def get_calc_ids(datadir=None): """ Extract the available calculation IDs from the datadir, in order. """ datadir = datadir or get_datadir() if not os.path.exists(datadir): return [] calc_ids = set() for f in os.listdir(datadir): mo = re.match(CALC_REGEX, f) if mo: ...
python
def get_calc_ids(datadir=None): """ Extract the available calculation IDs from the datadir, in order. """ datadir = datadir or get_datadir() if not os.path.exists(datadir): return [] calc_ids = set() for f in os.listdir(datadir): mo = re.match(CALC_REGEX, f) if mo: ...
[ "def", "get_calc_ids", "(", "datadir", "=", "None", ")", ":", "datadir", "=", "datadir", "or", "get_datadir", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "datadir", ")", ":", "return", "[", "]", "calc_ids", "=", "set", "(", ")", "...
Extract the available calculation IDs from the datadir, in order.
[ "Extract", "the", "available", "calculation", "IDs", "from", "the", "datadir", "in", "order", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/datastore.py#L46-L58
train
gem/oq-engine
openquake/baselib/datastore.py
get_last_calc_id
def get_last_calc_id(datadir=None): """ Extract the latest calculation ID from the given directory. If none is found, return 0. """ datadir = datadir or get_datadir() calcs = get_calc_ids(datadir) if not calcs: return 0 return calcs[-1]
python
def get_last_calc_id(datadir=None): """ Extract the latest calculation ID from the given directory. If none is found, return 0. """ datadir = datadir or get_datadir() calcs = get_calc_ids(datadir) if not calcs: return 0 return calcs[-1]
[ "def", "get_last_calc_id", "(", "datadir", "=", "None", ")", ":", "datadir", "=", "datadir", "or", "get_datadir", "(", ")", "calcs", "=", "get_calc_ids", "(", "datadir", ")", "if", "not", "calcs", ":", "return", "0", "return", "calcs", "[", "-", "1", "...
Extract the latest calculation ID from the given directory. If none is found, return 0.
[ "Extract", "the", "latest", "calculation", "ID", "from", "the", "given", "directory", ".", "If", "none", "is", "found", "return", "0", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/datastore.py#L61-L70
train
gem/oq-engine
openquake/baselib/datastore.py
DataStore.open
def open(self, mode): """ Open the underlying .hdf5 file and the parent, if any """ if self.hdf5 == (): # not already open kw = dict(mode=mode, libver='latest') if mode == 'r': kw['swmr'] = True try: self.hdf5 = hdf5.Fi...
python
def open(self, mode): """ Open the underlying .hdf5 file and the parent, if any """ if self.hdf5 == (): # not already open kw = dict(mode=mode, libver='latest') if mode == 'r': kw['swmr'] = True try: self.hdf5 = hdf5.Fi...
[ "def", "open", "(", "self", ",", "mode", ")", ":", "if", "self", ".", "hdf5", "==", "(", ")", ":", "# not already open", "kw", "=", "dict", "(", "mode", "=", "mode", ",", "libver", "=", "'latest'", ")", "if", "mode", "==", "'r'", ":", "kw", "[", ...
Open the underlying .hdf5 file and the parent, if any
[ "Open", "the", "underlying", ".", "hdf5", "file", "and", "the", "parent", "if", "any" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/datastore.py#L184-L195
train
gem/oq-engine
openquake/baselib/datastore.py
DataStore.create_dset
def create_dset(self, key, dtype, shape=(None,), compression=None, fillvalue=0, attrs=None): """ Create a one-dimensional HDF5 dataset. :param key: name of the dataset :param dtype: dtype of the dataset (usually composite) :param shape: shape of the dataset, ...
python
def create_dset(self, key, dtype, shape=(None,), compression=None, fillvalue=0, attrs=None): """ Create a one-dimensional HDF5 dataset. :param key: name of the dataset :param dtype: dtype of the dataset (usually composite) :param shape: shape of the dataset, ...
[ "def", "create_dset", "(", "self", ",", "key", ",", "dtype", ",", "shape", "=", "(", "None", ",", ")", ",", "compression", "=", "None", ",", "fillvalue", "=", "0", ",", "attrs", "=", "None", ")", ":", "return", "hdf5", ".", "create", "(", "self", ...
Create a one-dimensional HDF5 dataset. :param key: name of the dataset :param dtype: dtype of the dataset (usually composite) :param shape: shape of the dataset, possibly extendable :param compression: the kind of HDF5 compression to use :param attrs: dictionary of attributes of...
[ "Create", "a", "one", "-", "dimensional", "HDF5", "dataset", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/datastore.py#L270-L283
train
gem/oq-engine
openquake/baselib/datastore.py
DataStore.extend
def extend(self, key, array, **attrs): """ Extend the dataset associated to the given key; create it if needed :param key: name of the dataset :param array: array to store :param attrs: a dictionary of attributes """ try: dset = self.hdf5[key] ...
python
def extend(self, key, array, **attrs): """ Extend the dataset associated to the given key; create it if needed :param key: name of the dataset :param array: array to store :param attrs: a dictionary of attributes """ try: dset = self.hdf5[key] ...
[ "def", "extend", "(", "self", ",", "key", ",", "array", ",", "*", "*", "attrs", ")", ":", "try", ":", "dset", "=", "self", ".", "hdf5", "[", "key", "]", "except", "KeyError", ":", "dset", "=", "hdf5", ".", "create", "(", "self", ".", "hdf5", ",...
Extend the dataset associated to the given key; create it if needed :param key: name of the dataset :param array: array to store :param attrs: a dictionary of attributes
[ "Extend", "the", "dataset", "associated", "to", "the", "given", "key", ";", "create", "it", "if", "needed" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/datastore.py#L285-L301
train
gem/oq-engine
openquake/baselib/datastore.py
DataStore.save
def save(self, key, kw): """ Update the object associated to `key` with the `kw` dictionary; works for LiteralAttrs objects and automatically flushes. """ if key not in self: obj = hdf5.LiteralAttrs() else: obj = self[key] vars(obj).update(...
python
def save(self, key, kw): """ Update the object associated to `key` with the `kw` dictionary; works for LiteralAttrs objects and automatically flushes. """ if key not in self: obj = hdf5.LiteralAttrs() else: obj = self[key] vars(obj).update(...
[ "def", "save", "(", "self", ",", "key", ",", "kw", ")", ":", "if", "key", "not", "in", "self", ":", "obj", "=", "hdf5", ".", "LiteralAttrs", "(", ")", "else", ":", "obj", "=", "self", "[", "key", "]", "vars", "(", "obj", ")", ".", "update", "...
Update the object associated to `key` with the `kw` dictionary; works for LiteralAttrs objects and automatically flushes.
[ "Update", "the", "object", "associated", "to", "key", "with", "the", "kw", "dictionary", ";", "works", "for", "LiteralAttrs", "objects", "and", "automatically", "flushes", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/datastore.py#L303-L314
train
gem/oq-engine
openquake/baselib/datastore.py
DataStore.export_path
def export_path(self, relname, export_dir=None): """ Return the path of the exported file by adding the export_dir in front, the calculation ID at the end. :param relname: relative file name :param export_dir: export directory (if None use .export_dir) """ # remo...
python
def export_path(self, relname, export_dir=None): """ Return the path of the exported file by adding the export_dir in front, the calculation ID at the end. :param relname: relative file name :param export_dir: export directory (if None use .export_dir) """ # remo...
[ "def", "export_path", "(", "self", ",", "relname", ",", "export_dir", "=", "None", ")", ":", "# removing inner slashed to avoid creating intermediate directories", "name", ",", "ext", "=", "relname", ".", "replace", "(", "'/'", ",", "'-'", ")", ".", "rsplit", "(...
Return the path of the exported file by adding the export_dir in front, the calculation ID at the end. :param relname: relative file name :param export_dir: export directory (if None use .export_dir)
[ "Return", "the", "path", "of", "the", "exported", "file", "by", "adding", "the", "export_dir", "in", "front", "the", "calculation", "ID", "at", "the", "end", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/datastore.py#L316-L329
train
gem/oq-engine
openquake/baselib/datastore.py
DataStore.build_fname
def build_fname(self, prefix, postfix, fmt, export_dir=None): """ Build a file name from a realization, by using prefix and extension. :param prefix: the prefix to use :param postfix: the postfix to use (can be a realization object) :param fmt: the extension ('csv', 'xml', etc) ...
python
def build_fname(self, prefix, postfix, fmt, export_dir=None): """ Build a file name from a realization, by using prefix and extension. :param prefix: the prefix to use :param postfix: the postfix to use (can be a realization object) :param fmt: the extension ('csv', 'xml', etc) ...
[ "def", "build_fname", "(", "self", ",", "prefix", ",", "postfix", ",", "fmt", ",", "export_dir", "=", "None", ")", ":", "if", "hasattr", "(", "postfix", ",", "'sm_lt_path'", ")", ":", "# is a realization", "fname", "=", "'%s-rlz-%03d.%s'", "%", "(", "prefi...
Build a file name from a realization, by using prefix and extension. :param prefix: the prefix to use :param postfix: the postfix to use (can be a realization object) :param fmt: the extension ('csv', 'xml', etc) :param export_dir: export directory (if None use .export_dir) :ret...
[ "Build", "a", "file", "name", "from", "a", "realization", "by", "using", "prefix", "and", "extension", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/datastore.py#L331-L345
train
gem/oq-engine
openquake/baselib/datastore.py
DataStore.flush
def flush(self): """Flush the underlying hdf5 file""" if self.parent != (): self.parent.flush() if self.hdf5: # is open self.hdf5.flush()
python
def flush(self): """Flush the underlying hdf5 file""" if self.parent != (): self.parent.flush() if self.hdf5: # is open self.hdf5.flush()
[ "def", "flush", "(", "self", ")", ":", "if", "self", ".", "parent", "!=", "(", ")", ":", "self", ".", "parent", ".", "flush", "(", ")", "if", "self", ".", "hdf5", ":", "# is open", "self", ".", "hdf5", ".", "flush", "(", ")" ]
Flush the underlying hdf5 file
[ "Flush", "the", "underlying", "hdf5", "file" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/datastore.py#L347-L352
train
gem/oq-engine
openquake/baselib/datastore.py
DataStore.close
def close(self): """Close the underlying hdf5 file""" if self.parent != (): self.parent.flush() self.parent.close() if self.hdf5: # is open self.hdf5.flush() self.hdf5.close() self.hdf5 = ()
python
def close(self): """Close the underlying hdf5 file""" if self.parent != (): self.parent.flush() self.parent.close() if self.hdf5: # is open self.hdf5.flush() self.hdf5.close() self.hdf5 = ()
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "parent", "!=", "(", ")", ":", "self", ".", "parent", ".", "flush", "(", ")", "self", ".", "parent", ".", "close", "(", ")", "if", "self", ".", "hdf5", ":", "# is open", "self", ".", "hd...
Close the underlying hdf5 file
[ "Close", "the", "underlying", "hdf5", "file" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/datastore.py#L354-L362
train
gem/oq-engine
openquake/baselib/datastore.py
DataStore.getsize
def getsize(self, key=None): """ Return the size in byte of the output associated to the given key. If no key is given, returns the total size of all files. """ if key is None: return os.path.getsize(self.filename) return hdf5.ByteCounter.get_nbytes( ...
python
def getsize(self, key=None): """ Return the size in byte of the output associated to the given key. If no key is given, returns the total size of all files. """ if key is None: return os.path.getsize(self.filename) return hdf5.ByteCounter.get_nbytes( ...
[ "def", "getsize", "(", "self", ",", "key", "=", "None", ")", ":", "if", "key", "is", "None", ":", "return", "os", ".", "path", ".", "getsize", "(", "self", ".", "filename", ")", "return", "hdf5", ".", "ByteCounter", ".", "get_nbytes", "(", "h5py", ...
Return the size in byte of the output associated to the given key. If no key is given, returns the total size of all files.
[ "Return", "the", "size", "in", "byte", "of", "the", "output", "associated", "to", "the", "given", "key", ".", "If", "no", "key", "is", "given", "returns", "the", "total", "size", "of", "all", "files", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/datastore.py#L369-L377
train
gem/oq-engine
openquake/baselib/hdf5.py
maybe_encode
def maybe_encode(value): """ If value is a sequence of strings, encode it """ if isinstance(value, (list, tuple)) and isinstance(value[0], str): return encode(value) return value
python
def maybe_encode(value): """ If value is a sequence of strings, encode it """ if isinstance(value, (list, tuple)) and isinstance(value[0], str): return encode(value) return value
[ "def", "maybe_encode", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", "and", "isinstance", "(", "value", "[", "0", "]", ",", "str", ")", ":", "return", "encode", "(", "value", ")", "return", "val...
If value is a sequence of strings, encode it
[ "If", "value", "is", "a", "sequence", "of", "strings", "encode", "it" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/hdf5.py#L44-L50
train
gem/oq-engine
openquake/baselib/hdf5.py
extend
def extend(dset, array, **attrs): """ Extend an extensible dataset with an array of a compatible dtype. :param dset: an h5py dataset :param array: an array of length L :returns: the total length of the dataset (i.e. initial length + L) """ length = len(dset) if len(array) == 0: ...
python
def extend(dset, array, **attrs): """ Extend an extensible dataset with an array of a compatible dtype. :param dset: an h5py dataset :param array: an array of length L :returns: the total length of the dataset (i.e. initial length + L) """ length = len(dset) if len(array) == 0: ...
[ "def", "extend", "(", "dset", ",", "array", ",", "*", "*", "attrs", ")", ":", "length", "=", "len", "(", "dset", ")", "if", "len", "(", "array", ")", "==", "0", ":", "return", "length", "newlength", "=", "length", "+", "len", "(", "array", ")", ...
Extend an extensible dataset with an array of a compatible dtype. :param dset: an h5py dataset :param array: an array of length L :returns: the total length of the dataset (i.e. initial length + L)
[ "Extend", "an", "extensible", "dataset", "with", "an", "array", "of", "a", "compatible", "dtype", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/hdf5.py#L86-L106
train
gem/oq-engine
openquake/baselib/hdf5.py
extend3
def extend3(filename, key, array, **attrs): """ Extend an HDF5 file dataset with the given array """ with h5py.File(filename) as h5: try: dset = h5[key] except KeyError: if array.dtype.name == 'object': # vlen array shape = (None,) + preshape(arra...
python
def extend3(filename, key, array, **attrs): """ Extend an HDF5 file dataset with the given array """ with h5py.File(filename) as h5: try: dset = h5[key] except KeyError: if array.dtype.name == 'object': # vlen array shape = (None,) + preshape(arra...
[ "def", "extend3", "(", "filename", ",", "key", ",", "array", ",", "*", "*", "attrs", ")", ":", "with", "h5py", ".", "File", "(", "filename", ")", "as", "h5", ":", "try", ":", "dset", "=", "h5", "[", "key", "]", "except", "KeyError", ":", "if", ...
Extend an HDF5 file dataset with the given array
[ "Extend", "an", "HDF5", "file", "dataset", "with", "the", "given", "array" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/hdf5.py#L109-L126
train
gem/oq-engine
openquake/baselib/hdf5.py
get_nbytes
def get_nbytes(dset): """ If the dataset has an attribute 'nbytes', return it. Otherwise get the size of the underlying array. Returns None if the dataset is actually a group. """ if 'nbytes' in dset.attrs: # look if the dataset has an attribute nbytes return dset.attrs['nbytes'] ...
python
def get_nbytes(dset): """ If the dataset has an attribute 'nbytes', return it. Otherwise get the size of the underlying array. Returns None if the dataset is actually a group. """ if 'nbytes' in dset.attrs: # look if the dataset has an attribute nbytes return dset.attrs['nbytes'] ...
[ "def", "get_nbytes", "(", "dset", ")", ":", "if", "'nbytes'", "in", "dset", ".", "attrs", ":", "# look if the dataset has an attribute nbytes", "return", "dset", ".", "attrs", "[", "'nbytes'", "]", "elif", "hasattr", "(", "dset", ",", "'dtype'", ")", ":", "#...
If the dataset has an attribute 'nbytes', return it. Otherwise get the size of the underlying array. Returns None if the dataset is actually a group.
[ "If", "the", "dataset", "has", "an", "attribute", "nbytes", "return", "it", ".", "Otherwise", "get", "the", "size", "of", "the", "underlying", "array", ".", "Returns", "None", "if", "the", "dataset", "is", "actually", "a", "group", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/hdf5.py#L206-L216
train
gem/oq-engine
openquake/baselib/hdf5.py
decode_array
def decode_array(values): """ Decode the values which are bytestrings. """ out = [] for val in values: try: out.append(val.decode('utf8')) except AttributeError: out.append(val) return out
python
def decode_array(values): """ Decode the values which are bytestrings. """ out = [] for val in values: try: out.append(val.decode('utf8')) except AttributeError: out.append(val) return out
[ "def", "decode_array", "(", "values", ")", ":", "out", "=", "[", "]", "for", "val", "in", "values", ":", "try", ":", "out", ".", "append", "(", "val", ".", "decode", "(", "'utf8'", ")", ")", "except", "AttributeError", ":", "out", ".", "append", "(...
Decode the values which are bytestrings.
[ "Decode", "the", "values", "which", "are", "bytestrings", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/hdf5.py#L585-L595
train
gem/oq-engine
openquake/baselib/hdf5.py
File.temporary
def temporary(cls): """ Returns a temporary hdf5 file, open for writing. The temporary name is stored in the .path attribute. It is the user responsability to remove the file when closed. """ fh, path = tempfile.mkstemp(suffix='.hdf5') os.close(fh) self = ...
python
def temporary(cls): """ Returns a temporary hdf5 file, open for writing. The temporary name is stored in the .path attribute. It is the user responsability to remove the file when closed. """ fh, path = tempfile.mkstemp(suffix='.hdf5') os.close(fh) self = ...
[ "def", "temporary", "(", "cls", ")", ":", "fh", ",", "path", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.hdf5'", ")", "os", ".", "close", "(", "fh", ")", "self", "=", "cls", "(", "path", ",", "'w'", ")", "self", ".", "path", "=", "p...
Returns a temporary hdf5 file, open for writing. The temporary name is stored in the .path attribute. It is the user responsability to remove the file when closed.
[ "Returns", "a", "temporary", "hdf5", "file", "open", "for", "writing", ".", "The", "temporary", "name", "is", "stored", "in", "the", ".", "path", "attribute", ".", "It", "is", "the", "user", "responsability", "to", "remove", "the", "file", "when", "closed"...
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/hdf5.py#L280-L290
train
gem/oq-engine
openquake/baselib/hdf5.py
File.save_vlen
def save_vlen(self, key, data): """ Save a sequence of variable-length arrays :param key: name of the dataset :param data: data to store as a list of arrays """ shape = (None,) + data[0].shape[:-1] try: dset = self[key] except KeyError: ...
python
def save_vlen(self, key, data): """ Save a sequence of variable-length arrays :param key: name of the dataset :param data: data to store as a list of arrays """ shape = (None,) + data[0].shape[:-1] try: dset = self[key] except KeyError: ...
[ "def", "save_vlen", "(", "self", ",", "key", ",", "data", ")", ":", "shape", "=", "(", "None", ",", ")", "+", "data", "[", "0", "]", ".", "shape", "[", ":", "-", "1", "]", "try", ":", "dset", "=", "self", "[", "key", "]", "except", "KeyError"...
Save a sequence of variable-length arrays :param key: name of the dataset :param data: data to store as a list of arrays
[ "Save", "a", "sequence", "of", "variable", "-", "length", "arrays" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/hdf5.py#L292-L315
train
gem/oq-engine
openquake/baselib/hdf5.py
File.set_nbytes
def set_nbytes(self, key, nbytes=None): """ Set the `nbytes` attribute on the HDF5 object identified by `key`. """ obj = super().__getitem__(key) if nbytes is not None: # size set from outside obj.attrs['nbytes'] = nbytes else: # recursively determine the si...
python
def set_nbytes(self, key, nbytes=None): """ Set the `nbytes` attribute on the HDF5 object identified by `key`. """ obj = super().__getitem__(key) if nbytes is not None: # size set from outside obj.attrs['nbytes'] = nbytes else: # recursively determine the si...
[ "def", "set_nbytes", "(", "self", ",", "key", ",", "nbytes", "=", "None", ")", ":", "obj", "=", "super", "(", ")", ".", "__getitem__", "(", "key", ")", "if", "nbytes", "is", "not", "None", ":", "# size set from outside", "obj", ".", "attrs", "[", "'n...
Set the `nbytes` attribute on the HDF5 object identified by `key`.
[ "Set", "the", "nbytes", "attribute", "on", "the", "HDF5", "object", "identified", "by", "key", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/hdf5.py#L376-L385
train
gem/oq-engine
openquake/hazardlib/gsim/can15/eastern.py
EasternCan15Mid._get_delta
def _get_delta(self, stds, dists): """ Computes the additional delta to be used for the computation of the upp and low models """ delta = np.maximum((0.1-0.001*dists.repi), np.zeros_like(dists.repi)) return delta
python
def _get_delta(self, stds, dists): """ Computes the additional delta to be used for the computation of the upp and low models """ delta = np.maximum((0.1-0.001*dists.repi), np.zeros_like(dists.repi)) return delta
[ "def", "_get_delta", "(", "self", ",", "stds", ",", "dists", ")", ":", "delta", "=", "np", ".", "maximum", "(", "(", "0.1", "-", "0.001", "*", "dists", ".", "repi", ")", ",", "np", ".", "zeros_like", "(", "dists", ".", "repi", ")", ")", "return",...
Computes the additional delta to be used for the computation of the upp and low models
[ "Computes", "the", "additional", "delta", "to", "be", "used", "for", "the", "computation", "of", "the", "upp", "and", "low", "models" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/can15/eastern.py#L91-L97
train
gem/oq-engine
openquake/hazardlib/gsim/can15/eastern.py
EasternCan15Mid._get_mean_and_stddevs
def _get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ Returns only the mean values. See documentation for method `GroundShakingIntensityModel` in :class:~`openquake.hazardlib.gsim.base.GSIM` """ # distances distsl = copy.copy(dists) d...
python
def _get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ Returns only the mean values. See documentation for method `GroundShakingIntensityModel` in :class:~`openquake.hazardlib.gsim.base.GSIM` """ # distances distsl = copy.copy(dists) d...
[ "def", "_get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "# distances", "distsl", "=", "copy", ".", "copy", "(", "dists", ")", "distsl", ".", "rjb", ",", "distsl", ".", "rrup", "=",...
Returns only the mean values. See documentation for method `GroundShakingIntensityModel` in :class:~`openquake.hazardlib.gsim.base.GSIM`
[ "Returns", "only", "the", "mean", "values", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/can15/eastern.py#L99-L151
train
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.ensure_open
async def ensure_open(self) -> None: """ Check that the WebSocket connection is open. Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't. """ # Handle cases from most common to least common for performance. if self.state is State.OPEN: # If sel...
python
async def ensure_open(self) -> None: """ Check that the WebSocket connection is open. Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't. """ # Handle cases from most common to least common for performance. if self.state is State.OPEN: # If sel...
[ "async", "def", "ensure_open", "(", "self", ")", "->", "None", ":", "# Handle cases from most common to least common for performance.", "if", "self", ".", "state", "is", "State", ".", "OPEN", ":", "# If self.transfer_data_task exited without a closing handshake,", "# self.clo...
Check that the WebSocket connection is open. Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't.
[ "Check", "that", "the", "WebSocket", "connection", "is", "open", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L662-L700
train
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.transfer_data
async def transfer_data(self) -> None: """ Read incoming messages and put them in a queue. This coroutine runs in a task until the closing handshake is started. """ try: while True: message = await self.read_message() # Exit the loop...
python
async def transfer_data(self) -> None: """ Read incoming messages and put them in a queue. This coroutine runs in a task until the closing handshake is started. """ try: while True: message = await self.read_message() # Exit the loop...
[ "async", "def", "transfer_data", "(", "self", ")", "->", "None", ":", "try", ":", "while", "True", ":", "message", "=", "await", "self", ".", "read_message", "(", ")", "# Exit the loop when receiving a close frame.", "if", "message", "is", "None", ":", "break"...
Read incoming messages and put them in a queue. This coroutine runs in a task until the closing handshake is started.
[ "Read", "incoming", "messages", "and", "put", "them", "in", "a", "queue", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L702-L768
train
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.read_message
async def read_message(self) -> Optional[Data]: """ Read a single message from the connection. Re-assemble data frames if the message is fragmented. Return ``None`` when the closing handshake is started. """ frame = await self.read_data_frame(max_size=self.max_size) ...
python
async def read_message(self) -> Optional[Data]: """ Read a single message from the connection. Re-assemble data frames if the message is fragmented. Return ``None`` when the closing handshake is started. """ frame = await self.read_data_frame(max_size=self.max_size) ...
[ "async", "def", "read_message", "(", "self", ")", "->", "Optional", "[", "Data", "]", ":", "frame", "=", "await", "self", ".", "read_data_frame", "(", "max_size", "=", "self", ".", "max_size", ")", "# A close frame was received.", "if", "frame", "is", "None"...
Read a single message from the connection. Re-assemble data frames if the message is fragmented. Return ``None`` when the closing handshake is started.
[ "Read", "a", "single", "message", "from", "the", "connection", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L770-L841
train
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.read_data_frame
async def read_data_frame(self, max_size: int) -> Optional[Frame]: """ Read a single data frame from the connection. Process control frames received before the next data frame. Return ``None`` if a close frame is encountered before any data frame. """ # 6.2. Receiving ...
python
async def read_data_frame(self, max_size: int) -> Optional[Frame]: """ Read a single data frame from the connection. Process control frames received before the next data frame. Return ``None`` if a close frame is encountered before any data frame. """ # 6.2. Receiving ...
[ "async", "def", "read_data_frame", "(", "self", ",", "max_size", ":", "int", ")", "->", "Optional", "[", "Frame", "]", ":", "# 6.2. Receiving Data", "while", "True", ":", "frame", "=", "await", "self", ".", "read_frame", "(", "max_size", ")", "# 5.5. Control...
Read a single data frame from the connection. Process control frames received before the next data frame. Return ``None`` if a close frame is encountered before any data frame.
[ "Read", "a", "single", "data", "frame", "from", "the", "connection", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L843-L910
train
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.read_frame
async def read_frame(self, max_size: int) -> Frame: """ Read a single frame from the connection. """ frame = await Frame.read( self.reader.readexactly, mask=not self.is_client, max_size=max_size, extensions=self.extensions, ) ...
python
async def read_frame(self, max_size: int) -> Frame: """ Read a single frame from the connection. """ frame = await Frame.read( self.reader.readexactly, mask=not self.is_client, max_size=max_size, extensions=self.extensions, ) ...
[ "async", "def", "read_frame", "(", "self", ",", "max_size", ":", "int", ")", "->", "Frame", ":", "frame", "=", "await", "Frame", ".", "read", "(", "self", ".", "reader", ".", "readexactly", ",", "mask", "=", "not", "self", ".", "is_client", ",", "max...
Read a single frame from the connection.
[ "Read", "a", "single", "frame", "from", "the", "connection", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L912-L924
train
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.write_close_frame
async def write_close_frame(self, data: bytes = b"") -> None: """ Write a close frame if and only if the connection state is OPEN. This dedicated coroutine must be used for writing close frames to ensure that at most one close frame is sent on a given connection. """ # ...
python
async def write_close_frame(self, data: bytes = b"") -> None: """ Write a close frame if and only if the connection state is OPEN. This dedicated coroutine must be used for writing close frames to ensure that at most one close frame is sent on a given connection. """ # ...
[ "async", "def", "write_close_frame", "(", "self", ",", "data", ":", "bytes", "=", "b\"\"", ")", "->", "None", ":", "# Test and set the connection state before sending the close frame to", "# avoid sending two frames in case of concurrent calls.", "if", "self", ".", "state", ...
Write a close frame if and only if the connection state is OPEN. This dedicated coroutine must be used for writing close frames to ensure that at most one close frame is sent on a given connection.
[ "Write", "a", "close", "frame", "if", "and", "only", "if", "the", "connection", "state", "is", "OPEN", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L953-L969
train
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.keepalive_ping
async def keepalive_ping(self) -> None: """ Send a Ping frame and wait for a Pong frame at regular intervals. This coroutine exits when the connection terminates and one of the following happens: - :meth:`ping` raises :exc:`ConnectionClosed`, or - :meth:`close_connection...
python
async def keepalive_ping(self) -> None: """ Send a Ping frame and wait for a Pong frame at regular intervals. This coroutine exits when the connection terminates and one of the following happens: - :meth:`ping` raises :exc:`ConnectionClosed`, or - :meth:`close_connection...
[ "async", "def", "keepalive_ping", "(", "self", ")", "->", "None", ":", "if", "self", ".", "ping_interval", "is", "None", ":", "return", "try", ":", "while", "True", ":", "await", "asyncio", ".", "sleep", "(", "self", ".", "ping_interval", ",", "loop", ...
Send a Ping frame and wait for a Pong frame at regular intervals. This coroutine exits when the connection terminates and one of the following happens: - :meth:`ping` raises :exc:`ConnectionClosed`, or - :meth:`close_connection` cancels :attr:`keepalive_ping_task`.
[ "Send", "a", "Ping", "frame", "and", "wait", "for", "a", "Pong", "frame", "at", "regular", "intervals", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L971-L1009
train
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.close_connection
async def close_connection(self) -> None: """ 7.1.1. Close the WebSocket Connection When the opening handshake succeeds, :meth:`connection_open` starts this coroutine in a task. It waits for the data transfer phase to complete then it closes the TCP connection cleanly. ...
python
async def close_connection(self) -> None: """ 7.1.1. Close the WebSocket Connection When the opening handshake succeeds, :meth:`connection_open` starts this coroutine in a task. It waits for the data transfer phase to complete then it closes the TCP connection cleanly. ...
[ "async", "def", "close_connection", "(", "self", ")", "->", "None", ":", "try", ":", "# Wait for the data transfer phase to complete.", "if", "hasattr", "(", "self", ",", "\"transfer_data_task\"", ")", ":", "try", ":", "await", "self", ".", "transfer_data_task", "...
7.1.1. Close the WebSocket Connection When the opening handshake succeeds, :meth:`connection_open` starts this coroutine in a task. It waits for the data transfer phase to complete then it closes the TCP connection cleanly. When the opening handshake fails, :meth:`fail_connection` does...
[ "7", ".", "1", ".", "1", ".", "Close", "the", "WebSocket", "Connection" ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L1011-L1074
train
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.wait_for_connection_lost
async def wait_for_connection_lost(self) -> bool: """ Wait until the TCP connection is closed or ``self.close_timeout`` elapses. Return ``True`` if the connection is closed and ``False`` otherwise. """ if not self.connection_lost_waiter.done(): try: ...
python
async def wait_for_connection_lost(self) -> bool: """ Wait until the TCP connection is closed or ``self.close_timeout`` elapses. Return ``True`` if the connection is closed and ``False`` otherwise. """ if not self.connection_lost_waiter.done(): try: ...
[ "async", "def", "wait_for_connection_lost", "(", "self", ")", "->", "bool", ":", "if", "not", "self", ".", "connection_lost_waiter", ".", "done", "(", ")", ":", "try", ":", "await", "asyncio", ".", "wait_for", "(", "asyncio", ".", "shield", "(", "self", ...
Wait until the TCP connection is closed or ``self.close_timeout`` elapses. Return ``True`` if the connection is closed and ``False`` otherwise.
[ "Wait", "until", "the", "TCP", "connection", "is", "closed", "or", "self", ".", "close_timeout", "elapses", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L1076-L1095
train
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.fail_connection
def fail_connection(self, code: int = 1006, reason: str = "") -> None: """ 7.1.7. Fail the WebSocket Connection This requires: 1. Stopping all processing of incoming data, which means cancelling :attr:`transfer_data_task`. The close code will be 1006 unless a clos...
python
def fail_connection(self, code: int = 1006, reason: str = "") -> None: """ 7.1.7. Fail the WebSocket Connection This requires: 1. Stopping all processing of incoming data, which means cancelling :attr:`transfer_data_task`. The close code will be 1006 unless a clos...
[ "def", "fail_connection", "(", "self", ",", "code", ":", "int", "=", "1006", ",", "reason", ":", "str", "=", "\"\"", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"%s ! failing %s WebSocket connection with code %d\"", ",", "self", ".", "side", ",", ...
7.1.7. Fail the WebSocket Connection This requires: 1. Stopping all processing of incoming data, which means cancelling :attr:`transfer_data_task`. The close code will be 1006 unless a close frame was received earlier. 2. Sending a close frame with an appropriate code if...
[ "7", ".", "1", ".", "7", ".", "Fail", "the", "WebSocket", "Connection" ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L1097-L1156
train
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.abort_keepalive_pings
def abort_keepalive_pings(self) -> None: """ Raise ConnectionClosed in pending keepalive pings. They'll never receive a pong once the connection is closed. """ assert self.state is State.CLOSED exc = ConnectionClosed(self.close_code, self.close_reason) exc.__cau...
python
def abort_keepalive_pings(self) -> None: """ Raise ConnectionClosed in pending keepalive pings. They'll never receive a pong once the connection is closed. """ assert self.state is State.CLOSED exc = ConnectionClosed(self.close_code, self.close_reason) exc.__cau...
[ "def", "abort_keepalive_pings", "(", "self", ")", "->", "None", ":", "assert", "self", ".", "state", "is", "State", ".", "CLOSED", "exc", "=", "ConnectionClosed", "(", "self", ".", "close_code", ",", "self", ".", "close_reason", ")", "exc", ".", "__cause__...
Raise ConnectionClosed in pending keepalive pings. They'll never receive a pong once the connection is closed.
[ "Raise", "ConnectionClosed", "in", "pending", "keepalive", "pings", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L1158-L1180
train
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.connection_made
def connection_made(self, transport: asyncio.BaseTransport) -> None: """ Configure write buffer limits. The high-water limit is defined by ``self.write_limit``. The low-water limit currently defaults to ``self.write_limit // 4`` in :meth:`~asyncio.WriteTransport.set_write_buffe...
python
def connection_made(self, transport: asyncio.BaseTransport) -> None: """ Configure write buffer limits. The high-water limit is defined by ``self.write_limit``. The low-water limit currently defaults to ``self.write_limit // 4`` in :meth:`~asyncio.WriteTransport.set_write_buffe...
[ "def", "connection_made", "(", "self", ",", "transport", ":", "asyncio", ".", "BaseTransport", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"%s - event = connection_made(%s)\"", ",", "self", ".", "side", ",", "transport", ")", "# mypy thinks transport is...
Configure write buffer limits. The high-water limit is defined by ``self.write_limit``. The low-water limit currently defaults to ``self.write_limit // 4`` in :meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should be all right for reasonable use cases of this library. ...
[ "Configure", "write", "buffer", "limits", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L1184-L1201
train
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.eof_received
def eof_received(self) -> bool: """ Close the transport after receiving EOF. Since Python 3.5, `:meth:~StreamReaderProtocol.eof_received` returns ``True`` on non-TLS connections. See http://bugs.python.org/issue24539 for more information. This is inappropriate for webs...
python
def eof_received(self) -> bool: """ Close the transport after receiving EOF. Since Python 3.5, `:meth:~StreamReaderProtocol.eof_received` returns ``True`` on non-TLS connections. See http://bugs.python.org/issue24539 for more information. This is inappropriate for webs...
[ "def", "eof_received", "(", "self", ")", "->", "bool", ":", "logger", ".", "debug", "(", "\"%s - event = eof_received()\"", ",", "self", ".", "side", ")", "super", "(", ")", ".", "eof_received", "(", ")", "return", "False" ]
Close the transport after receiving EOF. Since Python 3.5, `:meth:~StreamReaderProtocol.eof_received` returns ``True`` on non-TLS connections. See http://bugs.python.org/issue24539 for more information. This is inappropriate for websockets for at least three reasons: 1. The u...
[ "Close", "the", "transport", "after", "receiving", "EOF", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L1203-L1228
train
aaugustin/websockets
src/websockets/protocol.py
WebSocketCommonProtocol.connection_lost
def connection_lost(self, exc: Optional[Exception]) -> None: """ 7.1.4. The WebSocket Connection is Closed. """ logger.debug("%s - event = connection_lost(%s)", self.side, exc) self.state = State.CLOSED logger.debug("%s - state = CLOSED", self.side) if not hasatt...
python
def connection_lost(self, exc: Optional[Exception]) -> None: """ 7.1.4. The WebSocket Connection is Closed. """ logger.debug("%s - event = connection_lost(%s)", self.side, exc) self.state = State.CLOSED logger.debug("%s - state = CLOSED", self.side) if not hasatt...
[ "def", "connection_lost", "(", "self", ",", "exc", ":", "Optional", "[", "Exception", "]", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"%s - event = connection_lost(%s)\"", ",", "self", ".", "side", ",", "exc", ")", "self", ".", "state", "=", ...
7.1.4. The WebSocket Connection is Closed.
[ "7", ".", "1", ".", "4", ".", "The", "WebSocket", "Connection", "is", "Closed", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L1230-L1253
train
aaugustin/websockets
src/websockets/handshake.py
build_request
def build_request(headers: Headers) -> str: """ Build a handshake request to send to the server. Return the ``key`` which must be passed to :func:`check_response`. """ raw_key = bytes(random.getrandbits(8) for _ in range(16)) key = base64.b64encode(raw_key).decode() headers["Upgrade"] = "w...
python
def build_request(headers: Headers) -> str: """ Build a handshake request to send to the server. Return the ``key`` which must be passed to :func:`check_response`. """ raw_key = bytes(random.getrandbits(8) for _ in range(16)) key = base64.b64encode(raw_key).decode() headers["Upgrade"] = "w...
[ "def", "build_request", "(", "headers", ":", "Headers", ")", "->", "str", ":", "raw_key", "=", "bytes", "(", "random", ".", "getrandbits", "(", "8", ")", "for", "_", "in", "range", "(", "16", ")", ")", "key", "=", "base64", ".", "b64encode", "(", "...
Build a handshake request to send to the server. Return the ``key`` which must be passed to :func:`check_response`.
[ "Build", "a", "handshake", "request", "to", "send", "to", "the", "server", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/handshake.py#L49-L62
train
aaugustin/websockets
src/websockets/handshake.py
check_request
def check_request(headers: Headers) -> str: """ Check a handshake request received from the client. If the handshake is valid, this function returns the ``key`` which must be passed to :func:`build_response`. Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake` exception and t...
python
def check_request(headers: Headers) -> str: """ Check a handshake request received from the client. If the handshake is valid, this function returns the ``key`` which must be passed to :func:`build_response`. Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake` exception and t...
[ "def", "check_request", "(", "headers", ":", "Headers", ")", "->", "str", ":", "connection", "=", "sum", "(", "[", "parse_connection", "(", "value", ")", "for", "value", "in", "headers", ".", "get_all", "(", "\"Connection\"", ")", "]", ",", "[", "]", "...
Check a handshake request received from the client. If the handshake is valid, this function returns the ``key`` which must be passed to :func:`build_response`. Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake` exception and the server must return an error like 400 Bad Request. ...
[ "Check", "a", "handshake", "request", "received", "from", "the", "client", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/handshake.py#L65-L123
train
aaugustin/websockets
src/websockets/handshake.py
build_response
def build_response(headers: Headers, key: str) -> None: """ Build a handshake response to send to the client. ``key`` comes from :func:`check_request`. """ headers["Upgrade"] = "websocket" headers["Connection"] = "Upgrade" headers["Sec-WebSocket-Accept"] = accept(key)
python
def build_response(headers: Headers, key: str) -> None: """ Build a handshake response to send to the client. ``key`` comes from :func:`check_request`. """ headers["Upgrade"] = "websocket" headers["Connection"] = "Upgrade" headers["Sec-WebSocket-Accept"] = accept(key)
[ "def", "build_response", "(", "headers", ":", "Headers", ",", "key", ":", "str", ")", "->", "None", ":", "headers", "[", "\"Upgrade\"", "]", "=", "\"websocket\"", "headers", "[", "\"Connection\"", "]", "=", "\"Upgrade\"", "headers", "[", "\"Sec-WebSocket-Accep...
Build a handshake response to send to the client. ``key`` comes from :func:`check_request`.
[ "Build", "a", "handshake", "response", "to", "send", "to", "the", "client", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/handshake.py#L126-L135
train
aaugustin/websockets
src/websockets/handshake.py
check_response
def check_response(headers: Headers, key: str) -> None: """ Check a handshake response received from the server. ``key`` comes from :func:`build_request`. If the handshake is valid, this function returns ``None``. Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake` exception...
python
def check_response(headers: Headers, key: str) -> None: """ Check a handshake response received from the server. ``key`` comes from :func:`build_request`. If the handshake is valid, this function returns ``None``. Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake` exception...
[ "def", "check_response", "(", "headers", ":", "Headers", ",", "key", ":", "str", ")", "->", "None", ":", "connection", "=", "sum", "(", "[", "parse_connection", "(", "value", ")", "for", "value", "in", "headers", ".", "get_all", "(", "\"Connection\"", ")...
Check a handshake response received from the server. ``key`` comes from :func:`build_request`. If the handshake is valid, this function returns ``None``. Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake` exception. This function doesn't verify that the response is an HTTP/1.1...
[ "Check", "a", "handshake", "response", "received", "from", "the", "server", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/handshake.py#L138-L178
train
aaugustin/websockets
src/websockets/extensions/permessage_deflate.py
PerMessageDeflate.decode
def decode(self, frame: Frame, *, max_size: Optional[int] = None) -> Frame: """ Decode an incoming frame. """ # Skip control frames. if frame.opcode in CTRL_OPCODES: return frame # Handle continuation data frames: # - skip if the initial data frame w...
python
def decode(self, frame: Frame, *, max_size: Optional[int] = None) -> Frame: """ Decode an incoming frame. """ # Skip control frames. if frame.opcode in CTRL_OPCODES: return frame # Handle continuation data frames: # - skip if the initial data frame w...
[ "def", "decode", "(", "self", ",", "frame", ":", "Frame", ",", "*", ",", "max_size", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Frame", ":", "# Skip control frames.", "if", "frame", ".", "opcode", "in", "CTRL_OPCODES", ":", "return", "f...
Decode an incoming frame.
[ "Decode", "an", "incoming", "frame", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/extensions/permessage_deflate.py#L91-L139
train
aaugustin/websockets
src/websockets/extensions/permessage_deflate.py
PerMessageDeflate.encode
def encode(self, frame: Frame) -> Frame: """ Encode an outgoing frame. """ # Skip control frames. if frame.opcode in CTRL_OPCODES: return frame # Since we always encode and never fragment messages, there's no logic # similar to decode() here at this ...
python
def encode(self, frame: Frame) -> Frame: """ Encode an outgoing frame. """ # Skip control frames. if frame.opcode in CTRL_OPCODES: return frame # Since we always encode and never fragment messages, there's no logic # similar to decode() here at this ...
[ "def", "encode", "(", "self", ",", "frame", ":", "Frame", ")", "->", "Frame", ":", "# Skip control frames.", "if", "frame", ".", "opcode", "in", "CTRL_OPCODES", ":", "return", "frame", "# Since we always encode and never fragment messages, there's no logic", "# similar ...
Encode an outgoing frame.
[ "Encode", "an", "outgoing", "frame", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/extensions/permessage_deflate.py#L141-L169
train
aaugustin/websockets
src/websockets/extensions/permessage_deflate.py
ClientPerMessageDeflateFactory.get_request_params
def get_request_params(self) -> List[ExtensionParameter]: """ Build request parameters. """ return _build_parameters( self.server_no_context_takeover, self.client_no_context_takeover, self.server_max_window_bits, self.client_max_window_bit...
python
def get_request_params(self) -> List[ExtensionParameter]: """ Build request parameters. """ return _build_parameters( self.server_no_context_takeover, self.client_no_context_takeover, self.server_max_window_bits, self.client_max_window_bit...
[ "def", "get_request_params", "(", "self", ")", "->", "List", "[", "ExtensionParameter", "]", ":", "return", "_build_parameters", "(", "self", ".", "server_no_context_takeover", ",", "self", ".", "client_no_context_takeover", ",", "self", ".", "server_max_window_bits",...
Build request parameters.
[ "Build", "request", "parameters", "." ]
17b3f47549b6f752a1be07fa1ba3037cb59c7d56
https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/extensions/permessage_deflate.py#L313-L323
train