text:
package org.apache.samza.operators.spec;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.samza.operators.KV;
import org.apache.samza.operators.Scheduler;
import org.apache.samza.operators.data.TestMessageEnvelope;
import org.apache.samza.operators.data.TestOutputMessageEnvelope;
import org.apache.samza.operators.functions.FilterFunction;
import org.apache.samza.operators.functions.FlatMapFunction;
import org.apache.samza.operators.functions.JoinFunction;
import org.apache.samza.operators.functions.MapFunction;
import org.apache.samza.operators.functions.ScheduledFunction;
import org.apache.samza.operators.functions.SinkFunction;
import org.apache.samza.operators.functions.StreamTableJoinFunction;
import org.apache.samza.operators.functions.WatermarkFunction;
import org.apache.samza.serializers.JsonSerdeV2;
import org.apache.samza.serializers.NoOpSerde;
import org.apache.samza.serializers.Serde;
import org.apache.samza.serializers.StringSerde;
import org.junit.Test;
import org.mockito.internal.util.reflection.Whitebox;

import static org.junit.Assert.*;

/**
 * Test for all {@link OperatorSpec}
 */
public class TestOperatorSpec {

  private static class MapWithWatermarkFn implements MapFunction<TestMessageEnvelope, TestOutputMessageEnvelope>, WatermarkFunction<TestOutputMessageEnvelope> {

    @Override
    public Collection<TestOutputMessageEnvelope> processWatermark(long watermark) {
      return null;
    }

    @Override
    public Long getOutputWatermark() {
      return null;
    }

    @Override
    public TestOutputMessageEnvelope apply(TestMessageEnvelope m) {
      return new TestOutputMessageEnvelope(m.getKey(), m.getMessage().hashCode());
    }
  }

  private static class MapWithScheduledFn implements MapFunction<TestMessageEnvelope, TestOutputMessageEnvelope>,
                                                     ScheduledFunction<String, TestOutputMessageEnvelope> {

    @Override
    public TestOutputMessageEnvelope apply(TestMessageEnvelope m) {
      return new TestOutputMessageEnvelope(m.getKey(), m.getMessage().hashCode());
    }

    @Override
    public void schedule(Scheduler<String> scheduler) {

    }

    @Override
    public Collection<TestOutputMessageEnvelope> onCallback(String key, long timestamp) {
      return null;
    }
  }

  private static class MapWithEnum implements MapFunction<TestMessageEnvelope, TestOutputMessageEnvelope> {
    private OperatorSpecTestUtils.TestEnum type;

    MapWithEnum(OperatorSpecTestUtils.TestEnum type) {
      this.type = type;
    }

    OperatorSpecTestUtils.TestEnum getType() {
      return this.type;
    }

    void setType(OperatorSpecTestUtils.TestEnum type) {
      this.type = type;
    }

    @Override
    public TestOutputMessageEnvelope apply(TestMessageEnvelope m) {
      return new TestOutputMessageEnvelope(m.getKey(), m.getMessage().hashCode());
    }
  }

  private static class TestJoinFunction implements JoinFunction<String, Object, Object, TestOutputMessageEnvelope> {
    @Override
    public TestOutputMessageEnvelope apply(Object message, Object otherMessage) {
      return new TestOutputMessageEnvelope(message.toString(), message.hashCode() + otherMessage.hashCode());
    }

    @Override
    public String getFirstKey(Object message) {
      return message.toString();
    }

    @Override
    public String getSecondKey(Object message) {
      return message.toString();
    }
  }

  private static class TestStreamTableJoinFunction implements StreamTableJoinFunction<String, Object, Object, TestOutputMessageEnvelope> {
    @Override
    public TestOutputMessageEnvelope apply(Object message, Object record) {
      return new TestOutputMessageEnvelope(message.toString(), message.hashCode() + record.hashCode());
    }

    @Override
    public String getMessageKey(Object message) {
      return message.toString();
    }

    @Override
    public String getRecordKey(Object record) {
      return record.toString();
    }
  }

  @Test
  public void testStreamOperatorSpecWithFlatMap() {
    FlatMapFunction<TestMessageEnvelope, TestOutputMessageEnvelope> flatMap = m -> {
      List<TestOutputMessageEnvelope> result = new ArrayList<>();
      result.add(new TestOutputMessageEnvelope(m.getKey(), m.getMessage().hashCode()));
      return result;
    };
    StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope> streamOperatorSpec =
        OperatorSpecs.createFlatMapOperatorSpec(flatMap, "op0");
    StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope> cloneOperatorSpec =
        (StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope>) OperatorSpecTestUtils.copyOpSpec(streamOperatorSpec);
    assertNotEquals(streamOperatorSpec, cloneOperatorSpec);
    assertTrue(streamOperatorSpec.isClone(cloneOperatorSpec));
    assertNotEquals(streamOperatorSpec.getTransformFn(), cloneOperatorSpec.getTransformFn());
    assertTrue(cloneOperatorSpec.getTransformFn() instanceof FlatMapFunction);
    assertNull(streamOperatorSpec.getWatermarkFn());
    assertNull(cloneOperatorSpec.getWatermarkFn());
    assertNull(streamOperatorSpec.getScheduledFn());
    assertNull(cloneOperatorSpec.getScheduledFn());
  }

  @Test
  public void testStreamOperatorSpecWithMap() {
    MapFunction<TestMessageEnvelope, TestOutputMessageEnvelope> mapFn =
        m -> new TestOutputMessageEnvelope(m.getKey(), m.getMessage().hashCode());
    StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope> streamOperatorSpec =
        OperatorSpecs.createMapOperatorSpec(mapFn, "op0");
    StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope> cloneOperatorSpec =
        (StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope>) OperatorSpecTestUtils.copyOpSpec(streamOperatorSpec);
    assertNotEquals(streamOperatorSpec, cloneOperatorSpec);
    assertTrue(streamOperatorSpec.isClone(cloneOperatorSpec));
    MapFunction userFn = (MapFunction) Whitebox.getInternalState(streamOperatorSpec, "mapFn");
    assertEquals(userFn, mapFn);
    assertNotEquals(streamOperatorSpec.getTransformFn(), cloneOperatorSpec.getTransformFn());
    MapFunction clonedUserFn = (MapFunction) Whitebox.getInternalState(cloneOperatorSpec, "mapFn");
    assertTrue(cloneOperatorSpec.getTransformFn() instanceof FlatMapFunction);
    assertTrue(clonedUserFn instanceof MapFunction);
    assertNotEquals(userFn, clonedUserFn);
    assertNull(streamOperatorSpec.getWatermarkFn());
    assertNull(cloneOperatorSpec.getWatermarkFn());
    assertNull(streamOperatorSpec.getScheduledFn());
    assertNull(cloneOperatorSpec.getScheduledFn());
  }

  @Test
  public void testStreamOperatorSpecWithFilter() {
    FilterFunction<TestMessageEnvelope> filterFn = m -> m.getKey().equals("key1");
    StreamOperatorSpec<TestMessageEnvelope, TestMessageEnvelope> streamOperatorSpec =
        OperatorSpecs.createFilterOperatorSpec(filterFn, "op0");
    StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope> cloneOperatorSpec =
        (StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope>) OperatorSpecTestUtils.copyOpSpec(streamOperatorSpec);
    assertNotEquals(streamOperatorSpec, cloneOperatorSpec);
    assertTrue(streamOperatorSpec.isClone(cloneOperatorSpec));
    FilterFunction userFn = (FilterFunction) Whitebox.getInternalState(streamOperatorSpec, "filterFn");
    assertEquals(userFn, filterFn);
    assertNotEquals(streamOperatorSpec.getTransformFn(), cloneOperatorSpec.getTransformFn());
    FilterFunction clonedUserFn = (FilterFunction) Whitebox.getInternalState(cloneOperatorSpec, "filterFn");
    assertTrue(cloneOperatorSpec.getTransformFn() instanceof FlatMapFunction);
    assertTrue(clonedUserFn instanceof FilterFunction);
    assertNotEquals(userFn, clonedUserFn);
    assertNull(streamOperatorSpec.getWatermarkFn());
    assertNull(cloneOperatorSpec.getWatermarkFn());
    assertNull(streamOperatorSpec.getScheduledFn());
    assertNull(cloneOperatorSpec.getScheduledFn());
  }

  @Test
  public void testInputOperatorSpec() {
    Serde<Object> objSerde = new Serde<Object>() {

      @Override
      public Object fromBytes(byte[] bytes) {
        return null;
      }

      @Override
      public byte[] toBytes(Object object) {
        return new byte[0];
      }
    };

    InputOperatorSpec inputOperatorSpec = new InputOperatorSpec(
        "mockStreamId", new StringSerde("UTF-8"), objSerde, null, true, "op0");
    InputOperatorSpec inputOpCopy = (InputOperatorSpec) OperatorSpecTestUtils.copyOpSpec(inputOperatorSpec);

    assertNotEquals("Expected deserialized copy of operator spec should not be the same as the original operator spec", inputOperatorSpec, inputOpCopy);
    assertTrue(inputOperatorSpec.isClone(inputOpCopy));

  }

  @Test
  public void testOutputOperatorSpec() {
    Serde<Object> objSerde = new Serde<Object>() {

      @Override
      public Object fromBytes(byte[] bytes) {
        return null;
      }

      @Override
      public byte[] toBytes(Object object) {
        return new byte[0];
      }
    };
    OutputStreamImpl<KV<String, Object>> outputStrmImpl = new OutputStreamImpl<>("mockStreamId", new StringSerde("UTF-8"), objSerde, true);
    OutputOperatorSpec<KV<String, Object>> outputOperatorSpec = new OutputOperatorSpec<>(outputStrmImpl, "op0");
    OutputOperatorSpec<KV<String, Object>> outputOpCopy = (OutputOperatorSpec<KV<String, Object>>) OperatorSpecTestUtils
        .copyOpSpec(outputOperatorSpec);
    assertNotEquals("Expected deserialized copy of operator spec should not be the same as the original operator spec", outputOperatorSpec, outputOpCopy);
    assertTrue(outputOperatorSpec.isClone(outputOpCopy));
  }

  @Test
  public void testSinkOperatorSpec() {
    SinkFunction<TestMessageEnvelope> sinkFn = (m, c, tc) -> System.out.print(m.toString());
    SinkOperatorSpec<TestMessageEnvelope> sinkOpSpec = new SinkOperatorSpec<>(sinkFn, "op0");
    SinkOperatorSpec<TestMessageEnvelope> sinkOpCopy = (SinkOperatorSpec<TestMessageEnvelope>) OperatorSpecTestUtils.copyOpSpec(sinkOpSpec);
    assertNotEquals("Expected deserialized copy of operator spec should not be the same as the original operator spec", sinkOpSpec, sinkOpCopy);
    assertTrue(sinkOpSpec.isClone(sinkOpCopy));
  }

  @Test
  public void testJoinOperatorSpec() {

    InputOperatorSpec leftOpSpec = new InputOperatorSpec(
        "test-input-1", new NoOpSerde<>(), new NoOpSerde<>(), null, false, "op0");
    InputOperatorSpec rightOpSpec = new InputOperatorSpec(
        "test-input-2", new NoOpSerde<>(), new NoOpSerde<>(), null, false, "op1");

    Serde<Object> objSerde = new Serde<Object>() {

      @Override
      public Object fromBytes(byte[] bytes) {
        return null;
      }

      @Override
      public byte[] toBytes(Object object) {
        return new byte[0];
      }
    };

    JoinFunction<String, Object, Object, TestOutputMessageEnvelope> joinFn = new TestJoinFunction();
    JoinOperatorSpec<String, Object, Object, TestOutputMessageEnvelope> joinOperatorSpec =
        new JoinOperatorSpec<>(leftOpSpec, rightOpSpec, joinFn, new StringSerde("UTF-8"), objSerde, objSerde, 50000, "op2");
    JoinOperatorSpec<String, Object, Object, TestOutputMessageEnvelope> joinOpCopy =
        (JoinOperatorSpec<String, Object, Object, TestOutputMessageEnvelope>) OperatorSpecTestUtils.copyOpSpec(joinOperatorSpec);
    assertNotEquals("Expected deserialized copy of operator spec should not be the same as the original operator spec", joinOperatorSpec, joinOpCopy);
    assertTrue(joinOperatorSpec.isClone(joinOpCopy));
    assertTrue(joinOpCopy.getLeftInputOpSpec().isClone(leftOpSpec));
    assertTrue(joinOpCopy.getRightInputOpSpec().isClone(rightOpSpec));
  }

