text:
using System.Threading.Tasks;
using VI.Neural.extension;
using VI.Neural.LossFunction;
using VI.Neural.Node;
using VI.NumSharp;
using VI.NumSharp.Arrays;

namespace VI.Neural.Models
{
    public class DenseModel
    {
        private Array<INeuron> w;

        private ILossFunction _lf;

        public int[] Len => w.Len();

        public DenseModel(Array<INeuron> layers)
        {
            w = layers;
        }

        public float Learn(FloatArray inputs, FloatArray target)
        {
            ( var error, _ ) =  ComputeErrorNBackward( inputs, target );
            ( var dw, var db ) = ComputeGradient( inputs );
            UpdateParams( dw, db );

            return error;
        }

        public DenseModel()
        {
            w = new Array<INeuron>(0);
        }

        public void SetLossFunction(ILossFunction lf)
        {
            _lf = lf;
        }

        /// <summary>
        /// Include a new Layer on the model
        /// </summary>
        /// <param name="layer"></param>
        public void AddLayer(INeuron layer)
        {
            w = w.Join(layer);
        }

        /// <summary>
        /// Execute Feedforward N Get All layer Results
        /// </summary>
        /// <param name="inputs"></param>
        /// <returns>All layer Results</returns>
        public Array<FloatArray> FeedForward(FloatArray inputs)
        {
            var result = new Array<FloatArray>(w.Length);
            result[-1] = inputs;

            for (int i = 0; i < w.Length; i++)
            {
                result[i] = w[i].FeedForward(result[i - 1]);
            }

            return result;
        }

        /// <summary>
        /// Execute Feedforward N Get Output Layer Result
        /// </summary>
        /// <param name="inputs"></param>
        /// <returns>Output Layer Result</returns>
        public FloatArray Output(FloatArray inputs)
        {
            return FeedForward(inputs)[- 1];
        }

        /// <summary>
        /// Compute error for linear timing
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public (float loss, FloatArray dw) ComputeErrorNBackward(FloatArray inputs, FloatArray target)
        {
            var result = FeedForward(inputs);

            var dw = w[w.Length - 1].ComputeErrorNBackWard(target);

            for (int i = w.Length - 2; i >= 0; i--)
            {
                dw = w[i].BackWard(dw);
            }

            return ( _lf.Loss(target, result[-1]),  dw );
        }

        /// <summary>
        /// Compute error for linear timing
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public (float loss, FloatArray dw) ComputeErrorNBackward(FloatArray target, Array<FloatArray> output)
        {
            w.SetOutputs(output);
            var dw = w[-1].ComputeErrorNBackWard(target);

            for (int i = w.Length - 2; i >= 0; i--)
            {
                dw = w[i].BackWard(dw);
            }

           return ( _lf.Loss(target, output[-1]),  dw );
        }

        /// <summary>
        /// Backward for linear timing
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public FloatArray Backward(FloatArray inputs, FloatArray error)
        {
            FeedForward(inputs);

            var dw = new FloatArray(0);

            for (int i = w.Length - 1; i >= 0; i--)
            {
                dw = w[i].BackWard(dw);
            }

            return dw;
        }

        /// <summary>
        /// Backward for non-linear timing
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public FloatArray Backward(FloatArray error, Array<FloatArray> output)
        {
            w.SetOutputs(output);
            var dw = new FloatArray(0);

            for (int i = w.Length - 1; i >= 0; i--)
            {
                dw = w[i].BackWard(dw);
            }

            return dw;
        }

        /// <summary>
        /// Compute All layer Gradients
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public (Array<FloatArray2D> dw, Array<FloatArray> db) ComputeGradient(FloatArray input)
        {
            w[0].ComputeGradient(input);

            for (int i = 1; i <  w.Length ; i++)
            {
                w[i].ComputeGradient(w[i - 1].Nodes.OutputVector);
            }

            return (w.GetWeightsGradient(), w.GetBiasGradient());
        }

        /// <summary>
        /// Update Params from all layers
        /// </summary>
        /// <param name="dw"></param>
        /// <param name="db"></param>
        public void UpdateParams(Array<FloatArray2D> dw, Array<FloatArray> db)
        {
            for (int i = 0; i <  w.Length ; i++)
            {
                w[i].UpdateParams(dw[i], db[i]);
            }
        }
    }
}


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.storage.resource;

import java.util.List;

import org.apache.log4j.Logger;
import org.apache.log4j.NDC;

import com.google.gson.Gson;
import com.vmware.vim25.ManagedObjectReference;

import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
import org.apache.cloudstack.storage.resource.SecondaryStorageResourceHandler;

import com.cloud.agent.api.Answer;
import com.cloud.agent.api.BackupSnapshotCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
import com.cloud.agent.api.storage.CopyVolumeCommand;
import com.cloud.agent.api.storage.CreateEntityDownloadURLCommand;
import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
import com.cloud.hypervisor.vmware.manager.VmwareHostService;
import com.cloud.hypervisor.vmware.manager.VmwareStorageManager;
import com.cloud.hypervisor.vmware.manager.VmwareStorageManagerImpl;
import com.cloud.hypervisor.vmware.manager.VmwareStorageMount;
import com.cloud.hypervisor.vmware.mo.ClusterMO;
import com.cloud.hypervisor.vmware.mo.HostMO;
import com.cloud.hypervisor.vmware.mo.VmwareHostType;
import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost;
import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHostNetworkSummary;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.cloud.serializer.GsonHelper;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils;

public class VmwareSecondaryStorageResourceHandler implements SecondaryStorageResourceHandler, VmwareHostService, VmwareStorageMount {
    private static final Logger s_logger = Logger.getLogger(VmwareSecondaryStorageResourceHandler.class);

    private final PremiumSecondaryStorageResource _resource;
    private final VmwareStorageManager _storageMgr;

    private final Gson _gson;
    private final StorageSubsystemCommandHandler storageSubsystemHandler;

    private static ThreadLocal<VmwareContext> currentContext = new ThreadLocal<VmwareContext>();

    /*
     * private Map<String, HostMO> _activeHosts = new HashMap<String, HostMO>();
     */

    public VmwareSecondaryStorageResourceHandler(PremiumSecondaryStorageResource resource, Integer nfsVersion) {
        _resource = resource;
        _storageMgr = new VmwareStorageManagerImpl(this, nfsVersion);
        _gson = GsonHelper.getGsonLogger();

        VmwareStorageProcessor storageProcessor = new VmwareStorageProcessor(this, true, this, resource.getTimeout(), null, null, _resource, nfsVersion);
        VmwareStorageSubsystemCommandHandler vmwareStorageSubsystemCommandHandler = new VmwareStorageSubsystemCommandHandler(storageProcessor, nfsVersion);
        vmwareStorageSubsystemCommandHandler.setStorageResource(_resource);
        vmwareStorageSubsystemCommandHandler.setStorageManager(_storageMgr);
        storageSubsystemHandler = vmwareStorageSubsystemCommandHandler;
    }

    private static String getCommandLogTitle(Command cmd) {
        StringBuffer sb = new StringBuffer();
        if (cmd.getContextParam("job") != null) {
            sb.append(cmd.getContextParam("job"));
        }

        sb.append(", cmd: ").append(cmd.getClass().getSimpleName());

        return sb.toString();
    }

    @Override
    public Answer executeRequest(Command cmd) {

        try {
            Answer answer;
            NDC.push(getCommandLogTitle(cmd));

            if (s_logger.isDebugEnabled())
                s_logger.debug("Executing " + _gson.toJson(cmd));

            if (cmd instanceof PrimaryStorageDownloadCommand) {
                answer = execute((PrimaryStorageDownloadCommand)cmd);
            } else if (cmd instanceof BackupSnapshotCommand) {
                answer = execute((BackupSnapshotCommand)cmd);
            } else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) {
                answer = execute((CreatePrivateTemplateFromVolumeCommand)cmd);
            } else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
                answer = execute((CreatePrivateTemplateFromSnapshotCommand)cmd);
            } else if (cmd instanceof CopyVolumeCommand) {
                answer = execute((CopyVolumeCommand)cmd);
            } else if (cmd instanceof CreateVolumeFromSnapshotCommand) {
                answer = execute((CreateVolumeFromSnapshotCommand)cmd);
            } else if (cmd instanceof StorageSubSystemCommand) {
                answer = storageSubsystemHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
            } else if (cmd instanceof CreateEntityDownloadURLCommand) {
                answer = execute((CreateEntityDownloadURLCommand)cmd);
            } else {
                answer = _resource.defaultAction(cmd);
            }

            // special handling to pass-back context info for cleanups
            if (cmd.getContextParam("execid") != null) {
                answer.setContextParam("execid", cmd.getContextParam("execid"));
            }

            if (cmd.getContextParam("checkpoint") != null) {
                answer.setContextParam("checkpoint", cmd.getContextParam("checkpoint"));
            }

            if (cmd.getContextParam("checkpoint2") != null) {
                answer.setContextParam("checkpoint2", cmd.getContextParam("checkpoint2"));
            }

            if (s_logger.isDebugEnabled())
                s_logger.debug("Command execution answer: " + _gson.toJson(answer));

