body
stringlengths
26
98.2k
body_hash
int64
-9,222,864,604,528,158,000
9,221,803,474B
docstring
stringlengths
1
16.8k
path
stringlengths
5
230
name
stringlengths
1
96
repository_name
stringlengths
7
89
lang
stringclasses
1 value
body_without_docstring
stringlengths
20
98.2k
def all_subclasses(cls: Any) -> List[Any]: 'Returns all known (imported) subclasses of a class.' classes = (cls.__subclasses__() + [g for s in cls.__subclasses__() for g in all_subclasses(s)]) return [subclass for subclass in classes if (not inspect.isabstract(subclass))]
4,921,096,479,315,253,000
Returns all known (imported) subclasses of a class.
rasa/shared/utils/common.py
all_subclasses
GCES-2021-1/rasa
python
def all_subclasses(cls: Any) -> List[Any]: classes = (cls.__subclasses__() + [g for s in cls.__subclasses__() for g in all_subclasses(s)]) return [subclass for subclass in classes if (not inspect.isabstract(subclass))]
def module_path_from_instance(inst: Any) -> Text: "Return the module path of an instance's class." return ((inst.__module__ + '.') + inst.__class__.__name__)
-4,999,740,613,213,153,000
Return the module path of an instance's class.
rasa/shared/utils/common.py
module_path_from_instance
GCES-2021-1/rasa
python
def module_path_from_instance(inst: Any) -> Text: return ((inst.__module__ + '.') + inst.__class__.__name__)
def sort_list_of_dicts_by_first_key(dicts: List[Dict]) -> List[Dict]: 'Sorts a list of dictionaries by their first key.' return sorted(dicts, key=(lambda d: list(d.keys())[0]))
2,533,327,906,987,913,700
Sorts a list of dictionaries by their first key.
rasa/shared/utils/common.py
sort_list_of_dicts_by_first_key
GCES-2021-1/rasa
python
def sort_list_of_dicts_by_first_key(dicts: List[Dict]) -> List[Dict]: return sorted(dicts, key=(lambda d: list(d.keys())[0]))
def lazy_property(function: Callable) -> Any: 'Allows to avoid recomputing a property over and over.\n\n The result gets stored in a local var. Computation of the property\n will happen once, on the first call of the property. All\n succeeding calls will use the value stored in the private property.' attr_name = ('_lazy_' + function.__name__) @property def _lazyprop(self: Any) -> Any: if (not hasattr(self, attr_name)): setattr(self, attr_name, function(self)) return getattr(self, attr_name) return _lazyprop
5,812,940,276,335,911,000
Allows to avoid recomputing a property over and over. The result gets stored in a local var. Computation of the property will happen once, on the first call of the property. All succeeding calls will use the value stored in the private property.
rasa/shared/utils/common.py
lazy_property
GCES-2021-1/rasa
python
def lazy_property(function: Callable) -> Any: 'Allows to avoid recomputing a property over and over.\n\n The result gets stored in a local var. Computation of the property\n will happen once, on the first call of the property. All\n succeeding calls will use the value stored in the private property.' attr_name = ('_lazy_' + function.__name__) @property def _lazyprop(self: Any) -> Any: if (not hasattr(self, attr_name)): setattr(self, attr_name, function(self)) return getattr(self, attr_name) return _lazyprop
def cached_method(f: Callable[(..., Any)]) -> Callable[(..., Any)]: "Caches method calls based on the call's `args` and `kwargs`.\n\n Works for `async` and `sync` methods. Don't apply this to functions.\n\n Args:\n f: The decorated method whose return value should be cached.\n\n Returns:\n The return value which the method gives for the first call with the given\n arguments.\n " assert ('self' in arguments_of(f)), 'This decorator can only be used with methods.' class Cache(): 'Helper class to abstract the caching details.' def __init__(self, caching_object: object, args: Any, kwargs: Any) -> None: self.caching_object = caching_object self.cache = getattr(caching_object, self._cache_name(), {}) self.cache_key = functools._make_key(args, kwargs, typed=False) def _cache_name(self) -> Text: return f'_cached_{self.caching_object.__class__.__name__}_{f.__name__}' def is_cached(self) -> bool: return (self.cache_key in self.cache) def cache_result(self, result: Any) -> None: self.cache[self.cache_key] = result setattr(self.caching_object, self._cache_name(), self.cache) def cached_result(self) -> Any: return self.cache[self.cache_key] if asyncio.iscoroutinefunction(f): @functools.wraps(f) async def decorated(self: object, *args: Any, **kwargs: Any) -> Any: cache = Cache(self, args, kwargs) if (not cache.is_cached()): to_cache = asyncio.ensure_future(f(self, *args, **kwargs)) cache.cache_result(to_cache) return (await cache.cached_result()) return decorated else: @functools.wraps(f) def decorated(self: object, *args: Any, **kwargs: Any) -> Any: cache = Cache(self, args, kwargs) if (not cache.is_cached()): to_cache = f(self, *args, **kwargs) cache.cache_result(to_cache) return cache.cached_result() return decorated
-4,378,592,147,679,460,400
Caches method calls based on the call's `args` and `kwargs`. Works for `async` and `sync` methods. Don't apply this to functions. Args: f: The decorated method whose return value should be cached. Returns: The return value which the method gives for the first call with the given arguments.
rasa/shared/utils/common.py
cached_method
GCES-2021-1/rasa
python
def cached_method(f: Callable[(..., Any)]) -> Callable[(..., Any)]: "Caches method calls based on the call's `args` and `kwargs`.\n\n Works for `async` and `sync` methods. Don't apply this to functions.\n\n Args:\n f: The decorated method whose return value should be cached.\n\n Returns:\n The return value which the method gives for the first call with the given\n arguments.\n " assert ('self' in arguments_of(f)), 'This decorator can only be used with methods.' class Cache(): 'Helper class to abstract the caching details.' def __init__(self, caching_object: object, args: Any, kwargs: Any) -> None: self.caching_object = caching_object self.cache = getattr(caching_object, self._cache_name(), {}) self.cache_key = functools._make_key(args, kwargs, typed=False) def _cache_name(self) -> Text: return f'_cached_{self.caching_object.__class__.__name__}_{f.__name__}' def is_cached(self) -> bool: return (self.cache_key in self.cache) def cache_result(self, result: Any) -> None: self.cache[self.cache_key] = result setattr(self.caching_object, self._cache_name(), self.cache) def cached_result(self) -> Any: return self.cache[self.cache_key] if asyncio.iscoroutinefunction(f): @functools.wraps(f) async def decorated(self: object, *args: Any, **kwargs: Any) -> Any: cache = Cache(self, args, kwargs) if (not cache.is_cached()): to_cache = asyncio.ensure_future(f(self, *args, **kwargs)) cache.cache_result(to_cache) return (await cache.cached_result()) return decorated else: @functools.wraps(f) def decorated(self: object, *args: Any, **kwargs: Any) -> Any: cache = Cache(self, args, kwargs) if (not cache.is_cached()): to_cache = f(self, *args, **kwargs) cache.cache_result(to_cache) return cache.cached_result() return decorated
def transform_collection_to_sentence(collection: Collection[Text]) -> Text: "Transforms e.g. a list like ['A', 'B', 'C'] into a sentence 'A, B and C'." x = list(collection) if (len(x) >= 2): return ((', '.join(map(str, x[:(- 1)])) + ' and ') + x[(- 1)]) return ''.join(collection)
-8,276,903,017,728,746,000
Transforms e.g. a list like ['A', 'B', 'C'] into a sentence 'A, B and C'.
rasa/shared/utils/common.py
transform_collection_to_sentence
GCES-2021-1/rasa
python
def transform_collection_to_sentence(collection: Collection[Text]) -> Text: x = list(collection) if (len(x) >= 2): return ((', '.join(map(str, x[:(- 1)])) + ' and ') + x[(- 1)]) return .join(collection)
def minimal_kwargs(kwargs: Dict[(Text, Any)], func: Callable, excluded_keys: Optional[List]=None) -> Dict[(Text, Any)]: 'Returns only the kwargs which are required by a function. Keys, contained in\n the exception list, are not included.\n\n Args:\n kwargs: All available kwargs.\n func: The function which should be called.\n excluded_keys: Keys to exclude from the result.\n\n Returns:\n Subset of kwargs which are accepted by `func`.\n\n ' excluded_keys = (excluded_keys or []) possible_arguments = arguments_of(func) return {k: v for (k, v) in kwargs.items() if ((k in possible_arguments) and (k not in excluded_keys))}
-4,158,038,673,499,428,000
Returns only the kwargs which are required by a function. Keys, contained in the exception list, are not included. Args: kwargs: All available kwargs. func: The function which should be called. excluded_keys: Keys to exclude from the result. Returns: Subset of kwargs which are accepted by `func`.
rasa/shared/utils/common.py
minimal_kwargs
GCES-2021-1/rasa
python
def minimal_kwargs(kwargs: Dict[(Text, Any)], func: Callable, excluded_keys: Optional[List]=None) -> Dict[(Text, Any)]: 'Returns only the kwargs which are required by a function. Keys, contained in\n the exception list, are not included.\n\n Args:\n kwargs: All available kwargs.\n func: The function which should be called.\n excluded_keys: Keys to exclude from the result.\n\n Returns:\n Subset of kwargs which are accepted by `func`.\n\n ' excluded_keys = (excluded_keys or []) possible_arguments = arguments_of(func) return {k: v for (k, v) in kwargs.items() if ((k in possible_arguments) and (k not in excluded_keys))}
def mark_as_experimental_feature(feature_name: Text) -> None: 'Warns users that they are using an experimental feature.' logger.warning(f'The {feature_name} is currently experimental and might change or be removed in the future 🔬 Please share your feedback on it in the forum (https://forum.rasa.com) to help us make this feature ready for production.')
-9,208,751,186,646,962,000
Warns users that they are using an experimental feature.
rasa/shared/utils/common.py
mark_as_experimental_feature
GCES-2021-1/rasa
python
def mark_as_experimental_feature(feature_name: Text) -> None: logger.warning(f'The {feature_name} is currently experimental and might change or be removed in the future 🔬 Please share your feedback on it in the forum (https://forum.rasa.com) to help us make this feature ready for production.')
def arguments_of(func: Callable) -> List[Text]: 'Return the parameters of the function `func` as a list of names.' import inspect return list(inspect.signature(func).parameters.keys())
-8,161,593,928,677,645,000
Return the parameters of the function `func` as a list of names.
rasa/shared/utils/common.py
arguments_of
GCES-2021-1/rasa
python
def arguments_of(func: Callable) -> List[Text]: import inspect return list(inspect.signature(func).parameters.keys())
def prepare_roidb(imdb): "Enrich the imdb's roidb by adding some derived quantities that\n are useful for training. This function precomputes the maximum\n overlap, taken over ground-truth boxes, between each ROI and\n each ground-truth box. The class with maximum overlap is also\n recorded.\n " roidb = imdb.roidb for i in xrange(len(imdb.image_index)): roidb[i]['image'] = imdb.image_path_at(i) gt_overlaps = roidb[i]['gt_overlaps'].toarray() max_overlaps = gt_overlaps.max(axis=1) max_classes = gt_overlaps.argmax(axis=1) roidb[i]['max_classes'] = max_classes roidb[i]['max_overlaps'] = max_overlaps zero_inds = np.where((max_overlaps == 0))[0] assert all((max_classes[zero_inds] == 0)) nonzero_inds = np.where((max_overlaps > 0))[0] assert all((max_classes[nonzero_inds] != 0))
-8,867,570,319,704,350,000
Enrich the imdb's roidb by adding some derived quantities that are useful for training. This function precomputes the maximum overlap, taken over ground-truth boxes, between each ROI and each ground-truth box. The class with maximum overlap is also recorded.
lib/roi_data_layer/roidb.py
prepare_roidb
sx14/hierarchical-relationship
python
def prepare_roidb(imdb): "Enrich the imdb's roidb by adding some derived quantities that\n are useful for training. This function precomputes the maximum\n overlap, taken over ground-truth boxes, between each ROI and\n each ground-truth box. The class with maximum overlap is also\n recorded.\n " roidb = imdb.roidb for i in xrange(len(imdb.image_index)): roidb[i]['image'] = imdb.image_path_at(i) gt_overlaps = roidb[i]['gt_overlaps'].toarray() max_overlaps = gt_overlaps.max(axis=1) max_classes = gt_overlaps.argmax(axis=1) roidb[i]['max_classes'] = max_classes roidb[i]['max_overlaps'] = max_overlaps zero_inds = np.where((max_overlaps == 0))[0] assert all((max_classes[zero_inds] == 0)) nonzero_inds = np.where((max_overlaps > 0))[0] assert all((max_classes[nonzero_inds] != 0))
def add_bbox_regression_targets(roidb): 'Add information needed to train bounding-box regressors.' assert (len(roidb) > 0) assert ('max_classes' in roidb[0]), 'Did you call prepare_roidb first?' num_images = len(roidb) num_classes = roidb[0]['gt_overlaps'].shape[1] for im_i in xrange(num_images): rois = roidb[im_i]['boxes'] max_overlaps = roidb[im_i]['max_overlaps'] max_classes = roidb[im_i]['max_classes'] roidb[im_i]['bbox_targets'] = _compute_targets(rois, max_overlaps, max_classes) class_counts = (np.zeros((num_classes, 1)) + cfg.EPS) sums = np.zeros((num_classes, 4)) squared_sums = np.zeros((num_classes, 4)) for im_i in xrange(num_images): targets = roidb[im_i]['bbox_targets'] for cls in xrange(1, num_classes): cls_inds = np.where((targets[:, 0] == cls))[0] if (cls_inds.size > 0): class_counts[cls] += cls_inds.size sums[cls, :] += targets[cls_inds, 1:].sum(axis=0) squared_sums[cls, :] += (targets[cls_inds, 1:] ** 2).sum(axis=0) means = (sums / class_counts) stds = np.sqrt(((squared_sums / class_counts) - (means ** 2))) for im_i in xrange(num_images): targets = roidb[im_i]['bbox_targets'] for cls in xrange(1, num_classes): cls_inds = np.where((targets[:, 0] == cls))[0] roidb[im_i]['bbox_targets'][cls_inds, 1:] -= means[cls, :] roidb[im_i]['bbox_targets'][cls_inds, 1:] /= stds[cls, :] return (means.ravel(), stds.ravel())
-6,998,400,248,771,317,000
Add information needed to train bounding-box regressors.
lib/roi_data_layer/roidb.py
add_bbox_regression_targets
sx14/hierarchical-relationship
python
def add_bbox_regression_targets(roidb): assert (len(roidb) > 0) assert ('max_classes' in roidb[0]), 'Did you call prepare_roidb first?' num_images = len(roidb) num_classes = roidb[0]['gt_overlaps'].shape[1] for im_i in xrange(num_images): rois = roidb[im_i]['boxes'] max_overlaps = roidb[im_i]['max_overlaps'] max_classes = roidb[im_i]['max_classes'] roidb[im_i]['bbox_targets'] = _compute_targets(rois, max_overlaps, max_classes) class_counts = (np.zeros((num_classes, 1)) + cfg.EPS) sums = np.zeros((num_classes, 4)) squared_sums = np.zeros((num_classes, 4)) for im_i in xrange(num_images): targets = roidb[im_i]['bbox_targets'] for cls in xrange(1, num_classes): cls_inds = np.where((targets[:, 0] == cls))[0] if (cls_inds.size > 0): class_counts[cls] += cls_inds.size sums[cls, :] += targets[cls_inds, 1:].sum(axis=0) squared_sums[cls, :] += (targets[cls_inds, 1:] ** 2).sum(axis=0) means = (sums / class_counts) stds = np.sqrt(((squared_sums / class_counts) - (means ** 2))) for im_i in xrange(num_images): targets = roidb[im_i]['bbox_targets'] for cls in xrange(1, num_classes): cls_inds = np.where((targets[:, 0] == cls))[0] roidb[im_i]['bbox_targets'][cls_inds, 1:] -= means[cls, :] roidb[im_i]['bbox_targets'][cls_inds, 1:] /= stds[cls, :] return (means.ravel(), stds.ravel())
def _compute_targets(rois, overlaps, labels): 'Compute bounding-box regression targets for an image.' rois = rois.astype(np.float, copy=False) gt_inds = np.where((overlaps == 1))[0] ex_inds = np.where((overlaps >= cfg.TRAIN.BBOX_THRESH))[0] ex_gt_overlaps = utils.cython_bbox.bbox_overlaps(rois[ex_inds, :], rois[gt_inds, :]) gt_assignment = ex_gt_overlaps.argmax(axis=1) gt_rois = rois[gt_inds[gt_assignment], :] ex_rois = rois[ex_inds, :] ex_widths = ((ex_rois[:, 2] - ex_rois[:, 0]) + cfg.EPS) ex_heights = ((ex_rois[:, 3] - ex_rois[:, 1]) + cfg.EPS) ex_ctr_x = (ex_rois[:, 0] + (0.5 * ex_widths)) ex_ctr_y = (ex_rois[:, 1] + (0.5 * ex_heights)) gt_widths = ((gt_rois[:, 2] - gt_rois[:, 0]) + cfg.EPS) gt_heights = ((gt_rois[:, 3] - gt_rois[:, 1]) + cfg.EPS) gt_ctr_x = (gt_rois[:, 0] + (0.5 * gt_widths)) gt_ctr_y = (gt_rois[:, 1] + (0.5 * gt_heights)) targets_dx = ((gt_ctr_x - ex_ctr_x) / ex_widths) targets_dy = ((gt_ctr_y - ex_ctr_y) / ex_heights) targets_dw = np.log((gt_widths / ex_widths)) targets_dh = np.log((gt_heights / ex_heights)) targets = np.zeros((rois.shape[0], 5), dtype=np.float32) targets[(ex_inds, 0)] = labels[ex_inds] targets[(ex_inds, 1)] = targets_dx targets[(ex_inds, 2)] = targets_dy targets[(ex_inds, 3)] = targets_dw targets[(ex_inds, 4)] = targets_dh return targets
4,698,837,056,146,223,000
Compute bounding-box regression targets for an image.
lib/roi_data_layer/roidb.py
_compute_targets
sx14/hierarchical-relationship
python
def _compute_targets(rois, overlaps, labels): rois = rois.astype(np.float, copy=False) gt_inds = np.where((overlaps == 1))[0] ex_inds = np.where((overlaps >= cfg.TRAIN.BBOX_THRESH))[0] ex_gt_overlaps = utils.cython_bbox.bbox_overlaps(rois[ex_inds, :], rois[gt_inds, :]) gt_assignment = ex_gt_overlaps.argmax(axis=1) gt_rois = rois[gt_inds[gt_assignment], :] ex_rois = rois[ex_inds, :] ex_widths = ((ex_rois[:, 2] - ex_rois[:, 0]) + cfg.EPS) ex_heights = ((ex_rois[:, 3] - ex_rois[:, 1]) + cfg.EPS) ex_ctr_x = (ex_rois[:, 0] + (0.5 * ex_widths)) ex_ctr_y = (ex_rois[:, 1] + (0.5 * ex_heights)) gt_widths = ((gt_rois[:, 2] - gt_rois[:, 0]) + cfg.EPS) gt_heights = ((gt_rois[:, 3] - gt_rois[:, 1]) + cfg.EPS) gt_ctr_x = (gt_rois[:, 0] + (0.5 * gt_widths)) gt_ctr_y = (gt_rois[:, 1] + (0.5 * gt_heights)) targets_dx = ((gt_ctr_x - ex_ctr_x) / ex_widths) targets_dy = ((gt_ctr_y - ex_ctr_y) / ex_heights) targets_dw = np.log((gt_widths / ex_widths)) targets_dh = np.log((gt_heights / ex_heights)) targets = np.zeros((rois.shape[0], 5), dtype=np.float32) targets[(ex_inds, 0)] = labels[ex_inds] targets[(ex_inds, 1)] = targets_dx targets[(ex_inds, 2)] = targets_dy targets[(ex_inds, 3)] = targets_dw targets[(ex_inds, 4)] = targets_dh return targets
def get_rmse_log(net, X_train, y_train): 'Gets root mse between the logarithms of the prediction and the truth.' num_train = X_train.shape[0] clipped_preds = nd.clip(net(X_train), 1, float('inf')) return np.sqrt(((2 * nd.sum(square_loss(nd.log(clipped_preds), nd.log(y_train))).asscalar()) / num_train))
-7,092,342,962,797,382,000
Gets root mse between the logarithms of the prediction and the truth.
example/gluon/kaggle_k_fold_cross_validation.py
get_rmse_log
ABAPPLO/Mxnetonspark
python
def get_rmse_log(net, X_train, y_train): num_train = X_train.shape[0] clipped_preds = nd.clip(net(X_train), 1, float('inf')) return np.sqrt(((2 * nd.sum(square_loss(nd.log(clipped_preds), nd.log(y_train))).asscalar()) / num_train))
def get_net(): 'Gets a neural network. Better results are obtained with modifications.' net = gluon.nn.Sequential() with net.name_scope(): net.add(gluon.nn.Dense(50, activation='relu')) net.add(gluon.nn.Dense(1)) net.initialize() return net
1,806,053,854,338,454,500
Gets a neural network. Better results are obtained with modifications.
example/gluon/kaggle_k_fold_cross_validation.py
get_net
ABAPPLO/Mxnetonspark
python
def get_net(): net = gluon.nn.Sequential() with net.name_scope(): net.add(gluon.nn.Dense(50, activation='relu')) net.add(gluon.nn.Dense(1)) net.initialize() return net
def train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size): 'Trains the model.' dataset_train = gluon.data.ArrayDataset(X_train, y_train) data_iter_train = gluon.data.DataLoader(dataset_train, batch_size, shuffle=True) trainer = gluon.Trainer(net.collect_params(), 'adam', {'learning_rate': learning_rate, 'wd': weight_decay}) net.collect_params().initialize(force_reinit=True) for epoch in range(epochs): for (data, label) in data_iter_train: with autograd.record(): output = net(data) loss = square_loss(output, label) loss.backward() trainer.step(batch_size) avg_loss = get_rmse_log(net, X_train, y_train) if (epoch > verbose_epoch): print(('Epoch %d, train loss: %f' % (epoch, avg_loss))) return avg_loss
-3,094,733,623,772,374,500
Trains the model.
example/gluon/kaggle_k_fold_cross_validation.py
train
ABAPPLO/Mxnetonspark
python
def train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size): dataset_train = gluon.data.ArrayDataset(X_train, y_train) data_iter_train = gluon.data.DataLoader(dataset_train, batch_size, shuffle=True) trainer = gluon.Trainer(net.collect_params(), 'adam', {'learning_rate': learning_rate, 'wd': weight_decay}) net.collect_params().initialize(force_reinit=True) for epoch in range(epochs): for (data, label) in data_iter_train: with autograd.record(): output = net(data) loss = square_loss(output, label) loss.backward() trainer.step(batch_size) avg_loss = get_rmse_log(net, X_train, y_train) if (epoch > verbose_epoch): print(('Epoch %d, train loss: %f' % (epoch, avg_loss))) return avg_loss
def k_fold_cross_valid(k, epochs, verbose_epoch, X_train, y_train, learning_rate, weight_decay, batch_size): 'Conducts k-fold cross validation for the model.' assert (k > 1) fold_size = (X_train.shape[0] // k) train_loss_sum = 0.0 test_loss_sum = 0.0 for test_idx in range(k): X_val_test = X_train[(test_idx * fold_size):((test_idx + 1) * fold_size), :] y_val_test = y_train[(test_idx * fold_size):((test_idx + 1) * fold_size)] val_train_defined = False for i in range(k): if (i != test_idx): X_cur_fold = X_train[(i * fold_size):((i + 1) * fold_size), :] y_cur_fold = y_train[(i * fold_size):((i + 1) * fold_size)] if (not val_train_defined): X_val_train = X_cur_fold y_val_train = y_cur_fold val_train_defined = True else: X_val_train = nd.concat(X_val_train, X_cur_fold, dim=0) y_val_train = nd.concat(y_val_train, y_cur_fold, dim=0) net = get_net() train_loss = train(net, X_val_train, y_val_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size) train_loss_sum += train_loss test_loss = get_rmse_log(net, X_val_test, y_val_test) print(('Test loss: %f' % test_loss)) test_loss_sum += test_loss return ((train_loss_sum / k), (test_loss_sum / k))
6,129,740,340,677,521,000
Conducts k-fold cross validation for the model.
example/gluon/kaggle_k_fold_cross_validation.py
k_fold_cross_valid
ABAPPLO/Mxnetonspark
python
def k_fold_cross_valid(k, epochs, verbose_epoch, X_train, y_train, learning_rate, weight_decay, batch_size): assert (k > 1) fold_size = (X_train.shape[0] // k) train_loss_sum = 0.0 test_loss_sum = 0.0 for test_idx in range(k): X_val_test = X_train[(test_idx * fold_size):((test_idx + 1) * fold_size), :] y_val_test = y_train[(test_idx * fold_size):((test_idx + 1) * fold_size)] val_train_defined = False for i in range(k): if (i != test_idx): X_cur_fold = X_train[(i * fold_size):((i + 1) * fold_size), :] y_cur_fold = y_train[(i * fold_size):((i + 1) * fold_size)] if (not val_train_defined): X_val_train = X_cur_fold y_val_train = y_cur_fold val_train_defined = True else: X_val_train = nd.concat(X_val_train, X_cur_fold, dim=0) y_val_train = nd.concat(y_val_train, y_cur_fold, dim=0) net = get_net() train_loss = train(net, X_val_train, y_val_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size) train_loss_sum += train_loss test_loss = get_rmse_log(net, X_val_test, y_val_test) print(('Test loss: %f' % test_loss)) test_loss_sum += test_loss return ((train_loss_sum / k), (test_loss_sum / k))
def learn(epochs, verbose_epoch, X_train, y_train, test, learning_rate, weight_decay, batch_size): 'Trains the model and predicts on the test data set.' net = get_net() _ = train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size) preds = net(X_test).asnumpy() test['SalePrice'] = pd.Series(preds.reshape(1, (- 1))[0]) submission = pd.concat([test['Id'], test['SalePrice']], axis=1) submission.to_csv('submission.csv', index=False)
8,761,738,220,094,372,000
Trains the model and predicts on the test data set.
example/gluon/kaggle_k_fold_cross_validation.py
learn
ABAPPLO/Mxnetonspark
python
def learn(epochs, verbose_epoch, X_train, y_train, test, learning_rate, weight_decay, batch_size): net = get_net() _ = train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size) preds = net(X_test).asnumpy() test['SalePrice'] = pd.Series(preds.reshape(1, (- 1))[0]) submission = pd.concat([test['Id'], test['SalePrice']], axis=1) submission.to_csv('submission.csv', index=False)
def create_game(gm): '\n Configure and create a game.\n\n Creates a game with base settings equivalent to one of the default presets.\n Allows user to customize the settings before starting the game.\n\n Parameters\n ----------\n gm : int\n Game type to replicate:\n 0: Normal mode.\n 1: Advanced mode.\n\n Returns\n -------\n BattleshipGame\n Game instance with user-chosen settings.\n ' print(('\n' * PAD_AMOUNT)) if (gm == 0): Utils.box_string('Normal Mode', print_string=True) settings = normal_mode_preset elif (gm == 1): Utils.box_string('Advanced Mode', print_string=True) settings = advanced_mode_preset else: Utils.box_string('Testing Mode', print_string=True) settings = testing_preset Utils.print_settings(settings) if (Utils.num_input('Would you like to change the settings?', 'No', 'Yes') == 1): while True: setting = Utils.num_input('Settings', 'Grid Size', 'Ship Amount', 'Special Abilities', 'Game Type', 'Exit') if (setting == 0): settings['width'] = int(Utils.string_input('Grid Width (5-26)', condition='^[5-9]$|^1[0-9]$|^2[0-6]$')) settings['height'] = int(Utils.string_input('Grid Height (5-26)', condition='^[5-9]$|^1[0-9]$|^2[0-6]$')) elif (setting == 1): while True: settings['5_ships'] = int(Utils.string_input('5-Long Ships (0-9)', condition='[0-9]')) settings['4_ships'] = int(Utils.string_input('4-Long Ships (0-9)', condition='[0-9]')) settings['3_ships'] = int(Utils.string_input('3-Long Ships (0-9)', condition='[0-9]')) settings['2_ships'] = int(Utils.string_input('2-Long Ships (0-9)', condition='[0-9]')) settings['1_ships'] = int(Utils.string_input('1-Long Ships (0-9)', condition='[0-9]')) count = ((((settings['5_ships'] + settings['4_ships']) + settings['3_ships']) + settings['2_ships']) + settings['1_ships']) if (count == 0): Utils.box_string('You must have at least one ship!', print_string=True) elif (count > 26): Utils.box_string('You have put in too many ships! (max 26)', print_string=True) elif ((((((settings['5_ships'] * 5) + (settings['4_ships'] * 4)) + (settings['3_ships'] * 3)) + (settings['2_ships'] * 2)) + settings['1_ships']) > (settings['width'] * settings['height'])): Utils.box_string('Your ships will not fit inside of the board!', print_string=True) else: break elif (setting == 2): settings['allow_moves'] = (Utils.num_input('Ship Moving', 'Enable', 'Disable') == 0) if settings['allow_moves']: settings['allow_mines'] = (Utils.num_input('Mines', 'Enable', 'Disable') == 0) settings['mine_turns'] = (int(Utils.string_input('Turns Between Mines', condition='\\d+')) if settings['allow_mines'] else None) elif (setting == 3): settings['p_type'] = ['CPU', 'Player'][Utils.num_input('Game Type', 'CPU', 'Player')] Utils.print_settings(settings) if (setting == 4): break return BattleshipGame(settings)
8,096,551,393,933,726,000
Configure and create a game. Creates a game with base settings equivalent to one of the default presets. Allows user to customize the settings before starting the game. Parameters ---------- gm : int Game type to replicate: 0: Normal mode. 1: Advanced mode. Returns ------- BattleshipGame Game instance with user-chosen settings.
battleship.py
create_game
GamrCorps/STEMExpoBattleship
python
def create_game(gm): '\n Configure and create a game.\n\n Creates a game with base settings equivalent to one of the default presets.\n Allows user to customize the settings before starting the game.\n\n Parameters\n ----------\n gm : int\n Game type to replicate:\n 0: Normal mode.\n 1: Advanced mode.\n\n Returns\n -------\n BattleshipGame\n Game instance with user-chosen settings.\n ' print(('\n' * PAD_AMOUNT)) if (gm == 0): Utils.box_string('Normal Mode', print_string=True) settings = normal_mode_preset elif (gm == 1): Utils.box_string('Advanced Mode', print_string=True) settings = advanced_mode_preset else: Utils.box_string('Testing Mode', print_string=True) settings = testing_preset Utils.print_settings(settings) if (Utils.num_input('Would you like to change the settings?', 'No', 'Yes') == 1): while True: setting = Utils.num_input('Settings', 'Grid Size', 'Ship Amount', 'Special Abilities', 'Game Type', 'Exit') if (setting == 0): settings['width'] = int(Utils.string_input('Grid Width (5-26)', condition='^[5-9]$|^1[0-9]$|^2[0-6]$')) settings['height'] = int(Utils.string_input('Grid Height (5-26)', condition='^[5-9]$|^1[0-9]$|^2[0-6]$')) elif (setting == 1): while True: settings['5_ships'] = int(Utils.string_input('5-Long Ships (0-9)', condition='[0-9]')) settings['4_ships'] = int(Utils.string_input('4-Long Ships (0-9)', condition='[0-9]')) settings['3_ships'] = int(Utils.string_input('3-Long Ships (0-9)', condition='[0-9]')) settings['2_ships'] = int(Utils.string_input('2-Long Ships (0-9)', condition='[0-9]')) settings['1_ships'] = int(Utils.string_input('1-Long Ships (0-9)', condition='[0-9]')) count = ((((settings['5_ships'] + settings['4_ships']) + settings['3_ships']) + settings['2_ships']) + settings['1_ships']) if (count == 0): Utils.box_string('You must have at least one ship!', print_string=True) elif (count > 26): Utils.box_string('You have put in too many ships! (max 26)', print_string=True) elif ((((((settings['5_ships'] * 5) + (settings['4_ships'] * 4)) + (settings['3_ships'] * 3)) + (settings['2_ships'] * 2)) + settings['1_ships']) > (settings['width'] * settings['height'])): Utils.box_string('Your ships will not fit inside of the board!', print_string=True) else: break elif (setting == 2): settings['allow_moves'] = (Utils.num_input('Ship Moving', 'Enable', 'Disable') == 0) if settings['allow_moves']: settings['allow_mines'] = (Utils.num_input('Mines', 'Enable', 'Disable') == 0) settings['mine_turns'] = (int(Utils.string_input('Turns Between Mines', condition='\\d+')) if settings['allow_mines'] else None) elif (setting == 3): settings['p_type'] = ['CPU', 'Player'][Utils.num_input('Game Type', 'CPU', 'Player')] Utils.print_settings(settings) if (setting == 4): break return BattleshipGame(settings)
@staticmethod def box_string(string, min_width=(- 1), print_string=False): "\n Place a string into an ASCII box.\n\n The result is placed inside of a ASCII box consisting of '+' characters for the corners and '-' characters for the edges.\n\n Parameters\n ----------\n string : str\n String to be boxed.\n min_width : int, optional\n Specifies that the box be of a certain minimum width. Defaults to input string width.\n print_string : bool, optional\n If True, prints the string after building it. Defaults to False.\n\n Returns\n -------\n str\n Input string with a box around it.\n " split_string = string.split('\n') height = len(split_string) length = max(min_width, *[len(x) for x in split_string]) result = (('+' + ('-' * (length + 2))) + '+\n') for i in range(height): result += ('| %s |\n' % split_string[i].center(length)) result += (('+' + ('-' * (length + 2))) + '+') if print_string: print(result) return result
7,150,828,423,301,797,000
Place a string into an ASCII box. The result is placed inside of a ASCII box consisting of '+' characters for the corners and '-' characters for the edges. Parameters ---------- string : str String to be boxed. min_width : int, optional Specifies that the box be of a certain minimum width. Defaults to input string width. print_string : bool, optional If True, prints the string after building it. Defaults to False. Returns ------- str Input string with a box around it.
battleship.py
box_string
GamrCorps/STEMExpoBattleship
python
@staticmethod def box_string(string, min_width=(- 1), print_string=False): "\n Place a string into an ASCII box.\n\n The result is placed inside of a ASCII box consisting of '+' characters for the corners and '-' characters for the edges.\n\n Parameters\n ----------\n string : str\n String to be boxed.\n min_width : int, optional\n Specifies that the box be of a certain minimum width. Defaults to input string width.\n print_string : bool, optional\n If True, prints the string after building it. Defaults to False.\n\n Returns\n -------\n str\n Input string with a box around it.\n " split_string = string.split('\n') height = len(split_string) length = max(min_width, *[len(x) for x in split_string]) result = (('+' + ('-' * (length + 2))) + '+\n') for i in range(height): result += ('| %s |\n' % split_string[i].center(length)) result += (('+' + ('-' * (length + 2))) + '+') if print_string: print(result) return result
@staticmethod def num_input(question, *choices): '\n Take user input based on several different options.\n\n The input question will be repeated until valid input is given.\n The choices will be displayed in order with a number next to them indicating their id.\n Responses can be given as the choice id or the full choice name.\n\n Parameters\n ----------\n question : str\n String to be displayed as the input question. Will be boxed with Utils#box_string before printing.\n *choices : *str\n Options for the user to choose from.\n\n Returns\n -------\n int\n Number of the answer choice, corresponding to the index of the choice in *choices.\n ' error = '' while True: Utils.box_string(((error + '\n') + question).strip(), print_string=True) for i in range(len(choices)): print(('%d: %s' % (i, choices[i]))) response = input('Response: ') if fullmatch('\\d+', response.strip()): to_int = int(response.strip()) if (to_int < len(choices)): return to_int else: error = 'ERROR: Invalid input! Input integer is not one of the available choices! Please try again.' continue else: for i in range(len(choices)): if (response.strip().lower() == choices[i].strip().lower()): return i error = 'ERROR: Invalid input! Input string is not one of the available choices! Please try again.' continue
-2,361,384,523,999,038,500
Take user input based on several different options. The input question will be repeated until valid input is given. The choices will be displayed in order with a number next to them indicating their id. Responses can be given as the choice id or the full choice name. Parameters ---------- question : str String to be displayed as the input question. Will be boxed with Utils#box_string before printing. *choices : *str Options for the user to choose from. Returns ------- int Number of the answer choice, corresponding to the index of the choice in *choices.
battleship.py
num_input
GamrCorps/STEMExpoBattleship
python
@staticmethod def num_input(question, *choices): '\n Take user input based on several different options.\n\n The input question will be repeated until valid input is given.\n The choices will be displayed in order with a number next to them indicating their id.\n Responses can be given as the choice id or the full choice name.\n\n Parameters\n ----------\n question : str\n String to be displayed as the input question. Will be boxed with Utils#box_string before printing.\n *choices : *str\n Options for the user to choose from.\n\n Returns\n -------\n int\n Number of the answer choice, corresponding to the index of the choice in *choices.\n ' error = while True: Utils.box_string(((error + '\n') + question).strip(), print_string=True) for i in range(len(choices)): print(('%d: %s' % (i, choices[i]))) response = input('Response: ') if fullmatch('\\d+', response.strip()): to_int = int(response.strip()) if (to_int < len(choices)): return to_int else: error = 'ERROR: Invalid input! Input integer is not one of the available choices! Please try again.' continue else: for i in range(len(choices)): if (response.strip().lower() == choices[i].strip().lower()): return i error = 'ERROR: Invalid input! Input string is not one of the available choices! Please try again.' continue
@staticmethod def string_input(question, condition='.+'): '\n Take string-based user input.\n\n The input question will be repeated until valid input is given, determined by the condition regex.\n\n Parameters\n ----------\n question : str\n String to be displayed as the input question. Will be boxed with Utils#box_string before printing.\n condition : r-string, optional\n Regex to test input string off of.\n\n Returns\n -------\n str\n Input string.\n ' error = '' while True: Utils.box_string(((error + '\n') + question).strip(), print_string=True) response = input() if fullmatch(condition, response): return response else: error = 'ERROR: Invalid input! Please try again.' continue
-8,818,709,648,197,799,000
Take string-based user input. The input question will be repeated until valid input is given, determined by the condition regex. Parameters ---------- question : str String to be displayed as the input question. Will be boxed with Utils#box_string before printing. condition : r-string, optional Regex to test input string off of. Returns ------- str Input string.
battleship.py
string_input
GamrCorps/STEMExpoBattleship
python
@staticmethod def string_input(question, condition='.+'): '\n Take string-based user input.\n\n The input question will be repeated until valid input is given, determined by the condition regex.\n\n Parameters\n ----------\n question : str\n String to be displayed as the input question. Will be boxed with Utils#box_string before printing.\n condition : r-string, optional\n Regex to test input string off of.\n\n Returns\n -------\n str\n Input string.\n ' error = while True: Utils.box_string(((error + '\n') + question).strip(), print_string=True) response = input() if fullmatch(condition, response): return response else: error = 'ERROR: Invalid input! Please try again.' continue
@staticmethod def print_settings(settings): '\n Pretty-print a settings dictionary.\n\n Parameters\n ----------\n settings : dict\n The settings dictionary to pretty-print.\n\n Returns\n -------\n None\n ' Utils.box_string('Current Settings', print_string=True) print('Grid Size:') print(('\tWidth: %d' % settings['width'])) print(('\tHeight: %d' % settings['height'])) print('Ship Amount:') print(('\t5-Long Ships: %d' % settings['5_ships'])) print(('\t4-Long Ships: %d' % settings['4_ships'])) print(('\t3-Long Ships: %d' % settings['3_ships'])) print(('\t2-Long Ships: %d' % settings['2_ships'])) print(('\t1-Long Ships: %d' % settings['1_ships'])) print('Special Abilities:') print(('\tShip Moving: %s' % str(settings['allow_moves']))) print(('\tMines: %s' % str(settings['allow_mines']))) if settings['allow_mines']: print(('\tTurns Between Mines: %d' % settings['mine_turns'])) print(('Game Type: Player vs. %s' % settings['p_type']))
-2,943,421,785,673,365,000
Pretty-print a settings dictionary. Parameters ---------- settings : dict The settings dictionary to pretty-print. Returns ------- None
battleship.py
print_settings
GamrCorps/STEMExpoBattleship
python
@staticmethod def print_settings(settings): '\n Pretty-print a settings dictionary.\n\n Parameters\n ----------\n settings : dict\n The settings dictionary to pretty-print.\n\n Returns\n -------\n None\n ' Utils.box_string('Current Settings', print_string=True) print('Grid Size:') print(('\tWidth: %d' % settings['width'])) print(('\tHeight: %d' % settings['height'])) print('Ship Amount:') print(('\t5-Long Ships: %d' % settings['5_ships'])) print(('\t4-Long Ships: %d' % settings['4_ships'])) print(('\t3-Long Ships: %d' % settings['3_ships'])) print(('\t2-Long Ships: %d' % settings['2_ships'])) print(('\t1-Long Ships: %d' % settings['1_ships'])) print('Special Abilities:') print(('\tShip Moving: %s' % str(settings['allow_moves']))) print(('\tMines: %s' % str(settings['allow_mines']))) if settings['allow_mines']: print(('\tTurns Between Mines: %d' % settings['mine_turns'])) print(('Game Type: Player vs. %s' % settings['p_type']))
@staticmethod def grid_pos_input(height, width, question='Enter a Position:'): "\n Take user-input in coordinate form.\n\n The input question will be repeated until valid input is given.\n The input must be a valid coordinate in battleship form (r'[A-Z]\\d+').\n The input coordinate must be inside of the grid defined by height and width.\n\n Parameters\n ----------\n height : int\n Specifies the height of the grid.\n width : int\n Specifies the width of the grid.\n question : str, optional\n String to be displayed as the input question. Will be boxed with Utils#box_string before printing. Defaults to 'Enter a Position'.\n\n Returns\n -------\n tuple\n Contains the following:\n int\n Height-aligned position (y-position) of input.\n int\n Width-aligned position (x-position) of input.\n " error = '' while True: Utils.box_string(((error + '\n') + question).strip(), print_string=True) loc = input().upper() if (not fullmatch('[A-Z][1-2]?[0-9]', loc)): error = 'ERROR: Invalid input! Input string is not a valid coordinate! Please try again.' continue elif ((loc[0] in letters[:height]) and (0 < int(loc[1:]) <= width)): return (letters.index(loc[0]), (int(loc[1:]) - 1)) else: error = 'ERROR: Invalid input! Input string is not in the grid! Please try again.' continue
-2,679,898,343,304,835,600
Take user-input in coordinate form. The input question will be repeated until valid input is given. The input must be a valid coordinate in battleship form (r'[A-Z]\d+'). The input coordinate must be inside of the grid defined by height and width. Parameters ---------- height : int Specifies the height of the grid. width : int Specifies the width of the grid. question : str, optional String to be displayed as the input question. Will be boxed with Utils#box_string before printing. Defaults to 'Enter a Position'. Returns ------- tuple Contains the following: int Height-aligned position (y-position) of input. int Width-aligned position (x-position) of input.
battleship.py
grid_pos_input
GamrCorps/STEMExpoBattleship
python
@staticmethod def grid_pos_input(height, width, question='Enter a Position:'): "\n Take user-input in coordinate form.\n\n The input question will be repeated until valid input is given.\n The input must be a valid coordinate in battleship form (r'[A-Z]\\d+').\n The input coordinate must be inside of the grid defined by height and width.\n\n Parameters\n ----------\n height : int\n Specifies the height of the grid.\n width : int\n Specifies the width of the grid.\n question : str, optional\n String to be displayed as the input question. Will be boxed with Utils#box_string before printing. Defaults to 'Enter a Position'.\n\n Returns\n -------\n tuple\n Contains the following:\n int\n Height-aligned position (y-position) of input.\n int\n Width-aligned position (x-position) of input.\n " error = while True: Utils.box_string(((error + '\n') + question).strip(), print_string=True) loc = input().upper() if (not fullmatch('[A-Z][1-2]?[0-9]', loc)): error = 'ERROR: Invalid input! Input string is not a valid coordinate! Please try again.' continue elif ((loc[0] in letters[:height]) and (0 < int(loc[1:]) <= width)): return (letters.index(loc[0]), (int(loc[1:]) - 1)) else: error = 'ERROR: Invalid input! Input string is not in the grid! Please try again.' continue
def __init__(self, settings): '\n Constructor for the BattleshipGame class.\n\n Parameters\n ----------\n settings : dict\n Settings to create the game based off of.\n ' self.settings = settings self.height = settings['height'] self.width = settings['width'] self.p1_grid = [[0 for _ in range(self.width)] for _ in range(self.height)] self.p1_grid_2 = [[0 for _ in range(self.width)] for _ in range(self.height)] self.p1_ships = [] self.p2_grid = [[0 for _ in range(self.width)] for _ in range(self.height)] self.p2_grid_2 = [[0 for _ in range(self.width)] for _ in range(self.height)] self.p2_ships = [] self.p2_cpu = (settings['p_type'] == 'CPU') self.turn = 0 self.p1_mines = 0 self.p2_mines = 0 self.p1_move = '' self.p2_move = '' self.cpu_data = {'shots': [], 'misses': [], 'hits': [], 'p1_ships': None}
-5,138,271,308,075,073,000
Constructor for the BattleshipGame class. Parameters ---------- settings : dict Settings to create the game based off of.
battleship.py
__init__
GamrCorps/STEMExpoBattleship
python
def __init__(self, settings): '\n Constructor for the BattleshipGame class.\n\n Parameters\n ----------\n settings : dict\n Settings to create the game based off of.\n ' self.settings = settings self.height = settings['height'] self.width = settings['width'] self.p1_grid = [[0 for _ in range(self.width)] for _ in range(self.height)] self.p1_grid_2 = [[0 for _ in range(self.width)] for _ in range(self.height)] self.p1_ships = [] self.p2_grid = [[0 for _ in range(self.width)] for _ in range(self.height)] self.p2_grid_2 = [[0 for _ in range(self.width)] for _ in range(self.height)] self.p2_ships = [] self.p2_cpu = (settings['p_type'] == 'CPU') self.turn = 0 self.p1_mines = 0 self.p2_mines = 0 self.p1_move = self.p2_move = self.cpu_data = {'shots': [], 'misses': [], 'hits': [], 'p1_ships': None}
def update_board(self, player): "\n Update both grids for a player.\n\n Adds new ships and puts them into the right locations.\n\n Parameters\n ----------\n player : int\n Determines which player's grids to print. Zero-indexed.\n " if (player == 0): board = self.p1_grid for ship in self.p1_ships: if (not ship['setup']): if (ship['direction'] == 0): for i in range(ship['size']): if (not ((1 <= board[ship['y_pos']][(ship['x_pos'] + i)] <= 26) or (board[ship['y_pos']][(ship['x_pos'] + i)] == 26))): board[ship['y_pos']][(ship['x_pos'] + i)] = (ship['num'] + 1) else: for j in range(ship['size']): if (not ((1 <= board[(ship['y_pos'] + j)][ship['x_pos']] <= 26) or (board[(ship['y_pos'] + j)][ship['x_pos']] == 26))): board[(ship['y_pos'] + j)][ship['x_pos']] = (ship['num'] + 1) ship['setup'] = True else: board = self.p2_grid for ship in self.p2_ships: if (not ship['setup']): if (ship['direction'] == 0): for i in range(ship['size']): if (not ((1 <= board[ship['y_pos']][(ship['x_pos'] + i)] <= 26) or (board[ship['y_pos']][(ship['x_pos'] + i)] == 26))): board[ship['y_pos']][(ship['x_pos'] + i)] = (ship['num'] + 1) else: for j in range(ship['size']): if (not ((1 <= board[(ship['y_pos'] + j)][ship['x_pos']] <= 26) or (board[(ship['y_pos'] + j)][ship['x_pos']] == 26))): board[(ship['y_pos'] + j)][ship['x_pos']] = (ship['num'] + 1) ship['setup'] = True
-1,463,448,551,345,982,700
Update both grids for a player. Adds new ships and puts them into the right locations. Parameters ---------- player : int Determines which player's grids to print. Zero-indexed.
battleship.py
update_board
GamrCorps/STEMExpoBattleship
python
def update_board(self, player): "\n Update both grids for a player.\n\n Adds new ships and puts them into the right locations.\n\n Parameters\n ----------\n player : int\n Determines which player's grids to print. Zero-indexed.\n " if (player == 0): board = self.p1_grid for ship in self.p1_ships: if (not ship['setup']): if (ship['direction'] == 0): for i in range(ship['size']): if (not ((1 <= board[ship['y_pos']][(ship['x_pos'] + i)] <= 26) or (board[ship['y_pos']][(ship['x_pos'] + i)] == 26))): board[ship['y_pos']][(ship['x_pos'] + i)] = (ship['num'] + 1) else: for j in range(ship['size']): if (not ((1 <= board[(ship['y_pos'] + j)][ship['x_pos']] <= 26) or (board[(ship['y_pos'] + j)][ship['x_pos']] == 26))): board[(ship['y_pos'] + j)][ship['x_pos']] = (ship['num'] + 1) ship['setup'] = True else: board = self.p2_grid for ship in self.p2_ships: if (not ship['setup']): if (ship['direction'] == 0): for i in range(ship['size']): if (not ((1 <= board[ship['y_pos']][(ship['x_pos'] + i)] <= 26) or (board[ship['y_pos']][(ship['x_pos'] + i)] == 26))): board[ship['y_pos']][(ship['x_pos'] + i)] = (ship['num'] + 1) else: for j in range(ship['size']): if (not ((1 <= board[(ship['y_pos'] + j)][ship['x_pos']] <= 26) or (board[(ship['y_pos'] + j)][ship['x_pos']] == 26))): board[(ship['y_pos'] + j)][ship['x_pos']] = (ship['num'] + 1) ship['setup'] = True
def print_board(self, player): "\n Pretty-print the current boards of a player.\n\n Prints both boards for a player, along with coordinate references, titles, and boxes around the grids.\n\n Parameters\n ----------\n player : int\n Determines which player's grids to print. Zero-indexed.\n\n Returns\n -------\n str\n Same as the string that is printed.\n " characters = (('.' + letters) + '*0#') self.update_board(player) if (player == 0): board = self.p1_grid board_2 = self.p1_grid_2 else: board = self.p2_grid board_2 = self.p2_grid_2 result = ((((' +' + ('-' * ((self.width * 2) + 1))) + '+') + ('-' * ((self.width * 2) + 1))) + '+\n') result += ((((' |' + 'Your Board'.center(((self.width * 2) + 1))) + '|') + 'Enemy Board'.center(((self.width * 2) + 1))) + '|\n') result += ((((' +' + ('-' * ((self.width * 2) + 1))) + '+') + ('-' * ((self.width * 2) + 1))) + '+\n') if (self.width > 9): result += ((((' | ' + ' '.join([str((x + 1)).rjust(2)[0] for x in range(self.width)])) + ' | ') + ' '.join([str((x + 1)).rjust(2)[0] for x in range(self.width)])) + ' |\n') result += ((((' | ' + ' '.join([str((x + 1)).rjust(2)[1] for x in range(self.width)])) + ' | ') + ' '.join([str((x + 1)).rjust(2)[1] for x in range(self.width)])) + ' |\n') result += (((('+---+' + ('-' * ((self.width * 2) + 1))) + '+') + ('-' * ((self.width * 2) + 1))) + '+\n') for i in range(self.height): result += (((((('| ' + letters[i]) + ' | ') + ' '.join([characters[x] for x in board[i]])) + ' | ') + ' '.join([characters[x] for x in board_2[i]])) + ' |\n') result += (((('+---+' + ('-' * ((self.width * 2) + 1))) + '+') + ('-' * ((self.width * 2) + 1))) + '+') print(result) return result
5,454,646,643,821,010,000
Pretty-print the current boards of a player. Prints both boards for a player, along with coordinate references, titles, and boxes around the grids. Parameters ---------- player : int Determines which player's grids to print. Zero-indexed. Returns ------- str Same as the string that is printed.
battleship.py
print_board
GamrCorps/STEMExpoBattleship
python
def print_board(self, player): "\n Pretty-print the current boards of a player.\n\n Prints both boards for a player, along with coordinate references, titles, and boxes around the grids.\n\n Parameters\n ----------\n player : int\n Determines which player's grids to print. Zero-indexed.\n\n Returns\n -------\n str\n Same as the string that is printed.\n " characters = (('.' + letters) + '*0#') self.update_board(player) if (player == 0): board = self.p1_grid board_2 = self.p1_grid_2 else: board = self.p2_grid board_2 = self.p2_grid_2 result = ((((' +' + ('-' * ((self.width * 2) + 1))) + '+') + ('-' * ((self.width * 2) + 1))) + '+\n') result += ((((' |' + 'Your Board'.center(((self.width * 2) + 1))) + '|') + 'Enemy Board'.center(((self.width * 2) + 1))) + '|\n') result += ((((' +' + ('-' * ((self.width * 2) + 1))) + '+') + ('-' * ((self.width * 2) + 1))) + '+\n') if (self.width > 9): result += ((((' | ' + ' '.join([str((x + 1)).rjust(2)[0] for x in range(self.width)])) + ' | ') + ' '.join([str((x + 1)).rjust(2)[0] for x in range(self.width)])) + ' |\n') result += ((((' | ' + ' '.join([str((x + 1)).rjust(2)[1] for x in range(self.width)])) + ' | ') + ' '.join([str((x + 1)).rjust(2)[1] for x in range(self.width)])) + ' |\n') result += (((('+---+' + ('-' * ((self.width * 2) + 1))) + '+') + ('-' * ((self.width * 2) + 1))) + '+\n') for i in range(self.height): result += (((((('| ' + letters[i]) + ' | ') + ' '.join([characters[x] for x in board[i]])) + ' | ') + ' '.join([characters[x] for x in board_2[i]])) + ' |\n') result += (((('+---+' + ('-' * ((self.width * 2) + 1))) + '+') + ('-' * ((self.width * 2) + 1))) + '+') print(result) return result
def setup_ship(self, pos, direction, player, count, size): '\n Create a ship.\n\n Creates a ship dictionary based on positional, directional, player, and size data and tests if placement is legal.\n\n Parameters\n ----------\n pos : tuple\n (y,x) coordinate pair of top-left corner of the ship.\n direction : int\n Determines the direction of the ship:\n 0: Horizontal.\n 1: Vertical.\n player : int\n Determines which player to assign the ship to. Zero-indexed.\n count : int\n Current ship count for internal tracking use.\n size : int\n Length of the ship.\n\n Returns\n -------\n str\n Error string if an error occurred, None otherwise.\n ' try: if (player == 0): board = self.p1_grid if (direction == 0): for i in range(size): if (board[pos[0]][(pos[1] + i)] != 0): return 'ERROR: You cannot place a ship on top of another!' else: for j in range(size): if (board[(pos[0] + j)][pos[1]] != 0): return 'ERROR: You cannot place a ship on top of another!' else: board = self.p2_grid if (direction == 0): for i in range(size): if (board[pos[0]][(pos[1] + i)] != 0): return 'ERROR: You cannot place a ship on top of another!' else: for j in range(size): if (board[(pos[0] + j)][pos[1]] != 0): return 'ERROR: You cannot place a ship on top of another!' except IndexError: return 'ERROR: You must place a ship inside the grid boundaries!' if (player == 0): self.p1_ships.append({'num': count, 'size': size, 'x_pos': pos[1], 'y_pos': pos[0], 'direction': direction, 'setup': False, 'health': size, 'hits': []}) else: self.p2_ships.append({'num': count, 'size': size, 'x_pos': pos[1], 'y_pos': pos[0], 'direction': direction, 'setup': False, 'health': size, 'hits': []}) return None
-2,972,751,348,295,731,000
Create a ship. Creates a ship dictionary based on positional, directional, player, and size data and tests if placement is legal. Parameters ---------- pos : tuple (y,x) coordinate pair of top-left corner of the ship. direction : int Determines the direction of the ship: 0: Horizontal. 1: Vertical. player : int Determines which player to assign the ship to. Zero-indexed. count : int Current ship count for internal tracking use. size : int Length of the ship. Returns ------- str Error string if an error occurred, None otherwise.
battleship.py
setup_ship
GamrCorps/STEMExpoBattleship
python
def setup_ship(self, pos, direction, player, count, size): '\n Create a ship.\n\n Creates a ship dictionary based on positional, directional, player, and size data and tests if placement is legal.\n\n Parameters\n ----------\n pos : tuple\n (y,x) coordinate pair of top-left corner of the ship.\n direction : int\n Determines the direction of the ship:\n 0: Horizontal.\n 1: Vertical.\n player : int\n Determines which player to assign the ship to. Zero-indexed.\n count : int\n Current ship count for internal tracking use.\n size : int\n Length of the ship.\n\n Returns\n -------\n str\n Error string if an error occurred, None otherwise.\n ' try: if (player == 0): board = self.p1_grid if (direction == 0): for i in range(size): if (board[pos[0]][(pos[1] + i)] != 0): return 'ERROR: You cannot place a ship on top of another!' else: for j in range(size): if (board[(pos[0] + j)][pos[1]] != 0): return 'ERROR: You cannot place a ship on top of another!' else: board = self.p2_grid if (direction == 0): for i in range(size): if (board[pos[0]][(pos[1] + i)] != 0): return 'ERROR: You cannot place a ship on top of another!' else: for j in range(size): if (board[(pos[0] + j)][pos[1]] != 0): return 'ERROR: You cannot place a ship on top of another!' except IndexError: return 'ERROR: You must place a ship inside the grid boundaries!' if (player == 0): self.p1_ships.append({'num': count, 'size': size, 'x_pos': pos[1], 'y_pos': pos[0], 'direction': direction, 'setup': False, 'health': size, 'hits': []}) else: self.p2_ships.append({'num': count, 'size': size, 'x_pos': pos[1], 'y_pos': pos[0], 'direction': direction, 'setup': False, 'health': size, 'hits': []}) return None
def setup_ships(self, size, player, count): '\n Setup all the ships of a particular size for a certain player.\n\n Sets up all of the length-n size ships for a player.\n Count is not updated in-place.\n\n Parameters\n ----------\n size : int\n Length of the ships.\n player : int\n Determines which player to assign the ships to. Zero-indexed.\n count : int\n Current ship count for internal tracking use.\n\n Returns\n -------\n int\n The updated cumulative ship count.\n ' for i in range(self.settings[('%d_ships' % size)]): error = '' while True: self.print_board(player) pos = Utils.grid_pos_input(self.height, self.width, question=(error + ("\nWhere do you want to place ship '%s' (%d-long)?" % (letters[count], size))).strip()) direction = Utils.num_input('Which direction?', 'Horizontal', 'Vertical') error = self.setup_ship(pos, direction, player, count, size) if (error is None): break count += 1 return count
7,149,102,928,931,009,000
Setup all the ships of a particular size for a certain player. Sets up all of the length-n size ships for a player. Count is not updated in-place. Parameters ---------- size : int Length of the ships. player : int Determines which player to assign the ships to. Zero-indexed. count : int Current ship count for internal tracking use. Returns ------- int The updated cumulative ship count.
battleship.py
setup_ships
GamrCorps/STEMExpoBattleship
python
def setup_ships(self, size, player, count): '\n Setup all the ships of a particular size for a certain player.\n\n Sets up all of the length-n size ships for a player.\n Count is not updated in-place.\n\n Parameters\n ----------\n size : int\n Length of the ships.\n player : int\n Determines which player to assign the ships to. Zero-indexed.\n count : int\n Current ship count for internal tracking use.\n\n Returns\n -------\n int\n The updated cumulative ship count.\n ' for i in range(self.settings[('%d_ships' % size)]): error = while True: self.print_board(player) pos = Utils.grid_pos_input(self.height, self.width, question=(error + ("\nWhere do you want to place ship '%s' (%d-long)?" % (letters[count], size))).strip()) direction = Utils.num_input('Which direction?', 'Horizontal', 'Vertical') error = self.setup_ship(pos, direction, player, count, size) if (error is None): break count += 1 return count
def p1_turn(self): "\n Execute a turn for Player 1.\n\n Handles input and output for the turn and updates both player's grids.\n\n Returns\n -------\n bool\n True if game ends after the move, False otherwise\n " print(('\n' * PAD_AMOUNT)) Utils.box_string("Player 1's Turn", min_width=((self.width * 4) + 5), print_string=True) self.p1_move = '' if (not self.p2_cpu): Utils.box_string('Player 2, please look away.', min_width=((self.width * 4) + 5), print_string=True) sleep(self.settings['player_timer']) self.print_board(0) if (self.p2_move != ''): Utils.box_string(('Note: ' + self.p2_move), min_width=((self.width * 4) + 5), print_string=True) if self.settings['allow_moves']: if (self.settings['allow_mines'] and (self.p1_mines > 0)): action = Utils.num_input('What do you want to do?', 'Fire Missile', 'Move a Ship', 'Clear Misses', 'Clear Hits', 'Place a Mine') else: action = Utils.num_input('What do you want to do?', 'Fire Missile', 'Move a Ship', 'Clear Misses', 'Clear Hits') if (action == 0): error = '' while True: (y_pos, x_pos) = Utils.grid_pos_input(self.height, self.width, question=(error + '\nWhere do you want to fire?').strip()) if ((True in [((y_pos, x_pos) in self.p2_ships[x]['hits']) for x in range(len(self.p2_ships))]) or (self.p1_grid_2[y_pos][x_pos] > 26)): error = 'ERROR: You already guessed there!' continue if (self.p2_grid[y_pos][x_pos] > 26): error = 'ERROR: You already guessed there!' continue if (self.p2_grid[y_pos][x_pos] != 0): Utils.box_string('Direct Hit!', min_width=((self.width * 4) + 5), print_string=True) self.p2_ships[(self.p2_grid[y_pos][x_pos] - 1)]['health'] -= 1 self.p2_ships[(self.p2_grid[y_pos][x_pos] - 1)]['hits'].append((y_pos, x_pos)) if (self.p2_ships[(self.p2_grid[y_pos][x_pos] - 1)]['health'] == 0): Utils.box_string('You sunk a ship!', min_width=((self.width * 4) + 5), print_string=True) self.p1_grid_2[y_pos][x_pos] = 27 self.p2_grid[y_pos][x_pos] = 27 else: Utils.box_string('Miss!', min_width=((self.width * 4) + 5), print_string=True) self.p1_grid_2[y_pos][x_pos] = 28 self.p2_grid[y_pos][x_pos] = 28 break elif (action == 1): error = '' ship_num = (- 1) while True: ship_num = letters.index(Utils.string_input((error + '\nWhich ship do you want to move?').strip(), condition=('[A-%sa-%s]' % (letters[(len(self.p1_ships) - 1)], letters[(len(self.p1_ships) - 1)].lower()))).upper()) ship = self.p1_ships[ship_num] if (ship['health'] == 0): error = 'ERROR: That ship is sunk!' continue move_direction = Utils.num_input('Which direction do you want to move it?', 'Up', 'Down', 'Left', 'Right') error = '' try: if (move_direction < 2): true_dir = ((- 1) if (move_direction == 0) else 1) board = self.p1_grid if (ship['direction'] == 0): for i in range(ship['size']): for ship2 in self.p1_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == (ship['y_pos'] + true_dir)) and ((ship2['x_pos'] + k) == (ship['x_pos'] + i))): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == (ship['y_pos'] + true_dir)) and (ship2['x_pos'] == (ship['x_pos'] + i))): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] <= 26) or (board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] == 29)) and (board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] != (ship_num + 1))) or ((ship['y_pos'] + true_dir) < 0) or (ship['y_pos'] >= self.height)): error = 'ERROR: You cannot move your ship there!' else: for j in range(ship['size']): for ship2 in self.p1_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == ((ship['y_pos'] + j) + true_dir)) and ((ship2['x_pos'] + k) == ship['x_pos'])): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == ((ship['y_pos'] + j) + true_dir)) and (ship2['x_pos'] == ship['x_pos'])): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] <= 26) or (board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] == 29)) and (board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] != (ship_num + 1))) or (((ship['y_pos'] + j) + true_dir) < 0) or (ship['y_pos'] >= self.height)): error = 'ERROR: You cannot move your ship there!' if (error == ''): self.p1_ships[ship_num]['setup'] = False self.p1_ships[ship_num]['y_pos'] += true_dir self.p1_move = ('Player 1 just moved a ship ' + ('up!' if (move_direction == 0) else 'down!')) if (ship['direction'] == 0): for i in range((ship['size'] - 1)): board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] = 0 else: for j in range((ship['size'] - 1)): board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] = 0 break else: true_dir = ((- 1) if (move_direction == 2) else 1) board = self.p1_grid if (ship['direction'] == 0): for i in range(ship['size']): for ship2 in self.p1_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == ship['y_pos']) and ((ship2['x_pos'] + k) == ((ship['x_pos'] + i) + true_dir))): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == ship['y_pos']) and (ship2['x_pos'] == ((ship['x_pos'] + i) + true_dir))): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] <= 26) or (board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] == 29)) and (board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] != (ship_num + 1))) or (((ship['x_pos'] + i) + true_dir) < 0) or (ship['x_pos'] >= self.width)): error = 'ERROR: You cannot move your ship there!' else: for j in range(ship['size']): for ship2 in self.p1_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == (ship['y_pos'] + j)) and ((ship2['x_pos'] + k) == (ship['x_pos'] + true_dir))): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == (ship['y_pos'] + j)) and (ship2['x_pos'] == (ship['x_pos'] + true_dir))): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] <= 26) or (board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] == 29)) and (board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] != (ship_num + 1))) or ((ship['x_pos'] + true_dir) < 0) or (ship['x_pos'] >= self.width)): error = 'ERROR: You cannot move your ship there!' if (error == ''): self.p1_ships[ship_num]['setup'] = False self.p1_ships[ship_num]['x_pos'] += true_dir self.p1_move = ('Player 1 just moved a ship to the ' + ('left!' if (move_direction == 2) else 'right!')) if (ship['direction'] == 0): for i in range((ship['size'] - 1)): board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] = 0 else: for j in range((ship['size'] - 1)): board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] = 0 break except IndexError: error = 'ERROR: You cannot move your ship there!' for i in range(self.height): for j in range(self.width): if (board[i][j] == (ship_num + 1)): board[i][j] = 0 self.p1_ships[ship_num]['hits'] = [] self.update_board(0) elif (action == 2): for i in range(self.height): for j in range(self.width): if (self.p1_grid_2[i][j] == 28): self.p1_grid_2[i][j] = 0 return self.p1_turn() elif (action == 3): for i in range(self.height): for j in range(self.width): if (self.p1_grid_2[i][j] == 27): self.p1_grid_2[i][j] = 0 return self.p1_turn() else: error = '' while True: (y_pos, x_pos) = Utils.grid_pos_input(self.height, self.width, question=(error + '\nWhere do you want to place the mine?').strip()) if (self.p2_grid[y_pos][x_pos] == 29): error = 'ERROR: You already placed a mine there!' continue if (1 <= self.p2_grid[y_pos][x_pos] <= 26): ship_num = (self.p2_grid[y_pos][x_pos] - 1) self.p2_ships[ship_num]['health'] = 0 for i in range(self.height): for j in range(self.width): if (self.p2_grid[i][j] == (ship_num + 1)): self.p2_grid[i][j] = 27 Utils.box_string('You sunk a ship!', min_width=((self.width * 4) + 5), print_string=True) self.p2_grid[y_pos][x_pos] = 29 self.p1_grid_2[y_pos][x_pos] = 29 self.p1_mines -= 1 break else: error = '' while True: (y_pos, x_pos) = Utils.grid_pos_input(self.height, self.width, question=(error + '\nWhere do you want to fire?').strip()) if (self.p1_grid_2[y_pos][x_pos] != 0): error = 'ERROR: You already guessed there!' continue if (self.p2_grid[y_pos][x_pos] > 26): error = 'ERROR: You already guessed there!' continue if (self.p2_grid[y_pos][x_pos] != 0): Utils.box_string('Direct Hit!', min_width=((self.width * 4) + 5), print_string=True) self.p2_ships[(self.p2_grid[y_pos][x_pos] - 1)]['health'] -= 1 self.p2_ships[(self.p2_grid[y_pos][x_pos] - 1)]['hits'].append((y_pos, x_pos)) if (self.p2_ships[(self.p2_grid[y_pos][x_pos] - 1)]['health'] == 0): Utils.box_string('You sunk a ship!', min_width=((self.width * 4) + 5), print_string=True) self.p1_grid_2[y_pos][x_pos] = 27 self.p2_grid[y_pos][x_pos] = 27 else: Utils.box_string('Miss!', min_width=((self.width * 4) + 5), print_string=True) self.p1_grid_2[y_pos][x_pos] = 28 self.p2_grid[y_pos][x_pos] = 28 break Utils.box_string('Your turn is now over.', print_string=True) sleep(self.settings['player_timer']) return (sum([x['health'] for x in self.p2_ships]) == 0)
-6,425,654,261,485,334,000
Execute a turn for Player 1. Handles input and output for the turn and updates both player's grids. Returns ------- bool True if game ends after the move, False otherwise
battleship.py
p1_turn
GamrCorps/STEMExpoBattleship
python
def p1_turn(self): "\n Execute a turn for Player 1.\n\n Handles input and output for the turn and updates both player's grids.\n\n Returns\n -------\n bool\n True if game ends after the move, False otherwise\n " print(('\n' * PAD_AMOUNT)) Utils.box_string("Player 1's Turn", min_width=((self.width * 4) + 5), print_string=True) self.p1_move = if (not self.p2_cpu): Utils.box_string('Player 2, please look away.', min_width=((self.width * 4) + 5), print_string=True) sleep(self.settings['player_timer']) self.print_board(0) if (self.p2_move != ): Utils.box_string(('Note: ' + self.p2_move), min_width=((self.width * 4) + 5), print_string=True) if self.settings['allow_moves']: if (self.settings['allow_mines'] and (self.p1_mines > 0)): action = Utils.num_input('What do you want to do?', 'Fire Missile', 'Move a Ship', 'Clear Misses', 'Clear Hits', 'Place a Mine') else: action = Utils.num_input('What do you want to do?', 'Fire Missile', 'Move a Ship', 'Clear Misses', 'Clear Hits') if (action == 0): error = while True: (y_pos, x_pos) = Utils.grid_pos_input(self.height, self.width, question=(error + '\nWhere do you want to fire?').strip()) if ((True in [((y_pos, x_pos) in self.p2_ships[x]['hits']) for x in range(len(self.p2_ships))]) or (self.p1_grid_2[y_pos][x_pos] > 26)): error = 'ERROR: You already guessed there!' continue if (self.p2_grid[y_pos][x_pos] > 26): error = 'ERROR: You already guessed there!' continue if (self.p2_grid[y_pos][x_pos] != 0): Utils.box_string('Direct Hit!', min_width=((self.width * 4) + 5), print_string=True) self.p2_ships[(self.p2_grid[y_pos][x_pos] - 1)]['health'] -= 1 self.p2_ships[(self.p2_grid[y_pos][x_pos] - 1)]['hits'].append((y_pos, x_pos)) if (self.p2_ships[(self.p2_grid[y_pos][x_pos] - 1)]['health'] == 0): Utils.box_string('You sunk a ship!', min_width=((self.width * 4) + 5), print_string=True) self.p1_grid_2[y_pos][x_pos] = 27 self.p2_grid[y_pos][x_pos] = 27 else: Utils.box_string('Miss!', min_width=((self.width * 4) + 5), print_string=True) self.p1_grid_2[y_pos][x_pos] = 28 self.p2_grid[y_pos][x_pos] = 28 break elif (action == 1): error = ship_num = (- 1) while True: ship_num = letters.index(Utils.string_input((error + '\nWhich ship do you want to move?').strip(), condition=('[A-%sa-%s]' % (letters[(len(self.p1_ships) - 1)], letters[(len(self.p1_ships) - 1)].lower()))).upper()) ship = self.p1_ships[ship_num] if (ship['health'] == 0): error = 'ERROR: That ship is sunk!' continue move_direction = Utils.num_input('Which direction do you want to move it?', 'Up', 'Down', 'Left', 'Right') error = try: if (move_direction < 2): true_dir = ((- 1) if (move_direction == 0) else 1) board = self.p1_grid if (ship['direction'] == 0): for i in range(ship['size']): for ship2 in self.p1_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == (ship['y_pos'] + true_dir)) and ((ship2['x_pos'] + k) == (ship['x_pos'] + i))): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == (ship['y_pos'] + true_dir)) and (ship2['x_pos'] == (ship['x_pos'] + i))): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] <= 26) or (board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] == 29)) and (board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] != (ship_num + 1))) or ((ship['y_pos'] + true_dir) < 0) or (ship['y_pos'] >= self.height)): error = 'ERROR: You cannot move your ship there!' else: for j in range(ship['size']): for ship2 in self.p1_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == ((ship['y_pos'] + j) + true_dir)) and ((ship2['x_pos'] + k) == ship['x_pos'])): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == ((ship['y_pos'] + j) + true_dir)) and (ship2['x_pos'] == ship['x_pos'])): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] <= 26) or (board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] == 29)) and (board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] != (ship_num + 1))) or (((ship['y_pos'] + j) + true_dir) < 0) or (ship['y_pos'] >= self.height)): error = 'ERROR: You cannot move your ship there!' if (error == ): self.p1_ships[ship_num]['setup'] = False self.p1_ships[ship_num]['y_pos'] += true_dir self.p1_move = ('Player 1 just moved a ship ' + ('up!' if (move_direction == 0) else 'down!')) if (ship['direction'] == 0): for i in range((ship['size'] - 1)): board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] = 0 else: for j in range((ship['size'] - 1)): board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] = 0 break else: true_dir = ((- 1) if (move_direction == 2) else 1) board = self.p1_grid if (ship['direction'] == 0): for i in range(ship['size']): for ship2 in self.p1_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == ship['y_pos']) and ((ship2['x_pos'] + k) == ((ship['x_pos'] + i) + true_dir))): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == ship['y_pos']) and (ship2['x_pos'] == ((ship['x_pos'] + i) + true_dir))): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] <= 26) or (board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] == 29)) and (board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] != (ship_num + 1))) or (((ship['x_pos'] + i) + true_dir) < 0) or (ship['x_pos'] >= self.width)): error = 'ERROR: You cannot move your ship there!' else: for j in range(ship['size']): for ship2 in self.p1_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == (ship['y_pos'] + j)) and ((ship2['x_pos'] + k) == (ship['x_pos'] + true_dir))): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == (ship['y_pos'] + j)) and (ship2['x_pos'] == (ship['x_pos'] + true_dir))): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] <= 26) or (board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] == 29)) and (board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] != (ship_num + 1))) or ((ship['x_pos'] + true_dir) < 0) or (ship['x_pos'] >= self.width)): error = 'ERROR: You cannot move your ship there!' if (error == ): self.p1_ships[ship_num]['setup'] = False self.p1_ships[ship_num]['x_pos'] += true_dir self.p1_move = ('Player 1 just moved a ship to the ' + ('left!' if (move_direction == 2) else 'right!')) if (ship['direction'] == 0): for i in range((ship['size'] - 1)): board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] = 0 else: for j in range((ship['size'] - 1)): board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] = 0 break except IndexError: error = 'ERROR: You cannot move your ship there!' for i in range(self.height): for j in range(self.width): if (board[i][j] == (ship_num + 1)): board[i][j] = 0 self.p1_ships[ship_num]['hits'] = [] self.update_board(0) elif (action == 2): for i in range(self.height): for j in range(self.width): if (self.p1_grid_2[i][j] == 28): self.p1_grid_2[i][j] = 0 return self.p1_turn() elif (action == 3): for i in range(self.height): for j in range(self.width): if (self.p1_grid_2[i][j] == 27): self.p1_grid_2[i][j] = 0 return self.p1_turn() else: error = while True: (y_pos, x_pos) = Utils.grid_pos_input(self.height, self.width, question=(error + '\nWhere do you want to place the mine?').strip()) if (self.p2_grid[y_pos][x_pos] == 29): error = 'ERROR: You already placed a mine there!' continue if (1 <= self.p2_grid[y_pos][x_pos] <= 26): ship_num = (self.p2_grid[y_pos][x_pos] - 1) self.p2_ships[ship_num]['health'] = 0 for i in range(self.height): for j in range(self.width): if (self.p2_grid[i][j] == (ship_num + 1)): self.p2_grid[i][j] = 27 Utils.box_string('You sunk a ship!', min_width=((self.width * 4) + 5), print_string=True) self.p2_grid[y_pos][x_pos] = 29 self.p1_grid_2[y_pos][x_pos] = 29 self.p1_mines -= 1 break else: error = while True: (y_pos, x_pos) = Utils.grid_pos_input(self.height, self.width, question=(error + '\nWhere do you want to fire?').strip()) if (self.p1_grid_2[y_pos][x_pos] != 0): error = 'ERROR: You already guessed there!' continue if (self.p2_grid[y_pos][x_pos] > 26): error = 'ERROR: You already guessed there!' continue if (self.p2_grid[y_pos][x_pos] != 0): Utils.box_string('Direct Hit!', min_width=((self.width * 4) + 5), print_string=True) self.p2_ships[(self.p2_grid[y_pos][x_pos] - 1)]['health'] -= 1 self.p2_ships[(self.p2_grid[y_pos][x_pos] - 1)]['hits'].append((y_pos, x_pos)) if (self.p2_ships[(self.p2_grid[y_pos][x_pos] - 1)]['health'] == 0): Utils.box_string('You sunk a ship!', min_width=((self.width * 4) + 5), print_string=True) self.p1_grid_2[y_pos][x_pos] = 27 self.p2_grid[y_pos][x_pos] = 27 else: Utils.box_string('Miss!', min_width=((self.width * 4) + 5), print_string=True) self.p1_grid_2[y_pos][x_pos] = 28 self.p2_grid[y_pos][x_pos] = 28 break Utils.box_string('Your turn is now over.', print_string=True) sleep(self.settings['player_timer']) return (sum([x['health'] for x in self.p2_ships]) == 0)
def p2_turn(self): "\n Execute a turn for Player 2.\n\n Handles input and output for the turn and updates both player's grids.\n\n Returns\n -------\n bool\n True if game ends after the move, False otherwise\n " print(('\n' * PAD_AMOUNT)) Utils.box_string("Player 2's Turn", min_width=((self.width * 4) + 5), print_string=True) self.p2_move = '' if (not self.p2_cpu): Utils.box_string('Player 1, please look away.', min_width=((self.width * 4) + 5), print_string=True) sleep(self.settings['player_timer']) self.print_board(1) if (self.p1_move != ''): Utils.box_string(('Note: ' + self.p1_move), min_width=((self.width * 4) + 5), print_string=True) if self.settings['allow_moves']: if (self.settings['allow_mines'] and (self.p2_mines > 0)): action = Utils.num_input('What do you want to do?', 'Fire Missile', 'Move a Ship', 'Clear Misses', 'Clear Hits', 'Place a Mine') else: action = Utils.num_input('What do you want to do?', 'Fire Missile', 'Move a Ship', 'Clear Misses', 'Clear Hits') if (action == 0): error = '' while True: (y_pos, x_pos) = Utils.grid_pos_input(self.height, self.width, question=(error + '\nWhere do you want to fire?').strip()) if ((True in [((y_pos, x_pos) in self.p1_ships[x]['hits']) for x in range(len(self.p1_ships))]) or (self.p2_grid_2[y_pos][x_pos] > 26)): error = 'ERROR: You already guessed there!' continue if (self.p1_grid[y_pos][x_pos] > 26): error = 'ERROR: You already guessed there!' continue if (self.p1_grid[y_pos][x_pos] != 0): Utils.box_string('Direct Hit!', min_width=((self.width * 4) + 5), print_string=True) self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['health'] -= 1 self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['hits'].append((y_pos, x_pos)) if (self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['health'] == 0): Utils.box_string('You sunk a ship!', min_width=((self.width * 4) + 5), print_string=True) self.p2_grid_2[y_pos][x_pos] = 27 self.p1_grid[y_pos][x_pos] = 27 else: Utils.box_string('Miss!', min_width=((self.width * 4) + 5), print_string=True) self.p2_grid_2[y_pos][x_pos] = 28 self.p1_grid[y_pos][x_pos] = 28 break elif (action == 1): error = '' ship_num = (- 1) while True: ship_num = letters.index(Utils.string_input((error + '\nWhich ship do you want to move?').strip(), condition=('[A-%sa-%s]' % (letters[(len(self.p1_ships) - 1)], letters[(len(self.p1_ships) - 1)].lower()))).upper()) ship = self.p2_ships[ship_num] if (ship['health'] == 0): error = 'ERROR: That ship is sunk!' continue move_direction = Utils.num_input('Which direction do you want to move it?', 'Up', 'Down', 'Left', 'Right') error = '' try: if (move_direction < 2): true_dir = ((- 1) if (move_direction == 0) else 1) board = self.p2_grid if (ship['direction'] == 0): for i in range(ship['size']): for ship2 in self.p2_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == (ship['y_pos'] + true_dir)) and ((ship2['x_pos'] + k) == (ship['x_pos'] + i))): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == (ship['y_pos'] + true_dir)) and (ship2['x_pos'] == (ship['x_pos'] + i))): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] <= 26) or (board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] == 29)) and (board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] != (ship_num + 1))) or ((ship['y_pos'] + true_dir) < 0) or (ship['y_pos'] >= self.height)): error = 'ERROR: You cannot move your ship there!' else: for j in range(ship['size']): for ship2 in self.p2_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == ((ship['y_pos'] + j) + true_dir)) and ((ship2['x_pos'] + k) == ship['x_pos'])): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == ((ship['y_pos'] + j) + true_dir)) and (ship2['x_pos'] == ship['x_pos'])): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] <= 26) or (board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] == 29)) and (board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] != (ship_num + 1))) or (((ship['y_pos'] + j) + true_dir) < 0) or (ship['y_pos'] >= self.height)): error = 'ERROR: You cannot move your ship there!' if (error == ''): self.p2_ships[ship_num]['setup'] = False self.p2_ships[ship_num]['y_pos'] += true_dir self.p2_move = ('Player 2 just moved a ship ' + ('up!' if (move_direction == 0) else 'down!')) if (ship['direction'] == 0): for i in range((ship['size'] - 1)): board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] = 0 else: for j in range((ship['size'] - 1)): board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] = 0 break else: true_dir = ((- 1) if (move_direction == 2) else 1) board = self.p2_grid if (ship['direction'] == 0): for i in range(ship['size']): for ship2 in self.p2_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == ship['y_pos']) and ((ship2['x_pos'] + k) == ((ship['x_pos'] + i) + true_dir))): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == ship['y_pos']) and (ship2['x_pos'] == ((ship['x_pos'] + i) + true_dir))): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] <= 26) or (board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] == 29)) and (board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] != (ship_num + 1))) or (((ship['x_pos'] + i) + true_dir) < 0) or (ship['x_pos'] >= self.width)): error = 'ERROR: You cannot move your ship there!' else: for j in range(ship['size']): for ship2 in self.p2_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == (ship['y_pos'] + j)) and ((ship2['x_pos'] + k) == (ship['x_pos'] + true_dir))): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == (ship['y_pos'] + j)) and (ship2['x_pos'] == (ship['x_pos'] + true_dir))): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] <= 26) or (board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] == 29)) and (board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] != (ship_num + 1))) or ((ship['x_pos'] + true_dir) < 0) or (ship['x_pos'] >= self.width)): error = 'ERROR: You cannot move your ship there!' if (error == ''): self.p2_ships[ship_num]['setup'] = False self.p2_ships[ship_num]['x_pos'] += true_dir self.p2_move = ('Player 2 just moved a ship to the ' + ('left!' if (move_direction == 2) else 'right!')) if (ship['direction'] == 0): for i in range((ship['size'] - 1)): board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] = 0 else: for j in range((ship['size'] - 1)): board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] = 0 break except IndexError: error = 'ERROR: You cannot move your ship there! (INDEX ERROR)' for i in range(self.height): for j in range(self.width): if (board[i][j] == (ship_num + 1)): board[i][j] = 0 self.p2_ships[ship_num]['hits'] = [] self.update_board(1) elif (action == 2): for i in range(self.height): for j in range(self.width): if (self.p2_grid_2[i][j] == 28): self.p2_grid_2[i][j] = 0 return self.p2_turn() elif (action == 3): for i in range(self.height): for j in range(self.width): if (self.p2_grid_2[i][j] == 27): self.p2_grid_2[i][j] = 0 return self.p2_turn() else: error = '' while True: (y_pos, x_pos) = Utils.grid_pos_input(self.height, self.width, question=(error + '\nWhere do you want to place the mine?').strip()) if (self.p1_grid[y_pos][x_pos] == 29): error = 'ERROR: You already placed a mine there!' continue if (1 <= self.p1_grid[y_pos][x_pos] <= 26): ship_num = (self.p1_grid[y_pos][x_pos] - 1) self.p1_ships[ship_num]['health'] = 0 for i in range(self.height): for j in range(self.width): if (self.p1_grid[i][j] == (ship_num + 1)): self.p1_grid[i][j] = 27 Utils.box_string('You sunk a ship!', min_width=((self.width * 4) + 5), print_string=True) self.p1_grid[y_pos][x_pos] = 29 self.p2_grid_2[y_pos][x_pos] = 29 self.p2_mines -= 1 break else: error = '' while True: (y_pos, x_pos) = Utils.grid_pos_input(self.height, self.width, question=(error + '\nWhere do you want to fire?').strip()) if (self.p2_grid_2[y_pos][x_pos] != 0): error = 'ERROR: You already guessed there!' continue if (self.p1_grid[y_pos][x_pos] > 26): error = 'ERROR: You already guessed there!' continue if (self.p1_grid[y_pos][x_pos] != 0): Utils.box_string('Direct Hit!', min_width=((self.width * 4) + 5), print_string=True) self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['health'] -= 1 self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['hits'].append((y_pos, x_pos)) if (self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['health'] == 0): Utils.box_string('You sunk a ship!', min_width=((self.width * 4) + 5), print_string=True) self.p2_grid_2[y_pos][x_pos] = 27 self.p1_grid[y_pos][x_pos] = 27 else: Utils.box_string('Miss!', min_width=((self.width * 4) + 5), print_string=True) self.p2_grid_2[y_pos][x_pos] = 28 self.p1_grid[y_pos][x_pos] = 28 break else: Utils.box_string('CPU is deciding...', min_width=((self.width * 4) + 5), print_string=True) sleep(2) rng = Random() while True: pos = (rng.randrange(self.height), rng.randrange(self.width)) (y_pos, x_pos) = pos if (self.p1_grid[y_pos][x_pos] != 0): self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['health'] -= 1 self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['hits'].append((y_pos, x_pos)) if (self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['health'] == 0): self.cpu_data['p1_ships'][('%d_ships' % self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['size'])] -= 1 self.p2_grid_2[y_pos][x_pos] = 27 self.p1_grid[y_pos][x_pos] = 27 else: self.p2_grid_2[y_pos][x_pos] = 28 self.p1_grid[y_pos][x_pos] = 28 break Utils.box_string('Your turn is now over.', print_string=True) sleep(self.settings['player_timer']) return (sum([x['health'] for x in self.p1_ships]) == 0)
8,144,884,848,283,960,000
Execute a turn for Player 2. Handles input and output for the turn and updates both player's grids. Returns ------- bool True if game ends after the move, False otherwise
battleship.py
p2_turn
GamrCorps/STEMExpoBattleship
python
def p2_turn(self): "\n Execute a turn for Player 2.\n\n Handles input and output for the turn and updates both player's grids.\n\n Returns\n -------\n bool\n True if game ends after the move, False otherwise\n " print(('\n' * PAD_AMOUNT)) Utils.box_string("Player 2's Turn", min_width=((self.width * 4) + 5), print_string=True) self.p2_move = if (not self.p2_cpu): Utils.box_string('Player 1, please look away.', min_width=((self.width * 4) + 5), print_string=True) sleep(self.settings['player_timer']) self.print_board(1) if (self.p1_move != ): Utils.box_string(('Note: ' + self.p1_move), min_width=((self.width * 4) + 5), print_string=True) if self.settings['allow_moves']: if (self.settings['allow_mines'] and (self.p2_mines > 0)): action = Utils.num_input('What do you want to do?', 'Fire Missile', 'Move a Ship', 'Clear Misses', 'Clear Hits', 'Place a Mine') else: action = Utils.num_input('What do you want to do?', 'Fire Missile', 'Move a Ship', 'Clear Misses', 'Clear Hits') if (action == 0): error = while True: (y_pos, x_pos) = Utils.grid_pos_input(self.height, self.width, question=(error + '\nWhere do you want to fire?').strip()) if ((True in [((y_pos, x_pos) in self.p1_ships[x]['hits']) for x in range(len(self.p1_ships))]) or (self.p2_grid_2[y_pos][x_pos] > 26)): error = 'ERROR: You already guessed there!' continue if (self.p1_grid[y_pos][x_pos] > 26): error = 'ERROR: You already guessed there!' continue if (self.p1_grid[y_pos][x_pos] != 0): Utils.box_string('Direct Hit!', min_width=((self.width * 4) + 5), print_string=True) self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['health'] -= 1 self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['hits'].append((y_pos, x_pos)) if (self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['health'] == 0): Utils.box_string('You sunk a ship!', min_width=((self.width * 4) + 5), print_string=True) self.p2_grid_2[y_pos][x_pos] = 27 self.p1_grid[y_pos][x_pos] = 27 else: Utils.box_string('Miss!', min_width=((self.width * 4) + 5), print_string=True) self.p2_grid_2[y_pos][x_pos] = 28 self.p1_grid[y_pos][x_pos] = 28 break elif (action == 1): error = ship_num = (- 1) while True: ship_num = letters.index(Utils.string_input((error + '\nWhich ship do you want to move?').strip(), condition=('[A-%sa-%s]' % (letters[(len(self.p1_ships) - 1)], letters[(len(self.p1_ships) - 1)].lower()))).upper()) ship = self.p2_ships[ship_num] if (ship['health'] == 0): error = 'ERROR: That ship is sunk!' continue move_direction = Utils.num_input('Which direction do you want to move it?', 'Up', 'Down', 'Left', 'Right') error = try: if (move_direction < 2): true_dir = ((- 1) if (move_direction == 0) else 1) board = self.p2_grid if (ship['direction'] == 0): for i in range(ship['size']): for ship2 in self.p2_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == (ship['y_pos'] + true_dir)) and ((ship2['x_pos'] + k) == (ship['x_pos'] + i))): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == (ship['y_pos'] + true_dir)) and (ship2['x_pos'] == (ship['x_pos'] + i))): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] <= 26) or (board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] == 29)) and (board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] != (ship_num + 1))) or ((ship['y_pos'] + true_dir) < 0) or (ship['y_pos'] >= self.height)): error = 'ERROR: You cannot move your ship there!' else: for j in range(ship['size']): for ship2 in self.p2_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == ((ship['y_pos'] + j) + true_dir)) and ((ship2['x_pos'] + k) == ship['x_pos'])): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == ((ship['y_pos'] + j) + true_dir)) and (ship2['x_pos'] == ship['x_pos'])): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] <= 26) or (board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] == 29)) and (board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] != (ship_num + 1))) or (((ship['y_pos'] + j) + true_dir) < 0) or (ship['y_pos'] >= self.height)): error = 'ERROR: You cannot move your ship there!' if (error == ): self.p2_ships[ship_num]['setup'] = False self.p2_ships[ship_num]['y_pos'] += true_dir self.p2_move = ('Player 2 just moved a ship ' + ('up!' if (move_direction == 0) else 'down!')) if (ship['direction'] == 0): for i in range((ship['size'] - 1)): board[(ship['y_pos'] + true_dir)][(ship['x_pos'] + i)] = 0 else: for j in range((ship['size'] - 1)): board[((ship['y_pos'] + j) + true_dir)][ship['x_pos']] = 0 break else: true_dir = ((- 1) if (move_direction == 2) else 1) board = self.p2_grid if (ship['direction'] == 0): for i in range(ship['size']): for ship2 in self.p2_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == ship['y_pos']) and ((ship2['x_pos'] + k) == ((ship['x_pos'] + i) + true_dir))): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == ship['y_pos']) and (ship2['x_pos'] == ((ship['x_pos'] + i) + true_dir))): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] <= 26) or (board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] == 29)) and (board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] != (ship_num + 1))) or (((ship['x_pos'] + i) + true_dir) < 0) or (ship['x_pos'] >= self.width)): error = 'ERROR: You cannot move your ship there!' else: for j in range(ship['size']): for ship2 in self.p2_ships: if (ship2['direction'] == 0): for k in range(ship2['size']): if ((ship2['num'] != ship_num) and (ship2['y_pos'] == (ship['y_pos'] + j)) and ((ship2['x_pos'] + k) == (ship['x_pos'] + true_dir))): error = 'ERROR: You cannot move your ship there!' continue else: for l in range(ship2['size']): if ((ship2['num'] != ship_num) and ((ship2['y_pos'] + l) == (ship['y_pos'] + j)) and (ship2['x_pos'] == (ship['x_pos'] + true_dir))): error = 'ERROR: You cannot move your ship there!' continue if ((((1 <= board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] <= 26) or (board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] == 29)) and (board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] != (ship_num + 1))) or ((ship['x_pos'] + true_dir) < 0) or (ship['x_pos'] >= self.width)): error = 'ERROR: You cannot move your ship there!' if (error == ): self.p2_ships[ship_num]['setup'] = False self.p2_ships[ship_num]['x_pos'] += true_dir self.p2_move = ('Player 2 just moved a ship to the ' + ('left!' if (move_direction == 2) else 'right!')) if (ship['direction'] == 0): for i in range((ship['size'] - 1)): board[ship['y_pos']][((ship['x_pos'] + i) + true_dir)] = 0 else: for j in range((ship['size'] - 1)): board[(ship['y_pos'] + j)][(ship['x_pos'] + true_dir)] = 0 break except IndexError: error = 'ERROR: You cannot move your ship there! (INDEX ERROR)' for i in range(self.height): for j in range(self.width): if (board[i][j] == (ship_num + 1)): board[i][j] = 0 self.p2_ships[ship_num]['hits'] = [] self.update_board(1) elif (action == 2): for i in range(self.height): for j in range(self.width): if (self.p2_grid_2[i][j] == 28): self.p2_grid_2[i][j] = 0 return self.p2_turn() elif (action == 3): for i in range(self.height): for j in range(self.width): if (self.p2_grid_2[i][j] == 27): self.p2_grid_2[i][j] = 0 return self.p2_turn() else: error = while True: (y_pos, x_pos) = Utils.grid_pos_input(self.height, self.width, question=(error + '\nWhere do you want to place the mine?').strip()) if (self.p1_grid[y_pos][x_pos] == 29): error = 'ERROR: You already placed a mine there!' continue if (1 <= self.p1_grid[y_pos][x_pos] <= 26): ship_num = (self.p1_grid[y_pos][x_pos] - 1) self.p1_ships[ship_num]['health'] = 0 for i in range(self.height): for j in range(self.width): if (self.p1_grid[i][j] == (ship_num + 1)): self.p1_grid[i][j] = 27 Utils.box_string('You sunk a ship!', min_width=((self.width * 4) + 5), print_string=True) self.p1_grid[y_pos][x_pos] = 29 self.p2_grid_2[y_pos][x_pos] = 29 self.p2_mines -= 1 break else: error = while True: (y_pos, x_pos) = Utils.grid_pos_input(self.height, self.width, question=(error + '\nWhere do you want to fire?').strip()) if (self.p2_grid_2[y_pos][x_pos] != 0): error = 'ERROR: You already guessed there!' continue if (self.p1_grid[y_pos][x_pos] > 26): error = 'ERROR: You already guessed there!' continue if (self.p1_grid[y_pos][x_pos] != 0): Utils.box_string('Direct Hit!', min_width=((self.width * 4) + 5), print_string=True) self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['health'] -= 1 self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['hits'].append((y_pos, x_pos)) if (self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['health'] == 0): Utils.box_string('You sunk a ship!', min_width=((self.width * 4) + 5), print_string=True) self.p2_grid_2[y_pos][x_pos] = 27 self.p1_grid[y_pos][x_pos] = 27 else: Utils.box_string('Miss!', min_width=((self.width * 4) + 5), print_string=True) self.p2_grid_2[y_pos][x_pos] = 28 self.p1_grid[y_pos][x_pos] = 28 break else: Utils.box_string('CPU is deciding...', min_width=((self.width * 4) + 5), print_string=True) sleep(2) rng = Random() while True: pos = (rng.randrange(self.height), rng.randrange(self.width)) (y_pos, x_pos) = pos if (self.p1_grid[y_pos][x_pos] != 0): self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['health'] -= 1 self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['hits'].append((y_pos, x_pos)) if (self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['health'] == 0): self.cpu_data['p1_ships'][('%d_ships' % self.p1_ships[(self.p1_grid[y_pos][x_pos] - 1)]['size'])] -= 1 self.p2_grid_2[y_pos][x_pos] = 27 self.p1_grid[y_pos][x_pos] = 27 else: self.p2_grid_2[y_pos][x_pos] = 28 self.p1_grid[y_pos][x_pos] = 28 break Utils.box_string('Your turn is now over.', print_string=True) sleep(self.settings['player_timer']) return (sum([x['health'] for x in self.p1_ships]) == 0)
def start_game(self): "\n Start a new game.\n\n Starts a game with the settings provided in the constructor.\n All game code is contained here, with relevant helper methods also called here.\n Every game has two stages: Setup and Play.\n\n Returns\n -------\n int\n Winning player's number. Zero-indexed.\n " print(('\n' * PAD_AMOUNT)) Utils.box_string('Setup Phase', min_width=((self.width * 4) + 5), print_string=True) Utils.box_string("Player 1's Turn", min_width=((self.width * 4) + 5), print_string=True) if (not self.p2_cpu): Utils.box_string('Player 2, please look away.', min_width=((self.width * 4) + 5), print_string=True) sleep(self.settings['player_timer']) Utils.box_string('Player 1 Setup', min_width=((self.width * 4) + 5), print_string=True) p1_ship_count = 0 for i in range(5): p1_ship_count = self.setup_ships((i + 1), 0, p1_ship_count) if self.p2_cpu: self.cpu_data['p1_ships'] = {} for size in range(1, 6): self.cpu_data['p1_ships'][('%d_ships' % size)] = self.settings[('%d_ships' % size)] p2_ship_count = 0 rng = Random() for size in range(1, 6): count = 0 for i in range(self.settings[('%d_ships' % size)]): while True: pos = (rng.randrange(self.height), rng.randrange(self.width)) direction = rng.randrange(2) error = self.setup_ship(pos, direction, 1, (p2_ship_count + count), size) if (error is None): print(((((((('Placed ship ' + str((p2_ship_count + count))) + ' at ') + str(pos)) + ' with direction ') + str(direction)) + ' with size ') + str(size))) break count += 1 p2_ship_count += count else: print(('\n' * PAD_AMOUNT)) Utils.box_string("Player 2's Turn", min_width=((self.width * 4) + 5), print_string=True) Utils.box_string('Player 1, please look away.', min_width=((self.width * 4) + 5), print_string=True) sleep(self.settings['player_timer']) Utils.box_string('Player 2 Setup', min_width=((self.width * 4) + 5), print_string=True) p2_ship_count = 0 for i in range(5): p2_ship_count = self.setup_ships((i + 1), 1, p2_ship_count) self.update_board(0) self.update_board(1) Utils.box_string('Play Phase', min_width=((self.width * 4) + 5), print_string=True) winner = None while True: if ((self.settings['mine_turns'] is not None) and ((self.turn % (self.settings['mine_turns'] * 2)) == 0)): self.p1_mines += 1 self.p2_mines += 1 if ((self.turn % 2) == 0): if self.p1_turn(): winner = 1 break elif self.p2_turn(): winner = 2 break self.turn += 1 Utils.box_string(('Player %d won!' % winner), min_width=((self.width * 4) + 5), print_string=True) return winner
-4,259,161,377,121,769,000
Start a new game. Starts a game with the settings provided in the constructor. All game code is contained here, with relevant helper methods also called here. Every game has two stages: Setup and Play. Returns ------- int Winning player's number. Zero-indexed.
battleship.py
start_game
GamrCorps/STEMExpoBattleship
python
def start_game(self): "\n Start a new game.\n\n Starts a game with the settings provided in the constructor.\n All game code is contained here, with relevant helper methods also called here.\n Every game has two stages: Setup and Play.\n\n Returns\n -------\n int\n Winning player's number. Zero-indexed.\n " print(('\n' * PAD_AMOUNT)) Utils.box_string('Setup Phase', min_width=((self.width * 4) + 5), print_string=True) Utils.box_string("Player 1's Turn", min_width=((self.width * 4) + 5), print_string=True) if (not self.p2_cpu): Utils.box_string('Player 2, please look away.', min_width=((self.width * 4) + 5), print_string=True) sleep(self.settings['player_timer']) Utils.box_string('Player 1 Setup', min_width=((self.width * 4) + 5), print_string=True) p1_ship_count = 0 for i in range(5): p1_ship_count = self.setup_ships((i + 1), 0, p1_ship_count) if self.p2_cpu: self.cpu_data['p1_ships'] = {} for size in range(1, 6): self.cpu_data['p1_ships'][('%d_ships' % size)] = self.settings[('%d_ships' % size)] p2_ship_count = 0 rng = Random() for size in range(1, 6): count = 0 for i in range(self.settings[('%d_ships' % size)]): while True: pos = (rng.randrange(self.height), rng.randrange(self.width)) direction = rng.randrange(2) error = self.setup_ship(pos, direction, 1, (p2_ship_count + count), size) if (error is None): print(((((((('Placed ship ' + str((p2_ship_count + count))) + ' at ') + str(pos)) + ' with direction ') + str(direction)) + ' with size ') + str(size))) break count += 1 p2_ship_count += count else: print(('\n' * PAD_AMOUNT)) Utils.box_string("Player 2's Turn", min_width=((self.width * 4) + 5), print_string=True) Utils.box_string('Player 1, please look away.', min_width=((self.width * 4) + 5), print_string=True) sleep(self.settings['player_timer']) Utils.box_string('Player 2 Setup', min_width=((self.width * 4) + 5), print_string=True) p2_ship_count = 0 for i in range(5): p2_ship_count = self.setup_ships((i + 1), 1, p2_ship_count) self.update_board(0) self.update_board(1) Utils.box_string('Play Phase', min_width=((self.width * 4) + 5), print_string=True) winner = None while True: if ((self.settings['mine_turns'] is not None) and ((self.turn % (self.settings['mine_turns'] * 2)) == 0)): self.p1_mines += 1 self.p2_mines += 1 if ((self.turn % 2) == 0): if self.p1_turn(): winner = 1 break elif self.p2_turn(): winner = 2 break self.turn += 1 Utils.box_string(('Player %d won!' % winner), min_width=((self.width * 4) + 5), print_string=True) return winner
def recipe_url(id): 'Construct URL for a single recipe based on its ID' return reverse('recipe:recipe-detail', args=[id])
-6,700,030,570,248,506,000
Construct URL for a single recipe based on its ID
app/recipe/tests/test_recipe_api.py
recipe_url
jamie-chapman/django-exercise-recipe-app
python
def recipe_url(id): return reverse('recipe:recipe-detail', args=[id])
def create_sample_recipe(**params): 'Helper function to create a user' return Recipe.objects.create(**params)
1,824,730,974,099,778,800
Helper function to create a user
app/recipe/tests/test_recipe_api.py
create_sample_recipe
jamie-chapman/django-exercise-recipe-app
python
def create_sample_recipe(**params): return Recipe.objects.create(**params)
def test_create_recipe_with_ingredients(self): 'Test creating a recipe including ingredients' payload = {'name': 'Vegan Roast Dinner', 'description': 'Roasted potatoes and mushroom wellington with vegetables and gravy.', 'ingredients': [{'name': 'carrots'}, {'name': 'potatoes'}, {'name': 'mushrooms'}]} response = self.client.post(RECIPE_URL, payload, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(payload['name'], Recipe.objects.get(id=response.data['id']).name) self.assertEquals(len(response.data['ingredients']), len(payload['ingredients']))
-6,914,610,480,633,387,000
Test creating a recipe including ingredients
app/recipe/tests/test_recipe_api.py
test_create_recipe_with_ingredients
jamie-chapman/django-exercise-recipe-app
python
def test_create_recipe_with_ingredients(self): payload = {'name': 'Vegan Roast Dinner', 'description': 'Roasted potatoes and mushroom wellington with vegetables and gravy.', 'ingredients': [{'name': 'carrots'}, {'name': 'potatoes'}, {'name': 'mushrooms'}]} response = self.client.post(RECIPE_URL, payload, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(payload['name'], Recipe.objects.get(id=response.data['id']).name) self.assertEquals(len(response.data['ingredients']), len(payload['ingredients']))
def test_get_recipes(self): 'Test retrieving a recipe' create_sample_recipe(name='Roast Dinner', description='Roasted potatoes and chicken with vegetables and gravy.') create_sample_recipe(name='Beans on Toast', description='Just the best.') response = self.client.get(RECIPE_URL) recipes = Recipe.objects.all().order_by('-name') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), len(recipes))
7,578,667,835,455,517,000
Test retrieving a recipe
app/recipe/tests/test_recipe_api.py
test_get_recipes
jamie-chapman/django-exercise-recipe-app
python
def test_get_recipes(self): create_sample_recipe(name='Roast Dinner', description='Roasted potatoes and chicken with vegetables and gravy.') create_sample_recipe(name='Beans on Toast', description='Just the best.') response = self.client.get(RECIPE_URL) recipes = Recipe.objects.all().order_by('-name') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), len(recipes))
def test_get_recipe(self): 'Test retrieving a single recipe using name as filter' test_recipe_name = 'Beans on Toast' create_sample_recipe(name='Roast Dinner', description='Roasted potatoes and chicken with vegetables and gravy.') create_sample_recipe(name=test_recipe_name, description='Just the best recipe.') response = self.client.get(RECIPE_URL, {'name': test_recipe_name}) recipes = Recipe.objects.all().order_by('-name') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertNotEqual(len(response.data), len(recipes)) self.assertEqual(response.data[0]['name'], test_recipe_name)
-466,724,916,212,570,050
Test retrieving a single recipe using name as filter
app/recipe/tests/test_recipe_api.py
test_get_recipe
jamie-chapman/django-exercise-recipe-app
python
def test_get_recipe(self): test_recipe_name = 'Beans on Toast' create_sample_recipe(name='Roast Dinner', description='Roasted potatoes and chicken with vegetables and gravy.') create_sample_recipe(name=test_recipe_name, description='Just the best recipe.') response = self.client.get(RECIPE_URL, {'name': test_recipe_name}) recipes = Recipe.objects.all().order_by('-name') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertNotEqual(len(response.data), len(recipes)) self.assertEqual(response.data[0]['name'], test_recipe_name)
def test_update_recipe(self): 'Test updating a recipe' self.recipe = create_sample_recipe(name='Roast Dinner', description='Roasted potatoes and chicken with vegetables and gravy.') payload = {'name': 'Vegan Roast Dinner', 'description': 'Roasted potatoes and mushroom wellington with vegetables and gravy.'} response = self.client.patch(recipe_url(self.recipe.id), payload, format='json') self.recipe.refresh_from_db() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(self.recipe.name, response.data['name']) self.assertEqual(self.recipe.description, response.data['description'])
-701,737,544,240,572,800
Test updating a recipe
app/recipe/tests/test_recipe_api.py
test_update_recipe
jamie-chapman/django-exercise-recipe-app
python
def test_update_recipe(self): self.recipe = create_sample_recipe(name='Roast Dinner', description='Roasted potatoes and chicken with vegetables and gravy.') payload = {'name': 'Vegan Roast Dinner', 'description': 'Roasted potatoes and mushroom wellington with vegetables and gravy.'} response = self.client.patch(recipe_url(self.recipe.id), payload, format='json') self.recipe.refresh_from_db() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(self.recipe.name, response.data['name']) self.assertEqual(self.recipe.description, response.data['description'])
def test_delete_recipe(self): 'Test deleting a recipe' self.recipe = create_sample_recipe(name='Carrot Cake', description='Sponge cake with hella carrots.') response = self.client.delete(recipe_url(self.recipe.id), format='json') self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertFalse(Recipe.objects.all())
3,177,215,768,312,454,700
Test deleting a recipe
app/recipe/tests/test_recipe_api.py
test_delete_recipe
jamie-chapman/django-exercise-recipe-app
python
def test_delete_recipe(self): self.recipe = create_sample_recipe(name='Carrot Cake', description='Sponge cake with hella carrots.') response = self.client.delete(recipe_url(self.recipe.id), format='json') self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertFalse(Recipe.objects.all())
def test_get_recipes_with_ingredients(self): 'Test retrieving a recipe including ingredients' self.recipe = create_sample_recipe(name='Carrot Cake', description='Sponge cake with hella carrots.') Ingredient.objects.create(name='Carrots', recipe=self.recipe) Ingredient.objects.create(name='Icing Sugar', recipe=self.recipe) response = self.client.get(RECIPE_URL) ingredients = Ingredient.objects.all() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEquals(len(response.data[0]['ingredients']), len(ingredients))
8,490,206,641,993,368,000
Test retrieving a recipe including ingredients
app/recipe/tests/test_recipe_api.py
test_get_recipes_with_ingredients
jamie-chapman/django-exercise-recipe-app
python
def test_get_recipes_with_ingredients(self): self.recipe = create_sample_recipe(name='Carrot Cake', description='Sponge cake with hella carrots.') Ingredient.objects.create(name='Carrots', recipe=self.recipe) Ingredient.objects.create(name='Icing Sugar', recipe=self.recipe) response = self.client.get(RECIPE_URL) ingredients = Ingredient.objects.all() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEquals(len(response.data[0]['ingredients']), len(ingredients))
def test_update_recipe_ingredients(self): 'Test updating a recipe with ingredients included' self.recipe = create_sample_recipe(name='Roast Dinner', description='Roasted potatoes and chicken with vegetables and gravy.') payload = {'name': 'Vegan Roast Dinner', 'description': 'Roasted potatoes and mushroom wellington with vegetables and gravy.', 'ingredients': [{'name': 'carrots'}, {'name': 'potatoes'}, {'name': 'mushrooms'}]} response = self.client.patch(recipe_url(self.recipe.id), payload, format='json') self.recipe.refresh_from_db() ingredients = Ingredient.objects.all() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(ingredients), len(payload['ingredients'])) self.assertEqual(ingredients[0].recipe.name, payload['name'])
-4,634,634,642,258,830,000
Test updating a recipe with ingredients included
app/recipe/tests/test_recipe_api.py
test_update_recipe_ingredients
jamie-chapman/django-exercise-recipe-app
python
def test_update_recipe_ingredients(self): self.recipe = create_sample_recipe(name='Roast Dinner', description='Roasted potatoes and chicken with vegetables and gravy.') payload = {'name': 'Vegan Roast Dinner', 'description': 'Roasted potatoes and mushroom wellington with vegetables and gravy.', 'ingredients': [{'name': 'carrots'}, {'name': 'potatoes'}, {'name': 'mushrooms'}]} response = self.client.patch(recipe_url(self.recipe.id), payload, format='json') self.recipe.refresh_from_db() ingredients = Ingredient.objects.all() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(ingredients), len(payload['ingredients'])) self.assertEqual(ingredients[0].recipe.name, payload['name'])
def test_delete_recipe_with_ingredients(self): 'Test deleting a recipe with ingredients included' self.recipe = create_sample_recipe(name='Carrot Cake', description='Sponge cake with hella carrots.') Ingredient.objects.create(name='Carrots', recipe=self.recipe) Ingredient.objects.create(name='Icing Sugar', recipe=self.recipe) response = self.client.delete(recipe_url(self.recipe.id), format='json') ingredients = Ingredient.objects.all() self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertFalse(Recipe.objects.all()) self.assertFalse(len(ingredients), 0)
8,174,779,375,099,401,000
Test deleting a recipe with ingredients included
app/recipe/tests/test_recipe_api.py
test_delete_recipe_with_ingredients
jamie-chapman/django-exercise-recipe-app
python
def test_delete_recipe_with_ingredients(self): self.recipe = create_sample_recipe(name='Carrot Cake', description='Sponge cake with hella carrots.') Ingredient.objects.create(name='Carrots', recipe=self.recipe) Ingredient.objects.create(name='Icing Sugar', recipe=self.recipe) response = self.client.delete(recipe_url(self.recipe.id), format='json') ingredients = Ingredient.objects.all() self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertFalse(Recipe.objects.all()) self.assertFalse(len(ingredients), 0)
def get_application_gateway(application_gateway_name: Optional[str]=None, resource_group_name: Optional[str]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableGetApplicationGatewayResult: '\n Application gateway resource.\n\n\n :param str application_gateway_name: The name of the application gateway.\n :param str resource_group_name: The name of the resource group.\n ' __args__ = dict() __args__['applicationGatewayName'] = application_gateway_name __args__['resourceGroupName'] = resource_group_name if (opts is None): opts = pulumi.InvokeOptions() if (opts.version is None): opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-nextgen:network/v20200701:getApplicationGateway', __args__, opts=opts, typ=GetApplicationGatewayResult).value return AwaitableGetApplicationGatewayResult(authentication_certificates=__ret__.authentication_certificates, autoscale_configuration=__ret__.autoscale_configuration, backend_address_pools=__ret__.backend_address_pools, backend_http_settings_collection=__ret__.backend_http_settings_collection, custom_error_configurations=__ret__.custom_error_configurations, enable_fips=__ret__.enable_fips, enable_http2=__ret__.enable_http2, etag=__ret__.etag, firewall_policy=__ret__.firewall_policy, force_firewall_policy_association=__ret__.force_firewall_policy_association, frontend_ip_configurations=__ret__.frontend_ip_configurations, frontend_ports=__ret__.frontend_ports, gateway_ip_configurations=__ret__.gateway_ip_configurations, http_listeners=__ret__.http_listeners, id=__ret__.id, identity=__ret__.identity, location=__ret__.location, name=__ret__.name, operational_state=__ret__.operational_state, private_endpoint_connections=__ret__.private_endpoint_connections, private_link_configurations=__ret__.private_link_configurations, probes=__ret__.probes, provisioning_state=__ret__.provisioning_state, redirect_configurations=__ret__.redirect_configurations, request_routing_rules=__ret__.request_routing_rules, resource_guid=__ret__.resource_guid, rewrite_rule_sets=__ret__.rewrite_rule_sets, sku=__ret__.sku, ssl_certificates=__ret__.ssl_certificates, ssl_policy=__ret__.ssl_policy, ssl_profiles=__ret__.ssl_profiles, tags=__ret__.tags, trusted_client_certificates=__ret__.trusted_client_certificates, trusted_root_certificates=__ret__.trusted_root_certificates, type=__ret__.type, url_path_maps=__ret__.url_path_maps, web_application_firewall_configuration=__ret__.web_application_firewall_configuration, zones=__ret__.zones)
-5,472,037,904,466,801,000
Application gateway resource. :param str application_gateway_name: The name of the application gateway. :param str resource_group_name: The name of the resource group.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
get_application_gateway
pulumi/pulumi-azure-nextgen
python
def get_application_gateway(application_gateway_name: Optional[str]=None, resource_group_name: Optional[str]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableGetApplicationGatewayResult: '\n Application gateway resource.\n\n\n :param str application_gateway_name: The name of the application gateway.\n :param str resource_group_name: The name of the resource group.\n ' __args__ = dict() __args__['applicationGatewayName'] = application_gateway_name __args__['resourceGroupName'] = resource_group_name if (opts is None): opts = pulumi.InvokeOptions() if (opts.version is None): opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-nextgen:network/v20200701:getApplicationGateway', __args__, opts=opts, typ=GetApplicationGatewayResult).value return AwaitableGetApplicationGatewayResult(authentication_certificates=__ret__.authentication_certificates, autoscale_configuration=__ret__.autoscale_configuration, backend_address_pools=__ret__.backend_address_pools, backend_http_settings_collection=__ret__.backend_http_settings_collection, custom_error_configurations=__ret__.custom_error_configurations, enable_fips=__ret__.enable_fips, enable_http2=__ret__.enable_http2, etag=__ret__.etag, firewall_policy=__ret__.firewall_policy, force_firewall_policy_association=__ret__.force_firewall_policy_association, frontend_ip_configurations=__ret__.frontend_ip_configurations, frontend_ports=__ret__.frontend_ports, gateway_ip_configurations=__ret__.gateway_ip_configurations, http_listeners=__ret__.http_listeners, id=__ret__.id, identity=__ret__.identity, location=__ret__.location, name=__ret__.name, operational_state=__ret__.operational_state, private_endpoint_connections=__ret__.private_endpoint_connections, private_link_configurations=__ret__.private_link_configurations, probes=__ret__.probes, provisioning_state=__ret__.provisioning_state, redirect_configurations=__ret__.redirect_configurations, request_routing_rules=__ret__.request_routing_rules, resource_guid=__ret__.resource_guid, rewrite_rule_sets=__ret__.rewrite_rule_sets, sku=__ret__.sku, ssl_certificates=__ret__.ssl_certificates, ssl_policy=__ret__.ssl_policy, ssl_profiles=__ret__.ssl_profiles, tags=__ret__.tags, trusted_client_certificates=__ret__.trusted_client_certificates, trusted_root_certificates=__ret__.trusted_root_certificates, type=__ret__.type, url_path_maps=__ret__.url_path_maps, web_application_firewall_configuration=__ret__.web_application_firewall_configuration, zones=__ret__.zones)
@property @pulumi.getter(name='authenticationCertificates') def authentication_certificates(self) -> Optional[Sequence['outputs.ApplicationGatewayAuthenticationCertificateResponse']]: '\n Authentication certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).\n ' return pulumi.get(self, 'authentication_certificates')
-4,062,952,323,035,735,000
Authentication certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
authentication_certificates
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='authenticationCertificates') def authentication_certificates(self) -> Optional[Sequence['outputs.ApplicationGatewayAuthenticationCertificateResponse']]: '\n \n ' return pulumi.get(self, 'authentication_certificates')
@property @pulumi.getter(name='autoscaleConfiguration') def autoscale_configuration(self) -> Optional['outputs.ApplicationGatewayAutoscaleConfigurationResponse']: '\n Autoscale Configuration.\n ' return pulumi.get(self, 'autoscale_configuration')
8,419,954,442,239,702,000
Autoscale Configuration.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
autoscale_configuration
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='autoscaleConfiguration') def autoscale_configuration(self) -> Optional['outputs.ApplicationGatewayAutoscaleConfigurationResponse']: '\n \n ' return pulumi.get(self, 'autoscale_configuration')
@property @pulumi.getter(name='backendAddressPools') def backend_address_pools(self) -> Optional[Sequence['outputs.ApplicationGatewayBackendAddressPoolResponse']]: '\n Backend address pool of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).\n ' return pulumi.get(self, 'backend_address_pools')
6,395,664,438,994,776,000
Backend address pool of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
backend_address_pools
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='backendAddressPools') def backend_address_pools(self) -> Optional[Sequence['outputs.ApplicationGatewayBackendAddressPoolResponse']]: '\n \n ' return pulumi.get(self, 'backend_address_pools')
@property @pulumi.getter(name='backendHttpSettingsCollection') def backend_http_settings_collection(self) -> Optional[Sequence['outputs.ApplicationGatewayBackendHttpSettingsResponse']]: '\n Backend http settings of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).\n ' return pulumi.get(self, 'backend_http_settings_collection')
7,237,127,856,813,792,000
Backend http settings of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
backend_http_settings_collection
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='backendHttpSettingsCollection') def backend_http_settings_collection(self) -> Optional[Sequence['outputs.ApplicationGatewayBackendHttpSettingsResponse']]: '\n \n ' return pulumi.get(self, 'backend_http_settings_collection')
@property @pulumi.getter(name='customErrorConfigurations') def custom_error_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayCustomErrorResponse']]: '\n Custom error configurations of the application gateway resource.\n ' return pulumi.get(self, 'custom_error_configurations')
-7,995,323,122,653,976,000
Custom error configurations of the application gateway resource.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
custom_error_configurations
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='customErrorConfigurations') def custom_error_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayCustomErrorResponse']]: '\n \n ' return pulumi.get(self, 'custom_error_configurations')
@property @pulumi.getter(name='enableFips') def enable_fips(self) -> Optional[bool]: '\n Whether FIPS is enabled on the application gateway resource.\n ' return pulumi.get(self, 'enable_fips')
3,620,545,089,823,313,000
Whether FIPS is enabled on the application gateway resource.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
enable_fips
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='enableFips') def enable_fips(self) -> Optional[bool]: '\n \n ' return pulumi.get(self, 'enable_fips')
@property @pulumi.getter(name='enableHttp2') def enable_http2(self) -> Optional[bool]: '\n Whether HTTP2 is enabled on the application gateway resource.\n ' return pulumi.get(self, 'enable_http2')
-2,189,973,886,906,387,700
Whether HTTP2 is enabled on the application gateway resource.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
enable_http2
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='enableHttp2') def enable_http2(self) -> Optional[bool]: '\n \n ' return pulumi.get(self, 'enable_http2')
@property @pulumi.getter def etag(self) -> str: '\n A unique read-only string that changes whenever the resource is updated.\n ' return pulumi.get(self, 'etag')
-4,757,010,955,465,940,000
A unique read-only string that changes whenever the resource is updated.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
etag
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter def etag(self) -> str: '\n \n ' return pulumi.get(self, 'etag')
@property @pulumi.getter(name='firewallPolicy') def firewall_policy(self) -> Optional['outputs.SubResourceResponse']: '\n Reference to the FirewallPolicy resource.\n ' return pulumi.get(self, 'firewall_policy')
-2,060,557,808,174,617,600
Reference to the FirewallPolicy resource.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
firewall_policy
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='firewallPolicy') def firewall_policy(self) -> Optional['outputs.SubResourceResponse']: '\n \n ' return pulumi.get(self, 'firewall_policy')
@property @pulumi.getter(name='forceFirewallPolicyAssociation') def force_firewall_policy_association(self) -> Optional[bool]: '\n If true, associates a firewall policy with an application gateway regardless whether the policy differs from the WAF Config.\n ' return pulumi.get(self, 'force_firewall_policy_association')
-6,839,923,985,103,754,000
If true, associates a firewall policy with an application gateway regardless whether the policy differs from the WAF Config.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
force_firewall_policy_association
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='forceFirewallPolicyAssociation') def force_firewall_policy_association(self) -> Optional[bool]: '\n \n ' return pulumi.get(self, 'force_firewall_policy_association')
@property @pulumi.getter(name='frontendIPConfigurations') def frontend_ip_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayFrontendIPConfigurationResponse']]: '\n Frontend IP addresses of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).\n ' return pulumi.get(self, 'frontend_ip_configurations')
-4,878,596,659,314,971,000
Frontend IP addresses of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
frontend_ip_configurations
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='frontendIPConfigurations') def frontend_ip_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayFrontendIPConfigurationResponse']]: '\n \n ' return pulumi.get(self, 'frontend_ip_configurations')
@property @pulumi.getter(name='frontendPorts') def frontend_ports(self) -> Optional[Sequence['outputs.ApplicationGatewayFrontendPortResponse']]: '\n Frontend ports of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).\n ' return pulumi.get(self, 'frontend_ports')
590,217,953,051,457,900
Frontend ports of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
frontend_ports
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='frontendPorts') def frontend_ports(self) -> Optional[Sequence['outputs.ApplicationGatewayFrontendPortResponse']]: '\n \n ' return pulumi.get(self, 'frontend_ports')
@property @pulumi.getter(name='gatewayIPConfigurations') def gateway_ip_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayIPConfigurationResponse']]: '\n Subnets of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).\n ' return pulumi.get(self, 'gateway_ip_configurations')
6,526,835,487,889,182,000
Subnets of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
gateway_ip_configurations
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='gatewayIPConfigurations') def gateway_ip_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayIPConfigurationResponse']]: '\n \n ' return pulumi.get(self, 'gateway_ip_configurations')
@property @pulumi.getter(name='httpListeners') def http_listeners(self) -> Optional[Sequence['outputs.ApplicationGatewayHttpListenerResponse']]: '\n Http listeners of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).\n ' return pulumi.get(self, 'http_listeners')
5,704,017,451,908,833,000
Http listeners of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
http_listeners
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='httpListeners') def http_listeners(self) -> Optional[Sequence['outputs.ApplicationGatewayHttpListenerResponse']]: '\n \n ' return pulumi.get(self, 'http_listeners')
@property @pulumi.getter def id(self) -> Optional[str]: '\n Resource ID.\n ' return pulumi.get(self, 'id')
6,887,155,523,158,811,000
Resource ID.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
id
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter def id(self) -> Optional[str]: '\n \n ' return pulumi.get(self, 'id')
@property @pulumi.getter def identity(self) -> Optional['outputs.ManagedServiceIdentityResponse']: '\n The identity of the application gateway, if configured.\n ' return pulumi.get(self, 'identity')
3,779,855,874,785,179,000
The identity of the application gateway, if configured.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
identity
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter def identity(self) -> Optional['outputs.ManagedServiceIdentityResponse']: '\n \n ' return pulumi.get(self, 'identity')
@property @pulumi.getter def location(self) -> Optional[str]: '\n Resource location.\n ' return pulumi.get(self, 'location')
8,841,543,228,718,414,000
Resource location.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
location
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter def location(self) -> Optional[str]: '\n \n ' return pulumi.get(self, 'location')
@property @pulumi.getter def name(self) -> str: '\n Resource name.\n ' return pulumi.get(self, 'name')
-2,625,941,459,458,898,000
Resource name.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
name
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter def name(self) -> str: '\n \n ' return pulumi.get(self, 'name')
@property @pulumi.getter(name='operationalState') def operational_state(self) -> str: '\n Operational state of the application gateway resource.\n ' return pulumi.get(self, 'operational_state')
-3,974,465,468,316,918,000
Operational state of the application gateway resource.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
operational_state
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='operationalState') def operational_state(self) -> str: '\n \n ' return pulumi.get(self, 'operational_state')
@property @pulumi.getter(name='privateEndpointConnections') def private_endpoint_connections(self) -> Sequence['outputs.ApplicationGatewayPrivateEndpointConnectionResponse']: '\n Private Endpoint connections on application gateway.\n ' return pulumi.get(self, 'private_endpoint_connections')
6,080,750,852,872,518,000
Private Endpoint connections on application gateway.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
private_endpoint_connections
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='privateEndpointConnections') def private_endpoint_connections(self) -> Sequence['outputs.ApplicationGatewayPrivateEndpointConnectionResponse']: '\n \n ' return pulumi.get(self, 'private_endpoint_connections')
@property @pulumi.getter(name='privateLinkConfigurations') def private_link_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayPrivateLinkConfigurationResponse']]: '\n PrivateLink configurations on application gateway.\n ' return pulumi.get(self, 'private_link_configurations')
293,996,003,584,253,440
PrivateLink configurations on application gateway.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
private_link_configurations
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='privateLinkConfigurations') def private_link_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayPrivateLinkConfigurationResponse']]: '\n \n ' return pulumi.get(self, 'private_link_configurations')
@property @pulumi.getter def probes(self) -> Optional[Sequence['outputs.ApplicationGatewayProbeResponse']]: '\n Probes of the application gateway resource.\n ' return pulumi.get(self, 'probes')
-5,541,267,534,319,744,000
Probes of the application gateway resource.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
probes
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter def probes(self) -> Optional[Sequence['outputs.ApplicationGatewayProbeResponse']]: '\n \n ' return pulumi.get(self, 'probes')
@property @pulumi.getter(name='provisioningState') def provisioning_state(self) -> str: '\n The provisioning state of the application gateway resource.\n ' return pulumi.get(self, 'provisioning_state')
6,226,561,025,582,350,000
The provisioning state of the application gateway resource.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
provisioning_state
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='provisioningState') def provisioning_state(self) -> str: '\n \n ' return pulumi.get(self, 'provisioning_state')
@property @pulumi.getter(name='redirectConfigurations') def redirect_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayRedirectConfigurationResponse']]: '\n Redirect configurations of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).\n ' return pulumi.get(self, 'redirect_configurations')
-1,933,333,427,948,408,300
Redirect configurations of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
redirect_configurations
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='redirectConfigurations') def redirect_configurations(self) -> Optional[Sequence['outputs.ApplicationGatewayRedirectConfigurationResponse']]: '\n \n ' return pulumi.get(self, 'redirect_configurations')
@property @pulumi.getter(name='requestRoutingRules') def request_routing_rules(self) -> Optional[Sequence['outputs.ApplicationGatewayRequestRoutingRuleResponse']]: '\n Request routing rules of the application gateway resource.\n ' return pulumi.get(self, 'request_routing_rules')
-7,748,220,298,369,710,000
Request routing rules of the application gateway resource.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
request_routing_rules
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='requestRoutingRules') def request_routing_rules(self) -> Optional[Sequence['outputs.ApplicationGatewayRequestRoutingRuleResponse']]: '\n \n ' return pulumi.get(self, 'request_routing_rules')
@property @pulumi.getter(name='resourceGuid') def resource_guid(self) -> str: '\n The resource GUID property of the application gateway resource.\n ' return pulumi.get(self, 'resource_guid')
-8,059,144,296,912,127,000
The resource GUID property of the application gateway resource.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
resource_guid
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='resourceGuid') def resource_guid(self) -> str: '\n \n ' return pulumi.get(self, 'resource_guid')
@property @pulumi.getter(name='rewriteRuleSets') def rewrite_rule_sets(self) -> Optional[Sequence['outputs.ApplicationGatewayRewriteRuleSetResponse']]: '\n Rewrite rules for the application gateway resource.\n ' return pulumi.get(self, 'rewrite_rule_sets')
-334,078,002,078,932,540
Rewrite rules for the application gateway resource.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
rewrite_rule_sets
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='rewriteRuleSets') def rewrite_rule_sets(self) -> Optional[Sequence['outputs.ApplicationGatewayRewriteRuleSetResponse']]: '\n \n ' return pulumi.get(self, 'rewrite_rule_sets')
@property @pulumi.getter def sku(self) -> Optional['outputs.ApplicationGatewaySkuResponse']: '\n SKU of the application gateway resource.\n ' return pulumi.get(self, 'sku')
6,988,512,906,409,414,000
SKU of the application gateway resource.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
sku
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter def sku(self) -> Optional['outputs.ApplicationGatewaySkuResponse']: '\n \n ' return pulumi.get(self, 'sku')
@property @pulumi.getter(name='sslCertificates') def ssl_certificates(self) -> Optional[Sequence['outputs.ApplicationGatewaySslCertificateResponse']]: '\n SSL certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).\n ' return pulumi.get(self, 'ssl_certificates')
-7,759,993,510,776,709,000
SSL certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
ssl_certificates
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='sslCertificates') def ssl_certificates(self) -> Optional[Sequence['outputs.ApplicationGatewaySslCertificateResponse']]: '\n \n ' return pulumi.get(self, 'ssl_certificates')
@property @pulumi.getter(name='sslPolicy') def ssl_policy(self) -> Optional['outputs.ApplicationGatewaySslPolicyResponse']: '\n SSL policy of the application gateway resource.\n ' return pulumi.get(self, 'ssl_policy')
8,010,652,428,415,810,000
SSL policy of the application gateway resource.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
ssl_policy
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='sslPolicy') def ssl_policy(self) -> Optional['outputs.ApplicationGatewaySslPolicyResponse']: '\n \n ' return pulumi.get(self, 'ssl_policy')
@property @pulumi.getter(name='sslProfiles') def ssl_profiles(self) -> Optional[Sequence['outputs.ApplicationGatewaySslProfileResponse']]: '\n SSL profiles of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).\n ' return pulumi.get(self, 'ssl_profiles')
-6,316,934,473,019,740,000
SSL profiles of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
ssl_profiles
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='sslProfiles') def ssl_profiles(self) -> Optional[Sequence['outputs.ApplicationGatewaySslProfileResponse']]: '\n \n ' return pulumi.get(self, 'ssl_profiles')
@property @pulumi.getter def tags(self) -> Optional[Mapping[(str, str)]]: '\n Resource tags.\n ' return pulumi.get(self, 'tags')
562,229,697,900,116,900
Resource tags.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
tags
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter def tags(self) -> Optional[Mapping[(str, str)]]: '\n \n ' return pulumi.get(self, 'tags')
@property @pulumi.getter(name='trustedClientCertificates') def trusted_client_certificates(self) -> Optional[Sequence['outputs.ApplicationGatewayTrustedClientCertificateResponse']]: '\n Trusted client certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).\n ' return pulumi.get(self, 'trusted_client_certificates')
6,098,422,283,827,539,000
Trusted client certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
trusted_client_certificates
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='trustedClientCertificates') def trusted_client_certificates(self) -> Optional[Sequence['outputs.ApplicationGatewayTrustedClientCertificateResponse']]: '\n \n ' return pulumi.get(self, 'trusted_client_certificates')
@property @pulumi.getter(name='trustedRootCertificates') def trusted_root_certificates(self) -> Optional[Sequence['outputs.ApplicationGatewayTrustedRootCertificateResponse']]: '\n Trusted Root certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).\n ' return pulumi.get(self, 'trusted_root_certificates')
2,609,331,369,265,081,300
Trusted Root certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
trusted_root_certificates
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='trustedRootCertificates') def trusted_root_certificates(self) -> Optional[Sequence['outputs.ApplicationGatewayTrustedRootCertificateResponse']]: '\n \n ' return pulumi.get(self, 'trusted_root_certificates')
@property @pulumi.getter def type(self) -> str: '\n Resource type.\n ' return pulumi.get(self, 'type')
-5,079,398,349,541,291,000
Resource type.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
type
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter def type(self) -> str: '\n \n ' return pulumi.get(self, 'type')
@property @pulumi.getter(name='urlPathMaps') def url_path_maps(self) -> Optional[Sequence['outputs.ApplicationGatewayUrlPathMapResponse']]: '\n URL path map of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).\n ' return pulumi.get(self, 'url_path_maps')
-4,925,109,192,802,691,000
URL path map of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
url_path_maps
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='urlPathMaps') def url_path_maps(self) -> Optional[Sequence['outputs.ApplicationGatewayUrlPathMapResponse']]: '\n \n ' return pulumi.get(self, 'url_path_maps')
@property @pulumi.getter(name='webApplicationFirewallConfiguration') def web_application_firewall_configuration(self) -> Optional['outputs.ApplicationGatewayWebApplicationFirewallConfigurationResponse']: '\n Web application firewall configuration.\n ' return pulumi.get(self, 'web_application_firewall_configuration')
-955,775,498,257,793,900
Web application firewall configuration.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
web_application_firewall_configuration
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter(name='webApplicationFirewallConfiguration') def web_application_firewall_configuration(self) -> Optional['outputs.ApplicationGatewayWebApplicationFirewallConfigurationResponse']: '\n \n ' return pulumi.get(self, 'web_application_firewall_configuration')
@property @pulumi.getter def zones(self) -> Optional[Sequence[str]]: '\n A list of availability zones denoting where the resource needs to come from.\n ' return pulumi.get(self, 'zones')
2,416,209,700,606,667,300
A list of availability zones denoting where the resource needs to come from.
sdk/python/pulumi_azure_nextgen/network/v20200701/get_application_gateway.py
zones
pulumi/pulumi-azure-nextgen
python
@property @pulumi.getter def zones(self) -> Optional[Sequence[str]]: '\n \n ' return pulumi.get(self, 'zones')
def is_good_response_json(resp): '\n Returns True if the response seems to be HTML, False otherwise.\n ' content_type = resp.headers['Content-Type'].lower() return ((resp.status_code == 200) and (content_type is not None) and (content_type.find('json') > (- 1)))
615,579,723,312,468,100
Returns True if the response seems to be HTML, False otherwise.
Pulling data/apiv2_pull.py
is_good_response_json
GBruening/succes_predictor
python
def is_good_response_json(resp): '\n \n ' content_type = resp.headers['Content-Type'].lower() return ((resp.status_code == 200) and (content_type is not None) and (content_type.find('json') > (- 1)))
def windows_msvc(context, force=False): 'Bootstrapper for MSVC building on Windows.' deps_dir = os.path.join(context.sharedir, 'msvc-dependencies') deps_url = 'https://servo-deps-2.s3.amazonaws.com/msvc-deps/' def version(package): return packages.WINDOWS_MSVC[package] def package_dir(package): return os.path.join(deps_dir, package, version(package)) def check_cmake(version): cmake_path = find_executable('cmake') if cmake_path: cmake = subprocess.Popen([cmake_path, '--version'], stdout=PIPE) cmake_version_output = six.ensure_str(cmake.stdout.read()).splitlines()[0] cmake_version = cmake_version_output.replace('cmake version ', '') if (LooseVersion(cmake_version) >= LooseVersion(version)): return True return False def prepare_file(zip_path, full_spec): if (not os.path.isfile(zip_path)): zip_url = '{}{}.zip'.format(deps_url, urllib.parse.quote(full_spec)) download_file(full_spec, zip_url, zip_path) print('Extracting {}...'.format(full_spec), end='') try: extract(zip_path, deps_dir) except BadZipfile: print(('\nError: %s.zip is not a valid zip file, redownload...' % full_spec)) os.remove(zip_path) prepare_file(zip_path, full_spec) else: print('done') to_install = {} for package in packages.WINDOWS_MSVC: if ((package == 'cmake') and check_cmake(version('cmake'))): continue if (not os.path.isdir(package_dir(package))): to_install[package] = version(package) if (not to_install): return 0 print('Installing missing MSVC dependencies...') for package in to_install: full_spec = '{}-{}'.format(package, version(package)) parent_dir = os.path.dirname(package_dir(package)) if (not os.path.isdir(parent_dir)): os.makedirs(parent_dir) zip_path = (package_dir(package) + '.zip') prepare_file(zip_path, full_spec) extracted_path = os.path.join(deps_dir, full_spec) os.rename(extracted_path, package_dir(package)) return 0
-3,342,560,424,296,585,700
Bootstrapper for MSVC building on Windows.
python/servo/bootstrap.py
windows_msvc
Florian-Schoenherr/servo
python
def windows_msvc(context, force=False): deps_dir = os.path.join(context.sharedir, 'msvc-dependencies') deps_url = 'https://servo-deps-2.s3.amazonaws.com/msvc-deps/' def version(package): return packages.WINDOWS_MSVC[package] def package_dir(package): return os.path.join(deps_dir, package, version(package)) def check_cmake(version): cmake_path = find_executable('cmake') if cmake_path: cmake = subprocess.Popen([cmake_path, '--version'], stdout=PIPE) cmake_version_output = six.ensure_str(cmake.stdout.read()).splitlines()[0] cmake_version = cmake_version_output.replace('cmake version ', ) if (LooseVersion(cmake_version) >= LooseVersion(version)): return True return False def prepare_file(zip_path, full_spec): if (not os.path.isfile(zip_path)): zip_url = '{}{}.zip'.format(deps_url, urllib.parse.quote(full_spec)) download_file(full_spec, zip_url, zip_path) print('Extracting {}...'.format(full_spec), end=) try: extract(zip_path, deps_dir) except BadZipfile: print(('\nError: %s.zip is not a valid zip file, redownload...' % full_spec)) os.remove(zip_path) prepare_file(zip_path, full_spec) else: print('done') to_install = {} for package in packages.WINDOWS_MSVC: if ((package == 'cmake') and check_cmake(version('cmake'))): continue if (not os.path.isdir(package_dir(package))): to_install[package] = version(package) if (not to_install): return 0 print('Installing missing MSVC dependencies...') for package in to_install: full_spec = '{}-{}'.format(package, version(package)) parent_dir = os.path.dirname(package_dir(package)) if (not os.path.isdir(parent_dir)): os.makedirs(parent_dir) zip_path = (package_dir(package) + '.zip') prepare_file(zip_path, full_spec) extracted_path = os.path.join(deps_dir, full_spec) os.rename(extracted_path, package_dir(package)) return 0
def bootstrap(context, force=False, specific=None): 'Dispatches to the right bootstrapping function for the OS.' bootstrapper = None if ('windows-msvc' in host_triple()): bootstrapper = windows_msvc elif ('linux-gnu' in host_triple()): (distrib, version) = get_linux_distribution() if (distrib.lower() == 'nixos'): print('NixOS does not need bootstrap, it will automatically enter a nix-shell') print('Just run ./mach build') print('') print('You will need to run a nix-shell if you are trying to run any of the built binaries') print('To enter the nix-shell manually use:') print(' $ nix-shell etc/shell.nix') return context.distro = distrib context.distro_version = version bootstrapper = LINUX_SPECIFIC_BOOTSTRAPPERS.get(specific, linux) if (bootstrapper is None): print('Bootstrap support is not yet available for your OS.') return 1 return bootstrapper(context, force=force)
-8,758,505,369,750,413,000
Dispatches to the right bootstrapping function for the OS.
python/servo/bootstrap.py
bootstrap
Florian-Schoenherr/servo
python
def bootstrap(context, force=False, specific=None): bootstrapper = None if ('windows-msvc' in host_triple()): bootstrapper = windows_msvc elif ('linux-gnu' in host_triple()): (distrib, version) = get_linux_distribution() if (distrib.lower() == 'nixos'): print('NixOS does not need bootstrap, it will automatically enter a nix-shell') print('Just run ./mach build') print() print('You will need to run a nix-shell if you are trying to run any of the built binaries') print('To enter the nix-shell manually use:') print(' $ nix-shell etc/shell.nix') return context.distro = distrib context.distro_version = version bootstrapper = LINUX_SPECIFIC_BOOTSTRAPPERS.get(specific, linux) if (bootstrapper is None): print('Bootstrap support is not yet available for your OS.') return 1 return bootstrapper(context, force=force)
def test_sctp_abort_after_smc(self): ' testing Sctp Abort after Security Mode Command for a single UE ' self._s1ap_wrapper.configUEDevice(1) req = self._s1ap_wrapper.ue_req print('************************* Running Sctp Abort after Security Mode Command for a single UE for UE id ', req.ue_id) attach_req = s1ap_types.ueAttachRequest_t() attach_req.ue_Id = req.ue_id sec_ctxt = s1ap_types.TFW_CREATE_NEW_SECURITY_CONTEXT id_type = s1ap_types.TFW_MID_TYPE_IMSI eps_type = s1ap_types.TFW_EPS_ATTACH_TYPE_EPS_ATTACH attach_req.mIdType = id_type attach_req.epsAttachType = eps_type attach_req.useOldSecCtxt = sec_ctxt print('Sending Attach Request ue-id', req.ue_id) self._s1ap_wrapper._s1_util.issue_cmd(s1ap_types.tfwCmd.UE_ATTACH_REQUEST, attach_req) response = self._s1ap_wrapper.s1_util.get_response() self.assertEqual(response.msg_type, s1ap_types.tfwCmd.UE_AUTH_REQ_IND.value) print('Received auth req ind ue-id', req.ue_id) auth_res = s1ap_types.ueAuthResp_t() auth_res.ue_Id = req.ue_id sqn_recvd = s1ap_types.ueSqnRcvd_t() sqn_recvd.pres = 0 auth_res.sqnRcvd = sqn_recvd print('Sending Auth Response ue-id', req.ue_id) self._s1ap_wrapper._s1_util.issue_cmd(s1ap_types.tfwCmd.UE_AUTH_RESP, auth_res) response = self._s1ap_wrapper.s1_util.get_response() self.assertEqual(response.msg_type, s1ap_types.tfwCmd.UE_SEC_MOD_CMD_IND.value) print('Received Security Mode Command ue-id', req.ue_id) print('send SCTP ABORT') sctp_abort = s1ap_types.FwSctpAbortReq_t() sctp_abort.cause = 3 self._s1ap_wrapper._s1_util.issue_cmd(s1ap_types.tfwCmd.SCTP_ABORT_REQ, sctp_abort)
8,980,921,758,346,578,000
testing Sctp Abort after Security Mode Command for a single UE
lte/gateway/python/integ_tests/s1aptests/test_sctp_abort_after_smc.py
test_sctp_abort_after_smc
119Vik/magma-1
python
def test_sctp_abort_after_smc(self): ' ' self._s1ap_wrapper.configUEDevice(1) req = self._s1ap_wrapper.ue_req print('************************* Running Sctp Abort after Security Mode Command for a single UE for UE id ', req.ue_id) attach_req = s1ap_types.ueAttachRequest_t() attach_req.ue_Id = req.ue_id sec_ctxt = s1ap_types.TFW_CREATE_NEW_SECURITY_CONTEXT id_type = s1ap_types.TFW_MID_TYPE_IMSI eps_type = s1ap_types.TFW_EPS_ATTACH_TYPE_EPS_ATTACH attach_req.mIdType = id_type attach_req.epsAttachType = eps_type attach_req.useOldSecCtxt = sec_ctxt print('Sending Attach Request ue-id', req.ue_id) self._s1ap_wrapper._s1_util.issue_cmd(s1ap_types.tfwCmd.UE_ATTACH_REQUEST, attach_req) response = self._s1ap_wrapper.s1_util.get_response() self.assertEqual(response.msg_type, s1ap_types.tfwCmd.UE_AUTH_REQ_IND.value) print('Received auth req ind ue-id', req.ue_id) auth_res = s1ap_types.ueAuthResp_t() auth_res.ue_Id = req.ue_id sqn_recvd = s1ap_types.ueSqnRcvd_t() sqn_recvd.pres = 0 auth_res.sqnRcvd = sqn_recvd print('Sending Auth Response ue-id', req.ue_id) self._s1ap_wrapper._s1_util.issue_cmd(s1ap_types.tfwCmd.UE_AUTH_RESP, auth_res) response = self._s1ap_wrapper.s1_util.get_response() self.assertEqual(response.msg_type, s1ap_types.tfwCmd.UE_SEC_MOD_CMD_IND.value) print('Received Security Mode Command ue-id', req.ue_id) print('send SCTP ABORT') sctp_abort = s1ap_types.FwSctpAbortReq_t() sctp_abort.cause = 3 self._s1ap_wrapper._s1_util.issue_cmd(s1ap_types.tfwCmd.SCTP_ABORT_REQ, sctp_abort)
@defer.inlineCallbacks def image(self): '\n Get an image from the camera.\n \n Returns an Image object.\n ' try: (flag, img_array) = (yield threads.deferToThread(self.camera.read)) except SystemError: return if (flag is False): print('No image') return defer.returnValue(Image(img_array, ColorSpace.BGR))
-6,829,252,595,344,101,000
Get an image from the camera. Returns an Image object.
src/octopus/image/source.py
image
gar-syn/congo-lab
python
@defer.inlineCallbacks def image(self): '\n Get an image from the camera.\n \n Returns an Image object.\n ' try: (flag, img_array) = (yield threads.deferToThread(self.camera.read)) except SystemError: return if (flag is False): print('No image') return defer.returnValue(Image(img_array, ColorSpace.BGR))
def dataReceived(self, data: bytes): '\n Byte 1: command\n Byte 2-5: length\n Byte 6+: data\n ' self._buffer += data if (len(self._buffer) > 5): command = chr(self._buffer[0]) length = int.from_bytes(self._buffer[1:5], byteorder='big') if (len(self._buffer) >= (length + 5)): data = self._buffer[5:(5 + length)] self._buffer = self._buffer[(5 + length):] if (command == 'F'): self.formatReceived(data) elif (command == 'I'): self.imageReceived(data)
-6,403,001,168,901,691,000
Byte 1: command Byte 2-5: length Byte 6+: data
src/octopus/image/source.py
dataReceived
gar-syn/congo-lab
python
def dataReceived(self, data: bytes): '\n Byte 1: command\n Byte 2-5: length\n Byte 6+: data\n ' self._buffer += data if (len(self._buffer) > 5): command = chr(self._buffer[0]) length = int.from_bytes(self._buffer[1:5], byteorder='big') if (len(self._buffer) >= (length + 5)): data = self._buffer[5:(5 + length)] self._buffer = self._buffer[(5 + length):] if (command == 'F'): self.formatReceived(data) elif (command == 'I'): self.imageReceived(data)
@defer.inlineCallbacks def image(self): '\n Get an image from the camera.\n \n Returns a SimpleCV Image.\n ' try: img_array = (yield self._protocol.requestImage()) except Exception as e: print('Exception fetching image', e) return defer.returnValue(Image(img_array, ColorSpace.BGR))
5,561,012,379,729,677,000
Get an image from the camera. Returns a SimpleCV Image.
src/octopus/image/source.py
image
gar-syn/congo-lab
python
@defer.inlineCallbacks def image(self): '\n Get an image from the camera.\n \n Returns a SimpleCV Image.\n ' try: img_array = (yield self._protocol.requestImage()) except Exception as e: print('Exception fetching image', e) return defer.returnValue(Image(img_array, ColorSpace.BGR))
def f_regression_block(fun, X, y, blocksize=None, **args): '\n runs f_regression for each block separately (saves memory).\n\n -------------------------\n fun : method that returns statistics,pval\n X : {array-like, sparse matrix} shape = (n_samples, n_features)\n The set of regressors that will tested sequentially.\n y : array of shape(n_samples).\n The data matrix\n blocksize : number of SNPs per block\n ' if (blocksize == None): return fun(X, y, **args) idx_start = 0 idx_stop = int(blocksize) pval = np.zeros(X.shape[1]) stats = np.zeros(X.shape[1]) while (idx_start < X.shape[1]): (stats[idx_start:idx_stop], pval[idx_start:idx_stop]) = fun(X[:, idx_start:idx_stop], y, **args) idx_start = idx_stop idx_stop += blocksize if (idx_stop > X.shape[1]): idx_stop = X.shape[1] return (stats, pval)
1,460,409,536,140,639,200
runs f_regression for each block separately (saves memory). ------------------------- fun : method that returns statistics,pval X : {array-like, sparse matrix} shape = (n_samples, n_features) The set of regressors that will tested sequentially. y : array of shape(n_samples). The data matrix blocksize : number of SNPs per block
fastlmm/inference/linear_regression.py
f_regression_block
HealthML/FaST-LMM
python
def f_regression_block(fun, X, y, blocksize=None, **args): '\n runs f_regression for each block separately (saves memory).\n\n -------------------------\n fun : method that returns statistics,pval\n X : {array-like, sparse matrix} shape = (n_samples, n_features)\n The set of regressors that will tested sequentially.\n y : array of shape(n_samples).\n The data matrix\n blocksize : number of SNPs per block\n ' if (blocksize == None): return fun(X, y, **args) idx_start = 0 idx_stop = int(blocksize) pval = np.zeros(X.shape[1]) stats = np.zeros(X.shape[1]) while (idx_start < X.shape[1]): (stats[idx_start:idx_stop], pval[idx_start:idx_stop]) = fun(X[:, idx_start:idx_stop], y, **args) idx_start = idx_stop idx_stop += blocksize if (idx_stop > X.shape[1]): idx_stop = X.shape[1] return (stats, pval)
def f_regression_cov_alt(X, y, C): '\n Implementation as derived in tex document\n\n See pg 12 of following document for definition of F-statistic\n http://www-stat.stanford.edu/~jtaylo/courses/stats191/notes/simple_diagnostics.pdf\n\n Parameters\n ----------\n X : {array-like, sparse matrix} shape = (n_samples, n_features)\n The set of regressors that will tested sequentially.\n\n y : array of shape(n_samples).\n The data matrix\n\n c : {array-like, sparse matrix} shape = (n_samples, n_covariates)\n The set of covariates.\n\n\n Returns\n -------\n F : array, shape=(n_features,)\n F values of features.\n\n pval : array, shape=(n_features,)\n p-values of F-scores.\n ' old_flag_X = X.flags.writeable old_flag_C = C.flags.writeable old_flag_y = y.flags.writeable X.flags.writeable = False C.flags.writeable = False y.flags.writeable = False y = y.ravel() X = X.copy(order='F') y = y.copy() assert (C.shape[1] < C.shape[0]) cpinv = np.linalg.pinv(C) X -= np.dot(C, np.dot(cpinv, X)) y -= np.dot(C, np.dot(cpinv, y)) yS = safe_sqr(y.T.dot(X)) X *= X denom = ((X.sum(0) * y.T.dot(y)) - yS) F = (yS / denom) dof = (((X.shape[0] - 1) - C.shape[1]) / 1) F *= dof pv = stats.f.sf(F, 1, dof) X.flags.writeable = old_flag_X C.flags.writeable = old_flag_C y.flags.writeable = old_flag_y return (F, pv)
8,574,460,787,851,393,000
Implementation as derived in tex document See pg 12 of following document for definition of F-statistic http://www-stat.stanford.edu/~jtaylo/courses/stats191/notes/simple_diagnostics.pdf Parameters ---------- X : {array-like, sparse matrix} shape = (n_samples, n_features) The set of regressors that will tested sequentially. y : array of shape(n_samples). The data matrix c : {array-like, sparse matrix} shape = (n_samples, n_covariates) The set of covariates. Returns ------- F : array, shape=(n_features,) F values of features. pval : array, shape=(n_features,) p-values of F-scores.
fastlmm/inference/linear_regression.py
f_regression_cov_alt
HealthML/FaST-LMM
python
def f_regression_cov_alt(X, y, C): '\n Implementation as derived in tex document\n\n See pg 12 of following document for definition of F-statistic\n http://www-stat.stanford.edu/~jtaylo/courses/stats191/notes/simple_diagnostics.pdf\n\n Parameters\n ----------\n X : {array-like, sparse matrix} shape = (n_samples, n_features)\n The set of regressors that will tested sequentially.\n\n y : array of shape(n_samples).\n The data matrix\n\n c : {array-like, sparse matrix} shape = (n_samples, n_covariates)\n The set of covariates.\n\n\n Returns\n -------\n F : array, shape=(n_features,)\n F values of features.\n\n pval : array, shape=(n_features,)\n p-values of F-scores.\n ' old_flag_X = X.flags.writeable old_flag_C = C.flags.writeable old_flag_y = y.flags.writeable X.flags.writeable = False C.flags.writeable = False y.flags.writeable = False y = y.ravel() X = X.copy(order='F') y = y.copy() assert (C.shape[1] < C.shape[0]) cpinv = np.linalg.pinv(C) X -= np.dot(C, np.dot(cpinv, X)) y -= np.dot(C, np.dot(cpinv, y)) yS = safe_sqr(y.T.dot(X)) X *= X denom = ((X.sum(0) * y.T.dot(y)) - yS) F = (yS / denom) dof = (((X.shape[0] - 1) - C.shape[1]) / 1) F *= dof pv = stats.f.sf(F, 1, dof) X.flags.writeable = old_flag_X C.flags.writeable = old_flag_C y.flags.writeable = old_flag_y return (F, pv)
def f_regression_cov(X, y, C): 'Univariate linear regression tests\n\n Quick linear model for testing the effect of a single regressor,\n sequentially for many regressors.\n\n This is done in 3 steps:\n 1. the regressor of interest and the data are orthogonalized\n wrt constant regressors\n 2. the cross correlation between data and regressors is computed\n 3. it is converted to an F score then to a p-value\n\n Parameters\n ----------\n X : {array-like, sparse matrix} shape = (n_samples, n_features)\n The set of regressors that will tested sequentially.\n\n y : array of shape(n_samples).\n The data matrix\n\n c : {array-like, sparse matrix} shape = (n_samples, n_covariates)\n The set of covariates.\n\n\n Returns\n -------\n F : array, shape=(n_features,)\n F values of features.\n\n pval : array, shape=(n_features,)\n p-values of F-scores.\n ' X = check_array(X, dtype=np.float) C = check_array(C, dtype=np.float) y = check_array(y, dtype=np.float) y = y.ravel() assert (C.shape[1] < C.shape[0]) cpinv = np.linalg.pinv(C) X -= np.dot(C, np.dot(cpinv, X)) y -= np.dot(C, np.dot(cpinv, y)) corr = np.dot(y, X) corr /= np.asarray(np.sqrt(safe_sqr(X).sum(axis=0))).ravel() corr /= np.asarray(np.sqrt(safe_sqr(y).sum())).ravel() dof = (((X.shape[0] - 1) - C.shape[1]) / 1) F = (((corr ** 2) / (1 - (corr ** 2))) * dof) pv = stats.f.sf(F, 1, dof) return (F, pv)
-1,825,297,868,363,056,400
Univariate linear regression tests Quick linear model for testing the effect of a single regressor, sequentially for many regressors. This is done in 3 steps: 1. the regressor of interest and the data are orthogonalized wrt constant regressors 2. the cross correlation between data and regressors is computed 3. it is converted to an F score then to a p-value Parameters ---------- X : {array-like, sparse matrix} shape = (n_samples, n_features) The set of regressors that will tested sequentially. y : array of shape(n_samples). The data matrix c : {array-like, sparse matrix} shape = (n_samples, n_covariates) The set of covariates. Returns ------- F : array, shape=(n_features,) F values of features. pval : array, shape=(n_features,) p-values of F-scores.
fastlmm/inference/linear_regression.py
f_regression_cov
HealthML/FaST-LMM
python
def f_regression_cov(X, y, C): 'Univariate linear regression tests\n\n Quick linear model for testing the effect of a single regressor,\n sequentially for many regressors.\n\n This is done in 3 steps:\n 1. the regressor of interest and the data are orthogonalized\n wrt constant regressors\n 2. the cross correlation between data and regressors is computed\n 3. it is converted to an F score then to a p-value\n\n Parameters\n ----------\n X : {array-like, sparse matrix} shape = (n_samples, n_features)\n The set of regressors that will tested sequentially.\n\n y : array of shape(n_samples).\n The data matrix\n\n c : {array-like, sparse matrix} shape = (n_samples, n_covariates)\n The set of covariates.\n\n\n Returns\n -------\n F : array, shape=(n_features,)\n F values of features.\n\n pval : array, shape=(n_features,)\n p-values of F-scores.\n ' X = check_array(X, dtype=np.float) C = check_array(C, dtype=np.float) y = check_array(y, dtype=np.float) y = y.ravel() assert (C.shape[1] < C.shape[0]) cpinv = np.linalg.pinv(C) X -= np.dot(C, np.dot(cpinv, X)) y -= np.dot(C, np.dot(cpinv, y)) corr = np.dot(y, X) corr /= np.asarray(np.sqrt(safe_sqr(X).sum(axis=0))).ravel() corr /= np.asarray(np.sqrt(safe_sqr(y).sum())).ravel() dof = (((X.shape[0] - 1) - C.shape[1]) / 1) F = (((corr ** 2) / (1 - (corr ** 2))) * dof) pv = stats.f.sf(F, 1, dof) return (F, pv)
def test_bias(): '\n make sure we get the same result for setting C=unitvec\n ' (S, y) = get_example_data() C = np.ones((len(y), 1)) from sklearn.feature_selection import f_regression (F1, pval1) = f_regression(S, y, center=True) (F2, pval2) = f_regression_cov(S, C, y) (F3, pval3) = f_regression_cov_alt(S, C, y) np.testing.assert_array_almost_equal(F1, F2) np.testing.assert_array_almost_equal(F2, F3) np.testing.assert_array_almost_equal(pval1, pval2) np.testing.assert_array_almost_equal(pval2, pval3)
1,822,580,387,070,520,300
make sure we get the same result for setting C=unitvec
fastlmm/inference/linear_regression.py
test_bias
HealthML/FaST-LMM
python
def test_bias(): '\n \n ' (S, y) = get_example_data() C = np.ones((len(y), 1)) from sklearn.feature_selection import f_regression (F1, pval1) = f_regression(S, y, center=True) (F2, pval2) = f_regression_cov(S, C, y) (F3, pval3) = f_regression_cov_alt(S, C, y) np.testing.assert_array_almost_equal(F1, F2) np.testing.assert_array_almost_equal(F2, F3) np.testing.assert_array_almost_equal(pval1, pval2) np.testing.assert_array_almost_equal(pval2, pval3)
def test_cov(): '\n compare different implementations, make sure results are the same\n ' (S, y) = get_example_data() C = S[:, 0:10] S = S[:, 10:] (F1, pval1) = f_regression_cov(S, C, y) (F2, pval2) = f_regression_cov_alt(S, C, y) np.testing.assert_array_almost_equal(F1, F2) np.testing.assert_array_almost_equal(pval1, pval2)
-5,899,294,841,173,599,000
compare different implementations, make sure results are the same
fastlmm/inference/linear_regression.py
test_cov
HealthML/FaST-LMM
python
def test_cov(): '\n \n ' (S, y) = get_example_data() C = S[:, 0:10] S = S[:, 10:] (F1, pval1) = f_regression_cov(S, C, y) (F2, pval2) = f_regression_cov_alt(S, C, y) np.testing.assert_array_almost_equal(F1, F2) np.testing.assert_array_almost_equal(pval1, pval2)
def fit(self, X=None, y=None, K0_train=None, K1_train=None, h2=None, mixing=None, count_A1=None): '\n Method for training a :class:`FastLMM` predictor. If the examples in X, y, K0_train, K1_train are not the same, they will be reordered and intersected.\n\n :param X: training covariate information, optional: \n If you give a string, it should be the file name of a PLINK phenotype-formatted file.\n :type X: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string.\n\n :param y: training phenotype:\n If you give a string, it should be the file name of a PLINK phenotype-formatted file.\n :type y: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string.\n\n :param K0_train: Must be None. Represents the identity similarity matrix.\n :type K0_train: None\n\n :param K1_train: Must be None. Represents the identity similarity matrix.\n :type K1_train: `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ or a string or `KernelReader <http://fastlmm.github.io/PySnpTools/#kernelreader-kernelreader>`__\n\n :param h2: Ignored. Optional.\n :type h2: number\n\n :param mixing: Ignored. Optional.\n :type mixing: number\n\n :param count_A1: If it needs to read SNP data from a BED-formatted file, tells if it should count the number of A1\n alleles (the PLINK standard) or the number of A2 alleles. False is the current default, but in the future the default will change to True.\n :type count_A1: bool\n\n\n :rtype: self, the fitted Linear Regression predictor\n ' self.is_fitted = True assert (K0_train is None) assert (K1_train is None) assert (y is not None), 'y must be given' y = _pheno_fixup(y, count_A1=count_A1) assert (y.sid_count == 1), 'Expect y to be just one variable' X = _pheno_fixup(X, iid_if_none=y.iid, count_A1=count_A1) (X, y) = intersect_apply([X, y]) y = y.read() (X, covar_unit_trained) = X.read().standardize(self.covariate_standardizer, return_trained=True) X = SnpData(iid=X.iid, sid=FastLMM._new_snp_name(X), val=np.c_[(X.val, np.ones((X.iid_count, 1)))]) lsqSol = np.linalg.lstsq(X.val, y.val[:, 0], rcond=(- 1)) bs = lsqSol[0] r2 = lsqSol[1] D = lsqSol[2] N = y.iid_count self.beta = bs self.ssres = float(r2) self.sstot = ((y.val - y.val.mean()) ** 2).sum() self.covar_unit_trained = covar_unit_trained self.iid_count = X.iid_count self.covar_sid = X.sid self.pheno_sid = y.sid return self
2,439,679,434,466,574,300
Method for training a :class:`FastLMM` predictor. If the examples in X, y, K0_train, K1_train are not the same, they will be reordered and intersected. :param X: training covariate information, optional: If you give a string, it should be the file name of a PLINK phenotype-formatted file. :type X: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string. :param y: training phenotype: If you give a string, it should be the file name of a PLINK phenotype-formatted file. :type y: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string. :param K0_train: Must be None. Represents the identity similarity matrix. :type K0_train: None :param K1_train: Must be None. Represents the identity similarity matrix. :type K1_train: `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ or a string or `KernelReader <http://fastlmm.github.io/PySnpTools/#kernelreader-kernelreader>`__ :param h2: Ignored. Optional. :type h2: number :param mixing: Ignored. Optional. :type mixing: number :param count_A1: If it needs to read SNP data from a BED-formatted file, tells if it should count the number of A1 alleles (the PLINK standard) or the number of A2 alleles. False is the current default, but in the future the default will change to True. :type count_A1: bool :rtype: self, the fitted Linear Regression predictor
fastlmm/inference/linear_regression.py
fit
HealthML/FaST-LMM
python
def fit(self, X=None, y=None, K0_train=None, K1_train=None, h2=None, mixing=None, count_A1=None): '\n Method for training a :class:`FastLMM` predictor. If the examples in X, y, K0_train, K1_train are not the same, they will be reordered and intersected.\n\n :param X: training covariate information, optional: \n If you give a string, it should be the file name of a PLINK phenotype-formatted file.\n :type X: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string.\n\n :param y: training phenotype:\n If you give a string, it should be the file name of a PLINK phenotype-formatted file.\n :type y: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string.\n\n :param K0_train: Must be None. Represents the identity similarity matrix.\n :type K0_train: None\n\n :param K1_train: Must be None. Represents the identity similarity matrix.\n :type K1_train: `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ or a string or `KernelReader <http://fastlmm.github.io/PySnpTools/#kernelreader-kernelreader>`__\n\n :param h2: Ignored. Optional.\n :type h2: number\n\n :param mixing: Ignored. Optional.\n :type mixing: number\n\n :param count_A1: If it needs to read SNP data from a BED-formatted file, tells if it should count the number of A1\n alleles (the PLINK standard) or the number of A2 alleles. False is the current default, but in the future the default will change to True.\n :type count_A1: bool\n\n\n :rtype: self, the fitted Linear Regression predictor\n ' self.is_fitted = True assert (K0_train is None) assert (K1_train is None) assert (y is not None), 'y must be given' y = _pheno_fixup(y, count_A1=count_A1) assert (y.sid_count == 1), 'Expect y to be just one variable' X = _pheno_fixup(X, iid_if_none=y.iid, count_A1=count_A1) (X, y) = intersect_apply([X, y]) y = y.read() (X, covar_unit_trained) = X.read().standardize(self.covariate_standardizer, return_trained=True) X = SnpData(iid=X.iid, sid=FastLMM._new_snp_name(X), val=np.c_[(X.val, np.ones((X.iid_count, 1)))]) lsqSol = np.linalg.lstsq(X.val, y.val[:, 0], rcond=(- 1)) bs = lsqSol[0] r2 = lsqSol[1] D = lsqSol[2] N = y.iid_count self.beta = bs self.ssres = float(r2) self.sstot = ((y.val - y.val.mean()) ** 2).sum() self.covar_unit_trained = covar_unit_trained self.iid_count = X.iid_count self.covar_sid = X.sid self.pheno_sid = y.sid return self
def predict(self, X=None, K0_whole_test=None, K1_whole_test=None, iid_if_none=None, count_A1=None): '\n Method for predicting from a fitted :class:`FastLMM` predictor.\n If the examples in X, K0_whole_test, K1_whole_test are not the same, they will be reordered and intersected.\n\n :param X: testing covariate information, optional: \n If you give a string, it should be the file name of a PLINK phenotype-formatted file.\n :type X: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string.\n\n :param K0_whole_test: Must be None. Represents the identity similarity matrix.\n :type K0_whole_test: None\n\n :param K1_whole_test: Must be None. Represents the identity similarity matrix.\n :type K1_whole_test: `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ or a string or `KernelReader <http://fastlmm.github.io/PySnpTools/#kernelreader-kernelreader>`__\n\n :param iid_if_none: Examples to predict for if no X, K0_whole_test, K1_whole_test is provided.\n :type iid_if_none: an ndarray of two strings\n\n :param count_A1: If it needs to read SNP data from a BED-formatted file, tells if it should count the number of A1\n alleles (the PLINK standard) or the number of A2 alleles. False is the current default, but in the future the default will change to True.\n :type count_A1: bool\n\n :rtype: A `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__ of the means and a :class:`KernelData` of the covariance\n ' assert self.is_fitted, 'Can only predict after predictor has been fitted' assert ((K0_whole_test is None) or isinstance(K0_whole_test, KernelIdentity)) assert ((K1_whole_test is None) or isinstance(K1_whole_test, KernelIdentity)) X = _pheno_fixup(X, iid_if_none=iid_if_none, count_A1=count_A1) X = X.read().standardize(self.covar_unit_trained) X = SnpData(iid=X.iid, sid=FastLMM._new_snp_name(X), val=np.c_[(X.read().val, np.ones((X.iid_count, 1)))]) assert np.array_equal(X.sid, self.covar_sid), 'Expect covar sids to be the same in train and test.' pheno_predicted = X.val.dot(self.beta).reshape((- 1), 1) ret0 = SnpData(iid=X.iid, sid=self.pheno_sid, val=pheno_predicted, pos=np.array([[np.nan, np.nan, np.nan]]), name='linear regression Prediction') from pysnptools.kernelreader import KernelData ret1 = KernelData(iid=X.iid, val=((np.eye(X.iid_count) * self.ssres) / self.iid_count)) return (ret0, ret1)
-5,795,757,412,969,956,000
Method for predicting from a fitted :class:`FastLMM` predictor. If the examples in X, K0_whole_test, K1_whole_test are not the same, they will be reordered and intersected. :param X: testing covariate information, optional: If you give a string, it should be the file name of a PLINK phenotype-formatted file. :type X: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string. :param K0_whole_test: Must be None. Represents the identity similarity matrix. :type K0_whole_test: None :param K1_whole_test: Must be None. Represents the identity similarity matrix. :type K1_whole_test: `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ or a string or `KernelReader <http://fastlmm.github.io/PySnpTools/#kernelreader-kernelreader>`__ :param iid_if_none: Examples to predict for if no X, K0_whole_test, K1_whole_test is provided. :type iid_if_none: an ndarray of two strings :param count_A1: If it needs to read SNP data from a BED-formatted file, tells if it should count the number of A1 alleles (the PLINK standard) or the number of A2 alleles. False is the current default, but in the future the default will change to True. :type count_A1: bool :rtype: A `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__ of the means and a :class:`KernelData` of the covariance
fastlmm/inference/linear_regression.py
predict
HealthML/FaST-LMM
python
def predict(self, X=None, K0_whole_test=None, K1_whole_test=None, iid_if_none=None, count_A1=None): '\n Method for predicting from a fitted :class:`FastLMM` predictor.\n If the examples in X, K0_whole_test, K1_whole_test are not the same, they will be reordered and intersected.\n\n :param X: testing covariate information, optional: \n If you give a string, it should be the file name of a PLINK phenotype-formatted file.\n :type X: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string.\n\n :param K0_whole_test: Must be None. Represents the identity similarity matrix.\n :type K0_whole_test: None\n\n :param K1_whole_test: Must be None. Represents the identity similarity matrix.\n :type K1_whole_test: `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ or a string or `KernelReader <http://fastlmm.github.io/PySnpTools/#kernelreader-kernelreader>`__\n\n :param iid_if_none: Examples to predict for if no X, K0_whole_test, K1_whole_test is provided.\n :type iid_if_none: an ndarray of two strings\n\n :param count_A1: If it needs to read SNP data from a BED-formatted file, tells if it should count the number of A1\n alleles (the PLINK standard) or the number of A2 alleles. False is the current default, but in the future the default will change to True.\n :type count_A1: bool\n\n :rtype: A `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__ of the means and a :class:`KernelData` of the covariance\n ' assert self.is_fitted, 'Can only predict after predictor has been fitted' assert ((K0_whole_test is None) or isinstance(K0_whole_test, KernelIdentity)) assert ((K1_whole_test is None) or isinstance(K1_whole_test, KernelIdentity)) X = _pheno_fixup(X, iid_if_none=iid_if_none, count_A1=count_A1) X = X.read().standardize(self.covar_unit_trained) X = SnpData(iid=X.iid, sid=FastLMM._new_snp_name(X), val=np.c_[(X.read().val, np.ones((X.iid_count, 1)))]) assert np.array_equal(X.sid, self.covar_sid), 'Expect covar sids to be the same in train and test.' pheno_predicted = X.val.dot(self.beta).reshape((- 1), 1) ret0 = SnpData(iid=X.iid, sid=self.pheno_sid, val=pheno_predicted, pos=np.array([[np.nan, np.nan, np.nan]]), name='linear regression Prediction') from pysnptools.kernelreader import KernelData ret1 = KernelData(iid=X.iid, val=((np.eye(X.iid_count) * self.ssres) / self.iid_count)) return (ret0, ret1)
def score(self, X=None, y=None, K0_whole_test=None, K1_whole_test=None, iid_if_none=None, return_mse_too=False, count_A1=None): '\n Method for calculating the negative log likelihood of testing examples.\n If the examples in X,y, K0_whole_test, K1_whole_test are not the same, they will be reordered and intersected.\n\n :param X: testing covariate information, optional: \n If you give a string, it should be the file name of a PLINK phenotype-formatted file.\n :type X: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string.\n\n :param y: testing phenotype:\n If you give a string, it should be the file name of a PLINK phenotype-formatted file.\n :type y: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string.\n\n :param K0_whole_test: Must be None. Represents the identity similarity matrix.\n :type K0_whole_test: None\n\n :param K1_whole_test: Must be None. Represents the identity similarity matrix.\n :type K1_whole_test: `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ or a string or `KernelReader <http://fastlmm.github.io/PySnpTools/#kernelreader-kernelreader>`__\n\n :param iid_if_none: Examples to predict for if no X, K0_whole_test, K1_whole_test is provided.\n :type iid_if_none: an ndarray of two strings\n\n :param return_mse_too: If true, will also return the mean squared error.\n :type return_mse_too: bool\n\n :param count_A1: If it needs to read SNP data from a BED-formatted file, tells if it should count the number of A1\n alleles (the PLINK standard) or the number of A2 alleles. False is the current default, but in the future the default will change to True.\n :type count_A1: bool\n\n :rtype: a float of the negative log likelihood and, optionally, a float of the mean squared error.\n ' (mean0, covar0) = self.predict(K0_whole_test=K0_whole_test, K1_whole_test=K1_whole_test, X=X, iid_if_none=iid_if_none, count_A1=count_A1) y = _pheno_fixup(y, iid_if_none=covar0.iid, count_A1=count_A1) (mean, covar, y) = intersect_apply([mean0, covar0, y]) var = multivariate_normal(mean=mean.read(order='A', view_ok=True).val.reshape((- 1)), cov=covar.read(order='A', view_ok=True).val) y_actual = y.read().val nll = (- np.log(var.pdf(y_actual.reshape((- 1))))) if (not return_mse_too): return nll else: mse = ((y_actual - mean) ** 2).sum() return (nll, mse)
-425,445,694,898,426,050
Method for calculating the negative log likelihood of testing examples. If the examples in X,y, K0_whole_test, K1_whole_test are not the same, they will be reordered and intersected. :param X: testing covariate information, optional: If you give a string, it should be the file name of a PLINK phenotype-formatted file. :type X: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string. :param y: testing phenotype: If you give a string, it should be the file name of a PLINK phenotype-formatted file. :type y: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string. :param K0_whole_test: Must be None. Represents the identity similarity matrix. :type K0_whole_test: None :param K1_whole_test: Must be None. Represents the identity similarity matrix. :type K1_whole_test: `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ or a string or `KernelReader <http://fastlmm.github.io/PySnpTools/#kernelreader-kernelreader>`__ :param iid_if_none: Examples to predict for if no X, K0_whole_test, K1_whole_test is provided. :type iid_if_none: an ndarray of two strings :param return_mse_too: If true, will also return the mean squared error. :type return_mse_too: bool :param count_A1: If it needs to read SNP data from a BED-formatted file, tells if it should count the number of A1 alleles (the PLINK standard) or the number of A2 alleles. False is the current default, but in the future the default will change to True. :type count_A1: bool :rtype: a float of the negative log likelihood and, optionally, a float of the mean squared error.
fastlmm/inference/linear_regression.py
score
HealthML/FaST-LMM
python
def score(self, X=None, y=None, K0_whole_test=None, K1_whole_test=None, iid_if_none=None, return_mse_too=False, count_A1=None): '\n Method for calculating the negative log likelihood of testing examples.\n If the examples in X,y, K0_whole_test, K1_whole_test are not the same, they will be reordered and intersected.\n\n :param X: testing covariate information, optional: \n If you give a string, it should be the file name of a PLINK phenotype-formatted file.\n :type X: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string.\n\n :param y: testing phenotype:\n If you give a string, it should be the file name of a PLINK phenotype-formatted file.\n :type y: a PySnpTools `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ (such as `Pheno <http://fastlmm.github.io/PySnpTools/#snpreader-pheno>`__ or `SnpData <http://fastlmm.github.io/PySnpTools/#snpreader-snpdata>`__) or string.\n\n :param K0_whole_test: Must be None. Represents the identity similarity matrix.\n :type K0_whole_test: None\n\n :param K1_whole_test: Must be None. Represents the identity similarity matrix.\n :type K1_whole_test: `SnpReader <http://fastlmm.github.io/PySnpTools/#snpreader-snpreader>`__ or a string or `KernelReader <http://fastlmm.github.io/PySnpTools/#kernelreader-kernelreader>`__\n\n :param iid_if_none: Examples to predict for if no X, K0_whole_test, K1_whole_test is provided.\n :type iid_if_none: an ndarray of two strings\n\n :param return_mse_too: If true, will also return the mean squared error.\n :type return_mse_too: bool\n\n :param count_A1: If it needs to read SNP data from a BED-formatted file, tells if it should count the number of A1\n alleles (the PLINK standard) or the number of A2 alleles. False is the current default, but in the future the default will change to True.\n :type count_A1: bool\n\n :rtype: a float of the negative log likelihood and, optionally, a float of the mean squared error.\n ' (mean0, covar0) = self.predict(K0_whole_test=K0_whole_test, K1_whole_test=K1_whole_test, X=X, iid_if_none=iid_if_none, count_A1=count_A1) y = _pheno_fixup(y, iid_if_none=covar0.iid, count_A1=count_A1) (mean, covar, y) = intersect_apply([mean0, covar0, y]) var = multivariate_normal(mean=mean.read(order='A', view_ok=True).val.reshape((- 1)), cov=covar.read(order='A', view_ok=True).val) y_actual = y.read().val nll = (- np.log(var.pdf(y_actual.reshape((- 1))))) if (not return_mse_too): return nll else: mse = ((y_actual - mean) ** 2).sum() return (nll, mse)
def fake_edtf_level_0(): 'Generates a fake publication_date string.' def fake_date(end_date=None): fake = Faker() date_pattern = ['%Y', '%m', '%d'] if random.choice([True, False]): date_pattern.pop() if random.choice([True, False]): date_pattern.pop() return fake.date('-'.join(date_pattern), end_datetime=end_date) f_date = fake_date() if random.choice([True, False]): parser = level0Expression('level0') parsed_date = parser.parseString(f_date)[0] date_tuple = parsed_date.lower_strict()[:3] f_date_object = datetime.date(*date_tuple) interval_start = fake_date(end_date=f_date_object) return '/'.join([interval_start, f_date]) return f_date
3,227,993,622,139,514,400
Generates a fake publication_date string.
invenio_rdm_records/fixtures/demo.py
fake_edtf_level_0
Pineirin/invenio-rdm-records
python
def fake_edtf_level_0(): def fake_date(end_date=None): fake = Faker() date_pattern = ['%Y', '%m', '%d'] if random.choice([True, False]): date_pattern.pop() if random.choice([True, False]): date_pattern.pop() return fake.date('-'.join(date_pattern), end_datetime=end_date) f_date = fake_date() if random.choice([True, False]): parser = level0Expression('level0') parsed_date = parser.parseString(f_date)[0] date_tuple = parsed_date.lower_strict()[:3] f_date_object = datetime.date(*date_tuple) interval_start = fake_date(end_date=f_date_object) return '/'.join([interval_start, f_date]) return f_date
def create_fake_record(): 'Create records for demo purposes.' fake = Faker() data_to_use = {'access': {'record': 'public', 'files': 'public'}, 'files': {'enabled': False}, 'pids': {}, 'metadata': {'resource_type': CachedVocabularies.fake_resource_type(), 'creators': [{'person_or_org': {'family_name': fake.last_name(), 'given_name': fake.first_name(), 'type': 'personal', 'identifiers': [{'scheme': 'orcid', 'identifier': '0000-0002-1825-0097'}]}, 'affiliations': [{'name': fake.company(), 'identifiers': [{'scheme': 'ror', 'identifier': '03yrm5c26'}]}]} for i in range(4)], 'title': (fake.company() + "'s gallery"), 'additional_titles': [{'title': 'a research data management platform', 'type': 'subtitle', 'lang': 'eng'}, {'title': (fake.company() + "'s gallery"), 'type': 'alternativetitle', 'lang': 'eng'}], 'publisher': 'InvenioRDM', 'publication_date': fake_edtf_level_0(), 'subjects': CachedVocabularies.fake_subjects(), 'contributors': [{'person_or_org': {'family_name': fake.last_name(), 'given_name': fake.first_name(), 'type': 'personal'}, 'affiliations': [{'name': fake.company(), 'identifiers': [{'scheme': 'ror', 'identifier': '03yrm5c26'}]}], 'role': 'rightsholder'} for i in range(3)], 'languages': [CachedVocabularies.fake_language()], 'sizes': ['11 pages'], 'formats': ['application/pdf'], 'version': 'v0.0.1', 'description': fake.text(max_nb_chars=3000), 'additional_descriptions': [{'description': fake.text(max_nb_chars=200), 'type': 'methods', 'lang': 'eng'} for i in range(2)], 'funding': [{'funder': {'name': 'European Commission', 'identifier': '03yrm5c26', 'scheme': 'ror'}, 'award': {'title': 'OpenAIRE', 'number': '246686', 'identifier': '0000-0002-1825-0097', 'scheme': 'orcid'}}], 'references': [{'reference': 'Reference to something et al.', 'identifier': '0000000114559647', 'scheme': 'isni'}], 'identifiers': [{'identifier': 'ark:/123/456', 'scheme': 'ark'}]}} return json.loads(json.dumps(data_to_use))
3,656,507,691,640,930,300
Create records for demo purposes.
invenio_rdm_records/fixtures/demo.py
create_fake_record
Pineirin/invenio-rdm-records
python
def create_fake_record(): fake = Faker() data_to_use = {'access': {'record': 'public', 'files': 'public'}, 'files': {'enabled': False}, 'pids': {}, 'metadata': {'resource_type': CachedVocabularies.fake_resource_type(), 'creators': [{'person_or_org': {'family_name': fake.last_name(), 'given_name': fake.first_name(), 'type': 'personal', 'identifiers': [{'scheme': 'orcid', 'identifier': '0000-0002-1825-0097'}]}, 'affiliations': [{'name': fake.company(), 'identifiers': [{'scheme': 'ror', 'identifier': '03yrm5c26'}]}]} for i in range(4)], 'title': (fake.company() + "'s gallery"), 'additional_titles': [{'title': 'a research data management platform', 'type': 'subtitle', 'lang': 'eng'}, {'title': (fake.company() + "'s gallery"), 'type': 'alternativetitle', 'lang': 'eng'}], 'publisher': 'InvenioRDM', 'publication_date': fake_edtf_level_0(), 'subjects': CachedVocabularies.fake_subjects(), 'contributors': [{'person_or_org': {'family_name': fake.last_name(), 'given_name': fake.first_name(), 'type': 'personal'}, 'affiliations': [{'name': fake.company(), 'identifiers': [{'scheme': 'ror', 'identifier': '03yrm5c26'}]}], 'role': 'rightsholder'} for i in range(3)], 'languages': [CachedVocabularies.fake_language()], 'sizes': ['11 pages'], 'formats': ['application/pdf'], 'version': 'v0.0.1', 'description': fake.text(max_nb_chars=3000), 'additional_descriptions': [{'description': fake.text(max_nb_chars=200), 'type': 'methods', 'lang': 'eng'} for i in range(2)], 'funding': [{'funder': {'name': 'European Commission', 'identifier': '03yrm5c26', 'scheme': 'ror'}, 'award': {'title': 'OpenAIRE', 'number': '246686', 'identifier': '0000-0002-1825-0097', 'scheme': 'orcid'}}], 'references': [{'reference': 'Reference to something et al.', 'identifier': '0000000114559647', 'scheme': 'isni'}], 'identifiers': [{'identifier': 'ark:/123/456', 'scheme': 'ark'}]}} return json.loads(json.dumps(data_to_use))
@classmethod def fake_resource_type(cls): 'Generate a random resource_type.' if (not cls._resource_type_ids): cls._resource_type_ids = [] dir_ = Path(__file__).parent res_types = cls._read_vocabulary('resource_types') for res in res_types: cls._resource_type_ids.append(res['id']) random_id = random.choice(cls._resource_type_ids) return {'id': random_id}
-7,887,511,485,965,187,000
Generate a random resource_type.
invenio_rdm_records/fixtures/demo.py
fake_resource_type
Pineirin/invenio-rdm-records
python
@classmethod def fake_resource_type(cls): if (not cls._resource_type_ids): cls._resource_type_ids = [] dir_ = Path(__file__).parent res_types = cls._read_vocabulary('resource_types') for res in res_types: cls._resource_type_ids.append(res['id']) random_id = random.choice(cls._resource_type_ids) return {'id': random_id}
@classmethod def fake_subjects(cls): 'Generate random subjects.' if (not cls._subject_ids): subjects = cls._read_vocabulary('subjects') for subj in subjects: cls._subject_ids.append(subj['id']) if (not cls._subject_ids): return [] n = random.choice([0, 1, 2]) random_ids = random.sample(cls._subject_ids, n) return [{'id': i} for i in random_ids]
-5,945,701,269,691,416,000
Generate random subjects.
invenio_rdm_records/fixtures/demo.py
fake_subjects
Pineirin/invenio-rdm-records
python
@classmethod def fake_subjects(cls): if (not cls._subject_ids): subjects = cls._read_vocabulary('subjects') for subj in subjects: cls._subject_ids.append(subj['id']) if (not cls._subject_ids): return [] n = random.choice([0, 1, 2]) random_ids = random.sample(cls._subject_ids, n) return [{'id': i} for i in random_ids]
@classmethod def fake_language(cls): 'Generate a random resource_type.' random_id = random.choice(['eng', 'aah', 'aag']) return {'id': random_id}
6,489,719,817,623,931,000
Generate a random resource_type.
invenio_rdm_records/fixtures/demo.py
fake_language
Pineirin/invenio-rdm-records
python
@classmethod def fake_language(cls): random_id = random.choice(['eng', 'aah', 'aag']) return {'id': random_id}