text:
import tls from 'tls';
import crypto from 'crypto';
import { EventEmitter } from 'events';

import {} from './buffertools';
import { Packet, TYPE, HEADER_LENGTH as packetHeaderLength } from './packet';
import StreamParser from './stream-parser';

class ReadablePacketStream extends StreamParser {
  *parser() {
    for (;;) {
      const header = yield this.readBuffer(packetHeaderLength);
      const length = header.readUInt16BE(2);
      const data = yield this.readBuffer(length - packetHeaderLength);

      this.push(new Packet(Buffer.concat([header, data])));
    }
  }
}

export default class MessageIO extends EventEmitter {
  constructor(socket, _packetSize, debug) {
    super();

    this.socket = socket;
    this._packetSize = _packetSize;
    this.debug = debug;
    this.sendPacket = this.sendPacket.bind(this);

    this.packetStream = new ReadablePacketStream();
    this.packetStream.on('data', (packet) => {
      this.logPacket('Received', packet);
      this.emit('data', packet.data());
      if (packet.isLast()) {
        this.emit('message');
      }
    });

    this.socket.pipe(this.packetStream);
    this.packetDataSize = this._packetSize - packetHeaderLength;
  }

  packetSize(packetSize) {
    if (arguments.length > 0) {
      this.debug.log("Packet size changed from " + this._packetSize + " to " + packetSize);
      this._packetSize = packetSize;
      this.packetDataSize = this._packetSize - packetHeaderLength;
    }
    return this._packetSize;
  }

  startTls(credentialsDetails) {
    const credentials = tls.createSecureContext ? tls.createSecureContext(credentialsDetails) : crypto.createCredentials(credentialsDetails);

    this.securePair = tls.createSecurePair(credentials);
    this.tlsNegotiationComplete = false;

    this.securePair.on('secure', () => {
      const cipher = this.securePair.cleartext.getCipher();
      this.debug.log("TLS negotiated (" + cipher.name + ", " + cipher.version + ")");
      this.emit('secure', this.securePair.cleartext);
      this.encryptAllFutureTraffic();
    });

    this.securePair.encrypted.on('data', (data) => {
      this.sendMessage(TYPE.PRELOGIN, data);
    });

    // On Node >= 0.12, the encrypted stream automatically starts spewing out
    // data once we attach a `data` listener. But on Node <= 0.10.x, this is not
    // the case. We need to kick the cleartext stream once to get the
    // encrypted end of the secure pair to emit the TLS handshake data.
    this.securePair.cleartext.write('');
  }

  encryptAllFutureTraffic() {
    this.socket.unpipe(this.packetStream);
    this.securePair.encrypted.removeAllListeners('data');
    this.socket.pipe(this.securePair.encrypted);
    this.securePair.encrypted.pipe(this.socket);
    this.securePair.cleartext.pipe(this.packetStream);
    this.tlsNegotiationComplete = true;
  }

  tlsHandshakeData(data) {
    this.securePair.encrypted.write(data);
  }

  // TODO listen for 'drain' event when socket.write returns false.
  // TODO implement incomplete request cancelation (2.2.1.6)
  sendMessage(packetType, data, resetConnection) {
    let numberOfPackets;
    if (data) {
      numberOfPackets = (Math.floor((data.length - 1) / this.packetDataSize)) + 1;
    } else {
      numberOfPackets = 1;
      data = new Buffer(0);
    }

    for (let packetNumber = 0; packetNumber < numberOfPackets; packetNumber++) {
      const payloadStart = packetNumber * this.packetDataSize;

      let payloadEnd;
      if (packetNumber < numberOfPackets - 1) {
        payloadEnd = payloadStart + this.packetDataSize;
      } else {
        payloadEnd = data.length;
      }

      const packetPayload = data.slice(payloadStart, payloadEnd);

      const packet = new Packet(packetType);
      packet.last(packetNumber === numberOfPackets - 1);
      packet.resetConnection(resetConnection);
      packet.packetId(packetNumber + 1);
      packet.addData(packetPayload);
      this.sendPacket(packet);
    }
  }

  sendPacket(packet) {
    this.logPacket('Sent', packet);
    if (this.securePair && this.tlsNegotiationComplete) {
      this.securePair.cleartext.write(packet.buffer);
    } else {
      this.socket.write(packet.buffer);
    }
  }

  logPacket(direction, packet) {
    this.debug.packet(direction, packet);
    return this.debug.data(packet);
  }
}


text:
function sortView(document, cols, list) {
	// The last portion of the id (. delimited) must be the name of the field in
	// the objects in our list.
	var sortField = null;
	var ascending = null;
	for (var i in cols) {
		var col = cols[i];
		if (document.getElementById(col) != null) {
			log("col=["+col+"]");
			var direction = document.getElementById(col).getAttribute("sortDirection");
		} else {
			log("col=["+col+"] (skipped)");
		}

		if (direction && direction != "natural") {
			ascending = (direction == "ascending");
			sortField = col.split('.').pop();
			break;
		}
	}

	if (sortField != null) {
		list.sort(function(a,b) {
	 var aVal = eval("a."+sortField+".toString().toLowerCase()");
	 var bVal = eval("b."+sortField+".toString().toLowerCase()");
	 if (aVal < bVal) return ascending?-1:1;
	 if (aVal > bVal) return ascending?1:-1;
	 return 0;
		});
	}
}

function cycleHeader(col, document, columnIdList, list) {
	var csd = col.element.getAttribute("sortDirection");
	var sortDirection = (csd == "ascending" || csd == "natural") ? "descending" : "ascending";
	for (var i = 0; i < col.columns.count; i++) {
		col.columns.getColumnAt(i).element.setAttribute("sortDirection", "natural");
	}
	col.element.setAttribute("sortDirection", sortDirection);
	sortView(document, columnIdList, list);
}

function getNodeValueByName(parent, nodeName) {
	var node = parent.getElementsByTagName(nodeName)[0];
	if (node == null) return "";
	return node.firstChild ? node.firstChild.nodeValue : "";
}

function methodPointer(obj, method) {
	 var wrap = function(x) { obj.method(x); }

}

function trim(s) {
	return s.replace(/^\s*/, '').replace(/\s*$/, '');
}

function getProperty(name, defValue) {
	try {
		return document.getElementById('ec2ui.properties.bundle').getString(name);
	} catch(e) {
		return defValue;
	}
}

function log(msg) {
	try {
		if (ec2ui_prefs.isDebugEnabled()) {
			var consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
			consoleService.logStringMessage("[ec2ui] " + msg);
		}
	} catch (e) {
	}
}

function copyToClipboard(text) {
   var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
   str.data = text;

   var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
   trans.addDataFlavor("text/unicode");
   trans.setTransferData("text/unicode", str, text.length * 2);

   var clipid = Components.interfaces.nsIClipboard;
   var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
   clip.setData(trans,null,clipid.kGlobalClipboard);
}

// With thanks to http://delete.me.uk/2005/03/iso8601.html
Date.prototype.setISO8601 = function (string) {
   var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" + "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" + "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
   var d = string.match(new RegExp(regexp));
   var offset = 0; var date = new Date(d[1], 0, 1);
   if (d[3]) {
      date.setMonth(d[3] - 1);
   }
   if (d[5]) {
      date.setDate(d[5]);
   }
   if (d[7]) {
      date.setHours(d[7]);
   }
   if (d[8]) {
      date.setMinutes(d[8]);
   }
   if (d[10]) {
      date.setSeconds(d[10]);
   }
   if (d[12]) {
      date.setMilliseconds(Number("0." + d[12]) * 1000);
   }
   if (d[14]) {
      offset = (Number(d[16]) * 60) + Number(d[17]);
      offset *= ((d[15] == '-') ? 1 : -1);
   }
   offset -= date.getTimezoneOffset();
   time = (Number(date) + (offset * 60 * 1000));
   this.setTime(Number(time));
}

redpajama_set_name: RedPajamaGithub


text:
package io.rtr.conduit.amqp.impl;

import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MetricsCollector;
import io.rtr.conduit.amqp.transport.TransportExecutor;

import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier;

public class AMQPConnection {
    private final ConnectionFactory connectionFactory;
    private Connection connection;
    private TransportExecutor executor;
    private final Supplier<TransportExecutor> executorFactory;

    public AMQPConnection(boolean ssl, String host, int port, MetricsCollector metricsCollector) {
        this(new ConnectionFactory(), TransportExecutor::new, ssl, host, port, metricsCollector);
    }

    public AMQPConnection(ConnectionFactory factory, Supplier<TransportExecutor> executorFactory, boolean ssl, String host, int port, MetricsCollector metricsCollector) {
        this.connectionFactory = factory;
        this.executorFactory = executorFactory;
        if (ssl) {
            factory.setSocketFactory(SSLSocketFactory.getDefault());
        }

        factory.setHost(host);
        factory.setPort(port);

        if (metricsCollector != null) {
            factory.setMetricsCollector(metricsCollector);
        }
    }

    public boolean isConnected() {
        return this.connection != null && this.connection.isOpen();
    }

    public synchronized void connect(AMQPConnectionProperties properties) throws IOException, TimeoutException {
        if (isConnected()) {
            return;
        }
        configureConnectionFactory(properties);
        initializeExecutor();
        connection = connectionFactory.newConnection(executor);
    }

    public synchronized void disconnect() throws IOException {
        //! We are going to assume that closing an already closed
        //  connection is considered success.
        if (isConnected()) {
            try {
                connection.close(connectionFactory.getConnectionTimeout());
                connection = null;
            } catch (AlreadyClosedException ignored) {}
        }
        stopListening();
    }

    public Channel createChannel() throws IOException {
        if (!isConnected()) {
            throw new ConduitConnectionStateException("Attempted to create channel whilst disconnected.");
        }
        Channel channel = connection.createChannel();
        channel.basicQos(1);
        return channel;
    }

    public void stopListening() {
        if (executor != null) {
            executor.shutdown();
            executor = null;
        }
    }

    public boolean waitToStopListening(Duration waitFor) throws InterruptedException {
        if (executor != null) {
            return executor.awaitTermination(waitFor.toMillis(), TimeUnit.MILLISECONDS);
        }
        return true;
    }

    private void initializeExecutor() {
        stopListening();
        executor = executorFactory.get();
    }

    private void configureConnectionFactory(AMQPConnectionProperties properties) {
        connectionFactory.setUsername(properties.getUsername());
        connectionFactory.setPassword(properties.getPassword());
        connectionFactory.setVirtualHost(properties.getVirtualHost());
        connectionFactory.setConnectionTimeout(properties.getConnectionTimeout());
        connectionFactory.setRequestedHeartbeat(properties.getHeartbeatInterval());
        connectionFactory.setAutomaticRecoveryEnabled(properties.isAutomaticRecoveryEnabled());
    }

}