            return answer;
        } finally {
            if (s_logger.isDebugEnabled())
                s_logger.debug("Done executing " + _gson.toJson(cmd));
            recycleServiceContext();
            NDC.pop();
        }
    }

    protected Answer execute(CreateEntityDownloadURLCommand cmd) {
        boolean success = _storageMgr.execute(this, cmd);
        if (success) {
            return _resource.defaultAction(cmd);
        }
        return new Answer(cmd, false, "Failed to download");
    }

    private Answer execute(PrimaryStorageDownloadCommand cmd) {
        return _storageMgr.execute(this, cmd);
    }

    private Answer execute(BackupSnapshotCommand cmd) {
        return _storageMgr.execute(this, cmd);
    }

    private Answer execute(CreatePrivateTemplateFromVolumeCommand cmd) {
        return _storageMgr.execute(this, cmd);
    }

    private Answer execute(CreatePrivateTemplateFromSnapshotCommand cmd) {
        return _storageMgr.execute(this, cmd);
    }

    private Answer execute(CopyVolumeCommand cmd) {
        return _storageMgr.execute(this, cmd);
    }

    private Answer execute(CreateVolumeFromSnapshotCommand cmd) {
        return _storageMgr.execute(this, cmd);
    }

    @Override
    public VmwareContext getServiceContext(Command cmd) {
        String guid = cmd.getContextParam("guid");
        if (guid == null || guid.isEmpty()) {
            s_logger.error("Invalid command context parameter guid");
            return null;
        }

        String username = cmd.getContextParam("username");
        if (username == null || username.isEmpty()) {
            s_logger.error("Invalid command context parameter username");
            return null;
        }

        String password = cmd.getContextParam("password");

        // validate command guid parameter
        String[] tokens = guid.split("@");
        if (tokens == null || tokens.length != 2) {
            s_logger.error("Invalid content in command context parameter guid");
            return null;
        }

        String vCenterAddress = tokens[1];
        String[] hostTokens = tokens[0].split(":");
        if (hostTokens == null || hostTokens.length != 2) {
            s_logger.error("Invalid content in command context parameter guid");
            return null;
        }

        int vCenterSessionTimeout = NumbersUtil.parseInt(cmd.getContextParam("vCenterSessionTimeout"), 1200000);

        try {
            _resource.ensureOutgoingRuleForAddress(vCenterAddress);

            VmwareContext context = currentContext.get();
            if (context != null && !context.validate()) {
                invalidateServiceContext(context);
                context = null;
            }
            if (context == null) {
                s_logger.info("Open new VmwareContext. vCenter: " + vCenterAddress + ", user: " + username + ", password: " + StringUtils.getMaskedPasswordForDisplay(password));
                VmwareSecondaryStorageContextFactory.setVcenterSessionTimeout(vCenterSessionTimeout);
                context = VmwareSecondaryStorageContextFactory.getContext(vCenterAddress, username, password);
            }
            if (context != null) {
                context.registerStockObject("serviceconsole", cmd.getContextParam("serviceconsole"));
                context.registerStockObject("manageportgroup", cmd.getContextParam("manageportgroup"));
                context.registerStockObject("noderuninfo", cmd.getContextParam("noderuninfo"));
            }
            currentContext.set(context);
            return context;
        } catch (Exception e) {
            s_logger.error("Unexpected exception " + e.toString(), e);
            return null;
        }
    }

    public void recycleServiceContext() {
        if (currentContext.get() != null) {
            VmwareContext context = currentContext.get();
            currentContext.set(null);
            assert (context.getPool() != null);
            context.getPool().registerContext(context);
        }
    }

    @Override
    public void invalidateServiceContext(VmwareContext context) {
        currentContext.set(null);
        VmwareSecondaryStorageContextFactory.invalidate(context);
    }

    @Override
    public VmwareHypervisorHost getHyperHost(VmwareContext context, Command cmd) {
        String guid = cmd.getContextParam("guid");
        assert (guid != null);

        String[] tokens = guid.split("@");
        assert (tokens != null && tokens.length == 2);

        ManagedObjectReference morHyperHost = new ManagedObjectReference();
        String[] hostTokens = tokens[0].split(":");
        if (hostTokens == null || hostTokens.length != 2) {
            s_logger.error("Invalid content in command context parameter guid");
            return null;
        }

        morHyperHost.setType(hostTokens[0]);
        morHyperHost.setValue(hostTokens[1]);

        if (morHyperHost.getType().equalsIgnoreCase("HostSystem")) {
            HostMO hostMo = new HostMO(context, morHyperHost);

            try {

                ManagedObjectReference mor = hostMo.getHyperHostCluster();
                ClusterMO clusterMo = new ClusterMO(hostMo.getContext(), mor);
                List<Pair<ManagedObjectReference, String>> hostsInCluster = clusterMo.getClusterHosts();
                for (Pair<ManagedObjectReference, String> hostPair : hostsInCluster) {
                    HostMO hostIteratorMo = new HostMO(hostMo.getContext(), hostPair.first());

                    VmwareHypervisorHostNetworkSummary netSummary =
                        hostIteratorMo.getHyperHostNetworkSummary(hostIteratorMo.getHostType() == VmwareHostType.ESXi ? cmd.getContextParam("manageportgroup")
                            : cmd.getContextParam("serviceconsole"));
                    _resource.ensureOutgoingRuleForAddress(netSummary.getHostIp());

                    s_logger.info("Setup firewall rule for host: " + netSummary.getHostIp());
                }
            } catch (Throwable e) {
                s_logger.warn("Unable to retrive host network information due to exception " + e.toString() + ", host: " + hostTokens[0] + "-" + hostTokens[1]);
            }

            return hostMo;
        }

        assert (false);
        return new ClusterMO(context, morHyperHost);
    }

    @Override
    public String getWorkerName(VmwareContext context, Command cmd, int workerSequence) {
        assert (cmd.getContextParam("worker") != null);
        assert (workerSequence < 2);

        if (workerSequence == 0)
            return cmd.getContextParam("worker");
        return cmd.getContextParam("worker2");
    }

    @Override
    public String getMountPoint(String storageUrl, Integer nfsVersion) {
        return _resource.getRootDir(storageUrl, nfsVersion);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<title>
More Black men in jail than college
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

The sick face of racism in the U.S.

More Black men in jail than college

By Elizabeth Schulte | September 6, 2002 | Page 12

THE U.S. would rather fill a jail than a school. That was the conclusion of a study released last month by the Washington-based research and advocacy group Justice Policy Institute (JPI). By the end of last year, one out of every 32 adults in the U.S.--or 6.6 million people--was behind bars, on probation or on parole.

The JPI report compared two decades of data from the Bureau of Justice Statistics and the National Center for Education Statistics--and found that while states had plenty to spend on prisons, they had much less to devote to education.

Between 1985 and 2000, the increase in state spending on corrections was nearly double the increase for higher education. "This report underlines the sad reality that the nation's colleges and universities have lost budget battles to the growing prison system," said Vincent Schiraldi, JPI's president and co-author of the study.

Meanwhile, states have shifted the financial burden onto students. Between 1980 and 1998, the cost of paying for tuition at a four-year college rose from 13 percent of a poor family's income to 25 percent.

These statistics are grim, but for Black men, they get even grimmer. African American men are more likely to go to jail than go to college, according to the JPI study. From 1980 to 2000, the number of African American men in jail or prison grew three times as fast as the number in colleges and universities.

Lamont and Lawrence Garrison are two examples. The twins, who are Black, were just a month away from finishing college at Howard University when they were arrested on drug charges in April 1998. They were found guilty based on the unsubstantiated testimony of a confessed drug dealer who was hoping to lower his sentence. Lamont was sentenced to 19 years; Lawrence got 15 years.

This is the price being paid for two decades of the politicians' tough-on-crime policies that have filled prisons, even as violent crime arrests have dropped.

And George W. Bush's law-and-order home state of Texas is the worst. Texas had more adults under correctional supervision than any other state--755,100--last year. From 1986 to 2000, the amount that Texas spent on higher education grew by 47 percent--while its corrections budget jumped by 346 percent!

Both mainstream political parties are to blame for this travesty. Bill Clinton matched the Republicans in punitive crime policies, with truth-in-sentencing and minimum-sentencing laws. "This is because policies that are 'tough on crime' are politically risk free," said Todd Clear, a professor at the John Jay College of Criminal Justice in New York. "They're made by politicians seeking election on the basis of what sounds good at the time, and paid for by people not yet voting. Their effects on the prison population don't come into play until 10 or 15 years down the line."

In some states, the obvious failure of tough sentencing laws has led some legislatures to propose laws to end mandatory minimum sentencing, reform the nation's drug laws and de-fund new prison construction and expansion.

But it's time to look at the whole criminal justice system. There's something wrong with a system that would rather lock away young people than teach them. Education, not incarceration!

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
package log

import (
	"fmt"
	"io"
	goLog "log"
	"os"
	"runtime"
	"strings"
	"time"
)

var (
	gologstderr   = goLog.New(os.Stderr, "", 0)
	gologstdout   = goLog.New(os.Stdout, "", 0)
	gologiowriter io.Writer

	standard Standard
)

type Standard struct{}

func (_ Standard) SetOutput(w io.Writer) {
	gologiowriter = w
	goLog.SetOutput(gologiowriter)
}

func StdErrOutput(level string, args ...interface{}) {
	_, file, line, _ := runtime.Caller(4)
	pkgs := strings.Split(file, "/")

	logMsg := fmt.Sprint(args...)
	timestamp := time.Now().Format("2006-01-02 15:04:05")
	if gologiowriter != nil { //give preference to gologiowriter
		// "\r" Eliminates the default message prefix so we can format as we like.
		goLog.Printf("\r%v [%v] %v:%v: %v", timestamp, level, pkgs[len(pkgs)-1], line, logMsg)
	} else {
		gologstderr.Printf("%v [%v] %v:%v: %v", timestamp, level, pkgs[len(pkgs)-1], line, logMsg)
	}
}

func StdOutOutput(level string, args ...interface{}) {
	_, file, line, _ := runtime.Caller(4)
	pkgs := strings.Split(file, "/")

	logMsg := fmt.Sprint(args...)
	timestamp := time.Now().Format("2006-01-02 15:04:05")
	if gologiowriter != nil { //give preference to gologiowriter
		// "\r" Eliminates the default message prefix so we can format as we like.
		goLog.Printf("\r%v [%v] %v:%v: %v", timestamp, level, pkgs[len(pkgs)-1], line, logMsg)
	} else {
		gologstdout.Printf("%v [%v] %v:%v: %v", timestamp, level, pkgs[len(pkgs)-1], line, logMsg)
	}
}

func (_ Standard) Fatal(args ...interface{}) {
	StdErrOutput("FATAL", args...)
	os.Exit(1)
}

func (_ Standard) Error(args ...interface{}) {
	StdErrOutput("ERROR", args...)
}

func (_ Standard) Warn(args ...interface{}) {
	StdOutOutput("WARN", args...)
}

func (_ Standard) Info(args ...interface{}) {
	StdOutOutput("INFO", args...)
}

func (_ Standard) Debug(args ...interface{}) {
	StdOutOutput("DEBUG", args...)
}

func (_ Standard) Trace(args ...interface{}) {
	StdOutOutput("TRACE", args...)
}


text:
// @formatter:off

package com.microsoft.alm.teamfoundation.sourcecontrol.webapi;

/**
 */
public class TfvcItemRequestData {

    /**
    * If true, include metadata about the file type
    */
    private boolean includeContentMetadata;
    /**
    * Whether to include the _links field on the shallow references
    */
    private boolean includeLinks;
    private TfvcItemDescriptor[] itemDescriptors;

    /**
    * If true, include metadata about the file type
    */
    public boolean getIncludeContentMetadata() {
        return includeContentMetadata;
    }

    /**
    * If true, include metadata about the file type
    */
    public void setIncludeContentMetadata(final boolean includeContentMetadata) {
        this.includeContentMetadata = includeContentMetadata;
    }

    /**
    * Whether to include the _links field on the shallow references
    */
    public boolean getIncludeLinks() {
        return includeLinks;
    }

    /**
    * Whether to include the _links field on the shallow references
    */
    public void setIncludeLinks(final boolean includeLinks) {
        this.includeLinks = includeLinks;
    }

    public TfvcItemDescriptor[] getItemDescriptors() {
        return itemDescriptors;
    }

    public void setItemDescriptors(final TfvcItemDescriptor[] itemDescriptors) {
        this.itemDescriptors = itemDescriptors;
    }
}


text:
from pysnmp.proto.mpmod import cache
from pysnmp.proto import error

class AbstractMessageProcessingModel:
    snmpMsgSpec = NotImplementedError
    def __init__(self):
        self._snmpMsgSpec = self.snmpMsgSpec()  # local copy
        self._cache = cache.Cache()

    def prepareOutgoingMessage(self, snmpEngine, transportDomain,
                               transportAddress, messageProcessingModel,
                               securityModel, securityName, securityLevel,
                               contextEngineId, contextName, pduVersion,
                               pdu, expectResponse, sendPduHandle):
        raise error.ProtocolError('method not implemented')

    def prepareResponseMessage(self, snmpEngine, messageProcessingModel,
                               securityModel, securityName, securityLevel,
                               contextEngineId, contextName, pduVersion,
                               pdu, maxSizeResponseScopedPDU,
                               stateReference, statusInformation):
        raise error.ProtocolError('method not implemented')

    def prepareDataElements(self, snmpEngine, transportDomain,
                            transportAddress, wholeMsg):
        raise error.ProtocolError('method not implemented')

    def releaseStateInformation(self, sendPduHandle):
        try:
            self._cache.popBySendPduHandle(sendPduHandle)
        except error.ProtocolError:
            pass # XXX maybe these should all follow some scheme?

    def receiveTimerTick(self, snmpEngine, timeNow):
        self._cache.expireCaches()


text:
define(['plugins/http', 'durandal/app', 'knockout'], function (http, app, ko) {
    //Note: This module exports an object.
    //That means that every module that "requires" it will get the same object instance.
    //If you wish to be able to create multiple instances, instead export a function.
    //See the "welcome" module for an example of function export.
    var mens_array = [];
    return {

        attached: function () {
            var Item = function (rem, ass, mens) {
                this.rem = rem;
                this.ass = ass;
                this.mens = mens;
            };
            if (localStorage.getItem("valor") == 1) {
                var x = (JSON.parse(localStorage.getItem('array_pedido')));
                var item = new Item(x[0], x[1], x[2]);
                mens_array.push(item);
                localStorage.setItem("mensagens_cliente", JSON.stringify(mens_array));
                localStorage.setItem("valor", 0);
            };
            addArray = function (rem, ass, mens) {
                if(rem!="" && ass!="" && mens!= ""){
                    var item = new Item(rem, ass, mens);
                    mens_array.push(item);
                    localStorage.setItem("mensagens_cliente", JSON.stringify(mens_array));
                    $('#myModal').modal('hide');
                    $('body').removeClass('modal-open');
                    $('.modal-backdrop').remove();
                } else {
                    alert("Dados por preencher");
                }
            };

            if (JSON.stringify(localStorage.getItem("mensagens_lavandaria")) != JSON.stringify('[]')) {
                var mens_array_2 = JSON.parse(localStorage.getItem("mensagens_lavandaria"));
                var remetente = "";
                var assunto = "";
                var mensagem = "";
                var botao = "";
                if (mens_array_2 == null || mens_array_2.length == 0) {
                    $("#caixa").append("
Não tem mensagens
");
                } else {
                    for (i = 0; i < mens_array_2.length; i++) {
                        remetente = "

REMETENTE:

" + mens_array_2[i].rem + "

";
                        assunto = "

ASSUNTO:

" + mens_array_2[i].ass + "

";
                        mensagem = "

MENSAGEM:

" + mens_array_2[i].mens + "

";
                        botao = "
<button type='button' class='btn btn-default' onclick='removeMessage2(" + i + ")'>Remover</button>
";
                        $("#caixa").append(remetente);
                        $("#caixa").append(assunto);
                        $("#caixa").append(mensagem);
                        $("#caixa").append(botao);
                    }
                }
            }
            removeMessage2 = function (numero) {
                $("#" + numero + "a").remove();
                $("#" + numero + "x").remove();
                $("#" + numero + "d").remove();
                $("#" + numero + "e").remove();
                for (z = 0; z < mens_array_2.length; z++) {
                    if (numero == z) {
                        mens_array_2.splice(z, 1);
                    }
                }
                localStorage.setItem("mensagens_lavandaria", JSON.stringify(mens_array_2));
                if (mens_array_2 == null || mens_array_2.length==0) {
                    $("#caixa").append("
Não tem mensagens
");
                }
            }

        },
        displayName: 'Flickr',
        select: function (item) {
            //the app model allows easy display of modal dialogs by passing a view model
            //views are usually located by convention, but you an specify it as well with viewUrl
            item.viewUrl = 'views/detail';
            app.showDialog(item);
        }
    }
});


text:
use std::thread;
use std::sync::{Arc, Mutex, MutexGuard};

use std::time::{Duration, Instant};

use connection::{Event, Writer};
use message::Prefix;

#[derive(Clone)]
enum MonitorStatus {
    // Last activity, timespec is when.
    Activity(Instant),
    // Ping was sent, timespec is when.
    Ping(Instant),
}

#[derive(Clone)]
enum ConnectionStatus {
    // Connection is alive and well.
    Connected(MonitorStatus),
    // Connection was dropped.
    Disconnected,
    // When the monitor receives a close event, it sets the status
    // to this value to let the background thread know it should stop.
    Quit,
}

#[derive(Clone)]
struct State {
    // Holds the status of the connection.
    status: Arc<Mutex<ConnectionStatus>>,
    // When sending a ping message on irc, you need to specify the server.
    // This holds the current server's name, it's grabbed from the event
    // stream by the feed method.
    server: Arc<Mutex<Option<String>>>,
}

impl State {

    fn new(ts: Instant) -> State {
        let conn_status = ConnectionStatus::Connected(MonitorStatus::Activity(ts));
        State {
            status: Arc::new(Mutex::new(conn_status)),
            server: Arc::new(Mutex::new(None)),
        }
    }

    // Set the last activity's timestamp.
    fn set_activity(&self, ts: Instant) {
        *self.status.lock().unwrap() = ConnectionStatus::Connected(MonitorStatus::Activity(ts));
    }

    // Set the status to disconnected.
    fn set_disconnected(&self) {
        *self.status.lock().unwrap() = ConnectionStatus::Disconnected;
    }

    // Set the status to quit.
    fn quit(&self) {
        *self.status.lock().unwrap() = ConnectionStatus::Quit;
    }

    // Get the connection status.
    fn connection_status<'a>(&self) -> MutexGuard<ConnectionStatus> {
        self.status.lock().unwrap()
    }

    // Check if the server variable is set.
    fn has_server(&self) -> bool {
        self.server.lock().unwrap().is_some()
    }

    // Get the server's name.
    fn get_server(&self) -> MutexGuard<Option<String>> {
        self.server.lock().unwrap()
    }

    // Set the server's name.
    fn set_server(&self, name: String) {
        *self.server.lock().unwrap() = Some(name);
    }

    // Unsert the server name. Used when a disconnection occurs.
    fn unset_server(&self) {
        *self.server.lock().unwrap() = None;
    }

}

fn periodic_checker(state: State, handle: Writer, settings: MonitorSettings) {
    loop {
        let mut conn_status = state.connection_status();

        // Clone here, to we can mutate the status inside the match.
        // The type is Copy anyway.
        match conn_status.clone() {
            ConnectionStatus::Connected(ref mon_status) => {
                match *mon_status {
                    // The monitor is in activity mode.
                    // If the timer expires, it will ping the server and set the monitor status
                    // to ping mode.
                    MonitorStatus::Activity(activity_ts) => {
                        let diff = activity_ts.elapsed();
                        if diff > settings.activity_timeout {
                            // Make sure we have a server name.
                            match *state.get_server() {
                                Some(ref server) =>  {
                                    // Set the monitor's status to ping mode.
                                    *conn_status = ConnectionStatus::Connected(MonitorStatus::Ping(Instant::now()));
                                    // Send a ping, which should trigger activity is the connection is still alive.
                                    let _ = handle.raw(format!("PING {}\n", server));
                                }
                                None => {
                                    // This should really never happen. The server's name should be grabbed
                                    // almost instantly, when the first message is received from the server
                                    // after establishing a new connection.
                                    panic!("Server is None! This scenario is highly unlikely, please report this issue!");
                                }
                            }

                        }
                    }
                    // The monitor is in ping mode, which means it expects a ping response anytime.
                    // If the timer expires, the connection is set to disconnect mode.
                    MonitorStatus::Ping(ping_ts) => {
                        let diff = ping_ts.elapsed();
                        if diff > settings.ping_timeout {
                            // trigger reconnection process
                            let _ = handle.disconnect();
                        }
                    },
                }
            },
            // Do nothing if the socket is disconnected, for now.
            ConnectionStatus::Disconnected => {},
            ConnectionStatus::Quit => break,
        }

        // Drop the lock to avoid a dead lock.
        drop(conn_status);
        thread::sleep(Duration::from_secs(1));
    }
}

/// These settings tell the monitor how to behave.
///
/// They allow you to configure the amount of time between the steps.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct MonitorSettings {
    /// Amount of time since the last activity.
    ///
    /// When the amount of time since the last activity gets higher than this value,
    /// tt will trigger a ping request. If there is not a lot of activity, this means
    /// that the server will be pinged everytime this duration expires.
    pub activity_timeout: Duration,
    /// Amount of time to wait for a ping reply.
    ///
    /// When the amount of time since the ping was sent gets higher than this value,
    /// and that no activity occured, assume the connection was dropped and trigger
    /// and a disconnect.
    pub ping_timeout: Duration,
}

/// Default values are provided for the settings.
///
/// They are:
///
/// `activity_timeout` = 60 seconds
///
/// `ping_timeout` = 15 seconds
impl Default for MonitorSettings {

    fn default() -> MonitorSettings {
        MonitorSettings {
            activity_timeout: Duration::from_secs(60),
            ping_timeout: Duration::from_secs(15),
        }
    }

}

/// This struct monitors a connection's activity.
///
/// It works in a few simple, steps.
/// First, it monitors activity via the feed method, saving a timestamp for relevant events.
/// If no activity is detected over the given period of time, it will send a ping request to
/// the IRC server. If no ping  reply is received, it will trigger a disconnect which may lead
/// to reconnection depending on the reconnection settings.
///
/// The amount of time to wait, without activity, before sending a ping request, and the amount
/// of time to wait for the ping reply can be configured via the `MonitorSettings` struct.
pub struct ActivityMonitor {
    state: State,
}

impl ActivityMonitor {

    /// Create a new ActivityMonitor.
    ///
    /// The handle to a Writer allows the monitor to notify the connection of disconnects.
    pub fn new(handle: &Writer, settings: MonitorSettings) -> ActivityMonitor {
        let state =  State::new(Instant::now());

        let state_clone = state.clone();
        let handle_clone = handle.clone();

        thread::spawn(move || {
            periodic_checker(state_clone, handle_clone, settings);
        });

        ActivityMonitor {
            state: state,
        }
    }

    /// Give an event received from the connection to the monitor.
    ///
    /// The monitor will process it accordingly. If an Event::Closed event
    /// is received, it will shutdown all of its activities.
    pub fn feed(&self, event: &Event) {
        match *event {
            Event::Closed(_) => {
                self.state.quit();
            }
            Event::Disconnected => {
                self.state.set_disconnected();
                self.state.unset_server();
            }
            Event::Reconnected => {
                self.state.set_activity(Instant::now());
            }
            Event::Message(ref msg) => {
                self.state.set_activity(Instant::now());
                if let Some(ref prefix) = msg.prefix {
                    match *prefix {
                        Prefix::Server(ref name) => {
                            if !self.state.has_server() {
                                self.state.set_server(name.clone());
                            }
                        }
                        _ => {}
                    }
                }
            }
            // Other events are irrelevant.
            _ => {}
        }
    }

}

/// Drop stops the background thread and clears the monitor's resources.
///
/// If you want the activity monitor to cease its activites, you can simply drop it.
/// It will not affect the connection on which the activity monitor operates.
impl Drop for ActivityMonitor {

    fn drop(&mut self) {
        self.state.quit();
    }

}


text:
<meta charset="UTF-8">
<title>MockerConfig.provideFieldPreparer - mockspresso-api</title>
<link rel="stylesheet" href="../../../style.css">

mockspresso-api / com.episode6.hackit.mockspresso.api / MockerConfig / provideFieldPreparer

provideFieldPreparer

@NotNull abstract fun provideFieldPreparer(): MockerConfig.FieldPreparer

Return

MockerConfig.FieldPreparer: The FieldPreparer to be used by this config.


text:
/*import {
  it,
  iit,
  describe,
  ddescribe,
  expect,
  inject,
  injectAsync,
  TestComponentBuilder,
  beforeEachProviders
} from 'angular2/testing';
import {provide} from 'angular2/core';
import {Languages} from './languages';

describe('Languages Component', () => {

  beforeEachProviders((): any[] => []);

  it('should ...', injectAsync([TestComponentBuilder], (tcb:TestComponentBuilder) => {
    return tcb.createAsync(Languages).then((fixture) => {
      fixture.detectChanges();
    });
  }));

});
*/


text:
import mongoose from 'mongoose'
// import rules from '../model/rules'

// import {
//   HTTP_OK,
//   // HTTP_CREATED,
//   HTTP_NOT_FOUND,
//   HTTP_BAD_REQUEST,
//   // HTTP_INTERNAL_SERVER_ERROR,
// } from '../../../shared/config'

import { DEFAULT_RANK } from '../../../shared/config'

mongoose.set('debug', true)

exports.calcRank = (nodeId: String) => {
  // Get rules
  // rules.get(() => {
    // calcMSBN * MSBNr + calcMSNS * MSNSr
    // TODO: save all syncs with server
    // TODO: retrieve sync with server
    // TODO: save max sync with server and max handshake counter
  let rank = DEFAULT_RANK
  if (nodeId != null) {
    rank = 3
  }
  rank = 2
  return rank
  // })
}


text:
package org.jboss.as.quickstarts.spring.petclinic.test.webdriver;

import java.io.File;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;

/**
 *
 * @author Karel Piwko
 *
 */
public class Deployments {
    private static final String PETCLINIC = "../target/jboss-spring-petclinic.war";

    public static WebArchive archive() {
        WebArchive archive = ShrinkWrap.createFromZipFile(WebArchive.class, new File(PETCLINIC));

        String discriminator = System.getProperty("discriminator");
        if (discriminator.equals("jdbc")) {
            archive.addAsWebInfResource(new File("src/test/resources/jdbc_web.xml"), "web.xml");
        } else if (discriminator.equals("spring-data-jpa")) {
            archive.addAsWebInfResource(new File("src/test/resources/spring_data_jpa_web.xml"), "web.xml");
        }
        return archive;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `WriteExt` trait in crate `std`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, WriteExt">

    <title>std::io::WriteExt - Rust</title>

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

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

std::<wbr>io

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Trait std::<wbr>io::<wbr>WriteExt<wbr>Unstable
            [-] [+]
        [src]

pub trait WriteExt: Write + Sized {
    fn by_ref(&mut self) -> &mut Self { ... }
    fn broadcast<W: Write>(self, other: W) -> Broadcast<Self, W> { ... }
}

Extension methods for all instances of Write, typically imported through
std::io::prelude::*.

Provided Methods

fn by_ref(&mut self) -> &mut Self

Create a "by reference" adaptor for this instance of Write.

The returned adaptor also implements Write and will simply borrow this
current writer.

fn broadcast<W: Write>(self, other: W) -> Broadcast<Self, W>

Creates a new writer which will write all data to both this writer and
another writer.

All data written to the returned writer will both be written to self
as well as other. Note that the error semantics of the current
implementation do not precisely track where errors happen. For example
an error on the second call to write will not report that the first
call to write succeeded.

Implementors

impl<T: Write> WriteExt for T

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
<!doctype html>

    <title>AngularJS Library - Combination Filter</title>

    <link rel="stylesheet" href="../../vendor/bootstrap/docs/assets/css/bootstrap.css">

    <link rel="stylesheet" href="../../vendor/google-code-prettify/src/prettify.css">
    <link rel="stylesheet" href="./css/main.css">

Combination Filter

            Query Name
            <input type="text" ng-model="query"/>

            Query status
            <input type="text" ng-model="from" placeholder="from"/>
            <input type="text" ng-model="end" placeholder="end"/>

            Query description
            <input type="text" ng-model="description"/>

                  Name
                  Desciption
                  Status

=from}&&{status.state:status.state<=end})||{description:description})'">
                  {{member.name}}
                  {{member.description}}
                  {{member.status.state}}