  @Test
  public void testStreamTableJoinOperatorSpec() {
    StreamTableJoinFunction<String, Object, Object, TestOutputMessageEnvelope> joinFn = new TestStreamTableJoinFunction();

    String tableId = "t1";

    StreamTableJoinOperatorSpec<String, Object, Object, TestOutputMessageEnvelope> joinOperatorSpec =
        new StreamTableJoinOperatorSpec<>(tableId, joinFn, "join-3", 1, null, "3");

    StreamTableJoinOperatorSpec<String, Object, Object, TestOutputMessageEnvelope> joinOpSpecCopy =
        (StreamTableJoinOperatorSpec<String, Object, Object, TestOutputMessageEnvelope>) OperatorSpecTestUtils.copyOpSpec(joinOperatorSpec);
    assertNotEquals(joinOpSpecCopy, joinOperatorSpec);
    assertEquals(joinOpSpecCopy.getOpId(), joinOperatorSpec.getOpId());
    assertEquals(joinOpSpecCopy.getTableId(), joinOperatorSpec.getTableId());
    assertArrayEquals(joinOpSpecCopy.getArgs(), joinOperatorSpec.getArgs());
  }

  @Test
  public void testSendToTableOperatorSpec() {
    String tableId = "t1";
    SendToTableOperatorSpec<String, Integer> sendOpSpec =
        new SendToTableOperatorSpec<>(tableId, "output-1", 1, null, "3");
    SendToTableOperatorSpec<String, Integer> sendToCopy = (SendToTableOperatorSpec<String, Integer>) OperatorSpecTestUtils
        .copyOpSpec(sendOpSpec);
    assertNotEquals(sendToCopy, sendOpSpec);
    assertEquals(sendToCopy.getOpId(), sendOpSpec.getOpId());
    assertArrayEquals(sendToCopy.getArgs(), sendOpSpec.getArgs());
    assertTrue(sendToCopy.getTableId().equals(sendOpSpec.getTableId()));
  }

  @Test
  public void testBroadcastOperatorSpec() {
    OutputStreamImpl<TestOutputMessageEnvelope> outputStream =
        new OutputStreamImpl<>("output-0", new StringSerde("UTF-8"), new JsonSerdeV2<TestOutputMessageEnvelope>(), true);
    BroadcastOperatorSpec<TestOutputMessageEnvelope> broadcastOpSpec = new BroadcastOperatorSpec<>(outputStream, "broadcast-1");
    BroadcastOperatorSpec<TestOutputMessageEnvelope> broadcastOpCopy = (BroadcastOperatorSpec<TestOutputMessageEnvelope>) OperatorSpecTestUtils
        .copyOpSpec(broadcastOpSpec);
    assertNotEquals(broadcastOpCopy, broadcastOpSpec);
    assertEquals(broadcastOpCopy.getOpId(), broadcastOpSpec.getOpId());
    assertTrue(broadcastOpCopy.getOutputStream() != broadcastOpSpec.getOutputStream());
    assertEquals(broadcastOpCopy.getOutputStream().getStreamId(), broadcastOpSpec.getOutputStream().getStreamId());
    assertEquals(broadcastOpCopy.getOutputStream().isKeyed(), broadcastOpSpec.getOutputStream().isKeyed());
  }

  @Test
  public void testMapStreamOperatorSpecWithWatermark() {
    MapWithWatermarkFn testMapFn = new MapWithWatermarkFn();

    StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope> streamOperatorSpec =
        OperatorSpecs.createMapOperatorSpec(testMapFn, "op0");
    StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope> cloneOperatorSpec =
        (StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope>) OperatorSpecTestUtils.copyOpSpec(streamOperatorSpec);
    assertNotEquals(streamOperatorSpec, cloneOperatorSpec);
    assertTrue(streamOperatorSpec.isClone(cloneOperatorSpec));
    assertNotEquals(streamOperatorSpec.getTransformFn(), cloneOperatorSpec.getTransformFn());
    assertEquals(streamOperatorSpec.getWatermarkFn(), testMapFn);
    assertNotNull(cloneOperatorSpec.getWatermarkFn());
    assertNotEquals(cloneOperatorSpec.getTransformFn(), cloneOperatorSpec.getWatermarkFn());
    assertNull(streamOperatorSpec.getScheduledFn());
    assertNull(cloneOperatorSpec.getScheduledFn());
  }

  @Test
  public void testMapStreamOperatorSpecWithScheduledFunction() {
    MapWithScheduledFn testMapFn = new MapWithScheduledFn();

    StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope> streamOperatorSpec =
        OperatorSpecs.createMapOperatorSpec(testMapFn, "op0");
    StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope> cloneOperatorSpec =
        (StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope>) OperatorSpecTestUtils.copyOpSpec(streamOperatorSpec);
    assertNotEquals(streamOperatorSpec, cloneOperatorSpec);
    assertTrue(streamOperatorSpec.isClone(cloneOperatorSpec));
    assertNotEquals(streamOperatorSpec.getTransformFn(), cloneOperatorSpec.getTransformFn());
    assertNull(streamOperatorSpec.getWatermarkFn());
    assertNull(cloneOperatorSpec.getWatermarkFn());
    assertNotEquals(cloneOperatorSpec.getTransformFn(), cloneOperatorSpec.getWatermarkFn());
    assertEquals(streamOperatorSpec.getScheduledFn(), testMapFn);
    assertNotNull(cloneOperatorSpec.getScheduledFn());
    assertNotEquals(streamOperatorSpec.getScheduledFn(), cloneOperatorSpec.getScheduledFn());
  }

  @Test
  public void testStreamOperatorSpecWithMapAndListInClosure() {
    List<Integer> integers = new ArrayList<>(1);
    integers.add(0, 100);
    List<String> keys = new ArrayList<>(1);
    keys.add(0, "test-1");
    MapFunction<TestMessageEnvelope, TestOutputMessageEnvelope> mapFn =
        m -> new TestOutputMessageEnvelope(keys.get(m.getKey().hashCode() % 1), integers.get(m.getMessage().hashCode() % 1));
    StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope> streamOperatorSpec =
        OperatorSpecs.createMapOperatorSpec(mapFn, "op0");
    StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope> cloneOperatorSpec =
        (StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope>) OperatorSpecTestUtils.copyOpSpec(streamOperatorSpec);
    assertNotEquals(streamOperatorSpec, cloneOperatorSpec);
    assertTrue(streamOperatorSpec.isClone(cloneOperatorSpec));
    MapFunction userFn = (MapFunction) Whitebox.getInternalState(streamOperatorSpec, "mapFn");
    assertEquals(userFn, mapFn);
    assertNotEquals(streamOperatorSpec.getTransformFn(), cloneOperatorSpec.getTransformFn());
    MapFunction clonedUserFn = (MapFunction) Whitebox.getInternalState(cloneOperatorSpec, "mapFn");
    assertTrue(cloneOperatorSpec.getTransformFn() instanceof FlatMapFunction);
    assertTrue(clonedUserFn instanceof MapFunction);
    assertNotEquals(userFn, clonedUserFn);

    // verify changing the values in the original keys and integers list will change the result of the original map function
    TestMessageEnvelope mockImsg = new TestMessageEnvelope("input-key-x", new String("value-x"));
    assertEquals(((MapFunction) userFn).apply(mockImsg), new TestOutputMessageEnvelope("test-1", 100));
    integers.set(0, 200);
    keys.set(0, "test-2");
    assertEquals(((MapFunction) userFn).apply(mockImsg), new TestOutputMessageEnvelope("test-2", 200));
    // verify that the cloned map function uses a different copy of lists and still yields the same result
    assertEquals(((MapFunction) clonedUserFn).apply(mockImsg), new TestOutputMessageEnvelope("test-1", 100));
  }

  @Test
  public void testStreamOperatorSpecWithMapWithFunctionReference() {
    MapFunction<KV<String, Object>, Object> mapFn = KV::getValue;
    StreamOperatorSpec<KV<String, Object>, Object> streamOperatorSpec =
        OperatorSpecs.createMapOperatorSpec(mapFn, "op0");
    StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope> cloneOperatorSpec =
        (StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope>) OperatorSpecTestUtils.copyOpSpec(streamOperatorSpec);
    assertNotEquals(streamOperatorSpec, cloneOperatorSpec);
    assertTrue(streamOperatorSpec.isClone(cloneOperatorSpec));
    MapFunction userFn = (MapFunction) Whitebox.getInternalState(streamOperatorSpec, "mapFn");
    assertEquals(userFn, mapFn);
    assertNotEquals(streamOperatorSpec.getTransformFn(), cloneOperatorSpec.getTransformFn());
    MapFunction clonedUserFn = (MapFunction) Whitebox.getInternalState(cloneOperatorSpec, "mapFn");
    assertTrue(cloneOperatorSpec.getTransformFn() instanceof FlatMapFunction);
    assertTrue(clonedUserFn instanceof MapFunction);
    assertNotEquals(userFn, clonedUserFn);
  }

  @Test
  public void testStreamOperatorSpecWithMapWithEnum() {
    MapFunction<TestMessageEnvelope, TestOutputMessageEnvelope> mapFn = new MapWithEnum(OperatorSpecTestUtils.TestEnum.One);
    StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope> streamOperatorSpec =
        OperatorSpecs.createMapOperatorSpec(mapFn, "op0");
    assertTrue(streamOperatorSpec instanceof MapOperatorSpec);
    StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope> cloneOperatorSpec =
        (StreamOperatorSpec<TestMessageEnvelope, TestOutputMessageEnvelope>) OperatorSpecTestUtils.copyOpSpec(streamOperatorSpec);
    assertNotEquals(streamOperatorSpec, cloneOperatorSpec);
    assertTrue(streamOperatorSpec.isClone(cloneOperatorSpec));
    MapFunction userFn = (MapFunction) Whitebox.getInternalState(streamOperatorSpec, "mapFn");
    assertEquals(userFn, mapFn);
    assertNotEquals(streamOperatorSpec.getTransformFn(), cloneOperatorSpec.getTransformFn());
    MapFunction clonedUserFn = (MapFunction) Whitebox.getInternalState(cloneOperatorSpec, "mapFn");
    assertTrue(cloneOperatorSpec.getTransformFn() instanceof FlatMapFunction);
    assertTrue(clonedUserFn instanceof MapWithEnum);
    assertNotEquals(userFn, clonedUserFn);
    // originally the types should be the same
    assertTrue(((MapWithEnum) userFn).getType() == ((MapWithEnum) clonedUserFn).getType());
    // after changing the type of the cloned user function, the types are different now
    ((MapWithEnum) clonedUserFn).setType(OperatorSpecTestUtils.TestEnum.Two);
    assertTrue(((MapWithEnum) userFn).getType() != ((MapWithEnum) clonedUserFn).getType());
  }
}


text:
var der = require('./der');
var fs = require('fs');
require('should');

suite('der', function(){
   suite('decoder-pfx-root', function() {

       var dec = new der.Decoder();
       function readAndDecode(filename, callback) {
           fs.readFile(filename, function(err,data) {
               if (err) {
                   return callback(err);
               }
               var elements = dec.parse(data);
               callback(null, elements);
           });
       }

       test('should have one root element', function(done) {
           readAndDecode('test/util/certificates/client-x509-rsa.pfx', function(err,elements) {
               if (err) {
                   return done(err);
               }

               elements.should.have.length(1);
               done();
           });
       });

       test('should have two or three children', function(done) {
           readAndDecode('test/util/certificates/client-x509-rsa.pfx', function(err,elements) {
               if (err) {
                   return done(err);
               }

               var children = dec.parse(elements[0].buffer);
               children.length.should.be.within(2,3);
               done();
           });
       });

       test('should have version number 3 and a sequence', function(done) {
           readAndDecode('test/util/certificates/client-x509-rsa.pfx', function(err,elements) {
               if (err) {
                   return done(err);
               }

               elements[0].should.have.property('tag', der.SEQUENCE);
               var children = dec.parse(elements[0].buffer);
               children[0].should.have.property('tag', der.INTEGER);
               children[0].should.have.property('value', 3);
               children[1].should.have.property('tag', der.SEQUENCE);
               done();
           });
       });
   });
});

