text:
title: Identity v4
layout: reference
---
# Identity v4

* [Limitations](#limitations)
* [Products and Editions](#products-editions)
* [Scope Usage](#scope-usage)
* [Dependencies](#dependencies)
* [Access Token Usage](#access-token-usage)
* [Retrieve Users](#GET-user)
* [Retrieve a User's Identity Profile](#GET-user-identity)
* Create a User's Identity Profile
* Update a User's Identity Profile
* Replace a User's Identity Profile
* [Schema](#schema)
  * [User](#schema-user)
  * [User List](#schema-userlist)
  * Company
  * [Schema Extension](#schema-schemaextension)
  * [Resource Type](#schema-resourcetype)
  * [Authenticated Schemas](#schema-authenticatedschemas)
  * [Service Provider Config](#schema-serviceproviderconfig)
  * [Service Provider Config Setting](#schema-serviceproviderconfigsetting)
  * [Concur Error](#schema-concurerror)
  * [Error Response](#schema-errorresponse)

The Identity v4 service is designed to create, update, and read user's core identity profile. This service is also available to look up the SAP Concur UUID to access any v4 API for a single user only.

This API is used to help provision and manage user accounts and profile details across multiple SAP Concur products, including Expense, Invoice, Request, Travel, and TripIt.

## Limitations

Only the GET operations are available at this time. This API is not available in the China Data Center. This API is only available to partners who have been granted access by SAP Concur. Access to this documentation does not provide access to the API.

## Products and Editions

* Concur Expense Professional Edition
* Concur Expense Standard Edition
* Concur Travel Professional Edition
* Concur Travel Standard Edition
* Concur Invoice Professional Edition
* Concur Invoice Standard Edition
* Concur Request Professional Edition
* Concur Request Standard Edition

## Scope Usage

Name|Description|Endpoint
---|---|---
`identity.user.ids.read`|Read user ID data.|GET
`identity.user.core.read`|Read user core data.|GET
`identity.user.coresensitive.read`|Read core sensitive data.|GET
`identity.user.enterprise.read`|Read user enterprise data.|GET
`identity.user.coreenterprise.writeonly`|Write access to all core and enterprise fields except `externalID`.|PUT, POST, PATCH
`identity.user.externalID.writeonly`|Write access to `externalID` only.|PUT, POST, PATCH

For more information on scope usage and mapping, please see the [Identity v4 Scope Mapping](./v4.scope-mapping.html) page.

## Dependencies

None.

## Access Token Usage

This API supports only company level access tokens.

## Retrieve Users

Retrieves all users of a given company. The filter operation can be used to fetch a unique user's identity information.

### Request

#### URI

##### Template

```
GET https://us.api.concursolutions.com/profile/identity/v4/Users
```

```
GET https://us.api.concursolutions.com/profile/identity/v4/Users?count=20
```

```
GET https://us.api.concursolutions.com/profile/identity/v4/Users/<UUID>
```

```
GET https://us.api.concursolutions.com/profile/identity/v4/Users?filter=attributes eq "value"
```

##### Parameters

Name|Type|Format|Description
---|---|---|---
`filter`|`string`|-|The filter string used to request a subset of resources.
`attributes`|`object`|-|A multi-valued list of strings indicating the names of resource attributes to return in the response. It is comma delimited.
`userName`|`string`|`user@domain`|The requested user's username. NOTE: The `userName` must be unique across all SAP Concur products. If a `userName` is currently in use in any SAP Concur product, it cannot be assigned again unless the original occurrence is changed. For example, assume that a `userName` was assigned in error. That `userName` can only be used again if an admin (either manually or via import) renames the original occurrence, allowing the `userName` to be used again. The following characters cannot be used as a value for this record: % [ # ! * & ( ) ~  ' { ^ } \ / ? > < , ; : " + = ], and pipe.
`companyId`|`string`|-|**Required, if `employeeNumber` is used** The ID of the company the user belongs to.
`employeeNumber`|`string`|-|**Required, if `companyId` is used** User's employee number.
`externalId`|`string`|-|User's external ID.
`excludedAttributes`|`string`|-|A multi-valued list of strings indicating the names of resource attributes to be removed from the default set of attributes to return.
`startIndex`|`string`|-|The 1-based index of the first query result. Default: `1`
`count`|`string`|-|The desired maximum number of query results per page. Maximum count: `100`. Default: `10`

#### Headers

* [RFC 7235 Authorization](https://tools.ietf.org/html/rfc7235#section-4.2)

#### Payload

None.

### Response

#### Status Codes

* [200 OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)
* [400 Bad Request](https://tools.ietf.org/html/rfc7231#section-6.5.1)
* [401 Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1)
* [404 Not Found](https://tools.ietf.org/html/rfc7231#section-6.5.4)
* [500 Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1)
* [501 Not Implemented](https://tools.ietf.org/html/rfc7231#section-6.6.2)
* [502 Bad Gateway](https://tools.ietf.org/html/rfc7231#section-6.6.3)
* [503 Service Unavailable](https://tools.ietf.org/html/rfc7231#section-6.6.4)
* [504 Gateway Timeout](https://tools.ietf.org/html/rfc7231#section-6.6.5)

#### Headers

* `concur-correlationid` is a SAP Concur specific custom header used for technical support in the form of a [RFC 4122 A Universally Unique IDentifier (UUID) URN Namespace](https://tools.ietf.org/html/rfc4122)
* [RFC 7231 Content-Type](https://tools.ietf.org/html/rfc7231#section-3.1.1.5)

#### Payload

[User Schema](#schema-user)

### Example

#### Request

```
GET https://us.api.concursolutions.com/profile/identity/v4/users/
Accept: application/json
Authorization: BEARER {token}
```

#### Response

```
200 OK
Content-Type: application/json
```

```json
{
  "schemas": [
    "urn:ietf:params:scim:api:messages:2.0:ListResponse"
  ],
  "totalResults": 107705,
  "startIndex": 1,
  "itemsPerPage": 20,
  "Resources": [
    { User 1 …},
    {User 2…},…
    {User 20…}
  ]
}
```

## Retrieve a User's Identity Profile

Retrieves a unique user based on the user's UUID.

### Request

#### URI

##### Template

```
GET https://us.api.concursolutions.com/profile/identity/v4/Users/
```
##### Parameters

Name|Type|Format|Description
---|---|---|---
`id`|`string`|-|Requested user's UUID.

#### Headers

* [RFC 7235 Authorization](https://tools.ietf.org/html/rfc7235#section-4.2)

#### Payload

None.

### Response

#### Status Codes

* [200 OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)
* [400 Bad Request](https://tools.ietf.org/html/rfc7231#section-6.5.1)
* [401 Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1)
* [404 Not Found](https://tools.ietf.org/html/rfc7231#section-6.5.4)
* [500 Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1)
* [501 Not Implemented](https://tools.ietf.org/html/rfc7231#section-6.6.2)
* [502 Bad Gateway](https://tools.ietf.org/html/rfc7231#section-6.6.3)
* [503 Service Unavailable](https://tools.ietf.org/html/rfc7231#section-6.6.4)
* [504 Gateway Timeout](https://tools.ietf.org/html/rfc7231#section-6.6.5)

#### Headers

* `concur-correlationid` is a SAP Concur specific custom header used for technical support in the form of a [RFC 4122 A Universally Unique IDentifier (UUID) URN Namespace](https://tools.ietf.org/html/rfc4122)
* [RFC 7231 Content-Type](https://tools.ietf.org/html/rfc7231#section-3.1.1.5)

#### Payload

[User Schema](#schema-user)

### Example

#### Request

```
GET https://us.api.concursolutions.com/profile/identity/v4/Users/
Accept: application/json
Authorization: BEARER {token}
```

#### Response

```
200 OK
Content-Type: application/json
```

```json
{
  "active": true,
  "addresses": [
    {
      "country": "string",
      "locality": "string",
      "postalCode": "string",
      "region": "string",
      "streetAddress": "string",
      "type": "work"
    }
  ],
  "dateOfBirth": "string",
  "displayName": "string",
  "emails": [
    {
      "dateAdded": "string",
      "dateVerified": "string",
      "notifications": true,
      "type": "work",
      "value": "string",
      "verified": true
    }
  ],
  "emergencyContacts": [
    {
      "country": "string",
      "emails": [
        "string"
      ],
      "locality": "string",
      "name": "string",
      "phones": [
        "string"
      ],
      "postalCode": "string",
      "region": "string",
      "relationship": "Spouse",
      "streetAddress": "string"
    }
  ],
  "entitlements": [
    "Expense"
  ],
  "externalId": "string",
  "gender": "Male",
  "id": "string",
  "localeOverrides": {
    "preference24Hour": "h:mm AM/PM",
    "preferenceCurrencySymbolLocation": "BeforeAmount",
    "preferenceDateFormat": "mm/dd/yyyy",
    "preferenceDefaultCalView": "day",
    "preferenceDistance": "mile",
    "preferenceEndDayViewHour": 0,
    "preferenceFirstDayOfWeek": "Monday",
    "preferenceHourMinuteSeparator": ":",
    "preferenceNegativeCurrencyFormat": "-100",
    "preferenceNegativeNumberFormat": "-100",
    "preferenceNumberFormat": "1,000.00",
    "preferenceStartDayViewHour": 0
  },
  "meta": {},
  "name": {
    "familyName": "string",
    "formatted": "string",
    "givenName": "string",
    "hasNoMiddleName": true,
    "honorificPrefix": "Miss",
    "honorificSuffix": "Jr.",
    "legalName": "string",
    "middleInitial": "string",
    "middleName": "string"
  },
  "nickName": "string",
  "phoneNumbers": [
    {
      "display": "string",
      "notifications": true,
      "operatingSystem": "Android Phone",
      "primary": true,
      "type": "work",
      "value": "string"
    }
  ],
  "preferredLanguage": "string",
  "schemas": [
    "urn:ietf:params:scim:schemas:core:2.0:User"
  ],
  "timezone": "string",
  "title": "string",
  "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": {
    "companyId": "string",
    "costCenter": "string",
    "department": "string",
    "division": "string",
    "employeeNumber": "string",
    "manager": {
      "$ref": "string",
      "displayName": "string",
      "employeeNumber": "string",
      "value": "string"
    },
    "orgUnit": "string",
    "organization": "string",
    "self": {
      "$ref": "string",
      "displayName": "string",
      "employeeNumber": "string",
      "value": "string"
    },
    "startDate": "string",
    "terminationDate": "string"
  },
  "userName": "string"
}
```

## Create a User's Identity Profile

{% include prerelease.html %}

Creates a user's identity profile.

### Request

#### URI

##### Template

```
POST https://us.api.concursolutions.com/profile/identity/v4/Users
```
##### Parameters

Name|Type|Format|Description
---|---|---|---
`user`|`string`|-|The user identity to create.

#### Headers

* [RFC 7231 Content-Type](https://tools.ietf.org/html/rfc7231#section-3.1.1.5)
* [RFC 7235 Authorization](https://tools.ietf.org/html/rfc7235#section-4.2)

#### Payload

None.

### Response

#### Status Codes

* [200 OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)
* [400 Bad Request](https://tools.ietf.org/html/rfc7231#section-6.5.1)
* [401 Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1)
* [404 Not Found](https://tools.ietf.org/html/rfc7231#section-6.5.4)
* [500 Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1)
* [501 Not Implemented](https://tools.ietf.org/html/rfc7231#section-6.6.2)
* [502 Bad Gateway](https://tools.ietf.org/html/rfc7231#section-6.6.3)
* [503 Service Unavailable](https://tools.ietf.org/html/rfc7231#section-6.6.4)
* [504 Gateway Timeout](https://tools.ietf.org/html/rfc7231#section-6.6.5)

#### Headers

* `concur-correlationid` is a SAP Concur specific custom header used for technical support in the form of a [RFC 4122 A Universally Unique IDentifier (UUID) URN Namespace](https://tools.ietf.org/html/rfc4122)
* [RFC 7231 Content-Type](https://tools.ietf.org/html/rfc7231#section-3.1.1.5)
* [RFC 7235 Authorization](https://tools.ietf.org/html/rfc7235#section-4.2)

#### Payload

[User Schema](#schema-user)

### Example

#### Request

```json
{
  "userName": "SAPDemoUser_User222@example.com",
  "active": true,
   "name": {
      "familyName": "SAPDemoUser",
      "givenName": "User222"
   },
  "emails": [
    {
        "value": "SAPDemoUser_User222@example.com"
    }
  ],
   "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": {
      "companyId": "aa076ada-80a9-4f57-8e98-9300b1c3171d"
    }
}
```

#### Response

```json
{
  "meta": {
    "resourceType": "User",
    "created": "2020-08-14T23:07:02.000739Z",
    "lastModified": "2020-08-14T23:07:02.000739Z",
    "version": 0,
    "location": "https://us.api.concursolutions.com/profile/identity/v4/users/b38316e0-e2f6-48c8-bb3b-193d4faef578"
  },
  "displayName": "User222",
  "name": {
    "familyName": "SAPDemoUser",
    "givenName": "User222",
    "formatted": "SAPDemoUser, User222 "
  },
  "phoneNumbers": [],
  "schemas": [
    "urn:ietf:params:scim:schemas:core:2.0:User",
    "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
  ],
  "active": true,
  "id": "b38316e0-e2f6-48c8-bb3b-193d4faef578",
  "emails": [
    {
      "value": "SAPDemoUser_User222@example.com"
    }
  ],
  "userName": "SAPDemoUser_User222@example.com",
  "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": {
    "companyId": "aa076ada-80a9-4f57-8e98-9300b1c3171d"
  }
}
```

## Update a User's Identity Profile

{% include prerelease.html %}

Updates applicable attributes in the user's identity profile.

### Request

#### URI

##### Template

```
PATCH https://us.api.concursolutions.com/profile/identity/v4/Users/UUID
```
##### Parameters

Name|Type|Format|Description
---|---|---|---
`id`|`string`|-|The user's UUID.

#### Headers

* [RFC 7231 Content-Type](https://tools.ietf.org/html/rfc7231#section-3.1.1.5)
* [RFC 7235 Authorization](https://tools.ietf.org/html/rfc7235#section-4.2)

#### Payload

None.

### Response

#### Status Codes

* [200 OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)
* [400 Bad Request](https://tools.ietf.org/html/rfc7231#section-6.5.1)
* [401 Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1)
* [404 Not Found](https://tools.ietf.org/html/rfc7231#section-6.5.4)
* [500 Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1)
* [501 Not Implemented](https://tools.ietf.org/html/rfc7231#section-6.6.2)
* [502 Bad Gateway](https://tools.ietf.org/html/rfc7231#section-6.6.3)
* [503 Service Unavailable](https://tools.ietf.org/html/rfc7231#section-6.6.4)
* [504 Gateway Timeout](https://tools.ietf.org/html/rfc7231#section-6.6.5)

#### Headers

* `concur-correlationid` is a SAP Concur specific custom header used for technical support in the form of a [RFC 4122 A Universally Unique IDentifier (UUID) URN Namespace](https://tools.ietf.org/html/rfc4122)
* [RFC 7231 Content-Type](https://tools.ietf.org/html/rfc7231#section-3.1.1.5)
* [RFC 7235 Authorization](https://tools.ietf.org/html/rfc7235#section-4.2)

#### Payload

[User Schema](#schema-user)

### Example

#### Request

```json
{
    "Operations": [
        {
            "op": "add",
	"path" : "externalId",
            "value": "123-222"
				}
            ]
 }
```

#### Response

```json
{
  "localeOverrides": {
    "preferenceEndDayViewHour": 20,
    "preferenceFirstDayOfWeek": "Sunday",
    "preferenceDateFormat": "mm/dd/yyyy",
    "preferenceCurrencySymbolLocation": "BeforeAmount",
    "preferenceHourMinuteSeparator": ":",
    "preferenceDefaultCalView": "month",
    "preference24Hour": "H:mm",
    "preferenceNumberFormat": "1,000.00",
    "preferenceStartDayViewHour": 8,
    "preferenceNegativeCurrencyFormat": "-100"
  },
"title": null,
  "addresses": [
    {
      "country": "US",
      "streetAddress": null,
      "postalCode": null,
      "locality": null,
      "type": "home",
      "region": null
    },
    {
      "country": "US",
      "streetAddress": null,
      "postalCode": null,
      "locality": null,
      "type": "work",
      "region": null
    }
  ],
  "timezone": "America/New_York",
  "meta": {
    "resourceType": "User",
    "created": "2020-08-14T23:07:02.000739Z",
    "lastModified": "2020-08-14T23:07:04.000900Z",
    "version": 2,
    "location": "https://us.api.concursolutions.com/profile/identity/v4/users/b38316e0-e2f6-48c8-bb3b-193d4faef578"
  },
  "displayName": "User222",
  "name": {
    "honorificSuffix": null,
    "hasNoMiddleName": true,
    "formatted": "SAPDemoUser, User222 ",
    "familyName": "SAPDemoUser",
    "givenName": "User222",
    "honorificPrefix": null,
    "middleName": null
  },
  "phoneNumbers": [],
  "emergencyContacts": [
    {
      "country": null,
      "streetAddress": null,
      "postalCode": null,
      "name": null,
      "locality": null,
      "phones": [],
      "region": null,
      "relationship": "Other"
    }
  ],
  "preferredLanguage": "en-US",
  "dateOfBirth": null,
  "nickName": null,
  "schemas": [
    "urn:ietf:params:scim:schemas:core:2.0:User",
    "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
  ],
  "externalId": "123-222",
  "active": true,
  "id": "b38316e0-e2f6-48c8-bb3b-193d4faef578",
  "gender": null,
  "emails": [],
  "userName": "SAPDemoUser_User222@example.com",
  "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": {
    "terminationDate": null,
    "companyId": "aa076ada-80a9-4f57-8e98-9300b1c3171d",
    "manager": null,
    "costCenter": null,
    "orgUnit": null,
    "startDate": "2020-08-14T23:07:00.000",
    "employeeNumber": null
  }
}
```

## Replace a User's Identity Profile

{% include prerelease.html %}

Replaces a user's identity profile.

### Request

#### URI

##### Template

```
PUT https://us.api.concursolutions.com/profile/identity/v4/Users/UUID
```
##### Parameters

Name|Type|Format|Description
---|---|---|---
`id`|`string`|-|The user's UUID.
`user`|`string`|-|The user identity to update.

#### Headers

* [RFC 7231 Content-Type](https://tools.ietf.org/html/rfc7231#section-3.1.1.5)
* [RFC 7235 Authorization](https://tools.ietf.org/html/rfc7235#section-4.2)

#### Payload

[User Schema](#schema-user)

### Response

#### Status Codes

* [200 OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)
* [400 Bad Request](https://tools.ietf.org/html/rfc7231#section-6.5.1)
* [401 Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1)
* [404 Not Found](https://tools.ietf.org/html/rfc7231#section-6.5.4)
* [500 Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1)
* [501 Not Implemented](https://tools.ietf.org/html/rfc7231#section-6.6.2)
* [502 Bad Gateway](https://tools.ietf.org/html/rfc7231#section-6.6.3)
* [503 Service Unavailable](https://tools.ietf.org/html/rfc7231#section-6.6.4)
* [504 Gateway Timeout](https://tools.ietf.org/html/rfc7231#section-6.6.5)

#### Headers

* `concur-correlationid` is a SAP Concur specific custom header used for technical support in the form of a [RFC 4122 A Universally Unique IDentifier (UUID) URN Namespace](https://tools.ietf.org/html/rfc4122)
* [RFC 7231 Content-Type](https://tools.ietf.org/html/rfc7231#section-3.1.1.5)
* [RFC 7235 Authorization](https://tools.ietf.org/html/rfc7235#section-4.2)

#### Payload

[User Schema](#schema-user)

### Example

#### Request

```json
{
  "active": true,
  "addresses": [
    {
      "country": "string",
      "locality": "string",
      "postalCode": "string",
      "region": "string",
      "streetAddress": "string",
      "type": "work"
    }
  ],
  "dateOfBirth": "string",
  "displayName": "string",
  "emails": [
    {
      "dateAdded": "string",
      "dateVerified": "string",
      "notifications": true,
      "type": "work",
      "value": "string",
      "verified": true
    }
  ],
  "emergencyContacts": [
    {
      "country": "string",
      "emails": [
        "string"
      ],
      "locality": "string",
      "name": "string",
      "phones": [
        "string"
      ],
      "postalCode": "string",
      "region": "string",
      "relationship": "Spouse",
      "streetAddress": "string"
    }
  ],
  "entitlements": [
    "Expense"
  ],
  "externalId": "string",
  "gender": "Male",
  "id": "string",
  "localeOverrides": {
    "preference24Hour": "h:mm AM/PM",
    "preferenceCurrencySymbolLocation": "BeforeAmount",
    "preferenceDateFormat": "mm/dd/yyyy",
    "preferenceDefaultCalView": "day",
    "preferenceDistance": "mile",
    "preferenceEndDayViewHour": 0,
    "preferenceFirstDayOfWeek": "Monday",
    "preferenceHourMinuteSeparator": ":",
    "preferenceNegativeCurrencyFormat": "-100",
    "preferenceNegativeNumberFormat": "-100",
    "preferenceNumberFormat": "1,000.00",
    "preferenceStartDayViewHour": 0
  },
  "meta": {},
  "name": {
    "academicTitle": [
      "Dr."
    ],
    "familyName": "string",
    "familyNamePrefix": "string",
    "formatted": "string",
    "givenName": "string",
    "hasNoMiddleName": true,
    "honorificPrefix": "Miss",
    "honorificSuffix": "Jr.",
    "legalName": "string",
    "middleInitial": "string",
    "middleName": "string"
  },
  "nickName": "string",
  "phoneNumbers": [
    {
      "display": "string",
      "notifications": true,
      "operatingSystem": "Android Phone",
      "primary": true,
      "type": "work",
      "value": "string"
    }
  ],
  "preferredLanguage": "string",
  "schemas": [
    "urn:ietf:params:scim:schemas:core:2.0:User"
  ],
  "timezone": "string",
  "title": "string",
  "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": {
    "companyId": "string",
    "costCenter": "string",
    "department": "string",
    "division": "string",
    "employeeNumber": "string",
    "manager": {
      "$ref": "string",
      "displayName": "string",
      "employeeNumber": "string",
      "value": "string"
    },
    "orgUnit": "string",
    "organization": "string",
    "self": {
      "$ref": "string",
      "displayName": "string",
      "employeeNumber": "string",
      "value": "string"
    },
    "startDate": "string",
    "terminationDate": "string"
  },
  "userName": "string"
}
```

#### Response
```json
{
  "meta": {
    "resourceType": "User",
    "created": "2020-08-14T23:07:02.000739Z",
    "lastModified": "2020-08-14T23:07:02.000739Z",
    "version": 0,
    "location": "https://us.api.concursolutions.com/profile/identity/v4/users/b38316e0-e2f6-48c8-bb3b-193d4faef578"
  },
  "displayName": "User222",
  "name": {
    "familyName": "SAPDemoUser",
    "givenName": "User222",
    "formatted": "SAPDemoUser, User222 "
  },
  "phoneNumbers": [],
  "schemas": [
    "urn:ietf:params:scim:schemas:core:2.0:User",
    "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
  ],
  "active": true,
  "id": "b38316e0-e2f6-48c8-bb3b-193d4faef578",
  "emails": [
    {
      "value": "SAPDemoUser_User222@example.com"
    }
  ],
  "userName": "SAPDemoUser_User222@example.com",
  "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": {
    "companyId": "aa076ada-80a9-4f57-8e98-9300b1c3171d"
  }
}
```

## Schema

### User

|Name|Type|Format|Description|
|---|---|---|---|
`active`|`boolean`|`true`/`false`|**Required** If `true`, the user is active.
`addresses`|`object`|-|A physical mailing address for this user. Examples: `work`, `home`, `other`
`addresses.country`|`string`|-|A two-letter country code defined in ISO 3166-1 alpha-2.
`addresses.locality`|`string`|-|The city or locality.
`addresses.postalCode`|`string`|-|The zip code or postal code.
`addresses.region`|`string`|-|The state or region.
`addresses.streetAddress`|`string`|-|The full street address component, which may include house number, street name, P.O. box, and multi-line extended street address information.
`addresses.type`|`string`|-|A label indicating the function of the address. Examples: `work`, `home`
`dateOfBirth`|`string`|`YYYY-MM-DD`|The user's date of birth.
`displayName`|`string`|-|The name of the user, suitable for public display.
`emails`|`object`|-|**Required** Email addresses for the user. The value should be canonicalized by the service provider.
`dateAdded`|`string`|-|The date and time the email was added to the user's profile.
`dateVerified`|`string`|-|The date and time the email was verified.
`emails.notifications`|`boolean`|`true`/`false`|If `true`, notifications have been opted-in for emails.
`emails.type`|`string`|-|A label indicating the attribute's function. Examples: `work`, `home`
`emails.value`|`string`|-|**Required** Email address value.
`emails.verified`|`boolean`|`true`/`false`|If `true`, the email has been verified by the user.
`emergencyContacts`|`object`|-|Emergency contact information for the user.
`emergencyContacts.country`|`string`|-|A two-letter country code defined in ISO 3166-1 alpha-2.
`emergencyContacts.emails`|`string`|-|Emails of the emergency contact.
`emergencyContacts.locality`|`string`|-|The city or locality of the emergency contact.
`emergencyContacts.name`|`string`|-|**Required** The emergency contact's name.
`emergencyContacts.phones`|`string`|-|Phone numbers of the emergency contact.
`emergencyContacts.postalCode`|`string`|-|The zip code or postal code of the emergency contact.
`emergencyContacts.region`|`string`|-|The state or region of the emergency contact.
`emergencyContacts.relationship`|`string`|-|**Required** The emergency contact's relationship to the user. Supported values: `Spouse`, `Brother`, `Parent`, `Sister`, `Life Partner`, `Other`
`emergencyContacts.streetAddress`|`string`|-|The full street address component, which may include house number, street name, P.O. box, and multi-line extended street address information.
`entitlements`|`string`|-|The features enabled for the user. Supported values: `Expense`, `Invoice`, `Locate`, `Request`, `Travel`
`externalId`|`string`|-|User identifier from the provisioning client.
`gender`|`string`|-|The user's gender.
`id`|`string`|-|**Required. Read Only** Unique identifier for the user, also known as the UUID.
`localeOverrides`|`object`|-|**Read Only** Support for users who want to override locale settings.
`localeOverrides.preference24Hour`|`string`|-|Preferred 24 hour format for the user. Supported values: `h:mm AM/PM`, `H:mm`
`localeOverrides.preferenceCurrencySymbolLocation`|`string`|-|Preferred currency symbol location for the user. Supported values: `BeforeAmount`, `AfterAmount`
`localeOverrides.preferenceDateFormat`|`string`|-|Preferred date format for the user.
`localeOverrides.preferenceDefaultCalView`|`string`|-|Preferred default calendar view for the user. Supported values: `day`, `week`, `month`
`localeOverrides.preferenceDistance`|`string`|-|Preferred distance metric. Supported values: `mile`, `km`
`localeOverrides.preferenceEndDayViewHour`|`integer`|-|Preferred hour setting for the end of day. Supported values: `0-23`
`localeOverrides.preferenceFirstDayOfWeek`|`string`|-|Preferred first day of the week for the user.
`localeOverrides.preferenceHourMinuteSeparator`|`string`|-|Preferred separator between hour and minute. Supported values: `:`, `.`
`localeOverrides.preferenceNegativeCurrencyFormat`|`string`|-|Preferred negative currency format for the user.
`localeOverrides.preferenceNegativeNumberFormat`|`string`|-|Preferred negative number format for the user.
`localeOverrides.preferenceNumberFormat`|`string`|-|Preferred number format for the user.
`localeOverrides.preferenceStartDayViewHour`|`integer`|-|Preferred start of day for the user, from `1`.
`meta`|`object`|-|**Read Only**
`name`|`object`|-|**Required** The user's name.
`name.academicTitle`|`string`|-|Title signifying level of academic achievement.
`familyName`|`string`|-|**Required** The family or last name of the user.
`name.familyName`|`string`|-|**Required** The family or last name of the user.
`name.familyNamePrefix`|`string`|-|The family name prefix of the user, if applicable.
`name.formatted`|`string`|-|The full name of the user, formatted for display. Example: `Jensen, Barbara Jane`
`name.givenName`|`string`|-|**Required** The given or first name of the user.
`name.hasNoMiddleName`|`boolean`|`true`/`false`|If `true`, the user has a middle name.
`name.honorificPrefix`|`string`|-|The honorific or title prefix(es) of the user.
`name.honorificSuffix`|`string`|-|The honorific suffix(es) of the user.
`name.legalName`|`string`|-|The legal name of the user.
`name.middleInitial`|`string`|-|The middle initial of the user, if applicable.
`name.middleName`|`string`|-|The middle name(s) of the user, if applicable.
`name.nickName`|`string`|-|The casual way to address the user. This attribute should not be used to represent a user's username.
`phoneNumbers`|`object`|-|Phone numbers for the user.  The value should be canonicalized by the service provider according to the format specified in RFC 3966. Duplicates are not allowed for types other than mobile.
`phoneNumbers.display`|`string`|-|A human-readable phone number for display.
`phoneNumbers.notifications`|`boolean`|`true`/`false`|If `true`, notifications have been opted in for phone numbers. This is only available for mobile phone numbers.
`phoneNumbers.operatingSystem`|`string`|-|The operating system of the device, when the phone is a `cellphone` type.
`phoneNumbers.primary`|`boolean`|`true`/`false`|If `true`, this is the primary mobile device. This is only available for mobile phone numbers. One mobile phone number must be set as the primary number and only one phone number can be set to primary at a time.
`phoneNumbers.type`|`string`|-|A label indicating the attribute's function. Examples: `work`, `home`, `mobile`
`phoneNumbers.value`|`string`|-|**Required** The phone number value.
`preferredLanguage`|`string`|-|Indicates the user's preferred written or spoken language.
`timezone`|`string`|-|The user's time zone in the Olson time zone database format. Example: `America/Los_Angeles`
`title`|`string`|-|The user's job title in the company.
`companyId`|`string`|-|**Required. Immutable** The SAP Concur ID of the company.
`costCenter`|`string`|-|The employee cost center for product. The value of this parameter is provisioned and is not related to the Concur Expense `costCenter`.
`department`|`string`|-|Client supplied department name. The value of this parameter is provisioned and is not related to the Concur Expense `department`.
`division`|`string`|-|Client supplied division name. The value of this parameter is provisioned and is not related to the Concur Expense `division`.
`employeeNumber`|`string`|-|Client supplied employee number within the company, unique for the company.
`manager`|`object`|-|The manager of this user.
`$ref`|`string`|-|The URI of the SCIM resource representing the referenced user.
`displayName`|`string`|-|**Read Only** The referenced user's display name.
`employeeNumber`|`string`|-|The referenced user's employee number, if it is an Enterprise user.
`value`|`string`|-|The referenced user's UUID.
`orgUnit`|`string`|-|Client supplied org unit name. The value of this parameter is provisioned and is not related to the Concur Expense `orgUnit`.
`organization`|`string`|-|**Read Only** The company name.
`self`|`object`|-|A reference to this user.
`$ref`|`string`|-|The URI of the SCIM resource representing the referenced user.
`displayName`|`string`|-|**Read Only** The referenced user's display name.
`employeeNumber`|`string`|-|The referenced user's employee number, if it is an Enterprise user.
`value`|`string`|-|The referenced user's UUID.
`startDate`|`string`|`YYYY-MM-DD`|The user's start date.
`terminationDate`|`string`|`YYYY-MM-DD`|The user's termination date.
`userName`|`string`|`user@domain`|**Required** The name that can be used to login to Concur Travel and Expense. NOTE: The `userName` must be unique across all SAP Concur products. If a `userName` is currently in use in any SAP Concur product, it cannot be assigned again unless the original occurrence is changed. For example, assume that a `userName` was assigned in error. That `userName` can only be used again if an admin (either manually or via import) renames the original occurrence, allowing the `userName` to be used again. The following characters cannot be used as a value for this record: % [ # ! * & ( ) ~  ' { ^ } \ / ? > < , ; : " + = ] and pipe

### UserList

|Name|Type|Format|Description|
|---|---|---|---|
`totalResults`|`integer`|-|The total number of results matching the client query.
`itemsPerPage`|`integer`|-|The number of query results returned in a query response page.
`startIndex`|`integer`|-|The 1-based index of the first result in the current set of query results.
`Resources`|[`User`](#schemauser)|-|-

### Company

|Name|Type|Format|Description|
|---|---|---|---|
`active`|`boolean`|`true`/`false`|**Required** If `true`, the company is active.
`addresses`|`object`|-|-
`country`|`string`|-|A two-letter country code defined in ISO 3166-1 alpha-2.
`locality`|`string`|-|The city or locality of the company address.
`postalCode`|`string`|-|The zip code or postal code of the company address.
`region`|`string`|-|The state or region of the company address.
`streetAddress`|`string`|-|The full street address component, which may include house number, street name, P.O. box, and multi-line extended street address information.
`companyDomain`|`string`|-|The company's company domain name.
`contact`|`object`|-|-
`country`|`string`|-|A two-letter country code defined in ISO 3166-1 alpha-2.
`emails`|`string`|-|Emails of the contact.
`locality`|`string`|-|The city or locality of the contact.
`name`|`string`|-|**Required** Name of the contact.
`phones`|`string`|-|Phone numbers of the contact.
`postalCode`|`string`|-|The zip code or postal code of the contact.
`region`|`string`|-|The state or region.
`streetAddress`|`string`|-|The full street address component, which may include house number, street name, P.O. box, and multi-line extended street address information.
`defaultLanguage`|`string`|-|Indicates the default language for the company.
`entitlements`|`string`|-|The features enabled for the company. Supported values: `Expense`, `Invoice`, `Locate`, `Request`, `Travel`
`id`|`string`|-|**Required** Unique identifier for the company, also known as the company UUID.
`internetDomain`|`string`|-|The company's internet domain name.
`meta`|`object`|-|-
`name`|`string`|-|The name of the company.
`schemas`|`string`|-|**Read Only**
`loginPolicy`|`object`|-|-
`hideForgotLoginIdLink`|`boolean`|`true`/`false`|If `true`, the Forgot LoginId Link will be hidden.
`loginFailureLockoutDuration`|`integer`|-|The duration of the login failure lockout.
`loginFailureWindowDuration`|`integer`|-|The window duration of the login failure.
`loginFailuresAllowed`|`integer`|-|The amount of login failures allowed.
`loginIPRestriction`|`string`|-|The login IP restrictions.
`loginOneTimeLinkExpirationLength`|`integer`|-|The length of the one time login expiration link.
`loginViaSsoOnly`|`boolean`|`true`/`false`|If `true`, the login is available via SSO only.
`passwordPolicy`|`object`|-|-
`daysUntilExpiration`|`integer`|-|Number of days until password expiration.
`expirePasswordOnUserCreation`|`boolean`|`true`/`false`|If `true`, the password will expire on user creation.
`maxLength`|`integer`|-|Maximum length of the password.
`minLength`|`integer`|-|Minimum length of the password.
`mobileAuthenticationLifetime`|`integer`|-|The mobile session timeout in seconds.
`mobileMinLength`|`integer`|-|The minimum length of the password for mobile.
`mobileRequiresMixedCase`|`boolean`|`true`/`false`|If `true`, the password will require mixed cases for mobile.
`mobileRequiresNonalphanum`|`boolean`|`true`/`false`|If `true`, the password will require non-alphanumeric characters for mobile.
`numGenerationsBeforeCanReuse`|`integer`|-|Number of generations before the password can be reused.
`numSecurityQuestions`|`integer`|-|The number of required security questions.
`numSecurityQuestionsUsersPick`|`integer`|-|The number of security questions users can pick.
`passwordResetEmailPolicy`|`string`|-|When the password reset email should be sent. Supported values: `never`, `anyTime`, `afterFirstLogin`
`passwordResetSupportEmail`|`string`|-|The from address of the password or PIN reset email.
`requiresMixedCase`|`boolean`|`true`/`false`|If `true`, the password will require mixed cases.
`requiresNonAlpha`|`boolean`|`true`/`false`|If `true`, the password will requires non-alphabetic characters.
`requiresNonAlphanum`|`boolean`|`true`/`false`|If `true`, the password will require non-alphanumeric characters.
`requiresNumber`|`boolean`|`true`/`false`|If `true`, the password will require numbers.
`requiresSecurityQuestions`|`boolean`|`true`/`false`|If `true` , security questions will be required.
`restrictPasswordResetOncePerDay`|`boolean`|`true`/`false`|If `true`, password resets will be limited to once a day.
`channels`|`string`|-|-
`enabled`|`boolean`|`true`/`false`|If `true`, channels will be enabled.
`tenantIdSpend`|`string`|-|The ID of the spend tenant for the company.
`tenantIdTravel`|`string`|-|The ID of the travel tenant for the company.

### Schema Extension

|Name|Type|Format|Description|
|---|---|---|---|
`schema`|`string`|-|**Required** The string identifier of the extension.
`required`|`boolean`|`true`/`false`|**Required** If `true`, this extension is a required part of the schema.

### Resource Type

|Name|Type|Format|Description|
|---|---|---|---|
`attributes`|[`SchemaExtension`](#schemaschemaextension)|-|**Required** The resource's extensions.
`description`|`string`|-|**Required** The resource's description.
`endpoint`|`string`|-|**Required** The resource's HTTP addressable endpoint relative to the base URL. Example: `/Users`
`id`|`string`|-|**Required** The resource's ID.
`name`|`string`|-|**Required** The resource's name. Example: `User`
`schema`|`string`|-|**Required** The resource's associated schema.

### Authenticated Schemas

|Name|Type|Format|Description|
|---|---|---|---|
`description`|`string`|-|**Required** The description of the authentication schema.
`documentationUrl`|`string`|-|**Required** An HTTP addressable URL pointing to the authentication schema's usage documentation.
`name`|`string`|-|**Required** The common authentication schema name. Example: `HTTP Basic`
`specUrl`|`string`|-|**Required** An HTTP addressable URL pointing to the authentication schema's specification.

### Service Provider Config

|Name|Type|Format|Description|
|---|---|---|---|
`authenticationSchemes`|[`AuthenticationSchemes`](#schemaauthenticationschemes)|-|**Required** Specifies supported authentication schema properties.
`bulk`|[`ServiceProviderConfigSetting`](#schemaserviceproviderconfigsetting)|-|**Required** Details about the feature support for the service provider.
`changePassword`|[`ServiceProviderConfigSetting`](#schemaserviceproviderconfigsetting)|-|**Required** Details about the feature support for the service provider.
`documentationUrl`|`string`|-|**Required** An HTTP addressable URL pointing to the service provider's help documentation.
`etag`|[`ServiceProviderConfigSetting`](#schemaserviceproviderconfigsetting)|-|**Required** Details about the feature support for the service provider.
`filter`|[`ServiceProviderConfigSetting`](#schemaserviceproviderconfigsetting)|-|**Required** Details about the feature support for the service provider.
`patch`|[`ServiceProviderConfigSetting`](#schemaserviceproviderconfigsetting)|-|**Required** Details about the feature support for the service provider.
`sort`|[`ServiceProviderConfigSetting`](#schemaserviceproviderconfigsetting)|-|**Required** Details about the feature support for the service provider.

### Service Provider Config Setting

|Name|Type|Format|Description|
|---|---|---|---|
`supported`|`boolean`|`true`/`false`|If `true`, the feature is supported.

### Concur Error

|Name|Type|Format|Description|
|---|---|---|---|
`messages`|`object`|-|Additional messages in case of errors/warnings.
`code`|`string`|-|**Required** The error message code.
`message`|`string`|-|The error message description.
`schemaPath`|`string`|-|The relative schema path of attribute.
`type`|`string`|-|**Required** The error message type. Supported values: `error`, `warning`

### Error Response

|Name|Type|Format|Description|
|---|---|---|---|
`scimType`|`string`|-|The SCIM detail error keyword.
`detail`|`string`|-|The human readable message.
`status`|`string`|-|**Required** The HTTP status code.


text:
// A non-trivial application of GaloisCPP library

// This program implements the Diffie-Hellmann Key Exchange Algorithm over
// a Galois Field with a relatively large prime modulus.

#include <iostream>
#include "gfelement.h"

using namespace std;
using namespace shk_galoiscpp;

#define PRIME 1008951599
#define DIM 6
// Therefore the Galois Field we are working with is GF(1008951599 ^ 6).
// This Galois Field has more than 10^60 elements.

int main()
{

   cout << "\n------------------------------------------------------\n";
   cout << "  DIFFIE-HELLMANN KEY EXCHANGE OVER A GALOIS FIELD";
   cout << "\n------------------------------------------------------\n";

   cout << "\n-------------Step 1---------------\n";
   cout << "Alice chooses a Galois Field with a large prime, a small dimension, and a\n";
   cout << "reduction polynomial of degree dimension+1.\n";

   // With the above modulus and dimension, it is known that the following
   // polynomial is irreducible. We choose it as the reduction polynomialthe Galois Field.
   Fint reduction_polynomial[DIM+1] = {1,1,1,1,1,1,1};

   // Declare a Galois Field
   GaloisField GF(PRIME, DIM, reduction_polynomial);
   cout << "\nLet's say Alice chose this Galois Field: " << GF << endl;

   cout << "\nAlice should also create at random a base Galois Field element G.\n";

   // Let's say this is the base polynomial G.
   Fint Gpoly[DIM] = {5017388,
                      18360017,
                      40011933,
                      8755039,
                      1237095,
                      49128817};

   // Create Galois Field Element G.
   GFelement G( &GF, Gpoly );
   cout << "Let's say Alice chose this base GFelement: " << G;

   cout << "Alice should send the Galois Field parameters (prime and dimension) to Bob.\n";
   cout << "Alice should also send Bob the base element G.\n";

   cout << "\n-------------Step 2---------------\n";
   cout << "Alice chooses a large random integer A and raises G to power A.\n";

   Fint A = 116441012; // a random number
   cout << "Let's say Alice chose A = : " << A << endl;

   cout << "Alice should raise G to power A and call it X.\n";
   GFelement X( &GF );   // create a GFelement X
   X = GFexp(G,A);       // raise G to power A.

   cout << "X = G^A = " << X << endl;

   cout << "Alice sends X to Bob.\n";

   cout << "\n-------------Step 3---------------\n";
   cout << "Bob chooses a large random integer B and raises G to power B.\n";

   Fint B = 1379921012; // a random number
   cout << "Let's say Bob chose B = : " << B << endl;

   cout << "Bob should raise G to power B and call it Y.\n";
   GFelement Y ( &GF );  // create a GFelement Y
   Y = GFexp(G,B);       // raise G to power B.

   cout << "Y = G^B = " << Y << endl;

   cout << "Bob sends Y to Alice.\n";

   cout << "\n-------------Step 4---------------\n";
   cout << "Alice should raise Y to power A and call it S_Alice.\n";

   GFelement S_Alice( &GF );   // create a GFelement S_Alice
   S_Alice = GFexp(Y,A);       // raise Y to power A.

   cout << "S_Alice = Y^A = " << S_Alice << endl;

   cout << "\n-------------Step 5---------------\n";
   cout << "Bob should raise X to power A and call it S_Alice.\n";

   GFelement S_Bob( &GF );   // create a GFelement S_Bob
   S_Bob = GFexp(X,B);       // raise X to power B.

   cout << "S_Bob = X^B = " << S_Bob << endl;

   cout << "\n-------------END---------------\n";
   cout << "The end result is that S_Alice should equal to S_Bob.\n";

   if (S_Alice == S_Bob)
   {
      cout << "Yes, S_Alice IS equal to S_Bob. All went ok!\n";
      cout << "Alice and Bob now have a shared secret called S = " << S_Alice;
   }
   else
   {
      cout << "Unfortunately, S_Alice is NOT equal to S_Bob!!!\n";
      cout << "Something went wrong!\n";
   }

   cout << "Caveat: To be secure, Diffie-Hellmann Key Exchange requires that the prime modulus\n";
   cout << "be well over 100 bits length. But GaloisCPP's modulus can only be up to\n";
   cout << "64 bits (the size of long long int).\n";

   return 0;
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true" >
    <scale
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="1000"
        android:fromXScale="3.0"
        android:fromYScale="3.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.0"
        android:toYScale="1.0" >
    </scale>
</set>


text:
double float_pow(double base, double exp) {
    return pow(base, exp);
}


text:
'use strict';

var rpio;

const Pin = function (config) {
    config = config || {};

    if (!config.mock) {
        rpio = require('rpio');
        rpio.init(config);
    }

    return {
        open: function (pinConfig) {
            if (pinConfig.pin === undefined ||
                (pinConfig.input === undefined &&
                    pinConfig.output === undefined)) {
                console.log(pinConfig);
                throw 'Invalid pin configuration';
            }
            return !config.mock ? new PinRpio(pinConfig) : new PinEmulated(pinConfig);
        }
    };
};

function PinRpio(pinConfig) {
    var pin = pinConfig.pin;

    //setup pin
    if (pinConfig.input) {
        if (pinConfig.pullDown) {
            rpio.open(pin, rpio.INPUT, rpio.PULL_DOWN);
        }
        else if (pinConfig.pullUp) {
            rpio.open(pin, rpio.INPUT, rpio.PULL_UP);
        }
        else {
            rpio.open(pin, rpio.INPUT);
        }
    }
    else if (pinConfig.output) {
        if (pinConfig.initial === true) {
            rpio.open(pin, rpio.OUTPUT, rpio.HIGH);
        }
        else if (pinConfig.initial === false) {
            rpio.open(pin, rpio.OUTPUT, rpio.LOW);
        }
        else {
            throw 'Output pinconfig must define an initial value';
        }
    }

    return {
        poll: function (onChange) {
            var lastValue = undefined;
            rpio.poll(pin, function () {
                //ignore consecutive duplicates
                var value = rpio.read(pin);
                if (value !== lastValue) {
                    lastValue = value;
                    onChange(value);
                }
            });
        },
        read: function () {
            return rpio.read(pin);
        },
        write: function (value) {
            rpio.write(pin, value ? rpio.HIGH : rpio.LOW);
        },
        close: function () {
            rpio.close(pin, rpio.PIN_RESET);
        }
    };
}

function PinEmulated(pinConfig) {
    return {
        poll: function (onChange) {
        },
        read: function () {
        },
        write: function (value) {
        },
        close: function () {
        }
    };
}

module.exports = Pin;


text:
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../wid-card-weight-behavior/wid-card-weight-behavior.html">
<link rel="import" href="../paper-material/paper-material.html">
<link rel="import" href="../neon-animation/neon-animation.html">
<link rel="import" href="../neon-animation/neon-animations.html">

<dom-module id="wid-card">

  <template>

    <iron-media-query query="(max-width: 639px)" query-matches="{{_isMobile}}"></iron-media-query>
    <paper-material id="container" elevation="3" class="layout vertical" hidden$="[[_hidden]]">

      <content></content>

    </paper-material>

  </template>

</dom-module>


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Class Kategori
 */
class Kategori extends MY_Controller {

	/**
	 * Kategori constructor.
	 */
	public function __construct() {
		parent::__construct();
		$this->load->model(array('kategori_m', 'barang_m'));
		$this->load->library('pagination');
		$this->data['js'] = 'kategori';
		$this->data['css'] = 'kategori';
	}

	/**
	 *  Menampilkan daftar Kategori
	 */
	public function index() {
		$filter = $this->input->get();
		$this->data['segment'] = $this->uri->segment(3, 0);
		if ($this->data['segment'] == 0 && empty($filter)) {
			$this->session->unset_userdata('filter_kategori');
		}
		if (empty($filter)) {
			$session_filter = $this->session->userdata('filter_kategori');
			$filter = (isset($session_filter)) ? $session_filter : array();
		} else {
			$this->session->set_userdata('filter_kategori', $filter);
		}
		$this->page($filter);
		$this->data['title'] = 'Kategori Barang';
		$this->data['allKategori'] = $this->kategori_m->get_all();
		$this->data['content'] = 'kategori/index';
		$this->data['js'] = 'kategori';
		$this->init();
	}

	private function page($filter) {
		//pagination settings
		$config['base_url'] = site_url('kategori/index');
        if(!empty($filter['page'])){
            $per_page = $filter['page'];
            unset($filter['page']);
        } else {
            $per_page = 10;
        }
        $config['per_page'] = $per_page;
        $config['total_rows'] = $this->kategori_m->count_by($filter);
		$config["uri_segment"] = 3;
		$choice = $config["total_rows"] / $config["per_page"];
		$config["num_links"] = 5;

		//config for bootstrap pagination class integration
		$config['full_tag_open'] = '
';
		$config['full_tag_close'] = '
';
		$config['first_link'] = 'First';
		$config['last_link'] = 'Last';
		$config['first_tag_open'] = '
';
		$config['first_tag_close'] = '
';
		$config['prev_link'] = '&laquo';
		$config['prev_tag_open'] = '
';
		$config['prev_tag_close'] = '
';
		$config['next_link'] = '&raquo';
		$config['next_tag_open'] = '
';
		$config['next_tag_close'] = '
';
		$config['last_tag_open'] = '
';
		$config['last_tag_close'] = '
';
		$config['cur_tag_open'] = '
';
		$config['cur_tag_close'] = '
';
		$config['num_tag_open'] = '
';
		$config['num_tag_close'] = '
';

		$this->pagination->initialize($config);
		$this->data['page'] = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

		//call the model function to get the department data
		$this->data['kategori'] = $this->kategori_m->fetch_data($config["per_page"], $this->data['page'], $filter);
		$this->data['filter'] = $filter;
        $this->data['per_page'] = $per_page;
		$this->data['pagination'] = $this->pagination->create_links();

	}

	/**
	 *  Menyimpan data baru ke database
	 */
	public function store() {
		$data = $this->input->post();
		$insert['kode_kategori'] = $data['sub_kategori'];
		$insert['nama'] = $data['nama_kategori'];
		if ($data['induk'] != "") {
			$insert['kode_induk_kategori'] = $this->kategori_m->get_by(array('id' => $data['induk']))->kode_kategori;
		}
		if ($this->kategori_m->insert($insert)) {
			$this->message('Berhasil! Data berhasil di simpan', 'success');
            $this->cache->delete('homepage');
            $this->cache->delete('list_kategori');
		} else {
			$this->message('Gagal! Data gagal di simpan', 'danger');
		}
		redirect('kategori');
	}

	/**
	 *  Menampilkan halaman edit kategori
	 */
	public function edit() {
		$id = $this->input->get('id');
		$data = $this->kategori_m->get_by(array('id' => $id));
		$kode_induk = $data->kode_induk_kategori;
		if (!is_null($kode_induk)) {
			$id_induk = $this->kategori_m->get_by(array('kode_kategori' => $kode_induk))->id;
			$data->id_induk = $id_induk;
		} else {
			$data->id_induk = "";
		}
		$this->printOptionOnCombobox($data, $id);
		echo json_encode($data);
	}

	/**
	 * @param $data
	 * @param $id
	 */
	private function printOptionOnCombobox($data, $id) {
		$data->kategori = array('<option value="">Pilih kategori</option>');
		$kategori = $this->kategori_m->get_all();
		foreach ($kategori as $list) {
			if ($list->id != $id) {
				array_push($data->kategori, "<option value='$list->id'>$list->kode_kategori. $list->nama</option>");
			}
		}
	}

	/**
	 *  Mengubah data di database sesuai inputan user
	 */
	public function update() {
		$id = $this->input->post('idUpdate');
		$data = $this->input->post();
		$update['nama'] = $data['nama_kategoriUpdate'];
		if ($this->kategori_m->update($id, $update)) {
			$this->message('Berhasil! Data berhasil di update', 'success');
            $this->cache->delete('homepage');
            $this->cache->delete('list_kategori');
		} else {
			$this->message('Gagal! Data gagal di update', 'danger');
		}
		redirect('kategori');
	}

	/**
	 * Mengubah status kategori menjadi tidak aktif
	 * @param $id
	 */
	public function destroy($id) {
		if ($this->kategori_m->update($id, array('status' => 0))) {
            $kode_induk = $this->kategori_m->get_by(array('id' => $id))->kode_kategori;
            $this->kategori_m->update_by(array("kode_induk_kategori like " => $kode_induk."%"), array('status' => 0));
			$this->message('Berhasil! Data berhasil di nonaktifkan', 'success');
            $this->cache->delete('homepage');
            $this->cache->delete('list_kategori');
		} else {
			$this->message('Gagal! Data gagal di nonaktifkan', 'danger');
		}
		redirect('kategori');
	}

	public function activate($id) {
		if ($this->kategori_m->update($id, array('status' => 1))) {
            $kode_induk = $this->kategori_m->get_by(array('id' => $id))->kode_kategori;
            $this->kategori_m->update_by(array("kode_induk_kategori like " => $kode_induk."%"), array('status' => 1));
			$this->message('Berhasil! Data berhasil di aktifkan', 'success');
            $this->cache->delete('homepage');
            $this->cache->delete('list_kategori');
		} else {
			$this->message('Gagal! Data gagal di aktifkan', 'danger');
		}
		redirect('kategori');
	}

	/**
	 *  Mendapatakan kode kategori baru untuk data kategori yang akan di inputkan
	 */
	public function get_kode() {
		$kategori = $this->input->get('kategori');
		if ($kategori != 0) {
			$kode_induk = $this->kategori_m->get_by(array('kode_kategori' => $kategori))->kode_kategori;
			$kode_sub = $this->kategori_m->get_kode_barang_baru($kode_induk);
			echo $kode_induk . $kode_sub;
		} else {
			echo "";
		}
	}

	public function get_kode_induk() {
		$kode_induk_tertinggi = $this->kategori_m->order_by('id', 'DESC')->limit(1)->get_by(array('kode_induk_kategori' => NULL))->kode_kategori;
		$kode_baru = (int) $kode_induk_tertinggi + 1;
		if ($kode_baru < 10) {
			$kode_baru = '0' . $kode_baru;
		}
		echo $kode_baru;
	}
}


text:
import numpy as np

def parse_feature_vectors(X, features):
    """ parse_feature_vectors
    Parse an array of feature vectors (inputs) into an array of ValueChart Alternatives.
    ----------
        X: array-like, shape = [n_samples, n_features]
            The array of feature vectors to parse into Alternatives.
        features: array-like, shape = [n_features, ]
            The array of feature objects that map features to ValueChart Objectives.
    """
    alternatives = []

    for x in X:
        alternatives.append(parse_feature_vector(x, features))

    return alternatives

def parse_feature_vector(x, features):
    """
    parse_feature_vector
    Parse a single feature vector (input) into a ValueChart Alternative.
    ----------
        x: array-like, shape = [n_features, ]
            The array of feature vectors to parse into Alternatives.
        feature: array-like, shape = [n_features, ]
            The array of feature objects that map features to ValueChart Objectives.
    """

    name = str(int(np.random.rand(1)[0] * 1000))
    # How do i decide on these? Random generation?
    alternative = {'name': ('sample-' + name), 'id': ('temp-' + name), 'description': 'none'}
    objectiveValues = []

    for i, feature in enumerate(features):
        if feature['type'] == 'continuous':
            val = (x[i] * (feature['bounds'][1] - feature['bounds'][0])) + feature['bounds'][0]
            objectiveValues.append([feature['objective_name'], val])
        elif x[i] == 1:
            objectiveValues.append([feature['objective_name'], feature['element']])

    alternative['objectiveValues'] = objectiveValues

    return alternative


text:
require 'spec_helper'

describe Cleanweb::Spam do
  context "spam?" do
    let(:params) { {subject: "subject", body: "body"} }
    let(:cleanweb) { Cleanweb.new params }
    let(:ok_response) { File.read(File.join("spec", "mocks", "ok.xml")) }
    let(:links_response) { File.read(File.join("spec", "mocks", "links.xml")) }
    let(:no_links_response) { File.read(File.join("spec", "mocks", "no_links.xml")) }
    let(:no_links_body_response) { File.read(File.join("spec", "mocks", "no_links_body.xml")) }
    let(:body_response) { File.read(File.join("spec", "mocks", "body.xml")) }

    it "возвращает false если контент не спам" do
      cleanweb.should_receive(:ask_yandex).and_return(ok_response)
      expect(cleanweb.spam?).to eq false
    end

    it "возвращает true если контент спам, а ссылки ок" do
      cleanweb.should_receive(:ask_yandex).and_return(body_response)
      expect(cleanweb.spam?).to eq true
    end

    it "возвращает true если контент ок, а ссылки спам" do
      cleanweb.should_receive(:ask_yandex).and_return(links_response)
      expect(cleanweb.spam?).to eq true
    end

    it "возвращает false если контент ок, а ссылкок нет" do
      cleanweb.should_receive(:ask_yandex).and_return(no_links_response)
      expect(cleanweb.spam?).to eq false
    end

    it "возвращает true если контент спам, а ссылкок нет" do
      cleanweb.should_receive(:ask_yandex).and_return(no_links_body_response)
      expect(cleanweb.spam?).to eq true
    end
  end
end


text:
import * as React from 'react';

export type RichTextInputAreaStatus = 'error' | 'warning' | 'loading';

export interface RichTextInputAreaProps {
  dataHook?: string;
  className?: string;
  initialValue?: string;
  placeholder?: string;
  disabled?: boolean;
  status?: RichTextInputAreaStatus;
  statusMessage?: React.ReactNode;
  onChange?: Function;
  minHeight?: string;
  maxHeight?: string;
  spellCheck?: boolean;
  texts?: texts;
}

export type texts = {
  toolbarButtons?: {
    boldButtonLabel?: string;
    italicButtonLabel?: string;
    underlineButtonLabel?: string;
    linkButtonLabel?: string;
    bulletedListButtonLabel?: string;
    numberedListButtonLabel?: string;
  };
  insertionForm?: {
    confirmButtonLabel?: string;
    cancelButtonLabel?: string;
    link?: {
      textInputPlaceholder?: string;
      urlInputPlaceholder?: string;
    };
  };
};

export default class RichTextInputArea extends React.PureComponent<RichTextInputAreaProps> {
  setValue: (value: string) => void;
}


text:
{-# LANGUAGE OverloadedStrings #-}

module Duckling.Duration.KO.Corpus
  ( corpus
  ) where

import Prelude
import Data.String

import Duckling.Duration.Types
import Duckling.Lang
import Duckling.Resolve
import Duckling.Testing.Types
import Duckling.TimeGrain.Types (Grain(..))

corpus :: Corpus
corpus = (testContext {lang = KO}, allExamples)

allExamples :: [Example]
allExamples = concat
  [ examples (DurationData 1 Second)
             [ "1 초"
             ]
  , examples (DurationData 30 Minute)
             [ "시간반"
             , "시반"
             , "서른분"
             ]
  , examples (DurationData 66 Minute)
             [ "1.1 시간"
             ]
  ]


text:
// This file is automatically generated.

package adila.db;

/*
 * Explay Bit
 *
 * DEVICE: Bit
 * MODEL: Bit
 */
final class bit_bit {
    public static final String DATA = "Explay|Bit|";
}


text:
/**
 * @file mali_kbase_js_policy_cfs.h
 * Completely Fair Job Scheduler Policy structure definitions
 */

#ifndef _KBASE_JS_POLICY_CFS_H_
#define _KBASE_JS_POLICY_CFS_H_

#define KBASE_JS_POLICY_AVAILABLE_CFS

/** @addtogroup base_api
 * @{ */
/** @addtogroup base_kbase_api
 * @{ */
/** @addtogroup kbase_js_policy
 * @{ */

/**
 * Internally, this policy keeps a few internal queues for different variants
 * of core requirements, which are used to decide how to schedule onto the
 * different job slots.
 *
 * Currently, one extra variant is supported: an NSS variant.
 *
 * Must be a power of 2 to keep the lookup math simple
 */
#define KBASEP_JS_MAX_NR_CORE_REQ_VARIANTS_LOG2 3
#define KBASEP_JS_MAX_NR_CORE_REQ_VARIANTS      (1u << KBASEP_JS_MAX_NR_CORE_REQ_VARIANTS_LOG2 )

/** Bits needed in the lookup to support all slots */
#define KBASEP_JS_VARIANT_LOOKUP_BITS_NEEDED (BASE_JM_MAX_NR_SLOTS * KBASEP_JS_MAX_NR_CORE_REQ_VARIANTS)
/** Number of u32s needed in the lookup array to support all slots */
#define KBASEP_JS_VARIANT_LOOKUP_WORDS_NEEDED ((KBASEP_JS_VARIANT_LOOKUP_BITS_NEEDED + 31) / 32)

typedef struct kbasep_js_policy_cfs
{
	/** List of all contexts in the context queue. Hold
	 * kbasep_js_device_data::queue_mutex whilst accessing. */
	osk_dlist ctx_queue_head;

	/** List of all contexts in the realtime (priority) context queue */
	osk_dlist ctx_rt_queue_head;

	/** List of scheduled contexts. Hold kbasep_jd_device_data::runpool_irq::lock
	 * whilst accessing, which is a spinlock */
	osk_dlist scheduled_ctxs_head;

	/** Number of valid elements in the core_req_variants member, and the
	 * kbasep_js_policy_rr_ctx::job_list_head array */
	u32 num_core_req_variants;

	/** Variants of the core requirements */
	kbasep_atom_req core_req_variants[KBASEP_JS_MAX_NR_CORE_REQ_VARIANTS];

	/* Lookups per job slot against which core_req_variants match it */
	u32 slot_to_variant_lookup_ss_state[KBASEP_JS_VARIANT_LOOKUP_WORDS_NEEDED];
	u32 slot_to_variant_lookup_ss_allcore_state[KBASEP_JS_VARIANT_LOOKUP_WORDS_NEEDED];
	u32 slot_to_variant_lookup_nss_state[KBASEP_JS_VARIANT_LOOKUP_WORDS_NEEDED];

	/* The timer tick used for rescheduling jobs */
	struct hrtimer scheduling_timer;

	/* Is the timer running?
	 *
	 * The kbasep_js_device_data::runpool_irq::lock (a spinlock) must be held
	 * whilst accessing this */
	mali_bool timer_running;

	/* Number of us the least-run context has been running for
	 *
	 * The kbasep_js_device_data::queue_mutex must be held whilst updating this
	 * Reads are possible without this mutex, but an older value might be read
	 * if no memory barriers are issued beforehand. */
	u64 head_runtime_us;
	/* Pointer to the kbase_device structure, for convenience to avoid deeply nested container_of
	 * statements. */
	kbase_device * kbdev;
} kbasep_js_policy_cfs;

/**
 * This policy contains a single linked list of all contexts.
 */
typedef struct kbasep_js_policy_cfs_ctx
{
	/** Link implementing the Policy's Queue, and Currently Scheduled list */
	osk_dlist_item list;

	/** Job lists for use when in the Run Pool - only using
	 * kbasep_js_policy_fcfs::num_unique_slots of them. We still need to track
	 * the jobs when we're not in the runpool, so this member is accessed from
	 * outside the policy queue (for the first job), inside the policy queue,
	 * and inside the runpool.
	 *
	 * If the context is in the runpool, then this must only be accessed with
	 * kbasep_js_device_data::runpool_irq::lock held
	 *
	 * Jobs are still added to this list even when the context is not in the
	 * runpool. In that case, the kbasep_js_kctx_info::ctx::jsctx_mutex must be
	 * held before accessing this. */
	osk_dlist job_list_head[KBASEP_JS_MAX_NR_CORE_REQ_VARIANTS];

	/** Number of us this context has been running for
	 *
	 * The kbasep_js_device_data::runpool_irq::lock (a spinlock) must be held
	 * whilst updating this. Initializing will occur on context init and
	 * context enqueue (which can only occur in one thread at a time), but
	 * multi-thread access only occurs while the context is in the runpool.
	 *
	 * Reads are possible without this spinlock, but an older value might be read
	 * if no memory barriers are issued beforehand */
	u64 runtime_us;

	/* Calling process policy scheme is a realtime scheduler and will use the priority queue
	 * Non-mutable after ctx init */
	mali_bool process_rt_policy;
	/* Calling process NICE priority */
	int process_priority;
	/* Average NICE priority of all atoms in bag:
	 * Hold the kbasep_js_kctx_info::ctx::jsctx_mutex when accessing  */
	int bag_priority;
	/* Total NICE priority of all atoms in bag
	 * Hold the kbasep_js_kctx_info::ctx::jsctx_mutex when accessing  */
	int bag_total_priority;
	/* Total number of atoms in the bag
	 * Hold the kbasep_js_kctx_info::ctx::jsctx_mutex when accessing  */
	int bag_total_nr_atoms;

} kbasep_js_policy_cfs_ctx;

/**
 * In this policy, each Job is part of at most one of the per_corereq lists
 */
typedef struct kbasep_js_policy_cfs_job
{
	osk_dlist_item list;      /**< Link implementing the Run Pool list/Jobs owned by the ctx */
	u32 cached_variant_idx;   /**< Cached index of the list this should be entered into on re-queue */

	/** Number of ticks that this job has been executing for
	 *
	 * To access this, the kbasep_js_device_data::runpool_irq::lock must be held */
	u32 ticks;
} kbasep_js_policy_cfs_job;

/** @} */ /* end group kbase_js_policy */
/** @} */ /* end group base_kbase_api */
/** @} */ /* end group base_api */

#endif


text:
package org.zeropage.apps.zeropage.network.login;

import android.support.annotation.NonNull;

import com.annimon.stream.function.FunctionalInterface;

import org.zeropage.apps.zeropage.network.common.RequestParameter;

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
import retrofit2.http.Path;

@FunctionalInterface
public interface LoginRequest {
    String BASE_URL = "http://zerobot.herokuapp.com/hubot/otp/";

    @POST("{username}/")
    @FormUrlEncoded
    Call<String> login(@Path("username") @NonNull String username,
                       @Field(RequestParameter.TOKEN) @NonNull String token);
}


text:
**DEPRECATED PROJECT**: I (@russss) am no longer maintaining this code - in fact I've never actually deployed it in production myself, although others have. I won't be accepting any more pull requests for this project. If you're maintaining a fork, let me know and I'll link to it.

## About

Herd is a torrent-based file distribution system based on [Murder](https://github.com/lg/murder).
It allows for quick and easy transfer of small and large files. You can probably use
it for other things too.

Herd requires no extra Python modules and includes everything needed for destinations including
its own (lightly modified) copy of BitTornado.

Herd has been updated from its fork [Horde](https://github.com/naterh/Horde) which removed limitations
around large file transfers, peer seeding, and python integration.  Herd now has the same capabilities
as Horde in that regard.

## Differences from Murder

[Murder](https://github.com/lg/murder) was Twitter's original BitTorrent-based file
distribution system. It's pretty dependent on Capistrano and requires that a separate
tracker process is started before you run the deploy task.

Herd spawns its own tracker in the background which makes it really trivial to integrate into whatever
deployment system you like.

## Requirements

Herd needs Python > 2.5 and argparse.  If you're using python 2.7+ nothing else is needed as argparse
was added to the standard library.

Argparse, if needed, can be installed with `easy_install` or `pip`:

    pip install argparse
    easy_install argparse

Herd also requires that key based passwordless authentication is enabled on all of your target
destinations.

## Install

    git clone https://github.com/russss/Herd
    cd Herd && sudo python setup.py install

Herd also supports `pypi_server` hosting.

## Usage

With a hosts file that includes a list of the hosts you want to copy to:

    herd myfile.tar.gz /path/to/destination.tar.gz hosts_file

Using a hosts list that is a single string comma separated:

    herd myfile.tar.gz /path/to/destination.tar.gz --hostlist "host1,host2,host3"

Reading the host list from stdin.

    cat /tmp/hosts_file | herd myfile.tar.gz /path/to/destination.tar.gz hosts_file

More options:

    herd --help

## Python Integration

Herd can also be imported as a python module.  This makes integration into existing projects
easy.  One would simply need to:

    import herd.herd as herd
    herd.run_with_opts('localfile', 'remotefile', hostlist='server1,server2')

## Credits

* [Russ Garrett](https://github.com/russss)
* [Laurie Denness](https://github.com/lozzd)
* [Nate House](https://github.com/naterh)
* [Sam Gleske](https://github.com/samrocketman)
* [Paul Sims](https://github.com/chalupaul)
* [Nandor Sivok](https://github.com/dominis)
* [Mikael Fridh](https://github.com/frimik)
* [Sebastian Borza](https://github.com/sebito91)
* [Patrick Ancillotti](https://github.com/neogenix)


text:
itv start 5 Checking Active sessions in interval mode, type 'Ctrl + C' to abort
set VERIFY on
ora actives
pro
PRO Determine if need to abort(20%) ...
var next_action varchar2
set VERIFY off

begin
    if dbms_random.value(0,10)>8 then
        :next_action := 'off';
    else
        :next_action := 'end';
    end if;
end;
/
pro next_action: itv &next_action
itv &next_action


text:
import libcontext, bee
from bee.segments import *
from libcontext.socketclasses import *
from libcontext.pluginclasses import *
from dragonfly.keycodes import *

class keyboard(bee.worker):

    """The keyboard sensor reports any keyboard input during the last tick"""

    # Which key are we listening for?
    keycode = variable(("str", "keycode"))
    parameter(keycode, "Any")

    #Are we listening for key presses or key releases?
    mode = variable("str")
    parameter(mode, "keypressed")

    #Has a key been pressed during the last tick?
    is_active = variable("bool")
    startvalue(is_active, False)
    active = output("pull", "bool")
    connect(is_active, active)

    #What is the value of the last key?
    # It will be "" if no key has been pressed/released during the last tick
    keyvalue = variable(("str", "keycode"))
    startvalue(keyvalue, "")
    key = output("pull", ("str", "keycode"))
    connect(keyvalue, key)

    # Mark "key" as an advanced output segment, and capitalize the I/O names
    guiparams = {"key": {"advanced": True, "name": "Key"},
                 "active": {"name": "Active"},
                 "_memberorder": ["key", "active"]}

    #Upon a key event, become active on the next tick
    #1. If we are listening for any key:
    def activate1(self, event):
        self.is_active_next = True
        #Also record the value of the key
        self.keyvalue_next = event[2]

    #2. if we are listening for a specific key:
    def activate2(self, event):
        self.is_active_next = True

    #Every tick, update the current output values to the next tick's values
    # and reset the next tick's values
    def update(self):
        self.is_active = self.is_active_next
        self.keyvalue = self.keyvalue_next
        self.is_active_next = False
        self.keyvalue_next = ""

    #Add event listeners at startup
    def set_add_listener(self, add_listener):
        self.add_listener = add_listener

    def enable(self):
        #Initialize the output values for the next tick
        self.is_active_next = False
        self.keyvalue_next = ""

        #Add a high-priority update() listener on every tick
        self.add_listener("trigger", self.update, "tick", priority=9)

        #Add an activate() listener for key events
        if self.keycode == "Any":
            activate = self.activate1
            event_head = ("keyboard", self.mode)
        else:
            activate = self.activate2
            event_head = ("keyboard", self.mode, self.keycode)
        self.add_listener("match_leader", activate, event_head)

    # Method to manipulate the parameter form as it appears in the GUI
    @classmethod
    def form(cls, f):
        f.keycode.name = "Key"
        f.keycode.options = ("Any",) + keycodes

        f.mode.advanced = True
        f.mode.name = "Sensor mode"
        f.mode.type = "option"
        f.mode.options = "keypressed", "keyreleased"
        f.mode.optiontitles = "Detect key presses", "Detect key releases"

        # Finally, declare our sockets and plugins, to communicate with the rest of the hive

    def place(self):
        #Grab the hive's function for adding listeners
        libcontext.socket(("evin", "add_listener"), socket_single_required(self.set_add_listener))
        #Make sure we are enabled at startup
        libcontext.plugin(("bee", "init"), plugin_single_required(self.enable))

        #Declare flag sockets, to declare that we require keyboard support
        # If there is no keyboard support, an error will now be raised when the hive is closed
        libcontext.socket(("evin", ("input", "keyboard")), socket_flag())
        # If we are listening for non-ASCII keys, we need support for those keys too
        # TODO might we also need non ASCII here?
        if self.keycode != "Any" and self.keycode not in asciilist:
            libcontext.socket(("evin", ("input", "keyboard", "extended")), socket_flag())


text:
@implementation LCImageCacheConfiguration

+ (instancetype)defaultConfiguration {
    LCImageCacheConfiguration *defaultConfiguration = [[LCImageCacheConfiguration alloc] init];
    return defaultConfiguration;
}

@end

@implementation LCImageCacheManager

@end


text:
export const Button: any;
export const PrimaryButton: any;
export const DangerButton: any;
export const QuietButton: any;
export const IconicButton: any;
export const ControlIcon: any;


text:
package org.apache.sentry.provider.db.log.entity;

import static junit.framework.Assert.assertEquals;

import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.hadoop.conf.Configuration;
import org.apache.log4j.Logger;
import org.apache.sentry.core.model.db.AccessConstants;
import org.apache.sentry.provider.db.log.util.CommandUtil;
import org.apache.sentry.provider.db.log.util.Constants;
import org.apache.sentry.provider.db.service.thrift.TAlterSentryRoleAddGroupsRequest;
import org.apache.sentry.provider.db.service.thrift.TAlterSentryRoleAddGroupsResponse;
import org.apache.sentry.provider.db.service.thrift.TAlterSentryRoleDeleteGroupsRequest;
import org.apache.sentry.provider.db.service.thrift.TAlterSentryRoleDeleteGroupsResponse;
import org.apache.sentry.provider.db.service.thrift.TAlterSentryRoleGrantPrivilegeRequest;
import org.apache.sentry.provider.db.service.thrift.TAlterSentryRoleGrantPrivilegeResponse;
import org.apache.sentry.provider.db.service.thrift.TAlterSentryRoleRevokePrivilegeRequest;
import org.apache.sentry.provider.db.service.thrift.TAlterSentryRoleRevokePrivilegeResponse;
import org.apache.sentry.provider.db.service.thrift.TCreateSentryRoleRequest;
import org.apache.sentry.provider.db.service.thrift.TCreateSentryRoleResponse;
import org.apache.sentry.provider.db.service.thrift.TDropSentryRoleRequest;
import org.apache.sentry.provider.db.service.thrift.TDropSentryRoleResponse;
import org.apache.sentry.provider.db.service.thrift.TSentryGroup;
import org.apache.sentry.provider.db.service.thrift.TSentryPrivilege;
import org.apache.sentry.service.thrift.ServiceConstants.PrivilegeScope;
import org.apache.sentry.service.thrift.ServiceConstants.ServerConfig;
import org.apache.sentry.service.thrift.Status;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestJsonLogEntityFactory {

  private static Configuration conf;
  private Logger sentryLogger = Logger.getRootLogger();

  private static String TEST_IP = "localhost/127.0.0.1";
  private static String TEST_IMPERSONATOR = "impersonator";
  private static String TEST_ROLE_NAME = "testRole";
  private static String TEST_USER_NAME = "requestUser";
  private static String TEST_DATABASE_NAME = "testDB";
  private static String TEST_TABLE_NAME = "testTable";
  private static String TEST_GROUP = "testGroup";

  @BeforeClass
  public static void init() {
    conf = new Configuration();
    conf.set(ServerConfig.SENTRY_SERVICE_NAME,
        ServerConfig.SENTRY_SERVICE_NAME_DEFAULT);
    CommandUtil.setIpAddress(TEST_IP);
    CommandUtil.setImpersonator(TEST_IMPERSONATOR);
  }

  @Test
  public void testCreateRole() {
    TCreateSentryRoleRequest request = new TCreateSentryRoleRequest();
    TCreateSentryRoleResponse response = new TCreateSentryRoleResponse();
    request.setRequestorUserName(TEST_USER_NAME);
    request.setRoleName(TEST_ROLE_NAME);
    response.setStatus(Status.OK());
    AuditMetadataLogEntity amle = (AuditMetadataLogEntity) JsonLogEntityFactory
        .getInstance().createJsonLogEntity(request, response, conf);
    assertCommon(amle, Constants.TRUE, Constants.OPERATION_CREATE_ROLE,
        "CREATE ROLE testRole", null, null, null, Constants.OBJECT_TYPE_ROLE);
    sentryLogger.debug(amle.toJsonFormatLog());

    response.setStatus(Status.InvalidInput("", null));
    amle = (AuditMetadataLogEntity) JsonLogEntityFactory.getInstance()
        .createJsonLogEntity(request, response, conf);
    assertCommon(amle, Constants.FALSE, Constants.OPERATION_CREATE_ROLE,
        "CREATE ROLE testRole", null, null, null, Constants.OBJECT_TYPE_ROLE);
    sentryLogger.debug(amle.toJsonFormatLog());
  }

  @Test
  public void testDropRole() {
    TDropSentryRoleRequest request = new TDropSentryRoleRequest();
    TDropSentryRoleResponse response = new TDropSentryRoleResponse();
    request.setRequestorUserName(TEST_USER_NAME);
    request.setRoleName(TEST_ROLE_NAME);
    response.setStatus(Status.OK());
    AuditMetadataLogEntity amle = (AuditMetadataLogEntity) JsonLogEntityFactory
        .getInstance().createJsonLogEntity(request, response, conf);
    assertCommon(amle, Constants.TRUE, Constants.OPERATION_DROP_ROLE,
        "DROP ROLE testRole", null, null, null, Constants.OBJECT_TYPE_ROLE);
    sentryLogger.debug(amle.toJsonFormatLog());

    response.setStatus(Status.InvalidInput("", null));
    amle = (AuditMetadataLogEntity) JsonLogEntityFactory.getInstance()
        .createJsonLogEntity(request, response, conf);
    assertCommon(amle, Constants.FALSE, Constants.OPERATION_DROP_ROLE,
        "DROP ROLE testRole", null, null, null, Constants.OBJECT_TYPE_ROLE);
    sentryLogger.debug(amle.toJsonFormatLog());
  }

  @Test
  public void testGrantRole() {
    TAlterSentryRoleGrantPrivilegeRequest request = new TAlterSentryRoleGrantPrivilegeRequest();
    request.setRequestorUserName(TEST_USER_NAME);
    request.setRoleName(TEST_ROLE_NAME);

    TAlterSentryRoleGrantPrivilegeResponse response = new TAlterSentryRoleGrantPrivilegeResponse();

    TSentryPrivilege privilege = getPrivilege(AccessConstants.ALL,
        PrivilegeScope.DATABASE.name(), TEST_DATABASE_NAME, null, null, null);
    request.setPrivilege(privilege);
    response.setStatus(Status.OK());
    AuditMetadataLogEntity amle = (AuditMetadataLogEntity) JsonLogEntityFactory
        .getInstance().createJsonLogEntity(request, response, conf);
    assertCommon(amle, Constants.TRUE, Constants.OPERATION_GRANT_PRIVILEGE,
        "GRANT ALL ON DATABASE testDB TO ROLE testRole", TEST_DATABASE_NAME,
        null, null, Constants.OBJECT_TYPE_PRINCIPAL);
    sentryLogger.debug(amle.toJsonFormatLog());

    privilege = getPrivilege(AccessConstants.ALL, PrivilegeScope.TABLE.name(),
        null, TEST_TABLE_NAME, null, null);
    request.setPrivilege(privilege);
    response.setStatus(Status.InvalidInput("", null));
    amle = (AuditMetadataLogEntity) JsonLogEntityFactory.getInstance()
        .createJsonLogEntity(request, response, conf);
    assertCommon(amle, Constants.FALSE, Constants.OPERATION_GRANT_PRIVILEGE,
        "GRANT ALL ON TABLE testTable TO ROLE testRole", null, TEST_TABLE_NAME,
        null, Constants.OBJECT_TYPE_PRINCIPAL);
    sentryLogger.debug(amle.toJsonFormatLog());
  }

  @Test
  public void testRevokeRole() {
    TAlterSentryRoleRevokePrivilegeRequest request = new TAlterSentryRoleRevokePrivilegeRequest();
    TAlterSentryRoleRevokePrivilegeResponse response = new TAlterSentryRoleRevokePrivilegeResponse();
    request.setRequestorUserName(TEST_USER_NAME);
    request.setRoleName(TEST_ROLE_NAME);

    TSentryPrivilege privilege = getPrivilege(AccessConstants.ALL,
        PrivilegeScope.DATABASE.name(), TEST_DATABASE_NAME, null, null, null);
    request.setPrivilege(privilege);
    response.setStatus(Status.OK());
    AuditMetadataLogEntity amle = (AuditMetadataLogEntity) JsonLogEntityFactory
        .getInstance().createJsonLogEntity(request, response, conf);
    assertCommon(amle, Constants.TRUE, Constants.OPERATION_REVOKE_PRIVILEGE,
        "REVOKE ALL ON DATABASE testDB FROM ROLE testRole", TEST_DATABASE_NAME,
        null, null, Constants.OBJECT_TYPE_PRINCIPAL);
    sentryLogger.debug(amle.toJsonFormatLog());

    privilege = getPrivilege(AccessConstants.ALL, PrivilegeScope.TABLE.name(),
        null, TEST_TABLE_NAME, null, null);
    request.setPrivilege(privilege);
    response.setStatus(Status.InvalidInput("", null));
    amle = (AuditMetadataLogEntity) JsonLogEntityFactory.getInstance()
        .createJsonLogEntity(request, response, conf);
    assertCommon(amle, Constants.FALSE, Constants.OPERATION_REVOKE_PRIVILEGE,
        "REVOKE ALL ON TABLE testTable FROM ROLE testRole", null,
        TEST_TABLE_NAME, null, Constants.OBJECT_TYPE_PRINCIPAL);
    sentryLogger.debug(amle.toJsonFormatLog());
  }

  @Test
  public void testAddRole() {
    TAlterSentryRoleAddGroupsRequest request = new TAlterSentryRoleAddGroupsRequest();
    TAlterSentryRoleAddGroupsResponse response = new TAlterSentryRoleAddGroupsResponse();
    request.setRequestorUserName(TEST_USER_NAME);
    request.setRoleName(TEST_ROLE_NAME);
    request.setGroups(getGroups());
    response.setStatus(Status.OK());
    AuditMetadataLogEntity amle = (AuditMetadataLogEntity) JsonLogEntityFactory
        .getInstance().createJsonLogEntity(request, response, conf);
    assertCommon(amle, Constants.TRUE, Constants.OPERATION_ADD_ROLE,
        "GRANT ROLE testRole TO GROUP testGroup", null, null, null,
        Constants.OBJECT_TYPE_ROLE);
    sentryLogger.debug(amle.toJsonFormatLog());

    response.setStatus(Status.InvalidInput("", null));
    amle = (AuditMetadataLogEntity) JsonLogEntityFactory.getInstance()
        .createJsonLogEntity(request, response, conf);
    assertCommon(amle, Constants.FALSE, Constants.OPERATION_ADD_ROLE,
        "GRANT ROLE testRole TO GROUP testGroup", null, null, null,
        Constants.OBJECT_TYPE_ROLE);
    sentryLogger.debug(amle.toJsonFormatLog());
  }

  @Test
  public void testDeleteRole() {
    TAlterSentryRoleDeleteGroupsRequest request = new TAlterSentryRoleDeleteGroupsRequest();
    TAlterSentryRoleDeleteGroupsResponse response = new TAlterSentryRoleDeleteGroupsResponse();
    request.setRequestorUserName(TEST_USER_NAME);
    request.setRoleName(TEST_ROLE_NAME);
    request.setGroups(getGroups());
    response.setStatus(Status.OK());
    AuditMetadataLogEntity amle = (AuditMetadataLogEntity) JsonLogEntityFactory
        .getInstance().createJsonLogEntity(request, response, conf);
    assertCommon(amle, Constants.TRUE, Constants.OPERATION_DELETE_ROLE,
        "REVOKE ROLE testRole FROM GROUP testGroup", null, null, null,
        Constants.OBJECT_TYPE_ROLE);
    sentryLogger.debug(amle.toJsonFormatLog());

    response.setStatus(Status.InvalidInput("", null));
    amle = (AuditMetadataLogEntity) JsonLogEntityFactory.getInstance()
        .createJsonLogEntity(request, response, conf);
    assertCommon(amle, Constants.FALSE, Constants.OPERATION_DELETE_ROLE,
        "REVOKE ROLE testRole FROM GROUP testGroup", null, null, null,
        Constants.OBJECT_TYPE_ROLE);
    sentryLogger.debug(amle.toJsonFormatLog());
  }

  private void assertCommon(AuditMetadataLogEntity amle,
      String allowedExcepted, String operationExcepted,
      String operationTextExcepted, String databaseNameExcepted,
      String tableNameExcepted, String resourcePathExcepted,
      String objectTypeExcepted) {
    assertEquals(ServerConfig.SENTRY_SERVICE_NAME_DEFAULT,
        amle.getServiceName());
    assertEquals(TEST_IP, amle.getIpAddress());
    assertEquals(TEST_USER_NAME, amle.getUserName());
    assertEquals(TEST_IMPERSONATOR, amle.getImpersonator());
    assertEquals(allowedExcepted, amle.getAllowed());
    assertEquals(operationExcepted, amle.getOperation());
    assertEquals(operationTextExcepted, amle.getOperationText());
    assertEquals(tableNameExcepted, amle.getTableName());
    assertEquals(databaseNameExcepted, amle.getDatabaseName());
    assertEquals(resourcePathExcepted, amle.getResourcePath());
    assertEquals(objectTypeExcepted, amle.getObjectType());
  }

  // private TAlterSentryRoleGrantPrivilegeRequest getGrantPrivilegeRequest() {
  // TAlterSentryRoleGrantPrivilegeRequest request = new
  // TAlterSentryRoleGrantPrivilegeRequest();
  // request.setRoleName(TEST_ROLE_NAME);
  // return request;
  // }
  //
  // private TAlterSentryRoleGrantPrivilegeResponse getGrantPrivilegeResponse(
  // TSentryResponseStatus status) {
  // TAlterSentryRoleGrantPrivilegeResponse response = new
  // TAlterSentryRoleGrantPrivilegeResponse();
  // response.setStatus(status);
  // return response;
  // }

  // private TAlterSentryRoleRevokePrivilegeRequest getRevokePrivilegeRequest()
  // {
  // TAlterSentryRoleRevokePrivilegeRequest request = new
  // TAlterSentryRoleRevokePrivilegeRequest();
  // request.setRoleName(TEST_ROLE_NAME);
  // return request;
  // }
  //
  // private TAlterSentryRoleRevokePrivilegeResponse getRevokePrivilegeResponse(
  // TSentryResponseStatus status) {
  // TAlterSentryRoleRevokePrivilegeResponse response = new
  // TAlterSentryRoleRevokePrivilegeResponse();
  // response.setStatus(status);
  // return response;
  // }

  private TSentryPrivilege getPrivilege(String action, String privilegeScope,
      String dbName, String tableName, String serverName, String URI) {
    TSentryPrivilege privilege = new TSentryPrivilege();
    privilege.setAction(action);
    privilege.setPrivilegeScope(privilegeScope);
    privilege.setDbName(dbName);
    privilege.setTableName(tableName);
    privilege.setServerName(serverName);
    privilege.setURI(URI);
    return privilege;
  }

  private Set<TSentryGroup> getGroups() {
    Set<TSentryGroup> groups = new LinkedHashSet<TSentryGroup>();
    TSentryGroup group = new TSentryGroup();
    group.setGroupName(TEST_GROUP);
    groups.add(group);
    return groups;
  }
}


text:
const mws = require('../lib/mws.js');
const xero = require('../lib/xero.js');
const wisecracker = require('../lib/wisecracker.js');

// Initialize the libraries
mws.init();
xero.init();

// First check the newest MWS order from xero
var getNewestOrder = function getNewestOrder() {
  var whereFilter = 'Type=="ACCREC" AND Contact.Name.StartsWith("Amazon")';
  var orderBy = 'Date DESC';
  var pageNum = 1;
  xero.getInvoices(whereFilter, orderBy, pageNum)
  .then(function(body) {

    // Get the newest invoice reference i
    var invoice = body.Invoices[0];
    var fixedDate = fixDate(invoice.Date);
    console.log(fixedDate.toString());
    console.log('Xero newest invoice: ' + invoice.InvoiceNumber + ' on ' + fixedDate);
    return fixedDate;
  })
  .then(function(fixedDate) {
    // Get the Amazon orders since then
    return mws.listOrders(fixedDate);
  })
  .then(function(result, metadata) {
    console.log('There are ' + result.result.length + ' orders.');
    for (var i=0; i < result.result.length; i++) {
      var mwsOrder = result.result[i];
      processOrder(mwsOrder);
    }
  })
}

// Process a single MWS Order
var processOrder = function processOrder(mwsOrder) {
  var mwsId = mwsOrder.AmazonOrderId;
  var customerName = 'Amazon Customer';
  console.log('Processing Order ' + mwsOrder.AmazonOrderId + ' for ' + customerName);
  var lineItems = [];

  mws.getItems(mwsId)
  .then(function(result, metadata) {
    lineItems = result.result;
    console.log(mwsId + ' has ' + lineItems.length + ' line items');
    var whereFilter = 'Name=="' + customerName + '"';
    return xero.getContacts(whereFilter)
  })
  .then(function(xeroContactResponse) {
    var xeroContact = xeroContactResponse.Contacts[0];
    return wisecracker.addAmazonOrder2Xero(mwsOrder, lineItems, xeroContact)
  })
  .then(function(xeroInvoice) {
    console.log('Xero Invoice AMZN#' + mwsId + ' added/updated.');
  })
  .catch(function(err) {
    console.error('processOrder failed: ' + err);
  });
}

var fixDate = function fixDate(invoiceDate) {
  var start = invoiceDate.indexOf('(') + 1;
  var end = invoiceDate.indexOf('+');
  var sub = invoiceDate.substring(start, end);
  var fixedDate = new Date(parseInt(sub));
  return fixedDate;
}

getNewestOrder();


text:
package net.piemaster.jario.spatials;

import net.piemaster.jario.spatials.generic.GenericImage;

import com.artemis.Entity;
import com.artemis.World;

public class Shell extends GenericImage
{
	private static final String IMAGE_PATH = "/images/shell.png";

	public Shell(World world, Entity e)
	{
		super(world, e, IMAGE_PATH);
	}
}


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% COSYNE-2007 Abstract Template
%%% Version 1.0
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\documentclass[11pt]{article}
\usepackage{times}
\usepackage[english,german]{babel}
\usepackage{graphicx}                 %zum Einfuegen von Bildern
\usepackage[square]{natbib}
\usepackage{wrapfig}

\oddsidemargin 0.0in		% margin, in addition to 1" standard
\textwidth 6.5in		% 8.5" - 2*(1+\oddsidemargin)

\topmargin -0.5in		% in addition to 1.5" standard margin
\textheight 9.5in 		% 11 - ( 1.5 + \topmargin + <bottom-margin> )

\columnsep 0.25in

\parindent 0pt
\parskip 9pt

\flushbottom \sloppy
\pagestyle{empty}		% No page numbers

\begin{document}

%%%-----------------------------------------------------------------
\begin{center}
{\LARGE\bf
Machine Learning WS2012/13 (Unsupervised Learning)}\\[.5cm]
{\Large Lecturer: Prof. Dr. Bethge}\\[1cm]
\end{center}

\textbf{Examples of unsupervised learning applications}
\begin{itemize}
	\item \emph{density estimation} (e.g. texture synthesis), image compression
	\item level set estimation
	\item clustering/mode finding e.g. spike sorting; algorithm Mixture of Gaussians
	\item metric learning e.g. 3D visualization; algorithm multidimensional scaling
	\item feature extraction -> representation learning, e.g. whitening; algorithm principle component analysis
\end{itemize}

{\bf 1. Set algebras, measures, and probabilities}

\begin{itemize}
\item {\bf Overview for the mathematical construction of random variables}
\begin{itemize}
\item Sample Space $S$ (often also $\Omega $). $s\in S$ ``outcomes''
\item Boolean Algebra (or Sigma Algebra)  $\mathcal{B}(S)$ and $A \in \mathcal{B}(S)$ are called ``events''. An event $A$ is realized if an outcome $s$ is in $A$. \\For example, $\mathcal{B}(S)=\mathcal{P}(S)$
\item Measure $m: \mathcal{B}(S) \to [0,\infty)$ and $m(A\dot\cup B) = m(A) + m(B)$
\item probability measure $p(S)=1$, if $m$ is a measure with $m(S)<\infty$ then $p(A) := m(A)/m(S)$ is a probability measure.
\item random variables: consider $M \in \mathcal{B}(S)$ with $M=\{s \in S: X(s) < \vartheta\} \subseteq S$
\end{itemize}

\item {\bf Power Set:}  $\mathcal{P}(S) := \{A\subseteq S\}$, $|\mathcal{P}(S) |= 2^{|S|}$

\item {\bf Boolean Algebra:}  $\mathcal{B}(S) \subseteq \mathcal{P}(S)$ is called a {\it Boolean Algebra} iff
\begin{itemize}
\item[(i)] $A \in \mathcal{B}(S)  \Rightarrow \overline{A} \in \mathcal{B}(S)  $
\item[(ii)] $A, B \in \mathcal{B}(S)  \Rightarrow A \cup B \in \mathcal{B}(S)  $
\end{itemize}
Examples:
\begin{itemize}
\item[(i)] $\{ \emptyset, S\}  $ and $\mathcal{P}(S)$ are Boolean Algebras.
\item[(ii)] If $a\in S$ then $\{\emptyset, \{a\}, S-\{a\}, S\}$ is the Boolean Algebra {\it generated by} $a$.
\item[(iii)] $I(R)$ is defined to be the smallest Boolean Algebra which contains all open intervals $(a,b)$ for which $-\infty \le a < b\le \infty$.
\end{itemize}

\item {\bf Sigma-Algebra:}  $\mathcal{B}(S) \subseteq \mathcal{P}(S)$ is called a Sigma-Algebra if
\begin{itemize}
\item[(i)] $A \in \mathcal{B}(S)  \Rightarrow \overline{A} \in \mathcal{B}(S)  $
\item[(ii)] For all sequences $A_1, A_2, \dots \in \mathcal{B}(S)  \Rightarrow \bigcup_{k=1}^\infty A_k \in \mathcal{B}(S)  $
\end{itemize}

\item {\bf Venn diagram}

\item {\bf Proposition 1 (Boolean laws):}
\begin{itemize}
\item[(B1)] Idempotency: $A \cup A = A$;   \hspace{.5cm} $A \cap A = A$
\item[(B2)] Associativity: $A \cap (B\cap C) = (A\cap B) \cap C$
\item[(B3)] Commutativity: $A \cup B = B \cup A$;    \hspace{.5cm}  $A \cap B = B \cap A$
\item[(B4)] Distributivity: $A \cap (B\cup C)  = (A \cap B) \cup (A \cap C)$; \hspace{.5cm}  $A \cup (B\cap C)  = (A \cup B) \cap (A \cup C)$
\item[(B5)] de Morgan's law:  $\overline{A \cup B} = \overline{A} \cap \overline{B} $;    \hspace{.5cm}  $\overline{A \cap B} = \overline{A} \cup \overline{B} $
\item[(B6)] Complements: $ \overline{ \overline{A}} =  A$; \hspace{.5cm}  $A \cap \overline{A} = \emptyset$; \hspace{.5cm}  $A \cup \overline{A} = S$
\item[(B7)] Properties of $S$ and $ \emptyset$: \hspace{.2cm} $A \cup S = S$; \hspace{.5cm} $A \cup \emptyset = A$; \hspace{.5cm} $A \cap S = A$; \hspace{.5cm} $A \cap \emptyset = \emptyset$

\end{itemize}

\item {\bf (Finite) Measure:} A mapping $m: \mathcal{B}(S) \rightarrow [0, \infty), A\in  \mathcal{B}(S) \to m(A) \in [0, \infty)$ is called a {\it measure} if for all $A,B \in \mathcal{B}(S)$ with $A\cap B = \emptyset$ holds: $m(A\cup B) = m(A) + m(B)$.\\(This property can be written compactly as $m(A\dot\cup B) = m(A) + m(B)$)

Examples:
\begin{itemize}
\item[(i)] $m(A) := |A|$ is the {\it counting measure}.
\item[(ii)] For $S=[a,b]$ and $\mathcal{B}(S)=\mathcal{I}([a,b])$ with $|a|, |b| < \infty$ the {\it Lebesgue Measure} is defined as $m([c, d]) := d-c$.
\item[(iii)] If $f(x) \ge 0$ for all $a \le x \le b$ with $\int_a^b f(x) dx <\infty$ then $m([c, d]) := \int_c^d f(x) dx $ is a measure.
\item[(iv)] For $S=R$ and $\mathcal{B}(S)=\mathcal{I}(R)$ the {\it Dirac Ma\ss} is given by $\delta_a(J) = 1$ if $a\in J$ and $\delta_a(J) = 0$ otherwise.
\end{itemize}

\item {\bf Proposition 2:}
\begin{itemize}
\item[(i)] If $B\subseteq A$ then $m(A-B) = m(A) - m(B)$.
\item[(ii)] If $B\subseteq A$ then $m(B) \le m(A)$.
\item[(iii)] $m(\emptyset) =0$.
\item[(iv)] $m(A \cup B) = m(A) + m(B) - m(A\cap B)$.
\end{itemize}

\item {\bf Proposition 3:}\\
If $A,B \in \mathcal{B}(S)$ then:
\begin{itemize}
\item[(i)] $ (A \cap B) \in \mathcal{B}(S)$ since $ (A \cap B) = \overline{\overline{A} \cup \overline{B}}$.
\item[(ii)] $\emptyset, S$ belong to every Boolean Algebra, since for $A \in \mathcal{B}(S)$ also $\overline{A} \in \mathcal{B}(S)$ and $A \cap \overline{A} = \emptyset$ and $A\cup \overline{A} = S$ .
\item[(iii)] $\mathcal{B}_B(S) := B \cap \mathcal{B}(S) = \{A \cap B: A \in \mathcal{B}(S)\}$ is a Boolean Algebra if $B\ne \emptyset$.
\item[(iv)] $\mathcal{B}_B(S) \subseteq \mathcal{B}(S)$.
\end{itemize}

\item {\bf Probability measure:} For a sample space $S$ and a Sigma Algebra $\mathcal{B}(S)$ a measure \, $P$ is a {\it probability measure} if $P(S)=1$.

\item {\bf Probability space:} A probability space consists of the triple $(S,\mathcal{B}(S), P)$ where $S$ is the sample space, $\mathcal{B}(S)$ the event algebra (which is a Boolean or a sigma algebra) and $P$ is a  probability measure on $\mathcal{B}(S)$.

\item {\bf Proposition 4:}
\begin{itemize}
\item[(i)] $0 \le P(A) \le 1$.
\item[(ii)] $P(\overline{A}) = 1-P(A)$.
\item[(iii)] If $\mathcal{E}= \{E_1, E_2, \dots, E_n\}$ is a partition of $S$ (that is $S= \bigcup_{k=1}^n E_k$ and $E_l \cap E_m = \emptyset$), then \quad $\sum_{k=1}^n P(E_k) = 1$ \quad and \quad $P(A)=\sum_{k=1}^n P(A\cap E_k)$.
\end{itemize}

\item {\bf Specification of probabilities}
\begin{itemize}
\item[(i)] As a limiting value of relative frequencies: $P(A) = \lim_{n\to \infty} \frac{r_n(A)}{n}$
\item[(ii)] Symmetrie assumptions (e.g. if we assume $P(s)=P(s^\prime)$ for all $s,s^\prime \in S$ then it follows: $P(s) = 1/|S|$).
\item[(iii)] Subjective probabilities (based on Cox axioms) can be determined via betting games.
\end{itemize}
\item {\bf Conditional probabilities:}
If $(S,\mathcal{B}(S), P)$ is a probability space and $B \in \mathcal{B}(S)$ then the restriction of $P$ to the reduced Sigma-Algebra $\mathcal{B}_B(S):=\{B\cap A: A \in \mathcal{B}(S)\}$ defines a measure \ $M_B: \mathcal{B}_B \to [0,\infty)$. If in addition $P(B) >0$, then $P_B: \mathcal{B}_B(S) \to [0,1], \quad A_B \mapsto P_B(A_B) :=  M_B(A_B)/P(B)=P(A_B)/P(B), \, \forall A_B \in \mathcal{B}_B(S)$ is a probability measure on $\mathcal{B}_B(S)$.\\
The $A_B\in \mathcal{B}_B(S)$ usually originate from intersection of the elements of the original Sigma-Algebra $\mathcal{B}(S)$ with the event $B$.
\item {\bf Independence:}\\
Two events $A$ and $B$ are {\it statistically independent} iff $P(A\cap B) = P(A) P(B)$.
\item {\bf Proposition 5:}
\begin{itemize}
\item[(i)] Two events $A$ and $B$ are (statistically) independent if $P(A)=0$ or $P(B)=0$.
\item[(ii)] If two events $A$ and $B$ are independent and $P(A)>0$, then: $P(B|A)=P_A(B)=P(B)$.
\item[(iii)] If two events $A$ and $B$ are independent and $P(A)>0$, then $A$ and $\overline{B}$ are independent as well.
\end{itemize}

\end{itemize}
\begin{center}
{\Large \bf Random Variables}
\end{center}

\begin{itemize}

\item {\bf Cumulative distribution function (cdf):}
Any univariate random variable can be uniquely defined by the cumulative distribution function:
$$
F(x) = P(\{s \in S: X(s) \le x\}), \quad \forall x \in S^\prime
$$
It holds:
\begin{itemize}
\item[(i)] $F$ is a nondecreasing function.
\item[(ii)] $\lim_{x\to -\infty} F(x)= 0$, $\lim_{x\to \infty} F(x)= 1$
\item[(iii)] Any function that fulfills (i)+(ii) is a cdf.
\item[(iv)] $ P(\{s \in S: X(s) > x\}) = 1-F(x)$
\item[(v)] $ P(\{s \in S: x_1 < X(s) \le x_2\}) = F(x_2)-F(x_1)$
\item[(vi)] discrete case: probability mass function / point probability $p(x) = F(x) - \lim_{\epsilon \to 0}F(x-\epsilon)$
\item[(vii)] continuous case: probability density function (pdf) $\rho(x) = \frac{d}{dx} \mathcal{F}(x)$
\end{itemize}

\item {\bf Expectation (value):}
$$
E[X] = \sum_{k=1}^n p(x_k) x_k , \quad E[f(X)] = \sum_{k=1}^n p(x_k) f(x_k)
$$
\item {\bf Moments:}
$$
E[X^m] =  \sum_{k=1}^n p(x_k) x_k^m
$$
\item {\bf Variance:}
$$
Var[X]= E[X^2]-E[X]^2
$$

\end{itemize}
\vfil

\end{document}


text:
from django.http import HttpResponse
import json

MIMEANY = '*/*'
MIMEJSON = 'application/json'
MIMETEXT = 'text/plain'

def response_mimetype(request):

    can_json = MIMEJSON in request.META['HTTP_ACCEPT']
    can_json |= MIMEANY in request.META['HTTP_ACCEPT']
    return MIMEJSON if can_json else MIMETEXT

class JSONResponse(HttpResponse):

    def __init__(self, obj='', json_opts=None, mimetype=MIMEJSON, *args, **kwargs):
        json_opts = json_opts if isinstance(json_opts, dict) else {}
        content = json.dumps(obj, **json_opts)
        super(JSONResponse, self).__init__(content, mimetype, *args, **kwargs)