text:
require "spec_helper"

describe "bundle update" do
  before :each do
    build_repo2

    install_gemfile <<-G
      source "file://#{gem_repo2}"
      gem "activesupport"
      gem "rack-obama"
    G
  end

  describe "with no arguments" do
    it "updates the entire bundle" do
      update_repo2 do
        build_gem "activesupport", "3.0"
      end

      bundle "update"
      should_be_installed "rack 1.2", "rack-obama 1.0", "activesupport 3.0"
    end

    it "doesn't delete the Gemfile.lock file if something goes wrong" do
      gemfile <<-G
        source "file://#{gem_repo2}"
        gem "activesupport"
        gem "rack-obama"
        exit!
      G
      bundle "update"
      expect(bundled_app("Gemfile.lock")).to exist
    end
  end

  describe "--quiet argument" do
    it "shows UI messages without --quiet argument" do
      bundle "update"
      expect(out).to include("Fetching source")
    end

    it "does not show UI messages with --quiet argument" do
      bundle "update --quiet"
      expect(out).not_to include("Fetching source")
    end
  end

  describe "with a top level dependency" do
    it "unlocks all child dependencies that are unrelated to other locked dependencies" do
      update_repo2 do
        build_gem "activesupport", "3.0"
      end

      bundle "update rack-obama"
      should_be_installed "rack 1.2", "rack-obama 1.0", "activesupport 2.3.5"
    end
  end

  describe "with an unknown dependency" do
    it "should inform the user" do
      bundle "update halting-problem-solver", :expect_err =>true
      expect(out).to include "Could not find gem 'halting-problem-solver'"
    end
    it "should suggest alternatives" do
      bundle "update active-support", :expect_err =>true
      expect(out).to include "Did you mean activesupport?"
    end
  end

  describe "with a child dependency" do
    it "should update the child dependency" do
      update_repo2
      bundle "update rack"
      should_be_installed "rack 1.2"
    end
  end

  describe "with --local option" do
    it "doesn't hit repo2" do
      FileUtils.rm_rf(gem_repo2)

      bundle "update --local"
      expect(out).not_to match(/Fetching source index/)
    end
  end

  describe "with --group option" do
    it "should update only specifed group gems" do
      install_gemfile <<-G
        source "file://#{gem_repo2}"
        gem "activesupport", :group => :development
        gem "rack"
      G
      update_repo2 do
        build_gem "activesupport", "3.0"
      end
      bundle "update --group development"
      should_be_installed "activesupport 3.0"
      should_not_be_installed "rack 1.2"
    end
  end
end

describe "bundle update in more complicated situations" do
  before :each do
    build_repo2
  end

  it "will eagerly unlock dependencies of a specified gem" do
    install_gemfile <<-G
      source "file://#{gem_repo2}"

      gem "thin"
      gem "rack-obama"
    G

    update_repo2 do
      build_gem "thin" , '2.0' do |s|
        s.add_dependency "rack"
      end
    end

    bundle "update thin"
    should_be_installed "thin 2.0", "rack 1.2", "rack-obama 1.0"
  end
end

describe "bundle update without a Gemfile.lock" do
  it "should not explode" do
    build_repo2

    gemfile <<-G
      source "file://#{gem_repo2}"

      gem "rack", "1.0"
    G

    bundle "update"

    should_be_installed "rack 1.0.0"
  end
end

describe "bundle update when a gem depends on a newer version of bundler" do
  before(:each) do
    build_repo2 do
      build_gem "rails", "3.0.1" do |s|
        s.add_dependency "bundler", Bundler::VERSION.succ
      end
    end

    gemfile <<-G
      source "file://#{gem_repo2}"
      gem "rails", "3.0.1"
    G
  end

  it "should not explode" do
    bundle "update"
    expect(err).to be_empty
  end

  it "should explain that bundler conflicted" do
    bundle "update"
    expect(out).not_to match(/in snapshot/i)
    expect(out).to match(/current Bundler version/i)
    expect(out).to match(/perhaps you need to update bundler/i)
  end
end

describe "bundle update" do
  it "shows the previous version of the gem when updated from rubygems source" do
    build_repo2

    install_gemfile <<-G
      source "file://#{gem_repo2}"
      gem "activesupport"
    G

    bundle "update"
    expect(out).to include("Using activesupport 2.3.5")

    update_repo2 do
      build_gem "activesupport", "3.0"
    end

    bundle "update"
    expect(out).to include("Installing activesupport 3.0 (was 2.3.5)")
  end

  it "shows error message when Gemfile.lock is not preset and gem is specified" do
    install_gemfile <<-G
      source "file://#{gem_repo2}"
      gem "activesupport"
    G

    bundle "update nonexisting", :exitstatus => true
    expect(out).to include("This Bundle hasn't been installed yet. Run `bundle install` to update and install the bundled gems.")
    expect(@exitstatus).to eq(22)
  end
end

redpajama_set_name: RedPajamaGithub


text:
module Selector

  # The condition that accepts any value
  #
  # @example (see #[])
  #
  class Anything < Condition

    include Singleton

    # @!method [](value)
    # Returns true
    #
    # @example
    #   condition = Selector::Anything.instance # singleton
    #   condition[:foo] # => true
    #
    # @param (see Selector::Condition#[])
    #
    # @return [true]
    #
    def [](_value)
      true
    end

  end # class Anything

end # module Selector


text:
using System;
using MyWebSocket;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using MyExtensions.Logging;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace WebSocketRunner
{
   class MainClass
   {
      public static void Main(string[] args)
      {
         Console.WriteLine("DOING SOMEWTHING");

         //This allows you to log stuff to a file and/or the console. You can set the various settings
         //for the logger, then pass it to the websocket server
         Logger logger = new Logger(100, "", LogLevel.SuperDebug);

         //I only support the asynchronous version now. The websocketserver takes one "WebSocketSettings"
         //object, which describes how the websocket server acts. At a minimum, you need the port,
         //a name for the protocol (anything, as long as it matches in the JS), and a "lambda" which
         //describes how to make a websocket user. A websocket user is a class which allows you to
         //intercept the messages that a connection receives. The WebSocketServerAsync class handles absolutely
         //everything for you; all you have to do is make a class in which you handle the messages. A new
         //web socket user class is created for each connection (user). My websocket user is called "EchoUser",
         //since it just echos everything is receives.
         WebSocketServerAsync server = new WebSocketServerAsync(
            new WebSocketSettings(45695, "chat", () => { return new EchoUser(); }, logger));

         //When you start an asynchronous function, you get back a "task" which is basically like an "I'm running"
         //token. The server is now running in the background, and you can stop it using this Task.
         Task serverWaitable = server.StartAsync();

         //The code will wait at the Console.Read until a user presses a button. Since the server is running in the
         //background, it's OK that we're waiting here.
         Console.WriteLine("Press any key to quit");
         Console.Read();

         //If you want to safely shut down the server, you should definitely call the Stop function on it.
         Console.WriteLine("*Trying to stop server");
         server.Stop();

         //Now you just have to wait for the background thread to stop. This is where we use that "Task"
         Console.WriteLine("*Server stopped. Now waiting on async context");
         serverWaitable.Wait(server.Settings.ShutdownTimeout);
      }
   }

   //The : means we're "deriving" from another class. It basically just means we are a "sub-species" of the
   //given class. It's like how an apple is also a fruit: our EchoUser is also a WebSocketUser, and obtains all
   //the abilities of the WebSocketUser base class.
   public class EchoUser : WebSocketUser
   {
      //We override the functionality for receiving messages using this function. Now we can tell the
      //websocket server how to handle messages it receives
      public override void ReceivedMessage(string message)
      {
         //"Send" will send the given message back to the current user only.
         Send("I got: " + message);

         try
         {
            dynamic json = JsonConvert.DeserializeObject(message);
            string first = json.message;
            first = System.Security.SecurityElement.Escape(first);
            Send("Got a good JSON message: " + first);
         }
         catch(Exception)
         {
            Send("Got a bad JSON message");
         }

         //"Broadcast" will send the given message to all connected users.
         if (message.Contains("broadcast"))
            Broadcast("Broadcast: " + message);
      }
   }
}


text:
var express = require('express');
var _ = require('underscore');
var app = express();
var server = require('http').createServer(app);
var config = require('./lib/config');
var path = require('path');
var async;

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/speedtest');
var speedSchema = mongoose.Schema({
    date: Date,
    ping: Number,
    down: Number,
    up: Number
});

var Speed = mongoose.model('speed', speedSchema);

var json = function(res, data) {
  res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });

  if(typeof data === "string") res.write(data);

  else res.write(JSON.stringify(data));

  res.end();
};
app.use(express.static(__dirname + '/static'));

app.get('/speeds', function(req, res) {
  var values;
  Speed.find(function (err, speeds) {
        if (err) return console.error(err);
          console.log(speeds);
          json(res, speeds);
  })
});

server.listen(process.env.PORT || config.port);


text:
package org.ice4j.ice.harvest;

import java.io.*;
import java.lang.ref.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;

import org.ice4j.*;
import org.ice4j.ice.*;
import org.ice4j.socket.*;

/**
 * An implementation of {@link AbstractTcpListener} which acts as a
 * {@link CandidateHarvester}. Sessions are accepted if their ufrag matches
 * a {@link Component} registered with this harvester, and the known addresses
 * of {@link AbstractTcpListener} are added as local host candidates (with type
 * "tcp" and tcptype "passive") when harvesting.
 *
 * @author Boris Grozev
 * @author Lyubomir Marinov
 */