redpajama_set_name: RedPajamaGithub


text:
using ForumSystem.Data.Common.Repository;
using ForumSystem.Data.Models;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ForumSystem.Web.Controllers
{
    [Authorize]
    public class VotesController : Controller
    {
        IRepository<PostVote> votes;

        public VotesController(IRepository<PostVote> votes)
        {
            this.votes = votes;
        }

        [HttpPost]
        public ActionResult Vote(int postId, int voteType)
        {
            if (voteType > 1)
            {
                voteType = 1;
            }
            if (voteType < -1)
            {
                voteType = -1;
            }

            var userId = this.User.Identity.GetUserId();
            var vote = this.votes.All().FirstOrDefault(x => x.AuthorId == userId && x.PostId == postId);
            if (vote == null)
            {
                vote = new PostVote
                {
                    AuthorId = userId,
                    PostId = postId,
                    Type = (VoteType)voteType
                };
                this.votes.Add(vote);
            }
            else
            {
                if (vote.Type != (VoteType)voteType)
                {
                    vote.Type = VoteType.Neutral;
                }
                else if(vote.Type == VoteType.Neutral)
                {
                    vote.Type = (VoteType)voteType;
                }
            }

            this.votes.SaveChanges();
            var postVotes = this.votes.All()
                .Where(x => x.PostId == postId)
                .Sum(x => (int)x.Type);

            return this.Json(new { Count = postVotes });
        }
    }
}


text:
require 'faraday'
require 'json'

module MailChimp3
  class Endpoint
    attr_reader :url, :last_result

    def initialize(oauth_access_token: nil, basic_auth_key: nil, dc: nil, url: nil, version: 3)
      @oauth_access_token = oauth_access_token
      @basic_auth_key = basic_auth_key
      @dc = dc
      @dc ||= @basic_auth_key.split('-').last if @basic_auth_key
      @url = url || _build_url
      @version = version
      fail Errors::DataCenterRequiredError, 'You must pass dc.' unless @dc || @url
      @cache = {}
    end

    def method_missing(method_name, *_args)
      _build_endpoint(method_name.to_s)
    end

    def [](id)
      _build_endpoint(id.to_s)
    end

    def get(params = {})
      @last_result = _connection.get(@url, params)
      _build_response(@last_result)
    end

    def post(body = {})
      @last_result = _connection.post(@url) do |req|
        body[:apikey] = @oauth_access_token || @basic_auth_key if @version == 2
        req.body = body.to_json
      end
      if @last_result.status == 204
        true
      else
        _build_response(@last_result)
      end
    end

    def patch(body = {})
      @last_result = _connection.patch(@url) do |req|
        req.body = body.to_json
      end
      _build_response(@last_result)
    end

    def put(body = {})
      @last_result = _connection.put(@url) do |req|
        req.body = body.to_json
      end
      _build_response(@last_result)
    end

    def delete
      @last_result = _connection.delete(@url)
      if @last_result.status == 204
        true
      else
        _build_response(@last_result)
      end
    end

    def v2
      self.class.new(
        url: _build_v2_url,
        basic_auth_key: @basic_auth_key,
        oauth_access_token: @oauth_access_token,
        version: 2
      )
    end

    private

    def _build_response(result)
      body = _parse_body(result)
      case (status = result.status)
      when 200..299
        body
      when 400
        fail Errors::BadRequest, status: status, body: body
      when 401
        fail Errors::Unauthorized, status: status, body: body
      when 403
        fail Errors::Forbidden, status: status, body: body
      when 404
        fail Errors::NotFound, status: status, body: body
      when 405
        fail Errors::MethodNotAllowed, status: status, body: body
      when 422
        fail Errors::UnprocessableEntity, status: status, body: body
      when 400..499
        fail Errors::ClientError, status: status, body: body
      when 500
        fail Errors::InternalServerError, status: status, body: body
      when 500..599
        fail Errors::ServerError, status: status, body: body
      else
        fail "unknown status #{status}"
      end
    end

    def _parse_body(result)
      JSON.parse(result.body)
    rescue JSON::ParserError
      raise Errors::ServerError, status: result.status, body: result.body
    end

    def _build_endpoint(path)
      @cache[path] ||= begin
        self.class.new(
          url: File.join(url, path.to_s),
          basic_auth_key: @basic_auth_key,
          oauth_access_token: @oauth_access_token,
          version: @version
        )
      end
    end

    def _build_url
      "https://#{@dc}.api.mailchimp.com/3.0/"
    end

    def _build_v2_url
      "https://#{@dc}.api.mailchimp.com/2.0/"
    end

    def _connection
      @connection ||= Faraday.new(url: url) do |faraday|
        if @basic_auth_key
          faraday.request :basic_auth, '', @basic_auth_key
        elsif @oauth_access_token
          faraday.headers['Authorization'] = "Bearer #{@oauth_access_token}"
        else
          fail Errors::AuthRequiredError, "You must specify either HTTP basic auth credentials or an OAuth2 access token."
        end
        faraday.adapter :excon
      end
    end
  end
end


text:
use gfx::format;
use gfx::handle::*;
use gfx::preset::blend;
use gfx::pso::buffer::*;
use gfx::pso::*;
use gfx::shade::*;
use gfx::state::*;
use gfx::traits::{FactoryExt, Pod};
use gfx::*;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use std::io::prelude::*;
use std::marker::PhantomData;
use std::path::Path;
use std::rc::Rc;

use crate::context::DebugId;
use crate::error::*;
use crate::graphics;
use crate::Context;

/// A type for empty shader data for shaders that do not require any additional
/// data to be sent to the GPU
#[derive(Clone, Copy, Debug)]
pub struct EmptyConst;

impl<F> Structure<F> for EmptyConst {
    fn query(_name: &str) -> Option<Element<F>> {
        None
    }
}

unsafe impl Pod for EmptyConst {}

/// An enum for specifying default and custom blend modes
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BlendMode {
    /// When combining two fragments, add their values together, saturating
    /// at 1.0
    Add,
    /// When combining two fragments, subtract the source value from the
    /// destination value
    Subtract,
    /// When combining two fragments, add the value of the source times its
    /// alpha channel with the value of the destination multiplied by the inverse
    /// of the source alpha channel. Has the usual transparency effect: mixes the
    /// two colors using a fraction of each one specified by the alpha of the source.
    Alpha,
    /// When combining two fragments, subtract the destination color from a constant
    /// color using the source color as weight. Has an invert effect with the constant
    /// color as base and source color controlling displacement from the base color.
    /// A white source color and a white value results in plain invert. The output
    /// alpha is same as destination alpha.
    Invert,
    /// When combining two fragments, multiply their values together.
    Multiply,
    /// When combining two fragments, choose the source value
    Replace,
    /// When combining two fragments, choose the lighter value
    Lighten,
    /// When combining two fragments, choose the darker value
    Darken,
}

impl From<BlendMode> for Blend {
    fn from(bm: BlendMode) -> Self {
        match bm {
            BlendMode::Add => blend::ADD,
            BlendMode::Subtract => Blend {
                color: BlendChannel {
                    equation: Equation::Sub,
                    source: Factor::One,
                    destination: Factor::One,
                },
                alpha: BlendChannel {
                    equation: Equation::Sub,
                    source: Factor::One,
                    destination: Factor::One,
                },
            },
            BlendMode::Alpha => blend::ALPHA,
            BlendMode::Invert => blend::INVERT,
            BlendMode::Multiply => blend::MULTIPLY,
            BlendMode::Replace => blend::REPLACE,
            BlendMode::Lighten => Blend {
                color: BlendChannel {
                    equation: Equation::Max,
                    source: Factor::One,
                    destination: Factor::One,
                },
                alpha: BlendChannel {
                    equation: Equation::Add,
                    source: Factor::ZeroPlus(BlendValue::SourceAlpha),
                    destination: Factor::OneMinus(BlendValue::SourceAlpha),
                },
            },
            BlendMode::Darken => Blend {
                color: BlendChannel {
                    equation: Equation::Min,
                    source: Factor::One,
                    destination: Factor::One,
                },
                alpha: BlendChannel {
                    equation: Equation::Add,
                    source: Factor::ZeroPlus(BlendValue::SourceAlpha),
                    destination: Factor::OneMinus(BlendValue::SourceAlpha),
                },
            },
        }
    }
}

/// A struct to easily store a set of pipeline state objects that are
/// associated with a specific shader program.
///
/// In gfx, because Vulkan and DX are more strict
/// about how blend modes work than GL is, blend modes are
/// baked in as a piece of state for a PSO and you can't change it
/// dynamically. After chatting with @kvark on IRC and looking
/// how he does it in three-rs, the best way to change blend
/// modes is to just make multiple PSOs with respective blend modes baked in.
/// The `PsoSet` struct is basically just a hash map for easily
/// storing each shader set's PSOs and then retrieving them based
/// on a [`BlendMode`](enum.BlendMode.html).
struct PsoSet<Spec, C>
where
    Spec: graphics::BackendSpec,
    C: Structure<ConstFormat>,
{
    psos: HashMap<BlendMode, PipelineState<Spec::Resources, ConstMeta<C>>>,
}

impl<Spec, C> PsoSet<Spec, C>
where
    Spec: graphics::BackendSpec,
    C: Structure<ConstFormat>,
{
    pub fn new(cap: usize) -> Self {
        Self {
            psos: HashMap::with_capacity(cap),
        }
    }

    pub fn insert_mode(
        &mut self,
        mode: BlendMode,
        pso: PipelineState<Spec::Resources, ConstMeta<C>>,
    ) {
        let _ = self.psos.insert(mode, pso);
    }

    pub fn mode(
        &self,
        mode: &BlendMode,
    ) -> GameResult<&PipelineState<Spec::Resources, ConstMeta<C>>> {
        match self.psos.get(mode) {
            Some(pso) => Ok(pso),
            None => Err(GameError::RenderError(
                "Could not find a pipeline for the specified shader and BlendMode".into(),
            )),
        }
    }
}

/// An ID used by the ggez graphics context to uniquely identify a shader
pub type ShaderId = usize;

/// A `ShaderGeneric` reprensents a handle user-defined shader that can be used
/// with a ggez graphics context that is generic over `gfx::Resources`
///
/// As an end-user you shouldn't ever have to touch this and should use
/// [`Shader`](type.Shader.html) instead.
#[derive(Clone)]
pub struct ShaderGeneric<Spec: graphics::BackendSpec, C: Structure<ConstFormat>> {
    id: ShaderId,
    buffer: Buffer<Spec::Resources, C>,
    debug_id: DebugId,
}

/// A `Shader` represents a handle to a user-defined shader that can be used
/// with a ggez graphics context
pub type Shader<C> = ShaderGeneric<graphics::GlBackendSpec, C>;

pub(crate) fn create_shader<C, S, Spec>(
    vertex_source: &[u8],
    pixel_source: &[u8],
    consts: C,
    name: S,
    encoder: &mut Encoder<Spec::Resources, Spec::CommandBuffer>,
    factory: &mut Spec::Factory,
    multisample_samples: u8,
    blend_modes: Option<&[BlendMode]>,
    color_format: format::Format,
    debug_id: DebugId,
) -> GameResult<(ShaderGeneric<Spec, C>, Box<dyn ShaderHandle<Spec>>)>
where
    C: 'static + Pod + Structure<ConstFormat> + Clone + Copy,
    S: Into<String>,
    Spec: graphics::BackendSpec + 'static,
{
    let buffer = factory.create_constant_buffer(1);

    encoder.update_buffer(&buffer, &[consts], 0)?;

    let default_mode = vec![BlendMode::Alpha];
    let blend_modes = blend_modes.unwrap_or(&default_mode[..]);

    let mut psos = PsoSet::new(blend_modes.len());
    let name: String = name.into();
    for mode in blend_modes {
        let init = ConstInit::<C>(
            graphics::pipe::Init {
                out: (
                    "Target0",
                    color_format,
                    ColorMask::all(),
                    Some((*mode).into()),
                ),
                ..graphics::pipe::new()
            },
            name.clone(),
            PhantomData,
        );
        let set = factory.create_shader_set(vertex_source, pixel_source)?;
        let sample = if multisample_samples > 1 {
            Some(MultiSample)
        } else {
            None
        };
        let rasterizer = Rasterizer {
            front_face: FrontFace::CounterClockwise,
            cull_face: CullFace::Nothing,
            method: RasterMethod::Fill,
            offset: None,
            samples: sample,
        };

        let pso = factory.create_pipeline_state(&set, Primitive::TriangleList, rasterizer, init)?;
        psos.insert_mode(*mode, pso);
    }

    let program = ShaderProgram {
        buffer: buffer.clone(),
        psos,
        active_blend_mode: blend_modes[0],
    };
    let draw: Box<dyn ShaderHandle<Spec>> = Box::new(program);

    let id = 0;
    let shader = ShaderGeneric {
        id,
        buffer,
        debug_id,
    };

    Ok((shader, draw))
}

