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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Netflix-Skunkworks/swag-client | swag_client/migrations/migrations.py | run_migration | def run_migration(data, version_start, version_end):
"""Runs migration against a data set."""
items = []
if version_start == 1 and version_end == 2:
for item in data['accounts']:
items.append(v2.upgrade(item))
if version_start == 2 and version_end == 1:
for item in data:
items.append(v2.downgrade(item))
items = {'accounts': items}
return items | python | def run_migration(data, version_start, version_end):
"""Runs migration against a data set."""
items = []
if version_start == 1 and version_end == 2:
for item in data['accounts']:
items.append(v2.upgrade(item))
if version_start == 2 and version_end == 1:
for item in data:
items.append(v2.downgrade(item))
items = {'accounts': items}
return items | [
"def",
"run_migration",
"(",
"data",
",",
"version_start",
",",
"version_end",
")",
":",
"items",
"=",
"[",
"]",
"if",
"version_start",
"==",
"1",
"and",
"version_end",
"==",
"2",
":",
"for",
"item",
"in",
"data",
"[",
"'accounts'",
"]",
":",
"items",
... | Runs migration against a data set. | [
"Runs",
"migration",
"against",
"a",
"data",
"set",
"."
] | e43816a85c4f48011cf497a4eae14f9df71fee0f | https://github.com/Netflix-Skunkworks/swag-client/blob/e43816a85c4f48011cf497a4eae14f9df71fee0f/swag_client/migrations/migrations.py#L4-L15 | train | 202,500 |
Netflix-Skunkworks/swag-client | swag_client/schemas/v2.py | AccountSchema.validate_type | def validate_type(self, data):
"""Performs field validation against the schema context
if values have been provided to SWAGManager via the
swag.schema_context config object.
If the schema context for a given field is empty, then
we assume any value is valid for the given schema field.
"""
fields_to_validate = ['type', 'environment', 'owner']
for field in fields_to_validate:
value = data.get(field)
allowed_values = self.context.get(field)
if allowed_values and value not in allowed_values:
raise ValidationError('Must be one of {}'.format(allowed_values), field_names=field) | python | def validate_type(self, data):
"""Performs field validation against the schema context
if values have been provided to SWAGManager via the
swag.schema_context config object.
If the schema context for a given field is empty, then
we assume any value is valid for the given schema field.
"""
fields_to_validate = ['type', 'environment', 'owner']
for field in fields_to_validate:
value = data.get(field)
allowed_values = self.context.get(field)
if allowed_values and value not in allowed_values:
raise ValidationError('Must be one of {}'.format(allowed_values), field_names=field) | [
"def",
"validate_type",
"(",
"self",
",",
"data",
")",
":",
"fields_to_validate",
"=",
"[",
"'type'",
",",
"'environment'",
",",
"'owner'",
"]",
"for",
"field",
"in",
"fields_to_validate",
":",
"value",
"=",
"data",
".",
"get",
"(",
"field",
")",
"allowed_... | Performs field validation against the schema context
if values have been provided to SWAGManager via the
swag.schema_context config object.
If the schema context for a given field is empty, then
we assume any value is valid for the given schema field. | [
"Performs",
"field",
"validation",
"against",
"the",
"schema",
"context",
"if",
"values",
"have",
"been",
"provided",
"to",
"SWAGManager",
"via",
"the",
"swag",
".",
"schema_context",
"config",
"object",
"."
] | e43816a85c4f48011cf497a4eae14f9df71fee0f | https://github.com/Netflix-Skunkworks/swag-client/blob/e43816a85c4f48011cf497a4eae14f9df71fee0f/swag_client/schemas/v2.py#L70-L83 | train | 202,501 |
Netflix-Skunkworks/swag-client | swag_client/schemas/v2.py | AccountSchema.validate_account_status | def validate_account_status(self, data):
"""Performs field validation for account_status. If any
region is not deleted, account_status cannot be deleted
"""
deleted_status = 'deleted'
region_status = data.get('status')
account_status = data.get('account_status')
for region in region_status:
if region['status'] != deleted_status and account_status == deleted_status:
raise ValidationError('Account Status cannot be "deleted" if a region is not "deleted"') | python | def validate_account_status(self, data):
"""Performs field validation for account_status. If any
region is not deleted, account_status cannot be deleted
"""
deleted_status = 'deleted'
region_status = data.get('status')
account_status = data.get('account_status')
for region in region_status:
if region['status'] != deleted_status and account_status == deleted_status:
raise ValidationError('Account Status cannot be "deleted" if a region is not "deleted"') | [
"def",
"validate_account_status",
"(",
"self",
",",
"data",
")",
":",
"deleted_status",
"=",
"'deleted'",
"region_status",
"=",
"data",
".",
"get",
"(",
"'status'",
")",
"account_status",
"=",
"data",
".",
"get",
"(",
"'account_status'",
")",
"for",
"region",
... | Performs field validation for account_status. If any
region is not deleted, account_status cannot be deleted | [
"Performs",
"field",
"validation",
"for",
"account_status",
".",
"If",
"any",
"region",
"is",
"not",
"deleted",
"account_status",
"cannot",
"be",
"deleted"
] | e43816a85c4f48011cf497a4eae14f9df71fee0f | https://github.com/Netflix-Skunkworks/swag-client/blob/e43816a85c4f48011cf497a4eae14f9df71fee0f/swag_client/schemas/v2.py#L86-L95 | train | 202,502 |
Netflix-Skunkworks/swag-client | swag_client/schemas/v2.py | AccountSchema.validate_regions_schema | def validate_regions_schema(self, data):
"""Performs field validation for regions. This should be
a dict with region names as the key and RegionSchema as the value
"""
region_schema = RegionSchema()
supplied_regions = data.get('regions', {})
for region in supplied_regions.keys():
result = region_schema.validate(supplied_regions[region])
if len(result.keys()) > 0:
raise ValidationError(result) | python | def validate_regions_schema(self, data):
"""Performs field validation for regions. This should be
a dict with region names as the key and RegionSchema as the value
"""
region_schema = RegionSchema()
supplied_regions = data.get('regions', {})
for region in supplied_regions.keys():
result = region_schema.validate(supplied_regions[region])
if len(result.keys()) > 0:
raise ValidationError(result) | [
"def",
"validate_regions_schema",
"(",
"self",
",",
"data",
")",
":",
"region_schema",
"=",
"RegionSchema",
"(",
")",
"supplied_regions",
"=",
"data",
".",
"get",
"(",
"'regions'",
",",
"{",
"}",
")",
"for",
"region",
"in",
"supplied_regions",
".",
"keys",
... | Performs field validation for regions. This should be
a dict with region names as the key and RegionSchema as the value | [
"Performs",
"field",
"validation",
"for",
"regions",
".",
"This",
"should",
"be",
"a",
"dict",
"with",
"region",
"names",
"as",
"the",
"key",
"and",
"RegionSchema",
"as",
"the",
"value"
] | e43816a85c4f48011cf497a4eae14f9df71fee0f | https://github.com/Netflix-Skunkworks/swag-client/blob/e43816a85c4f48011cf497a4eae14f9df71fee0f/swag_client/schemas/v2.py#L98-L107 | train | 202,503 |
pyviz/geoviews | geoviews/data/iris.py | coord_to_dimension | def coord_to_dimension(coord):
"""
Converts an iris coordinate to a HoloViews dimension.
"""
kwargs = {}
if coord.units.is_time_reference():
kwargs['value_format'] = get_date_format(coord)
else:
kwargs['unit'] = str(coord.units)
return Dimension(coord.name(), **kwargs) | python | def coord_to_dimension(coord):
"""
Converts an iris coordinate to a HoloViews dimension.
"""
kwargs = {}
if coord.units.is_time_reference():
kwargs['value_format'] = get_date_format(coord)
else:
kwargs['unit'] = str(coord.units)
return Dimension(coord.name(), **kwargs) | [
"def",
"coord_to_dimension",
"(",
"coord",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"coord",
".",
"units",
".",
"is_time_reference",
"(",
")",
":",
"kwargs",
"[",
"'value_format'",
"]",
"=",
"get_date_format",
"(",
"coord",
")",
"else",
":",
"kwargs",
"[... | Converts an iris coordinate to a HoloViews dimension. | [
"Converts",
"an",
"iris",
"coordinate",
"to",
"a",
"HoloViews",
"dimension",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/data/iris.py#L31-L40 | train | 202,504 |
pyviz/geoviews | geoviews/data/iris.py | sort_coords | def sort_coords(coord):
"""
Sorts a list of DimCoords trying to ensure that
dates and pressure levels appear first and the
longitude and latitude appear last in the correct
order.
"""
import iris
order = {'T': -2, 'Z': -1, 'X': 1, 'Y': 2}
axis = iris.util.guess_coord_axis(coord)
return (order.get(axis, 0), coord and coord.name()) | python | def sort_coords(coord):
"""
Sorts a list of DimCoords trying to ensure that
dates and pressure levels appear first and the
longitude and latitude appear last in the correct
order.
"""
import iris
order = {'T': -2, 'Z': -1, 'X': 1, 'Y': 2}
axis = iris.util.guess_coord_axis(coord)
return (order.get(axis, 0), coord and coord.name()) | [
"def",
"sort_coords",
"(",
"coord",
")",
":",
"import",
"iris",
"order",
"=",
"{",
"'T'",
":",
"-",
"2",
",",
"'Z'",
":",
"-",
"1",
",",
"'X'",
":",
"1",
",",
"'Y'",
":",
"2",
"}",
"axis",
"=",
"iris",
".",
"util",
".",
"guess_coord_axis",
"(",... | Sorts a list of DimCoords trying to ensure that
dates and pressure levels appear first and the
longitude and latitude appear last in the correct
order. | [
"Sorts",
"a",
"list",
"of",
"DimCoords",
"trying",
"to",
"ensure",
"that",
"dates",
"and",
"pressure",
"levels",
"appear",
"first",
"and",
"the",
"longitude",
"and",
"latitude",
"appear",
"last",
"in",
"the",
"correct",
"order",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/data/iris.py#L43-L53 | train | 202,505 |
pyviz/geoviews | geoviews/data/iris.py | CubeInterface.values | def values(cls, dataset, dim, expanded=True, flat=True, compute=True):
"""
Returns an array of the values along the supplied dimension.
"""
dim = dataset.get_dimension(dim, strict=True)
if dim in dataset.vdims:
coord_names = [c.name() for c in dataset.data.dim_coords]
data = dataset.data.copy().data
data = cls.canonicalize(dataset, data, coord_names)
return data.T.flatten() if flat else data
elif expanded:
data = cls.coords(dataset, dim.name, expanded=True)
return data.T.flatten() if flat else data
else:
return cls.coords(dataset, dim.name, ordered=True) | python | def values(cls, dataset, dim, expanded=True, flat=True, compute=True):
"""
Returns an array of the values along the supplied dimension.
"""
dim = dataset.get_dimension(dim, strict=True)
if dim in dataset.vdims:
coord_names = [c.name() for c in dataset.data.dim_coords]
data = dataset.data.copy().data
data = cls.canonicalize(dataset, data, coord_names)
return data.T.flatten() if flat else data
elif expanded:
data = cls.coords(dataset, dim.name, expanded=True)
return data.T.flatten() if flat else data
else:
return cls.coords(dataset, dim.name, ordered=True) | [
"def",
"values",
"(",
"cls",
",",
"dataset",
",",
"dim",
",",
"expanded",
"=",
"True",
",",
"flat",
"=",
"True",
",",
"compute",
"=",
"True",
")",
":",
"dim",
"=",
"dataset",
".",
"get_dimension",
"(",
"dim",
",",
"strict",
"=",
"True",
")",
"if",
... | Returns an array of the values along the supplied dimension. | [
"Returns",
"an",
"array",
"of",
"the",
"values",
"along",
"the",
"supplied",
"dimension",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/data/iris.py#L175-L189 | train | 202,506 |
pyviz/geoviews | geoviews/data/iris.py | CubeInterface.groupby | def groupby(cls, dataset, dims, container_type=HoloMap, group_type=None, **kwargs):
"""
Groups the data by one or more dimensions returning a container
indexed by the grouped dimensions containing slices of the
cube wrapped in the group_type. This makes it very easy to
break up a high-dimensional dataset into smaller viewable chunks.
"""
import iris
if not isinstance(dims, list): dims = [dims]
dims = [dataset.get_dimension(d, strict=True) for d in dims]
constraints = [d.name for d in dims]
slice_dims = [d for d in dataset.kdims if d not in dims]
# Update the kwargs appropriately for Element group types
group_kwargs = {}
group_type = dict if group_type == 'raw' else group_type
if issubclass(group_type, Element):
group_kwargs.update(util.get_param_values(dataset))
group_kwargs['kdims'] = slice_dims
group_kwargs.update(kwargs)
drop_dim = any(d not in group_kwargs['kdims'] for d in slice_dims)
unique_coords = product(*[cls.values(dataset, d, expanded=False)
for d in dims])
data = []
for key in unique_coords:
constraint = iris.Constraint(**dict(zip(constraints, key)))
extracted = dataset.data.extract(constraint)
if drop_dim:
extracted = group_type(extracted, kdims=slice_dims,
vdims=dataset.vdims).columns()
cube = group_type(extracted, **group_kwargs)
data.append((key, cube))
if issubclass(container_type, NdMapping):
with item_check(False), sorted_context(False):
return container_type(data, kdims=dims)
else:
return container_type(data) | python | def groupby(cls, dataset, dims, container_type=HoloMap, group_type=None, **kwargs):
"""
Groups the data by one or more dimensions returning a container
indexed by the grouped dimensions containing slices of the
cube wrapped in the group_type. This makes it very easy to
break up a high-dimensional dataset into smaller viewable chunks.
"""
import iris
if not isinstance(dims, list): dims = [dims]
dims = [dataset.get_dimension(d, strict=True) for d in dims]
constraints = [d.name for d in dims]
slice_dims = [d for d in dataset.kdims if d not in dims]
# Update the kwargs appropriately for Element group types
group_kwargs = {}
group_type = dict if group_type == 'raw' else group_type
if issubclass(group_type, Element):
group_kwargs.update(util.get_param_values(dataset))
group_kwargs['kdims'] = slice_dims
group_kwargs.update(kwargs)
drop_dim = any(d not in group_kwargs['kdims'] for d in slice_dims)
unique_coords = product(*[cls.values(dataset, d, expanded=False)
for d in dims])
data = []
for key in unique_coords:
constraint = iris.Constraint(**dict(zip(constraints, key)))
extracted = dataset.data.extract(constraint)
if drop_dim:
extracted = group_type(extracted, kdims=slice_dims,
vdims=dataset.vdims).columns()
cube = group_type(extracted, **group_kwargs)
data.append((key, cube))
if issubclass(container_type, NdMapping):
with item_check(False), sorted_context(False):
return container_type(data, kdims=dims)
else:
return container_type(data) | [
"def",
"groupby",
"(",
"cls",
",",
"dataset",
",",
"dims",
",",
"container_type",
"=",
"HoloMap",
",",
"group_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"iris",
"if",
"not",
"isinstance",
"(",
"dims",
",",
"list",
")",
":",
"dim... | Groups the data by one or more dimensions returning a container
indexed by the grouped dimensions containing slices of the
cube wrapped in the group_type. This makes it very easy to
break up a high-dimensional dataset into smaller viewable chunks. | [
"Groups",
"the",
"data",
"by",
"one",
"or",
"more",
"dimensions",
"returning",
"a",
"container",
"indexed",
"by",
"the",
"grouped",
"dimensions",
"containing",
"slices",
"of",
"the",
"cube",
"wrapped",
"in",
"the",
"group_type",
".",
"This",
"makes",
"it",
"... | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/data/iris.py#L211-L250 | train | 202,507 |
pyviz/geoviews | geoviews/data/iris.py | CubeInterface.concat_dim | def concat_dim(cls, datasets, dim, vdims):
"""
Concatenates datasets along one dimension
"""
import iris
from iris.experimental.equalise_cubes import equalise_attributes
cubes = []
for c, cube in datasets.items():
cube = cube.copy()
cube.add_aux_coord(iris.coords.DimCoord([c], var_name=dim.name))
cubes.append(cube)
cubes = iris.cube.CubeList(cubes)
equalise_attributes(cubes)
return cubes.merge_cube() | python | def concat_dim(cls, datasets, dim, vdims):
"""
Concatenates datasets along one dimension
"""
import iris
from iris.experimental.equalise_cubes import equalise_attributes
cubes = []
for c, cube in datasets.items():
cube = cube.copy()
cube.add_aux_coord(iris.coords.DimCoord([c], var_name=dim.name))
cubes.append(cube)
cubes = iris.cube.CubeList(cubes)
equalise_attributes(cubes)
return cubes.merge_cube() | [
"def",
"concat_dim",
"(",
"cls",
",",
"datasets",
",",
"dim",
",",
"vdims",
")",
":",
"import",
"iris",
"from",
"iris",
".",
"experimental",
".",
"equalise_cubes",
"import",
"equalise_attributes",
"cubes",
"=",
"[",
"]",
"for",
"c",
",",
"cube",
"in",
"d... | Concatenates datasets along one dimension | [
"Concatenates",
"datasets",
"along",
"one",
"dimension"
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/data/iris.py#L253-L267 | train | 202,508 |
pyviz/geoviews | geoviews/data/iris.py | CubeInterface.range | def range(cls, dataset, dimension):
"""
Computes the range along a particular dimension.
"""
dim = dataset.get_dimension(dimension, strict=True)
values = dataset.dimension_values(dim.name, False)
return (np.nanmin(values), np.nanmax(values)) | python | def range(cls, dataset, dimension):
"""
Computes the range along a particular dimension.
"""
dim = dataset.get_dimension(dimension, strict=True)
values = dataset.dimension_values(dim.name, False)
return (np.nanmin(values), np.nanmax(values)) | [
"def",
"range",
"(",
"cls",
",",
"dataset",
",",
"dimension",
")",
":",
"dim",
"=",
"dataset",
".",
"get_dimension",
"(",
"dimension",
",",
"strict",
"=",
"True",
")",
"values",
"=",
"dataset",
".",
"dimension_values",
"(",
"dim",
".",
"name",
",",
"Fa... | Computes the range along a particular dimension. | [
"Computes",
"the",
"range",
"along",
"a",
"particular",
"dimension",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/data/iris.py#L271-L277 | train | 202,509 |
pyviz/geoviews | geoviews/data/iris.py | CubeInterface.redim | def redim(cls, dataset, dimensions):
"""
Rename coords on the Cube.
"""
new_dataset = dataset.data.copy()
for name, new_dim in dimensions.items():
if name == new_dataset.name():
new_dataset.rename(new_dim.name)
for coord in new_dataset.dim_coords:
if name == coord.name():
coord.rename(new_dim.name)
return new_dataset | python | def redim(cls, dataset, dimensions):
"""
Rename coords on the Cube.
"""
new_dataset = dataset.data.copy()
for name, new_dim in dimensions.items():
if name == new_dataset.name():
new_dataset.rename(new_dim.name)
for coord in new_dataset.dim_coords:
if name == coord.name():
coord.rename(new_dim.name)
return new_dataset | [
"def",
"redim",
"(",
"cls",
",",
"dataset",
",",
"dimensions",
")",
":",
"new_dataset",
"=",
"dataset",
".",
"data",
".",
"copy",
"(",
")",
"for",
"name",
",",
"new_dim",
"in",
"dimensions",
".",
"items",
"(",
")",
":",
"if",
"name",
"==",
"new_datas... | Rename coords on the Cube. | [
"Rename",
"coords",
"on",
"the",
"Cube",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/data/iris.py#L281-L292 | train | 202,510 |
pyviz/geoviews | geoviews/data/iris.py | CubeInterface.length | def length(cls, dataset):
"""
Returns the total number of samples in the dataset.
"""
return np.product([len(d.points) for d in dataset.data.coords(dim_coords=True)], dtype=np.intp) | python | def length(cls, dataset):
"""
Returns the total number of samples in the dataset.
"""
return np.product([len(d.points) for d in dataset.data.coords(dim_coords=True)], dtype=np.intp) | [
"def",
"length",
"(",
"cls",
",",
"dataset",
")",
":",
"return",
"np",
".",
"product",
"(",
"[",
"len",
"(",
"d",
".",
"points",
")",
"for",
"d",
"in",
"dataset",
".",
"data",
".",
"coords",
"(",
"dim_coords",
"=",
"True",
")",
"]",
",",
"dtype",... | Returns the total number of samples in the dataset. | [
"Returns",
"the",
"total",
"number",
"of",
"samples",
"in",
"the",
"dataset",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/data/iris.py#L296-L300 | train | 202,511 |
pyviz/geoviews | geoviews/data/iris.py | CubeInterface.add_dimension | def add_dimension(cls, columns, dimension, dim_pos, values, vdim):
"""
Adding value dimensions not currently supported by iris interface.
Adding key dimensions not possible on dense interfaces.
"""
if not vdim:
raise Exception("Cannot add key dimension to a dense representation.")
raise NotImplementedError | python | def add_dimension(cls, columns, dimension, dim_pos, values, vdim):
"""
Adding value dimensions not currently supported by iris interface.
Adding key dimensions not possible on dense interfaces.
"""
if not vdim:
raise Exception("Cannot add key dimension to a dense representation.")
raise NotImplementedError | [
"def",
"add_dimension",
"(",
"cls",
",",
"columns",
",",
"dimension",
",",
"dim_pos",
",",
"values",
",",
"vdim",
")",
":",
"if",
"not",
"vdim",
":",
"raise",
"Exception",
"(",
"\"Cannot add key dimension to a dense representation.\"",
")",
"raise",
"NotImplemente... | Adding value dimensions not currently supported by iris interface.
Adding key dimensions not possible on dense interfaces. | [
"Adding",
"value",
"dimensions",
"not",
"currently",
"supported",
"by",
"iris",
"interface",
".",
"Adding",
"key",
"dimensions",
"not",
"possible",
"on",
"dense",
"interfaces",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/data/iris.py#L328-L335 | train | 202,512 |
pyviz/geoviews | geoviews/data/iris.py | CubeInterface.select_to_constraint | def select_to_constraint(cls, dataset, selection):
"""
Transform a selection dictionary to an iris Constraint.
"""
import iris
def get_slicer(start, end):
def slicer(cell):
return start <= cell.point < end
return slicer
constraint_kwargs = {}
for dim, constraint in selection.items():
if isinstance(constraint, slice):
constraint = (constraint.start, constraint.stop)
if isinstance(constraint, tuple):
if constraint == (None, None):
continue
constraint = get_slicer(*constraint)
dim = dataset.get_dimension(dim, strict=True)
constraint_kwargs[dim.name] = constraint
return iris.Constraint(**constraint_kwargs) | python | def select_to_constraint(cls, dataset, selection):
"""
Transform a selection dictionary to an iris Constraint.
"""
import iris
def get_slicer(start, end):
def slicer(cell):
return start <= cell.point < end
return slicer
constraint_kwargs = {}
for dim, constraint in selection.items():
if isinstance(constraint, slice):
constraint = (constraint.start, constraint.stop)
if isinstance(constraint, tuple):
if constraint == (None, None):
continue
constraint = get_slicer(*constraint)
dim = dataset.get_dimension(dim, strict=True)
constraint_kwargs[dim.name] = constraint
return iris.Constraint(**constraint_kwargs) | [
"def",
"select_to_constraint",
"(",
"cls",
",",
"dataset",
",",
"selection",
")",
":",
"import",
"iris",
"def",
"get_slicer",
"(",
"start",
",",
"end",
")",
":",
"def",
"slicer",
"(",
"cell",
")",
":",
"return",
"start",
"<=",
"cell",
".",
"point",
"<"... | Transform a selection dictionary to an iris Constraint. | [
"Transform",
"a",
"selection",
"dictionary",
"to",
"an",
"iris",
"Constraint",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/data/iris.py#L339-L359 | train | 202,513 |
pyviz/geoviews | geoviews/data/iris.py | CubeInterface.select | def select(cls, dataset, selection_mask=None, **selection):
"""
Apply a selection to the data.
"""
import iris
constraint = cls.select_to_constraint(dataset, selection)
pre_dim_coords = [c.name() for c in dataset.data.dim_coords]
indexed = cls.indexed(dataset, selection)
extracted = dataset.data.extract(constraint)
if indexed and not extracted.dim_coords:
return extracted.data.item()
post_dim_coords = [c.name() for c in extracted.dim_coords]
dropped = [c for c in pre_dim_coords if c not in post_dim_coords]
for d in dropped:
extracted = iris.util.new_axis(extracted, d)
return extracted | python | def select(cls, dataset, selection_mask=None, **selection):
"""
Apply a selection to the data.
"""
import iris
constraint = cls.select_to_constraint(dataset, selection)
pre_dim_coords = [c.name() for c in dataset.data.dim_coords]
indexed = cls.indexed(dataset, selection)
extracted = dataset.data.extract(constraint)
if indexed and not extracted.dim_coords:
return extracted.data.item()
post_dim_coords = [c.name() for c in extracted.dim_coords]
dropped = [c for c in pre_dim_coords if c not in post_dim_coords]
for d in dropped:
extracted = iris.util.new_axis(extracted, d)
return extracted | [
"def",
"select",
"(",
"cls",
",",
"dataset",
",",
"selection_mask",
"=",
"None",
",",
"*",
"*",
"selection",
")",
":",
"import",
"iris",
"constraint",
"=",
"cls",
".",
"select_to_constraint",
"(",
"dataset",
",",
"selection",
")",
"pre_dim_coords",
"=",
"[... | Apply a selection to the data. | [
"Apply",
"a",
"selection",
"to",
"the",
"data",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/data/iris.py#L363-L379 | train | 202,514 |
pyviz/geoviews | geoviews/operation/__init__.py | convert_to_geotype | def convert_to_geotype(element, crs=None):
"""
Converts a HoloViews element type to the equivalent GeoViews
element if given a coordinate reference system.
"""
geotype = getattr(gv_element, type(element).__name__, None)
if crs is None or geotype is None or isinstance(element, _Element):
return element
return geotype(element, crs=crs) | python | def convert_to_geotype(element, crs=None):
"""
Converts a HoloViews element type to the equivalent GeoViews
element if given a coordinate reference system.
"""
geotype = getattr(gv_element, type(element).__name__, None)
if crs is None or geotype is None or isinstance(element, _Element):
return element
return geotype(element, crs=crs) | [
"def",
"convert_to_geotype",
"(",
"element",
",",
"crs",
"=",
"None",
")",
":",
"geotype",
"=",
"getattr",
"(",
"gv_element",
",",
"type",
"(",
"element",
")",
".",
"__name__",
",",
"None",
")",
"if",
"crs",
"is",
"None",
"or",
"geotype",
"is",
"None",... | Converts a HoloViews element type to the equivalent GeoViews
element if given a coordinate reference system. | [
"Converts",
"a",
"HoloViews",
"element",
"type",
"to",
"the",
"equivalent",
"GeoViews",
"element",
"if",
"given",
"a",
"coordinate",
"reference",
"system",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/operation/__init__.py#L20-L28 | train | 202,515 |
pyviz/geoviews | geoviews/operation/__init__.py | add_crs | def add_crs(op, element, **kwargs):
"""
Converts any elements in the input to their equivalent geotypes
if given a coordinate reference system.
"""
return element.map(lambda x: convert_to_geotype(x, kwargs.get('crs')), Element) | python | def add_crs(op, element, **kwargs):
"""
Converts any elements in the input to their equivalent geotypes
if given a coordinate reference system.
"""
return element.map(lambda x: convert_to_geotype(x, kwargs.get('crs')), Element) | [
"def",
"add_crs",
"(",
"op",
",",
"element",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"element",
".",
"map",
"(",
"lambda",
"x",
":",
"convert_to_geotype",
"(",
"x",
",",
"kwargs",
".",
"get",
"(",
"'crs'",
")",
")",
",",
"Element",
")"
] | Converts any elements in the input to their equivalent geotypes
if given a coordinate reference system. | [
"Converts",
"any",
"elements",
"in",
"the",
"input",
"to",
"their",
"equivalent",
"geotypes",
"if",
"given",
"a",
"coordinate",
"reference",
"system",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/operation/__init__.py#L49-L54 | train | 202,516 |
pyviz/geoviews | geoviews/element/geo.py | is_geographic | def is_geographic(element, kdims=None):
"""
Utility to determine whether the supplied element optionally
a subset of its key dimensions represent a geographic coordinate
system.
"""
if isinstance(element, (Overlay, NdOverlay)):
return any(element.traverse(is_geographic, [_Element]))
if kdims:
kdims = [element.get_dimension(d) for d in kdims]
else:
kdims = element.kdims
if len(kdims) != 2 and not isinstance(element, (Graph, Nodes)):
return False
if isinstance(element.data, geographic_types) or isinstance(element, (WMTS, Feature)):
return True
elif isinstance(element, _Element):
return kdims == element.kdims and element.crs
else:
return False | python | def is_geographic(element, kdims=None):
"""
Utility to determine whether the supplied element optionally
a subset of its key dimensions represent a geographic coordinate
system.
"""
if isinstance(element, (Overlay, NdOverlay)):
return any(element.traverse(is_geographic, [_Element]))
if kdims:
kdims = [element.get_dimension(d) for d in kdims]
else:
kdims = element.kdims
if len(kdims) != 2 and not isinstance(element, (Graph, Nodes)):
return False
if isinstance(element.data, geographic_types) or isinstance(element, (WMTS, Feature)):
return True
elif isinstance(element, _Element):
return kdims == element.kdims and element.crs
else:
return False | [
"def",
"is_geographic",
"(",
"element",
",",
"kdims",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"element",
",",
"(",
"Overlay",
",",
"NdOverlay",
")",
")",
":",
"return",
"any",
"(",
"element",
".",
"traverse",
"(",
"is_geographic",
",",
"[",
"_E... | Utility to determine whether the supplied element optionally
a subset of its key dimensions represent a geographic coordinate
system. | [
"Utility",
"to",
"determine",
"whether",
"the",
"supplied",
"element",
"optionally",
"a",
"subset",
"of",
"its",
"key",
"dimensions",
"represent",
"a",
"geographic",
"coordinate",
"system",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/element/geo.py#L39-L60 | train | 202,517 |
pyviz/geoviews | geoviews/element/geo.py | Feature.geoms | def geoms(self, scale=None, bounds=None, as_element=True):
"""
Returns the geometries held by the Feature.
Parameters
----------
scale: str
Scale of the geometry to return expressed as string.
Available scales depends on the Feature type.
NaturalEarthFeature:
'10m', '50m', '110m'
GSHHSFeature:
'auto', 'coarse', 'low', 'intermediate', 'high', 'full'
bounds: tuple
Tuple of a bounding region to query for geometries in
as_element: boolean
Whether to wrap the geometries in an element
Returns
-------
geometries: Polygons/Path
Polygons or Path object wrapping around returned geometries
"""
feature = self.data
if scale is not None:
feature = feature.with_scale(scale)
if bounds:
extent = (bounds[0], bounds[2], bounds[1], bounds[3])
else:
extent = None
geoms = [g for g in feature.intersecting_geometries(extent) if g is not None]
if not as_element:
return geoms
elif not geoms or 'Polygon' in geoms[0].geom_type:
return Polygons(geoms, crs=feature.crs)
elif 'Point' in geoms[0].geom_type:
return Points(geoms, crs=feature.crs)
else:
return Path(geoms, crs=feature.crs) | python | def geoms(self, scale=None, bounds=None, as_element=True):
"""
Returns the geometries held by the Feature.
Parameters
----------
scale: str
Scale of the geometry to return expressed as string.
Available scales depends on the Feature type.
NaturalEarthFeature:
'10m', '50m', '110m'
GSHHSFeature:
'auto', 'coarse', 'low', 'intermediate', 'high', 'full'
bounds: tuple
Tuple of a bounding region to query for geometries in
as_element: boolean
Whether to wrap the geometries in an element
Returns
-------
geometries: Polygons/Path
Polygons or Path object wrapping around returned geometries
"""
feature = self.data
if scale is not None:
feature = feature.with_scale(scale)
if bounds:
extent = (bounds[0], bounds[2], bounds[1], bounds[3])
else:
extent = None
geoms = [g for g in feature.intersecting_geometries(extent) if g is not None]
if not as_element:
return geoms
elif not geoms or 'Polygon' in geoms[0].geom_type:
return Polygons(geoms, crs=feature.crs)
elif 'Point' in geoms[0].geom_type:
return Points(geoms, crs=feature.crs)
else:
return Path(geoms, crs=feature.crs) | [
"def",
"geoms",
"(",
"self",
",",
"scale",
"=",
"None",
",",
"bounds",
"=",
"None",
",",
"as_element",
"=",
"True",
")",
":",
"feature",
"=",
"self",
".",
"data",
"if",
"scale",
"is",
"not",
"None",
":",
"feature",
"=",
"feature",
".",
"with_scale",
... | Returns the geometries held by the Feature.
Parameters
----------
scale: str
Scale of the geometry to return expressed as string.
Available scales depends on the Feature type.
NaturalEarthFeature:
'10m', '50m', '110m'
GSHHSFeature:
'auto', 'coarse', 'low', 'intermediate', 'high', 'full'
bounds: tuple
Tuple of a bounding region to query for geometries in
as_element: boolean
Whether to wrap the geometries in an element
Returns
-------
geometries: Polygons/Path
Polygons or Path object wrapping around returned geometries | [
"Returns",
"the",
"geometries",
"held",
"by",
"the",
"Feature",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/element/geo.py#L142-L184 | train | 202,518 |
pyviz/geoviews | geoviews/element/geo.py | Shape.from_shapefile | def from_shapefile(cls, shapefile, *args, **kwargs):
"""
Loads a shapefile from disk and optionally merges
it with a dataset. See ``from_records`` for full
signature.
Parameters
----------
records: list of cartopy.io.shapereader.Record
Iterator containing Records.
dataset: holoviews.Dataset
Any HoloViews Dataset type.
on: str or list or dict
A mapping between the attribute names in the records and the
dimensions in the dataset.
value: str
The value dimension in the dataset the values will be drawn
from.
index: str or list
One or more dimensions in the dataset the Shapes will be
indexed by.
drop_missing: boolean
Whether to drop shapes which are missing from the provides
dataset.
Returns
-------
shapes: Polygons or Path object
A Polygons or Path object containing the geometries
"""
reader = Reader(shapefile)
return cls.from_records(reader.records(), *args, **kwargs) | python | def from_shapefile(cls, shapefile, *args, **kwargs):
"""
Loads a shapefile from disk and optionally merges
it with a dataset. See ``from_records`` for full
signature.
Parameters
----------
records: list of cartopy.io.shapereader.Record
Iterator containing Records.
dataset: holoviews.Dataset
Any HoloViews Dataset type.
on: str or list or dict
A mapping between the attribute names in the records and the
dimensions in the dataset.
value: str
The value dimension in the dataset the values will be drawn
from.
index: str or list
One or more dimensions in the dataset the Shapes will be
indexed by.
drop_missing: boolean
Whether to drop shapes which are missing from the provides
dataset.
Returns
-------
shapes: Polygons or Path object
A Polygons or Path object containing the geometries
"""
reader = Reader(shapefile)
return cls.from_records(reader.records(), *args, **kwargs) | [
"def",
"from_shapefile",
"(",
"cls",
",",
"shapefile",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"reader",
"=",
"Reader",
"(",
"shapefile",
")",
"return",
"cls",
".",
"from_records",
"(",
"reader",
".",
"records",
"(",
")",
",",
"*",
"args... | Loads a shapefile from disk and optionally merges
it with a dataset. See ``from_records`` for full
signature.
Parameters
----------
records: list of cartopy.io.shapereader.Record
Iterator containing Records.
dataset: holoviews.Dataset
Any HoloViews Dataset type.
on: str or list or dict
A mapping between the attribute names in the records and the
dimensions in the dataset.
value: str
The value dimension in the dataset the values will be drawn
from.
index: str or list
One or more dimensions in the dataset the Shapes will be
indexed by.
drop_missing: boolean
Whether to drop shapes which are missing from the provides
dataset.
Returns
-------
shapes: Polygons or Path object
A Polygons or Path object containing the geometries | [
"Loads",
"a",
"shapefile",
"from",
"disk",
"and",
"optionally",
"merges",
"it",
"with",
"a",
"dataset",
".",
"See",
"from_records",
"for",
"full",
"signature",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/element/geo.py#L661-L692 | train | 202,519 |
pyviz/geoviews | geoviews/element/geo.py | Shape.from_records | def from_records(cls, records, dataset=None, on=None, value=None,
index=[], drop_missing=False, element=None, **kwargs):
"""
Load data from a collection of `cartopy.io.shapereader.Record`
objects and optionally merge it with a dataset to assign
values to each polygon and form a chloropleth. Supplying just
records will return an NdOverlayof Shape Elements with a
numeric index. If a dataset is supplied, a mapping between the
attribute names in the records and the dimension names in the
dataset must be supplied. The values assigned to each shape
file can then be drawn from the dataset by supplying a
``value`` and keys the Shapes are indexed by specifying one or
index dimensions.
Parameters
----------
records: list of cartopy.io.shapereader.Record
Iterator containing Records.
dataset: holoviews.Dataset
Any HoloViews Dataset type.
on: str or list or dict
A mapping between the attribute names in the records and the
dimensions in the dataset.
value: str
The value dimension in the dataset the values will be drawn
from.
index: str or list
One or more dimensions in the dataset the Shapes will be
indexed by.
drop_missing: boolean
Whether to drop shapes which are missing from the provides
dataset.
Returns
-------
shapes: Polygons or Path object
A Polygons or Path object containing the geometries
"""
if dataset is not None and not on:
raise ValueError('To merge dataset with shapes mapping '
'must define attribute(s) to merge on.')
if util.pd and isinstance(dataset, util.pd.DataFrame):
dataset = Dataset(dataset)
if not isinstance(on, (dict, list)):
on = [on]
if on and not isinstance(on, dict):
on = {o: o for o in on}
if not isinstance(index, list):
index = [index]
kdims = []
for ind in index:
if dataset and dataset.get_dimension(ind):
dim = dataset.get_dimension(ind)
else:
dim = Dimension(ind)
kdims.append(dim)
ddims = []
if dataset:
if value:
vdims = [dataset.get_dimension(value)]
else:
vdims = dataset.vdims
ddims = dataset.dimensions()
if None in vdims:
raise ValueError('Value dimension %s not found '
'in dataset dimensions %s' % (value, ddims) )
else:
vdims = []
data = []
for i, rec in enumerate(records):
geom = {}
if dataset:
selection = {dim: rec.attributes.get(attr, None)
for attr, dim in on.items()}
row = dataset.select(**selection)
if len(row):
values = {k: v[0] for k, v in row.iloc[0].columns().items()}
elif drop_missing:
continue
else:
values = {vd.name: np.nan for vd in vdims}
geom.update(values)
if index:
for kdim in kdims:
if kdim in ddims and len(row):
k = row[kdim.name][0]
elif kdim.name in rec.attributes:
k = rec.attributes[kdim.name]
else:
k = None
geom[kdim.name] = k
geom['geometry'] = rec.geometry
data.append(geom)
if element is not None:
pass
elif data and data[0]:
if isinstance(data[0]['geometry'], poly_types):
element = Polygons
else:
element = Path
else:
element = Polygons
return element(data, vdims=kdims+vdims, **kwargs).opts(color=value) | python | def from_records(cls, records, dataset=None, on=None, value=None,
index=[], drop_missing=False, element=None, **kwargs):
"""
Load data from a collection of `cartopy.io.shapereader.Record`
objects and optionally merge it with a dataset to assign
values to each polygon and form a chloropleth. Supplying just
records will return an NdOverlayof Shape Elements with a
numeric index. If a dataset is supplied, a mapping between the
attribute names in the records and the dimension names in the
dataset must be supplied. The values assigned to each shape
file can then be drawn from the dataset by supplying a
``value`` and keys the Shapes are indexed by specifying one or
index dimensions.
Parameters
----------
records: list of cartopy.io.shapereader.Record
Iterator containing Records.
dataset: holoviews.Dataset
Any HoloViews Dataset type.
on: str or list or dict
A mapping between the attribute names in the records and the
dimensions in the dataset.
value: str
The value dimension in the dataset the values will be drawn
from.
index: str or list
One or more dimensions in the dataset the Shapes will be
indexed by.
drop_missing: boolean
Whether to drop shapes which are missing from the provides
dataset.
Returns
-------
shapes: Polygons or Path object
A Polygons or Path object containing the geometries
"""
if dataset is not None and not on:
raise ValueError('To merge dataset with shapes mapping '
'must define attribute(s) to merge on.')
if util.pd and isinstance(dataset, util.pd.DataFrame):
dataset = Dataset(dataset)
if not isinstance(on, (dict, list)):
on = [on]
if on and not isinstance(on, dict):
on = {o: o for o in on}
if not isinstance(index, list):
index = [index]
kdims = []
for ind in index:
if dataset and dataset.get_dimension(ind):
dim = dataset.get_dimension(ind)
else:
dim = Dimension(ind)
kdims.append(dim)
ddims = []
if dataset:
if value:
vdims = [dataset.get_dimension(value)]
else:
vdims = dataset.vdims
ddims = dataset.dimensions()
if None in vdims:
raise ValueError('Value dimension %s not found '
'in dataset dimensions %s' % (value, ddims) )
else:
vdims = []
data = []
for i, rec in enumerate(records):
geom = {}
if dataset:
selection = {dim: rec.attributes.get(attr, None)
for attr, dim in on.items()}
row = dataset.select(**selection)
if len(row):
values = {k: v[0] for k, v in row.iloc[0].columns().items()}
elif drop_missing:
continue
else:
values = {vd.name: np.nan for vd in vdims}
geom.update(values)
if index:
for kdim in kdims:
if kdim in ddims and len(row):
k = row[kdim.name][0]
elif kdim.name in rec.attributes:
k = rec.attributes[kdim.name]
else:
k = None
geom[kdim.name] = k
geom['geometry'] = rec.geometry
data.append(geom)
if element is not None:
pass
elif data and data[0]:
if isinstance(data[0]['geometry'], poly_types):
element = Polygons
else:
element = Path
else:
element = Polygons
return element(data, vdims=kdims+vdims, **kwargs).opts(color=value) | [
"def",
"from_records",
"(",
"cls",
",",
"records",
",",
"dataset",
"=",
"None",
",",
"on",
"=",
"None",
",",
"value",
"=",
"None",
",",
"index",
"=",
"[",
"]",
",",
"drop_missing",
"=",
"False",
",",
"element",
"=",
"None",
",",
"*",
"*",
"kwargs",... | Load data from a collection of `cartopy.io.shapereader.Record`
objects and optionally merge it with a dataset to assign
values to each polygon and form a chloropleth. Supplying just
records will return an NdOverlayof Shape Elements with a
numeric index. If a dataset is supplied, a mapping between the
attribute names in the records and the dimension names in the
dataset must be supplied. The values assigned to each shape
file can then be drawn from the dataset by supplying a
``value`` and keys the Shapes are indexed by specifying one or
index dimensions.
Parameters
----------
records: list of cartopy.io.shapereader.Record
Iterator containing Records.
dataset: holoviews.Dataset
Any HoloViews Dataset type.
on: str or list or dict
A mapping between the attribute names in the records and the
dimensions in the dataset.
value: str
The value dimension in the dataset the values will be drawn
from.
index: str or list
One or more dimensions in the dataset the Shapes will be
indexed by.
drop_missing: boolean
Whether to drop shapes which are missing from the provides
dataset.
Returns
-------
shapes: Polygons or Path object
A Polygons or Path object containing the geometries | [
"Load",
"data",
"from",
"a",
"collection",
"of",
"cartopy",
".",
"io",
".",
"shapereader",
".",
"Record",
"objects",
"and",
"optionally",
"merge",
"it",
"with",
"a",
"dataset",
"to",
"assign",
"values",
"to",
"each",
"polygon",
"and",
"form",
"a",
"chlorop... | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/element/geo.py#L696-L807 | train | 202,520 |
pyviz/geoviews | geoviews/plotting/bokeh/callbacks.py | get_cb_plot | def get_cb_plot(cb, plot=None):
"""
Finds the subplot with the corresponding stream.
"""
plot = plot or cb.plot
if isinstance(plot, GeoOverlayPlot):
plots = [get_cb_plot(cb, p) for p in plot.subplots.values()]
plots = [p for p in plots if any(s in cb.streams and getattr(s, '_triggering', False)
for s in p.streams)]
if plots:
plot = plots[0]
return plot | python | def get_cb_plot(cb, plot=None):
"""
Finds the subplot with the corresponding stream.
"""
plot = plot or cb.plot
if isinstance(plot, GeoOverlayPlot):
plots = [get_cb_plot(cb, p) for p in plot.subplots.values()]
plots = [p for p in plots if any(s in cb.streams and getattr(s, '_triggering', False)
for s in p.streams)]
if plots:
plot = plots[0]
return plot | [
"def",
"get_cb_plot",
"(",
"cb",
",",
"plot",
"=",
"None",
")",
":",
"plot",
"=",
"plot",
"or",
"cb",
".",
"plot",
"if",
"isinstance",
"(",
"plot",
",",
"GeoOverlayPlot",
")",
":",
"plots",
"=",
"[",
"get_cb_plot",
"(",
"cb",
",",
"p",
")",
"for",
... | Finds the subplot with the corresponding stream. | [
"Finds",
"the",
"subplot",
"with",
"the",
"corresponding",
"stream",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/plotting/bokeh/callbacks.py#L23-L34 | train | 202,521 |
pyviz/geoviews | geoviews/plotting/bokeh/callbacks.py | skip | def skip(cb, msg, attributes):
"""
Skips applying transforms if data is not geographic.
"""
if not all(a in msg for a in attributes):
return True
plot = get_cb_plot(cb)
return (not getattr(plot, 'geographic', False) or
not hasattr(plot.current_frame, 'crs')) | python | def skip(cb, msg, attributes):
"""
Skips applying transforms if data is not geographic.
"""
if not all(a in msg for a in attributes):
return True
plot = get_cb_plot(cb)
return (not getattr(plot, 'geographic', False) or
not hasattr(plot.current_frame, 'crs')) | [
"def",
"skip",
"(",
"cb",
",",
"msg",
",",
"attributes",
")",
":",
"if",
"not",
"all",
"(",
"a",
"in",
"msg",
"for",
"a",
"in",
"attributes",
")",
":",
"return",
"True",
"plot",
"=",
"get_cb_plot",
"(",
"cb",
")",
"return",
"(",
"not",
"getattr",
... | Skips applying transforms if data is not geographic. | [
"Skips",
"applying",
"transforms",
"if",
"data",
"is",
"not",
"geographic",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/plotting/bokeh/callbacks.py#L37-L45 | train | 202,522 |
pyviz/geoviews | geoviews/plotting/bokeh/callbacks.py | project_ranges | def project_ranges(cb, msg, attributes):
"""
Projects ranges supplied by a callback.
"""
if skip(cb, msg, attributes):
return msg
plot = get_cb_plot(cb)
x0, x1 = msg.get('x_range', (0, 1000))
y0, y1 = msg.get('y_range', (0, 1000))
extents = x0, y0, x1, y1
x0, y0, x1, y1 = project_extents(extents, plot.projection,
plot.current_frame.crs)
coords = {'x_range': (x0, x1), 'y_range': (y0, y1)}
return {k: v for k, v in coords.items() if k in attributes} | python | def project_ranges(cb, msg, attributes):
"""
Projects ranges supplied by a callback.
"""
if skip(cb, msg, attributes):
return msg
plot = get_cb_plot(cb)
x0, x1 = msg.get('x_range', (0, 1000))
y0, y1 = msg.get('y_range', (0, 1000))
extents = x0, y0, x1, y1
x0, y0, x1, y1 = project_extents(extents, plot.projection,
plot.current_frame.crs)
coords = {'x_range': (x0, x1), 'y_range': (y0, y1)}
return {k: v for k, v in coords.items() if k in attributes} | [
"def",
"project_ranges",
"(",
"cb",
",",
"msg",
",",
"attributes",
")",
":",
"if",
"skip",
"(",
"cb",
",",
"msg",
",",
"attributes",
")",
":",
"return",
"msg",
"plot",
"=",
"get_cb_plot",
"(",
"cb",
")",
"x0",
",",
"x1",
"=",
"msg",
".",
"get",
"... | Projects ranges supplied by a callback. | [
"Projects",
"ranges",
"supplied",
"by",
"a",
"callback",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/plotting/bokeh/callbacks.py#L48-L62 | train | 202,523 |
pyviz/geoviews | geoviews/plotting/bokeh/callbacks.py | project_point | def project_point(cb, msg, attributes=('x', 'y')):
"""
Projects a single point supplied by a callback
"""
if skip(cb, msg, attributes): return msg
plot = get_cb_plot(cb)
x, y = msg.get('x', 0), msg.get('y', 0)
crs = plot.current_frame.crs
coordinates = crs.transform_points(plot.projection, np.array([x]), np.array([y]))
msg['x'], msg['y'] = coordinates[0, :2]
return {k: v for k, v in msg.items() if k in attributes} | python | def project_point(cb, msg, attributes=('x', 'y')):
"""
Projects a single point supplied by a callback
"""
if skip(cb, msg, attributes): return msg
plot = get_cb_plot(cb)
x, y = msg.get('x', 0), msg.get('y', 0)
crs = plot.current_frame.crs
coordinates = crs.transform_points(plot.projection, np.array([x]), np.array([y]))
msg['x'], msg['y'] = coordinates[0, :2]
return {k: v for k, v in msg.items() if k in attributes} | [
"def",
"project_point",
"(",
"cb",
",",
"msg",
",",
"attributes",
"=",
"(",
"'x'",
",",
"'y'",
")",
")",
":",
"if",
"skip",
"(",
"cb",
",",
"msg",
",",
"attributes",
")",
":",
"return",
"msg",
"plot",
"=",
"get_cb_plot",
"(",
"cb",
")",
"x",
",",... | Projects a single point supplied by a callback | [
"Projects",
"a",
"single",
"point",
"supplied",
"by",
"a",
"callback"
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/plotting/bokeh/callbacks.py#L65-L75 | train | 202,524 |
pyviz/geoviews | geoviews/plotting/bokeh/callbacks.py | project_drawn | def project_drawn(cb, msg):
"""
Projects a drawn element to the declared coordinate system
"""
stream = cb.streams[0]
old_data = stream.data
stream.update(data=msg['data'])
element = stream.element
stream.update(data=old_data)
proj = cb.plot.projection
if not isinstance(element, _Element) or element.crs == proj:
return None
crs = element.crs
element.crs = proj
return project(element, projection=crs) | python | def project_drawn(cb, msg):
"""
Projects a drawn element to the declared coordinate system
"""
stream = cb.streams[0]
old_data = stream.data
stream.update(data=msg['data'])
element = stream.element
stream.update(data=old_data)
proj = cb.plot.projection
if not isinstance(element, _Element) or element.crs == proj:
return None
crs = element.crs
element.crs = proj
return project(element, projection=crs) | [
"def",
"project_drawn",
"(",
"cb",
",",
"msg",
")",
":",
"stream",
"=",
"cb",
".",
"streams",
"[",
"0",
"]",
"old_data",
"=",
"stream",
".",
"data",
"stream",
".",
"update",
"(",
"data",
"=",
"msg",
"[",
"'data'",
"]",
")",
"element",
"=",
"stream"... | Projects a drawn element to the declared coordinate system | [
"Projects",
"a",
"drawn",
"element",
"to",
"the",
"declared",
"coordinate",
"system"
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/plotting/bokeh/callbacks.py#L78-L92 | train | 202,525 |
pyviz/geoviews | geoviews/operation/regrid.py | weighted_regrid.clean_weight_files | def clean_weight_files(cls):
"""
Cleans existing weight files.
"""
deleted = []
for f in cls._files:
try:
os.remove(f)
deleted.append(f)
except FileNotFoundError:
pass
print('Deleted %d weight files' % len(deleted))
cls._files = [] | python | def clean_weight_files(cls):
"""
Cleans existing weight files.
"""
deleted = []
for f in cls._files:
try:
os.remove(f)
deleted.append(f)
except FileNotFoundError:
pass
print('Deleted %d weight files' % len(deleted))
cls._files = [] | [
"def",
"clean_weight_files",
"(",
"cls",
")",
":",
"deleted",
"=",
"[",
"]",
"for",
"f",
"in",
"cls",
".",
"_files",
":",
"try",
":",
"os",
".",
"remove",
"(",
"f",
")",
"deleted",
".",
"append",
"(",
"f",
")",
"except",
"FileNotFoundError",
":",
"... | Cleans existing weight files. | [
"Cleans",
"existing",
"weight",
"files",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/operation/regrid.py#L117-L129 | train | 202,526 |
pyviz/geoviews | geoviews/plotting/plot.py | _get_projection | def _get_projection(el):
"""
Get coordinate reference system from non-auxiliary elements.
Return value is a tuple of a precedence integer and the projection,
to allow non-auxiliary components to take precedence.
"""
result = None
if hasattr(el, 'crs'):
result = (int(el._auxiliary_component), el.crs)
return result | python | def _get_projection(el):
"""
Get coordinate reference system from non-auxiliary elements.
Return value is a tuple of a precedence integer and the projection,
to allow non-auxiliary components to take precedence.
"""
result = None
if hasattr(el, 'crs'):
result = (int(el._auxiliary_component), el.crs)
return result | [
"def",
"_get_projection",
"(",
"el",
")",
":",
"result",
"=",
"None",
"if",
"hasattr",
"(",
"el",
",",
"'crs'",
")",
":",
"result",
"=",
"(",
"int",
"(",
"el",
".",
"_auxiliary_component",
")",
",",
"el",
".",
"crs",
")",
"return",
"result"
] | Get coordinate reference system from non-auxiliary elements.
Return value is a tuple of a precedence integer and the projection,
to allow non-auxiliary components to take precedence. | [
"Get",
"coordinate",
"reference",
"system",
"from",
"non",
"-",
"auxiliary",
"elements",
".",
"Return",
"value",
"is",
"a",
"tuple",
"of",
"a",
"precedence",
"integer",
"and",
"the",
"projection",
"to",
"allow",
"non",
"-",
"auxiliary",
"components",
"to",
"... | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/plotting/plot.py#L9-L18 | train | 202,527 |
pyviz/geoviews | geoviews/plotting/plot.py | ProjectionPlot.get_extents | def get_extents(self, element, ranges, range_type='combined'):
"""
Subclasses the get_extents method using the GeoAxes
set_extent method to project the extents to the
Elements coordinate reference system.
"""
proj = self.projection
if self.global_extent and range_type in ('combined', 'data'):
(x0, x1), (y0, y1) = proj.x_limits, proj.y_limits
return (x0, y0, x1, y1)
extents = super(ProjectionPlot, self).get_extents(element, ranges, range_type)
if not getattr(element, 'crs', None) or not self.geographic:
return extents
elif any(e is None or not np.isfinite(e) for e in extents):
extents = None
else:
extents = project_extents(extents, element.crs, proj)
return (np.NaN,)*4 if not extents else extents | python | def get_extents(self, element, ranges, range_type='combined'):
"""
Subclasses the get_extents method using the GeoAxes
set_extent method to project the extents to the
Elements coordinate reference system.
"""
proj = self.projection
if self.global_extent and range_type in ('combined', 'data'):
(x0, x1), (y0, y1) = proj.x_limits, proj.y_limits
return (x0, y0, x1, y1)
extents = super(ProjectionPlot, self).get_extents(element, ranges, range_type)
if not getattr(element, 'crs', None) or not self.geographic:
return extents
elif any(e is None or not np.isfinite(e) for e in extents):
extents = None
else:
extents = project_extents(extents, element.crs, proj)
return (np.NaN,)*4 if not extents else extents | [
"def",
"get_extents",
"(",
"self",
",",
"element",
",",
"ranges",
",",
"range_type",
"=",
"'combined'",
")",
":",
"proj",
"=",
"self",
".",
"projection",
"if",
"self",
".",
"global_extent",
"and",
"range_type",
"in",
"(",
"'combined'",
",",
"'data'",
")",
... | Subclasses the get_extents method using the GeoAxes
set_extent method to project the extents to the
Elements coordinate reference system. | [
"Subclasses",
"the",
"get_extents",
"method",
"using",
"the",
"GeoAxes",
"set_extent",
"method",
"to",
"project",
"the",
"extents",
"to",
"the",
"Elements",
"coordinate",
"reference",
"system",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/plotting/plot.py#L57-L74 | train | 202,528 |
pyviz/geoviews | geoviews/util.py | wrap_lons | def wrap_lons(lons, base, period):
"""
Wrap longitude values into the range between base and base+period.
"""
lons = lons.astype(np.float64)
return ((lons - base + period * 2) % period) + base | python | def wrap_lons(lons, base, period):
"""
Wrap longitude values into the range between base and base+period.
"""
lons = lons.astype(np.float64)
return ((lons - base + period * 2) % period) + base | [
"def",
"wrap_lons",
"(",
"lons",
",",
"base",
",",
"period",
")",
":",
"lons",
"=",
"lons",
".",
"astype",
"(",
"np",
".",
"float64",
")",
"return",
"(",
"(",
"lons",
"-",
"base",
"+",
"period",
"*",
"2",
")",
"%",
"period",
")",
"+",
"base"
] | Wrap longitude values into the range between base and base+period. | [
"Wrap",
"longitude",
"values",
"into",
"the",
"range",
"between",
"base",
"and",
"base",
"+",
"period",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/util.py#L20-L25 | train | 202,529 |
pyviz/geoviews | geoviews/util.py | geom_dict_to_array_dict | def geom_dict_to_array_dict(geom_dict, coord_names=['Longitude', 'Latitude']):
"""
Converts a dictionary containing an geometry key to a dictionary
of x- and y-coordinate arrays and if present a list-of-lists of
hole array.
"""
x, y = coord_names
geom = geom_dict['geometry']
new_dict = {k: v for k, v in geom_dict.items() if k != 'geometry'}
array = geom_to_array(geom)
new_dict[x] = array[:, 0]
new_dict[y] = array[:, 1]
if geom.geom_type == 'Polygon':
holes = []
for interior in geom.interiors:
holes.append(geom_to_array(interior))
if holes:
new_dict['holes'] = [holes]
elif geom.geom_type == 'MultiPolygon':
outer_holes = []
for g in geom:
holes = []
for interior in g.interiors:
holes.append(geom_to_array(interior))
outer_holes.append(holes)
if any(hs for hs in outer_holes):
new_dict['holes'] = outer_holes
return new_dict | python | def geom_dict_to_array_dict(geom_dict, coord_names=['Longitude', 'Latitude']):
"""
Converts a dictionary containing an geometry key to a dictionary
of x- and y-coordinate arrays and if present a list-of-lists of
hole array.
"""
x, y = coord_names
geom = geom_dict['geometry']
new_dict = {k: v for k, v in geom_dict.items() if k != 'geometry'}
array = geom_to_array(geom)
new_dict[x] = array[:, 0]
new_dict[y] = array[:, 1]
if geom.geom_type == 'Polygon':
holes = []
for interior in geom.interiors:
holes.append(geom_to_array(interior))
if holes:
new_dict['holes'] = [holes]
elif geom.geom_type == 'MultiPolygon':
outer_holes = []
for g in geom:
holes = []
for interior in g.interiors:
holes.append(geom_to_array(interior))
outer_holes.append(holes)
if any(hs for hs in outer_holes):
new_dict['holes'] = outer_holes
return new_dict | [
"def",
"geom_dict_to_array_dict",
"(",
"geom_dict",
",",
"coord_names",
"=",
"[",
"'Longitude'",
",",
"'Latitude'",
"]",
")",
":",
"x",
",",
"y",
"=",
"coord_names",
"geom",
"=",
"geom_dict",
"[",
"'geometry'",
"]",
"new_dict",
"=",
"{",
"k",
":",
"v",
"... | Converts a dictionary containing an geometry key to a dictionary
of x- and y-coordinate arrays and if present a list-of-lists of
hole array. | [
"Converts",
"a",
"dictionary",
"containing",
"an",
"geometry",
"key",
"to",
"a",
"dictionary",
"of",
"x",
"-",
"and",
"y",
"-",
"coordinate",
"arrays",
"and",
"if",
"present",
"a",
"list",
"-",
"of",
"-",
"lists",
"of",
"hole",
"array",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/util.py#L92-L119 | train | 202,530 |
pyviz/geoviews | geoviews/util.py | polygons_to_geom_dicts | def polygons_to_geom_dicts(polygons, skip_invalid=True):
"""
Converts a Polygons element into a list of geometry dictionaries,
preserving all value dimensions.
For array conversion the following conventions are applied:
* Any nan separated array are converted into a MultiPolygon
* Any array without nans is converted to a Polygon
* If there are holes associated with a nan separated array
the holes are assigned to the polygons by testing for an
intersection
* If any single array does not have at least three coordinates
it is skipped by default
* If skip_invalid=False and an array has less than three
coordinates it will be converted to a LineString
"""
interface = polygons.interface.datatype
if interface == 'geodataframe':
return [row.to_dict() for _, row in polygons.data.iterrows()]
elif interface == 'geom_dictionary':
return polygons.data
polys = []
xdim, ydim = polygons.kdims
has_holes = polygons.has_holes
holes = polygons.holes() if has_holes else None
for i, polygon in enumerate(polygons.split(datatype='columns')):
array = np.column_stack([polygon.pop(xdim.name), polygon.pop(ydim.name)])
splits = np.where(np.isnan(array[:, :2].astype('float')).sum(axis=1))[0]
arrays = np.split(array, splits+1) if len(splits) else [array]
invalid = False
subpolys = []
subholes = None
if has_holes:
subholes = [[LinearRing(h) for h in hs] for hs in holes[i]]
for j, arr in enumerate(arrays):
if j != (len(arrays)-1):
arr = arr[:-1] # Drop nan
if len(arr) == 0:
continue
elif len(arr) == 1:
if skip_invalid:
continue
poly = Point(arr[0])
invalid = True
elif len(arr) == 2:
if skip_invalid:
continue
poly = LineString(arr)
invalid = True
elif not len(splits):
poly = Polygon(arr, (subholes[j] if has_holes else []))
else:
poly = Polygon(arr)
hs = [h for h in subholes[j]] if has_holes else []
poly = Polygon(poly.exterior, holes=hs)
subpolys.append(poly)
if invalid:
polys += [dict(polygon, geometry=sp) for sp in subpolys]
continue
elif len(subpolys) == 1:
geom = subpolys[0]
elif subpolys:
geom = MultiPolygon(subpolys)
else:
continue
polygon['geometry'] = geom
polys.append(polygon)
return polys | python | def polygons_to_geom_dicts(polygons, skip_invalid=True):
"""
Converts a Polygons element into a list of geometry dictionaries,
preserving all value dimensions.
For array conversion the following conventions are applied:
* Any nan separated array are converted into a MultiPolygon
* Any array without nans is converted to a Polygon
* If there are holes associated with a nan separated array
the holes are assigned to the polygons by testing for an
intersection
* If any single array does not have at least three coordinates
it is skipped by default
* If skip_invalid=False and an array has less than three
coordinates it will be converted to a LineString
"""
interface = polygons.interface.datatype
if interface == 'geodataframe':
return [row.to_dict() for _, row in polygons.data.iterrows()]
elif interface == 'geom_dictionary':
return polygons.data
polys = []
xdim, ydim = polygons.kdims
has_holes = polygons.has_holes
holes = polygons.holes() if has_holes else None
for i, polygon in enumerate(polygons.split(datatype='columns')):
array = np.column_stack([polygon.pop(xdim.name), polygon.pop(ydim.name)])
splits = np.where(np.isnan(array[:, :2].astype('float')).sum(axis=1))[0]
arrays = np.split(array, splits+1) if len(splits) else [array]
invalid = False
subpolys = []
subholes = None
if has_holes:
subholes = [[LinearRing(h) for h in hs] for hs in holes[i]]
for j, arr in enumerate(arrays):
if j != (len(arrays)-1):
arr = arr[:-1] # Drop nan
if len(arr) == 0:
continue
elif len(arr) == 1:
if skip_invalid:
continue
poly = Point(arr[0])
invalid = True
elif len(arr) == 2:
if skip_invalid:
continue
poly = LineString(arr)
invalid = True
elif not len(splits):
poly = Polygon(arr, (subholes[j] if has_holes else []))
else:
poly = Polygon(arr)
hs = [h for h in subholes[j]] if has_holes else []
poly = Polygon(poly.exterior, holes=hs)
subpolys.append(poly)
if invalid:
polys += [dict(polygon, geometry=sp) for sp in subpolys]
continue
elif len(subpolys) == 1:
geom = subpolys[0]
elif subpolys:
geom = MultiPolygon(subpolys)
else:
continue
polygon['geometry'] = geom
polys.append(polygon)
return polys | [
"def",
"polygons_to_geom_dicts",
"(",
"polygons",
",",
"skip_invalid",
"=",
"True",
")",
":",
"interface",
"=",
"polygons",
".",
"interface",
".",
"datatype",
"if",
"interface",
"==",
"'geodataframe'",
":",
"return",
"[",
"row",
".",
"to_dict",
"(",
")",
"fo... | Converts a Polygons element into a list of geometry dictionaries,
preserving all value dimensions.
For array conversion the following conventions are applied:
* Any nan separated array are converted into a MultiPolygon
* Any array without nans is converted to a Polygon
* If there are holes associated with a nan separated array
the holes are assigned to the polygons by testing for an
intersection
* If any single array does not have at least three coordinates
it is skipped by default
* If skip_invalid=False and an array has less than three
coordinates it will be converted to a LineString | [
"Converts",
"a",
"Polygons",
"element",
"into",
"a",
"list",
"of",
"geometry",
"dictionaries",
"preserving",
"all",
"value",
"dimensions",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/util.py#L181-L253 | train | 202,531 |
pyviz/geoviews | geoviews/util.py | path_to_geom_dicts | def path_to_geom_dicts(path, skip_invalid=True):
"""
Converts a Path element into a list of geometry dictionaries,
preserving all value dimensions.
"""
interface = path.interface.datatype
if interface == 'geodataframe':
return [row.to_dict() for _, row in path.data.iterrows()]
elif interface == 'geom_dictionary':
return path.data
geoms = []
invalid = False
xdim, ydim = path.kdims
for i, path in enumerate(path.split(datatype='columns')):
array = np.column_stack([path.pop(xdim.name), path.pop(ydim.name)])
splits = np.where(np.isnan(array[:, :2].astype('float')).sum(axis=1))[0]
arrays = np.split(array, splits+1) if len(splits) else [array]
subpaths = []
for j, arr in enumerate(arrays):
if j != (len(arrays)-1):
arr = arr[:-1] # Drop nan
if len(arr) == 0:
continue
elif len(arr) == 1:
if skip_invalid:
continue
g = Point(arr[0])
invalid = True
else:
g = LineString(arr)
subpaths.append(g)
if invalid:
geoms += [dict(path, geometry=sp) for sp in subpaths]
continue
elif len(subpaths) == 1:
geom = subpaths[0]
elif subpaths:
geom = MultiLineString(subpaths)
path['geometry'] = geom
geoms.append(path)
return geoms | python | def path_to_geom_dicts(path, skip_invalid=True):
"""
Converts a Path element into a list of geometry dictionaries,
preserving all value dimensions.
"""
interface = path.interface.datatype
if interface == 'geodataframe':
return [row.to_dict() for _, row in path.data.iterrows()]
elif interface == 'geom_dictionary':
return path.data
geoms = []
invalid = False
xdim, ydim = path.kdims
for i, path in enumerate(path.split(datatype='columns')):
array = np.column_stack([path.pop(xdim.name), path.pop(ydim.name)])
splits = np.where(np.isnan(array[:, :2].astype('float')).sum(axis=1))[0]
arrays = np.split(array, splits+1) if len(splits) else [array]
subpaths = []
for j, arr in enumerate(arrays):
if j != (len(arrays)-1):
arr = arr[:-1] # Drop nan
if len(arr) == 0:
continue
elif len(arr) == 1:
if skip_invalid:
continue
g = Point(arr[0])
invalid = True
else:
g = LineString(arr)
subpaths.append(g)
if invalid:
geoms += [dict(path, geometry=sp) for sp in subpaths]
continue
elif len(subpaths) == 1:
geom = subpaths[0]
elif subpaths:
geom = MultiLineString(subpaths)
path['geometry'] = geom
geoms.append(path)
return geoms | [
"def",
"path_to_geom_dicts",
"(",
"path",
",",
"skip_invalid",
"=",
"True",
")",
":",
"interface",
"=",
"path",
".",
"interface",
".",
"datatype",
"if",
"interface",
"==",
"'geodataframe'",
":",
"return",
"[",
"row",
".",
"to_dict",
"(",
")",
"for",
"_",
... | Converts a Path element into a list of geometry dictionaries,
preserving all value dimensions. | [
"Converts",
"a",
"Path",
"element",
"into",
"a",
"list",
"of",
"geometry",
"dictionaries",
"preserving",
"all",
"value",
"dimensions",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/util.py#L256-L299 | train | 202,532 |
pyviz/geoviews | geoviews/util.py | to_ccw | def to_ccw(geom):
"""
Reorients polygon to be wound counter-clockwise.
"""
if isinstance(geom, sgeom.Polygon) and not geom.exterior.is_ccw:
geom = sgeom.polygon.orient(geom)
return geom | python | def to_ccw(geom):
"""
Reorients polygon to be wound counter-clockwise.
"""
if isinstance(geom, sgeom.Polygon) and not geom.exterior.is_ccw:
geom = sgeom.polygon.orient(geom)
return geom | [
"def",
"to_ccw",
"(",
"geom",
")",
":",
"if",
"isinstance",
"(",
"geom",
",",
"sgeom",
".",
"Polygon",
")",
"and",
"not",
"geom",
".",
"exterior",
".",
"is_ccw",
":",
"geom",
"=",
"sgeom",
".",
"polygon",
".",
"orient",
"(",
"geom",
")",
"return",
... | Reorients polygon to be wound counter-clockwise. | [
"Reorients",
"polygon",
"to",
"be",
"wound",
"counter",
"-",
"clockwise",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/util.py#L302-L308 | train | 202,533 |
pyviz/geoviews | geoviews/util.py | geom_length | def geom_length(geom):
"""
Calculates the length of coordinates in a shapely geometry.
"""
if geom.geom_type == 'Point':
return 1
if hasattr(geom, 'exterior'):
geom = geom.exterior
if not geom.geom_type.startswith('Multi') and hasattr(geom, 'array_interface_base'):
return len(geom.array_interface_base['data'])//2
else:
length = 0
for g in geom:
length += geom_length(g)
return length | python | def geom_length(geom):
"""
Calculates the length of coordinates in a shapely geometry.
"""
if geom.geom_type == 'Point':
return 1
if hasattr(geom, 'exterior'):
geom = geom.exterior
if not geom.geom_type.startswith('Multi') and hasattr(geom, 'array_interface_base'):
return len(geom.array_interface_base['data'])//2
else:
length = 0
for g in geom:
length += geom_length(g)
return length | [
"def",
"geom_length",
"(",
"geom",
")",
":",
"if",
"geom",
".",
"geom_type",
"==",
"'Point'",
":",
"return",
"1",
"if",
"hasattr",
"(",
"geom",
",",
"'exterior'",
")",
":",
"geom",
"=",
"geom",
".",
"exterior",
"if",
"not",
"geom",
".",
"geom_type",
... | Calculates the length of coordinates in a shapely geometry. | [
"Calculates",
"the",
"length",
"of",
"coordinates",
"in",
"a",
"shapely",
"geometry",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/util.py#L327-L341 | train | 202,534 |
pyviz/geoviews | geoviews/util.py | geo_mesh | def geo_mesh(element):
"""
Get mesh data from a 2D Element ensuring that if the data is
on a cylindrical coordinate system and wraps globally that data
actually wraps around.
"""
if len(element.vdims) > 1:
xs, ys = (element.dimension_values(i, False, False)
for i in range(2))
zs = np.dstack([element.dimension_values(i, False, False)
for i in range(2, 2+len(element.vdims))])
else:
xs, ys, zs = (element.dimension_values(i, False, False)
for i in range(3))
lon0, lon1 = element.range(0)
if isinstance(element.crs, ccrs._CylindricalProjection) and (lon1 - lon0) == 360:
xs = np.append(xs, xs[0:1] + 360, axis=0)
zs = np.ma.concatenate([zs, zs[:, 0:1]], axis=1)
return xs, ys, zs | python | def geo_mesh(element):
"""
Get mesh data from a 2D Element ensuring that if the data is
on a cylindrical coordinate system and wraps globally that data
actually wraps around.
"""
if len(element.vdims) > 1:
xs, ys = (element.dimension_values(i, False, False)
for i in range(2))
zs = np.dstack([element.dimension_values(i, False, False)
for i in range(2, 2+len(element.vdims))])
else:
xs, ys, zs = (element.dimension_values(i, False, False)
for i in range(3))
lon0, lon1 = element.range(0)
if isinstance(element.crs, ccrs._CylindricalProjection) and (lon1 - lon0) == 360:
xs = np.append(xs, xs[0:1] + 360, axis=0)
zs = np.ma.concatenate([zs, zs[:, 0:1]], axis=1)
return xs, ys, zs | [
"def",
"geo_mesh",
"(",
"element",
")",
":",
"if",
"len",
"(",
"element",
".",
"vdims",
")",
">",
"1",
":",
"xs",
",",
"ys",
"=",
"(",
"element",
".",
"dimension_values",
"(",
"i",
",",
"False",
",",
"False",
")",
"for",
"i",
"in",
"range",
"(",
... | Get mesh data from a 2D Element ensuring that if the data is
on a cylindrical coordinate system and wraps globally that data
actually wraps around. | [
"Get",
"mesh",
"data",
"from",
"a",
"2D",
"Element",
"ensuring",
"that",
"if",
"the",
"data",
"is",
"on",
"a",
"cylindrical",
"coordinate",
"system",
"and",
"wraps",
"globally",
"that",
"data",
"actually",
"wraps",
"around",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/util.py#L369-L387 | train | 202,535 |
pyviz/geoviews | geoviews/util.py | check_crs | def check_crs(crs):
"""
Checks if the crs represents a valid grid, projection or ESPG string.
(Code copied from https://github.com/fmaussion/salem)
Examples
--------
>>> p = check_crs('+units=m +init=epsg:26915')
>>> p.srs
'+units=m +init=epsg:26915 '
>>> p = check_crs('wrong')
>>> p is None
True
Returns
-------
A valid crs if possible, otherwise None
"""
import pyproj
if isinstance(crs, pyproj.Proj):
out = crs
elif isinstance(crs, dict) or isinstance(crs, basestring):
try:
out = pyproj.Proj(crs)
except RuntimeError:
try:
out = pyproj.Proj(init=crs)
except RuntimeError:
out = None
else:
out = None
return out | python | def check_crs(crs):
"""
Checks if the crs represents a valid grid, projection or ESPG string.
(Code copied from https://github.com/fmaussion/salem)
Examples
--------
>>> p = check_crs('+units=m +init=epsg:26915')
>>> p.srs
'+units=m +init=epsg:26915 '
>>> p = check_crs('wrong')
>>> p is None
True
Returns
-------
A valid crs if possible, otherwise None
"""
import pyproj
if isinstance(crs, pyproj.Proj):
out = crs
elif isinstance(crs, dict) or isinstance(crs, basestring):
try:
out = pyproj.Proj(crs)
except RuntimeError:
try:
out = pyproj.Proj(init=crs)
except RuntimeError:
out = None
else:
out = None
return out | [
"def",
"check_crs",
"(",
"crs",
")",
":",
"import",
"pyproj",
"if",
"isinstance",
"(",
"crs",
",",
"pyproj",
".",
"Proj",
")",
":",
"out",
"=",
"crs",
"elif",
"isinstance",
"(",
"crs",
",",
"dict",
")",
"or",
"isinstance",
"(",
"crs",
",",
"basestrin... | Checks if the crs represents a valid grid, projection or ESPG string.
(Code copied from https://github.com/fmaussion/salem)
Examples
--------
>>> p = check_crs('+units=m +init=epsg:26915')
>>> p.srs
'+units=m +init=epsg:26915 '
>>> p = check_crs('wrong')
>>> p is None
True
Returns
-------
A valid crs if possible, otherwise None | [
"Checks",
"if",
"the",
"crs",
"represents",
"a",
"valid",
"grid",
"projection",
"or",
"ESPG",
"string",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/util.py#L397-L428 | train | 202,536 |
pyviz/geoviews | geoviews/util.py | proj_to_cartopy | def proj_to_cartopy(proj):
"""
Converts a pyproj.Proj to a cartopy.crs.Projection
(Code copied from https://github.com/fmaussion/salem)
Parameters
----------
proj: pyproj.Proj
the projection to convert
Returns
-------
a cartopy.crs.Projection object
"""
import cartopy.crs as ccrs
try:
from osgeo import osr
has_gdal = True
except ImportError:
has_gdal = False
proj = check_crs(proj)
if proj.is_latlong():
return ccrs.PlateCarree()
srs = proj.srs
if has_gdal:
# this is more robust, as srs could be anything (espg, etc.)
s1 = osr.SpatialReference()
s1.ImportFromProj4(proj.srs)
srs = s1.ExportToProj4()
km_proj = {'lon_0': 'central_longitude',
'lat_0': 'central_latitude',
'x_0': 'false_easting',
'y_0': 'false_northing',
'k': 'scale_factor',
'zone': 'zone',
}
km_globe = {'a': 'semimajor_axis',
'b': 'semiminor_axis',
}
km_std = {'lat_1': 'lat_1',
'lat_2': 'lat_2',
}
kw_proj = dict()
kw_globe = dict()
kw_std = dict()
for s in srs.split('+'):
s = s.split('=')
if len(s) != 2:
continue
k = s[0].strip()
v = s[1].strip()
try:
v = float(v)
except:
pass
if k == 'proj':
if v == 'tmerc':
cl = ccrs.TransverseMercator
if v == 'lcc':
cl = ccrs.LambertConformal
if v == 'merc':
cl = ccrs.Mercator
if v == 'utm':
cl = ccrs.UTM
if k in km_proj:
kw_proj[km_proj[k]] = v
if k in km_globe:
kw_globe[km_globe[k]] = v
if k in km_std:
kw_std[km_std[k]] = v
globe = None
if kw_globe:
globe = ccrs.Globe(**kw_globe)
if kw_std:
kw_proj['standard_parallels'] = (kw_std['lat_1'], kw_std['lat_2'])
# mercatoooor
if cl.__name__ == 'Mercator':
kw_proj.pop('false_easting', None)
kw_proj.pop('false_northing', None)
return cl(globe=globe, **kw_proj) | python | def proj_to_cartopy(proj):
"""
Converts a pyproj.Proj to a cartopy.crs.Projection
(Code copied from https://github.com/fmaussion/salem)
Parameters
----------
proj: pyproj.Proj
the projection to convert
Returns
-------
a cartopy.crs.Projection object
"""
import cartopy.crs as ccrs
try:
from osgeo import osr
has_gdal = True
except ImportError:
has_gdal = False
proj = check_crs(proj)
if proj.is_latlong():
return ccrs.PlateCarree()
srs = proj.srs
if has_gdal:
# this is more robust, as srs could be anything (espg, etc.)
s1 = osr.SpatialReference()
s1.ImportFromProj4(proj.srs)
srs = s1.ExportToProj4()
km_proj = {'lon_0': 'central_longitude',
'lat_0': 'central_latitude',
'x_0': 'false_easting',
'y_0': 'false_northing',
'k': 'scale_factor',
'zone': 'zone',
}
km_globe = {'a': 'semimajor_axis',
'b': 'semiminor_axis',
}
km_std = {'lat_1': 'lat_1',
'lat_2': 'lat_2',
}
kw_proj = dict()
kw_globe = dict()
kw_std = dict()
for s in srs.split('+'):
s = s.split('=')
if len(s) != 2:
continue
k = s[0].strip()
v = s[1].strip()
try:
v = float(v)
except:
pass
if k == 'proj':
if v == 'tmerc':
cl = ccrs.TransverseMercator
if v == 'lcc':
cl = ccrs.LambertConformal
if v == 'merc':
cl = ccrs.Mercator
if v == 'utm':
cl = ccrs.UTM
if k in km_proj:
kw_proj[km_proj[k]] = v
if k in km_globe:
kw_globe[km_globe[k]] = v
if k in km_std:
kw_std[km_std[k]] = v
globe = None
if kw_globe:
globe = ccrs.Globe(**kw_globe)
if kw_std:
kw_proj['standard_parallels'] = (kw_std['lat_1'], kw_std['lat_2'])
# mercatoooor
if cl.__name__ == 'Mercator':
kw_proj.pop('false_easting', None)
kw_proj.pop('false_northing', None)
return cl(globe=globe, **kw_proj) | [
"def",
"proj_to_cartopy",
"(",
"proj",
")",
":",
"import",
"cartopy",
".",
"crs",
"as",
"ccrs",
"try",
":",
"from",
"osgeo",
"import",
"osr",
"has_gdal",
"=",
"True",
"except",
"ImportError",
":",
"has_gdal",
"=",
"False",
"proj",
"=",
"check_crs",
"(",
... | Converts a pyproj.Proj to a cartopy.crs.Projection
(Code copied from https://github.com/fmaussion/salem)
Parameters
----------
proj: pyproj.Proj
the projection to convert
Returns
-------
a cartopy.crs.Projection object | [
"Converts",
"a",
"pyproj",
".",
"Proj",
"to",
"a",
"cartopy",
".",
"crs",
".",
"Projection"
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/util.py#L431-L518 | train | 202,537 |
pyviz/geoviews | geoviews/util.py | load_tiff | def load_tiff(filename, crs=None, apply_transform=False, nan_nodata=False, **kwargs):
"""
Returns an RGB or Image element loaded from a geotiff file.
The data is loaded using xarray and rasterio. If a crs attribute
is present on the loaded data it will attempt to decode it into
a cartopy projection otherwise it will default to a non-geographic
HoloViews element.
Parameters
----------
filename: string
Filename pointing to geotiff file to load
crs: Cartopy CRS or EPSG string (optional)
Overrides CRS inferred from the data
apply_transform: boolean
Whether to apply affine transform if defined on the data
nan_nodata: boolean
If data contains nodata values convert them to NaNs
**kwargs:
Keyword arguments passed to the HoloViews/GeoViews element
Returns
-------
element: Image/RGB/QuadMesh element
"""
try:
import xarray as xr
except:
raise ImportError('Loading tiffs requires xarray to be installed')
with warnings.catch_warnings():
warnings.filterwarnings('ignore')
da = xr.open_rasterio(filename)
return from_xarray(da, crs, apply_transform, nan_nodata, **kwargs) | python | def load_tiff(filename, crs=None, apply_transform=False, nan_nodata=False, **kwargs):
"""
Returns an RGB or Image element loaded from a geotiff file.
The data is loaded using xarray and rasterio. If a crs attribute
is present on the loaded data it will attempt to decode it into
a cartopy projection otherwise it will default to a non-geographic
HoloViews element.
Parameters
----------
filename: string
Filename pointing to geotiff file to load
crs: Cartopy CRS or EPSG string (optional)
Overrides CRS inferred from the data
apply_transform: boolean
Whether to apply affine transform if defined on the data
nan_nodata: boolean
If data contains nodata values convert them to NaNs
**kwargs:
Keyword arguments passed to the HoloViews/GeoViews element
Returns
-------
element: Image/RGB/QuadMesh element
"""
try:
import xarray as xr
except:
raise ImportError('Loading tiffs requires xarray to be installed')
with warnings.catch_warnings():
warnings.filterwarnings('ignore')
da = xr.open_rasterio(filename)
return from_xarray(da, crs, apply_transform, nan_nodata, **kwargs) | [
"def",
"load_tiff",
"(",
"filename",
",",
"crs",
"=",
"None",
",",
"apply_transform",
"=",
"False",
",",
"nan_nodata",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"import",
"xarray",
"as",
"xr",
"except",
":",
"raise",
"ImportError",
"... | Returns an RGB or Image element loaded from a geotiff file.
The data is loaded using xarray and rasterio. If a crs attribute
is present on the loaded data it will attempt to decode it into
a cartopy projection otherwise it will default to a non-geographic
HoloViews element.
Parameters
----------
filename: string
Filename pointing to geotiff file to load
crs: Cartopy CRS or EPSG string (optional)
Overrides CRS inferred from the data
apply_transform: boolean
Whether to apply affine transform if defined on the data
nan_nodata: boolean
If data contains nodata values convert them to NaNs
**kwargs:
Keyword arguments passed to the HoloViews/GeoViews element
Returns
-------
element: Image/RGB/QuadMesh element | [
"Returns",
"an",
"RGB",
"or",
"Image",
"element",
"loaded",
"from",
"a",
"geotiff",
"file",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/util.py#L557-L591 | train | 202,538 |
pyviz/geoviews | geoviews/plotting/mpl/__init__.py | WMTSPlot.teardown_handles | def teardown_handles(self):
"""
If no custom update_handles method is supplied this method
is called to tear down any previous handles before replacing
them.
"""
if not isinstance(self.handles.get('artist'), GoogleTiles):
self.handles['artist'].remove() | python | def teardown_handles(self):
"""
If no custom update_handles method is supplied this method
is called to tear down any previous handles before replacing
them.
"""
if not isinstance(self.handles.get('artist'), GoogleTiles):
self.handles['artist'].remove() | [
"def",
"teardown_handles",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"handles",
".",
"get",
"(",
"'artist'",
")",
",",
"GoogleTiles",
")",
":",
"self",
".",
"handles",
"[",
"'artist'",
"]",
".",
"remove",
"(",
")"
] | If no custom update_handles method is supplied this method
is called to tear down any previous handles before replacing
them. | [
"If",
"no",
"custom",
"update_handles",
"method",
"is",
"supplied",
"this",
"method",
"is",
"called",
"to",
"tear",
"down",
"any",
"previous",
"handles",
"before",
"replacing",
"them",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/plotting/mpl/__init__.py#L393-L400 | train | 202,539 |
pyviz/geoviews | geoviews/operation/resample.py | find_geom | def find_geom(geom, geoms):
"""
Returns the index of a geometry in a list of geometries avoiding
expensive equality checks of `in` operator.
"""
for i, g in enumerate(geoms):
if g is geom:
return i | python | def find_geom(geom, geoms):
"""
Returns the index of a geometry in a list of geometries avoiding
expensive equality checks of `in` operator.
"""
for i, g in enumerate(geoms):
if g is geom:
return i | [
"def",
"find_geom",
"(",
"geom",
",",
"geoms",
")",
":",
"for",
"i",
",",
"g",
"in",
"enumerate",
"(",
"geoms",
")",
":",
"if",
"g",
"is",
"geom",
":",
"return",
"i"
] | Returns the index of a geometry in a list of geometries avoiding
expensive equality checks of `in` operator. | [
"Returns",
"the",
"index",
"of",
"a",
"geometry",
"in",
"a",
"list",
"of",
"geometries",
"avoiding",
"expensive",
"equality",
"checks",
"of",
"in",
"operator",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/operation/resample.py#L13-L20 | train | 202,540 |
pyviz/geoviews | geoviews/operation/resample.py | compute_zoom_level | def compute_zoom_level(bounds, domain, levels):
"""
Computes a zoom level given a bounds polygon, a polygon of the
overall domain and the number of zoom levels to divide the data
into.
Parameters
----------
bounds: shapely.geometry.Polygon
Polygon representing the area of the current viewport
domain: shapely.geometry.Polygon
Polygon representing the overall bounding region of the data
levels: int
Number of zoom levels to divide the domain into
Returns
-------
zoom_level: int
Integer zoom level
"""
area_fraction = min(bounds.area/domain.area, 1)
return int(min(round(np.log2(1/area_fraction)), levels)) | python | def compute_zoom_level(bounds, domain, levels):
"""
Computes a zoom level given a bounds polygon, a polygon of the
overall domain and the number of zoom levels to divide the data
into.
Parameters
----------
bounds: shapely.geometry.Polygon
Polygon representing the area of the current viewport
domain: shapely.geometry.Polygon
Polygon representing the overall bounding region of the data
levels: int
Number of zoom levels to divide the domain into
Returns
-------
zoom_level: int
Integer zoom level
"""
area_fraction = min(bounds.area/domain.area, 1)
return int(min(round(np.log2(1/area_fraction)), levels)) | [
"def",
"compute_zoom_level",
"(",
"bounds",
",",
"domain",
",",
"levels",
")",
":",
"area_fraction",
"=",
"min",
"(",
"bounds",
".",
"area",
"/",
"domain",
".",
"area",
",",
"1",
")",
"return",
"int",
"(",
"min",
"(",
"round",
"(",
"np",
".",
"log2",... | Computes a zoom level given a bounds polygon, a polygon of the
overall domain and the number of zoom levels to divide the data
into.
Parameters
----------
bounds: shapely.geometry.Polygon
Polygon representing the area of the current viewport
domain: shapely.geometry.Polygon
Polygon representing the overall bounding region of the data
levels: int
Number of zoom levels to divide the domain into
Returns
-------
zoom_level: int
Integer zoom level | [
"Computes",
"a",
"zoom",
"level",
"given",
"a",
"bounds",
"polygon",
"a",
"polygon",
"of",
"the",
"overall",
"domain",
"and",
"the",
"number",
"of",
"zoom",
"levels",
"to",
"divide",
"the",
"data",
"into",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/operation/resample.py#L22-L43 | train | 202,541 |
pyviz/geoviews | geoviews/operation/resample.py | bounds_to_poly | def bounds_to_poly(bounds):
"""
Constructs a shapely Polygon from the provided bounds tuple.
Parameters
----------
bounds: tuple
Tuple representing the (left, bottom, right, top) coordinates
Returns
-------
polygon: shapely.geometry.Polygon
Shapely Polygon geometry of the bounds
"""
x0, y0, x1, y1 = bounds
return Polygon([(x0, y0), (x1, y0), (x1, y1), (x0, y1)]) | python | def bounds_to_poly(bounds):
"""
Constructs a shapely Polygon from the provided bounds tuple.
Parameters
----------
bounds: tuple
Tuple representing the (left, bottom, right, top) coordinates
Returns
-------
polygon: shapely.geometry.Polygon
Shapely Polygon geometry of the bounds
"""
x0, y0, x1, y1 = bounds
return Polygon([(x0, y0), (x1, y0), (x1, y1), (x0, y1)]) | [
"def",
"bounds_to_poly",
"(",
"bounds",
")",
":",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
"=",
"bounds",
"return",
"Polygon",
"(",
"[",
"(",
"x0",
",",
"y0",
")",
",",
"(",
"x1",
",",
"y0",
")",
",",
"(",
"x1",
",",
"y1",
")",
",",
"(",
"x0"... | Constructs a shapely Polygon from the provided bounds tuple.
Parameters
----------
bounds: tuple
Tuple representing the (left, bottom, right, top) coordinates
Returns
-------
polygon: shapely.geometry.Polygon
Shapely Polygon geometry of the bounds | [
"Constructs",
"a",
"shapely",
"Polygon",
"from",
"the",
"provided",
"bounds",
"tuple",
"."
] | cc70ac2d5a96307769bc6192eaef8576c3d24b30 | https://github.com/pyviz/geoviews/blob/cc70ac2d5a96307769bc6192eaef8576c3d24b30/geoviews/operation/resample.py#L46-L61 | train | 202,542 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cmds/stats.py | StatsCmd.get_assignment | def get_assignment(self):
"""Parse the given json plan in dict format."""
try:
plan = json.loads(open(self.args.plan_file_path).read())
return plan_to_assignment(plan)
except IOError:
self.log.exception(
'Given json file {file} not found.'
.format(file=self.args.plan_file_path),
)
raise
except ValueError:
self.log.exception(
'Given json file {file} could not be decoded.'
.format(file=self.args.plan_file_path),
)
raise
except KeyError:
self.log.exception(
'Given json file {file} could not be parsed in desired format.'
.format(file=self.args.plan_file_path),
)
raise | python | def get_assignment(self):
"""Parse the given json plan in dict format."""
try:
plan = json.loads(open(self.args.plan_file_path).read())
return plan_to_assignment(plan)
except IOError:
self.log.exception(
'Given json file {file} not found.'
.format(file=self.args.plan_file_path),
)
raise
except ValueError:
self.log.exception(
'Given json file {file} could not be decoded.'
.format(file=self.args.plan_file_path),
)
raise
except KeyError:
self.log.exception(
'Given json file {file} could not be parsed in desired format.'
.format(file=self.args.plan_file_path),
)
raise | [
"def",
"get_assignment",
"(",
"self",
")",
":",
"try",
":",
"plan",
"=",
"json",
".",
"loads",
"(",
"open",
"(",
"self",
".",
"args",
".",
"plan_file_path",
")",
".",
"read",
"(",
")",
")",
"return",
"plan_to_assignment",
"(",
"plan",
")",
"except",
... | Parse the given json plan in dict format. | [
"Parse",
"the",
"given",
"json",
"plan",
"in",
"dict",
"format",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cmds/stats.py#L73-L95 | train | 202,543 |
Yelp/kafka-utils | kafka_utils/kafka_rolling_restart/main.py | generate_requests | def generate_requests(hosts, jolokia_port, jolokia_prefix):
"""Return a generator of requests to fetch the under replicated
partition number from the specified hosts.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server for the Jolokia queries
:type jolokia_prefix: string
:returns: generator of requests
"""
session = FuturesSession()
for host in hosts:
url = "http://{host}:{port}/{prefix}/read/{key}".format(
host=host,
port=jolokia_port,
prefix=jolokia_prefix,
key=UNDER_REPL_KEY,
)
yield host, session.get(url) | python | def generate_requests(hosts, jolokia_port, jolokia_prefix):
"""Return a generator of requests to fetch the under replicated
partition number from the specified hosts.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server for the Jolokia queries
:type jolokia_prefix: string
:returns: generator of requests
"""
session = FuturesSession()
for host in hosts:
url = "http://{host}:{port}/{prefix}/read/{key}".format(
host=host,
port=jolokia_port,
prefix=jolokia_prefix,
key=UNDER_REPL_KEY,
)
yield host, session.get(url) | [
"def",
"generate_requests",
"(",
"hosts",
",",
"jolokia_port",
",",
"jolokia_prefix",
")",
":",
"session",
"=",
"FuturesSession",
"(",
")",
"for",
"host",
"in",
"hosts",
":",
"url",
"=",
"\"http://{host}:{port}/{prefix}/read/{key}\"",
".",
"format",
"(",
"host",
... | Return a generator of requests to fetch the under replicated
partition number from the specified hosts.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server for the Jolokia queries
:type jolokia_prefix: string
:returns: generator of requests | [
"Return",
"a",
"generator",
"of",
"requests",
"to",
"fetch",
"the",
"under",
"replicated",
"partition",
"number",
"from",
"the",
"specified",
"hosts",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_rolling_restart/main.py#L198-L218 | train | 202,544 |
Yelp/kafka-utils | kafka_utils/kafka_rolling_restart/main.py | read_cluster_status | def read_cluster_status(hosts, jolokia_port, jolokia_prefix):
"""Read and return the number of under replicated partitions and
missing brokers from the specified hosts.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server for the Jolokia queries
:type jolokia_prefix: string
:returns: tuple of integers
"""
under_replicated = 0
missing_brokers = 0
for host, request in generate_requests(hosts, jolokia_port, jolokia_prefix):
try:
response = request.result()
if 400 <= response.status_code <= 599:
print("Got status code {0}. Exiting.".format(response.status_code))
sys.exit(1)
json = response.json()
under_replicated += json['value']
except RequestException as e:
print("Broker {0} is down: {1}."
"This maybe because it is starting up".format(host, e), file=sys.stderr)
missing_brokers += 1
except KeyError:
print("Cannot find the key, Kafka is probably still starting up", file=sys.stderr)
missing_brokers += 1
return under_replicated, missing_brokers | python | def read_cluster_status(hosts, jolokia_port, jolokia_prefix):
"""Read and return the number of under replicated partitions and
missing brokers from the specified hosts.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server for the Jolokia queries
:type jolokia_prefix: string
:returns: tuple of integers
"""
under_replicated = 0
missing_brokers = 0
for host, request in generate_requests(hosts, jolokia_port, jolokia_prefix):
try:
response = request.result()
if 400 <= response.status_code <= 599:
print("Got status code {0}. Exiting.".format(response.status_code))
sys.exit(1)
json = response.json()
under_replicated += json['value']
except RequestException as e:
print("Broker {0} is down: {1}."
"This maybe because it is starting up".format(host, e), file=sys.stderr)
missing_brokers += 1
except KeyError:
print("Cannot find the key, Kafka is probably still starting up", file=sys.stderr)
missing_brokers += 1
return under_replicated, missing_brokers | [
"def",
"read_cluster_status",
"(",
"hosts",
",",
"jolokia_port",
",",
"jolokia_prefix",
")",
":",
"under_replicated",
"=",
"0",
"missing_brokers",
"=",
"0",
"for",
"host",
",",
"request",
"in",
"generate_requests",
"(",
"hosts",
",",
"jolokia_port",
",",
"joloki... | Read and return the number of under replicated partitions and
missing brokers from the specified hosts.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server for the Jolokia queries
:type jolokia_prefix: string
:returns: tuple of integers | [
"Read",
"and",
"return",
"the",
"number",
"of",
"under",
"replicated",
"partitions",
"and",
"missing",
"brokers",
"from",
"the",
"specified",
"hosts",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_rolling_restart/main.py#L221-L250 | train | 202,545 |
Yelp/kafka-utils | kafka_utils/kafka_rolling_restart/main.py | print_brokers | def print_brokers(cluster_config, brokers):
"""Print the list of brokers that will be restarted.
:param cluster_config: the cluster configuration
:type cluster_config: map
:param brokers: the brokers that will be restarted
:type brokers: map of broker ids and host names
"""
print("Will restart the following brokers in {0}:".format(cluster_config.name))
for id, host in brokers:
print(" {0}: {1}".format(id, host)) | python | def print_brokers(cluster_config, brokers):
"""Print the list of brokers that will be restarted.
:param cluster_config: the cluster configuration
:type cluster_config: map
:param brokers: the brokers that will be restarted
:type brokers: map of broker ids and host names
"""
print("Will restart the following brokers in {0}:".format(cluster_config.name))
for id, host in brokers:
print(" {0}: {1}".format(id, host)) | [
"def",
"print_brokers",
"(",
"cluster_config",
",",
"brokers",
")",
":",
"print",
"(",
"\"Will restart the following brokers in {0}:\"",
".",
"format",
"(",
"cluster_config",
".",
"name",
")",
")",
"for",
"id",
",",
"host",
"in",
"brokers",
":",
"print",
"(",
... | Print the list of brokers that will be restarted.
:param cluster_config: the cluster configuration
:type cluster_config: map
:param brokers: the brokers that will be restarted
:type brokers: map of broker ids and host names | [
"Print",
"the",
"list",
"of",
"brokers",
"that",
"will",
"be",
"restarted",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_rolling_restart/main.py#L253-L263 | train | 202,546 |
Yelp/kafka-utils | kafka_utils/kafka_rolling_restart/main.py | ask_confirmation | def ask_confirmation():
"""Ask for confirmation to the user. Return true if the user confirmed
the execution, false otherwise.
:returns: bool
"""
while True:
print("Do you want to restart these brokers? ", end="")
choice = input().lower()
if choice in ['yes', 'y']:
return True
elif choice in ['no', 'n']:
return False
else:
print("Please respond with 'yes' or 'no'") | python | def ask_confirmation():
"""Ask for confirmation to the user. Return true if the user confirmed
the execution, false otherwise.
:returns: bool
"""
while True:
print("Do you want to restart these brokers? ", end="")
choice = input().lower()
if choice in ['yes', 'y']:
return True
elif choice in ['no', 'n']:
return False
else:
print("Please respond with 'yes' or 'no'") | [
"def",
"ask_confirmation",
"(",
")",
":",
"while",
"True",
":",
"print",
"(",
"\"Do you want to restart these brokers? \"",
",",
"end",
"=",
"\"\"",
")",
"choice",
"=",
"input",
"(",
")",
".",
"lower",
"(",
")",
"if",
"choice",
"in",
"[",
"'yes'",
",",
"... | Ask for confirmation to the user. Return true if the user confirmed
the execution, false otherwise.
:returns: bool | [
"Ask",
"for",
"confirmation",
"to",
"the",
"user",
".",
"Return",
"true",
"if",
"the",
"user",
"confirmed",
"the",
"execution",
"false",
"otherwise",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_rolling_restart/main.py#L266-L280 | train | 202,547 |
Yelp/kafka-utils | kafka_utils/kafka_rolling_restart/main.py | start_broker | def start_broker(host, connection, start_command, verbose):
"""Execute the start"""
_, stdout, stderr = connection.sudo_command(start_command)
if verbose:
report_stdout(host, stdout)
report_stderr(host, stderr) | python | def start_broker(host, connection, start_command, verbose):
"""Execute the start"""
_, stdout, stderr = connection.sudo_command(start_command)
if verbose:
report_stdout(host, stdout)
report_stderr(host, stderr) | [
"def",
"start_broker",
"(",
"host",
",",
"connection",
",",
"start_command",
",",
"verbose",
")",
":",
"_",
",",
"stdout",
",",
"stderr",
"=",
"connection",
".",
"sudo_command",
"(",
"start_command",
")",
"if",
"verbose",
":",
"report_stdout",
"(",
"host",
... | Execute the start | [
"Execute",
"the",
"start"
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_rolling_restart/main.py#L283-L288 | train | 202,548 |
Yelp/kafka-utils | kafka_utils/kafka_rolling_restart/main.py | stop_broker | def stop_broker(host, connection, stop_command, verbose):
"""Execute the stop"""
_, stdout, stderr = connection.sudo_command(stop_command)
if verbose:
report_stdout(host, stdout)
report_stderr(host, stderr) | python | def stop_broker(host, connection, stop_command, verbose):
"""Execute the stop"""
_, stdout, stderr = connection.sudo_command(stop_command)
if verbose:
report_stdout(host, stdout)
report_stderr(host, stderr) | [
"def",
"stop_broker",
"(",
"host",
",",
"connection",
",",
"stop_command",
",",
"verbose",
")",
":",
"_",
",",
"stdout",
",",
"stderr",
"=",
"connection",
".",
"sudo_command",
"(",
"stop_command",
")",
"if",
"verbose",
":",
"report_stdout",
"(",
"host",
",... | Execute the stop | [
"Execute",
"the",
"stop"
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_rolling_restart/main.py#L291-L296 | train | 202,549 |
Yelp/kafka-utils | kafka_utils/kafka_rolling_restart/main.py | wait_for_stable_cluster | def wait_for_stable_cluster(
hosts,
jolokia_port,
jolokia_prefix,
check_interval,
check_count,
unhealthy_time_limit,
):
"""
Block the caller until the cluster can be considered stable.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server for the Jolokia queries
:type jolokia_prefix: string
:param check_interval: the number of seconds it will wait between each check
:type check_interval: integer
:param check_count: the number of times the check should be positive before
restarting the next broker
:type check_count: integer
:param unhealthy_time_limit: the maximum number of seconds it will wait for
the cluster to become stable before exiting with error
:type unhealthy_time_limit: integer
"""
stable_counter = 0
max_checks = int(math.ceil(unhealthy_time_limit / check_interval))
for i in itertools.count():
partitions, brokers = read_cluster_status(
hosts,
jolokia_port,
jolokia_prefix,
)
if partitions or brokers:
stable_counter = 0
else:
stable_counter += 1
print(
"Under replicated partitions: {p_count}, missing brokers: {b_count} ({stable}/{limit})".format(
p_count=partitions,
b_count=brokers,
stable=stable_counter,
limit=check_count,
))
if stable_counter >= check_count:
print("The cluster is stable")
return
if i >= max_checks:
raise WaitTimeoutException()
time.sleep(check_interval) | python | def wait_for_stable_cluster(
hosts,
jolokia_port,
jolokia_prefix,
check_interval,
check_count,
unhealthy_time_limit,
):
"""
Block the caller until the cluster can be considered stable.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server for the Jolokia queries
:type jolokia_prefix: string
:param check_interval: the number of seconds it will wait between each check
:type check_interval: integer
:param check_count: the number of times the check should be positive before
restarting the next broker
:type check_count: integer
:param unhealthy_time_limit: the maximum number of seconds it will wait for
the cluster to become stable before exiting with error
:type unhealthy_time_limit: integer
"""
stable_counter = 0
max_checks = int(math.ceil(unhealthy_time_limit / check_interval))
for i in itertools.count():
partitions, brokers = read_cluster_status(
hosts,
jolokia_port,
jolokia_prefix,
)
if partitions or brokers:
stable_counter = 0
else:
stable_counter += 1
print(
"Under replicated partitions: {p_count}, missing brokers: {b_count} ({stable}/{limit})".format(
p_count=partitions,
b_count=brokers,
stable=stable_counter,
limit=check_count,
))
if stable_counter >= check_count:
print("The cluster is stable")
return
if i >= max_checks:
raise WaitTimeoutException()
time.sleep(check_interval) | [
"def",
"wait_for_stable_cluster",
"(",
"hosts",
",",
"jolokia_port",
",",
"jolokia_prefix",
",",
"check_interval",
",",
"check_count",
",",
"unhealthy_time_limit",
",",
")",
":",
"stable_counter",
"=",
"0",
"max_checks",
"=",
"int",
"(",
"math",
".",
"ceil",
"("... | Block the caller until the cluster can be considered stable.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server for the Jolokia queries
:type jolokia_prefix: string
:param check_interval: the number of seconds it will wait between each check
:type check_interval: integer
:param check_count: the number of times the check should be positive before
restarting the next broker
:type check_count: integer
:param unhealthy_time_limit: the maximum number of seconds it will wait for
the cluster to become stable before exiting with error
:type unhealthy_time_limit: integer | [
"Block",
"the",
"caller",
"until",
"the",
"cluster",
"can",
"be",
"considered",
"stable",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_rolling_restart/main.py#L299-L349 | train | 202,550 |
Yelp/kafka-utils | kafka_utils/kafka_rolling_restart/main.py | execute_rolling_restart | def execute_rolling_restart(
brokers,
jolokia_port,
jolokia_prefix,
check_interval,
check_count,
unhealthy_time_limit,
skip,
verbose,
pre_stop_task,
post_stop_task,
start_command,
stop_command,
ssh_password=None
):
"""Execute the rolling restart on the specified brokers. It checks the
number of under replicated partitions on each broker, using Jolokia.
The check is performed at constant intervals, and a broker will be restarted
when all the brokers are answering and are reporting zero under replicated
partitions.
:param brokers: the brokers that will be restarted
:type brokers: map of broker ids and host names
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server for the Jolokia queries
:type jolokia_prefix: string
:param check_interval: the number of seconds it will wait between each check
:type check_interval: integer
:param check_count: the number of times the check should be positive before
restarting the next broker
:type check_count: integer
:param unhealthy_time_limit: the maximum number of seconds it will wait for
the cluster to become stable before exiting with error
:type unhealthy_time_limit: integer
:param skip: the number of brokers to skip
:type skip: integer
:param verbose: print commend execution information
:type verbose: bool
:param pre_stop_task: a list of tasks to execute before running stop
:type pre_stop_task: list
:param post_stop_task: a list of task to execute after running stop
:type post_stop_task: list
:param start_command: the start command for kafka
:type start_command: string
:param stop_command: the stop command for kafka
:type stop_command: string
:param ssh_password: The ssh password to use if needed
:type ssh_password: string
"""
all_hosts = [b[1] for b in brokers]
for n, host in enumerate(all_hosts[skip:]):
with ssh(host=host, forward_agent=True, sudoable=True, max_attempts=3, max_timeout=2,
ssh_password=ssh_password) as connection:
execute_task(pre_stop_task, host)
wait_for_stable_cluster(
all_hosts,
jolokia_port,
jolokia_prefix,
check_interval,
1 if n == 0 else check_count,
unhealthy_time_limit,
)
print("Stopping {0} ({1}/{2})".format(host, n + 1, len(all_hosts) - skip))
stop_broker(host, connection, stop_command, verbose)
execute_task(post_stop_task, host)
# we open a new SSH connection in case the hostname has a new IP
with ssh(host=host, forward_agent=True, sudoable=True, max_attempts=3, max_timeout=2,
ssh_password=ssh_password) as connection:
print("Starting {0} ({1}/{2})".format(host, n + 1, len(all_hosts) - skip))
start_broker(host, connection, start_command, verbose)
# Wait before terminating the script
wait_for_stable_cluster(
all_hosts,
jolokia_port,
jolokia_prefix,
check_interval,
check_count,
unhealthy_time_limit,
) | python | def execute_rolling_restart(
brokers,
jolokia_port,
jolokia_prefix,
check_interval,
check_count,
unhealthy_time_limit,
skip,
verbose,
pre_stop_task,
post_stop_task,
start_command,
stop_command,
ssh_password=None
):
"""Execute the rolling restart on the specified brokers. It checks the
number of under replicated partitions on each broker, using Jolokia.
The check is performed at constant intervals, and a broker will be restarted
when all the brokers are answering and are reporting zero under replicated
partitions.
:param brokers: the brokers that will be restarted
:type brokers: map of broker ids and host names
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server for the Jolokia queries
:type jolokia_prefix: string
:param check_interval: the number of seconds it will wait between each check
:type check_interval: integer
:param check_count: the number of times the check should be positive before
restarting the next broker
:type check_count: integer
:param unhealthy_time_limit: the maximum number of seconds it will wait for
the cluster to become stable before exiting with error
:type unhealthy_time_limit: integer
:param skip: the number of brokers to skip
:type skip: integer
:param verbose: print commend execution information
:type verbose: bool
:param pre_stop_task: a list of tasks to execute before running stop
:type pre_stop_task: list
:param post_stop_task: a list of task to execute after running stop
:type post_stop_task: list
:param start_command: the start command for kafka
:type start_command: string
:param stop_command: the stop command for kafka
:type stop_command: string
:param ssh_password: The ssh password to use if needed
:type ssh_password: string
"""
all_hosts = [b[1] for b in brokers]
for n, host in enumerate(all_hosts[skip:]):
with ssh(host=host, forward_agent=True, sudoable=True, max_attempts=3, max_timeout=2,
ssh_password=ssh_password) as connection:
execute_task(pre_stop_task, host)
wait_for_stable_cluster(
all_hosts,
jolokia_port,
jolokia_prefix,
check_interval,
1 if n == 0 else check_count,
unhealthy_time_limit,
)
print("Stopping {0} ({1}/{2})".format(host, n + 1, len(all_hosts) - skip))
stop_broker(host, connection, stop_command, verbose)
execute_task(post_stop_task, host)
# we open a new SSH connection in case the hostname has a new IP
with ssh(host=host, forward_agent=True, sudoable=True, max_attempts=3, max_timeout=2,
ssh_password=ssh_password) as connection:
print("Starting {0} ({1}/{2})".format(host, n + 1, len(all_hosts) - skip))
start_broker(host, connection, start_command, verbose)
# Wait before terminating the script
wait_for_stable_cluster(
all_hosts,
jolokia_port,
jolokia_prefix,
check_interval,
check_count,
unhealthy_time_limit,
) | [
"def",
"execute_rolling_restart",
"(",
"brokers",
",",
"jolokia_port",
",",
"jolokia_prefix",
",",
"check_interval",
",",
"check_count",
",",
"unhealthy_time_limit",
",",
"skip",
",",
"verbose",
",",
"pre_stop_task",
",",
"post_stop_task",
",",
"start_command",
",",
... | Execute the rolling restart on the specified brokers. It checks the
number of under replicated partitions on each broker, using Jolokia.
The check is performed at constant intervals, and a broker will be restarted
when all the brokers are answering and are reporting zero under replicated
partitions.
:param brokers: the brokers that will be restarted
:type brokers: map of broker ids and host names
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server for the Jolokia queries
:type jolokia_prefix: string
:param check_interval: the number of seconds it will wait between each check
:type check_interval: integer
:param check_count: the number of times the check should be positive before
restarting the next broker
:type check_count: integer
:param unhealthy_time_limit: the maximum number of seconds it will wait for
the cluster to become stable before exiting with error
:type unhealthy_time_limit: integer
:param skip: the number of brokers to skip
:type skip: integer
:param verbose: print commend execution information
:type verbose: bool
:param pre_stop_task: a list of tasks to execute before running stop
:type pre_stop_task: list
:param post_stop_task: a list of task to execute after running stop
:type post_stop_task: list
:param start_command: the start command for kafka
:type start_command: string
:param stop_command: the stop command for kafka
:type stop_command: string
:param ssh_password: The ssh password to use if needed
:type ssh_password: string | [
"Execute",
"the",
"rolling",
"restart",
"on",
"the",
"specified",
"brokers",
".",
"It",
"checks",
"the",
"number",
"of",
"under",
"replicated",
"partitions",
"on",
"each",
"broker",
"using",
"Jolokia",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_rolling_restart/main.py#L360-L440 | train | 202,551 |
Yelp/kafka-utils | kafka_utils/kafka_rolling_restart/main.py | validate_opts | def validate_opts(opts, brokers_num):
"""Basic option validation. Returns True if the options are not valid,
False otherwise.
:param opts: the command line options
:type opts: map
:param brokers_num: the number of brokers
:type brokers_num: integer
:returns: bool
"""
if opts.skip < 0 or opts.skip >= brokers_num:
print("Error: --skip must be >= 0 and < #brokers")
return True
if opts.check_count < 0:
print("Error: --check-count must be >= 0")
return True
if opts.unhealthy_time_limit < 0:
print("Error: --unhealthy-time-limit must be >= 0")
return True
if opts.check_count == 0:
print("Warning: no check will be performed")
if opts.check_interval < 0:
print("Error: --check-interval must be >= 0")
return True
return False | python | def validate_opts(opts, brokers_num):
"""Basic option validation. Returns True if the options are not valid,
False otherwise.
:param opts: the command line options
:type opts: map
:param brokers_num: the number of brokers
:type brokers_num: integer
:returns: bool
"""
if opts.skip < 0 or opts.skip >= brokers_num:
print("Error: --skip must be >= 0 and < #brokers")
return True
if opts.check_count < 0:
print("Error: --check-count must be >= 0")
return True
if opts.unhealthy_time_limit < 0:
print("Error: --unhealthy-time-limit must be >= 0")
return True
if opts.check_count == 0:
print("Warning: no check will be performed")
if opts.check_interval < 0:
print("Error: --check-interval must be >= 0")
return True
return False | [
"def",
"validate_opts",
"(",
"opts",
",",
"brokers_num",
")",
":",
"if",
"opts",
".",
"skip",
"<",
"0",
"or",
"opts",
".",
"skip",
">=",
"brokers_num",
":",
"print",
"(",
"\"Error: --skip must be >= 0 and < #brokers\"",
")",
"return",
"True",
"if",
"opts",
"... | Basic option validation. Returns True if the options are not valid,
False otherwise.
:param opts: the command line options
:type opts: map
:param brokers_num: the number of brokers
:type brokers_num: integer
:returns: bool | [
"Basic",
"option",
"validation",
".",
"Returns",
"True",
"if",
"the",
"options",
"are",
"not",
"valid",
"False",
"otherwise",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_rolling_restart/main.py#L443-L467 | train | 202,552 |
Yelp/kafka-utils | kafka_utils/kafka_rolling_restart/main.py | validate_broker_ids_subset | def validate_broker_ids_subset(broker_ids, subset_ids):
"""Validate that user specified broker ids to restart exist in the broker ids retrieved
from cluster config.
:param broker_ids: all broker IDs in a cluster
:type broker_ids: list of integers
:param subset_ids: broker IDs specified by user
:type subset_ids: list of integers
:returns: bool
"""
all_ids = set(broker_ids)
valid = True
for subset_id in subset_ids:
valid = valid and subset_id in all_ids
if subset_id not in all_ids:
print("Error: user specified broker id {0} does not exist in cluster.".format(subset_id))
return valid | python | def validate_broker_ids_subset(broker_ids, subset_ids):
"""Validate that user specified broker ids to restart exist in the broker ids retrieved
from cluster config.
:param broker_ids: all broker IDs in a cluster
:type broker_ids: list of integers
:param subset_ids: broker IDs specified by user
:type subset_ids: list of integers
:returns: bool
"""
all_ids = set(broker_ids)
valid = True
for subset_id in subset_ids:
valid = valid and subset_id in all_ids
if subset_id not in all_ids:
print("Error: user specified broker id {0} does not exist in cluster.".format(subset_id))
return valid | [
"def",
"validate_broker_ids_subset",
"(",
"broker_ids",
",",
"subset_ids",
")",
":",
"all_ids",
"=",
"set",
"(",
"broker_ids",
")",
"valid",
"=",
"True",
"for",
"subset_id",
"in",
"subset_ids",
":",
"valid",
"=",
"valid",
"and",
"subset_id",
"in",
"all_ids",
... | Validate that user specified broker ids to restart exist in the broker ids retrieved
from cluster config.
:param broker_ids: all broker IDs in a cluster
:type broker_ids: list of integers
:param subset_ids: broker IDs specified by user
:type subset_ids: list of integers
:returns: bool | [
"Validate",
"that",
"user",
"specified",
"broker",
"ids",
"to",
"restart",
"exist",
"in",
"the",
"broker",
"ids",
"retrieved",
"from",
"cluster",
"config",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_rolling_restart/main.py#L470-L486 | train | 202,553 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cmds/command.py | ClusterManagerCmd.run | def run(
self,
cluster_config,
rg_parser,
partition_measurer,
cluster_balancer,
args,
):
"""Initialize cluster_config, args, and zk then call run_command."""
self.cluster_config = cluster_config
self.args = args
with ZK(self.cluster_config) as self.zk:
self.log.debug(
'Starting %s for cluster: %s and zookeeper: %s',
self.__class__.__name__,
self.cluster_config.name,
self.cluster_config.zookeeper,
)
brokers = self.zk.get_brokers()
assignment = self.zk.get_cluster_assignment()
pm = partition_measurer(
self.cluster_config,
brokers,
assignment,
args,
)
ct = ClusterTopology(
assignment,
brokers,
pm,
rg_parser.get_replication_group,
)
if len(ct.partitions) == 0:
self.log.info("The cluster is empty. No actions to perform.")
return
# Exit if there is an on-going reassignment
if self.is_reassignment_pending():
self.log.error('Previous reassignment pending.')
sys.exit(1)
self.run_command(ct, cluster_balancer(ct, args)) | python | def run(
self,
cluster_config,
rg_parser,
partition_measurer,
cluster_balancer,
args,
):
"""Initialize cluster_config, args, and zk then call run_command."""
self.cluster_config = cluster_config
self.args = args
with ZK(self.cluster_config) as self.zk:
self.log.debug(
'Starting %s for cluster: %s and zookeeper: %s',
self.__class__.__name__,
self.cluster_config.name,
self.cluster_config.zookeeper,
)
brokers = self.zk.get_brokers()
assignment = self.zk.get_cluster_assignment()
pm = partition_measurer(
self.cluster_config,
brokers,
assignment,
args,
)
ct = ClusterTopology(
assignment,
brokers,
pm,
rg_parser.get_replication_group,
)
if len(ct.partitions) == 0:
self.log.info("The cluster is empty. No actions to perform.")
return
# Exit if there is an on-going reassignment
if self.is_reassignment_pending():
self.log.error('Previous reassignment pending.')
sys.exit(1)
self.run_command(ct, cluster_balancer(ct, args)) | [
"def",
"run",
"(",
"self",
",",
"cluster_config",
",",
"rg_parser",
",",
"partition_measurer",
",",
"cluster_balancer",
",",
"args",
",",
")",
":",
"self",
".",
"cluster_config",
"=",
"cluster_config",
"self",
".",
"args",
"=",
"args",
"with",
"ZK",
"(",
"... | Initialize cluster_config, args, and zk then call run_command. | [
"Initialize",
"cluster_config",
"args",
"and",
"zk",
"then",
"call",
"run_command",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cmds/command.py#L61-L102 | train | 202,554 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cmds/command.py | ClusterManagerCmd.execute_plan | def execute_plan(self, plan, allow_rf_change=False):
"""Save proposed-plan and execute the same if requested."""
if self.should_execute():
result = self.zk.execute_plan(plan, allow_rf_change=allow_rf_change)
if not result:
self.log.error('Plan execution unsuccessful.')
sys.exit(1)
else:
self.log.info(
'Plan sent to zookeeper for reassignment successfully.',
)
else:
self.log.info('Proposed plan won\'t be executed (--apply and confirmation needed).') | python | def execute_plan(self, plan, allow_rf_change=False):
"""Save proposed-plan and execute the same if requested."""
if self.should_execute():
result = self.zk.execute_plan(plan, allow_rf_change=allow_rf_change)
if not result:
self.log.error('Plan execution unsuccessful.')
sys.exit(1)
else:
self.log.info(
'Plan sent to zookeeper for reassignment successfully.',
)
else:
self.log.info('Proposed plan won\'t be executed (--apply and confirmation needed).') | [
"def",
"execute_plan",
"(",
"self",
",",
"plan",
",",
"allow_rf_change",
"=",
"False",
")",
":",
"if",
"self",
".",
"should_execute",
"(",
")",
":",
"result",
"=",
"self",
".",
"zk",
".",
"execute_plan",
"(",
"plan",
",",
"allow_rf_change",
"=",
"allow_r... | Save proposed-plan and execute the same if requested. | [
"Save",
"proposed",
"-",
"plan",
"and",
"execute",
"the",
"same",
"if",
"requested",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cmds/command.py#L107-L119 | train | 202,555 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cmds/command.py | ClusterManagerCmd.should_execute | def should_execute(self):
"""Confirm if proposed-plan should be executed."""
return self.args.apply and (self.args.no_confirm or self.confirm_execution()) | python | def should_execute(self):
"""Confirm if proposed-plan should be executed."""
return self.args.apply and (self.args.no_confirm or self.confirm_execution()) | [
"def",
"should_execute",
"(",
"self",
")",
":",
"return",
"self",
".",
"args",
".",
"apply",
"and",
"(",
"self",
".",
"args",
".",
"no_confirm",
"or",
"self",
".",
"confirm_execution",
"(",
")",
")"
] | Confirm if proposed-plan should be executed. | [
"Confirm",
"if",
"proposed",
"-",
"plan",
"should",
"be",
"executed",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cmds/command.py#L121-L123 | train | 202,556 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cmds/command.py | ClusterManagerCmd.is_reassignment_pending | def is_reassignment_pending(self):
"""Return True if there are reassignment tasks pending."""
in_progress_plan = self.zk.get_pending_plan()
if in_progress_plan:
in_progress_partitions = in_progress_plan['partitions']
self.log.info(
'Previous re-assignment in progress for {count} partitions.'
' Current partitions in re-assignment queue: {partitions}'
.format(
count=len(in_progress_partitions),
partitions=in_progress_partitions,
)
)
return True
else:
return False | python | def is_reassignment_pending(self):
"""Return True if there are reassignment tasks pending."""
in_progress_plan = self.zk.get_pending_plan()
if in_progress_plan:
in_progress_partitions = in_progress_plan['partitions']
self.log.info(
'Previous re-assignment in progress for {count} partitions.'
' Current partitions in re-assignment queue: {partitions}'
.format(
count=len(in_progress_partitions),
partitions=in_progress_partitions,
)
)
return True
else:
return False | [
"def",
"is_reassignment_pending",
"(",
"self",
")",
":",
"in_progress_plan",
"=",
"self",
".",
"zk",
".",
"get_pending_plan",
"(",
")",
"if",
"in_progress_plan",
":",
"in_progress_partitions",
"=",
"in_progress_plan",
"[",
"'partitions'",
"]",
"self",
".",
"log",
... | Return True if there are reassignment tasks pending. | [
"Return",
"True",
"if",
"there",
"are",
"reassignment",
"tasks",
"pending",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cmds/command.py#L125-L140 | train | 202,557 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cmds/command.py | ClusterManagerCmd.get_reduced_assignment | def get_reduced_assignment(
self,
original_assignment,
cluster_topology,
max_partition_movements,
max_leader_only_changes,
max_movement_size=DEFAULT_MAX_MOVEMENT_SIZE,
force_progress=False,
):
"""Reduce the assignment based on the total actions.
Actions represent actual partition movements
and/or changes in preferred leader.
Get the difference of original and proposed assignment
and take the subset of this plan for given limit.
Argument(s):
original_assignment: Current assignment of cluster in zookeeper
cluster_topology: Cluster topology containing the new proposed-assignment of cluster
max_partition_movements:Maximum number of partition-movements in
final set of actions
max_leader_only_changes:Maximum number of actions with leader only changes
max_movement_size: Maximum size, in bytes, to move in final set of actions
force_progress: Whether to force progress if max_movement_size is too small
:return:
:reduced_assignment: Final reduced assignment
"""
new_assignment = cluster_topology.assignment
if (not original_assignment or not new_assignment or
max_partition_movements < 0 or max_leader_only_changes < 0 or
max_movement_size < 0):
return {}
# The replica set stays the same for leaders only changes
leaders_changes = [
(t_p, new_assignment[t_p])
for t_p, replica in six.iteritems(original_assignment)
if replica != new_assignment[t_p] and
set(replica) == set(new_assignment[t_p])
]
# The replica set is different for partitions changes
# Here we create a list of tuple ((topic, partion), # replica movements)
partition_change_count = [
(
t_p,
len(set(replica) - set(new_assignment[t_p])),
)
for t_p, replica in six.iteritems(original_assignment)
if set(replica) != set(new_assignment[t_p])
]
self.log.info(
"Total number of actions before reduction: %s.",
len(partition_change_count) + len(leaders_changes),
)
# Extract reduced plan maximizing uniqueness of topics and ensuring we do not
# go over the max_movement_size
reduced_actions = self._extract_actions_unique_topics(
partition_change_count,
max_partition_movements,
cluster_topology,
max_movement_size,
)
# Ensure progress is made if force_progress=True
if len(reduced_actions) == 0 and force_progress:
smallest_size = min([cluster_topology.partitions[t_p[0]].size for t_p in partition_change_count])
self.log.warning(
'--max-movement-size={max_movement_size} is too small, using smallest size'
' in set of partitions to move, {smallest_size} instead to force progress'.format(
max_movement_size=max_movement_size,
smallest_size=smallest_size,
)
)
max_movement_size = smallest_size
reduced_actions = self._extract_actions_unique_topics(
partition_change_count,
max_partition_movements,
cluster_topology,
max_movement_size,
)
reduced_partition_changes = [
(t_p, new_assignment[t_p]) for t_p in reduced_actions
]
self.log.info(
"Number of partition changes: %s."
" Number of leader-only changes: %s",
len(reduced_partition_changes),
min(max_leader_only_changes, len(leaders_changes)),
)
# Merge leaders and partition changes and generate the assignment
reduced_assignment = {
t_p: replicas
for t_p, replicas in (
reduced_partition_changes + leaders_changes[:max_leader_only_changes]
)
}
return reduced_assignment | python | def get_reduced_assignment(
self,
original_assignment,
cluster_topology,
max_partition_movements,
max_leader_only_changes,
max_movement_size=DEFAULT_MAX_MOVEMENT_SIZE,
force_progress=False,
):
"""Reduce the assignment based on the total actions.
Actions represent actual partition movements
and/or changes in preferred leader.
Get the difference of original and proposed assignment
and take the subset of this plan for given limit.
Argument(s):
original_assignment: Current assignment of cluster in zookeeper
cluster_topology: Cluster topology containing the new proposed-assignment of cluster
max_partition_movements:Maximum number of partition-movements in
final set of actions
max_leader_only_changes:Maximum number of actions with leader only changes
max_movement_size: Maximum size, in bytes, to move in final set of actions
force_progress: Whether to force progress if max_movement_size is too small
:return:
:reduced_assignment: Final reduced assignment
"""
new_assignment = cluster_topology.assignment
if (not original_assignment or not new_assignment or
max_partition_movements < 0 or max_leader_only_changes < 0 or
max_movement_size < 0):
return {}
# The replica set stays the same for leaders only changes
leaders_changes = [
(t_p, new_assignment[t_p])
for t_p, replica in six.iteritems(original_assignment)
if replica != new_assignment[t_p] and
set(replica) == set(new_assignment[t_p])
]
# The replica set is different for partitions changes
# Here we create a list of tuple ((topic, partion), # replica movements)
partition_change_count = [
(
t_p,
len(set(replica) - set(new_assignment[t_p])),
)
for t_p, replica in six.iteritems(original_assignment)
if set(replica) != set(new_assignment[t_p])
]
self.log.info(
"Total number of actions before reduction: %s.",
len(partition_change_count) + len(leaders_changes),
)
# Extract reduced plan maximizing uniqueness of topics and ensuring we do not
# go over the max_movement_size
reduced_actions = self._extract_actions_unique_topics(
partition_change_count,
max_partition_movements,
cluster_topology,
max_movement_size,
)
# Ensure progress is made if force_progress=True
if len(reduced_actions) == 0 and force_progress:
smallest_size = min([cluster_topology.partitions[t_p[0]].size for t_p in partition_change_count])
self.log.warning(
'--max-movement-size={max_movement_size} is too small, using smallest size'
' in set of partitions to move, {smallest_size} instead to force progress'.format(
max_movement_size=max_movement_size,
smallest_size=smallest_size,
)
)
max_movement_size = smallest_size
reduced_actions = self._extract_actions_unique_topics(
partition_change_count,
max_partition_movements,
cluster_topology,
max_movement_size,
)
reduced_partition_changes = [
(t_p, new_assignment[t_p]) for t_p in reduced_actions
]
self.log.info(
"Number of partition changes: %s."
" Number of leader-only changes: %s",
len(reduced_partition_changes),
min(max_leader_only_changes, len(leaders_changes)),
)
# Merge leaders and partition changes and generate the assignment
reduced_assignment = {
t_p: replicas
for t_p, replicas in (
reduced_partition_changes + leaders_changes[:max_leader_only_changes]
)
}
return reduced_assignment | [
"def",
"get_reduced_assignment",
"(",
"self",
",",
"original_assignment",
",",
"cluster_topology",
",",
"max_partition_movements",
",",
"max_leader_only_changes",
",",
"max_movement_size",
"=",
"DEFAULT_MAX_MOVEMENT_SIZE",
",",
"force_progress",
"=",
"False",
",",
")",
":... | Reduce the assignment based on the total actions.
Actions represent actual partition movements
and/or changes in preferred leader.
Get the difference of original and proposed assignment
and take the subset of this plan for given limit.
Argument(s):
original_assignment: Current assignment of cluster in zookeeper
cluster_topology: Cluster topology containing the new proposed-assignment of cluster
max_partition_movements:Maximum number of partition-movements in
final set of actions
max_leader_only_changes:Maximum number of actions with leader only changes
max_movement_size: Maximum size, in bytes, to move in final set of actions
force_progress: Whether to force progress if max_movement_size is too small
:return:
:reduced_assignment: Final reduced assignment | [
"Reduce",
"the",
"assignment",
"based",
"on",
"the",
"total",
"actions",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cmds/command.py#L160-L259 | train | 202,558 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cmds/command.py | ClusterManagerCmd._extract_actions_unique_topics | def _extract_actions_unique_topics(self, movement_counts, max_movements, cluster_topology, max_movement_size):
"""Extract actions limiting to given max value such that
the resultant has the minimum possible number of duplicate topics.
Algorithm:
1. Group actions by by topic-name: {topic: action-list}
2. Iterate through the dictionary in circular fashion and keep
extracting actions with until max_partition_movements
are reached.
:param movement_counts: list of tuple ((topic, partition), movement count)
:param max_movements: max number of movements to extract
:param cluster_topology: cluster topology containing the new proposed assignment for the cluster
:param max_movement_size: maximum size of data to move at a time in extracted actions
:return: list of tuple (topic, partitions) to include in the reduced plan
"""
# Group actions by topic
topic_actions = defaultdict(list)
for t_p, replica_change_cnt in movement_counts:
topic_actions[t_p[0]].append((t_p, replica_change_cnt))
# Create reduced assignment minimizing duplication of topics
extracted_actions = []
curr_movements = 0
curr_size = 0
action_available = True
while curr_movements < max_movements and curr_size <= max_movement_size and action_available:
action_available = False
for topic, actions in six.iteritems(topic_actions):
for action in actions:
action_size = cluster_topology.partitions[action[0]].size
if curr_movements + action[1] > max_movements or curr_size + action_size > max_movement_size:
# Remove action since it won't be possible to use it
actions.remove(action)
else:
# Append (topic, partition) to the list of movements
action_available = True
extracted_actions.append(action[0])
curr_movements += action[1]
curr_size += action_size
actions.remove(action)
break
return extracted_actions | python | def _extract_actions_unique_topics(self, movement_counts, max_movements, cluster_topology, max_movement_size):
"""Extract actions limiting to given max value such that
the resultant has the minimum possible number of duplicate topics.
Algorithm:
1. Group actions by by topic-name: {topic: action-list}
2. Iterate through the dictionary in circular fashion and keep
extracting actions with until max_partition_movements
are reached.
:param movement_counts: list of tuple ((topic, partition), movement count)
:param max_movements: max number of movements to extract
:param cluster_topology: cluster topology containing the new proposed assignment for the cluster
:param max_movement_size: maximum size of data to move at a time in extracted actions
:return: list of tuple (topic, partitions) to include in the reduced plan
"""
# Group actions by topic
topic_actions = defaultdict(list)
for t_p, replica_change_cnt in movement_counts:
topic_actions[t_p[0]].append((t_p, replica_change_cnt))
# Create reduced assignment minimizing duplication of topics
extracted_actions = []
curr_movements = 0
curr_size = 0
action_available = True
while curr_movements < max_movements and curr_size <= max_movement_size and action_available:
action_available = False
for topic, actions in six.iteritems(topic_actions):
for action in actions:
action_size = cluster_topology.partitions[action[0]].size
if curr_movements + action[1] > max_movements or curr_size + action_size > max_movement_size:
# Remove action since it won't be possible to use it
actions.remove(action)
else:
# Append (topic, partition) to the list of movements
action_available = True
extracted_actions.append(action[0])
curr_movements += action[1]
curr_size += action_size
actions.remove(action)
break
return extracted_actions | [
"def",
"_extract_actions_unique_topics",
"(",
"self",
",",
"movement_counts",
",",
"max_movements",
",",
"cluster_topology",
",",
"max_movement_size",
")",
":",
"# Group actions by topic",
"topic_actions",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"t_p",
",",
"repl... | Extract actions limiting to given max value such that
the resultant has the minimum possible number of duplicate topics.
Algorithm:
1. Group actions by by topic-name: {topic: action-list}
2. Iterate through the dictionary in circular fashion and keep
extracting actions with until max_partition_movements
are reached.
:param movement_counts: list of tuple ((topic, partition), movement count)
:param max_movements: max number of movements to extract
:param cluster_topology: cluster topology containing the new proposed assignment for the cluster
:param max_movement_size: maximum size of data to move at a time in extracted actions
:return: list of tuple (topic, partitions) to include in the reduced plan | [
"Extract",
"actions",
"limiting",
"to",
"given",
"max",
"value",
"such",
"that",
"the",
"resultant",
"has",
"the",
"minimum",
"possible",
"number",
"of",
"duplicate",
"topics",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cmds/command.py#L261-L302 | train | 202,559 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cmds/command.py | ClusterManagerCmd.confirm_execution | def confirm_execution(self):
"""Confirm from your if proposed-plan be executed."""
permit = ''
while permit.lower() not in ('yes', 'no'):
permit = input('Execute Proposed Plan? [yes/no] ')
if permit.lower() == 'yes':
return True
else:
return False | python | def confirm_execution(self):
"""Confirm from your if proposed-plan be executed."""
permit = ''
while permit.lower() not in ('yes', 'no'):
permit = input('Execute Proposed Plan? [yes/no] ')
if permit.lower() == 'yes':
return True
else:
return False | [
"def",
"confirm_execution",
"(",
"self",
")",
":",
"permit",
"=",
"''",
"while",
"permit",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'yes'",
",",
"'no'",
")",
":",
"permit",
"=",
"input",
"(",
"'Execute Proposed Plan? [yes/no] '",
")",
"if",
"permit",
"... | Confirm from your if proposed-plan be executed. | [
"Confirm",
"from",
"your",
"if",
"proposed",
"-",
"plan",
"be",
"executed",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cmds/command.py#L304-L312 | train | 202,560 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cmds/command.py | ClusterManagerCmd.write_json_plan | def write_json_plan(self, proposed_layout, proposed_plan_file):
"""Dump proposed json plan to given output file for future usage."""
with open(proposed_plan_file, 'w') as output:
json.dump(proposed_layout, output) | python | def write_json_plan(self, proposed_layout, proposed_plan_file):
"""Dump proposed json plan to given output file for future usage."""
with open(proposed_plan_file, 'w') as output:
json.dump(proposed_layout, output) | [
"def",
"write_json_plan",
"(",
"self",
",",
"proposed_layout",
",",
"proposed_plan_file",
")",
":",
"with",
"open",
"(",
"proposed_plan_file",
",",
"'w'",
")",
"as",
"output",
":",
"json",
".",
"dump",
"(",
"proposed_layout",
",",
"output",
")"
] | Dump proposed json plan to given output file for future usage. | [
"Dump",
"proposed",
"json",
"plan",
"to",
"given",
"output",
"file",
"for",
"future",
"usage",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cmds/command.py#L314-L317 | train | 202,561 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/partition.py | Partition.swap_leader | def swap_leader(self, new_leader):
"""Change the preferred leader with one of
given replicas.
Note: Leaders for all the replicas of current
partition needs to be changed.
"""
# Replica set cannot be changed
assert(new_leader in self._replicas)
curr_leader = self.leader
idx = self._replicas.index(new_leader)
self._replicas[0], self._replicas[idx] = \
self._replicas[idx], self._replicas[0]
return curr_leader | python | def swap_leader(self, new_leader):
"""Change the preferred leader with one of
given replicas.
Note: Leaders for all the replicas of current
partition needs to be changed.
"""
# Replica set cannot be changed
assert(new_leader in self._replicas)
curr_leader = self.leader
idx = self._replicas.index(new_leader)
self._replicas[0], self._replicas[idx] = \
self._replicas[idx], self._replicas[0]
return curr_leader | [
"def",
"swap_leader",
"(",
"self",
",",
"new_leader",
")",
":",
"# Replica set cannot be changed",
"assert",
"(",
"new_leader",
"in",
"self",
".",
"_replicas",
")",
"curr_leader",
"=",
"self",
".",
"leader",
"idx",
"=",
"self",
".",
"_replicas",
".",
"index",
... | Change the preferred leader with one of
given replicas.
Note: Leaders for all the replicas of current
partition needs to be changed. | [
"Change",
"the",
"preferred",
"leader",
"with",
"one",
"of",
"given",
"replicas",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/partition.py#L104-L117 | train | 202,562 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/partition.py | Partition.replace | def replace(self, source, dest):
"""Replace source broker with destination broker in replica set if found."""
for i, broker in enumerate(self.replicas):
if broker == source:
self.replicas[i] = dest
return | python | def replace(self, source, dest):
"""Replace source broker with destination broker in replica set if found."""
for i, broker in enumerate(self.replicas):
if broker == source:
self.replicas[i] = dest
return | [
"def",
"replace",
"(",
"self",
",",
"source",
",",
"dest",
")",
":",
"for",
"i",
",",
"broker",
"in",
"enumerate",
"(",
"self",
".",
"replicas",
")",
":",
"if",
"broker",
"==",
"source",
":",
"self",
".",
"replicas",
"[",
"i",
"]",
"=",
"dest",
"... | Replace source broker with destination broker in replica set if found. | [
"Replace",
"source",
"broker",
"with",
"destination",
"broker",
"in",
"replica",
"set",
"if",
"found",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/partition.py#L119-L124 | train | 202,563 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/partition.py | Partition.count_siblings | def count_siblings(self, partitions):
"""Count siblings of partition in given partition-list.
:key-term:
sibling: partitions with same topic
"""
count = sum(
int(self.topic == partition.topic)
for partition in partitions
)
return count | python | def count_siblings(self, partitions):
"""Count siblings of partition in given partition-list.
:key-term:
sibling: partitions with same topic
"""
count = sum(
int(self.topic == partition.topic)
for partition in partitions
)
return count | [
"def",
"count_siblings",
"(",
"self",
",",
"partitions",
")",
":",
"count",
"=",
"sum",
"(",
"int",
"(",
"self",
".",
"topic",
"==",
"partition",
".",
"topic",
")",
"for",
"partition",
"in",
"partitions",
")",
"return",
"count"
] | Count siblings of partition in given partition-list.
:key-term:
sibling: partitions with same topic | [
"Count",
"siblings",
"of",
"partition",
"in",
"given",
"partition",
"-",
"list",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/partition.py#L126-L136 | train | 202,564 |
Yelp/kafka-utils | kafka_utils/util/metadata.py | get_topic_partition_metadata | def get_topic_partition_metadata(hosts):
"""Returns topic-partition metadata from Kafka broker.
kafka-python 1.3+ doesn't include partition metadata information in
topic_partitions so we extract it from metadata ourselves.
"""
kafka_client = KafkaToolClient(hosts, timeout=10)
kafka_client.load_metadata_for_topics()
topic_partitions = kafka_client.topic_partitions
resp = kafka_client.send_metadata_request()
for _, topic, partitions in resp.topics:
for partition_error, partition, leader, replicas, isr in partitions:
if topic_partitions.get(topic, {}).get(partition) is not None:
topic_partitions[topic][partition] = PartitionMetadata(topic, partition, leader,
replicas, isr, partition_error)
return topic_partitions | python | def get_topic_partition_metadata(hosts):
"""Returns topic-partition metadata from Kafka broker.
kafka-python 1.3+ doesn't include partition metadata information in
topic_partitions so we extract it from metadata ourselves.
"""
kafka_client = KafkaToolClient(hosts, timeout=10)
kafka_client.load_metadata_for_topics()
topic_partitions = kafka_client.topic_partitions
resp = kafka_client.send_metadata_request()
for _, topic, partitions in resp.topics:
for partition_error, partition, leader, replicas, isr in partitions:
if topic_partitions.get(topic, {}).get(partition) is not None:
topic_partitions[topic][partition] = PartitionMetadata(topic, partition, leader,
replicas, isr, partition_error)
return topic_partitions | [
"def",
"get_topic_partition_metadata",
"(",
"hosts",
")",
":",
"kafka_client",
"=",
"KafkaToolClient",
"(",
"hosts",
",",
"timeout",
"=",
"10",
")",
"kafka_client",
".",
"load_metadata_for_topics",
"(",
")",
"topic_partitions",
"=",
"kafka_client",
".",
"topic_parti... | Returns topic-partition metadata from Kafka broker.
kafka-python 1.3+ doesn't include partition metadata information in
topic_partitions so we extract it from metadata ourselves. | [
"Returns",
"topic",
"-",
"partition",
"metadata",
"from",
"Kafka",
"broker",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/metadata.py#L27-L43 | train | 202,565 |
Yelp/kafka-utils | kafka_utils/util/metadata.py | get_unavailable_brokers | def get_unavailable_brokers(zk, partition_metadata):
"""Returns the set of unavailable brokers from the difference of replica
set of given partition to the set of available replicas.
"""
topic_data = zk.get_topics(partition_metadata.topic)
topic = partition_metadata.topic
partition = partition_metadata.partition
expected_replicas = set(topic_data[topic]['partitions'][str(partition)]['replicas'])
available_replicas = set(partition_metadata.replicas)
return expected_replicas - available_replicas | python | def get_unavailable_brokers(zk, partition_metadata):
"""Returns the set of unavailable brokers from the difference of replica
set of given partition to the set of available replicas.
"""
topic_data = zk.get_topics(partition_metadata.topic)
topic = partition_metadata.topic
partition = partition_metadata.partition
expected_replicas = set(topic_data[topic]['partitions'][str(partition)]['replicas'])
available_replicas = set(partition_metadata.replicas)
return expected_replicas - available_replicas | [
"def",
"get_unavailable_brokers",
"(",
"zk",
",",
"partition_metadata",
")",
":",
"topic_data",
"=",
"zk",
".",
"get_topics",
"(",
"partition_metadata",
".",
"topic",
")",
"topic",
"=",
"partition_metadata",
".",
"topic",
"partition",
"=",
"partition_metadata",
".... | Returns the set of unavailable brokers from the difference of replica
set of given partition to the set of available replicas. | [
"Returns",
"the",
"set",
"of",
"unavailable",
"brokers",
"from",
"the",
"difference",
"of",
"replica",
"set",
"of",
"given",
"partition",
"to",
"the",
"set",
"of",
"available",
"replicas",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/metadata.py#L46-L55 | train | 202,566 |
Yelp/kafka-utils | kafka_utils/util/offsets.py | get_current_consumer_offsets | def get_current_consumer_offsets(
kafka_client,
group,
topics,
raise_on_error=True,
):
""" Get current consumer offsets.
NOTE: This method does not refresh client metadata. It is up to the caller
to avoid using stale metadata.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic requests in batch
and save both in performance and Kafka load.
:param kafka_client: a connected KafkaToolClient
:param group: kafka group_id
:param topics: topic list or dict {<topic>: [partitions]}
:param raise_on_error: if False the method ignores missing topics and
missing partitions. It still may fail on the request send.
:returns: a dict topic: partition: offset
:raises:
:py:class:`kafka_utils.util.error.UnknownTopic`: upon missing
topics and raise_on_error=True
:py:class:`kafka_utils.util.error.UnknownPartition`: upon missing
partitions and raise_on_error=True
FailedPayloadsError: upon send request error.
"""
topics = _verify_topics_and_partitions(kafka_client, topics, raise_on_error)
group_offset_reqs = [
OffsetFetchRequestPayload(topic, partition)
for topic, partitions in six.iteritems(topics)
for partition in partitions
]
group_offsets = {}
send_api = kafka_client.send_offset_fetch_request_kafka
if group_offset_reqs:
# fail_on_error = False does not prevent network errors
group_resps = send_api(
group=group,
payloads=group_offset_reqs,
fail_on_error=False,
callback=pluck_topic_offset_or_zero_on_unknown,
)
for resp in group_resps:
group_offsets.setdefault(
resp.topic,
{},
)[resp.partition] = resp.offset
return group_offsets | python | def get_current_consumer_offsets(
kafka_client,
group,
topics,
raise_on_error=True,
):
""" Get current consumer offsets.
NOTE: This method does not refresh client metadata. It is up to the caller
to avoid using stale metadata.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic requests in batch
and save both in performance and Kafka load.
:param kafka_client: a connected KafkaToolClient
:param group: kafka group_id
:param topics: topic list or dict {<topic>: [partitions]}
:param raise_on_error: if False the method ignores missing topics and
missing partitions. It still may fail on the request send.
:returns: a dict topic: partition: offset
:raises:
:py:class:`kafka_utils.util.error.UnknownTopic`: upon missing
topics and raise_on_error=True
:py:class:`kafka_utils.util.error.UnknownPartition`: upon missing
partitions and raise_on_error=True
FailedPayloadsError: upon send request error.
"""
topics = _verify_topics_and_partitions(kafka_client, topics, raise_on_error)
group_offset_reqs = [
OffsetFetchRequestPayload(topic, partition)
for topic, partitions in six.iteritems(topics)
for partition in partitions
]
group_offsets = {}
send_api = kafka_client.send_offset_fetch_request_kafka
if group_offset_reqs:
# fail_on_error = False does not prevent network errors
group_resps = send_api(
group=group,
payloads=group_offset_reqs,
fail_on_error=False,
callback=pluck_topic_offset_or_zero_on_unknown,
)
for resp in group_resps:
group_offsets.setdefault(
resp.topic,
{},
)[resp.partition] = resp.offset
return group_offsets | [
"def",
"get_current_consumer_offsets",
"(",
"kafka_client",
",",
"group",
",",
"topics",
",",
"raise_on_error",
"=",
"True",
",",
")",
":",
"topics",
"=",
"_verify_topics_and_partitions",
"(",
"kafka_client",
",",
"topics",
",",
"raise_on_error",
")",
"group_offset_... | Get current consumer offsets.
NOTE: This method does not refresh client metadata. It is up to the caller
to avoid using stale metadata.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic requests in batch
and save both in performance and Kafka load.
:param kafka_client: a connected KafkaToolClient
:param group: kafka group_id
:param topics: topic list or dict {<topic>: [partitions]}
:param raise_on_error: if False the method ignores missing topics and
missing partitions. It still may fail on the request send.
:returns: a dict topic: partition: offset
:raises:
:py:class:`kafka_utils.util.error.UnknownTopic`: upon missing
topics and raise_on_error=True
:py:class:`kafka_utils.util.error.UnknownPartition`: upon missing
partitions and raise_on_error=True
FailedPayloadsError: upon send request error. | [
"Get",
"current",
"consumer",
"offsets",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/offsets.py#L174-L231 | train | 202,567 |
Yelp/kafka-utils | kafka_utils/util/offsets.py | get_topics_watermarks | def get_topics_watermarks(kafka_client, topics, raise_on_error=True):
""" Get current topic watermarks.
NOTE: This method does not refresh client metadata. It is up to the caller
to use avoid using stale metadata.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic requests in batch
and save both in performance and Kafka load.
:param kafka_client: a connected KafkaToolClient
:param topics: topic list or dict {<topic>: [partitions]}
:param raise_on_error: if False the method ignores missing topics
and missing partitions. It still may fail on the request send.
:returns: a dict topic: partition: Part
:raises:
:py:class:`~kafka_utils.util.error.UnknownTopic`: upon missing
topics and raise_on_error=True
:py:class:`~kafka_utils.util.error.UnknownPartition`: upon missing
partitions and raise_on_error=True
FailedPayloadsError: upon send request error.
"""
topics = _verify_topics_and_partitions(
kafka_client,
topics,
raise_on_error,
)
highmark_offset_reqs = []
lowmark_offset_reqs = []
for topic, partitions in six.iteritems(topics):
# Batch watermark requests
for partition in partitions:
# Request the the latest offset
highmark_offset_reqs.append(
OffsetRequestPayload(
topic, partition, -1, max_offsets=1
)
)
# Request the earliest offset
lowmark_offset_reqs.append(
OffsetRequestPayload(
topic, partition, -2, max_offsets=1
)
)
watermark_offsets = {}
if not (len(highmark_offset_reqs) + len(lowmark_offset_reqs)):
return watermark_offsets
# fail_on_error = False does not prevent network errors
highmark_resps = kafka_client.send_offset_request(
highmark_offset_reqs,
fail_on_error=False,
callback=_check_fetch_response_error,
)
lowmark_resps = kafka_client.send_offset_request(
lowmark_offset_reqs,
fail_on_error=False,
callback=_check_fetch_response_error,
)
# At this point highmark and lowmark should ideally have the same length.
assert len(highmark_resps) == len(lowmark_resps)
aggregated_offsets = defaultdict(lambda: defaultdict(dict))
for resp in highmark_resps:
aggregated_offsets[resp.topic][resp.partition]['highmark'] = \
resp.offsets[0]
for resp in lowmark_resps:
aggregated_offsets[resp.topic][resp.partition]['lowmark'] = \
resp.offsets[0]
for topic, partition_watermarks in six.iteritems(aggregated_offsets):
for partition, watermarks in six.iteritems(partition_watermarks):
watermark_offsets.setdefault(
topic,
{},
)[partition] = PartitionOffsets(
topic,
partition,
watermarks['highmark'],
watermarks['lowmark'],
)
return watermark_offsets | python | def get_topics_watermarks(kafka_client, topics, raise_on_error=True):
""" Get current topic watermarks.
NOTE: This method does not refresh client metadata. It is up to the caller
to use avoid using stale metadata.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic requests in batch
and save both in performance and Kafka load.
:param kafka_client: a connected KafkaToolClient
:param topics: topic list or dict {<topic>: [partitions]}
:param raise_on_error: if False the method ignores missing topics
and missing partitions. It still may fail on the request send.
:returns: a dict topic: partition: Part
:raises:
:py:class:`~kafka_utils.util.error.UnknownTopic`: upon missing
topics and raise_on_error=True
:py:class:`~kafka_utils.util.error.UnknownPartition`: upon missing
partitions and raise_on_error=True
FailedPayloadsError: upon send request error.
"""
topics = _verify_topics_and_partitions(
kafka_client,
topics,
raise_on_error,
)
highmark_offset_reqs = []
lowmark_offset_reqs = []
for topic, partitions in six.iteritems(topics):
# Batch watermark requests
for partition in partitions:
# Request the the latest offset
highmark_offset_reqs.append(
OffsetRequestPayload(
topic, partition, -1, max_offsets=1
)
)
# Request the earliest offset
lowmark_offset_reqs.append(
OffsetRequestPayload(
topic, partition, -2, max_offsets=1
)
)
watermark_offsets = {}
if not (len(highmark_offset_reqs) + len(lowmark_offset_reqs)):
return watermark_offsets
# fail_on_error = False does not prevent network errors
highmark_resps = kafka_client.send_offset_request(
highmark_offset_reqs,
fail_on_error=False,
callback=_check_fetch_response_error,
)
lowmark_resps = kafka_client.send_offset_request(
lowmark_offset_reqs,
fail_on_error=False,
callback=_check_fetch_response_error,
)
# At this point highmark and lowmark should ideally have the same length.
assert len(highmark_resps) == len(lowmark_resps)
aggregated_offsets = defaultdict(lambda: defaultdict(dict))
for resp in highmark_resps:
aggregated_offsets[resp.topic][resp.partition]['highmark'] = \
resp.offsets[0]
for resp in lowmark_resps:
aggregated_offsets[resp.topic][resp.partition]['lowmark'] = \
resp.offsets[0]
for topic, partition_watermarks in six.iteritems(aggregated_offsets):
for partition, watermarks in six.iteritems(partition_watermarks):
watermark_offsets.setdefault(
topic,
{},
)[partition] = PartitionOffsets(
topic,
partition,
watermarks['highmark'],
watermarks['lowmark'],
)
return watermark_offsets | [
"def",
"get_topics_watermarks",
"(",
"kafka_client",
",",
"topics",
",",
"raise_on_error",
"=",
"True",
")",
":",
"topics",
"=",
"_verify_topics_and_partitions",
"(",
"kafka_client",
",",
"topics",
",",
"raise_on_error",
",",
")",
"highmark_offset_reqs",
"=",
"[",
... | Get current topic watermarks.
NOTE: This method does not refresh client metadata. It is up to the caller
to use avoid using stale metadata.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic requests in batch
and save both in performance and Kafka load.
:param kafka_client: a connected KafkaToolClient
:param topics: topic list or dict {<topic>: [partitions]}
:param raise_on_error: if False the method ignores missing topics
and missing partitions. It still may fail on the request send.
:returns: a dict topic: partition: Part
:raises:
:py:class:`~kafka_utils.util.error.UnknownTopic`: upon missing
topics and raise_on_error=True
:py:class:`~kafka_utils.util.error.UnknownPartition`: upon missing
partitions and raise_on_error=True
FailedPayloadsError: upon send request error. | [
"Get",
"current",
"topic",
"watermarks",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/offsets.py#L234-L320 | train | 202,568 |
Yelp/kafka-utils | kafka_utils/util/offsets.py | set_consumer_offsets | def set_consumer_offsets(
kafka_client,
group,
new_offsets,
raise_on_error=True,
):
"""Set consumer offsets to the specified offsets.
This method does not validate the specified offsets, it is up to
the caller to specify valid offsets within a topic partition.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic requests in batch
and save both in performance and Kafka load.
:param kafka_client: a connected KafkaToolClient
:param group: kafka group_id
:param topics: dict {<topic>: {<partition>: <offset>}}
:param raise_on_error: if False the method does not raise exceptions
on errors encountered. It may still fail on the request send.
:returns: a list of errors for each partition offset update that failed.
:rtype: list [OffsetCommitError]
:raises:
:py:class:`kafka_utils.util.error.UnknownTopic`: upon missing
topics and raise_on_error=True
:py:class:`kafka_utils.util.error.UnknownPartition`: upon missing
partitions and raise_on_error=True
:py:class:`exceptions.TypeError`: upon badly formatted input
new_offsets
FailedPayloadsError: upon send request error.
"""
valid_new_offsets = _verify_commit_offsets_requests(
kafka_client,
new_offsets,
raise_on_error
)
group_offset_reqs = [
OffsetCommitRequestPayload(
topic,
partition,
offset,
metadata='',
)
for topic, new_partition_offsets in six.iteritems(valid_new_offsets)
for partition, offset in six.iteritems(new_partition_offsets)
]
send_api = kafka_client.send_offset_commit_request_kafka
status = []
if group_offset_reqs:
status = send_api(
group,
group_offset_reqs,
raise_on_error,
callback=_check_commit_response_error
)
return [_f for _f in status
if _f and _f.error != 0] | python | def set_consumer_offsets(
kafka_client,
group,
new_offsets,
raise_on_error=True,
):
"""Set consumer offsets to the specified offsets.
This method does not validate the specified offsets, it is up to
the caller to specify valid offsets within a topic partition.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic requests in batch
and save both in performance and Kafka load.
:param kafka_client: a connected KafkaToolClient
:param group: kafka group_id
:param topics: dict {<topic>: {<partition>: <offset>}}
:param raise_on_error: if False the method does not raise exceptions
on errors encountered. It may still fail on the request send.
:returns: a list of errors for each partition offset update that failed.
:rtype: list [OffsetCommitError]
:raises:
:py:class:`kafka_utils.util.error.UnknownTopic`: upon missing
topics and raise_on_error=True
:py:class:`kafka_utils.util.error.UnknownPartition`: upon missing
partitions and raise_on_error=True
:py:class:`exceptions.TypeError`: upon badly formatted input
new_offsets
FailedPayloadsError: upon send request error.
"""
valid_new_offsets = _verify_commit_offsets_requests(
kafka_client,
new_offsets,
raise_on_error
)
group_offset_reqs = [
OffsetCommitRequestPayload(
topic,
partition,
offset,
metadata='',
)
for topic, new_partition_offsets in six.iteritems(valid_new_offsets)
for partition, offset in six.iteritems(new_partition_offsets)
]
send_api = kafka_client.send_offset_commit_request_kafka
status = []
if group_offset_reqs:
status = send_api(
group,
group_offset_reqs,
raise_on_error,
callback=_check_commit_response_error
)
return [_f for _f in status
if _f and _f.error != 0] | [
"def",
"set_consumer_offsets",
"(",
"kafka_client",
",",
"group",
",",
"new_offsets",
",",
"raise_on_error",
"=",
"True",
",",
")",
":",
"valid_new_offsets",
"=",
"_verify_commit_offsets_requests",
"(",
"kafka_client",
",",
"new_offsets",
",",
"raise_on_error",
")",
... | Set consumer offsets to the specified offsets.
This method does not validate the specified offsets, it is up to
the caller to specify valid offsets within a topic partition.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic requests in batch
and save both in performance and Kafka load.
:param kafka_client: a connected KafkaToolClient
:param group: kafka group_id
:param topics: dict {<topic>: {<partition>: <offset>}}
:param raise_on_error: if False the method does not raise exceptions
on errors encountered. It may still fail on the request send.
:returns: a list of errors for each partition offset update that failed.
:rtype: list [OffsetCommitError]
:raises:
:py:class:`kafka_utils.util.error.UnknownTopic`: upon missing
topics and raise_on_error=True
:py:class:`kafka_utils.util.error.UnknownPartition`: upon missing
partitions and raise_on_error=True
:py:class:`exceptions.TypeError`: upon badly formatted input
new_offsets
FailedPayloadsError: upon send request error. | [
"Set",
"consumer",
"offsets",
"to",
"the",
"specified",
"offsets",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/offsets.py#L453-L516 | train | 202,569 |
Yelp/kafka-utils | kafka_utils/util/offsets.py | nullify_offsets | def nullify_offsets(offsets):
"""Modify offsets metadata so that the partition offsets
have null payloads.
:param offsets: dict {<topic>: {<partition>: <offset>}}
:returns: a dict topic: partition: offset
"""
result = {}
for topic, partition_offsets in six.iteritems(offsets):
result[topic] = _nullify_partition_offsets(partition_offsets)
return result | python | def nullify_offsets(offsets):
"""Modify offsets metadata so that the partition offsets
have null payloads.
:param offsets: dict {<topic>: {<partition>: <offset>}}
:returns: a dict topic: partition: offset
"""
result = {}
for topic, partition_offsets in six.iteritems(offsets):
result[topic] = _nullify_partition_offsets(partition_offsets)
return result | [
"def",
"nullify_offsets",
"(",
"offsets",
")",
":",
"result",
"=",
"{",
"}",
"for",
"topic",
",",
"partition_offsets",
"in",
"six",
".",
"iteritems",
"(",
"offsets",
")",
":",
"result",
"[",
"topic",
"]",
"=",
"_nullify_partition_offsets",
"(",
"partition_of... | Modify offsets metadata so that the partition offsets
have null payloads.
:param offsets: dict {<topic>: {<partition>: <offset>}}
:returns: a dict topic: partition: offset | [
"Modify",
"offsets",
"metadata",
"so",
"that",
"the",
"partition",
"offsets",
"have",
"null",
"payloads",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/offsets.py#L526-L536 | train | 202,570 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/display.py | display_table | def display_table(headers, table):
"""Print a formatted table.
:param headers: A list of header objects that are displayed in the first
row of the table.
:param table: A list of lists where each sublist is a row of the table.
The number of elements in each row should be equal to the number of
headers.
"""
assert all(len(row) == len(headers) for row in table)
str_headers = [str(header) for header in headers]
str_table = [[str(cell) for cell in row] for row in table]
column_lengths = [
max(len(header), *(len(row[i]) for row in str_table))
for i, header in enumerate(str_headers)
]
print(
" | ".join(
str(header).ljust(length)
for header, length in zip(str_headers, column_lengths)
)
)
print("-+-".join("-" * length for length in column_lengths))
for row in str_table:
print(
" | ".join(
str(cell).ljust(length)
for cell, length in zip(row, column_lengths)
)
) | python | def display_table(headers, table):
"""Print a formatted table.
:param headers: A list of header objects that are displayed in the first
row of the table.
:param table: A list of lists where each sublist is a row of the table.
The number of elements in each row should be equal to the number of
headers.
"""
assert all(len(row) == len(headers) for row in table)
str_headers = [str(header) for header in headers]
str_table = [[str(cell) for cell in row] for row in table]
column_lengths = [
max(len(header), *(len(row[i]) for row in str_table))
for i, header in enumerate(str_headers)
]
print(
" | ".join(
str(header).ljust(length)
for header, length in zip(str_headers, column_lengths)
)
)
print("-+-".join("-" * length for length in column_lengths))
for row in str_table:
print(
" | ".join(
str(cell).ljust(length)
for cell, length in zip(row, column_lengths)
)
) | [
"def",
"display_table",
"(",
"headers",
",",
"table",
")",
":",
"assert",
"all",
"(",
"len",
"(",
"row",
")",
"==",
"len",
"(",
"headers",
")",
"for",
"row",
"in",
"table",
")",
"str_headers",
"=",
"[",
"str",
"(",
"header",
")",
"for",
"header",
"... | Print a formatted table.
:param headers: A list of header objects that are displayed in the first
row of the table.
:param table: A list of lists where each sublist is a row of the table.
The number of elements in each row should be equal to the number of
headers. | [
"Print",
"a",
"formatted",
"table",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/display.py#L32-L63 | train | 202,571 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/display.py | display_replica_imbalance | def display_replica_imbalance(cluster_topologies):
"""Display replica replication-group distribution imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object.
"""
assert cluster_topologies
rg_ids = list(next(six.itervalues(cluster_topologies)).rgs.keys())
assert all(
set(rg_ids) == set(cluster_topology.rgs.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
rg_imbalances = [
stats.get_replication_group_imbalance_stats(
list(cluster_topology.rgs.values()),
list(cluster_topology.partitions.values()),
)
for cluster_topology in six.itervalues(cluster_topologies)
]
_display_table_title_multicolumn(
'Extra Replica Count',
'Replication Group',
rg_ids,
list(cluster_topologies.keys()),
[
[erc[rg_id] for rg_id in rg_ids]
for _, erc in rg_imbalances
],
)
for name, imbalance in zip(
six.iterkeys(cluster_topologies),
(imbalance for imbalance, _ in rg_imbalances)
):
print(
'\n'
'{name}'
'Total extra replica count: {imbalance}'
.format(
name='' if len(cluster_topologies) == 1 else name + '\n',
imbalance=imbalance,
)
) | python | def display_replica_imbalance(cluster_topologies):
"""Display replica replication-group distribution imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object.
"""
assert cluster_topologies
rg_ids = list(next(six.itervalues(cluster_topologies)).rgs.keys())
assert all(
set(rg_ids) == set(cluster_topology.rgs.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
rg_imbalances = [
stats.get_replication_group_imbalance_stats(
list(cluster_topology.rgs.values()),
list(cluster_topology.partitions.values()),
)
for cluster_topology in six.itervalues(cluster_topologies)
]
_display_table_title_multicolumn(
'Extra Replica Count',
'Replication Group',
rg_ids,
list(cluster_topologies.keys()),
[
[erc[rg_id] for rg_id in rg_ids]
for _, erc in rg_imbalances
],
)
for name, imbalance in zip(
six.iterkeys(cluster_topologies),
(imbalance for imbalance, _ in rg_imbalances)
):
print(
'\n'
'{name}'
'Total extra replica count: {imbalance}'
.format(
name='' if len(cluster_topologies) == 1 else name + '\n',
imbalance=imbalance,
)
) | [
"def",
"display_replica_imbalance",
"(",
"cluster_topologies",
")",
":",
"assert",
"cluster_topologies",
"rg_ids",
"=",
"list",
"(",
"next",
"(",
"six",
".",
"itervalues",
"(",
"cluster_topologies",
")",
")",
".",
"rgs",
".",
"keys",
"(",
")",
")",
"assert",
... | Display replica replication-group distribution imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object. | [
"Display",
"replica",
"replication",
"-",
"group",
"distribution",
"imbalance",
"statistics",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/display.py#L76-L121 | train | 202,572 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/display.py | display_partition_imbalance | def display_partition_imbalance(cluster_topologies):
"""Display partition count and weight imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object.
"""
broker_ids = list(next(six.itervalues(cluster_topologies)).brokers.keys())
assert all(
set(broker_ids) == set(cluster_topology.brokers.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
broker_partition_counts = [
stats.get_broker_partition_counts(
cluster_topology.brokers[broker_id]
for broker_id in broker_ids
)
for cluster_topology in six.itervalues(cluster_topologies)
]
broker_weights = [
stats.get_broker_weights(
cluster_topology.brokers[broker_id]
for broker_id in broker_ids
)
for cluster_topology in six.itervalues(cluster_topologies)
]
_display_table_title_multicolumn(
'Partition Count',
'Broker',
broker_ids,
list(cluster_topologies.keys()),
broker_partition_counts,
)
print('')
_display_table_title_multicolumn(
'Partition Weight',
'Broker',
broker_ids,
list(cluster_topologies.keys()),
broker_weights,
)
for name, bpc, bw in zip(
list(cluster_topologies.keys()),
broker_partition_counts,
broker_weights
):
print(
'\n'
'{name}'
'Partition count imbalance: {net_imbalance}\n'
'Broker weight mean: {weight_mean}\n'
'Broker weight stdev: {weight_stdev}\n'
'Broker weight cv: {weight_cv}'
.format(
name='' if len(cluster_topologies) == 1 else name + '\n',
net_imbalance=stats.get_net_imbalance(bpc),
weight_mean=stats.mean(bw),
weight_stdev=stats.stdevp(bw),
weight_cv=stats.coefficient_of_variation(bw),
)
) | python | def display_partition_imbalance(cluster_topologies):
"""Display partition count and weight imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object.
"""
broker_ids = list(next(six.itervalues(cluster_topologies)).brokers.keys())
assert all(
set(broker_ids) == set(cluster_topology.brokers.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
broker_partition_counts = [
stats.get_broker_partition_counts(
cluster_topology.brokers[broker_id]
for broker_id in broker_ids
)
for cluster_topology in six.itervalues(cluster_topologies)
]
broker_weights = [
stats.get_broker_weights(
cluster_topology.brokers[broker_id]
for broker_id in broker_ids
)
for cluster_topology in six.itervalues(cluster_topologies)
]
_display_table_title_multicolumn(
'Partition Count',
'Broker',
broker_ids,
list(cluster_topologies.keys()),
broker_partition_counts,
)
print('')
_display_table_title_multicolumn(
'Partition Weight',
'Broker',
broker_ids,
list(cluster_topologies.keys()),
broker_weights,
)
for name, bpc, bw in zip(
list(cluster_topologies.keys()),
broker_partition_counts,
broker_weights
):
print(
'\n'
'{name}'
'Partition count imbalance: {net_imbalance}\n'
'Broker weight mean: {weight_mean}\n'
'Broker weight stdev: {weight_stdev}\n'
'Broker weight cv: {weight_cv}'
.format(
name='' if len(cluster_topologies) == 1 else name + '\n',
net_imbalance=stats.get_net_imbalance(bpc),
weight_mean=stats.mean(bw),
weight_stdev=stats.stdevp(bw),
weight_cv=stats.coefficient_of_variation(bw),
)
) | [
"def",
"display_partition_imbalance",
"(",
"cluster_topologies",
")",
":",
"broker_ids",
"=",
"list",
"(",
"next",
"(",
"six",
".",
"itervalues",
"(",
"cluster_topologies",
")",
")",
".",
"brokers",
".",
"keys",
"(",
")",
")",
"assert",
"all",
"(",
"set",
... | Display partition count and weight imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object. | [
"Display",
"partition",
"count",
"and",
"weight",
"imbalance",
"statistics",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/display.py#L124-L187 | train | 202,573 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/display.py | display_leader_imbalance | def display_leader_imbalance(cluster_topologies):
"""Display leader count and weight imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object.
"""
broker_ids = list(next(six.itervalues(cluster_topologies)).brokers.keys())
assert all(
set(broker_ids) == set(cluster_topology.brokers.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
broker_leader_counts = [
stats.get_broker_leader_counts(
cluster_topology.brokers[broker_id]
for broker_id in broker_ids
)
for cluster_topology in six.itervalues(cluster_topologies)
]
broker_leader_weights = [
stats.get_broker_leader_weights(
cluster_topology.brokers[broker_id]
for broker_id in broker_ids
)
for cluster_topology in six.itervalues(cluster_topologies)
]
_display_table_title_multicolumn(
'Leader Count',
'Brokers',
broker_ids,
list(cluster_topologies.keys()),
broker_leader_counts,
)
print('')
_display_table_title_multicolumn(
'Leader weight',
'Brokers',
broker_ids,
list(cluster_topologies.keys()),
broker_leader_weights,
)
for name, blc, blw in zip(
list(cluster_topologies.keys()),
broker_leader_counts,
broker_leader_weights
):
print(
'\n'
'{name}'
'Leader count imbalance: {net_imbalance}\n'
'Broker leader weight mean: {weight_mean}\n'
'Broker leader weight stdev: {weight_stdev}\n'
'Broker leader weight cv: {weight_cv}'
.format(
name='' if len(cluster_topologies) == 1 else name + '\n',
net_imbalance=stats.get_net_imbalance(blc),
weight_mean=stats.mean(blw),
weight_stdev=stats.stdevp(blw),
weight_cv=stats.coefficient_of_variation(blw),
)
) | python | def display_leader_imbalance(cluster_topologies):
"""Display leader count and weight imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object.
"""
broker_ids = list(next(six.itervalues(cluster_topologies)).brokers.keys())
assert all(
set(broker_ids) == set(cluster_topology.brokers.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
broker_leader_counts = [
stats.get_broker_leader_counts(
cluster_topology.brokers[broker_id]
for broker_id in broker_ids
)
for cluster_topology in six.itervalues(cluster_topologies)
]
broker_leader_weights = [
stats.get_broker_leader_weights(
cluster_topology.brokers[broker_id]
for broker_id in broker_ids
)
for cluster_topology in six.itervalues(cluster_topologies)
]
_display_table_title_multicolumn(
'Leader Count',
'Brokers',
broker_ids,
list(cluster_topologies.keys()),
broker_leader_counts,
)
print('')
_display_table_title_multicolumn(
'Leader weight',
'Brokers',
broker_ids,
list(cluster_topologies.keys()),
broker_leader_weights,
)
for name, blc, blw in zip(
list(cluster_topologies.keys()),
broker_leader_counts,
broker_leader_weights
):
print(
'\n'
'{name}'
'Leader count imbalance: {net_imbalance}\n'
'Broker leader weight mean: {weight_mean}\n'
'Broker leader weight stdev: {weight_stdev}\n'
'Broker leader weight cv: {weight_cv}'
.format(
name='' if len(cluster_topologies) == 1 else name + '\n',
net_imbalance=stats.get_net_imbalance(blc),
weight_mean=stats.mean(blw),
weight_stdev=stats.stdevp(blw),
weight_cv=stats.coefficient_of_variation(blw),
)
) | [
"def",
"display_leader_imbalance",
"(",
"cluster_topologies",
")",
":",
"broker_ids",
"=",
"list",
"(",
"next",
"(",
"six",
".",
"itervalues",
"(",
"cluster_topologies",
")",
")",
".",
"brokers",
".",
"keys",
"(",
")",
")",
"assert",
"all",
"(",
"set",
"("... | Display leader count and weight imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object. | [
"Display",
"leader",
"count",
"and",
"weight",
"imbalance",
"statistics",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/display.py#L190-L254 | train | 202,574 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/display.py | display_topic_broker_imbalance | def display_topic_broker_imbalance(cluster_topologies):
"""Display topic broker imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object.
"""
broker_ids = list(next(six.itervalues(cluster_topologies)).brokers.keys())
assert all(
set(broker_ids) == set(cluster_topology.brokers.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
topic_names = list(next(six.itervalues(cluster_topologies)).topics.keys())
assert all(
set(topic_names) == set(cluster_topology.topics.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
imbalances = [
stats.get_topic_imbalance_stats(
[cluster_topology.brokers[broker_id] for broker_id in broker_ids],
[cluster_topology.topics[tname] for tname in topic_names],
)
for cluster_topology in six.itervalues(cluster_topologies)
]
weighted_imbalances = [
stats.get_weighted_topic_imbalance_stats(
[cluster_topology.brokers[broker_id] for broker_id in broker_ids],
[cluster_topology.topics[tname] for tname in topic_names],
)
for cluster_topology in six.itervalues(cluster_topologies)
]
_display_table_title_multicolumn(
'Extra-Topic-Partition Count',
'Brokers',
broker_ids,
list(cluster_topologies.keys()),
[
[i[1][broker_id] for broker_id in broker_ids]
for i in imbalances
]
)
print('')
_display_table_title_multicolumn(
'Weighted Topic Imbalance',
'Brokers',
broker_ids,
list(cluster_topologies.keys()),
[
[wi[1][broker_id] for broker_id in broker_ids]
for wi in weighted_imbalances
]
)
for name, topic_imbalance, weighted_topic_imbalance in zip(
six.iterkeys(cluster_topologies),
(i[0] for i in imbalances),
(wi[0] for wi in weighted_imbalances),
):
print(
'\n'
'{name}'
'Topic partition imbalance count: {topic_imbalance}\n'
'Weighted topic partition imbalance: {weighted_topic_imbalance}'
.format(
name='' if len(cluster_topologies) == 1 else name + '\n',
topic_imbalance=topic_imbalance,
weighted_topic_imbalance=weighted_topic_imbalance,
)
) | python | def display_topic_broker_imbalance(cluster_topologies):
"""Display topic broker imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object.
"""
broker_ids = list(next(six.itervalues(cluster_topologies)).brokers.keys())
assert all(
set(broker_ids) == set(cluster_topology.brokers.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
topic_names = list(next(six.itervalues(cluster_topologies)).topics.keys())
assert all(
set(topic_names) == set(cluster_topology.topics.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
imbalances = [
stats.get_topic_imbalance_stats(
[cluster_topology.brokers[broker_id] for broker_id in broker_ids],
[cluster_topology.topics[tname] for tname in topic_names],
)
for cluster_topology in six.itervalues(cluster_topologies)
]
weighted_imbalances = [
stats.get_weighted_topic_imbalance_stats(
[cluster_topology.brokers[broker_id] for broker_id in broker_ids],
[cluster_topology.topics[tname] for tname in topic_names],
)
for cluster_topology in six.itervalues(cluster_topologies)
]
_display_table_title_multicolumn(
'Extra-Topic-Partition Count',
'Brokers',
broker_ids,
list(cluster_topologies.keys()),
[
[i[1][broker_id] for broker_id in broker_ids]
for i in imbalances
]
)
print('')
_display_table_title_multicolumn(
'Weighted Topic Imbalance',
'Brokers',
broker_ids,
list(cluster_topologies.keys()),
[
[wi[1][broker_id] for broker_id in broker_ids]
for wi in weighted_imbalances
]
)
for name, topic_imbalance, weighted_topic_imbalance in zip(
six.iterkeys(cluster_topologies),
(i[0] for i in imbalances),
(wi[0] for wi in weighted_imbalances),
):
print(
'\n'
'{name}'
'Topic partition imbalance count: {topic_imbalance}\n'
'Weighted topic partition imbalance: {weighted_topic_imbalance}'
.format(
name='' if len(cluster_topologies) == 1 else name + '\n',
topic_imbalance=topic_imbalance,
weighted_topic_imbalance=weighted_topic_imbalance,
)
) | [
"def",
"display_topic_broker_imbalance",
"(",
"cluster_topologies",
")",
":",
"broker_ids",
"=",
"list",
"(",
"next",
"(",
"six",
".",
"itervalues",
"(",
"cluster_topologies",
")",
")",
".",
"brokers",
".",
"keys",
"(",
")",
")",
"assert",
"all",
"(",
"set",... | Display topic broker imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object. | [
"Display",
"topic",
"broker",
"imbalance",
"statistics",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/display.py#L257-L328 | train | 202,575 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/display.py | display_movements_stats | def display_movements_stats(ct, base_assignment):
"""Display how the amount of movement between two assignments.
:param ct: The cluster's ClusterTopology.
:param base_assignment: The cluster assignment to compare against.
"""
movement_count, movement_size, leader_changes = \
stats.get_partition_movement_stats(ct, base_assignment)
print(
'Total partition movements: {movement_count}\n'
'Total partition movement size: {movement_size}\n'
'Total leader changes: {leader_changes}'
.format(
movement_count=movement_count,
movement_size=movement_size,
leader_changes=leader_changes,
)
) | python | def display_movements_stats(ct, base_assignment):
"""Display how the amount of movement between two assignments.
:param ct: The cluster's ClusterTopology.
:param base_assignment: The cluster assignment to compare against.
"""
movement_count, movement_size, leader_changes = \
stats.get_partition_movement_stats(ct, base_assignment)
print(
'Total partition movements: {movement_count}\n'
'Total partition movement size: {movement_size}\n'
'Total leader changes: {leader_changes}'
.format(
movement_count=movement_count,
movement_size=movement_size,
leader_changes=leader_changes,
)
) | [
"def",
"display_movements_stats",
"(",
"ct",
",",
"base_assignment",
")",
":",
"movement_count",
",",
"movement_size",
",",
"leader_changes",
"=",
"stats",
".",
"get_partition_movement_stats",
"(",
"ct",
",",
"base_assignment",
")",
"print",
"(",
"'Total partition mov... | Display how the amount of movement between two assignments.
:param ct: The cluster's ClusterTopology.
:param base_assignment: The cluster assignment to compare against. | [
"Display",
"how",
"the",
"amount",
"of",
"movement",
"between",
"two",
"assignments",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/display.py#L331-L348 | train | 202,576 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/display.py | display_assignment_changes | def display_assignment_changes(plan_details, to_log=True):
"""Display current and proposed changes in
topic-partition to replica layout over brokers.
"""
curr_plan_list, new_plan_list, total_changes = plan_details
action_cnt = '\n[INFO] Total actions required {0}'.format(total_changes)
_log_or_display(to_log, action_cnt)
action_cnt = (
'[INFO] Total actions that will be executed {0}'
.format(len(new_plan_list))
)
_log_or_display(to_log, action_cnt)
changes = ('[INFO] Proposed Changes in current cluster-layout:\n')
_log_or_display(to_log, changes)
tp_str = 'Topic - Partition'
curr_repl_str = 'Previous-Assignment'
new_rep_str = 'Proposed-Assignment'
tp_list = [tp_repl[0] for tp_repl in curr_plan_list]
# Display heading
msg = '=' * 80
_log_or_display(to_log, msg)
row = (
'{tp:^30s}: {curr_rep_str:^20s} ==> {new_rep_str:^20s}' .format(
tp=tp_str,
curr_rep_str=curr_repl_str,
new_rep_str=new_rep_str,
)
)
_log_or_display(to_log, row)
msg = '=' * 80
_log_or_display(to_log, msg)
# Display each topic-partition list with changes
tp_list_sorted = sorted(tp_list, key=lambda tp: (tp[0], tp[1]))
for tp in tp_list_sorted:
curr_repl = [
tp_repl[1] for tp_repl in curr_plan_list if tp_repl[0] == tp
][0]
proposed_repl = [
tp_repl[1] for tp_repl in new_plan_list if tp_repl[0] == tp
][0]
tp_str = '{topic} - {partition:<2d}'.format(topic=tp[0], partition=tp[1])
row = (
'{tp:<30s}: {curr_repl:<20s} ==> {proposed_repl:<20s}'.format(
tp=tp_str,
curr_repl=curr_repl,
proposed_repl=proposed_repl,
)
)
_log_or_display(to_log, row) | python | def display_assignment_changes(plan_details, to_log=True):
"""Display current and proposed changes in
topic-partition to replica layout over brokers.
"""
curr_plan_list, new_plan_list, total_changes = plan_details
action_cnt = '\n[INFO] Total actions required {0}'.format(total_changes)
_log_or_display(to_log, action_cnt)
action_cnt = (
'[INFO] Total actions that will be executed {0}'
.format(len(new_plan_list))
)
_log_or_display(to_log, action_cnt)
changes = ('[INFO] Proposed Changes in current cluster-layout:\n')
_log_or_display(to_log, changes)
tp_str = 'Topic - Partition'
curr_repl_str = 'Previous-Assignment'
new_rep_str = 'Proposed-Assignment'
tp_list = [tp_repl[0] for tp_repl in curr_plan_list]
# Display heading
msg = '=' * 80
_log_or_display(to_log, msg)
row = (
'{tp:^30s}: {curr_rep_str:^20s} ==> {new_rep_str:^20s}' .format(
tp=tp_str,
curr_rep_str=curr_repl_str,
new_rep_str=new_rep_str,
)
)
_log_or_display(to_log, row)
msg = '=' * 80
_log_or_display(to_log, msg)
# Display each topic-partition list with changes
tp_list_sorted = sorted(tp_list, key=lambda tp: (tp[0], tp[1]))
for tp in tp_list_sorted:
curr_repl = [
tp_repl[1] for tp_repl in curr_plan_list if tp_repl[0] == tp
][0]
proposed_repl = [
tp_repl[1] for tp_repl in new_plan_list if tp_repl[0] == tp
][0]
tp_str = '{topic} - {partition:<2d}'.format(topic=tp[0], partition=tp[1])
row = (
'{tp:<30s}: {curr_repl:<20s} ==> {proposed_repl:<20s}'.format(
tp=tp_str,
curr_repl=curr_repl,
proposed_repl=proposed_repl,
)
)
_log_or_display(to_log, row) | [
"def",
"display_assignment_changes",
"(",
"plan_details",
",",
"to_log",
"=",
"True",
")",
":",
"curr_plan_list",
",",
"new_plan_list",
",",
"total_changes",
"=",
"plan_details",
"action_cnt",
"=",
"'\\n[INFO] Total actions required {0}'",
".",
"format",
"(",
"total_cha... | Display current and proposed changes in
topic-partition to replica layout over brokers. | [
"Display",
"current",
"and",
"proposed",
"changes",
"in",
"topic",
"-",
"partition",
"to",
"replica",
"layout",
"over",
"brokers",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/display.py#L384-L435 | train | 202,577 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/stats.py | get_net_imbalance | def get_net_imbalance(count_per_broker):
"""Calculate and return net imbalance based on given count of
partitions or leaders per broker.
Net-imbalance in case of partitions implies total number of
extra partitions from optimal count over all brokers.
This is also implies, the minimum number of partition movements
required for overall balancing.
For leaders, net imbalance implies total number of extra brokers
as leaders from optimal count.
"""
net_imbalance = 0
opt_count, extra_allowed = \
compute_optimum(len(count_per_broker), sum(count_per_broker))
for count in count_per_broker:
extra_cnt, extra_allowed = \
get_extra_element_count(count, opt_count, extra_allowed)
net_imbalance += extra_cnt
return net_imbalance | python | def get_net_imbalance(count_per_broker):
"""Calculate and return net imbalance based on given count of
partitions or leaders per broker.
Net-imbalance in case of partitions implies total number of
extra partitions from optimal count over all brokers.
This is also implies, the minimum number of partition movements
required for overall balancing.
For leaders, net imbalance implies total number of extra brokers
as leaders from optimal count.
"""
net_imbalance = 0
opt_count, extra_allowed = \
compute_optimum(len(count_per_broker), sum(count_per_broker))
for count in count_per_broker:
extra_cnt, extra_allowed = \
get_extra_element_count(count, opt_count, extra_allowed)
net_imbalance += extra_cnt
return net_imbalance | [
"def",
"get_net_imbalance",
"(",
"count_per_broker",
")",
":",
"net_imbalance",
"=",
"0",
"opt_count",
",",
"extra_allowed",
"=",
"compute_optimum",
"(",
"len",
"(",
"count_per_broker",
")",
",",
"sum",
"(",
"count_per_broker",
")",
")",
"for",
"count",
"in",
... | Calculate and return net imbalance based on given count of
partitions or leaders per broker.
Net-imbalance in case of partitions implies total number of
extra partitions from optimal count over all brokers.
This is also implies, the minimum number of partition movements
required for overall balancing.
For leaders, net imbalance implies total number of extra brokers
as leaders from optimal count. | [
"Calculate",
"and",
"return",
"net",
"imbalance",
"based",
"on",
"given",
"count",
"of",
"partitions",
"or",
"leaders",
"per",
"broker",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/stats.py#L65-L84 | train | 202,578 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/stats.py | get_extra_element_count | def get_extra_element_count(curr_count, opt_count, extra_allowed_cnt):
"""Evaluate and return extra same element count based on given values.
:key-term:
group: In here group can be any base where elements are place
i.e. replication-group while placing replicas (elements)
or brokers while placing partitions (elements).
element: Generic term for units which are optimally placed over group.
:params:
curr_count: Given count
opt_count: Optimal count for each group.
extra_allowed_cnt: Count of groups which can have 1 extra element
_ on each group.
"""
if curr_count > opt_count:
# We still can allow 1 extra count
if extra_allowed_cnt > 0:
extra_allowed_cnt -= 1
extra_cnt = curr_count - opt_count - 1
else:
extra_cnt = curr_count - opt_count
else:
extra_cnt = 0
return extra_cnt, extra_allowed_cnt | python | def get_extra_element_count(curr_count, opt_count, extra_allowed_cnt):
"""Evaluate and return extra same element count based on given values.
:key-term:
group: In here group can be any base where elements are place
i.e. replication-group while placing replicas (elements)
or brokers while placing partitions (elements).
element: Generic term for units which are optimally placed over group.
:params:
curr_count: Given count
opt_count: Optimal count for each group.
extra_allowed_cnt: Count of groups which can have 1 extra element
_ on each group.
"""
if curr_count > opt_count:
# We still can allow 1 extra count
if extra_allowed_cnt > 0:
extra_allowed_cnt -= 1
extra_cnt = curr_count - opt_count - 1
else:
extra_cnt = curr_count - opt_count
else:
extra_cnt = 0
return extra_cnt, extra_allowed_cnt | [
"def",
"get_extra_element_count",
"(",
"curr_count",
",",
"opt_count",
",",
"extra_allowed_cnt",
")",
":",
"if",
"curr_count",
">",
"opt_count",
":",
"# We still can allow 1 extra count",
"if",
"extra_allowed_cnt",
">",
"0",
":",
"extra_allowed_cnt",
"-=",
"1",
"extra... | Evaluate and return extra same element count based on given values.
:key-term:
group: In here group can be any base where elements are place
i.e. replication-group while placing replicas (elements)
or brokers while placing partitions (elements).
element: Generic term for units which are optimally placed over group.
:params:
curr_count: Given count
opt_count: Optimal count for each group.
extra_allowed_cnt: Count of groups which can have 1 extra element
_ on each group. | [
"Evaluate",
"and",
"return",
"extra",
"same",
"element",
"count",
"based",
"on",
"given",
"values",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/stats.py#L87-L111 | train | 202,579 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/stats.py | get_replication_group_imbalance_stats | def get_replication_group_imbalance_stats(rgs, partitions):
"""Calculate extra replica count replica count over each replication-group
and net extra-same-replica count.
"""
tot_rgs = len(rgs)
extra_replica_cnt_per_rg = defaultdict(int)
for partition in partitions:
# Get optimal replica-count for each partition
opt_replica_cnt, extra_replicas_allowed = \
compute_optimum(tot_rgs, partition.replication_factor)
# Extra replica count for each rg
for rg in rgs:
replica_cnt_rg = rg.count_replica(partition)
extra_replica_cnt, extra_replicas_allowed = \
get_extra_element_count(
replica_cnt_rg,
opt_replica_cnt,
extra_replicas_allowed,
)
extra_replica_cnt_per_rg[rg.id] += extra_replica_cnt
# Evaluate net imbalance across all replication-groups
net_imbalance = sum(extra_replica_cnt_per_rg.values())
return net_imbalance, extra_replica_cnt_per_rg | python | def get_replication_group_imbalance_stats(rgs, partitions):
"""Calculate extra replica count replica count over each replication-group
and net extra-same-replica count.
"""
tot_rgs = len(rgs)
extra_replica_cnt_per_rg = defaultdict(int)
for partition in partitions:
# Get optimal replica-count for each partition
opt_replica_cnt, extra_replicas_allowed = \
compute_optimum(tot_rgs, partition.replication_factor)
# Extra replica count for each rg
for rg in rgs:
replica_cnt_rg = rg.count_replica(partition)
extra_replica_cnt, extra_replicas_allowed = \
get_extra_element_count(
replica_cnt_rg,
opt_replica_cnt,
extra_replicas_allowed,
)
extra_replica_cnt_per_rg[rg.id] += extra_replica_cnt
# Evaluate net imbalance across all replication-groups
net_imbalance = sum(extra_replica_cnt_per_rg.values())
return net_imbalance, extra_replica_cnt_per_rg | [
"def",
"get_replication_group_imbalance_stats",
"(",
"rgs",
",",
"partitions",
")",
":",
"tot_rgs",
"=",
"len",
"(",
"rgs",
")",
"extra_replica_cnt_per_rg",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"partition",
"in",
"partitions",
":",
"# Get optimal replica-coun... | Calculate extra replica count replica count over each replication-group
and net extra-same-replica count. | [
"Calculate",
"extra",
"replica",
"count",
"replica",
"count",
"over",
"each",
"replication",
"-",
"group",
"and",
"net",
"extra",
"-",
"same",
"-",
"replica",
"count",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/stats.py#L115-L139 | train | 202,580 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/stats.py | get_topic_imbalance_stats | def get_topic_imbalance_stats(brokers, topics):
"""Return count of topics and partitions on each broker having multiple
partitions of same topic.
:rtype dict(broker_id: same-topic-partition count)
Example:
Total-brokers (b1, b2): 2
Total-partitions of topic t1: 5
(b1 has 4 partitions), (b2 has 1 partition)
opt-count: 5/2 = 2
extra-count: 5%2 = 1
i.e. 1 broker can have 2 + 1 = 3 partitions
and rest of brokers can have 2 partitions for given topic
Extra-partition or imbalance:
b1: current-partitions - optimal-count = 4 - 2 - 1(extra allowed) = 1
Net-imbalance = 1
"""
extra_partition_cnt_per_broker = defaultdict(int)
tot_brokers = len(brokers)
# Sort the brokers so that the iteration order is deterministic.
sorted_brokers = sorted(brokers, key=lambda b: b.id)
for topic in topics:
# Optimal partition-count per topic per broker
total_partition_replicas = \
len(topic.partitions) * topic.replication_factor
opt_partition_cnt, extra_partitions_allowed = \
compute_optimum(tot_brokers, total_partition_replicas)
# Get extra-partition count per broker for each topic
for broker in sorted_brokers:
partition_cnt_broker = broker.count_partitions(topic)
extra_partitions, extra_partitions_allowed = \
get_extra_element_count(
partition_cnt_broker,
opt_partition_cnt,
extra_partitions_allowed,
)
extra_partition_cnt_per_broker[broker.id] += extra_partitions
# Net extra partitions over all brokers
net_imbalance = sum(six.itervalues(extra_partition_cnt_per_broker))
return net_imbalance, extra_partition_cnt_per_broker | python | def get_topic_imbalance_stats(brokers, topics):
"""Return count of topics and partitions on each broker having multiple
partitions of same topic.
:rtype dict(broker_id: same-topic-partition count)
Example:
Total-brokers (b1, b2): 2
Total-partitions of topic t1: 5
(b1 has 4 partitions), (b2 has 1 partition)
opt-count: 5/2 = 2
extra-count: 5%2 = 1
i.e. 1 broker can have 2 + 1 = 3 partitions
and rest of brokers can have 2 partitions for given topic
Extra-partition or imbalance:
b1: current-partitions - optimal-count = 4 - 2 - 1(extra allowed) = 1
Net-imbalance = 1
"""
extra_partition_cnt_per_broker = defaultdict(int)
tot_brokers = len(brokers)
# Sort the brokers so that the iteration order is deterministic.
sorted_brokers = sorted(brokers, key=lambda b: b.id)
for topic in topics:
# Optimal partition-count per topic per broker
total_partition_replicas = \
len(topic.partitions) * topic.replication_factor
opt_partition_cnt, extra_partitions_allowed = \
compute_optimum(tot_brokers, total_partition_replicas)
# Get extra-partition count per broker for each topic
for broker in sorted_brokers:
partition_cnt_broker = broker.count_partitions(topic)
extra_partitions, extra_partitions_allowed = \
get_extra_element_count(
partition_cnt_broker,
opt_partition_cnt,
extra_partitions_allowed,
)
extra_partition_cnt_per_broker[broker.id] += extra_partitions
# Net extra partitions over all brokers
net_imbalance = sum(six.itervalues(extra_partition_cnt_per_broker))
return net_imbalance, extra_partition_cnt_per_broker | [
"def",
"get_topic_imbalance_stats",
"(",
"brokers",
",",
"topics",
")",
":",
"extra_partition_cnt_per_broker",
"=",
"defaultdict",
"(",
"int",
")",
"tot_brokers",
"=",
"len",
"(",
"brokers",
")",
"# Sort the brokers so that the iteration order is deterministic.",
"sorted_br... | Return count of topics and partitions on each broker having multiple
partitions of same topic.
:rtype dict(broker_id: same-topic-partition count)
Example:
Total-brokers (b1, b2): 2
Total-partitions of topic t1: 5
(b1 has 4 partitions), (b2 has 1 partition)
opt-count: 5/2 = 2
extra-count: 5%2 = 1
i.e. 1 broker can have 2 + 1 = 3 partitions
and rest of brokers can have 2 partitions for given topic
Extra-partition or imbalance:
b1: current-partitions - optimal-count = 4 - 2 - 1(extra allowed) = 1
Net-imbalance = 1 | [
"Return",
"count",
"of",
"topics",
"and",
"partitions",
"on",
"each",
"broker",
"having",
"multiple",
"partitions",
"of",
"same",
"topic",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/stats.py#L162-L202 | train | 202,581 |
Yelp/kafka-utils | kafka_utils/kafka_check/metadata_file.py | _read_generated_broker_id | def _read_generated_broker_id(meta_properties_path):
"""reads broker_id from meta.properties file.
:param string meta_properties_path: path for meta.properties file
:returns int: broker_id from meta_properties_path
"""
try:
with open(meta_properties_path, 'r') as f:
broker_id = _parse_meta_properties_file(f)
except IOError:
raise IOError(
"Cannot open meta.properties file: {path}"
.format(path=meta_properties_path),
)
except ValueError:
raise ValueError("Broker id not valid")
if broker_id is None:
raise ValueError("Autogenerated broker id missing from data directory")
return broker_id | python | def _read_generated_broker_id(meta_properties_path):
"""reads broker_id from meta.properties file.
:param string meta_properties_path: path for meta.properties file
:returns int: broker_id from meta_properties_path
"""
try:
with open(meta_properties_path, 'r') as f:
broker_id = _parse_meta_properties_file(f)
except IOError:
raise IOError(
"Cannot open meta.properties file: {path}"
.format(path=meta_properties_path),
)
except ValueError:
raise ValueError("Broker id not valid")
if broker_id is None:
raise ValueError("Autogenerated broker id missing from data directory")
return broker_id | [
"def",
"_read_generated_broker_id",
"(",
"meta_properties_path",
")",
":",
"try",
":",
"with",
"open",
"(",
"meta_properties_path",
",",
"'r'",
")",
"as",
"f",
":",
"broker_id",
"=",
"_parse_meta_properties_file",
"(",
"f",
")",
"except",
"IOError",
":",
"raise"... | reads broker_id from meta.properties file.
:param string meta_properties_path: path for meta.properties file
:returns int: broker_id from meta_properties_path | [
"reads",
"broker_id",
"from",
"meta",
".",
"properties",
"file",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_check/metadata_file.py#L9-L29 | train | 202,582 |
Yelp/kafka-utils | kafka_utils/kafka_check/metadata_file.py | get_broker_id | def get_broker_id(data_path):
"""This function will look into the data folder to get the automatically created
broker_id.
:param string data_path: the path to the kafka data folder
:returns int: the real broker_id
"""
# Path to the meta.properties file. This is used to read the automatic broker id
# if the given broker id is -1
META_FILE_PATH = "{data_path}/meta.properties"
if not data_path:
raise ValueError("You need to specify the data_path if broker_id == -1")
meta_properties_path = META_FILE_PATH.format(data_path=data_path)
return _read_generated_broker_id(meta_properties_path) | python | def get_broker_id(data_path):
"""This function will look into the data folder to get the automatically created
broker_id.
:param string data_path: the path to the kafka data folder
:returns int: the real broker_id
"""
# Path to the meta.properties file. This is used to read the automatic broker id
# if the given broker id is -1
META_FILE_PATH = "{data_path}/meta.properties"
if not data_path:
raise ValueError("You need to specify the data_path if broker_id == -1")
meta_properties_path = META_FILE_PATH.format(data_path=data_path)
return _read_generated_broker_id(meta_properties_path) | [
"def",
"get_broker_id",
"(",
"data_path",
")",
":",
"# Path to the meta.properties file. This is used to read the automatic broker id",
"# if the given broker id is -1",
"META_FILE_PATH",
"=",
"\"{data_path}/meta.properties\"",
"if",
"not",
"data_path",
":",
"raise",
"ValueError",
... | This function will look into the data folder to get the automatically created
broker_id.
:param string data_path: the path to the kafka data folder
:returns int: the real broker_id | [
"This",
"function",
"will",
"look",
"into",
"the",
"data",
"folder",
"to",
"get",
"the",
"automatically",
"created",
"broker_id",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_check/metadata_file.py#L32-L47 | train | 202,583 |
Yelp/kafka-utils | kafka_utils/util/monitoring.py | merge_offsets_metadata | def merge_offsets_metadata(topics, *offsets_responses):
"""Merge the offset metadata dictionaries from multiple responses.
:param topics: list of topics
:param offsets_responses: list of dict topic: partition: offset
:returns: dict topic: partition: offset
"""
result = dict()
for topic in topics:
partition_offsets = [
response[topic]
for response in offsets_responses
if topic in response
]
result[topic] = merge_partition_offsets(*partition_offsets)
return result | python | def merge_offsets_metadata(topics, *offsets_responses):
"""Merge the offset metadata dictionaries from multiple responses.
:param topics: list of topics
:param offsets_responses: list of dict topic: partition: offset
:returns: dict topic: partition: offset
"""
result = dict()
for topic in topics:
partition_offsets = [
response[topic]
for response in offsets_responses
if topic in response
]
result[topic] = merge_partition_offsets(*partition_offsets)
return result | [
"def",
"merge_offsets_metadata",
"(",
"topics",
",",
"*",
"offsets_responses",
")",
":",
"result",
"=",
"dict",
"(",
")",
"for",
"topic",
"in",
"topics",
":",
"partition_offsets",
"=",
"[",
"response",
"[",
"topic",
"]",
"for",
"response",
"in",
"offsets_res... | Merge the offset metadata dictionaries from multiple responses.
:param topics: list of topics
:param offsets_responses: list of dict topic: partition: offset
:returns: dict topic: partition: offset | [
"Merge",
"the",
"offset",
"metadata",
"dictionaries",
"from",
"multiple",
"responses",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/monitoring.py#L150-L165 | train | 202,584 |
Yelp/kafka-utils | kafka_utils/util/monitoring.py | merge_partition_offsets | def merge_partition_offsets(*partition_offsets):
"""Merge the partition offsets of a single topic from multiple responses.
:param partition_offsets: list of dict partition: offset
:returns: dict partition: offset
"""
output = dict()
for partition_offset in partition_offsets:
for partition, offset in six.iteritems(partition_offset):
prev_offset = output.get(partition, 0)
output[partition] = max(prev_offset, offset)
return output | python | def merge_partition_offsets(*partition_offsets):
"""Merge the partition offsets of a single topic from multiple responses.
:param partition_offsets: list of dict partition: offset
:returns: dict partition: offset
"""
output = dict()
for partition_offset in partition_offsets:
for partition, offset in six.iteritems(partition_offset):
prev_offset = output.get(partition, 0)
output[partition] = max(prev_offset, offset)
return output | [
"def",
"merge_partition_offsets",
"(",
"*",
"partition_offsets",
")",
":",
"output",
"=",
"dict",
"(",
")",
"for",
"partition_offset",
"in",
"partition_offsets",
":",
"for",
"partition",
",",
"offset",
"in",
"six",
".",
"iteritems",
"(",
"partition_offset",
")",... | Merge the partition offsets of a single topic from multiple responses.
:param partition_offsets: list of dict partition: offset
:returns: dict partition: offset | [
"Merge",
"the",
"partition",
"offsets",
"of",
"a",
"single",
"topic",
"from",
"multiple",
"responses",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/monitoring.py#L168-L179 | train | 202,585 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/cluster_balancer.py | ClusterBalancer.rebalance_replicas | def rebalance_replicas(
self,
max_movement_count=None,
max_movement_size=None,
):
"""Balance replicas across replication-groups.
:param max_movement_count: The maximum number of partitions to move.
:param max_movement_size: The maximum total size of the partitions to move.
:returns: A 2-tuple whose first element is the number of partitions moved
and whose second element is the total size of the partitions moved.
"""
movement_count = 0
movement_size = 0
for partition in six.itervalues(self.cluster_topology.partitions):
count, size = self._rebalance_partition_replicas(
partition,
None if not max_movement_count
else max_movement_count - movement_count,
None if not max_movement_size
else max_movement_size - movement_size,
)
movement_count += count
movement_size += size
return movement_count, movement_size | python | def rebalance_replicas(
self,
max_movement_count=None,
max_movement_size=None,
):
"""Balance replicas across replication-groups.
:param max_movement_count: The maximum number of partitions to move.
:param max_movement_size: The maximum total size of the partitions to move.
:returns: A 2-tuple whose first element is the number of partitions moved
and whose second element is the total size of the partitions moved.
"""
movement_count = 0
movement_size = 0
for partition in six.itervalues(self.cluster_topology.partitions):
count, size = self._rebalance_partition_replicas(
partition,
None if not max_movement_count
else max_movement_count - movement_count,
None if not max_movement_size
else max_movement_size - movement_size,
)
movement_count += count
movement_size += size
return movement_count, movement_size | [
"def",
"rebalance_replicas",
"(",
"self",
",",
"max_movement_count",
"=",
"None",
",",
"max_movement_size",
"=",
"None",
",",
")",
":",
"movement_count",
"=",
"0",
"movement_size",
"=",
"0",
"for",
"partition",
"in",
"six",
".",
"itervalues",
"(",
"self",
".... | Balance replicas across replication-groups.
:param max_movement_count: The maximum number of partitions to move.
:param max_movement_size: The maximum total size of the partitions to move.
:returns: A 2-tuple whose first element is the number of partitions moved
and whose second element is the total size of the partitions moved. | [
"Balance",
"replicas",
"across",
"replication",
"-",
"groups",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/cluster_balancer.py#L91-L117 | train | 202,586 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/cluster_balancer.py | ClusterBalancer._rebalance_partition_replicas | def _rebalance_partition_replicas(
self,
partition,
max_movement_count=None,
max_movement_size=None,
):
"""Rebalance replication groups for given partition."""
# Separate replication-groups into under and over replicated
total = partition.replication_factor
over_replicated_rgs, under_replicated_rgs = separate_groups(
list(self.cluster_topology.rgs.values()),
lambda g: g.count_replica(partition),
total,
)
# Move replicas from over-replicated to under-replicated groups
movement_count = 0
movement_size = 0
while (
under_replicated_rgs and over_replicated_rgs
) and (
max_movement_size is None or
movement_size + partition.size <= max_movement_size
) and (
max_movement_count is None or
movement_count < max_movement_count
):
# Decide source and destination group
rg_source = self._elect_source_replication_group(
over_replicated_rgs,
partition,
)
rg_destination = self._elect_dest_replication_group(
rg_source.count_replica(partition),
under_replicated_rgs,
partition,
)
if rg_source and rg_destination:
# Actual movement of partition
self.log.debug(
'Moving partition {p_name} from replication-group '
'{rg_source} to replication-group {rg_dest}'.format(
p_name=partition.name,
rg_source=rg_source.id,
rg_dest=rg_destination.id,
),
)
rg_source.move_partition(rg_destination, partition)
movement_count += 1
movement_size += partition.size
else:
# Groups balanced or cannot be balanced further
break
# Re-compute under and over-replicated replication-groups
over_replicated_rgs, under_replicated_rgs = separate_groups(
list(self.cluster_topology.rgs.values()),
lambda g: g.count_replica(partition),
total,
)
return movement_count, movement_size | python | def _rebalance_partition_replicas(
self,
partition,
max_movement_count=None,
max_movement_size=None,
):
"""Rebalance replication groups for given partition."""
# Separate replication-groups into under and over replicated
total = partition.replication_factor
over_replicated_rgs, under_replicated_rgs = separate_groups(
list(self.cluster_topology.rgs.values()),
lambda g: g.count_replica(partition),
total,
)
# Move replicas from over-replicated to under-replicated groups
movement_count = 0
movement_size = 0
while (
under_replicated_rgs and over_replicated_rgs
) and (
max_movement_size is None or
movement_size + partition.size <= max_movement_size
) and (
max_movement_count is None or
movement_count < max_movement_count
):
# Decide source and destination group
rg_source = self._elect_source_replication_group(
over_replicated_rgs,
partition,
)
rg_destination = self._elect_dest_replication_group(
rg_source.count_replica(partition),
under_replicated_rgs,
partition,
)
if rg_source and rg_destination:
# Actual movement of partition
self.log.debug(
'Moving partition {p_name} from replication-group '
'{rg_source} to replication-group {rg_dest}'.format(
p_name=partition.name,
rg_source=rg_source.id,
rg_dest=rg_destination.id,
),
)
rg_source.move_partition(rg_destination, partition)
movement_count += 1
movement_size += partition.size
else:
# Groups balanced or cannot be balanced further
break
# Re-compute under and over-replicated replication-groups
over_replicated_rgs, under_replicated_rgs = separate_groups(
list(self.cluster_topology.rgs.values()),
lambda g: g.count_replica(partition),
total,
)
return movement_count, movement_size | [
"def",
"_rebalance_partition_replicas",
"(",
"self",
",",
"partition",
",",
"max_movement_count",
"=",
"None",
",",
"max_movement_size",
"=",
"None",
",",
")",
":",
"# Separate replication-groups into under and over replicated",
"total",
"=",
"partition",
".",
"replicatio... | Rebalance replication groups for given partition. | [
"Rebalance",
"replication",
"groups",
"for",
"given",
"partition",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/cluster_balancer.py#L119-L178 | train | 202,587 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/cluster_balancer.py | ClusterBalancer._elect_source_replication_group | def _elect_source_replication_group(
self,
over_replicated_rgs,
partition,
):
"""Decide source replication-group based as group with highest replica
count.
"""
return max(
over_replicated_rgs,
key=lambda rg: rg.count_replica(partition),
) | python | def _elect_source_replication_group(
self,
over_replicated_rgs,
partition,
):
"""Decide source replication-group based as group with highest replica
count.
"""
return max(
over_replicated_rgs,
key=lambda rg: rg.count_replica(partition),
) | [
"def",
"_elect_source_replication_group",
"(",
"self",
",",
"over_replicated_rgs",
",",
"partition",
",",
")",
":",
"return",
"max",
"(",
"over_replicated_rgs",
",",
"key",
"=",
"lambda",
"rg",
":",
"rg",
".",
"count_replica",
"(",
"partition",
")",
",",
")"
] | Decide source replication-group based as group with highest replica
count. | [
"Decide",
"source",
"replication",
"-",
"group",
"based",
"as",
"group",
"with",
"highest",
"replica",
"count",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/cluster_balancer.py#L180-L191 | train | 202,588 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/cluster_balancer.py | ClusterBalancer._elect_dest_replication_group | def _elect_dest_replication_group(
self,
replica_count_source,
under_replicated_rgs,
partition,
):
"""Decide destination replication-group based on replica-count."""
min_replicated_rg = min(
under_replicated_rgs,
key=lambda rg: rg.count_replica(partition),
)
# Locate under-replicated replication-group with lesser
# replica count than source replication-group
if min_replicated_rg.count_replica(partition) < replica_count_source - 1:
return min_replicated_rg
return None | python | def _elect_dest_replication_group(
self,
replica_count_source,
under_replicated_rgs,
partition,
):
"""Decide destination replication-group based on replica-count."""
min_replicated_rg = min(
under_replicated_rgs,
key=lambda rg: rg.count_replica(partition),
)
# Locate under-replicated replication-group with lesser
# replica count than source replication-group
if min_replicated_rg.count_replica(partition) < replica_count_source - 1:
return min_replicated_rg
return None | [
"def",
"_elect_dest_replication_group",
"(",
"self",
",",
"replica_count_source",
",",
"under_replicated_rgs",
",",
"partition",
",",
")",
":",
"min_replicated_rg",
"=",
"min",
"(",
"under_replicated_rgs",
",",
"key",
"=",
"lambda",
"rg",
":",
"rg",
".",
"count_re... | Decide destination replication-group based on replica-count. | [
"Decide",
"destination",
"replication",
"-",
"group",
"based",
"on",
"replica",
"-",
"count",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/cluster_balancer.py#L193-L208 | train | 202,589 |
Yelp/kafka-utils | kafka_utils/kafka_consumer_manager/commands/offset_restore.py | OffsetRestore.parse_consumer_offsets | def parse_consumer_offsets(cls, json_file):
"""Parse current offsets from json-file."""
with open(json_file, 'r') as consumer_offsets_json:
try:
parsed_offsets = {}
parsed_offsets_data = json.load(consumer_offsets_json)
# Create new dict with partition-keys as integers
parsed_offsets['groupid'] = parsed_offsets_data['groupid']
parsed_offsets['offsets'] = {}
for topic, topic_data in six.iteritems(parsed_offsets_data['offsets']):
parsed_offsets['offsets'][topic] = {}
for partition, offset in six.iteritems(topic_data):
parsed_offsets['offsets'][topic][int(partition)] = offset
return parsed_offsets
except ValueError:
print(
"Error: Given consumer-data json data-file {file} could not be "
"parsed".format(file=json_file),
file=sys.stderr,
)
raise | python | def parse_consumer_offsets(cls, json_file):
"""Parse current offsets from json-file."""
with open(json_file, 'r') as consumer_offsets_json:
try:
parsed_offsets = {}
parsed_offsets_data = json.load(consumer_offsets_json)
# Create new dict with partition-keys as integers
parsed_offsets['groupid'] = parsed_offsets_data['groupid']
parsed_offsets['offsets'] = {}
for topic, topic_data in six.iteritems(parsed_offsets_data['offsets']):
parsed_offsets['offsets'][topic] = {}
for partition, offset in six.iteritems(topic_data):
parsed_offsets['offsets'][topic][int(partition)] = offset
return parsed_offsets
except ValueError:
print(
"Error: Given consumer-data json data-file {file} could not be "
"parsed".format(file=json_file),
file=sys.stderr,
)
raise | [
"def",
"parse_consumer_offsets",
"(",
"cls",
",",
"json_file",
")",
":",
"with",
"open",
"(",
"json_file",
",",
"'r'",
")",
"as",
"consumer_offsets_json",
":",
"try",
":",
"parsed_offsets",
"=",
"{",
"}",
"parsed_offsets_data",
"=",
"json",
".",
"load",
"(",... | Parse current offsets from json-file. | [
"Parse",
"current",
"offsets",
"from",
"json",
"-",
"file",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_consumer_manager/commands/offset_restore.py#L56-L76 | train | 202,590 |
Yelp/kafka-utils | kafka_utils/kafka_consumer_manager/commands/offset_restore.py | OffsetRestore.build_new_offsets | def build_new_offsets(cls, client, topics_offset_data, topic_partitions, current_offsets):
"""Build complete consumer offsets from parsed current consumer-offsets
and lowmarks and highmarks from current-offsets for.
"""
new_offsets = defaultdict(dict)
try:
for topic, partitions in six.iteritems(topic_partitions):
# Validate current offsets in range of low and highmarks
# Currently we only validate for positive offsets and warn
# if out of range of low and highmarks
valid_partitions = set()
for topic_partition_offsets in current_offsets[topic]:
partition = topic_partition_offsets.partition
valid_partitions.add(partition)
# Skip the partition not present in list
if partition not in topic_partitions[topic]:
continue
lowmark = topic_partition_offsets.lowmark
highmark = topic_partition_offsets.highmark
new_offset = topics_offset_data[topic][partition]
if new_offset < 0:
print(
"Error: Given offset: {offset} is negative"
.format(offset=new_offset),
file=sys.stderr,
)
sys.exit(1)
if new_offset < lowmark or new_offset > highmark:
print(
"Warning: Given offset {offset} for topic-partition "
"{topic}:{partition} is outside the range of lowmark "
"{lowmark} and highmark {highmark}".format(
offset=new_offset,
topic=topic,
partition=partition,
lowmark=lowmark,
highmark=highmark,
)
)
new_offsets[topic][partition] = new_offset
if not set(partitions).issubset(valid_partitions):
print(
"Error: Some invalid partitions {partitions} for topic "
"{topic} found. Valid partition-list {valid_partitions}. "
"Exiting...".format(
partitions=', '.join([str(p) for p in partitions]),
valid_partitions=', '.join([str(p) for p in valid_partitions]),
topic=topic,
),
file=sys.stderr,
)
sys.exit(1)
except KeyError as ex:
print(
"Error: Possible invalid topic or partition. Error msg: {ex}. "
"Exiting...".format(ex=ex),
)
sys.exit(1)
return new_offsets | python | def build_new_offsets(cls, client, topics_offset_data, topic_partitions, current_offsets):
"""Build complete consumer offsets from parsed current consumer-offsets
and lowmarks and highmarks from current-offsets for.
"""
new_offsets = defaultdict(dict)
try:
for topic, partitions in six.iteritems(topic_partitions):
# Validate current offsets in range of low and highmarks
# Currently we only validate for positive offsets and warn
# if out of range of low and highmarks
valid_partitions = set()
for topic_partition_offsets in current_offsets[topic]:
partition = topic_partition_offsets.partition
valid_partitions.add(partition)
# Skip the partition not present in list
if partition not in topic_partitions[topic]:
continue
lowmark = topic_partition_offsets.lowmark
highmark = topic_partition_offsets.highmark
new_offset = topics_offset_data[topic][partition]
if new_offset < 0:
print(
"Error: Given offset: {offset} is negative"
.format(offset=new_offset),
file=sys.stderr,
)
sys.exit(1)
if new_offset < lowmark or new_offset > highmark:
print(
"Warning: Given offset {offset} for topic-partition "
"{topic}:{partition} is outside the range of lowmark "
"{lowmark} and highmark {highmark}".format(
offset=new_offset,
topic=topic,
partition=partition,
lowmark=lowmark,
highmark=highmark,
)
)
new_offsets[topic][partition] = new_offset
if not set(partitions).issubset(valid_partitions):
print(
"Error: Some invalid partitions {partitions} for topic "
"{topic} found. Valid partition-list {valid_partitions}. "
"Exiting...".format(
partitions=', '.join([str(p) for p in partitions]),
valid_partitions=', '.join([str(p) for p in valid_partitions]),
topic=topic,
),
file=sys.stderr,
)
sys.exit(1)
except KeyError as ex:
print(
"Error: Possible invalid topic or partition. Error msg: {ex}. "
"Exiting...".format(ex=ex),
)
sys.exit(1)
return new_offsets | [
"def",
"build_new_offsets",
"(",
"cls",
",",
"client",
",",
"topics_offset_data",
",",
"topic_partitions",
",",
"current_offsets",
")",
":",
"new_offsets",
"=",
"defaultdict",
"(",
"dict",
")",
"try",
":",
"for",
"topic",
",",
"partitions",
"in",
"six",
".",
... | Build complete consumer offsets from parsed current consumer-offsets
and lowmarks and highmarks from current-offsets for. | [
"Build",
"complete",
"consumer",
"offsets",
"from",
"parsed",
"current",
"consumer",
"-",
"offsets",
"and",
"lowmarks",
"and",
"highmarks",
"from",
"current",
"-",
"offsets",
"for",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_consumer_manager/commands/offset_restore.py#L79-L137 | train | 202,591 |
Yelp/kafka-utils | kafka_utils/kafka_consumer_manager/commands/offset_restore.py | OffsetRestore.restore_offsets | def restore_offsets(cls, client, parsed_consumer_offsets):
"""Fetch current offsets from kafka, validate them against given
consumer-offsets data and commit the new offsets.
:param client: Kafka-client
:param parsed_consumer_offsets: Parsed consumer offset data from json file
:type parsed_consumer_offsets: dict(group: dict(topic: partition-offsets))
"""
# Fetch current offsets
try:
consumer_group = parsed_consumer_offsets['groupid']
topics_offset_data = parsed_consumer_offsets['offsets']
topic_partitions = dict(
(topic, [partition for partition in offset_data.keys()])
for topic, offset_data in six.iteritems(topics_offset_data)
)
except IndexError:
print(
"Error: Given parsed consumer-offset data {consumer_offsets} "
"could not be parsed".format(consumer_offsets=parsed_consumer_offsets),
file=sys.stderr,
)
raise
current_offsets = get_consumer_offsets_metadata(
client,
consumer_group,
topic_partitions,
)
# Build new offsets
new_offsets = cls.build_new_offsets(
client,
topics_offset_data,
topic_partitions,
current_offsets,
)
# Commit offsets
consumer_group = parsed_consumer_offsets['groupid']
set_consumer_offsets(client, consumer_group, new_offsets)
print("Restored to new offsets {offsets}".format(offsets=dict(new_offsets))) | python | def restore_offsets(cls, client, parsed_consumer_offsets):
"""Fetch current offsets from kafka, validate them against given
consumer-offsets data and commit the new offsets.
:param client: Kafka-client
:param parsed_consumer_offsets: Parsed consumer offset data from json file
:type parsed_consumer_offsets: dict(group: dict(topic: partition-offsets))
"""
# Fetch current offsets
try:
consumer_group = parsed_consumer_offsets['groupid']
topics_offset_data = parsed_consumer_offsets['offsets']
topic_partitions = dict(
(topic, [partition for partition in offset_data.keys()])
for topic, offset_data in six.iteritems(topics_offset_data)
)
except IndexError:
print(
"Error: Given parsed consumer-offset data {consumer_offsets} "
"could not be parsed".format(consumer_offsets=parsed_consumer_offsets),
file=sys.stderr,
)
raise
current_offsets = get_consumer_offsets_metadata(
client,
consumer_group,
topic_partitions,
)
# Build new offsets
new_offsets = cls.build_new_offsets(
client,
topics_offset_data,
topic_partitions,
current_offsets,
)
# Commit offsets
consumer_group = parsed_consumer_offsets['groupid']
set_consumer_offsets(client, consumer_group, new_offsets)
print("Restored to new offsets {offsets}".format(offsets=dict(new_offsets))) | [
"def",
"restore_offsets",
"(",
"cls",
",",
"client",
",",
"parsed_consumer_offsets",
")",
":",
"# Fetch current offsets",
"try",
":",
"consumer_group",
"=",
"parsed_consumer_offsets",
"[",
"'groupid'",
"]",
"topics_offset_data",
"=",
"parsed_consumer_offsets",
"[",
"'of... | Fetch current offsets from kafka, validate them against given
consumer-offsets data and commit the new offsets.
:param client: Kafka-client
:param parsed_consumer_offsets: Parsed consumer offset data from json file
:type parsed_consumer_offsets: dict(group: dict(topic: partition-offsets)) | [
"Fetch",
"current",
"offsets",
"from",
"kafka",
"validate",
"them",
"against",
"given",
"consumer",
"-",
"offsets",
"data",
"and",
"commit",
"the",
"new",
"offsets",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_consumer_manager/commands/offset_restore.py#L150-L189 | train | 202,592 |
Yelp/kafka-utils | kafka_utils/util/__init__.py | tuple_replace | def tuple_replace(tup, *pairs):
"""Return a copy of a tuple with some elements replaced.
:param tup: The tuple to be copied.
:param pairs: Any number of (index, value) tuples where index is the index
of the item to replace and value is the new value of the item.
"""
tuple_list = list(tup)
for index, value in pairs:
tuple_list[index] = value
return tuple(tuple_list) | python | def tuple_replace(tup, *pairs):
"""Return a copy of a tuple with some elements replaced.
:param tup: The tuple to be copied.
:param pairs: Any number of (index, value) tuples where index is the index
of the item to replace and value is the new value of the item.
"""
tuple_list = list(tup)
for index, value in pairs:
tuple_list[index] = value
return tuple(tuple_list) | [
"def",
"tuple_replace",
"(",
"tup",
",",
"*",
"pairs",
")",
":",
"tuple_list",
"=",
"list",
"(",
"tup",
")",
"for",
"index",
",",
"value",
"in",
"pairs",
":",
"tuple_list",
"[",
"index",
"]",
"=",
"value",
"return",
"tuple",
"(",
"tuple_list",
")"
] | Return a copy of a tuple with some elements replaced.
:param tup: The tuple to be copied.
:param pairs: Any number of (index, value) tuples where index is the index
of the item to replace and value is the new value of the item. | [
"Return",
"a",
"copy",
"of",
"a",
"tuple",
"with",
"some",
"elements",
"replaced",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/__init__.py#L24-L34 | train | 202,593 |
Yelp/kafka-utils | kafka_utils/util/__init__.py | tuple_alter | def tuple_alter(tup, *pairs):
"""Return a copy of a tuple with some elements altered.
:param tup: The tuple to be copied.
:param pairs: Any number of (index, func) tuples where index is the index
of the item to alter and the new value is func(tup[index]).
"""
# timeit says that this is faster than a similar
tuple_list = list(tup)
for i, f in pairs:
tuple_list[i] = f(tuple_list[i])
return tuple(tuple_list) | python | def tuple_alter(tup, *pairs):
"""Return a copy of a tuple with some elements altered.
:param tup: The tuple to be copied.
:param pairs: Any number of (index, func) tuples where index is the index
of the item to alter and the new value is func(tup[index]).
"""
# timeit says that this is faster than a similar
tuple_list = list(tup)
for i, f in pairs:
tuple_list[i] = f(tuple_list[i])
return tuple(tuple_list) | [
"def",
"tuple_alter",
"(",
"tup",
",",
"*",
"pairs",
")",
":",
"# timeit says that this is faster than a similar",
"tuple_list",
"=",
"list",
"(",
"tup",
")",
"for",
"i",
",",
"f",
"in",
"pairs",
":",
"tuple_list",
"[",
"i",
"]",
"=",
"f",
"(",
"tuple_list... | Return a copy of a tuple with some elements altered.
:param tup: The tuple to be copied.
:param pairs: Any number of (index, func) tuples where index is the index
of the item to alter and the new value is func(tup[index]). | [
"Return",
"a",
"copy",
"of",
"a",
"tuple",
"with",
"some",
"elements",
"altered",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/__init__.py#L37-L48 | train | 202,594 |
Yelp/kafka-utils | kafka_utils/util/__init__.py | tuple_remove | def tuple_remove(tup, *items):
"""Return a copy of a tuple with some items removed.
:param tup: The tuple to be copied.
:param items: Any number of items. The first instance of each item will
be removed from the tuple.
"""
tuple_list = list(tup)
for item in items:
tuple_list.remove(item)
return tuple(tuple_list) | python | def tuple_remove(tup, *items):
"""Return a copy of a tuple with some items removed.
:param tup: The tuple to be copied.
:param items: Any number of items. The first instance of each item will
be removed from the tuple.
"""
tuple_list = list(tup)
for item in items:
tuple_list.remove(item)
return tuple(tuple_list) | [
"def",
"tuple_remove",
"(",
"tup",
",",
"*",
"items",
")",
":",
"tuple_list",
"=",
"list",
"(",
"tup",
")",
"for",
"item",
"in",
"items",
":",
"tuple_list",
".",
"remove",
"(",
"item",
")",
"return",
"tuple",
"(",
"tuple_list",
")"
] | Return a copy of a tuple with some items removed.
:param tup: The tuple to be copied.
:param items: Any number of items. The first instance of each item will
be removed from the tuple. | [
"Return",
"a",
"copy",
"of",
"a",
"tuple",
"with",
"some",
"items",
"removed",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/__init__.py#L51-L61 | train | 202,595 |
Yelp/kafka-utils | kafka_utils/util/__init__.py | positive_int | def positive_int(string):
"""Convert string to positive integer."""
error_msg = 'Positive integer required, {string} given.'.format(string=string)
try:
value = int(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value < 0:
raise ArgumentTypeError(error_msg)
return value | python | def positive_int(string):
"""Convert string to positive integer."""
error_msg = 'Positive integer required, {string} given.'.format(string=string)
try:
value = int(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value < 0:
raise ArgumentTypeError(error_msg)
return value | [
"def",
"positive_int",
"(",
"string",
")",
":",
"error_msg",
"=",
"'Positive integer required, {string} given.'",
".",
"format",
"(",
"string",
"=",
"string",
")",
"try",
":",
"value",
"=",
"int",
"(",
"string",
")",
"except",
"ValueError",
":",
"raise",
"Argu... | Convert string to positive integer. | [
"Convert",
"string",
"to",
"positive",
"integer",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/__init__.py#L64-L73 | train | 202,596 |
Yelp/kafka-utils | kafka_utils/util/__init__.py | positive_nonzero_int | def positive_nonzero_int(string):
"""Convert string to positive integer greater than zero."""
error_msg = 'Positive non-zero integer required, {string} given.'.format(string=string)
try:
value = int(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value <= 0:
raise ArgumentTypeError(error_msg)
return value | python | def positive_nonzero_int(string):
"""Convert string to positive integer greater than zero."""
error_msg = 'Positive non-zero integer required, {string} given.'.format(string=string)
try:
value = int(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value <= 0:
raise ArgumentTypeError(error_msg)
return value | [
"def",
"positive_nonzero_int",
"(",
"string",
")",
":",
"error_msg",
"=",
"'Positive non-zero integer required, {string} given.'",
".",
"format",
"(",
"string",
"=",
"string",
")",
"try",
":",
"value",
"=",
"int",
"(",
"string",
")",
"except",
"ValueError",
":",
... | Convert string to positive integer greater than zero. | [
"Convert",
"string",
"to",
"positive",
"integer",
"greater",
"than",
"zero",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/__init__.py#L76-L85 | train | 202,597 |
Yelp/kafka-utils | kafka_utils/util/__init__.py | positive_float | def positive_float(string):
"""Convert string to positive float."""
error_msg = 'Positive float required, {string} given.'.format(string=string)
try:
value = float(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value < 0:
raise ArgumentTypeError(error_msg)
return value | python | def positive_float(string):
"""Convert string to positive float."""
error_msg = 'Positive float required, {string} given.'.format(string=string)
try:
value = float(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value < 0:
raise ArgumentTypeError(error_msg)
return value | [
"def",
"positive_float",
"(",
"string",
")",
":",
"error_msg",
"=",
"'Positive float required, {string} given.'",
".",
"format",
"(",
"string",
"=",
"string",
")",
"try",
":",
"value",
"=",
"float",
"(",
"string",
")",
"except",
"ValueError",
":",
"raise",
"Ar... | Convert string to positive float. | [
"Convert",
"string",
"to",
"positive",
"float",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/__init__.py#L88-L97 | train | 202,598 |
Yelp/kafka-utils | kafka_utils/util/__init__.py | dict_merge | def dict_merge(set1, set2):
"""Joins two dictionaries."""
return dict(list(set1.items()) + list(set2.items())) | python | def dict_merge(set1, set2):
"""Joins two dictionaries."""
return dict(list(set1.items()) + list(set2.items())) | [
"def",
"dict_merge",
"(",
"set1",
",",
"set2",
")",
":",
"return",
"dict",
"(",
"list",
"(",
"set1",
".",
"items",
"(",
")",
")",
"+",
"list",
"(",
"set2",
".",
"items",
"(",
")",
")",
")"
] | Joins two dictionaries. | [
"Joins",
"two",
"dictionaries",
"."
] | cdb4d64308f3079ee0873250bf7b34d0d94eca50 | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/__init__.py#L105-L107 | train | 202,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.