text:
package mockit.emulation.hibernate3;

import java.io.*;
import java.lang.reflect.*;
import java.sql.*;
import java.util.*;

import org.hibernate.*;
import org.hibernate.jdbc.*;
import org.hibernate.stat.*;

@SuppressWarnings({"ClassWithTooManyMethods", "OverlyCoupledClass"})
class SessionEmul implements Session
{
   final Map<Serializable, Object> entityCache = new HashMap<Serializable, Object>();
   final Map<Serializable, Object> loadedEntities = new HashMap<Serializable, Object>();
   final SessionFactory sessionFactory;
   Connection connection;
   FlushMode flushMode = FlushMode.AUTO;
   CacheMode cacheMode = CacheMode.NORMAL;
   boolean open;

   SessionEmul(SessionFactory sessionFactory, Connection connection)
   {
      this.sessionFactory = sessionFactory;
      this.connection = connection;
   }

   public EntityMode getEntityMode()
   {
      return null;
   }

   public Session getSession(EntityMode entityMode)
   {
      return null;
   }

   public void flush()
   {
   }

   public void setFlushMode(FlushMode flushMode)
   {
      this.flushMode = flushMode;
   }

   public FlushMode getFlushMode()
   {
      return flushMode;
   }

   public void setCacheMode(CacheMode cacheMode)
   {
      this.cacheMode = cacheMode;
   }

   public CacheMode getCacheMode()
   {
      return cacheMode;
   }

   public SessionFactory getSessionFactory()
   {
      return sessionFactory;
   }

   public Connection connection()
   {
      return connection;
   }

   public Connection close()
   {
      open = false;
      Connection currentConnection = connection;
      connection = null;
      return currentConnection;
   }

   public void cancelQuery()
   {
   }

   public boolean isOpen()
   {
      return open;
   }

   public boolean isConnected()
   {
      return connection != null;
   }

   public boolean isDirty()
   {
      return false;
   }

   public Serializable getIdentifier(Object object)
   {
      try {
         Method idGetter = object.getClass().getMethod("getId");
         return (Serializable) idGetter.invoke(object);
      }
      catch (NoSuchMethodException e) {
         throw new RuntimeException(e);
      }
      catch (IllegalAccessException e) {
         throw new RuntimeException(e);
      }
      catch (InvocationTargetException e) {
         throw new RuntimeException(e);
      }
   }

   public boolean contains(Object object)
   {
      return loadedEntities.containsValue(object);
   }

   public void evict(Object object)
   {
      Serializable id = getIdentifier(object);
      loadedEntities.remove(id);
   }

   @SuppressWarnings({"RawUseOfParameterizedType"})
   public Object load(Class theClass, Serializable id, LockMode lockMode)
   {
      return load(theClass, id);
   }

   public Object load(String entityName, Serializable id, LockMode lockMode)
   {
      return null;
   }

   @SuppressWarnings({"RawUseOfParameterizedType"})
   public Object load(Class theClass, Serializable id) throws ObjectNotFoundException
   {
      Object entity = get(theClass, id);

      if (entity == null) {
         throw new ObjectNotFoundException(id, theClass.getName());
      }

      return entity;
   }

   public Object load(String entityName, Serializable id)
   {
      return null;
   }

   public void load(Object object, Serializable id)
   {
   }

   public void replicate(Object object, ReplicationMode replicationMode)
   {
   }

   public void replicate(String entityName, Object object, ReplicationMode replicationMode)
   {
   }

   public Serializable save(Object object)
   {
      Serializable id = getIdentifier(object);
      loadedEntities.put(id, object);
      entityCache.put(id, object);
      return id;
   }

   public Serializable save(String entityName, Object object)
   {
      return null;
   }

   public void saveOrUpdate(Object object)
   {
   }

   public void saveOrUpdate(String entityName, Object object)
   {
   }

   public void update(Object object)
   {
   }

   public void update(String entityName, Object object)
   {
   }

   public Object merge(Object object)
   {
      return null;
   }

   public Object merge(String entityName, Object object)
   {
      return null;
   }

   public void persist(Object object)
   {
      save(object);
   }

   public void persist(String entityName, Object object)
   {
   }

   public void delete(Object object)
   {
      Serializable id = getIdentifier(object);
      loadedEntities.remove(id);
      entityCache.remove(id);
   }

   public void delete(String entityName, Object object)
   {
   }

   public void lock(Object object, LockMode lockMode)
   {
   }

   public void lock(String entityName, Object object, LockMode lockMode)
   {
   }

   public void refresh(Object object)
   {
   }

   public void refresh(Object object, LockMode lockMode)
   {
   }

   public LockMode getCurrentLockMode(Object object)
   {
      return null;
   }

   public Transaction beginTransaction()
   {
      return null;
   }

   public Transaction getTransaction()
   {
      return new TransactionEmul();
   }

   @SuppressWarnings({"RawUseOfParameterizedType"})
   public Criteria createCriteria(Class persistentClass)
   {
      return null;
   }

   @SuppressWarnings({"RawUseOfParameterizedType"})
   public Criteria createCriteria(Class persistentClass, String alias)
   {
      return null;
   }

   public Criteria createCriteria(String entityName)
   {
      return null;
   }

   public Criteria createCriteria(String entityName, String alias)
   {
      return null;
   }

   public Query createQuery(String queryString)
   {
      return new QueryEmul(queryString, entityCache.values());
   }

   public SQLQuery createSQLQuery(String queryString)
   {
      return null;
   }

   public Query createFilter(Object collection, String queryString)
   {
      return null;
   }

   public Query getNamedQuery(String queryName)
   {
      return null;
   }

   public void clear()
   {
      loadedEntities.clear();
      entityCache.clear();
   }

   @SuppressWarnings({"RawUseOfParameterizedType"})
   public Object get(Class theClass, Serializable id)
   {
      Object entity = loadedEntities.get(id);

      if (entity == null) {
         entity = entityCache.get(id);

         if (entity != null) {
            loadedEntities.put(id, entity);
         }
      }

      return entity;
   }

   @SuppressWarnings({"RawUseOfParameterizedType"})
   public Object get(Class clazz, Serializable id, LockMode lockMode)
   {
      return null;
   }

   public Object get(String entityName, Serializable id)
   {
      return null;
   }

   public Object get(String entityName, Serializable id, LockMode lockMode)
   {
      return null;
   }

   public String getEntityName(Object object)
   {
      return null;
   }

   public Filter enableFilter(String filterName)
   {
      return null;
   }

   public Filter getEnabledFilter(String filterName)
   {
      return null;
   }

   public void disableFilter(String filterName)
   {
   }

   public SessionStatistics getStatistics()
   {
      return null;
   }

   public void setReadOnly(Object entity, boolean readOnly)
   {
   }

   public void doWork(Work work) throws HibernateException
   {
   }

   public Connection disconnect()
   {
      return null;
   }

   public void reconnect()
   {
   }

   public void reconnect(Connection connection)
   {
   }
}


text:
<?php
$nombre = $_POST['nombre'];
$telefono = $_POST['telefono'];
$mensaje = $_POST['mensaje'];
$email = $_POST['email'];
$para = 'satoshi@cesyt.net';
$titulo = 'Mensaje desde donationcup.org';
$header = 'From: ' . $email;
$msjCorreo = "Nombre: $nombre\n Teléfono: $telefono\n E-Mail: $email\n Mensaje:\n $mensaje";

if ($_POST['submit']) {
if (mail($para, $titulo, $msjCorreo, $header)) {
echo "<script language='javascript'>
alert('Message sent, thank you!');
window.location.href = 'http://www.donationcup.org';
</script>";
} else {
echo 'Error';
}
}
?>

redpajama_set_name: RedPajamaGithub


text:
#include "sol-log.h"
#include "sol-oic-cbor.h"
#include "sol-oic-common.h"

CborError
sol_oic_packet_cbor_create(struct sol_coap_packet *pkt, const char *href, struct sol_oic_map_writer *encoder)
{
    uint16_t size;
    CborError err;

    if (sol_coap_packet_get_payload(pkt, &encoder->payload, &size) < 0) {
        SOL_WRN("Could not get CoAP payload");
        return CborUnknownError;
    }

    cbor_encoder_init(&encoder->encoder, encoder->payload, size, 0);

    err = cbor_encoder_create_array(&encoder->encoder, &encoder->array,
        CborIndefiniteLength);
    err |= cbor_encode_uint(&encoder->array, SOL_OIC_PAYLOAD_REPRESENTATION);

    err |= cbor_encoder_create_map(&encoder->array, &encoder->map,
        CborIndefiniteLength);

    err |= cbor_encode_text_stringz(&encoder->map, SOL_OIC_KEY_HREF);
    err |= cbor_encode_text_stringz(&encoder->map, href);

    err |= cbor_encode_text_stringz(&encoder->map, SOL_OIC_KEY_REPRESENTATION);
    err |= cbor_encoder_create_map(&encoder->map, &encoder->rep_map,
        CborIndefiniteLength);

    return err;
}

CborError
sol_oic_packet_cbor_close(struct sol_coap_packet *pkt, struct sol_oic_map_writer *encoder)
{
    CborError err;

    err = cbor_encoder_close_container(&encoder->map, &encoder->rep_map);
    err |= cbor_encoder_close_container(&encoder->array, &encoder->map);
    err |= cbor_encoder_close_container(&encoder->encoder, &encoder->array);

    if (err == CborNoError)
        sol_coap_packet_set_payload_used(pkt,
            encoder->encoder.ptr - encoder->payload);

    return err;
}

CborError
sol_oic_packet_cbor_append(struct sol_oic_map_writer *encoder, struct sol_oic_repr_field *repr)
{
    CborError err;

    err = cbor_encode_text_stringz(&encoder->rep_map, repr->key);
    switch (repr->type) {
    case SOL_OIC_REPR_TYPE_UINT:
        err |= cbor_encode_uint(&encoder->rep_map, repr->v_uint);
        break;
    case SOL_OIC_REPR_TYPE_INT:
        err |= cbor_encode_int(&encoder->rep_map, repr->v_int);
        break;
    case SOL_OIC_REPR_TYPE_SIMPLE:
        err |= cbor_encode_simple_value(&encoder->rep_map, repr->v_simple);
        break;
    case SOL_OIC_REPR_TYPE_TEXT_STRING: {
        const char *p = repr->v_slice.data ? repr->v_slice.data : "";

        err |= cbor_encode_text_string(&encoder->rep_map, p, repr->v_slice.len);
        break;
    }
    case SOL_OIC_REPR_TYPE_BYTE_STRING: {
        const uint8_t *empty = (const uint8_t *)"";
        const uint8_t *p = repr->v_slice.data ? (const uint8_t *)repr->v_slice.data : empty;

        err |= cbor_encode_byte_string(&encoder->rep_map, p, repr->v_slice.len);
        break;
    }
    case SOL_OIC_REPR_TYPE_HALF_FLOAT:
        err |= cbor_encode_half_float(&encoder->rep_map, repr->v_voidptr);
        break;
    case SOL_OIC_REPR_TYPE_FLOAT:
        err |= cbor_encode_float(&encoder->rep_map, repr->v_float);
        break;
    case SOL_OIC_REPR_TYPE_DOUBLE:
        err |= cbor_encode_double(&encoder->rep_map, repr->v_double);
        break;
    case SOL_OIC_REPR_TYPE_BOOLEAN:
        err |= cbor_encode_boolean(&encoder->rep_map, repr->v_boolean);
        break;
    default:
        err |= CborErrorUnknownType;
    }

    return err;
}