text:
<form data-ng-show="$ctrl.rights.showControlBar" class="control-bar form-inline">

            <button data-ng-disabled="$ctrl.selected.length == 0" data-ng-show="$ctrl.rights.publish" class="btn btn-std"
                    data-ng-click="$ctrl.publishProjects()">
                Re-publish Projects</button>
            <button data-ng-disabled="$ctrl.selected.length == 0" data-ng-show="$ctrl.rights.remove" class="btn btn-std"
                    data-ng-click="$ctrl.deleteProjects()" style="color:black">Delete Projects</button>

</form>

<listview hide-if-empty="true" items="$ctrl.archivedProjects" visible-items="visibleProjects" select="">

                <input type="checkbox" data-ng-checked="$ctrl.isSelected(project)"
                       data-ng-click="$ctrl.updateSelection($event, project)">

                        {{project.projectName}}

                    {{$ctrl.projectTypeNames[project.appName]}}

Archived on {{project.dateModified | date:'fullDate'}}

</listview>


text:
import webbrowser
from xierpa3.components import Theme, Page, Text
from xierpa3.builders.htmlbuilder import HtmlBuilder

class HelloWorld(Theme):
    u"""The **HelloWorld** site class implements a basic "Hello, world!",
    showing the smallest possible web page"""
    TITLE = u'The standard "Hello, world!" page.' # Use as title of window.

    def baseComponents(self):
        u"""Create a theme site with just one single template home page. Answer a list
        of page instances that are used as templates for this site."""
        # Create an instance (=object) of the text component to be placed on the page.
        text = Text('Hello, world!')
        # Create an instance (=object) of the page, containing the "text" Text instance.
        # The page class is also the page name in the url: http://localhost:8060/index
        # Components can be a single component or a list of components.
        homePage = Page(class_=self.C.TEMPLATE_INDEX, components=text, title=self.TITLE)
        # Answer a list of types of pages for this site.
        return [homePage]

    def make(self, root):
        u"""The instance of this class builds the HTML file at the optional path *root*.
        If not defined, then @Builder.C.DEFAULT_ROOTPATH@ is used, as in general builders
        are associated where output should go to.
        E.g. the default @HtmlBuilder.C.DEFAULT_ROOTPATH@ is defined as to the user extended
        path of @~/Desktop/Xierpa3Examples/[component.name]@.
        And for @CssBuilder@ it is @~/Desktop/Xierpa3Examples/[component.name]/css/style.css@."""
        # H T M L
        # Create the main HTML builder instance to build the HTML part of the site.
        htmlBuilder = HtmlBuilder()
        # Compile the site instance and its components into HTML code.
        self.build(htmlBuilder)
        # Save the resulting HTML file in "index.html"
        # Answer the file path, so we can directly open the file with a browser.
        return htmlBuilder.save(self, path=root + 'index.html')

