text:
var generate = require("../lib");
var assert   = require("assert");
var parse    = require("babylon").parse;
var chai     = require("chai");
var t        = require("babel-types");
var _        = require("lodash");

suite("generation", function () {
  test("completeness", function () {
    _.each(t.VISITOR_KEYS, function (keys, type) {
      assert.ok(!!generate.CodeGenerator.prototype[type], type + " should exist");
    });

    _.each(generate.CodeGenerator.prototype, function (fn, type) {
      if (!/[A-Z]/.test(type[0])) return;
      assert.ok(t.VISITOR_KEYS[type], type + " should not exist");
    });
  });
});

var suites = require("babel-helper-fixtures").default(__dirname + "/fixtures");

suites.forEach(function (testSuite) {
  suite("generation/" + testSuite.title, function () {
    _.each(testSuite.tests, function (task) {
      test(task.title, !task.disabled && function () {
        var expect = task.expect;
        var actual = task.actual;

        var actualAst = parse(actual.code, {
          filename: actual.loc,
          plugins: [
            "jsx",
            "flow",
            "decorators",
            "asyncFunctions",
            "exportExtensions",
            "functionBind",
            "classConstructorCall",
          ],
          strictMode: false,
          sourceType: "module",
        });

        var actualCode = generate.default(actualAst, task.options, actual.code).code;
        chai.expect(actualCode).to.equal(expect.code, actual.loc + " !== " + expect.loc);
      });
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
using IdentityServer4.Models;
using IdentityServer4.Services;
using System.Threading.Tasks;

namespace IdentityServer.UnitTests.Common
{
    class MockTokenCreationService : ITokenCreationService
    {
        public string Token { get; set; }

        public Task<string> CreateTokenAsync(Token token)
        {
            return Task.FromResult(Token);
        }
    }
}


text:
var expect = require('expect.js'),
    Asset = require('../lib/asset');

describe('asset.initialize()', function() {
  beforeEach(function() {
    this.asset_1 = new Asset({
      label: 'That Movie',
      original_name: 'movie1.mov',
      size: 1024
    });

    this.asset_2 = new Asset({
      label: 'That Other Movie',
      original_name: 'movie2.mov',
      size: 512
    });
  });

  it('should have a unique tag array', function() {
    this.asset_1.tags.push('blah');

    expect(this.asset_2.tags).to.not.eql(['blah']);
    expect(this.asset_1.tags).not.to.be(this.asset_2.tags);
  });

  it('should have a unique uri object', function() {
    this.asset_1.uri.location = 'http://www.google.com';

    expect(this.asset_2.uri.location).not.to.be('http://www.google.com');
    expect(this.asset_1.uri).not.to.be(this.asset_2.uri);
  });
});


text:
from wtforms import TextField, SelectField
from wtforms.validators import DataRequired, Email, IPAddress, NumberRange

from ..base import BaseReactForm

class ReactForm(BaseReactForm):

    ''' Class that creates a CloudFlare Reaction form for the dashboard '''
    title = "CloudFlare: Change Security Level"
    description = """

      This reaction is designed to modify the security level of a CloudFlare protected domain. When called, this reaction will interface with CloudFlare's API changing the domain's security level to the specified level.

      The ability to increase the security level can be extremely useful when combined with logging service monitors that can be used to detect potential attacks.

    """
    placeholders = BaseReactForm.placeholders
    placeholders.update({
        'rec_name' : "www",
        'content' : '10.0.0.1'
   })

    actions = [
        ('essentially_off', 'Essentially Off'),
        ('low', 'Low'),
        ('medium', 'Medium'),
        ('high', 'High'),
        ('under_attack', 'Help I am under attack!')
    ]

    email = TextField(
        "Email",
        description=BaseReactForm.descriptions['cloudflare']['email'],
        validators=[Email(message='Email address invalid')])
    domain = TextField(
        "Domain",
        description=BaseReactForm.descriptions['cloudflare']['domain'],
        validators=[DataRequired(message='Domain is a required field')])
    apikey = TextField(
        "API Key",
        description=BaseReactForm.descriptions['apikey'],
        validators=[DataRequired(message='API Key is a required field')])
    action = SelectField(
        "Level",
        description="""
          Specify the desired security level for the CloudFlare protected domain
        """,
        choices=actions,
        validators=[DataRequired(message='Security Level is a required field')])
    call_on = SelectField(
        "Call On",
        description=BaseReactForm.descriptions['callon'],
        choices=[('false', 'False Monitors'), ('true', 'True Monitors')],
        validators=[DataRequired(message='Call On is a required field')])

if __name__ == '__main__':
    pass


text:
package com.ppmessage.ppcomlib.services;

import android.content.Context;
import android.content.SharedPreferences;

import com.ppmessage.ppcomlib.PPComSDK;
import com.ppmessage.ppcomlib.PPComSDKConfiguration;
import com.ppmessage.ppcomlib.PPComSDKException;
import com.ppmessage.sdk.core.L;
import com.ppmessage.sdk.core.PPMessageException;
import com.ppmessage.sdk.core.PPMessageSDK;
import com.ppmessage.sdk.core.PPMessageSDKConfiguration;
import com.ppmessage.sdk.core.api.OnAPIRequestCompleted;
import com.ppmessage.sdk.core.bean.common.User;
import com.ppmessage.sdk.core.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 1. get anonymous / email user
 * 2. update user info // We don't care the update result
 * 3. create and update device // We also don't care the result
 *

 * Example:
 *

 *

 *
 *     1. -Async get ppcom user
 *     PPComSDK sdk = PPComSDK.getInstance();
 *     PPComUser ppcomUser = new PPComUser(sdk);
 *
 *     ppcomUser.getPPComUser(new OnGetPPComUserEvent() {
 *
 *         void onCompleted(User user) {
 *             // success: user != null
 *             // error: user == null
 *         }
 *     } );
 *
 *     2. -get ppcom cached user
 *     User user = ppcomUser.getUser();
 *

 *

 * Created by ppmessage on 5/13/16.
 */
public final class PPComUser {

    private static final String SHARED_PREF_NAME = "user_pref";
    private static final String SHARED_PREF_TRACE_ID_KEY = "anonymous_user_trace_id";

    private static final String DEVICE_OS_TYPE = "AND";

    private static final String LOG_UPDATE_USER_INFO_ERROR = "[PPComUser] update user info failed";
    private static final String LOG_GET_DEVICE_UUID_ERROR = "[PPComUser] get device_uuid failed";
    private static final String LOG_UPDATE_DEVICE_INFO_ERROR = "[PPComUser] update device info failed";
    private static final String LOG_CREATE_USER_INFO_ERROR = "[PPComUser] create user info failed";

    public interface OnGetPPComUserEvent {
        void onCompleted(User user);
    }

    private PPMessageSDK messageSDK;
    private PPComSDK sdk;
    private Context context;
    private PPComSDKConfiguration configuration;

    private User user; // cached user

    public PPComUser(PPComSDK sdk) {
        this.sdk = sdk;
        this.configuration = sdk.getConfiguration();
        this.context = this.configuration.getContext();
        this.messageSDK = sdk.getPPMessageSDK();
    }

    public User getUser() {
        return user;
    }

    public void getUser(OnGetPPComUserEvent event) {
        if (user != null) {
            if (event != null) event.onCompleted(user);
            return;
        }
        createUser(event);
    }

    private void createUser(final OnGetPPComUserEvent event) {
        if (isAnonymousUser()) {
            createAnonymousUser(getAnonymousUserTraceUUID(), event);
        } else if (isEntUser()) {
            createEntUser(event);
        } else {
            L.w(LOG_CREATE_USER_INFO_ERROR);
        }
    }

    // 1. create anonymous user
    private void createAnonymousUser(String ppcomTraceUUID, final OnGetPPComUserEvent event) {
        String traceUUID = ppcomTraceUUID;
        String appUUID = sdk.getConfiguration().getAppUuid();

        JSONObject params = new JSONObject();
        try {
            params.put("app_uuid", appUUID);
            params.put("ppcom_trace_uuid", traceUUID);
            params.put("is_app_user", true);
            params.put("is_browser_user", false);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        L.d("CREATE_ANONYMOUS_USER");

        // Create anonymous user
        messageSDK.getAPI().createAnonymousUser(params, new OnAPIRequestCompleted() {
            @Override
            public void onResponse(JSONObject jsonResponse) {
                User user = User.parse(jsonResponse);
                PPComUser.this.user = user; // Cache It
                updateDevice(user, event);
            }

            @Override
            public void onCancelled() {
                if (event != null) event.onCompleted(PPComUser.this.user);
            }

            @Override
            public void onError(int errorCode) {
                if (event != null) event.onCompleted(PPComUser.this.user);
            }
        });
    }

    private void createEntUser(final OnGetPPComUserEvent event) {
        final JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("app_uuid", sdk.getConfiguration().getAppUuid());
            jsonObject.put("ent_user_icon", sdk.getConfiguration().getEntUserIcon());
            jsonObject.put("ent_user_name", sdk.getConfiguration().getEntUserName());
            jsonObject.put("ent_user_id", sdk.getConfiguration().getEntUserId());
            jsonObject.put("ent_user_create_time", sdk.getConfiguration().getEntUserCreateTime());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        messageSDK.getAPI().getUserUUID(jsonObject, new OnAPIRequestCompleted() {
            @Override
            public void onResponse(JSONObject jsonResponse) {
                try {
                    if (jsonObject.getInt("error_code") == 0) {
                        User user = User.parse(jsonResponse);
                        PPComUser.this.user = user;
                        updateDevice(user, event);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onCancelled() {
                if (event != null) event.onCompleted(PPComUser.this.user);
            }

            @Override
            public void onError(int errorCode) {
                if (event != null) event.onCompleted(PPComUser.this.user);
            }
        });
    }

    private void updateDevice(final User user, final OnGetPPComUserEvent event) {
        String deviceUUID = Utils.getDeviceUUID(context);

        final JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("app_uuid", sdk.getConfiguration().getAppUuid());
            jsonObject.put("user_uuid", user.getUuid());
            jsonObject.put("device_ostype", DEVICE_OS_TYPE);
            jsonObject.put("is_browser_device", false);
            jsonObject.put("device_android_jpushtoken", sdk.getConfiguration().getJpushRegistrationId());
            jsonObject.put("device_android_gcmtoken", sdk.getConfiguration().getGcmPushRegistrationId());
            jsonObject.put("ppcom_trace_uuid", getAnonymousUserTraceUUID());
            jsonObject.put("device_id", deviceUUID);
        } catch (JSONException e) {
            L.e(e);
        }

        messageSDK.getAPI().createPPComDevice(jsonObject, new OnAPIRequestCompleted() {
            @Override
            public void onResponse(JSONObject jsonResponse) {
                try {
                    String deviceUUID = jsonResponse.getString("uuid");
                    user.setDeviceUUID(deviceUUID);
                } catch (JSONException e) {
                    L.e(e);
                }
                if (event != null) {
                    event.onCompleted(user);
                }

                createDefaultConversation(user, event);
            }

            @Override
            public void onCancelled() {
                L.w(LOG_GET_DEVICE_UUID_ERROR);
            }

            @Override
            public void onError(int errorCode) {
                L.w(LOG_GET_DEVICE_UUID_ERROR);
            }
        });
    }

    private void createDefaultConversation(final User user, final OnGetPPComUserEvent event) {

        final JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("app_uuid", sdk.getConfiguration().getAppUuid());
            jsonObject.put("user_uuid", user.getUuid());
            jsonObject.put("device_uuid", user.getDeviceUUID());
            jsonObject.put("is_app_user", true);
        } catch (JSONException e) {
            L.e(e);
        }

        messageSDK.getAPI().createPPComDefaultConversation(jsonObject, new OnAPIRequestCompleted() {
            @Override
            public void onResponse(JSONObject jsonResponse) {
            }

            @Override
            public void onCancelled() {
            }

            @Override
            public void onError(int errorCode) {
            }
        });
    }

    private boolean isAnonymousUser() {
        return (sdk.getConfiguration().getEntUserId() == null);
    }

    private boolean isEntUser() {
        return (sdk.getConfiguration().getEntUserId() != null);
    }

    public String getAnonymousUserTraceUUID() {
        SharedPreferences sp = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        if (sp.getString(SHARED_PREF_TRACE_ID_KEY, null) == null) {
            sp.edit().putString(SHARED_PREF_TRACE_ID_KEY, Utils.randomUUID()).commit();
        }
        return sp.getString(SHARED_PREF_TRACE_ID_KEY, null);
    }

}


text:
package gobblin.broker;

import gobblin.broker.iface.SharedResourceFactoryResponse;
import java.io.Closeable;
import java.io.IOException;
import java.util.Random;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;

import gobblin.broker.gobblin_scopes.GobblinScopeTypes;
import gobblin.broker.iface.ConfigView;
import gobblin.broker.iface.ScopeType;
import gobblin.broker.iface.ScopedConfigView;
import gobblin.broker.iface.SharedResourceFactory;
import gobblin.broker.iface.SharedResourcesBroker;

import lombok.Data;

public class TestFactory<S extends ScopeType<S>> implements SharedResourceFactory<TestFactory.SharedResource, TestResourceKey, S> {

  private static final Joiner JOINER = Joiner.on(".");
  private static final String AUTOSCOPE_AT = "autoscope.at";

  public static final String NAME = TestFactory.class.getSimpleName();

  public static Config setAutoScopeLevel(Config config, GobblinScopeTypes level) {
    return ConfigFactory.parseMap(ImmutableMap.of(
        JOINER.join(BrokerConstants.GOBBLIN_BROKER_CONFIG_PREFIX, NAME, AUTOSCOPE_AT), level.name()))
        .withFallback(config);
  }

  @Override
  public String getName() {
    return NAME;
  }

  @Override
  public SharedResourceFactoryResponse<SharedResource>
      createResource(SharedResourcesBroker<S> broker, ScopedConfigView<S, TestResourceKey> config) {
    return new ResourceInstance<>(new SharedResource(config.getKey().getKey(), config.getConfig()));
  }

  @Override
  public S getAutoScope(SharedResourcesBroker<S> broker, ConfigView<S, TestResourceKey> config) {
    if (config.getConfig().hasPath(AUTOSCOPE_AT)) {
      return (S) GobblinScopeTypes.valueOf(config.getConfig().getString(AUTOSCOPE_AT));
    } else {
      return broker.selfScope().getType();
    }
  }

  @Data
  public static class SharedResource implements Closeable {
    private final String key;
    private final Config config;
    private final long id = new Random().nextLong();
    private boolean closed = false;

    @Override
    public void close()
        throws IOException {
      if (this.closed) {
        throw new RuntimeException("Already closed.");
      }
      this.closed = true;
    }
  }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<title>OpenCV: cv::stereo::MVKernel< num_images > Struct Template Reference</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>

<link href="../../search/search.css" rel="stylesheet" type="text/css"/>

<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
<link href="../../stylesheet.css" rel="stylesheet" type="text/css"/>

OpenCV
    3.2.0

Open Source Computer Vision

cv

stereo

MVKernel

Public Member Functions |
Public Attributes |
List of all members

cv::stereo::MVKernel< num_images > Struct Template Reference

#include "descriptor.hpp"

Public Member Functions

 	MVKernel ()

 	MVKernel (uint8_t **images, int **integral)

void 	operator() (int rrWidth, int w2, int rWidth, int jj, int j, int c[num_images]) const

Public Attributes

uint8_t * 	image [num_images]

int * 	integralImage [num_images]

int 	stop

Detailed Description

template<int num_images>

struct cv::stereo::MVKernel< num_images >

Mean Variation is a robust kernel that compares a pixel not just with the center but also with the mean of the window

Constructor & Destructor Documentation

§ MVKernel() [1/2]

template<int num_images>

          cv::stereo::MVKernel< num_images >::MVKernel
          (
          	)

§ MVKernel() [2/2]

template<int num_images>

          cv::stereo::MVKernel< num_images >::MVKernel
          (
          uint8_t **
          images,

          int **
          integral

          )

Member Function Documentation

§ operator()()

template<int num_images>

          void cv::stereo::MVKernel< num_images >::operator()
          (
          int
          rrWidth,

          int
          w2,

          int
          rWidth,

          int
          jj,

          int
          j,

          int
          c[num_images]

          )
          	 const

Member Data Documentation

§ image

template<int num_images>

          uint8_t* cv::stereo::MVKernel< num_images >::image[num_images]

§ integralImage

template<int num_images>

          int* cv::stereo::MVKernel< num_images >::integralImage[num_images]

§ stop

template<int num_images>

          int cv::stereo::MVKernel< num_images >::stop

The documentation for this struct was generated from the following file:

/build/master-contrib_docs-lin64/opencv_contrib/modules/stereo/include/opencv2/stereo/descriptor.hpp

<address class="footer">
Generated on Fri Dec 23 2016 13:00:29 for OpenCV by

 1.8.12
</address>


text:
namespace bitwave {
namespace net {

    typedef IocpService IoService;
    typedef Socket<BaseSocket, IoService> AsyncSocket;
    typedef Listener<BaseSocket, IoService> AsyncListener;

    // a help function to construct a AsyncSocket by service and BaseSocket
    inline AsyncSocket MakeAsyncSocket(IoService& service,
                                       const BaseSocket& socket)
    {
        return AsyncSocket(service, socket);
    }

} // namespace net
} // namespace bitwave

#endif // IO_SERVICE_H


text:
// Copyright (c) 2013, Gerson Kurz
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer. Redistributions in binary form must
// reproduce the above copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with the distribution.
//
// Neither the name regdiff nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

using System;
using System.Collections.Generic;
using System.Text;

namespace com.tikumo.regis3.ini
{
    /// <summary>
    /// This class represents a section in an .INI file. INI files can be organized to have recursive sections, so for example
    ///
    /// [foo\bar\blub]
    ///
    /// could either be represented as a single section named 'foo\bar\blub', or three sections named 'foo', 'bar' and 'blub' respectively.
    /// </summary>
    public class IniFileSection
    {
        /// <summary>
        /// List of child sections. Can be empty for flat files
        /// </summary>
        public readonly List<IniFileSection> Sections = new List<IniFileSection>();

        /// <summary>
        /// List of entries in this section.
        /// </summary>
        public readonly List<IniFileEntry> Entries = new List<IniFileEntry>();

        /// <summary>
        /// Name of this section
        /// </summary>
        public string Name { get; protected set; }

        /// <summary>
        /// Parent section or null if this is the root section
        /// </summary>
        public readonly IniFileSection Parent;

        /// <summary>
        /// The default constructor creates an unamed section without a parent. Used only by the public IniFile constructor.
        /// </summary>
        protected IniFileSection()
        {
            Name = null;
            Parent = null;
        }

        /// <summary>
        /// This constructor creates a named section with a parent
        /// </summary>
        /// <param name="name">Name of this section</param>
        /// <param name="parent">Parent section. Must not be null</param>
        public IniFileSection(string name, IniFileSection parent)
        {
            Name = name;
            Parent = parent;
            Parent.Sections.Add(this);
        }

        /// <summary>
        /// Create a string description of this instance
        /// </summary>
        /// <returns>String description of this instance</returns>
        public override string ToString()
        {
            StringBuilder output = new StringBuilder();

            foreach (IniFileSection section in Sections)
            {
                output.AppendLine(section.ToString());
            }

            if (Parent != null)
            {
                Console.WriteLine("[{0}]", Name);
            }

            foreach (IniFileEntry entry in Entries)
            {
                if (entry.HasComment)
                {
                    Console.WriteLine("{0}={1} # {2}",
                        entry.Name, entry.Data, entry.Comment);
                }
                else
                {
                    Console.WriteLine("{0}={1}",
                        entry.Name, entry.Data);
                }
            }

            return output.ToString();
        }
    }
}


text:
from __future__ import print_function, division
import matplotlib
import logging
from sys import stdout
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
from neuralnilm import (Net, RealApplianceSource)
from neuralnilm.source import (standardise, discretize, fdiff, power_and_fdiff,
                               RandomSegments, RandomSegmentsInMemory,
                               SameLocation, MultiSource)
from neuralnilm.experiment import run_experiment, init_experiment
from neuralnilm.net import TrainingError
from neuralnilm.layers import (MixtureDensityLayer, DeConv1DLayer,
                               SharedWeightsDenseLayer)
from neuralnilm.objectives import (scaled_cost, mdn_nll,
                                   scaled_cost_ignore_inactive, ignore_inactive,
                                   scaled_cost3)
from neuralnilm.plot import MDNPlotter, CentralOutputPlotter, Plotter, RectangularOutputPlotter, StartEndMeanPlotter
from neuralnilm.updates import clipped_nesterov_momentum
from neuralnilm.disaggregate import disaggregate
from neuralnilm.rectangulariser import rectangularise

from lasagne.nonlinearities import sigmoid, rectify, tanh, identity, softmax
from lasagne.objectives import squared_error, binary_crossentropy
from lasagne.init import Uniform, Normal
from lasagne.layers import (DenseLayer, Conv1DLayer,
                            ReshapeLayer, FeaturePoolLayer,
                            DimshuffleLayer, DropoutLayer, ConcatLayer, PadLayer)
from lasagne.updates import nesterov_momentum, momentum
from functools import partial
import os
import __main__
from copy import deepcopy
from math import sqrt
import numpy as np
import theano.tensor as T
import gc

"""
Max powers:
microwave = 3000W
"""

NAME = os.path.splitext(os.path.split(__main__.__file__)[1])[0]
#PATH = "/homes/dk3810/workspace/python/neuralnilm/figures"
PATH = "/data/dk3810/figures"
# PATH = "/home/jack/experiments/neuralnilm/figures"
SAVE_PLOT_INTERVAL = 25000

UKDALE_FILENAME = '/data/dk3810/ukdale.h5'

MAX_TARGET_POWER = 1500
TARGET_APPLIANCE = 'microwave'

SEQ_LENGTH = 128
N_SEQ_PER_BATCH = 64
TRAIN_BUILDINGS = [1, 3, 4, 5]
VALIDATION_BUILDINGS = [2]
SKIP_PROBABILITY_FOR_TARGET = 0.5
INDEPENDENTLY_CENTER_INPUTS = True

WINDOW_PER_BUILDING = {
    1: ("2013-03-17", "2014-12-01"),
    2: ("2013-05-22", "2013-10-01"),
    3: ("2013-02-27", "2013-04-01"),
    4: ("2013-03-09", "2013-09-20"),
    5: ("2014-06-29", "2014-08-27")
}

INPUT_STATS = {
    'mean': np.array([297.87216187], dtype=np.float32),
    'std': np.array([374.43884277], dtype=np.float32)
}

def only_train_on_real_data(net, iteration):
    net.logger.info(
        "Iteration {}: Now only training on real data.".format(iteration))
    net.source.sources[0]['train_probability'] = 0.0
    net.source.sources[1]['train_probability'] = 1.0

net_dict = dict(
    save_plot_interval=SAVE_PLOT_INTERVAL,
    loss_function=lambda x, t: squared_error(x, t).mean(),
    updates_func=nesterov_momentum,
    learning_rate=1e-5,
    learning_rate_changes_by_iteration={
        # 400000: 1e-6,
        # 500000: 1e-7
    },
    epoch_callbacks={
        350000: only_train_on_real_data
    },
    do_save_activations=True,
    auto_reshape=False,
    layers_config=[
        {
            'type': DimshuffleLayer,
            'pattern': (0, 2, 1)  # (batch, features, time)
        },
        {
            'type': PadLayer,
            'width': 4
        },
        {
            'type': Conv1DLayer,  # convolve over the time axis
            'num_filters': 16,
            'filter_size': 4,
            'stride': 1,
            'nonlinearity': None,
            'border_mode': 'valid'
        },
        {
            'type': Conv1DLayer,  # convolve over the time axis
            'num_filters': 16,
            'filter_size': 4,
            'stride': 1,
            'nonlinearity': None,
            'border_mode': 'valid'
        },
        {
            'type': DimshuffleLayer,
            'pattern': (0, 2, 1),  # back to (batch, time, features)
            'label': 'dimshuffle3'
        },
        {
            'type': DenseLayer,
            'num_units': 512 * 8,
            'nonlinearity': rectify,
            'label': 'dense0'
        },
        {
            'type': DenseLayer,
            'num_units': 512 * 6,
            'nonlinearity': rectify,
            'label': 'dense1'
        },
        {
            'type': DenseLayer,
            'num_units': 512 * 4,
            'nonlinearity': rectify,
            'label': 'dense2'
        },
        {
            'type': DenseLayer,
            'num_units': 512,
            'nonlinearity': rectify
        },
        {
            'type': DenseLayer,
            'num_units': 3,
            'nonlinearity': None
        }
    ]
)

def exp_a(name):
    logger = logging.getLogger(name)
    real_appliance_source1 = RealApplianceSource(
        logger=logger,
        filename=UKDALE_FILENAME,
        appliances=[
            TARGET_APPLIANCE,
            ['fridge freezer', 'fridge', 'freezer'],
            'dish washer',
            'kettle',
            ['washer dryer', 'washing machine']
        ],
        max_appliance_powers=[MAX_TARGET_POWER, 300, 2500, 2600, 2400],
        on_power_thresholds=[5] * 5,
        min_on_durations=[12, 60, 1800, 12, 1800],
        min_off_durations=[12, 12, 1800, 12, 600],
        divide_input_by_max_input_power=False,
        window_per_building=WINDOW_PER_BUILDING,
        seq_length=SEQ_LENGTH,
        output_one_appliance=True,
        train_buildings=TRAIN_BUILDINGS,
        validation_buildings=VALIDATION_BUILDINGS,
        n_seq_per_batch=N_SEQ_PER_BATCH,
        skip_probability=0.75,
        skip_probability_for_first_appliance=SKIP_PROBABILITY_FOR_TARGET,
        target_is_start_and_end_and_mean=True,
        standardise_input=True,
        input_stats=INPUT_STATS,
        independently_center_inputs=INDEPENDENTLY_CENTER_INPUTS
    )

    same_location_source1 = SameLocation(
        logger=logger,
        filename=UKDALE_FILENAME,
        target_appliance=TARGET_APPLIANCE,
        window_per_building=WINDOW_PER_BUILDING,
        seq_length=SEQ_LENGTH,
        train_buildings=TRAIN_BUILDINGS,
        validation_buildings=VALIDATION_BUILDINGS,
        n_seq_per_batch=N_SEQ_PER_BATCH,
        skip_probability=SKIP_PROBABILITY_FOR_TARGET,
        target_is_start_and_end_and_mean=True,
        standardise_input=True,
        offset_probability=1,
        divide_target_by=MAX_TARGET_POWER,
        input_stats=INPUT_STATS,
        independently_center_inputs=INDEPENDENTLY_CENTER_INPUTS
    )

    multi_source = MultiSource(
        sources=[
            {
                'source': real_appliance_source1,
                'train_probability': 0.5,
                'validation_probability': 0
            },
            {
                'source': same_location_source1,
                'train_probability': 0.5,
                'validation_probability': 1
            }
        ],
        standardisation_source=same_location_source1
    )

    net_dict_copy = deepcopy(net_dict)
    net_dict_copy.update(dict(
        experiment_name=name,
        source=multi_source,
        plotter=StartEndMeanPlotter(
            n_seq_to_plot=32,
            n_training_examples_to_plot=16,
            max_target_power=MAX_TARGET_POWER)
    ))
    net = Net(**net_dict_copy)
    net.load_params(730532)
    return net

def main():
    EXPERIMENTS = list('a')
    for experiment in EXPERIMENTS:
        full_exp_name = NAME + experiment
        func_call = init_experiment(PATH, experiment, full_exp_name)
        logger = logging.getLogger(full_exp_name)
        try:
            net = eval(func_call)
            run_experiment(net, epochs=None)
        except KeyboardInterrupt:
            logger.info("KeyboardInterrupt")
            break
        except Exception:
            logger.exception("Exception")
            # raise
        finally:
            logging.shutdown()

if __name__ == "__main__":
    main()

"""
Emacs variables
Local Variables:
compile-command: "cp /home/jack/workspace/python/neuralnilm/scripts/e552.py /mnt/sshfs/imperial/workspace/python/neuralnilm/scripts/"
End:
"""


text: Rooster Teeth Comics mass downloading application.


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 缓存管理器 -->
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache/ehcache.xml"/>
    </bean>

    <!-- Realm实现 -->
    <bean id="oAuth2Realm" class="onlive.babylove.www.oauth2.OAuth2Realm">
        <property name="cachingEnabled" value="true"/>
        <property name="authenticationCachingEnabled" value="true"/>
        <property name="authenticationCacheName" value="authenticationCache"/>
        <property name="authorizationCachingEnabled" value="true"/>
        <property name="authorizationCacheName" value="authorizationCache"/>

        <property name="clientId" value="c1ebe466-1cdc-4bd3-ab69-77c3561b9dee"/>
        <property name="clientSecret" value="d8346ea2-6017-43ed-ad68-19c0f971738b"/>
        <property name="accessTokenUrl" value="http://localhost:8080/accessToken"/>
        <property name="userInfoUrl" value="http://localhost:8080/userInfo"/>
        <property name="redirectUrl" value="http://localhost:8070/oauth2-login"/>
    </bean>

    <!-- 会话ID生成器 -->
    <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>

    <!-- 会话Cookie模板 -->
    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <constructor-arg value="sid"/>
        <property name="httpOnly" value="true"/>
        <property name="maxAge" value="-1"/>
    </bean>

    <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <constructor-arg value="rememberMe"/>
        <property name="httpOnly" value="true"/>
        <property name="maxAge" value="2592000"/><!-- 30天 -->
    </bean>

    <!-- rememberMe管理器 -->
    <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
        <!-- rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位)-->
        <property name="cipherKey"
                  value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}"/>
        <property name="cookie" ref="rememberMeCookie"/>
    </bean>

    <!-- 会话DAO -->
    <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
        <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
        <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
    </bean>

    <!-- 会话验证调度器 -->
    <bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler">
        <property name="sessionValidationInterval" value="1800000"/>
        <property name="sessionManager" ref="sessionManager"/>
    </bean>

    <!-- 会话管理器 -->
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <property name="globalSessionTimeout" value="1800000"/>
        <property name="deleteInvalidSessions" value="true"/>
        <property name="sessionValidationSchedulerEnabled" value="true"/>
        <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
        <property name="sessionDAO" ref="sessionDAO"/>
        <property name="sessionIdCookieEnabled" value="true"/>
        <property name="sessionIdCookie" ref="sessionIdCookie"/>
    </bean>

    <!-- 安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="oAuth2Realm"/>
        <property name="sessionManager" ref="sessionManager"/>
        <property name="cacheManager" ref="cacheManager"/>
        <property name="rememberMeManager" ref="rememberMeManager"/>
    </bean>

    <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
        <property name="arguments" ref="securityManager"/>
    </bean>

    <!-- OAuth2身份验证过滤器 -->
    <bean id="oAuth2AuthenticationFilter" class="onlive.babylove.www.oauth2.OAuth2AuthenticationFilter">
        <property name="authCodeParam" value="code"/>
        <property name="failureUrl" value="/oauth2Failure.jsp"/>
    </bean>

    <!-- Shiro的Web过滤器 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="http://localhost:8080/authorize?client_id=c1ebe466-1cdc-4bd3-ab69-77c3561b9dee&response_type=code&redirect_uri=http://localhost:8070/oauth2-login"/>
        <property name="successUrl" value="/"/>
        <property name="filters">
            <util:map>
                <entry key="oauth2Authc" value-ref="oAuth2AuthenticationFilter"/>
            </util:map>
        </property>
        <property name="filterChainDefinitions">
            <value>
                / = anon
                /oauth2Failure.jsp = anon
                /oauth2-login = oauth2Authc
                /logout = logout
                /** = user
            </value>
        </property>
    </bean>

    <!-- Shiro生命周期处理器-->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

</beans>


text:
from django import forms

from pennyblack.module.subscriber.models import NewsletterSubscriber

class NewsletterSignupForm(forms.ModelForm):
    class Meta:
        model = NewsletterSubscriber


text:
package com.raspoid.brickpi.nxt.sensor;

import static com.raspoid.brickpi.nxt.sensor.SensorType.TYPE_SENSOR_RAW;

import com.raspoid.brickpi.Sensor;

/**
 * Implementation of a Raw Sensor.
 *
 * @author Julien Louette & Gaël Wittorski
 * @version 1.0
 */
public class RawSensor extends Sensor {

    @Override
    public SensorType getType() {
        return TYPE_SENSOR_RAW;
    }
}


text:
import pytest

@pytest.mark.xfail(strict=True, reason='Stub: test not implemented yet.')
def test_row_similarity_basic():
    raise ValueError('Implement me!')


text:
    #ifndef VG_PATH_HPP_INCLUDED
#define VG_PATH_HPP_INCLUDED

#include <iostream>
#include <algorithm>
#include <functional>
#include <set>
#include <list>
#include <sstream>
#include "vg/io/json2pb.h"
#include <vg/vg.pb.h>
#include "vg/io/edit.hpp"
#include "hash_map.hpp"
#include "utility.hpp"
#include "types.hpp"
#include "position.hpp"
#include "nodetraversal.hpp"

//#define debug

namespace vg {

using namespace std;

class mapping_t {
public:
    int64_t traversal; // negative implies reverse
    int32_t length;
    int32_t rank;
    mapping_t(void);
    mapping_t(const Mapping& m);
    Mapping to_mapping(void) const;
    id_t node_id(void) const;
    void set_node_id(id_t id);
    bool is_reverse(void) const;
    void set_is_reverse(bool is_rev);
};

/// Allow a mapping_t to be printed, for debugging purposes
ostream& operator<<(ostream& out, mapping_t mapping);

class Paths {
public:

    // This predicate matches the names of alt paths.
    // We used to use a regex but that's a very slow way to check a prefix.
    const static function<bool(const string&)> is_alt;

    // look for suffix of form [offset] or [offset-end_offset] and parse it. ex:
    // chr1 would return <false, "", 0, 0>
    // chr1[10] would return <true, chr1, 10, 0>
    // chr1[10-20] would return <true, chr1, 10, 20>
    // note: the start/end are as in BED : 0-based open-ended
    tuple<bool, string, size_t, size_t> static parse_subpath_name(const string& path_name);

    // Create a subpath name
    string static make_subpath_name(const string& path_name, size_t offset, size_t end_offset = 0);

    Paths(void);

    // copy
    Paths(const Paths& other) {
        if (this != &other) {
            _paths = other._paths;
            rebuild_node_mapping();
        }
    }
    // move constructor
    Paths(Paths&& other) noexcept {
        _paths = std::move(other._paths);
        other.clear();
        rebuild_node_mapping();
    }

    // copy assignment operator
    Paths& operator=(const Paths& other) {
        Paths tmp(other);
        *this = std::move(tmp);
        return *this;
    }

    // move assignment operator
    Paths& operator=(Paths&& other) noexcept {
        std::swap(_paths, other._paths);
        rebuild_node_mapping();
        return *this;
    }

    // This maps from path name to the list of Mappings for that path.
    map<string, list<mapping_t> > _paths;

private:
    // These need to be private because path names are lazily assigned IDs by the accessors
    // They also need to be mutable because we want our accessors to treat our object as logical const
    mutable int64_t max_path_id;
    mutable map<string, int64_t> name_to_id;
    mutable map<int64_t, string> id_to_name;
public:
    /// Get the lazily assigned numeric ID for a path, by name.
    int64_t get_path_id(const string& name) const;
    /// Get the name of a path, by numeric ID.
    const string& get_path_name(int64_t id) const;

    // This maps from mapping_t* pointer to its iterator in its list of Mappings
    // for its path and the id of the path.
    // The list in question is stored above in _paths.
    // Recall that std::list iterators are bidirectional.
    hash_map<const mapping_t*, pair<list<mapping_t>::iterator, int64_t> > mapping_itr;
    // This maps from mapping_t* pointer to the name of the path it belongs to
    // (which can then be used to get the list its iterator belongs to).
    void sort_by_mapping_rank(void);
    /// Reassign ranks and rebuild indexes, treating the mapping lists in _paths as the truth.
    void rebuild_mapping_aux(void);
    // We need this in order to make sure we aren't adding duplicate mappings
    // with the same rank in the same path. Maps from path name and rank to
    // Mapping pointer.
    map<string, hash_map<int32_t, mapping_t*>> mappings_by_rank;
    // This maps from node ID, then path name, then rank and orientation, to
    // Mapping pointers for the mappings on that path to that node.
    hash_map<id_t, map<int64_t, set<mapping_t*>>> node_mapping;
    // record which head nodes we have
    // we'll use this when determining path edge crossings--- all paths implicitly cross these nodes
    set<id_t> head_tail_nodes;
    bool is_head_or_tail_node(id_t);
    vector<string> all_path_names(void);
    // records which paths are circular
    set<string> circular;
    void make_circular(const string& name);
    void make_linear(const string& name);

    void rebuild_node_mapping(void);

    // Find the given mapping in its path, so mappings can be inserted before
    // it.
    list<mapping_t>::iterator find_mapping(mapping_t* m);
    // remove the given Mapping from its path. Returns an iterator to the
    // mapping that came after it, or the end of the list if no mapping came
    // after it.
    list<mapping_t>::iterator remove_mapping(mapping_t* m);
    // insert the given mapping into the given path, before the mapping pointed
    // to by the given iterator. Returns an iterator to the newly-inserted
    // mapping.
    list<mapping_t>::iterator insert_mapping(list<mapping_t>::iterator w,
                                             const string& path_name, const mapping_t& m);
    pair<mapping_t*, mapping_t*> divide_mapping(mapping_t* m, const Position& pos);
    pair<mapping_t*, mapping_t*> divide_mapping(mapping_t* m, size_t offset);
    // replace the mapping with two others in the order provided
    pair<mapping_t*, mapping_t*> replace_mapping(mapping_t* m, pair<mapping_t, mapping_t> n);
    // Note that this clears and rebuilds all the indexes
    void remove_paths(const set<string>& names);
    // This one actually unthreads the path from the indexes. It's O(path
    // length), but you can do several calls without thrashing the index
    // clear and rebuild functions.
    void remove_path(const string& name);
    void keep_paths(const set<string>& name);
    void remove_node(id_t id);
    bool has_path(const string& name) const;
    void to_json(ostream& out);
    list<mapping_t>& get_path(const string& name);
    list<mapping_t>& get_create_path(const string& name);
    list<mapping_t>& create_path(const string& name);
    // Does the given path have a mapping meeting the given criteria?
    // Is there a mapping in the given path with the given assigned rank? Note
    // that the rank passed may not be 0.
    bool has_mapping(const string& name, int32_t rank);
    // We used to be able to search for a Mapping by value, but that's not
    // efficient if the Mappings don't have ranks, and it never checked the
    // edits for equality anyway.
    bool has_node_mapping(id_t id) const;
    bool has_node_mapping(Node* n) const;
    map<int64_t, set<mapping_t*> >& get_node_mapping(Node* n);
    map<int64_t, set<mapping_t*> >& get_node_mapping(id_t id);
    const map<int64_t, set<mapping_t*> >& get_node_mapping(id_t id) const;
    map<string, set<mapping_t*> > get_node_mapping_by_path_name(Node* n);
    map<string, set<mapping_t*> > get_node_mapping_by_path_name(id_t id);
    map<string, map<int, mapping_t*> > get_node_mappings_by_rank(id_t id);
    // Copy all the mappings for the node with the given ID, and return them in
    // a map by path name and then by rank.
    map<string, map<int, mapping_t> > get_node_mapping_copies_by_rank(id_t id);
    // Go left along the path that this mapping_t* belongs to, and return the
    // mapping_t* there, or null if this Mapping* is the first in its path.
    mapping_t* traverse_left(mapping_t* mapping);
    // Go right along the path that this mapping_t* belongs to, and return the
    // mapping_t* there, or null if this mapping_t* is the last in its path.
    mapping_t* traverse_right(mapping_t* mapping);
    // TODO: should this be a reference?
    const string mapping_path_name(mapping_t* m);
    int64_t mapping_path_id(mapping_t* m);
    // the patsh of the node
    set<string> of_node(id_t id);
    // get the paths on this node and the number of mappings from each one
    map<string, int> node_path_traversal_counts(id_t id, bool rev = false);
    // the return vector contains the name of each path that crosses the node
    // repeated as many times as it crosses
    vector<string> node_path_traversals(id_t id, bool rev = false);
    bool are_consecutive_nodes_in_path(id_t id1, id_t id2, const string& path_name);
    // paths that cross the edge,
    vector<string> over_edge(id_t id1, bool rev1,
                             id_t id2, bool rev2,
                             vector<string> following);
    vector<string> over_directed_edge(id_t id1, bool rev1,
                                      id_t id2, bool rev2,
                                      vector<string> following);
    size_t size(void) const;
    bool empty(void) const;
    // clear the internal data structures tracking mappings and storing the paths
    void clear(void);
    void clear_mapping_ranks(void);
    void compact_ranks(void);
    //void add_node_mapping(Node* n);
    void load(istream& in);
    /// Write paths to the given stream, ending with an EOF marker.
    void write(ostream& out);
    /// Add all paths into the given Protobuf graph. Creates a new path for every path.
    void to_graph(Graph& g);
    // get a path
    Path path(const string& name);
    // add mappings. Mappings are assumed to either be pre-sorted or to have
    // ranks assigned already. If you append a mapping with no rank after
    // mappings with ranks, or visa versa, the relative ordering is undefined.
    // Also, if both pre-ranked and un-ranked mappings are appended, or if you
    // called clear_mapping_ranks before appending, mappings_by_rank may be
    // incorrect until rebuild_mapping_aux() is called.
    void append_mapping(const string& name, const mapping_t& m, bool warn_on_duplicates = false);
    void append_mapping(const string& name, id_t id, bool is_reverse, size_t length, size_t rank = 0, bool warn_on_duplicates = false);
    // TODO: Adapt this to use mapping_t instead.
    void prepend_mapping(const string& name, const Mapping& m, bool warn_on_duplicates = false);
    void prepend_mapping(const string& name, id_t id, bool is_reverse, size_t length, size_t rank = 0, bool warn_on_duplicates = false);
    size_t get_next_rank(const string& name);
    void append(const Paths& paths, bool warn_on_duplicates = false, bool rebuild_indexes = true);
    void append(const Graph& g, bool warn_on_duplicates = false, bool rebuild_indexes = true);
    void extend(const Paths& paths, bool warn_on_duplicates = false, bool rebuild_indexes = true);
    void extend(const Path& p, bool warn_on_duplicates = false, bool rebuild_indexes = true);
    void extend(const vector<Path> & paths, bool warn_on_duplicates = false, bool rebuild_indexes = true);
    void for_each(const function<void(const Path&)>& lambda);
    // Loop over the names of paths without actually extracting the Path objects.
    void for_each_name(const function<void(const string&)>& lambda) const;
    // Like for_each_name but allows stopping early.
    // TODO: Use the libhandlegraph unified iteratee pattern here.
    bool for_each_name_stoppable(const function<bool(const string&)>& lambda) const;
    void for_each_stream(istream& in, const function<void(Path&)>& lambda);
    void increment_node_ids(id_t inc);
    // Replace the node IDs according to a mapping from old ID to new ID.
    // This is only efficient to do in a batch.
    void swap_node_ids(const std::function<nid_t(const nid_t&)>& get_new_id);
    void swap_node_ids(hash_map<id_t, id_t>& id_mapping);
    // sets the mapping to the new id
    // erases current (old index information)
    void reassign_node(id_t new_id, mapping_t* m);
    void for_each_mapping(const function<void(mapping_t&)>& lambda);
};

string  path_to_string(Path p);
Path& increment_node_mapping_ids(Path& p, id_t inc);
Path& append_path(Path& a, const Path& b);
const Paths paths_from_graph(Graph& g);
int path_to_length(const Path& path);
int path_from_length(const Path& path);
int mapping_to_length(const Mapping& m);
int mapping_from_length(const Mapping& m);
Position first_path_position(const Path& path);
Position last_path_position(const Path& path);
int to_length(const Mapping& m);
int from_length(const Mapping& m);
bool mapping_ends_in_deletion(const Mapping& m);
bool mapping_starts_in_deletion(const Mapping& m);
bool mapping_is_total_deletion(const Mapping& m);
bool mapping_is_simple_match(const Mapping& m);
bool path_is_simple_match(const Path& p);
// convert the mapping to the particular node into the sequence implied by the mapping
const string mapping_sequence(const Mapping& m, const string& node_seq);
const string mapping_sequence(const Mapping& m, const Node& n);
// convert the path to a sequence
string path_sequence(const HandleGraph& graph, const Path& path);
// Reverse-complement a Mapping and all the Edits in it. A function to get node
// lengths is needed, because the mapping will need to count its position from
// the other end of the node.
Mapping reverse_complement_mapping(const Mapping& m,
                                   const function<int64_t(id_t)>& node_length);
// Reverse-complement a Path and all the Mappings in it. A function to get node
// lengths is needed, because the mappings will need to count their positions
// from the other ends of their nodes.
Path reverse_complement_path(const Path& path,
                             const function<int64_t(id_t)>& node_length);
// Reverse-complement a Mapping and all the Edits in it in place.
void reverse_complement_mapping_in_place(Mapping* m,
                                         const function<int64_t(id_t)>& node_length);
// Reverse-complement a Path and all the Mappings in it in place.
void reverse_complement_path_in_place(Path* path,
                                      const function<int64_t(id_t)>& node_length);
/// Simplify the path for addition as new material in the graph. Remove any
/// mappings that are merely single deletions, merge adjacent edits of the same
/// type, strip leading and trailing deletion edits on mappings, and make sure no
/// mappings have missing positions.
Path simplify(const Path& p, bool trim_internal_deletions = true);
/// Merge adjacent edits of the same type, strip leading and trailing deletion
/// edits (while updating positions if necessary), and makes sure position is
/// actually set.
Mapping simplify(const Mapping& m, bool trim_internal_deletions = true);

/// Merge adjacent edits of the same type
Path merge_adjacent_edits(const Path& m);
/// Merge adjacent edits of the same type
Mapping merge_adjacent_edits(const Mapping& m);
// trim path so it starts and begins with a match (or is empty)
Path trim_hanging_ends(const Path& p);
// make a new mapping that concatenates the mappings
Mapping concat_mappings(const Mapping& m, const Mapping& n, bool trim_internal_deletions = true);
// make a new path that concatenates the two given paths
Path concat_paths(const Path& path1, const Path& path2);
// extend the first path by the second, avoiding copy operations
Path& extend_path(Path& path1, const Path& path2);
// divide mapping at reference-relative position
pair<Mapping, Mapping> cut_mapping(const Mapping& m, const Position& pos);
pair<mapping_t, mapping_t> cut_mapping(const mapping_t& m, const Position& pos);
// divide mapping at reference-relative offset (as measure in from_length)
pair<Mapping, Mapping> cut_mapping_offset(const Mapping& m, size_t offset);
pair<mapping_t, mapping_t> cut_mapping_offset(const mapping_t& m, size_t offset);
// divide mapping at target-relative offset (as measured in to_length)
pair<Mapping, Mapping> cut_mapping(const Mapping& m, size_t offset);
pair<mapping_t, mapping_t> cut_mapping(const mapping_t& m, size_t offset);
// divide path at reference-relative position
pair<Path, Path> cut_path(const Path& path, const Position& pos);
// divide the path at a path-relative offset as measured in to_length from start
pair<Path, Path> cut_path(const Path& path, size_t offset);
bool maps_to_node(const Path& p, id_t id);
// the position that starts just after the path ends
Position path_start_position(const Path& path);
Position path_end_position(const Path& path);
bool adjacent_mappings(const Mapping& m1, const Mapping& m2);
// Return true if a mapping is a perfect match (i.e. contains no non-match edits)
bool mapping_is_match(const Mapping& m);
double divergence(const Mapping& m);
// Return the identity for the path: perfect matches over total length.
// For zero-length paths, returns 0.
double identity(const Path& path);
// compare the agreement between two alignments
double overlap(const Path& p1, const Path& p2);
// helps estimate overapls quickly
void decompose(const Path& path, map<pos_t, int>& ref_positions, map<pos_t, Edit>& edits);

/// Switches the node ids in the path to the ones indicated by the translator
void translate_node_ids(Path& path, const unordered_map<id_t, id_t>& translator);
/// Replaces the node IDs in the path with the ones indicated by the
/// translator. Supports a single cut node in the source graph, where the given
/// number of bases of the given node were removed from its left or right side
/// when making the source graph from the destination graph.
void translate_node_ids(Path& path, const unordered_map<id_t, id_t>& translator, id_t cut_node, size_t bases_removed, bool from_right);
/// Switches the node ids and orientations in the path to the ones indicated by the translator
void translate_oriented_node_ids(Path& path, const unordered_map<id_t, pair<id_t, bool>>& translator);
/// Switches node ids and orientations in the path to the ones indicated by the translator
void translate_oriented_node_ids(Path& path, const function<pair<id_t, bool>(id_t)>& translator);

// the first position on the path
pos_t initial_position(const Path& path);
// the last position on the path
pos_t final_position(const Path& path);

// Turn a list of node traversals into a path
Path path_from_node_traversals(const list<NodeTraversal>& traversals);

// Remove the paths with names matching the predicate from the graph.
// Store them in the list unless it is nullptr.
void remove_paths(Graph& graph, const function<bool(const string&)>& paths_to_take, std::list<Path>* matching);

// Get a Path from a handle graph
Path path_from_path_handle(const PathHandleGraph& graph, path_handle_t path_handle);

// Wrap a Path in an Alignment
Alignment alignment_from_path(const HandleGraph& graph, const Path& path);

/*
 * STL implementations of the protobuf object for use in in-memory operations
 */
class edit_t {
public:
    edit_t() = default;
    edit_t(const edit_t&) = default;
    edit_t(edit_t&&) = default;
    ~edit_t() = default;
    edit_t& operator=(const edit_t&) = default;
    edit_t& operator=(edit_t&&) = default;
    inline int32_t from_length() const;
    inline void set_from_length(int32_t l);
    inline int32_t to_length() const;
    inline void set_to_length(int32_t l);
    inline const string& sequence() const;
    inline void set_sequence(const string& s);
    inline string* mutable_sequence();
    inline bool operator==(const edit_t& other) const;
    inline bool operator!=(const edit_t& other) const;
private:
    int32_t _from_length;
    int32_t _to_length;
    string _sequence;
};

// the mapping_t name is already taken
class path_mapping_t {
public:
    path_mapping_t() = default;
    path_mapping_t(const path_mapping_t&) = default;
    path_mapping_t(path_mapping_t&&) = default;
    ~path_mapping_t() = default;
    path_mapping_t& operator=(const path_mapping_t&) = default;
    path_mapping_t& operator=(path_mapping_t&&) = default;
    inline const position_t& position() const;
    inline position_t* mutable_position();
    inline const vector<edit_t>& edit() const;
    inline const edit_t& edit(size_t i) const;
    inline vector<edit_t>* mutable_edit();
    inline edit_t* mutable_edit(size_t i);
    inline edit_t* add_edit();
    inline size_t edit_size() const;
    inline bool operator==(const path_mapping_t& other) const;
    inline bool operator!=(const path_mapping_t& other) const;
private:
    position_t _position;
    vector<edit_t> _edit;
};

class path_t {
public:
    path_t() = default;
    path_t(const path_t&) = default;
    path_t(path_t&&) = default;
    ~path_t() = default;
    path_t& operator=(const path_t&) = default;
    path_t& operator=(path_t&&) = default;
    inline const vector<path_mapping_t>& mapping() const;
    inline const path_mapping_t& mapping(size_t i) const;
    inline vector<path_mapping_t>* mutable_mapping();
    inline path_mapping_t* mutable_mapping(size_t i);
    inline path_mapping_t* add_mapping();
    inline void clear_mapping();
    inline size_t mapping_size() const;
    inline bool operator==(const path_t& other) const;
    inline bool operator!=(const path_t& other) const;
private:
    vector<path_mapping_t> _mapping;
};

void from_proto_edit(const Edit& proto_edit, edit_t& edit);
void to_proto_edit(const edit_t& edit, Edit& proto_edit);
void from_proto_mapping(const Mapping& proto_mapping, path_mapping_t& mapping);
void to_proto_mapping(const path_mapping_t& mapping, Mapping& proto_mapping);
void from_proto_path(const Path& proto_path, path_t& path);
void to_proto_path(const path_t& path, Path& proto_path);

// repeated functions for the new path_t class
void translate_node_ids(path_t& path, const unordered_map<id_t, id_t>& translator);
void translate_oriented_node_ids(path_t& path, const unordered_map<id_t, pair<id_t, bool>>& translator);
void translate_oriented_node_ids(path_t& path, const function<pair<id_t, bool>(id_t)>& translator);

int mapping_from_length(const path_mapping_t& mapping);
int path_from_length(const path_t& path);
int mapping_to_length(const path_mapping_t& mapping);
int path_to_length(const path_t& path);

path_mapping_t reverse_complement_mapping(const path_mapping_t& m,
                                          const function<int64_t(id_t)>& node_length);
path_t reverse_complement_path(const path_t& path,
                               const function<int64_t(id_t)>& node_length);
void reverse_complement_mapping_in_place(path_mapping_t* m,
                                         const function<int64_t(id_t)>& node_length);
void reverse_complement_path_in_place(path_t* path,
                                      const function<int64_t(id_t)>& node_length);

// the first position on the path
pos_t initial_position(const path_t& path);
// the last position on the path
pos_t final_position(const path_t& path);

int corresponding_to_length(const path_t& path, int from_length, bool from_end);
int corresponding_from_length(const path_t& path, int to_length, bool from_end);

string debug_string(const path_t& path);
string debug_string(const path_mapping_t& mapping);
string debug_string(const edit_t& edit);

/*
 * Implementations of inline methods
 */

/*
 * edit_t
 */
inline int32_t edit_t::from_length() const {
    return _from_length;
}
inline void edit_t::set_from_length(int32_t l) {
    _from_length = l;
}
inline int32_t edit_t::to_length() const {
    return _to_length;
}
inline void edit_t::set_to_length(int32_t l) {
    _to_length = l;
}
inline const string& edit_t::sequence() const {
    return _sequence;
}
inline void edit_t::set_sequence(const string& s) {
    _sequence = s;
}
inline string* edit_t::mutable_sequence() {
    return &_sequence;
}
inline bool edit_t::operator==(const edit_t& other) const {
    return (_to_length == other._to_length
            && _from_length == other._from_length
            && _sequence == other._sequence);
}
inline bool edit_t::operator!=(const edit_t& other) const {
    return !(*this == other);
}

/*
 * path_mapping_t
 */
inline const position_t& path_mapping_t::position() const {
    return _position;
}
inline position_t* path_mapping_t::mutable_position() {
    return &_position;
}
inline const vector<edit_t>& path_mapping_t::edit() const {
    return _edit;
}
inline const edit_t& path_mapping_t::edit(size_t i) const {
    return _edit[i];
}
inline vector<edit_t>* path_mapping_t::mutable_edit() {
    return &_edit;
}
inline edit_t* path_mapping_t::add_edit() {
    _edit.emplace_back();
    return &_edit.back();
}
inline edit_t* path_mapping_t::mutable_edit(size_t i) {
    return &_edit[i];
}
inline size_t path_mapping_t::edit_size() const {
    return _edit.size();
}
inline bool path_mapping_t::operator==(const path_mapping_t& other) const {
    return (_position == other._position && _edit == other._edit);
}
inline bool path_mapping_t::operator!=(const path_mapping_t& other) const {
    return !(*this == other);
}

/*
 * path_t
 */
inline const vector<path_mapping_t>& path_t::mapping() const {
    return _mapping;
}
inline const path_mapping_t& path_t::mapping(size_t i) const {
    return _mapping[i];
}
inline vector<path_mapping_t>* path_t::mutable_mapping() {
    return &_mapping;
}
inline path_mapping_t* path_t::mutable_mapping(size_t i) {
    return &_mapping[i];
}
inline path_mapping_t* path_t::add_mapping() {
    _mapping.emplace_back();
    return &_mapping.back();
}
inline void path_t::clear_mapping() {
    _mapping.clear();
}
inline size_t path_t::mapping_size() const {
    return _mapping.size();
}
inline bool path_t::operator==(const path_t& other) const {
    return _mapping == other._mapping;
}
inline bool path_t::operator!=(const path_t& other) const {
    return !(*this == other);
}
}

#endif


text:
package com.google.errorprone.matchers;

import static com.google.common.base.MoreObjects.firstNonNull;

import com.google.errorprone.VisitorState;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePathScanner;

/**
 * Matches if the given matcher matches all of the identifiers under this syntax tree.
 *
 * @author alexloh@google.com (Alex Loh)
 */
public class HasIdentifier implements Matcher<Tree> {

  private final Matcher<IdentifierTree> nodeMatcher;

  public HasIdentifier(Matcher<IdentifierTree> nodeMatcher) {
    this.nodeMatcher = nodeMatcher;
  }

  @Override
  public boolean matches(Tree tree, VisitorState state) {
    Boolean matches = new HasIdentifierScanner(state, nodeMatcher).scan(state.getPath(), null);
    return firstNonNull(matches, false);
  }

  /** AST Visitor that matches identifiers in a Tree */
  private static class HasIdentifierScanner extends TreePathScanner<Boolean, Void> {

    private Matcher<IdentifierTree> idMatcher;
    private VisitorState ancestorState;

    public HasIdentifierScanner(VisitorState ancestorState, Matcher<IdentifierTree> idMatcher) {
      this.ancestorState = ancestorState;
      this.idMatcher = idMatcher;
    }

    @Override
    public Boolean visitIdentifier(IdentifierTree node, Void v) {
      return idMatcher.matches(node, ancestorState.withPath(getCurrentPath()));
    }

    @Override
    public Boolean reduce(Boolean r1, Boolean r2) {
      return firstNonNull(r1, false) || firstNonNull(r2, false);
    }

    @Override
    public Boolean visitClass(ClassTree node, Void v) {
      return firstNonNull(super.visitClass(node, v), false);
    }
  }
}


text:
const { chain, authCheck, adminCheck, userCheck, permCheck, tokenCheck, Permissions } = require('./auth');

describe('chain', () => {

  test('should call fns in a serial manner', async () => {
    const fn1 = jest.fn().mockImplementation(v => 1 + v);
    const fn2 = jest.fn().mockImplementation(v => 2 + v);
    const chained = chain(fn1, fn2);
    expect(fn1.mock.calls).toEqual([]);
    expect(fn2.mock.calls).toEqual([]);
    const result = await chained(10);
    expect(fn1.mock.calls).toEqual([[10]]);
    expect(fn2.mock.calls).toEqual([[10]]);
    expect(result).toBe(12);
  });

  test('should cancel serial fn calls if there is an error', async () => {
    const fn1 = jest.fn().mockImplementation(() => { throw new Error('err') });
    const fn2 = jest.fn().mockImplementation(v => 2 + v);
    const chained = chain(fn1, fn2);
    expect(fn1.mock.calls).toEqual([]);
    expect(fn2.mock.calls).toEqual([]);
    try {
      await chained(10);
    } catch (e) {
      expect(e).toEqual(new Error('err'));
    }
    expect(fn1.mock.calls).toEqual([[10]]);
    expect(fn2.mock.calls).toEqual([]);
  });

});

describe('authCheck', () => {

  test('when ctx has no user', () => {
    expect(() => authCheck(null, null, {})).toThrow('You need to pass an authorization token');
  });

  test('when ctx has a user', () => {
    expect(authCheck(null, null, { user: {} })).toBeUndefined();
  });

});

describe('roleCheck', () => {

  test('adminCheck', async () => {
    const ctx = {
      user: {
        role: 'admin',
      },
    };
    const v = await adminCheck(null, null, ctx);
    expect(v).toBeUndefined();
  });

  test('userCheck', async () => {
    const ctx = {
      user: {
        role: 'user',
      },
    };
    const v = await userCheck(null, null, ctx);
    expect(v).toBeUndefined();
  });

});

describe('permCheck', () => {

  test('throw an error if there the user doesnt have the permission', async () => {
    const ctx = {
      user: {
        role: 'user',
      },
    };
    try {
      await permCheck(Permissions.OTHER_USER_CREATE)(null, null, ctx);
    } catch (e) {
      expect(e).toEqual(new Error('You need to have the right permission to perform this action'));
    }
  });

  test('whether the user has the permission', async () => {
    const ctx = {
      user: {
        role: 'user',
      },
    };
    const v = await permCheck(Permissions.OTHER_USER_READ)(null, null, ctx);
    expect(v).toBeUndefined();
  });

});

describe('tokenCheck', () => {

  test('throw an error if there the token isnt the right type', async () => {
    const ctx = {
      token: {
        type: 'user',
      },
    };
    try {
      await tokenCheck('PASSWORD_RESET')(null, null, ctx);
    } catch (e) {
      expect(e).toEqual(new Error('Invalid Token'));
    }
  });

  test('whether the user has the permission', async () => {
     const ctx = {
      token: {
        type: 'PASSWORD_RESET',
      },
    };
    const v = await tokenCheck('PASSWORD_RESET')(null, null, ctx);
    expect(v).toBeUndefined();
  });

});


text:
package org.apache.camel.dataformat.beanio;

public class B1Record extends Record {
    String securityName;

    public B1Record() {
    }

    public B1Record(String sedol, String source, String securityName) {
        super(sedol, source);
        this.securityName = securityName;
    }

    public String getSecurityName() {
        return securityName;
    }

    public void setSecurityName(String securityName) {
        this.securityName = securityName;
    }

    @Override
    public int hashCode() {
        return securityName != null ? securityName.hashCode() : 0;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        } else if (obj == this) {
            return true;
        } else {
            B1Record record = (B1Record) obj;
            return super.equals(record) && this.securityName.equals(record.getSecurityName());
        }
    }

    @Override
    public String toString() {
        return "SEDOL[" + this.sedol + "], SOURCE[" + this.source + "], NAME[" + this.securityName + "]";
    }
}


text:
using System;
using System.Collections.Generic;
using SwitchAppDesign.AniListAPI.v2.Common;
using SwitchAppDesign.AniListAPI.v2.Graph.QueryBuilders;
using SwitchAppDesign.AniListAPI.v2.Graph.Types;

namespace SwitchAppDesign.AniListAPI.v2.Graph.Common
{
    /// <summary>
    /// A wrapper class for a graph query field.
    /// </summary>
    public class GraphQueryField
    {
        /// <summary>
        /// Initilizes an instance of a GraphQueryField.
        /// </summary>
        /// <param name="fieldName">Raw name of the field to be used in a graph query.</param>
        /// <param name="parentClassType">The class this fields belongs to.</param>
        /// <param name="allowedInQueryType">The query type this instance of graph query field is allowed to be used in.</param>
        /// <param name="rules">The rules and contraints to be applied to this field in a graph query.</param>
        public GraphQueryField(string fieldName, Type parentClassType, AniListQueryType allowedInQueryType, FieldRules rules)
        {
            FieldName = fieldName;
            ParentClassType = parentClassType;
            Rules = rules;
            AllowedInQueryType = allowedInQueryType;
        }

        /// <summary>
        /// Initilizes an instance of a GraphQueryField.
        /// </summary>
        /// <param name="fieldName">Raw name of the field to be used in a graph query.</param>
        /// <param name="parentClassType">The class this fields belongs to.</param>
        /// <param name="allowedInQueryType">The query type this instance of graph query field is allowed to be used in.</param>
        /// <param name="rules">The rules and contraints to be applied to this field in a graph query.</param>
        /// <param name="childFieldParentType">The parent class of the collection of fields accepted by this query field</param>
        public GraphQueryField(string fieldName, Type parentClassType, AniListQueryType allowedInQueryType, FieldRules rules, Type childFieldParentType)
        {
            FieldName = fieldName;
            ParentClassType = parentClassType;
            Rules = rules;
            AllowedInQueryType = allowedInQueryType;
            ChildFieldParentType = childFieldParentType;
        }

        /// <summary>
        /// Raw name of the field to be used in a graph query
        /// </summary>
        public string FieldName { get; }

        /// <summary>
        /// The class this fields belongs to.
        /// </summary>
        public Type ParentClassType { get; }

        /// <summary>
        /// The rules and contraints to be applied to this field in a graph query.
        /// </summary>
        public FieldRules Rules { get; }

        /// <summary>
        /// The arguments to be used in a graph query.
        /// </summary>
        public IEnumerable<object> Arguments { get; private set; }

        /// <summary>
        /// The fields to be used in a graph query.
        /// </summary>
        public IEnumerable<GraphQueryField> Fields { get; private set; }

        /// <summary>
        /// The query type this instance of graph query field is allowed to be used in.
        /// </summary>
        public AniListQueryType AllowedInQueryType { get; }

        /// <summary>
        /// The child field parent class.
        /// </summary>
        public Type ChildFieldParentType { get; }

        /// <summary>
        /// Gets the value of the GraphQLQueryField after setting the field arguments value.
        /// </summary>
        /// <param name="fields">The fields to be used in a graph query.</param>
        /// <param name="arguments">The arguments to be used in a graph query.</param>
        public GraphQueryField GetGraphFieldAndSetFieldArguments(IEnumerable<GraphQueryField> fields, IEnumerable<object> arguments = null)
        {
            SetFieldArguments(arguments);
            SetFields(fields);
            return this;
        }

        private void SetFieldArguments(IEnumerable<object> arguments)
        {
            Arguments = arguments;
        }

        private void SetFields(IEnumerable<GraphQueryField> fields)
        {
            Fields = fields;
        }

        /// <summary>
        /// Validates the current state of the query field according to its rules.
        /// </summary>
        /// <exception cref="GraphQueryFieldInvalidException">Thrown if the query field is in an invalid state.</exception>
        public void Validate(bool isAuthenticated)
        {
            if (Rules.AuthenticationRequired && !isAuthenticated)
            {
                throw new GraphQueryFieldInvalidException($"Field ({GetType().Name}) requires authentication to be accessed.");
            }
        }
    }
}

///// <summary>
///// A wrapper class for a graph query field.
///// TArgs: The arguments to be used in the graph query.
///// </summary>
//public class GraphQueryField<TArgs>
//{
//    /// <summary>
//    /// Initilizes an instance of a GraphQueryField.
//    /// </summary>
//    /// <param name="fieldName">Raw name of the field to be used in a graph query.</param>
//    /// <param name="rules">The rules and contraints to be applied to this field in a graph query.</param>
//    public GraphQueryField(string fieldName, FieldRules rules)
//    {
//        FieldName = fieldName;
//        Rules = rules;
//    }

//    /// <summary>
//    /// Raw name of the field to be used in a graph query.
//    /// </summary>
//    public string FieldName { get; }

//    /// <summary>
//    ///
//    /// </summary>
//    public IList<GraphQueryField> QueryFields { get; }

//    /// <summary>
//    /// The arguments to be used in the graph query.
//    /// </summary>
//    public TArgs FieldArgument { get; private set; }

//    /// <summary>
//    /// The rules and contraints to be applied to this field in a graph query.
//    /// </summary>
//    public FieldRules Rules { get; }

//    /// <summary>
//    /// Gets the value of the GraphQLQueryField after setting the field arguments value.
//    /// </summary>
//    /// <param name="value">The arguments to be used in a graph query.</param>
//    public GraphQueryField<TArgs> GetGraphFieldAndSetFieldArguments(TArgs value)
//    {
//        SetFieldArguments(value);
//        return this;
//    }

//    private void SetFieldArguments(TArgs value)
//    {
//        FieldArgument = value;
//    }

//    /// <summary>
//    /// Validates the current state of the query field according to its rules.
//    /// </summary>
//    /// <exception cref="GraphQueryFieldInvalidException">Thrown if the query field is in an invalid state.</exception>
//    public void IsValid(bool isAuthenticated)
//    {
//        if (Rules.AuthenticationRequired && !isAuthenticated)
//        {
//            throw new GraphQueryFieldInvalidException($"Field ({GetType().Name}) requires authentication to be accessed.");
//        }
//    }
//}


text:
using System;

namespace Azure.Management.Network.Models
{
    /// <summary> Parameters to compare with network configuration. </summary>
    public partial class NetworkConfigurationDiagnosticProfile
    {
        /// <summary> Initializes a new instance of NetworkConfigurationDiagnosticProfile. </summary>
        /// <param name="direction"> The direction of the traffic. </param>
        /// <param name="protocol"> Protocol to be verified on. Accepted values are '*', TCP, UDP. </param>
        /// <param name="source"> Traffic source. Accepted values are '*', IP Address/CIDR, Service Tag. </param>
        /// <param name="destination"> Traffic destination. Accepted values are: '*', IP Address/CIDR, Service Tag. </param>
        /// <param name="destinationPort"> Traffic destination port. Accepted values are '*' and a single port in the range (0 - 65535). </param>
        public NetworkConfigurationDiagnosticProfile(Direction direction, string protocol, string source, string destination, string destinationPort)
        {
            if (protocol == null)
            {
                throw new ArgumentNullException(nameof(protocol));
            }
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }
            if (destinationPort == null)
            {
                throw new ArgumentNullException(nameof(destinationPort));
            }

            Direction = direction;
            Protocol = protocol;
            Source = source;
            Destination = destination;
            DestinationPort = destinationPort;
        }

        /// <summary> The direction of the traffic. </summary>
        public Direction Direction { get; set; }
        /// <summary> Protocol to be verified on. Accepted values are '*', TCP, UDP. </summary>
        public string Protocol { get; set; }
        /// <summary> Traffic source. Accepted values are '*', IP Address/CIDR, Service Tag. </summary>
        public string Source { get; set; }
        /// <summary> Traffic destination. Accepted values are: '*', IP Address/CIDR, Service Tag. </summary>
        public string Destination { get; set; }
        /// <summary> Traffic destination port. Accepted values are '*' and a single port in the range (0 - 65535). </summary>
        public string DestinationPort { get; set; }
    }
}


text:
DELETE FROM `{table.users.permissions}`
WHERE `user_id` = '{0}' AND `permission_key` = '{1}';


text:
/*jshint expr: true*/
describe('rightclick', function() {

    before(h.setup());

    it('text should be visible after right-clicking on .btn1', function(done) {

        this.client
            .isVisible('.btn1_right_clicked', function(err,isVisible) {
                assert.ifError(err);
                isVisible.should.be.false;
            })
            .rightClick('.btn1')
            .isVisible('.btn1_right_clicked', function(err,isVisible) {
                assert.ifError(err);
                isVisible.should.be.true;
            })
            .call(done);

    });

});


text:
package org.vitrivr.cineast.core.metadata;

import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.vitrivr.cineast.core.data.entities.MultimediaMetadataDescriptor;
import org.vitrivr.cineast.core.util.json.JacksonJsonProvider;

public class JsonMetaDataExtractor implements MetadataExtractor {

  private static final JacksonJsonProvider jsonProvider = new JacksonJsonProvider();

  @Override
  public List<MultimediaMetadataDescriptor> extract(String objectId, Path path) {
    File file = path.toFile();
    File parent = file.getParentFile();
    File jsonFile = new File(parent, file.getName() + ".json");

    if(!jsonFile.exists()){
        jsonFile = new File(parent, com.google.common.io.Files.getNameWithoutExtension(file.getName()) + ".json");
    }

    if(!jsonFile.exists()){
      return new ArrayList<>(0);
    }

    @SuppressWarnings("unchecked")
    Map<String, Object> json = jsonProvider.toObject(jsonFile, Map.class);

    if(json == null || json.isEmpty()){
      return new ArrayList<>(0);
    }

    ArrayList<MultimediaMetadataDescriptor> _return = new ArrayList<>(json.size());

    Set<String> keys = json.keySet();

    for(String key : keys){
      _return.add(
          MultimediaMetadataDescriptor.of(objectId, domain(), key, json.get(key))
          );
    }

    return _return;
  }

  @Override
  public String domain() {
    return "JSON";
  }

}


text:
/** Defines helper functions for working with environment config values. */

/**
 * Checks that a config value is a non-empty string. The standard {@link process.env} produces
 * either a {@link string} or a {@link undefined}. This will allow the first case to pass, provided
 * that the string is non-empty, and will raise an application-stopping error in the second case.
 * @param name - the name of the config value.
 * @returns The value of the environment variable if it exists and is non-empty.
 * @throws If the value is missing or empty.
 */
export function getFromEnv(name: string): string {
    const value = process.env[name];

    if (typeof value == 'undefined') {
        throw Error(`Config value ${name} is not specified`);
    }

    const trimmedValue = value.trim();

    if (trimmedValue.length == 0) {
        throw Error(`Config value ${name} is not specified`);
    }

    return trimmedValue;
}


text:
package net.sf.mmm.util.nls.api;

/**
 * This is the marker interface for all "resource-bundles" for this native language support. Instead of a
 * {@link java.util.ResourceBundle} you create a custom interface extending this one in order to define the
 * {@link NlsMessage#getInternationalizedMessage() messages}. This is done by defining methods with {@link NlsMessage}
 * as return type and the {@link NlsMessage#getArgument(String) NLS argument values} as parameter.

 * NOTE:

 * You should NOT create an implementation of that interface as this is created for you automatically via
 * {@link NlsBundleFactory#createBundle(Class)}. This is the recommended approach for defining and binding
 * {@link NlsMessage}s. In order to make your {@link NlsBundle} work even in limited environments such as GWT (google
 * web toolkit) clients, we had to define the following convention:

 *

 *
For your bundle you define a {@link Package} and a base name (e.g. {@code my.package.NlsBundleExample}). This
 * namespace must not be occupied by an existing type.

 *
The interface you create and extend from {@link NlsBundle} has to be named using the base name followed by the
 * suffix {@link #INTERFACE_NAME_SUFFIX Root} (e.g. {@code my.package.NlsBundleExampleRoot}). This interface defines the
 * {@link NlsMessage}es for the {@link java.util.Locale#ROOT root locale} what is the reason for the suffix.

 *
Your localized {@code *.properties} files have to be named using the base name followed by the according locale
 * suffix as for a regular {@link java.util.ResourceBundle} (e.g. {@code my/package/NlsBundleExample_de.properties} or
 * {@code my/package/NlsBundleExample_zh_HK.properties}). To override the message texts for the root locale (e.g. as
 * customization of a {@link NlsBundle} provided by a third-party library) you could also create a properties file
 * without the locale suffix (e.g. {@code my/package/NlsBundleExample.properties})

 *

 * Here is an example:
 *
 *

 * public interface NlsBundleMynameRoot extends {@link NlsBundle} {
 *   {@literal @}{@link NlsBundleMessage}("The value {value} has to be in the range from {min} to {max}!")
 *   {@link NlsMessage} errorValueOutOfRange({@literal @}{@link javax.inject.Named}("value") int value,
 *            {@literal @}{@link javax.inject.Named}("min") int min, {@literal @}{@link javax.inject.Named}("max") int max);
 * }
 *

 *
 * For localization you create {@code *.properties} files (see
 * {@code net.sf.mmm.util.nls.base.ResourceBundleSynchronizer}) in the same package for each supported
 * {@link java.util.Locale}. In the example above e.g. {@code NlsBundleMyname_de.properties} with this content:
 *
 *

 * errorValueOutOfRange = Der Wert {value} muss innerhalb des Wertebereichs von {min} bis {max} liegen!
 *

 *
 * For a real example see {@link net.sf.mmm.util.NlsBundleUtilCoreRoot}.

 * IMPORTANT:

 * Unless annotated with {@link NlsBundleKey} the {@link java.util.ResourceBundle#getString(String) key} is derived from
 * the name of the method. You have to ensure that the keys are unique as otherwise the localization is NOT possible.
 * Please strictly avoid having methods with the same name.

 *

 * For maintenance and better support of localizers it is strongly recommended to use
 * {@link NlsMessage#getArgument(String) named arguments} instead of {@link NlsMessage#getArgument(int) indexed
 * arguments}. Unfortunately Java does not include names of parameters in abstract methods (including methods of
 * interfaces). Java8 introduced this feature that we might support in the future. Currently the only way to work around
 * this is to add an annotation to each parameter. The {@link NlsBundleFactory} therefore supports the
 * {@link javax.inject.Named} annotation for this purpose. As it is nasty to add these annotations manually here is a
 * script for automation. This is just an example - please add more types as needed.
 *
 *

 * sed -i -r 's/([(]|, )((Object|Type|int|Number|String|boolean)([.]{3})?) ([a-z][a-zA-Z0-9]*)/\1@Named("\5") \2 \5/g' NlsBundleExampleRoot.java
 *

 *
 * ATTENTION:

 * It is strongly recommended NOT to use inheritance for {@link NlsBundle} interfaces. Instead create an interface that
 * directly extends {@link NlsBundle} (and nothing else). However, for purpose of abstraction feel free to add an empty
 * custom extension of {@link NlsBundle} as intermediate interface for your project to decouple dependencies.
 *
 * @see NlsBundleMessage
 * @see NlsBundleKey
 *
 * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
 * @since 3.0.0
 */
@SuppressWarnings("javadoc")
public abstract interface NlsBundle {

  /** The suffix for the interfaces derived from {@link NlsBundle}. This suffix will not change in the future. */
  String INTERFACE_NAME_SUFFIX = "Root";

}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Equipmentrental = mongoose.model('Equipmentrental'),
	_ = require('lodash');

/**
 * Create a Equipmentrental
 */
exports.create = function(req, res) {
	var equipmentrental = new Equipmentrental(req.body);
	equipmentrental.user = req.user;

	equipmentrental.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(equipmentrental);
		}
	});
};

/**
 * Show the current Equipmentrental
 */
exports.read = function(req, res) {
	res.jsonp(req.equipmentrental);
};

/**
 * Update a Equipmentrental
 */
exports.update = function(req, res) {
	var equipmentrental = req.equipmentrental ;

	equipmentrental = _.extend(equipmentrental , req.body);

	equipmentrental.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(equipmentrental);
		}
	});
};

