text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.engine.test.bpmn.gateway;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.flowable.engine.common.api.FlowableException;
import org.flowable.engine.common.impl.util.CollectionUtil;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.test.PluggableFlowableTestCase;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.task.Task;
import org.flowable.engine.test.Deployment;

/**
 * @author Joram Barrez
 * @author Tom Van Buskirk
 * @author Tijs Rademakers
 * @author Saeid Mirzaei
 */
public class InclusiveGatewayTest extends PluggableFlowableTestCase {

  private static final String TASK1_NAME = "Task 1";
  private static final String TASK2_NAME = "Task 2";
  private static final String TASK3_NAME = "Task 3";

  private static final String BEAN_TASK1_NAME = "Basic service";
  private static final String BEAN_TASK2_NAME = "Standard service";
  private static final String BEAN_TASK3_NAME = "Gold Member service";

  @Deployment
  public void testDivergingInclusiveGateway() {
    for (int i = 1; i <= 3; i++) {
      ProcessInstance pi = runtimeService.startProcessInstanceByKey("inclusiveGwDiverging", CollectionUtil.singletonMap("input", i));
      List<Task> tasks = taskService.createTaskQuery().processInstanceId(pi.getId()).list();
      List<String> expectedNames = new ArrayList<String>();
      if (i == 1) {
        expectedNames.add(TASK1_NAME);
      }
      if (i <= 2) {
        expectedNames.add(TASK2_NAME);
      }
      expectedNames.add(TASK3_NAME);
      assertEquals(4 - i, tasks.size());
      for (Task task : tasks) {
        expectedNames.remove(task.getName());
      }
      assertEquals(0, expectedNames.size());
      runtimeService.deleteProcessInstance(pi.getId(), "testing deletion");
    }
  }

  @Deployment
  public void testMergingInclusiveGateway() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("inclusiveGwMerging", CollectionUtil.singletonMap("input", 2));
    assertEquals(1, taskService.createTaskQuery().count());