if __name__ == '__main__':
    # This construction "__name__ == '__main__'" makes this Python file only
    # be executed when called in direct mode, such as "python make.py" in the terminal.
    # Since no rootPath is added to make(), the file export is in builder.DEFAULT_ROOTPATH
    # which typically is the user extended path of ~/Desktop/Xierpa3Examples/HelloWorld/

    # TODO: for some reason there is double output of HTML right now, using make()
    # TODO: Make(root) implements on other example classes

    site = HelloWorld()
    root = site.getRootDir()
    filePath = site.make(root)
    webbrowser.open('file://'+filePath)


text:
package com.sw.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.sw.dao.UserDao;
import com.sw.domain.User;

/*
 *@Author swxctx
 *@time 2017Äê5ÔÂ10ÈÕ
 *@Explain:Dao²ãʵÏÖ
 */
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

	@Override
	public User findUserByUsername(String username) {
		Session session=null;
		User user=new User();
		try {
			session=this.getHibernateTemplate().getSessionFactory().openSession();
			Criteria criteria=(Criteria) session.createCriteria(User.class);
			//¼ÓÈëÌõ¼þ²éѯ
			criteria.add(Restrictions.eq("username", username));
			user=(User) criteria.uniqueResult();
		} finally {
			if(session!=null){
				session.close();
			}
		}
		return user;
	}

}