text:
class Dummy
  include Permissionable

  permissions run: 1,
              walk: 2,
              sit: 3,
              play: 4,
              eat: 5

  def persisted?
    true
  end

  def initialize(attributes={})
    attributes.each do |attribute,value|
      setter_method = "#{attribute}=".to_sym
      self.send(setter_method, value)
    end
  end

end


text:
#pragma once
#include <aws/glue/Glue_EXPORTS.h>
#include <aws/glue/GlueRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/glue/model/TableInput.h>
#include <utility>

namespace Aws
{
namespace Glue
{
namespace Model
{

  /**
   */
  class AWS_GLUE_API UpdateTableRequest : public GlueRequest
  {
  public:
    UpdateTableRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateTable"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The ID of the Data Catalog where the table resides. If none is provided, the
     * Amazon Web Services account ID is used by default.

     */
    inline const Aws::String& GetCatalogId() const{ return m_catalogId; }

    /**
     *
The ID of the Data Catalog where the table resides. If none is provided, the
     * Amazon Web Services account ID is used by default.

     */
    inline bool CatalogIdHasBeenSet() const { return m_catalogIdHasBeenSet; }

    /**
     *
The ID of the Data Catalog where the table resides. If none is provided, the
     * Amazon Web Services account ID is used by default.

     */
    inline void SetCatalogId(const Aws::String& value) { m_catalogIdHasBeenSet = true; m_catalogId = value; }

    /**
     *
The ID of the Data Catalog where the table resides. If none is provided, the
     * Amazon Web Services account ID is used by default.

     */
    inline void SetCatalogId(Aws::String&& value) { m_catalogIdHasBeenSet = true; m_catalogId = std::move(value); }

    /**
     *
The ID of the Data Catalog where the table resides. If none is provided, the
     * Amazon Web Services account ID is used by default.

     */
    inline void SetCatalogId(const char* value) { m_catalogIdHasBeenSet = true; m_catalogId.assign(value); }

    /**
     *
The ID of the Data Catalog where the table resides. If none is provided, the
     * Amazon Web Services account ID is used by default.

     */
    inline UpdateTableRequest& WithCatalogId(const Aws::String& value) { SetCatalogId(value); return *this;}

    /**
     *
The ID of the Data Catalog where the table resides. If none is provided, the
     * Amazon Web Services account ID is used by default.

     */
    inline UpdateTableRequest& WithCatalogId(Aws::String&& value) { SetCatalogId(std::move(value)); return *this;}

    /**
     *
The ID of the Data Catalog where the table resides. If none is provided, the
     * Amazon Web Services account ID is used by default.

     */
    inline UpdateTableRequest& WithCatalogId(const char* value) { SetCatalogId(value); return *this;}

    /**
     *
The name of the catalog database in which the table resides. For Hive
     * compatibility, this name is entirely lowercase.

     */
    inline const Aws::String& GetDatabaseName() const{ return m_databaseName; }

    /**
     *
The name of the catalog database in which the table resides. For Hive
     * compatibility, this name is entirely lowercase.

     */
    inline bool DatabaseNameHasBeenSet() const { return m_databaseNameHasBeenSet; }

    /**
     *
The name of the catalog database in which the table resides. For Hive
     * compatibility, this name is entirely lowercase.

     */
    inline void SetDatabaseName(const Aws::String& value) { m_databaseNameHasBeenSet = true; m_databaseName = value; }

    /**
     *
The name of the catalog database in which the table resides. For Hive
     * compatibility, this name is entirely lowercase.

     */
    inline void SetDatabaseName(Aws::String&& value) { m_databaseNameHasBeenSet = true; m_databaseName = std::move(value); }

    /**
     *
The name of the catalog database in which the table resides. For Hive
     * compatibility, this name is entirely lowercase.

     */
    inline void SetDatabaseName(const char* value) { m_databaseNameHasBeenSet = true; m_databaseName.assign(value); }

    /**
     *
The name of the catalog database in which the table resides. For Hive
     * compatibility, this name is entirely lowercase.

     */
    inline UpdateTableRequest& WithDatabaseName(const Aws::String& value) { SetDatabaseName(value); return *this;}

    /**
     *
The name of the catalog database in which the table resides. For Hive
     * compatibility, this name is entirely lowercase.

     */
    inline UpdateTableRequest& WithDatabaseName(Aws::String&& value) { SetDatabaseName(std::move(value)); return *this;}

    /**
     *
The name of the catalog database in which the table resides. For Hive
     * compatibility, this name is entirely lowercase.

     */
    inline UpdateTableRequest& WithDatabaseName(const char* value) { SetDatabaseName(value); return *this;}

    /**
     *
An updated TableInput object to define the metadata table in the
     * catalog.

     */
    inline const TableInput& GetTableInput() const{ return m_tableInput; }

    /**
     *
An updated TableInput object to define the metadata table in the
     * catalog.

     */
    inline bool TableInputHasBeenSet() const { return m_tableInputHasBeenSet; }

    /**
     *
An updated TableInput object to define the metadata table in the
     * catalog.

     */
    inline void SetTableInput(const TableInput& value) { m_tableInputHasBeenSet = true; m_tableInput = value; }

    /**
     *
An updated TableInput object to define the metadata table in the
     * catalog.

     */
    inline void SetTableInput(TableInput&& value) { m_tableInputHasBeenSet = true; m_tableInput = std::move(value); }

    /**
     *
An updated TableInput object to define the metadata table in the
     * catalog.

     */
    inline UpdateTableRequest& WithTableInput(const TableInput& value) { SetTableInput(value); return *this;}

    /**
     *
An updated TableInput object to define the metadata table in the
     * catalog.

     */
    inline UpdateTableRequest& WithTableInput(TableInput&& value) { SetTableInput(std::move(value)); return *this;}

    /**
     *
By default, UpdateTable always creates an archived version of
     * the table before updating it. However, if skipArchive is set to
     * true, UpdateTable does not create the archived version.

     */
    inline bool GetSkipArchive() const{ return m_skipArchive; }

    /**
     *
By default, UpdateTable always creates an archived version of
     * the table before updating it. However, if skipArchive is set to
     * true, UpdateTable does not create the archived version.

     */
    inline bool SkipArchiveHasBeenSet() const { return m_skipArchiveHasBeenSet; }

    /**
     *
By default, UpdateTable always creates an archived version of
     * the table before updating it. However, if skipArchive is set to
     * true, UpdateTable does not create the archived version.

     */
    inline void SetSkipArchive(bool value) { m_skipArchiveHasBeenSet = true; m_skipArchive = value; }

    /**
     *
By default, UpdateTable always creates an archived version of
     * the table before updating it. However, if skipArchive is set to
     * true, UpdateTable does not create the archived version.

     */
    inline UpdateTableRequest& WithSkipArchive(bool value) { SetSkipArchive(value); return *this;}

  private:

    Aws::String m_catalogId;
    bool m_catalogIdHasBeenSet;

    Aws::String m_databaseName;
    bool m_databaseNameHasBeenSet;

    TableInput m_tableInput;
    bool m_tableInputHasBeenSet;

    bool m_skipArchive;
    bool m_skipArchiveHasBeenSet;
  };

} // namespace Model
} // namespace Glue
} // namespace Aws


text:
#ifndef DELAYEDSCHEDULER_H
#define DELAYEDSCHEDULER_H

#include <chrono>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <unordered_map>

#include "joynr/BoostIoserviceForwardDecl.h"
#include "joynr/DelayedRunnable.h"
#include "joynr/JoynrExport.h"
#include "joynr/Logger.h"
#include "joynr/PrivateCopyAssign.h"

namespace joynr
{

/**
 * @class DelayedScheduler
 * @brief Using a @ref Timer and @ref BlockingQueue to execute a runnable delayed
 */
class JOYNR_EXPORT DelayedScheduler : public std::enable_shared_from_this<DelayedScheduler>
{
public:
    /*! Handle to reference a @ref Runnable scheduled to work */
    typedef std::uint32_t RunnableHandle;

    /*! Invalid handle */
    static const RunnableHandle _INVALID_RUNNABLE_HANDLE = 0;

    /**
     * @brief Constructor
     * @param onWorkAvailable Callback done if work is available after timer
     *      has expired
     * @param defaultDelayMs Default delay used by @ref schedule
     */
    DelayedScheduler(std::function<void(std::shared_ptr<Runnable>)> onWorkAvailable,
                     boost::asio::io_service& ioService,
                     std::chrono::milliseconds defaultDelayMs = std::chrono::milliseconds::zero());

    /**
     * @brief Destructor
     * @note Be sure to call @ref shutdown and wait for return before
     *      destroying this object
     */
    virtual ~DelayedScheduler();

    /**
     * @brief Schedule a @ref Runnable to be added to execution queue
     * @param runnable Runnable to be added to queue
     * @param delay Number of milliseconds to delay adding the @ref Runnable
     *      to the queue.
     *      If this parameter value is invalid (aka null) its default value will be used.
     * @return Handle referencing the given @ref Runnable in this scheduler. If
     *      @ref INVALID_RUNNABLE_HANDLE is returned, the @ref Runnable either
     *      is directly submitted to run or the @ref DelayedScheduler is already
     *      shutting down.
     */
    virtual RunnableHandle schedule(std::shared_ptr<Runnable> runnable,
                                    std::chrono::milliseconds delay);

    /**
     * @brief Schedule a @ref Runnable to be added to execution queue
     *
     * This method calls @ref schedule with the default delay.
     *
     * @param runnable Runnable to be added to queue
     * @return Handle referencing the given @ref Runnable in this scheduler. If
     *      @ref INVALID_RUNNABLE_HANDLE is returned, the @ref Runnable either
     *      is directly submitted to run or the @ref DelayedScheduler is already
     *      shutting down.
     */
    virtual RunnableHandle schedule(std::shared_ptr<Runnable> runnable);

    /**
     * @brief Try to remove a @ref Runnable while waiting
     * @param runnableHandle Handle given by @ref schedule
     */
    virtual void unschedule(const RunnableHandle runnableHandle);

    /**
     * @brief Does an ordinary shutdown of @ref DelayedScheduler
     * @note Must be called before destructor is called
     */
    virtual void shutdown();

protected:
    /*! Logger */
    ADD_LOGGER(DelayedScheduler)

private:
    /*! @ref DelayedScheduler is not allowed to be copied */
    DISALLOW_COPY_AND_ASSIGN(DelayedScheduler);

private:
    /*! Default delay set by the constructor */
    const std::chrono::milliseconds _defaultDelayMs;

    /*! Callback on timer expired */
    std::function<void(std::shared_ptr<Runnable>)> _onWorkAvailable;