    runtimeService.deleteProcessInstance(pi.getId(), "testing deletion");
  }

  @Deployment
  public void testPartialMergingInclusiveGateway() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("partialInclusiveGwMerging", CollectionUtil.singletonMap("input", 2));
    Task partialTask = taskService.createTaskQuery().singleResult();
    assertEquals("partialTask", partialTask.getTaskDefinitionKey());

    taskService.complete(partialTask.getId());

    Task fullTask = taskService.createTaskQuery().singleResult();
    assertEquals("theTask", fullTask.getTaskDefinitionKey());

    runtimeService.deleteProcessInstance(pi.getId(), "testing deletion");
  }

  @Deployment
  public void testNoSequenceFlowSelected() {
    try {
      runtimeService.startProcessInstanceByKey("inclusiveGwNoSeqFlowSelected", CollectionUtil.singletonMap("input", 4));
      fail();
    } catch (FlowableException e) {
      // Exception expected
    }
  }

  /**
   * Test for ACT-1216: When merging a concurrent execution the parent is not activated correctly
   */
  @Deployment
  public void testParentActivationOnNonJoiningEnd() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("parentActivationOnNonJoiningEnd");

    List<Execution> executionsBefore = runtimeService.createExecutionQuery().list();
    assertEquals(3, executionsBefore.size());

    // start first round of tasks
    List<Task> firstTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
    assertEquals(2, firstTasks.size());

    for (Task t : firstTasks) {
      taskService.complete(t.getId());
    }

    // start second round of tasks
    List<Task> secondTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
    assertEquals(2, secondTasks.size());

    // complete one task
    Task task = secondTasks.get(0);
    taskService.complete(task.getId());

    List<Execution> executionsAfter = runtimeService.createExecutionQuery().list();
    assertEquals(2, executionsAfter.size());

    Execution execution = null;
    for (Execution e : executionsAfter) {
      if (e.getParentId() != null) {
        execution = e;
      }
    }

    // and should have one active activity
    List<String> activeActivityIds = runtimeService.getActiveActivityIds(execution.getId());
    assertEquals(1, activeActivityIds.size());

    // Completing last task should finish the process instance

    Task lastTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    taskService.complete(lastTask.getId());

    assertEquals(0l, runtimeService.createProcessInstanceQuery().active().count());
  }

  /**
   * Test for bug ACT-10: whitespaces/newlines in expressions lead to exceptions
   */
  @Deployment
  public void testWhitespaceInExpression() {
    // Starting a process instance will lead to an exception if whitespace
    // are
    // incorrectly handled
    runtimeService.startProcessInstanceByKey("inclusiveWhiteSpaceInExpression", CollectionUtil.singletonMap("input", 1));
  }

  @Deployment(resources = { "org/flowable/engine/test/bpmn/gateway/InclusiveGatewayTest.testDivergingInclusiveGateway.bpmn20.xml" })
  public void testUnknownVariableInExpression() {
    // Instead of 'input' we're starting a process instance with the name
    // 'iinput' (ie. a typo)
    try {
      runtimeService.startProcessInstanceByKey("inclusiveGwDiverging", CollectionUtil.singletonMap("iinput", 1));
      fail();
    } catch (FlowableException e) {
      assertTextPresent("Unknown property used in expression", e.getMessage());
    }
  }

  @Deployment
  public void testDecideBasedOnBeanProperty() {
    runtimeService.startProcessInstanceByKey("inclusiveDecisionBasedOnBeanProperty", CollectionUtil.singletonMap("order", new InclusiveGatewayTestOrder(150)));
    List<Task> tasks = taskService.createTaskQuery().list();
    assertEquals(2, tasks.size());
    Map<String, String> expectedNames = new HashMap<String, String>();
    expectedNames.put(BEAN_TASK2_NAME, BEAN_TASK2_NAME);
    expectedNames.put(BEAN_TASK3_NAME, BEAN_TASK3_NAME);
    for (Task task : tasks) {
      expectedNames.remove(task.getName());
    }
    assertEquals(0, expectedNames.size());
  }

  @Deployment
  public void testDecideBasedOnListOrArrayOfBeans() {
    List<InclusiveGatewayTestOrder> orders = new ArrayList<InclusiveGatewayTestOrder>();
    orders.add(new InclusiveGatewayTestOrder(50));
    orders.add(new InclusiveGatewayTestOrder(300));
    orders.add(new InclusiveGatewayTestOrder(175));

    try {
      runtimeService.startProcessInstanceByKey("inclusiveDecisionBasedOnListOrArrayOfBeans", CollectionUtil.singletonMap("orders", orders));
      fail();
    } catch (FlowableException e) {
      // expect an exception to be thrown here as there is
    }

    orders.set(1, new InclusiveGatewayTestOrder(175));
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("inclusiveDecisionBasedOnListOrArrayOfBeans", CollectionUtil.singletonMap("orders", orders));
    Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
    assertNotNull(task);
    assertEquals(BEAN_TASK3_NAME, task.getName());

    orders.set(1, new InclusiveGatewayTestOrder(125));
    pi = runtimeService.startProcessInstanceByKey("inclusiveDecisionBasedOnListOrArrayOfBeans", CollectionUtil.singletonMap("orders", orders));
    List<Task> tasks = taskService.createTaskQuery().processInstanceId(pi.getId()).list();
    assertNotNull(tasks);
    assertEquals(2, tasks.size());
    List<String> expectedNames = new ArrayList<String>();
    expectedNames.add(BEAN_TASK2_NAME);
    expectedNames.add(BEAN_TASK3_NAME);
    for (Task t : tasks) {
      expectedNames.remove(t.getName());
    }
    assertEquals(0, expectedNames.size());

    // Arrays are usable in exactly the same way
    InclusiveGatewayTestOrder[] orderArray = orders.toArray(new InclusiveGatewayTestOrder[orders.size()]);
    orderArray[1].setPrice(10);
    pi = runtimeService.startProcessInstanceByKey("inclusiveDecisionBasedOnListOrArrayOfBeans", CollectionUtil.singletonMap("orders", orderArray));
    tasks = taskService.createTaskQuery().processInstanceId(pi.getId()).list();
    assertNotNull(tasks);
    assertEquals(3, tasks.size());
    expectedNames.clear();
    expectedNames.add(BEAN_TASK1_NAME);
    expectedNames.add(BEAN_TASK2_NAME);
    expectedNames.add(BEAN_TASK3_NAME);
    for (Task t : tasks) {
      expectedNames.remove(t.getName());
    }
    assertEquals(0, expectedNames.size());
  }

  @Deployment
  public void testDecideBasedOnBeanMethod() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("inclusiveDecisionBasedOnBeanMethod", CollectionUtil.singletonMap("order", new InclusiveGatewayTestOrder(200)));
    Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
    assertNotNull(task);
    assertEquals(BEAN_TASK3_NAME, task.getName());

    pi = runtimeService.startProcessInstanceByKey("inclusiveDecisionBasedOnBeanMethod", CollectionUtil.singletonMap("order", new InclusiveGatewayTestOrder(125)));
    List<Task> tasks = taskService.createTaskQuery().processInstanceId(pi.getId()).list();
    assertEquals(2, tasks.size());
    List<String> expectedNames = new ArrayList<String>();
    expectedNames.add(BEAN_TASK2_NAME);
    expectedNames.add(BEAN_TASK3_NAME);
    for (Task t : tasks) {
      expectedNames.remove(t.getName());
    }
    assertEquals(0, expectedNames.size());

    try {
      runtimeService.startProcessInstanceByKey("inclusiveDecisionBasedOnBeanMethod", CollectionUtil.singletonMap("order", new InclusiveGatewayTestOrder(300)));
      fail();
    } catch (FlowableException e) {
      // Should get an exception indicating that no path could be taken
    }

  }

  @Deployment
  public void testInvalidMethodExpression() {
    try {
      runtimeService.startProcessInstanceByKey("inclusiveInvalidMethodExpression", CollectionUtil.singletonMap("order", new InclusiveGatewayTestOrder(50)));
      fail();
    } catch (FlowableException e) {
      assertTextPresent("Unknown method used in expression", e.getMessage());
    }
  }

  @Deployment
  public void testDefaultSequenceFlow() {
    // Input == 1 -> default is not selected, other 2 tasks are selected
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("inclusiveGwDefaultSequenceFlow", CollectionUtil.singletonMap("input", 1));
    List<Task> tasks = taskService.createTaskQuery().processInstanceId(pi.getId()).list();
    assertEquals(2, tasks.size());
    Map<String, String> expectedNames = new HashMap<String, String>();
    expectedNames.put("Input is one", "Input is one");
    expectedNames.put("Input is three or one", "Input is three or one");
    for (Task t : tasks) {
      expectedNames.remove(t.getName());
    }
    assertEquals(0, expectedNames.size());
    runtimeService.deleteProcessInstance(pi.getId(), null);

    // Input == 3 -> default is not selected, "one or three" is selected
    pi = runtimeService.startProcessInstanceByKey("inclusiveGwDefaultSequenceFlow", CollectionUtil.singletonMap("input", 3));
    Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
    assertEquals("Input is three or one", task.getName());

    // Default input
    pi = runtimeService.startProcessInstanceByKey("inclusiveGwDefaultSequenceFlow", CollectionUtil.singletonMap("input", 5));
    task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
    assertEquals("Default input", task.getName());
  }

  @Deployment
  public void testNoIdOnSequenceFlow() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("inclusiveNoIdOnSequenceFlow", CollectionUtil.singletonMap("input", 3));
    Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
    assertEquals("Input is more than one", task.getName());

    // Both should be enabled on 1
    pi = runtimeService.startProcessInstanceByKey("inclusiveNoIdOnSequenceFlow", CollectionUtil.singletonMap("input", 1));
    List<Task> tasks = taskService.createTaskQuery().processInstanceId(pi.getId()).list();
    assertEquals(2, tasks.size());
    Map<String, String> expectedNames = new HashMap<String, String>();
    expectedNames.put("Input is one", "Input is one");
    expectedNames.put("Input is more than one", "Input is more than one");
    for (Task t : tasks) {
      expectedNames.remove(t.getName());
    }
    assertEquals(0, expectedNames.size());
  }

  /**
   * This test the isReachable() check that is done to check if upstream tokens can reach the inclusive gateway.
   *
   * In case of loops, special care needs to be taken in the algorithm, or else stackoverflows will happen very quickly.
   */
  @Deployment
  public void testLoop() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("inclusiveTestLoop", CollectionUtil.singletonMap("counter", 1));

    Task task = taskService.createTaskQuery().singleResult();
    assertEquals("task C", task.getName());

    taskService.complete(task.getId());
    assertEquals(0, taskService.createTaskQuery().count());

    assertEquals("Found executions: " + runtimeService.createExecutionQuery().list(), 0, runtimeService.createExecutionQuery().count());
    assertProcessEnded(pi.getId());
  }

  @Deployment
  public void testJoinAfterSubprocesses() {
    // Test case to test act-1204
    Map<String, Object> variableMap = new HashMap<String, Object>();
    variableMap.put("a", 1);
    variableMap.put("b", 1);
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("InclusiveGateway", variableMap);
    assertNotNull(processInstance.getId());

    List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
    assertEquals(2, taskService.createTaskQuery().count());

    taskService.complete(tasks.get(0).getId());
    assertEquals(1, taskService.createTaskQuery().count());

    taskService.complete(tasks.get(1).getId());

    Task task = taskService.createTaskQuery().taskAssignee("c").singleResult();
    assertNotNull(task);
    taskService.complete(task.getId());

    processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
    assertNull(processInstance);

    variableMap = new HashMap<String, Object>();
    variableMap.put("a", 1);
    variableMap.put("b", 2);
    processInstance = runtimeService.startProcessInstanceByKey("InclusiveGateway", variableMap);
    assertNotNull(processInstance.getId());

    tasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
    assertEquals(1, taskService.createTaskQuery().count());

    task = tasks.get(0);
    assertEquals("a", task.getAssignee());
    taskService.complete(task.getId());

    task = taskService.createTaskQuery().taskAssignee("c").singleResult();
    assertNotNull(task);
    taskService.complete(task.getId());

    processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
    assertNull(processInstance);

    variableMap = new HashMap<String, Object>();
    variableMap.put("a", 2);
    variableMap.put("b", 2);
    try {
      runtimeService.startProcessInstanceByKey("InclusiveGateway", variableMap);
      fail();
    } catch (FlowableException e) {
      assertTrue(e.getMessage().contains("No outgoing sequence flow"));
    }
  }

  @Deployment(resources = { "org/flowable/engine/test/bpmn/gateway/InclusiveGatewayTest.testJoinAfterCall.bpmn20.xml",
      "org/flowable/engine/test/bpmn/gateway/InclusiveGatewayTest.testJoinAfterCallSubProcess.bpmn20.xml" })
  public void testJoinAfterCall() {
    // Test case to test act-1026
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("InclusiveGatewayAfterCall");
    assertNotNull(processInstance.getId());
    assertEquals(3, taskService.createTaskQuery().count());

    // now complete task A and check number of remaining tasks.
    // inclusive gateway should wait for the "Task B" and "Task C"
    Task taskA = taskService.createTaskQuery().taskName("Task A").singleResult();
    assertNotNull(taskA);
    taskService.complete(taskA.getId());
    assertEquals(2, taskService.createTaskQuery().count());

    // now complete task B and check number of remaining tasks
    // inclusive gateway should wait for "Task C"
    Task taskB = taskService.createTaskQuery().taskName("Task B").singleResult();
    assertNotNull(taskB);
    taskService.complete(taskB.getId());
    assertEquals(1, taskService.createTaskQuery().count());

    // now complete task C. Gateway activates and "Task C" remains
    Task taskC = taskService.createTaskQuery().taskName("Task C").singleResult();
    assertNotNull(taskC);
    taskService.complete(taskC.getId());
    assertEquals(1, taskService.createTaskQuery().count());

    // check that remaining task is in fact task D
    Task taskD = taskService.createTaskQuery().taskName("Task D").singleResult();
    assertNotNull(taskD);
    assertEquals("Task D", taskD.getName());
    taskService.complete(taskD.getId());

    processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
    assertNull(processInstance);
  }

  @Deployment
  public void testAsyncBehavior() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("async");
    waitForJobExecutorToProcessAllJobs(5000L, 250);
    assertEquals(0, runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).count());
  }

  @Deployment
  public void testDirectSequenceFlow() {
    Map<String, Object> varMap = new HashMap<String, Object>();
    varMap.put("input", 1);
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("inclusiveGwDirectSequenceFlow", varMap);
    Task task = taskService.createTaskQuery().singleResult();
    assertNotNull(task);
    assertEquals("theTask1", task.getTaskDefinitionKey());
    taskService.complete(task.getId());
    assertEquals(0, runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).count());

    varMap = new HashMap<String, Object>();
    varMap.put("input", 3);
    processInstance = runtimeService.startProcessInstanceByKey("inclusiveGwDirectSequenceFlow", varMap);
    List<Task> tasks = taskService.createTaskQuery().list();
    assertEquals(2, tasks.size());
    taskService.complete(tasks.get(0).getId());
    taskService.complete(tasks.get(1).getId());
    assertEquals(0, runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).count());

    varMap = new HashMap<String, Object>();
    varMap.put("input", 0);
    processInstance = runtimeService.startProcessInstanceByKey("inclusiveGwDirectSequenceFlow", varMap);
    assertTrue(processInstance.isEnded());
  }

  @Deployment
  public void testSkipExpression() {
    Map<String, Object> varMap = new HashMap<String, Object>();
    varMap.put("_ACTIVITI_SKIP_EXPRESSION_ENABLED", true);
    varMap.put("input", 10);
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("inclusiveGwSkipExpression", varMap);
    Task task = taskService.createTaskQuery().singleResult();
    assertNotNull(task);
    assertEquals("theTask1", task.getTaskDefinitionKey());
    taskService.complete(task.getId());
    assertEquals(0, runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).count());

    varMap = new HashMap<String, Object>();
    varMap.put("_ACTIVITI_SKIP_EXPRESSION_ENABLED", true);
    varMap.put("input", 30);
    processInstance = runtimeService.startProcessInstanceByKey("inclusiveGwSkipExpression", varMap);
    List<Task> tasks = taskService.createTaskQuery().list();
    assertEquals(2, tasks.size());
    taskService.complete(tasks.get(0).getId());
    taskService.complete(tasks.get(1).getId());
    assertEquals(0, runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).count());

    varMap = new HashMap<String, Object>();
    varMap.put("_ACTIVITI_SKIP_EXPRESSION_ENABLED", true);
    varMap.put("input", 3);
    processInstance = runtimeService.startProcessInstanceByKey("inclusiveGwSkipExpression", varMap);
    assertTrue(processInstance.isEnded());
  }

  @Deployment
  public void testMultipleProcessInstancesMergedBug() {

    // Start first process instance, continue A. Process instance should be in C
    ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("testMultipleProcessInstancesMergedBug");
    taskService.complete(taskService.createTaskQuery().processInstanceId(processInstance1.getId()).taskName("A").singleResult().getId());
    Task taskCInPi1 = taskService.createTaskQuery().processInstanceId(processInstance1.getId()).singleResult();
    assertNotNull(taskCInPi1);

    // Start second process instance, continue A. Process instance should be in B
    ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("testMultipleProcessInstancesMergedBug", CollectionUtil.singletonMap("var", "goToB"));
    taskService.complete(taskService.createTaskQuery().processInstanceId(processInstance2.getId()).taskName("A").singleResult().getId());
    Task taskBInPi2 = taskService.createTaskQuery().processInstanceId(processInstance2.getId()).singleResult();
    assertNotNull(taskBInPi2);

    // Verify there is an inactive execution in the inclusive gateway before the task complete of process instance 1
    // (cannot combine activityId and inactive together, hence the workaround)
    assertEquals(2, getInactiveExecutionsInActivityId("inclusiveGw").size());

    // Completing C of PI 1 should not trigger C
    taskService.complete(taskCInPi1.getId());

    // Verify structure after complete.
    // Before bugfix: in BOTH process instances the inactive execution was removed (result was 0)
    assertEquals(1, getInactiveExecutionsInActivityId("inclusiveGw").size());

    assertEquals(1L, taskService.createTaskQuery().taskName("After Merge").count());

    // Finish both processes

    List<Task> tasks = taskService.createTaskQuery().list();
    while (tasks.size() > 0) {
      for (Task task : tasks) {
        taskService.complete(task.getId());
      }
      tasks = taskService.createTaskQuery().list();
    }
    assertEquals(0L, runtimeService.createProcessInstanceQuery().count());

  }

  protected List<Execution> getInactiveExecutionsInActivityId(String activityId) {
    List<Execution> result = new ArrayList<Execution>();
    List<Execution> executions = runtimeService.createExecutionQuery().list();
    Iterator<Execution> iterator = executions.iterator();
    while (iterator.hasNext()) {
      Execution execution = iterator.next();
      if (execution.getActivityId() != null
          && execution.getActivityId().equals(activityId)
          && !((ExecutionEntity) execution).isActive()) {
        result.add(execution);
      }
    }
    return result;
  }

  /*
   * @Deployment public void testAsyncBehavior() { for (int i = 0; i < 100; i++) { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("async"); } assertEquals(200,
   * managementService.createJobQuery().count()); waitForJobExecutorToProcessAllJobs(120000, 5000); assertEquals(0, managementService.createJobQuery().count()); assertEquals(0,
   * runtimeService.createProcessInstanceQuery().count()); }
   */

  // /* This test case is related to ACT-1877 */
  //
  // @Deployment(resources={"org/flowable/engine/test/bpmn/gateway/InclusiveGatewayTest.testWithSignalBoundaryEvent.bpmn20.xml"})
  // public void testJoinAfterBoudarySignalEvent() {
  //
  //
  // ProcessInstance processInstanceId =
  // runtimeService.startProcessInstanceByKey("InclusiveGatewayAfterSignalBoundaryEvent");
  //
  // /// Gets the execution waiting for a message notification*/
  // String subcriptedExecutionId =
  // runtimeService.createExecutionQuery().processInstanceId(processInstanceId.getId()).messageEventSubscriptionName("MyMessage").singleResult().getId();
  //
  // /*Notify message received: this makes one execution to go on*/
  // runtimeService.messageEventReceived("MyMessage", subcriptedExecutionId);
  //
  // /*The other execution goes on*/
  // Task userTask =
  // taskService.createTaskQuery().processInstanceId(processInstanceId.getId()).singleResult();
  // assertEquals("There's still an active execution waiting in the first task",
  // "usertask1",userTask.getTaskDefinitionKey());
  //
  // taskService.complete( userTask.getId());
  //
  // /*The two executions become one because of Inclusive Gateway*/
  // /*The process ends*/
  // userTask =
  // taskService.createTaskQuery().processInstanceId(processInstanceId.getId()).singleResult();
  // assertEquals("Only when both executions reach the inclusive gateway, flow arrives to the last user task",
  // "usertask2",userTask.getTaskDefinitionKey());
  // taskService.complete(userTask.getId());
  //
  // long nExecutions =
  // runtimeService.createExecutionQuery().processInstanceId(processInstanceId.getId()).count();
  // assertEquals(0, nExecutions);
  //
  // }
}


