text:
[![FIWARE Security](https://nexus.lab.fiware.org/repository/raw/public/badges/chapters/security.svg)](https://www.fiware.org/developers/catalogue/)
[![License: MIT](https://img.shields.io/github/license/ging/fiware-idm.svg)](https://opensource.org/licenses/MIT)
[![Docker badge](https://img.shields.io/docker/pulls/fiware/idm.svg)](https://hub.docker.com/r/fiware/idm/)
[![Support badge](https://img.shields.io/badge/tag-fiware-orange.svg?logo=stackoverflow)](https://stackoverflow.com/questions/tagged/fiware-keyrock)
<br>
[![Documentation](https://img.shields.io/readthedocs/fiware-idm.svg)](https://fiware-idm.readthedocs.io/en/latest/)
[![Build Status](https://travis-ci.org/ging/fiware-idm.svg?branch=master)](https://travis-ci.org/ging/fiware-idm)
[![Coverage Status](https://coveralls.io/repos/github/ging/fiware-idm/badge.svg?branch=master)](https://coveralls.io/github/ging/fiware-idm?branch=master)
![Status](https://nexus.lab.fiware.org/repository/raw/public/static/badges/statuses/keyrock.svg)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/c1f1239e878341b782be7ed9a67afdfd)](https://app.codacy.com/app/apozohue10/fiware-idm?utm_source=github.com&utm_medium=referral&utm_content=ging/fiware-idm&utm_campaign=Badge_Grade_Dashboard)

Keyrock is the FIWARE component responsible for Identity Management. Using
Keyrock (in conjunction with other security components such as
[PEP Proxy](https://github.com/ging/fiware-pep-proxy) and
[Authzforce](https://github.com/authzforce/server)) enables you to add
OAuth2-based authentication and authorization security to your services and
applications.

This project is part of [FIWARE](https://www.fiware.org/). For more information
check the FIWARE Catalogue entry for
[Security](https://github.com/Fiware/catalogue/tree/master/security).

| :books: [Documentation](https://fiware-idm.readthedocs.io/en/latest/) | :mortar_board: [Academy](https://fiware-academy.readthedocs.io/en/latest/security/keyrock) | :whale: [Docker Hub](https://hub.docker.com/r/fiware/idm/) | :dart: [Roadmap](https://github.com/ging/fiware-idm/blob/master/roadmap.md) |
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------- | --------------------------------------------------------------------------- |

## Content

-   [Background](#background)
    -   [Software requirements](#software-requirements)
-   [Install](#install)
    -   [Docker](#docker)
-   [Usage](#usage)
-   [API](#api)
-   [Tests](#tests)
-   [Advanced Documentation](#advanced-documentation)
-   [Changes Introduced in 7.x](#changes-introduced-in-7x)
-   [Quality Assurance](#quality-assurance)
-   [License](#license)

---

## Background

The main identity management concepts within Keyrock are:

-   Users
    -   Have a registered account in Keyrock.
    -   Can manage organizations and register applications.
-   Organizations
    -   Are group of users that share resources of an application (roles and
        permissions).
    -   Users can be members or owners (manage the organization).
-   Applications
    -   has the client role in the OAuth 2.0 architecture and will request
        protected user data.
    -   Are able to authenticate users using their Oauth credentials (ID and
        secret) which unequivocally identify the application
    -   Define roles and permissions to manage authorization of users and
        organizations
    -   Can register Pep Proxy to protect backends.
    -   Can register IoT Agents.

Keyrock provides both a GUI and an API interface.

### Software requirements

This GE is based on a JavaScript environment and SQL databases. In order to run
the identity manager the following requirements must be installed:

-   node.js
-   npm
-   mysql-server (^5.7)
-   build-essential

## Install

1.  Clone Proxy repository:

```console
git clone https://github.com/ging/fiware-idm.git
```

2.  Install the dependencies:

```console
cd fiware-idm/
npm install
```

3.  Duplicate config.template in config.js:

```console
cp config.js.template config.js
```

4.  Configure data base access credentials:

```javascript
config.database = {
    host: 'localhost', // default: 'localhost'
    password: 'idm', // default: 'idm'
    username: 'root', // default: 'root'
    database: 'idm', // default: 'idm'
    dialect: 'mysql' // default: 'mysql'
};
```

5.  To configure the server to listen HTTPS requests, generate certificates
    OpenSSL and configure config.js:

```console
./generate_openssl_keys.sh
```

```javascript
config.https = {
    enabled: true, //default: 'false'
    cert_file: 'certs/idm-2018-cert.pem',
    key_file: 'certs/idm-2018-key.pem',
    port: 443
};
```

6.  Create database, run migrations and seeders:

```console
npm run-script create_db
npm run-script migrate_db
npm run-script seed_db
```

7.  Start server with admin rights (server listens in 3000 port by default or in
    443 if HTTPS is enabled).

```console
sudo npm start
```

You can test the Identity manager using the default user:

-   Email: `admin@test.com`
-   Password: `1234`

### Docker

We also provide a Docker image to facilitate you the building of this GE.

-   [Here](https://github.com/ging/fiware-idm/tree/master/extras/docker) you
    will find the Dockerfile and the documentation explaining how to use it.
-   In [Docker Hub](https://hub.docker.com/r/fiware/idm/) you will find the
    public image.

## Usage

Information about how to use the Keyrock GUI can be found in the
[User & Programmers Manual](https://fiware-idm.readthedocs.io/en/latest/user_and_programmers_guide/introduction).

## API

Resources can be managed through the API (e.g. Users, applications and
organizations). Further information can be found in the
[API section](https://fiware-idm.readthedocs.io/en/latest/api/introduction).

Finally, one of the main uses of this Generic Enabler is to allow developers to
add identity management (authentication and authorization) to their applications
based on FIWARE identity. This is posible thanks to
[OAuth2](https://oauth.net/2/) protocol. For more information check the
[OAuth2 API](https://fiware-idm.readthedocs.io/en/latest/oauth/introduction).

## Tests

For performing a basic end-to-end test, you have to follow the next steps. A
detailed description about how to run tests can be found
[here](https://fiware-idm.readthedocs.io/en/latest/installation_and_administration_guide/sanity_check/).

1.  Verify that the host address of IdM can be reached. By default, web access
    will show a Login Page.
2.  Acquire a valid username and password and access with those credentials. The
    resulting web page is the landing page of the IdM KeyRock Portal.
3.  Verify that you can view the list of applications, organizations, etc.

## Advanced Documentation

-   [How to run tests](https://fiware-idm.readthedocs.io/en/latest/installation_and_administration_guide/sanity_check/)
-   [User & Programmers Manual](https://fiware-idm.readthedocs.io/en/latest/user_and_programmers_guide/introduction/)
-   [Installation & Administration Guide](https://fiware-idm.readthedocs.io/en/latest/installation_and_administration_guide/introduction/)
-   [Connecting IdM to a eIDAS node](https://fiware-idm.readthedocs.io/en/latest/oauth/introduction)

## Changes Introduced in 7.x

They biggest change introduced in 7.x is that the identity manager no longer
depends on Openstack components Keystone and Horizon. Now is fully implemented
in Node JS. Another remarkable changes have been made:

1.  A driver has been implemented in order to make authentication against
    another database different from the default one.
2.  The appearance of the web portal can be easily modified though configurable
    themes.
3.  Now users don't need to switch session in order to create an application
    that will belong to an organization.
4.  Permissions of an application can be edited or deleted.
5.  IdM could play the role of gateway between services and eDIAS Node in order
    to allow users authentication with their national eID.
6.  OAuth Refresh Token Supported.
7.  Configurable OAuth token types (Permanent tokens and Json Web Tokens).
8.  OAuth Revoke Token endpoint enable.
9.  Internazionalization od UI (Spanish and English supported).
10. User Admin Panel.
11. Trusted application for OAuth token validation.
12. IdM could play the role as PDP for basic authorization.
13. Complete Sign out. Delete session in services as well as in Keyrock.

## Quality Assurance

This project is part of [FIWARE](https://www.fiware.org/) and has been rated as
follows:

-   **Version Tested:**
    ![](https://img.shields.io/badge/dynamic/json.svg?label=Version&url=https://fiware.github.io/catalogue/json/keyrock.json&query=$.version&colorB=blue)
-   **Documentation:**
    ![](https://img.shields.io/badge/dynamic/json.svg?label=Completeness&url=https://fiware.github.io/catalogue/json/keyrock.json&query=$.docCompleteness&colorB=blue)
    ![](https://img.shields.io/badge/dynamic/json.svg?label=Usability&url=https://fiware.github.io/catalogue/json/keyrock.json&query=$.docSoundness&colorB=blue)
-   **Responsiveness:**
    ![](https://img.shields.io/badge/dynamic/json.svg?label=Time%20to%20Respond&url=https://fiware.github.io/catalogue/json/keyrock.json&query=$.timeToCharge&colorB=blue)
    ![](https://img.shields.io/badge/dynamic/json.svg?label=Time%20to%20Fix&url=https://fiware.github.io/catalogue/json/keyrock.json&query=$.timeToFix&colorB=blue)
-   **FIWARE Testing:**
    ![](https://img.shields.io/badge/dynamic/json.svg?label=Tests%20Passed&url=https://fiware.github.io/catalogue/json/keyrock.json&query=$.failureRate&colorB=blue)
    ![](https://img.shields.io/badge/dynamic/json.svg?label=Scalability&url=https://fiware.github.io/catalogue/json/keyrock.json&query=$.scalability&colorB=blue)
    ![](https://img.shields.io/badge/dynamic/json.svg?label=Performance&url=https://fiware.github.io/catalogue/json/keyrock.json&query=$.performance&colorB=blue)
    ![](https://img.shields.io/badge/dynamic/json.svg?label=Stability&url=https://fiware.github.io/catalogue/json/keyrock.json&query=$.stability&colorB=blue)

---

## License

Keyrock is licensed under the [MIT](LICENSE) License.

© 2018 Universidad Politécnica de Madrid.


text:
<md-content gv-theme-element="portal.apisList">

 0"
            ng-repeat="view in apisCtrl.views track by view.id"
            ui-sref=".({ view: view.id })">
          {{view.name}}

          {{apisCtrl.view.description}}

        <md-content ng-show="!apisCtrl.hideApis"
                    layout="row" layout-align="start start"
                    layout-wrap
                    class="api-gallery">
          <input type="text" class="form-control apis-filter" placeholder="{{'apis.filter' | translate}}" ng-model="$ctrl.apiFilter" />
          <md-card class="api-box gravitee-card gravitee-api-card"
                   ng-repeat="api in apisCtrl.apis | filter:$ctrl.apiFilter track by api.id"
                   ng-click="apisCtrl.goToApi(api)"
                   layout-wrap>
            <md-card-title style="padding-top: 15px; padding-bottom: 0px;">
              <md-card-title-text>
                {{::api.name}}
                {{::api.version}}
              </md-card-title-text>
              <md-card-title-media>

              </md-card-title-media>
            </md-card-title>
            <md-card-content>

                {{::api.description}}

                {{view}}

            </md-card-content>
          </md-card>
        </md-content>

</md-content>

redpajama_set_name: RedPajamaGithub


text:
			Posted on

			by


text:
@interface CIAPITests : SenTestCase {
@private

}

@end


text:
package org.stropa.data;

import java.util.Map;

public interface DataTransformer {

    public Map<String, Object> transform(Map<String, Object> data);

}


text:
sudo apt-get update
sudo apt-get install -y build-essential checkinstall cmake git
echo 'Installing NodeJS build tools'
sudo apt-get remove gyp
curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
sudo apt-get install -y nodejs
su - vagrant -c 'bash /vagrant/bootstrap/config/testclient.sh'


text:
/* global SourceMetric, Document, Source, SourceMetricSource, Cleaner*/
"use strict";

const test = require('./../helper.js');
const should = require('should');
const _ = require('lodash');

describe('Documents clean sources', function () {
    before(test.cleanDb);

    const documentsData = test.getAllDocumentData();
    const sourcesData = test.getAllSourceData();
    const metricsData = test.getAllMetricData();

    it("should merge same sources", async function () {

        await Promise.all(sourcesData.map(s => Source.create(s)));

        await Cleaner.cleanSourceCopies();

        const cleanedSources = await Source.find();

        const test1Sources = cleanedSources.filter(s => s.title === 'Test1');
        const test2Sources = cleanedSources.filter(s => s.title === 'Test2');

        test1Sources.length.should.equal(2);
        test2Sources.length.should.equal(1);

        const conferenceSource = test1Sources.find(s => s.type === 'conference');
        const bookSource = test1Sources.find(s => s.type === 'book');

        conferenceSource.should.not.equal(undefined);
        conferenceSource.issn.should.equal('33331234');
        conferenceSource.acronym.should.equal('t1');

        bookSource.should.not.equal(undefined);
        bookSource.eissn.should.equal('11111234');

        test2Sources[0].acronym.should.equal('t2');
    });

    it("should update documents and metrics", async function () {
        await Source.destroy();

        const sData = sourcesData.slice(3, 8);
        await Promise.all(sData.map(s => Source.create(s)));
        const [
            sourceToMerge,
            sourceUnmodified1,
            sourceToMergeAndDelete,
            sourceUnmodified2,
            sourceUnmodified3
        ] = await Source.find();

        await Promise.all(metricsData.map(m => SourceMetric.create(m)));
        await SourceMetric.assignMetrics();

        const docsData = await test.fixDocumentsDocumenttype(documentsData.slice(0, 5));
        docsData[0].source = sourceToMerge;
        docsData[1].source = sourceUnmodified1;
        docsData[2].source = sourceToMergeAndDelete;
        docsData[3].source = sourceUnmodified2;
        docsData[4].source = sourceUnmodified3;
        const documents = await Promise.all(docsData.map(m => Document.create(m)));
        const sourceMetricsSources = await SourceMetricSource.find();

        await Cleaner.cleanSourceCopies();

        const cleanedSources = await Source.find();
        const cleanedDocments = await Document.find();
        const cleanedSourceMetricSources = await SourceMetricSource.find();

        cleanedDocments.length.should.equal(5);
        const mergedSourceDocuments = cleanedDocments.filter(d => d.source === sourceToMerge.id && [documents[0].id, documents[2].id].includes(d.id));
        mergedSourceDocuments.length.should.equal(2);

        const mergedAndDeletedSourceDocuments = cleanedDocments.filter(d => d.source === sourceToMergeAndDelete.id);
        mergedAndDeletedSourceDocuments.length.should.equal(0);

        should.exist(cleanedDocments.find(d => d.source === sourceUnmodified3.id));

        cleanedSources.length.should.equal(4);
        cleanedSources.filter(s => s.id !== sourceToMergeAndDelete.id).length.should.equal(4);

        const sourceToMergeMetrics = sourceMetricsSources.filter(sms => sms.source === sourceToMerge.id);
        const sourceUnmodified1Metrics = sourceMetricsSources.filter(sms => sms.source === sourceUnmodified1.id);
        const sourceToMergeAndDeleteMetrics = sourceMetricsSources.filter(sms => sms.source === sourceToMergeAndDelete.id);

        const shouldSourceToMergeMetrics = _.uniqWith(sourceToMergeMetrics.concat(sourceToMergeAndDeleteMetrics),
            (sms, newSms) => sms.source === newSms.source && sms.sourceMetric === newSms.sourceMetric);

        const cleanedSourceToMergeMetrics = cleanedSourceMetricSources.filter(sms => sms.source === sourceToMerge.id);
        const cleanedSourceUnmodified1Metrics = cleanedSourceMetricSources.filter(sms => sms.source === sourceUnmodified1.id);
        const cleanedSourceToMergeAndDeleteMetrics = cleanedSourceMetricSources.filter(sms => sms.source === sourceToMergeAndDelete.id);

        cleanedSourceToMergeMetrics.length.should.equal(shouldSourceToMergeMetrics.length);
        cleanedSourceUnmodified1Metrics.length.should.equal(sourceUnmodified1Metrics.length);
        cleanedSourceToMergeAndDeleteMetrics.length.should.equal(0);
    });

});


text:
# gradle-android-utils [![Build Status](https://secure.travis-ci.org/gfx/gradle-android-utils.png)](http://travis-ci.org/gfx/gradle-android-utils)

This is a set of utilities for Android build system.

NOTE: **This project is still alpha-qality; API will be change without notice**

# METHODS

### `void iconToGrayScale(File inputFile, File outputFile)`

Converts the input icon file into grayscaled one.

### `void copyFile(File inputFile, File outputFile, boolean toOverwrite = false)`

Create `outputFile` from `inputFile` if it does not exist.

You can force overwrite with specifies the `true` to the 3rd argument.

### `void initSdkDir(Map<String, String> extra = null)`

Creates `local.properties` if it does not exist, which includes
`sdk.dir`, `ndk.dir` and `extra` properties.

### `void writeResources(File file, Map<String, String> dict)`

Creates a resource XML file, which contains `dict`.

### `Version parseVersion(String versionName)`, `Version readVersion(File versionFile)`

Prases or reads a version object, which has `toVersionCode()` and `toVersionName()` methods.

## `void setBuildConfigField(buildType, Map<String, Object> buildConfigMap)`

Set `buildConfigField` from `Map`. Requirements to 'com.android.tools.build:gradle:0.8.0' or later.

``` groovy
// For example

android.variantFilter{ variant ->
    def buildConfigMap = [
        'APP_NAME': 'MyApp' + variant.buildType.name.capitalize(),
        'EXTENSION_MIN_SDK_INT': 14,
        'API_SERVER_PRODUCTION': false,
    ]

    setBuildConfigField(variant.buildType, buildConfigMap)
    // or
    //setBuildConfigField(variant.flavors.get(0), buildConfigMap)
}

/**
 * //Build result
 *
 * public final class BuildConfig {
 *   ...
 *   // Fields from build type: debug
 *   public static final String APP_NAME = "MyAppDebug";
 *   public static final Integer EXTENSION_MIN_SDK_INT = 14;
 *   public static final Boolean API_SERVER_PRODUCTION = false;
 * }
 */
```

# SEE ALSO

* https://github.com/gfx/Android-HankeiN which uses this project

# LICENSE

This program is free software; you can redistribute it and/or modify it under the same terms of the MIT license.


text:
package brooklyn.entity.rebind;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import brooklyn.entity.Application;
import brooklyn.mementos.BrooklynMementoPersister;
import brooklyn.util.time.Duration;

import com.google.common.annotations.VisibleForTesting;

/**
 * Manages the persisting of brooklyn's state, and recreating that state, e.g. on
 * brooklyn restart.
 *
 * Users are not expected to implement this class, or to call methods on it directly.
 */
public interface RebindManager {

    // FIXME Should we be calling managementContext.getRebindManager().rebind, using a
    // new empty instance of managementContext?
    //
    // Or is that a risky API because you could call it on a non-empty managementContext?

    public enum RebindFailureMode {
        FAIL_FAST,
        FAIL_AT_END,
        CONTINUE;
    }

    public void setPersister(BrooklynMementoPersister persister);

    @VisibleForTesting
    public BrooklynMementoPersister getPersister();

    /**
     * @deprecated since 0.7; use {@link #rebind(ClassLoader)}
     */
    @Deprecated
    public List<Application> rebind() throws IOException;

    public List<Application> rebind(ClassLoader classLoader) throws IOException;

    public List<Application> rebind(ClassLoader classLoader, RebindExceptionHandler exceptionHandler) throws IOException;

    public ChangeListener getChangeListener();

    /**
     * Starts the persisting of state (if persister is set; otherwise will start persisting as soon as
     * persister is set). Until {@link #start()} is called, no data will be persisted but entities can
     * rebind.
     */
    public void start();

    public void stop();

    /** @deprecated since 0.7.0; use {@link #waitForPendingComplete(Duration)} */
    @VisibleForTesting
    @Deprecated
    public void waitForPendingComplete(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException;
    /** waits for any needed or pending writes to complete */
    @VisibleForTesting
    public void waitForPendingComplete(Duration duration) throws InterruptedException, TimeoutException;
    /** forcibly performs persistence, in the foreground */
    @VisibleForTesting
    public void forcePersistNow();

}


text:
package griffon.plugins.domain.methods;

import griffon.plugins.domain.GriffonDomain;

import java.util.Map;

/**
 * @author Andres Almiray
 */
public interface DeleteMethod extends InstanceMethodInvocation {
    String METHOD_NAME = "delete";

    MethodSignature[] METHOD_SIGNATURES = new MethodSignature[]{
        new MethodSignature(GriffonDomain.class, METHOD_NAME),
        new MethodSignature(GriffonDomain.class, METHOD_NAME, Map.class)
    };
}


text:
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define */

define(function (require, exports, module) {
    "use strict";

    var FileSystemError = require("filesystem/FileSystemError"),
        FileSystemStats = require("filesystem/FileSystemStats"),
        Filer           = require("filesystem/impls/filer/BracketsFiler"),
        BlobUtils       = require("filesystem/impls/filer/BlobUtils"),
        Handlers        = require("filesystem/impls/filer/lib/handlers");

    var fs              = Filer.fs(),
        Path            = Filer.Path,
        watchers        = {};

    var _changeCallback;            // Callback to notify FileSystem of watcher changes

    function showOpenDialog(allowMultipleSelection, chooseDirectories, title, initialPath, fileTypes, callback) {
        throw new Error("Filer dialogs not supported. See: https://github.com/humphd/brackets/pull/309");
    }

    function showSaveDialog(title, initialPath, defaultName, callback) {
        throw new Error("Filer dialogs not supported. See: https://github.com/humphd/brackets/pull/309");
    }

    /**
     * Convert Filer error codes to FileSystemError values.
     *
     * @param {?Object} err A Filer error code or Brackets error string
     * @return {?string} A FileSystemError string, or null if there was no error code.
     * @private
     **/
    function _mapError(err) {
        if (!err) {
            return null;
        }

        // If we get a raw Brackets error string passed through,
        // we don't need to map anything, and can just use it directly.
        if (typeof err === "string") {
            return err;
        }

        // Otherwise it's a Filer error, try and use err.code
        switch (err.code) {
        case 'EINVAL':
            return FileSystemError.INVALID_PARAMS;
        case 'ENOENT':
            return FileSystemError.NOT_FOUND;
        case 'EROFS':
            return FileSystemError.NOT_WRITABLE;
        case 'ENOSPC':
            return FileSystemError.OUT_OF_SPACE;
        case 'ENOTEMPTY':
            // There's no good case for this in Brackets (trying to rmdir non-empty dir)
            return "Directory Not Empty";
        case 'EEXIST':
            return FileSystemError.ALREADY_EXISTS;
        case 'ENOTDIR':
            return FileSystemError.INVALID_PARAMS;
        case 'EBADF':
            return FileSystemError.NOT_READABLE;
        }

        // We don't know what this is, log it. We likely need a new case above.
        console.log('[Brackets Filesystem] Unknown I/O error', err);
        return FileSystemError.UNKNOWN;
    }

    /**
     * Convert a callback to one that transforms its first parameter from a
     * Filer error code to a FileSystemError string.
     *
     * @param {function(?number)} cb A callback that expects an Filer error code
     * @return {function(?string)} A callback that expects a FileSystemError string
     * @private
     **/
    function _wrap(cb) {
        return function (err) {
            var args = Array.prototype.slice.call(arguments);
            args[0] = _mapError(args[0]);
            cb.apply(null, args);
        };
    }

    function stat(path, callback) {
        fs.stat(path, function(err, stats) {
            if (err){
                callback(_mapError(err));
                return;
            }

            var mtime = new Date(stats.mtime);

            var options = {
                isFile: stats.isFile(),
                mtime: mtime,
                size: stats.size,
                // TODO: figure out how to deal with realPath
                realPath: path,
                hash: mtime.getTime()
            };

            var fsStats = new FileSystemStats(options);

            callback(null, fsStats);
        });
    }

    function exists(path, callback) {
        fs.exists(path, function(exists) {
            callback(null, exists);
        });
    }

    function readdir(path, callback) {
        path = Path.normalize(path);

        fs.readdir(path, function (err, contents) {
            if (err) {
                callback(_mapError(err));
                return;
            }

            var count = contents.length;
            if (!count) {
                callback(null, [], []);
                return;
            }

            var stats = [];
            contents.forEach(function (val, idx) {
                stat(Path.join(path, val), function (err, stat) {
                    stats[idx] = err || stat;
                    count--;
                    if (count <= 0) {
                        callback(null, contents, stats);
                    }
                });
            });
        });
    }

    function mkdir(path, mode, callback) {
        if(typeof mode === 'function') {
            callback = mode;
        }

        fs.mkdir(path, mode, function (err) {
            if (err) {
                callback(_mapError(err));
                return;
            }
            stat(path, callback);
        });
    }

    function rename(oldPath, newPath, callback) {
        function updateBlobURL(err) {
            if(err) {
                return callback(_mapError(err));
            }

            // If this was a rename on a file path, update the Blob cache too
            stat(newPath, function(err, stat) {
                if(err) {
                    return callback(_mapError(err));
                }

                if(stat.isFile) {
                    BlobUtils.rename(oldPath, newPath);
                }

                callback();
            });
        }

        fs.rename(oldPath, newPath, _wrap(updateBlobURL));
    }

    function readFile(path, options, callback) {
        if(typeof options === 'function') {
            callback = options;
        }
        options = options || {};

        var encoding = options.encoding || "utf8";

        // Execute the read and stat calls in parallel. Callback early if the
        // read call completes first with an error; otherwise wait for both
        // to finish.
        var done = false, data, stat, err;

        if (options.stat) {
            done = true;
            stat = options.stat;
        } else {
            exports.stat(path, function (_err, _stat) {
                if (done) {
                    callback(_err, _err ? null : data, _stat);
                } else {
                    done = true;
                    stat = _stat;
                    err = _err;
                }
            });
        }

        fs.readFile(path, encoding, function (_err, _data) {
            if (_err) {
                callback(_mapError(_err));
                return;
            }

            if (done) {
                callback(err, err ? null : _data, stat);
            } else {
                done = true;
                data = _data;
            }
        });
    }

    function writeFile(path, data, options, callback) {
        if(typeof options === 'function') {
            callback = options;
        }
        options = options || {};

        var encoding = options.encoding || "utf8";

        function _finishWrite(created) {
            fs.writeFile(path, data, encoding, function (err) {
                if (err) {
                    callback(_mapError(err));
                    return;
                }

                // Cache a Blob URL for the file
                Handlers.handleFile(path, data);

                stat(path, function (err, stat) {
                    callback(_mapError(err), stat, created);
                });
            });
        }

        stat(path, function (err, stats) {
            if (err) {
                switch (err) {
                case FileSystemError.NOT_FOUND:
                    _finishWrite(true);
                    break;
                default:
                    callback(err);
                }
                return;
            }

            if (options.hasOwnProperty("expectedHash") && options.expectedHash !== stats._hash) {
                console.error("Blind write attempted: ", path, stats._hash, options.expectedHash);

                if (options.hasOwnProperty("expectedContents")) {
                    fs.readFile(path, encoding, function (_err, _data) {
                        if (_err || _data !== options.expectedContents) {
                            callback(FileSystemError.CONTENTS_MODIFIED);
                            return;
                        }

                        _finishWrite(false);
                    });
                    return;
                } else {
                    callback(FileSystemError.CONTENTS_MODIFIED);
                    return;
                }
            }

            _finishWrite(false);
        });
    }

    function unlink(path, callback) {
        fs.stat(path, function(err, stats) {
            if (err) {
                callback(_mapError(err));
                return;
            }

            // Deal with dir vs. file
            var fnName = stats.isDirectory() ? 'rmdir' : 'unlink';
            fs[fnName](path, function(err) {
                // TODO: deal with the symlink case (i.e., only remove cache
                // item if file is really going away).
                BlobUtils.remove(path);
                callback(_mapError(err));
            });
        });
    }

    function moveToTrash(path, callback) {
        // TODO: do we want to support a .trash/ dir or the like?
        unlink(path, callback);
    }

    function initWatchers(changeCallback, offlineCallback) {
        _changeCallback = changeCallback;
    }

    function watchPath(path, callback) {
        path = Path.normalize(path);

        if(watchers[path]) {
            return;
        }
        watchers[path] = fs.watch(path, {recursive: true}, function(event, filename) {
            stat(filename, function(err, stats) {
                if(err) {
                    return;
                }
                _changeCallback(filename, stats);
            });
        });
        callback();
    }

    function unwatchPath(path, callback) {
        path = Path.normalize(path);

        if(watchers[path]) {
            watchers[path].close();
            delete watchers[path];
        }
        callback();
    }

    function unwatchAll(callback) {
        Object.keys(watchers).forEach(function(path) {
            unwatchPath(path, function(){});
        });
        callback();
    }

    // Export public API
    exports.showOpenDialog  = showOpenDialog;
    exports.showSaveDialog  = showSaveDialog;
    exports.exists          = exists;
    exports.readdir         = readdir;
    exports.mkdir           = mkdir;
    exports.rename          = rename;
    exports.stat            = stat;
    exports.readFile        = readFile;
    exports.writeFile       = writeFile;
    exports.unlink          = unlink;
    exports.moveToTrash     = moveToTrash;
    exports.initWatchers    = initWatchers;
    exports.watchPath       = watchPath;
    exports.unwatchPath     = unwatchPath;
    exports.unwatchAll      = unwatchAll;

    exports.recursiveWatch    = true;
    exports.normalizeUNCPaths = false;
});


text:
package com.liubo.calculate;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @EnableDiscoveryClient注解,该注解能激活Eureka中的DiscoveryClient实现, 才能实现Controller中对服务信息的输出
 */
@EnableDiscoveryClient
@SpringBootApplication
public class LiuboCalculateApplication {
    public static void main(String[] args) {
        SpringApplication.run(LiuboCalculateApplication.class, args);
    }
}


text:
<?php

namespace PandawanTechnology\Neo4jBundle\Form\ChoiceList;

use GraphAware\Neo4j\Client\Client as Neo4jClient;
use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;

class Neo4jChoiceLoader implements ChoiceLoaderInterface
{
    /**
     * @var Neo4jClient
     */
    private $neo4jClient;

    /**
     * @var ChoiceListFactoryInterface
     */
    private $choiceListFactory;

    /**
     * @var string
     */
    private $queryStatement;

    /**
     * @var ChoiceListInterface
     */
    private $choiceList;

    /**
     * @var string
     */
    private $recordAlias;

    /**
     * @var IdReader
     */
    private $idReader;

    /**
     * @param Neo4jClient                $neo4jClient
     * @param ChoiceListFactoryInterface $choiceListFactory
     * @param string                     $queryStatement
     * @param string                     $recordAlias
     * @param IdReader                   $idReader
     */
    public function __construct(
        Neo4jClient $neo4jClient,
        ChoiceListFactoryInterface $choiceListFactory,
        $queryStatement,
        $recordAlias,
        IdReader $idReader
    ) {
        $this->neo4jClient = $neo4jClient;
        $this->choiceListFactory = $choiceListFactory;
        $this->queryStatement = $queryStatement;
        $this->recordAlias = $recordAlias;
        $this->idReader = $idReader;
    }

    /**
     * {@inheritdoc}
     */
    public function loadChoiceList($value = null)
    {
        if ($this->choiceList) {
            return $this->choiceList;
        }

        $recordsResult = [];
        $records = $this->neo4jClient->run($this->queryStatement)->records();

        foreach ($records as $record) {
            $recordsResult[] = $record->get($this->recordAlias);
        }

        $this->choiceList = $this->choiceListFactory->createListFromChoices(
            $recordsResult,
            $value
        );

        return $this->choiceList;
    }

    /**
     * {@inheritdoc}
     */
    public function loadChoicesForValues(array $values, $value = null)
    {
        if (empty($values)) {
            return [];
        }

        // Optimize performance in case we have an object loader and
        // a single-field identifier
        $optimize = null === $value || is_array($value) && $value[0] === $this->idReader;

        if ($optimize && !$this->choiceList) {
            $unorderedObjects = $this->getItemById($values);
            $objectsById = $objects = [];

            // Maintain order and indices from the given $values
            // An alternative approach to the following loop is to add the
            // "INDEX BY" clause to the Doctrine query in the loader,
            // but I'm not sure whether that's doable in a generic fashion.
            foreach ($unorderedObjects as $object) {
                $objectsById[(string) $this->idReader->getIdValue($object)] = $object;
            }

            foreach ($values as $i => $id) {
                if (isset($objectsById[$id])) {
                    $objects[$i] = $objectsById[$id];
                }
            }

            return $objects;
        }

        return $this->loadChoiceList($value)->getChoicesForValues($values);
    }

    /**
     * {@inheritdoc}
     */
    public function loadValuesForChoices(array $choices, $value = null)
    {
        // Performance optimization
        if (empty($choices)) {
            return [];
        }

        // Optimize performance for single-field identifiers. We already
        // know that the IDs are used as values

        // Attention: This optimization does not check choices for existence
        if (!$this->choiceList) {
            $values = [];

            // Maintain order and indices of the given objects
            foreach ($choices as $i => $object) {
                $values[$i] = (string) $this->idReader->getIdValue($object);
            }

            return $values;
        }

        return $this->loadChoiceList($value)->getValuesForChoices($choices);
    }

    /**
     * @param array $ids
     *
     * @return array
     */
    private function getItemById(array $ids)
    {
        $ids = array_map('intval', $ids);

        try {
            $stmtResult = $this->neo4jClient->run('MATCH (n) WHERE ID(n) IN {ids} RETURN n', ['ids' => $ids]);
        } catch (\Exception $e) {
            return [];
        }

        $result = [];

        if (!$stmtResult->size()) {
            return $result;
        }

        foreach ($stmtResult->records() as $record) {
            $result[] = $record->get('n');
        }

        return $result;
    }
}


text:
/**
 * menu module for snake game
 * @author - Andrii Priadko
 */

(function() {
  define("modules/objects/menu", [], function() {

    return {
      ctx: null, //canvas 2d context
      cols: 0, //number of cols in game field
      rows: 0, //number of rows in game field
      tileSize: 0, //size of tile in the game field
      width: 0, //game field width
      height: 0, //game field height

      /**
       * Initialize a begining state
       */
      init: function(cols, rows, tileSize) {
        this.cols = cols;
        this.rows = rows;
        this.tileSize = tileSize;
        this.width = this.cols * this.tileSize;
        this.height = this.rows * this.tileSize;
      },

      /**
       * That function renders a gameover screen
       *
       */
      gameOver: function(ctx, pts) {
        var best = this.getBestScore() > pts ? this.getBestScore() : pts;

        ctx.clearRect(0, 0, this.cols*this.tileSize, this.rows*this.tileSize);
        ctx.font = "bold 20px serif";
        ctx.textAlign = "center";
        ctx.fillText("Game Over", this.width/2, this.height/2-40);

        ctx.font = "16px serif";
        ctx.textAlign = "center";
        ctx.fillText("press <Enter> to start a new game", this.width/2, this.height/2-20);

        ctx.font = "16px serif";
        ctx.textAlign = "center";
        ctx.fillText("your score is: "+(pts || 0), this.width/2, this.height - 100);

        ctx.font = "16px serif";
        ctx.textAlign = "center";
        ctx.fillText("the best score is: " + best, this.width/2, this.height - 80);

        this.setBestScore(best);
      },

      /**
       * Gets a bestScore value from the localStorage
       * @return {Number} - best score
       */
      getBestScore: function() {
        return localStorage.getItem("bestScore") || 0;
      },

      /**
       * Store best score value to the localStorage
       * @return {Boolean} - best score save result
       */
      setBestScore: function(pts) {
        return localStorage.setItem("bestScore", (pts || 0));
      }
    }
  });
})();


text:
namespace eja
{
	class entity;

	make_thread_safe_component(upload_index_map_component, std::multimap<std::shared_ptr<entity>, u32>);
	make_thread_safe_component(upload_index_set_component, std::set<u32>);
	make_thread_safe_component(upload_list_component, std::vector<std::shared_ptr<entity>>);
	make_thread_safe_component(upload_map_component, std::map<std::string, std::shared_ptr<entity>>);
	make_thread_safe_component(upload_multimap_component, std::multimap<std::string, std::shared_ptr<entity>>);

	struct upload_data
	{
		u32 index;
		std::string data;
		using ptr = std::shared_ptr<upload_data>;

		// Static
		static ptr create() { return ptr(new upload_data()); }
	};

	class upload_data_list_component : public thread_safe_ex<component, std::deque<std::shared_ptr<upload_data>>>
	{
		make_factory(upload_data_list_component);

	private:
		boost::atomic<size_t> m_buffer;

	public:
		upload_data_list_component() : m_buffer(0) { }
		upload_data_list_component(const upload_data_list_component& comp) : thread_safe_ex(comp) { m_buffer.store(comp.m_buffer); }

		// Operator
		upload_data_list_component& operator=(const upload_data_list_component& comp);

		// Utility
		virtual bool valid() const override { return !empty(); }

		void add_buffer(const size_t buffer) { m_buffer += buffer; }
		void sub_buffer(const size_t buffer) { m_buffer = std::max(static_cast<int>(m_buffer - buffer), 0); }

		// Has
		bool has_buffer() const { return m_buffer > 0; }

		// Set
		void set_buffer(const size_t buffer) { m_buffer = buffer; }

		// Get
		size_t get_buffer() const { return m_buffer; }
	};
}

#endif