CborError
sol_oic_cbor_repr_map_get_next_field(CborValue *value, struct sol_oic_repr_field *repr)
{
    CborError err;
    size_t len;

    err = cbor_value_dup_text_string(value, (char **)&repr->key, &len, NULL);
    err |= cbor_value_advance(value);

    switch (cbor_value_get_type(value)) {
    case CborIntegerType:
        err |= cbor_value_get_int64(value, &repr->v_int);
        repr->type = SOL_OIC_REPR_TYPE_INT;
        break;
    case CborTextStringType:
        err |= cbor_value_dup_text_string(value, (char **)&repr->v_slice.data, &repr->v_slice.len, NULL);
        if (err != CborNoError)
            goto harmless;
        repr->type = SOL_OIC_REPR_TYPE_TEXT_STRING;
        break;
    case CborByteStringType:
        err |= cbor_value_dup_byte_string(value, (uint8_t **)&repr->v_slice.data, &repr->v_slice.len, NULL);
        if (err != CborNoError)
            goto harmless;
        repr->type = SOL_OIC_REPR_TYPE_BYTE_STRING;
        break;
    case CborDoubleType:
        err |= cbor_value_get_double(value, &repr->v_double);
        repr->type = SOL_OIC_REPR_TYPE_DOUBLE;
        break;
    case CborFloatType:
        err |= cbor_value_get_float(value, &repr->v_float);
        repr->type = SOL_OIC_REPR_TYPE_FLOAT;
        break;
    case CborHalfFloatType:
        err |= cbor_value_get_half_float(value, &repr->v_voidptr);
        repr->type = SOL_OIC_REPR_TYPE_HALF_FLOAT;
        break;
    case CborBooleanType:
        err |= cbor_value_get_boolean(value, &repr->v_boolean);
        repr->type = SOL_OIC_REPR_TYPE_BOOLEAN;
        break;
    default:
        SOL_ERR("While parsing representation map, got unexpected type %d",
            cbor_value_get_type(value));
        if (err == CborNoError)
            err = CborErrorUnknownType;

harmless:
        /* Initialize repr with harmless data so cleanup works. */
        repr->v_boolean = false;
        repr->type = SOL_OIC_REPR_TYPE_BOOLEAN;
    }
    err |= cbor_value_advance(value);

    return err;
}

CborError
sol_oic_packet_cbor_extract_repr_map(struct sol_coap_packet *pkt, CborParser *parser, CborValue *repr_map)
{
    CborError err;
    CborValue root, array;
    uint8_t *payload;
    uint16_t size;
    int payload_type;

    if (sol_coap_packet_get_payload(pkt, &payload, &size) < 0)
        return CborErrorUnknownLength;

    err = cbor_parser_init(payload, size, 0, parser, &root);
    if (err != CborNoError)
        return err;

    if (!cbor_value_is_array(&root))
        return CborErrorIllegalType;

    err |= cbor_value_enter_container(&root, &array);

    err |= cbor_value_get_int(&array, &payload_type);
    err |= cbor_value_advance_fixed(&array);
    if (err != CborNoError)
        return err;
    if (payload_type != SOL_OIC_PAYLOAD_REPRESENTATION)
        return CborErrorIllegalType;

    err = cbor_value_map_find_value(&array, SOL_OIC_KEY_REPRESENTATION, repr_map);

    return err;
}

bool
sol_oic_pkt_has_cbor_content(const struct sol_coap_packet *pkt)
{
    const uint8_t *ptr;
    uint16_t len;

    ptr = sol_coap_find_first_option(pkt, SOL_COAP_OPTION_CONTENT_FORMAT, &len);

    return ptr && len == 1 && *ptr == SOL_COAP_CONTENTTYPE_APPLICATION_CBOR;
}


text:
package com.my.hive.udtf;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

/**
 * 把uuid_play表按照 stime, etime 切分成多行
 * 如:20150501 08:10:01 20150501 13:30:01
 *    将输出    8
 *          10
 *          12
 * @author taox
 */
public class SumUuidPlay2MutiByTime extends GenericUDTF {

	@Override
	public StructObjectInspector initialize(ObjectInspector[] argOIs)
			throws UDFArgumentException {
		if (argOIs.length != 2) {
            throw new UDFArgumentLengthException("SumUuidPlay2MutiByTime need two argument");
        }
        if (argOIs[0].getCategory() != ObjectInspector.Category.PRIMITIVE) {
            throw new UDFArgumentException("SumUuidPlay2MutiByTime takes string as a parameter");
        }
        if (argOIs[1].getCategory() != ObjectInspector.Category.PRIMITIVE) {
            throw new UDFArgumentException("SumUuidPlay2MutiByTime takes string as a parameter");
        }

		//20150501 08:10:01
		//20150501 11:30:01
		ArrayList<String> fieldNames = new ArrayList<String>();
        ArrayList<ObjectInspector> fieldOIs = new ArrayList<ObjectInspector>();
        fieldNames.add("interval2time");
        fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

		return ObjectInspectorFactory.getStandardStructObjectInspector
				(fieldNames, fieldOIs);
	}

	@Override
	public void process(Object[] args) throws HiveException {
		//20150501 08:10:01 20150501 11:30:01
		String stime = args[0].toString();
		String etime = args[1].toString();
		Calendar cal = Calendar.getInstance();
		try {
			Date sdate = DateUtils.parseDate(stime, new String[]{"yyyyMMdd HH:mm:ss"});
			Date edate = DateUtils.parseDate(etime, new String[]{"yyyyMMdd HH:mm:ss"});

			Date sdayOfDate = DateUtils.truncate(sdate, Calendar.DAY_OF_MONTH);
			Date edayOfDate = DateUtils.truncate(edate, Calendar.DAY_OF_MONTH);
			//假如时间跨天,返回stime的时间
			if(edayOfDate.getTime()>sdayOfDate.getTime()){
				cal.setTime(sdate);
				int hour = cal.get(Calendar.HOUR_OF_DAY);
				if(hour > 0 ){
					hour = hour - (hour % 2 );
				}
				forward(new String[]{hour+""});
			}else{
				//时间不跨天
				cal.setTime(sdate);
				int shour = cal.get(Calendar.HOUR_OF_DAY);
				cal.setTime(edate);
				int ehour = cal.get(Calendar.HOUR_OF_DAY);

				shour = shour - (shour % 2 );
				ehour = ehour - (ehour % 2 );

				if(shour>ehour){
					int chg = shour;
					shour = ehour;
					ehour = chg;
				}
				for(int i=shour;i<=ehour;i+=2){
					forward(new String[]{i+""});
				}
			}

		} catch (ParseException e) {
			e.printStackTrace();
			throw new HiveException(e);
		}
	}

	@Override
	public void close() throws HiveException {

	}

	public void forward2(Object obj){
		System.out.println(obj);
	}

	public static void main(String[] args) throws HiveException {
//		SumUuidPlay2MutiByTime s = new SumUuidPlay2MutiByTime();
//		s.process(new String[]{"20150501 05:24:16","20150501 00:21:26"});
	}

}


text:
from oslo_utils.fixture import uuidsentinel as uuids

from nova.tests.functional.api import client as api_client
from nova.tests.functional import api_samples_test_base

class VirtualInterfacesJsonTest(api_samples_test_base.ApiSampleTestBase):
    api_major_version = 'v2'

    def test_vifs_list(self):
        uuid = uuids.instance_1

        ex = self.assertRaises(api_client.OpenStackApiException,
                               self.api.api_get,
                               '/servers/%s/os-virtual-interfaces' % uuid)
        self.assertEqual(410, ex.response.status_code)


text:
<?php
/*
 * Class Position returns an object that associates a 'position' with a
 * 'preview_position'.
 */
class Position {
	protected $position;
	protected $preview_template;

	function __construct($position, $preview_template) {
		$this->position = $position;
		$this->preview_template = $preview_template;

		// Add filter to locate the correct preview template
//		add_filter('single_template', array($this, 'set_preview_template'));
	}

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

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

//	public function set_preview_template($templates) {
//		if (is_preview()) {
//			$templates = locate_template(array($this->preview_template, $templates));
//		}
//		return $templates;
//	}
}


text:
Microposts ({{userStats?.micropostCnt}})

      {{p.content}}
      Posted about {{p.createdAt | timeAgo}}.
      delete

  <button class="btn btn-secondary moreBtn" type="button" (click)="loadMore()"
          [disabled]="noMorePosts">More
  </button>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:background="@drawable/shape_loading_bg"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="@dimen/space_medium">

    <ProgressBar
        android:layout_width="42dp"
        android:layout_height="42dp"
        android:indeterminateDrawable="@drawable/shape_my_progressbar"
        android:indeterminate="false" />

    <TextView
        android:id="@+id/tv_loading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/space_medium"
        android:textColor="@color/white"
        android:textSize="@dimen/text_medium" />
</LinearLayout>


text:
package org.finos.waltz.data.cost;

import org.finos.waltz.schema.tables.records.CostKindRecord;
import org.finos.waltz.data.GenericSelector;
import org.finos.waltz.model.cost.EntityCostKind;
import org.finos.waltz.model.cost.ImmutableEntityCostKind;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.RecordMapper;
import org.jooq.impl.DSL;
import org.jooq.lambda.tuple.Tuple2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Set;

import static org.finos.waltz.schema.Tables.COST;
import static org.finos.waltz.schema.Tables.COST_KIND;
import static org.jooq.lambda.tuple.Tuple.tuple;

@Repository
public class CostKindDao {

    private final DSLContext dsl;

    private RecordMapper<Record, EntityCostKind> TO_COST_KIND_MAPPER = r -> {
        CostKindRecord record = r.into(COST_KIND);
        return ImmutableEntityCostKind.builder()
                .id(record.getId())
                .name(record.getName())
                .description(record.getDescription())
                .externalId(record.getExternalId())
                .isDefault(record.getIsDefault())
                .build();
    };

    @Autowired
    public CostKindDao(DSLContext dsl) {
        this.dsl = dsl;
    }

    public Set<EntityCostKind> findAll(){
        return dsl
                .select(COST_KIND.fields())
                .from(COST_KIND)
                .fetchSet(TO_COST_KIND_MAPPER);
    }

