text:
## Repository for the CoNLL 2019 paper: A Richly Annotated Corpus for Different Tasks in Automated Fact-Checking

Link to the paper: [A Richly Annotated Corpus for Different Tasks in Automated Fact-Checking](https://public.ukp.informatik.tu-darmstadt.de/UKP_Webpage/publications/2019/2019_SIGNLL_AnH_RichlyAnnotatedCorpus.pdf)

Please use the following citation:
```
@inproceedings{hanselowski2019snopes,
          title={A Richly Annotated Corpus for Different Tasks in Automated Fact-Checking},
          author={Hanselowski, Andreas and Stab, Christian and Schulz, Claudia and Li, Zile and Gurevych, Iryna},
          booktitle={Proceedings of the 22nd Conference on Computational Natural Language Learning (CoNLL2019)},
          year={2019}
        }
```

Disclaimer:
> This repository contains experimental software and is published for the sole purpose of giving additional background details on the respective publication.

### Corpus for this repository
 * You can either recreate the corpus using [the web crawler](https://github.com/UKPLab/conll2019-snopes-crawling)
 * Or request the original siplits of the data for the reproduction of the results on this [data archive website](https://tudatalib.ulb.tu-darmstadt.de/handle/tudatalib/2081) (However, please take note of the licence agreement as the corpus is not publicly available)

### Installation

* Download and install Anaconda (https://www.anaconda.com/)
* Create a Python Environment and activate it:
```bash
    conda create -n snopes python=3.6
    source activate snopes
```
* Install the required dependencies
```bash
    pip install -r requirements.txt
    pip install git+git://github.com/j6mes/drqa@parallel
```
* Download NLTK Punkt Tokenizer
```bash
    python -c "import nltk; nltk.download('punkt')"
```

* For BERT models, create separately a Python Environment:
```bash
    conda create -n bert python=3.6
    source activate bert
    pip install -r requirements_bert.txt
    pip install git+git://github.com/j6mes/drqa@parallel
```

* Proceed with downloading the data set, the embeddings, the models and the evidence data

### Download the word embeddings

Download pretrained GloVe Vectors
```bash
    wget http://nlp.stanford.edu/data/wordvecs/glove.6B.zip
    mkdir -p data/glove
    unzip glove.6B.zip -d data/glove
    gzip data/glove/*.txt
```
Download pretrained Wiki FastText Vectors
```bash
    wget https://s3-us-west-1.amazonaws.com/fasttext-vectors/wiki.en.zip
    mkdir -p data/fasttext
    unzip wiki.en.zip -d data/fasttext

    or (in this case the folder path "fasttext_path": "data/fasttext/wiki.en.bin" the config files in the folders conf_snopes_paper and conf_snopes_stance_paper need to be changed to "data/fasttext/wiki-news-300d-1M.vec" )

    wget https://dl.fbaipublicfiles.com/fasttext/vectors-english/wiki-news-300d-1M.vec
    mkdir -p data/fasttext
    unzip wiki-news-300d-1M.vec.zip -d data/fasttext

```

### Pre-processed datasets

Ask for permission to dowload the dataset:  [Snopes Corpus](https://tudatalib.ulb.tu-darmstadt.de/handle/tudatalib/2081)

```bash
    unzip ukp_snopes_corpus.zip
    cp -r snopes_corpus/datasets data/
```

### Evidence extraction

```bash
    PYTHONPATH=src python src/scripts/evidence_extraction.py --model  [esim or bilstm_ranking or decompos_att or tf-idf or random_baseline]
    e.g.: PYTHONPATH=src python src/scripts/evidence_extraction.py --model bilstm_ranking
```

Available configuration files:

|Field|Description|
|---|---|
|esim|ESIM ranking model|
|bilstm_ranking|BiLSTM ranking model|
|decompos_att|Decomposable attention ranking model|
|tf-idf|TF-IDF ranking|
|random_baseline|Random basline|

### Stance detection

To run the stance detection models, launch the script as following:
```bash
    PYTHONPATH=src python src/scripts/rte.py --mode <train/test> [--config conf_cnopes_stance_paper <path/to/config/file/json>]
    e.g.: PYTHONPATH=src python src/scripts/rte.py --mode train --config conf_snopes_stance_paper/config_snopes_use_bilstm.json
```

Available configuration files:

|Field|Description|
|---|---|
|config_snopes_bert_sent_bilstm.json|BERT sentence embeddings with BiLSTM encoding|
|config_snopes_bert_word_bilstm.json|BERT word embeddings with BiLSTM encoding|
|config_snopes_use_bilstm.json|Google Universal Sentence Encoder (USE+Attent) |

### Claim validation

To run the claim validation models, launch the script as following:
```bash
    PYTHONPATH=src python src/scripts/rte.py --mode <train/test> [--config_cnopes_paper <path/to/config/file/json>]
    e.g.: PYTHONPATH=src python src/scripts/rte.py --mode train --config conf_snopes_paper/config_snopes_bilstm.json
```

Available configuration files:

|Field|Description|
|---|---|
|config_snopes_bilstm.json|BilSTM|
|config_snopes_bert_sent_attention.json|BERT sentence embeddings with attention|
|config_snopes_esim_glove.json|Extended ESIM with GloVe embeddings|
|config_snopes_use_attention.json|Google Universal Sentence Encoder with attention|

#### Run Decomposable Attention model (different configurations are required)
To run the decomposable attention model with Snopes corpus, run the script below:
##### Training:
```bash
    PYTHONPATH=src python src/scripts/train_da.py data/datasets/snopes.page.json [config/snopes.json or config/stance.json] <folder/to/keep/the/model> --cuda-device <GPU Number> --is-snopes True
    e.g.: PYTHONPATH=src python src/scripts/train_da.py data/datasets/snopes.page.json config/stance.json model/decomp_attention_stance/ --cuda-device 0 --is-snopes True
```
##### Testing:
```bash
    PYTHONPATH=src python src/scripts/eval_da.py data/datasets/snopes.page.json <folder/to/keep/the/model>/model.tar.gz [data/datasets/snopes.test.jsonl or data/datasets/snopes.stance.test.jsonl] --cuda-device <GPU Number> --is-snopes True
    e.g.: PYTHONPATH=src python src/scripts/eval_da.py data/datasets/snopes.page.json model/decomp_attention_stance/model.tar.gz data/datasets/snopes.stance.test.jsonl --cuda-device 0 --is-snopes True
```

#### BERT models (different configurations are required)

For BERT models, change Python environment to bert
```bash
    source activate bert
```
The pretrained model need to be downloaded and the bert-as-service server need to be first started.
To download the pretrained model:
```bash
    mkdir bert
    cd bert
    wget https://storage.googleapis.com/bert_models/2018_10_18/cased_L-24_H-1024_A-16.zip
    unzip cased_L-24_H-1024_A-16.zip
```
For BERT word embedding:
```bash
    bert-serving-start -pooling_strategy NONE -model_dir bert/cased_L-24_H-1024_A-16 -max_seq_len 50 [-port <bert_port> -port_out <bert_port_out> -graph_tmp_dir <path/to/tmp/folder, default as /tmp>]
```
For BERT sentence embedding:
```bash
    bert-serving-start -model_dir bert/cased_L-24_H-1024_A-16 -max_seq_len 50 [-port <bert_port> -port_out <bert_port_out> -graph_tmp_dir <path/to/tmp/folder, default as /tmp>]
```
bert_port is default as 5555, and bert_port_out default as 5556. These two ports should refer to the same fields in the config.

For more detail, please refer to [bert-as-service](https://github.com/hanxiao/bert-as-service).

### Run AtheneMLP model for stance detection (not yet fixed)

Please note, the comand below is not yet wroking properly and will be fixed later. If you want to fix it yourselfe, the required files are in the directory src/fnc

```bash
    PYTHONPATH=src python python src/fnc/pipeline.py
```

### Description of the Config File
The config file regarding the file paths and the hyper parameters is [src/athene/utils/config.py](https://git.ukp.informatik.tu-darmstadt.de/zli/athene-fever/blob/snopes/src/athene/utils/config.py). The descriptions of each field are followings:

|Field|Description|
|---|---|
|model_name|Name of the RTE model. Used as part of the path to save the trained RTE model.|
|glove_path|Path to the pre-trained GloVe word embedding. Either point to the glove.6B.300d.txt.gz or the glove.6B.300d.txt file.|
|fasttext_path|Path to the pre-trained FastText word embedding. Should point to the wiki.en.bin file.|
|ckpt_folder|Path to the checkpoint folder for the trained RTE model. Default as model/<model_name>/rte_checkpoints.|
|db_path|Path to the FEVER database file.|
|dataset_folder|Path to the dataset folder.|
|raw_training_set|Path to the original training set file.|
|raw_dev_set|Path to the original development set file.|
|raw_test_set|Path to the original test set file.|
|training_doc_file|Path to the training set with predicted pages, i.e. the output of the training set through document retrieval sub-task.|
|dev_doc_file|Path to the development set with predicted pages, i.e. the output of the development set through document retrieval sub-task.|
|test_doc_file|Path to the test set with predicted pages, i.e. the output of the test set through document retrieval sub-task.|
|training_set_file|Path to the training set with predicted evidences, i.e. the output of the training set through sentence retrieval sub-task.|
|dev_set_file|Path to the development set with predicted evidences, i.e. the output of the development set through sentence retrieval sub-task.|
|test_set_file|Path to the test set with predicted evidences, i.e. the output of the test set through sentence retrieval sub-task.|
|document_k_wiki|The maximal number of candidate pages for each claim in the document retrieval sub-task.|
|document_parallel|Whether to perform the document retrieval sub-task parallel. True or False.|
|document_add_claim|Whether to append the original claim to the query to the MediaWiki API in the document retrieval sub-task. True or False.|
|submission_file|Path to the final submission file.|
|estimator_name|The name of the RTE estimator referring to [src/athene/rte/utils/estimator_definitions.py](https://git.ukp.informatik.tu-darmstadt.de/zli/athene-fever/blob/snopes/src/athene/rte/utils/estimator_definitions.py).|
|max_sentences|The maximal number of predicted evidences for each claim.|
|max_sentence_size|The maximal length of each predicted evidence. The words that exceed the maximal length are truncated.|
|max_claim_size|The maximal length of each claim. The words that exceed the maximal length are truncated.|
|seed|Random seed of the RTE sub-task.|
|name|The prefix of the checkpoint files for the RTE sub-task. The checkpoint files will be saved in the <ckpt_folder>.|
|bert_port|port for the BERT server. Only for BERT models.|
|bert_port_out|port_out for the BERT server. Only for BERT models.|
|max_gpu_memory|Maximal GPU memory usage. Percentage. (0.0, 1.0]. Default as 0.5|
|tensorboard_folder|TensorBoard folder. Default as None, meaning no tensorboard data will be collected.|

'**esim_hyper_param**' field contains the hyper parameters regarding the ESIM based model and the model using BERT word encodings in the RTE sub-task. The descriptions of several special parameters are followings:

|Field|Description|
|---|---|
|num_neurons|The number of neurons for each layer in the model. The first 2 numbers refer to the numbers of neurons of the two bidirectional RNNs in the ESIM model.|
|pos_weight|The positive weights of the 3 classes for the weighted loss. The order is Supported, Refuted, Not Enough Info.|
|max_checks_no_progress|Early stopping policy. Stop training if no improvement in the last x epochs.|
|trainable|Whether to fine tune the word embeddings. True or False.|

'**esim_mtl_hyper_param**' field contains the hyper parameters regarding the ESIM Multi-Task Learning model and the model using BERT word encodings in the RTE sub-task. The descriptions of several special parameters are followings:

|Field|Description|
|---|---|
|num_neurons_esim|The number of neurons for the shared ESIM component, i.e. 2 BiLSTM layers.|
|num_neurons_claim_validation|The number of neurons of the MLP for the claim validation task.|
|num_neurons_evidence_evaluation|The number of neurons of the MLP for the evidence evaluation task.|

'**esim_end_2_end_hyper_param**' field contains the hyper parameters regarding the ESIM End-2-End model and the model using BERT word encodings in the RTE sub-task. The descriptions of several special parameters are followings:

|Field|Description|
|---|---|
|sentence_selection_criterion|The criterion of selecting candidate evidences. '**n_best_sents**': Select top N sentences. '**sent_threshold**': Select sentences with scores higher than a threshold.|
|n_best_sents|The number of sentences to select. Only for the criterion '**n_best_sents**'.|
|sent_threshold|The threshold for selecting sentences. Only for the criterion '**sent_threshold**'.|

'**esim_credibility_hyper_param**' field contains the hyper parameters regarding the model using source information for Snopes corpora in the RTE sub-task. The descriptions of several special parameters are followings:

|Field|Description|
|---|---|
|word_trainable|True or False. Whether the word embeddings are trainable.|
|domain_trainable|True or False. Whether the domain name embeddings are trainable.|
|suffix_trainable|True or False. Whether the embeddings for the suffix of domain names are trainable.|
|stance_trainable|True or False. Whether the stance embeddings are trainable.|
|protocol_trainable|True or False. Whether the embeddings for the protocols (HTTP or HTTPS) are trainable.|
|domain_embedding_size|The dimensionality of the domain name embeddings.|
|suffix_embedding_size|The dimensionality of the embeddings for the suffix of the domain name .|
|protocol_embedding_size|The dimensionality of the embeddings for the protocols of the domain name .|
|stance_embedding_size|The dimensionality of the stance embeddings.|
|features_embeddings_path|The path where the embeddings are stored after training.|

'**esim_credibility_mtl_hyper_param**' field contains the hyper parameters regarding the Multi-Task Learning model using source information for Snopes corpora in the RTE sub-task. The descriptions of several special parameters are followings:

|Field|Description|
|---|---|
|num_neurons_esim|The number of neurons for the shared ESIM component, i.e. 2 BiLSTM layers.|
|num_neurons_claim_validation|The number of neurons of the MLP for the claim validation task.|
|num_neurons_stance_detection|The number of neurons of the MLP for the stance detection task.|
|word_trainable|True or False. Whether the word embeddings are trainable.|
|domain_trainable|True or False. Whether the domain name embeddings are trainable.|
|suffix_trainable|True or False. Whether the embeddings for the suffix of domain names are trainable.|
|stance_trainable|True or False. Whether the stance embeddings are trainable.|
|protocol_trainable|True or False. Whether the embeddings for the protocols (HTTP or HTTPS) are trainable.|
|domain_embedding_size|The dimensionality of the domain name embeddings.|
|suffix_embedding_size|The dimensionality of the embeddings for the suffix of the domain name .|
|protocol_embedding_size|The dimensionality of the embeddings for the protocols of the domain name .|
|stance_embedding_size|The dimensionality of the stance embeddings.|
|claim_training_set|The path to the training set of the claim validation task.|
|claim_dev_set|The path to the development set of the claim validation task.|
|claim_test_set|The path to the test set of the claim validation task.|
|stance_training_set|The path to the training set of the stance detection task.|
|stance_dev_set|The path to the development set of the stance detection task.|
|stance_test_set|The path to the test set of the stance detection task.|
|features_embeddings_path|The path where the embeddings are stored after training.|

'**han_hyper_param**' field contains the hyper parameters regarding the Hierarchical Attention Network models in the RTE sub-task. The descriptions of several special parameters are followings:

|Field|Description|
|---|---|
|word_output_size|The dimensionality of the word-level output after aligned by the attention|
|sent_output_size|The dimensionality of the sentence-level output after aligned by the attention|

'**use_hyper_param**' field contains the hyper parameters regarding the Universal Sentence Encoder based models in the RTE sub-task. The descriptions of several special parameters are followings:

|Field|Description|
|---|---|
|attention_function|Only for **use_attention** models. The attention implementations to choose. Choices are: '**cosine_similarity**', '**weight_matrix**': *c* as claim and *e* as evidence, randomly initialize a 512*512 trainable matrix *m*, and calculate the attention weights as *c·m·e*. '**weight_matrix_2**': vector *v=W·e + b*, and the attention weight as *v·c*. '**weight_matrix_3**': *c* and *e* both through a feed-forward layer, then the multiplication as attention weight.|
|do_finetune|Only for **use_attention** models. True or False. Whether to fine tune USE.|

'**bert_sent_hyper_param**' field contains the hyper parameters regarding the models using the BERT sentence encoding in the RTE sub-task. The descriptions of several special parameters are followings:

|Field|Description|
|---|---|
|attention_function|The attention implementations to choose. Choices are: '**cosine_similarity**', '**weight_matrix**': *c* as claim and *e* as evidence, randomly initialize a 512*512 trainable matrix *m*, and calculate the attention weights as *c·m·e*. '**weight_matrix_2**': vector *v=W·e + b*, and the attention weight as *v·c*. '**weight_matrix_3**': *c* and *e* both through a feed-forward layer, then the multiplication as attention weight.|

'**sentence_retrieval_ensemble_param**' field contains the hyper parameters regarding the ESIM based model in the sentence retrieval sub-task. The descriptions of several special parameters are followings:

|Field|Description|
|---|---|
|num_model|The number of models to ensemble.|
|tf_random_state|The random seeds for the models to ensemble.|
|num_negatives|The number of negative sampling, i.e. false evidences, for each claim in the training phase.|
|c_max_length|The maximal length of each claim. The words that exceed the maximal length are truncated.|
|s_max_length|The maximal length of each candidate evidence sentence. The words that exceed the maximal length are truncated.|
|reserve_embed|Whether to reserve slots in the word embeddings for unseen words. True or False.|
|model_path|Path to the folder for the checkpoint files of the ensemble models.|

### Contacts:
  *<EMAIL_ADDRESS>  * https://www.informatik.tu-darmstadt.de/ukp/ukp_home/
  * https://www.tu-darmstadt.de

### Credit:

This repository was build by Zile Li, Hao Zhang, and Andreas Hanselowski.

### License:
  * Apache License Version 2.0


text:
# herd.json
Ceylon JSON object representation

This project is based and in general is similar to SDK module `ceylon.json`.
In contrast with SDK it contains mutable and immutable JSON object and array.

####JSON value
Value JSON operates with: `String | Boolean | Integer | Float | JsonObject | JsonArray | Null`

####JSON Object
JSON object is enumerated with three states: mutable, immutable and empty:

      shared interface JsonObject
          of MutableJsonMap | JsonMap | EmptyJsonMap
          satisfies Map<String, JsonValue>

* `MutableJsonMap` is mutable JSON object and it is very similar to SDK `ceylon.json.object`.
Any embeded objects and arrays mutable object contains are mutable. If immutable sub-item passed to mutable object it is converted to mutable internaly.
* `JsonMap` is immutable JSON object. It can be filled only at initialization. `JsonMap` contains only immutable
embeded JSON objects and arrays. If mutable sub-item passed to initializer it is converted to immutable internaly.
* `EmptyJsonMap` is immutable and represents object which is always empty.

####JSON Array
JSON array structure is similar to JSON object:

    shared interface JsonArray
        of MutableJsonList | JsonList | EmptyJsonList
        satisfies List<JsonValue>

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
---
layout: post
number: 8
name: Captain Shaddid
date: 2017-10-24
short_text: Decisive and tough, with a taste for style and comfort.
tweet_text: Star Helix's Ceres commander and Miller's tough boss.
hero: /assets/images/008-CaptainShaddid-card.jpg
drink_crop: /assets/images/008-CaptainShaddid-drink.jpg
twitter_url: "https://twitter.com/Paine_MacTane/status/922853110506287105"
author: Paine×Mactane
tags:
  - "Difficulty: Hard"
  - Rye
  - Irish Coffee Glass
  - Hot Drink
  - Easy to Batch
  - Spicy
  - Homemade Ingredient
  - Fall/Winter
  - Character Drink
  - Belter
  - Bit Part
  - Expanse Cocktails Project
ingredients:
  - amount: 2
    unit: parts
    name: spiced syrup (recipe below)
  - amount: 1
    unit: part
    name: lemon juice
  - amount: 3
    unit: parts
    name: rye whiskey
  - amount: ½
    unit: part
    name: Cointreau
  - amount: ½
    unit: part
    name: allspice dram
  - amount: 4
    unit: dashes
    name: orange bitters

---

The incisive commander of the Ceres division of Star Helix, Captain Shaddid knows which of her officers are washed-up and ripe for assignments meant to fail. She keeps an air filter on her desk that emits spiced fragrances.

We wanted the drink to be a nod to Captain Shaddid's air filter and its aromas & spices. Bonus for Earthers: it'll be a great fall/winter cocktail!

{% include image.html url="/assets/images/shaddid-filter.jpg" description="Here's Captain Shaddid adding fragrance to the air filter in her elegant office. In the books, many characters customize their home and office scents for comfort or nostalgia." %}

Customize your drink with the peppercorns: the more you crack them, the spicier it will be. (When we said lightly, we weren't kidding.) We cracked our peppercorns in Ziploc bags with a marble rolling pin & some Pyrex measuring cups. Any hard object on a hard surface will do.

{% include ingredients.html %}

#### Instructions:

Spiced Syrup: Simmer 1½ cups water, ½ cup Demerara sugar, 1 heaping tbsp lightly cracked black peppercorns, 1 cinnamon stick, and 1 vanilla bean split lengthwise for 1 hour, covered. Add 1 star anise in the last 5 minutes and strain.

Cocktail: Bring spiced syrup and lemon juice to a light simmer, then immediately remove from heat.  Add rye, Cointreau, allspice dram, and bitters to the pot. Stir and strain into an Irish coffee cup. Garnish with a cinnamon stick.

Add all ingredients to a large shot glass, then stir briefly with a swizzle stick or stirring rod. No garnish.

{% include tags.html %}

repository: hannep/paine-mactane

extension: markdown

gha_language: SCSS

gha_license_id: MIT

repo_name: hannep/paine-mactane


text:
# Mathfreak231's Wonder Launcher mod

Version 0.0 alpha.

This mod implements the Wonder Launcher into the Pokémon Showdown simulator.

**THIS MOD IS EXPERIMENTAL.** Use this mod at your own risk; if it is bugged or crashes your battle, please report it to me!

The Wonder Launcher was a feature from Generation V that could be toggled in link battles.
Sides get points each turn and use them on items like Potions, Antidotes, X Attacks, and Revives.
It has been the only way items from the Bag could be used in multiplayer battles since the beginning of time.

## Client specification

Players will choose to use the Wonder Launcher on any Pokémon's turn with the following choice string:

```
launch SWITCHSPEC ITEMSPEC
```

or, when the item requires a move target (such as Ether):

```
launch SWITCHSPEC ITEMSPEC MOVESLOTSPEC
```

`SWITCHSPEC` and `MOVESLOTSPEC` are the same as they are when switching and using a move, respectively,
except that `SWITCHSPEC` cannot contain a space (therefore, using numbers instead of nicknames to choose is preferred).
`ITEMSPEC` is an item name, such as `X Attack`; if `MOVESLOTSPEC` is required, `ITEMSPEC` must not contain a space.

Examples of valid launch choice strings are:
- `launch 1 hyperpotion` uses a Hyper Potion on the Pokémon currently in slot 1.
- `launch Sparky Max Revive` uses a Max Revive on a Pokémon named Sparky.
- `launch 1 ether 2` uses an Ether on the 2nd move of the Pokémon currently in slot 1.
- `launch 2 Ether Hydro Pump` uses an Ether on the move Hydro Pump of the Pokémon currently in slot 2.

## Server specification

As far as battle mechanics go, the Wonder Launcher will be implemented as if the items were used in Gen VII.
Thus, for instance, the Hyper Potion restores only 120 HP.

## Credits

Thanks to [CertainlySomeoneHere](https://www.twitch.tv/certainlysomeonehere) for helping out with a bit of Gen VII research.

Minor thanks to Lycanium Z for helping me get started with the Revive code.

repository: MathyFurret/random-showdown-mods

repo_name: MathyFurret/random-showdown-mods


text:
---
layout: article
permalink: /about-en
title: "About the project"
author: ilya
---

*Demographic Digest*  is a regular column at [Demoscope Weekly][demoscope] which publishes (in Russian) brief summaries of fresh demographic papers from the best academic journals.

The aim of the project is to present notable demographic papers of our western colleagues to Russian speaking audience. We do not strive to cover all the results and the methodological nuances of the reviewed papers. In some reviews, the interest drives our attention to the small details that might seem insignificant to the reader, while the other reviews may seem rather sketchy. To resolve any additional questions concerning the papers covered in Digest, the reader is invited to investigate the original publications. The presented reviews are no more than just one possible way of reading the academic texts.

**[The archive of Demographic Digest at Demoscope Weekly][archive]**

[demoscope]: http://demoscope.ru
[archive]: http://demoscope.ru/weekly/arc/arcdigest.php

***

# Demographic Review

Selected reviews from *Demographic Digest* are reprinted in Russian academic journal *[Demographic Review][demrev]* and are in open access. Below are the links to all publications of Demographic Digest in *Demographic Review*, in **year-issue** format.

[demrev]: https://demreview.hse.ru/en/

|------------------|------------------|------------------|------------------|
|                  |                  | [[2015-3][153]]  | [[2015-4][154]]  |
| [[2016-1][161]]  | [[2016-2][162]]  | [[2016-3][163]]  | [[2016-4][164]]  |
| [[2017-1][171]]  | [[2017-2][172]]  | [[2017-3][173]]  |                  |

[153]: https://demreview.hse.ru/2015--3/174844051.html
[154]: https://demreview.hse.ru/2015--4/179986337.html
[161]: https://demreview.hse.ru/2016--1/185829684.html
[162]: https://demreview.hse.ru/2016--2/190973840.html
[163]: https://demreview.hse.ru/2016--3/196886615.html
[164]: https://demreview.hse.ru/2016--4/202163189.html
[171]: https://demreview.hse.ru/2017--1/206925692.html
[172]: https://demreview.hse.ru/2017--2/210565796.html
[173]: https://demreview.hse.ru/2017--3/212768468.html

***

# Participation of HSE students

Since 2016 *Demographic Digest* welcomes contributions from external authors. In February 2017 we launched a permanent research project for the students of National Research University Higher School of Economics using the university's platform [Project Fair][pfair]. So far, there have been 5 waves of the project: [one][one], [two][two], [three][three], [four][four], [five][five].

[pfair]: https://pf.hse.ru
[one]: https://www.hse.ru/org/hse/pfair/199751652.html
[two]: https://pf.hse.ru/204830140.html
[three]: https://pf.hse.ru/207849207.html
[four]: https://pf.hse.ru/211202187.html
[five]: https://pf.hse.ru/214092077.html

### Here are the participated students:

|------------------|--------------------------------------------------------|
| ![][a01]         | Maria Vilkova                                          |
| ![][a02]         | Olesya Kliushina                                       |
| ![][a03]         | Anna Levina                                            |
| ![][a04]         | Julia Lonshchikova                                     |
| ![][a05]         | Natalia Klimenko                                       |
| ![][a06]         | Anna Bezhanishvili                                     |
| ![][a07]         | Danil Arakelyan                                        |
| ![][a08]         | Nikita Gandzha                                         |
| ![][a09]         | Sophia Akhmanayva                                      |
| ![][a10]         | Irina Zamishchak                                       |
| ![][a11]         | Galina Mankova                                         |
| ![][a12]         | Vadim Khryukov                                         |

[a01]: /dem-digest/images/bio-maria-vilkova.jpg
{: height="80px" width="80px"}
[a02]: /dem-digest/images/bio-olesya-kliushina.jpg
{: height="80px" width="80px"}
[a03]: /dem-digest/images/bio-anna-levina.jpg
{: height="80px" width="80px"}
[a04]: /dem-digest/images/bio-julia-lonshchikova.jpg
{: height="80px" width="80px"}
[a05]: /dem-digest/images/bio-natalia-klimemko.jpg
{: height="80px" width="80px"}
[a06]: /dem-digest/images/bio-anna-bezhanishvili.jpg
{: height="80px" width="80px"}
[a07]: /dem-digest/images/bio-danil-arakelyan.jpg
{: height="80px" width="80px"}
[a08]: /dem-digest/images/bio-nikita-gandzha.jpg
{: height="80px" width="80px"}
[a09]: /dem-digest/images/bio-sophia-akhmanayva.jpg
{: height="80px" width="80px"}
[a10]: /dem-digest/images/bio-irina-zamishchak.jpg
{: height="80px" width="80px"}
[a11]: /dem-digest/images/bio-galina-mankova.jpg
{: height="80px" width="80px"}
[a12]: /dem-digest/images/bio-vadim-khryukov.jpg
{: height="80px" width="80px"}

repository: ikashnitsky/dem-digest

repo_name: ikashnitsky/dem-digest


text:
# MoonPhaseView

MoonPhaseView is a custom UIVew used in iOS which will draw a shadow over a moon image. It was used for a talk on IBDesignable and IBInspectable. When used in Interface Builder in Xcode (version 6 or greater) you can modify the following parameters on the fly:
* Moon phase - number from 0.0 to 1.0 where 0.0 is new moon, 0.5 is full moon, and 1.0 is back to new moon.
* Shadow alpha - opacity of the shadow, 0.6 is about where I like it. range 0.0 to 1.0.
* Shadow color - tint of the shadow. Could have used the alpha from the color but 1) really added color to show it in IB and 2) it's more likely the shadow opacity is what is being changed more so there is easier access with 2 parameters.

## Legal

MIT license


text:
[https://bower.io/](https://bower.io/)

search bower packages

```
https://bower.io/search/
```

install bower

```
npm install -g bower
```

install packages

```
bower install <package>
```

```
# installs the project dependencies listed in bower.json
bower install
# registered package
bower install jquery
# GitHub shorthand
bower install desandro/masonry
# Git endpoint
bower install git://github.com/user/package.git
# URL
bower install http://example.com/script.js
```

## install frontend package with bower

$ bower install jsgrid --save

[with bower.json]
$ bower install

repository: loggar/node

gha_language: JavaScript

repo_name: loggar/node


text:
# rxjs-reactive-state: Reactive State with RxJS

RxJS powered state management library for Reactive Applications implementing observable store. Go to https://github.com/ramartinez7/angular-observable-store to see a full implementation in an use case with Angular (under construction).

### Installation

```sh
npm i rxjs-reactive-state --save
```

Extension recommended: Auto Import, link: https://marketplace.visualstudio.com/items?itemName=steoates.autoimport

### API
The classes are strongly-typed so you will have a lot of help of intellisense in VS Code. Exist two main classes: Store < T > and EntityStore<S extends EntityState<T>, T> extends Store<S

```sh
  Store<T> where T is your state class, example:
```

![configure Store](images/1.png "Configuring store")

| type | name | description | Example |
| ------ | ------ | ------ | ------ |
| property | observer$ | Observable state |
| property | state | State value
| property | logActions | Wheter log actions in console or not
| method | change | Change state value | this.store.change({ products: products }), this.store.change(state => ({...}))
| method | listen | Listen to changes in state | this.store.listen(), this.store.listen(state => state.entities), this.store.listen('products'), this.store.listen(['name', 'email'])
| method | destroy | Completes the store subject.

```sh
  EntityStore<S extends EntityState<T>, T> extends Store<S>, you have to set the entity-state and entity class, example:
```

![configure Entity Store](images/2.png "Configuring entity-store")

```sh
  EntityState<T> class looks like this
```
![EntityState class](images/3_1.png "entitystate class")

EntityStore class extends the properties and methods from Store class. Also,

| type | name | description | Example |
| ------ | ------ | ------ | ------ |
| method | add | adds one or many items to the entities property  | this.store.add(product)
| method | update | updates one property in the entities property, recieves a function with a boolean expression to find the element to update and the new element | this.store.update(product => product.id === 1, new Product())
| method | remove | remove an element from the entities property, recieves a function to find the element  | this.store.remove(product => product.id === 1)
| method | exists | Verifies if an element exists in the entities property, recieves a function to search the element | this.store.exists(product => product.id === 1)
| method | setAction | Sets the current action, recieves a string and by default starts with LOADING status |  this.store.setAction(ProductActions.GET_ALL);
| method | setStatus | Set the state of the current action (LOADING, SUCCESS, FAILED, COMPLETE) | this.store.setStatus(Status.FAILED)

```sh
  Actions and Status
```

To control changes to the state you can use Actions and Status, example:

![Configure actions and status](images/4.png "entitystate class")

Here you must use the Status enum imported from the package.

Submit an issue or fork the project to improve it. Soon I'll be posting more info about the implementation of the library.
Go to https://github.com/ramartinez7/angular-observable-store to see a full implementation in an use case with Angular (under construction).


text:
# CONTRIBUTING

Contributions are always welcome, no matter how large or small. Before contributing,
please read the [code of conduct](CODE_OF_CONDUCT.md).

## Setup

```sh
$ git clone https://github.com/netlify/victor-hugo
$ cd victor-hugo
$ npm install
```

## Building

```sh
$ npm run build
```

## Testing

```sh
$ npm run test
```

```sh
$ npm run test:watch
```

## Running the server

```sh
$ npm run start
```

## Pull Requests

We actively welcome your pull requests.

1. Fork the repo and create your branch from `master`.
2. If you've added code that should be tested, add tests.
3. If you've changed APIs, update the documentation.
4. Ensure the test suite passes.
5. Make sure your code lints.

## License

By contributing to Victor-Hugo, you agree that your contributions will be licensed
under its [MIT license](LICENSE).

repository: talentdmrripley/hugo-half-lifed

gha_language: CSS

repo_name: talentdmrripley/hugo-half-lifed


text:
# Release History

## SNAPSHOT

## release 0.82.2
* ** [edision-mongo] use version of mongo driver to 3.4.1, fongo 2.0.11

## release 0.82.1
* **[edison-jobs]** add _primaryPreferred_ for jobRepository to avoid data loss while updating a jobState

## release 0.82.0
* **[edison-jobs]** Show only latest 10 jobs in Job Overview by default

## release 0.81.0
* **[edison-mongo]** Allow configuration of mongo read preference by setting the property `edison.mongo.readPreference`. The default configuration is primary.

## release 0.80.0
* **[edison-service]** Make edison-service independent of other edison packages
  - This might break your build because you did not write your project dependencies explicitly in
    your build script. Just add the missing edison packages and everything will be fine.
* **[edison-cache]** Allow CacheInfoController to be disabled

## release 0.79.3
* **[edison-cache]** Allow registering custom built caches via `CacheRegistry` to gather cache metrics

## release 0.79.2
* **[edison-mongo]** Bugfix: AbstractMongoRepository does not accept null as ID of objects anymore.

## Release 0.79.1
* **[edison]** Upgrade thymeleaf to version 3.0.2.RELEASE
* **[edison-jobs]** jobdetails page uses div tags instead of spans

## Release 0.79.0
* **[edison]** Upgrade spring boot to 1.4.2.RELEASE
* **[edison]** Upgrade spring version to 4.3.4.RELEASE
* **[edison]** Upgrade guava version to 20.0
* **[edison]** Upgrade caffeine version to 2.3.5
* **[edison]** Upgrade async http client to 1.9.40

## Release 0.78.0
* **[edison-mongo]** Support streaming for findAll methods. The old methods are deprecated now, so please use the new ones.

## Release 0.77.0
* **[edison-service]** Make edison-cache the default caching behaviour

## Release 0.76.1
* **[edison-jobs]** KeepLastJobs is not loading Job messages anymore, avoiding OutOfMemory errors
for lots of large jobs.

## Release 0.76.0
* **[edison-mongo]** Make AbstractRepository.byId() and AbstractRepository.matchAll() non final again
* **[edison-guava]** Make edison-guava deprecated in favor of the new and shiny edison-cache
* **[edison-cache]** Create edison-cache with support for Caffeine caches instead of Guava

## Release 0.75.0
* [edison-jobs],[edison-mongo] Add setJobStatus and setLastUpdate to JobRepository interface and both
  implementations - This fixes a race condition during keepalive and message.
  This is a **breaking change** if you wrote your own JobRepository.

## Release 0.74.0
* Removed dependency to edison-hal (was introduced for testing purposes only).
* Removed usage of testng and replaced it by Junit

## Release 0.73.0
* [edison-mongo] Refactored AbstractRepository.update() which returns an boolean now.
* [edison-mongo] **Breaking change:** UpdateIfMatch returns an enum (UpdateIfMatchResult) instead of throwing undocumented exceptions.
                 To migrate, you have to remove the exception handling and evaluate the return code to handle it properly.
* [edison-mongo] Removed NotFoundException from edison-mongo
* [edison-jobs] Log job errors.

## Release 0.72.1
* Add some logging information

## Release 0.72.0
* Upgrade Spring Boot to 1.4.0-RELEASE
* Upgrade Spring to 4.3.2-RELEASE
* Add spring-boot-starter-test dependency for @SpringBootTest annotation

 * IMPORTANT: Please follow the Migration Guide on
 https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-1.4-Release-Notes
 when upgrading an existing service to this Edison Microservice version

## Release 0.71.0
* Upgrade mongodb-driver to 3.3.0
* Upgrade togglz to 2.3.0.Final
* Reduce default shutdown period from 30 to 25 seconds

## Release 0.70.0
* do not show distinct jobs if type is given
* optimize createOrUpdate in AbstractMongoRepository by using upsert

## Release 0.69.1
* Job Overview shows distinct jobs as default (old behaviour can be activated via distinct=false parameter)
* Add possibility to add slf4j markers to jobevents

## Release 0.69.1
* Status page header and title configurable via property `edison.status.application.title`
* Add time of start/stop to job status detail

## Release 0.69.0
* Add JobEvents class. Use it to avoid handing a JobEventPublisher to helper classes of a Job.
* Indicate job errors with configured mapping in application status (default is ERROR).
  The property name is `edison.jobs.status.indicate-joberror-with-level`, possible values are `OK`, `WARNING` and `ERROR`

## Release 0.68.1
* Hide feature toggles menu entry if feature toggles UI is disabled

## Release 0.68.0
* Introduced dependency to github.com/otto-de/edison-hal
* Added media type application/hal+json for /internal/status
* indicate job errors as application error instead of warning
* Catch and log RuntimeExceptions that may occur while persisting JobMessages and StateChanges

## Release 0.67.0
* Fix circular dependencies in JobConfiguration
* Update to latest Spring Boot version
* Update outdated dependencies

## Release 0.66.2
* Fix NullPointerException in disableJobs Feature

## Release 0.66.1
* Add possibility to temporarily disable jobs via the jobdefinitions GUI
* Fix ClearDeadLocks Cleanup: Also clear a lock if the JobId does not exist anymore.

## Release 0.65.0
* Add `ClearDeadLocks` Cleanup Strategy.
* *BREAKING CHANGE* : `JobRepository` Add method `runningJobsDocument`. Changed signature of `markJobAsRunningIfPossible`

## Release 0.64.0
* Add parameter distinct=true|false to jobcontroller to get only the latest of each jobs in the overview

## Release 0.63.0
* Cronexpressions of JobDefinitions are evaluated on construction of a JobDefinition
* Bugfix: JobLocks are now properly released when Jobs are marked dead.
* Optimization of JobLocking.
* Breaking Change: `JobRepository` interface: add methods `markAsRunningIfPossible` and `clearRunningMark`. Delete unused methods.
* Breaking Change: `StopDeadJobs` constructor now needs a `JobService` and a `JobRepository`. Those can be obtained by autowiring.

## Release 0.62.0
* JobInfo is immutable, this is a breaking change, use the JobInfo.builder() instead

## Release 0.61.0
* Modified Mutex Behavior. The new MutexHandler is now able to use a mongoJobLockProvider which persists the
  mutex-handling in the database. That prevents raceconditions if two jobs of the same type or in the same group should
  be started at the same time.
* Fixed representation of feature toggles to be consistent with
  status mediatype.
* Moved html representation of feature toggles from /internal/togglz
  to /internal/toggles/console
* Moved json representation of feature toggles from /internal/status/togglz
  to /internal/toggles

## Release 0.60.0
* added MetricsFilter to provide counters for http requests

## Release 0.59.0
* upgrade spring boot to 1.3.5.RELEASE
* upgrade spring to 4.2.6.RELEASE

## Release 0.58.1
* edison-togglz: Fixed a bug in the LDAP authentication filter
* edison-togglz-mongo: Log name of the user switching a toggle also in the mongo state repository

## Release 0.58.0
* edison-togglz: added optional LDAP authentication

## Release 0.57.2
* Small bugfix: Fix job detail URL in jobs template

## Release 0.57.1
* set the /internal/jobs/ in the URL of the Location header

## Release 0.57.0
* The JobIds do not contain slashes any more, (/internal/jobs/ is not part of the jobIds)
* Note that jobs which were persisted with older releases might not be accessible any more after the upgrade.
* Also note that some jobs might show up with a red status on your dashboard after the upgrade. Simply rerun the job to
  fix this.

## Release 0.56.3
* togglz: FilterRegistrationBean in TogglzWebConfiguration uses filter name "togglzFilter"

## Release 0.56.2
* edison-jobs-(mongo): Moved handling of persisting error status to PersistenceJobEventListener

## Release 0.56.1
+ Bugfix: Do not aggregate application status in constructor. Use @PostConstruct instead

## Release 0.56.0
* New Feature: Mutually exclusion of jobs using JobMutexGroups

## Release 0.55.2
* JobDefinition show fixedDelay in seconds if minutes would be zero

## Release 0.55.1
* Set job status to error after receiving an error message
* Make mongo codec registry configurable

## Release 0.55.0
* Optimized handling of persisting job messages
* add serverSelectionTimeout (default 30secs) to mongo config

## Release 0.54.1
* JobStatusDetailIndicator: Indicate error if job could not be retrieved from the repository

## Release 0.54.0
* Keep last jobs strategy now keeps the last N jobs of each type
* Create indices in jobs collection
* Return DeleteResult of mongo delete queries

## Release 0.53.1
* edison-jobs-mongo: Create index on jobtype and started to sort jobs by date when all job documents are bigger then 32MB

## Release 0.52.2
* edison-metrics: Refactored auto configuration of `LoadDetector` to allow strategy selection by `application.properties` as well as exposing your own bean the same time

## Release 0.52.1
* Refactored load indication (see 0.52.0) from edison-status to edison-metrics and introduced new endpoint `/internal/load` which returns the load status to be used by consumers (ie. auto-scaling drivers). See `example-metrics` for an usage example on average response time behaviour.

## Release 0.52.0
* Added status indicator allowing the application to signal overload (see `LoadStatusIndicator`), which enables ie. watchers to autoscale the application accordingly
* two default strategies to discover load, one making use of metrics library, allowing to leverage `@Timed` annotations on your classes  (see `application.properties` in `example-status`)
* Fixed behaviour of application status aggregation to provide instant calculation instead of waiting until first update has ran

## Release 0.51.1
* Updated to Spring Boot 1.3.3 (with Spring 4.2.5)

## Release 0.51.0
* edison-guava: Refactored edison-guava. Guava caches can now be configured using GuavaCacheConfig. These caches will
now expose cache statistics as /internal/metrics (JSON) and /internal/caches/statistics (HTML).
See edison-guava/README.md for more details on how to use Guava caches.
* edison-metrics: Fixed package name (...metrics instead of ...health)

## Release 0.50.3
* Housekeeping: Updated Spring Boot to version 1.3.2, MongoDB driver to 3.2.2 and Logback to 1.1.5

## Release 0.50.2
* edison-status: Added status to /internal/status.html

## Release 0.50.1
* edison-jobs: Bug-Fix in find implementations to limit search result after sorting has happened
* edison-jobs: Added method to find job instances by type and status

## Release 0.50.0
* Added InternalController that is redirecting requests from /internal to /internal/status. This can be disabled
by setting edison.status.redirect-internal.enabled=false

## Release 0.49.4
* Reverted: "removed unnecessary bean from togglz configuration" because embedded containers in Spring Boot don't scan web-fragments

## Release 0.49.3
* removed unnecessary bean from togglz configuration
* Extended `JobService` to cover also synchronous job execution

## Release 0.49.2
* Fix error on job page for long-running jobs
* Job Lifecycle: set hostname via SystemInfo (to overcome problems on Mesos)

## Release 0.49.1
* Added field `hostname` to JobInfo, which allows to track on which server the job gets executed
* Updated dependencies: async-http-client (to 1.9.32) and mongodb-driver (to 3.2.1)

## Release 0.49.0
* Removed unneeded appId from ServiceSpec and ApplicationInfo
* Fixed path in navigation from /internal to /internal/status
* Using edison.status.application.environment + .group instead of edison.servicediscovery.environment + .group.
The properties edison.servicediscovery.environment and edison.servicediscovery.group
can be removed from application.properties/.yml

## Release 0.48.0
* VCS information are now expected in edison.status.vcs.* instead of info.build.*. Change in build.gradle required
* Added ServiceSpecs to be able to specify dependencies to other services
* Added TeamInfo to the /internal/status
* Added environment, group and appId to /internal/status

## Release 0.47.2
* Added convenience methods to `JobEventPublisher` to make logging more fun again
* Updated spring-boot to version 1.3.1.
* Update to org.springframework.boot:spring-boot-starter-thymeleaf:1.3.1.RELEASE required

## Release 0.47.1
* Fixed bug in navigation: broken path to bootstrap css

## Release 0.47.0
* Added some more information to /internal/status
* Fixed the format of the status JSON
* Update to com.github.fakemongo:fongo:2.0.4 required

## Release 0.46.2
* Removed StateChangeEvent.State.CREATE, replaced it by START
* Renamed State.STILL_ALIVE to KEEP_ALIVE
* Job HTML templates are now using the Thymeleaf navigation fragments so µServices have a common menu on all pages.

## Release 0.46.1
* Minor refactorings in handling of job events.

## Release 0.46.0
* Rebuild job state architecture due to introduce an event bus to separate the JobInfo and the
  JobRepository. From now on the JobRunner and the specific jobs will report changes (states and messages) to
  an EventPublisher, which will propagate the events to the JobEventListeners (e.g. persist them or log them).
  You can register your own JobEventListeners. The JobMonitor is removed.
 Then the job will be retriggered (if retry configured).

## Release 0.45.3
* Fixed default JobMonitor to save log messages in JobRepository for every message.

## Release 0.45.2
* Minor bugfixes
* Using Guava CacheStats in CacheStatistics

## Release 0.45.1

New Features:
* Show the runtime of the job to identify the complete exports with actions.
* Format details in status.json to camel case key names

## Release 0.45.0

New Features:
* Broken Jobs are automatically restarted according to the number of retries specified in the `JobDefintion`.
* `JobDefinition` now has a new field `restarts`, specifying how often a job is restarted if it failed because of an error.

Breaking Changes:
* Renamed libraries: all libs now have the prefix "edison-".
* The factory methods of the `DefaultJobDefinition` now have an additional parameter for the number of restarts.
* Every `JobRunnable` now needs to provide a `JobDefinition`
* Removed `JobRunnable#getJobType`. The job type is accessed by the `JobDefinition`
* Renamed to `DefaultJobDefinition#notTriggerableJobDefinition` to `manuallyTriggerableJobDefinition` to clarify purpose
* Removed hystrix module

## Release 0.44.0

New Features:
* MongoDB persistence: Allow to retrieve the object (including key) when it is created.
  Changed signature of `create` and  `createOrUpdate` in `AbstractMongoRepository`
  to return the object instead of void

Bug Fixes:
* Allow also a value without key to be given to `AbstractMongoRepository#createOrUpdate` without throwing a NPE
* `application.properties`: renamed ``edison.application.name`` (introduced in Release 0.35.0) back into `spring.application.name`
  (see [ContextIdApplicationContextInitializer](https://github.com/spring-projects/spring-boot/blob/v1.3.0.RELEASE/spring-boot/src/main/java/org/springframework/boot/context/ContextIdApplicationContextInitializer.java)
  for details on identifying your application)
* Added dummy feature toggle implementations (for `FeatureClassProvider`) to example projects, which can now
  be run on its own again (ie. `gradle example-jobs:bootRun`)

## Release 0.43.0
* Updated spring-boot to version [1.3.0](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-1.3-Release-Notes), hystrix to 1.4.21 and metrics library dependency to 3.1.3

## Release 0.40.0
* Update togglz library to 2.2.0

## Release 0.39.2
* Cleaned up link construction on internal status and job pages
* Timestamps in JSON status representation are now in ISO-8601 date format (including timezone)

## Release 0.39.1
* Fixed possible broken links on /internal pages

## Release 0.39.0
* Added servicediscovery-client to edison-microservice
* ServiceDiscovery is only used if edison.servicediscovery.* properties are available

## Release 0.38.0
* JobDefinitions extended to support jobs that are not triggered automatically.

## Release 0.37.0
* Fixed links on internal pages

## Release 0.35.0

New Features:
* New library servicediscovery-client introduced to provide basic ServiceDiscovery features for Edison Microservices.
This lib may be used to register services at an Edison JobTrigger.

Bug Fixes:
* Fixed possible ConcurrentModificationException if job messages are accessed from JobInfo.

Breaking Changes:
* application.properties is now using server.context-path instead of server.contextPath.
* application.properties is now using edison.application.name instead of application.name.

## Release 0.34.0
* Added ID to panel with job messages for identification in JobTrigger

## Release 0.33.0
* Added UIs for Status pages
* Nicer internal pages, including reworked jobs and job-definitions

## Release 0.29.0

New Features:
* Prepared integration with (upcoming) Edison JobTrigger
* Added Bootstrap UIs for Jobs and /internal
* Added edison-service for typical microservices, including jobs, health, status,
* Using webjars in edison-service to include bootstrap and jquery

Breaking Changes:
* The format of job definitions and jobs has changed.

## Release 0.28.2

Bugs fixed:
* Fixed critical bug that prevented the startup of the server in combination with usage of edison jobs-mongo

## Release 0.28.1

Bugs fixed:
* Fixed bugs that prevented the StatusDetails of jobs to be added to status page.

## Release 0.28.0

New Features:
* Jobs are rendered with absolute URLs in JSON and HTML representations.
* Introduced the (optional) concept of JobDefinitions to describe the expected frequency etc. to trigger jobs.
* Based on the JobDefinitions, for every Job a StatusDetailIndicator is registered automatically. This may be
disabled by either not providing a JobDefinition, or by setting property edison.jobs.status.enabled=false

Breaking Changes:
* Jobs in earlier version where identified by the URI of the job including the servlet context path. Starting with
this version, the context path is not part of the identifier anymore. You should DELETE all old jobs, otherwise
the URLs a broken.
* Job representations now contain the full URL of the jobs instead of relative URIs.

repository: waffle-iron/edison-microservice

repo_name: waffle-iron/edison-microservice


text:
---
metaTitle: "Java - Operators"
description: "The Increment/Decrement Operators (++/--), The Conditional Operator (? :), The Bitwise and Logical Operators (~, &, |, ^), The String Concatenation Operator (+), The Arithmetic Operators (+, -, *, /, %), The Instanceof Operator, The Assignment Operators (=, +=, -=, *=, /=, %=, <<=, >>= , >>>=, &=, |= and ^=), The conditional-and and conditional-or Operators ( && and || ), The Shift Operators (<<, >> and >>>), The Equality Operators (==, !=), The Lambda operator ( -> ), The Relational Operators (<, <=, >, >=)"
---

# Operators

[Operators](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html) in Java programming language are special symbols that perform specific operations on one, two, or three operands, and then return a result.

## The Increment/Decrement Operators (++/--)

Variables can be incremented or decremented by 1 using the `++` and `--` operators, respectively.

When the `++` and `--` operators follow variables, they are called **post-increment** and **post-decrement** respectively.

```java
int a = 10;
a++; // a now equals 11
a--; // a now equals 10 again

```

When the `++` and `--` operators precede the variables the operations are called **pre-increment** and **pre-decrement** respectively.

```java
int x = 10;
--x; // x now equals 9
++x; // x now equals 10

```

If the operator precedes the variable, the value of the expression is the value of the variable after being incremented or decremented. If the operator follows the variable, the value of the expression is the value of the variable prior to being incremented or decremented.

```java
int x=10;

System.out.println("x=" + x + " x=" + x++ + " x=" + x); // outputs x=10 x=10 x=11
System.out.println("x=" + x + " x=" + ++x + " x=" + x); // outputs x=11 x=12 x=12
System.out.println("x=" + x + " x=" + x-- + " x=" + x); // outputs x=12 x=12 x=11
System.out.println("x=" + x + " x=" + --x + " x=" + x); // outputs x=11 x=10 x=10

```

Be careful not to overwrite post-increments or decrements. This happens if you use a post-in/decrement operator at the end of an expression which is reassigned to the in/decremented variable itself. The in/decrement will not have an effect. Even though the variable on the left hand side is incremented correctly, its value will be immediately overwritten with the previously evaluated result from the right hand side of the expression:

```java
int x = 0;
x = x++ + 1 + x++;      // x = 0 + 1 + 1
                        // do not do this - the last increment has no effect (bug!)
System.out.println(x);  // prints 2 (not 3!)

```

Correct:

```java
int x = 0;
x = x++ + 1 + x;        // evaluates to x = 0 + 1 + 1
x++;                    // adds 1
System.out.println(x);  // prints 3

```

## The Conditional Operator (? :)

### Syntax

**{condition-to-evaluate}** **?** **{statement-executed-on-true}** **:** **{statement-executed-on-false}**

As shown in the syntax, the Conditional Operator (also known as the Ternary Operator1) uses the `?` (question mark) and `:` (colon) characters to enable a conditional expression of two possible outcomes. It can be used to replace longer `if-else` blocks to return one of two values based on condition.

```java
result = testCondition ? value1 : value2

```

Is equivalent to

```java
if (testCondition) {
    result = value1;
} else {
    result = value2;
}

```

It can be read as ****“If testCondition is true, set result to value1; otherwise, set result to value2”.****

For example:

```java
// get absolute value using conditional operator
a = -10;
int absValue = a < 0 ? -a : a;
System.out.println("abs = " + absValue); // prints "abs = 10"

```

Is equivalent to

```java
// get absolute value using if/else loop
a = -10;
int absValue;
if (a < 0) {
    absValue = -a;
} else {
    absValue = a;
}
System.out.println("abs = " + absValue); // prints "abs = 10"

```

### Common Usage

You can use the conditional operator for conditional assignments (like null checking).

```java
String x = y != null ? y.toString() : ""; //where y is an object

```

This example is equivalent to:

```java
String x = "";

if (y != null) {
    x = y.toString();
}

```

Since the Conditional Operator has the second-lowest precedence, above the [Assignment Operators](http://stackoverflow.com/documentation/java/176/operators/12239/the-assignment-operators-and), there is rarely a need for use parenthesis around the **condition**, but parenthesis is required around the entire Conditional Operator construct when combined with other operators:

```java
// no parenthesis needed for expressions in the 3 parts
10 <= a && a < 19 ? b * 5 : b * 7

// parenthesis required
7 * (a > 0 ? 2 : 5)

```

Conditional operators nesting can also be done in the third part, where it works more like chaining or like a switch statement.

```java
a ? "a is true" :
b ? "a is false, b is true" :
c ? "a and b are false, c is true" :
    "a, b, and c are false"

//Operator precedence can be illustrated with parenthesis:

a ? x : (b ? y : (c ? z : w))

```

Footnote:

1 - Both the [Java Language Specification](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25) and the [Java Tutorial](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html) call the (`? :`) operator the **Conditional Operator**.  The Tutorial says that it is "also known as the Ternary Operator" as it is (currently) the only ternary operator defined by Java.  The "Conditional Operator" terminology is consistent with C and C++ and other languages with an equivalent operator.

## The Bitwise and Logical Operators (~, &, |, ^)

The Java language provides 4 operators that perform bitwise or logical operations on integer or boolean operands.

- The complement (`~`) operator is a unary operator that performs a bitwise or logical inversion of the bits of one operand; see [JLS 15.15.5.](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.15.5).
- The AND (`&`) operator is a binary operator that performs a bitwise or logical "and" of two operands; see [JLS 15.22.2.](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22.2).
- The OR (`|`) operator is a binary operator that performs a bitwise or logical "inclusive or" of two operands; see [JLS 15.22.2.](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22.2).
- The XOR (`^`) operator is a binary operator that performs a bitwise or logical "exclusive or" of two operands; see [JLS 15.22.2.](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22.2).

The logical operations performed by these operators when the operands are booleans can be summarized as follows:

|A|B|~A|A & B|A | B|A ^ B
|---|---|---|---|---|---|---|---|---|---
|0|0|1|0|0|0
|0|1|1|0|1|1
|1|0|0|0|1|1
|1|1|0|1|1|0

Note that for integer operands, the above table describes what happens for individual bits.  The operators actually operate on all 32 or 64 bits of the operand or operands in parallel.

### Operand types and result types.

The usual arithmetic conversions apply when the operands are integers.
Common use-cases for the bitwise operators

The `~` operator is used to reverse a boolean value, or change all the bits in an integer operand.

The `&` operator is used for "masking out" some of the bits in an integer operand.  For example:

```java
int word = 0b00101010;
int mask = 0b00000011;   // Mask for masking out all but the bottom
                         // two bits of a word
int lowBits = word & mask;            // -> 0b00000010
int highBits = word & ~mask;          // -> 0b00101000

```

The `|` operator is used to combine the truth values of two operands.  For example:

```java
int word2 = 0b01011111;
// Combine the bottom 2 bits of word1 with the top 30 bits of word2
int combined = (word & mask) | (word2 & ~mask);   // -> 0b01011110

```

The `^` operator is used for toggling or "flipping" bits:

```java
int word3 = 0b00101010;
int word4 = word3 ^ mask;             // -> 0b00101001

```

For more examples of the use of the bitwise operators, see [Bit Manipulation](http://stackoverflow.com/documentation/java/1177/bit-manipulation#t=201610101439344327372)

## The String Concatenation Operator (+)

The `+` symbol can mean three distinct operators in Java:

- If there is no operand before the `+`, then it is the unary Plus operator.
- If there are two operands, and they are both numeric. then it is the binary Addition operator.
- If there are two operands, and at least one of them is a `String`, then it it the binary Concatenation operator.

In the simple case, the Concatenation operator joins two strings to give a third string.  For example:

```java
String s1 = "a String";
String s2 = "This is " + s1;    // s2 contains "This is a String"

```

When one of the two operands is not a string, it is converted to a `String` as follows:

An operand whose type is a primitive type is converted **as if** by calling `toString()` on the boxed value.

An operand whose type is a reference type is converted by calling the operand's `toString()` method.  If the operand is `null`, or if the `toString()` method returns `null`, then the string literal `"null"` is used instead.

For example:

```java
int one = 1;
String s3 = "One is "  + one;         // s3 contains "One is 1"
String s4 = null + " is null";        // s4 contains "null is null"
String s5 = "{1} is " + new int[]{1}; // s5 contains something like
                                      // "{} is [I@xxxxxxxx"

```

The explanation for the `s5` example is that the `toString()` method on array types is inherited from `java.lang.Object`, and the behavior is to produce a string that consists of the type name, and the object's identity hashcode.

The Concatenation operator is specified to create a new `String` object, except in the case where the expression is a Constant Expression.  In the latter case, the expression is evaluated at compile type, and its runtime value is equivalent to a string literal.  This means that there is no runtime overhead in splitting a long string literal like this:

```java
String typing = "The quick brown fox " +
                "jumped over the " +
                "lazy dog";           // constant expression

```

### Optimization and efficiency

As noted above, with the exception of constant expressions, each string concatenation expression creates a new `String` object.  Consider this code:

```java
public String stars(int count) {
    String res = "";
    for (int i = 0; i < count; i++) {
        res = res + "*";
    }
    return res;
}

```

In the method above, each iteration of the loop will create a new `String` that is one character longer than the previous iteration.  Each concatenation copies all of the characters in the operand strings to form the new `String`.  Thus, `stars(N)` will:

- create `N` new `String` objects, and throw away all but the last one,
- copy `N * (N + 1) / 2` characters, and
- generate `O(N^2)` bytes of garbage.

This is very expensive for large `N`.  Indeed, any code that concatenates strings in a loop is liable to have this problem.  A better way to write this would be as follows:

```java
public String stars(int count) {
    // Create a string builder with capacity 'count'
    StringBuilder sb = new StringBuilder(count);
    for (int i = 0; i < count; i++) {
        sb.append("*");
    }
    return sb.toString();
}

```

Ideally, you should set the capacity of the `StringBuilder`, but if this is not practical, the class will automatically **grow** the backing array that the builder uses to hold characters.  (Note: the implementation expands the backing array exponentially.  This strategy keeps that amount of character copying to a `O(N)` rather than `O(N^2)`.)

Some people apply this pattern to all string concatenations.  However, this is unnecessary because the JLS **allows** a Java compiler to optimize string concatenations within a single expression.  For example:

```java
String s1 = ...;
String s2 = ...;
String test = "Hello " + s1 + ". Welcome to " + s2 + "\n";

```

will **typically** be optimized by the bytecode compiler to something like this;

```java
StringBuilder tmp = new StringBuilder();
tmp.append("Hello ")
tmp.append(s1 == null ? "null" + s1);
tmp.append("Welcome to ");
tmp.append(s2 == null ? "null" + s2);
tmp.append("\n");
String test = tmp.toString();

```

(The JIT compiler may optimize that further if it can deduce that `s1` or `s2` cannot be `null`.)  But note that this optimization is only permitted within a single expression.

In short, if you are concerned about the efficiency of string concatenations:

- Do hand-optimize if you are doing repeated concatenation in a loop (or similar).
- Don't hand-optimize a single concatenation expression.

## The Arithmetic Operators (+, -, *, /, %)

The Java language provides 7 operators that perform arithmetic on integer and floating point values.

There are two `+` operators:

- The binary addition operator adds one number to another one.  (There is also a binary `+` operator that performs string concatenation. That is described in a separate example.)
- The unary plus operator does nothing apart from triggering numeric promotion (see below)

- The binary subtraction operator subtracts one number from another one.
- The unary minus operator is equivalent to subtracting its operand from zero.

1. This is often incorrectly referred to as the "modulus" operator. "Remainder" is the term that is used by the JLS. "Modulus" and "remainder" are not the same thing.

### Operand and result types, and numeric promotion

The operators require numeric operands and produce numeric results.  The operand types can be any primitive numeric type (i.e. `byte`, `short`, `char`, `int`, `long`, `float` or `double`) or any numeric wrapper type define in `java.lang`; i.e. (`Byte`, `Character`, `Short`, `Integer`, `Long`, `Float` or `Double`.

The result type is determined base on the types of the operand or operands, as follows:

- If either of the operands is a `double` or `Double`, then the result type is `double`.
- Otherwise, if either of the operands is a `float` or `Float`, then the result type is `float`.
- Otherwise, if either of the operands is a `long` or `Long`, then the result type is `long`.
- Otherwise, the result type is `int`.  This covers `byte`, `short` and `char` operands as well as `int.

The result type of the operation determines how the arithmetic operation is performed, and how the operands are handled

- If the result type is `double`, the operands are promoted to `double`, and the operation is performed using 64-bit (double precision binary) IEE 754 floating point arithmetic.
- If the result type is `float`, the operands are promoted to `float`, and the operation is performed using 32-bit (single precision binary) IEE 754 floating point arithmetic.
- If the result type is `long`, the operands are promoted to `long`, and the operation is performed using 64-bit signed twos-complement binary integer arithmetic.
- If the result type is `int`, the operands are promoted to `int`, and the operation is performed using 32-bit signed twos-complement binary integer arithmetic.

Promotion is performed in two stages:

- If the operand type is a wrapper type, the operand value is **unboxed** to a value of the corresponding primitive type.

If necessary, the primitive type is promoted to the required type:

- Promotion of integers to `int` or `long` is loss-less.
- Promotion of `float` to `double` is loss-less.
- Promotion of an integer to a floating point value can lead to loss of precision.  The conversion is performed using IEE 768 "round-to-nearest" semantics.

### The meaning of division

The / operator divides the left-hand operand `n` (the **dividend**) and the right-hand operand `d` (the **divisor**) and produces the result `q` (the **quotient**).

Java integer division rounds towards zero.  The [JLS Section 15.17.2](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.2) specifies the behavior of Java integer division as follows:

>
The quotient produced for operands `n` and `d`  is an integer value `q` whose magnitude is as large as possible while satisfying `|d ⋅ q| ≤ |n|`. Moreover, `q` is positive when `|n| ≥ |d|` and `n` and `d` have the same sign, but `q` is negative when `|n| ≥ |d|` and `n` and `d` have opposite signs.

There are a couple of special cases:

- If the `n` is `MIN_VALUE`, and the divisor is -1, then integer overflow occurs and the result is `MIN_VALUE`. No exception is thrown in this case.
- If `d` is 0, then `ArithmeticException is thrown.

Java floating point division has more edge cases to consider.  However the basic idea is that the result `q` is the value that is closest to satisfying `d . q = n`.

Floating point division will never result in an exception.  Instead, operations that divide by zero result in an INF and NaN values; see below.

### The meaning of remainder

Unlike C and C++, the remainder operator in Java works with both integer and floating point operations.

For integer cases, the result of `a % b` is defined to be the number `r` such that `(a / b) * b + r` is equal to `a`, where `/`, `*` and `+` are the appropriate Java integer operators.  This applies in all cases except when `b` is zero.  That case, remainder results in an `ArithmeticException`.

It follows from the above definition that `a % b` can be negative only if `a` is negative, and it be positive only if `a` is positive. Moreover, the magnitude of `a % b` is always less than the magnitude of `b`.

Floating point remainder operation is a generalization of the integer case.  The result of `a % b` is the remainder `r` is defined by the mathematical relation `r = a - (b ⋅ q)` where:

- `q` is an integer,
- it is negative only if `a / b` is negative an positive only if `a / b` is positive, and
- its magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of `a` and `b`.

Floating point remainder can produce `INF` and `NaN` values in edge-cases such as when `b` is zero; see below.  It will not throw an exception.

Important note:

>
The result of a floating-point remainder operation as computed by `%` **is not the same** as that produced by the remainder operation defined by IEEE 754.  The IEEE 754 remainder may be computed using the `Math.IEEEremainder` library method.

### Integer Overflow

Java 32 and 64 bit integer values are signed and use twos-complement binary representation.  For example, the range of numbers representable as (32 bit) `int`  -231 through +231 - 1.

When you add, subtract or multiple two N bit integers (N == 32 or 64), the result of the operation may be too large to represent as an N bit integer.  In this case, the operation leads to **integer overflow**, and the result can be computed as follows:

- The mathematical operation is performed to give a intermediate two's-complement representation of the entire number.  This representation will be larger than N bits.
- The bottom 32 or 64 bits of the intermediate representation are used as the result.

It should be noted that integer overflow does not result in exceptions under any circumstances.

### Floating point INF and NAN values

Java uses IEE 754 floating point representations for `float` and `double`.  These representations have some special values for representing values that fall outside of the domain of Real numbers:

- The "infinite" or INF values denote numbers that are too large.  The `+INF` value denote numbers that are too large and positive.  The `-INF` value denote numbers that are too large and negative.
- The "indefinite" / "not a number" or NaN denote values resulting from meaningless operations.

The INF values are produced by floating operations that cause overflow, or by division by zero.

The NaN values are produced by dividing zero by zero, or computing zero remainder zero.

Surprisingly, it is possible perform arithmetic using INF and NaN operands without triggering exceptions.  For example:

- Adding +INF and a finite value gives +INF.
- Adding +INF and +INF gives +INF.
- Adding +INF and -INF gives NaN.
- Dividing by INF gives either +0.0 or -0.0.
- All operations with one or more NaN operands give NaN.

For full details, please refer to the relevant subsections of [JLS 15](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html).  Note that this is largely "academic".  For typical calculations, an `INF` or `NaN` means that something has gone wrong; e.g. you have incomplete or incorrect input data, or the calculation has been programmed incorrectly.

## The Instanceof Operator

This operator checks whether the object is of a particular class/interface type. **instanceof** operator is written as:

```java
( Object reference variable ) instanceof  (class/interface type)

```

Example:

```java
public class Test {

   public static void main(String args[]){
      String name = "Buyya";
      // following will return true since name is type of String
      boolean result = name instanceof String;
      System.out.println( result );
   }
}

```

This would produce the following result:

```java
true

```

This operator will still return true if the object being compared is the assignment compatible with the type on the right.

Example:

```java
class Vehicle {}

public class Car extends Vehicle {
   public static void main(String args[]){
      Vehicle a = new Car();
      boolean result =  a instanceof Car;
      System.out.println( result );
   }
}

```

This would produce the following result:

```java
true

```

## The Assignment Operators (=, +=, -=, *=, /=, %=, <<=, >>= , >>>=, &=, |= and ^=)

The left hand operand for these operators must be a either a non-final variable or an element of an array.  The right hand operand must be **assignment compatible** with the left hand operand.  This means that either the types must be the same, or the right operand type must be convertible to the left operands type by a combination of boxing, unboxing or widening.  (For complete details refer to [JLS 5.2](http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.2).)

The precise meaning of the "operation and assign" operators is specified by [JLS 15.26.2](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2) as:

>
A compound assignment expression of the form `E1 op= E2` is equivalent to `E1 = (T) ((E1) op (E2))`, where `T` is the type of `E1`, except that `E1` is evaluated only once.

Note that there is an implicit type-cast before the final assignment.

**1.   `=`**

The simple assignment operator: assigns the value of the right hand operand to the left hand operand.

>
Example: `c = a + b` will add the value of `a + b` to the value of `c` and assign it to `c`

**2.    `+=`**

The "add and assign" operator: adds the value of right hand operand to the value of the left hand operand and assigns the result to left hand operand. If the left hand operand has type `String`, then this a "concatenate and assign" operator.

>
Example: `c += a` is roughly the same as `c = c + a`

**3.    `-=`**

The "subtract and assign" operator: subtracts the value of the right operand from the value of the left hand operand and assign the result to left hand operand.

>
Example: `c -= a` is roughly the same as `c = c - a`

**4.    `*=`**

The "multiply and assign" operator: multiplies the value of the right hand operand by the value of the left hand operand and assign the result to left hand operand.  .

>
Example: `c *= a` is roughly the same as `c = c * a`

**5.    `/=`**

The "divide and assign" operator: divides the value of the right hand operand by the value of the left hand operand and assign the result to left hand operand.

>
Example: `c /*= a` is roughly the same as `c = c / a`

**6.    `%=`**

The "modulus and assign" operator: calculates the modulus of the value of the right hand operand by the value of the left hand operand and assign the result to left hand operand.

>
Example: `c %*= a` is roughly the same as `c = c % a`

**7.    `<<=`**

The "left shift and assign" operator.

>
Example: `c <<= 2` is roughly the same as `c = c << 2`

**8.    `>>=`**

The "arithmetic right shift and assign" operator.

>
Example: `c >>= 2` is roughly the same as `c = c >> 2`

**9.    `>>>=`**

The "logical right shift and assign" operator.

>
Example: `c >>>= 2` is roughly the same as `c = c >>> 2`

**10.    `&=`**

The "bitwise and and assign" operator.

>
Example: `c &= 2` is roughly the same as `c = c & 2`

**11.    `|=`**

The "bitwise or and assign" operator.

>
Example: `c |= 2` is roughly the same as `c = c | 2`

**12.    `^=`**

The "bitwise exclusive or and assign" operator.

>
Example: `c ^= 2` is roughly the same as `c = c ^ 2`

## The conditional-and and conditional-or Operators ( && and || )

Java provides a conditional-and and a conditional-or operator, that both take one or two operands of type `boolean` and produce a `boolean` result.  These are:

`&&` - the conditional-AND operator,

`||` - the conditional-OR operators.
The evaluation of `<left-expr> && <right-expr>` is equivalent to the following pseudo-code:

```java
{
   boolean L = evaluate(<left-expr>);
   if (L) {
       return evaluate(<right-expr>);
   } else {
       // short-circuit the evaluation of the 2nd operand expression
       return false;
   }
}

```

The evaluation of `<left-expr> || <right-expr>` is equivalent to the following pseudo-code:

```

   {
       boolean L = evaluate(<left-expr>);
       if (!L) {
           return evaluate(<right-expr>);
       } else {
           // short-circuit the evaluation of the 2nd operand expression
           return true;
       }
    }

```

As the pseudo-code above illustrates, the behavior of the short-circuit operators are equivalent to using `if` / `else` statements.

### Example - using && as a guard in an expression

The following example shows the most common usage pattern for the `&&` operator.  Compare these two versions of a method to test if a supplied `Integer` is zero.

```java
public boolean isZero(Integer value) {
    return value == 0;
}

public boolean isZero(Integer value) {
    return value != null && value == 0;
}

```

The first version works in most cases, but if the `value` argument is `null`, then a `NullPointerException` will be thrown.

In the second version we have added a "guard" test.  The `value != null && value == 0` expression is evaluated by first performing the `value != null` test.  If the `null` test succeeds (i.e. it evaluates to `true`) then the `value == 0` expression is evaluated.  If the `null` test fails, then the evaluation of `value == 0` is skipped (short-circuited), and we **don't** get a `NullPointerException`.

### Example - using && to avoid a costly calculation

The following example shows how `&&` can be used to avoid a relatively costly calculation:

```java
public boolean verify(int value, boolean needPrime) {
    return !needPrime | isPrime(value);
}

public boolean verify(int value, boolean needPrime) {
    return !needPrime || isPrime(value);
}

```

In the first version, both operands of the `|` will always be evaluated, so the (expensive) `isPrime` method will be called unnecessarily.  The second version avoids the unnecessary call by using `||` instead of `|`.

## The Shift Operators (<<, >> and >>>)

The Java language provides three operator for performing bitwise shifting on 32 and 64 bit integer values.  These are all binary operators with the first operand being the value to be shifted, and the second operand saying how far to shift.

The `<<` or **left shift** operator shifts the value given by the first operand **leftwards** by the number of bit positions given by the second operand.  The empty positions at the right end are filled with zeros.

The '>>' or **arithmetic shift** operator shifts the value given by the first operand **rightwards** by the number of bit positions given by the second operand.  The empty positions at the left end are filled by copying the left-most bit.  This process is known as **sign extension**.

The '>>>' or **logical right shift** operator shifts the value given by the first operand **rightwards** by the number of bit positions given by the second operand.  The empty positions at the left end are filled with zeros.

Notes:

These operators require an `int` or `long` value as the first operand, and produce a value with the same type as the first operand.  (You will need to use an explicit type cast when assigning the result of a shift to a `byte`, `short` or `char` variable.)

If you use a shift operator with a first operand that is a `byte`, `char` or `short`, it is promoted to an `int` and the operation produces an `int`.)

The second operand is reduced **modulo the number of bits of the operation** to give the amount of the shift.  For more about the **mod mathematical concept**, see [Modulus examples](http://stackoverflow.com/documentation/java/176/operators/14283/modulus-examples#t=201607262031550001554).

The bits that are shifted off the left or right end by the operation are discarded.  (Java does not provide a primitive "rotate" operator.)

The arithmetic shift operator is equivalent dividing a (two's complement) number by a power of 2.

The left shift operator is equivalent multiplying a (two's complement) number by a power of 2.

The following table will help you see the effects of the three shift operators.  (The numbers have been expressed in binary notation to aid vizualization.)

|Operand1|Operand2|`<<`|`>>`|`>>>`
|---|---|---|---|---|---|---|---|---|---
|0b0000000000001011|0|0b0000000000001011|0b0000000000001011|0b0000000000001011
|0b0000000000001011|1|0b0000000000010110|0b0000000000000101|0b0000000000000101
|0b0000000000001011|2|0b0000000000101100|0b0000000000000010|0b0000000000000010
|0b0000000000001011|28|0b1011000000000000|0b0000000000000000|0b0000000000000000
|0b0000000000001011|31|0b1000000000000000|0b0000000000000000|0b0000000000000000
|0b0000000000001011|32|0b0000000000001011|0b0000000000001011|0b0000000000001011
|...|...|...|...|...
|0b1000000000001011|0|0b1000000000001011|0b1000000000001011|0b1000000000001011
|0b1000000000001011|1|0b0000000000010110|0b1100000000000101|0b0100000000000101
|0b1000000000001011|2|0b0000000000101100|0b1110000000000010|0b00100000000000100
|0b1000000000001011|31|0b1000000000000000|0b1111111111111111|0b0000000000000001

There examples of the user of shift operators in [Bit manipulation](http://stackoverflow.com/documentation/java/1177/bit-manipulation#t=201610101439344327372)

## The Equality Operators (==, !=)

The `==` and `!=` operators are binary operators that evaluate to `true` or `false` depending on whether the operands are equal.  The `==` operator gives `true` if the operands are equal and `false` otherwise.  The `!=` operator gives `false` if the operands are equal and `true` otherwise.

These operators can be used operands with primitive and reference types, but the behavior is significantly different.  According to the JLS, there are actually three distinct sets of these operators:

- The Boolean `==` and `!=` operators.
- The Numeric `==` and `!=` operators.
- The Reference `==` and `!=` operators.

However, in all cases, the result type of the `==` and `!=` operators is `boolean`.

### The Numeric `==` and `!=` operators

When one (or both) of the operands of an `==` or `!=` operator is a primitive numeric type (`byte`, `short`, `char`, `int,` `long`, `float` or `double`), the operator is a numeric comparison.  The second operand must be either a primitive numeric type, or a boxed numeric type.

The behavior other numeric operators is as follows:

1. If one of the operands is a boxed type, it is unboxed.
1. If either of the operands now a `byte`, `short` or `char`, it is promoted to an `int`.
1. If the types of the operands are not the same, then the operand with the "smaller" type is promoted to the "larger" type.

The comparison is then carried out as follows:

1. If the promoted operands are `int` or `long` then the values are tested to see if they are identical.

If the promoted operands are `float` or `double` then:

1. the two versions of zero (`+0.0` and `-0.0`) are treated as equal
1. a `NaN` value is treated as not equals to anything, and
1. other values are equal if their IEEE 754 representations are identical.

Note: you need to be careful when using `==` and `!=` to compare floating point values.

### The Boolean `==` and `!=` operators

If both operands are `boolean`, or one is `boolean` and the other is `Boolean`, these operators the Boolean `==` and `!=` operators.  The behavior is as follows:

1. If one of the operands is a `Boolean`, it is unboxed.
1. The unboxed operands are tested and the boolean result is calculated according to the following truth table

|A|B|A == B|A != B
|---|---|---|---|---|---|---|---|---|---
|false|false|true|false
|false|true|false|true
|true|false|false|true
|true|true|true|false

There are two "pitfalls" that make it advisable to use `==` and `!=` sparingly with truth values:

If you use `==` or `!=` to compare two `Boolean` objects, then the Reference operators are used.  This may give an unexpected result; see [Pitfall: using == to compare primitive wrappers objects such as Integer](http://stackoverflow.com/documentation/java/4388/java-pitfalls/8996/pitfall-using-to-compare-primitive-wrappers-objects-such-as-integer#t=201612061208590356301)

The `==` operator can easily be mistyped as `=`.  For most operand types, this mistake leads to a compilation error.  However, for `boolean` and `Boolean` operands the mistake leads to incorrect runtime behavior; see [Pitfall - Using '==' to test a boolean](http://stackoverflow.com/documentation/java/5382/java-pitfalls-language-syntax/20112/pitfall-using-to-test-a-boolean#t=201612061213124111596)

### The Reference `==` and `!=` operators

If both operands are object references, the `==` and `!=` operators test if the two operands **refer to the same object**.  This often not what you want.  To test if two objects are equal **by value**, the `.equals()` method should be used instead.

```java
String s1 = "We are equal";
String s2 = new String("We are equal");

s1.equals(s2); // true

// WARNING - don't use == or != with String values
s1 == s2;      // false

```

Warning: using `==` and `!=` to compare `String` values is **incorrect** in most cases; see [http://stackoverflow.com/documentation/java/4388/java-pitfalls/16290/using-to-compare-strings](http://stackoverflow.com/documentation/java/4388/java-pitfalls/16290/using-to-compare-strings) .  A similar problem applies to primitive wrapper types; see [http://stackoverflow.com/documentation/java/4388/java-pitfalls/8996/using-to-compare-primitive-wrappers-objects-such-as-integer](http://stackoverflow.com/documentation/java/4388/java-pitfalls/8996/using-to-compare-primitive-wrappers-objects-such-as-integer) .

### About the NaN edge-cases

[JLS 15.21.1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.21.1) states the following:

>
If either operand is `NaN`, then the result of `==` is `false` but the result of `!=` is `true`.   Indeed, the test `x != x` is `true` if and only if the value of `x` is `NaN`.

This behavior is (to most programmers) unexpected.  If you test if a `NaN` value is equal to itself, the answer is "No it isn't!".  In other words, `==` is not **reflexive** for `NaN` values.

However, this is not a Java "oddity", this behavior is specified in the IEEE 754 floating-point standards, and you will find that it is implemented by most modern programming languages.  (For more information, see [http://stackoverflow.com/a/1573715/139985](http://stackoverflow.com/a/1573715/139985) ... noting that this is written by someone who was "in the room when the decisions were made"!)

## The Lambda operator ( -> )

From Java 8 onwards, the Lambda operator ( `->` ) is the operator used to introduce a Lambda Expression.  There are two common syntaxes, as illustrated by these examples:

```

 a -> a + 1              // a lambda that adds one to its argument
  a -> { return a + 1; }  // an equivalent lambda using a block.

```

A lambda expression defines an anonymous function, or more correctly an instance of an anonymous class that implements a **functional interface**.

(This example is included here for completeness.  Refer to the [Lambda Expressions](http://stackoverflow.com/documentation/java/91/lambda-expressions#t=201701012346164142062) topic for the full treatment.)

## The Relational Operators (<, <=, >, >=)

The operators `<`, `<=`, `>` and `>=` are binary operators for comparing numeric types.  The meaning of the operators is as you would expect.  For example, if `a` and `b` are declared as any of `byte`, `short`, `char`, `int`, `long`, `float`, `double` or the corresponding boxed types:

```java
- `a < b` tests if the value of `a` is less than the value of `b`.
- `a <= b` tests if the value of `a` is less than or equal to the value of `b`.
- `a > b` tests if the value of `a` is greater than the value of `b`.
- `a >= b` tests if the value of `a` is greater than or equal to the value of `b`.

```

The result type for these operators is `boolean` in all cases.

Relational operators can be used to compare numbers with different types.  For example:

```java
int i = 1;
long l = 2;
if (i < l) {
    System.out.println("i is smaller");
}

```

Relational operators can be used when either or both numbers are instances of boxed numeric types.  For example:

```java
Integer i = 1;   // 1 is autoboxed to an Integer
Integer j = 2;   // 2 is autoboxed to an Integer
if (i < j) {
    System.out.println("i is smaller");
}

```

The precise behavior is summarized as follows:

1. If one of the operands is a boxed type, it is unboxed.
1. If either of the operands now a `byte`, `short` or `char`, it is promoted to an `int`.
1. If the types of the operands are not the same, then the operand with the "smaller" type is promoted to the "larger" type.
1. The comparison is performed on the resulting `int`, `long`, `float` or `double` values.

You need to be careful with relational comparisons that involve floating point numbers:

- Expressions that compute floating point numbers often incur rounding errors due to the fact that the computer floating-point representations have limited precision.
- When comparing an integer type and a floating point type, the conversion of the integer to floating point can also lead to rounding errors.

Finally, Java does bit support the use of relational operators with any types other than the ones listed above.  For example, you **cannot** use these operators to compare strings, arrays of numbers, and so on.

#### Remarks

An **operator** is a symbol (or symbols) that tells a Java program to perform an **operation** on one, two or three **operands**.  An operator and its operands form an **expression** (see the Expressions topic).  The operands of an operator are themselves expressions.

This topic describes the 40 or so distinct operators defined by Java.  The separate Expressions topic explains:

- how operators, operands and other things are combined into expressions,
- how the expressions are evaluated, and
- how expression typing, conversions, and expression evaluation work.

repository: haifenghuang/generate

repo_name: haifenghuang/generate


text:
---
title: "PSY317L & PSY120R Guidebook"
author: "James P. Curley & Tyler M. Milewski"
date: "2021-07-22T17:15:55Z"
tags: [Guide, Statistics, Course, R Programming, Textbook]
link: "https://bookdown.org/content/50286a34-7e39-4500-8dd2-62bf686c1710/"
length_weight: "100%"
pinned: false
---

PSY317L & PSY120R Guidebook [...] This book is written to help students enrolled in the University of Texas at Austin Introduction to Statistics for the Behavioral Sciences (PSY317L) course or R Programming for Behavioral Sciences (PSY120R) led by Professor James Curley. We hope that the book will be a useful resource to help you learn both R and statistics. If you have any suggestions for improvements, please get in touch with Professor Curley. This is in between a textbook and a study guide. We’re trying to build materials that will enable students to quickly find what they’re looking for ...

branch_name: refs/heads/main

gha_language: R


text:
# Mutant

A [mutation testing][wiki] library for Clojure.

> *tl;dr:* Mutant breaks your code and lets you know if your test suite is
> still green.

Mutant tries to break your code. It goes through your namespaces and
introduces changes to your sources. After each mutation it attempts to run
your test suite. If all tests still pass despite the mutation Mutant reports
the mutation as a survivor.

[wiki]: https://en.wikipedia.org/wiki/Mutation_testing

## Usage

1. Add `mutant` to the dependencies in your `project.clj`

``` [mutant "0.0.0"] ```

2. Start a repl (e.g. with `lein repl`). Ensure that your current tests pass.

3. Make sure your test namespaces are loaded.

4. Now run Mutant:

```clojure
user=> (require 'mutant.core 'mutant.helpers.clojure-test)

user=> (def results
         (mutant.core/run "src" "test" mutant.helpers.clojure-test/test-fn))

user=> (spit "results" (with-out-str (mutant.core/pprint (last results))))
```

5. Print the report or save it in a file and highlight it with [colordiff][cd].

![coloured diff](https://stepien.cc/~jan/mutant/pretty.png)

[cd]: http://www.colordiff.org/

### API

The public API consists of two functions and one helper.

#### `(mutant.core/run source-directory test-directory test-fn)`

Subjects code in `source-directory` to mutation testing. After each
mutation it reloads relevant namespaces found in `source-directory`
and `test-directory` and invokes `test-fn`. `test-fn` should throw
or return a falsey value upon failure.

Returns a lazy seq of maps of results consisting of following keys:

  - `:total` is the total number of generated mutants so far, and
  - `:survivors` is a sequence of mutants which didn't cause `test-fn`
    to report failure. Each mutant is a map with following keys:
    - `:ns` is the mutant's namespace,
    - `:original` is the original form, and
    - `:mutant` is the mutated form.

#### `(mutant.core/pprint results)`

Pretty-prints `results` returned by `mutant.core/run`.

#### `(mutant.helpers.clojure-test/test-fn)`

A simple wrapper around `clojure.test/run-all-tests`, which makes it return
false in case of any failures or errors. An optional argument is a regular
expression passed to `clojure.test/run-all-tests`.

## Maturity status

Wildly experimental 🔥

## Related work

  - Markus Schirp's [Mutant](https://github.com/mbj/mutant/) is a mutation
    testing tool for Ruby.

## License

    Copyright 2016 Jan Stępień<EMAIL_ADDRESS>
    Licensed under the Apache License, Version 2.0 (the "License"); you may
    not use this file except in compliance with the License. You may obtain
    a copy of the License at https://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

repository: vsmart/mutant

repo_name: vsmart/mutant