impl<Spec, C> ShaderGeneric<Spec, C>
where
    Spec: graphics::BackendSpec,
    C: 'static + Pod + Structure<ConstFormat> + Clone + Copy,
{
    /// Create a new `Shader` given a gfx pipeline object
    ///
    /// In order to use a specific blend mode when this shader is being
    /// used, you must include that blend mode as part of the
    /// `blend_modes` parameter at creation. If `None` is given, only the
    /// default [`Alpha`](enum.BlendMode.html#variant.Alpha) blend mode is used.
    pub fn new<P: AsRef<Path>, S: Into<String>>(
        ctx: &mut Context,
        vertex_path: P,
        pixel_path: P,
        consts: C,
        name: S,
        blend_modes: Option<&[BlendMode]>,
    ) -> GameResult<Shader<C>> {
        let vertex_source = {
            let mut buf = Vec::new();
            let mut reader = ctx.filesystem.open(vertex_path)?;
            let _ = reader.read_to_end(&mut buf)?;
            buf
        };
        let pixel_source = {
            let mut buf = Vec::new();
            let mut reader = ctx.filesystem.open(pixel_path)?;
            let _ = reader.read_to_end(&mut buf)?;
            buf
        };
        Shader::from_u8(
            ctx,
            &vertex_source,
            &pixel_source,
            consts,
            name,
            blend_modes,
        )
    }

    /// Create a new `Shader` directly from source given a gfx pipeline
    /// object
    ///
    /// In order to use a specific blend mode when this shader is being
    /// used, you must include that blend mode as part of the
    /// `blend_modes` parameter at creation. If `None` is given, only the
    /// default [`Alpha`](enum.BlendMode.html#variant.Alpha) blend mode is used.
    pub fn from_u8<S: Into<String>>(
        ctx: &mut Context,
        vertex_source: &[u8],
        pixel_source: &[u8],
        consts: C,
        name: S,
        blend_modes: Option<&[BlendMode]>,
    ) -> GameResult<Shader<C>> {
        let debug_id = DebugId::get(ctx);
        let color_format = ctx.gfx_context.color_format();
        let (mut shader, draw) = create_shader(
            vertex_source,
            pixel_source,
            consts,
            name,
            &mut ctx.gfx_context.encoder,
            &mut *ctx.gfx_context.factory,
            ctx.gfx_context.multisample_samples,
            blend_modes,
            color_format,
            debug_id,
        )?;
        shader.id = ctx.gfx_context.shaders.len();
        ctx.gfx_context.shaders.push(draw);

        Ok(shader)
    }
}

impl<C> Shader<C>
where
    C: 'static + Pod + Structure<ConstFormat> + Clone + Copy,
{
    /// Send data to the GPU for use with the `Shader`
    pub fn send(&self, ctx: &mut Context, consts: C) -> GameResult {
        ctx.gfx_context
            .encoder
            .update_buffer(&self.buffer, &[consts], 0)?;
        Ok(())
    }

    /// Gets the shader ID for the `Shader` which is used by the
    /// graphics context for identifying shaders in its cache
    pub fn shader_id(&self) -> ShaderId {
        self.id
    }
}

impl<Spec, C> fmt::Debug for ShaderGeneric<Spec, C>
where
    Spec: graphics::BackendSpec,
    C: Structure<ConstFormat>,
{
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "<Shader[{}]: {:p}>", self.id, self)
    }
}

struct ShaderProgram<Spec: graphics::BackendSpec, C: Structure<ConstFormat>> {
    buffer: Buffer<Spec::Resources, C>,
    psos: PsoSet<Spec, C>,
    active_blend_mode: BlendMode,
}

impl<Spec, C> fmt::Debug for ShaderProgram<Spec, C>
where
    Spec: graphics::BackendSpec,
    C: Structure<ConstFormat>,
{
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "<ShaderProgram: {:p}>", self)
    }
}

/// A trait that is used to create trait objects to abstract away the
/// `gfx::Structure<ConstFormat>` type of the constant data for drawing
pub trait ShaderHandle<Spec: graphics::BackendSpec>: fmt::Debug {
    /// Draw with the current Shader
    fn draw(
        &self,
        encoder: &mut Encoder<Spec::Resources, Spec::CommandBuffer>,
        slice: &Slice<Spec::Resources>,
        data: &graphics::pipe::Data<Spec::Resources>,
    ) -> GameResult;

    /// Sets the shader program's blend mode
    fn set_blend_mode(&mut self, mode: BlendMode) -> GameResult;

    /// Gets the shader program's current blend mode
    fn blend_mode(&self) -> BlendMode;
}

impl<Spec, C> ShaderHandle<Spec> for ShaderProgram<Spec, C>
where
    Spec: graphics::BackendSpec,
    C: Structure<ConstFormat>,
{
    fn draw(
        &self,
        encoder: &mut Encoder<Spec::Resources, Spec::CommandBuffer>,
        slice: &Slice<Spec::Resources>,
        data: &graphics::pipe::Data<Spec::Resources>,
    ) -> GameResult {
        let pso = self.psos.mode(&self.active_blend_mode)?;
        encoder.draw(slice, pso, &ConstData(data, &self.buffer));
        Ok(())
    }

    fn set_blend_mode(&mut self, mode: BlendMode) -> GameResult {
        let _ = self.psos.mode(&mode)?;
        self.active_blend_mode = mode;
        Ok(())
    }

    fn blend_mode(&self) -> BlendMode {
        self.active_blend_mode
    }
}

/// A lock for RAII shader regions. The shader automatically gets cleared once
/// the lock goes out of scope, restoring the previous shader (if any).
///
/// Essentially, binding a [`Shader`](type.Shader.html) will return one of these,
/// and the shader will remain active as long as this object exists.  When this is
/// dropped, the previous shader is restored.
#[derive(Debug, Clone)]
pub struct ShaderLock {
    cell: Rc<RefCell<Option<ShaderId>>>,
    previous_shader: Option<ShaderId>,
}

impl Drop for ShaderLock {
    fn drop(&mut self) {
        *self.cell.borrow_mut() = self.previous_shader;
    }
}

/// Use a shader until the returned lock goes out of scope
pub fn use_shader<C>(ctx: &mut Context, ps: &Shader<C>) -> ShaderLock
where
    C: Structure<ConstFormat>,
{
    ps.debug_id.assert(ctx);
    let cell = Rc::clone(&ctx.gfx_context.current_shader);
    let previous_shader = *cell.borrow();
    set_shader(ctx, ps);
    ShaderLock {
        cell,
        previous_shader,
    }
}

/// Set the current shader for the `Context` to render with
pub fn set_shader<C>(ctx: &mut Context, ps: &Shader<C>)
where
    C: Structure<ConstFormat>,
{
    ps.debug_id.assert(ctx);
    *ctx.gfx_context.current_shader.borrow_mut() = Some(ps.id);
}

/// Clears the the current shader for the `Context`, restoring the default shader.
///
/// However, calling this and then dropping a [`ShaderLock`](struct.ShaderLock.html)
/// will still set the shader to whatever was set when the `ShaderLock` was created.
pub fn clear_shader(ctx: &mut Context) {
    *ctx.gfx_context.current_shader.borrow_mut() = None;
}

#[derive(Debug)]
struct ConstMeta<C: Structure<ConstFormat>>(graphics::pipe::Meta, ConstantBuffer<C>);

#[derive(Debug)]
struct ConstData<'a, R: Resources, C: 'a>(&'a graphics::pipe::Data<R>, &'a Buffer<R, C>);

impl<'a, R, C> PipelineData<R> for ConstData<'a, R, C>
where
    R: Resources,
    C: Structure<ConstFormat>,
{
    type Meta = ConstMeta<C>;

    fn bake_to(
        &self,
        out: &mut RawDataSet<R>,
        meta: &Self::Meta,
        man: &mut Manager<R>,
        access: &mut AccessInfo<R>,
    ) {
        self.0.bake_to(out, &meta.0, man, access);
        meta.1.bind_to(out, self.1, man, access);
    }
}

#[derive(Debug)]
struct ConstInit<'a, C>(graphics::pipe::Init<'a>, String, PhantomData<C>);

impl<'a, C> PipelineInit for ConstInit<'a, C>
where
    C: Structure<ConstFormat>,
{
    type Meta = ConstMeta<C>;

    fn link_to<'s>(
        &self,
        desc: &mut Descriptor,
        info: &'s ProgramInfo,
    ) -> Result<Self::Meta, InitError<&'s str>> {
        let mut meta1 = ConstantBuffer::<C>::new();

        let mut index = None;
        for (i, cb) in info.constant_buffers.iter().enumerate() {
            match meta1.link_constant_buffer(cb, &self.1.as_str()) {
                Some(Ok(d)) => {
                    assert!(meta1.is_active());
                    desc.constant_buffers[cb.slot as usize] = Some(d);
                    index = Some(i);
                    break;
                }
                Some(Err(e)) => return Err(InitError::ConstantBuffer(&cb.name, Some(e))),
                None => (),
            }
        }

        if let Some(index) = index {
            // create a local clone of the program info so that we can remove
            // the var we found from the `constant_buffer`
            let mut program_info = info.clone();
            let _ = program_info.constant_buffers.remove(index);

            let meta0 = match self.0.link_to(desc, &program_info) {
                Ok(m) => m,
                Err(e) => {
                    // unfortunately... the error lifetime is bound to the
                    // lifetime of our cloned program info which is bad since it
                    // will go out of scope at the end of the function, so lets
                    // convert the error to one that is bound to the lifetime of
                    // the program info that was passed in!
                    macro_rules! fixlifetimes {
                        ($e:ident {
                            $( $ty:path => $a:ident, )*
                        }) => {{
                            match $e {
                                $( $ty(name, _) => {
                                    let var = info.$a.iter().find(|v| v.name == name).unwrap();
                                    // We can do better with the error data...
                                    return Err($ty(&var.name, None));
                                } )*
                            }
                        }}
                    }
                    fixlifetimes!(e {
                        InitError::VertexImport => vertex_attributes,
                        InitError::ConstantBuffer => constant_buffers,
                        InitError::GlobalConstant => globals,
                        InitError::ResourceView => textures,
                        InitError::UnorderedView => unordereds,
                        InitError::Sampler => samplers,
                        InitError::PixelExport => outputs,
                    })
                }
            };

            Ok(ConstMeta(meta0, meta1))
        } else {
            Ok(ConstMeta(self.0.link_to(desc, info)?, meta1))
        }
    }
}


text:
int fixup_exception(struct pt_regs *regs)
{
	const struct exception_table_entry *fixup;
	unsigned long pc = instruction_pointer(regs);

	fixup = search_exception_tables(pc);
	if (fixup)
		regs->ctx.CurrPC = fixup->fixup;

	return fixup != NULL;
}


text:
<?php
$script = <<<JS
function onDiv(url)
{
$("#content").html('<object type="text/html" data="'+url+'" ></object>');

}
JS;
$this->registerJs($script, \yii\web\View::POS_HEAD);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSpider.Data.DatabaseConnection;
using WebSpider.Data.DatabaseManager;
using WebSpider.Objects.AdiExport;

namespace WebSpider.Data.AdiExport
{
    public class AdiInventoryManager : DataManager
    {
        #region [Constructror]
        public AdiInventoryManager(string ConnectionString)
        {
            // TODO: Complete member initialization
            this.ConnectionString = ConnectionString;
        }
        #endregion

        #region [ Get Data ]
        public List<ADI_Inventory> GetData()
        {
            String Query = "SELECT * FROM ADIInventory";
            OleDbDataManager oDm = new OleDbDataManager(ConnectionString, Query, true);
            return DataParser.ToList<ADI_Inventory>(oDm.GetTable());
        }