text:
<?php

use DTS\eBaySDK\Trading\Types\StoreInventoryEnabledDefinitionType;

class StoreInventoryEnabledDefinitionTypeTest extends \PHPUnit_Framework_TestCase
{
    private $obj;

    protected function setUp()
    {
        $this->obj = new StoreInventoryEnabledDefinitionType();
    }

    public function testCanBeCreated()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\Trading\Types\StoreInventoryEnabledDefinitionType', $this->obj);
    }

    public function testExtendsBaseType()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\Types\BaseType', $this->obj);
    }
}

redpajama_set_name: RedPajamaGithub


text:
{% extends "base.html" %}
{% from 'products/includes/product_macros.html' import product_cards with context %}
{% set title = _('Products') %}
{% set crumbs = [(None, title)] %}
{% set styles = ('products',) %}

{% set canonical_url = canonicalize(viewname='products') %}

{% block content %}

    {{ search_box(settings, id='support-search-products', params=search_params) }}

{{ title }}

    {{ product_cards(products) }}

{% endblock %}


text:
package com.nick.scalpel.core.binding;

import android.content.Context;
import android.os.Build;

import com.nick.scalpel.annotation.binding.FindColor;
import com.nick.scalpel.config.Configuration;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

import static com.nick.scalpel.core.utils.ReflectionUtils.setField;

class ColorFinder extends AbsIdFinder {

    public ColorFinder(Configuration configuration) {
        super(configuration);
    }

    @Override
    protected int getIdRes(Field field) {
        FindColor findColor = field.getAnnotation(FindColor.class);
        return findColor.id();
    }

    @Override
    protected void wireFromId(int id, Context context, Object object, Field field) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            setField(field, object, context.getResources().getColor(id, context.getTheme()));
        } else {
            //noinspection deprecation
            setField(field, object, context.getResources().getColor(id));
        }
    }

    @Override
    public Class<? extends Annotation> annotationClass() {
        return FindColor.class;
    }
}


text:
using System;
using System.Reflection;
using System.Security;

[assembly: CLSCompliant(true)]
[assembly: AllowPartiallyTrustedCallers]

[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("../../nunit.snk")]
[assembly: AssemblyKeyName("")]


text:
package com.google.android.enterprise.connectedapps.internal;

import android.os.Parcel;

/** This class is only for internal use by the SDK. */
public final class ParcelUtilities {
  private ParcelUtilities() {}

  public static void writeThrowableToParcel(Parcel parcel, Throwable throwable) {
    parcel.writeSerializable(throwable);
  }

  public static Throwable readThrowableFromParcel(Parcel parcel) {
    return (Throwable) parcel.readSerializable();
  }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Revue Mycol. , Paris 31(2): 163 (1966)

#### Original name
Endogonopsis sacramentarium R. Heim, 1966

### Remarks
null


text:
"""Setting up closed-form-matting package during pip installation"""

import os
import re

import setuptools

# Project root directory
root_dir = os.path.dirname(__file__)

# Get version string from __init__.py in the package
with open(os.path.join(root_dir, 'closed_form_matting', '__init__.py')) as f:
    version = re.search(r'__version__ = \'(.*?)\'', f.read()).group(1)

# Get dependency list from requirements.txt
with open(os.path.join(root_dir, 'requirements.txt')) as f:
    requirements = f.read().split()

setuptools.setup(
    name='closed-form-matting',
    version=version,
    author='Marco Forte',
    author_email='fortemarco.irl@gmail.com',
    maintainer='Marco Forte',
    maintainer_email='fortemarco.irl@gmail.com',
    url='https://github.com/MarcoForte/closed-form-matting',
    description='A closed-form solution to natural image matting',
    long_description=open(os.path.join(root_dir, 'README.md')).read(),
    long_description_content_type='text/markdown',
    packages=setuptools.find_packages(),
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Science/Research',
        'Topic :: Scientific/Engineering :: Image Processing',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
    ],
    keywords=['closed-form matting', 'image matting', 'image processing'],
    license='MIT',
    python_requires='>=3.5',
    install_requires=requirements,
    entry_points={
        'console_scripts': [
            'closed-form-matting=closed_form_matting.closed_form_matting:main',
            'solve-foreground-background=closed_form_matting.solve_foreground_background:main',
        ],
    },
)


text:
#import <Foundation/Foundation.h>
#import "PNTimeAPICallBuilder.h"
#import "PubNub+Core.h"

#pragma mark Class forward

@class PNErrorStatus, PNTimeResult;

NS_ASSUME_NONNULL_BEGIN

#pragma mark - API group interface

@interface PubNub (Time)

///------------------------------------------------
/// @name API Builder support
///------------------------------------------------

/**
 @brief      Stores reference on time API access \c builder construction block.
 @discussion On block call return builder which allow to configure parameters for time API access.

 @since 4.5.4
 */
@property (nonatomic, readonly, strong) PNTimeAPICallBuilder *(^time)(void);

///------------------------------------------------
/// @name Time token request
///------------------------------------------------

/**
 @brief      Request current time from \b PubNub service servers.
 @discussion \b Example:

 @code
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo"
                                                                  subscribeKey:@"demo"];
self.client = [PubNub clientWithConfiguration:configuration];
[self.client timeWithCompletion:^(PNTimeResult *result, PNErrorStatus *status) {

    // Check whether request successfully completed or not.
    if (!status.isError) {

        // Handle downloaded server time token using: result.data.timetoken
    }
    // Request processing failed.
    else {

        // Handle tmie token download error. Check 'category' property to find out possible
        // issue because of which request did fail.
        //
        // Request can be resent using: [status retry];
    }
}];
 @endcode

 @param block Time request process results handling block which pass two arguments: \c result - in
              case of successful request processing \c data field will contain server-provided time
              token; \c status - in case if error occurred during request processing.

 @since 4.0
 */
- (void)timeWithCompletion:(PNTimeCompletionBlock)block NS_SWIFT_NAME(timeWithCompletion(_:));

#pragma mark -

@end

NS_ASSUME_NONNULL_END


text:
from eventlet import greenthread
from eventlet import queue
from heleosapi import constants as h_con
from heleosapi import exceptions as h_exc