text:
import { IFileItem } from "../../../model/IFileItem";
import { ITermNode } from "../../../model/ITermNode";

export interface ITermLabelProps {
    node: ITermNode;
    selectedNode: string;
    renderFiles: (files: IFileItem[]) => void;
    resetChecked: (s: string) => void;
    addTerm: (file: IFileItem, newValue: string) => void;
    replaceTerm: (file: IFileItem, newValue: string) => void;
    copyFile: (file: IFileItem, newValue: string) => void;
}


text:
@rem Do not use "echo off" to not affect any child calls.

@rem Enable extensions, the `verify other 2>nul` is a trick from the setlocal help
@verify other 2>nul
@setlocal enableDelayedExpansion
@if errorlevel 1 (
    @echo Unable to enable delayed expansion. Immediate expansion will be used.
    @goto fallback
)

@rem Get the absolute path to the parent directory, which is assumed to be the
@rem Git installation root.
@for /F "delims=" %%I in ("%~dp0..") do @set git_install_root=%%~fI
@set PATH=!git_install_root!\bin;!git_install_root!\mingw\bin;!PATH!

@if not exist "!HOME!" @set HOME=!HOMEDRIVE!!HOMEPATH!
@if not exist "!HOME!" @set HOME=!USERPROFILE!

@start "gitk" wish.exe "!git_install_root!\bin\gitk" -- %*
@goto end

:fallback
@rem The above script again with immediate expansion, in case delayed expansion
@rem is unavailable.
@for /F "delims=" %%I in ("%~dp0..") do @set git_install_root=%%~fI
@set PATH=%git_install_root%\bin;%git_install_root%\mingw\bin;%PATH%

@if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH%
@if not exist "%HOME%" @set HOME=%USERPROFILE%

@start "gitk" wish.exe "%git_install_root%\bin\gitk" -- %*

:end
@rem End of script


text:
exports.register = function (events) {
  addKeyboardEventListeners(events);
};

exports.unregister = function (events) {
  removeKeyboardEventListeners(events);
};

function addKeyboardEventListeners (events) {
  events.on('keydown', function (event) {
    if (event.metaKey || event.ctrlKey) {
      // Bail out if meta or ctrl key was pressed
      return;
    }

    switch (event.keyCode) {
      case 33: // Page up
      case 37: // Left
      case 38: // Up
        events.emit('gotoPreviousSlide');
        break;
      case 32: // Space
      case 34: // Page down
      case 39: // Right
      case 40: // Down
        events.emit('gotoNextSlide');
        break;
      case 36: // Home
        events.emit('gotoFirstSlide');
        break;
      case 35: // End
        events.emit('gotoLastSlide');
        break;
      case 27: // Escape
        events.emit('hideOverlay');
        break;
    }
  });

  events.on('keypress', function (event) {
    if (event.metaKey || event.ctrlKey) {
      // Bail out if meta or ctrl key was pressed
      return;
    }

    switch (String.fromCharCode(event.which).toLowerCase()) {
      case 'j':
        events.emit('gotoNextSlide');
        break;
      case 'k':
        events.emit('gotoPreviousSlide');
        break;
      case 'b':
        events.emit('toggleBlackout');
        break;
      case 'm':
        events.emit('toggleMirrored');
        break;
      case 'c':
        events.emit('createClone');
        break;
      case 'p':
        events.emit('togglePresenterMode');
        break;
      case 'f':
        events.emit('toggleFullscreen');
        break;
      case 't':
        events.emit('resetTimer');
        break;
      case 'h':
      case '?':
        events.emit('toggleHelp');
        break;
    }
  });
}

function removeKeyboardEventListeners(events) {
  events.removeAllListeners("keydown");
  events.removeAllListeners("keypress");
}


text:
package com.gdn.venice.server.app.fraud.rule;

import java.util.List;

import org.apache.log4j.Logger;

import com.djarum.raf.utilities.Locator;
import com.djarum.raf.utilities.Log4jLoggerFactory;
import com.gdn.venice.facade.FrdParameterRule4SessionEJBRemote;
import com.gdn.venice.persistence.FrdParameterRule4;
import com.gdn.venice.persistence.VenOrder;

/**
 * Class for calculate fraud rule 4: Order made up of big ticket items
 *
 * @author Roland
 */

public class Rule4 {
	protected static Logger _log = null;

    public Rule4() {
        super();
		Log4jLoggerFactory loggerFactory = new Log4jLoggerFactory();
		_log = loggerFactory.getLog4JLogger("com.gdn.venice.server.app.fraud.rule.Rule4");
    }