        public List<ADI_Inventory> GetData(String PART_NUM)
        {
            String Query = "SELECT * FROM ADIInventory WHERE PART_NUM = \"" + PART_NUM + "\"";
            OleDbDataManager oDm = new OleDbDataManager(ConnectionString, Query, true);
            //oDm.AddVarcharPara("PART_NUM", 4000, PART_NUM);
            return DataParser.ToList<ADI_Inventory>(oDm.GetTable());
        }
        #endregion

        #region [ Save ]
        public int Save(ADI_Inventory ADIInventory)
        {
            return Save(ADIInventory.ID, ADIInventory.PART_NUM, ADIInventory.TotalInventory, ADIInventory.Dallas, ADIInventory.DC_AtlantaHub
                , ADIInventory.DC_Dallas_Hub, ADIInventory.DC_Elk_Grove_Hub, ADIInventory.DC_Feura_Bush, ADIInventory.DC_Louisville_Hub
                , ADIInventory.DC_Reno_Hub, ADIInventory.DC_Richmond_Dist_Ctr, ADIInventory.Oklahama, ADIInventory.RemainingBranches, ADIInventory.LastUpdate);
        }

        public int Save(long ID, string PART_NUM, int? TotalInventory, int? Dallas, int? DC_AtlantaHub, int? DC_Dallas_Hub, int? DC_Elk_Grove_Hub, int? DC_Feura_Bush, int? DC_Louisville_Hub, int? DC_Reno_Hub, int? DC_Richmond_Dist_Ctr, int? Oklahama, int? RemainingBranches, DateTime? LastUpdate)
        {
            var inv = GetData(PART_NUM);
            var count = inv.Count();
            if (count == 0)
                return Insert(ID, PART_NUM, TotalInventory, Dallas, DC_AtlantaHub, DC_Dallas_Hub, DC_Elk_Grove_Hub, DC_Feura_Bush, DC_Louisville_Hub, DC_Reno_Hub, DC_Richmond_Dist_Ctr, Oklahama, RemainingBranches, LastUpdate);
            else
                return Update(inv[0].ID, PART_NUM, TotalInventory, Dallas, DC_AtlantaHub, DC_Dallas_Hub, DC_Elk_Grove_Hub, DC_Feura_Bush, DC_Louisville_Hub, DC_Reno_Hub, DC_Richmond_Dist_Ctr, Oklahama, RemainingBranches, LastUpdate);
        }

        #endregion

        #region [ Insert / Update ]

        public int Insert(long ID, string PART_NUM, int? TotalInventory, int? Dallas, int? DC_AtlantaHub, int? DC_Dallas_Hub, int? DC_Elk_Grove_Hub
            , int? DC_Feura_Bush, int? DC_Louisville_Hub, int? DC_Reno_Hub, int? DC_Richmond_Dist_Ctr, int? Oklahama, int? RemainingBranches, DateTime? LastUpdate)
        {
            String Query = "INSERT INTO ADIInventory (PART_NUM, TotalInventory, Dallas, DC_AtlantaHub, DC_Dallas_Hub, DC_Elk_Grove_Hub, DC_Feura_Bush, DC_Louisville_Hub, DC_Reno_Hub, DC_Richmond_Dist_Ctr, Oklahama, RemainingBranches, LastUpdate)"
                + " VALUES ( @PART_NUM, @TotalInventory, @Dallas, @DC_AtlantaHub, @DC_Dallas_Hub, @DC_Elk_Grove_Hub, @DC_Feura_Bush, @DC_Louisville_Hub, @DC_Reno_Hub, @DC_Richmond_Dist_Ctr, @Oklahama, @RemainingBranches, @LastUpdate)";
            OleDbDataManager oDm = new OleDbDataManager(ConnectionString, Query, true);
            //oDm.AddIntegerBigPara("ID", ID);
            oDm.AddVarcharPara("PART_NUM", 4000, PART_NUM);
            oDm.AddIntegerPara("TotalInventory", TotalInventory);
            oDm.AddIntegerPara("Dallas", Dallas);
            oDm.AddIntegerPara("DC_AtlantaHub", DC_AtlantaHub);
            oDm.AddIntegerPara("DC_Dallas_Hub", DC_Dallas_Hub);
            oDm.AddIntegerPara("DC_Elk_Grove_Hub", DC_Elk_Grove_Hub);
            oDm.AddIntegerPara("DC_Feura_Bush", DC_Feura_Bush);
            oDm.AddIntegerPara("DC_Louisville_Hub", DC_Louisville_Hub);
            oDm.AddIntegerPara("DC_Reno_Hub", DC_Reno_Hub);
            oDm.AddIntegerPara("DC_Richmond_Dist_Ctr", DC_Richmond_Dist_Ctr);
            oDm.AddIntegerPara("Oklahama", Oklahama);
            oDm.AddIntegerPara("RemainingBranches", RemainingBranches);
            oDm.AddDateTimePara("LastUpdate", LastUpdate);
            return oDm.RunActionQuery();
        }

        public int Update(long ID, string PART_NUM, int? TotalInventory, int? Dallas, int? DC_AtlantaHub, int? DC_Dallas_Hub, int? DC_Elk_Grove_Hub
            , int? DC_Feura_Bush, int? DC_Louisville_Hub, int? DC_Reno_Hub, int? DC_Richmond_Dist_Ctr, int? Oklahama, int? RemainingBranches, DateTime? LastUpdate)
        {
            String Query = "UPDATE ADIInventory SET TotalInventory = @TotalInventory, Dallas = @Dallas, "
                + " DC_AtlantaHub = @DC_AtlantaHub, DC_Dallas_Hub = @DC_Dallas_Hub, DC_Elk_Grove_Hub = @DC_Elk_Grove_Hub, "
                + " DC_Feura_Bush = @DC_Feura_Bush, DC_Louisville_Hub = @DC_Louisville_Hub, DC_Reno_Hub = @DC_Reno_Hub, "
                + " DC_Richmond_Dist_Ctr = @DC_Richmond_Dist_Ctr, Oklahama = @Oklahama, RemainingBranches = @RemainingBranches, LastUpdate = @LastUpdate"
                + " WHERE PART_NUM = \"" + PART_NUM + "\" AND ID = " + ID.ToString();
            OleDbDataManager oDm = new OleDbDataManager(ConnectionString, Query, true);
            //oDm.AddIntegerBigPara("ID", ID);
            //oDm.AddVarcharPara("PART_NUM", 4000, PART_NUM);
            oDm.AddIntegerPara("TotalInventory", TotalInventory);
            oDm.AddIntegerPara("Dallas", Dallas);
            oDm.AddIntegerPara("DC_AtlantaHub", DC_AtlantaHub);
            oDm.AddIntegerPara("DC_Dallas_Hub", DC_Dallas_Hub);
            oDm.AddIntegerPara("DC_Elk_Grove_Hub", DC_Elk_Grove_Hub);
            oDm.AddIntegerPara("DC_Feura_Bush", DC_Feura_Bush);
            oDm.AddIntegerPara("DC_Louisville_Hub", DC_Louisville_Hub);
            oDm.AddIntegerPara("DC_Reno_Hub", DC_Reno_Hub);
            oDm.AddIntegerPara("DC_Richmond_Dist_Ctr", DC_Richmond_Dist_Ctr);
            oDm.AddIntegerPara("Oklahama", Oklahama);
            oDm.AddIntegerPara("RemainingBranches", RemainingBranches);
            oDm.AddDateTimePara("LastUpdate", LastUpdate);
            return oDm.RunActionQuery();
        }

        #endregion

        #region [ Delete ]
        public int Delete(String PART_NUM)
        {
            String Query = "DELETE FROM ADIInventory SET WHERE PART_NUM = \"" + PART_NUM + "\"";
            OleDbDataManager oDm = new OleDbDataManager(ConnectionString, Query, true);
            //oDm.AddVarcharPara("PART_NUM", 4000, PART_NUM);
            return oDm.RunActionQuery();
        }
        public int Delete(String PART_NUM, String PropertyName)
        {
            String Query = "DELETE FROM ADIInventory SET WHERE PART_NUM = \"" + PART_NUM + "\" AND PropertyName = \"" + PropertyName + "\"";
            OleDbDataManager oDm = new OleDbDataManager(ConnectionString, Query, true);
            //oDm.AddVarcharPara("PART_NUM", 4000, PART_NUM);
            //oDm.AddVarcharPara("PropertyName", 4000, PropertyName);
            return oDm.RunActionQuery();
        }
        #endregion

    }
}


text:
#ifndef GRPCXX_SUPPORT_SYNC_STREAM_H
#define GRPCXX_SUPPORT_SYNC_STREAM_H

#include <grpc/support/log.h>
#include <grpc++/channel.h>
#include <grpc++/client_context.h>
#include <grpc++/completion_queue.h>
#include <grpc++/impl/call.h>
#include <grpc++/impl/service_type.h>
#include <grpc++/server_context.h>
#include <grpc++/support/status.h>

namespace grpc {

// Common interface for all client side streaming.
class ClientStreamingInterface {
 public:
  virtual ~ClientStreamingInterface() {}

  // Wait until the stream finishes, and return the final status. When the
  // client side declares it has no more message to send, either implicitly or
  // by calling WritesDone, it needs to make sure there is no more message to
  // be received from the server, either implicitly or by getting a false from
  // a Read().
  // This function will return either:
  // - when all incoming messages have been read and the server has returned
  //   status
  // - OR when the server has returned a non-OK status
  virtual Status Finish() = 0;
};

// An interface that yields a sequence of R messages.
template <class R>
class ReaderInterface {
 public:
  virtual ~ReaderInterface() {}

  // Blocking read a message and parse to msg. Returns true on success.
  // The method returns false when there will be no more incoming messages,
  // either because the other side has called WritesDone or the stream has
  // failed (or been cancelled).
  virtual bool Read(R* msg) = 0;
};

// An interface that can be fed a sequence of W messages.
template <class W>
class WriterInterface {
 public:
  virtual ~WriterInterface() {}

  // Blocking write msg to the stream. Returns true on success.
  // Returns false when the stream has been closed.
  virtual bool Write(const W& msg, const WriteOptions& options) = 0;

  inline bool Write(const W& msg) { return Write(msg, WriteOptions()); }
};

template <class R>
class ClientReaderInterface : public ClientStreamingInterface,
                              public ReaderInterface<R> {
 public:
  virtual void WaitForInitialMetadata() = 0;
};

template <class R>
class ClientReader GRPC_FINAL : public ClientReaderInterface<R> {
 public:
  // Blocking create a stream and write the first request out.
  template <class W>
  ClientReader(Channel* channel, const RpcMethod& method,
               ClientContext* context, const W& request)
      : context_(context), call_(channel->CreateCall(method, context, &cq_)) {
    CallOpSet<CallOpSendInitialMetadata, CallOpSendMessage,
              CallOpClientSendClose> ops;
    ops.SendInitialMetadata(context->send_initial_metadata_);
    // TODO(ctiller): don't assert
    GPR_ASSERT(ops.SendMessage(request).ok());
    ops.ClientSendClose();
    call_.PerformOps(&ops);
    cq_.Pluck(&ops);
  }

  // Blocking wait for initial metadata from server. The received metadata
  // can only be accessed after this call returns. Should only be called before
  // the first read. Calling this method is optional, and if it is not called
  // the metadata will be available in ClientContext after the first read.
  void WaitForInitialMetadata() {
    GPR_ASSERT(!context_->initial_metadata_received_);

    CallOpSet<CallOpRecvInitialMetadata> ops;
    ops.RecvInitialMetadata(context_);
    call_.PerformOps(&ops);
    cq_.Pluck(&ops);  // status ignored
  }

  bool Read(R* msg) GRPC_OVERRIDE {
    CallOpSet<CallOpRecvInitialMetadata, CallOpRecvMessage<R>> ops;
    if (!context_->initial_metadata_received_) {
      ops.RecvInitialMetadata(context_);
    }
    ops.RecvMessage(msg);
    call_.PerformOps(&ops);
    return cq_.Pluck(&ops) && ops.got_message;
  }

  Status Finish() GRPC_OVERRIDE {
    CallOpSet<CallOpClientRecvStatus> ops;
    Status status;
    ops.ClientRecvStatus(context_, &status);
    call_.PerformOps(&ops);
    GPR_ASSERT(cq_.Pluck(&ops));
    return status;
  }