from neutron.openstack.common import log as logging
from neutron.plugins.embrane.agent.operations import router_operations
from neutron.plugins.embrane.common import constants as p_con
from neutron.plugins.embrane.common import contexts as ctx

LOG = logging.getLogger(__name__)

class Dispatcher(object):

    def __init__(self, plugin, async=True):
        self._async = async
        self._plugin = plugin
        self.sync_items = dict()

    def dispatch_l3(self, d_context, args=(), kwargs={}):
        item = d_context.item
        event = d_context.event
        q_context = d_context.q_context
        chain = d_context.chain

        item_id = item["id"]
        handlers = router_operations.handlers
        if event in handlers:
            for f in handlers[event]:
                first_run = False
                if item_id not in self.sync_items:
                    self.sync_items[item_id] = (queue.Queue(),)
                    first_run = True
                self.sync_items[item_id][0].put(
                    ctx.OperationContext(event, q_context, item, chain, f,
                                         args, kwargs))
                t = None
                if first_run:
                    t = greenthread.spawn(self._consume_l3,
                                          item_id,
                                          self.sync_items[item_id][0],
                                          self._plugin,
                                          self._async)
                    self.sync_items[item_id] += (t,)
                if not self._async:
                    t = self.sync_items[item_id][1]
                    t.wait()

    def _consume_l3(self, sync_item, sync_queue, plugin, a_sync):
        current_state = None
        while True:
            try:
                # If the DVA is deleted, the thread (and the associated queue)
                # can die as well
                if current_state == p_con.Status.DELETED:
                    del self.sync_items[sync_item]
                    return
                try:
                    # If synchronous op, empty the queue as fast as possible
                    operation_context = sync_queue.get(
                        block=a_sync,
                        timeout=p_con.QUEUE_TIMEOUT)
                except queue.Empty:
                    del self.sync_items[sync_item]
                    return
                # Execute the preliminary operations
                (operation_context.chain and
                 operation_context.chain.execute_all())
                # Execute the main operation, a transient state is maintained
                # so that the consumer can decide if it has
                # to be burned to the DB
                transient_state = None
                try:
                    dva_state = operation_context.function(
                        plugin._esm_api,
                        operation_context.q_context.tenant_id,
                        operation_context.item,
                        *operation_context.args,
                        **operation_context.kwargs)
                    if dva_state == p_con.Status.DELETED:
                        transient_state = dva_state
                    else:
                        if not dva_state:
                            transient_state = p_con.Status.ERROR
                        elif dva_state == h_con.DvaState.POWER_ON:
                            transient_state = p_con.Status.ACTIVE
                        else:
                            transient_state = p_con.Status.READY

                except (h_exc.PendingDva, h_exc.DvaNotFound,
                        h_exc.BrokenInterface, h_exc.DvaCreationFailed,
                        h_exc.DvaCreationPending, h_exc.BrokenDva,
                        h_exc.ConfigurationFailed) as ex:
                    LOG.warning(p_con.error_map[type(ex)] % ex.message)
                    transient_state = p_con.Status.ERROR
                except h_exc.DvaDeleteFailed as ex:
                    LOG.warning(p_con.error_map[type(ex)] % ex.message)
                    transient_state = p_con.Status.DELETED
                finally:
                    # if the returned transient state is None, no operations
                    # are required on the DVA status
                    if transient_state:
                        if transient_state == p_con.Status.DELETED:
                            current_state = plugin._delete_router(
                                operation_context.q_context,
                                operation_context.item["id"])
                        # Error state cannot be reverted
                        elif transient_state != p_con.Status.ERROR:
                            current_state = plugin._update_neutron_state(
                                operation_context.q_context,
                                operation_context.item,
                                transient_state)
            except Exception:
                LOG.exception(_("Unhandled exception occurred"))


text:
// Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in project root for information.

package com.microsoft.ml.spark

import com.microsoft.ml.spark.FileUtilities._
import com.microsoft.ml.spark.Readers.implicits._
import com.microsoft.ml.spark.schema.ImageSchema.isImage

object FileReaderSuiteUtils {
  val fileLocation = s"${sys.env("DATASETS_HOME")}"
  val imagesDirectory = fileLocation + "/Images"
  val groceriesDirectory = imagesDirectory + "/Grocery"
  val cifarDirectory = imagesDirectory + "/CIFAR"

  def createZip(directory: String): Unit ={
      val dir = new File(directory)
      val zipfile = new File(directory + ".zip")
      if (!zipfile.exists()) zipFolder(dir, zipfile)
  }

  def createZips(): Unit ={
    createZip(groceriesDirectory)
    createZip(cifarDirectory)
  }
}

import com.microsoft.ml.spark.FileReaderSuiteUtils._

class ImageReaderSuite extends TestBase {

  test("image dataframe") {

    val images = session.readImages(groceriesDirectory, recursive = true)

    println(time { images.count })

    assert(isImage(images, "image")) // make sure the column "images" exists and has the right type

    val paths = images.select("image.path") //make sure that SQL has access to the sub-fields
    assert(paths.count == 30)

    val areas = images.select(images("image.width") * images("image.height")) //more complicated SQL statement

    println(s"   area of image 1 ${areas.take(1)(0)}")
  }

  test("with zip file") {
    /* remove when datasets/Images is updated */
    createZips

    val images = session.readImages(imagesDirectory, recursive = true)
    assert(isImage(images, "image"))
    assert(images.count == 72)

    val images1 = session.readImages(imagesDirectory, recursive = true, inspectZip = false)
    assert(images1.count == 36)
  }

  test("sample ratio test") {

    sc.hadoopConfiguration.set("mapreduce.input.fileinputformat.input.dir.recursive", "true")

    val f = sc.binaryFiles(groceriesDirectory)
    println(time { f.count })

    val images = session.readImages(groceriesDirectory, recursive = true, sampleRatio = 0.5)
    println(time { images.count })      //the count changes depending on random number generator
  }

}


text:
var db = require('../config/db.js');
var User = require('./UserModel.js');
var Session = require('./SessionModel.js');
var Practice = require('./PracticeModel.js');

db.knex.schema.hasTable('snapshots').then(function(exists){
  if(!exists) {
    db.knex.schema.createTable('snapshots', function(snapshot) {
      snapshot.increments('id').primary();
      snapshot.integer('mood');
      snapshot.integer('gender-c');
      snapshot.string('gender-v');
      snapshot.integer('age');
      snapshot.integer('ethnicity-c');
      snapshot.string('ethnicity-v', 50);

      snapshot.integer('sadness');
      snapshot.integer('anger');
      snapshot.integer('surprise');
      snapshot.integer('fear');
      snapshot.integer('happiness');
      snapshot.integer('disgust');

      snapshot.integer('userId');
      snapshot.integer('sessionId');
      snapshot.integer('practice_id').unsigned().references('practices.id');
      snapshot.timestamps();
    }).then(function(){
      console.log('Snapshots table created')
    })
  }
});

var Snapshot = db.Model.extend({
  tableName: 'snapshots',
  hasTimestamps: true,
  user: function() {
    return this.belongsTo(User, 'userId');
  },
  session: function() {
    return this.belongsTo(Session, 'sessionId');
  },
  practice: function() {
    return this.belongsTo(Practice, 'practice_id');
  }
})

module.exports = Snapshot;


text:
@interface HRSSimpleIndexPathMappingTableViewController : UITableViewController

@end


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/csblogs_red</item>
        <item name="colorPrimaryDark">@color/csblogs_red_dark</item>
        <item name="colorAccent">@color/csblogs_red_accent</item>
    </style>

</resources>


text:
<!Doctype html>
<html>
    <head>
        <title>Holy Child Montessori</title>
        <style>html, body{
            margin: 0px;
            padding: 0px;
            overflow: hidden;
        }
        webview{
             width: 100vw;
            height: 95vh;
        }
        </style>
        <script>
        // Include jQuery
        window.$ = window.jQuery = require('jquery');
        // Include Libs
        const TitlebarWindows = require('electron-titlebar-windows');
        const {dialog} = require('electron').remote;
        const {shell} = require('electron')
        const remote = require('electron').remote;

        // Construct titlebar properties
        var opts = {
            backgroundColor: 'seagreen',
            draggable: true
        }
        const titlebar = new TitlebarWindows(opts);

        // Titlebar  events
        titlebar.on('minimize',function(e){
             var window = remote.getCurrentWindow();
             window.minimize();
        });

        titlebar.on('resize',function(e){
             var window = remote.getCurrentWindow();
            if (!window.isMaximized()) {
                window.maximize();
            } else {
                 window.unmaximize();
            }
        });

        titlebar.on('close', function(e) {
            var window = remote.getCurrentWindow();
            window.close();
        });
        </script>
    </head>
    <body>
    <script>
        // Initialize Toolbar
        titlebar.appendTo(document.body);
    </script>
        <div id='renderBlock'>
                    <webview src="http://hcmontessori.likesyou.org/account" minwidth="600" minheight="800" useragent="hcm-windows-1.0.0" allowpopups autosize></webview>
        </div>
    </body>
</html>
<script>
    // Starts script on page load
    $(document).ready(function(){
        init();
    });

    // Things to do when application window loads
    function init(){

        // Checks if there is network connection
        if(navigator.onLine){
        } else {
            dialog.showMessageBox({type:"error", title:"No Internet!", message:"You need an internet connection to use HCM for Windows.",detail:"Please connect to the internet before opening this application."},function(){window.close()})
        }
    }

    const webview = document.querySelector('webview')

    // Updates Application Title
    webview.addEventListener('page-title-updated', () => {
        var window = remote.getCurrentWindow();
        var vwTitle = webview.getTitle()
        window.setTitle(vwTitle);
    })

    // Listens if webview fails to load page
    webview.addEventListener('did-fail-load', () => {
        dialog.showMessageBox({type:"error", title:"Error Loading Application", message:"There was a problem loading the application", detail: "Please re-open this application to reload the application, you may be offline or there is a problem in our server."},function(){window.close()})
    })