public class TcpHarvester
    extends AbstractTcpListener
    implements CandidateHarvester
{
    /**
     * Our class logger.
     */
    private static final Logger logger
        = Logger.getLogger(TcpHarvester.class.getName());

    /**
     * The constant which specifies how often to perform purging on
     * {@link #components}.
     */
    private static final int PURGE_INTERVAL = 20;

    /**
     * Maps a local "ufrag" to the single <tt>Component</tt> instance with that
     * "ufrag".
     *
     * We only keep weak references, because we do not want to prevent
     * <tt>Component</tt>s from being freed.
     */
    private final Map<String, WeakReference<Component>> components
        = new HashMap<>();

    /**
     * Maps a public address to a local address. Used to add additional
     * candidates with type "srflx" when harvesting.
     */
    private final Map<InetAddress, InetAddress> mappedAddresses
        = new HashMap<>();

    /**
     * Sets of additional ports, for which server reflexive candidates will be
     * added.
     */
    private final Set<Integer> mappedPorts = new HashSet<>();

    /**
     * A counter used to decide when to purge {@link #components}.
     */
    private int purgeCounter = 0;

    /**
     * Whether to advertise candidates with type "ssltcp" (if true) or "tcp"
     * (if false).
     */
    private final boolean ssltcp;

    /**
     * Manages statistics about harvesting time.
     */
    private HarvestStatistics harvestStatistics = new HarvestStatistics();

    /**
     * Initializes a new <tt>TcpHarvester</tt>, which is to
     * listen on port number <tt>port</tt> on all IP addresses on all available
     * interfaces.
     *
     * @param port the port to listen on.
     * @throws IOException when {@link StackProperties#ALLOWED_ADDRESSES} or
     * {@link StackProperties#BLOCKED_ADDRESSES} contains invalid values, or
     * if an I/O error occurs.
     */
    public TcpHarvester(int port)
        throws IOException
    {
        super(port);
        this.ssltcp = false;
        addMappedAddresses();
    }

    /**
     * Initializes a new <tt>TcpHarvester</tt>, which is to
     * listen on port number <tt>port</tt> on all IP addresses on all available
     * interfaces.
     *
     * @param port the port to listen on.
     * @param ssltcp <tt>true</tt> to use ssltcp; otherwise, <tt>false</tt>
     * @throws IOException when {@link StackProperties#ALLOWED_ADDRESSES} or
     * {@link StackProperties#BLOCKED_ADDRESSES} contains invalid values, or
     * if an I/O error occurs.
     */
    public TcpHarvester(int port, boolean ssltcp)
            throws IOException
    {
        super(port, Collections.list(NetworkInterface.getNetworkInterfaces()));
        this.ssltcp = ssltcp;
        addMappedAddresses();
    }

    /**
     * Initializes a new <tt>TcpHarvester</tt>, which is to
     * listen on port number <tt>port</tt> on all the IP addresses on the
     * specified <tt>NetworkInterface</tt>s.
     *
     * @param port the port to listen on.
     * @param interfaces the interfaces to listen on.
     * @param ssltcp <tt>true</tt> to use ssltcp; otherwise, <tt>false</tt>
     * @throws IOException when {@link StackProperties#ALLOWED_ADDRESSES} or
     * {@link StackProperties#BLOCKED_ADDRESSES} contains invalid values, or
     * if an I/O error occurs.
     */
    public TcpHarvester(
            int port,
            List<NetworkInterface> interfaces,
            boolean ssltcp)
        throws IOException
    {
        super(port, interfaces);
        this.ssltcp = ssltcp;
        addMappedAddresses();
    }

    /**
     * Initializes a new <tt>TcpHarvester</tt>, which is to
     * listen on the specified list of <tt>TransportAddress</tt>es.
     *
     * @param transportAddresses the transport addresses to listen on.
     * @throws IOException when {@link StackProperties#ALLOWED_ADDRESSES} or
     * {@link StackProperties#BLOCKED_ADDRESSES} contains invalid values, or
     * if an I/O error occurs.
     */
    public TcpHarvester(List<TransportAddress> transportAddresses)
        throws IOException
    {
        super(transportAddresses);
        this.ssltcp = false;
        addMappedAddresses();
    }

    /**
     * Initializes a new <tt>TcpHarvester</tt>, which is to
     * listen on the specified list of <tt>TransportAddress</tt>es.
     *
     * @param transportAddresses the transport addresses to listen on.
     * @param ssltcp <tt>true</tt> to use ssltcp; otherwise, <tt>false</tt>
     * @throws IOException when {@link StackProperties#ALLOWED_ADDRESSES} or
     * {@link StackProperties#BLOCKED_ADDRESSES} contains invalid values, or
     * if an I/O error occurs.
     */
    public TcpHarvester(
            List<TransportAddress> transportAddresses,
            boolean ssltcp)
        throws IOException
    {
        super(transportAddresses);
        this.ssltcp = ssltcp;
        addMappedAddresses();
    }

    /**
     * Adds the mapped addresses known from {@link MappingCandidateHarvesters}.
     */
    private void addMappedAddresses()
    {
        for (MappingCandidateHarvester harvester
                    : MappingCandidateHarvesters.getHarvesters())
        {
            addMappedAddress(
                    harvester.getMask().getAddress(),
                    harvester.getFace().getAddress());
        }
    }

    /**
     * Adds a mapping between <tt>publicAddress</tt> and <tt>localAddress</tt>.
     * This means that on harvest, along with any host candidates that have
     * <tt>publicAddress</tt>, a server reflexive candidate will be added (with
     * the same port as the host candidate).
     *
     * @param publicAddress the public address.
     * @param localAddress the local address.
     */
    public void addMappedAddress(InetAddress publicAddress,
                                 InetAddress localAddress)
    {
        if (logger.isLoggable(Level.FINE))
        {
            logger.fine("Adding a mapped address: " + localAddress
                            + " => " + publicAddress);
        }
        mappedAddresses.put(publicAddress, localAddress);
    }

    /**
     * Adds port as an additional port. When harvesting, additional server
     * reflexive candidates will be added with this port.
     *
     * @param port the port to add.
     */
    public void addMappedPort(int port)
    {
        mappedPorts.add(port);
    }

    /**
     * Creates and returns the list of <tt>LocalCandidate</tt>s which are to be
     * added by this <tt>TcpHarvester</tt> to a specific
     * <tt>Component</tt>.
     *
     * @param component the <tt>Component</tt> for which to create candidates.
     * @return the list of <tt>LocalCandidate</tt>s which are to be added by
     * this <tt>TcpHarvester</tt> to a specific
     * <tt>Component</tt>.
     */
    private List<LocalCandidate> createLocalCandidates(Component component)
    {
        List<TcpHostCandidate> hostCandidates = new LinkedList<>();

        // Add the host candidates for the addresses we really listen on
        for (TransportAddress transportAddress : localAddresses)
        {
            TcpHostCandidate candidate
                = new TcpHostCandidate(transportAddress, component);

            candidate.setTcpType(CandidateTcpType.PASSIVE);
            if (ssltcp)
                candidate.setSSL(true);

            hostCandidates.add(candidate);
        }

        // Add srflx candidates for any mapped addresses
        List<LocalCandidate> mappedCandidates = new LinkedList<>();

        for (Map.Entry<InetAddress, InetAddress> mapping
                : mappedAddresses.entrySet())
        {
            InetAddress localAddress = mapping.getValue();

            for (TcpHostCandidate base : hostCandidates)
            {
                TransportAddress baseTransportAddress
                    = base.getTransportAddress();

                if (localAddress.equals(baseTransportAddress.getAddress()))
                {
                    InetAddress publicAddress = mapping.getKey();
                    ServerReflexiveCandidate mappedCandidate
                        = new ServerReflexiveCandidate(
                            new TransportAddress(publicAddress,
                                                 baseTransportAddress.getPort(),
                                                 Transport.TCP),
                            base,
                            base.getStunServerAddress(),
                            CandidateExtendedType.STATICALLY_MAPPED_CANDIDATE);

                    if (base.isSSL())
                        mappedCandidate.setSSL(true);
                    mappedCandidate.setTcpType(CandidateTcpType.PASSIVE);

                    mappedCandidates.add(mappedCandidate);
                }
            }
        }

        // Add srflx candidates for mapped ports
        List<LocalCandidate> portMappedCandidates = new LinkedList<>();

        for (TcpHostCandidate base : hostCandidates)
        {
            for (Integer port : mappedPorts)
            {
                ServerReflexiveCandidate portMappedCandidate
                    = new ServerReflexiveCandidate(
                        new TransportAddress(
                            base.getTransportAddress().getAddress(),
                            port,
                            Transport.TCP),
                        base,
                        base.getStunServerAddress(),
                        CandidateExtendedType.STATICALLY_MAPPED_CANDIDATE);

                if (base.isSSL())
                    portMappedCandidate.setSSL(true);
                portMappedCandidate.setTcpType(CandidateTcpType.PASSIVE);

                portMappedCandidates.add(portMappedCandidate);
            }
        }
        // Mapped ports for mapped addresses
        for (LocalCandidate mappedCandidate : mappedCandidates)
        {
            TcpHostCandidate base
                = (TcpHostCandidate) mappedCandidate.getBase();

            for (Integer port : mappedPorts)
            {
                ServerReflexiveCandidate portMappedCandidate
                    = new ServerReflexiveCandidate(
                        new TransportAddress(
                                mappedCandidate.getTransportAddress()
                                        .getAddress(),
                                port,
                                Transport.TCP),
                        base,
                        base.getStunServerAddress(),
                        CandidateExtendedType.STATICALLY_MAPPED_CANDIDATE);

                if (base.isSSL())
                    portMappedCandidate.setSSL(true);
                portMappedCandidate.setTcpType(CandidateTcpType.PASSIVE);

                portMappedCandidates.add(portMappedCandidate);
            }
        }

        LinkedList<LocalCandidate> allCandidates = new LinkedList<>();

        allCandidates.addAll(hostCandidates);
        allCandidates.addAll(mappedCandidates);
        allCandidates.addAll(portMappedCandidates);
        return allCandidates;
    }

    /**
     * Returns the <tt>Component</tt> instance, if any, for a given local
     * "ufrag".
     *
     * @param localUfrag the local "ufrag"
     * @return the <tt>Component</tt> instance, if any, for a given local
     * "ufrag".
     */
    private Component getComponent(String localUfrag)
    {
        synchronized (components)
        {
            WeakReference<Component> wr = components.get(localUfrag);

            if (wr != null)
            {
                Component component = wr.get();

                if (component == null)
                {
                    components.remove(localUfrag);
                }

                return component;
            }
            return null;
        }
    }

    /**
     * {@inheritDoc}
     *
     * Saves a (weak) reference to <tt>Component</tt>, so that it can be
     * notified if/when a socket for one of it <tt>LocalCandidate</tt>s is
     * accepted.
     * <p>
     * The method does not perform any network operations and should return
     * quickly.
     * </p>
     */
    @Override
    public Collection<LocalCandidate> harvest(Component component)
    {
        IceMediaStream stream = component.getParentStream();
        Agent agent = stream.getParentAgent();

        if (stream.getComponentCount() != 1 || agent.getStreamCount() != 1)
        {
            /*
             * TcpHarvester only works with streams with a
             * single component, and agents with a single stream. This is
             * because we use the local "ufrag" to de-multiplex the accept()-ed
             * sockets between the known components.
             */
            logger.info(
                    "More than one Component for an Agent, cannot harvest.");
            return new LinkedList<>();
        }

        List<LocalCandidate> candidates = createLocalCandidates(component);

        for (LocalCandidate candidate : candidates)
            component.addLocalCandidate(candidate);

        synchronized (components)
        {
            components.put(
                    agent.getLocalUfrag(),
                    new WeakReference<>(component));
            purgeComponents();
        }

        return candidates;
    }

    /**
     * Removes entries from {@link #components} for which the
     * <tt>WeakReference</tt> has been cleared.
     */
    private void purgeComponents()
    {
        ++purgeCounter;
        if (purgeCounter % PURGE_INTERVAL == 0)
        {
            synchronized (components)
            {
                for (Iterator<WeakReference<Component>> i
                            = components.values().iterator();
                        i.hasNext();)
                {
                    if (i.next().get() == null)
                        i.remove();
                }
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void acceptSession(Socket socket, String ufrag,
                                 DatagramPacket pushback)
        throws IOException, IllegalStateException
    {
        Component component = getComponent(ufrag);
        if (component == null)
        {
            throw new IllegalStateException(
                    "No component found for ufrag " + ufrag);
        }

        addSocketToComponent(socket, component, pushback);
    }

    /**
     * Makes <tt>socket</tt> available to <tt>component</tt> and pushes back
     * <tt>datagramPacket</tt> into the STUN socket.
     *
     * @param socket the <tt>Socket</tt>.
     * @param component the <tt>Component</tt>.
     * @param datagramPacket the <tt>DatagramPacket</tt> to push back.
     * @throws IllegalStateException if the ICE state is incorrect, or an
     * appropriate candidate could not be found.
     * @throws IOException if creation of some of the required socket instances
     * failed.
     */
    private void addSocketToComponent(
            Socket socket, Component component, DatagramPacket datagramPacket)
        throws IOException, IllegalStateException
    {
        IceProcessingState state
            = component.getParentStream().getParentAgent().getState();

        if (logger.isLoggable(Level.FINE)
            && !IceProcessingState.WAITING.equals(state)
            && !IceProcessingState.RUNNING.equals(state))
        {
            logger.fine("Adding a socket to an Agent in state " + state);
        }

        // Socket to add to the candidate
        IceSocketWrapper candidateSocket = null;
        // STUN-only filtered socket to add to the StunStack
        IceSocketWrapper stunSocket = null;

        MultiplexingSocket multiplexing = new MultiplexingSocket(socket);
        candidateSocket = new IceTcpSocketWrapper(multiplexing);

        stunSocket
            = new IceTcpSocketWrapper(
                multiplexing.getSocket(new StunDatagramPacketFilter()));
        stunSocket = new PushBackIceSocketWrapper(stunSocket, datagramPacket);

        TcpHostCandidate candidate = findCandidate(component, socket);
        if (candidate == null)
        {
            throw new IOException(
                    "Failed to find the local candidate for socket: " + socket);
        }

        component.getParentStream().getParentAgent().getStunStack()
                .addSocket(stunSocket);
        candidate.addSocket(candidateSocket);

        // TODO: Maybe move this code to the candidate.
        component.getComponentSocket().add(multiplexing);

        // the socket is not our responsibility anymore. It is up to
        // the candidate/component to close/free it.
    }

    /**
     * Searches among the local candidates of <tt>Component</tt> for a
     * <tt>TcpHostCandidate</tt> with the same transport address as the
     * local transport address of <tt>socket</tt>.
     *
     * We expect to find such a candidate, which has been added by this
     * <tt>TcpHarvester</tt> while harvesting.
     *
     * @param component the <tt>Component</tt> to search.
     * @param socket the <tt>Socket</tt> to match the local transport
     * address of.
     * @return a <tt>TcpHostCandidate</tt> among the local candidates of
     * <tt>Component</tt> with the same transport address as the local
     * address of <tt>Socket</tt>, or <tt>null</tt> if no such candidate
     * exists.
     */
    private TcpHostCandidate findCandidate(
        Component component,
        Socket socket)
    {
        InetAddress localAddress = socket.getLocalAddress();
        int localPort = socket.getLocalPort();

        for (LocalCandidate candidate : component.getLocalCandidates())
        {
            TransportAddress transportAddress
                = candidate.getTransportAddress();

            if (candidate instanceof TcpHostCandidate
                && Transport.TCP.equals(transportAddress.getTransport())
                && localPort == transportAddress.getPort()
                && localAddress.equals(transportAddress.getAddress()))
            {
                return (TcpHostCandidate) candidate;
            }
        }
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isHostHarvester()
    {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    public HarvestStatistics getHarvestStatistics()
    {
        return harvestStatistics;
    }

}


text:
SELECT * FROM GROUP_USER_RELATIONSHIP
 WHERE
SECTION_CODE = ?
;
;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AH.PRMS.DAL;
using AH.PRMS.MODEL;

namespace AH.PRMS.BLL
{
    public class NurseStationBLL
    {
        public List<NurseStation> GetNurseStation()
        {
            return new NurseStationDAL().GetNurseStation();
        }
        public Dictionary<string, string> GetNurseStationDic(string type)
        {
            Dictionary<string, string> nurseDic = new Dictionary<string, string>();
            foreach (NurseStation nurse in new NurseStationDAL().GetNurseStation())
            {
                nurseDic.Add(nurse.NurseStationID, nurse.NurseStationTitle);
            }
            return nurseDic;
        }
        public short SaveNurseStation(NurseStation nurse)
        {
            return new NurseStationDAL().SaveNurseStation(nurse);
        }
        public List<NurseStation> GetNurseAllStation()
        {
            return new NurseStationDAL().GetNurseAllStation();
        }
        public short UpdateNurseStation(NurseStation nurse)
        {
            return new NurseStationDAL().UpdateNurseStation(nurse);
        }
        public List<NurseStation> GetNurseStationFloorWise(int floorNo)
        {
            return new NurseStationDAL().GetNurseStationFloorWise(floorNo);
        }

    }
}


text:
from fixture.variables import UserLogin
from functools import wraps
from fixture.variables import Profinity
from sys import maxsize

def connection(fn):
    @wraps(fn)
    def wrapper(app):
        app.session.login(UserLogin.name, UserLogin.password)
        try:
            fn(app)
        finally:
            app.session.logout()

    return wrapper

class Contact:
    def __init__(self, first_name=None, middle_name=None, last_name=None, nickname=None, title=None, company_name=None,
                 address_name=None, home=None, mobile=None, work=None, fax=None, email1=None, email2=None, email3=None,
                 homepage=None, address=None, phone=None, notes=None, add_year=None, id=None, contact_name=None):

        self.first_name = first_name
        self.middle_name = middle_name
        self.last_name = last_name
        self.nickname = nickname
        self.title = title
        self.company_name = company_name
        self.address_name = address_name
        self.home = home
        self.mobile = mobile
        self.work = work
        self.fax = fax
        self.email1 = email1
        self.email2 = email2
        self.email3 = email3
        self.homepage = homepage
        self.address = address
        self.phone = phone
        self.notes = notes
        self.add_year = add_year
        self.contract_name = contact_name
        self.id = id

    def __repr__(self):
        return '%s:%s:%s' % (self.id, self.first_name, self.last_name)

    def __eq__(self, other):
        return (self.id is None or other.id is None or self.id == other.id) and self.first_name == other.first_name and \
                self.last_name == other.last_name

    def if_or_max(self):
        if self.id:
            return int(self.id)
        else:
            return maxsize

class ContactBase():
    def __init__(self, app):
        self.app = app

    def count(self):
        wd = self.app.wd
        self.open_contract_page()
        return len(wd.find_elements_by_name("selected[]"))

    def open_contract_page(self):
        wd = self.app.wd
        if not (wd.current_url.endswith('addressbook/')): #and len(wd.find_elements_by_name('new')) > 0):
            wd.find_element_by_link_text("home").click()

    def validation_of_contact_exist(self):
        if self.count() == 0:
            self.create((Contact(first_name=Profinity.correct_data, last_name=Profinity.correct_data,
                        middle_name=Profinity.correct_data, nickname=Profinity.correct_data)))

    def edit_contract(self, Contract):
        wd = self.app.wd
        self.open_contract_page()

        wd.find_element_by_css_selector("img[alt=\"Edit\"]").click()
        self.contract_field(Contract)
        wd.find_element_by_xpath("//div[@id='content']/form[1]/input[22]").click()
        self.open_contract_page()
        contract_cache = None

    def contract_field(self, Contact):
        wd = self.app.wd
        if Contact.first_name:
            wd.find_element_by_name("firstname").click()
            wd.find_element_by_name("firstname").clear()
            wd.find_element_by_name("firstname").send_keys("%s" % Contact.first_name)
        if Contact.middle_name:
            wd.find_element_by_name("middlename").click()
            wd.find_element_by_name("middlename").clear()
            wd.find_element_by_name("middlename").send_keys("%s" % Contact.middle_name)
        if Contact.last_name:
            wd.find_element_by_name("lastname").click()
            wd.find_element_by_name("lastname").clear()
            wd.find_element_by_name("lastname").send_keys("%s" % Contact.last_name)
        if Contact.nickname:
            wd.find_element_by_name("nickname").click()
            wd.find_element_by_name("nickname").clear()
            wd.find_element_by_name("nickname").send_keys("%s" % Contact.nickname)

        if Contact.title:
            wd.find_element_by_name("title").click()
            wd.find_element_by_name("title").clear()
            wd.find_element_by_name("title").send_keys("%s" % Contact.title)

        if Contact.company_name:
            wd.find_element_by_name("company").click()
            wd.find_element_by_name("company").clear()
            wd.find_element_by_name("company").send_keys("%s" % Contact.company_name)

        if Contact.address_name:
            wd.find_element_by_name("address").click()
            wd.find_element_by_name("address").clear()
            wd.find_element_by_name("address").send_keys("%s" % Contact.address_name)

        if Contact.home:
            wd.find_element_by_name("home").click()
            wd.find_element_by_name("home").clear()
            wd.find_element_by_name("home").send_keys("%s" % Contact.home)
        if Contact.mobile:
            wd.find_element_by_name("mobile").click()
            wd.find_element_by_name("mobile").clear()
            wd.find_element_by_name("mobile").send_keys("%s" % Contact.mobile)
        if Contact.work:
            wd.find_element_by_name("work").click()
            wd.find_element_by_name("work").clear()
            wd.find_element_by_name("work").send_keys("%s" % Contact.work)
        if Contact.fax:
            wd.find_element_by_name("fax").click()
            wd.find_element_by_name("fax").clear()
            wd.find_element_by_name("fax").send_keys("%s" % Contact.fax)

        if Contact.email1:
            wd.find_element_by_name("email").click()
            wd.find_element_by_name("email").click()
            wd.find_element_by_name("email").clear()
            wd.find_element_by_name("email").send_keys("%s" % Contact.email1)
        if Contact.email2:
            wd.find_element_by_name("email2").click()
            wd.find_element_by_name("email2").clear()
            wd.find_element_by_name("email2").send_keys("%s" % Contact.email2)
        if Contact.email3:
            wd.find_element_by_name("email3").click()
            wd.find_element_by_name("email3").clear()
            wd.find_element_by_name("email3").send_keys("%s" % Contact.email3)

        if Contact.homepage:
            wd.find_element_by_name("homepage").click()
            wd.find_element_by_name("homepage").clear()
            wd.find_element_by_name("homepage").send_keys("%s" % Contact.homepage)

        if Contact.add_year:
            # in futures we can made function where we will sent date and it choose it with similar way as previous
            if not wd.find_element_by_xpath("//div[@id='content']/form/select[1]//option[3]").is_selected():
                wd.find_element_by_xpath("//div[@id='content']/form/select[1]//option[3]").click()
            if not wd.find_element_by_xpath("//div[@id='content']/form/select[2]//option[2]").is_selected():
                wd.find_element_by_xpath("//div[@id='content']/form/select[2]//option[2]").click()
            wd.find_element_by_name("byear").click()
            wd.find_element_by_name("byear").clear()
            wd.find_element_by_name("byear").send_keys("1999")
            if not wd.find_element_by_xpath("//div[@id='content']/form/select[3]//option[3]").is_selected():
                wd.find_element_by_xpath("//div[@id='content']/form/select[3]//option[3]").click()
            if not wd.find_element_by_xpath("//div[@id='content']/form/select[4]//option[2]").is_selected():
                wd.find_element_by_xpath("//div[@id='content']/form/select[4]//option[2]").click()
            wd.find_element_by_name("ayear").click()
            wd.find_element_by_name("ayear").clear()
            wd.find_element_by_name("ayear").send_keys("1999")

        if Contact.address:
            wd.find_element_by_name("address2").click()
            wd.find_element_by_name("address2").clear()
            wd.find_element_by_name("address2").send_keys("%s" % Contact.address)

        if Contact.phone:
            wd.find_element_by_name("phone2").click()
            wd.find_element_by_name("phone2").clear()
            wd.find_element_by_name("phone2").send_keys("%s" % Contact.phone)

        if Contact.notes:
            wd.find_element_by_name("notes").click()
            wd.find_element_by_name("notes").clear()
            wd.find_element_by_name("notes").send_keys("%s" % Contact.notes)

    def create(self, Contact):
        wd = self.app.wd
        wd.find_element_by_link_text("add new").click()

        self.contract_field(Contact)

        wd.find_element_by_xpath("//div[@id='content']/form/input[21]").click()
        contract_cache = None

    def delete_contact(self):
        self.delete_contact_by_index(0)

    contract_cache = None

    def get_contact_list(self):
        if self.contract_cache is None:
            wd = self.app.wd
            self.open_contract_page()
            contract_cache = []
            row = 2

            for element in wd.find_elements_by_name("entry"):
                text = []
                for column in range(2, 4):
                    text.append(wd.find_element_by_xpath("//*[@id='maintable']/tbody/tr["+str(row)+"]/td["+str(column)+"]").text)

                my_id = element.find_element_by_name("selected[]").get_attribute("value")

                contract_cache.append(Contact(first_name=text[1], last_name=text[0], id=my_id))
                row += 1

            return contract_cache

    def delete_contact_by_index(self, index):
        wd = self.app.wd
        self.open_contract_page()

        wd.find_elements_by_name("selected[]")[index].click()

        wd.find_element_by_xpath("//div[@id='content']/form[2]/div[2]/input").click()
        wd.switch_to_alert().accept()
        contract_cache = None

    def edit_contract_by_index(self, Contract, index):
        wd = self.app.wd
        self.open_contract_page()

        wd.find_elements_by_css_selector("img[alt=\"Edit\"]")[index].click()
        #wd.find_elements_by_name()
        self.contract_field(Contract)
        wd.find_element_by_xpath("//div[@id='content']/form[1]/input[22]").click()
        self.open_contract_page()
        contract_cache = None


text:
import React from 'react';

import NotAuthorizedPage from '../../../../components/NotAuthorizedPage';
import { usePermission } from '../../../../contexts/AuthorizationContext';
import ChatTable from './ChatTable';

function ChatTab(props) {
	const hasAccess = usePermission('view-l-room');

	if (hasAccess) {
		return <ChatTable {...props} />;
	}

	return <NotAuthorizedPage />;
}

export default ChatTab;


text:
DECLARE_REGISTER(uint8_t, SREG);
DECLARE_REGISTER(uint8_t, SPH);
DECLARE_REGISTER(uint8_t, SPL);
DECLARE_REGISTER(uint16_t, SP);
DECLARE_REGISTER(uint8_t, CCP);
DECLARE_REGISTER(uint8_t, RSTFLR);
DECLARE_REGISTER(uint8_t, SMCR);
DECLARE_REGISTER(uint8_t, OSCCAL);
DECLARE_REGISTER(uint8_t, CLKMSR);
DECLARE_REGISTER(uint8_t, CLKPSR);
DECLARE_REGISTER(uint8_t, PRR);
DECLARE_REGISTER(uint8_t, VLMCSR);
DECLARE_REGISTER(uint8_t, NVMCMD);
DECLARE_REGISTER(uint8_t, NVMCSR);
DECLARE_REGISTER(uint8_t, WDTCSR);
DECLARE_REGISTER(uint8_t, GTCCR);
DECLARE_REGISTER(uint8_t, TCCR0A);
DECLARE_REGISTER(uint8_t, TCCR0B);
DECLARE_REGISTER(uint8_t, TCCR0C);
DECLARE_REGISTER(uint8_t, TIMSK0);
DECLARE_REGISTER(uint8_t, TIFR0);
DECLARE_REGISTER(uint8_t, TCNT0H);
DECLARE_REGISTER(uint8_t, TCNT0L);
DECLARE_REGISTER(uint16_t, TCNT0);
DECLARE_REGISTER(uint8_t, OCR0AH);
DECLARE_REGISTER(uint8_t, OCR0AL);
DECLARE_REGISTER(uint16_t, OCR0A);
DECLARE_REGISTER(uint8_t, OCR0BH);
DECLARE_REGISTER(uint8_t, OCR0BL);
DECLARE_REGISTER(uint16_t, OCR0B);
DECLARE_REGISTER(uint8_t, ICR0H);
DECLARE_REGISTER(uint8_t, ICR0L);
DECLARE_REGISTER(uint16_t, ICR0);
DECLARE_REGISTER(uint8_t, ACSR);
DECLARE_REGISTER(uint8_t, DIDR0);
DECLARE_REGISTER(uint8_t, EICRA);
DECLARE_REGISTER(uint8_t, EIFR);
DECLARE_REGISTER(uint8_t, EIMSK);
DECLARE_REGISTER(uint8_t, PCICR);
DECLARE_REGISTER(uint8_t, PCIFR);
DECLARE_REGISTER(uint8_t, PCMSK);
DECLARE_REGISTER(uint8_t, PORTCR);
DECLARE_REGISTER(uint8_t, PUEB);
DECLARE_REGISTER(uint8_t, PORTB);
DECLARE_REGISTER(uint8_t, DDRB);
DECLARE_REGISTER(uint8_t, PINB);


text:
    <title>Transformed resize corner tracking</title>

        Test for
        https://bugs.webkit.org/show_bug.cgi?id=9221
        resize property doesn't work on iframes.


text:
<?php
namespace Icecave\Pasta\AST\Expr;

use Icecave\Pasta\AST\ContainerNode;
use Icecave\Pasta\AST\Identifier;

class QualifiedIdentifier extends ContainerNode implements IExpression
{
    const NAMESPACE_SEPARATOR = '\\';

    public function __construct(array $children, $isAbsolute = true)
    {
        parent::__construct('Icecave\Pasta\AST\Identifier', $children, 1);
        $this->isAbsolute = $isAbsolute;
    }

    public static function fromString($string)
    {
        $isAbsolute = false;
        if ($string{0} === self::NAMESPACE_SEPARATOR) {
            $isAbsolute = true;
            $string = substr($string, 1);
        }

        $children = array();
        foreach (explode(self::NAMESPACE_SEPARATOR, $string) as $atom) {
            $children[] = new Identifier($atom);
        }

        return new static($children, $isAbsolute);
    }

    public function isAbsolute()
    {
        return $this->isAbsolute;
    }

    public function setIsAbsolute($isAbsolute)
    {
        $this->isAbsolute = $isAbsolute;
    }

    public function string()
    {
        $string = '';
        foreach ($this->children() as $index => $child) {
            if ($this->isAbsolute() || $index > 0) {
                $string .= self::NAMESPACE_SEPARATOR;
            }
            $string .= $child->name();
        }

        return $string;
    }

    private $isAbsolute;
}


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

	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="osgi.properties"/>
	</bean>

	<bean id="initializer" class="java.util.Properties" depends-on="weatherTest"/>

	<osgi:bundle id="weatherTestBundle" depends-on="weatherServiceBundle" symbolic-name="org.springframework.osgi.samples.weather.service.test"
	             location="file:${localRepository}/org/springframework/osgi/samples/weather-service-test/${pom.version}/weather-service-test-${pom.version}.jar" action="start"/>

	<osgi:bundle id="weatherDaoBundle" symbolic-name="org.springframework.osgi.samples.weather-dao"
	             location="file:${localRepository}/org/springframework/osgi/samples/weather-dao/${pom.version}/weather-dao-${pom.version}.jar"
	             action="start"/>

	<osgi:bundle id="weatherServiceBundle" action="start">
		<ref local="weatherServiceVirtualBundle"/>
	</osgi:bundle>

	<!-- Note that this is not a real bundle - we are creating it on the fly from a regular jar -->
	<extension:virtual-bundle id="weatherServiceVirtualBundle" depends-on="weatherDaoBundle"
	                     location="file:${localRepository}/org/springframework/osgi/samples/weather-service/${pom.version}/weather-service-${pom.version}.jar"
	                     version="${spring.osgi.bundle.version}" group-id="org.springframework.osgi.samples.weather" artifact-id="service">
		<extension:imports>
			<extension:package name="org.springframework.osgi.samples.weather.dao" version="${spring.osgi.bundle.version}"/>
			<extension:package name="org.springframework.osgi.config"/>
		</extension:imports>
		<extension:exports>
			<extension:package name="org.springframework.osgi.samples.weather.service" version="${spring.osgi.bundle.version}"/>
		</extension:exports>
	</extension:virtual-bundle>

	<osgi:reference id="weatherService" interface="org.springframework.osgi.samples.weather.service.WeatherService"
	                bean-name="weatherService" timeout="2000" depends-on="weatherServiceBundle,weatherTestBundle">
		<osgi:listener ref="weatherListener"/>
	</osgi:reference>

	<bean id="weatherListener" class="org.springframework.osgi.samples.weather.test.WeatherListener" lazy-init="true"/>

	<bean id="weatherTest" class="org.springframework.osgi.samples.weather.test.WeatherServiceTest"
	      init-method="testSample2" lazy-init="true" depends-on="weatherTestBundle">
		<property name="weatherService" ref="weatherService"/>
	</bean>

	<!--bean id="jmxExporter" class="org.springframework.jmx.export.MBeanExporter">
		<property name="beans">
			<map>
				<entry key="weatherService:service=bundle" value-ref="weatherServiceBundle"/>
			</map>
		</property>
		<property name="assembler">
			<bean class="org.springframework.jmx.export.assembler.InterfaceBasedMBeanInfoAssembler">
				<property name="interfaceMappings">
					<props>
						<prop key="weatherService:service=bundle">org.osgi.framework.Bundle</prop>
					</props>
				</property>
			</bean>
		</property>
		<property name="autodetect" value="true"/>
	</bean-->

</beans>


text:
require 'rouge/plugins/redcarpet'
module MarkdownSupport

  class HTML < MdEmoji::Render
    include Rouge::Plugins::Redcarpet
  end

  extend ControllerSupport::Base

  before_filter :setup_markdown
  helper_method :markdown

  def markdown
    @markdown
  end

  def setup_markdown
    @markdown = Redcarpet::Markdown.new(HTML,
                                        :autolink => true,
                                        :space_after_headers => true,
                                        :fenced_code_blocks => true,
                                        :disable_indented_code_blocks => true
    )
  end

end


text:
docker build ../src/monot-brain

docker build ../src/monot-vision

docker build ../src-monot-hearing


text:
package oap.fs;

import oap.testng.Fixtures;
import oap.testng.TestDirectoryFixture;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;

public class LocalFileManagerTest extends Fixtures {
    {
        fixture( TestDirectoryFixture.FIXTURE );
    }

    private LocalFileManager fileManager;
    private Path tmp = TestDirectoryFixture.testPath( "/tmp/test" );

    @BeforeClass
    public void setUp() {
        fileManager = new LocalFileManager( Map.of( FileManager.DEFAULT_BUCKET, tmp ) );
    }

    @Test
    public void readWrite() throws Exception {
        fileManager.write( new Data( "file.txt", "text/plain", "dGVzdA==" ) );
        var read = fileManager.read( TestDirectoryFixture.testPath( "/tmp/test/file.txt" ).toString() );

        assertThat( read.isPresent() ).isTrue();
        assertThat( new String( read.get() ) ).isEqualTo( "test" );
    }

    @AfterClass
    public void cleanUp() throws Exception {
        Files.deleteIfExists( tmp );
    }
}


text:
$.namespace('azkaban');

azkaban.ChangeSlaView = Backbone.View.extend({
  events: {
    "click": "closeEditingTarget",
    "click #set-sla-btn": "handleSetSla",
    "click #remove-sla-btn": "handleRemoveSla",
    "click #add-btn": "handleAddRow"
  },

  initialize: function (setting) {
    $('#sla-options').on('hidden.bs.modal', function () {
      slaView.handleSlaCancel();
    });
  },

  handleSlaCancel: function () {
    console.log("Clicked cancel button");
    var scheduleURL = contextURL + "/schedule";
    var tFlowRules = document.getElementById("flowRulesTbl").tBodies[0];
    var rows = tFlowRules.rows;
    var rowLength = rows.length
    for (var i = 0; i < rowLength - 1; i++) {
      tFlowRules.deleteRow(0);
    }
  },

  initFromSched: function (scheduleId, flowName) {
    this.scheduleId = scheduleId;
    var scheduleURL = contextURL + "/schedule"
    this.scheduleURL = scheduleURL;

    var indexToName = {};
    var nameToIndex = {};
    var indexToText = {};
    this.indexToName = indexToName;
    this.nameToIndex = nameToIndex;
    this.indexToText = indexToText;

    var ruleBoxOptions = ["SUCCESS", "FINISH"];
    this.ruleBoxOptions = ruleBoxOptions;

    var fetchScheduleData = {
      "scheduleId": this.scheduleId,
      "ajax": "slaInfo"
    };

    var successHandler = function (data) {
      if (data.error) {
        alert(data.error);
        return;
      }
      if (data.slaEmails) {
        $('#slaEmails').val(data.slaEmails.join());
      }

      var allJobNames = data.allJobNames;

      indexToName[0] = "";
      nameToIndex[flowName] = 0;
      indexToText[0] = "flow " + flowName;
      for (var i = 1; i <= allJobNames.length; i++) {
        indexToName[i] = allJobNames[i - 1];
        nameToIndex[allJobNames[i - 1]] = i;
        indexToText[i] = "job " + allJobNames[i - 1];
      }

      // populate with existing settings
      if (data.settings) {
        var tFlowRules = document.getElementById("flowRulesTbl").tBodies[0];
        for (var setting in data.settings) {
          var rFlowRule = tFlowRules.insertRow(0);

          var cId = rFlowRule.insertCell(-1);
          var idSelect = document.createElement("select");
          idSelect.setAttribute("class", "form-control");
          for (var i in indexToName) {
            idSelect.options[i] = new Option(indexToText[i], indexToName[i]);
            if (data.settings[setting].id == indexToName[i]) {
              idSelect.options[i].selected = true;
            }
          }
          cId.appendChild(idSelect);

          var cRule = rFlowRule.insertCell(-1);
          var ruleSelect = document.createElement("select");
          ruleSelect.setAttribute("class", "form-control");
          for (var i in ruleBoxOptions) {
            ruleSelect.options[i] = new Option(ruleBoxOptions[i],
                ruleBoxOptions[i]);
            if (data.settings[setting].rule == ruleBoxOptions[i]) {
              ruleSelect.options[i].selected = true;
            }
          }
          cRule.appendChild(ruleSelect);

          var cDuration = rFlowRule.insertCell(-1);
          var duration = document.createElement("input");
          duration.type = "text";
          duration.setAttribute("class", "form-control durationpick");
          var rawMinutes = data.settings[setting].duration;
          var intMinutes = rawMinutes.substring(0, rawMinutes.length - 1);
          var minutes = parseInt(intMinutes);
          var hours = Math.floor(minutes / 60);
          minutes = minutes % 60;
          duration.value = hours + ":" + minutes;
          cDuration.appendChild(duration);

          var cEmail = rFlowRule.insertCell(-1);
          var emailCheck = document.createElement("input");
          emailCheck.type = "checkbox";
          for (var act in data.settings[setting].actions) {
            if (data.settings[setting].actions[act] == "EMAIL") {
              emailCheck.checked = true;
            }
          }
          cEmail.appendChild(emailCheck);

          var cKill = rFlowRule.insertCell(-1);
          var killCheck = document.createElement("input");
          killCheck.type = "checkbox";
          for (var act in data.settings[setting].actions) {
            if (data.settings[setting].actions[act] == "KILL") {
              killCheck.checked = true;
            }
          }
          cKill.appendChild(killCheck);
          $('.durationpick').datetimepicker({
            format: 'HH:mm'
          });
        }
      }
      $('.durationpick').datetimepicker({
        format: 'HH:mm'
      });
    };

    $.get(this.scheduleURL, fetchScheduleData, successHandler, "json");

    $('#sla-options').modal();

    //this.schedFlowOptions = sched.flowOptions
    console.log("Loaded schedule info. Ready to set SLA.");
  },

  handleRemoveSla: function (evt) {
    console.log("Clicked remove sla button");
    var scheduleURL = this.scheduleURL;
    var redirectURL = this.scheduleURL;
    var requestData = {
      "action": "removeSla",
      "scheduleId": this.scheduleId
    };
    var successHandler = function (data) {
      if (data.error) {
        $('#errorMsg').text(data.error)
      }
      else {
        window.location = redirectURL
      }
    };
    $.post(scheduleURL, requestData, successHanlder, "json");
  },

  handleSetSla: function (evt) {
    var slaEmails = $('#slaEmails').val().trim();
    var settings = {};
    var tFlowRules = document.getElementById("flowRulesTbl").tBodies[0];
    for (var row = 0; row < tFlowRules.rows.length - 1; row++) {
      var rFlowRule = tFlowRules.rows[row];
      var id = rFlowRule.cells[0].firstChild.value;
      var rule = rFlowRule.cells[1].firstChild.value;
      var duration = rFlowRule.cells[2].firstChild.value;
      var email = rFlowRule.cells[3].firstChild.checked;
      var kill = rFlowRule.cells[4].firstChild.checked;
      if (!email && !kill) {
        alert("Unable to create SLA Action. Please set either Kill or Email"
            + " action");
        return false;
      }
      if (!email && slaEmails === "") {
        alert("Unable to create SLA Action. Please provide at least one email"
            + " address for Email action");
        return false;
      }
      settings[row] = id + "," + rule + "," + duration + "," + email + ","
          + kill;
    }

    var slaData = {
      scheduleId: this.scheduleId,
      ajax: "setSla",
      slaEmails: slaEmails,
      settings: settings
    };

    var scheduleURL = this.scheduleURL;
    var successHandler = function (data) {
      if (data.error) {
        alert(data.error);
      }
      else {
        tFlowRules.length = 0;
        window.location = scheduleURL;
      }
    };
    $.post(scheduleURL, slaData, successHandler, "json");
  },

  handleAddRow: function (evt) {
    var indexToName = this.indexToName;
    var nameToIndex = this.nameToIndex;
    var indexToText = this.indexToText;
    var ruleBoxOptions = this.ruleBoxOptions;

    var tFlowRules = document.getElementById("flowRulesTbl").tBodies[0];
    var rFlowRule = tFlowRules.insertRow(tFlowRules.rows.length - 1);

    var cId = rFlowRule.insertCell(-1);
    var idSelect = document.createElement("select");
    idSelect.setAttribute("class", "form-control");
    for (var i in indexToName) {
      idSelect.options[i] = new Option(indexToText[i], indexToName[i]);
    }
    cId.appendChild(idSelect);

    var cRule = rFlowRule.insertCell(-1);
    var ruleSelect = document.createElement("select");
    ruleSelect.setAttribute("class", "form-control");
    for (var i in ruleBoxOptions) {
      ruleSelect.options[i] = new Option(ruleBoxOptions[i], ruleBoxOptions[i]);
    }
    cRule.appendChild(ruleSelect);

    var cDuration = rFlowRule.insertCell(-1);
    var duration = document.createElement("input");
    duration.type = "text";
    duration.setAttribute("class", "durationpick form-control");
    cDuration.appendChild(duration);

    var cEmail = rFlowRule.insertCell(-1);
    var emailCheck = document.createElement("input");
    emailCheck.type = "checkbox";
    cEmail.appendChild(emailCheck);

    var cKill = rFlowRule.insertCell(-1);
    var killCheck = document.createElement("input");
    killCheck.type = "checkbox";
    cKill.appendChild(killCheck);

    $('.durationpick').datetimepicker({
      format: 'HH:mm'
    });
    return rFlowRule;
  },

  handleEditColumn: function (evt) {
    var curTarget = evt.currentTarget;
    if (this.editingTarget != curTarget) {
      this.closeEditingTarget();

      var text = $(curTarget).children(".spanValue").text();
      $(curTarget).empty();

      var input = document.createElement("input");
      $(input).attr("type", "text");
      $(input).css("width", "100%");
      $(input).val(text);
      $(curTarget).addClass("editing");
      $(curTarget).append(input);
      $(input).focus();
      this.editingTarget = curTarget;
    }
  },

  handleRemoveColumn: function (evt) {
    var curTarget = evt.currentTarget;
    // Should be the table
    var row = curTarget.parentElement.parentElement;
    $(row).remove();
  },

  closeEditingTarget: function (evt) {
  }
});


text:
package com.eaw1805.www.shared.orders.army;

import com.eaw1805.data.constants.NationConstants;
import com.eaw1805.data.dto.web.army.ArmyTypeDTO;
import com.eaw1805.data.dto.web.army.BattalionDTO;
import com.eaw1805.data.dto.web.army.BrigadeDTO;
import com.eaw1805.www.shared.orders.Order;

import java.util.ArrayList;

public class AddBattalionToBrigade
        implements Order {

    private final BrigadeDTO brig;
    private final ArmyTypeDTO armyType;
    private final int slot;

    public AddBattalionToBrigade(final BrigadeDTO brigade, final ArmyTypeDTO armyType, final int slot) {
        brig = brigade;
        this.armyType = armyType;
        this.slot = slot;
    }

    public int execute(final int unitId) {
        final BattalionDTO batt = new BattalionDTO();
        batt.setEmpireArmyType(armyType);
        batt.setOrder(slot);
        batt.setTypeId(armyType.getIndPt());
        batt.setExperience(1);
        batt.setBrigadeId(unitId);
        batt.setFleeing(false);
        batt.setNotSupplied(false);
        batt.setParticipated(false);
        batt.setId(0);
        int headcount = 800;
        if (armyType.getNationId() == NationConstants.NATION_MOROCCO
                || armyType.getNationId() == NationConstants.NATION_OTTOMAN
                || armyType.getNationId() == NationConstants.NATION_EGYPT) {
            headcount = 1000;
        }
        batt.setHeadcount(headcount);

        if (brig.getBattalions() == null) {
            brig.setBattalions(new ArrayList<BattalionDTO>());
        }

        brig.getBattalions().add(batt);
        return 0;
    }

}


text:
FROM stratos/base-image:4.2.0
MAINTAINER dev@stratos.apache.org

ENV JDK_VERSION 1.7.0_80
ENV JDK_TAR_FILENAME jdk-7u80-linux-x64.tar.gz
ENV TOMCAT_VERSION 7.0.55

# ----------------------
# Install prerequisites
# ----------------------
WORKDIR /opt
ADD packs/${JDK_TAR_FILENAME} /mnt/${JDK_TAR_FILENAME}
RUN mv /mnt/${JDK_TAR_FILENAME}/jdk${JDK_VERSION} /opt/jdk${JDK_VERSION}
ENV JAVA_HOME /opt/jdk${JDK_VERSION}

ENV CATALINA_HOME /opt/tomcat

# ----------------------
# Install Tomcat
# ----------------------
ADD packs/apache-tomcat-${TOMCAT_VERSION}.tar.gz /opt/apache-tomcat-${TOMCAT_VERSION}.tar.gz
RUN mv /opt/apache-tomcat-${TOMCAT_VERSION}.tar.gz/apache-tomcat-${TOMCAT_VERSION} /opt/tomcat && \
    rm -rf /opt/apache-tomcat-${TOMCAT_VERSION}.tar.gz

# -----------------------
# Add shell scripts
# -----------------------
ADD files/create-admin-user.sh /opt/create-admin-user.sh
RUN chmod +x /opt/create-admin-user.sh && \
    bash /opt/create-admin-user.sh

ADD files/env /tmp/env
RUN chmod +x /tmp/env && \
    sleep 1 && \
    /tmp/env ${JAVA_HOME} ${CATALINA_HOME}

#------------------------
# Copy Tomcat related PCA plugins
#-----------------------
ADD packs/plugins /mnt/plugins

EXPOSE 8080

# -----------------------
# Define entry point
# -----------------------
ENTRYPOINT /usr/local/bin/run | /usr/sbin/sshd -D


text:
title: Soccer
date: 2012-11-12 00:00:00 Z
permalink: "/2012/11/12/20121112soccer/"
categories:
- Picture of the Day
- Uncategorized
author: Jennifer
layout: post
---

[<img alt="20121112-160949.jpg" class="alignnone size-full" src="http://static.squarespace.com/static/50db6bb3e4b015296cd43789/50dfa5b1e4b0dc6320e0b5ea/50dfa5b5e4b0dc6320e0b9a5/1352736592000/?format=original" />](http://static.squarespace.com/static/50db6bb3e4b015296cd43789/50dfa5b1e4b0dc6320e0b5ea/50dfa5b5e4b0dc6320e0b9a5/1352736592000/?format=original)

Jennifer helped coach Noah’s soccer team this year and it really took on a life of its own. We just concluded the season and they threw a party to celebrate the kiddos and the coaches. Parents cried talking about how much their kids had improved and really excelled on this team. It was the first of many moments for us to be a part of something like this. So so proud of my hubby and of course my little gamechanger!!!! GO LIGHTENING TIGERS!


text:
from __future__ import absolute_import

import logging

from keras.layers import Lambda, Dense, Concatenate
from keras.models import Model, Input

from .architectures import get_network_by_name
from .generic_layer_utils import slice_vector

logger = logging.getLogger(__name__)

class BaseDecoder(object):
    def __init__(self, latent_dim, data_dim, network_architecture='synthetic', name='decoder'):
        logger.info("Initialising {} model with {}-dimensional data "
                    "and {}-dimensional latent input.".format(name, data_dim, latent_dim))
        self.name = '_'.join(name.lower().split())
        self.data_dim = data_dim
        self.latent_dim = latent_dim
        self.network_architecture = network_architecture
        self.data_input = Input(shape=(self.data_dim,), name='dec_ll_estimator_data_input')
        self.latent_input = Input(shape=(self.latent_dim,), name='dec_latent_input')

    def __call__(self, *args, **kwargs):
        return None

class StandardDecoder(BaseDecoder):
    """
    A StandardDecoder model has inputs comprising of a latent encoding given by an Encoder model, a prior sampler
    or other custom input and the raw Encoder data input, which is needed to estimate the reconstructed
    data log likelihood. It can be visualised as:

      Data    Latent
       |        |
       |    -----------
       |    | Decoder |
       |    -----------
       |        |
       |      Output
       |    probability    --->  Generated data
       |        |
       ---> Log Likelihood ---> -(reconstruction loss)

    Note that the reconstruction loss is not used when the model training ends. It serves only the purpose to
    define a measure of loss which is optimised.
    """
    def __init__(self, latent_dim, data_dim, network_architecture='synthetic', name=None):
        """
        Args:
            latent_dim: int, the flattened dimensionality of the latent space
            data_dim: int, the flattened dimensionality of the output space (data space)
            network_architecture: str, the architecture name for the body of the StandardDecoder model
            name: str, identifier of the model
        """
        super(StandardDecoder, self).__init__(latent_dim=latent_dim, data_dim=data_dim,
                                              network_architecture=network_architecture,
                                              name=name or 'Standard Decoder')

        generator_body = get_network_by_name['decoder'][network_architecture](self.latent_input, name_prefix=self.name)

        # NOTE: all decoder layers have names prefixed by `dec`.
        # This is essential for the partial model freezing during training.
        sampler_params = Dense(self.data_dim, activation='sigmoid',
                               name=self.name + 'dec_sampler_params')(generator_body)

        # a probability clipping is necessary for the Bernoulli `log_prob` property produces NaNs in the border cases.
        sampler_params = Lambda(lambda x: 1e-6 + (1 - 2e-6) * x,
                                name=self.name + 'dec_probs_clipper')(sampler_params)

        def bernoulli_log_probs(args):
            from tensorflow.contrib.distributions import Bernoulli
            mu, x = args
            log_px = Bernoulli(probs=mu, name=self.name + 'dec_bernoulli').log_prob(x)
            return log_px

        log_probs = Lambda(bernoulli_log_probs, name=self.name + 'dec_bernoulli_logprob')([sampler_params,
                                                                                self.data_input])

        self.generator = Model(inputs=self.latent_input, outputs=sampler_params, name=self.name + 'dec_sampling')
        self.ll_estimator = Model(inputs=[self.data_input, self.latent_input], outputs=log_probs,
                                  name=self.name + 'dec_trainable')

    def __call__(self, *args, **kwargs):
        """
        Make the StandardDecoder model callable on lists of Input layers or tensors.

        Args:
            *args: a list of input layers or tensors or numpy arrays, or a single input layer, tensor or numpy array.
        Keyword Args:
            is_learning: bool, whether the model is used for training or data generation. The output is either
                the reconstruction log likelihood or the output probabilities in the data space respectively.

        Returns:
            A StandardDecoder model in `training` or `data generation` mode.
        """
        is_learninig = kwargs.get('is_learning', True)
        if is_learninig:
            return self.ll_estimator(args[0])
        else:
            return self.generator(args[0])

class ConjointDecoder(object):
    """
    A ConjointDecoder model takes multiple latent dimensions and from each generates a data output. There is also a
    shared latent input which is used by all decoders:

               Latent_1 -- Latent_2 -- Latent_shared <-- concatenated
                         /              \
        Latent_1-Latent_shared     Latent_2-Latent_shared
                  |                         |
             -------------             -------------
             | Decoder_1 |             | Decoder_2 |
             -------------             -------------
                  |                         |
               Output_1                  Output_2

    For more details about the loss computation, see the StandardDecoder class.
    """

    def __init__(self, latent_dims, data_dims, network_architecture='synthetic'):
        """
        Args:
            latent_dims: tuple, the flattened dimensions of the private latent spaces and the shared latent space
            data_dims: int, the flattened dimensions of the output spaces (data spaces)
            network_architecture: str, the architecture name for the body of all the decoders
        """
        assert len(latent_dims) == len(data_dims) + 1, \
            "Expected too receive {} private latent spaces and one shared for {} data inputs " \
            "but got {} instead.".format(len(data_dims) + 1, len(data_dims), len(latent_dims))

        name = "Conjoint Decoder"
        logger.info("Initialising {} model with {}-dimensional outputs "
                    "and {}-dimensional latent inputs.".format(name, data_dims, latent_dims))

        def bernoulli_log_probs(args):
            from tensorflow.contrib.distributions import Bernoulli
            mu, x = args
            log_px = Bernoulli(probs=mu, name='dec_bernoulli').log_prob(x)
            return log_px

        data_inputs = [Input(shape=(d,), name='dec_data_input_{}'.format(i)) for i, d in enumerate(data_dims)]
        latent_input = Input(shape=(sum(latent_dims),), name='dec_latent_input')

        shared_latent_factors = Lambda(slice_vector, arguments={'start': -latent_dims[-1], 'stop': None},
                                       name='dec_slice_shared_lat')(latent_input)
        sampling_outputs, log_probs = [], []
        stop_id = 0
        for i in range(len(data_dims)):
            start_id = stop_id
            stop_id += latent_dims[i]
            latent_i = Lambda(slice_vector, arguments={'start': start_id, 'stop': stop_id},
                              name='dec_slice_{}'.format(i))(latent_input)
            latent_i = Concatenate(axis=-1, name='dec_merged_latent_{}'.format(i))([latent_i, shared_latent_factors])
            generator_body = get_network_by_name['conjoint_decoder'][network_architecture](latent_i,
                                                                                'dec_conj_{}'.format(i))
            sampler_params = Dense(data_dims[i], activation='sigmoid',
                                   name='dec_sampler_params_{}'.format(i))(generator_body)
            # probability clipping is necessary for the Bernoulli `log_prob` property produces NaNs in the limit cases
            sampler_params = Lambda(lambda x: 1e-6 + (1 - 2e-6) * x,
                                    name='dec_probs_clipper_{}'.format(i))(sampler_params)
            log_prob = Lambda(bernoulli_log_probs,
                              name='dec_bernoulli_logprob_{}'.format(i))([sampler_params, data_inputs[i]])
            sampling_outputs.append(sampler_params)
            log_probs.append(log_prob)

        log_probs = Concatenate(axis=-1, name='dec_conc_log_probs')(log_probs)

        self.generator = Model(inputs=latent_input, outputs=sampling_outputs, name='dec_sampling')
        self.ll_estimator = Model(inputs=data_inputs + [latent_input], outputs=log_probs, name='dec_trainable')

    def __call__(self, *args, **kwargs):
        """
        Make the StandardDecoder model callable on lists of Input layers or tensors.

        Args:
            *args: a list of input layers or tensors or numpy arrays, or a single input layer, tensor or numpy array.
        Keyword Args:
            is_learning: bool, whether the model is used for training or data generation. The output is either
                the reconstruction log likelihood or the output probabilities in the data space respectively.

        Returns:
            A StandardDecoder model in `training` or `data generation` mode.
        """
        is_learninig = kwargs.get('is_learning', True)
        if is_learninig:
            return self.ll_estimator(args[0])
        else:
            return self.generator(args[0])


text:
package it.gabrieletondi.soliddoubles;

public interface UseCaseRequest {
}


text:
'use strict';

var ActionConstants = require('../constants/ActionConstants');
var Dispatcher = require('../dispatcher/Dispatcher');
var {Store} = require('flux/utils');

var invariant = require('react/lib/invariant');

class CurrentUserStore extends Store {
  constructor(dispatcher) {
    super(dispatcher);
    this._currentUser = null;
    this._isBootstrapped = false;
  }

  getCurrentUser() {
    this._assertBootstrapped();
    return this._currentUser;
  }

  getFinalized() {
    this._assertBootstrapped();
    return this._currentUser.school.assignments_finalized;
  }

  addListener(callback) {
    this._assertBootstrapped();
    return super.addListener(callback);
  }

  __onDispatch(action) {
    switch (action.actionType) {
      case ActionConstants.BOOTSTRAP:
        this._bootstrap();
        break;
      case ActionConstants.LOGIN:
        this._currentUser = action.user;
        break;
      case ActionConstants.LOGOUT:
        this._currentUser = {};
        break;
      case ActionConstants.UPDATE_SCHOOL:
        this._currentUser.school = action.school;
        break;
      default:
        return;
    }

    this.__emitChange();
  }

  _bootstrap() {
    invariant(
      !this._isBootstrapped,
      'CurrentUserStore can only be bootstrapped once.'
    );
    invariant(
      global.currentUser !== undefined,
      'currentUser must be defined to bootstrap CurrentUserStore.'
    );

    this._currentUser = global.currentUser;
    delete global.currentUser;
    this._isBootstrapped = true;
  }

  _assertBootstrapped() {
    invariant(
      this._isBootstrapped,
      'CurrentUserStore must be bootstrapped before being used.'
    );
  }
}

module.exports = new CurrentUserStore(Dispatcher);


text:
import Vue from 'vue';

import dropdownValueComponent from '~/vue_shared/components/sidebar/labels_select/dropdown_value.vue';

import mountComponent from 'spec/helpers/vue_mount_component_helper';

import { mockConfig, mockLabels } from './mock_data';

const createComponent = (
  labels = mockLabels,
  labelFilterBasePath = mockConfig.labelFilterBasePath,
) => {
  const Component = Vue.extend(dropdownValueComponent);

  return mountComponent(Component, {
    labels,
    labelFilterBasePath,
  });
};

describe('DropdownValueComponent', () => {
  let vm;

  beforeEach(() => {
    vm = createComponent();
  });

  afterEach(() => {
    vm.$destroy();
  });

  describe('computed', () => {
    describe('isEmpty', () => {
      it('returns true if `labels` prop is empty', () => {
        const vmEmptyLabels = createComponent([]);

        expect(vmEmptyLabels.isEmpty).toBe(true);
        vmEmptyLabels.$destroy();
      });

      it('returns false if `labels` prop is empty', () => {
        expect(vm.isEmpty).toBe(false);
      });
    });
  });

  describe('methods', () => {
    describe('labelFilterUrl', () => {
      it('returns URL string starting with labelFilterBasePath and encoded label.title', () => {
        expect(
          vm.labelFilterUrl({
            title: 'Foo bar',
          }),
        ).toBe('/gitlab-org/my-project/issues?label_name[]=Foo%20bar');
      });
    });

    describe('labelStyle', () => {
      it('returns object with `color` & `backgroundColor` properties from label.textColor & label.color', () => {
        const label = {
          textColor: '#FFFFFF',
          color: '#BADA55',
        };
        const styleObj = vm.labelStyle(label);

        expect(styleObj.color).toBe(label.textColor);
        expect(styleObj.backgroundColor).toBe(label.color);
      });
    });
  });

  describe('template', () => {
    it('renders component container element with classes `hide-collapsed value issuable-show-labels`', () => {
      expect(vm.$el.classList.contains('hide-collapsed', 'value', 'issuable-show-labels')).toBe(
        true,
      );
    });

    it('render slot content inside component when `labels` prop is empty', () => {
      const vmEmptyLabels = createComponent([]);

      expect(vmEmptyLabels.$el.querySelector('.text-secondary').innerText.trim()).toBe(
        mockConfig.emptyValueText,
      );
      vmEmptyLabels.$destroy();
    });

    it('renders label element with filter URL', () => {
      expect(vm.$el.querySelector('a').getAttribute('href')).toBe(
        '/gitlab-org/my-project/issues?label_name[]=Foo%20Label',
      );
    });

    it('renders label element with tooltip and styles based on label details', () => {
      const labelEl = vm.$el.querySelector('a span.badge.color-label');

      expect(labelEl).not.toBeNull();
      expect(labelEl.dataset.placement).toBe('bottom');
      expect(labelEl.dataset.container).toBe('body');
      expect(labelEl.dataset.originalTitle).toBe(mockLabels[0].description);
      expect(labelEl.getAttribute('style')).toBe('background-color: rgb(186, 218, 85);');
      expect(labelEl.innerText.trim()).toBe(mockLabels[0].title);
    });
  });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<comment version="3.0">
  <caption/>
  <note>Small businesses still abound and most of them begin operations with manual accounting systems and convert to computerized systems as business grows. To understand what computerized accounting systems do, one must understand how manual accounting systems work.</note>
  <place/>
  <categories/>
</comment>


text:
namespace Microsoft.Azure.Management.Monitor.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Criterion to filter metrics.
    /// </summary>
    [Newtonsoft.Json.JsonObject("StaticThresholdCriterion")]
    public partial class MetricCriteria : MultiMetricCriteria
    {
        /// <summary>
        /// Initializes a new instance of the MetricCriteria class.
        /// </summary>
        public MetricCriteria()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the MetricCriteria class.
        /// </summary>
        /// <param name="name">Name of the criteria.</param>
        /// <param name="metricName">Name of the metric.</param>
        /// <param name="timeAggregation">the criteria time aggregation
        /// types.</param>
        /// <param name="operatorProperty">the criteria operator. Possible
        /// values include: 'Equals', 'NotEquals', 'GreaterThan',
        /// 'GreaterThanOrEqual', 'LessThan', 'LessThanOrEqual'</param>
        /// <param name="threshold">the criteria threshold value that activates
        /// the alert.</param>
        /// <param name="additionalProperties">Unmatched properties from the
        /// message are deserialized this collection</param>
        /// <param name="metricNamespace">Namespace of the metric.</param>
        /// <param name="dimensions">List of dimension conditions.</param>
        public MetricCriteria(string name, string metricName, object timeAggregation, string operatorProperty, double threshold, IDictionary<string, object> additionalProperties = default(IDictionary<string, object>), string metricNamespace = default(string), IList<MetricDimension> dimensions = default(IList<MetricDimension>))
            : base(name, metricName, timeAggregation, additionalProperties, metricNamespace, dimensions)
        {
            OperatorProperty = operatorProperty;
            Threshold = threshold;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the criteria operator. Possible values include:
        /// 'Equals', 'NotEquals', 'GreaterThan', 'GreaterThanOrEqual',
        /// 'LessThan', 'LessThanOrEqual'
        /// </summary>
        [JsonProperty(PropertyName = "operator")]
        public string OperatorProperty { get; set; }

        /// <summary>
        /// Gets or sets the criteria threshold value that activates the alert.
        /// </summary>
        [JsonProperty(PropertyName = "threshold")]
        public double Threshold { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public override void Validate()
        {
            base.Validate();
            if (OperatorProperty == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "OperatorProperty");
            }
        }
    }
}


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

class Product extends CI_Controller {

	function __construct(){
	parent::__construct();
	$this->load->model('m_product');
	$this->load->helper('url');

	if (isset($_SESSION['email_sess']) == 0) {
		redirect('login');
	}

	}
	public function header(){
		$cat['cat']=$this->m_product->read_category()->result();
		$this->load->view('header',$cat);
	}

	public function index()
	{
		$email = $_SESSION['email_sess'];
		$data['product']=$this->m_product->getProduct($email);
		$data['count']=$this->m_product->getCountProduct($email);
		$data['seller'] = $this->m_product->getSeller($email);
		$this->header();
		$this->load->view('product_all', $data);
		$this->load->view('footer', $data);
	}
	public function pilih_cat()
	{
		$id=$this->input->get('id');
		$data['data']=$this->m_product->cari_cat($id);
		$this->header();
		$this->load->view('product_search', $data);
		$this->load->view('footer', $data);
	}
	public function search_prod()
	{
		$id=$this->input->post('name');
		$data['data']=$this->m_product->cari_prod($id);
		$this->header();
		$this->load->view('product_search', $data);
		$this->load->view('footer', $data);
	}
	public function suggest_prod(){
		$kode = $_GET['term'];
        $query = $this->m_product->suggest_prod($kode);
        $searchData=array();
        foreach ($query as $key) {
                $searchData[] = array('id'=>$key->PROD_ID,'label'=>$key->PROD_NAME,'value'=>$key->PROD_NAME);
        }
        echo json_encode($searchData);
	}
	function add_product(){
		$email = $_SESSION['email_sess'];
		$data['seller'] = $this->m_product->getSeller($email);
		$data['category'] = $this->m_product->getCategory();
		$this->header();
		$this->load->view('product', $data);
		$this->load->view('footer');
	}
	function d_product(){
		$this->header();
		$this->load->view('product_details');
		$this->load->view('footer');
	}
	function product_details($id){
		$where = array('PROD_ID' => $id);
		$data['product'] = $this->m_product->product_details($where,'tb_product')->result();
		$this->header();
		$this->load->view('product_details', $data);
		$this->load->view('footer', $data);
	}
	function act_add(){
		$q = $this->db->query("SELECT MAX(RIGHT(prod_id,3)) AS idmax FROM tb_product");
			$kd = ""; //kode awal
			if($q->num_rows()>0){ //jika data ada
				foreach($q->result() as $k){
					$tmp = ((int)$k->idmax)+1; //string kode diset ke integer dan ditambahkan 1 dari kode terakhir
					$kd = sprintf('%03s', $tmp); //kode ambil 3 karakter terakhir
				}
			}else{ //jika data kosong diset ke kode awal
				$kd = "001";
			}
			$kar = "PROD"; //karakter depan kodenya
		$this->load->library('upload');
        $nmfile = "file_".time(); //nama file saya beri nama langsung dan diikuti fungsi time
        $config['upload_path'] = './assets/product/'; //path folder
        $config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; //type yang dapat diakses bisa anda sesuaikan
        $config['max_size'] = '5024'; //maksimum besar file 2M
        $config['max_width']  = '2000'; //lebar maksimum 1288 px
        $config['max_height']  = '2000'; //tinggi maksimu 768 px
        $config['file_name'] = $nmfile; //nama yang terupload nantinya

        $this->upload->initialize($config);

        if($_FILES['gambar']['name'])
        {
            if ($this->upload->do_upload('gambar'))
            {
                $gbr = $this->upload->data();
                $data = array(
					'prod_id' => $kar.$kd,
                  	'sell_id' => $this->input->post('idseller'),
					'cat_id' =>$this->input->post('kategori'),
					'prod_name' =>$this->input->post('nama'),
					'prod_stock' =>$this->input->post('stok'),
					'prod_description' => $this->input->post('deskripsi'),
					'prod_image' =>$gbr['file_name'],
					'prod_price' => $this->input->post('harga'),
					'prod_condition' => $this->input->post('kondisi'),
					'prod_weight' => $this->input->post('berat'),
					'prod_other_desc' => $this->input->post('DeskripsiTambah')

                );

                $this->m_product->tambah($data); //akses model untuk menyimpan ke database

                if(isset($_POST['submit1'])){
				redirect(base_url('index.php/product/add_product'));
				}else{
				redirect(base_url('index.php/product')); //jika berhasil maka akan ditampilkan view vupload
				}

            }else{

                echo "gagal"; //jika gagal maka akan ditampilkan form upload
            }
        }
	}

	function delete($id){
		$where = array('PROD_ID' => $id);
		$path= './assets/product/';
		$data = $this->m_product->get_data($where);
		@unlink($path.$data->PROD_IMAGE);

		$this->m_product->hapus($where,'tb_product');
		redirect(base_url('index.php/product'));

	}
	function EditProduct($id){
		$email = $_SESSION['email_sess'];
		$where = array(
			'PROD_ID' => $id
		);
		$data['seller'] = $this->m_product->getSeller($email);
		$data['category'] = $this->m_product->getCategory();
		$data['product'] = $this->m_product->edit_data('tb_product',$id);
		$this->header();
		$this->load->view('EditProduct',$data);
		$this->load->view('footer',$data);
	}
	function UpdateProduct(){

		$this->load->library('upload');
        $nmfile = "file_".time(); //nama file saya beri nama langsung dan diikuti fungsi time
        $config['upload_path'] = './assets/product/'; //path folder
        $config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; //type yang dapat diakses bisa anda sesuaikan
        $config['max_size'] = '5024'; //maksimum besar file 2M
        $config['max_width']  = '2000'; //lebar maksimum 1288 px
        $config['max_height']  = '2000'; //tinggi maksimu 768 px
        $config['file_name'] = $nmfile; //nama yang terupload nantinya

        $this->upload->initialize($config);
        $image = $this->input->post('lama');
        $path = './assets/product/';

		if ($_FILES['gambar']['name']) {
			if ($this->upload->do_upload('gambar'))
            {
                $gbr = $this->upload->data();
               $data = array(
                  	'prod_name' =>$this->input->post('nama'),
					'prod_stock' =>$this->input->post('stok'),
					'prod_description' => $this->input->post('deskripsi'),
					'prod_price' => $this->input->post('harga'),
					'prod_condition' => $this->input->post('kondisi'),
					'prod_weight' => $this->input->post('berat'),
					'prod_other_desc' => $this->input->post('DeskripsiTambah'),
					'prod_image' => $gbr['file_name']
			);
				$where = array('PROD_ID'=> $this->input->post('prod_id'));

				@unlink($path.$image);

				$this->m_product->UpdateProduct($where,$data,'tb_product');

                redirect('product'); //jika berhasil maka akan ditampilkan view vupload
            }else{

                echo 'gagal';
            }
		} else {
			$data = array(
                  	'prod_name' =>$this->input->post('nama'),
					'prod_stock' =>$this->input->post('stok'),
					'prod_description' => $this->input->post('deskripsi'),
					'prod_price' => $this->input->post('harga'),
					'prod_condition' => $this->input->post('kondisi'),
					'prod_weight' => $this->input->post('berat'),
					'prod_other_desc' => $this->input->post('DeskripsiTambah')
			);
			$where = array('PROD_ID'=> $this->input->post('prod_id'));
			$this->m_product->UpdateProduct($where, $data, 'tb_product');
			redirect('product');
		}
	}

}


text:
name = 'tinymce'
authors = 'Joost Cassee, Aljosa Mohorovic'
version = '1.5.1b4'
release = version


text:
import React from 'react';
import { TouchableOpacity } from 'react-native';
declare type TouchableProps = {
    onPress?: (...args: any[]) => any;
};
declare type AdTriggerViewProps<P> = {
    renderInteractiveComponent?: (props: P) => React.ReactElement<P>;
} & P;
export default class AdTriggerView<P extends TouchableProps = React.ComponentProps<typeof TouchableOpacity>> extends React.Component<AdTriggerViewProps<P>> {
    _trigger: React.Component<P> | null;
    render(): JSX.Element;
    _getForwardedProps(): P;
    _renderDefaultInteractiveComponent(props: P): React.ReactElement<P>;
}
export {};
//# sourceMappingURL=AdTriggerView.d.ts.map


text:
/*
 * Author: Kjell Winblad
 */

#ifndef YCF_AST_H
#define YCF_AST_H

#include "ycf_utils.h"
#include "ycf_symbol.h"
#include "ycf_string.h"
#include "ycf_node.h"

typedef struct {
  bool success;
  ycf_symbol* next_symbol;
  ycf_node* result;
} ycf_parse_result;

/* Functions for strings */

void string_item_list_print(ycf_string_item_list n);

/* Functions for symbol lists */

int ycf_symbol_list_get_item_position(ycf_symbol_list* list, ycf_symbol* node);

ycf_symbol* ycf_symbol_shallow_copy(ycf_symbol* n);
ycf_symbol* ycf_symbol_list_get_item_at_position(ycf_symbol_list* list, int pos);

void ycf_symbol_list_append(ycf_symbol_list* list, ycf_symbol* node);
void ycf_symbol_list_prepend(ycf_symbol_list* list, ycf_symbol* node);
void ycf_symbol_list_insert_before(ycf_symbol_list* list, ycf_symbol* before_this, ycf_symbol* to_insert);
void ycf_symbol_list_insert_after(ycf_symbol_list* list, ycf_symbol* after_this, ycf_symbol* to_insert);
void ycf_symbol_list_remove(ycf_symbol_list* list, ycf_symbol* to_remove);
void ycf_symbol_list_replace(ycf_symbol_list* list, ycf_symbol* to_replace, ycf_symbol* replace_with);
void ycf_symbol_list_concat(ycf_symbol_list* list1, ycf_symbol_list* list2);

ycf_symbol_list ycf_symbol_list_empty();
ycf_symbol_list ycf_symbol_list_shallow_copy(ycf_symbol_list n);
ycf_symbol_list ycf_symbol_list_copy_append(ycf_symbol_list list, ycf_symbol* node);
ycf_symbol_list ycf_symbol_list_copy_prepend(ycf_symbol_list list, ycf_symbol* node);
ycf_symbol_list ycf_symbol_list_copy_insert_before(ycf_symbol_list list, ycf_symbol* before_this, ycf_symbol* to_insert);
ycf_symbol_list ycf_symbol_list_copy_insert_after(ycf_symbol_list list, ycf_symbol* after_this, ycf_symbol* to_insert);
ycf_symbol_list ycf_symbol_list_copy_remove(ycf_symbol_list list, ycf_symbol* to_remove);
ycf_symbol_list ycf_symbol_list_copy_replace(ycf_symbol_list list, ycf_symbol* to_replace, ycf_symbol* replace_with);
ycf_symbol_list ycf_symbol_list_copy_concat(ycf_symbol_list list1, ycf_symbol_list list2);

/* Functions for parsing text to AST */

ycf_node* ycf_node_scope_new(ycf_symbol* start,
                             ycf_node_list declaration_nodes,
                             ycf_node_list other_nodes,
                             ycf_symbol* end);
ycf_parse_result parse_expression(ycf_symbol* symbols);

void print_abstract_syntax_tree(ycf_node* node);
void print_node_code_paran_expression(ycf_node_parentheses_expression e, ycf_string_printable_buffer* b);
void print_node_code_expression(ycf_node_expression e, ycf_string_printable_buffer* b);

void ast_add_yield_code_generated_define(ycf_node* source_out_tree/*Will be changed*/, bool debug_mode);
void print_symbol_list(ycf_symbol_list* l, ycf_string_printable_buffer* b);

/* Abstract syntax tree functions */

ycf_node* ycf_node_find_function(ycf_node* c_file_node, char* fun_name);
ycf_node_list ycf_node_get_all_definitions_in_function(ycf_node_function* f);

ycf_node* ast_get_ast_with_yieldified_function(ycf_node* source_tree,
                                               ycf_node* header_tree, /*Will be changed*/
                                               char* yielding_function_name,
                                               ycf_string_item_list* all_yielding_function_names,
                                               bool auto_yield,
                                               bool recusive_auto_yield,
                                               bool debug_mode,
                                               bool only_yielding_funs,
                                               ycf_node** only_yielding_funs_tree,
                                               bool static_aux_funs);

void print_abstract_syntax_tree(ycf_node* node);
void print_node_code_expression(ycf_node_expression e, ycf_string_printable_buffer* b);
void print_node_list_code(ycf_node* n, ycf_string_printable_buffer* b);
void ast_add_yield_code_generated_define(ycf_node* source_out_tree, bool debug_mode);

#endif


text:
using System;
using System.Collections;
using System.Collections.Generic;

namespace Windows.Forms
{
    public enum Parameters
    {
        A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
    }
    public class MathParser
    {
        private Dictionary<Parameters, decimal> _Parameters = new Dictionary<Parameters, decimal>();
        private List<String> OperationOrder = new List<string>();

        public Dictionary<Parameters, decimal> Parameters
        {
            get { return _Parameters; }
            set { _Parameters = value; }
        }

        public MathParser()
        {
            OperationOrder.Add("/");
            OperationOrder.Add("*");
            OperationOrder.Add("-");
            OperationOrder.Add("+");
        }
        public decimal Calculate(string Formula)
        {
            try
            {
                var arr = Formula.Split("/+-*()".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                foreach (var de in _Parameters)
                {
                    foreach (var s in arr)
                    {
                        if (s != de.Key.ToString() && s.EndsWith(de.Key.ToString()))
                        {
                            Formula = Formula.Replace(s, (Convert.ToDecimal(s.Replace(de.Key.ToString(), "")) * de.Value).ToString());
                        }
                    }
                    Formula = Formula.Replace(de.Key.ToString(), de.Value.ToString());
                }
                while (Formula.LastIndexOf("(") > -1)
                {
                    var lastOpenPhrantesisIndex = Formula.LastIndexOf("(");
                    var firstClosePhrantesisIndexAfterLastOpened = Formula.IndexOf(")", lastOpenPhrantesisIndex);
                    var result = ProcessOperation(Formula.Substring(lastOpenPhrantesisIndex + 1, firstClosePhrantesisIndexAfterLastOpened - lastOpenPhrantesisIndex - 1));
                    var AppendAsterix = false;
                    if (lastOpenPhrantesisIndex > 0)
                    {
                        if (Formula.Substring(lastOpenPhrantesisIndex - 1, 1) != "(" && !OperationOrder.Contains(Formula.Substring(lastOpenPhrantesisIndex - 1, 1)))
                        {
                            AppendAsterix = true;
                        }
                    }

                    Formula = Formula.Substring(0, lastOpenPhrantesisIndex) + (AppendAsterix ? "*" : "") + result.ToString() + Formula.Substring(firstClosePhrantesisIndexAfterLastOpened + 1);

                }
                return ProcessOperation(Formula);
            }
            catch (Exception ex)
            {
                throw new Exception("Error Occured While Calculating. Check Syntax", ex);
            }
        }

        private decimal ProcessOperation(string operation)
        {
            var arr = new ArrayList();
            var s = "";
            for (var i = 0; i < operation.Length; i++)
            {
                var currentCharacter = operation.Substring(i, 1);
                if (OperationOrder.IndexOf(currentCharacter) > -1)
                {
                    if (s != "")
                    {
                        arr.Add(s);
                    }
                    arr.Add(currentCharacter);
                    s = "";
                }
                else
                {
                    s += currentCharacter;
                }
            }
            arr.Add(s);
            s = "";
            foreach (var op in OperationOrder)
            {
                while (arr.IndexOf(op) > -1)
                {
                    var operatorIndex = arr.IndexOf(op);
                    var digitBeforeOperator = Convert.ToDecimal(arr[operatorIndex - 1]);
                    decimal digitAfterOperator = 0;
                    if (arr[operatorIndex + 1].ToString() == "-")
                    {
                        arr.RemoveAt(operatorIndex + 1);
                        digitAfterOperator = Convert.ToDecimal(arr[operatorIndex + 1]) * -1;
                    }
                    else
                    {
                        digitAfterOperator = Convert.ToDecimal(arr[operatorIndex + 1]);
                    }
                    arr[operatorIndex] = CalculateByOperator(digitBeforeOperator, digitAfterOperator, op);
                    arr.RemoveAt(operatorIndex - 1);
                    arr.RemoveAt(operatorIndex);
                }
            }
            return Convert.ToDecimal(arr[0]);
        }
        private decimal CalculateByOperator(decimal number1, decimal number2, string op)
        {
            if (op == "/")
            {
                return number1 / number2;
            }
            else if (op == "*")
            {
                return number1 * number2;
            }
            else if (op == "-")
            {
                return number1 - number2;
            }
            else if (op == "+")
            {
                return number1 + number2;
            }
            else
            {
                return 0;
            }
        }
    }
}