	public int execute(VenOrder venOrder) throws Exception{
		_log.info("Start execute rule 4");
		int fraudPoint=0;
		Locator<Object> locator = null;

		try{
			locator = new Locator<Object>();
			FrdParameterRule4SessionEJBRemote rule4SessionHome = (FrdParameterRule4SessionEJBRemote) locator.lookup(FrdParameterRule4SessionEJBRemote.class, "FrdParameterRule4SessionEJBBean");
			_log.debug("amount: "+venOrder.getAmount());

			List<FrdParameterRule4> parameterList = rule4SessionHome.queryByRange("select o from FrdParameterRule4 o where "+venOrder.getAmount()+" between o.minValue and o.maxValue", 0, 1);
			if(parameterList.size()>0){
				fraudPoint=parameterList.get(0).getRiskPoint();
				_log.info("parameter match: "+parameterList.get(0).getDescription());
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception();
		} finally {
			try {
				if (locator != null) {
					locator.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		_log.info("Done execute rule 4, fraudPoint is: "+fraudPoint);
		return fraudPoint;
	}
}


text:
package ru.skuznetsov;

import org.junit.Assert;
import org.junit.Test;

/**
 * Created by Sergey on 28.11.2016.
 */
public class SubCheckerTest {
    /**
     * Test method check is string contains specified sub string.
     * */
    @Test
    public void checkIsStringContainsSubString() {
        SubChecker checker = new SubChecker();
        String str = "HolidayNewYear";
        String sub = "day";

        Assert.assertTrue(checker.contains(str, sub));
    }
    /**
     * Test method check is string not contains specified sub string.
     * */
    @Test
    public void checkIsStringContainsSubStringToFalse() {
        SubChecker checker = new SubChecker();
        String str = "HolidayNewYear";
        String sub = "da23y";

        Assert.assertFalse(checker.contains(str, sub));
    }
}


text:
package com.mmnaseri.cs.clrs.ch32.s1;

import java.util.List;
import java.util.Objects;

/**
 * @author Mohammad Milad Naseri (mmnaseri@programmer.net)
 * @since 1.0 (11/4/16, 6:34 PM)
 */
public abstract class AbstractStringMatcher implements StringMatcher {

  @Override
  public Integer[] indexOf(String needle, String haystack) {
    Objects.requireNonNull(needle, "The needle cannot be null");
    Objects.requireNonNull(haystack, "The haystack cannot be null");
    if (needle.isEmpty()) {
      throw new IllegalArgumentException("The needle cannot be empty");
    }
    if (haystack.isEmpty()) {
      return new Integer[0];
    }
    final List<Integer> indices = findIndexOf(needle, haystack);
    return indices.toArray(new Integer[0]);
  }

  protected abstract List<Integer> findIndexOf(String needle, String haystack);
}


text:
A type must implement `DeleteOverrider` to override `delete`. Method receiver is set to the first parameter of `delete`.

```go
type DeleteOverrider interface {
	generic(Index)
	OverrideDelete(Index)
}
```

Following is an example.

```go
type S struct {
	M map[string]int
}

// Override `delete`.
func (s *S) OverrideDelete(index string) {
	delete(s.M, index)
}

s := &S{}
s.M = make(generic(s.M)) // Make a map value.
s.M["foo"] = 123

delete(s, "foo")
s.M["foo"] == nil // true
```


text:
<?php

namespace AppBundle\DataFixtures\ORM;

use AppBundle\Entity\Image;
use AppBundle\Entity\ImageTag;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Collections\ArrayCollection;

class LoadImagesData extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
    const IMAGES_COUNT = 5;
    const TAGS_COUNT = 5;

    /**
     * @var ContainerInterface
     */
    private $container;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    public function load(ObjectManager $manager)
    {
        $faker = $this->container->get('davidbadura_faker.faker');

        for ($i = 0; $i < self::IMAGES_COUNT; $i++) {
            $image = new Image();
            $image->setTitle($faker->word);
            $image->setDescription($faker->text);
            $image->setImageName("$i.jpg");
            $index = rand(1, count(LoadImageTagsData::$tagNames));
            $image->addTag($this->getReference("image_tag_$index"));
            $manager->persist($image);
        }

        $manager->flush();
    }

    /**
     * Get the order of this fixture
     *
     * @return integer
     */
    public function getOrder()
    {
        //Make possibility to insert fixtures between this one and tags - just for a case
        return 20;
    }
}


text:
<?php
namespace Elastica\Filter;

/**
 * Exists query.
 *
 * @author Oleg Cherniy <oleg.cherniy@gmail.com>
 *
 * @link http://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-filter.html
 */
class Exists extends AbstractFilter
{
    /**
     * Construct exists filter.
     *
     * @param string $field
     */
    public function __construct($field)
    {
        $this->setField($field);
    }

    /**
     * Set field.
     *
     * @param string $field
     *
     * @return $this
     */
    public function setField($field)
    {
        return $this->setParam('field', $field);
    }
}


text:
"""
    test_Entity_Azure

    test Entity against Azure Service
"""
import pytest
from AzureODM.Entity import Entity
from AzureODM.Fields import *
from AzureODM.QuerySet import Q
from datetime import datetime

class TestEntity(Entity):

    PartitionKey = KeyField()
    RowKey = KeyField()
    boolAttr = BooleanField(required=True)
    strAttr = StringField(required=True)
    floatAttr = FloatField(required=True)
    intAttr = IntField(required=True)
    dateAttr = DateField(required=True)

    metas = {
        'table_name': 'test'
    }

@pytest.mark.azure
class Test_save:

    new_entity = None

    def test_save_new(self, azure_ts, request):
        def fin():
            azure_ts.delete_entity(
                'test',
                'p1',
                'r1'
            )
        request.addfinalizer(fin)
        self.new_entity = TestEntity()
        self.new_entity.PartitionKey = 'p1'
        self.new_entity.RowKey = 'r1'
        self.new_entity.boolAttr = True
        self.new_entity.strAttr = 'lol'
        self.new_entity.floatAttr = 1.11
        self.new_entity.intAttr = 1123
        self.new_entity.dateAttr = datetime(2013, 1, 1, 1, 1, 1)
        assert self.new_entity._is_new is True
        assert self.new_entity._saved_copy == {}
        assert self.new_entity._saved_etag is None
        self.new_entity.save()
        assert self.new_entity._is_new is False
        assert self.new_entity._is_changed is False
        assert self.new_entity._saved_etag is not None
        assert self.new_entity._saved_copy['intAttr'] == 1123
        assert self.new_entity._saved_copy['dateAttr'].isoformat() == \
            '2013-01-01T01:01:01+00:00'

    def test_10_entities(self, azure_ts, request):
        entities = []
        # create ten
        for x in range(0, 9):
            new_entity = TestEntity()
            new_entity.PartitionKey = 'p1'
            new_entity.RowKey = 'r{}'.format(x)
            new_entity.boolAttr = True
            new_entity.strAttr = 'lol'
            new_entity.floatAttr = 1.11
            new_entity.intAttr = 1123
            new_entity.dateAttr = datetime(2013, 1, 1, 1, 1, 1)
            entities.append(new_entity)

        # added to different PartitionKey
        for x in range(0, 9):
            new_entity = TestEntity()
            new_entity.PartitionKey = 'p2'
            new_entity.RowKey = 'r{}'.format(x)
            new_entity.boolAttr = True
            new_entity.strAttr = 'lol'
            new_entity.floatAttr = 1.11
            new_entity.intAttr = 1123
            new_entity.dateAttr = datetime(2013, 1, 1, 1, 1, 1)
            entities.append(new_entity)

        def fin():
            for entity in entities:
                entity.delete(force_delete=True)
        request.addfinalizer(fin)

        for entity in entities:
            entity.save()

        # query 3 of them
        res_entities = TestEntity.select(['strAttr', 'dateAttr']) \
            .where(PartitionKey='p1') \
            .andWhere(RowKey__gt='r2').limit(3).go()
        assert len(res_entities) == 3
        assert res_entities[0].PartitionKey == 'p1'
        assert res_entities[0].strAttr == 'lol'
        assert res_entities[0].dateAttr.isoformat() == \
            '2013-01-01T01:01:01+00:00'
        assert res_entities[0].intAttr is None
        assert res_entities[0].RowKey == 'r3'
        assert res_entities[1].RowKey == 'r4'
        assert res_entities[2].RowKey == 'r5'

        r4 = res_entities[1]
        r4.intAttr = 8765
        r4.save()
        # test merge
        merged_r4 = TestEntity.findOne(partition_key='p1',
                                       row_key='r4',
                                       select='*')
        assert merged_r4.intAttr == 8765
        assert merged_r4.strAttr == 'lol'
        assert merged_r4.floatAttr == 1.11
        assert merged_r4._saved_etag == r4._saved_etag

        # query 2 of them
        res_entities = TestEntity.select(['boolAttr', 'dateAttr']) \
            .where(PartitionKey='p1') \
            .andWhere(RowKey__gt='r5').andWhere(RowKey__lt='r8').limit(3).go()
        assert len(res_entities) == 2
        assert res_entities[0].boolAttr is True
        assert res_entities[0].RowKey == 'r6'
        assert res_entities[1].RowKey == 'r7'

        # query 2 of them using or
        res_entities = TestEntity.select(['boolAttr', 'dateAttr']) \
            .where(PartitionKey='p1') \
            .andWhere(Q(RowKey='r1') | Q(RowKey='r8')).limit(3).go()

        assert len(res_entities) == 2
        assert res_entities[0].RowKey == 'r1'
        assert res_entities[1].RowKey == 'r8'

        # query on two different PartitionKey s
        res_entities = TestEntity.select() \
            .where(Q(PartitionKey='p1') | Q(PartitionKey='p2')) \
            .andWhere(RowKey__ge='r5') \
            .andWhere(RowKey__lt='r7') \
            .go()

        assert len(res_entities) == 4
        res_p1 = [
            e for e in filter(lambda x: x.PartitionKey == 'p1', res_entities)]
        assert len(res_p1) == 2
        assert res_p1[0].RowKey == 'r5'
        assert res_p1[1].RowKey == 'r6'
        res_p2 = [
            e for e in filter(lambda x: x.PartitionKey == 'p2', res_entities)]
        assert res_p2[0].RowKey == 'r5'
        assert res_p2[1].RowKey == 'r6'

    @pytest.mark.slow
    @pytest.mark.unimportant
    def test_multiple_partition_speed(self, azure_ts, request):
        from time import time
        # add 20 entities into 20 partitions
        entities = []
        #insert_batch_time = []
        for i in range(0, 20):
            insert_start = time()
            for x in range(0, 20):
                e_start_time = time()
                new_entity = TestEntity()
                new_entity.PartitionKey = 'p{0:02d}'.format(i)
                new_entity.RowKey = 'r{0:02d}'.format(x)
                new_entity.boolAttr = True
                new_entity.strAttr = 'lol'
                new_entity.floatAttr = 1.11
                new_entity.intAttr = 1123
                new_entity.dateAttr = datetime(2013, 1, 1, 1, 1, 1)
                new_entity.save()
                e_end_time = time()
                print('----- insert #{}-{} in {}'.format(
                    i, x, e_end_time - e_start_time))
                entities.append(new_entity)
            insert_end = time()
            #insert_batch_time.append(insert_end - insert_start)
            print('----- insert #{} time: {}'.format(
                i, insert_end - insert_start))

        def fin():
            d_st = time()
            for entity in entities:
                entity.delete(force_delete=True)
            d_et = time()
            print('--- delete finished at in {}'.format(d_et - d_st))
        request.addfinalizer(fin)

        # test query from 4 partition for 40 objects
        #query_constr_time = time()
        s = TestEntity.select()
        #a = Q(RowKey='r{0:02d}'.format(0))
        #b = Q(RowKey='r{0:02d}'.format(0))
        # for q in range(1, 19):
        #    a = (a | Q(RowKey='r{0:02d}'.format(q)))
        #    b = (b | Q(RowKey='r{0:02d}'.format(q)))
        s.where(Q(PartitionKey='p02') & Q(RowKey__ge='r00')).orWhere(
            Q(PartitionKey='p12') & Q(RowKey__ge='r00'))
        #print('----- query constr time: {}'.format(time() - query_constr_time))
        print('------ raw query: \n {}'.format(s.filter))
        query_start_time = time()

        res = s.go()
        query_end_time = time()
        print('----- query rtn time: {}'.format(
            query_end_time - query_start_time))
        print('----- returned: {} entities'.format(len(res)))
        print('---------------- returned entities -------------')
        for entity in res:
            print('P#{} - R#{}'.format(entity.PartitionKey, entity.RowKey))

        # test query 20 partitions for 40 objects
        s2 = TestEntity.select().where(Q(PartitionKey='p00') & Q(RowKey='r12'))
        s2.orWhere(Q(PartitionKey='p00') & Q(RowKey='r10'))
        for r in range(1, 20):
            s2.orWhere(
                Q(PartitionKey='p{0:02d}'.format(r)) &
                Q(RowKey='r02'))
            s2.orWhere(
                Q(PartitionKey='p{0:02d}'.format(r)) &
                Q(RowKey='r18'))
        print('------ raw query: \n {}'.format(s2.filter))
        q2_start = time()
        res2 = s2.go()
        q2_end = time()
        print('----- query2 rtn time: {}'.format(
            q2_end - q2_start))
        print('----- returned {} entities'.format(len(res2)))
        print('---------------- returned entities -------------')
        for entity in res2:
            print('P#{} - R#{}'.format(entity.PartitionKey, entity.RowKey))

        # test in query
        p_keys = ['p{0:02d}'.format(r) for r in range(0, 20)]
        r_keys = ['r18', 'r02']
        s3 = TestEntity.select() \
            .where(Q(PartitionKey__in=p_keys) & Q(RowKey__in=r_keys))
        print('------ raw query: \n {}'.format(s3.filter))
        q3_start = time()
        res3 = s3.go()
        q3_end = time()
        print('----- query3 rtn time: {}'.format(
            q3_end - q3_start))
        print('----- returned {} entities'.format(len(res3)))
        print('---------------- returned entities -------------')
        for entity in res3:
            print('P#{} - R#{}'.format(entity.PartitionKey, entity.RowKey))


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (C) 2016 LinkedIn Corp.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- i18n-resource -->
<resources>
    <string name="shaky_dialog_title">Shake to send feedback</string>
    <string name="shaky_dialog_message">You shook your device! Would you like to send feedback about your experience?</string>
    <string name="shaky_dialog_positive">Send Feedback</string>
    <string name="shaky_dialog_negative">Dismiss</string>

    <string name="shaky_feedback_title">Send feedback</string>

    <string name="shaky_collecting_feedback">Collecting debug data…</string>

    <string name="shaky_row1_title">Report a bug</string>
    <string name="shaky_row1_subtitle">Something doesn't seem quite right.</string>
    <string name="shaky_bug_title">Bug Report</string>
    <string name="shaky_bug_hint">Describe the bug</string>

    <string name="shaky_row2_title">Request a new feature</string>
    <string name="shaky_row2_subtitle">It would be super cool if…</string>
    <string name="shaky_feature_title">Feature Request</string>
    <string name="shaky_feature_hint">Write your request</string>

    <string name="shaky_row3_title">Send app feedback</string>
    <string name="shaky_row3_subtitle">Tell us how we're doing!</string>
    <string name="shaky_general_title">General Feedback</string>
    <string name="shaky_general_hint">Write your feedback</string>

    <string name="shaky_message_hint">Write your feedback</string>
    <string name="shaky_image_action">Tap to edit image</string>

    <string name="shaky_form_submit">Send</string>

    <string name="shaky_draw_hint">Please mark the affected area(s)</string>
    <string name="shaky_draw_save">save</string>
    <string name="shaky_draw_clear">clear</string>
    <string name="shaky_draw_brush">brush</string>
    <string name="shaky_draw_undo">undo</string>
    <string name="shaky_draw_brush_white">whiteout</string>
    <string name="shaky_draw_brush_hint">Toggles the brush style</string>

    <string name="shaky_empty_feedback_message">Please write your feedback.</string>
    <string name="shaky_empty_feedback_confirm">OK</string>

    <string name="shaky_sensitivity_high">High</string>
    <string name="shaky_sensitivity_medium">Medium</string>
    <string name="shaky_sensitivity_low">Low</string>
    <string name="shaky_sensor_sensitivity">Sensor Sensitivity</string>

    <string name="shaky_setting">Settings</string>
    <string name="shaky_general_ok_string">OK</string>

    <string name="shaky_select_subcategory">Select a subcategory</string>
    <string-array name="shaky_bug_subcategories">
        <item>The app crashed</item>
        <item>Something is broken</item>
    </string-array>
    <string name="shaky_subcategory_not_selected_message">Please select a subcategory</string>
</resources>


text:
require "spec_helper"

describe Jfb do
	before :all do
		@db = JFB.new('lnx-firebird://root/BDDS/SERIES.FDB', 'SYSDBA' , 'N3w0rd3r')
		@db.connect()
	end

  it "has a version number" do
    expect(Jfb::VERSION).not_to be nil
  end

	it "can query from a database" do
		h = @db.query("select * from setormacro")
		expect(h.class.to_s).to eq('Array')
		expect(h.size > 0).to eq(true)
	end

	after :all do
		@db.close()
	end
end


text:
import keycode from 'keycode';
import Vue from 'vue';
import { pageUri } from '@nymag/dom';
import NProgress from 'vue-nprogress';
import addClayListeners from './lib/utils/shift-clay';
import { addToolbarButton } from './lib/utils/custom-buttons'; // eslint-disable-line
import store from './lib/core-data/store';
import toolbar from './lib/toolbar/view-toolbar.vue';
import getSites from './lib/preloader/sites';
import parseUrl from './lib/preloader/parse-url';
import {
  PRELOAD_PENDING, LOADING_SUCCESS, PRELOAD_SITE, PRELOAD_ALL_SITES, PRELOAD_USER, PRELOAD_URL
} from './lib/preloader/mutationTypes';
import { UPDATE_PAGE_STATE, UPDATE_PAGEURI } from './lib/page-state/mutationTypes';
import { META_PRESS, META_UNPRESS } from './lib/preloader/mutationTypes';
import { props } from './lib/utils/promises';
import { getItem } from './lib/utils/local';
import conditionalFocus from './directives/conditional-focus';
import 'keen-ui/src/bootstrap'; // import this once, for KeenUI components

const progressOptions = {
    parent: '.nprogress-container',
    template: '

',
    showSpinner: false,
    easing: 'linear',
    speed: 500,
    trickle: false,
    minimum: 0.001
  },
  nprogress = new NProgress(progressOptions);

// register directives
Vue.directive('conditional-focus', conditionalFocus());

// add progress bar
Vue.use(NProgress, {
  router: false,
  http: false
});

// Require all scss/css files needed
require.context('./styleguide', true, /^.*\.(scss|css)$/);

addClayListeners();

store.commit(PRELOAD_PENDING);

// kick off loading when DOM is ready
document.addEventListener('DOMContentLoaded', function () {
  store.commit(PRELOAD_SITE, window.kiln.preloadSite);

  new Vue({
    debug: process.env.NODE_ENV !== 'production',
    strict: true,
    el: '#kiln-app',
    render(h) {
      return h('view-toolbar');
    },
    store,
    nprogress,
    components: {
      'view-toolbar': toolbar
    }
  });

  // don't preload all the data, just grab the page state, site info, and user
  props({
    pageState: store.dispatch('getListData', { uri: pageUri(), prefix: window.kiln.preloadSite.prefix }),
    allSites: getSites(window.kiln.preloadSite),
    lists: store.dispatch('getList', 'new-pages'),
    favoritePageCategory: getItem('kiln-page-category')
  }).then(({ pageState, allSites, favoritePageCategory }) => {
    store.commit(UPDATE_PAGE_STATE, pageState);
    store.commit(UPDATE_PAGEURI, pageUri());
    store.commit(PRELOAD_ALL_SITES, allSites);
    store.commit(PRELOAD_USER, window.kiln.preloadUser);
    store.commit(PRELOAD_URL, parseUrl());
    store.commit(LOADING_SUCCESS);
    // if the user has a favorite new page category set,
    // make sure it'll be in the state when they open that list
    if (favoritePageCategory) {
      store.commit('CHANGE_FAVORITE_PAGE_CATEGORY', favoritePageCategory);
    }
  }).then(() => store.dispatch('parseURLHash')); // check for deep-linked clay menu

  // when ESC bubbles up to the document, close the current form or pane / unselect components
  document.body.addEventListener('keydown', (e) => {
    const key = keycode(e);

    if (key === 'ctrl' || key === 'left command') {
      // pressing and holding meta key will unlock additional functionality,
      // such as the ability to duplicate the selected component
      store.commit(META_PRESS);
    }
  });

  // when user stops pressing a key, toggle this off
  document.body.addEventListener('keyup', (e) => {
    const key = keycode(e);

    if (key === 'ctrl' || key === 'left command') {
      store.commit(META_UNPRESS);
    }
  });

  // when user tabs / clicks away from the page, toggle this off
  document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
      store.commit(META_UNPRESS);
    }
  });
});