</script>


text:
import * as bcrypt from 'bcryptjs';

import Image from './image';

export default function (sequelize, DataTypes) {

  const User = sequelize.define('User', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notEmpty: true,
      },
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notEmpty: true,
      },
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notEmpty: true,
      },
    },
  });

  User.associate = (models) => User.hasMany(models.Image);

  User.beforeCreate((user) => {
    return hashPassword(user);
  });

  User.beforeUpdate((user) => {
    return hashPassword(user);
  });

  function hashPassword(user) {
    const salt = bcrypt.genSaltSync(10);
    user.set('password', bcrypt.hashSync(user.password, salt));
  }

  return User;
}


text:
package collector

import (
	"fullerite/metric"

	"bufio"
	"encoding/json"
	"net"
	"strings"
	"time"

	l "github.com/Sirupsen/logrus"
)

const (
	// DefaultDiamondCollectorPort is the TCP port that diamond
	// collectors write to and we read off of.
	DefaultDiamondCollectorPort = "19191"
)

// Diamond collector type
type Diamond struct {
	baseCollector
	port          string
	serverStarted bool
	incoming      chan []byte
}

func init() {
	RegisterCollector("Diamond", newDiamond)
}

// newDiamond creates a new Diamond collector.
func newDiamond(channel chan metric.Metric, initialInterval int, log *l.Entry) Collector {
	d := new(Diamond)

	d.log = log
	d.channel = channel
	d.interval = initialInterval

	d.name = "Diamond"
	d.incoming = make(chan []byte)
	d.port = DefaultDiamondCollectorPort
	d.serverStarted = false
	d.SetCollectorType("listener")
	return d
}

// Configure the collector
func (d *Diamond) Configure(configMap map[string]interface{}) {
	if port, exists := configMap["port"]; exists {
		d.port = port.(string)
	}
	d.configureCommonParams(configMap)
}

// Port returns Diamond collectors listen port
func (d *Diamond) Port() string {
	return d.port
}

// collectDiamond opens up and reads from the a TCP socket and
// writes what it's read to a local channel. Diamond handler (running in
// separate processes) write to the same port.
//
// When Collect() is called it reads from the local channel converts
// strings to metrics and publishes metrics to handlers.
func (d *Diamond) collectDiamond() {
	addr, err := net.ResolveTCPAddr("tcp", ":"+d.port)

	if err != nil {
		panic(err)
	}

	l, err := net.ListenTCP("tcp4", addr)
	if err != nil {
		d.log.Fatal("Cannot listen on diamond socket", err)
	}

	// figure out the port bind for Port()
	d.port = strings.Split(l.Addr().String(), ":")[1]

	for {
		conn, err := l.AcceptTCP()
		if err != nil {
			d.log.Fatal(err)
		}
		go d.readDiamondMetrics(conn)
	}
}

// readDiamondMetrics reads from the connection
func (d *Diamond) readDiamondMetrics(conn *net.TCPConn) {
	defer conn.Close()
	conn.SetKeepAlive(true)
	conn.SetKeepAlivePeriod(time.Second)
	reader := bufio.NewReader(conn)
	d.log.Info("Connection started: ", conn.RemoteAddr())
	for {
		line, err := reader.ReadBytes('\n')
		if err != nil {
			d.log.Warn("Error while reading diamond metrics", err)
			break
		}
		d.log.Debug("Read: ", string(line))
		d.incoming <- line
	}
	d.log.Info("Connection closed: ", conn.RemoteAddr())
}

// Collect reads metrics collected from Diamond collectors, converts
// them to fullerite's Metric type and publishes them to handlers.
func (d *Diamond) Collect() {
	if !d.serverStarted {
		d.serverStarted = true
		go d.collectDiamond()
	}

	for line := range d.incoming {
		if metrics, ok := d.parseMetrics(line); ok {
			for _, metric := range metrics {
				d.Channel() <- metric
			}
		}
	}
}

func (d *Diamond) parseMetrics(line []byte) ([]metric.Metric, bool) {
	var metrics []metric.Metric
	if err := json.Unmarshal(line, &metrics); err != nil {
		d.log.Error("Cannot unmarshal metric line from diamond:", line)
		return metrics, false
	}
	// All diamond metric_types are reported in uppercase, lets make them
	// fullerite compatible
	for i := range metrics {
		metrics[i].MetricType = strings.ToLower(metrics[i].MetricType)
		metrics[i].AddDimension("diamond", "yes")
		metrics[i].SetTime(time.Now())
	}
	return metrics, true
}


text:
<?php

  /*****************************************************
  ** Title........: Tell A Friend Script Language File (English)
  ** Filename.....: language.en.inc.php
  ** Author.......: Ralf Stadtaus
  ** Homepage.....: http://www.stadtaus.com/
  ** Contact......: mailto:info@stadtaus.com
  ** Version......: 0.3
  ** Notes........: If you have translated this language
  **                file we would be happy if you could
  **                send us the file.
  **
  ** Last changed.: 2004-03-27
  ** Last change..:
  *****************************************************/

  $txt = array (

                   'txt_content_direction'            => 'ltr',
                   'txt_charset'                      => 'iso-8859-1',
                   'txt_cannot_lock_file'             => 'Kan inte låsa filen: ',
                   'txt_cannot_open_file'             => 'Kan inte öppna filen: ',
                   'txt_comment'                      => 'Kommentarer',
                   'txt_email'                        => 'Din e-mailadress',
                   'txt_fill_in'                      => 'Var vänlig fyll i följande fält:',
                   'txt_firstname'                    => 'Ditt förnamn',
                   'txt_friend_email'                 => 'Vännens e-mail Adress',
                   'txt_friend_name'                  => 'Friend\'s Name',
                   'txt_email_syntax'                 => 'Kontrollera e-mailadressen i följande fält:',
                   'txt_empty_referrer'               => 'Tom reference (tillåtna siter). Av säkerhetsskäl kan formuläret endast användas av sidor som är en del av denna webbsite. En tomt fält kan vara orsakad av din webbläsare, brandvägg eller andra program som döljer referensen. Beklagligt.',
                   'txt_ip_address_expiration'        => 'Du har skickat max antal e-mail från din IP-adress. Detta är en säkerhetsspärr för att förhindra missbruk av denna formuläret. Du kan använda formuläret igen, efter din nästa inloggning på internet.',
                   'txt_lastname'                     => 'Ditt efternamn',
                   'txt_mandatory_fields'             => 'Obligatoriska fält',
                   'txt_multiple_friend_email_1'      => 'E-mail Friend #1',
                   'txt_multiple_friend_email_2'      => 'E-mail Friend #2',
                   'txt_multiple_friend_email_3'      => 'E-mail Friend #3',
                   'txt_multiple_friend_email_4'      => 'E-mail Friend #4',
                   'txt_multiple_friend_name_1'       => 'Name Friend #1',
                   'txt_multiple_friend_name_2'       => 'Name Friend #2',
                   'txt_multiple_friend_name_3'       => 'Name Friend #3',
                   'txt_multiple_friend_name_4'       => 'Name Friend #4',
                   'txt_no'                           => 'Nej',
                   'txt_popen_error'                  => 'Funktionen popen() fel. Kunde inte utföras.',
                   'txt_preview'                      => 'Förhandsgranska',
                   'txt_problems'                     => '
Fått problem? Skript dokumentationen och instruktioner: ./docu/index.html

Få svar på dina frågor support forum på webbsidan för Tell A Friend Skript hos STADTAUS.com.
',
                   'txt_receive_information'          => 'Ta emot mer information?',
                   'txt_recipient_expiration'         => 'Du har nått taket för hur många e-mail du får sända till samma e-mailadress. Detta är en säkerhetsåtgärd för att förhindra missbruk av detta skript.',
                   'txt_required_firstname'           => 'Please enter your first name.',
                   'txt_required_friend_email'        => 'Please enter your friend\'s e-mail address.',
                   'txt_required_sender_email'        => 'Please enter your e-mail address.',
                   'txt_salutation'                   => 'Man eller kvinna',
                   'txt_script_name'                  => 'Tipsa En Vän Skript',
                   'txt_send_homepage'                => 'Eller vill du sända hemsidan?',
                   'txt_send_referer'                 => 'Vill du rekommendera sidan du just kom ifrån?',
                   'txt_sender_email'                 => 'Din e-mail Adress',
                   'txt_sender_expiration'            => 'Du har nått taket för hur många e-mail du får sända till samma e-mailadress. Detta är en säkerhetsåtgärd för att förhindra missbruk av detta skript.',
                   'txt_set_off_note'                 => 'Observera: När du har konfigurerat skriptet klart, bör du sätta system messages off i  (index.php - $show_error_messages).',
                   'txt_subject'                      => 'Ärende',
                   'txt_submit'                       => 'Skicka',
                   'txt_subscribe_newsletter'         => 'Prenumerera på nyhetsbrev?',
                   'txt_syntax_email'                 => 'Please enter a valid e-mail address.',
                   'txt_system_message'               => 'System Meddelande',
                   'txt_thank_you'                    => 'Thank you. Your recommendation e-mail is on its way.',
                   'txt_vote'                         => 'Gillar du Tipsa En Vän skriptet?',
                   'txt_welcome_text'                 => 'Tipsa en vän om den här sidan, om du tror det skulle vara intressant för henne eller honom.',
                   'txt_wrong_html_template'          => 'Den HTML-mall som du angivit i index.php filen index.php ($file[\'default_html\']) eller i <input type="hidden" name="html_template" value="" /> finns inte. Försäkra dig om att filens namn är rätt stavat och att filen finns i template biblioteket.',
                   'txt_wrong_ip_address'             => 'Den IP-adress du använder nu är "svartlistad" hos oss. Du kan inte använda denna funktion.',
                   'txt_wrong_mail_template'          => 'Den mail mall du definierat i index.php konfigurations filen index.php ($file[\'default_mail\']) eller i <input type="hidden" name="mail_template" value="" /> finns inte. Försäkra dig om att filens namn är rätt stavat och att filen finns i template biblioteket.',
                   'txt_wrong_referrer'               => 'Fel hänvisad site (referring site). Av säkerhetsskäl Tips En Vän kan bara användas av sidor som är en del av denna webbsite.',
                   'txt_wrong_referrer_admin'         => '

Observera Admin: Lägg till namnet på din server till referrer variabeln i index.php configuration file: ',
                   'txt_wrong_template_path'          => 'Sökvägen till template biblioteket är fel. Lägg till den korrekta sökvägen i variabeln $path[\'templates\'] i filen index.php',
                   'txt_yes'                          => 'Ja',
                   'txt_your_data'                    => 'Så här ser ditt meddelande ut.'

               );

