text:
package org.xtreemfs.utils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.xtreemfs.common.uuids.ServiceUUID;
import org.xtreemfs.common.uuids.UUIDResolver;
import org.xtreemfs.dir.DIRClient;
import org.xtreemfs.foundation.SSLOptions;
import org.xtreemfs.foundation.TimeSync;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.logging.Logging.Category;
import org.xtreemfs.foundation.pbrpc.Schemes;
import org.xtreemfs.foundation.pbrpc.client.RPCNIOSocketClient;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.Auth;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.AuthPassword;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.AuthType;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.UserCredentials;
import org.xtreemfs.foundation.util.CLIParser;
import org.xtreemfs.foundation.util.CLIParser.CliOption;
import org.xtreemfs.foundation.util.OutputUtils;
import org.xtreemfs.osd.drain.OSDDrain;
import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceSet;
import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceType;
import org.xtreemfs.pbrpc.generatedinterfaces.DIRServiceClient;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.PORTS;
import org.xtreemfs.pbrpc.generatedinterfaces.MRCServiceClient;
import org.xtreemfs.pbrpc.generatedinterfaces.OSDServiceClient;

public class xtfs_remove_osd {

    private OSDServiceClient   osd;
    private DIRClient          dir;
    private MRCServiceClient   mrc;
    private RPCNIOSocketClient dirClient;
    private RPCNIOSocketClient osdClient;
    private RPCNIOSocketClient mrcClient;
    private InetSocketAddress  osdAddr;
    private InetSocketAddress  mrcAddr;
    private SSLOptions         sslOptions;
    private String[]           dirAddresses;
    private UUIDResolver       resolver;
    private RPCNIOSocketClient resolverClient;
    private Auth               authHeader;
    private UserCredentials    credentials;
    private String             osdUUIDString;
    private ServiceUUID        osdUUID;

    public static void main(String[] args) {

        Map<String, CliOption> options = null;
        try {
            // parse the call arguments
            options = utils.getDefaultAdminToolOptions(true);
            List<String> arguments = new ArrayList<String>(1);

            CliOption oDir = new CliOption(CliOption.OPTIONTYPE.STRING,
                    "directory service to use (e.g. 'pbrpc://localhost:32638')", "<uri>");
            oDir.urlDefaultPort = PORTS.DIR_PBRPC_PORT_DEFAULT.getNumber();
            oDir.urlDefaultProtocol = Schemes.SCHEME_PBRPC;
            options.put("dir", oDir);
            options.put("s", new CliOption(CliOption.OPTIONTYPE.SWITCH, "shutdown OSD", ""));
            options.put("d", new CliOption(CliOption.OPTIONTYPE.SWITCH, "enbable debug output", ""));
            CLIParser.parseCLI(args, options, arguments);

            // start logging
            if (options.get("d").switchValue) {
                Logging.start(Logging.LEVEL_DEBUG);
            } else {
                Logging.start(Logging.LEVEL_ERROR);
            }

            if (options.get(utils.OPTION_HELP).switchValue || options.get(utils.OPTION_HELP_LONG).switchValue
                    || arguments.size() == 0) {
                usage(options);
                return;
            }

            if (arguments.size() > 1) {
                // print error.
                error("invalid number of arguments", options, true);
            }

            boolean shutdown = options.get("s").switchValue;
            String password = (options.get(utils.OPTION_ADMIN_PASS).stringValue != null) ? options
                    .get(utils.OPTION_ADMIN_PASS).stringValue : "";

            String[] dirURLs = (options.get("dir").stringValue != null) ? options.get("dir").stringValue
                    .split(",") : null;

            // read default settings for the OSD
            String osdUUID = null;
            if (arguments.get(0).startsWith("uuid:")) {
                osdUUID = arguments.get(0).substring("uuid:".length());
            } else {
                error("There was no UUID for the OSD given!", options);
            }

            SSLOptions sslOptions = null;
            String[] dirAddrs = null;

            // parse security info if protocol is 'https'
            if (dirURLs != null) {
                int i = 0;
                boolean gridSSL = false;
                dirAddrs = new String[dirURLs.length];
                for (String dirURL : dirURLs) {

                    // parse security info if protocol is 'https'
                    if (dirURL.contains(Schemes.SCHEME_PBRPCS + "://")
                            || dirURL.contains(Schemes.SCHEME_PBRPCG + "://") && sslOptions == null) {
                        String serviceCredsFile = options.get(utils.OPTION_USER_CREDS_FILE).stringValue;
                        String serviceCredsPass = options.get(utils.OPTION_USER_CREDS_PASS).stringValue;
                        if(serviceCredsPass != null && serviceCredsPass.equals("-")) {
                        	serviceCredsPass = new String(System.console().readPassword("Enter credentials password: "));
                        }
                        String trustedCAsFile = options.get(utils.OPTION_TRUSTSTORE_FILE).stringValue;
                        String trustedCAsPass = options.get(utils.OPTION_TRUSTSTORE_PASS).stringValue;
                        if(trustedCAsPass != null && trustedCAsPass.equals("-")) {
                        	trustedCAsPass = new String(System.console().readPassword("Enter trust store password: "));
                        }
                        String sslProtocolString = options.get(utils.OPTION_SSL_PROTOCOL).stringValue;
                        if (dirURL.contains(Schemes.SCHEME_PBRPCG + "://")) {
                            gridSSL = true;
                        }

                        if (serviceCredsFile == null) {
                            System.out.println("SSL requires '-" + utils.OPTION_USER_CREDS_FILE
                                    + "' parameter to be specified");
                            usage(options);
                            System.exit(1);
                        } else if (trustedCAsFile == null) {
                            System.out.println("SSL requires '-" + utils.OPTION_TRUSTSTORE_FILE
                                    + "' parameter to be specified");
                            usage(options);
                            System.exit(1);
                        }

                        // TODO: support custom SSL trust managers
                        try {
                            sslOptions = new SSLOptions(serviceCredsFile, serviceCredsPass,
                                    SSLOptions.PKCS12_CONTAINER, trustedCAsFile, trustedCAsPass,
                                    SSLOptions.JKS_CONTAINER, false, gridSSL, sslProtocolString, null);
                        } catch (Exception e) {
                            System.err.println("unable to get SSL options, because:" + e.getMessage());
                            System.exit(1);
                        }
                    }

                    // add URL to dirAddrs
                    if (dirURL.contains("://")) {
                        // remove Protocol information
                        String[] tmp = dirURL.split("://");
                        // remove possible slash
                        dirAddrs[i++] = tmp[1].replace("/", "");
                    } else {
                        // remove possible slash
                        dirAddrs[i++] = dirURL.replace("/", "");
                    }
                }
            }

            // read default settings
            if (dirURLs == null) {
                try {
                    DefaultDirConfig cfg = new DefaultDirConfig();
                    sslOptions = cfg.getSSLOptions();
                    dirAddrs = cfg.getDirectoryServices();
                } catch (Exception e) {
                    System.err.println("unable to get SSL options, because: " + e.getMessage());
                    System.exit(1);
                }
            }

            xtfs_remove_osd removeOsd = new xtfs_remove_osd(dirAddrs, osdUUID, sslOptions, password);
            removeOsd.initialize();
            removeOsd.drainOSD(shutdown);
            removeOsd.shutdown();

            System.exit(0);

        } catch (Exception e) {

            error(e.getMessage(), options);
        }
    }

    public xtfs_remove_osd(String[] dirAddresses, String osdUUIDString, SSLOptions sslOptions, String password)
            throws Exception {
        try {

            this.sslOptions = sslOptions;
            this.dirAddresses = dirAddresses;
            this.osdUUIDString = osdUUIDString;
            if (password.equals("")) {
                this.authHeader = Auth.newBuilder().setAuthType(AuthType.AUTH_NONE).build();
            } else {
                this.authHeader = Auth.newBuilder().setAuthType(AuthType.AUTH_PASSWORD)
                        .setAuthPasswd(AuthPassword.newBuilder().setPassword(password).build()).build();
            }

            // TODO: use REAL user credentials (this is a SECURITY HOLE)
            this.credentials = UserCredentials.newBuilder().setUsername("root").addGroups("root").build();

        } catch (Exception e) {
            shutdown();
            throw e;
        }
    }

    public void initialize() throws Exception {

        TimeSync.initializeLocal(0);

        // TODO(lukas): support multiple DIRs
        // connect to DIR
        dirClient = new RPCNIOSocketClient(sslOptions, 10000, 5 * 60 * 1000, "xtfs_remove_osd (dir)");
        dirClient.start();
        dirClient.waitForStartup();
        String[] dirAddr = dirAddresses[0].split(":");
        InetSocketAddress dirSocketAddr = new InetSocketAddress(dirAddr[0], Integer.parseInt(dirAddr[1]));
        DIRServiceClient tmp = new DIRServiceClient(dirClient, dirSocketAddr);
        dir = new DIRClient(tmp, new InetSocketAddress[] { dirSocketAddr }, 100, 15 * 1000);

        resolverClient = new RPCNIOSocketClient(sslOptions, 10000, 5 * 60 * 1000, "xtfs_remove_osd (resolver)");
        resolverClient.start();
        resolverClient.waitForStartup();
        this.resolver = UUIDResolver.startNonSingelton(dir, 1000, 10 * 10 * 1000);

        // create OSD client
        osdUUID = new ServiceUUID(osdUUIDString, resolver);
        osdUUID.resolve();
        osdAddr = osdUUID.getAddress();

        osdClient = new RPCNIOSocketClient(sslOptions, 10000, 5 * 60 * 1000, "xtfs_remove_osd (osd)");
        osdClient.start();
        osdClient.waitForStartup();
        osd = new OSDServiceClient(osdClient, osdAddr);

        // create MRC client
        ServiceSet sSet = null;
        try {
            sSet = dir.xtreemfs_service_get_by_type(null, authHeader, credentials,
                    ServiceType.SERVICE_TYPE_MRC);
        } catch (IOException ioe) {
            Logging.logMessage(Logging.LEVEL_WARN, Category.proc, new Object(),
                    OutputUtils.stackTraceToString(ioe));
            throw ioe;
        }

        mrcClient = new RPCNIOSocketClient(sslOptions, 100000, 5 * 60 * 10000, "xtfs_remove_osd (mrc)");
        mrcClient.start();
        mrcClient.waitForStartup();

        if (sSet.getServicesCount() == 0) {
            throw new IOException("No MRC is currently registred at DIR");
        }

        String mrcUUID = sSet.getServices(0).getUuid();
        ServiceUUID UUIDService = new ServiceUUID(mrcUUID, resolver);
        UUIDService.resolve();
        mrcAddr = UUIDService.getAddress();

        mrc = new MRCServiceClient(mrcClient, mrcAddr);

    }