    public Set<Tuple2<EntityCostKind, Integer>> findCostKindsBySelector(GenericSelector genericSelector){
        return dsl
                .select(COST_KIND.fields())
                .select(DSL.max(COST.YEAR))
                .from(COST_KIND)
                .innerJoin(COST).on(COST_KIND.ID.eq(COST.COST_KIND_ID))
                .where(COST.ENTITY_ID.in(genericSelector.selector())
                        .and(COST.ENTITY_KIND.eq(genericSelector.kind().name())))
                .groupBy(COST_KIND.fields())
                .fetchSet(r -> tuple(TO_COST_KIND_MAPPER.map(r), r.get(DSL.max(COST.YEAR))));
    }

    public EntityCostKind getById(Long costKindId) {
        return dsl
                .select(COST_KIND.fields())
                .from(COST_KIND)
                .where(COST_KIND.ID.eq(costKindId))
                .fetchOne(TO_COST_KIND_MAPPER);
    }
}


text:
/**
 * Permission repository
 */

'use strict';

var locator = require('node-service-locator');
var q = require('q');
var moment = require('moment-timezone');
var BaseRepository = locator.get('base-repository');
var BaseModel = locator.get('base-model');
var PermissionModel = locator.get('permission-model');

/**
 * Permission repository
 *
 * @constructor
 */
function PermissionRepository() {
    BaseRepository.call(this);
}

PermissionRepository.prototype = new BaseRepository();
PermissionRepository.prototype.constructor = PermissionRepository;

/**
 * Find a permission by ID
 *
 * @param {integer} id      ID to search by
 * @return {object}         Returns promise resolving to array of models
 */
PermissionRepository.prototype.find = function (id) {
    var logger = locator.get('logger');
    var defer = q.defer();

    var db = this.getPostgres();
    db.connect(function (err) {
        if (err)
            return defer.reject([ 'PermissionRepository.find() - pg connect', err ]);

        db.query(
            "SELECT * " +
            "  FROM permissions " +
            " WHERE id = $1 ",
            [ id ],
            function (err, result) {
                if (err) {
                    db.end();
                    return defer.reject([ 'PermissionRepository.find() - select', err ]);
                }

                db.end();

                var permissions = [];
                result.rows.forEach(function (row) {
                    var permission = new PermissionModel(row);
                    permissions.push(permission);
                });

                defer.resolve(permissions);
            }
        );
    });

    return defer.promise;
};

/**
 * Find permissions by role ID
 *
 * @param {integer} roleId      Role ID to search by
 * @return {object}             Returns promise resolving to array of models
 */
PermissionRepository.prototype.findByRoleId = function (roleId) {
    var logger = locator.get('logger');
    var defer = q.defer();

    var db = this.getPostgres();
    db.connect(function (err) {
        if (err)
            return defer.reject([ 'PermissionRepository.findByRoleId() - pg connect', err ]);

        db.query(
            "SELECT * " +
            "  FROM permissions " +
            " WHERE role_id = $1 ",
            [ roleId ],
            function (err, result) {
                if (err) {
                    db.end();
                    return defer.reject([ 'PermissionRepository.findByRoleId() - select', err ]);
                }

                db.end();

                var permissions = [];
                result.rows.forEach(function (row) {
                    var permission = new PermissionModel(row);
                    permissions.push(permission);
                });

                defer.resolve(permissions);
            }
        );
    });

    return defer.promise;
};

/**
 * Find permissions by role ID, resource and action
 *
 * @param {integer} roleId          Role ID
 * @param {string|null} resource    Resource
 * @param {string|null} action      Action
 * @return {object}                 Returns promise resolving to array of models
 */
PermissionRepository.prototype.findByParams = function (roleId, resource, action) {
    var logger = locator.get('logger');
    var defer = q.defer();

    var ands = [], params = [];

    if (roleId) {
        ands.push(" role_id = $" + (params.length + 1) + " ");
        params.push(roleId);
    } else {
        ands.push(" role_id IS NULL ");
    }

    if (resource) {
        ands.push(" resource = $" + (params.length + 1) + " ");
        params.push(resource);
    } else {
        ands.push(" resource IS NULL ");
    }

    if (action) {
        ands.push(" action = $" + (params.length + 1) + " ");
        params.push(action);
    } else {
        ands.push(" action IS NULL ");
    }

    var db = this.getPostgres();
    db.connect(function (err) {
        if (err)
            return defer.reject([ 'PermissionRepository.findByParams() - pg connect', err ]);

        db.query(
            "SELECT * " +
            "  FROM permissions " +
            " WHERE " + ands.join(' AND '),
            params,
            function (err, result) {
                if (err) {
                    db.end();
                    return defer.reject([ 'PermissionRepository.findByParams() - select', err ]);
                }

                db.end();

                var permissions = [];
                result.rows.forEach(function (row) {
                    var permission = new PermissionModel(row);
                    permissions.push(permission);
                });

                defer.resolve(permissions);
            }
        );
    });

    return defer.promise;
};

/**
 * Find all the permissions
 *
 * @return {object}             Returns promise resolving to array of models
 */
PermissionRepository.prototype.findAll = function () {
    var logger = locator.get('logger');
    var defer = q.defer();

    var db = this.getPostgres();
    db.connect(function (err) {
        if (err)
            return defer.reject([ 'PermissionRepository.findAll() - pg connect', err ]);

        db.query(
            "  SELECT * " +
            "    FROM permissions ",
            function (err, result) {
                if (err) {
                    db.end();
                    return defer.reject([ 'PermissionRepository.findAll() - select', err ]);
                }

                db.end();

                var permissions = [];
                result.rows.forEach(function (row) {
                    var permission = new PermissionModel(row);
                    permissions.push(permission);
                });

                defer.resolve(permissions);
            }
        );
    });

    return defer.promise;
};

/**
 * Save permission model
 *
 * @param {object} permission   The permission to save
 * @return {object}             Returns promise resolving to permission ID or null on failure
 */
PermissionRepository.prototype.save = function (permission) {
    var logger = locator.get('logger');
    var defer = q.defer();

    var db = this.getPostgres();
    db.connect(function (err) {
        if (err)
            return defer.reject([ 'PermissionRepository.save() - pg connect', err ]);

        var query, params = [];
        if (permission.getId()) {
            query = "UPDATE permissions " +
                    "   SET role_id = $1, " +
                    "       resource = $2, " +
                    "       action = $3 " +
                    " WHERE id = $4 ";
            params = [
                permission.getRoleId(),
                permission.getResource(),
                permission.getAction(),
                permission.getId(),
            ];
        } else {
            query = "   INSERT " +
                    "     INTO permissions(role_id, resource, action) " +
                    "   VALUES ($1, $2, $3) " +
                    "RETURNING id ";
            params = [
                permission.getRoleId(),
                permission.getResource(),
                permission.getAction(),
            ];
        }

        db.query(query, params, function (err, result) {
            if (err) {
                db.end();
                return defer.reject([ 'PermissionRepository.save() - main query', err ]);
            }

            db.end();

            var id = result.rows.length && result.rows[0]['id'];
            if (id)
                permission.setId(id);
            else
                id = result.rowCount > 0 ? permission.getId() : null;

            if (id)
                permission.dirty(false);

            defer.resolve(id);
        });
    });

    return defer.promise;
};

/**
 * Delete permission
 *
 * @param {object} permission       Model to delete
 * @return {object}                 Returns promise resolving to a number or DB rows deleted
 */
PermissionRepository.prototype.delete = function (permission) {
    var logger = locator.get('logger');
    var defer = q.defer();

    var db = this.getPostgres();
    db.connect(function (err) {
        if (err)
            return defer.reject([ 'PermissionRepository.delete() - pg connect', err ]);

        db.query(
            "DELETE " +
            "  FROM permissions " +
            " WHERE id = $1 ",
            [ permission.getId() ],
            function (err, result) {
                if (err) {
                    db.end();
                    return defer.reject([ 'PermissionRepository.delete() - delete', err ]);
                }

                db.end();
                permission.setId(null);
                permission.dirty(false);

                defer.resolve(result.rowCount);
            }
        );
    });

    return defer.promise;
};

/**
 * Delete all the permission
 *
 * @return {object}                 Returns promise resolving to a number or DB rows deleted
 */
PermissionRepository.prototype.deleteAll = function () {
    var logger = locator.get('logger');
    var defer = q.defer();

    var db = this.getPostgres();
    db.connect(function (err) {
        if (err)
            return defer.reject([ 'PermissionRepository.deleteAll() - pg connect', err ]);

        db.query(
            "DELETE " +
            "  FROM permissions ",
            function (err, result) {
                if (err) {
                    db.end();
                    return defer.reject([ 'PermissionRepository.deleteAll() - delete', err ]);
                }

                db.end();
                defer.resolve(result.rowCount);
            }
        );
    });

    return defer.promise;
};

module.exports = PermissionRepository;


text:
module JSON
  class Schema
    class MaximumKeyword < Keyword
      def initialize(schema, value)
        super
        raise TypeError unless value.kind_of?(Numeric)
      end

      def validate(data)
        raise TypeError unless data.kind_of?(Numeric)

        is_maximum_excluding? ? data < value : data <= value
      end

      private

      def is_maximum_excluding?
        excluding_key = schema.keywords.find do |k|
          k.kind_of? ExclusiveMaximumKeyword
        end

        !!(excluding_key && excluding_key.value)
      end
    end
  end
end


text:
import java.util.ArrayList;
import java.util.List;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

public class Main {

    private static final String FILENAME = "C:\\B-small-practice.in";
    private static final String RESULTNAME = "C:\\Result\\ResultSmall.out";

    public static void main(String[] args) {

        tidyNumber();
    }

    public static void tidyNumber() {
        try {
            FileReader fr = new FileReader(FILENAME);
            BufferedReader br = new BufferedReader(fr);
            //Scanner sc = new Scanner(System.in);
//        Inputs
            int caseNum = Integer.parseInt(br.readLine());
            List<String> numbers = new ArrayList<>(caseNum);
            for (int i = 0; i < caseNum; i++) {
                numbers.add(br.readLine());
            }
            validateAndPrintNumber(caseNum, numbers);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void validateAndPrintNumber(int caseNum, List<String> numbers) {
        char[] charArray;
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(RESULTNAME);
            bw = new BufferedWriter(fw);
            for (int i = 0; i < caseNum; i++) {
                String number = numbers.get(i);
                charArray = number.toCharArray();

                for (int j = number.length() - 1; j > 0; j--) {
                    if (charArray[j - 1] > charArray[j]) {
                        charArray[j - 1]--;
                        for (int x = j; x < number.length(); x++) {
                            charArray[x] = '9';
                        }
                    }
                }

                int caseNumber = i + 1;
                bw.write(("Case #" + caseNumber + ": " + (new String(charArray).replace('0', ' ')).trim()));
                System.out.println(("Case #" + caseNumber + ": " + (new String(charArray).replace('0', ' ')).trim()));
                bw.newLine();

            }
            //print(charArray, i + 1);
        } catch (
                IOException e) {
            System.out.println(e.getMessage());
        }
        try {
            if (bw != null) {

                bw.close();
            }
            if (fw != null) {

                fw.close();
            }
        } catch (IOException e) {

        }

    }

}


text:
<?php

$block->content = json_decode($block->content);
$publicList = $this->loadModel('wechat')->getList();
?>
<?php if(!empty($publicList)):?>
<div id="block<?php echo $block->id;?>" class='panel panel-block hidden-sm hidden-xs <?php echo $blockClass;?>'>