?>


text:
// Copyright Kevlin Henney, 2000-2005.
// Copyright Alexander Nasonov, 2006-2010.
// Copyright Antony Polukhin, 2011-2014.
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// what:  lexical_cast custom keyword cast
// who:   contributed by Kevlin Henney,
//        enhanced with contributions from Terje Slettebo,
//        with additional fixes and suggestions from Gennaro Prota,
//        Beman Dawes, Dave Abrahams, Daryle Walker, Peter Dimov,
//        Alexander Nasonov, Antony Polukhin, Justin Viiret, Michael Hofmann,
//        Cheng Yang, Matthew Bradbury, David W. Birdsall, Pavel Korzh and other Boosters
// when:  November 2000, March 2003, June 2005, June 2006, March 2011 - 2014

#ifndef BOOST_LEXICAL_CAST_DETAIL_CONVERTER_LEXICAL_HPP
#define BOOST_LEXICAL_CAST_DETAIL_CONVERTER_LEXICAL_HPP

#include <boost/config.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#   pragma once
#endif

#if defined(BOOST_NO_STRINGSTREAM) || defined(BOOST_NO_STD_WSTRING)
#define BOOST_LCAST_NO_WCHAR_T
#endif

#include <cstddef>
#include <string>
#include <boost/limits.hpp>
#include <boost/mpl/if.hpp>
#include <boost/type_traits/ice.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <boost/type_traits/is_float.hpp>
#include <boost/type_traits/has_left_shift.hpp>
#include <boost/type_traits/has_right_shift.hpp>
#include <boost/static_assert.hpp>
#include <boost/detail/lcast_precision.hpp>

#include <boost/lexical_cast/detail/widest_char.hpp>
#include <boost/lexical_cast/detail/is_character.hpp>

#ifndef BOOST_NO_CXX11_HDR_ARRAY
#include <array>
#endif

#include <boost/array.hpp>
#include <boost/range/iterator_range_core.hpp>
#include <boost/container/container_fwd.hpp>

#include <boost/lexical_cast/detail/converter_lexical_streams.hpp>

namespace boost {

    namespace detail // normalize_single_byte_char<Char>
    {
        // Converts signed/unsigned char to char
        template < class Char >
        struct normalize_single_byte_char
        {
            typedef Char type;
        };

        template <>
        struct normalize_single_byte_char< signed char >
        {
            typedef char type;
        };

        template <>
        struct normalize_single_byte_char< unsigned char >
        {
            typedef char type;
        };
    }

    namespace detail // deduce_character_type_later<T>
    {
        // Helper type, meaning that stram character for T must be deduced
        // at Stage 2 (See deduce_source_char<T> and deduce_target_char<T>)
        template < class T > struct deduce_character_type_later {};
    }

    namespace detail // stream_char_common<T>
    {
        // Selectors to choose stream character type (common for Source and Target)
        // Returns one of char, wchar_t, char16_t, char32_t or deduce_character_type_later<T> types
        // Executed on Stage 1 (See deduce_source_char<T> and deduce_target_char<T>)
        template < typename Type >
        struct stream_char_common: public boost::mpl::if_c<
            boost::detail::is_character< Type >::value,
            Type,
            boost::detail::deduce_character_type_later< Type >
        > {};

        template < typename Char >
        struct stream_char_common< Char* >: public boost::mpl::if_c<
            boost::detail::is_character< Char >::value,
            Char,
            boost::detail::deduce_character_type_later< Char* >
        > {};

        template < typename Char >
        struct stream_char_common< const Char* >: public boost::mpl::if_c<
            boost::detail::is_character< Char >::value,
            Char,
            boost::detail::deduce_character_type_later< const Char* >
        > {};

        template < typename Char >
        struct stream_char_common< boost::iterator_range< Char* > >: public boost::mpl::if_c<
            boost::detail::is_character< Char >::value,
            Char,
            boost::detail::deduce_character_type_later< boost::iterator_range< Char* > >
        > {};

        template < typename Char >
        struct stream_char_common< boost::iterator_range< const Char* > >: public boost::mpl::if_c<
            boost::detail::is_character< Char >::value,
            Char,
            boost::detail::deduce_character_type_later< boost::iterator_range< const Char* > >
        > {};

        template < class Char, class Traits, class Alloc >
        struct stream_char_common< std::basic_string< Char, Traits, Alloc > >
        {
            typedef Char type;
        };

        template < class Char, class Traits, class Alloc >
        struct stream_char_common< boost::container::basic_string< Char, Traits, Alloc > >
        {
            typedef Char type;
        };

        template < typename Char, std::size_t N >
        struct stream_char_common< boost::array< Char, N > >: public boost::mpl::if_c<
            boost::detail::is_character< Char >::value,
            Char,
            boost::detail::deduce_character_type_later< boost::array< Char, N > >
        > {};

        template < typename Char, std::size_t N >
        struct stream_char_common< boost::array< const Char, N > >: public boost::mpl::if_c<
            boost::detail::is_character< Char >::value,
            Char,
            boost::detail::deduce_character_type_later< boost::array< const Char, N > >
        > {};

#ifndef BOOST_NO_CXX11_HDR_ARRAY
        template < typename Char, std::size_t N >
        struct stream_char_common< std::array<Char, N > >: public boost::mpl::if_c<
            boost::detail::is_character< Char >::value,
            Char,
            boost::detail::deduce_character_type_later< std::array< Char, N > >
        > {};

        template < typename Char, std::size_t N >
        struct stream_char_common< std::array< const Char, N > >: public boost::mpl::if_c<
            boost::detail::is_character< Char >::value,
            Char,
            boost::detail::deduce_character_type_later< std::array< const Char, N > >
        > {};
#endif

#ifdef BOOST_HAS_INT128
        template <> struct stream_char_common< boost::int128_type >: public boost::mpl::identity< char > {};
        template <> struct stream_char_common< boost::uint128_type >: public boost::mpl::identity< char > {};
#endif

#if !defined(BOOST_LCAST_NO_WCHAR_T) && defined(BOOST_NO_INTRINSIC_WCHAR_T)
        template <>
        struct stream_char_common< wchar_t >
        {
            typedef char type;
        };
#endif
    }

    namespace detail // deduce_source_char_impl<T>
    {
        // If type T is `deduce_character_type_later` type, then tries to deduce
        // character type using boost::has_left_shift<T> metafunction.
        // Otherwise supplied type T is a character type, that must be normalized
        // using normalize_single_byte_char<Char>.
        // Executed at Stage 2  (See deduce_source_char<T> and deduce_target_char<T>)
        template < class Char >
        struct deduce_source_char_impl
        {
            typedef BOOST_DEDUCED_TYPENAME boost::detail::normalize_single_byte_char< Char >::type type;
        };

        template < class T >
        struct deduce_source_char_impl< deduce_character_type_later< T > >
        {
            typedef boost::has_left_shift< std::basic_ostream< char >, T > result_t;

#if defined(BOOST_LCAST_NO_WCHAR_T)
            BOOST_STATIC_ASSERT_MSG((result_t::value),
                "Source type is not std::ostream`able and std::wostream`s are not supported by your STL implementation");
            typedef char type;
#else
            typedef BOOST_DEDUCED_TYPENAME boost::mpl::if_c<
                result_t::value, char, wchar_t
            >::type type;

            BOOST_STATIC_ASSERT_MSG((result_t::value || boost::has_left_shift< std::basic_ostream< type >, T >::value),
                "Source type is neither std::ostream`able nor std::wostream`able");
#endif
        };
    }

    namespace detail  // deduce_target_char_impl<T>
    {
        // If type T is `deduce_character_type_later` type, then tries to deduce
        // character type using boost::has_right_shift<T> metafunction.
        // Otherwise supplied type T is a character type, that must be normalized
        // using normalize_single_byte_char<Char>.
        // Executed at Stage 2  (See deduce_source_char<T> and deduce_target_char<T>)
        template < class Char >
        struct deduce_target_char_impl
        {
            typedef BOOST_DEDUCED_TYPENAME normalize_single_byte_char< Char >::type type;
        };

        template < class T >
        struct deduce_target_char_impl< deduce_character_type_later<T> >
        {
            typedef boost::has_right_shift<std::basic_istream<char>, T > result_t;

#if defined(BOOST_LCAST_NO_WCHAR_T)
            BOOST_STATIC_ASSERT_MSG((result_t::value),
                "Target type is not std::istream`able and std::wistream`s are not supported by your STL implementation");
            typedef char type;
#else
            typedef BOOST_DEDUCED_TYPENAME boost::mpl::if_c<
                result_t::value, char, wchar_t
            >::type type;

            BOOST_STATIC_ASSERT_MSG((result_t::value || boost::has_right_shift<std::basic_istream<wchar_t>, T >::value),
                "Target type is neither std::istream`able nor std::wistream`able");
#endif
        };
    }