    public void shutdown() {
        try {
            resolverClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Removes (drain) an OSD.
     *
     * @throws Exception
     */
    public void drainOSD(boolean shutdown) throws Exception {
        OSDDrain osdDrain = new OSDDrain(dir, osd, mrc, osdUUID, authHeader, credentials, resolver);
        osdDrain.drain(shutdown);
    }

    /**
     * Prints the error message and delegates to usage() if "printUsage" is true.
     *
     * @param message
     *            The error message
     * @param options
     *            The CLI Options.
     * @param printUsage
     *            True if usage should be printed. False otherwise.
     *
     */
    private static void error(String message, Map<String, CliOption> options, boolean printUsage) {
        System.err.println(message);

        if (printUsage) {
            System.out.println();
            usage(options);
        }
        System.exit(1);
    }

    /**
     * Prints the error message and delegates to usage().
     *
     * @param message
     *            The error message
     * @param options
     *            The CLI Options.
     */
    private static void error(String message, Map<String, CliOption> options) {
        error(message, options, false);
    }

    public static void usage(Map<String, CliOption> options) {

        System.out.println("usage: xtfs_remove_osd [options] uuid:<osd_uuid>\n");
        System.out.println("  " + "<osd_uuid> the unique identifier of the OSD to be removed\n");
        System.out.println("  " + "options:");

        utils.printOptions(options);
    }
}


text:
#include <stdlib.h>
#include <pthread.h>

#include <cutils/log.h>
#include <cutils/properties.h>

#include <utils/CallStack.h>

#include <EGL/egl.h>

#include "egl_tls.h"

namespace android {

pthread_key_t egl_tls_t::sKey = TLS_KEY_NOT_INITIALIZED;
pthread_once_t egl_tls_t::sOnceKey = PTHREAD_ONCE_INIT;

egl_tls_t::egl_tls_t()
    : error(EGL_SUCCESS), ctx(0), logCallWithNoContext(EGL_TRUE) {
}

const char *egl_tls_t::egl_strerror(EGLint err) {
    switch (err) {
        case EGL_SUCCESS:               return "EGL_SUCCESS";
        case EGL_NOT_INITIALIZED:       return "EGL_NOT_INITIALIZED";
        case EGL_BAD_ACCESS:            return "EGL_BAD_ACCESS";
        case EGL_BAD_ALLOC:             return "EGL_BAD_ALLOC";
        case EGL_BAD_ATTRIBUTE:         return "EGL_BAD_ATTRIBUTE";
        case EGL_BAD_CONFIG:            return "EGL_BAD_CONFIG";
        case EGL_BAD_CONTEXT:           return "EGL_BAD_CONTEXT";
        case EGL_BAD_CURRENT_SURFACE:   return "EGL_BAD_CURRENT_SURFACE";
        case EGL_BAD_DISPLAY:           return "EGL_BAD_DISPLAY";
        case EGL_BAD_MATCH:             return "EGL_BAD_MATCH";
        case EGL_BAD_NATIVE_PIXMAP:     return "EGL_BAD_NATIVE_PIXMAP";
        case EGL_BAD_NATIVE_WINDOW:     return "EGL_BAD_NATIVE_WINDOW";
        case EGL_BAD_PARAMETER:         return "EGL_BAD_PARAMETER";
        case EGL_BAD_SURFACE:           return "EGL_BAD_SURFACE";
        case EGL_CONTEXT_LOST:          return "EGL_CONTEXT_LOST";
        default: return "UNKNOWN";
    }
}

void egl_tls_t::validateTLSKey()
{
    struct TlsKeyInitializer {
        static void create() {
            pthread_key_create(&sKey, (void (*)(void*))&eglReleaseThread);
        }
    };
    pthread_once(&sOnceKey, TlsKeyInitializer::create);
}

void egl_tls_t::setErrorEtcImpl(
        const char* caller, int line, EGLint error, bool quiet) {
    validateTLSKey();
    egl_tls_t* tls = getTLS();
    if (tls->error != error) {
        if (!quiet) {
            ALOGE("%s:%d error %x (%s)",
                    caller, line, error, egl_strerror(error));
            char value[PROPERTY_VALUE_MAX];
            property_get("debug.egl.callstack", value, "0");
            if (atoi(value)) {
                CallStack stack(LOG_TAG);
            }
        }
        tls->error = error;
    }
}

bool egl_tls_t::logNoContextCall() {
    egl_tls_t* tls = getTLS();
    if (tls->logCallWithNoContext == true) {
        tls->logCallWithNoContext = false;
        return true;
    }
    return false;
}

egl_tls_t* egl_tls_t::getTLS() {
    egl_tls_t* tls = (egl_tls_t*)pthread_getspecific(sKey);
    if (tls == 0) {
        tls = new egl_tls_t;
        pthread_setspecific(sKey, tls);
    }
    return tls;
}

void egl_tls_t::clearTLS() {
    if (sKey != TLS_KEY_NOT_INITIALIZED) {
        egl_tls_t* tls = (egl_tls_t*)pthread_getspecific(sKey);
        if (tls) {
            pthread_setspecific(sKey, 0);
            delete tls;
        }
    }
}

void egl_tls_t::clearError() {
    // This must clear the error from all the underlying EGL implementations as
    // well as the EGL wrapper layer.
    eglGetError();
}

EGLint egl_tls_t::getError() {
    if (sKey == TLS_KEY_NOT_INITIALIZED) {
        return EGL_SUCCESS;
    }
    egl_tls_t* tls = (egl_tls_t*)pthread_getspecific(sKey);
    if (!tls) {
        return EGL_SUCCESS;
    }
    EGLint error = tls->error;
    tls->error = EGL_SUCCESS;
    return error;
}

void egl_tls_t::setContext(EGLContext ctx) {
    validateTLSKey();
    getTLS()->ctx = ctx;
}

EGLContext egl_tls_t::getContext() {
    if (sKey == TLS_KEY_NOT_INITIALIZED) {
        return EGL_NO_CONTEXT;
    }
    egl_tls_t* tls = (egl_tls_t *)pthread_getspecific(sKey);
    if (!tls) return EGL_NO_CONTEXT;
    return tls->ctx;
}

} // namespace android

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe "company_businesses/edit" do
  before(:each) do
    @company_business = assign(:company_business, stub_model(CompanyBusiness,
      :name => "MyString",
      :enabled => false
    ))
  end

  it "renders the edit company_business form" do
    render

    # Run the generator again with the --webrat flag if you want to use webrat matchers
    assert_select "form", :action => company_businesses_path(@company_business), :method => "post" do
      assert_select "input#company_business_name", :name => "company_business[name]"
      assert_select "input#company_business_enabled", :name => "company_business[enabled]"
    end
  end
end


text:
package queues;

import java.util.Iterator;
import java.util.NoSuchElementException;
import edu.princeton.cs.algs4.StdRandom;

/*************************************************************************
 * Name: Yulian Zhou
 * Email: zhouyulian17@gmail.com
 *
 * Compilation:  javac RandomizedQueue.java
 * Execution:    java RandomizedQueue
 * Dependencies: StdRandom.java
 *
 * Description:  A randomized queue where item is sampled/removed/iterated
 *               by random order.
 * http://coursera.cs.princeton.edu/algs4/assignments/queues.html
 *
 *************************************************************************/

public class RandomizedQueue<Item> implements Iterable<Item> {

    private int N = 0;       // number of items on queue
    private Item[] rdque;    // rdque[i] = the ith item on the randomized queue

    /**
     * Construct an empty randomized queue.
     */
    public RandomizedQueue() { rdque = (Item[]) new Object[1]; }

    /**
     * Returns true if queue is empty.
     */
    public boolean isEmpty() { return N == 0; }

    /**
     * Return the number of items on the queue.
     */
    public int size() { return N; }

    /**
     * Adds item to the queue, if full, increases size by 2 fold.
     */
    public void enqueue(Item item) {
        if (item == null) { throw new NullPointerException(); }
        if (N == rdque.length) resize(2 * rdque.length);
        rdque [N++] = item;
    }

    /**
     * Removes item from the queue, if 1/4 full, decreases size to 1/2.
     */
    public Item dequeue() {
        if (isEmpty()) { throw new NoSuchElementException(); }
        int r = StdRandom.uniform(N);
        Item item = rdque[r];
        rdque[r] = rdque[--N];
        rdque[N] = null;
        if (N > 0 && N == rdque.length/4) resize(rdque.length/2);
        return item;
    }

    // resize the queue
    private void resize(int capacity) {
        Item[] copy = (Item[]) new Object[capacity];
        for (int i = 0; i < N; i++) {
            copy[i] = rdque[i];
        }
        rdque = copy;
    }

    /**
     * Returns a random item from the queue.
     */
    public Item sample() {
        if (isEmpty()) { throw new NoSuchElementException(); }
        int r = StdRandom.uniform(N);
        return rdque[r];
    }

    /**
     * Returns an iterator that iterates over the items in this queue in random order.
     */
    public Iterator<Item> iterator() { return new RandomIterator(); }

    // an iterator
    private class RandomIterator implements Iterator<Item> {
        private Item[] temp;
        private int n;

        public RandomIterator() {
            n = N;
            temp = (Item[]) new Object[n];
            for (int i = 0; i < n; i++) {
                temp[i] = rdque[i];
            }
            StdRandom.shuffle(temp);
        }

        public boolean hasNext() { return n != 0; }
        public void remove() { throw new UnsupportedOperationException(); }

        public Item next() {
            if (hasNext()) return temp[--n];
            else { throw new NoSuchElementException(); }
        }
    }

    public static void main(String[] args) {

        // unit testing
        RandomizedQueue<String> rdque = new RandomizedQueue<String>();
        for (int i = 0; i < 10; i++) {
            rdque.enqueue(Integer.toString(i));
        }
        Iterator<String> it1 = rdque.iterator();
        //rdque.dequeue();
        Iterator<String> it2 = rdque.iterator();
        while (it1.hasNext()) {
            System.out.printf("%s %s \n", it1.next(), it2.next());
        }
    }
}


text:
require 'test_helper'

class ProfissionalTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
set -e  # If occur any error, exit
set -x  # Verbose mode

continuous_delivery/build.sh

$GAE_SDK/appcfg.py update build --email=$BOT_EMAIL --passin <<<"$BOT_PASSWORD"

$GAE_SDK/appcfg.py set_default_version build --email=$BOT_EMAIL --passin <<<"$BOT_PASSWORD"


text:
using Xamarin.Forms;

namespace AudioPlayTest.Views
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
    }
}


text:
package opennlp.tools.cmdline.sentdetect;

import java.io.IOException;

import opennlp.tools.cmdline.AbstractCrossValidatorTool;
import opennlp.tools.cmdline.CmdLineUtil;
import opennlp.tools.cmdline.TerminateToolException;
import opennlp.tools.cmdline.params.CVParams;
import opennlp.tools.cmdline.sentdetect.SentenceDetectorCrossValidatorTool.CVToolParams;
import opennlp.tools.dictionary.Dictionary;
import opennlp.tools.sentdetect.SDCrossValidator;
import opennlp.tools.sentdetect.SentenceDetectorEvaluationMonitor;
import opennlp.tools.sentdetect.SentenceDetectorFactory;
import opennlp.tools.sentdetect.SentenceSample;
import opennlp.tools.sentdetect.SentenceSampleStream;
import opennlp.tools.util.eval.FMeasure;
import opennlp.tools.util.model.ModelUtil;