    /*! Flag indicating @ref DelayedScheduler will be stopped */
    bool _stoppingDelayedScheduler;

    std::unordered_map<RunnableHandle, DelayedRunnable> _delayedRunnables;

    /*! Guard to limit write access to @ref delayedRunnables */
    std::mutex _writeLock;

    /*! Next runnable handle which will be returned by ::schedule */
    RunnableHandle _nextRunnableHandle;

    /*! Used for async timers. */
    boost::asio::io_service& _ioService;
};

} // namespace joynr
#endif // DELAYEDSCHEDULER_H


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using Microsoft.Azure.SignalR;
using Newtonsoft.Json;

namespace Microsoft.Azure.WebJobs.Extensions.SignalRService
{
    internal class ServiceEndpointJsonConverter : JsonConverter<ServiceEndpoint>
    {
        private const string FakeAccessKey = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        public override ServiceEndpoint ReadJson(JsonReader reader, Type objectType, ServiceEndpoint existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            return ToEqualServiceEndpoint(serializer.Deserialize<LiteServiceEndpoint>(reader));
        }

        public override void WriteJson(JsonWriter writer, ServiceEndpoint value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, new LiteServiceEndpoint(value));
        }

        private static ServiceEndpoint ToEqualServiceEndpoint(LiteServiceEndpoint e)
        {
            if (e == null)
            {
                return null;
            }

            var connectionString = $"Endpoint={e.Endpoint};AccessKey={FakeAccessKey};Version=1.0;";
            return new ServiceEndpoint(connectionString, e.EndpointType, e.Name);
        }
    }
}


text:
import {ComponentHarness, HarnessPredicate} from '@angular/cdk/testing';
import {MatStepHarness} from './step-harness';
import {
  StepperHarnessFilters,
  StepHarnessFilters,
  StepperOrientation,
} from './step-harness-filters';

/** Harness for interacting with a standard Material stepper in tests. */
export class MatStepperHarness extends ComponentHarness {
  /** The selector for the host element of a `MatStepper` instance. */
  static hostSelector = '.mat-stepper-horizontal, .mat-stepper-vertical';

  /**
   * Gets a `HarnessPredicate` that can be used to search for a `MatStepperHarness` that meets
   * certain criteria.
   * @param options Options for filtering which stepper instances are considered a match.
   * @return a `HarnessPredicate` configured with the given options.
   */
  static with(options: StepperHarnessFilters = {}): HarnessPredicate<MatStepperHarness> {
    return new HarnessPredicate(MatStepperHarness, options).addOption(
      'orientation',
      options.orientation,
      async (harness, orientation) => (await harness.getOrientation()) === orientation,
    );
  }

  /**
   * Gets the list of steps in the stepper.
   * @param filter Optionally filters which steps are included.
   */
  async getSteps(filter: StepHarnessFilters = {}): Promise<MatStepHarness[]> {
    return this.locatorForAll(MatStepHarness.with(filter))();
  }

  /** Gets the orientation of the stepper. */
  async getOrientation(): Promise<StepperOrientation> {
    const host = await this.host();
    return (await host.hasClass('mat-stepper-horizontal'))
      ? StepperOrientation.HORIZONTAL
      : StepperOrientation.VERTICAL;
  }

  /**
   * Selects a step in this stepper.
   * @param filter An optional filter to apply to the child steps. The first step matching the
   *    filter will be selected.
   */
  async selectStep(filter: StepHarnessFilters = {}): Promise<void> {
    const steps = await this.getSteps(filter);
    if (!steps.length) {
      throw Error(`Cannot find mat-step matching filter ${JSON.stringify(filter)}`);
    }
    await steps[0].select();
  }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace fcs.web.Models
{
    [Table("TipiArticolo")]
    public class TipoArticolo
    {
        [Key]
        public int TipoArticoloID { get; set; }
        public string Nome { get; set; }
        public string Descrizione { get; set; }
        public string Immagine { get; set; }
    }
}


text:
<title>towctrans - Untitled</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Untitled">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Ctype.html#Ctype" title="Ctype">
<link rel="prev" href="towupper.html#towupper" title="towupper">
<link rel="next" href="wctrans.html#wctrans" title="wctrans">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<meta http-equiv="Content-Style-Type" content="text/css">

Next: wctrans,
Previous: towupper,
Up: Ctype

3.31 towctrans—extensible wide-character translation

Synopsis

     #include <wctype.h>
     wint_t towctrans(wint_t <var>c</var>, wctrans_t <var>w</var>);

Description

towctrans is a function which converts wide characters based on
a specified translation type <var>w</var>.  If the translation type is
invalid or cannot be applied to the current character, no change
to the character is made.

Returns

towctrans returns the translated equivalent of <var>c</var> when it is a
valid for the given translation, otherwise, it returns the input character.
When the translation type is invalid, errno is set EINVAL.

Portability

towctrans is C99.

No supporting OS subroutines are required.


text:
import { GraphQLError } from "./GraphQLError";
import { SourceLocation } from "../language/location";

/**
 * Given a GraphQLError, format it according to the rules described by the
 * Response Format, Errors section of the GraphQL Specification.
 */
export function formatError(error: GraphQLError): GraphQLFormattedError;

export interface GraphQLFormattedError {
    readonly message: string;
    readonly locations: ReadonlyArray<SourceLocation> | undefined;
    readonly path: ReadonlyArray<string | number> | undefined;
    readonly extensions?: { [key: string]: any };
}


text:
using System;
using System.Reflection;

namespace TestRunner.System.Reflection
{
    [TestFixture]
    public static class IntrospectionExtensionsTest
    {
        [Test]
        public static void GetTypeInfoOnNullThrowsNullReferenceException()
        {
            const Type type = null;
            // ReSharper disable once ExpressionIsAlwaysNull
            Assert.Throws<ArgumentNullException>(() => type.GetTypeInfo());
        }
    }
}


text:
<?php

namespace Dero\Core;

/**
 * Timing class
 */
class Timing
{
    private static $aTimes = [];

    private function __construct()
    {
    }

    public static function start(string $strTime)
    {
        self::$aTimes[$strTime] = microtime(true) * 1000;
    }

    public static function end(string $strTime)
    {
        if (isset(self::$aTimes[$strTime])) {
            self::$aTimes[$strTime] = round(microtime(true) * 1000 - self::$aTimes[$strTime], 2);
        }
    }

    public static function getTimings(): array
    {
        return self::$aTimes;
    }

    public static function setHeaderTimings()
    {
        foreach (self::$aTimes as $strKey => $fTiming) {
            if (!headers_sent()) {
                header(sprintf('X-%s-Timing: %0.4fms', ucfirst($strKey), $fTiming));
            }
        }
    }

    public static function printTimings()
    {
        foreach (self::$aTimes as $strKey => $fTiming) {
            printf("%s timing: %0.4fms\n", $strKey, $fTiming);
        }
    }
}


text:
package resumeonline.jfx.core.ui.component;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.Tooltip;
import javafx.scene.image.ImageView;

public final class ButtonConfigurator {

    private final Button component;

    public ButtonConfigurator(
        final Button component) {
        this.component = component;
    }

    public ButtonConfigurator toolTip(
        final String value) {
        component.setTooltip(new Tooltip(value));
        return this;
    }

    public ButtonConfigurator text(
        final String text) {
        component.setText(text);
        return this;
    }

    public ButtonConfigurator onAction(
        final EventHandler<ActionEvent> eventHandler) {
        component.setOnAction(eventHandler);
        return this;
    }