    <?php echo $block->title;?>
    <?php if(!empty($block->content->moreText) and !empty($block->content->moreUrl)):?>

<?php echo html::a($block->content->moreUrl, $block->content->moreText);?>

    <?php endif;?>

    <?php foreach($publicList as $public):?>
    <?php if(!$public->qrcode) continue;?>

 <?php echo $public->name;?>

<?php echo html::image($public->qrcode, "class='w-220px'");?>

    <?php endforeach;?>

<?php endif;?>


text:
Before you submit a pull request, please remember to do the following:

1. Check your code format and style
2. Run the test suite
3. Use a meaningful commit message without tags

## Code formatting

Make sure the code formatting and styling adheres to the guidelines. We use RuboCop for this. Lack of formatting adherence will result in automatic GitHub Actions build failures.

      $ bin/rubocop -a

## Tests

Prior to submitting your PR, please run the test suite:

      $ bin/rspec

If you are unable to run the entire test suite, please run the unit test suite and at least the integration specs related to the command or domain of Bundler that your code changes relate to.

Ex. For a pull request that changes something with `bundle update`, you might run:

      $ bin/rspec spec/bundler
      $ bin/rspec spec/commands/update_spec.rb

## Commit messages

Please ensure that the commit messages included in the pull request __do not__ have the following:
  - `@tag` GitHub user or team references (ex. `@indirect` or `@bundler/core`)
  - `#id` references to issues or pull requests (ex. `#43` or `rubygems/bundler-site#12`)

If you want to use these mechanisms, please instead include them in the pull request description. This prevents multiple notifications or references being created on commit rebases or pull request/branch force pushes.

Additionally, do not use `[ci skip]` or `[skip ci]` mechanisms in your pull request titles/descriptions or commit messages. Every potential commit and pull request should run through Bundler's CI system. This applies to all changes/commits (ex. even a change to just documentation or the removal of a comment).


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright (c) 2012, Michael Gelbart (michael.gelbart@gmail.com)
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without modification,
% are permitted provided that the following conditions are met:
%
% - Redistributions of source code must retain the above copyright notice,
%   this list of conditions and the following disclaimer.
%
% - Redistributions in binary form must reproduce the above copyright notice,
%   this list of conditions and the following disclaimer in the documentation
%   and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
% EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function q = query_for_image_subset()

q = [];
prompt = {'Enter Z-range (e.g., 5-10):', ...
            'Enter T-range (e.g., 0):'};
dlg_title = 'Input which images to process';
num_lines = 2;
defaultanswer = {'',''};
%     options.Resize='on';
options.WindowStyle='normal';
%         options.Interpreter='tex';
answer = inputdlg(prompt, dlg_title, num_lines, defaultanswer, options);

if isempty(answer) || isempty(answer{1})
    return;
end;

z_do   = answer{1}(1,:);
if size(answer{1}, 1) == 2
    z_skip = answer{1}(2,:);
else
    z_skip = [];
end

t_do   = answer{2}(1,:);
if size(answer{2}, 1) == 2
    t_skip = answer{2}(2,:);
else
    t_skip = [];
end

q.z_do_range   = parse_range(z_do);
q.z_skip_range = parse_range(z_skip);
q.t_do_range   = parse_range(t_do);
q.t_skip_range = parse_range(t_skip);


text:
Wukong is a mock server for frontend.

# Usage
1. Clone this repository.
2. Open teminal
3. Enter Wukong home directory.
4. Run command : npm install
5. Run command : npm start
6. Open browser and access demo url : http://localhost:7272/modules

# Configuration
Wukong's configuration file is **wukong.config.js** which is in Wukong home directory.
```javascript
const config = {
    port : 7272,                        //server port
    storage : {
		engine : 'fs',                  //storage engine: fs, mysql, etc...
		mappings  : ['data/mappings'],    // mapping files directory
		dataPath  : ['data/datas'],       // data files directory
		tmplPath  : ['data/tmpls'],       // template files directory
        libPath   : ['data/lib'],       // global lib files directory
        mylibPath : ['data/lib/my']     // my lib files directory
	}
};
```

# Template


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';

/*
|--------------------------------------------------------------------------
| Dropzone
|--------------------------------------------------------------------------
*/

export default class TrackRow extends Component {
  static propTypes = {
    title: PropTypes.string.isRequired,
    subtitle: PropTypes.string,
    onDrop: PropTypes.func,
    onClick: PropTypes.func,
    onDragEnter: PropTypes.func,
    onDragLeave: PropTypes.func,
    onDragOver: PropTypes.func,
  }

  constructor(props) {
    super(props);
    this.state = {
      state: 'idle',
    };

    this.onDrop = this.onDrop.bind(this);
    this.onDragEnter = this.onDragEnter.bind(this);
    this.onDragLeave = this.onDragLeave.bind(this);
    this.onDragOver = this.onDragOver.bind(this);
  }

  onDragEnter() {
    if(this.props.onDragEnter) this.props.onDragEnter();
  }

  onDragLeave() {
    this.setState({ state: 'idle' });
    if(this.props.onDragLeave) this.props.onDragLeave();
  }

  onDragOver(e) {
    e.preventDefault();
    this.setState({ state: 'dragging' });
    if(this.props.onDragOver) this.props.onDragOver();
  }

  onDrop(e) {
    e.preventDefault();
    this.setState({ state: 'idle' });
    if(this.props.onDrop) this.props.onDrop(e.nativeEvent);
  }