    namespace detail  // deduce_target_char<T> and deduce_source_char<T>
    {
        // We deduce stream character types in two stages.
        //
        // Stage 1 is common for Target and Source. At Stage 1 we get
        // non normalized character type (may contain unsigned/signed char)
        // or deduce_character_type_later<T> where T is the original type.
        // Stage 1 is executed by stream_char_common<T>
        //
        // At Stage 2 we normalize character types or try to deduce character
        // type using metafunctions.
        // Stage 2 is executed by deduce_target_char_impl<T> and
        // deduce_source_char_impl<T>
        //
        // deduce_target_char<T> and deduce_source_char<T> functions combine
        // both stages

        template < class T >
        struct deduce_target_char
        {
            typedef BOOST_DEDUCED_TYPENAME stream_char_common< T >::type stage1_type;
            typedef BOOST_DEDUCED_TYPENAME deduce_target_char_impl< stage1_type >::type stage2_type;

            typedef stage2_type type;
        };

        template < class T >
        struct deduce_source_char
        {
            typedef BOOST_DEDUCED_TYPENAME stream_char_common< T >::type stage1_type;
            typedef BOOST_DEDUCED_TYPENAME deduce_source_char_impl< stage1_type >::type stage2_type;

            typedef stage2_type type;
        };
    }

    namespace detail // extract_char_traits template
    {
        // We are attempting to get char_traits<> from T
        // template parameter. Otherwise we'll be using std::char_traits<Char>
        template < class Char, class T >
        struct extract_char_traits
                : boost::false_type
        {
            typedef std::char_traits< Char > trait_t;
        };

        template < class Char, class Traits, class Alloc >
        struct extract_char_traits< Char, std::basic_string< Char, Traits, Alloc > >
            : boost::true_type
        {
            typedef Traits trait_t;
        };

        template < class Char, class Traits, class Alloc>
        struct extract_char_traits< Char, boost::container::basic_string< Char, Traits, Alloc > >
            : boost::true_type
        {
            typedef Traits trait_t;
        };
    }

    namespace detail // array_to_pointer_decay<T>
    {
        template<class T>
        struct array_to_pointer_decay
        {
            typedef T type;
        };

        template<class T, std::size_t N>
        struct array_to_pointer_decay<T[N]>
        {
            typedef const T * type;
        };
    }

    namespace detail // is_this_float_conversion_optimized<Float, Char>
    {
        // this metafunction evaluates to true, if we have optimized comnversion
        // from Float type to Char array.
        // Must be in sync with lexical_stream_limited_src<Char, ...>::shl_real_type(...)
        template <typename Float, typename Char>
        struct is_this_float_conversion_optimized
        {
            typedef boost::type_traits::ice_and<
                boost::is_float<Float>::value,
#if !defined(BOOST_LCAST_NO_WCHAR_T) && !defined(BOOST_NO_SWPRINTF) && !defined(__MINGW32__)
                boost::type_traits::ice_or<
                    boost::type_traits::ice_eq<sizeof(Char), sizeof(char) >::value,
                    boost::is_same<Char, wchar_t>::value
                >::value
#else
                boost::type_traits::ice_eq<sizeof(Char), sizeof(char) >::value
#endif
            > result_type;

            BOOST_STATIC_CONSTANT(bool, value = (result_type::value) );
        };
    }

    namespace detail // lcast_src_length
    {
        // Return max. length of string representation of Source;
        template< class Source,         // Source type of lexical_cast.
                  class Enable = void   // helper type
                >
        struct lcast_src_length
        {
            BOOST_STATIC_CONSTANT(std::size_t, value = 1);
        };

        // Helper for integral types.
        // Notes on length calculation:
        // Max length for 32bit int with grouping "\1" and thousands_sep ',':
        // "-2,1,4,7,4,8,3,6,4,7"
        //  ^                    - is_signed
        //   ^                   - 1 digit not counted by digits10
        //    ^^^^^^^^^^^^^^^^^^ - digits10 * 2
        //
        // Constant is_specialized is used instead of constant 1
        // to prevent buffer overflow in a rare case when
        // <boost/limits.hpp> doesn't add missing specialization for
        // numeric_limits<T> for some integral type T.
        // When is_specialized is false, the whole expression is 0.
        template <class Source>
        struct lcast_src_length<
                    Source, BOOST_DEDUCED_TYPENAME boost::enable_if<boost::is_integral<Source> >::type
                >
        {
#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
            BOOST_STATIC_CONSTANT(std::size_t, value =
                  std::numeric_limits<Source>::is_signed +
                  std::numeric_limits<Source>::is_specialized + /* == 1 */
                  std::numeric_limits<Source>::digits10 * 2
              );
#else
            BOOST_STATIC_CONSTANT(std::size_t, value = 156);
            BOOST_STATIC_ASSERT(sizeof(Source) * CHAR_BIT <= 256);
#endif
        };

#ifndef BOOST_LCAST_NO_COMPILE_TIME_PRECISION
        // Helper for floating point types.
        // -1.23456789e-123456
        // ^                   sign
        //  ^                  leading digit
        //   ^                 decimal point
        //    ^^^^^^^^         lcast_precision<Source>::value
        //            ^        "e"
        //             ^       exponent sign
        //              ^^^^^^ exponent (assumed 6 or less digits)
        // sign + leading digit + decimal point + "e" + exponent sign == 5
        template<class Source>
        struct lcast_src_length<
                Source, BOOST_DEDUCED_TYPENAME boost::enable_if<boost::is_float<Source> >::type
            >
        {
            BOOST_STATIC_ASSERT(
                    std::numeric_limits<Source>::max_exponent10 <=  999999L &&
                    std::numeric_limits<Source>::min_exponent10 >= -999999L
                );

            BOOST_STATIC_CONSTANT(std::size_t, value =
                    5 + lcast_precision<Source>::value + 6
                );
        };
#endif // #ifndef BOOST_LCAST_NO_COMPILE_TIME_PRECISION
    }

    namespace detail // lexical_cast_stream_traits<Source, Target>
    {
        template <class Source, class Target>
        struct lexical_cast_stream_traits {
            typedef BOOST_DEDUCED_TYPENAME boost::detail::array_to_pointer_decay<Source>::type src;
            typedef BOOST_DEDUCED_TYPENAME boost::remove_cv<src>::type            no_cv_src;

            typedef boost::detail::deduce_source_char<no_cv_src>                           deduce_src_char_metafunc;
            typedef BOOST_DEDUCED_TYPENAME deduce_src_char_metafunc::type           src_char_t;
            typedef BOOST_DEDUCED_TYPENAME boost::detail::deduce_target_char<Target>::type target_char_t;

            typedef BOOST_DEDUCED_TYPENAME boost::detail::widest_char<
                target_char_t, src_char_t
            >::type char_type;

#if !defined(BOOST_NO_CXX11_CHAR16_T) && defined(BOOST_NO_CXX11_UNICODE_LITERALS)
            BOOST_STATIC_ASSERT_MSG(( !boost::is_same<char16_t, src_char_t>::value
                                        && !boost::is_same<char16_t, target_char_t>::value),
                "Your compiler does not have full support for char16_t" );
#endif
#if !defined(BOOST_NO_CXX11_CHAR32_T) && defined(BOOST_NO_CXX11_UNICODE_LITERALS)
            BOOST_STATIC_ASSERT_MSG(( !boost::is_same<char32_t, src_char_t>::value
                                        && !boost::is_same<char32_t, target_char_t>::value),
                "Your compiler does not have full support for char32_t" );
#endif

            typedef BOOST_DEDUCED_TYPENAME boost::mpl::if_c<
                boost::detail::extract_char_traits<char_type, Target>::value,
                BOOST_DEDUCED_TYPENAME boost::detail::extract_char_traits<char_type, Target>,
                BOOST_DEDUCED_TYPENAME boost::detail::extract_char_traits<char_type, no_cv_src>
            >::type::trait_t traits;

            typedef boost::type_traits::ice_and<
                boost::is_same<char, src_char_t>::value,                                  // source is not a wide character based type
                boost::type_traits::ice_ne<sizeof(char), sizeof(target_char_t) >::value,  // target type is based on wide character
                boost::type_traits::ice_not<
                    boost::detail::is_character<no_cv_src>::value                     // single character widening is optimized
                >::value                                                                  // and does not requires stringbuffer
            >   is_string_widening_required_t;

            typedef boost::type_traits::ice_not< boost::type_traits::ice_or<
                boost::is_integral<no_cv_src>::value,
                boost::detail::is_this_float_conversion_optimized<no_cv_src, char_type >::value,
                boost::detail::is_character<
                    BOOST_DEDUCED_TYPENAME deduce_src_char_metafunc::stage1_type          // if we did not get character type at stage1
                >::value                                                                  // then we have no optimization for that type
            >::value >   is_source_input_not_optimized_t;

            // If we have an optimized conversion for
            // Source, we do not need to construct stringbuf.
            BOOST_STATIC_CONSTANT(bool, requires_stringbuf =
                (boost::type_traits::ice_or<
                    is_string_widening_required_t::value, is_source_input_not_optimized_t::value
                >::value)
            );

            typedef boost::detail::lcast_src_length<no_cv_src> len_t;
        };
    }

    namespace detail
    {
        template<typename Target, typename Source>
        struct lexical_converter_impl
        {
            typedef lexical_cast_stream_traits<Source, Target>  stream_trait;

            typedef detail::lexical_istream_limited_src<
                BOOST_DEDUCED_TYPENAME stream_trait::char_type,
                BOOST_DEDUCED_TYPENAME stream_trait::traits,
                stream_trait::requires_stringbuf,
                stream_trait::len_t::value + 1
            > i_interpreter_type;

            typedef detail::lexical_ostream_limited_src<
                BOOST_DEDUCED_TYPENAME stream_trait::char_type,
                BOOST_DEDUCED_TYPENAME stream_trait::traits
            > o_interpreter_type;