    public ButtonConfigurator image(
        final ImageView image) {
        component.setGraphic(image);
        return this;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.bjuvensjo.maven.plugins</groupId>
    <artifactId>drools-template-plugin</artifactId>
    <version>1.0.0</version>
    <packaging>maven-plugin</packaging>

    <description>This plugin generates drools rules from template.</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <mavenVersion>3.1.1</mavenVersion>
    </properties>

    <dependencies>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>${mavenVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-project</artifactId>
            <version>3.0-alpha-2</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.5</version>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.10.19</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-source-plugin</artifactId>
                    <version>2.3</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerId>groovy-eclipse-compiler</compilerId>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.codehaus.groovy</groupId>
                        <artifactId>groovy-eclipse-compiler</artifactId>
                        <version>2.9.2-01</version>
                    </dependency>
                    <!-- for 2.8.0-01 and later you must have an explicit dependency on groovy-eclipse-batch -->
                    <dependency>
                        <groupId>org.codehaus.groovy</groupId>
                        <artifactId>groovy-eclipse-batch</artifactId>
                        <version>2.4.3-01</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-plugin-plugin</artifactId>
                <version>3.2</version>
                <executions>
                    <execution>
                        <id>generate-helpmojo</id>
                        <goals>
                            <goal>helpmojo</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
import re
import numpy as np

RECIPE_SIZE = 100
MAXCALORIES = 500
ingreds = {}
scores1 = []
scores2 = []

with open('in.txt', 'r') as f:
	for line in f:
		line = line.strip()
		if(not line): continue

		if __debug__: print(line)
		ingreds[line.split(':')[0]] = {k: int(v) for (k, v) in re.findall(r'([a-z]+) (-?\d+)', line)}

if __debug__: print('Ingredients parsed: {0}'.format(ingreds))

""" each recipe must contain exactly RECIPE_SIZE (100) spoons of ingredients total """
""" number of input ingredients is variable """
""" not the best solution, slow as hell, but it covers such options as: """
""" recipe has a missing ingredient, or there's only one ingredient. example: [50, 0, 0, 50] or [0, 0, 100, 0] """
#recipes = filter(lambda x: sum(x) == RECIPE_SIZE, np.ndindex((RECIPE_SIZE + 1, ) * len(ingreds)))
#recipes = [row for row in np.ndindex((RECIPE_SIZE + 1, ) * len(ingreds)) if sum(row) == RECIPE_SIZE] # seems a bit faster
for recipe in (row for row in np.ndindex((RECIPE_SIZE + 1, ) * len(ingreds)) if sum(row) == RECIPE_SIZE):
	if __debug__: print(recipe)
	props = {'cap': 0, 'dur': 0, 'fla': 0, 'tex': 0, 'cal': 0}
	for idx, amt in enumerate(recipe):
		ingred = ingreds[ingreds.keys()[idx]]
		if __debug__: print ('Amount of {0} is: {1}. props: {2}'.format(ingreds.keys()[idx], amt, ingred))
		props['cap'] += ingred['capacity'] * amt
		props['dur'] += ingred['durability'] * amt
		props['fla'] += ingred['flavor'] * amt
		props['tex'] += ingred['texture'] * amt
		props['cal'] += ingred['calories'] * amt

	props = {k: max(0, v) for k, v in props.items()}
	if(props['cal'] == MAXCALORIES):
		scores2.append(np.prod( {k: v for k, v in props.items() if k != 'cal'}.values() ))
	else:
		scores1.append(np.prod( {k: v for k, v in props.items() if k != 'cal'}.values() ))

print("Part 1 answer: {0}".format(max(scores1)))
print("Part 2 answer: {0}".format(max(scores2)))

r"""
--- Day 15: Science for Hungry People ---

Today, you set out on the task of perfecting your milk-dunking cookie recipe. All you have to do is find the right balance of ingredients.

Your recipe leaves room for exactly 100 teaspoons of ingredients. You make a list of the remaining ingredients you could use to finish the recipe (your puzzle input) and their properties per teaspoon:

    capacity (how well it helps the cookie absorb milk)
    durability (how well it keeps the cookie intact when full of milk)
    flavor (how tasty it makes the cookie)
    texture (how it improves the feel of the cookie)
    calories (how many calories it adds to the cookie)

You can only measure ingredients in whole-teaspoon amounts accurately, and you have to be accurate so you can reproduce your results in the future. The total score of a cookie can be found by adding up each of the properties (negative totals become 0) and then multiplying together everything except calories.

For instance, suppose you have these two ingredients:

Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8
Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3

Then, choosing to use 44 teaspoons of butterscotch and 56 teaspoons of cinnamon (because the amounts of each ingredient must add up to 100) would result in a cookie with the following properties:

    A capacity of 44*-1 + 56*2 = 68
    A durability of 44*-2 + 56*3 = 80
    A flavor of 44*6 + 56*-2 = 152
    A texture of 44*3 + 56*-1 = 76

Multiplying these together (68 * 80 * 152 * 76, ignoring calories for now) results in a total score of 62842880, which happens to be the best score possible given these ingredients. If any properties had produced a negative total, it would have instead become zero, causing the whole score to multiply to zero.

Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you can make?

--- Part Two ---

Your cookie recipe becomes wildly popular! Someone asks if you can make another recipe that has exactly 500 calories per cookie (so they can use it as a meal replacement). Keep the rest of your award-winning process the same (100 teaspoons, same ingredients, same scoring system).

For example, given the ingredients above, if you had instead selected 40 teaspoons of butterscotch and 60 teaspoons of cinnamon (which still adds to 100), the total calorie count would be 40*8 + 60*3 = 500. The total score would go down, though: only 57600000, the best you can do in such trying circumstances.

Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you can make with a calorie total of 500?
"""


text:
package com.gzuddas.excangerates.core;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.gzuddas.excangerates.core.pojo.Rate;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * Created by gianluca on 17/04/17.
 */

public class Utils {

    /**
     * Iterates all rates and build the rates graph<br>
     *     Data type explanation :
     *     the key of this Map is the "from" rate.
     *     the value is another Map with key "to" and value equals to conversion rate
     * @param rates The list of rates
     * @return the rates graph
     */
    public static Map<String,Map<String,Double>> buildRatesGraph(List<Rate> rates) {
        Map<String,Map<String,Double>> ratesGraph = new HashMap<>();

        for (Rate rate : rates) {

            if(rate.rate<=0.0d)//NOT VALID RATE AND AVOID THE DIVISION BY ZERO!!!
                continue;

            Map<String, Double> fromNeighbors = ratesGraph.get(rate.from);
            Map<String, Double> toNeighbors = ratesGraph.get(rate.to);

            /*
            Every Rate is a double conversion
            conversion from->to have rate "rate"
            conversion to->from have rate "1/rate"
             */

            if (fromNeighbors == null) {
                fromNeighbors = new HashMap<>();
                ratesGraph.put(rate.from, fromNeighbors);
            }

            if (toNeighbors == null) {
                toNeighbors = new HashMap<>();
                ratesGraph.put(rate.to, toNeighbors);
            }

            if(fromNeighbors.get(rate.to)!=null && !fromNeighbors.get(rate.to).equals(rate.rate)) {
                //Conflict!!! we already have the conversion, using the first founded
            } else {
                //Add this edge to ratesGraph
                fromNeighbors.put(rate.to, rate.rate);
                //Round result
                toNeighbors.put(rate.from, (1 / rate.rate));
            }

        }

        return ratesGraph;

    }

    /**
     *
     * @param table an empty Map
     * @param ratesGraph the rates graph, {@link #buildRatesGraph(List)}
     * @param root the target currency, table will be built with all rates from currency "X" to currency "root"
     * @param visited, the list of visited nodes, initially empty
     * @param cumulate starting from "root" in each node that i visit, the conversion rate from current node to root was be cumulated, the first iteraction we have conversion from "root" to "root" and this value the first call is 1.0d
     */
    public static void buildConversionTable(Map<String,Double> table, Map<String,Map<String,Double>> ratesGraph, String root, HashSet<String> visited, Double cumulate) {

        visited.add(root);
        table.put(root, cumulate);
        Map<String, Double> neighbors = ratesGraph.get(root);

        if (neighbors!=null && neighbors.size() > 0) {
            for (String neighbour : neighbors.keySet()) {
                if (!visited.contains(neighbour)) {
                    buildConversionTable(table, ratesGraph, neighbour, visited, cumulate * (1 / neighbors.get(neighbour)));
                }
            }
        }
    }

    /**
     * round number with N decimal places
     * @param value
     * @param digits
     * @return
     */
    public static double round(double value, int digits) {
        double temp = Math.pow(10, digits);
        return Math.round(value * temp) / temp;
    }

    /**
     *
     * @param context
     * @return true if the device is connected to Internet
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

}


text:
namespace BankAccounts.Models
{
   public class MortgageAccount : Account
    {
       public MortgageAccount(Customer customer, decimal balance, decimal interestRate)
            :base(customer, balance, interestRate)
        {

        }

       public override decimal CalculateInterest(int months)
       {
           if (this.Customer is Company)
           {
               if (months <= 12)
               {
                   return (this.InterestRate / 100 * months) / 2;
               }

               return (this.InterestRate / 100 * (months - 12)) + (this.InterestRate / 100 * months) / 2;
           }
           else if (this.Customer is Individual)
           {
               if (months <= 6)
               {
                   return 0;
               }

               return this.InterestRate / 100 * (months - 6);
           }

           return this.InterestRate / 100 * months;
       }
    }
}


text:
import sys, cpp, glob, os, re, getopt, kernel
from utils import *
from defaults import *

program_dir = find_program_dir()

wanted_archs   = kernel_archs
wanted_config  = None

def usage():
    print """\
  usage:  find_headers.py [options] <kernel-root> (file|directory|@listfile)+

     options:
        -c <file>          specify .config file (none by default)

        -a <archs>         used to specify an alternative list
                           of architectures to support
                           ('%s' by default)

        -v                 enable verbose mode

    this program is used to find all the kernel headers that are used
    by a set of source files or directories containing them. the search
    is recursive to find *all* required files.

""" % ( string.join(kernel_archs,",") )
    sys.exit(1)

try:
    optlist, args = getopt.getopt( sys.argv[1:], 'vc:d:a:k:' )
except:
    # unrecognized option
    print "error: unrecognized option"
    usage()

for opt, arg in optlist:
    if opt == '-a':
        wanted_archs = string.split(arg,',')
    elif opt == '-c':
        wanted_config = arg
    elif opt == '-v':
        kernel.verboseSearch = 1
        kernel.verboseFind   = 1
        verbose = 1
    else:
        usage()

if len(args) < 2:
    usage()

kernel_root = args[0]
if not os.path.exists(kernel_root):
    sys.stderr.write( "error: directory '%s' does not exist\n" % kernel_root )
    sys.exit(1)

if not os.path.isdir(kernel_root):
    sys.stderr.write( "error: '%s' is not a directory\n" % kernel_root )
    sys.exit(1)

if not os.path.isdir(kernel_root+"/include/linux"):
    sys.stderr.write( "error: '%s' does not have an 'include/linux' directory\n" % kernel_root )
    sys.exit(1)

if wanted_config:
    if not os.path.exists(wanted_config):
        sys.stderr.write( "error: file '%s' does not exist\n" % wanted_config )
        sys.exit(1)

    if not os.path.isfile(wanted_config):
        sys.stderr.write( "error: '%s' is not a file\n" % wanted_config )
        sys.exit(1)

# find all architectures in the kernel tree
archs   = []
for archdir in os.listdir(kernel_root+"/arch"):
    if os.path.exists("%s/arch/%s/include/asm" % (kernel_root, archdir)):
        if verbose:
            print "Found arch '%s'" % archdir
        archs.append(archdir)

# if we're using the 'kernel_headers' directory, there is only asm/
# and no other asm-<arch> directories
#
in_kernel_headers = False
if len(archs) == 0:
    # this can happen when we're using the 'kernel_headers' directory
    if os.path.isdir(kernel_root+"/asm"):
        in_kernel_headers = True
        archs = [ "arm", "mips"]

# if the user has specified some architectures with -a <archs> ensure that
# all those he wants are available from the kernel include tree
if wanted_archs != None:
    if in_kernel_headers and wanted_archs != [ "arm", "mips" ]:
        sys.stderr.write( "error: when parsing kernel_headers, only 'arm' and 'mips' architectures are supported at the moment\n" )
        sys.exit(1)
    missing = []
    for arch in wanted_archs:
        if arch not in archs:
            missing.append(arch)
    if len(missing) > 0:
        sys.stderr.write( "error: the following requested architectures are not in the kernel tree: " )
        for a in missing:
            sys.stderr.write( " %s" % a )
        sys.stderr.write( "\n" )
        sys.exit(1)

    archs = wanted_archs

# helper function used to walk the user files
def parse_file(path, parser):
    #print "parse %s" % path
    parser.parseFile(path)

# remove previous destination directory
#destdir = "/tmp/bionic-kernel-headers/"
#cleanup_dir(destdir)

# try to read the config file
try:
    cparser = kernel.ConfigParser()
    if wanted_config:
        cparser.parseFile( wanted_config )
except:
    sys.stderr.write( "error: can't parse '%s'" % wanted_config )
    sys.exit(1)

kernel_config = cparser.getDefinitions()

# first, obtain the list of kernel files used by our clients
fparser = kernel.HeaderScanner()
dir_excludes=[".repo","external/kernel-headers","ndk","out","prebuilt","bionic/libc/kernel","development/ndk","external/qemu/distrib"]
walk_source_files( args[1:], parse_file, fparser, excludes=["./"+f for f in dir_excludes] )
headers = fparser.getHeaders()
files   = fparser.getFiles()

# now recursively scan the kernel headers for additionnal sub-included headers
hparser = kernel.KernelHeaderFinder(headers,archs,kernel_root,kernel_config)
headers = hparser.scanForAllArchs()

if 0:    # just for debugging
    dumpHeaderUsers = False

    print "the following %d headers:" % len(headers)
    for h in sorted(headers):
        if dumpHeaderUsers:
            print "  %s (%s)" % (h, repr(hparser.getHeaderUsers(h)))
        else:
            print "  %s" % h

    print "are used by the following %d files:" % len(files)
    for f in sorted(files):
        print "  %s" % f

    sys.exit(0)

for h in sorted(headers):
    print "%s" % h

sys.exit(0)


text:
package io.crossbar.autobahn.wamp.messages;

import java.util.ArrayList;
import java.util.List;

import io.crossbar.autobahn.wamp.interfaces.IMessage;
import io.crossbar.autobahn.wamp.utils.MessageUtil;

public class Unsubscribe implements IMessage {

    public static final int MESSAGE_TYPE = 34;
    private final long request;
    private final long subscription;

    public Unsubscribe(long request, long subscription) {
        this.request = request;
        this.subscription = subscription;
    }

    public static Unsubscribe parse(List<Object> wmsg) {
        MessageUtil.validateMessage(wmsg, MESSAGE_TYPE, "UNSUBSCRIBE", 3);
        return new Unsubscribe(MessageUtil.parseLong(wmsg.get(1)), MessageUtil.parseLong(wmsg.get(2)));
    }

    @Override
    public List<Object> marshal() {
        List<Object> marshaled = new ArrayList<>();
        marshaled.add(MESSAGE_TYPE);
        marshaled.add(request);
        marshaled.add(subscription);
        return marshaled;
    }
}


text:
layout: post
title: 'Recruitment: Group Leaders, EMBL, Heidelberg'
date: '2011-06-14T09:22:00.000+01:00'
author: John Overington
tags:
- Staff and Recruitment
modified_time: '2011-06-14T09:22:23.243+01:00'
thumbnail: http://1.bp.blogspot.com/-_MghI8B80mA/TfcZsN711fI/AAAAAAAABMw/gasO0X9A-8c/s72-c/general_header_it.jpg
blogger_id: tag:blogger.com,1999:blog-2546008714740235720.post-4000298076820371403
blogger_orig_url: http://chembl.blogspot.com/2011/06/recruitment-group-leaders-embl.html
---

There are two group leader positions currently listed at the recruitment pages for the Heidelberg site for EMBL. Due to the goofy web recruitment system we have, I can't give a link to the jobs themselves, but you should be able to find them from here.

Areas of interest for one of these posts include:

structural bioinformatics (e.g. modeling of protein complexes and their interactions and/or dynamics in a cellular context).

image analysis/visualization (e.g. reading out data from GFP screens, E-tomograms or visualizing a virtual cell atlas).

cheminformatics (e.g. chemical-protein-network analysis).

systems bioinformatics (e.g. tissue modeling, analysis network perturbations).

transcriptional regulation/epigenetics (e.g. chromatin modification analysis).

The closing deadline is June 19th 2011 - so real soon!!


text:
import {CubeGeometry,
        MeshPhongMaterial,
        Mesh,
        DoubleSide} from 'three';

import Meta from '../Meta';

import * as THREE from 'three';

import './loaders/GLTFLoader'

let models = []

export default class Graphics {

  constructor(props, stop = false){

    this.position = {
      x:props!==undefined&&props.position!==undefined&&props.position.x!==undefined?props.position.x:0,
      y:props!==undefined&&props.position!==undefined&&props.position.y!==undefined?props.position.y:0,
      z:props!==undefined&&props.position!==undefined&&props.position.z!==undefined?props.position.z:0
    };

    this.rotation = {
      x:props!==undefined&&props.rotation!==undefined&&props.rotation.x!==undefined?props.rotation.x:0,
      y:props!==undefined&&props.rotation!==undefined&&props.rotation.y!==undefined?props.rotation.y:0,
      z:props!==undefined&&props.rotation!==undefined&&props.rotation.z!==undefined?props.rotation.z:0
    };

    this.size = {
      x:props!==undefined&&props.size!==undefined&&props.size.x!==undefined?props.size.x:0,
      y:props!==undefined&&props.size!==undefined&&props.size.y!==undefined?props.size.y:0,
      z:props!==undefined&&props.size!==undefined&&props.size.z!==undefined?props.size.z:0
    };

    this.geometry = props!==undefined&&props.geometry!==undefined&&props.geometry!==true?props.geometry:new CubeGeometry();
    this.material = props!==undefined&&props.material!==undefined&&props.material!==true?props.material:new MeshPhongMaterial({color:Math.random()*0xffffff, side: DoubleSide});
    this.mesh = props!==undefined&&props.mesh!==undefined&&props.mesh!==true?props.mesh:new Mesh(this.geometry, this.material);

    this.type = props!==undefined&&props.type!==undefined?props.type:'box'

    this.model = props.model!==undefined?props.model:undefined;

    this.loader = undefined;

    //Is it a model?
    if(this.model !== undefined){

    this.fileName = this.model;

    //Add models default directory
    this.model = 'models/'+this.model

    this.mesh = new THREE.Object3D();
    //this.mesh.position.copy(this.position)

    const extentions = [
      'gltf'
    ]
    const loaders = [
      'new THREE.GLTFLoader()'
    ]

    const loadModel = (loader) => {

      loader.load( this.model, ( gltf ) => {

        //Add model to scene
        this.mesh.add( gltf.scene );
        this.mesh.position.set(this.position)
        console.log(this.position.x)

        //Add model id to list
        models.push([gltf.scene.id, this.model])

        //Set size
        //this.setSize()

      })

    }

    //Check for provided file extention
    if(this.model.includes(".")){

      //Auto-detect loader by provided model file extension
      let fileExtention;

      const pattern = /\.([0-9a-z]+)(?:[\?#]|$)/i;

      const result = this.model.match(pattern);

      fileExtention = result[1]

      this.loader = eval(loaders[extentions.indexOf(fileExtention)])

      loadModel(this.loader)

      return
    }

    //Auto-detect loader by testing model file extension
    console.log('auto dectect file extention')
    extentions.forEach((extention) => {
      if(this.loader!==undefined) return;
      fetch(this.model+extention)
      .then((response) => {
        //Check if this file exists
        if(response.status===200){
          //Select loader
          this.loader = eval(loaders[extentions.indexOf(extention)])
          //Add extentions to model file path
          this.model = this.model+'.'+extention
          //load model
          loadModel(this.loader)
        }
      })
      .catch(error => console.error(error));
    })

    }

    if(stop)
      return this;

    return new Meta({graphics: this, position: this.position, rotation: this.rotation, size: this.size});

  }

  setScale(scale){
    scale = scale!==undefined?scale:this.scale
    this.mesh.scale.set({
      x:scale.x,
      y:scale.y,
      z:scale.z
    })
  }

  setPosition(position){
    position = position!==undefined?position:this.position
    this.mesh.position.copy(position)
    return this;
  }

  setRotation(rotation){
    rotation = rotation!==undefined?rotation:this.rotation
    this.mesh.rotation.x = rotation.x * (Math.PI / 180);
    this.mesh.rotation.y = rotation.y * (Math.PI / 180);
    this.mesh.rotation.z = rotation.z * (Math.PI / 180);
    return this;
  }

  add(instance){
    this.geometry = instance;
  }

}


text:
import express from 'express';

const router = express.Router();

router.get('/', (req, res, next) => {
  res.render('index', {
    title: 'Webpack-Express-Template'
  });
});

export default router;


text:
var Preact          = window.Preact = require('preact'),
    h               = require('preact').h,
    createClass     = require('preact-compat').createClass,
    SearchBar       = require('./searchbar.jsx'),
    PluginList      = require('./pluginlist.jsx'),
    PlatformButton  = require('./platformbutton.jsx')
    App             = {},
    SortDropdown    = require('./sortdropdown.jsx'),
    SortCriteria    = require('./SortCriteria'),
    ZeroClipboard   = require("../js/lib/ZeroClipboard.js");

var INPUT_DELAY = 500; // in milliseconds

var timer = null;
var Constants = {
    DownloadCountBatch: 100,
    NpmSearchInitialSize: 500
}

var UrlParameters = {
    SortBy: 'sortBy',
    Query: 'q',
    Platfroms: 'platforms',
}

var App = createClass({
    getInitialState: function() {
        var staticFilters = [];
        staticFilters['platforms'] = [];
        staticFilters['authors'] = [];
        staticFilters['licenses'] = [];
        var platforms = App.getURLParameter(UrlParameters.Platfroms);
        if(platforms) {
            staticFilters['platforms'] = staticFilters['platforms'].concat(platforms.split(','));
        }
        var q = App.getURLParameter(UrlParameters.Query);
        var sortBy = App.getURLParameter(UrlParameters.SortBy);
        if (!sortBy) {
            sortBy = SortCriteria.Quality;
        }
        var state = {
            plugins: [],
            placeHolderText: 'Loading...',
            searchResults: [],
            staticFilters: staticFilters,
            sortCriteria: sortBy,
            flashEnabled: true,
            downloadsReceived: false
        }

        if (q) {
            state.filterText = q;
        } else {
            state.filterText = '';
        }

        return state;
    },
    handleUserInput: function(filterText) {
        var self = this;
        /* We receive events for all inputs, so make sure text changed */
        if(this.state.filterText !== filterText) {
            /* Routing logic */
            var platformFilters = this.state.staticFilters["platforms"];
            delay(function(){
                App.updateURL(filterText, platformFilters, self.state.sortCriteria);
            }, INPUT_DELAY);

            this.setState({
                filterText: filterText,
                searchResults: App.filterPlugins(self.state.plugins, filterText, self.state.staticFilters)
            });
        }
    },
    toggleCondition: function(keyword, condition) {
        var state = this.state;
        this.setState(function(previousState, currentProps) {
            var conditionIndex = previousState.staticFilters[keyword].indexOf(condition);
            if(conditionIndex > -1) {
                previousState.staticFilters[keyword].splice(conditionIndex, 1);
            }
            else {
                previousState.staticFilters[keyword].push(condition);
            }

            App.updateURL(previousState.filterText, previousState.staticFilters['platforms'], previousState.sortCriteria);

            return {
                staticFilters: previousState.staticFilters,
                plugins: previousState.plugins,
                searchResults: App.filterPlugins(previousState.plugins, state.filterText, state.staticFilters)
            };
        });
    },
    setSort: function(sort) {
        var state = this.state;
        this.setState(function(previousState, currentProps) {
            App.sortPlugins(previousState.plugins, sort)
             delay(function(){
                App.updateURL(previousState.filterText, previousState.staticFilters['platforms'], previousState.sortCriteria);
            }, INPUT_DELAY);
            return {
                plugins: previousState.plugins,
                searchResults: App.filterPlugins(previousState.plugins, state.filterText, state.staticFilters),
                sortCriteria: sort
            }
        });
    },
    statics: {
        appendURLParameter : function(qs, urlParameter) {
            if(!qs) {
                qs = '?' + urlParameter + '=';
            } else {
                qs = qs + '&' + urlParameter + '=';
            }
            return qs;
        },
        getURLParameter : function(name) {
                try {
                    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)
                        ||[,""])[1].replace(/\+/g, '%20'))||null;
                } catch(error) {
                    // Improperly encoded URLs are ignored
                    if (error instanceof URIError) {
                        window.history.replaceState({}, "", "./");
                        return null;
                    }

                    // Throw other errors back out
                    throw error;
                }
        },
        shallowCopy: function(src) {
            var dst = {};
            for(var i in src) {
                if(src.hasOwnProperty(i)) {
                    dst[i] = src[i];
                }
            }
            return dst;
        },
        tagOfficialPlugins: function() {

        },
        filterPlugins: function(plugins, filter, staticFilters) {
            var contains = function(values, pluginInfo) {
                var allValuesPresent = true;
                if(values.length == 0) {
                    return allValuesPresent;
                }
                if(!pluginInfo) {
                    return false;
                }
                values.forEach(function(value) {
                    var valuePresent = false;
                    for(var index=0; index < pluginInfo.length; index++) {
                        if(pluginInfo[index] && pluginInfo[index].toLowerCase().indexOf(value.toLowerCase()) > -1) {
                            valuePresent = true;
                        }
                    }
                    if(!valuePresent) {
                        allValuesPresent = false;
                    }
                });
                return allValuesPresent;
            }
            var populateFilters = function(filterText) {
                var searchStrings = filterText.split(" ");
                var filters = [];
                filters['platforms'] = [];
                filters['authors'] = [];
                filters['licenses'] = [];
                filters['searchWords'] = [];

                searchStrings.forEach(function(searchString) {
                    var keywords = searchString.split(":");
                    if(keywords.length == 1) {
                        var param = keywords[0].trim();
                        if(param) {
                            filters['searchWords'].push(param);
                        }
                    }
                    else if(keywords[1].trim()) {
                        var param = keywords[1].trim();
                        switch(keywords[0]) {
                            case 'platform':
                                filters['platforms'].push(param);
                                break;
                            case 'author':
                                filters['authors'].push(param);
                                break;
                            case 'license':
                                filters['licenses'].push(param);
                                break;
                            default:
                                filters['searchWords'].push(searchString);
                        }
                    }
                    else {
                        filters['searchWords'].push(searchString);
                    }
                });
                return filters;
            }
            var results = [];
            var filters = populateFilters(filter);

            var combine = function(filter1, filter2) {
                var result = [].concat(filter1)
                for(var i = 0; i < filter2.length; i++) {
                    if(result.indexOf(filter2[i]) === -1) {
                        result.push(filter2[i])
                    }
                }
                return result;
            }

            for (var i = 0; i < plugins.length; i++) {
                var plugin = plugins[i];
                var fullPluginText = plugin.name.concat(plugin.author, plugin.keywords, plugin.license, plugin.description);

                if(contains(combine(filters['platforms'], staticFilters['platforms']), plugin.keywords)
                    && contains(combine(filters['authors'], staticFilters['authors']), plugin.author)
                    && contains(combine(filters['licenses'], staticFilters['licenses']), plugin.license)
                    && contains(filters['searchWords'], fullPluginText)) {
                        results.push(plugin);
                }
            };
            return results;
        },
        sortPlugins: function(plugins, criteria) {
            // Search results should be deterministic, so we need a secondary
            // sort function for cases where the plugins are equal
            var compareName = function(p1, p2) {
                if(p1.name === p2.name) {
                    return 0;
                } else if(p1.name > p2.name) {
                    return 1;
                } else {
                    return -1;
                }
            }
            switch(criteria) {
                case SortCriteria.Downloads:
                    plugins.sort(function(p1, p2) {
                        if(!p1.downloadCount) {
                            return 1;
                        } else if(!p2.downloadCount) {
                            return -1;
                        }
                        if(p2.downloadCount === p1.downloadCount) {
                            return compareName(p1, p2);
                        };
                        return p2.downloadCount - p1.downloadCount;
                    });
                    break;
                case SortCriteria.RecentlyUpdated:
                    plugins.sort(function(p1, p2) {
                        if(p2.modified === p1.modified) {
                            return compareName(p1, p2);
                        };
                        return p1.modified - p2.modified;
                    });
                    break;
                case SortCriteria.Quality:
                default:
                    plugins.sort(function(p1, p2) {
                        if(p2.rating === p1.rating) {
                            return compareName(p1, p2);
                        };
                        return p2.rating - p1.rating;
                    });
                    break;
            }
            return plugins;
        },
        updateURL: function(filterText, platformFilters, sortCriteria) {
            var query = '';
            var stateObj = {};
            if(filterText) {
                var filterTextLowerCase = filterText;
                query = App.appendURLParameter(query, UrlParameters.Query);
                query += encodeURIComponent(filterTextLowerCase);
                stateObj.filterText = filterTextLowerCase;
            }

            if(platformFilters.length > 0) {
                query = App.appendURLParameter(query, UrlParameters.Platfroms);
                query += encodeURIComponent(platformFilters.join());
                stateObj.platforms = platformFilters;
            }

            if(sortCriteria !== SortCriteria.Quality) {
                query = App.appendURLParameter(query, UrlParameters.SortBy);
                query += encodeURIComponent(sortCriteria);
                stateObj.sortBy = sortCriteria;
            }
            window.history.replaceState(stateObj, "", query);
            ga('send', 'pageview', '/index.html' + query);
        },
    },
    componentWillMount: function() {
        var that = this;
        ZeroClipboard.config({swfPath: "{{ site.baseurl }}/static/js/lib/ZeroClipboard.swf"});
        ZeroClipboard.on({
            "ready": function(event) {that.setState({ flashEnabled: true });},
            "error": function(event) {that.setState({ flashEnabled: false });}
        });
    },
    componentDidMount: function() {
        var plugins = [],
            officialPlugins = require('./official-plugins.json').plugins,
            blacklistedPlugins = require('./blacklisted-plugins.json').plugins,
            pluginCount = 0,
            self = this,
            queryProtocol = window.location.protocol === "https:" ? "https:" : "http:",
            queryHost = queryProtocol + "//npmsearch.com/query",
            queryFields = "fields=name,keywords,license,description,author,modified,homepage,version,rating",
            queryKeywords = "q=keywords:%22ecosystem:cordova%22",
            queryInitialSize = Constants.NpmSearchInitialSize,
            baseUrl = queryHost + "?" + queryFields + "&" + queryKeywords + "&sort=rating:desc";

        xhrRequest(baseUrl + "&size=" + queryInitialSize + "&start=0", function(xhrResult) {
            plugins = xhrResult.results;
            pluginCount = xhrResult.total;
            if (pluginCount <= queryInitialSize) {
                processPlugins.bind(self, officialPlugins, plugins)();
            } else {
                xhrRequest(baseUrl + "&size=" + (pluginCount - queryInitialSize) + "&start=" + queryInitialSize, function(xhrResult) {
                        plugins = [].concat(plugins, xhrResult.results);
                        processPlugins.bind(self, officialPlugins, plugins)();
                }, function() { console.log('xhr err'); });
            }
        }, function() { console.log('xhr err'); });

        var getDownloadCount = function(plugins) {
            var packageNames = "";
            var downloadCountRequests = [];
            for(var index = 0; index < plugins.length; index++) {
                if (/^@.*\//.test(plugins[index].name)) {
                    continue;
                }
                packageNames += plugins[index].name + ",";

                if(index % Constants.DownloadCountBatch === 0 || index === plugins.length - 1) {
                    downloadCountRequests.push($.getJSON("https://api.npmjs.org/downloads/point/last-month/" + packageNames));
                    packageNames = "";
                }
            }
            // When all the download count requests return - we can populate the plugins and sort them
            $.when.apply($, downloadCountRequests).done(function() {
                for(var i = 0; i < arguments.length; i ++) {
                    var xhrResult = arguments[i][0];
                    for(var j = 0; j < plugins.length; j++) {
                        if(xhrResult[plugins[j].name]) {
                            plugins[j] = App.shallowCopy(plugins[j]);
                            plugins[j].downloadCount = xhrResult[plugins[j].name].downloads;
                        }
                    }
                }
                if(self.state.sortCriteria === SortCriteria.Downloads) {
                    App.sortPlugins(plugins, self.state.sortCriteria);
                }
                self.setState({
                    plugins: plugins,
                    searchResults: App.filterPlugins(plugins, self.state.filterText, self.state.staticFilters),
                    downloadsReceived: true
                });
            })
            .fail( function() { console.log('xhr err'); });
        }

        function processPlugins(officialPlugins, plugins) {
            var pluginCount = plugins.length,
                dateNow = new Date(),
                oneDay = 1000*60*60*24;

            officialPlugins.forEach(function(plugin) {
                for (var i = 0; i < plugins.length; i++) {
                    // Check if plugin name is in official list
                    if (plugins[i].name[0] === plugin) {
                        plugins[i].isOfficial = true;
                        return;
                    }
                };
            });

            for(var i = plugins.length -1; i >= 0 ; i--)
            {
                for(var j = 0; j < blacklistedPlugins.length; j++)
                {
                    if(plugins[i].name[0] === blacklistedPlugins[j])
                    {
                        plugins.splice(i, 1);
                        break;
                    }
                }
            }

            for (var i = 0; i < plugins.length; i++) {
                // Calculate last time plugin is modified (in days)
                plugins[i].modified = Math.ceil((dateNow - new Date(plugins[i].modified)) / oneDay);
            };

            // Initial sort cannot be on downloads as download counts have not been populated.
            if (this.state.sortCriteria !== SortCriteria.Downloads) {
                plugins = App.sortPlugins(plugins, this.state.sortCriteria);
            } else {
                plugins = App.sortPlugins(plugins, SortCriteria.Quality);
            }

            if (this.isMounted()) {
                var q = App.getURLParameter(UrlParameters.Query);
                if(q) {
                    this.setState({
                        plugins: plugins,
                        filterText: q,
                        placeHolderText: 'Search ' + plugins.length + ' plugins...',
                        searchResults: App.filterPlugins(plugins, q, this.state.staticFilters)
                    });
                }
                else {
                    this.setState({
                        plugins: plugins,
                        placeHolderText: 'Search ' + plugins.length + ' plugins...',
                        searchResults: App.filterPlugins(plugins, '', this.state.staticFilters)
                    });
                }
                getDownloadCount(plugins);
            }
        }
    },
    render: function() {
        var toggleCondition = this.toggleCondition;
        var createPlatformButton = function(platform, keyword, state) {
            var active = state.staticFilters["platforms"].indexOf(keyword) > -1;
            return (
                <PlatformButton platform={platform} keyword={keyword} initiallyActive={active} toggleCondition={toggleCondition}/>
            );
        }

        var listContent = <PluginList plugins={this.state.searchResults} flashEnabled={this.state.flashEnabled}/>;

        return (

Cordova Plugins

                            <SearchBar
                                initialValue={this.state.filterText}
                                placeHolderText={this.state.placeHolderText}
                                onUserInput={this.handleUserInput}
                            />

What is a Cordova plugin?

A plugin is a bit of add-on code that provides JavaScript interface to native components.  They allow your app to use native device capabilities beyond what is available to pure web apps.

 Contribute Plugins

 Plugin Help

Must Support Platform(s):

                                {createPlatformButton('Android', 'cordova-android', this.state)}
                                {createPlatformButton('iOS', 'cordova-ios', this.state)}
                                {createPlatformButton('Windows', 'cordova-windows', this.state)}
                                {createPlatformButton('macOS', 'cordova-osx', this.state)}
                                {createPlatformButton('Browser', 'cordova-browser', this.state)}

{this.state.searchResults.length} result(s) found

                            <SortDropdown setSort={this.setSort} selected={this.state.sortCriteria} downloadsEnabled={this.state.downloadsReceived}/>

                {listContent}

                    Search results powered by npmsearch.com

        );
    }
});