public final class SentenceDetectorCrossValidatorTool
    extends AbstractCrossValidatorTool<SentenceSample, CVToolParams> {

  interface CVToolParams extends TrainingParams, CVParams {
  }

  public SentenceDetectorCrossValidatorTool() {
    super(SentenceSample.class, CVToolParams.class);
  }

  public String getShortDescription() {
    return "K-fold cross validator for the learnable sentence detector";
  }

  public void run(String format, String[] args) {
    super.run(format, args);

    mlParams = CmdLineUtil.loadTrainingParameters(params.getParams(), false);
    if (mlParams == null) {
      mlParams = ModelUtil.createDefaultTrainingParameters();
    }

    SDCrossValidator validator;

    SentenceDetectorEvaluationMonitor errorListener = null;
    if (params.getMisclassified()) {
      errorListener = new SentenceEvaluationErrorListener();
    }

    char[] eos = null;
    if (params.getEosChars() != null) {
      String eosString = SentenceSampleStream.replaceNewLineEscapeTags(params.getEosChars());
      eos = eosString.toCharArray();
    }

    try {
      Dictionary abbreviations = SentenceDetectorTrainerTool.loadDict(params.getAbbDict());
      SentenceDetectorFactory sdFactory = SentenceDetectorFactory.create(
          params.getFactory(), params.getLang(), true, abbreviations, eos);
      validator = new SDCrossValidator(params.getLang(), mlParams, sdFactory,
          errorListener);

      validator.evaluate(sampleStream, params.getFolds());
    }
    catch (IOException e) {
      throw new TerminateToolException(-1, "IO error while reading training data or indexing data: " +
          e.getMessage(), e);
    }
    finally {
      try {
        sampleStream.close();
      } catch (IOException e) {
        // sorry that this can fail
      }
    }

    FMeasure result = validator.getFMeasure();

    System.out.println(result.toString());
  }
}


text:
namespace {

// checkForNoMissingOps() is an unused function that simply exists to try and
// detect missing opcodes in "SpirvShaderInstructions.inl".
// If there are missing opcodes, then some compilers will warn that not all
// enum values are handled by the switch case below.
constexpr void checkForNoMissingOps(spv::Op op)
{
	// self-reference to avoid unused-function warnings.
	(void)&checkForNoMissingOps;

	switch(op)
	{
#define DECORATE_OP(isStatement, op) \
	case spv::op:                    \
		return;
#include "SpirvShaderInstructions.inl"
#undef DECORATE_OP
	case spv::OpMax: return;
	}
}

}  // anonymous namespace

namespace sw {

const char *SpirvShader::OpcodeName(spv::Op op)
{
	return spvOpcodeString(op);
}

bool SpirvShader::IsStatement(spv::Op op)
{
	switch(op)
	{
#define IS_STATEMENT_T(op) case spv::op:
#define IS_STATEMENT_F(op)
#define DECORATE_OP(isStatement, op)    \
	CONCAT2(IS_STATEMENT_, isStatement) \
	(op)
#include "SpirvShaderInstructions.inl"
#undef IS_STATEMENT_T
#undef IS_STATEMENT_F
#undef DECORATE_OP
		return true;

	default:
		return false;
	}
}

}  // namespace sw


text:
This is a very simple http server lib designed to export APIs in python.

The lib is based on tornado.

The latest version is v1.2.3.

## Installment

`pip install http_api_exporter`

## Usage

```
from http_api_exporter import ApiHttpServer #import the class

def function():                    #define the functions you want to export
    ...

# Then you have two choices to bind the server with functions.

app = ApiHttpServer({"route" : function})
app.start()

# or

app = ApiHttpServer()
app.bind("route", function)
app.start()

# Finally, you have two ways to pass the args.

{                                   #pass the args as a list named "Input"
   Input: [args]
}

{                                   #pass the args as a dict
    arg: value,
    arg0: value,
    ...
}

{                                   #combine both
    Input: [args],
    arg0: value,
    ...
}
```

## API

Class __SimpleApiServer__:
* The simplest api server. Designed to easily bind functions to routes' post method.
    * __\_\_init\_\___(function\_dict=None, welcome\_page="Python APIs are providing.", debug=False) :
        * Initialize the class.
            * __function\_dict__ : A dictionary which is composed by "Route" as keys and functions as values.
            * __welcome\_page__ : A string that allow you modify the welcome page, which can be visited at the root route('\\').
            * __debug__ : Enable debug log stdout, default is `False`.
    * __bind__(self, route=None, function=None, dictionary=None) :
        * Bind the function.
            * __route__ : The route to call the corresponding function.
            * __function__ : The corresponding function.
            * __dictionary__ : If "dictionary" is not `None`, then the "route" and the "function" will be ignored. And unfold the dict that keys as routes and values as functions.
    * __add\_periodic_task__(self, function, interval) :
        * Add periodic task to application, task will be execute every `interval` millisecond. This function should be called before `start()`
            * __function__ : The task expected to execute.
            * __interval__ : The interval between two executions in milliseconds.
    * __start__(port=80, retry=0) :
        * Start the server.
            * __port__ : Choose which port to listen on.
            * __retry__ : How many times to retry if the port has been used, default is `0` which means no retry.

Class __ApiHttpServer__:
* An alias of `SimpleApiServer` because of compatibility, and will be removed in the future(maybe v2.0.0).

## Example

```
from http_api_exporter import ApiHttpServer

def test_function(arg0, arg1):
    #do nothing
    return {
        "a" : 1
    }

if __name__ == "__main__":
    app = ApiHttpServer({"/test", test_function})
    app.start()

# then post url http://localhost/test
```

## Attention

Your function must returns a dictionary which could be jsonified or has no returned value.

## What's more

### DONE

bind the functions to routes.

support function without return.

support function without parameters.

support pass parameters by "Input" array.

support pass parameters by dictionary form.

support pass parameters by both of the above.

support periodic tasks.

### TODO

Add a complex server to handle websocket.

anything else if anyone need.


text: <link rel="stylesheet" href="twentytwenty.css" type="text/css" media="screen" />


text:
package org.ritvik.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/WorkController")
@Scope("request")
public class WorkController {

	@Autowired
	private Logger logger;

	@RequestMapping(method = RequestMethod.GET)
	public String processRequest() {
		logger.info("WorkController");
		return "/work.htm";
	}

}


text:
const newRelic = require('newrelic');
import * as express from 'express';
import * as http from 'http';
import * as compression from 'compression';
import * as morgan from 'morgan';
import * as fs from 'fs';
import * as helmet from 'helmet';

import { ObjectId } from 'bson';
import { join } from 'path';
import { json, urlencoded } from 'body-parser';
import { mongoose, Database } from './config/database';
import { Constants } from './constants';
import { Config } from './config/config';
import { Router } from 'express';
import { ApiErrorHandler } from './api-error-handler';
import * as routers from './routers';

import methodOverride = require('method-override');
import log = require('winston');
import jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens

// Creates and configures an ExpressJS web server.
class Application {

  // ref to Express instance
  public express: express.Application;
  public currentDatabase: Database;
  public server: http.Server;

  private setupComplete: boolean = false;

  // Run configuration methods on the Express instance.
  constructor() {
    log.info('Starting up Express Server.');

    this.checkEnvironment();

    this.express = express();
    this.logging();      // Initialize logging
    this.healthcheck();  // Router for the healthcheck
    this.loggingEndpoint();
    this.connectDatabase();     // Setup database connection
    this.secure();       // Turn on security measures
    this.swagger();      // Serve up swagger, this is before authentication, as swagger is open
    this.configureJWT(); // Sets up the way that json web tokens works
    this.middleware();   // Setup the middleware
    this.routes();       // Setup routers for all the controllers
    this.handlers();     // Any additional handlers, home page, etc.

    this.server = this.express.listen(Config.active.get('port'));

    log.info(`Listening on http://localhost:${Config.active.get('port')}`);
  }

  private connectDatabase(){
    this.currentDatabase = new Database();
    this.currentDatabase.connect().then(connected =>{
      this.setupComplete = connected as boolean;
      log.info('Completed Setup, database now online');
    });
  }

  private loggingEndpoint(){
    this.express.post('/clientlogs', (request: express.Request, response: express.Response) => {
          log.log(request.body.level,request.body.message);
      });
  }

  private healthcheck() {
    this.express.get('/healthcheck', (request: express.Request, response: express.Response) => {
      response.statusCode = this.setupComplete ? 200 : 500;
      response.json({
        ApplicationName: Constants.ApplicationName,
        StatusCode: this.setupComplete ? 200 : 500,
        SetupComplete: this.setupComplete,
      });
    });
  }

  private secure(){
    //app.use(helmet()); //Protecting the app from a lot of vulnerabilities turn on when you want to use TLS.
  }

  // Here we're going to make sure that the environment is setup.
  // We're also going to double check that nothing goofy is going on.
  private checkEnvironment(){
    if(!process.env.NODE_ENV){
      throw JSON.stringify({
        error: 'You must have a node environment set: NODE_ENV',
        message: 'You can set a node environemnt using set NODE_ENV development. Be sure to close and reopen any active console windows',
      });
    }
    else{
      log.info(`Current Environment set via environment variables (NODE_ENV):${process.env.NODE_ENV}`);
    }
  }

  // We want to configure logging so that if we're outputting it to the console
  // it's nice and colorized, otherwise we remove that transport.
  private logging(): void {
    if (Config.active.get('isConsoleLoggingActive')) {
      log.remove(log.transports.Console);
      log.add(log.transports.Console, { colorize: true });
      this.express.use(morgan('dev')); //Using morgan middleware for logging all requests.  the 'dev' here is just a particular format.
    }
    else {
      log.remove(log.transports.Console);
    }
  }

  // Sets up authentication, and sets it with our jwt secret token.
  private configureJWT() {
    this.express.set('jwtSecretToken', Config.active.get('jwtSecretToken'));
  }

  // Configure Express middleware.
  private middleware(): void {
    log.info('Initializing Middleware');
    //app.use(helmet()); //Protecting the app from a lot of vulnerabilities turn on when you want to use TLS.
    this.express.disable('x-powered-by');
    this.express.use(json());
    this.express.use(urlencoded({ extended: true }));
    this.express.use(methodOverride(function (req) {
      if (req.body && typeof req.body === 'object' && '_method' in req.body) {
        // look in urlencoded POST bodies and delete it
        const method = req.body._method;
        delete req.body._method;
        return method;
      }
    }));
    // compress all requests
    this.express.use(compression());
  }

  private routes(): void {
    log.info('Initializing Routers');
    // The authentication endpoint is 'Open', and should be added to the router pipeline before the other routers
    this.express.use('/authenticate', new routers.AuthenticationRouter().getRouter());
    this.express.use('/api*', new routers.AuthenticationRouter().authMiddleware);
    this.express.use(Constants.APIEndpoint + Constants.APIVersion1, new routers.AddressRouter().getRouter());
    this.express.use(Constants.APIEndpoint + Constants.APIVersion1, new routers.OrganizationRouter().getRouter());
    this.express.use(Constants.APIEndpoint + Constants.APIVersion1, new routers.UserRouter().getRouter());
    this.express.use(Constants.APIEndpoint + Constants.APIVersion1, new routers.RoleRouter().getRouter());
    this.express.use(Constants.APIEndpoint + Constants.APIVersion1, new routers.PermissionRouter().getRouter());

    log.info('Instantiating Default Error Handler Route');
    this.express.use((error: Error & { status: number }, request: express.Request, response: express.Response, next: express.NextFunction): void => {
      ApiErrorHandler.HandleApiError(error, request, response, next);
    });
  }

  // We want to return a json response that will at least be helpful for
  // the root route of our api.
  private handlers(): void {
    this.express.get('/', (request: express.Request, response: express.Response) => {
      response.json({
        name: Constants.ApplicationName,
        DocumentationLocation:`${Config.active.get('publicURL')}:${Config.active.get('port')}/api-docs`,
        APILocation: `${Config.active.get('publicURL')}:${Config.active.get('port')}/api`,
        AuthenticationEndpoint: `${Config.active.get('publicURL')}:${Config.active.get('port')}/api/authenticate`,
      })
    });

    this.express.get('*', function (req, res, next) {
      next({message: `No router was found for your request, page not found.  Requested Page: ${req.originalUrl}`, status: 404});
    });
  }