            static inline bool try_convert(const Source& arg, Target& result) {
                i_interpreter_type i_interpreter;

                // Disabling ADL, by directly specifying operators.
                if (!(i_interpreter.operator <<(arg)))
                    return false;

                o_interpreter_type out(i_interpreter.cbegin(), i_interpreter.cend());

                // Disabling ADL, by directly specifying operators.
                if(!(out.operator >>(result)))
                    return false;

                return true;
            }
        };
    }

} // namespace boost

#undef BOOST_LCAST_NO_WCHAR_T

#endif // BOOST_LEXICAL_CAST_DETAIL_CONVERTER_LEXICAL_HPP


text:
package utils;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtil {
	private static SqlSessionFactory sf;

	/*
	 * ¼ÓÔØÅäÖÃÎļþ
	 */
	static{
		SqlSessionFactoryBuilder builder  = new SqlSessionFactoryBuilder();
		sf= builder.build(MybatisUtil.class.getClassLoader().getResourceAsStream("mybatisConf.xml"));
	}

	/**
	 * »ñÈ¡Á¬½Ó
	 * @return
	 */
	public static SqlSession getSqlSession(){
		return sf.openSession();
	}

	/**
	 * ¹Ø±ÕÁ¬½Ó
	 * @param session
	 */
	public static void close(SqlSession session){
		if(session!=null){
			session.close();
		}
	}
}


text:
Hi there~

My name is Nathan, I'm a software developer and general technical problem solver. You can find this blog on [GitHub](https://github.com/nmcginn/blog).

There should be some posts around here somewhere. Some of them may be worth reading, some may not be.

¯\\\_(ツ)\_/¯


text:
package com.cody.xf.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.View;

import com.cody.xf.XFoundation;

/**
 * Created by dong.wang
 * Date: 2016/7/27
 * Time: 10:14
 * Description:
 */
public class DeviceUtil {

    private static int sDensityDpi;
    private static float sDensity;
    private static float sScreenHeight;
    private static float sScreenWidth;
    private static float sScreenWidthDpi;
    private static float sScreenHeightDpi;

    /**
     * dp---> px
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * px-->dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    // 将px值转换为sp值,保证文字大小不变
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    // 将sp值转换为px值,保证文字大小不变
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    private static void getInfoFromDisplayMetrics() {
        DisplayMetrics display = XFoundation.getContext().getResources()
                .getDisplayMetrics();
        sDensityDpi = display.densityDpi;
        sDensity = display.density;
        sScreenHeight = display.heightPixels;
        sScreenWidth = display.widthPixels;
        sScreenWidthDpi = (sScreenWidth / sDensity);
        sScreenHeightDpi = (sScreenHeight / sDensity);
    }

    public static float getDensity() {
        return sDensity;
    }

    public static float getScreenWidth() {
        getInfoFromDisplayMetrics();
        return sScreenWidth;
    }

    public static float getScreenHeight() {
        getInfoFromDisplayMetrics();
        return sScreenHeight;
    }

    public static Float getScreenWidthDpi() {
        if (sScreenWidthDpi == 0) {
            getInfoFromDisplayMetrics();
        }
        return sScreenWidthDpi;
    }

    public static Float getScreenHeightDpi() {
        if (sScreenHeightDpi == 0) {
            getInfoFromDisplayMetrics();
        }
        return sScreenHeightDpi;
    }

    /**
     * 获取IMEI号
     */
    public static String getDeviceId(Context context) {
        TelephonyManager mTm = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        return mTm.getDeviceId();
    }

    //版本名
    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    //版本号
    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    public static boolean isWifi(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    /**
     * 手机系统版本
     */
    public static String getSdkVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 测量View的宽高
     *
     * @param view View
     */
    public static void measureWidthAndHeight(View view) {
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(widthMeasureSpec, heightMeasureSpec);
    }

    /**
     * 获取状态栏高度
     *
     * @return 状态栏高度
     */
    public static int getStatusBarHeight() {
        int statusBarHeight = DeviceUtil.dip2px(XFoundation.getContext(), 20);
        //获取status_bar_height资源的ID
        int resourceId = XFoundation.getContext().getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight = XFoundation.getContext().getResources().getDimensionPixelSize(resourceId);
        }
        return statusBarHeight;
    }
}


text:
//
//  YGMapManagerView.h
//  CashBack
//
//  Created by Rainy on 2017/12/4.
//  Copyright © 2017年 Rainy. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

typedef void(^LatitudeAndLongitude)(CLLocationDegrees latitude,CLLocationDegrees longitude);
typedef void(^Address)(NSString *address);

@interface YGMapManagerView : UIView

/** @[YGAnnotation] */
@property(nonatomic,strong)NSArray *annotationPins;
/** 获取当前位置 */
- (void)getCurrentLocation:(LatitudeAndLongitude)latitudeAndLongitude
                   address:(Address)address;
/** 自带地图app导航 */
+ (void)navigateTolatitude:(CLLocationDegrees)latitude
                 longitude:(CLLocationDegrees)longitude;

@end


text:
/*Generated By KISSY Module Compiler*/
config({
'combobox': {requires: ['node','component/control','menu','attribute','io']}
});


text:
class AddCommentCountToTasks < ActiveRecord::Migration
  def change
  	change_table :nimbos_tasks do |t|
      t.integer  :comments_count, default: 0
    end
  end
end


text:
namespace Superscribe.WebApi
{
    using System.Net;
    using System.Net.Http;
    using System.Threading;
    using System.Threading.Tasks;

    using Superscribe.Models;

    public class SuperscribeHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var provider = request.GetRouteDataProvider();
            var info = provider.GetData(request);

            if (info.ExtraneousMatch || !info.FinalFunctionExecuted || info.Response is FinalFunction.ExecuteAndContinue)
            {
                return base.SendAsync(request, cancellationToken);
            }

            var responseMessage = info.Response as HttpResponseMessage;
            if (responseMessage != null)
            {
                return Task.FromResult(responseMessage);
            }

            var statusCode = info.Response as HttpStatusCode?;
            if (statusCode != null)
            {
                return Task.FromResult(request.CreateResponse(statusCode.Value));
            }

            return Task.FromResult(request.CreateResponse(HttpStatusCode.OK, info.Response));
        }
    }
}


text:
<?php get_header(); ?>

<?php the_post() ?>

<a href="<?php echo get_permalink($post->post_parent) ?>" rev="attachment"><?php echo get_the_title($post->post_parent) ?>

				<div id="post-<?php the_ID(); ?>" class="<?php blogtxt_post_class(); ?>">

<?php the_title(); ?>

<a href="<?php echo wp_get_attachment_url($post->ID); ?>" title="<?php echo wp_specialchars( get_the_title($post->ID), 1 ) ?>" rel="attachment"><?php echo basename($post->guid) ?>

<?php if ( !empty($post->post_excerpt) ) the_excerpt(); ?>

<?php the_content(''.__('Continue reading ›', 'blogtxt').''); ?>

<?php comments_template(); ?>

<a href="<?php bloginfo('home') ?>" title="<?php echo wp_specialchars(get_bloginfo('name'), 1) ?>"><?php _e('« Home', 'blogtxt'); ?>

<?php _e('About This Post', 'blogtxt') ?>

<?php printf(__('Posted by %s', 'blogtxt'), blogtxt_author_link() ) ?>

<?php printf(__('%3$s at %4$s', 'blogtxt'), get_the_time('Y-m-d'), get_the_time('H:i:sO'), get_the_time('F jS, Y'), get_the_time() ) ?>

					<?php edit_post_link(__('Edit this entry', 'blogtxt'),'
≡ ','
') ?>

<?php _e('Interact', 'blogtxt') ?>

<?php if (('open' == $post-> comment_status) && ('open' == $post->ping_status)) : ?>

<?php _e('Post a comment', 'blogtxt') ?>

<?php printf(__('Trackback URI', 'blogtxt'), get_trackback_url() ) ?>

<?php elseif (!('open' == $post-> comment_status) && ('open' == $post->ping_status)) : ?>

<?php _e('Comments closed', 'blogtxt') ?>

<?php printf(__('Trackback URI', 'blogtxt'), get_trackback_url() ) ?>

<?php elseif (('open' == $post-> comment_status) && !('open' == $post->ping_status)) : ?>

<?php _e('Post a comment', 'blogtxt') ?>

<?php _e('Trackbacks closed', 'blogtxt') ?>

<?php elseif (!('open' == $post-> comment_status) && !('open' == $post->ping_status)) : ?>

<?php _e('Comments closed', 'blogtxt') ?>

<?php _e('Trackbacks closed', 'blogtxt') ?>

<?php endif; ?>

<?php _e('RSS Feeds', 'blogtxt') ?>

<?php comments_rss_link(__('Comments to this post', 'blogtxt')); ?>

<a href="<?php bloginfo('rss2_url') ?>" title="<?php echo wp_specialchars(get_bloginfo('name'), 1) ?> RSS 2.0 Feed" rel="alternate" type="application/rss+xml"><?php _e('All posts', 'blogtxt') ?>

<a href="<?php bloginfo('comments_rss2_url') ?>" title="<?php echo wp_specialchars(bloginfo('name'), 1) ?> Comments RSS 2.0 Feed" rel="alternate" type="application/rss+xml"><?php _e('All comments', 'blogtxt') ?>

<?php _e('Search', 'blogtxt') ?>

				<form id="searchform" method="get" action="<?php bloginfo('home') ?>">

						<input id="s" name="s" type="text" value="<?php echo wp_specialchars(stripslashes($_GET['s']), true) ?>" size="10" />
						<input id="searchsubmit" name="searchsubmit" type="submit" value="<?php _e('Find', 'blogtxt') ?>" />

				</form>

<?php get_footer() ?>