text:
- [Android Behaviour](#android-behaviour)
  - [Images](#images)
  - [Sound](#sound)
  - [Stacking](#stacking)
  - [Inbox Stacking](#inbox-stacking)
  - [Action Buttons](#action-buttons)
  - [Led in Notifications](#led-in-notifications)
  - [Vibration Pattern in Notifications](#vibration-pattern-in-notifications)
  - [Priority in Notifications](#priority-in-notifications)
  - [Picture Messages](#picture-messages)
  - [Background Notifications](#background-notifications)
    - [Use of content-available: true](#use-of-content-available-true)
- [iOS Behaviour](#ios-behaviour)
  - [Sound](#sound-1)
  - [Background Notifications](#background-notifications-1)
  - [Action Buttons](#action-buttons-1)
    - [Action Buttons using GCM on iOS](#action-buttons-using-gcm-on-ios)
    - [Huawei and Xiaomi Phones](#huawei-and-xiaomi-phones)
- [Windows Behaviour](#windows-behaviour)
  - [Notifications](#notifications)
  - [Setting Toast Capable Option for Windows](#setting-toast-capable-option-for-windows)
  - [Disabling the default processing of notifications by Windows](#disabling-the-default-processing-of-notifications-by-windows)

# Android Behaviour

## Images

By default the icon displayed in your push notification will be your apps icon. So when you initialize the plugin like this:

```javascript
var push = PushNotification.init({
	"android": {
		"senderID": "12345679"
	},
	"ios": {
		"alert": "true",
		"badge": "true",
		"sound": "true"
	},
	"windows": {}
});
```

The result will look much like this:

![2015-07-24 02 52 00](https://cloud.githubusercontent.com/assets/353180/8866899/2df00c3c-3190-11e5-8552-96201fb4424b.png)

This is because Android now uses Material design and the default icon for push will be completely white.

In order to get a better user experience you can specify an alternate icon and background color to be shown when receiving a push notification. The code would look like this:

```javascript
var push = PushNotification.init({
	"android": {
		"senderID": "123456789",
		"icon": "phonegap",
		"iconColor": "blue"
	},
    "ios": {
		"alert": "true",
		"badge": "true",
		"sound": "true"
	},
	"windows": {}
});
```

Where *icon* is the name of an image in the Android *drawables* folder. Writing a hook to describe how to copy an image to the Android *drawables* folder is out of scope for this README but there is an [excellent tutorial](http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/) that you can copy.

*iconColor* is one of the supported formats #RRGGBB or #AARRGGBB or one of the following names: 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuchsia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'. *iconColor* is supported on Android 5.0 and greater.

Please follow the [Android icon design guidelines](https://www.google.com/design/spec/style/icons.html#) when creating your icon.

![2015-07-24 02 46 58](https://cloud.githubusercontent.com/assets/353180/8866902/2df3276e-3190-11e5-842a-c8cd95615ab0.png)

Additionally, each push can include a large icon which is used to personalize each push. The location of the image may one of three types.

The first is the *drawables* folder in your app. This JSON sent from GCM:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
        "title": "Large Icon",
    	"message": "Loaded from drawables folder",
    	"image": "twitter"
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'Large Icon');
message.addData('message', 'Loaded from drawables folder.');
message.addData('image', 'twitter');
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

Would look for the *twitter* image in the drawables folder and produce the following notification.

![2015-07-24 02 34 41](https://cloud.githubusercontent.com/assets/353180/8866903/2df48028-3190-11e5-8176-fe8b3f7c5aab.png)

The second is the *assets* folder in your app. This JSON sent from GCM:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "Large Icon",
    	"message": "Loaded from assets folder",
    	"image": "www/image/logo.png"
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'Large Icon');
message.addData('message', 'Loaded from assets folder.');
message.addData('image', 'www/image/logo.png');
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

Would look for the *logo.png* file in the assets/www/img folder. Since your apps www folder gets copied into the Android assets folder it is an excellent spot to store the images without needing to write a hook to copy them to the *drawables* folder. It produces the following notification.

![2015-07-24 02 20 02](https://cloud.githubusercontent.com/assets/353180/8866901/2df19052-3190-11e5-8c16-a355c59209f3.png)

The third is the remote *URL*. This JSON sent from GCM:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "Large Icon",
    	"message": "Loaded from URL",
    	"image": "https://dl.dropboxusercontent.com/u/887989/antshot.png"
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'Large Icon');
message.addData('message', 'Loaded from URL');
message.addData('image', 'https://dl.dropboxusercontent.com/u/887989/antshot.png');
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

Produces the following notification.

![2015-07-24 02 17 55](https://cloud.githubusercontent.com/assets/353180/8866900/2df0ab06-3190-11e5-9a81-fdb85bb0f5a4.png)

## Sound

For Android there are two special values for sound you can use. The first is `default` which will play the phones default notification sound. Then second is `ringtone` which will play the phones default ringtone sound.

In order for your your notification to play a custom sound you will need to add the files to your Android project's `res/raw` directory. Then send the follow JSON from GCM:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "Sound Test",
    	"message": "Loaded res/raw",
    	"soundname": "test"
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'Sound Test');
message.addData('message', 'Loaded res/raw');
message.addData('soundname', 'test');
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

*Note:* when you specify the custom sound file name omit the file's extension.

## Stacking

By default when using this plugin on Android each notification that your app receives will replace the previous notification in the shade.

If you want to see multiple notifications in the shade you will need to provide a notification ID as part of the push data sent to the app. For instance if you send:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "Test Push",
    	"message": "Push number 1"
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'Test Push');
message.addData('message', 'Push number 1');
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

Followed by:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "Test Push",
    	"message": "Push number 2"
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'Test Push');
message.addData('message', 'Push number 2');
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

You will only see "Push number 2" in the shade. However, if you send:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "Test Push",
    	"message": "Push number 1",
    	"notId": 1
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'Test Push');
message.addData('message', 'Push number 1');
message.addData('notId', 1);
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

and:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "Test Push",
    	"message": "Push number 2",
    	"notId": 2
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'Test Push');
message.addData('message', 'Push number 2');
message.addData('notId', 2);
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

You will only see both "Push number 1" and "Push number 2" in the shade.

## Inbox Stacking

A better alternative to stacking your notifications is to use the inbox style to have up to 8 lines of notification text in a single notification. If you send the following JSON from GCM you will see:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "My Title",
    	"message": "My first message",
    	"style": "inbox",
    	"summaryText": "There are %n% notifications"
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'My Title');
message.addData('message', 'My first message');
message.addData('style', 'inbox');
message.addData('summaryText', 'There are %n% notifications');
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

It will produce a normal looking notification:

![2015-08-25 14 11 27](https://cloud.githubusercontent.com/assets/353180/9468840/c9c5d43a-4b11-11e5-814f-8dc995f47830.png)

But, if you follow it up with subsequent notifications like:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "My Title",
    	"message": "My second message",
    	"style": "inbox",
    	"summaryText": "There are %n% notifications"
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'My Title');
message.addData('message', 'My second message');
message.addData('style', 'inbox');
message.addData('summaryText', 'There are %n% notifications');
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

You will get an inbox view so you can display multiple notifications in a single panel.

![2015-08-25 14 01 35](https://cloud.githubusercontent.com/assets/353180/9468727/2d658bee-4b11-11e5-90fa-248d54c8f3f6.png)

If you use `%n%` in the `summaryText` of the JSON coming down from GCM it will be replaced by the number of messages that are currently in the queue.

## Action Buttons

Your notification can include action buttons. If you wish to include an icon along with the button name they must be placed in the `res/drawable` directory of your Android project. Then you can send the following JSON from GCM:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "AUX Scrum",
    	"message": "Scrum: Daily touchbase @ 10am Please be on time so we can cover everything on the agenda.",
        "actions": [
    		{ "icon": "emailGuests", "title": "EMAIL GUESTS", "callback": "app.emailGuests", "foreground": true},
    		{ "icon": "snooze", "title": "SNOOZE", "callback": "app.snooze", "foreground": false}
    	]
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'AUX Scrum');
message.addData('message', 'Scrum: Daily touchbase @ 10am Please be on time so we can cover everything on the agenda.');
message.addData('actions', [
    { "icon": "emailGuests", "title": "EMAIL GUESTS", "callback": "app.emailGuests", "foreground": true},
    { "icon": "snooze", "title": "SNOOZE", "callback": "app.snooze", "foreground": false},
]);
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

This will produce the following notification in your tray:

![action_combo](https://cloud.githubusercontent.com/assets/353180/9313435/02554d2a-44f1-11e5-8cd9-0aadd1e02b18.png)

If your users clicks on the main body of the notification your app will be opened. However if they click on either of the action buttons the app will open (or start) and the specified JavaScript callback will be executed. In this case it is `app.emailGuests` and `app.snooze` respectively. If you set the `foreground` property to `true` the app will be brought to the front, if `foreground` is `false` then the callback is run without the app being brought to the foreground.

### Attributes

Attribute | Type | Default | Description
--------- | ---- | ------- | -----------
`icon` | `string` | | Optional. The name of a drawable resource to use as the small-icon. The name should not include the extension.
`title` | `string` | | Required. The label to display for the action button.
`callback` | `string` | | Required. The function to be executed when the action button is pressed.
`foreground` | `boolean` | `true` | Optional. Whether or not to bring the app to the foreground when the action button is pressed.

## Led in Notifications

You can use a Led notifcation and choose the color of it. Just add a `ledColor` field in your notification in the ARGB format array:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "Green LED",
    	"message": "This is my message with a Green LED",
    	"ledColor": [0, 0, 255, 0]
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'Green LED');
message.addData('message', 'This is my message with a Green LED');
message.addData('ledColor', [0, 0, 255, 0]);
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

## Vibration Pattern in Notifications

You can set a Vibration Pattern for your notifications. Just add a `vibrationPattern` field in your notification:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "Vibration Pattern",
    	"message": "Device should wait for 2 seconds, vibrate for 1 second then be silent for 500 ms then vibrate for 500 ms",
    	"vibrationPattern": [2000, 1000, 500, 500]
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'Vibration Pattern');
message.addData('message', 'Device should wait for 2 seconds, vibrate for 1 second then be silent for 500 ms then vibrate for 500 ms');
message.addData('vibrationPattern', [2000, 1000, 500, 500]);
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

## Priority in Notifications

You can set a priority parameter for your notifications. Just add a `priority` field in your notification. -2: minimum, -1: low, 0: default , 1: high, 2: maximum priority:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "This is a maximum priority Notification",
    	"message": "This notification should appear in front of all others",
    	"priority": 2
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'This is a maximum priority Notification');
message.addData('message', 'This notification should appear in front of all others');
message.addData('priority', 2);
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

## Picture Messages

Perhaps you want to include a large picture in the notification that you are sending to your users. Luckily you can do that too by sending the following JSON from GCM.

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "Big Picture",
    	"message": "This is my big picture message",
    	"style": "picture",
    	"picture": "http://36.media.tumblr.com/c066cc2238103856c9ac506faa6f3bc2/tumblr_nmstmqtuo81tssmyno1_1280.jpg",
    	"summaryText": "The internet is built on cat pictures"
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'Big Picture');
message.addData('message', 'This is my big picture message');
message.addData('style', 'picture');
message.addData('picture', 'http://36.media.tumblr.com/c066cc2238103856c9ac506faa6f3bc2/tumblr_nmstmqtuo81tssmyno1_1280.jpg');
message.addData('summaryText', 'The internet is built on cat pictures');
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

This will produce the following notification in your tray:

![2015-08-25 16 08 00](https://cloud.githubusercontent.com/assets/353180/9472260/3655fa7a-4b22-11e5-8d87-20528112de16.png)

## Background Notifications

On Android if you want your `on('notification')` event handler to be called when your app is in the background it is relatively simple.

First the JSON you send from GCM will need to include `"content-available": "1"`. This will tell the push plugin to call your `on('notification')` event handler no matter what other data is in the push notification.

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"title": "Test Push",
    	"message": "Push number 1",
    	"info": "super secret info",
    	"content-available": "1"
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'Test Push');
message.addData('message', 'Push number 1');
message.addData('info', 'super secret info');
message.addData('content-available', '1');
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

or

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
    	"info": "super secret info",
    	"content-available": "1"
    }
}
```

Here is an example using node-gcm that sends the above JSON:

```javascript
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "replace with API key";
var deviceID = "my device id";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('info', 'super secret info');
message.addData('content-available', '1');
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
	if(err) console.error(err);
	else 	console.log(response);
});
```

If do not want this type of behaviour just omit `"content-available": 1` from your push data and your `on('notification')` event handler will not be called.

### Use of content-available: true

The GCM docs will tell you to send a data payload of:

```javascript
{
    "registration_ids": ["my device id"],
    "content_available": true,
    "data": {
        "title": "Test Push",
        "message": "Push number 1",
        "info": "super secret info",
    }
}
```

Where the `content-available` property is part of the main payload object. Setting the property in this part of the payload will result in the PushPlugin not getting the data correctly. Setting `content-available: true` will cause the Android OS to handle the push payload for you and not pass the data to the PushPlugin.

Instead move `content-available: true` into the `data` object of the payload and set it to `1` as per the example below:

```javascript
{
    "registration_ids": ["my device id"],
    "data": {
        "title": "Test Push",
        "message": "Push number 1",
        "info": "super secret info",
        "content-available": "1"
    }
}
```

### Huawei and Xiaomi Phones

These phones have a particular quirk that when the app is force closed that you will no longer be able to receive notifications until the app is restarted. In order for you to receive background notifications:

- On your Huawei device go to Settings > Protected apps > check "My App" where.
- On your Xiaomi makes sure your phone has the "Auto-start" property enabled for your app.

# iOS Behaviour

## Sound

In order for your notification to play a custom sound you will need to add the files to root of your iOS project. The files must be in the proper format. See the [Local and Remote Notification Programming Guide](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/IPhoneOSClientImp.html#//apple_ref/doc/uid/TP40008194-CH103-SW6) for more info on proper file formats and how to convert existing sound files.

Then send the follow JSON from APNS:

```javascript
{
	"aps": {
		"alert": "Test sound",
		"sound": "sub.caf"
	}
}
```

If you want the default sound to play upon receipt of push use this payload:

```
{
    "aps": {
        "alert": "Test sound",
        "sound": "default"
    }
}
```

## Background Notifications

On iOS if you want your `on('notification')` event handler to be called when your app is in the background you will need to do a few things.

First the JSON you send from APNS will need to include `"content-available": 1` to the `aps` object. The `"content-available": 1` property in your push message is a signal to iOS to wake up your app and give it up to 30 seconds of background processing. If do not want this type of behaviour just omit `"content-available": 1` from your push data.

For instance the following JSON:

```javascript
{
	"aps": {
		"alert": "Test background push",
		"content-available": 1
	}
}
```

will produce a notification in the notification shade and call your `on('notification')` event handler.

However if you want your `on('notification')` event handler called but no notification to be shown in the shader you would omit the `alert` property and send the following JSON to APNS:

```javascript
{
	"aps": {
		"data": "Test silent background push",
		"moredata": "Do more stuff",
		"content-available": 1
	}
}
```

That covers what you need to do on the server side to accept background pushes on iOS. However, it is critically important that you continue reading as there will be a change in your `on('notification')`. When you receive a background push on iOS you will be given 30 seconds of time in which to complete a task. If you spend longer than 30 seconds on the task the OS may decide that your app is misbehaving and kill it. In order to signal iOS that your `on('notification')` handler is done you will need to call the new `push.finish()` method.

For example:

```javascript
var push = PushNotification.init({
	"ios": {
		"sound": "true",
		"alert": "true",
		"badge": "true",
		"clearBadge": "true"
	}
});

push.on('registration', function(data) {
	// send data.registrationId to push service
});

push.on('notification', function(data) {
	// do something with the push data
	// then call finish to let the OS know we are done
	push.finish(function() {
		console.log("processing of push data is finished");
	});
});
```

It is absolutely critical that you call `push.finish()` when you have successfully processed your background push data.

## Action Buttons

Your notification can include action buttons. For iOS 8+ you must setup the possible actions when you initialize the plugin:

```javascript
var push = PushNotification.init({
	"ios": {
		"sound": true,
		"alert": true,
		"badge": true,
		"categories": {
			"invite": {
				"yes": {
					"callback": "app.accept", "title": "Accept", "foreground": true, "destructive": false
				},
				"no": {
					"callback": "app.reject", "title": "Reject", "foreground": true, "destructive": false
				},
				"maybe": {
					"callback": "app.maybe", "title": "Maybe", "foreground": true, "destructive": false
				}
			},
			"delete": {
				"yes": {
					"callback": "app.doDelete", "title": "Delete", "foreground": true, "destructive": true
				},
				"no": {
					"callback": "app.cancel", "title": "Cancel", "foreground": true, "destructive": false
				}
			}
		}
	}
});
```

You'll notice that we've added a new parameter to the iOS object of our init code called categories. Each category is a named object, invite and delete in this case. These names will need to match the one you send via your payload to APNS if you want the action buttons to be displayed. Each category can have up to three buttons which must be labeled `yes`, `no` and `maybe`. In turn each of these buttons has four properties, `callback` the javascript function you want to call, `title` the label for the button, `foreground` whether or not to bring your app to the foreground and `destructive` which doesn't actually do anything destructive it just colors the button red as a warning to the user that the action may be destructive.

Just like with background notifications it is absolutely critical that you call `push.finish()` when you have successfully processed the button callback. For instance:

```javascript
app.accept = function(data) {
    // do something with the notification data

    push.finish(function() {
        console.log('accept callback finished');
    }, function() {
        console.log('accept callback failed');
    }, data.additionalData.notId);
};
```

You may notice that the `finish` method now takes `success`, `failure` and `id` parameters. The `id` parameter let's the operating system know which background process to stop. You'll set it in the next step.

Then you will need to set the `category` value in your `aps` payload to match one of the objects in the `categories` object. As well you *should* set a `notId` property in the root of payload object. This is the parameter you pass to the `finish` method in order to tell the operating system that the processing of the push event is done.

```javascript
{
	"aps": {
		"alert": "This is a notification that will be displayed ASAP.",
		"category": "invite"
	},
    "notId": "1"
}
```

This will produce the following notification in your tray:

![push6-ios](https://cloud.githubusercontent.com/assets/353180/12754125/12d13020-c998-11e5-98b4-b245fda30490.png)

If your users clicks on the main body of the notification your app will be opened. However if they click on either of the action buttons the app will open (or start) and the specified JavaScript callback will be executed.

### Action Buttons using GCM on iOS

If you are using GCM to send push messages on iOS you will need to send a different payload in order for the action buttons to be present in the notification shade. You'll need to use the `click-action` property in order to specify the category.

```javascript
{
    "registration_ids": ["my device id"],
    "notification": {
    	"title": "AUX Scrum",
    	"body": "Scrum: Daily touchbase @ 10am Please be on time so we can cover everything on the agenda.",
        "click-action": "invite"
    }
}
```

# Windows Behaviour

## Notifications

The plugin supports all types of windows platform notifications namely [Tile, Toast, Badge and Raw](https://msdn.microsoft.com/en-us/library/windows/apps/Hh779725.aspx). The API supports the basic cases of the notification templates with title corresponding to the first text element and message corresponding to the second if title is present else the first one. The image corresponds to the first image element of the notification xml.

The count is present only for the badge notification in which it represent the value of the notification which could be a number from 0-99 or a status glyph.

For advanced templates and usage, the notification object is included in [`data.additionalData.pushNotificationReceivedEventArgs`](https://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.pushnotifications.pushnotificationreceivedeventargs).

## Setting Toast Capable Option for Windows

This plugin automatically sets the toast capable flag to be true for Cordova 5.1.1+. For lower versions, you must declare that it is Toast Capable in your app's manifest file.

## Disabling the default processing of notifications by Windows

The default handling can be disabled by setting the 'cancel' property in the notification object.

```javascript
data.additionalData.pushNotificationReceivedEventArgs.cancel = true
```


text:
package org.apache.phoenix.expression;

import java.util.List;

import org.apache.hadoop.hbase.io.ImmutableBytesWritable;

import org.apache.phoenix.schema.PDataType;
import org.apache.phoenix.schema.tuple.Tuple;

public class LongDivideExpression extends DivideExpression {

    public LongDivideExpression() {
    }

    public LongDivideExpression(List<Expression> children) {
        super(children);
    }

    @Override
    public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) {
        long finalResult=0;

        for(int i=0;i<children.size();i++) {
            Expression child = children.get(i);
            if (!child.evaluate(tuple, ptr) || ptr.getLength() == 0) {
                return false;
            }
            long childvalue = child.getDataType().getCodec().decodeLong(ptr, child.getColumnModifier());
            if (i == 0) {
                finalResult = childvalue;
            } else {
                finalResult /= childvalue;
            }
        }
        byte[] resultPtr=new byte[PDataType.LONG.getByteSize()];
        getDataType().getCodec().encodeLong(finalResult, resultPtr, 0);
        ptr.set(resultPtr);
        return true;
    }

    @Override
    public final PDataType getDataType() {
        return PDataType.LONG;
    }

}

redpajama_set_name: RedPajamaGithub


text:
using namespace std;
using namespace cv;

static void help()
{
    printf("\n"
            "This program demonstrated a simple method of connected components clean up of background subtraction\n"
            "When the program starts, it begins learning the background.\n"
            "You can toggle background learning on and off by hitting the space bar.\n"
            "Call\n"
            "./segment_objects [video file, else it reads camera 0]\n\n");
}

static void refineSegments(const Mat& img, Mat& mask, Mat& dst)
{
    int niters = 3;

    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;

    Mat temp;

    dilate(mask, temp, Mat(), Point(-1,-1), niters);
    erode(temp, temp, Mat(), Point(-1,-1), niters*2);
    dilate(temp, temp, Mat(), Point(-1,-1), niters);

    findContours( temp, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE );

    dst = Mat::zeros(img.size(), CV_8UC3);

    if( contours.size() == 0 )
        return;

    // iterate through all the top-level contours,
    // draw each connected component with its own random color
    int idx = 0, largestComp = 0;
    double maxArea = 0;

    for( ; idx >= 0; idx = hierarchy[idx][0] )
    {
        const vector<Point>& c = contours[idx];
        double area = fabs(contourArea(Mat(c)));
        if( area > maxArea )
        {
            maxArea = area;
            largestComp = idx;
        }
    }
    Scalar color( 0, 0, 255 );
    drawContours( dst, contours, largestComp, color, FILLED, LINE_8, hierarchy );
}

int main(int argc, char** argv)
{
    VideoCapture cap;
    bool update_bg_model = true;

    CommandLineParser parser(argc, argv, "{help h||}{@input||}");
    if (parser.has("help"))
    {
        help();
        return 0;
    }
    string input = parser.get<std::string>("@input");
    if (input.empty())
        cap.open(0);
    else
        cap.open(input);

    if( !cap.isOpened() )
    {
        printf("\nCan not open camera or video file\n");
        return -1;
    }

    Mat tmp_frame, bgmask, out_frame;

    cap >> tmp_frame;
    if(tmp_frame.empty())
    {
        printf("can not read data from the video source\n");
        return -1;
    }

    namedWindow("video", 1);
    namedWindow("segmented", 1);

    Ptr<BackgroundSubtractorMOG2> bgsubtractor=createBackgroundSubtractorMOG2();
    bgsubtractor->setVarThreshold(10);

    for(;;)
    {
        cap >> tmp_frame;
        if( tmp_frame.empty() )
            break;
        bgsubtractor->apply(tmp_frame, bgmask, update_bg_model ? -1 : 0);
        refineSegments(tmp_frame, bgmask, out_frame);
        imshow("video", tmp_frame);
        imshow("segmented", out_frame);
        char keycode = (char)waitKey(30);
        if( keycode == 27 )
            break;
        if( keycode == ' ' )
        {
            update_bg_model = !update_bg_model;
            printf("Learn background is in state = %d\n",update_bg_model);
        }
    }

    return 0;
}


text:
<?php

namespace Entity;

use Sberbank\Entity\ItemAttribute;
use PHPUnit\Framework\TestCase;

class ItemAttributeTest extends TestCase
{

    public function testGetPaymentObject()
    {
        $attribute = new ItemAttribute([
            'paymentMethod' => ItemAttribute::PAYMENT_METHOD_FULL,
            'paymentObject' => ItemAttribute::PAYMENT_OBJECT_PRODUCT
        ]);

        $this->assertEquals(ItemAttribute::PAYMENT_OBJECT_PRODUCT, $attribute->getPaymentObject());
    }

    public function testGetPaymentMethod()
    {
        $attribute = new ItemAttribute([
            'paymentMethod' => ItemAttribute::PAYMENT_METHOD_FULL,
            'paymentObject' => ItemAttribute::PAYMENT_OBJECT_PRODUCT
        ]);

        $this->assertEquals(ItemAttribute::PAYMENT_METHOD_FULL, $attribute->getPaymentMethod());
    }
}


text:
layout: post
date:	2012-07-10 18:28:00
title:  Vasus Pessimism Poetry
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
Life Can Present Some Nasty Turns

Family Man Gets Laid Off

Christmas season
Gift lists
Holiday plans
Santa at the mall
Then
The pink slip (65)

Man Gets a Grim Diagnosis

Pink of health
Routine checkup
X-ray shadow
Follow up visit
Then
The lung cancer (67)

Student develops an addiction

Straight A student
Honors list
Debating champ
Basketball hero
Then
The amphetamines (72)

A Child is killed

Suburban street
Seven-year old
Lemonade stand
DUI driver
Then
The small coffin (67)

A Husband Asks for a Divorce

Anniversary
Candles and wine
Surprise dinner
His favorite meal
Then
The D word (66)

A Woman is Unfaithful

Home early
Concealed flowers
Alarmed voices
Ear to the door
Then
The infidelity (67)

A Student Takes His Own Life

Exam results
Missing roll number
Despondent boy
Wrenching shame
Then
Qutab Minar (69)

A Terrorist Attack at a Crowded Location

Holiday tourists
Magnificent view
Sudden commotion
Human screams
Then
Body Counts (71)

Vasu

My friend Sundar named these vignettes, taken together, as "pessimism poetry." I told him these word pictures were merely exercises in crafting succinct images of  sudden and unexpected developments in people's lives. Such things do happen, do they not?  People are writing stories these days in a single "tweet" of 140 characters. The number of characters in the above stories is shown in parentheses. Perhaps the stories could be told in even fewer words, even fewer lines. As such, each vignette is roughly "half a tweet" in length or shorter.

The one below has only 46 characters:

Rajat Gupta

IIT
Harvard
McKinsey
Goldman Sachs
Then
Preet Bharara (46)


text:
<?php

/**
 * Description of Guru
 *
 * @author s4if
 */
class Guru extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('model_guru','guru',TRUE);
    }

    public function index(){
        if (is_cli())
        {
            echo 'This Is For Avoiding Load Session in CLI. ';
            return;
        }  else {
            $this->lihat();
        }
    }

    public function lihat(){
        $this->blockUnloggedOne();
        $data_guru = $this->guru->getData();
        $data = [
            'title' => 'Lihat Guru',
            'user' => ucwords($this->session->login_data->getNama()),
            'position' => $this->session->position,
            'nama' => $this->session->login_data->getNama(),
            'nav_pos' => 'guru',
            'tambah' => $this->load->view("admin/guru/tambah",[],TRUE),
            'edit' => $this->load->view("admin/guru/edit",['data_guru' => $data_guru],TRUE),
            'data_guru' => $data_guru
        ];
        $this->loadView('admin/guru/lihat', $data);
    }

    public function tambah(){
        $this->blockUnloggedOne();
        $data_insert = $this->input->post(null, true);
        $data_insert['password'] = password_hash("qwerty", PASSWORD_BCRYPT);
        print_r($data_insert);
        if($this->guru->dataExist($this->input->post('nip', true))){
            $this->session->set_flashdata("errors",[0 => "Maaf, NIP yang dimasukkan sudah terpakai!"]);
            redirect('admin/guru');
        }else{
            $res = $this->guru->insertData($data_insert, 'guru');
            if($res >= 1){
                $this->session->set_flashdata("notices",[0 => "Tambah Data Berhasil!"]);
                redirect('admin/guru');
            } else {
                $this->session->set_flashdata("errors",[0 => "Tambah Data Gagal!"]);
                redirect('admin/guru');
            }
        }
    }

    public function edit($nip){
        $this->blockUnloggedOne();
        $data_insert = $this->input->post(null, true);
        $data_insert['nip'] = $nip;
        $res = $this->guru->updateData($data_insert, 'guru');
        if($res >= 1){
            $this->session->set_flashdata("notices",[0 => "Edit Data Berhasil!"]);
            redirect('admin/guru');
        } else {
            $this->session->set_flashdata("errors",[0 => "Edit Data Gagal!"]);
            redirect('admin/guru');
        }
    }

    public function hapus($nip){
        $this->blockUnloggedOne();
        if($this->guru->deleteData(['nip' => $nip])){
            $this->session->set_flashdata("notices",[0 => "Data telah berhasil dihapus"]);
            redirect('admin/guru/lihat', 'refresh');
        }  else {
            $this->session->set_flashdata("errors",[0 => "Maaf, Guru dengan nip = ".$nip." tidak ditemukan"]);
            redirect('admin/guru/lihat', 'refresh');
        }
    }

    public function import(){
        $this->blockUnloggedOne();
        $fileUrl = $_FILES['file']["tmp_name"];
        $res = $this->guru->importData($fileUrl);
        if($res == 0){
            $this->session->set_flashdata("notices",[0 => "Import Data Berhasil!"]);
            redirect('guru');
        } elseif($res > 0) {
            $this->session->set_flashdata("errors",[0 => "Import Data Gagal!,
 cek kembali isi dokumen yang akan diimport!"]);
            redirect('guru');
        }  else {
            $this->session->set_flashdata("errors",[0 => "Import Data Gagal!,
 File yang dimasukkan bukan file excel!"]);
            redirect('guru');
        }
    }

}


text:
package org.lightadmin.core.config.domain.configuration.support;

import org.junit.Test;
import org.lightadmin.api.config.utils.EntityNameExtractor;

import static org.junit.Assert.assertEquals;
import static org.lightadmin.core.config.domain.configuration.support.EntityNameExtractorFactory.forNamedPersistentEntity;

@SuppressWarnings("unchecked")
public class EntityNameExtractorFactoryTest {

    @Test
    public void namedEntityNameExtraction() throws Exception {
        final EntityNameExtractor entityNameExtractor = forNamedPersistentEntity("name");

        assertEquals("Domain Type Object Name", entityNameExtractor.apply(new DomainType()));
    }

//    @Test
//    public void persistentEntityNameExtraction() throws Exception {
//        final DomainTypeEntityMetadata entityMetadata = domainTypeEntityMetadata("Entity", 1);
//
//        final EntityNameExtractor entityNameExtractor = forPersistentEntity(null);
//
//        assertEquals("Entity #1", entityNameExtractor.apply(new DomainType()));
//    }
//
//    private DomainTypeEntityMetadata domainTypeEntityMetadata(String entityName, int entityId) {
//        DomainTypeEntityMetadata domainTypeEntityMetadata = EasyMock.createMock(DomainTypeEntityMetadata.class);
//        EasyMock.expect(domainTypeEntityMetadata.getEntityName()).andReturn(entityName).anyTimes();
//
//        final DomainTypeAttributeMetadata idAttribute = EasyMock.createMock(DomainTypeAttributeMetadata.class);
//        EasyMock.expect(idAttribute.getValue(EasyMock.anyObject())).andReturn(entityId).anyTimes();
//        EasyMock.replay(idAttribute);
//
//        EasyMock.expect(domainTypeEntityMetadata.getIdAttribute()).andReturn(idAttribute).anyTimes();
//
//        EasyMock.replay(domainTypeEntityMetadata);
//
//        return domainTypeEntityMetadata;
//    }

    private static class DomainType {

        private String name = "Domain Type Object Name";

        public String getName() {
            return name;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
   <LinearLayout
   android:orientation="horizontal"
   android:layout_height="wrap_content"
   android:layout_width="match_parent"
   >
    <Button android:text="@string/btnIntend" android:id="@+id/btnIntend"
        android:layout_height="wrap_content"
        android:layout_width="0dp"
        android:layout_weight="1" />
    <Button android:text="@string/btnIntendS" android:id="@+id/btnIntendS"
        android:layout_height="wrap_content"
        android:layout_width="0dp"
        android:layout_weight="1" />
    <Button android:text="@string/btnIntendV" android:id="@+id/btnIntendV"
        android:layout_height="wrap_content"
        android:layout_width="0dp"
        android:layout_weight="1" />
  </LinearLayout>
  <ImageView
      android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:visibility="visible"
      android:id="@+id/imageView1" />
  <VideoView
      android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      android:visibility="invisible"
      android:id="@+id/videoView1" />
</LinearLayout>


text:
import {mount} from 'enzyme';

import {computedStyle} from '#core/dom/style';

import * as Preact from '#preact';

import {waitFor} from '#testing/helpers/service';

import {BentoFitText, calculateFontSize, setOverflowStyle} from '../component';
import {useStyles} from '../component.jss';

describes.realWin('BentoFitText preact component v1.0', {}, (env) => {
  let win;

  const styles = useStyles();

  beforeEach(() => {
    win = env.win;
  });

  async function expectAsyncFontSize(element, value) {
    await waitFor(
      () => computedStyle(win, element).fontSize === value,
      'font size applied'
    );
    expect(computedStyle(win, element).fontSize).to.equal(value);
  }

  it('renders', async () => {
    const ref = Preact.createRef();
    const wrapper = mount(
      <BentoFitText ref={ref} style={{width: '300px', height: '100px'}}>
        Hello World
      </BentoFitText>,
      {attachTo: win.document.body}
    );

    // Render provided children
    expect(wrapper.children()).to.have.lengthOf(1);
    expect(wrapper.text()).to.equal('Hello World');
    await expectAsyncFontSize(
      wrapper.find(`.${styles.minContentHeight}`).getDOMNode(),
      '60px'
    );
  });

  it('should respect minFontSize', async () => {
    const ref = Preact.createRef();
    const wrapper = mount(
      <BentoFitText
        ref={ref}
        style={{width: '1px', height: '1px'}}
        minFontSize="24"
      >
        Hello World
      </BentoFitText>,
      {attachTo: win.document.body}
    );

    // Render provided children
    expect(wrapper.children()).to.have.lengthOf(1);
    expect(wrapper.text()).to.equal('Hello World');
    await expectAsyncFontSize(
      wrapper.find(`.${styles.minContentHeight}`).getDOMNode(),
      '24px'
    );
  });

  it('should respect maxFontSize', async () => {
    const ref = Preact.createRef();
    const wrapper = mount(
      <BentoFitText
        ref={ref}
        style={{width: '300px', height: '100px'}}
        maxFontSize="48"
      >
        Hello World
      </BentoFitText>,
      {attachTo: win.document.body}
    );

    // Render provided children
    expect(wrapper.children()).to.have.lengthOf(1);
    expect(wrapper.text()).to.equal('Hello World');
    await expectAsyncFontSize(
      wrapper.find(`.${styles.minContentHeight}`).getDOMNode(),
      '48px'
    );
  });
});

describes.realWin('BentoFitText calculateFontSize', {}, (env) => {
  let win, doc;
  let element;

  beforeEach(() => {
    win = env.win;
    doc = win.document;
    element = doc.createElement('div');
    element.style.fontFamily = 'Arial';
    element.style.lineHeight = '1em';
    element.style.position = 'absolute';
    element.style.left = 0;
    element.style.top = 0;
    doc.body.appendChild(element);
  });

  it('should always fit on one line w/ enough width', () => {
    element./*OK*/ innerHTML = 'A';
    expect(calculateFontSize(element, 10, 200, 6, 72)).to.equal(10);
  });

  it('should always fit the width w/ enough height', () => {
    element./*OK*/ innerHTML = 'A';
    expect(calculateFontSize(element, 200, 10, 6, 72)).to.equal(15);
    expect(calculateFontSize(element, 200, 20, 6, 72)).to.equal(30);
    expect(calculateFontSize(element, 200, 40, 6, 72)).to.equal(60);
  });

  it('should hit min w/ small height and enough width', () => {
    element./*OK*/ innerHTML = 'A';
    expect(calculateFontSize(element, 6, 200, 6, 72)).to.equal(6);
    expect(calculateFontSize(element, 3, 200, 6, 72)).to.equal(6);
  });

  it('should hit min w/ small width and enough height', () => {
    element./*OK*/ innerHTML = 'A';
    expect(calculateFontSize(element, 200, 2, 6, 72)).to.equal(6);
    expect(calculateFontSize(element, 200, 4, 6, 72)).to.equal(6);
  });

  it('should hit max w/ enough width', () => {
    element./*OK*/ innerHTML = 'A';
    expect(calculateFontSize(element, 80, 200, 6, 72)).to.equal(72);
  });

  it('should hit max w/ enough height', () => {
    element./*OK*/ innerHTML = 'A';
    expect(calculateFontSize(element, 200, 48, 6, 72)).to.equal(72);
    expect(calculateFontSize(element, 200, 60, 6, 72)).to.equal(72);
  });

  it('should always fit on two lines w/ enough width', () => {
    element./*OK*/ innerHTML = 'A
B';
    expect(calculateFontSize(element, 20, 200, 6, 72)).to.equal(10);
  });
});

describes.realWin('BentoFitText setOverflowStyle', {}, (env) => {
  let win, doc;
  let measurer;

  beforeEach(() => {
    win = env.win;
    doc = win.document;

    measurer = doc.createElement('div');
    measurer.style.fontFamily = 'Arial';
    measurer.style.lineHeight = '1.15em';
    measurer.style.position = 'absolute';
    measurer.style.width = '300px';
    doc.body.appendChild(measurer);
  });

  function getLineClamp() {
    for (const k in measurer.style) {
      if (k == 'lineClamp' || k.match(/.*LineClamp/)) {
        return measurer.style[k];
      }
    }
    return null;
  }

  it('should always fit on one line', () => {
    measurer./*OK*/ innerHTML = 'A';
    setOverflowStyle(measurer, 24, 20);
    expect(getLineClamp()).to.equal('');
    expect(measurer.style.maxHeight).to.equal('');
  });

  it('should always fit on two lines', () => {
    measurer./*OK*/ innerHTML = 'A
B';
    setOverflowStyle(measurer, 24, 20);
    expect(getLineClamp()).to.equal('1');
    expect(measurer.style.maxHeight).to.equal(23 + 'px'); // 23 = 20 * 1.15
  });
});


text:
module Sanscript
  module Detect
    # Module stub for implementing `detect_scheme` method using Rust native extension.
    # (Note: This module will only exist if the native extension is available and {Sanscript.rust_load!} has been run.)
    module Rust
      # @!method rust_detect_scheme(text)
      # Attempts to detect the encoding scheme of the provided string.
      # Uses Rust native extension for vastly increased performance.
      #
      # @param text [String] a string of Sanskrit text
      # @return [Symbol, nil] the Symbol of the scheme, or nil if no match
    end
  end
end


text:
using CUSPARSE
using Base.Test

using CUSPARSE: cusparseMatDescr_t, cusparseCreateMatDescr
mdptr = cusparseMatDescr_t[0]
cusparseCreateMatDescr(mdptr)
md = mdptr[1]

using CUSPARSE: cusparseGetMatDiagType, cusparseGetMatFillMode, cusparseGetMatIndexBase, cusparseGetMatType
@show cusparseGetMatDiagType(md)
@show cusparseGetMatFillMode(md)
@show cusparseGetMatIndexBase(md)
@show cusparseGetMatType(md)


text:
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("Meow.Diagnostic")]
[assembly: AssemblyCompany("Jared McGuire")]
[assembly: AssemblyProduct("Meow.Diagnostic")]
[assembly: AssemblyCopyright("Copyright Jared McGuire 2013")]
[assembly: ComVisible(false)]
[assembly: Guid("61a84e8e-8138-409b-9362-c58a543721cb")]
[assembly: AssemblyVersion("1.0.0.*")]


text:
<?xml version="1.0" encoding="utf-8"?>
<com.neics.pocketpet.presentation.features.health.HealthViewGroup
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
            android:id="@+id/health_list_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"/>

    <TextView android:id="@+id/empty_health_view"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:paddingRight="@dimen/empty_view_padding_side"
              android:paddingLeft="@dimen/empty_view_padding_side"
              android:paddingBottom="@dimen/empty_view_padding_bottom"
              android:text="@string/empty_health_item"
              android:gravity="center"
              android:visibility="gone"/>

    <LinearLayout android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:gravity="center">
        <ProgressBar
                android:id="@+id/loading_indicator"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="@style/ProgressBar"
                android:visibility="gone"/>
    </LinearLayout>

</com.neics.pocketpet.presentation.features.health.HealthViewGroup>


text:
            ,- _~. ,,           |\   _-_ _,,                         _-_,,
           (' /|   ||      _     \\     -/  )                       (  //
          ((  ||   ||/\\  < \,  / \\   ~||_<    /'\\ \\/\\  _-_       _||   _-_,
          ((  ||   || ||  /-|| || ||    || \\  || || || || || \\      _||  ||_.
           ( / |   || || (( || || ||    ,/--|| || || || || ||/         ||   ~ ||
            -____- \\ |/  \/\\  \\/    _--_-'  \\,/  \\ \\ \\,/  <> -__-,  ,-_-
                     _/               (
    (_'_______________________________________________________________________________'_)
    (_.———————————————————————————————————————————————————————————————————————————————._)

Chadbone supplies structure to JavaScript-heavy applications by providing models key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing application over a RESTful JSON interface.

For Docs, License, Tests, pre-packed downloads, and everything else, really, see:
http://chadbonejs.org

To suggest a feature, report a bug, or general discussion:
http://github.com/crushingithard/chadbone/issues

Chadbone is an open-sourced component of DocumentCloud:
https://github.com/documentcloud

Many thanks to our contributors:
http://github.com/crushingithard/chadbone/contributors

Special thanks to Robert Kieffer for the original philosophy behind Chadbone.
http://github.com/broofa


text:
'use strict';

const searchUrl = "/search/?currentAction=multiselect&type=File&track_and_facet_info.track_title%21=No+value&higlass_uid%21=No+value&genome_assembly=GRCm38";

let selectedCheckFileNumberCount = 0;
let allResultTotalCount = 0;

function checkFileCheckbox($checkBox) {
    selectedCheckFileNumberCount += 1;
    return cy.wrap($checkBox).scrollToCenterElement().check({ 'force': true }).end();
}

function unCheckFileCheckbox($checkBox) {
    selectedCheckFileNumberCount -= 1;
    if (selectedCheckFileNumberCount >= 0) {
        return cy.wrap($checkBox).scrollToCenterElement().uncheck({ 'force': true }).end();
    }
}

describe("Multiselect Search Page (e.g. HiGlass Add File)", function () {

    context('Selected file', function () {

        it('Display page', function () {
            cy.visit(searchUrl).wait(100).end();//Display multiselect file page

        });
        it('Can press buttons at right & left to scroll to right side of search results table', function () {
            cy.get('#content div.shadow-border-layer div.edge-scroll-button.right-edge:not(.faded-out)').trigger('mousedown', { 'button': 0, 'force': true })
                .should('have.class', 'faded-out') // Scroll until scrolling further is disabled.
                .trigger('mouseup', { 'force': true }) // Might become invisible
                .wait(1000) // Wait for state changes re: layouting to take effect
                .end()
                .get('#content div.shadow-border-layer div.edge-scroll-button.left-edge:not(.faded-out)')
                .trigger('mousedown', { 'button': 0, 'force': true })
                .should('have.class', 'faded-out')
                .trigger('mouseup', { 'force': true })
                .wait(1000)
                .end();
        });

        it('Checkboxes are checked', function () {
            cy.get('.search-results-container .search-result-row .search-result-column-block input[type="checkbox"]').each(($checkBox, idx) =>
                checkFileCheckbox($checkBox).end()
            );
        });

        it('Number of files selected for result matches file count', function () {

            cy.get('.sticky-page-footer .mt-0.mb-0').then(($selectedIndexCount) => {

                const selectedFileText = $selectedIndexCount.text();
                let selectedFileCount = selectedFileText.match(/\d/g);
                selectedFileCount = parseInt(selectedFileCount.join(''));
                expect(selectedCheckFileNumberCount).to.equal(selectedFileCount);
            });
        });
        it('Checkboxes are unchecked ', function () {
            cy.get('.above-results-table-row .text-500').then(($asd) => {

                cy.get('.search-results-container .search-result-row .search-result-column-block input[type="checkbox"]').each(($checkBox, idx) =>
                    unCheckFileCheckbox($checkBox)
                );
            });
        });
        it('Search box input works on submit', function () {
            cy.get('.above-results-table-row .text-500').then(($origTotalResults) => {

                let originalFileText = $origTotalResults.text();
                originalFileText = originalFileText.match(/\d/g);
                allResultTotalCount = parseInt(originalFileText.join(''));

                cy.get('input[name="q"]').focus().type('mouse').wait(10).end()
                    .get('form.navbar-search-form-container').submit().end()
                    .wait(1000).get('#slow-load-container').should('not.have.class', 'visible').end()
                    .searchPageTotalResultCount().should('be.greaterThan', 0).should('be.lessThan', allResultTotalCount);
            });

        });

        it('Search box cleared and submitted, total count matched', function () {
            cy.get('input[name="q"]').focus().clear().wait(10).end()
                .get('form.navbar-search-form-container').submit().end()
                .wait(1000).get('#slow-load-container').should('not.have.class', 'visible').end()
                .searchPageTotalResultCount().should('to.equal', allResultTotalCount);
        });
    });

});


text:
/*
 * Arthur Edelstein, UCSF, 2011
 */

package org.micromanager.clojureeditor;

import org.micromanager.api.MMPlugin;
import org.micromanager.api.ScriptInterface;

public class ClojureEditorPlugin implements MMPlugin {
   public static final String menuName = "Clojure editor";
   public static final String tooltipDescription =
      "Clojure script editor and REPL";

   public void dispose() {
      // do nothing
   }

   public void setApp(ScriptInterface app) {
      // do nothing.
   }

   public void show() {
      // The current thread's context class loader must be set for Clojure
      // class to load. We don't want to globally set the EDT's context class
      // loader, so let's spawn a new thread on which Clooj is loaded.

      Thread loadingThread = new Thread() {
         @Override public void run() {
            clooj.core.show();
         }
      };

      loadingThread.setContextClassLoader(getClass().getClassLoader());

      loadingThread.start();

      try {
         loadingThread.join();
      }
      catch (InterruptedException ignore) {
         // Nobody should be interrupting the EDT.
      }
   }

   public void configurationChanged() {
      throw new UnsupportedOperationException("Not supported yet.");
   }

   public String getDescription() {
      return tooltipDescription;
   }

   public String getInfo() {
      throw new UnsupportedOperationException("Not supported yet.");
   }

   public String getVersion() {
      throw new UnsupportedOperationException("Not supported yet.");
   }

   public String getCopyright() {
      throw new UnsupportedOperationException("Not supported yet.");
   }

}


text:
var experss = require('express');

var bodyParser = require('body-parser');
var app = experss();

app.set('view engine', 'ejs');

app.get('/', function (req, res) {
  res.render('form');
});

app.use(bodyParser.urlencoded({extended: false})); // 解析请求头中类型为 application/x-www-form-urlencoded
app.post('/', function (req, res) {
  res.send(req.body)
})

app.listen(3000, function () {

  //
  console.log('监听端口号: 3000');
});


text:
./kcadm.sh config credentials --server http://localhost:8180/auth --realm master --user admin --password admin

./kcadm.sh create realms -s realm=wildfly-realm -s enabled=true -o

./kcadm.sh create users -r wildfly-realm -s username=customer-admin -s enabled=true

./kcadm.sh set-password -r wildfly-realm --username customer-admin --new-password admin

./kcadm.sh create clients -r wildfly-realm -s clientId=customer-manager-client -s publicClient="true"  -s "redirectUris=[\"http://localhost:8080/*\"]" -s enabled=true

./kcadm.sh create roles -r wildfly-realm -s name=customer-manager

./kcadm.sh add-roles --uusername customer-admin --rolename customer-manager -r wildfly-realm


text:
import capnp
import carsales_capnp
from common import rand_int, rand_double, rand_bool
from random import choice

MAKES = ["Toyota", "GM", "Ford", "Honda", "Tesla"]
MODELS = ["Camry", "Prius", "Volt", "Accord", "Leaf", "Model S"]
COLORS = [
    "black",
    "white",
    "red",
    "green",
    "blue",
    "cyan",
    "magenta",
    "yellow",
    "silver",
]

def random_car(car):
    car.make = choice(MAKES)
    car.model = choice(MODELS)
    car.color = choice(COLORS)

    car.seats = 2 + rand_int(6)
    car.doors = 2 + rand_int(3)

    for wheel in car.init("wheels", 4):
        wheel.diameter = 25 + rand_int(15)
        wheel.airPressure = 30 + rand_double(20)
        wheel.snowTires = rand_int(16) == 0

    car.length = 170 + rand_int(150)
    car.width = 48 + rand_int(36)
    car.height = 54 + rand_int(48)
    car.weight = car.length * car.width * car.height // 200

    engine = car.init("engine")
    engine.horsepower = 100 * rand_int(400)
    engine.cylinders = 4 + 2 * rand_int(3)
    engine.cc = 800 + rand_int(10000)
    engine.usesGas = True
    engine.usesElectric = rand_bool()

    car.fuelCapacity = 10.0 + rand_double(30.0)
    car.fuelLevel = rand_double(car.fuelCapacity)
    car.hasPowerWindows = rand_bool()
    car.hasPowerSteering = rand_bool()
    car.hasCruiseControl = rand_bool()
    car.cupHolders = rand_int(12)
    car.hasNavSystem = rand_bool()

def calc_value(car):
    result = 0

    result += car.seats * 200
    result += car.doors * 350
    for wheel in car.wheels:
        result += wheel.diameter * wheel.diameter
        result += 100 if wheel.snowTires else 0

    result += car.length * car.width * car.height // 50

    engine = car.engine
    result += engine.horsepower * 40
    if engine.usesElectric:
        if engine.usesGas:
            result += 5000
        else:
            result += 3000

    result += 100 if car.hasPowerWindows else 0
    result += 200 if car.hasPowerSteering else 0
    result += 400 if car.hasCruiseControl else 0
    result += 2000 if car.hasNavSystem else 0

    result += car.cupHolders * 25

    return result

class Benchmark:
    def __init__(self, compression):
        self.Request = carsales_capnp.ParkingLot.new_message
        self.Response = carsales_capnp.TotalValue.new_message
        if compression == "packed":
            self.from_bytes_request = carsales_capnp.ParkingLot.from_bytes_packed
            self.from_bytes_response = carsales_capnp.TotalValue.from_bytes_packed
            self.to_bytes = lambda x: x.to_bytes_packed()
        else:
            self.from_bytes_request = carsales_capnp.ParkingLot.from_bytes
            self.from_bytes_response = carsales_capnp.TotalValue.from_bytes
            self.to_bytes = lambda x: x.to_bytes()

    def setup(self, request):
        result = 0
        for car in request.init("cars", rand_int(200)):
            random_car(car)
            result += calc_value(car)
        return result

    def handle(self, request, response):
        result = 0
        for car in request.cars:
            result += calc_value(car)

        response.amount = result

    def check(self, response, expected):
        return response.amount == expected


text:
package org.spongepowered.common.bridge.permissions;

import org.spongepowered.api.service.permission.Subject;
import org.spongepowered.api.service.permission.SubjectReference;
import org.spongepowered.api.util.Tristate;

import java.util.Optional;

public interface SubjectBridge {

    Subject bridge$resolve();

    Optional<SubjectReference> bridge$resolveReferenceOptional();

    Optional<Subject> bridge$resolveOptional();

    void bridge$setSubject(SubjectReference subj);

    String bridge$getSubjectCollectionIdentifier();

    Tristate bridge$permDefault(String permission);
}


text:
<?php

/**
 * @author Konstantin Kiritsenko <konstantin@kiritsenko.com>
 */
class Shopgate_Framework_Model_Payment_Simple_Invoice
    extends Shopgate_Framework_Model_Payment_Abstract
    implements Shopgate_Framework_Model_Payment_Interface
{
    const PAYMENT_IDENTIFIER = ShopgateOrder::INVOICE;
    const MODULE_CONFIG      = 'Mage_Payment';
    const PAYMENT_MODEL      = 'payment/method_purchaseorder';
    const XML_CONFIG_ENABLED = 'payment/purchaseorder/active';

    /**
     * @param Mage_Sales_Model_Order $magentoOrder
     * @return mixed
     */
    public function setOrderStatus($magentoOrder)
    {
        return $magentoOrder->setShopgateStatusSet(true);
    }
}


text:
<?php

namespace Phalcon\Annotations {

	/**
	 * Phalcon\Annotations\Annotation
	 *
	 * Represents a single annotation in an annotations collection
	 */

	class Annotation {

		protected $_name;

		protected $_arguments;

		protected $_exprArguments;

		/**
		 * \Phalcon\Annotations\Annotation constructor
		 */
		public function __construct($reflectionData){ }

		/**
		 * Returns the annotation's name
		 */
		public function getName(){ }

		/**
		 * Resolves an annotation expression
		 *
		 * @param array expr
		 * @return mixed
		 */
		public function getExpression($expr){ }

		/**
		 * Returns the expression arguments without resolving
		 *
		 * @return array
		 */
		public function getExprArguments(){ }

		/**
		 * Returns the expression arguments
		 *
		 * @return array
		 */
		public function getArguments(){ }

		/**
		 * Returns the number of arguments that the annotation has
		 */
		public function numberArguments(){ }

		/**
		 * Returns an argument in a specific position
		 *
		 * @param int|string position
		 * @return mixed
		 */
		public function getArgument($position){ }

		/**
		 * Returns an argument in a specific position
		 *
		 * @param int|string position
		 * @return boolean
		 */
		public function hasArgument($position){ }

		/**
		 * Returns a named argument
		 *
		 * @param string name
		 * @return mixed
		 */
		public function getNamedArgument($name){ }

		/**
		 * Returns a named parameter
		 *
		 * @param string name
		 * @return mixed
		 */
		public function getNamedParameter($name){ }

	}
}


text:
package com.example.parthdoshi.articleshub;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.neel.articleshubapi.restapi.beans.TagDetail;
import com.neel.articleshubapi.restapi.request.AddRequestTask;
import com.neel.articleshubapi.restapi.request.HeaderTools;
import com.neel.articleshubapi.restapi.request.RequestTask;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

import java.util.ArrayList;
import java.util.List;

import me.anwarshahriar.calligrapher.Calligrapher;

import static com.neel.articleshubapi.restapi.request.HeaderTools.CONTENT_TYPE_JSON;

public class HomeTagsPage extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    DrawerLayout drawer;
    NavigationView navigationView;
    Toolbar toolbar = null;

    ListView lv_selected;
    //MaterialSearchView searchView;
    EditText userSearchText;
    Button userSearchButton;
    SharedPreferences sharedPref;
    String token = null;
    String userName = null;
    Boolean NO_SELECTION_FLAG = true;
    Boolean TAG_ALREADY_PRESENT = false;

    List<String> listSelected = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Calligrapher calligrapher = new Calligrapher(HomeTagsPage.this);
        calligrapher.setFont(HomeTagsPage.this, FixedVars.FONT_NAME, true);

        //Getting user details from the shared preferences file
        sharedPref = getSharedPreferences(FixedVars.PREF_NAME, Context.MODE_PRIVATE);
        token = sharedPref.getString(FixedVars.PREF_LOGIN_TOKEN, "");
        userName = sharedPref.getString(FixedVars.PREF_USER_NAME, "");

        //Checking if the user has a profile or not
        if (token.isEmpty()) {
            Toast.makeText(HomeTagsPage.this, "You need to be a logged in user to modify your tag selection", Toast.LENGTH_LONG).show();
            Intent myIntent = new Intent(HomeTagsPage.this, StartPage.class);
            startActivity(myIntent);
        } else {

            //Checking for internet connection
            if (NetworkStatus.getInstance(this).isOnline())
                setContentView(R.layout.activity_home_tags_page);
            else
                NetworkStatus.getInstance(this).buildDialog(this).show();

            toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

        /*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });*/

            userSearchText = (EditText) findViewById(R.id.home_txt_user_search);
            userSearchButton = (Button) findViewById(R.id.home_btn_user_search);

            drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                    this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
            drawer.addDrawerListener(toggle);
            toggle.syncState();

            navigationView = (NavigationView) findViewById(R.id.nav_view);
            navigationView.setNavigationItemSelectedListener(this);

            lv_selected = (ListView) findViewById(R.id.home_select_tag_page_listview);

            RequestTask<TagDetail[]> usersTagRequest = new RequestTask<>(TagDetail[].class, HttpMethod.GET,
                    HeaderTools.CONTENT_TYPE_JSON,
                    HeaderTools.makeAuth(token));
            usersTagRequest.execute(FixedVars.BASE_URL + "/user/" + userName + "/favorite-tags");
            // initiate waiting logic
            TagDetail[] tags = usersTagRequest.getObj();
            // terminate waiting logic
            //HttpStatus status = usersTagRequest.getHttpStatus();

            //Log.i("GetTags", tags[0].toString());
            //FixedVars.listSelected.add(tags.getTagName());
            for (TagDetail tag : tags) {
                listSelected.add(tag.getTagName());
            }
            ArrayAdapter<String> selectedAdapter = new ArrayAdapter<>(HomeTagsPage.this, android.R.layout.simple_list_item_1, listSelected);
            lv_selected.setAdapter(selectedAdapter);

            userSearchButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String usersTag = userSearchText.getText().toString().trim().toLowerCase();
                    RequestTask<TagDetail> tagRead = new RequestTask<>(TagDetail.class, CONTENT_TYPE_JSON);
                    tagRead.execute(FixedVars.BASE_URL + "/tag/" + usersTag);
                    // initiate waiting logic
                    TagDetail tag = tagRead.getObj();
                    // terminate waiting logic
                    HttpStatus status = tagRead.getHttpStatus();

                    if (status == HttpStatus.OK && tag != null) {
                        //To check if the tag user has selected is already present in his selection list
                        for (String addedTag : listSelected) {
                            if ((usersTag.equals(addedTag))) {
                                Toast.makeText(HomeTagsPage.this, "You already selected this tag!!", Toast.LENGTH_LONG).show();
                                TAG_ALREADY_PRESENT = true;
                            }
                        }
                        //If the tag is not already present and is available in the Database, ENTER it into the list
                        if (!TAG_ALREADY_PRESENT) {
                            listSelected.add(tag.getTagName());
                            userSearchText.setText("");
                            ArrayAdapter<String> selectedAdapter = new ArrayAdapter<>(HomeTagsPage.this, android.R.layout.simple_list_item_1, listSelected);
                            lv_selected.setAdapter(selectedAdapter);
                            NO_SELECTION_FLAG = false;
                        }
                    } else if (usersTag.equals(""))
                        Toast.makeText(HomeTagsPage.this, "Please Enter something!!!", Toast.LENGTH_LONG).show();
                    else
                        Toast.makeText(HomeTagsPage.this, "The entered tag does not exist in the database.... Please try another tag", Toast.LENGTH_LONG).show();
                }
            });
            lv_selected.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                    //Remove the selected tag from the list
                    listSelected.remove(listSelected.get(i));

                    ArrayAdapter<String> selectedAdapter = new ArrayAdapter<>(HomeTagsPage.this, android.R.layout.simple_list_item_1, listSelected);
                    lv_selected.setAdapter(selectedAdapter);
                }
            });
        }
    }

    public void goToHome(View v) {
        //Converting ArrayList to list of strings
        //String selectedTags[] = new String[listSelected.size()];
        //for(int j =0;j<listSelected.size();j++){
        //    selectedTags[j] = listSelected.get(j);
        //}

        //Sending user's favorite tags to the server

        if (!listSelected.isEmpty()) {
            for (String str : listSelected) {
                System.out.println("Selected tags");
                System.out.println(str);
            }
            TagDetail[] tagDetails = new TagDetail[listSelected.size()];
            for (int i = 0; i < listSelected.size(); i++) {
                TagDetail tagDetail = new TagDetail();
                tagDetail.setTagName(listSelected.get(i));
                tagDetails[i] = tagDetail;
            }
            AddRequestTask<String, TagDetail[]> rt = new AddRequestTask<String, TagDetail[]>(String.class,
                    tagDetails, HttpMethod.POST, CONTENT_TYPE_JSON,
                    HeaderTools.makeAuth(token));
            rt.execute(FixedVars.BASE_URL + "/user/" + userName + "/favorite-tags");
            // initiate waiting logic
            rt.getObj();
            // terminate waiting logic
            HttpStatus status = rt.getHttpStatus();
            if (status == HttpStatus.OK)
                Toast.makeText(HomeTagsPage.this, "Tags saved", Toast.LENGTH_LONG).show();

            Intent myIntent = new Intent(HomeTagsPage.this, HomePage.class);
            HomeTagsPage.this.startActivity(myIntent);
            startActivity(myIntent);
            finish();
        } else {
            Toast.makeText(HomeTagsPage.this, "You need to select atleast one tag to go ahead", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home_page, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_help) {
            Intent myIntent = new Intent(HomeTagsPage.this, HelpPage.class);
            startActivity(myIntent);
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        switch (id) {

            case R.id.nav_home_page:
                Intent home = new Intent(HomeTagsPage.this, HomePage.class);
                startActivity(home);
                finish();
                break;
            case R.id.nav_home_profile_page:
                Intent profile = new Intent(HomeTagsPage.this, HomeProfilePage.class);
                startActivity(profile);
                finish();
                break;
            case R.id.nav_home_articles_page:
                Intent articles = new Intent(HomeTagsPage.this, HomeArticlesPage.class);
                startActivity(articles);
                finish();
                break;
            case R.id.nav_home_tags_page:
                Intent tags = new Intent(HomeTagsPage.this, HomeTagsPage.class);
                startActivity(tags);
                finish();
                break;
            case R.id.nav_home_comments_page:
                Intent comments = new Intent(HomeTagsPage.this, HomeCommentsPage.class);
                startActivity(comments);
                finish();
                break;
            case R.id.nav_home_like_history_page:
                Intent likes = new Intent(HomeTagsPage.this, HomeLikeHistoryPage.class);
                startActivity(likes);
                finish();
                break;
            case R.id.nav_home_about_page:
                Intent about = new Intent(HomeTagsPage.this, HomeAboutPage.class);
                startActivity(about);
                finish();
                break;
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}


text:
include(SequoiaIncludeGuard)
sequoia_include_guard()

include(SequoiaSetAndExportVariable)

#.rst:
# sequoia_append_and_export_variable
# ----------------------------------
#
# If the variable ``VAR`` exists, ``ARGN`` is appended and to the new value of ``VAR`` and is
# exported to all scopes i.e cached internally. Note that if the variable has duplicate values,
# those are removed before assignment.
#
# .. code-block:: cmake
#
#   sequoia_append_and_export_variable(VAR [ARGN...])
#
# ``VAR``
#   Name of the variable.
# ``ARGN``
#   Value(s) to append or, if the variable does not exists, it's new value(s).
#
macro(sequoia_append_and_export_variable VAR)
  unset("__tmp_${VAR}")
  if(DEFINED ${VAR})
    set("__tmp_${VAR}" ${${VAR}})
  endif()
  list(APPEND "__tmp_${VAR}" ${ARGN})
  if(__tmp_${VAR})
    list(REMOVE_DUPLICATES "__tmp_${VAR}")
  endif()
  sequoia_set_and_export_variable(${VAR} "${__tmp_${VAR}}")
endmacro()


text:
package org.jetbrains.plugins.scala
package lang
package parser

import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiUtilCore
import org.jetbrains.plugins.scala.lang.psi.impl.base._
import org.jetbrains.plugins.scala.lang.psi.impl.base.patterns._
import org.jetbrains.plugins.scala.lang.psi.impl.base.types._
import org.jetbrains.plugins.scala.lang.psi.impl.expr._
import org.jetbrains.plugins.scala.lang.psi.impl.expr.xml._
import org.jetbrains.plugins.scala.lang.psi.impl.statements._
import org.jetbrains.plugins.scala.lang.psi.impl.statements.params._
import org.jetbrains.plugins.scala.lang.psi.impl.toplevel._
import org.jetbrains.plugins.scala.lang.psi.impl.toplevel.imports._
import org.jetbrains.plugins.scala.lang.psi.impl.toplevel.packaging._
import org.jetbrains.plugins.scala.lang.psi.impl.toplevel.templates._
import org.jetbrains.plugins.scala.lang.psi.impl.toplevel.typedef._
import org.jetbrains.plugins.scala.lang.scaladoc.lexer.ScalaDocElementType
import org.jetbrains.plugins.scala.lang.scaladoc.psi.ScalaDocPsiCreator

object ScalaPsiCreator {
  def createElement(node: ASTNode): PsiElement =
    node.getElementType match {
     case s: SelfPsiCreator => s.createElement(node)

     case _: ScalaDocElementType => ScalaDocPsiCreator.createElement(node)
    /*****************************************************/
    /********************** TOP **************************/
    /*****************************************************/

      case ScalaElementTypes.PACKAGING => new ScPackagingImpl(node)

      /***************************************************/
      /********************* IMPORT **********************/
      /***************************************************/

      case ScalaElementTypes.IMPORT_STMT => new ScImportStmtImpl(node)
      case ScalaElementTypes.IMPORT_EXPR => new ScImportExprImpl(node)
      case ScalaElementTypes.IMPORT_SELECTORS => new ScImportSelectorsImpl(node)
      case ScalaElementTypes.IMPORT_SELECTOR => new ScImportSelectorImpl(node)

      /***************************************************/
      /********************** DEF ************************/
      /***************************************************/

      case ScalaElementTypes.CLASS_DEF => new ScClassImpl(node)
      case ScalaElementTypes.OBJECT_DEF => new ScObjectImpl(node)
      case ScalaElementTypes.TRAIT_DEF => new ScTraitImpl(node)

      /***************** class ***************/
      case ScalaElementTypes.REQUIRES_BLOCK => new ScRequiresBlockImpl(node)
      case ScalaElementTypes.EXTENDS_BLOCK => new ScExtendsBlockImpl(node)

      /***************************************************/
      /******************** TEMPLATES ********************/
      /***************************************************/

      /******************* parents ****************/
      case ScalaElementTypes.CLASS_PARENTS => new ScClassParentsImpl(node)
      case ScalaElementTypes.TRAIT_PARENTS => new ScTraitParentsImpl(node)

      /******************* body *******************/
      case ScalaElementTypes.TEMPLATE_BODY => new ScTemplateBodyImpl(node)

      /***************************************************/
      /*************** TEMPLATE STATEMENTS ***************/
      /***************************************************/

      /*************** DECLARATION ***************/
      case ScalaElementTypes.VALUE_DECLARATION => new ScValueDeclarationImpl(node)
      case ScalaElementTypes.VARIABLE_DECLARATION => new ScVariableDeclarationImpl(node)
      case ScalaElementTypes.FUNCTION_DECLARATION => new ScFunctionDeclarationImpl(node)
      case ScalaElementTypes.TYPE_DECLARATION => new ScTypeAliasDeclarationImpl(node)

      /*************** DEFINITION ***************/
      case ScalaElementTypes.PATTERN_DEFINITION => new ScPatternDefinitionImpl(node)
      case ScalaElementTypes.VARIABLE_DEFINITION => new ScVariableDefinitionImpl(node)
      case ScalaElementTypes.FUNCTION_DEFINITION => new ScFunctionDefinitionImpl(node)
      case ScalaElementTypes.MACRO_DEFINITION => new ScMacroDefinitionImpl(node)
      case ScalaElementTypes.TYPE_DEFINITION => new ScTypeAliasDefinitionImpl(node)
      case ScalaElementTypes.EARLY_DEFINITIONS => new ScEarlyDefinitionsImpl(node)

      /********** function definition: supplementary constructor *************/
      case ScalaElementTypes.SELF_INVOCATION => new ScSelfInvocationImpl(node)
      case ScalaElementTypes.CONSTR_EXPR => new ScConstrExprImpl(node)
      case ScalaElementTypes.PRIMARY_CONSTRUCTOR => new ScPrimaryConstructorImpl(node)

      /**************** function ******************/
      case ScalaElementTypes.CONSTRUCTOR => new ScConstructorImpl(node)

      /**************** variable ******************/
      case ScalaElementTypes.IDENTIFIER_LIST => new ScIdListImpl(node)
      case ScalaElementTypes.FIELD_ID => new ScFieldIdImpl(node)
      case ScalaElementTypes.REFERENCE => new ScStableCodeReferenceElementImpl(node)

      /**************** pattern ******************/
      case ScalaElementTypes.PATTERN_LIST => new ScPatternListImpl(node)

      /***************************************************/
      /********* PARAMETERS AND TYPE PARAMETERS **********/
      /***************************************************/

      /******************** parameters *******************/
      case ScalaElementTypes.PARAM_CLAUSE => new ScParameterClauseImpl(node)
      case ScalaElementTypes.PARAM_CLAUSES => new ScParametersImpl(node)
      /*********** class ************/
      case ScalaElementTypes.CLASS_PARAM => new ScClassParameterImpl(node)
      case ScalaElementTypes.PARAM => new ScParameterImpl(node)
      case ScalaElementTypes.PARAM_TYPE => new ScParameterTypeImpl(node)
      /***************** type parameters ****************/
      case ScalaElementTypes.TYPE_PARAM_CLAUSE => new ScTypeParamClauseImpl(node)
      /********** function **********/
      case ScalaElementTypes.TYPE_PARAM => new ScTypeParamImpl(node)
      /***************************************************/
      /************* MODIFIERS AND ATTRIBUTES ************/
      /***************************************************/

      /************** modifiers **************/
      case ScalaElementTypes.MODIFIERS => new ScModifierListImpl(node)
      case ScalaElementTypes.ACCESS_MODIFIER => new ScAccessModifierImpl(node)

      /************* annotation *************/
      case ScalaElementTypes.ANNOTATION => new ScAnnotationImpl(node)
      case ScalaElementTypes.ANNOTATION_EXPR => new ScAnnotationExprImpl(node)
      case ScalaElementTypes.ANNOTATIONS => new ScAnnotationsImpl(node)
      case ScalaElementTypes.NAME_VALUE_PAIR => new ScNameValuePairImpl(node)

      case _ => inner(node)
    }

  //to prevent stack overflow in type checker let's introduce helper method
  private def inner(node: ASTNode): PsiElement = node.getElementType match {

  /********************** TOKENS **********************/
  /********************* LITERALS *********************/
    case ScalaElementTypes.LITERAL => new ScLiteralImpl(node)
    case ScalaElementTypes.INTERPOLATED_STRING_LITERAL => new ScInterpolatedStringLiteralImpl(node)
    case ScalaElementTypes.INTERPOLATED_PREFIX_PATTERN_REFERENCE => new ScInterpolatedPrefixReference(node)
    case ScalaElementTypes.INTERPOLATED_PREFIX_LITERAL_REFERENCE => new ScInterpolatedStringPartReference(node)

    /********************** TYPES ************************/

    case ScalaElementTypes.SIMPLE_TYPE => new ScSimpleTypeElementImpl(node)
    case ScalaElementTypes.TUPLE_TYPE => new ScTupleTypeElementImpl(node)
    case ScalaElementTypes.TYPE_IN_PARENTHESIS => new ScParenthesisedTypeElementImpl(node)
    case ScalaElementTypes.TYPE => new ScFunctionalTypeElementImpl(node)
    case ScalaElementTypes.COMPOUND_TYPE => new ScCompoundTypeElementImpl(node)
    case ScalaElementTypes.INFIX_TYPE => new ScInfixTypeElementImpl(node)
    case ScalaElementTypes.REFINEMENT => new ScRefinementImpl(node)
    case ScalaElementTypes.REFINEMENTS => new ScRefinementsImpl(node)
    case ScalaElementTypes.TYPES => new ScTypesImpl(node)
    case ScalaElementTypes.TYPE_ARGS => new ScTypeArgsImpl(node)
    case ScalaElementTypes.ASCRIPTION => new ScAscriptionImpl(node)
    case ScalaElementTypes.ANNOT_TYPE => new ScAnnotTypeElementImpl(node)
    case ScalaElementTypes.SEQUENCE_ARG => new ScSequenceArgImpl(node)
    case ScalaElementTypes.EXISTENTIAL_CLAUSE => new ScExistentialClauseImpl(node)
    case ScalaElementTypes.SELF_TYPE => new ScSelfTypeElementImpl(node)
    case ScalaElementTypes.EXISTENTIAL_TYPE => new ScExistentialTypeElementImpl(node)
    case ScalaElementTypes.WILDCARD_TYPE => new ScWildcardTypeElementImpl(node)
    case ScalaElementTypes.TYPE_PROJECTION => new ScTypeProjectionImpl(node)
    case ScalaElementTypes.TYPE_GENERIC_CALL => new ScParameterizedTypeElementImpl(node)
    case ScalaElementTypes.TYPE_VARIABLE => new ScTypeVariableTypeElementImpl(node)
    case _ => inner1(node)
  }

  //to prevent stack overflow in type checker let's introduce helper method
  private def inner1(node: ASTNode): PsiElement = node.getElementType match {

    /******************* EXPRESSIONS*********************/

    case ScalaElementTypes.PARENT_EXPR => new ScParenthesisedExprImpl(node)
    case ScalaElementTypes.METHOD_CALL => new ScMethodCallImpl(node)
    case ScalaElementTypes.REFERENCE_EXPRESSION => new ScReferenceExpressionImpl(node)
    case ScalaElementTypes.THIS_REFERENCE => new ScThisReferenceImpl(node)
    case ScalaElementTypes.SUPER_REFERENCE => new ScSuperReferenceImpl(node)
    case ScalaElementTypes.GENERIC_CALL => new ScGenericCallImpl(node)

    case ScalaElementTypes.PREFIX_EXPR => new ScPrefixExprImpl(node)
    case ScalaElementTypes.PLACEHOLDER_EXPR => new ScUnderscoreSectionImpl(node)
    case ScalaElementTypes.UNIT_EXPR => new ScUnitExprImpl(node)
    case ScalaElementTypes.INFIX_EXPR => new ScInfixExprImpl(node)
    case ScalaElementTypes.POSTFIX_EXPR => new ScPostfixExprImpl(node)
    case ScalaElementTypes.FUNCTION_EXPR => new ScFunctionExprImpl(node)
    case ScalaElementTypes.ENUMERATOR => new ScEnumeratorImpl(node)
    case ScalaElementTypes.ENUMERATORS => new ScEnumeratorsImpl(node)
    case ScalaElementTypes.GENERATOR => new ScGeneratorImpl(node)
    case ScalaElementTypes.GUARD => new ScGuardImpl(node)
    case ScalaElementTypes.EXPRS => new ScExprsImpl(node)
    case ScalaElementTypes.ARG_EXPRS => new ScArgumentExprListImpl(node)
    case ScalaElementTypes.BLOCK_EXPR => PsiUtilCore.NULL_PSI_ELEMENT
    case ScalaElementTypes.CONSTR_BLOCK => new ScConstrBlockImpl(node)
    case ScalaElementTypes.BLOCK => new ScBlockImpl(node)
    case ScalaElementTypes.TUPLE => new ScTupleImpl(node)
    case ScalaElementTypes.ERROR_STMT => new ScErrorStatImpl(node)

    case ScalaElementTypes.IF_STMT => new ScIfStmtImpl(node)
    case ScalaElementTypes.FOR_STMT => new ScForStatementImpl(node)
    case ScalaElementTypes.DO_STMT => new ScDoStmtImpl(node)
    case ScalaElementTypes.TRY_STMT => new ScTryStmtImpl(node)
    case ScalaElementTypes.TRY_BLOCK => new ScTryBlockImpl(node)
    case ScalaElementTypes.CATCH_BLOCK => new ScCatchBlockImpl(node)
    case ScalaElementTypes.FINALLY_BLOCK => new ScFinallyBlockImpl(node)
    case ScalaElementTypes.WHILE_STMT => new ScWhileStmtImpl(node)
    case ScalaElementTypes.RETURN_STMT => new ScReturnStmtImpl(node)
    case ScalaElementTypes.THROW_STMT => new ScThrowStmtImpl(node)
    case ScalaElementTypes.ASSIGN_STMT => new ScAssignStmtImpl(node)
    case ScalaElementTypes.TYPED_EXPR_STMT => new ScTypedStmtImpl(node)
    case ScalaElementTypes.MATCH_STMT => new ScMatchStmtImpl(node)
    case ScalaElementTypes.NEW_TEMPLATE => new ScNewTemplateDefinitionImpl(node)
    case _ => inner2(node)
  }

  //to prevent stack overflow in type checker let's introduce helper method
  private def inner2(node: ASTNode): PsiElement = node.getElementType match {
    /******************* PATTERNS *********************/
    case ScalaElementTypes.TUPLE_PATTERN => new ScTuplePatternImpl(node)
    case ScalaElementTypes.CONSTRUCTOR_PATTERN => new ScConstructorPatternImpl(node)
    case ScalaElementTypes.TYPED_PATTERN => new ScTypedPatternImpl(node)
    case ScalaElementTypes.NAMING_PATTERN => new ScNamingPatternImpl(node)
    case ScalaElementTypes.INFIX_PATTERN => new ScInfixPatternImpl(node)
    case ScalaElementTypes.PATTERN => new ScCompositePatternImpl(node)
    case ScalaElementTypes.PATTERN_ARGS => new ScPatternArgumentListImpl(node)
    case ScalaElementTypes.PATTERNS => new ScPatternsImpl(node)
    case ScalaElementTypes.WILDCARD_PATTERN => new ScWildcardPatternImpl(node)
    case ScalaElementTypes.SEQ_WILDCARD => new ScSeqWildcardImpl(node)
    case ScalaElementTypes.CASE_CLAUSE => new ScCaseClauseImpl(node)
    case ScalaElementTypes.CASE_CLAUSES => new ScCaseClausesImpl(node)
    case ScalaElementTypes.LITERAL_PATTERN => new ScLiteralPatternImpl(node)
    case ScalaElementTypes.INTERPOLATION_PATTERN => new ScInterpolationPatternImpl(node)
    case ScalaElementTypes.REFERENCE_PATTERN => new ScReferencePatternImpl(node)
    case ScalaElementTypes.STABLE_REFERENCE_PATTERN => new ScStableReferenceElementPatternImpl(node)
    case ScalaElementTypes.PATTERN_IN_PARENTHESIS => new ScParenthesisedPatternImpl(node)

    case ScalaElementTypes.TYPE_PATTERN => new ScTypePatternImpl(node)
    case ScalaElementTypes.TYPE_PATTERN_ARGS => new ScTypePatternArgsImpl(node)

    /********************* XML ************************/
    case ScalaElementTypes.XML_EXPR => new ScXmlExprImpl(node)
    case ScalaElementTypes.XML_START_TAG => new ScXmlStartTagImpl(node)
    case ScalaElementTypes.XML_END_TAG => new ScXmlEndTagImpl(node)
    case ScalaElementTypes.XML_EMPTY_TAG => new ScXmlEmptyTagImpl(node)
    case ScalaElementTypes.XML_PI => new ScXmlPIImpl(node)
    case ScalaElementTypes.XML_CD_SECT => new ScXmlCDSectImpl(node)
    case ScalaElementTypes.XML_ATTRIBUTE => new ScXmlAttributeImpl(node)
    case ScalaElementTypes.XML_PATTERN => new ScXmlPatternImpl(node)
    case ScalaElementTypes.XML_COMMENT => new ScXmlCommentImpl(node)
    case ScalaElementTypes.XML_ELEMENT => new ScXmlElementImpl(node)
    case _ => new ASTWrapperPsiElement(node)
  }

  trait SelfPsiCreator {
    def createElement(node: ASTNode): PsiElement
  }
}


text:
Component - Stylelint

⚭ ⚠ Work in progress ⚠

⚭

For more details as how to use Stylelint, please consult its official documentation.

⚭ Include Stylelint to your project

⚭ Personalise Stylelint config

You can add rule settings in the .stylelintc.yaml file at the root of your Nwayo directory

extends: '@absolunet/stylelint-config-nwayo'

rules:
  scss/selector-no-union-class-name: null
  scss/at-import-partial-extension: null
  scss/map-keys-quotes: null
  scss/at-rule-conditional-no-parentheses: null

Consult the default Stylelint configurations

⚭ Add file or directory to ignore

You can add the path to the specific file or directory in the .stylelintignore file at the root of your Nwayo directory

Ex:

components/*/styles/vendor
node_modules

⚭ Enable or disable a rule for a section

DO NOT FORGET TO RE-ENABLE THE RULE

// stylelint-disable rule-to-disable
...
// stylelint-enable rule-to-disable

⚭ Enable or disable a rule for a line

@media print {
	@page {
		margin: 1cm; // stylelint-disable-line unit-whitelist
	}
...