 private:
  ClientContext* context_;
  CompletionQueue cq_;
  Call call_;
};

template <class W>
class ClientWriterInterface : public ClientStreamingInterface,
                              public WriterInterface<W> {
 public:
  virtual bool WritesDone() = 0;
};

template <class W>
class ClientWriter : public ClientWriterInterface<W> {
 public:
  // Blocking create a stream.
  template <class R>
  ClientWriter(Channel* channel, const RpcMethod& method,
               ClientContext* context, R* response)
      : context_(context), call_(channel->CreateCall(method, context, &cq_)) {
    finish_ops_.RecvMessage(response);

    CallOpSet<CallOpSendInitialMetadata> ops;
    ops.SendInitialMetadata(context->send_initial_metadata_);
    call_.PerformOps(&ops);
    cq_.Pluck(&ops);
  }

  using WriterInterface<W>::Write;
  bool Write(const W& msg, const WriteOptions& options) GRPC_OVERRIDE {
    CallOpSet<CallOpSendMessage> ops;
    if (!ops.SendMessage(msg, options).ok()) {
      return false;
    }
    call_.PerformOps(&ops);
    return cq_.Pluck(&ops);
  }

  bool WritesDone() GRPC_OVERRIDE {
    CallOpSet<CallOpClientSendClose> ops;
    ops.ClientSendClose();
    call_.PerformOps(&ops);
    return cq_.Pluck(&ops);
  }

  // Read the final response and wait for the final status.
  Status Finish() GRPC_OVERRIDE {
    Status status;
    finish_ops_.ClientRecvStatus(context_, &status);
    call_.PerformOps(&finish_ops_);
    GPR_ASSERT(cq_.Pluck(&finish_ops_));
    return status;
  }

 private:
  ClientContext* context_;
  CallOpSet<CallOpGenericRecvMessage, CallOpClientRecvStatus> finish_ops_;
  CompletionQueue cq_;
  Call call_;
};

// Client-side interface for bi-directional streaming.
template <class W, class R>
class ClientReaderWriterInterface : public ClientStreamingInterface,
                                    public WriterInterface<W>,
                                    public ReaderInterface<R> {
 public:
  virtual void WaitForInitialMetadata() = 0;
  virtual bool WritesDone() = 0;
};

template <class W, class R>
class ClientReaderWriter GRPC_FINAL : public ClientReaderWriterInterface<W, R> {
 public:
  // Blocking create a stream.
  ClientReaderWriter(Channel* channel, const RpcMethod& method,
                     ClientContext* context)
      : context_(context), call_(channel->CreateCall(method, context, &cq_)) {
    CallOpSet<CallOpSendInitialMetadata> ops;
    ops.SendInitialMetadata(context->send_initial_metadata_);
    call_.PerformOps(&ops);
    cq_.Pluck(&ops);
  }

  // Blocking wait for initial metadata from server. The received metadata
  // can only be accessed after this call returns. Should only be called before
  // the first read. Calling this method is optional, and if it is not called
  // the metadata will be available in ClientContext after the first read.
  void WaitForInitialMetadata() {
    GPR_ASSERT(!context_->initial_metadata_received_);

    CallOpSet<CallOpRecvInitialMetadata> ops;
    ops.RecvInitialMetadata(context_);
    call_.PerformOps(&ops);
    cq_.Pluck(&ops);  // status ignored
  }

  bool Read(R* msg) GRPC_OVERRIDE {
    CallOpSet<CallOpRecvInitialMetadata, CallOpRecvMessage<R>> ops;
    if (!context_->initial_metadata_received_) {
      ops.RecvInitialMetadata(context_);
    }
    ops.RecvMessage(msg);
    call_.PerformOps(&ops);
    return cq_.Pluck(&ops) && ops.got_message;
  }

  using WriterInterface<W>::Write;
  bool Write(const W& msg, const WriteOptions& options) GRPC_OVERRIDE {
    CallOpSet<CallOpSendMessage> ops;
    if (!ops.SendMessage(msg, options).ok()) return false;
    call_.PerformOps(&ops);
    return cq_.Pluck(&ops);
  }

  bool WritesDone() GRPC_OVERRIDE {
    CallOpSet<CallOpClientSendClose> ops;
    ops.ClientSendClose();
    call_.PerformOps(&ops);
    return cq_.Pluck(&ops);
  }

  Status Finish() GRPC_OVERRIDE {
    CallOpSet<CallOpClientRecvStatus> ops;
    Status status;
    ops.ClientRecvStatus(context_, &status);
    call_.PerformOps(&ops);
    GPR_ASSERT(cq_.Pluck(&ops));
    return status;
  }

 private:
  ClientContext* context_;
  CompletionQueue cq_;
  Call call_;
};

template <class R>
class ServerReader GRPC_FINAL : public ReaderInterface<R> {
 public:
  ServerReader(Call* call, ServerContext* ctx) : call_(call), ctx_(ctx) {}

  void SendInitialMetadata() {
    GPR_ASSERT(!ctx_->sent_initial_metadata_);

    CallOpSet<CallOpSendInitialMetadata> ops;
    ops.SendInitialMetadata(ctx_->initial_metadata_);
    ctx_->sent_initial_metadata_ = true;
    call_->PerformOps(&ops);
    call_->cq()->Pluck(&ops);
  }

  bool Read(R* msg) GRPC_OVERRIDE {
    CallOpSet<CallOpRecvMessage<R>> ops;
    ops.RecvMessage(msg);
    call_->PerformOps(&ops);
    return call_->cq()->Pluck(&ops) && ops.got_message;
  }

 private:
  Call* const call_;
  ServerContext* const ctx_;
};

template <class W>
class ServerWriter GRPC_FINAL : public WriterInterface<W> {
 public:
  ServerWriter(Call* call, ServerContext* ctx) : call_(call), ctx_(ctx) {}

  void SendInitialMetadata() {
    GPR_ASSERT(!ctx_->sent_initial_metadata_);

    CallOpSet<CallOpSendInitialMetadata> ops;
    ops.SendInitialMetadata(ctx_->initial_metadata_);
    ctx_->sent_initial_metadata_ = true;
    call_->PerformOps(&ops);
    call_->cq()->Pluck(&ops);
  }

  using WriterInterface<W>::Write;
  bool Write(const W& msg, const WriteOptions& options) GRPC_OVERRIDE {
    CallOpSet<CallOpSendInitialMetadata, CallOpSendMessage> ops;
    if (!ops.SendMessage(msg, options).ok()) {
      return false;
    }
    if (!ctx_->sent_initial_metadata_) {
      ops.SendInitialMetadata(ctx_->initial_metadata_);
      ctx_->sent_initial_metadata_ = true;
    }
    call_->PerformOps(&ops);
    return call_->cq()->Pluck(&ops);
  }

 private:
  Call* const call_;
  ServerContext* const ctx_;
};

// Server-side interface for bi-directional streaming.
template <class W, class R>
class ServerReaderWriter GRPC_FINAL : public WriterInterface<W>,
                                      public ReaderInterface<R> {
 public:
  ServerReaderWriter(Call* call, ServerContext* ctx) : call_(call), ctx_(ctx) {}

  void SendInitialMetadata() {
    GPR_ASSERT(!ctx_->sent_initial_metadata_);

    CallOpSet<CallOpSendInitialMetadata> ops;
    ops.SendInitialMetadata(ctx_->initial_metadata_);
    ctx_->sent_initial_metadata_ = true;
    call_->PerformOps(&ops);
    call_->cq()->Pluck(&ops);
  }

  bool Read(R* msg) GRPC_OVERRIDE {
    CallOpSet<CallOpRecvMessage<R>> ops;
    ops.RecvMessage(msg);
    call_->PerformOps(&ops);
    return call_->cq()->Pluck(&ops) && ops.got_message;
  }

  using WriterInterface<W>::Write;
  bool Write(const W& msg, const WriteOptions& options) GRPC_OVERRIDE {
    CallOpSet<CallOpSendInitialMetadata, CallOpSendMessage> ops;
    if (!ops.SendMessage(msg, options).ok()) {
      return false;
    }
    if (!ctx_->sent_initial_metadata_) {
      ops.SendInitialMetadata(ctx_->initial_metadata_);
      ctx_->sent_initial_metadata_ = true;
    }
    call_->PerformOps(&ops);
    return call_->cq()->Pluck(&ops);
  }

 private:
  Call* const call_;
  ServerContext* const ctx_;
};

}  // namespace grpc

#endif  // GRPCXX_SUPPORT_SYNC_STREAM_H


text:
package vista;

import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.WindowListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 * Vista para calcular el area del triangulo
 * @author cesar
 * @version 1.0
 *
 */
public class ATriangulo extends JFrame {

	private JLabel lbBase = new JLabel("Medida de la base");
	private JLabel lbAltura = new JLabel("Medida de la altura");
	private JLabel lbResultado = new JLabel("Resultado");

	private JTextField txtBase = new JTextField();
	private JTextField txtAltura = new JTextField();

	private JButton btnCalcular = new JButton("Calcular área");
	private Container c = getContentPane();

	/**
	 * Constructor de la clase ATriangulo para inicializar el Frame
	 */
	public ATriangulo() {
		super.setTitle("Área Triangulo");
		super.setSize(320, 480);
		super.setResizable(false);
		super.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

		cargarControles();
	}

	/**
	 * Método para cargar los controles de la aplicación a la ventana
	 */
	private void cargarControles() {
		c.setLayout(null);

		lbBase.setBounds(10, 10, 300, 30);
		txtBase.setBounds(10, 40, 300, 30);
		lbAltura.setBounds(10, 80, 300, 30);
		txtAltura.setBounds(10, 120, 300, 30);
		btnCalcular.setBounds(10, 160, 300, 60);
		lbResultado.setBounds(10, 230, 300, 30);

		c.add(lbBase);
		c.add(lbAltura);
		c.add(txtBase);
		c.add(txtAltura);
		c.add(btnCalcular);
		c.add(lbResultado);
	}
	/**
	 * Retorna el valor de la base en formato double
	 * @return Retorna el valor de la base en formato double
	 */
	public double getBase(){
		return Double.parseDouble(txtBase.getText());
	}
	/**
	 * Retorna el valor de la altura en formato double
	 * @return Retorna el valor de la altura en formato double
	 */
	public double getAltura() {
		return Double.parseDouble(txtAltura.getText());
	}

	/**
	 * Muestra el resultado de la operacion en la vista
	 * @param resultado Resultado de la operacion en formato String
	 */
	public void setResultado(String resultado) {
		lbResultado.setText(resultado);
	}

	/**
	 * ActionListener para el boton calcular
	 * @param al Objeto de tipo ActionListener
	 */
	public void onClickBtnCalcular(ActionListener al) {
		btnCalcular.addActionListener(al);
	}

	/**
	 * WindowListener para la vista
	 * @param wl Objeto de tipo WindowListener
	 */
	public void eventoCerrar(WindowListener wl) {
		this.addWindowListener(wl);
	}

	/**
	 * Retorna el acceso al boton calcular
	 * @return Retorna el acceso al boton calcular
	 */
	public JButton getBtnCalcular() {
		return btnCalcular;
	}

	/**
	 * Método para mostrar una alerta de error
	 * @param error Error generado en formato String
	 */
	public void mostrarError(String error) {
		JOptionPane.showMessageDialog(this, error, "Error !", JOptionPane.ERROR_MESSAGE);
	}

	/**
	 * Método para limpiar las cajas de texto de la aplicación
	 */
	public void limpiarCajas() {
		txtBase.setText(null);
		txtAltura.setText(null);
	}

}


text:
package org.onvif.client;

import de.onvif.discovery.OnvifDiscovery;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Class calls OnvifDiscovery and for each device URL found, calls TestDevice This assumes all onvif
 * devices on your network use the same username and password.
 *
 * @author Brad Lowe
 */
public class DiscoverAndTest {
  private static final Logger LOG = LoggerFactory.getLogger(TestDevice.class);