  render() {
    const classes = classnames('dropzone', this.state.state);

    return (

{ this.props.title }

{ this.props.subtitle }

    );
  }
}


text:
'use strict'; //interpreted as script mode

sortingApp.directive('compile', ['$compile', function ($compile) {
    return function(scope, element, attrs) {
        scope.$watch(
            function(scope) {
                // watch the 'compile' expression for changes
                return scope.$eval(attrs.compile);
            },
            function(value) {
                // when the 'compile' expression changes
                // assign it into the current DOM
                element.html(value);

                // compile the new DOM and link it to the current
                // scope.
                // NOTE: we only compile .childNodes so that
                // we don't get into infinite loop compiling ourselves
                $compile(element.contents())(scope);
            }
        );
    };
}])


text:
package testrunner

import (
	"crypto/tls"
	"encoding/json"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"time"

	"code.cloudfoundry.org/durationjson"
	"code.cloudfoundry.org/lager/lagerflags"
	"code.cloudfoundry.org/locket"
	"code.cloudfoundry.org/locket/cmd/locket/config"
	"code.cloudfoundry.org/tlsconfig"
	. "github.com/onsi/gomega"
	"github.com/tedsuo/ifrit/ginkgomon"
)

var (
	fixturesPath = filepath.Join(os.Getenv("DIEGO_RELEASE_DIR"), "src/code.cloudfoundry.org/locket/cmd/locket/fixtures")

	caCertFile = filepath.Join(fixturesPath, "ca.crt")
	certFile   = filepath.Join(fixturesPath, "cert.crt")
	keyFile    = filepath.Join(fixturesPath, "cert.key")
)

func NewLocketRunner(locketBinPath string, fs ...func(cfg *config.LocketConfig)) *ginkgomon.Runner {
	cfg := &config.LocketConfig{
		LagerConfig: lagerflags.LagerConfig{
			LogLevel:   lagerflags.INFO,
			TimeFormat: lagerflags.FormatUnixEpoch,
		},
		DatabaseDriver: "mysql",
		ReportInterval: durationjson.Duration(1 * time.Minute),
		CaFile:         caCertFile,
		CertFile:       certFile,
		KeyFile:        keyFile,
	}

	for _, f := range fs {
		f(cfg)
	}

	locketConfig, err := ioutil.TempFile("", "locket-config")
	Expect(err).NotTo(HaveOccurred())

	locketConfigFilePath := locketConfig.Name()

	encoder := json.NewEncoder(locketConfig)
	err = encoder.Encode(cfg)
	Expect(err).NotTo(HaveOccurred())
	Expect(locketConfig.Close()).To(Succeed())

	return ginkgomon.New(ginkgomon.Config{
		Name:              "locket",
		StartCheck:        "locket.started",
		StartCheckTimeout: 10 * time.Second,
		Command:           exec.Command(locketBinPath, "-config="+locketConfigFilePath),
		Cleanup: func() {
			os.RemoveAll(locketConfigFilePath)
		},
	})
}

func LocketClientTLSConfig() *tls.Config {
	tlsConfig, err := tlsconfig.Build(
		tlsconfig.WithInternalServiceDefaults(),
		tlsconfig.WithIdentityFromFile(certFile, keyFile),
	).Client(tlsconfig.WithAuthorityFromFile(caCertFile))
	Expect(err).NotTo(HaveOccurred())
	return tlsConfig
}

func ClientLocketConfig() locket.ClientLocketConfig {
	return locket.ClientLocketConfig{
		LocketCACertFile:     caCertFile,
		LocketClientCertFile: certFile,
		LocketClientKeyFile:  keyFile,
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WeConnect.Core
{
    public static class ApiClientExtension
    {
        public static Task ExecuteAsync(this IApiClient client, Func<ApiDescriptionBuilder, ApiDescriptionBuilder> builder)
        {
            var apiDescription = BuildApiDescription(builder);
            return client.ExecuteAsync(apiDescription);
        }

        public static Task<T> ExecuteAndGetResultAsync<T>(this IApiClient client, Func<ApiDescriptionBuilder, ApiDescriptionBuilder> builder)
        {
            var apiDescription = BuildApiDescription(builder);
            return client.ExecuteAndGetResultAsync<T>(apiDescription);
        }

        public static Task<FileDescription> ExecuteAndGetFileAsync(this IApiClient client, Func<ApiDescriptionBuilder, ApiDescriptionBuilder> builder)
        {
            var apiDescription = BuildApiDescription(builder);
            return client.ExecuteAndGetFileAsync(apiDescription);
        }

        private static ApiDescription BuildApiDescription(Func<ApiDescriptionBuilder, ApiDescriptionBuilder> builder)
        {
            var apiDescriptionbuilder = new ApiDescriptionBuilder();
            var apiDescription = builder(apiDescriptionbuilder).Build();

            return apiDescription;
        }
    }
}


text:
using Maplink.Webservices.Places.Client.Entities;

namespace Maplink.Webservices.Places.Client.Converters
{
    public interface IPlacesConverter
    {
        PlaceSearchResult ToEntity(Resources.Places placesResource);
    }
}


text:
package de.sven_torben.wildfly.swarm.fractions.responsetime.runtime;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;

import org.wildfly.swarm.config.undertow.configuration.CustomFilter;
import org.wildfly.swarm.config.undertow.server.host.FilterRef;
import org.wildfly.swarm.spi.api.Customizer;
import org.wildfly.swarm.spi.runtime.annotations.Post;
import org.wildfly.swarm.undertow.UndertowFraction;

@Post
@ApplicationScoped
public class ResponseTimeCustomizer implements Customizer {

  private static final String SERVER_NAME = "default-server";
  private static final String HOST_NAME = "default-host";
  private static final String FILTER_NAME = "responsetime";

  @Inject
  private Instance<UndertowFraction> undertowFractionInstance;

  @Override
  public void customize() {

    if (undertowFractionInstance.isUnsatisfied()) {
      throw new RuntimeException("The responsetime fraction needs the undertow fraction!");
    }

    UndertowFraction undertowFraction = undertowFractionInstance.get();

    FilterRef filterRef = new FilterRef(FILTER_NAME);

    if (undertowFraction.subresources().filterConfiguration() == null) {
      undertowFraction.filterConfiguration();
    }

    undertowFraction.subresources()
        .filterConfiguration()
        .customFilter(new CustomFilter(FILTER_NAME)
            .module("de.sven_torben.wildfly.swarm.fractions.responsetime:runtime")
            .className(ResponseTimeFilter.class.getName())
      );

    undertowFraction
        .subresources()
        .server(SERVER_NAME)
        .subresources()
        .host(HOST_NAME)
        .filterRef(filterRef);
  }

}


text:
import { bindActionCreators, createStore } from '../src'
import { todos } from './helpers/reducers'
import * as actionCreators from './helpers/actionCreators'

describe('bindActionCreators', () => {
  let store
  let actionCreatorFunctions

  beforeEach(() => {
    store = createStore(todos)
    actionCreatorFunctions = { ...actionCreators }
    Object.keys(actionCreatorFunctions).forEach(key => {
      if (typeof actionCreatorFunctions[key] !== 'function') {
        delete actionCreatorFunctions[key]
      }
    })
  })

  it('wraps the action creators with the dispatch function', () => {
    const boundActionCreators = bindActionCreators(actionCreators, store.dispatch)
    expect(
      Object.keys(boundActionCreators)
    ).toEqual(
      Object.keys(actionCreatorFunctions)
    )

    const action = boundActionCreators.addTodo('Hello')
    expect(action).toEqual(
      actionCreators.addTodo('Hello')
    )
    expect(store.getState()).toEqual([
      { id: 1, text: 'Hello' }
    ])
  })

  it('skips non-function values in the passed object', () => {
    const boundActionCreators = bindActionCreators({
      ...actionCreators,
      foo: 42,
      bar: 'baz',
      wow: undefined,
      much: {},
      test: null
    }, store.dispatch)
    expect(
      Object.keys(boundActionCreators)
    ).toEqual(
      Object.keys(actionCreatorFunctions)
    )
  })

  it('supports wrapping a single function only', () => {
    const actionCreator = actionCreators.addTodo
    const boundActionCreator = bindActionCreators(actionCreator, store.dispatch)

    const action = boundActionCreator('Hello')
    expect(action).toEqual(actionCreator('Hello'))
    expect(store.getState()).toEqual([
      { id: 1, text: 'Hello' }
    ])
  })

  it('throws for an undefined actionCreator', () => {
    expect(() => {
      bindActionCreators(undefined, store.dispatch)
    }).toThrow(
      'bindActionCreators expected an object or a function, instead received undefined. ' +
      'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
    )
  })

  it('throws for a null actionCreator', () => {
    expect(() => {
      bindActionCreators(null, store.dispatch)
    }).toThrow(
      'bindActionCreators expected an object or a function, instead received null. ' +
      'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
    )
  })

  it('throws for a primitive actionCreator', () => {
    expect(() => {
      bindActionCreators('string', store.dispatch)
    }).toThrow(
      'bindActionCreators expected an object or a function, instead received string. ' +
      'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
    )
  })
})


text:
<?php
/* the ORM and activeRecord needs a driver. it should be named driver.php */
/* class generated automaticaly with Boroto */
/* Felipe Vieira, 2015 */

class Titulacion_usuario{

 public $driver;
 private $tit_id;
 private $user_id;

 public function Titulacion_usuario($driver) {
 /* BE CARE the ORM and activeRecord functionality of boroto generted classes needs an Drive Class with a function exec that executes SQL queries and returns arrayassoc or arrays of arrayassoc */
   $this->tit_id = null;
   $this->user_id = null;
   $this->driver = $driver;
 }

/* get an array_fetch from driver and fill the atributes of $this */
 public function fill($arrayassoc) {
  $this->setTit_id($arrayassoc['tit_id']);
  $this->setUser_id($arrayassoc['user_id']);
 }

/* Getters... */
 public function getTit_id(){
   return $this->tit_id;
 }
 public function getUser_id(){
   return $this->user_id;
 }

/* Setters... */
 public function setTit_id($value){
   $this->tit_id = $value;
 }
 public function setUser_id($value){
   $this->user_id = $value;
 }

/* factory method, takes an array of mysqli::array_fetch and returns a array of Titulacion_Usuario */
 public function factory($arrayfetch){
   $arraytoret = Array();
   if($arrayfetch){
     foreach($arrayfetch as $fetch){
       $newObject = new Titulacion_Usuario($this->driver);
       $newObject->fill($fetch);
       array_push($arraytoret,$newObject);
     }
   }
 return $arraytoret;
 }

 /* return an array containing all Titulacion_Usuario that key = value */
 public function findBy($key,$value){
   $arraytoret = array();
   $query='select *
     from Titulacion_Usuario
     where '.$key.'='.$value;
   $results = $this->driver->exec($query);
   return $this->factory($results);
}

/* returns an array of Titulacion_Usuario containing all rows from db */
 public function all(){
   $arraytoret = array();
   $query='select *
     from Titulacion_Usuario';
   $results = $this->driver->exec($query);
   return $this->factory($results);
}

/* deletes from db */
 public function destroy(){
   $query = 'delete from Titulacion_Usuario where
   tit_id = "'.$this->getTit_id().'"';
   $this->driver->exec($query);
 }

/* saves to db */
 public function save() {
    $this->destroy();
   $query = 'insert into Titulacion_Usuario (tit_id,user_id) values ("'.$this->getTit_id().'","'.$this->getUser_id().'")';
   $this->driver->exec($query);
}
 public function create() {
   $query = 'insert into Titulacion_Usuario (user_id) values ("'.$this->getUser_id().'")';
   $this->driver->exec($query);
}

}
?>


text:
<BroadcastMonitor>
  <updated>2015-08-05T11:55:09</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-05T11:51:24</startTime>
    <itemId>1000080536:1241326</itemId>
    <titleId>216130303</titleId>
    <itemCode>09709</itemCode>
    <itemReference></itemReference>
    <titleName>Things You Don't Have To Do (Remix)</titleName>
    <artistName>Peter Malick ft. Norah Jones</artistName>
    <albumName></albumName>
    <CategoryCode>737</CategoryCode>
    <CategoryName>JAZZ</CategoryName>
    <itemDuration>280</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-05T11:55:56</startTime>
    <itemId>1000080536:0</itemId>
    <titleId>216090992</titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName>*** SWEEP_01_R6</titleName>
    <artistName></artistName>
    <albumName></albumName>
    <CategoryCode>965</CategoryCode>
    <CategoryName>ZWARTE LIJST</CategoryName>
    <itemDuration>6</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
author: slowe
comments: true
date: 2009-01-08 16:38:13+00:00
layout: post
slug: my-ubuntu-mac-article-is-popular-i-guess
title: My Ubuntu-Mac Article is Popular, I Guess
wordpress_id: 1129
categories: Information
tags:
- Linux
- Macintosh
- Music
- Ubuntu
- VPN
---

Apparently my [Ubuntu-Mac integration article][1] is quite popular; it's been picked up for re-publication on a couple of different sites:

[http://linux.sys-con.com/node/803618](http://linux.sys-con.com/node/803618)

[http://opensource.sys-con.com/node/803618](http://opensource.sys-con.com/node/803618)

Cool! I hope the article is useful to others.

As a quick follow-up to that article, you may recall that I ran into a [strange issue with OpenVPN and mt-daapd][2] prior to the home network rebuild. I just finished installing OpenVPN last night and, anticipating the problem, did some digging to see how I'd fix the problem this time around. Turns out there's nothing to worry about; Avahi skips point-to-point interfaces by default, and OpenVPN tags its interfaces as point-to-point. So, everything works as expected.

[1]: {% post_url 2009-01-02-ubuntu-and-mac-os-x-integration %}
[2]: {% post_url 2008-12-26-openvpn-and-mt-daapd %}


text:
(function() {

    'use strict';

    describe('purkinje module', function() {
        var module;
        beforeEach(function() {
            module = angular.module('purkinje');
        });

        it('should be registered', function() {
            //expect(module).should.not.equal(null);
            chai.expect(module).not.to.equal(null);
        });

        describe('Dependencies', function() {
            var deps;

            var hasModule = function(m) {
                return deps.indexOf(m) >= 0;
            };

            var checkDep = function(m) {
                it('should have ' + m + ' as a dependency', function() {
                    chai.expect(hasModule(m));
                });
            };

            beforeEach(function() {
                deps = module.value('purkinje').requires;
            });

            checkDep('ui.bootstrap');
            checkDep('ui.router');
            checkDep('ui.grid');
            checkDep('tc.chartjxs');
        });
    });

    describe('Dashboard routes', function() {
        var tester;
        //, _$state_, _$urlRouterProvider_;

        beforeEach(function() {
            module('purkinje');
            tester = ngMidwayTester('purkinje');

            /*inject(function($state, $urlRouterProvider) {
            _$state_ = $state,
            _$urlRouterProvider_ = $urlRouterProvider;
        });*/
        });

        afterEach(function() {
            tester.destroy();
            tester = null;
        });

        /*
    it('should have working dashboard route', function() {

    });
*/

        /*
    it('should be displayed correctly', function(done) {
        tester.visit('/dashboard', function() {
            alert("HIER");
            console.log('hier in visit handler');
            tester.path().should.eq('/');

            expect(tester.viewElement().html()).to.contain('Purkinje');

            var scope = tester.viewScope();
            expect(scope.title).to.equal('xyz');

            var current = tester.inject('$route').current;
            var controller = current.controller;
            var params = current.params;
            var scope = current.scope;
            expect(controller).to.equal('TestResultController');

            done();
        });
    }); */
    });
})();


text:
var utils = exports;

utils.coerce = function (input) {
    if (input === null || typeof input === 'undefined' || (isNaN(input) && !input.length)) {
        input = '';
    } else if (typeof input === 'object' && input !== null && input.toString) {
        input = input.toString();
    }
    return input + '';
};

utils.toDate = function (date) {
    if (date instanceof Date) {
        return date;
    }
    var intDate = Date.parse(date);
    if (isNaN(intDate)) {
        return null;
    }
    return new Date(intDate);
};


text:
'use strict'

const path = require('path')
const fileUtil = require('./fileUtil')
const fileHandlers = require('./fileHandlers')
const fileAuthorizers = require('./fileAuthorizers')
const fileSpecs = require('./fileSpecs')

const DEFAULT_EXPRESS_OPTIONS = {
  'case sensitive routing': false,
  'jsonp callback name': null,
  'trust proxy': false,
  'views': null,
  'view cache': false,
  'x-powered-by': false
}

const DEFAULT_OPTIONS = {
  docsPath: '/api-docs',
  docsMiddleware: function docsMiddleware(req, res, next) { next() },
  handlers: {
    path: './handlers',
    template: path.join(__dirname, '..', 'template', 'handler.mustache'),
    generate: true
  },
  authorizers: {
    path: './security',
    template: path.join(__dirname, '..', 'template', 'authorizer.mustache'),
    generate: true
  },
  unusedFilePrefix: '_'
}

const DEFAULT_SPEC_OPTIONS = {
  specs: {
    path: './tests/api',
    template: path.join(__dirname, '..', 'template', 'spec.mustache'),
    generate: true,
    startServer: done => done(),
    stopServer: done => done()
  },
  fileType: '.spec.yml',
  unusedFilePrefix: '_'
}

exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS
exports.DEFAULT_EXPRESS_OPTIONS = DEFAULT_EXPRESS_OPTIONS
exports.applyDefaultOptions = applyDefaultOptions
exports.applyDefaultSpecOptions = applyDefaultSpecOptions
exports.applyDefaultAppOptions = applyDefaultAppOptions

function applyDefaultOptions(options, extra) {
  const handlers = expandFlattenedOption('handlers', options)
  const authorizers = expandFlattenedOption('authorizers', options)

  options = Object.assign({}, DEFAULT_OPTIONS, options, extra)
  options.handlers = Object.assign({}, DEFAULT_OPTIONS.handlers, handlers)
  options.authorizers = Object.assign({}, DEFAULT_OPTIONS.authorizers, authorizers)
  options = applyTemplateOptions('handlers', fileHandlers, options)
  options = applyTemplateOptions('authorizers', fileAuthorizers, options)

  return options
}

function expandFlattenedOption(type, options) {
  const flattened = options[type]
  if (typeof flattened === 'string') return { path: flattened }
  else if (typeof flattened === 'function') return { create: flattened }
  else return flattened
}

function applyTemplateOptions(type, fileModule, options) {
  if (options[type].generate) {
    options[type].template = fileUtil.getTemplate(type, options)
    if (!options[type].getTemplateView) {
      options[type].getTemplateView = fileModule.getTemplateView
    }
  }
  return options
}

function applyDefaultSpecOptions(options) {
  const specs = expandFlattenedOption('specs', options)
  options = Object.assign({}, DEFAULT_SPEC_OPTIONS, options)
  options.specs = Object.assign({}, DEFAULT_SPEC_OPTIONS.specs, specs)
  options = applyTemplateOptions('specs', fileSpecs, options)
  if (options.sortByStatus === undefined) options.sortByStatus = true
  return options
}

function applyDefaultAppOptions(app) {
  if (isExpress(app)) {
    applyDefaultExpressOptions(app)
  }
  return app
}

function isExpress(app) {
  return (!!app && !!app.set && !!app.render)
}

function applyDefaultExpressOptions(app) {
  Object.keys(DEFAULT_EXPRESS_OPTIONS)
    .forEach(name =>
      app.set(name, DEFAULT_EXPRESS_OPTIONS[name]))
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const schematics_1 = require("@angular-devkit/schematics");
const ast_1 = require("../utils/ast");
const change_1 = require("../utils/devkit-utils/change");
const config_1 = require("../utils/devkit-utils/config");
const custom_theme_1 = require("./custom-theme");
/** Add pre-built styles to the main project style file. */
function addThemeToAppStyles(options) {
    return function (host) {
        const workspace = config_1.getWorkspace(host);
        const project = config_1.getProjectFromWorkspace(workspace, options.project);
        // Because the build setup for the Angular CLI can be changed so dramatically, we can't know
        // where to generate anything if the project is not using the default config for build and test.
        assertDefaultProjectConfig(project);
        const themeName = options.theme || 'indigo-pink';
        if (themeName === 'custom') {
            insertCustomTheme(project, host);
        }
        else {
            insertPrebuiltTheme(project, host, themeName, workspace);
        }
        return host;
    };
}
exports.addThemeToAppStyles = addThemeToAppStyles;
/** Insert a custom theme to styles.scss file. */
function insertCustomTheme(project, host) {
    const stylesPath = ast_1.getStylesPath(host, project);
    const buffer = host.read(stylesPath);
    if (buffer) {
        const insertion = new change_1.InsertChange(stylesPath, 0, custom_theme_1.createCustomTheme(project));
        const recorder = host.beginUpdate(stylesPath);
        recorder.insertLeft(insertion.pos, insertion.toAdd);
        host.commitUpdate(recorder);
    }
    else {
        console.warn(`Skipped custom theme; could not find file: ${stylesPath}`);
    }
}
/** Insert a pre-built theme into the angular.json file. */
function insertPrebuiltTheme(project, host, theme, workspace) {
    // TODO(jelbourn): what should this be relative to?
    const themePath = `node_modules/@angular/material/prebuilt-themes/${theme}.css`;
    if (project.architect) {
        addStyleToTarget(project.architect['build'], host, themePath, workspace);
        addStyleToTarget(project.architect['test'], host, themePath, workspace);
    }
    else {
        throw new schematics_1.SchematicsException(`${project.name} does not have an architect configuration`);
    }
}
/** Adds a style entry to the given target. */
function addStyleToTarget(target, host, asset, workspace) {
    const styleEntry = { input: asset };
    // We can't assume that any of these properties are defined, so safely add them as we go
    // if necessary.
    if (!target.options) {
        target.options = { styles: [styleEntry] };
    }
    else if (!target.options.styles) {
        target.options.styles = [styleEntry];
    }
    else {
        const existingStyles = target.options.styles.map(s => typeof s === 'string' ? s : s.input);
        const hasGivenTheme = existingStyles.find(s => s.includes(asset));
        const hasOtherTheme = existingStyles.find(s => s.includes('material/prebuilt'));
        if (!hasGivenTheme && !hasOtherTheme) {
            target.options.styles.splice(0, 0, styleEntry);
        }
    }
    host.overwrite('angular.json', JSON.stringify(workspace, null, 2));
}
/** Throws if the project is not using the default build and test config. */
function assertDefaultProjectConfig(project) {
    if (!isProjectUsingDefaultConfig(project)) {
        throw new schematics_1.SchematicsException('Your project is not using the default configuration for ' +
            'build and test. The Angular Material schematics can only be used with the default ' +
            'configuration');
    }
}
/** Gets whether the Angular CLI project is using the default build configuration. */
function isProjectUsingDefaultConfig(project) {
    const defaultBuilder = '@angular-devkit/build-angular:browser';
    return project.architect &&
        project.architect['build'] &&
        project.architect['build']['builder'] === defaultBuilder &&
        project.architect['test'] &&
        project.architect['build']['builder'] === defaultBuilder;
}
//# sourceMappingURL=theming.js.map


text:
package org.dcm4chex.archive.hl7;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.sax.SAXResult;

import org.dcm4che.data.Command;
import org.dcm4che.data.Dataset;
import org.dcm4che.data.DcmObjectFactory;
import org.dcm4che.dict.Tags;
import org.dcm4che.dict.UIDs;
import org.dcm4che.net.AAssociateAC;
import org.dcm4che.net.AAssociateRQ;
import org.dcm4che.net.ActiveAssociation;
import org.dcm4che.net.Association;
import org.dcm4che.net.AssociationFactory;
import org.dcm4che.net.Dimse;
import org.dcm4che.net.FutureRSP;
import org.dcm4che.net.PDU;
import org.dcm4chex.archive.config.DicomPriority;
import org.dcm4chex.archive.config.RetryIntervalls;
import org.dcm4chex.archive.ejb.jdbc.AECmd;
import org.dcm4chex.archive.ejb.jdbc.AEData;
import org.dcm4chex.archive.mbean.JMSDelegate;
import org.dcm4chex.archive.mbean.TLSConfigDelegate;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.DocumentSource;
import org.dom4j.io.SAXContentHandler;
import org.jboss.system.ServiceMBeanSupport;
import org.regenstrief.xhl7.HL7XMLLiterate;
import org.regenstrief.xhl7.HL7XMLReader;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * @author Gunter Zeilinger <gunterze@gmail.com>
 * @version $Revision: 3008 $ $Date: 2006-12-07 23:38:46 +0800 (周四, 07 12月 2006) $
 * @since Nov 30, 2006
 */
public class PrefetchService extends ServiceMBeanSupport implements
        NotificationListener, MessageListener {

    private String prefetchSourceAET;
    private String destinationQueryAET;
    private String destinationStorageAET;
    private String callingAET = "DCM4CHEE";
    private String stylesheetURL = "resource:dcm4chee-hl7/orm2prefetch.xsl";
    private ObjectName hl7ServerName;
    private ObjectName moveScuServiceName;
    private String queueName;
    private RetryIntervalls retryIntervalls = new RetryIntervalls();
    private int sourceQueryPriority = 0;
    private int destinationQueryPriority = 0;
    private int retrievePriority = 0;

    private int acTimeout;
    private int dimseTimeout;
    private int maxPDUlen = 16352;
    private int soCloseDelay;

    private int concurrency = 1;

    private JMSDelegate jmsDelegate = new JMSDelegate(this);
    private TLSConfigDelegate tlsConfig = new TLSConfigDelegate(this);

    private static final String ONLINE = "ONLINE";

    public final String getPrefetchSourceAET() {
        return prefetchSourceAET != null ? prefetchSourceAET : "NONE";
    }

    public final void setPrefetchSourceAET(String aet) {
        this.prefetchSourceAET = "NONE".equalsIgnoreCase(aet) ? null : aet;
    }

    public final String getDestinationQueryAET() {
        return destinationQueryAET;
    }

    public final void setDestinationQueryAET(String aet) {
        this.destinationQueryAET = aet;
    }

    public final String getDestinationStorageAET() {
        return destinationStorageAET;
    }

    public final void setDestinationStorageAET(String aet) {
        this.destinationStorageAET = aet;
    }

    public final String getSourceQueryPriority() {
        return DicomPriority.toString(sourceQueryPriority);
    }

    public final void setSourceQueryPriority(String cs) {
        this.sourceQueryPriority = DicomPriority.toCode(cs);
    }

    public final String getDestinationQueryPriority() {
        return DicomPriority.toString(destinationQueryPriority);
    }

    public final void setDestinationQueryPriority(String cs) {
        this.destinationQueryPriority = DicomPriority.toCode(cs);
    }

    public final String getRetrievePriority() {
        return DicomPriority.toString(retrievePriority);
    }

    public final void setRetrievePriority(String retrievePriority) {
        this.retrievePriority = DicomPriority.toCode(retrievePriority);
    }

    /**
     * @return the callingAET
     */
    public String getCallingAET() {
        return callingAET;
    }

    /**
     * @param callingAET the callingAET to set
     */
    public void setCallingAET(String callingAET) {
        this.callingAET = callingAET;
    }

    public final int getMaxPDUlen() {
        return maxPDUlen;
    }
    public final void setMaxPDUlen(int maxPDUlen) {
        this.maxPDUlen = maxPDUlen;
    }

    public String getStylesheetURL() {
        return stylesheetURL;
    }

    public void setStylesheetURL(String stylesheetURL) {
        this.stylesheetURL = stylesheetURL;
        reloadStylesheets();
    }

    public final ObjectName getJmsServiceName() {
        return jmsDelegate.getJmsServiceName();
    }

    public final void setJmsServiceName(ObjectName jmsServiceName) {
        jmsDelegate.setJmsServiceName(jmsServiceName);
    }

    public final int getConcurrency() {
        return concurrency;
    }

    public final void setConcurrency(int concurrency) throws Exception {
        if (concurrency <= 0)
            throw new IllegalArgumentException("Concurrency: " + concurrency);
        if (this.concurrency != concurrency) {
            final boolean restart = getState() == STARTED;
            if (restart)
                stop();
            this.concurrency = concurrency;
            if (restart)
                start();
        }
    }

    public String getRetryIntervalls() {
        return retryIntervalls.toString();
    }

    public void setRetryIntervalls(String text) {
        retryIntervalls = new RetryIntervalls(text);
    }

    public final String getQueueName() {
        return queueName;
    }

    public final void setQueueName(String queueName) {
        this.queueName = queueName;
    }

    public final ObjectName getHL7ServerName() {
        return hl7ServerName;
    }

    public final void setHL7ServerName(ObjectName hl7ServerName) {
        this.hl7ServerName = hl7ServerName;
    }

    public final ObjectName getTLSConfigName() {
        return tlsConfig.getTLSConfigName();
    }

    public final void setTLSConfigName(ObjectName tlsConfigName) {
        tlsConfig.setTLSConfigName(tlsConfigName);
    }

    public final ObjectName getMoveScuServiceName() {
            return moveScuServiceName;
    }

    public final void setMoveScuServiceName(ObjectName moveScuServiceName) {
            this.moveScuServiceName = moveScuServiceName;
    }

    /**
     * @return the acTimeout
     */
    public int getAcTimeout() {
        return acTimeout;
    }

    /**
     * @param acTimeout the acTimeout to set
     */
    public void setAcTimeout(int acTimeout) {
        this.acTimeout = acTimeout;
    }

    /**
     * @return the dimseTimeout
     */
    public int getDimseTimeout() {
        return dimseTimeout;
    }

    /**
     * @param dimseTimeout the dimseTimeout to set
     */
    public void setDimseTimeout(int dimseTimeout) {
        this.dimseTimeout = dimseTimeout;
    }

    /**
     * @return the soCloseDelay
     */
    public int getSoCloseDelay() {
        return soCloseDelay;
    }

    /**
     * @param soCloseDelay the soCloseDelay to set
     */
    public void setSoCloseDelay(int soCloseDelay) {
        this.soCloseDelay = soCloseDelay;
    }

    protected void startService() throws Exception {
        jmsDelegate.startListening(queueName, this, concurrency);
        server.addNotificationListener(hl7ServerName, this,
                HL7ServerService.NOTIF_FILTER, null);
    }

    protected void stopService() throws Exception {
        server.removeNotificationListener(hl7ServerName, this,
                HL7ServerService.NOTIF_FILTER, null);
        jmsDelegate.stopListening(queueName);
    }

    public void handleNotification(Notification notif, Object handback) {
        if (prefetchSourceAET == null) {
            return;
        }
        Object[] hl7msg = (Object[]) notif.getUserData();
        Document hl7doc = (Document) hl7msg[1];
        if (isORM_O01_NW(hl7doc)) {
            Dataset findRQ = DcmObjectFactory.getInstance().newDataset();
            try {
                Transformer t = getTemplates(stylesheetURL).newTransformer();
                t.transform(new DocumentSource(hl7doc), new SAXResult(findRQ
                        .getSAXHandler2(null)));
            } catch (TransformerException e) {
                log.error("Failed to transform ORM into prefetch request", e);
                return;
            }
            prepareFindReqDS(findRQ);
            PrefetchOrder order = new PrefetchOrder(findRQ);
            try {
                log.info("Scheduling " + order);
                jmsDelegate.queue(queueName, order, Message.DEFAULT_PRIORITY,
                        0L);
            } catch (Exception e) {
                log.error("Failed to schedule " + order, e);
            }
        }
    }

    private boolean isORM_O01_NW(Document hl7doc) {
        MSH msh = new MSH(hl7doc);
        return "ORM".equals(msh.messageType) && "O01".equals(msh.triggerEvent)
            && "NW".equals(hl7doc.getRootElement().element("ORC")
                    .element(HL7XMLLiterate.TAG_FIELD).getText());
    }

    public void onMessage(Message message) {
        ObjectMessage om = (ObjectMessage) message;
        try {
            PrefetchOrder order = (PrefetchOrder) om.getObject();
            log.info("Start processing " + order);
            try {
                process(order);
                log.info("Finished processing " + order);
            } catch (Exception e) {
                final int failureCount = order.getFailureCount() + 1;
                order.setFailureCount(failureCount);
                final long delay = retryIntervalls.getIntervall(failureCount);
                if (delay == -1L) {
                    log.error("Give up to process " + order, e);
                } else {
                    log.warn("Failed to process " + order
                            + ". Scheduling retry.", e);
                    jmsDelegate.queue(queueName, order, 0, System
                            .currentTimeMillis()
                            + delay);
                }
            }
        } catch (JMSException e) {
            log.error("jms error during processing message: " + message, e);
        } catch (Throwable e) {
            log.error("unexpected error during processing message: " + message,
                    e);
        }
    }

    private Templates getTemplates(String uri) {
        try {
            return (Templates) server.invoke(hl7ServerName, "getTemplates",
                    new Object[] { uri },
                    new String[] { String.class.getName() });
        } catch (Exception e) {
            String prompt = "Failed to load XSL " + uri;
            log.error(prompt, e);
            throw new RuntimeException(prompt, e);
        }
    }

    private void reloadStylesheets() {
        if (getState() != STARTED) return;
        try {
            server.invoke(hl7ServerName, "reloadStylesheets",
                    null, null);
        } catch (Exception e) {
            log.error("JMX error:", e);
            throw new RuntimeException("JMX error:", e);
        }
    }

    private void process(PrefetchOrder order) throws Exception {
        Dataset keys = order.getDataset();
        log.debug("SearchDS from order:");log.debug(keys);
        Map srcList = doCFIND(prefetchSourceAET, callingAET, keys, sourceQueryPriority);
        Map destList = doCFIND(destinationQueryAET, callingAET, keys, destinationQueryPriority);
        List notAvail = this.getListOfNotAvail(srcList, destList);
        if (notAvail.size() > 0 ) {
            log.debug("notAvail:"+notAvail);
            log.info(notAvail.size()+" Series are not available on destination AE! Schedule for Pre-Fetch");
            for ( Iterator iter = notAvail.iterator() ; iter.hasNext() ; ) {
                scheduleMove( prefetchSourceAET, destinationStorageAET, retrievePriority,
                        (Dataset) iter.next(), 0l);
            }
        }
    }

    /**
     * @param keys
     */
    private void prepareFindReqDS(Dataset keys) {
        String qrLevel = keys.getString(Tags.QueryRetrieveLevel);
        if ( qrLevel != null && !qrLevel.equals("SERIES") ) {
            log.warn("QueryRetrieveLevel of PrefetchOrder is "+qrLevel+"! Set to SERIES!");
        }
        keys.putCS(Tags.QueryRetrieveLevel,"SERIES");
        if ( !keys.contains(Tags.PatientID) ) keys.putUI(Tags.PatientID);
        if ( !keys.contains(Tags.StudyInstanceUID) ) keys.putUI(Tags.StudyInstanceUID);
        if ( !keys.contains(Tags.SeriesInstanceUID) ) keys.putUI(Tags.SeriesInstanceUID);
        keys.putIS(Tags.NumberOfSeriesRelatedInstances);
        keys.putCS(Tags.InstanceAvailability);
    }

    private Map doCFIND(String calledAET, String callingAET, Dataset keys, int priority ) throws Exception {
        ActiveAssociation assoc = null;
        try {
            AEData aeData = new AECmd(calledAET).getAEData();
            assoc = openAssoc(tlsConfig.createSocket(aeData),
                    getCFINDAssocReq(calledAET, callingAET));
            if (assoc == null) {
                log.error("Couldnt open association to " + aeData);
                return null;
            }
            Association as = assoc.getAssociation();
            if (as.getAcceptedTransferSyntaxUID(1) == null) {
                log.error(calledAET + " doesnt support CFIND request!", null);
                return null;
            }
            Map result = new HashMap();
            // send cfind request.
            Command cmd = DcmObjectFactory.getInstance().newCommand();
            cmd.initCFindRQ(1, UIDs.StudyRootQueryRetrieveInformationModelFIND,
                    priority);
            Dimse mcRQ = AssociationFactory.getInstance().newDimse(1, cmd,
                    keys);
            FutureRSP findRsp = assoc.invoke(mcRQ);
            Dimse dimse = findRsp.get();
            List pending = findRsp.listPending();
            Iterator iter = pending.iterator();
            Dataset ds;
            while (iter.hasNext()) {
                ds = ((Dimse) iter.next()).getDataset();
                result.put(ds.getString(Tags.SeriesInstanceUID), ds);
                log.debug(calledAET+": received Dataset:");log.debug(ds);
            }
            if (log.isDebugEnabled()) {
                log.debug(calledAET+" : received final C-FIND RSP :"
                        + dimse);
            }
            return result;
        } finally {
            if (assoc != null)
                try {
                    assoc.release(true);
                } catch (Exception e1) {
                    log.error(
                            "Cant release association for CFIND"
                                    + assoc.getAssociation(), e1);
                }
        }
    }

    /**
     * Return the association request for modality worklist C-FIND.
     * <p>
     * This association is used for sending modality worklist C-FIND request and action
     * command.
     *
     * @return Association for media creation.
     */
    private AAssociateRQ getCFINDAssocReq(String calledAET, String callingAET) {
        AssociationFactory aFact = AssociationFactory.getInstance();
        AAssociateRQ assocRQ = aFact.newAAssociateRQ();
        assocRQ.setCalledAET(calledAET);
        assocRQ.setCallingAET(callingAET);
        assocRQ.setMaxPDULength(maxPDUlen);
        assocRQ.addPresContext(aFact.newPresContext(1,
                UIDs.StudyRootQueryRetrieveInformationModelFIND, new String[]{ UIDs.ExplicitVRLittleEndian,
                    UIDs.ImplicitVRLittleEndian }));
        return assocRQ;
    }

    private ActiveAssociation openAssoc(Socket sock, AAssociateRQ assocRQ)
        throws IOException, GeneralSecurityException {
        AssociationFactory aFact = AssociationFactory.getInstance();
        Association assoc = aFact.newRequestor(sock);
        assoc.setAcTimeout(acTimeout);
        assoc.setDimseTimeout(dimseTimeout);
        assoc.setSoCloseDelay(soCloseDelay);
        PDU assocAC = assoc.connect(assocRQ);
        if (!(assocAC instanceof AAssociateAC)) {
            return null;
        }
        ActiveAssociation retval = aFact.newActiveAssociation(assoc, null);
        retval.start();
        return retval;
    }

    private List getListOfNotAvail(Map all, Map map ) {
        ArrayList l = new ArrayList();
        Dataset ds, dsAll;
        Entry entry;
        String seriesIUID;
        StringBuffer sb = new StringBuffer();
        for ( Iterator iter = all.entrySet().iterator() ; iter.hasNext() ; ) {
            entry = (Entry) iter.next();
            seriesIUID = (String) entry.getKey();
            dsAll = (Dataset) entry.getValue();
            ds = (Dataset) map.get(seriesIUID);
            sb.setLength(0);
            sb.append("Series ").append(seriesIUID).append(": ");
            if ( ds == null ) {
                log.debug(sb.append("Only known on source AE"));
                l.add( dsAll );
            } else if ( ! ONLINE.equals( ds.getString(Tags.InstanceAvailability)) ) {
                log.debug(sb.append("Instances are not available (ONLINE) on destination AE!"));
                l.add( dsAll );
            } else {
                int noi = ds.getInt(Tags.NumberOfSeriesRelatedInstances, -1);
                int noi1 = dsAll.getInt(Tags.NumberOfSeriesRelatedInstances, -1);
                sb.append("NumberOfSeriesRelatedInstances ");
                if ( noi == -1 || noi1 == -1 ) {
                    sb.append("is not available to check count of instances! dest:");
                    log.warn(sb.append(noi).append(" src:").append(noi1));
                } else if ( noi < noi1 ) {
                    sb.append("on destination AE is less than on source AE! dest:");
                    log.debug(sb.append(noi).append(" src:").append(noi1));
                    l.add(dsAll);
                }
            }
        }
        return l;
    }

    private void scheduleMove(String retrieveAET, String destAET, int priority,
            Dataset ds, long scheduledTime) {
        try {
            server.invoke(moveScuServiceName, "scheduleMove", new Object[] {
                    retrieveAET, destAET, new Integer(priority), ds.getString(Tags.PatientID),
                    ds.getString(Tags.StudyInstanceUID),
                    ds.getString(Tags.SeriesInstanceUID), null, new Long(scheduledTime) },
                    new String[] { String.class.getName(),
                            String.class.getName(), int.class.getName(),
                            String.class.getName(), String.class.getName(),
                            String.class.getName(), String[].class.getName(),
                            long.class.getName() });
        } catch (Exception e) {
            log.error("Schedule Move failed:", e);
        }
    }

    public void processFile(String filename) throws DocumentException, IOException, SAXException {
        Dataset findRQ = DcmObjectFactory.getInstance().newDataset();
        HL7XMLReader reader = new HL7XMLReader();
        File file = new File(filename);
        SAXContentHandler hl7in = new SAXContentHandler();
        reader.setContentHandler(hl7in);
        reader.parse(new InputSource( new FileInputStream(file)));
        Document doc = hl7in.getDocument();
        try {
            Transformer t = getTemplates(stylesheetURL).newTransformer();
            t.transform(new DocumentSource(doc), new SAXResult(findRQ.getSAXHandler2(null)));
        } catch (TransformerException e) {
            log.error("Failed to transform into prefetch request", e);
            return;
        }
        this.prepareFindReqDS(findRQ);
        PrefetchOrder order = new PrefetchOrder(findRQ);
        try {
            log.info("Scheduling Test PrefetchOrder:" + order);
            jmsDelegate.queue(queueName, order, Message.DEFAULT_PRIORITY, 0L);
        } catch (Exception e) {
            log.error("Failed to schedule Test Order" + order, e);
        }
     }

}


text:
$(function () {
  // Returns the value of a query param if it exists, null otherwise
  const getParameterByName = function(name) {
    name = name.replace(/[\[\]]/g, "\\$&");
    const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
    const results = regex.exec(window.location.href);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
  }

  const skipBeers = getParameterByName('skip-beers') ? true : false;

  const container = document.querySelector("#breweries");
  const query =
    `query ($city: String, $skipBeers: Boolean!) {
      breweries(city: $city) {
        name
        address
        website
        beers @skip(if: $skipBeers) {
          name
          abv
          description(charLimit: 200)
          style {
            name
          }
        }
      }
    }`;

  const handleSearch = function(city) {
    fetch('/graphql', {
      method: 'post',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        query: query,
        variables: {
          city: city,
          skipBeers: skipBeers
        }
      }),

    }).then(function (response) {
      return response.text();
    }).then(function (responseBody) {
      try {
        return JSON.parse(responseBody);
      } catch (error) {
        return responseBody;
      }
    }).then(function(response) {
      // Empty potential previous results
      while (container.hasChildNodes()) {
        container.removeChild(container.firstChild);
      }

      if (response.data.breweries.length === 0) {
        const noBreweriesTemplate = document.querySelector('#no-breweries-template');
        const noBreweriesClone = document.importNode(noBreweriesTemplate.content, true);
        container.appendChild(noBreweriesClone);
      }

      response.data.breweries.forEach(brewery => {
        const breweryTemplate = document.querySelector('#brewery-template');
        breweryTemplate.content.querySelector('.brewery-name').textContent = brewery.name;
        breweryTemplate.content.querySelector('.brewery-address').textContent = brewery.address;
        breweryTemplate.content.querySelector('.brewery-website').href = brewery.website;
        breweryTemplate.content.querySelector('.brewery-website').textContent = brewery.website;

        const breweryClone = document.importNode(breweryTemplate.content, true);

        // This is a hack to allow for a "beer-less" version of the app by
        // opening it with ?skip-beers=1
        if (skipBeers) {
          breweryClone.querySelector('.panel-body').removeChild(
            breweryClone.querySelector('.brewery-beers-block')
          );
        } else {
          const beersContainer = breweryClone.querySelector('.brewery-beers');

          brewery.beers.forEach(beer => {
            const beerTemplate = document.querySelector('#beer-template');
            const style = beer.style.name.toLowerCase();
            let styleColor;

            if(/white|wheat|weizen|weiss|winter/.test(style)) {
              styleColor = "white";
            } else if (/red|amber|sour|lambic|smoke|rye/.test(style)) {
              styleColor = "red";
            } else if (/pale|bitter|summer|light|fresh/.test(style)) {
              styleColor = "pale";
            } else if (/gose|kolsch|honey|cream|keller|lager|pilsener|pilsner|oktoberfest|saison|pumpkin/.test(style)) {
              styleColor = "blonde";
            } else if (/dark|heavy|scottish|scotch|barley|brown|old|strong|dubbel|tripel|quadrupel|bock|chocolate/.test(style)) {
              styleColor = "dark";
            } else if (/black|stout|porter|schwarz|coffee/.test(style)) {
              styleColor = "black";
            } else {
              styleColor = "other";
            }

            beerTemplate.content.querySelector('.beer-popover').dataset.styleColor = styleColor;
            beerTemplate.content.querySelector('.beer-popover').dataset.content =
              `
${beer.name}

                ${beer.style.name}

                ${beer.abv}% ABV

${beer.description.replace(/\n/g, "
")}
`;

            const beerClone = document.importNode(beerTemplate.content, true);
            beersContainer.appendChild(beerClone);
          });
        }

        container.appendChild(breweryClone);
      });

      $('[data-toggle="popover"]').popover({
        html: true,
        trigger: 'hover focus'
      });
    });
  };

  document.querySelector('form#search').addEventListener("submit", event => {
    const city = document.querySelector('#search input').value;
    if (city.length > 0) {
      handleSearch(city);
    }
    event.preventDefault();
  });

  const invertColorCheckbox = document.querySelector('.invert-colors input[type=checkbox]');
  invertColorCheckbox.addEventListener('change', event => {
    if (invertColorCheckbox.checked) {
      document.querySelector('html').classList.add('inverted-colors');
    } else {
      document.querySelector('html').classList.remove('inverted-colors');
    }
  });
});


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
	<title>Simple Lightbox - Responsive touch friendly Image lightbox</title>
	<link href='http://fonts.googleapis.com/css?family=Slabo+27px' rel='stylesheet' type='text/css'>
	<link href='../dist/simplelightbox.min.css' rel='stylesheet' type='text/css'>
	<link href='demo.css' rel='stylesheet' type='text/css'>

Simple Lightbox Demo Page

All images are free availabled on Unsplash

Documentation and download here


text:
var exec = require('./exec-meshctl');
var test = require('tap').test;
var version = require('../package.json').version;

test('Test help messages', function(t) {
  exec(0, '--version', function(err, version1) {
    t.ifError(err, 'command should not error');
    t.equal(version1.trim(), version, 'package version should match');
    exec(0, '-v', function(err, version2) {
      t.ifError(err, 'command should not error');
      t.equal(version1, version2, 'package version should match');
      t.end();
    });
  });
});


text:
using System;
using System.Windows.Input;

namespace Rxns.DDD.Commanding
{
    public interface IRxnCommand : ICommand, IDisposable
    {

    }
}


text:
class AddCustomersScoreColumn < ActiveRecord::Migration
  def change
    add_column :customers, :score, :integer, :null => false, :defaults => 0, after: :mobile
  end
end


text:
<?php

namespace Sortable\Fixture;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 */
class Category
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\OneToMany(targetEntity="Item", mappedBy="category")
     */
    private $items;

    public function __construct()
    {
        $this->items = new ArrayCollection();
    }

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

    public function setName($name)
    {
        $this->name = $name;
    }

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