App.start = function() {
    Preact.render(<App />, document.getElementById('pluginsAppContainer'));
};

function delay(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
}

function xhrRequest(url, success, fail) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE ) {
            if(xhr.status == 200){
                success(JSON.parse(xhr.responseText));
                return;
            } else {
                fail();
                return;
            }
        }
    }.bind(this)
    xhr.open("GET", url, true);
    xhr.send();
}

module.exports = window.App = App;

// run the app
App.start();


text:
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import delay from 'delay'
import reducer from './reducer'
import sagas from './sagas'
import {
  resourceCreateRequest,
  resourceListReadRequest,
  resourceDetailReadRequest,
  resourceUpdateRequest,
  resourceDeleteRequest,
} from './actions'
import { getList, getDetail } from './selectors'

const sagaMiddleware = createSagaMiddleware()

const api = {
  post: (path, data) => Promise.resolve(data),
  get: () => Promise.resolve([1, 2, 3]),
  put: (path, data) => Promise.resolve(data),
  delete: () => Promise.resolve(),
}

const getStore = (initialState) => {
  const store = createStore(reducer, initialState, applyMiddleware(sagaMiddleware))
  sagaMiddleware.run(sagas, { api })
  return store
}

describe('resource', () => {
  test('resourceCreateRequest', async () => {
    const { getState, dispatch } = getStore()

    expect(getList(getState(), 'resources')).toEqual([])

    dispatch(resourceCreateRequest('resources', { title: 'foo' }))
    await delay()
    expect(getList(getState(), 'resources')).toEqual([{ title: 'foo' }])

    dispatch(resourceCreateRequest('resources', { title: 'bar' }))
    await delay()
    expect(getList(getState(), 'resources')).toEqual([{ title: 'bar' }, { title: 'foo' }])
  })

  test('resourceListReadRequest', async () => {
    const { getState, dispatch } = getStore()

    expect(getList(getState(), 'resources')).toEqual([])

    dispatch(resourceListReadRequest('resources'))
    await delay()
    expect(getList(getState(), 'resources')).toEqual([1, 2, 3])

    dispatch(resourceListReadRequest('resources'))
    await delay()
    expect(getList(getState(), 'resources')).toEqual([1, 2, 3])
  })

  test('resourceDetailReadRequest', async () => {
    const { getState, dispatch } = getStore()

    expect(getDetail(getState(), 'resources')).toBeNull()

    dispatch(resourceDetailReadRequest('resources'))
    await delay()
    expect(getDetail(getState(), 'resources')).toEqual([1, 2, 3])

    dispatch(resourceDetailReadRequest('resources'))
    await delay()
    expect(getDetail(getState(), 'resources')).toEqual([1, 2, 3])
  })

  test('resourceUpdateRequest', async () => {
    const { getState, dispatch } = getStore({ resources: { list: [1, 2, 3] } })

    expect(getList(getState(), 'resources')).toEqual([1, 2, 3])

    dispatch(resourceUpdateRequest('resources', 1, 4))
    await delay()
    expect(getList(getState(), 'resources')).toEqual([4, 2, 3])

    dispatch(resourceUpdateRequest('resources', 4, { title: 'foo' }))
    await delay()
    expect(getList(getState(), 'resources')).toEqual([{ title: 'foo' }, 2, 3])

    dispatch(resourceUpdateRequest('resources', { title: 'foo' }, { foo: 'bar' }))
    await delay()
    expect(getList(getState(), 'resources')).toEqual([{ title: 'foo', foo: 'bar' }, 2, 3])
  })

  test('resourceDeleteRequest', async () => {
    const { getState, dispatch } = getStore({ resources: { list: [1, 2, { foo: 'bar' }] } })

    expect(getList(getState(), 'resources')).toEqual([1, 2, { foo: 'bar' }])

    dispatch(resourceDeleteRequest('resources', 1))
    await delay()
    expect(getList(getState(), 'resources')).toEqual([2, { foo: 'bar' }])

    dispatch(resourceDeleteRequest('resources', { foo: 'bar' }))
    await delay()
    expect(getList(getState(), 'resources')).toEqual([2])
  })
})