/**
 * Delete an Equipmentrental
 */
exports.delete = function(req, res) {
	var equipmentrental = req.equipmentrental ;

	equipmentrental.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(equipmentrental);
		}
	});
};

/**
 * List of Equipmentrentals
 */
exports.list = function(req, res) {
	Equipmentrental.find().sort('-created').populate('user', 'displayName').exec(function(err, equipmentrentals) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(equipmentrentals);
		}
	});
};

/**
 * Equipmentrental middleware
 */
exports.equipmentrentalByID = function(req, res, next, id) {
	Equipmentrental.findById(id).populate('user', 'displayName').exec(function(err, equipmentrental) {
		if (err) return next(err);
		if (! equipmentrental) return next(new Error('Failed to load Equipmentrental ' + id));
		req.equipmentrental = equipmentrental ;
		next();
	});
};

/**
 * Equipmentrental authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.equipmentrental.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};


text:
Ingo Hoffmann

## Perfil

Mentor para Desenvolvedores Java, backend, devops e sistemas operacionais.

## Links

* [GitHub](https://github.com/lasombra)
* [Twitter](https://twitter.com/lasombra_br)


text:
/**
 * Created by kaidi on 2016/10/18.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    TouchableOpacity,
    requireNativeComponent,
} from 'react-native';

var UIText = requireNativeComponent('KDView', KDView);

var KDView = React.createClass({
    render(){
        return(
                    <UIText style={{flex : 1,backgroundColor:'green'}}></UIText>
        );
    },

});

const styles = StyleSheet.create({
    viewS : {
        flex : 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
});

module.exports = KDView;


text:
define("dojox/grid/enhanced/_Plugin", [
	"dojo/_base/kernel",
	"dojo/_base/lang",
	"dojo/_base/declare",
	"dojo/_base/array",
	"dojo/_base/connect",
    "../EnhancedGrid"
], function(dojo, lang, declare, array, connect){

return declare("dojox.grid.enhanced._Plugin", null, {
	// summary:
	//		Base class for all plugins.
	// description:
	//		Provides common plugin functionality and basic life cycle management.
	//
	//		Each concrete plugin must have a name field and is responsible for registering itself to the global plugin registry
	//		e.g. for dnd plugin:
	// |		dojox.grid.EnhancedGrid.registerPlugin("dnd" /*plugin name*/,
	// |												dojox.grid.enhanced.plugins.DnD /*full class name of a plugin*/
	// |												{"preInit": false, "dependency": ["nestedSorting"]} /*properties*/);
	//
	//		[Keywords] of plugin properties (case sensitive):
	//
	//		- "preInit": boolean, whether a plugin should be created before EnhancedGrid.postCreate(),
	//		   false by default(plugins are created after EnhancedGrid.postCreate()).
	//		- "dependency": array or string, plugin(s) indicated by "dependency" will be created before the current one.
	//		   Note: recursive cycle dependencies are not supported e.g. following dependency is invalid:
	//		   pluginA -> pluginB -> pluginA
	//
	// example:
	//		1. Customize default DnD plugin
	//
	// |	declare("mygrid.MyDnD", dojox.grid.enhanced.plugins.DnD, {
	// |		name:"dnd" //still reuse the plugin name
	// |		constructor: function(inGrid, option){ ... }
	// |	});
	// |	dojox.grid.EnhancedGrid.registerPlugin("dnd", mygrid.MyDnD);
	//
	//		2. Add new plugin - PluginA
	//
	// |	declare("mygrid.PluginA", dojox.grid.enhanced._Plugin, {
	// |		name: "pA",
	// |		constructor: function(inGrid, option){ ... }
	// |	});
	// |	dojox.grid.EnhancedGrid.registerPlugin("pA",mygrid.PluginA);
	//
	//		3. Use plugins
	//
	// |	dojo.require("mygrid.MyDnD");
	// |	dojo.require("mygrid.PluginA");
	// |
	// |	<script type="text/javascript">
	// |		var grid = new dojox.grid.EnhancedGrid(
	// |		{plugins: {dnd:true, pA:true}, ... }, dojo.byId("gridDiv"));
	// |		grid.startup();
	// |	</script>

	// name: String
	//		Plugin name, e.g. 'nestedSorting', 'dnd'...
	name: 'plugin',

	// grid: Object
	//		Grid that the plugin belongs to
	grid: null,

	// option: Object
	//		Plugin properties - leveraged with default and user specified properties.
	//		e.g. for dnd plugin, it may look like {"class": dojox.grid.enhanced.plugins.DnD, "dependency": ["nestedSorting"], ...}
	option: {},

	// _connects: Array
	//		List of all connections.
	_connects: [],

	// _subscribes: Array
	//		List of all subscribes.
	_subscribes: [],

	// privates: Object
	//		Private properties/methods shouldn't be mixin-ed anytime.
	privates: {},

	constructor: function(inGrid, option){
		this.grid = inGrid;
		this.option = option;
		this._connects = [];
		this._subscribes = [];
		this.privates = lang.mixin({},dojox.grid.enhanced._Plugin.prototype);
		this.init();
	},

	init: function(){},

	onPreInit: function(){},

	onPostInit: function(){},

	onStartUp: function(){},

	connect: function(obj, event, method){
		// summary:
		//		Connects specified obj/event to specified method of this object.
		// example:
		//	|	var plugin = new dojox.grid.enhanced._Plugin(grid,"myPlugin",{...});
		//	|	// when foo.bar() is called, call the listener in the scope of plugin
		//	|	plugin.connect(foo, "bar", function(){
		//	|		console.debug(this.xxx());//"this" - plugin scope
		//	|	});
		var conn = connect.connect(obj, event, this, method);
		this._connects.push(conn);
		return conn;
	},
	disconnect: function(handle){
		// summary:
		//		Disconnects handle and removes it from connection list.
		array.some(this._connects, function(conn, i, conns){
			if(conn == handle){
				connect.disconnect(handle);
				conns.splice(i, 1);
				return true;
			}
			return false;
		});
	},
	subscribe: function(topic, method){
		// summary:
		//		Subscribes to the specified topic and calls the specified method
		//		of this object.
		// example:
		//	|	var plugin = new dojox.grid.enhanced._Plugin(grid,"myPlugin",{...});
		//	|	// when /my/topic is published, call the subscriber in the scope of plugin
		//	|	// with passed parameter - "v"
		//	|	plugin.subscribe("/my/topic", function(v){
		//	|		console.debug(this.xxx(v));//"this" - plugin scope
		//	|	});
		var subscribe = connect.subscribe(topic, this, method);
		this._subscribes.push(subscribe);
		return subscribe;
	},
	unsubscribe: function(handle){
		// summary:
		//		Un-subscribes handle and removes it from subscriptions list.
		array.some(this._subscribes, function(subscribe, i, subscribes){
			if(subscribe == handle){
				connect.unsubscribe(handle);
				subscribes.splice(i, 1);
				return true;
			}
			return false;
		});
	},
	onSetStore: function(store){
		// summary:
		//		Called when store is changed.
	},
	destroy: function(){
		// summary:
		//		Destroy all resources.
		array.forEach(this._connects, connect.disconnect);
		array.forEach(this._subscribes, connect.unsubscribe);
		delete this._connects;
		delete this._subscribes;
		delete this.option;
		delete this.privates;
		//console.log('Plugin [', this.name, '].destroy() executed!');
	}
});