  public static String discoverAndTest(String user, String password) {
    String sep = "\n";
    StringBuffer out = new StringBuffer();

    Collection<URL> urls = OnvifDiscovery.discoverOnvifURLs();
    for (URL u : urls) {
      out.append("Discovered URL:" + u.toString() + sep);
    }
    ArrayList<String> results = new ArrayList<>();

    int good = 0, bad = 0;

    for (URL u : urls) {

      try {
        String result = TestDevice.testCamera(u, user, password);
        LOG.info(u + "->" + result);
        good++;
        results.add(u.toString() + ":" + result);
      } catch (Throwable e) {
        bad++;
        LOG.error("error:" + u, e);
        // This is a bit of a hack. When a camera is password protected (it should be!)
        // and the password is not provided or wrong, a "Unable to Send Message" exception
        // may be thrown. This is not clear-- buried in the stack track is the real cause.
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        String trace = sw.getBuffer().toString();
        if (trace.contains("Unauthorized")) results.add(u + ":Unauthorized:");
        else results.add(u + ":" + trace);
      }
    }
    out.append("RESULTS: " + sep);
    for (String s : results) out.append(s + sep);
    out.append("cameras found:" + urls.size() + " good=" + good + ", bad=" + bad + sep);
    return out.toString();
  }

  public static void main(String[] args) {
    // get user and password.. we will ignore device host
    String user = "";
    String password = "";
    if (args.length > 0) user = args[0];
    if (args.length > 1) password = args[1];

    if (password.isEmpty()) {
      LOG.warn(
          "Warning: No password for discover and test... run with common user password as arguments");
    }
    // OnvifDevice.setVerbose(true);
    LOG.info(discoverAndTest(user, password));
  }
}


text:
<?php

namespace Gordalina\Easypay\Tests\Request;

use Gordalina\Easypay\Config;
use Gordalina\Easypay\Request\FetchAllPayments;

class FetchAllPaymentsTest extends \PHPUnit_Framework_TestCase
{
    public function testEndpoint()
    {
        $request = new FetchAllPayments();

        $this->assertSame(FetchAllPayments::ENDPOINT, $request->getEndpoint());
    }

    public function testNormal()
    {
        $request = new FetchAllPayments();
        $params = $request->handleRequest($this->getConfig());

        $this->assertTrue(is_array($params));
        $this->assertCount(5, $params);
        $this->assertSame('cin', $params['ep_cin']);
        $this->assertSame('user', $params['ep_user']);
        $this->assertSame('entity', $params['ep_entity']);
        $this->assertSame('language', $params['ep_language']);
        $this->assertSame('country', $params['ep_country']);
        $this->assertArrayNotHasKey('s_code', $params);
    }

    public function testCode()
    {
        $request = new FetchAllPayments();
        $params = $request->handleRequest($this->getConfig('code'));

        $this->assertTrue(is_array($params));
        $this->assertCount(6, $params);
        $this->assertSame('cin', $params['ep_cin']);
        $this->assertSame('user', $params['ep_user']);
        $this->assertSame('entity', $params['ep_entity']);
        $this->assertSame('language', $params['ep_language']);
        $this->assertSame('country', $params['ep_country']);
        $this->assertSame('code', $params['s_code']);
    }

    public function testFilter()
    {
        $request = new FetchAllPayments();
        $request->setFilter('date');
        $request->setStartDate('2013-01-01');
        $request->setEndDate('2014-01-01');

        $params = $request->handleRequest($this->getConfig());

        $this->assertTrue(is_array($params));
        $this->assertCount(8, $params);
        $this->assertSame('cin', $params['ep_cin']);
        $this->assertSame('user', $params['ep_user']);
        $this->assertSame('entity', $params['ep_entity']);
        $this->assertSame('language', $params['ep_language']);
        $this->assertSame('country', $params['ep_country']);
        $this->assertSame('2013-01-01', $params['o_ini']);
        $this->assertSame('2014-01-01', $params['o_last']);
        $this->assertSame('date', $params['ep_list_type']);
    }

    public function testHandleResponseNormalWithMultipleRecords()
    {
        $request = new FetchAllPayments();
        $response = $request->handleResponse(array(
            'ep_status' => 'ok0',
            'ep_message' => 'message',
            'ep_num_records' => 2,
            'ref_detail' => array(
                'ref' => array(
                    array(
                        'ep_cin' => 'cin',
                        'ep_user' => 'user',
                        'ep_entity' => 'entity',
                        'ep_reference' => 'reference',
                        'ep_value' => '10.0',
                        't_key' => '10.0',
                        'ep_key' => '10.0',
                        'ep_doc' => 'doc',
                        'ep_payment_type' => 'paymentType',
                        'ep_value_fixed' => 'valueFixed',
                        'ep_value_var' => 'valueVariable',
                        'ep_value_tax' => 'valueTax',
                        'ep_value_transf' => 'valueTransfered',
                        'ep_date_transf' => 'dateTransfered',
                        'ep_date_read' => 'dateRead',
                        'ep_status_read' => 'statusRead',
                        'o_obs' => 'observations',
                        'o_email' => 'email',
                        'o_mobile' => 'mobile',
                        'ep_date' => 'date',
                    ),
                    array(
                        'ep_cin' => 'cin',
                        'ep_user' => 'user',
                        'ep_entity' => 'entity',
                        'ep_reference' => 'reference',
                        'ep_value' => '10.0',
                        't_key' => '10.0',
                        'ep_key' => '10.0',
                        'ep_doc' => 'doc',
                        'ep_payment_type' => 'paymentType',
                        'ep_value_fixed' => 'valueFixed',
                        'ep_value_var' => 'valueVariable',
                        'ep_value_tax' => 'valueTax',
                        'ep_value_transf' => 'valueTransfered',
                        'ep_date_transf' => 'dateTransfered',
                        'ep_date_read' => 'dateRead',
                        'ep_status_read' => 'statusRead',
                        'o_obs' => 'observations',
                        'o_email' => 'email',
                        'o_mobile' => 'mobile',
                        'ep_date' => 'date',
                    ),
                ),
            ),
        ));

        $this->assertInstanceOf('Gordalina\Easypay\Response\FetchAllPayments', $response);
        $this->assertTrue($response->isValid());
        $this->assertSame('ok0', $response->getStatus());
        $this->assertSame('message', $response->getMessage());
        $this->assertSame(2, $response->getRecordCount());

        $payments = $response->getRecords();
        $this->assertTrue(is_array($payments));

        foreach ($payments as $payment) {
            $this->assertInstanceOf('Gordalina\Easypay\Payment\PaymentComplete', $payment);
            $this->assertSame('cin', $payment->getCin());
            $this->assertSame('user', $payment->getUser());
            $this->assertSame('entity', $payment->getEntity());
            $this->assertSame('reference', $payment->getReference());
            $this->assertSame(10.0, $payment->getValue());
            $this->assertSame('10.0', $payment->getKey());
            $this->assertSame(10, $payment->getEpKey());
            $this->assertSame('doc', $payment->getDoc());
            $this->assertSame('paymentType', $payment->getPaymentType());
            $this->assertSame('valueFixed', $payment->getValueFixed());
            $this->assertSame('valueVariable', $payment->getValueVariable());
            $this->assertSame('valueTax', $payment->getValueTax());
            $this->assertSame('valueTransfered', $payment->getValueTransfered());
            $this->assertSame('dateTransfered', $payment->getDateTransfered());
            $this->assertSame('dateRead', $payment->getDateRead());
            $this->assertSame('statusRead', $payment->getStatusRead());
            $this->assertSame('observations', $payment->getObservations());
            $this->assertSame('email', $payment->getEmail());
            $this->assertSame('mobile', $payment->getMobile());
            $this->assertSame('date', $payment->getDate());
        }
    }

    public function testHandleResponseNormalWithOneRecord()
    {
        $request = new FetchAllPayments();
        $response = $request->handleResponse(array(
            'ep_status' => 'ok0',
            'ep_message' => 'message',
            'ep_num_records' => 1,
            'ref_detail' => array(
                'ref' => array(
                    'ep_cin' => 'cin',
                    'ep_user' => 'user',
                    'ep_entity' => 'entity',
                    'ep_reference' => 'reference',
                    'ep_value' => '10.0',
                    't_key' => '10.0',
                    'ep_key' => '10.0',
                    'ep_doc' => 'doc',
                    'ep_payment_type' => 'paymentType',
                    'ep_value_fixed' => 'valueFixed',
                    'ep_value_var' => 'valueVariable',
                    'ep_value_tax' => 'valueTax',
                    'ep_value_transf' => 'valueTransfered',
                    'ep_date_transf' => 'dateTransfered',
                    'ep_date_read' => 'dateRead',
                    'ep_status_read' => 'statusRead',
                    'o_obs' => 'observations',
                    'o_email' => 'email',
                    'o_mobile' => 'mobile',
                    'ep_date' => 'date',
                ),
            ),
        ));

        $this->assertInstanceOf('Gordalina\Easypay\Response\FetchAllPayments', $response);
        $this->assertTrue($response->isValid());
        $this->assertSame('ok0', $response->getStatus());
        $this->assertSame('message', $response->getMessage());
        $this->assertSame(1, $response->getRecordCount());

        $payments = $response->getRecords();
        $this->assertTrue(is_array($payments));

        foreach ($payments as $payment) {
            $this->assertInstanceOf('Gordalina\Easypay\Payment\PaymentComplete', $payment);
            $this->assertSame('cin', $payment->getCin());
            $this->assertSame('user', $payment->getUser());
            $this->assertSame('entity', $payment->getEntity());
            $this->assertSame('reference', $payment->getReference());
            $this->assertSame(10.0, $payment->getValue());
            $this->assertSame('10.0', $payment->getKey());
            $this->assertSame(10, $payment->getEpKey());
            $this->assertSame('doc', $payment->getDoc());
            $this->assertSame('paymentType', $payment->getPaymentType());
            $this->assertSame('valueFixed', $payment->getValueFixed());
            $this->assertSame('valueVariable', $payment->getValueVariable());
            $this->assertSame('valueTax', $payment->getValueTax());
            $this->assertSame('valueTransfered', $payment->getValueTransfered());
            $this->assertSame('dateTransfered', $payment->getDateTransfered());
            $this->assertSame('dateRead', $payment->getDateRead());
            $this->assertSame('statusRead', $payment->getStatusRead());
            $this->assertSame('observations', $payment->getObservations());
            $this->assertSame('email', $payment->getEmail());
            $this->assertSame('mobile', $payment->getMobile());
            $this->assertSame('date', $payment->getDate());
        }
    }

    public function testHandleResponseNoPayments()
    {
        $request = new FetchAllPayments();
        $response = $request->handleResponse(array(
            'ep_status' => 'ok0',
            'ep_message' => 'message',
            'ep_num_records' => 0,
            'ref_detail' => array(
                'ref' => array()
            ),
        ));

        $this->assertInstanceOf('Gordalina\Easypay\Response\FetchAllPayments', $response);
        $this->assertTrue($response->isValid());
        $this->assertSame('ok0', $response->getStatus());
        $this->assertSame('message', $response->getMessage());
        $this->assertSame(0, $response->getRecordCount());

        $this->assertTrue(is_array($response->getRecords()));
        $this->assertCount(0, $response->getRecords());
    }

    public function getConfig($code = NULL)
    {
        return new Config('user', 'entity', 'cin', 'country', 'language', $code);
    }
}


text:
namespace bfcp
{
class BfcpConnection;
class ThreadPool;
class Conference;
typedef boost::shared_ptr<BfcpConnection> BfcpConnectionPtr;
typedef boost::shared_ptr<Conference> ConferencePtr;

class BaseServer
{
public:
  typedef boost::function<void ()> WorkerThreadInitCallback;
  typedef boost::function<void (ControlError)> ResultCallback;
  typedef boost::function<void (ControlError, void*)> ResultWithDataCallback;
  typedef std::vector<uint32_t> ConferenceIDList;

  static const double kDefaultUserObsoletedTime;

  BaseServer(muduo::net::EventLoop* loop,
             const muduo::net::InetAddress& listenAddr);

  muduo::net::EventLoop* getLoop() { return loop_; }

  // NOTE: call before start
  void enableConnectionThread();

  void setWorkerThreadNum(int numThreads) { numThreads_ = numThreads; }

  void setWorkerThreadInitCallback(const WorkerThreadInitCallback &cb)
  { workerThreadInitCallback_ = cb; }
  void setWorkerThreadInitCallback(WorkerThreadInitCallback &&cb)
  { workerThreadInitCallback_ = std::move(cb); }

  void setUserObsoleteTime(double timeInSec) { userObsoletedTime_ = timeInSec; }

  void start();
  void stop();

  void addConference(
    uint32_t conferenceID,
    const ConferenceConfig &config,
    const ResultCallback &cb);