text:
const path = require('path');
const HummusRecipe = require('../lib');
const fs = require('fs');

function compare(a, b) {
    // Use toUpperCase() to ignore character casing
    const nameA = a.last_name.toUpperCase();
    const nameB = b.last_name.toUpperCase();

    let comparison = 0;
    if (nameA > nameB) {
        comparison = 1;
    } else if (nameA < nameB) {
        comparison = -1;
    }
    return comparison;
}

function hilight(text, record) {
    if (record.gender.toLowerCase() === 'female') {
        return { color: '#ff1493' };
    }
}

describe('Text - Columns', () => {

    it('Table', (done) => {
        const output = path.join(__dirname, 'output/table.pdf');
        const pplFile = path.join(__dirname, 'materials/people.json');
        const recipe = new HummusRecipe('new', output);
        const peeps = fs.readFileSync(pplFile, 'utf8');
        const people = JSON.parse(peeps);

        const contents = [{
            name: 'Steven Haehn',
            address: '257 Banana Ave.',
            city: 'Colorado Springs',
            state: 'Colorado',
            job: 'computer programmer'
        }, {
            name: 'Yunjin Kim',
            address: '123 Laurel Blvd.',
            city: 'Phoenix',
            state: 'Arizona',
            job: 'musical director, teacher'
        }, {
            name: 'Chunyen Huang',
            address: '34178 Sunset Lane',
            city: 'Los Angles',
            state: 'California',
            job: 'computer analyst'
        }, {
            name: 'Iris Johansen',
            address: '341 Washington Ave.',
            city: 'Atlanta',
            state: 'Georgia',
            job: 'author'
        }, {
            name: 'Terry Brooks',
            address: '1523 Bernard Blvd.',
            // city: "Seattle",
            state: 'Oregon',
            job: 'author'
        }, {
            name: 'Joy Merchand',
            address: '46 Medulla Lane',
            city: 'San Jose',
            state: 'California',
            job: 'psycologist'
        }];

        const pcols = [{
            name: 'email',
            width: 170
        }, {
            name: 'ip_address',
            width: 110
        }, {
            name: 'first_name',
            renderer: hilight,
            width: 80
        }, {
            name: 'last_name',
            renderer: hilight,
            width: 80
        }];

        const columns = [{
            text: 'Name',
            name: 'name',
            width: 110,
            cell: {textAlign:'center center'}
        }, {
            text: 'Address',
            name: 'address',
            width: 130,
            cell: {textAlign:'left center'}
        }, {
            text: 'City/Town',
            name: 'city',
            width: 100,
            cell: {textAlign:'center center'}
        }, {
            text: 'State',
            name: 'state',
            width: 80
        }, {
            text: 'Occupation',
            name: 'job',
            width: 100,
            color: 'red',
            size: 10,
            cell: {textAlign:'right bottom'},
            hcell: {textAlign:'center center'}
        }];

        // const stop = () => { return true; };

        const newPage = (self) => {
            self.endPage();
            self.createPage('letter');
            return { position: [30, 52] };
        };

        let nextTable = 30;
        const samePage = () => {
            nextTable += 170;
            if (nextTable > 500) {
                return true;
            }
            return { position: [nextTable, 302] };
        };

        let x = 50;
        let y = 52;
        recipe
            .createPage('letter')
            .text('Table with alternating row properties', 230, 30, { color: '#000000' })
            .table(x, y, contents, {
                columns: columns,
                header: { alignToData: true, cell: { padding: [8, 2, 8, 2], textAlign: 'left'} },
                border: { stroke: '#dddddd' },
                row: { nth: 'odd', cell: { style: { fill: '#dddddd' } } }
            })
            .text('Tables showing new position when "overflow" encountered.', 80, y + 200, { color: '#000000' })
            .text('Note data driven property (color) assignment', 130, y + 220, { size: 12, color: '#000000' })
            .table(x - 20, y + 250, people.sort(compare), {
                columns: pcols,
                border: true,
                header: { cell: { textAlign: 'left' } },
                row: { size: 10 },
                overflow: samePage,
                order: 'first_name,last_name'
            })
            .endPage()
            .createPage('letter')
            .text('Table continued onto subsequent pages (overflow encountered)', x, y - 30, { color: '#000000' })
            .table(x - 20, y, people.sort(compare), {
                columns: pcols,
                border: true,
                header: true,
                row: { size: 10 },
                overflow: newPage,
                order: 'first_name,last_name,email'
            })
            .endPage()
            .createPage('letter')
            .text('Table with less columns than fields in data', 230, 30, { color: '#000000' })
            .table(x, y, contents, {
                columns: columns.slice(0,4),
                header: { alignToData: true, cell: { padding: [8, 2, 8, 2], textAlign: 'left'} },
                border: { stroke: '#dddddd' },
                row: { size: 10 }
            });

        recipe.endPage();
        recipe.endPDF(done);
    });
});