  // This will allow us to serve the static homepage for our swagger definition
  // along with the swagger ui explorer.
  private swagger(): void {
    this.express.use(Constants.APIDocsEndpoint, express.static(__dirname + '/swagger/swagger-ui'));
    this.express.use(Constants.APISwaggerDefinitionEndpoint, express.static(__dirname + '/swagger/'));
  }
}
export default new Application();


text:
This cop checks for a line break before the first parameter in a
multi-line method parameter definition.

### Example:

      # bad
      def method(foo, bar,
          baz)
        do_something
      end

      # good
      def method(
          foo, bar,
          baz)
        do_something
      end

      # ignored
      def method foo,
          bar
        do_something
      end


text:
<!DOCTYPE HTML>

		<meta http-equiv="X-UA-Compatible" content="IE=edge">

		<link rel="stylesheet" href="../../../../../resources/sap/ui/thirdparty/qunit.css" type="text/css" media="screen">

		<title>QUnit Test for DatePicker</title>
		<link rel="shortcut icon" type="image/x-icon" href="../images/controls/sap.ui.commons.DatePicker.gif">

QUnit Page for sap.ui.commons.Datepicker

test markup, will be hidden


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="drawer_menu">
        <item>@string/room_overview_title</item>
        <item>@string/music_overview_title</item>
        <item>@string/about_title</item>
    </string-array>
</resources>