  void removeConference(
    uint32_t conferenceID,
    const ResultCallback &cb);

  void modifyConference(
    uint32_t conferenceID,
    const ConferenceConfig &config,
    const ResultCallback &cb);

  void addFloor(
    uint32_t conferenceID,
    uint16_t floorID,
    const FloorConfig &config,
    const ResultCallback &cb);

  void removeFloor(
    uint32_t conferenceID,
    uint16_t floorID,
    const ResultCallback &cb);

  void modifyFloor(
    uint32_t conferenceID,
    uint16_t floorID,
    const FloorConfig &config,
    const ResultCallback &cb);

  void addUser(
    uint32_t conferenceID,
    const UserInfoParam &user,
    const ResultCallback &cb);

  void removeUser(
    uint32_t conferenceID,
    uint16_t userID,
    const ResultCallback &cb);

  void setChair(
    uint32_t conferenceID,
    uint16_t floorID,
    uint16_t userID,
    const ResultCallback &cb);

  void removeChair(
    uint32_t conferenceID,
    uint16_t floorID,
    const ResultCallback &cb);

  void getConferenceIDs(
    const ResultWithDataCallback &cb);

  void getConferenceInfo(
    uint32_t conferenceID,
    const ResultWithDataCallback &cb);

private:
  typedef boost::function<ControlError ()> ConferenceTask;

  void onStartedRecv(const muduo::net::UdpSocketPtr& socket);
  void onMessage(const muduo::net::UdpSocketPtr& socket,
                 muduo::net::Buffer* buf,
                 const muduo::net::InetAddress& src,
                 muduo::Timestamp time);
  void onWriteComplete(const muduo::net::UdpSocketPtr& socket, int messageId);

  void onNewRequest(const BfcpMsgPtr &msg);

  void onResponse(
    uint32_t conferenceID,
    bfcp_prim expectedPrimitive,
    uint16_t userID,
    ResponseError err,
    const BfcpMsgPtr &msg);

  void onChairActionTimeout(
    uint32_t conferenceID,
    uint16_t floorRequestID);

  void onHoldingFloorsTimeout(
    uint32_t conferenceID,
    uint16_t floorRequestID);

  void addConferenceInLoop(
    uint32_t conferenceID,
    uint16_t maxFloorRequest,
    AcceptPolicy policy,
    double timeForChairAction,
    const ResultCallback &cb);

  void addConferenceInLoop(
    uint32_t conferenceID,
    const ConferenceConfig &config,
    const ResultCallback &cb);

  void removeConferenceInLoop(
    uint32_t conferenceID,
    const ResultCallback &cb);

  void modifyConferenceInLoop(
    uint32_t conferenceID,
    const ConferenceConfig &config,
    const ResultCallback &cb);

  void addFloorInLoop(
    uint32_t conferenceID,
    uint16_t floorID,
    const FloorConfig &config,
    const ResultCallback &cb);

  void removeFloorInLoop(
    uint32_t conferenceID,
    uint16_t floorID,
    const ResultCallback &cb);

  void modifyFloorInLoop(
    uint32_t conferenceID,
    uint16_t floorID,
    const FloorConfig &config,
    const ResultCallback &cb);

  void addUserInLoop(
    uint32_t conferenceID,
    const UserInfoParam &user,
    const ResultCallback &cb);

  void removeUserInLoop(
    uint32_t conferenceID,
    uint16_t userID,
    const ResultCallback &cb);

  void setChairInLoop(
    uint32_t conferenceID,
    uint16_t floorID,
    uint16_t userID,
    const ResultCallback &cb);

  void removeChairInLoop(
    uint32_t conferenceID,
    uint16_t floorID,
    const ResultCallback &cb);

  void getConferenceIDsInLoop(
    const ResultWithDataCallback &cb);

  void getConferenceInfoInLoop(
      uint32_t conferenceID,
      const ResultWithDataCallback &cb);

  void wrapTaskAndCallback(
    const ConferenceTask &task,
    const ResultCallback &cb)
  {
    auto res = task();
    if (cb)
    {
      cb(res);
    }
  }

  template <typename Func, typename Arg1>
  void runInLoop(Func func, const Arg1 &arg1);

  template <typename Func, typename Arg1, typename Arg2>
  void runInLoop(
    Func func, const Arg1 &arg1, const Arg2 &arg2);

  template <typename Func, typename Arg1, typename Arg2, typename Arg3>
  void runInLoop(
    Func func, const Arg1 &arg1, const Arg2 &arg2, const Arg3 &arg3);

  template <typename Func, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
  void runInLoop(
    Func func, const Arg1 &arg1, const Arg2 &arg2, const Arg3 &arg3, const Arg4 &arg4);

  template <typename Func, typename Arg1>
  void runTask(
    Func func,
    uint32_t conferenceID,
    const Arg1 &arg1,
    const ResultCallback &cb);

  template <typename Func, typename Arg1>
  void runTask(
    Func func,
    uint32_t conferenceID,
    const ResultWithDataCallback &cb);

  template <typename Func, typename Arg1, typename Arg2>
  void runTask(
    Func func,
    uint32_t conferenceID,
    const Arg1 &arg1,
    const Arg2 &arg2,
    const ResultCallback &cb);

private:
  muduo::net::EventLoop* loop_;
  muduo::net::UdpServer server_;
  BfcpConnectionPtr connection_;
  muduo::net::EventLoop *connectionLoop_;
  boost::scoped_ptr<muduo::net::EventLoopThread> connectionThread_;
  WorkerThreadInitCallback workerThreadInitCallback_;
  int numThreads_;
  boost::shared_ptr<ThreadPool> threadPool_;
  muduo::AtomicInt32 started_;
  std::map<uint32_t, ConferencePtr> conferenceMap_;
  bool enableConnectionThread_;
  double userObsoletedTime_;
};

} // namespace bfcp

#endif // BFCP_BASE_SERVER_H


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 31: 268 (1939)

#### Original name
Mycena corticalis (Berk. & M.A. Curtis) Sacc.

### Remarks
null


text:
#include "../libk.h"
/*
    malloc/realloc struct text
    text[line.count].row
    text[line.size].size
*/
int readAline(void)
{
    line.row = NULL; linecap = 0;
    line.size = getline (&line.row, &linecap, fp);

    if (line.size == -1) {return line.size;} /* read failure */

    line.size = line.size - 1;
    assert(line.size >= 0);

    if((line.count == 0)) {text = malloc(sizeof(slot));}
    else {
           text = realloc(text,(1+line.count)*sizeof(slot));
           if(!text) assert(text);
         }

    char* ptr = NULL;
    if (line.size > 0) ptr = malloc(line.size*sizeof(char));
    text[line.count].row = ptr  ;
    text[line.count].size = line.size;

    if (line.size > 0) memcpy(ptr,line.row,line.size);

    line.count++; return 0;
}


text:
@interface IDESourceEditorFontAndColorItemProvider : NSObject
{
}

+ (id)fontAndColorItems;

@end


text:
//
//  ========================================================================
//  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//
/**
 * Based on org.eclipse.jetty.util.thread.ExecutorThreadPool
 *
 * Modified by Jesper André Lyngesen Pedersen (jalpedersen@gmail.com), 2013
 *
 */

package org.signaut.util.thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.ThreadPool;

/* ------------------------------------------------------------ */
/**
 * Jetty ThreadPool using java 5 ThreadPoolExecutor
 * This class wraps a {@link ExecutorService} as a {@link ThreadPool} and
 * {@link LifeCycle} interfaces so that it may be used by the Jetty org.eclipse.jetty.server.Server
 */
public class ReplaceableThreadPool extends AbstractLifeCycle implements ThreadPool, LifeCycle
{
    private static final Logger LOG = Log.getLogger(ReplaceableThreadPool.class);
    private ExecutorService replaceableExecutor;
	private final int corePoolSize;
	private final int maximumPoolSize;
	private final long keepAliveTime;
	private final TimeUnit unit;
	private final BlockingQueue<Runnable> workQueue;

	  public ReplaceableThreadPool(int corePoolSize)
	    {
	        this(corePoolSize, corePoolSize, 30*1000, TimeUnit.MILLISECONDS);
	    }

    /* ------------------------------------------------------------ */
    /**
     * Wraps an {@link ThreadPoolExecutor} using
     * an unbounded {@link LinkedBlockingQueue} is used for the jobs queue;
     * @param corePoolSize must be equal to maximumPoolSize
     * @param maximumPoolSize the maximum number of threads to allow in the pool
     * @param keepAliveTime the max time a thread can remain idle, in milliseconds
     */
    public ReplaceableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime)
    {
        this(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS);
    }

    /* ------------------------------------------------------------ */
    /**
     * Wraps an {@link ThreadPoolExecutor} using
     * an unbounded {@link LinkedBlockingQueue} is used for the jobs queue.
     * @param corePoolSize must be equal to maximumPoolSize
     * @param maximumPoolSize the maximum number of threads to allow in the pool
     * @param keepAliveTime the max time a thread can remain idle
     * @param unit the unit for the keepAliveTime
     */
    public ReplaceableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit)
    {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, new LinkedBlockingQueue<Runnable>());
    }

    /* ------------------------------------------------------------ */

    /**
     * Wraps an {@link ThreadPoolExecutor}
     * @param corePoolSize the number of threads to keep in the pool, even if they are idle
     * @param maximumPoolSize the maximum number of threads to allow in the pool
     * @param keepAliveTime the max time a thread can remain idle
     * @param unit the unit for the keepAliveTime
     * @param workQueue the queue to use for holding tasks before they are executed
     */
    public ReplaceableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
    {
    	this.corePoolSize = corePoolSize;
    	this.maximumPoolSize = maximumPoolSize;
    	this.keepAliveTime = keepAliveTime;
    	this.unit = unit;
    	this.workQueue = workQueue;
        this.replaceableExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    /* ------------------------------------------------------------ */
    @Override
    public void execute(Runnable job)
    {
        replaceableExecutor.execute(job);
    }

    /* ------------------------------------------------------------ */
    public boolean dispatch(Runnable job)
    {
        try
        {
            replaceableExecutor.execute(job);
            return true;
        }
        catch(RejectedExecutionException e)
        {
            LOG.warn(e);
            return false;
        }
    }

    /* ------------------------------------------------------------ */
    public int getIdleThreads()
    {
        if (replaceableExecutor instanceof ThreadPoolExecutor)
        {
            final ThreadPoolExecutor tpe = (ThreadPoolExecutor)replaceableExecutor;
            return tpe.getPoolSize() - tpe.getActiveCount();
        }
        return -1;
    }

    /* ------------------------------------------------------------ */
    public int getThreads()
    {
        if (replaceableExecutor instanceof ThreadPoolExecutor)
        {
            final ThreadPoolExecutor tpe = (ThreadPoolExecutor)replaceableExecutor;
            return tpe.getPoolSize();
        }
        return -1;
    }

    /* ------------------------------------------------------------ */
    public boolean isLowOnThreads()
    {
        if (replaceableExecutor instanceof ThreadPoolExecutor)
        {
            final ThreadPoolExecutor tpe = (ThreadPoolExecutor)replaceableExecutor;
            // getActiveCount() locks the thread pool, so execute it last
            return tpe.getPoolSize() == tpe.getMaximumPoolSize() &&
                    tpe.getQueue().size() >= tpe.getPoolSize() - tpe.getActiveCount();
        }
        return false;
    }

    /* ------------------------------------------------------------ */
    public void join() throws InterruptedException
    {
        replaceableExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    }

    public synchronized void replaceThreads() {
        final ExecutorService obsolete = replaceableExecutor;
    	this.replaceableExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        LOG.debug("Replacing threads");
    	obsolete.shutdown();
    }

    /* ------------------------------------------------------------ */
    @Override
    protected void doStop() throws Exception
    {
        super.doStop();
        replaceableExecutor.shutdownNow();
    }
}


text:
pub enum BodySectionType {
    AllSection,
    MsgtextSection(Msgtext),
    PartSection(Vec<usize>, Option<Msgtext>)
}

#[derive(PartialEq, Debug)]
pub enum Msgtext {
    HeaderMsgtext,
    HeaderFieldsMsgtext(Vec<String>),
    HeaderFieldsNotMsgtext(Vec<String>),
    TextMsgtext,
    MimeMsgtext
}


text:
package securesocial.controllers

object Assets extends controllers.AssetsBuilder