text:
using System;
using System.Collections.Generic;
using HackerNewsUwp.Network.Internal;
using HackerNewsUwp.UserControls.ItemHotel;

namespace HackerNewsUwp.Network
{
    public class Items
    {
        private readonly List<ItemId> _itemIds;

        public interface IItemIdConsumer
        {
            void ConsumeItemId(ItemId itemId);
        }

        public Items(List<ItemId> itemIds)
        {
            _itemIds = itemIds;
            if (itemIds == null)
            {
                throw new ArgumentNullException();
            }
        }
        public int Count() => _itemIds.Count;

        public void ProvideId(int index, IItemIdConsumer itemIdConsumer )
        {
            itemIdConsumer.ConsumeItemId(_itemIds[index]);
        }
    }
}


text:
import { Module, Logger } from '@nestjs/common';
import { HelloController } from './hello.controller';
import { HelloRequestService } from './hello-request/hello-request.service';
import { HelloTransientService } from './hello-transient/hello-transient.service';
import { RequestLogger } from './hello-request/request-logger.service';
import { TransientLogger } from './hello-transient/transient-logger.service';

@Module({
  controllers: [HelloController],
  providers: [
    HelloRequestService,
    HelloTransientService,
    RequestLogger,
    TransientLogger,
    Logger,
  ],
})
export class HelloModule {}