text:
"""Tests for training routines."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import logging

import numpy as np

from tensorflow.python import keras
from tensorflow.python.data.experimental.ops import cardinality
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.eager import context
from tensorflow.python.framework import test_util as tf_test_util
from tensorflow.python.keras import keras_parameterized
from tensorflow.python.keras import metrics as metrics_module
from tensorflow.python.keras import testing_utils
from tensorflow.python.ops.losses import losses_impl
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging as logging

class TestTrainingWithDatasetIterators(keras_parameterized.TestCase):

  @keras_parameterized.run_with_all_model_types
  @keras_parameterized.run_all_keras_modes
  def test_training_and_eval_methods_on_iterators_single_io(self):
    model = testing_utils.get_small_mlp(1, 4, input_dim=3)
    optimizer = 'rmsprop'
    loss = 'mse'
    metrics = ['mae', metrics_module.CategoricalAccuracy()]
    model.compile(optimizer, loss, metrics=metrics,
                  run_eagerly=testing_utils.should_run_eagerly())

    inputs = np.zeros((10, 3), np.float32)
    targets = np.zeros((10, 4), np.float32)
    dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
    dataset = dataset.repeat(100)
    dataset = dataset.batch(10)
    iterator = dataset_ops.make_one_shot_iterator(dataset)

    model.fit(iterator, epochs=1, steps_per_epoch=2, verbose=1)
    model.evaluate(iterator, steps=2, verbose=1)
    model.predict(iterator, steps=2)

    # Test with validation data
    model.fit(iterator,
              epochs=1, steps_per_epoch=2, verbose=0,
              validation_data=iterator, validation_steps=2)
    # Test with validation split
    with self.assertRaisesRegexp(
        ValueError, '`validation_split` argument is not supported '
        'when input `x` is a dataset or a dataset iterator'):
      model.fit(iterator,
                epochs=1, steps_per_epoch=2, verbose=0,
                validation_split=0.5, validation_steps=2)

    # Test with sample weight.
    sample_weight = np.random.random((10,))
    with self.assertRaisesRegexp(
        ValueError, '`sample_weight` argument is not supported '
        'when input `x` is a dataset or a dataset iterator'):
      model.fit(
          iterator,
          epochs=1,
          steps_per_epoch=2,
          verbose=0,
          sample_weight=sample_weight)

    # Test invalid usage
    with self.assertRaisesRegexp(ValueError,
                                 'you should not specify a target'):
      model.fit(iterator, iterator,
                epochs=1, steps_per_epoch=2, verbose=0)

    with self.assertRaisesRegexp(
        ValueError, 'the `steps_per_epoch` argument'):
      model.fit(iterator, epochs=1, verbose=0)
    with self.assertRaisesRegexp(ValueError,
                                 'the `steps` argument'):
      model.evaluate(iterator, verbose=0)
    with self.assertRaisesRegexp(ValueError,
                                 'the `steps` argument'):
      model.predict(iterator, verbose=0)

  @keras_parameterized.run_with_all_model_types
  @keras_parameterized.run_all_keras_modes
  def test_iterators_running_out_of_data(self):
    model = testing_utils.get_small_mlp(1, 4, input_dim=3)
    optimizer = 'rmsprop'
    loss = 'mse'
    metrics = ['mae']
    model.compile(optimizer, loss, metrics=metrics,
                  run_eagerly=testing_utils.should_run_eagerly())

    inputs = np.zeros((10, 3), np.float32)
    targets = np.zeros((10, 4), np.float32)
    dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
    dataset = dataset.repeat(2)
    dataset = dataset.batch(10)
    iterator = dataset_ops.make_one_shot_iterator(dataset)

    with test.mock.patch.object(logging, 'warning') as mock_log:
      model.fit(iterator, epochs=1, steps_per_epoch=3, verbose=0)
      self.assertRegexpMatches(
          str(mock_log.call_args),
          'dataset iterator ran out of data')

class TestTrainingWithDataset(keras_parameterized.TestCase):

  @keras_parameterized.run_with_all_model_types
  @keras_parameterized.run_all_keras_modes
  def test_calling_model_on_same_dataset(self):
    if ((not testing_utils.should_run_eagerly())
        and testing_utils.get_model_type() == 'subclass'
        and context.executing_eagerly()):
      self.skipTest('b/120673224')

    model = testing_utils.get_small_mlp(1, 4, input_dim=3)
    optimizer = 'rmsprop'
    loss = 'mse'
    metrics = ['mae']
    model.compile(optimizer, loss, metrics=metrics,
                  run_eagerly=testing_utils.should_run_eagerly())

    inputs = np.zeros((10, 3), np.float32)
    targets = np.zeros((10, 4), np.float32)
    dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
    dataset = dataset.repeat(100)
    dataset = dataset.batch(10)

    # Call fit with validation data
    model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0,
              validation_data=dataset, validation_steps=2)
    model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0,
              validation_data=dataset, validation_steps=2)

  @keras_parameterized.run_with_all_model_types
  @keras_parameterized.run_all_keras_modes
  def test_training_and_eval_methods_on_dataset(self):
    model = testing_utils.get_small_mlp(1, 4, input_dim=3)
    optimizer = 'rmsprop'
    loss = 'mse'
    metrics = ['mae', metrics_module.CategoricalAccuracy()]
    model.compile(optimizer, loss, metrics=metrics,
                  run_eagerly=testing_utils.should_run_eagerly())

    inputs = np.zeros((10, 3), np.float32)
    targets = np.zeros((10, 4), np.float32)
    dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
    dataset = dataset.repeat()  # Infinite dataset.
    dataset = dataset.batch(10)

    model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1)
    model.evaluate(dataset, steps=2, verbose=1)
    model.predict(dataset, steps=2)

    # Test with validation data
    model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0,
              validation_data=dataset, validation_steps=2)

    # Test with validation split
    with self.assertRaisesRegexp(
        ValueError, '`validation_split` argument is not supported '
        'when input `x` is a dataset or a dataset iterator'):
      model.fit(dataset,
                epochs=1, steps_per_epoch=2, verbose=0,
                validation_split=0.5, validation_steps=2)

    # Test with sample weight.
    sample_weight = np.random.random((10,))
    with self.assertRaisesRegexp(
        ValueError, '`sample_weight` argument is not supported '
        'when input `x` is a dataset or a dataset iterator'):
      model.fit(
          dataset,
          epochs=1,
          steps_per_epoch=2,
          verbose=0,
          sample_weight=sample_weight)

    # Test invalid usage
    with self.assertRaisesRegexp(ValueError, 'The `batch_size` argument'
                                 ' must not be specified when using dataset'
                                 ' as an input.'):
      model.fit(dataset, batch_size=10, epochs=1, steps_per_epoch=2,
                verbose=0)
    with self.assertRaisesRegexp(ValueError, 'The `batch_size` argument'
                                 ' must not be specified when using dataset'
                                 ' as an input.'):
      model.predict(dataset, batch_size=10, steps=2, verbose=0)
    with self.assertRaisesRegexp(ValueError, 'The `batch_size` argument'
                                 ' must not be specified when using dataset'
                                 ' as an input.'):
      model.evaluate(dataset, batch_size=10, steps=2, verbose=0)

    with self.assertRaisesRegexp(ValueError,
                                 'you should not specify a target'):
      model.fit(dataset, dataset,
                epochs=1, steps_per_epoch=2, verbose=0)

    # With an infinite dataset, `steps_per_epoch`/`steps` argument is required.
    with self.assertRaisesRegexp(
        ValueError, 'the `steps_per_epoch` argument'):
      model.fit(dataset, epochs=1, verbose=0)
    with self.assertRaisesRegexp(ValueError,
                                 'the `steps` argument'):
      model.evaluate(dataset, verbose=0)
    with self.assertRaisesRegexp(ValueError,
                                 'the `steps` argument'):
      model.predict(dataset, verbose=0)

  @keras_parameterized.run_with_all_model_types
  @keras_parameterized.run_all_keras_modes
  def test_dataset_with_sample_weights(self):
    model = testing_utils.get_small_mlp(1, 4, input_dim=3)
    optimizer = 'rmsprop'
    loss = 'mse'
    metrics = ['mae', metrics_module.CategoricalAccuracy()]
    model.compile(optimizer, loss, metrics=metrics,
                  run_eagerly=testing_utils.should_run_eagerly())

    inputs = np.zeros((10, 3), np.float32)
    targets = np.zeros((10, 4), np.float32)
    sample_weights = np.ones((10), np.float32)
    dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets,
                                                      sample_weights))
    dataset = dataset.repeat(100)
    dataset = dataset.batch(10)

    model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1)
    model.evaluate(dataset, steps=2, verbose=1)
    model.predict(dataset, steps=2)

  @keras_parameterized.run_with_all_model_types
  @keras_parameterized.run_all_keras_modes
  def test_dataset_with_sparse_labels(self):
    model = testing_utils.get_small_mlp(1, 4, input_dim=3)
    optimizer = 'rmsprop'
    for loss in ['sparse_categorical_crossentropy',
                 losses_impl.sparse_softmax_cross_entropy]:
      model.compile(optimizer, loss,
                    run_eagerly=testing_utils.should_run_eagerly())

      inputs = np.zeros((10, 3), dtype=np.float32)
      targets = np.random.randint(0, 4, size=10, dtype=np.int32)
      dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
      dataset = dataset.repeat(100)
      dataset = dataset.batch(10)

      model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1)

  @keras_parameterized.run_all_keras_modes
  def test_dataset_fit_correctness(self):

    class SumLayer(keras.layers.Layer):

      def build(self, _):
        self.w = self.add_weight('w', ())

      def call(self, inputs):
        return keras.backend.sum(inputs) + self.w * 0

    model = keras.Sequential([SumLayer(input_shape=(2,))])
    model.compile(
        'rmsprop', loss='mae', run_eagerly=testing_utils.should_run_eagerly())

    inputs = np.zeros((40, 2), dtype=np.float32)
    inputs[10:20, :] = 2
    inputs[20:30, :] = 1
    inputs[30:, :] = 4
    targets = np.zeros((40, 1), dtype=np.float32)
    dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
    dataset = dataset.batch(10)
    history = model.fit(dataset,
                        epochs=2, steps_per_epoch=2, verbose=1, shuffle=False)
    self.assertListEqual(history.history['loss'],
                         [inputs[:20].sum() / 2, inputs[20:].sum() / 2])

  @tf_test_util.run_deprecated_v1
  def test_dataset_input_shape_validation(self):
    with self.cached_session():
      model = testing_utils.get_small_functional_mlp(1, 4, input_dim=3)
      model.compile(optimizer='rmsprop', loss='mse')

      # User forgets to batch the dataset
      inputs = np.zeros((10, 3))
      targets = np.zeros((10, 4))
      dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
      dataset = dataset.repeat(100)

      with self.assertRaisesRegexp(
          ValueError,
          r'expected (.*?) to have shape \(3,\) but got array with shape \(1,\)'
      ):
        model.train_on_batch(dataset)

      # Wrong input shape
      inputs = np.zeros((10, 5))
      targets = np.zeros((10, 4))
      dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
      dataset = dataset.repeat(100)
      dataset = dataset.batch(10)

      with self.assertRaisesRegexp(ValueError,
                                   r'expected (.*?) to have shape \(3,\)'):
        model.train_on_batch(dataset)

  @keras_parameterized.run_with_all_model_types
  @keras_parameterized.run_all_keras_modes
  def test_finite_dataset_known_cardinality_no_steps_arg(self):
    model = testing_utils.get_small_mlp(1, 4, input_dim=3)
    optimizer = 'rmsprop'
    model.compile(optimizer, 'mse',
                  run_eagerly=testing_utils.should_run_eagerly())

    inputs = np.zeros((100, 3), dtype=np.float32)
    targets = np.random.randint(0, 4, size=100, dtype=np.int32)
    dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
    dataset = dataset.batch(10)

    history = model.fit(dataset, epochs=2, verbose=1)
    self.assertEqual(len(history.history['loss']), 2)
    model.evaluate(dataset)
    out = model.predict(dataset)
    self.assertEqual(out.shape[0], 100)

  @keras_parameterized.run_with_all_model_types
  @keras_parameterized.run_all_keras_modes
  def test_finite_dataset_unknown_cardinality_no_steps_arg(self):
    model = testing_utils.get_small_mlp(1, 4, input_dim=3)
    optimizer = 'rmsprop'
    model.compile(optimizer, 'mse',
                  run_eagerly=testing_utils.should_run_eagerly())

    inputs = np.zeros((100, 3), dtype=np.float32)
    targets = np.random.randint(0, 4, size=100, dtype=np.int32)
    dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets))
    dataset = dataset.filter(lambda x, y: True).batch(10)
    self.assertEqual(keras.backend.get_value(cardinality.cardinality(dataset)),
                     cardinality.UNKNOWN)

    history = model.fit(dataset, epochs=2, verbose=1)
    self.assertEqual(len(history.history['loss']), 2)
    model.evaluate(dataset)
    out = model.predict(dataset)
    self.assertEqual(out.shape[0], 100)

class TestMetricsWithDatasetIterators(keras_parameterized.TestCase):

  @keras_parameterized.run_with_all_model_types
  @keras_parameterized.run_all_keras_modes
  def test_metrics_correctness_with_iterator(self):
    layers = [
        keras.layers.Dense(8, activation='relu', input_dim=4,
                           kernel_initializer='ones'),
        keras.layers.Dense(1, activation='sigmoid', kernel_initializer='ones')
    ]

    model = testing_utils.get_model_from_layers(layers, (4,))

    model.compile(
        loss='binary_crossentropy',
        metrics=['accuracy', metrics_module.BinaryAccuracy()],
        optimizer='rmsprop',
        run_eagerly=testing_utils.should_run_eagerly())

    np.random.seed(123)
    x = np.random.randint(10, size=(100, 4)).astype(np.float32)
    y = np.random.randint(2, size=(100, 1)).astype(np.float32)
    dataset = dataset_ops.Dataset.from_tensor_slices((x, y))
    dataset = dataset.batch(10)
    iterator = dataset_ops.make_one_shot_iterator(dataset)
    outs = model.evaluate(iterator, steps=10)
    self.assertEqual(np.around(outs[1], decimals=1), 0.5)
    self.assertEqual(np.around(outs[2], decimals=1), 0.5)

    y = np.zeros((100, 1), dtype=np.float32)
    dataset = dataset_ops.Dataset.from_tensor_slices((x, y))
    dataset = dataset.repeat(100)
    dataset = dataset.batch(10)
    iterator = dataset_ops.make_one_shot_iterator(dataset)
    outs = model.evaluate(iterator, steps=10)
    self.assertEqual(outs[1], 0.)
    self.assertEqual(outs[2], 0.)

if __name__ == '__main__':
  test.main()


text:
package gov.va.isaac.gui.treeview;

import gov.va.isaac.interfaces.gui.views.commonFunctionality.taxonomyView.SctTreeItemDisplayPolicies;
import gov.va.isaac.interfaces.gui.views.commonFunctionality.taxonomyView.SctTreeItemI;
import gov.va.isaac.util.OchreUtility;
import gov.vha.isaac.metadata.source.IsaacMetadataAuxiliaryBinding;
import gov.vha.isaac.ochre.api.Get;
import gov.vha.isaac.ochre.api.LookupService;
import gov.vha.isaac.ochre.api.component.concept.ConceptChronology;
import gov.vha.isaac.ochre.api.component.concept.ConceptSnapshotService;
import gov.vha.isaac.ochre.api.component.concept.ConceptVersion;
import gov.vha.isaac.ochre.api.coordinate.TaxonomyCoordinate;
import gov.vha.isaac.ochre.api.tree.Tree;
import gov.vha.isaac.ochre.util.WorkExecutors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import javafx.application.Platform;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.scene.Node;
import javafx.scene.control.TreeItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A {@link TreeItem} for modeling nodes in the SNOMED CT taxonomy.
 *
 * @author kec
 * @author ocarlsen
 * @author Dan Armbrust
 */
class SctTreeItem extends TreeItem<ConceptChronology<? extends ConceptVersion<?>>> implements SctTreeItemI, Comparable<SctTreeItem> {

    private static final Logger LOG = LoggerFactory.getLogger(SctTreeItem.class);

    private final List<SctTreeItem> extraParents = new ArrayList<>();
    private CountDownLatch childrenLoadedLatch = new CountDownLatch(1);
    //-2 when not yet started, -1 for started indeterminate - between 0 and 1, if we can determine, 1 when complete.
    private DoubleProperty childLoadPercentComplete = new SimpleDoubleProperty(-2.0);
    private volatile boolean cancelLookup = false;
    private boolean defined = false;
    private boolean multiParent = false;
    private int multiParentDepth = 0;
    private boolean secondaryParentOpened = false;
    private SctTreeItemDisplayPolicies displayPolicies;
    private final ReadOnlyObjectProperty<TaxonomyCoordinate> taxonomyCoordinate;
    private final ReadOnlyObjectProperty<Tree> taxonomyTree;
    private final ReadOnlyObjectProperty<ConceptSnapshotService> conceptSnapshotService;

    public ReadOnlyObjectProperty<Tree> getTaxonomyTree() {
    	return taxonomyTree;
    }
    public ReadOnlyObjectProperty<TaxonomyCoordinate> getTaxonomyCoordinate() {
    	return taxonomyCoordinate;
    }
    public ReadOnlyObjectProperty<ConceptSnapshotService> getConceptSnapshotService() {
    	return conceptSnapshotService;
    }

    private static WorkExecutors workExecutors_ = null;
    private static WorkExecutors getWorkExecutors()
    {
        if (workExecutors_ == null)
        {
            workExecutors_ = LookupService.getService(WorkExecutors.class);
        }
        return workExecutors_;
    }

    private static TreeItem<ConceptChronology<? extends ConceptVersion<?>>> getTreeRoot(TreeItem<ConceptChronology<? extends ConceptVersion<?>>> item) {
        TreeItem<ConceptChronology<? extends ConceptVersion<?>>> parent = item.getParent();

        if (parent == null) {
            return item;
        } else {
            return getTreeRoot(parent);
        }
    }

    SctTreeItem(int conceptSequence, SctTreeItemDisplayPolicies displayPolicies,
            ReadOnlyObjectProperty<TaxonomyCoordinate> vcp, ReadOnlyObjectProperty<Tree> ttp, ReadOnlyObjectProperty<ConceptSnapshotService> css) {
        this(Get.conceptService().getConcept(conceptSequence), displayPolicies, vcp, ttp, css, (Node) null);
    }

    SctTreeItem(ConceptChronology<? extends ConceptVersion<?>> conceptChronology, SctTreeItemDisplayPolicies displayPolicies,
            ReadOnlyObjectProperty<TaxonomyCoordinate> vcp, ReadOnlyObjectProperty<Tree> ttp, ReadOnlyObjectProperty<ConceptSnapshotService> css, Node node) {
        super(conceptChronology, node);
        this.taxonomyCoordinate = vcp;
        this.taxonomyTree = ttp;
        this.conceptSnapshotService = css;
        this.displayPolicies = displayPolicies;
    }

    SctTreeItemDisplayPolicies getDisplayPolicies() {
        return displayPolicies;
    }

    void addChildren() {
        childLoadStarts();
        try
        {
            final ConceptChronology<? extends ConceptVersion<?>> conceptChronology = getValue();
            if (! shouldDisplay()) {
                // Don't add children to something that shouldn't be displayed
                LOG.debug("this.shouldDisplay() == false: not adding children to " + this.getConceptUuid());
            } else if (conceptChronology == null) {
                LOG.debug("addChildren(): conceptChronology={}", conceptChronology);
            } else { // if (conceptChronology != null)
                // Gather the children
                ArrayList<SctTreeItem> childrenToAdd = new ArrayList<>();
                ArrayList<GetSctTreeItemConceptCallable> childrenToProcess = new ArrayList<>();

                for (int childSequence : getTaxonomyTree().get().getChildrenSequences(conceptChronology.getConceptSequence())) {
                    SctTreeItem childItem = new SctTreeItem(childSequence, displayPolicies, taxonomyCoordinate, taxonomyTree, conceptSnapshotService);
                    if (childItem.shouldDisplay()) {
                        childrenToAdd.add(childItem);
                        childrenToProcess.add(new GetSctTreeItemConceptCallable(childItem));
                    } else {
                        LOG.debug("item.shouldDisplay() == false: not adding " + childItem.getConceptUuid() + " as child of " + this.getConceptUuid());
                    }
                }

                Collections.sort(childrenToAdd);
                if (cancelLookup) {
                    return;
                }

                Platform.runLater(() ->
                {
                    getChildren().addAll(childrenToAdd);
                });
                //This loads the children of this child
                for (GetSctTreeItemConceptCallable child : childrenToProcess) {
                    getWorkExecutors().getPotentiallyBlockingExecutor().execute(child);
                }

            }
        }
        catch (Exception e)
        {
            LOG.error("Unexpected error computing children and/or grandchildren", e);
        }
        finally
        {
            childLoadComplete();
        }
    }

    void addChildrenConceptsAndGrandchildrenItems() {
        ArrayList<GetSctTreeItemConceptCallable> grandChildrenToProcess = new ArrayList<>();
        childLoadStarts();
        try
        {
            if (! shouldDisplay()) {
                // Don't add children to something that shouldn't be displayed
                LOG.debug("this.shouldDisplay() == false: not adding children concepts and grandchildren items to " + this.getConceptUuid());
            } else {
                for (TreeItem<ConceptChronology<? extends ConceptVersion<?>>> child : getChildren()) {
                    if (cancelLookup) {
                        return;
                    }
                    if (((SctTreeItem)child).shouldDisplay()) {
                        if (child.getChildren().isEmpty() && (child.getValue() != null)) {
                            if (getTaxonomyTree().get().getChildrenSequences(child.getValue().getConceptSequence()).length == 0) {
                                ConceptChronology<? extends ConceptVersion<?>> value = child.getValue();
                                child.setValue(null);
                                SctTreeItem noChildItem = (SctTreeItem) child;
                                noChildItem.computeGraphic();
                                noChildItem.setValue(value);
                            } else if (((SctTreeItem)child).getChildLoadPercentComplete().get() == -2.0){ //If this child hasn't yet been told to load
                                ArrayList<SctTreeItem> grandChildrenToAdd = new ArrayList<>();
                                ((SctTreeItem)child).childLoadStarts();

                                for (int childSequence : getTaxonomyTree().get().getChildrenSequences(child.getValue().getConceptSequence())) {
                                    if (cancelLookup) {
                                        return;
                                    }
                                            SctTreeItem grandChildItem = new SctTreeItem(childSequence, displayPolicies, taxonomyCoordinate, taxonomyTree, conceptSnapshotService);

                                            if (grandChildItem.shouldDisplay()) {
                                                grandChildrenToProcess.add(new GetSctTreeItemConceptCallable(grandChildItem));
                                                grandChildrenToAdd.add(grandChildItem);
                                            } else {
                                                LOG.debug("grandChildItem.shouldDisplay() == false: not adding " + grandChildItem.getConceptUuid() + " as child of " + ((SctTreeItem)child).getConceptUuid());
                                            }
                                }

                                Collections.sort(grandChildrenToAdd);
                                if (cancelLookup) {
                                    return;
                                }

                                CountDownLatch wait = new CountDownLatch(1);
                                Platform.runLater(() ->
                                {
                                    child.getChildren().addAll(grandChildrenToAdd);
                                    ((SctTreeItem)child).childLoadComplete();
                                    wait.countDown();
                                });
                                wait.await();
                            }
                        } else if ((child.getValue() == null) && ((SctTreeItem)child).getChildLoadPercentComplete().get() == -2.0) {
                            grandChildrenToProcess.add(new GetSctTreeItemConceptCallable((SctTreeItem) child));
                        }
                    } else {
                        LOG.debug("childItem.shouldDisplay() == false: not adding " + ((SctTreeItem)child).getConceptUuid() + " as child of " + this.getConceptUuid());
                    }
                }

                if (cancelLookup) {
                    return;
                }

                //This loads the childrens children
                for (GetSctTreeItemConceptCallable childsChild : grandChildrenToProcess) {
                    getWorkExecutors().getPotentiallyBlockingExecutor().execute(childsChild);
                }
            }
        }
        catch (Exception e)
        {
            LOG.error("Unexpected error computing children and/or grandchildren", e);
        }
        finally
        {
            childLoadComplete();
        }
    }

    @Override
    public int compareTo(SctTreeItem o) {
        return this.toString().compareTo(o.toString());
    }

    public UUID getConceptUuid() {
        return getValue() != null ? getValue().getPrimordialUuid() : null;
    }
    @Override
    public Integer getConceptNid() {
        return getValue() != null ? getValue().getNid() : null;
    }
    private static Integer getConceptNid(TreeItem<ConceptChronology<? extends ConceptVersion<?>>> item) {
        return item != null && item.getValue() != null ? item.getValue().getNid() : null;
    }

    @Override
    public boolean isRoot() {
        if (IsaacMetadataAuxiliaryBinding.ISAAC_ROOT.getPrimodialUuid().equals(this.getConceptUuid())) {
            return true;
        } else if (this.getParent() == null) {
            return true;
        } else {
            TreeItem<ConceptChronology<? extends ConceptVersion<?>>> root = getTreeRoot(this);

            if (this == root) {
                return true;
            } else if (getConceptNid(root) == getConceptNid()) {
                return true;
            }
            else {
                return false;
            }
        }
    }

    public Node computeGraphic() {
        return displayPolicies.computeGraphic(this);
    }

    public boolean shouldDisplay() {
        return displayPolicies.shouldDisplay(this);
    }

    /**
     * @see javafx.scene.control.TreeItem#toString()
     * WARNING: toString is currently used in compareTo()
     */
    @Override
    public String toString() {
        return toString(this);
    }

    public static String toString(SctTreeItem item) {
        try {
            if (item.getValue() != null) {
                Optional<String> desc = OchreUtility.getDescription(item.getValue().getNid(), item.getTaxonomyCoordinate().get());
                if (desc.isPresent()) {
                	return desc.get();
                } else {
                	LOG.debug("No description found for concept {}", item.getValue().toUserString());
                }
            }

            return "root";
        } catch (RuntimeException re) {
            LOG.error("Caught {} \"{}\"", re.getClass().getName(), re.getLocalizedMessage());
            throw re;
        } catch (Error e) {
            LOG.error("Caught {} \"{}\"", e.getClass().getName(), e.getLocalizedMessage());
            throw e;
        }
    }

    public List<SctTreeItem> getExtraParents() {
        return extraParents;
    }

    @Override
    public int getMultiParentDepth() {
        return multiParentDepth;
    }

    /**
     * returns -2 when not yet started, -1 when started, but indeterminate otherwise, a value between 0 and 1 (1 when complete)
     */
    public DoubleProperty getChildLoadPercentComplete() {
        return childLoadPercentComplete;
    }

    @Override
    public boolean isDefined() {
        return defined;
    }

    @Override
    public boolean isLeaf() {
        if (multiParentDepth > 0) {
            return true;
        }

        return super.isLeaf();
    }

    @Override
    public boolean isMultiParent() {
        if (multiParent) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean isSecondaryParentOpened() {
        if (secondaryParentOpened) {
            return true;
        } else {
            return false;
        }
    }

    public void setDefined(boolean defined) {
        this.defined = defined;
    }

    public void setMultiParent(boolean multiParent) {
        this.multiParent = multiParent;
    }

    public void setMultiParentDepth(int multiParentDepth) {
        this.multiParentDepth = multiParentDepth;
    }

    public void setSecondaryParentOpened(boolean secondaryParentOpened) {
        this.secondaryParentOpened = secondaryParentOpened;
    }

    public void blockUntilChildrenReady() throws InterruptedException {
        childrenLoadedLatch.await();
    }

    public void clearChildren()
    {
        cancelLookup = true;
        childrenLoadedLatch.countDown();
        for (TreeItem<ConceptChronology<? extends ConceptVersion<?>>> child : getChildren())
        {
            ((SctTreeItem)child).clearChildren();
        }
        getChildren().clear();
    }

    protected void resetChildrenCalculators()
    {
        CountDownLatch cdl = new CountDownLatch(1);
        Runnable r = new Runnable()
        {
            @Override
            public void run()
            {
                cancelLookup = false;
                childLoadPercentComplete.set(-2);
                childrenLoadedLatch.countDown();
                childrenLoadedLatch = new CountDownLatch(1);
                cdl.countDown();
            }
        };
        if (Platform.isFxApplicationThread())
        {
            r.run();
        }
        else
        {
            Platform.runLater(r);
        }
        try
        {
            cdl.await();
        }
        catch (InterruptedException e)
        {
            LOG.error("unexpected interrupt", e);
        }
    }

    public void removeGrandchildren() {
        for (TreeItem<ConceptChronology<? extends ConceptVersion<?>>> child : getChildren()) {
           ((SctTreeItem)child).clearChildren();
           ((SctTreeItem)child).resetChildrenCalculators();
        }
    }

    /**
     * Can be called on either a background or the FX thread
     */
    protected void childLoadStarts()
    {
        CountDownLatch cdl = new CountDownLatch(1);
        Runnable r = new Runnable()
        {
            @Override
            public void run()
            {
                childLoadPercentComplete.set(-1);
                cdl.countDown();
            }
        };
        if (Platform.isFxApplicationThread())
        {
            r.run();
        }
        else
        {
            Platform.runLater(r);
        }
        try
        {
            cdl.await();
        }
        catch (InterruptedException e)
        {
            LOG.error("unexpected interrupt", e);
        }
    }

    /**
     * Can be called on either a background or the FX thread
     */
    protected void childLoadComplete()
    {
        Runnable r = new Runnable()
        {
            @Override
            public void run()
            {
                childLoadPercentComplete.set(1.0);
                childrenLoadedLatch.countDown();
            }
        };
        if (Platform.isFxApplicationThread())
        {
            r.run();
        }
        else
        {
            Platform.runLater(r);
        }
    }

    protected boolean isCancelRequested()
    {
        return cancelLookup;
    }
}


text:
maintainer       "Mathieu Sauve-Frankel"
maintainer_email "msf@kisoku.net"
license          "Apache 2.0"
description      "mail_alias provider"
long_description  IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          "0.1.0"
depends          "minitest-handler"


text:
import pygtk
import gtk
import gtk.glade
import numpy
import matplotlib.pyplot as plt
import serial
import scipy
from time import sleep

from matplotlib.figure import Figure
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas
from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar

def aplicar(self):
    puertoserie = str(entry4.get_text())
    puerto = serial.Serial(puertoserie, baudrate=9600)

    # Reseteo placa Arduino
    # Sólo necesario en Linux
    puerto.setDTR(False)
    sleep(1)
    puerto.flushInput()
    puerto.setDTR(True)

    Fs = float(entry1.get_text())  # Frecuencia de muestreo
    N = int(entry2.get_text())  # Número de muestras
    n = float(entry2.get_text())
    L = int(entry3.get_text())   # Longitud de los segmentos
    l = float(entry3.get_text())

    data = []  # Lista contenedora del muestreo
    data_seg = numpy.zeros((N / L, L))  # Lista contenedora de los segmentos de longitud L
    resultado = numpy.zeros((N / L, L))
    promedio = numpy.zeros(L)

    # Lectura de muestras por el puerto serie
    for i in range(0, N):
        line = puerto.readline()
        if not line:
            continue
        dato = numpy.fromstring(line.decode('ascii', errors='replace'), sep=' ')
        dato = float(dato)
        # Escalado
        dato = (dato - 128.0) / 25.6
        data.append(dato)

    t = numpy.arange(0, N * (1 / Fs), (1 / Fs))

    tiempo.set_canvas(canvastiempo)
    tiempoplot.clear()
    tiempoplot.plot(t, data)
    canvastiempo.draw()

    # División de la señal en los distintos segmentos
    for i in range(0, (N / L)):
        data_seg[i] = data[(L * i):(L + (L * i))]

    # Cálculos del Método de Bartlett
    ventana = numpy.hamming(L)
    for i in range(0, (N / L)):
        ejeXV = (data_seg[i] * ventana)
        resultado[i] = numpy.abs(numpy.fft.fft(ejeXV))
        resultado[i] = resultado[i] * resultado[i]
        resultado[i] /= 1 / l

    # Promedio de todos los segmentos de señal
    for columna in range(0, L):
        for fila in range(0, (N / L)):
            promedio[columna] = promedio[columna] + resultado[fila][columna]
    promedio = promedio / (n / l)

    k = scipy.arange(l)
    T = l / Fs  # Periodo
    frq = k / T  # Frecuencia

    # Graficar la Frecuencia entre |0... Fs/2|
    # Si se eliminan ambas líneas, se graficará entre |0... Fs|
    freq = freq[range(L / 2)]
    promedio = promedio[range(L / 2)]

    frecuencia.set_canvas(canvasfrecuencia)
    frecuenciaplot.clear()
    frecuenciaplot.plot(freq, promedio)
    canvasfrecuencia.draw()

gladefile = "proyecto.glade"
proyecto = gtk.Builder()
proyecto.add_from_file(gladefile)

eventos = {
    'evento_terminar': gtk.main_quit,
    'evento_aplicar': aplicar
}
proyecto.connect_signals(eventos)
vbox3 = proyecto.get_object("vbox3")
vbox4 = proyecto.get_object("vbox4")
vbox1 = proyecto.get_object("vbox1")
hbox1 = proyecto.get_object("hbox1")
entry1 = proyecto.get_object("entry1")
entry2 = proyecto.get_object("entry2")
entry3 = proyecto.get_object("entry3")
entry4 = proyecto.get_object("entry4")
win = proyecto.get_object("window1")
#Definición del objeto gráfico para el dominio del tiempo
tiempo = Figure(figsize=(300, 100), dpi=50)
tiempoplot = tiempo.add_subplot(111)
tiempo.subplots_adjust(bottom=0.2)
tiempoplot.set_title("Vibracion Temporal")
tiempoplot.set_xlabel("Tiempo (s)")
tiempoplot.set_ylabel("Aceleracion (G)")
tiempoplot.plot()
canvastiempo = FigureCanvas(tiempo)
vbox3.pack_start(canvastiempo)
toolbartiempo = NavigationToolbar(canvastiempo, win)
vbox3.pack_start(toolbartiempo, False, False)
#Definición del objeto gráfico para el dominio de la frecuencia
frecuencia = Figure(figsize=(300, 100), dpi=50)
frecuenciaplot = frecuencia.add_subplot(111)
frecuencia.subplots_adjust(bottom=0.2)
frecuenciaplot.set_title("Espectro de Frecuencia")
frecuenciaplot.set_xlabel("Frecuencia (hz)")
frecuenciaplot.set_ylabel("Magnitud")
frecuenciaplot.plot()
canvasfrecuencia = FigureCanvas(frecuencia)
vbox4.pack_start(canvasfrecuencia)
toolbarfrecuencia = NavigationToolbar(canvasfrecuencia, win)
vbox4.pack_start(toolbarfrecuencia, False, False)

win.show_all()
gtk.main()


text:
package ru.job4j.chess;

import java.util.Scanner;

/**
 * Class Input.
 *
 * @author Ekaterina Turka (ekaterina2rka@gmail.com)
 * @version 1
 * @since 12.11.2017
 */
public class Input {
    /**
     * Scanner type.
     */
    private Scanner scanner = new Scanner(System.in);

    /**
     * Ask question and return an answer.
     *
     * @param question the question for user
     * @return answer
     */
    public String ask(String question) {
        System.out.print(question);
        return scanner.nextLine();
    }
}


text:
package org.efix.message;

import org.efix.util.ByteSequenceWrapper;

public class TestRequest {

    protected final ByteSequenceWrapper testReqID = new ByteSequenceWrapper();

    public ByteSequenceWrapper testReqID() {
        return testReqID;
    }

}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('localities', '0029_auto_20141114_1500'),
    ]

    operations = [
        migrations.AlterField(
            model_name='localityindex',
            name='locality',
            field=models.OneToOneField(to='localities.Locality'),
            preserve_default=True,
        ),
    ]


text:
package tk.mybatis.mapper.additional.dialect.oracle;

import org.apache.ibatis.annotations.InsertProvider;
import tk.mybatis.mapper.annotation.KeySql;

import java.util.List;

/**
 *
Oracle批量插入
 *
支持@{@link KeySql#genId()},不支持@{@link KeySql#sql()}
 *
因INSERT ALL语法不支持序列,可手工获取序列并设置至Entity或绑定触发器
 *
 * @author qrqhuangcy
 * @date 2018-11-16
 */
@tk.mybatis.mapper.annotation.RegisterMapper
public interface InsertListMapper<T> {

    /**
     *
生成如下批量SQL:
     *
INSERT ALL
     *
INTO demo_country ( country_id,country_name,country_code ) VALUES ( ?,?,? )
     *
INTO demo_country ( country_id,country_name,country_code ) VALUES ( ?,?,? )
     *
INTO demo_country ( country_id,country_name,country_code ) VALUES ( ?,?,? )
     *
SELECT 1 FROM DUAL
     *
     * @param recordList
     * @return
     */
    @InsertProvider(type = OracleProvider.class, method = "dynamicSQL")
    int insertList(List<? extends T> recordList);

}


text:
<?php

namespace Revmsg\Mobilize\Entity;

class Object implements \Revmsg\Mobilize\Entity\ObjectInterface
{
    protected $model = null;
    protected $client = null;
    protected $map = array(
        'v1' => array(),
        'v2' => array()
        );
    public function __construct($signifier = null, $type = null)
    {
        $this->model = new $this->scheme;
        $this->client = new \Guzzle\Http\Client('https://mobile.reverehq.com/api');
        foreach ($this->map as $version => $operations) {
            if (empty($this->customMap[$version])) {
                unset($this->map[$version]);
            }
            if (!empty($operations)) {
                foreach ($operations as $operation => $parameter) {
                    if (!isset($this->customMap[$version][$operation])) {
                        unset($this->map[$version][$operation]);
                    }
                }
            }
            $this->map = array_replace_recursive($this->map, $this->customMap);
        }
        if (!empty($signifier)) {
            if (is_array($signifier)) {
                $this-> model-> setVariables($signifier);
            } elseif (is_string($signifier)) {
                if (strpos(get_class($this), 'Page')) {
                    $this->element = $signifier;
                    if (!empty($type)) {
                        $this->setVariable('type', $type);
                    }
                    $this->fetch();
                } else {
                    $this-> retrieve($signifier);
                }
            }

        }

        return $this;
    }
    public function operation($operation, $version = 'v1', $session = null)
    {
        if (!isset($this->map[$version]) || !isset($this->map[$version][$operation])) {
            throw new \Exception(get_class($this)." objects do not have the $operation method in $version API");
        } else {
            if (!is_null($session)) {
               /* $request = $session()->create($this-> urls[$version]['create'].'/'.$this-> model->getVariable('name'));
                $response = $request-> send();*/
            } elseif (defined('REVMSG_MOBILIZE_KEY')) {
                if (empty($this->client)) {
                    $this->client = new \Guzzle\Http\Client(
                        array(
                            'base_url' => 'https://mobile.reverehq.com/api/'
                            )
                    );
                }
                $request = $this->client->createRequest(
                    $this->map[$version][$operation]['method'],
                    $this->buildUrl($operation, $version),
                    array(
                            'Accept' => 'application/json',
                            'Content-Type' => 'application/json',
                            'Authorization' => REVMSG_MOBILIZE_KEY
                        ),
                    $this->buildPayload($operation, $version),
                    array(
                        'exceptions' =>false,
                        'query' => $this->buildQuery($operation, $version)/*,
'debug' => true*/
                        )
                );
                try {
                    $response = $this->client->send($request);
                    if ($response->getStatusCode() > 300) {
                        $body =
                        'Response: '.$response->getBody().
                        ' URL: '.$request->getUrl().
                        ' Method: '.$request->getMethod().
                        ' Payload: '.$this->buildPayload($operation, $version);
                        throw new \Exception($body);
                    } elseif ($response->getBody()) {
                        $this->setVariables($response->json());
                    } else {

                    }
                    return $this;
                } catch (Exception $e) {
                    echo $e;
                }

            } else {
                throw new \Exception("API key or active session required.");
            }
        }
    }
    protected function buildUrl ($operation, $version = 'v1')
    {
        $args = array(
            $this->map[$version][$operation]['url']
            );
        if (isset($this->map[$version][$operation]['payload']['url'])) {
            foreach ($this->map[$version][$operation]['payload']['url'] as $property) {
                if ($this->getVariable($property)) {
                    $args[] = $this->getVariable($property);
                } else {
                    throw new \Exception($operation.' ('.$version.') requires the \''.$property.'\'property to be set.');
                }

            }
        }
        return call_user_func_array('sprintf', $args);
    }
    protected function buildPayload ($operation, $version = 'v1')
    {
        if (in_array($this->map[$version][$operation]['method'], array('POST', 'PUT'))) {
            if (!isset($this->map[$version][$operation]['payload']['model'])) {
                $payload = $this->getVariables();
                if (isset($this->map[$version][$operation]['payload']['required'])) {
                    foreach ($this->map[$version][$operation]['payload']['required'] as $index => $property) {
                        if (empty($payload[$property])) {
                            throw new \Exception($property." required");
                        }
                    }
                }
                if (isset($this->map[$version][$operation]['payload']['ignored'])) {
                    foreach ($this->map[$version][$operation]['payload']['ignored'] as $index => $property) {
                        unset($payload[$property]);
                    }
                }
            } else {
                foreach ($this->getModel($this->map[$version][$operation]['payload']['model']) as $prop => $val) {
                    if (!empty($val)) {
                        $payload[$prop] = $val;
                    }
                }
            }
            return json_encode($payload);
        }
        return false;
    }
    protected function buildQuery ($operation, $version = 'v1')
    {
        $payload = array();
        if (isset($this->map[$version][$operation]['payload']['query'])) {
            foreach ($this->map[$version][$operation]['payload']['query'] as $index => $property) {
                if ($this->getVariable($property)) {
                    $payload[$property] = ($this->getVariable($property));
                }
            }
        }
        return $payload;
    }
    public function __toString()
    {
        return json_encode($this->getVariables());
    }
    public function __get($name)
    {
        $this->getVariable($name);
    }
    public function set($name, $val)
    {
        $this->setVariable($name, $val);
        return $this;
    }
    public function __set($name, $val)
    {
        $this->setVariable($name, $val);
    }
    public function __call($method, $args)
    {
        if (method_exists($this->model, $method)) {
            return call_user_func_array(array($this->model, $method), $args);
        } else {
            throw new \Exception('Tried to call unknown method '.$method);
        }
    }
}


text:
'use strict';

var matrix = angular.module('matrix', [
    'angular-sweetnotifier',
    'ngAnimate'
]);

var TYPES = [
    'info',
    'error',
    'warning',
    'success'
];

var getType = function() {
    return TYPES[Math.floor(Math.random() * (3 + 1))];
};

matrix.controller('MatrixController', function($scope, notifier) {
    $scope.notify = function(ver, hor) {
        $scope.placement = ver + ',' + hor;
        var type = getType();
        notifier.emit({
            type: type,
            timeout: 3000,
            title: type,
            content: 'This is an ' + type + ' notification!'
        });
    };

    $scope.native = function() {
        var type = getType();
        notifier.emit({
            useNative: true,
            type: type,
            timeout: 3000,
            title: type,
            content: 'This is an ' + type + ' notification!'
        });
    };
});
var $win = $(window);

var updateTooltip = function() {
    if ($win.width() >= 768) {
        $('.tooltip').tooltipster({position: 'right'});
    } else {
        $('.tooltip').tooltipster('destroy');
    }
};

updateTooltip();

$win.on('resize', updateTooltip);

$('.matrix ul li').on('mouseenter', function() {
    $(this).addClass('z-depth-5');
});
$('.matrix ul li').on('mouseleave', function() {
    $(this).removeClass('z-depth-5');
});


text:
import { createStore, createState } from 'test/support/Helpers'
import Model from '@/model/Model'

describe('Features – Relations – Morph One – Persist', () => {
  it('can create data containing the morph one relation', async () => {
    class Post extends Model {
      static entity = 'posts'

      static fields() {
        return {
          id: this.attr(null),
          comment: this.morphOne(Comment, 'commentable_id', 'commentable_type')
        }
      }
    }

    class Comment extends Model {
      static entity = 'comments'

      static fields() {
        return {
          id: this.attr(null),
          body: this.attr(''),
          commentable_id: this.attr(null),
          commentable_type: this.attr(null),
          commentable: this.morphTo('commentable_id', 'commentable_type')
        }
      }
    }

    const store = createStore([{ model: Post }, { model: Comment }])

    await store.dispatch('entities/posts/create', {
      data: {
        id: 1,
        comment: {
          id: 1,
          body: 'The Body',
          commentable_type: 'posts',
          commentable_id: 1
        }
      }
    })

    const expected = createState({
      posts: {
        1: { $id: '1', id: 1, comment: null }
      },
      comments: {
        1: {
          $id: '1',
          id: 1,
          body: 'The Body',
          commentable_type: 'posts',
          commentable_id: 1,
          commentable: null
        }
      }
    })

    expect(store.state.entities).toEqual(expected)
  })

  it('generates id and types for the morph one relations', async () => {
    class Post extends Model {
      static entity = 'posts'

      static fields() {
        return {
          id: this.attr(null),
          comment: this.morphOne(Comment, 'commentable_id', 'commentable_type')
        }
      }
    }

    class Video extends Model {
      static entity = 'videos'

      static fields() {
        return {
          id: this.attr(null),
          comment: this.morphOne(Comment, 'commentable_id', 'commentable_type')
        }
      }
    }

    class Comment extends Model {
      static entity = 'comments'

      static fields() {
        return {
          id: this.attr(null),
          body: this.attr(''),
          commentable_id: this.attr(null),
          commentable_type: this.attr(null)
        }
      }
    }

    const store = createStore([
      { model: Post },
      { model: Video },
      { model: Comment }
    ])

    await Post.create({
      data: {
        id: 1,
        comment: { id: 2, body: 'comment1' }
      }
    })

    expect(store.state.entities.posts.data['1'].id).toBe(1)
    expect(store.state.entities.comments.data['2'].id).toBe(2)
    expect(store.state.entities.comments.data['2'].commentable_id).toBe(1)
    expect(store.state.entities.comments.data['2'].commentable_type).toBe(
      'posts'
    )
  })

  it('generates only missing id or types for the morph one relations', async () => {
    class Post extends Model {
      static entity = 'posts'

      static fields() {
        return {
          id: this.attr(null),
          comment: this.morphOne(Comment, 'commentable_id', 'commentable_type')
        }
      }
    }

    class Video extends Model {
      static entity = 'videos'

      static fields() {
        return {
          id: this.attr(null),
          comment: this.morphOne(Comment, 'commentable_id', 'commentable_type')
        }
      }
    }

    class Comment extends Model {
      static entity = 'comments'

      static fields() {
        return {
          id: this.attr(null),
          body: this.attr(''),
          commentable_id: this.attr(null),
          commentable_type: this.attr(null)
        }
      }
    }

    const store = createStore([
      { model: Post },
      { model: Video },
      { model: Comment }
    ])

    await Post.create({
      data: {
        id: 1,
        comment: { id: 2, body: 'comment1', commentable_id: 1 }
      }
    })

    createState({
      posts: {
        1: { $id: '1', id: 1, comment: null }
      },
      videos: {},
      comments: {
        2: {
          $id: '2',
          id: 2,
          body: 'comment1',
          commentable_id: 1,
          commentable_type: 'posts'
        }
      }
    })

    expect(store.state.entities.posts.data['1'].id).toBe(1)
    expect(store.state.entities.comments.data['2'].id).toBe(2)
    expect(store.state.entities.comments.data['2'].commentable_id).toBe(1)
    expect(store.state.entities.comments.data['2'].commentable_type).toBe(
      'posts'
    )
  })

  it('would not generate id or types for non nested relations', async () => {
    class Post extends Model {
      static entity = 'posts'

      static fields() {
        return {
          id: this.attr(null),
          comments: this.morphOne(Comment, 'commentable_id', 'commentable_type')
        }
      }
    }

    class Video extends Model {
      static entity = 'videos'

      static fields() {
        return {
          id: this.attr(null),
          comments: this.morphOne(Comment, 'commentable_id', 'commentable_type')
        }
      }
    }

    class Comment extends Model {
      static entity = 'comments'

      static fields() {
        return {
          id: this.attr(null),
          body: this.attr(''),
          commentable_id: this.attr(null),
          commentable_type: this.attr(null)
        }
      }
    }

    const store = createStore([
      { model: Post },
      { model: Video },
      { model: Comment }
    ])

    await Comment.create({
      data: [
        { id: 2, body: 'comment1' },
        { id: 3, body: 'comment2' }
      ]
    })

    expect(store.state.entities.comments.data['2'].id).toBe(2)
    expect(store.state.entities.comments.data['2'].commentable_id).toBe(null)
    expect(store.state.entities.comments.data['2'].commentable_type).toBe(null)
    expect(store.state.entities.comments.data['3'].id).toBe(3)
    expect(store.state.entities.comments.data['3'].commentable_id).toBe(null)
    expect(store.state.entities.comments.data['3'].commentable_type).toBe(null)
  })

  it('generates id or types for the deeply nested morph one relations', async () => {
    class User extends Model {
      static entity = 'users'

      static fields() {
        return {
          id: this.attr('null'),
          posts: this.hasMany(Post, 'user_id')
        }
      }
    }

    class Post extends Model {
      static entity = 'posts'

      static fields() {
        return {
          id: this.attr(null),
          user_id: this.attr(null),
          comment: this.morphOne(Comment, 'commentable_id', 'commentable_type')
        }
      }
    }

    class Video extends Model {
      static entity = 'videos'

      static fields() {
        return {
          id: this.attr(null),
          comment: this.morphOne(Comment, 'commentable_id', 'commentable_type')
        }
      }
    }

    class Comment extends Model {
      static entity = 'comments'

      static fields() {
        return {
          id: this.attr(null),
          body: this.attr(''),
          commentable_id: this.attr(null),
          commentable_type: this.attr(null)
        }
      }
    }

    const store = createStore([
      { model: User },
      { model: Post },
      { model: Video },
      { model: Comment }
    ])

    await User.create({
      data: {
        id: 1,
        posts: [
          {
            id: 5,
            user_id: 1,
            comment: { id: 2, body: 'comment1', commentable_id: 1 }
          }
        ]
      }
    })

    createState({
      users: {
        1: { $id: '1', id: 1, posts: [] }
      },
      posts: {
        5: { $id: '5', id: 5, user_id: 1, comment: null }
      },
      videos: {},
      comments: {
        2: {
          $id: '2',
          id: 2,
          body: 'comment1',
          commentable_id: 1,
          commentable_type: 'posts'
        }
      }
    })

    expect(store.state.entities.users.data['1'].id).toBe(1)
    expect(store.state.entities.posts.data['5'].id).toBe(5)
    expect(store.state.entities.comments.data['2'].id).toBe(2)
    expect(store.state.entities.comments.data['2'].commentable_id).toBe(1)
    expect(store.state.entities.comments.data['2'].commentable_type).toBe(
      'posts'
    )
  })

  it('can create data containing the empty morph one relation', async () => {
    class Post extends Model {
      static entity = 'posts'

      static fields() {
        return {
          id: this.attr(null),
          comment: this.morphOne(Comment, 'commentable_id', 'commentable_type')
        }
      }
    }

    class Comment extends Model {
      static entity = 'comments'

      static fields() {
        return {
          id: this.attr(null),
          body: this.attr(''),
          commentable_id: this.attr(null),
          commentable_type: this.attr(null),
          commentable: this.morphTo('commentable_id', 'commentable_type')
        }
      }
    }

    const store = createStore([{ model: Post }, { model: Comment }])

    await store.dispatch('entities/posts/create', {
      data: [
        {
          id: 1,
          comment: {
            id: 1,
            body: 'The Body',
            commentable_type: 'posts',
            commentable_id: 1
          }
        },
        {
          id: 2,
          comment: null
        }
      ]
    })

    const expected = createState({
      posts: {
        1: { $id: '1', id: 1, comment: null },
        2: { $id: '2', id: 2, comment: null }
      },
      comments: {
        1: {
          $id: '1',
          id: 1,
          body: 'The Body',
          commentable_type: 'posts',
          commentable_id: 1,
          commentable: null
        }
      }
    })

    expect(store.state.entities).toEqual(expected)
  })

  it('can resolve a morph one relation', async () => {
    class Post extends Model {
      static entity = 'posts'

      static fields() {
        return {
          id: this.attr(null),
          comment: this.morphOne(Comment, 'commentable_id', 'commentable_type')
        }
      }
    }

    class Video extends Model {
      static entity = 'videos'

      static fields() {
        return {
          id: this.attr(null),
          comment: this.morphOne(Comment, 'commentable_id', 'commentable_type')
        }
      }
    }

    class Comment extends Model {
      static entity = 'comments'

      static fields() {
        return {
          id: this.attr(null),
          body: this.attr(''),
          commentable_id: this.attr(null),
          commentable_type: this.attr(null)
        }
      }
    }

    const store = createStore([
      { model: Post },
      { model: Video },
      { model: Comment }
    ])

    await store.dispatch('entities/posts/create', {
      data: {
        id: 1,
        comment: {
          id: 1,
          body: 'comment1',
          commentabe_id: 1,
          commentable_type: 'posts'
        }
      }
    })

    const post = store.getters['entities/posts/query']().with('comment').find(1)

    expect(post).toBeInstanceOf(Post)
    expect(post.comment).toBeInstanceOf(Comment)
  })

  it('generates id or type for the moprh relation', async () => {
    class Post extends Model {
      static entity = 'posts'

      static fields() {
        return {
          id: this.attr(null),
          comment: this.morphOne(Comment, 'commentable_id', 'commentable_type')
        }
      }
    }

    class Video extends Model {
      static entity = 'videos'

      static fields() {
        return {
          id: this.attr(null),
          comment: this.morphOne(Comment, 'commentable_id', 'commentable_type')
        }
      }
    }

    class Comment extends Model {
      static entity = 'comments'

      static fields() {
        return {
          id: this.attr(null),
          body: this.attr(''),
          commentable_id: this.attr(null),
          commentable_type: this.attr(null)
        }
      }
    }

    const store = createStore([
      { model: Post },
      { model: Video },
      { model: Comment }
    ])

    await store.dispatch('entities/posts/create', {
      data: {
        id: 1,
        comment: { id: 1, body: 'comment1' }
      }
    })

    const post = store.getters['entities/posts/query']().with('comment').find(1)

    expect(post).toBeInstanceOf(Post)
    expect(post.comment).toBeInstanceOf(Comment)
  })
})


text:
require 'active_support/dependencies'
require 'dialectic/engine'

module Dialectic
  mattr_accessor :orm

   def self.configure
     yield self
   end
end