//Each plugin is responsible for registering itself
// e.g. for DnD plugin(name:'dnd'):
// |	dojox.grid.EnhancedGrid.registerPlugin(dojox.grid.enhanced.plugins.DnD/*class*/,
// |		{"dependency": ["nestedSorting"]}/*Optional - properties*/);

});


text:
<?php

namespace Sdz\BlogBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Tools\Pagination\Paginator;

/**
 * ArticleRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ArticleRepository extends EntityRepository
{

  public function getArticles($nombreParPage,$page)
  {

  if ($page < 1) {
      throw new \InvalidArgumentException('L\'argument $page ne peut être inférieur à 1 (valeur : "'.$page.'").');
    }

    $query = $this->createQueryBuilder('a')
		//Joint sur attri image
		->leftJoin('a.image','i')
		->addSelect('i')
		//Joint attri catego
		->leftJoin('a.categories','c')
		->addSelect('c')
                ->orderBy('a.date', 'DESC')
                ->getQuery();
 // On définit l'article à partir duquel commencer la liste
    $query->setFirstResult(($page-1) * $nombreParPage)
    // Ainsi que le nombre d'articles à afficher
          ->setMaxResults($nombreParPage);

    // Enfin, on retourne l'objet Paginator correspondant à la requête construite
    // (n'oubliez pas le use correspondant en début de fichier)
    return new Paginator($query);

  }

}


text:
cask "springtoolsuite" do
  version "4.11.1,4.20.0"
  sha256 "6aae95483104417b61f25754fdd3f38724fda17e25535382fdc60203d8576427"

  url "https://download.springsource.com/release/STS#{version.major}/#{version.before_comma}.RELEASE/dist/e#{version.after_comma.major_minor}/spring-tool-suite-#{version.major}-#{version.before_comma}.RELEASE-e#{version.after_comma}-macosx.cocoa.x86_64.dmg",
      verified: "download.springsource.com/release/"
  name "Spring Tool Suite"
  desc "Next generation tooling for Spring Boot"
  homepage "https://spring.io/tools"

  livecheck do
    url :homepage
    strategy :page_match do |page|
      match = page.match(
        %r{href=.*?/spring-tool-suite-\d+-(\d+(?:\.\d+)*)\.RELEASE-e(\d+(?:\.\d+)*)-macosx\.cocoa\.x86_64\.dmg}i,
      )
      "#{match[1]},#{match[2]}"
    end
  end

  auto_updates true

  app "SpringToolSuite#{version.major}.app"
end


text:
static inline LSStubRequestDSL *stubAnyRequest() {
    NSError *regexError;
    NSRegularExpression *anyRequestRegex =
        [NSRegularExpression regularExpressionWithPattern:@".*"
                                                  options:0
                                                    error:&regexError];
    NSCParameterAssert(!regexError);
    return stubRequest(@"GET", anyRequestRegex);
}