text:
package ch.wsl.box.client.views.components.widget.child

import ch.wsl.box.client.RoutingState
import ch.wsl.box.client.routes.Routes
import ch.wsl.box.client.services.Navigate
import ch.wsl.box.client.views.components.widget.helpers.Link
import ch.wsl.box.client.views.components.widget.lookup.DynamicLookupWidget
import ch.wsl.box.client.views.components.widget.{ComponentWidgetFactory, Widget, WidgetParams}
import ch.wsl.box.model.shared._
import ch.wsl.box.shared.utils.JSONUtils.EnhancedJson
import io.circe.Json
import io.udash._
import io.udash.bindings.modifiers.Binding
import org.scalajs.dom.Event
import scalatags.JsDom
import scalatags.JsDom.all._
import scribe.Logging

object LookupFormWidget extends ComponentWidgetFactory {

  override def name: String = WidgetsNames.lookupForm

  override def create(params: WidgetParams): Widget = LookupFormWidgetImpl(params)

  case class LookupFormWidgetImpl(params: WidgetParams) extends Widget with Logging with Link {

    val field: JSONField = params.field

    val linked: LinkedForm = field.linked.get

    val linkedData: ReadableProperty[JSONID] = params.allData.transform { js =>
      val parentValues = linked.parentValueFields.map(k => js.js(k))
      JSONID.fromMap(linked.childValueFields.zip(parentValues))
    }

    def _params = params

    val lab = (linked.lookup,linked.label) match {
      case (Some(lookup),_) => new DynamicLookupWidget {
        override def params: WidgetParams = _params.copy(field = _params.field.copy(lookupLabel = Some(lookup)))

        override protected def show(nested:Binding.NestedInterceptor): JsDom.all.Modifier = widget().showOnTable(nested)

        override protected def edit(nested:Binding.NestedInterceptor): JsDom.all.Modifier = show(nested)

      }
      case (_,Some(label)) => Widget.forString(params.field,label)
      case (_,_) => Widget.forString(params.field,"Open")
    }

    def navigate(goTo: Routes => RoutingState) = (e: Event) => {
      Navigate.to(goTo(Routes(EntityKind.FORM.kind, linked.name)))
      e.preventDefault()
    }

    override protected def show(nested:Binding.NestedInterceptor): Modifier = nested(produce(linkedData) { case id =>
      linkRenderer(lab.render(false,Property(true),nested),field.params,navigate(_.show(id.asString))).render
    })

    override protected def edit(nested:Binding.NestedInterceptor): Modifier = nested(produce(linkedData) { case id =>
      linkRenderer(lab.render(false,Property(true),nested),field.params,navigate(_.edit(id.asString))).render
    })

    override def showOnTable(nested:Binding.NestedInterceptor): JsDom.all.Modifier =  nested(produce(linkedData) { case id =>
      a(onclick :+= navigate(_.show(id.asString)),lab.render(false,Property(true),nested)).render
    })

    override def editOnTable(nested:Binding.NestedInterceptor): JsDom.all.Modifier =  nested(produce(linkedData) { case id =>
      a(onclick :+= navigate(_.edit(id.asString)),lab.render(false,Property(true),nested)).render
    })
  }

}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>qLibc: utilities/qcount.c File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