text:
package com.tum.ident.fftpack;

/**
 * FFT transform of a complex periodic sequence.
 *
 * @author Baoshe Zhang
 * @author Astronomical Instrument Group of University of Lethbridge.
 */
public class ComplexDoubleFFT extends ComplexDoubleFFT_Mixed {
	/**
	 * norm_factor can be used to normalize this FFT transform. This is
	 * because a call of forward transform (ft) followed by a call of
	 * backward transform (bt) will multiply the input sequence by
	 * norm_factor.
	 */
	public double norm_factor;
	private double wavetable[];
	private int ndim;

	/**
	 * Construct a wavenumber table with size n for Complex FFT. The
	 * sequences with the same size can share a wavenumber table. The prime
	 * factorization of n together with a tabulation of the
	 * trigonometric functions are computed and stored.
	 *
	 * @param n
	 *            the size of a complex data sequence. When n is a
	 *            multiplication of small numbers (4, 2, 3, 5), this FFT
	 *            transform is very efficient.
	 */
	public ComplexDoubleFFT(int n) {
		ndim = n;
		norm_factor = n;
		if (wavetable == null || wavetable.length != (4 * ndim + 15)) {
			wavetable = new double[4 * ndim + 15];
		}
		cffti(ndim, wavetable);
	}

	/**
	 * Forward complex FFT transform.
	 *
	 * @param x
	 *            2*n real double data representing n complex
	 *            double data. As an input parameter, x is an array of
	 *            2*n real data representing n complex data.
	 *            As an output parameter, x represents n FFT'd
	 *            complex data. Their relation as follows:

	 *            x[2*i] is the real part of i-th complex data;

	 *            x[2*i+1] is the imaginary part of i-the complex data.
	 *
	 */
	public void ft(double x[]) {
		if (x.length != 2 * ndim)
			throw new IllegalArgumentException(
					"The length of data can not match that of the wavetable");
		cfftf(ndim, x, wavetable);
	}

	/**
	 * Forward complex FFT transform.
	 *
	 * @param x
	 *            an array of n Complex data
	 */
	public void ft(Complex1D x) {
		if (x.x.length != ndim)
			throw new IllegalArgumentException(
					"The length of data can not match that of the wavetable");
		double[] y = new double[2 * ndim];
		for (int i = 0; i < ndim; i++) {
			y[2 * i] = x.x[i];
			y[2 * i + 1] = x.y[i];
		}
		cfftf(ndim, y, wavetable);
		for (int i = 0; i < ndim; i++) {
			x.x[i] = y[2 * i];
			x.y[i] = y[2 * i + 1];
		}
	}

	/**
	 * Backward complex FFT transform. It is the unnormalized inverse transform
	 * of ft(double[]).
	 *
	 * @param x
	 *            2*n real double data representing n complex
	 *            double data.
	 *
	 *            As an input parameter, x is an array of 2*n
	 *            real data representing n complex data. As an output
	 *            parameter, x represents n FFT'd complex
	 *            data. Their relation as follows:

	 *            x[2*i] is the real part of i-th complex
	 *            data;

	 *            x[2*i+1] is the imaginary part of i-the
	 *            complex data.
	 *
	 */
	public void bt(double x[]) {
		if (x.length != 2 * ndim)
			throw new IllegalArgumentException(
					"The length of data can not match that of the wavetable");
		cfftb(ndim, x, wavetable);
	}

	/**
	 * Backward complex FFT transform. It is the unnormalized inverse transform
	 * of ft(Complex1D[]).
	 *
	 *
	 * @param x
	 *            an array of n Complex data
	 */
	public void bt(Complex1D x) {
		if (x.x.length != ndim)
			throw new IllegalArgumentException(
					"The length of data can not match that of the wavetable");
		double[] y = new double[2 * ndim];
		for (int i = 0; i < ndim; i++) {
			y[2 * i] = x.x[i];
			y[2 * i + 1] = x.y[i];
		}
		cfftb(ndim, y, wavetable);
		for (int i = 0; i < ndim; i++) {
			x.x[i] = y[2 * i];
			x.y[i] = y[2 * i + 1];
		}
	}
}


text:
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from django.core import mail
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission

from froide.publicbody.models import PublicBody
from froide.foirequest.tests import factories
from froide.foirequest.models import FoiProject, FoiRequest

User = get_user_model()

class RequestProjectTest(TestCase):
    def setUp(self):
        factories.make_world()
        self.pb1 = PublicBody.objects.filter(jurisdiction__slug="bund")[0]
        self.pb2 = PublicBody.objects.filter(jurisdiction__slug="nrw")[0]
        ct = ContentType.objects.get_for_model(FoiRequest)
        self.perm = Permission.objects.get(content_type=ct, codename="create_batch")

    def test_create_project(self):
        user = User.objects.get(email="info@fragdenstaat.de")
        user.user_permissions.add(self.perm)

        ok = self.client.login(email=user.email, password="froide")
        self.assertTrue(ok)

        pb_ids = "%s+%s" % (self.pb1.pk, self.pb2.pk)
        response = self.client.get(
            reverse("foirequest-make_request", kwargs={"publicbody_ids": pb_ids})
        )
        self.assertEqual(response.status_code, 200)
        data = {
            "subject": "Test-Subject",
            "body": "This is another test body with Ümläut€n",
            "public": "on",
            "publicbody": pb_ids.split("+"),
        }
        mail.outbox = []
        response = self.client.post(reverse("foirequest-make_request"), data)
        self.assertEqual(response.status_code, 302)
        project = FoiProject.objects.get(title=data["subject"])
        self.assertEqual(
            set([str(x.pk) for x in project.publicbodies.all()]), set(pb_ids.split("+"))
        )
        request_sent = reverse("foirequest-request_sent") + "?project=%s" % project.pk
        self.assertEqual(response["Location"], request_sent)
        self.assertEqual(project.title, data["subject"])
        self.assertEqual(project.description, data["body"])
        self.assertEqual(project.foirequest_set.all().count(), 2)
        self.assertEqual(len(mail.outbox), 3)  # 2 to pb, one to user
        requests = project.foirequest_set.all()
        first_message_1 = requests[0].messages[0]
        first_message_2 = requests[1].messages[0]
        self.assertNotEqual(first_message_1.plaintext, data["body"])
        last_part_1 = first_message_1.plaintext.split(data["body"])[1]
        last_part_2 = first_message_2.plaintext.split(data["body"])[1]
        self.assertNotEqual(last_part_1, last_part_2)

        response = self.client.get(
            reverse("foirequest-project_shortlink", kwargs={"obj_id": project.pk})
        )
        self.assertEqual(response.status_code, 302)

    def test_create_project_full_text(self):
        user = User.objects.get(email="info@fragdenstaat.de")
        user.user_permissions.add(self.perm)

        ok = self.client.login(email=user.email, password="froide")
        self.assertTrue(ok)

        pb_ids = (self.pb1.pk, self.pb2.pk)
        data = {
            "subject": "Test-Subject",
            "body": "This is another test body with Ümläut€n",
            "public": "on",
            "publicbody": pb_ids,
            "full_text": "on",
        }
        response = self.client.post(reverse("foirequest-make_request"), data)
        self.assertEqual(response.status_code, 302)
        project = FoiProject.objects.get(title=data["subject"])
        requests = project.foirequest_set.all()
        first_message_1 = requests[0].messages[0]
        first_message_2 = requests[1].messages[0]
        self.assertTrue(first_message_1.plaintext.startswith(data["body"]))
        self.assertTrue(first_message_2.plaintext.startswith(data["body"]))

    def test_draft_project(self):
        """
        A non-batch user can be assigned a batch draft
        The user cannot change the public bodies, but is able to sent
        the request.
        """
        user = User.objects.get(email="dummy@example.org")

        old_project = factories.FoiProjectFactory(user=user)

        ok = self.client.login(email=user.email, password="froide")
        self.assertTrue(ok)
        draft = factories.RequestDraftFactory.create(user=user)
        draft.publicbodies.add(self.pb1, self.pb2)

        evil_pb3 = PublicBody.objects.filter(jurisdiction__slug="nrw")[1]
        pb_ids = [self.pb1.pk, self.pb2.pk]
        response = self.client.get(draft.get_absolute_url())
        self.assertEqual(response.status_code, 200)
        mail.outbox = []

        draft.project = old_project
        draft.save()

        data = {
            "subject": "Test-Subject",
            "body": "This is another test body with Ümläut€n",
            "public": "on",
            "publicbody": pb_ids + [evil_pb3],
            "draft": draft.pk,
        }

        request_url = reverse("foirequest-make_request")
        response = self.client.post(request_url, data)
        self.assertContains(response, "Draft cannot be used again", status_code=400)

        draft.project = None
        draft.save()

        response = self.client.post(request_url, data)
        self.assertEqual(response.status_code, 302)

        project = FoiProject.objects.get(title=data["subject"])
        self.assertEqual(set(pb_ids), set(x.id for x in project.publicbodies.all()))
        self.assertEqual(len(mail.outbox), 3)  # two pbs, one user to user


text:
@echo off

rem Erases the existing server key store and client trust store and recreates them using all the available key algorithms.

rem Delete the existing keystores
del ServerPrivateKeyStore.jks
del ServerPublicCertificateKeyStore.jks

rem Add a key and certificate using DSA, RSA and EC key algorithms
call addKeyType.bat dsa
call addKeyType.bat rsa
rem EC only supports key sizes of 571 bits.
call addKeyType.bat ec 571