qLibc

Main Page

Files

File List

Globals

Functions

qcount.c File Reference

Counter file handling APIs.
More...

Go to the source code of this file.

Functions

int64_t 	qcount_read (const char *filepath)

 	Read counter(integer) from file with advisory file locking.  More...

bool 	qcount_save (const char *filepath, int64_t number)

 	Save counter(integer) to file with advisory file locking.  More...

int64_t 	qcount_update (const char *filepath, int64_t number)

 	Increases(or decrease) the counter value as much as specified number with advisory file locking.  More...

Detailed Description

Counter file handling APIs.

Definition in file qcount.c.

Function Documentation

          int64_t qcount_read
          (
          const char *
          filepath	)

Read counter(integer) from file with advisory file locking.

Parameters

filepath	file path

Returns

counter value readed from file. in case of failure, returns 0.

qcount_save("number.dat", 75);

int count = qcount_read("number.dat");

---- number.dat ----

75

--------------------

Definition at line 65 of file qcount.c.

          bool qcount_save
          (
          const char *
          filepath,

          int64_t
          number

          )

Save counter(integer) to file with advisory file locking.

Parameters

filepath	file path

number	counter integer value

Returns

true if successful, otherwise returns false.

qcount_save("number.dat", 75);

Definition at line 95 of file qcount.c.

          int64_t qcount_update
          (
          const char *
          filepath,

          int64_t
          number

          )

Increases(or decrease) the counter value as much as specified number with advisory file locking.

Parameters

filepath	file path

number	how much increase or decrease

Returns

updated counter value. in case of failure, returns 0.

int count;

count = qcount_update("number.dat", -3);

Definition at line 124 of file qcount.c.

utilities

qcount.c

Generated by

     1.8.6


text:
package junit.reflection;

import static junit.util.AssertWrapper.*;
import static org.junit.Assert.*;

import java.util.*;

import org.junit.*;

/**
 * ForcedValueSetterのテストクラス。
 *
 * @author cobot00
 *
 */
public class ForcedValueSetterTest {

    /**
     * 動作検証用のやっつけクラス。
     *
     * @author Kobori
     *
     */
    private class TargetCalss {
        private int intValue;
        private long longValue;
        private Integer integerValue;
        private String stringValue;
        private Map<String, String> map = new HashMap<String, String>();

        private TargetCalss(int aInt, long aLong, Integer aInteger, String aString, String[][] aValues) {
            intValue = aInt;
            longValue = aLong;
            integerValue = aInteger;
            stringValue = aString;
            for (String[] each : aValues) {
                map.put(each[0], each[1]);
            }
        }

        private int getIntValue() {
            return intValue;
        }

        private long getLongValue() {
            return longValue;
        }

        private Integer getInteger() {
            return integerValue;
        }

        private String getString() {
            return stringValue;
        }

        private String getMapValue(String key) {
            return map.get(key);
        }
    }

    private static final String FIELD_INT_VALUE = "intValue";
    private static final String FIELD_LONG_VALUE = "longValue";
    private static final String FIELD_INTEGER_VALUE = "integerValue";
    private static final String FIELD_STRING_VALUE = "stringValue";

    private static final int INITIAL_INT_VALUE = 1;
    private static final long INITIAL_LONG_VALUE = 2;
    private static final int INITIAL_INTEGER_VALUE = 100;
    private static final String INITIAL_STRING_VALUE = "A";
    private static final String[][] VALUES = { { "1", "a" }, { "2", "b" }, { "3", "c" } };

    private TargetCalss target;

    @Before
    public void setUp() throws Exception {
        target = new TargetCalss(INITIAL_INT_VALUE, INITIAL_LONG_VALUE, new Integer(INITIAL_INTEGER_VALUE), "A", VALUES);
    }

    /**
     * int値が置き換わるかの確認。

     * 他の変数に影響がないかも確認しています。
     */
    @Test
    public void setValueInt() {
        final int intValue = 10;
        ForcedValueSetter.setValue(target, FIELD_INT_VALUE, intValue);

        assertEquals(target.getIntValue(), intValue);
        assertEquals(target.getLongValue(), INITIAL_LONG_VALUE);
        assertEquals(target.getInteger(), Integer.valueOf(INITIAL_INTEGER_VALUE));
        assertEquals(target.getString(), INITIAL_STRING_VALUE);
    }

    /**
     * long値が置き換わるかの確認。

     * 他の変数に影響がないかも確認しています。
     */
    @Test
    public void setValueLong() {
        final long longValue = 123;
        ForcedValueSetter.setValue(target, FIELD_LONG_VALUE, longValue);

        assertEquals(target.getIntValue(), INITIAL_INT_VALUE);
        assertEquals(target.getLongValue(), longValue);
        assertEquals(target.getInteger(), Integer.valueOf(INITIAL_INTEGER_VALUE));
        assertEquals(target.getString(), INITIAL_STRING_VALUE);
    }

    /**
     * Integerインスタンスが置き換わるかの確認。

     * 他の変数に影響がないかも確認しています。
     */
    @Test
    public void setValueInteger() {
        final Integer integerValue = new Integer(65536);
        ForcedValueSetter.setValue(target, FIELD_INTEGER_VALUE, integerValue);

        assertEquals(target.getIntValue(), INITIAL_INT_VALUE);
        assertEquals(target.getLongValue(), INITIAL_LONG_VALUE);
        assertEquals(target.getInteger(), integerValue);
        assertEquals(target.getString(), INITIAL_STRING_VALUE);
    }

    /**
     * Stringインスタンスが置き換わるかの確認。

     * 他の変数に影響がないかも確認しています。
     */
    @Test
    public void setValueString() {
        final String stringValue = "abcde";
        ForcedValueSetter.setValue(target, FIELD_STRING_VALUE, stringValue);

        assertEquals(target.getIntValue(), INITIAL_INT_VALUE);
        assertEquals(target.getLongValue(), INITIAL_LONG_VALUE);
        assertEquals(target.getInteger(), Integer.valueOf(INITIAL_INTEGER_VALUE));
        assertEquals(target.getString(), stringValue);
    }

    /**
     * Mapインスタンスが置き換わるかの確認。
     */
    @Test
    public void setValueMap() {
        final Map<String, String> map = new HashMap<String, String>();
        map.put("a", "A1");
        map.put("b", "B2");
        map.put("c", "C3");

        ForcedValueSetter.setValue(target, "map", map);

        assertThatWrapper(target.getMapValue("a"), "A1");
        assertThatWrapper(target.getMapValue("b"), "B2");
        assertThatWrapper(target.getMapValue("c"), "C3");

        assertThatWrapper(target.getMapValue("1"), null);
        assertThatWrapper(target.getMapValue("2"), null);
        assertThatWrapper(target.getMapValue("3"), null);
    }

    /**
     * Mapインスタンスの指定した要素が置き換わるかの確認。
     */
    @Test
    public void setValueToMap() {
        ForcedValueSetter.setValueToMap(target, "map", "1", "A");
        ForcedValueSetter.setValueToMap(target, "map", "2", "B");
        ForcedValueSetter.setValueToMap(target, "map", "3", "C");
        ForcedValueSetter.setValueToMap(target, "map", "4", "D");

        assertThatWrapper(target.getMapValue("1"), "A");
        assertThatWrapper(target.getMapValue("2"), "B");
        assertThatWrapper(target.getMapValue("3"), "C");
        assertThatWrapper(target.getMapValue("4"), "D");
    }
}


text:
puts "Pushing published case studies to publishing API"
CaseStudy.published.find_each do |case_study|
  print '.'
  PublishingApiEditionWorker.perform_async(case_study.id)
end
puts "\n#{CaseStudy.count} case studies queued for pushing to the publishing API"