text:
package org.aguilar.swinglib.swing.models;

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

/**
 *  The BeanTableModel will use reflection to determine the columns of
 *  data to be displayed in the table model. Reflection is used to find all
 *  the methods declared in the specified bean. The criteria used for
 *  adding columns to the model are:
 *
 *  a) the method name must start with either "get" or "is"
 *  b) the parameter list for the method must contain 0 parameters
 *
 *  You can also specify an ancestor class in which case the declared methods
 *  of the ancestor and all its descendents will be included in the model.
 *
 *  A column name will be assigned to each column based on the method name.
 *
 *  The cell will be considered editable when a corresponding "set" method
 *  name is found.
 *
 *  Reflection will also be used to implement the getValueAt() and
 *  setValueAt() methods.
 */
public class BeanTableModel<T> extends RowTableModel<T>
{
	//  Map "type" to "class". Class is needed for the getColumnClass() method.

	private static Map<Class, Class> primitives = new HashMap<Class, Class>(10) {{
            put(Boolean.TYPE, Boolean.class);
            put(Byte.TYPE, Byte.class);
            put(Character.TYPE, Character.class);
            put(Double.TYPE, Double.class);
            put(Float.TYPE, Float.class);
            put(Integer.TYPE, Integer.class);
            put(Long.TYPE, Long.class);
            put(Short.TYPE, Short.class);
        }};

//	static
//	{
//		primitives.put(Boolean.TYPE, Boolean.class);
//		primitives.put(Byte.TYPE, Byte.class);
//		primitives.put(Character.TYPE, Character.class);
//		primitives.put(Double.TYPE, Double.class);
//		primitives.put(Float.TYPE, Float.class);
//		primitives.put(Integer.TYPE, Integer.class);
//		primitives.put(Long.TYPE, Long.class);
//		primitives.put(Short.TYPE, Short.class);
//	}

	private Class beanClass;
	private Class ancestorClass;

	private List<ColumnInformation> columns = new ArrayList<ColumnInformation>();

	/**
	 *  Constructs an empty BeanTableModel for the specified bean.
	 *
	 *  @param beanClass  class of the beans that will be added to the model.
	 *                    The class is also used to determine the columns that
	 *                    will be displayed in the model
	 */
	public BeanTableModel(Class beanClass)
	{
		this(beanClass, beanClass, new ArrayList<T>());
	}

	/**
	 *  Constructs an empty BeanTableModel for the specified bean.
	 *
	 *  @param beanClass      class of the beans that will be added to the model.
	 *  @param ancestorClass  the methods of this class and its descendents down
	 *						 to the bean class can be included in the model.
	 */
	public BeanTableModel(Class beanClass, Class ancestorClass)
	{
		this(beanClass, ancestorClass, new ArrayList<T>());
	}

	/**
	 *  Constructs an empty BeanTableModel for the specified bean.
	 *
	 *  @param beanClass      class of the beans that will be added to the model.
	 *  @param modelData      the data of the table
	 */
	public BeanTableModel(Class beanClass, List<T> modelData)
	{
		this(beanClass, beanClass, modelData);
	}

	/**
	 *  Constructs an empty BeanTableModel for the specified bean.
	 *
	 *  @param beanClass      class of the beans that will be added to the model.
	 *  @param ancestorClass  the methods of this class and its descendents down
	 *						 to the bean class can be included in the model.
	 *  @param modelData      the data of the table
	 */
	public BeanTableModel(Class beanClass, Class ancestorClass, List<T> modelData)
	{
		super( beanClass );
		this.beanClass = beanClass;
		this.ancestorClass = ancestorClass;

		//  Use reflection on the beanClass and ancestorClass to find properties
		//  to add to the TableModel

		createColumnInformation();

		//  Initialize the column name List to the proper size. The actual
		//  column names will be reset in the resetModelDefaults() method.

		List<String> columnNames = new ArrayList<String>();

		for (ColumnInformation info: columns)
		{
			columnNames.add( info.getName() );
		}

		//  Reset all the values in the RowTableModel

		super.setDataAndColumnNames(modelData, columnNames);
		resetModelDefaults();
	}

	/*
	 *  Use reflection to find all the methods that should be included in the
	 *  model.
	 */
	@SuppressWarnings("unchecked")
	private void createColumnInformation()
	{
		Method[] theMethods = beanClass.getMethods();

		//  Check each method to make sure it should be used in the model

		for (int i = 0; i < theMethods.length; i++)
		{
			Method theMethod = theMethods[i];

			if (theMethod.getParameterTypes().length == 0
			&&  ancestorClass.isAssignableFrom(theMethod.getDeclaringClass()) )
			{
				String methodName = theMethod.getName();

				if (theMethod.getName().startsWith("get"))
					buildColumnInformation(theMethod, methodName.substring(3));

				if (theMethod.getName().startsWith("is"))
					buildColumnInformation(theMethod, methodName.substring(2));
			}
		}
	}

	/*
	 *	We found a method candidate so gather the information needed to fully
	 *  implemennt the table model.
	 */
	@SuppressWarnings("unchecked")
	private void buildColumnInformation(Method theMethod, String theMethodName)
	{
		//  Make sure the method returns an appropriate type

		Class returnType = getReturnType( theMethod );

		if (returnType == null) return;

		//  Convert the method name to a display name for each column and
		//  then check for a related "set" method.

		String headerName = formatColumnName( theMethodName );

		Method setMethod = null;

		try
		{
			String setMethodName = "set" + theMethodName;
			setMethod = beanClass.getMethod(setMethodName, theMethod.getReturnType());
		}
		catch(NoSuchMethodException e) {}

		//  We have all the information we need, so save it for later use
		//  by the table model methods.

		ColumnInformation ci = new ColumnInformation(headerName, returnType, theMethod, setMethod);
                columns.add( ci );
	}

	/*
	 *  Make sure the return type of the method is something we can use
	 */
	private Class getReturnType(Method theMethod)
	{
		Class returnType = theMethod.getReturnType();

		if (returnType.isInterface()
		||  returnType.isArray())
			return null;

		//  The primitive class type is different then the wrapper class of the
		//  primitive. We need the wrapper class.

		if (returnType.isPrimitive())
			returnType = primitives.get(returnType);

		return returnType;
	}

	/*
	 *  Use information collected from the bean to set model default values.
	 */
	private void resetModelDefaults()
	{
		columnNames.clear();

		for (int i = 0; i < columns.size(); i++)
		{
			ColumnInformation info = columns.get(i);
			columnNames.add( info.getName() );
			super.setColumnClass(i, info.getReturnType());
			super.setColumnEditable(i, info.getSetter() == null ? false : true);
		}
	}

	/**
	 *  Returns an attribute value for the cell at row
	 *  and column.
	 *
	 *  @param   row        the row whose value is to be queried
	 *  @param   column     the column whose value is to be queried
	 *  @return             the value Object at the specified cell
	 *  @exception  IndexOutOfBoundsException
	 *                     if an invalid row or column was given
	 */
	@Override
	public Object getValueAt(int row, int column)
	{
		ColumnInformation ci = (ColumnInformation)columns.get( column );

		Object value = null;

		try
		{
			value = ci.getGetter().invoke(getRow(row));
		}
		catch(IllegalAccessException e) {}
		catch(InvocationTargetException e) {}

		return value;
	}

	/**
	 *  Sets the object value for the cell at column and
	 *  row.  value is the new value.  This method
	 *  will generate a tableChanged notification.
	 *
	 * @param   value           the new value; this can be null
	 * @param   row             the row whose value is to be changed
	 * @param   column          the column whose value is to be changed
	 * @exception  IndexOutOfBoundsException  if an invalid row or
	 *			   column was given
	 */
	@Override
	public void setValueAt(Object value, int row, int column)
	{
		ColumnInformation ci = (ColumnInformation)columns.get( column );

		try
		{
			Method setMethod = ci.getSetter();

			if (setMethod != null)
			{
				setMethod.invoke(getRow(row), value);
				fireTableCellUpdated(row, column);
			}
		}
		catch(IllegalAccessException e) {}
		catch(InvocationTargetException e) {}
	}

	/**
	 *  You are not allowed to change the class of any column.
	 */
	@Override
	public void setColumnClass(int column, Class columnClass)
	{
	}

	/**
	 *  Sets the editability for the specified column.
	 *
	 *	Override to make sure you can't set a column editable that doesn't
	 *  have a defined setter method.
	 *
	 *  @param  column       the column whose Class is being changed
	 *  @param  isEditable   indicates if the column is editable or not
	 *  @exception  ArrayIndexOutOfBoundsException
	 *	 		            if an invalid column was given
	 */
	@Override
	public void setColumnEditable(int column, boolean isEditable)
	{
		ColumnInformation ci = (ColumnInformation)columns.get( column );

		if (isEditable && ci.getSetter() == null) return;

		super.setColumnEditable(column, isEditable);
	}

	/**
	 *  Convenience method to change the generated column header name.
	 *
	 *  This method must be invoked before the model is added to the table.
	 *
	 *  @param   column     the column whose value is to be queried
	 *  @exception  IndexOutOfBoundsException  if an invalid column
	 *	            was given
	 */
	public void setColumnName(int column, String name)
	{
		ColumnInformation ci = (ColumnInformation)columns.get( column );
		ci.setName( name );
		resetModelDefaults();
	}

	/*
	 *  Columns are created in the order in which they are defined in the
	 *  bean class. This method will sort the columns by colum header name.
	 *
	 *  This method must be invoked before the model is added to the table.
	 */
	public void sortColumnNames()
	{
		Collections.sort(columns);
		resetModelDefaults();
	}

	/*
	 *  Class to hold data required to implement the TableModel interface
	 */
	private class ColumnInformation implements Comparable<ColumnInformation>
	{
		private String name;
		private Class returnType;
		private Method getter;
		private Method setter;

		public ColumnInformation(String name, Class returnType, Method getter, Method setter)
		{
			this.name = name;
			this.returnType = returnType;
			this.getter = getter;
			this.setter = setter;
		}

		/*
		 *  The column class of the model
		 */
		public Class getReturnType()
		{
			return returnType;
		}

		/*
		 *  Used by the getValueAt() method to get the data for the cell
		 */
		public Method getGetter()
		{
			return getter;
		}

		/*
		 *  The value used as the column header name
		 */
		public String getName()
		{
			return name;
		}

		/*
		 *  Used by the setValueAt() method to update the bean
		 */
		public Method getSetter()
		{
			return setter;
		}

		/*
		 *  Use to change the column header name
		 */
		public void setName(String name)
		{
			this.name = name;
		}

    	/*
    	 *  Implement the natural sort order for this class
    	 */
    	public int compareTo(ColumnInformation o)
    	{
    		return getName().compareTo(o.getName());
    	}
	}
}


text:
from __future__ import absolute_import
import itertools

import tensorflow as tf

import deep_architect.helpers.tensorflow_eager_support as htfe
from deep_architect.contrib.deep_learning_backend.tensorflow_keras_ops import (
    relu, batch_normalization, conv2d, max_pool2d, fc_layer, dropout, flatten,
    add)

import deep_architect.modules as mo
from deep_architect.hyperparameters import Discrete as D
from deep_architect.hyperparameters import Bool

def genetic_stage(input_fn, node_fn, output_fn, h_connections, num_nodes):

    def substitution_fn(dh):
        num_ins = [
            sum([dh['%d_%d' % (in_id, out_id)]
                 for in_id in range(1, out_id)])
            for out_id in range(1, num_nodes + 1)
        ]
        num_outs = [
            sum([
                dh['%d_%d' % (in_id, out_id)]
                for out_id in range(in_id + 1, num_nodes + 1)
            ])
            for in_id in range(1, num_nodes + 1)
        ]
        if sum(num_ins) == 0:
            return input_fn()

        nodes = [input_fn()]
        nodes += [
            node_fn(max(num_ins[i], 1))
            if num_ins[i] > 0 or num_outs[i] > 0 else None
            for i in range(num_nodes)
        ]
        nodes.append(
            output_fn(
                len([
                    i for i in range(len(num_outs))
                    if num_outs[i] == 0 and nodes[i + 1] is not None
                ])))

        num_connected = [0] * (num_nodes + 2)
        for in_id in range(1, num_nodes + 1):
            # Connect nodes with no input to original input
            if num_ins[in_id - 1] == 0 and nodes[in_id] is not None:
                nodes[0][1]['out'].connect(nodes[in_id][0]['in0'])
            # Connect nodes with no output to final output node
            if num_outs[in_id - 1] == 0 and nodes[in_id] is not None:
                nodes[in_id][1]['out'].connect(nodes[-1][0]['in%d' %
                                                            num_connected[-1]])
                num_connected[-1] += 1

            # Connect internal nodes
            for out_id in range(in_id + 1, num_nodes + 1):
                if dh['%d_%d' % (in_id, out_id)] == 1:
                    nodes[in_id][1]['out'].connect(
                        nodes[out_id][0]['in' + str(num_connected[out_id])])
                    num_connected[out_id] += 1
        return nodes[0][0], nodes[-1][1]

    i = 0
    name_to_hparam = {}
    for ix, hparam in enumerate(
            itertools.combinations(range(1, num_nodes + 1), 2)):
        name_to_hparam['%d_%d' % hparam] = h_connections[ix]
    return mo.substitution_module('GeneticStage',
                                  substitution_fn,
                                  name_to_hparam, ['in'], ['out'],
                                  scope=None)

def intermediate_node_fn(num_inputs, filters):
    return mo.siso_sequential([
        add(num_inputs),
        conv2d(D([filters]), D([3])),
        batch_normalization(),
        relu()
    ])

def generate_stage(stage_num, num_nodes, filters, filter_size):
    h_connections = [
        Bool(name='%d_in_%d_%d' % (stage_num, in_id, out_id))
        for (in_id,
             out_id) in itertools.combinations(range(1, num_nodes + 1), 2)
    ]

    return genetic_stage(
        lambda: mo.siso_sequential([
            conv2d(D([filters]), D([filter_size])),
            batch_normalization(),
            relu()
        ]), lambda num_inputs: intermediate_node_fn(num_inputs, filters), lambda
        num_inputs: intermediate_node_fn(num_inputs, filters), h_connections,
        num_nodes)

def generate_search_space(nodes_per_stage, filters_per_stage,
                          filter_size_per_stage):
    search_space = []

    for i in range(len(nodes_per_stage)):
        search_space.append(
            generate_stage(i, nodes_per_stage[i], filters_per_stage[i],
                           filter_size_per_stage[i]))
        search_space.append(max_pool2d(D([3]), D([2]), D(['SAME'])))
    search_space += [
        flatten(),
        fc_layer(D([1024])),
        dropout(D([.5])),
        fc_layer(D([10]))
    ]
    return mo.siso_sequential(search_space)

class SSF_Genetic(mo.SearchSpaceFactory):

    def __init__(self):
        mo.SearchSpaceFactory.__init__(
            self, lambda: generate_search_space([3, 4, 5], [64, 128, 256],
                                                [5, 5, 5]))

redpajama_set_name: RedPajamaGithub


text:
package org.hyperledger.indy.sdk.anoncreds;

import org.hyperledger.indy.sdk.ErrorCode;
import org.hyperledger.indy.sdk.ErrorCodeMatcher;
import org.hyperledger.indy.sdk.utils.StorageUtils;
import org.hyperledger.indy.sdk.wallet.InMemWalletType;
import org.hyperledger.indy.sdk.wallet.Wallet;
import org.hyperledger.indy.sdk.wallet.WalletType;
import org.json.JSONArray;
import org.junit.*;

import java.util.concurrent.ExecutionException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class ProverGetClaimOfferTest extends AnoncredsIntegrationTest {

	@Test
	public void testsProverGetClaimOffersWorksForEmptyFilter() throws Exception {

		initCommonWallet();

		String claimOffers = Anoncreds.proverGetClaimOffers(wallet, "{}").get();
		JSONArray claimOffersArray = new JSONArray(claimOffers);

		assertEquals(3, claimOffersArray.length());
	}

	@Test
	public void testsProverGetClaimOffersWorksForFilterByIssuer() throws Exception {

		initCommonWallet();

		String filter = String.format("{\"issuer_did\":\"%s\"}", issuerDid);

		String claimOffers = Anoncreds.proverGetClaimOffers(wallet, filter).get();
		JSONArray claimOffersArray = new JSONArray(claimOffers);

		assertEquals(2, claimOffersArray.length());

		assertTrue(claimOffersArray.toString().contains(String.format(claimOfferTemplate, issuerDid, 1)));
		assertTrue(claimOffersArray.toString().contains(String.format(claimOfferTemplate, issuerDid, 2)));
	}

	@Test
	public void testsProverGetClaimOffersWorksForFilterBySchema() throws Exception {

		initCommonWallet();

		String filter = String.format("{\"schema_seq_no\":%d}", 2);

		String claimOffers = Anoncreds.proverGetClaimOffers(wallet, filter).get();
		JSONArray claimOffersArray = new JSONArray(claimOffers);

		assertEquals(2, claimOffersArray.length());

		assertTrue(claimOffersArray.toString().contains(String.format(claimOfferTemplate, issuerDid, 2)));
		assertTrue(claimOffersArray.toString().contains(String.format(claimOfferTemplate, issuerDid2, 2)));
	}

	@Test
	public void testsProverGetClaimOffersWorksForFilterByIssuerAndSchema() throws Exception {

		initCommonWallet();

		String filter = String.format("{\"issuer_did\":\"%s\",\"schema_seq_no\":%d}", issuerDid, 1);

		String claimOffers = Anoncreds.proverGetClaimOffers(wallet, filter).get();
		JSONArray claimOffersArray = new JSONArray(claimOffers);

		assertEquals(1, claimOffersArray.length());

		assertTrue(claimOffersArray.toString().contains(String.format(claimOfferTemplate, issuerDid, 1)));
	}

	@Test
	public void testsProverGetClaimOffersWorksForNoResult() throws Exception {

		initCommonWallet();

		String filter = String.format("{\"schema_seq_no\":%d}", 3);

		String claimOffers = Anoncreds.proverGetClaimOffers(wallet, filter).get();
		JSONArray claimOffersArray = new JSONArray(claimOffers);

		assertEquals(0, claimOffersArray.length());
	}

	@Test
	public void testsProverGetClaimOffersWorksForInvalidFilterJson() throws Exception {

		initCommonWallet();

		thrown.expect(ExecutionException.class);
		thrown.expectCause(new ErrorCodeMatcher(ErrorCode.CommonInvalidStructure));

		String filter = String.format("{\"schema_seq_no\":\"%d\"}", 1);

		Anoncreds.proverGetClaimOffers(wallet, filter).get();
	}

	@Test
	public void testGetClaimOffersForPlugged() throws Exception {
		String type = "proverInmem";
		String poolName = "default";
		String walletName = "proverCustomWallet";

		Wallet.registerWalletType(type, new InMemWalletType()).get();

		Wallet.createWallet(poolName, walletName, type, null, null).get();
		Wallet wallet = Wallet.openWallet(walletName, null, null).get();

		String claimOffer = String.format(claimOfferTemplate, issuerDid, 1);
		String claimOffer2 = String.format(claimOfferTemplate, issuerDid, 2);
		String claimOffer3 = String.format(claimOfferTemplate, issuerDid2, 2);

		Anoncreds.proverStoreClaimOffer(wallet, claimOffer).get();
		Anoncreds.proverStoreClaimOffer(wallet, claimOffer2).get();
		Anoncreds.proverStoreClaimOffer(wallet, claimOffer3).get();

		String filter = String.format("{\"issuer_did\":\"%s\"}", issuerDid);

		String claimOffers = Anoncreds.proverGetClaimOffers(wallet, filter).get();
		JSONArray claimOffersArray = new JSONArray(claimOffers);
		System.out.println(claimOffersArray);
		assertEquals(2, claimOffersArray.length());

		assertTrue(claimOffersArray.toString().contains(claimOffer));
		assertTrue(claimOffersArray.toString().contains(claimOffer2));
	}
}


text:
package org.kaazing.gateway.server.test.config.builder;

import java.util.Set;
import org.kaazing.gateway.server.test.config.ServiceDefaultsConfiguration;
import org.kaazing.gateway.server.test.config.Suppressible;
import org.kaazing.gateway.server.test.config.SuppressibleConfiguration.Suppression;

public class AbstractServiceDefaultsConfigurationBuilder<R> extends
        AbstractConfigurationBuilder<ServiceDefaultsConfiguration, R> {

    protected AbstractServiceDefaultsConfigurationBuilder(ServiceDefaultsConfiguration configuration, R result,
                                                          Set<Suppression> suppressions) {
        super(configuration, result, suppressions);
    }

    public AbstractServiceDefaultsConfigurationBuilder<R> mimeMapping(String extension, String type) {
        configuration.getSuppressibleConfiguration().addMimeMapping(extension,
                new Suppressible<>(type, getCurrentSuppressions()));
        return this;
    }

    public AbstractServiceDefaultsConfigurationBuilder<R> acceptOption(String option, String value) {
        configuration.getSuppressibleConfiguration().addAcceptOption(option,
                new Suppressible<>(value, getCurrentSuppressions()));
        return this;
    }

    public AbstractServiceDefaultsConfigurationBuilder<R> connectOption(String option, String value) {
        configuration.getSuppressibleConfiguration().addConnectOption(option,
                new Suppressible<>(value, getCurrentSuppressions()));
        return this;
    }

    @Override
    public AbstractServiceDefaultsConfigurationBuilder<R> suppress(Suppression... suppressions) {
        super.addCurrentSuppressions(suppressions);
        return this;
    }

}


text:
{% extends "activity/competition_list.html" %}
{% load humanize %}

            {% block pageheader %}

COMPETITION ACTIVITY DETAIL

            {% endblock pageheader %}

            {% block searchform %}
            {% endblock searchform %}

            {% block content %}

                        Rep
                        {{ entry.rep }}

Product	{{ entry.product }}

Company	{{ entry.competing_company }}

Competing Product	{{ entry.competing_product }}

Activity	{{ entry.activity|linebreaks }}

Expected Effect	{{ entry.expected_effect|linebreaks }}

Suggestion	{{ entry.suggestion|linebreaks }}

Entered On	{{ entry.recorded_date }}

            {% endblock content %}


text:
Stacy Loeb, MD

Commentary by

Stacy Loeb, MD

Contributions from

Stacy Loeb, MD

Stacy Loeb, MD


text:
#include "config.h"

#include "OpaqueRectTrackingContentLayerDelegate.h"

#include "AffineTransform.h"
#include "FloatRect.h"
#include "GraphicsContext.h"
#include "IntRect.h"
#include "PlatformContextSkia.h"
#include <public/WebFloatRect.h>
#include <public/WebRect.h>

using WebKit::WebFloatRect;
using WebKit::WebRect;

namespace WebCore {

OpaqueRectTrackingContentLayerDelegate::OpaqueRectTrackingContentLayerDelegate(GraphicsContextPainter* painter)
    : m_painter(painter)
    , m_opaque(false)
{
}

OpaqueRectTrackingContentLayerDelegate::~OpaqueRectTrackingContentLayerDelegate()
{
}

void OpaqueRectTrackingContentLayerDelegate::paintContents(SkCanvas* canvas, const WebRect& clip, bool canPaintLCDText, WebFloatRect& opaque)
{
    PlatformContextSkia platformContext(canvas);
#if defined(SK_SUPPORT_HINTING_SCALE_FACTOR)
    if (canvas)
        platformContext.setHintingScaleFactor(canvas->getTotalMatrix().getScaleX());
#endif
    platformContext.setTrackOpaqueRegion(!m_opaque);
    // FIXME: Rename PlatformContextSkia::setDrawingToImageBuffer to setCanPaintLCDText.
    // I also suspect that a function on PlatformContextSkia is not really needed.
    // GraphicsContext::setAllowsFontSmoothing can be used for this purpose.
    platformContext.setDrawingToImageBuffer(!(canPaintLCDText && m_opaque));
    GraphicsContext context(&platformContext);

    // Record transform prior to painting, as all opaque tracking will be
    // relative to this current value.
    AffineTransform canvasToContentTransform = context.getCTM().inverse();

    m_painter->paint(context, clip);

    // Transform tracked opaque paints back to our layer's content space.
    ASSERT(canvasToContentTransform.isInvertible());
    ASSERT(canvasToContentTransform.preservesAxisAlignment());
    opaque = canvasToContentTransform.mapRect(platformContext.opaqueRegion().asRect());
}

}


text:
package org.apache.pdfbox.contentstream.operator.graphics;

import java.util.List;

import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine;
import org.apache.pdfbox.contentstream.operator.Operator;
import org.apache.pdfbox.contentstream.operator.OperatorName;

import java.io.IOException;

/**
 * S Stroke the path.
 *
 * @author Ben Litchfield
 */
public final class StrokePath extends GraphicsOperatorProcessor
{
    public StrokePath(PDFGraphicsStreamEngine context)
    {
        super(context);
    }

    @Override
    public void process(Operator operator, List<COSBase> operands) throws IOException
    {
        getGraphicsContext().strokePath();
    }

    @Override
    public String getName()
    {
        return OperatorName.STROKE_PATH;
    }
}


text:
#ifndef _ES_BLOCK_PROCESSOR_H_
#define _ES_BLOCK_PROCESSOR_H_

#ifdef BSP_ENABLED

#include "bundling/BlockProcessor.h"
#include "Ciphersuite.h"
#include "AS_BlockProcessor.h"

namespace dtn {

/**
 * Block processor implementation for the extension security block
 */
class ES_BlockProcessor : public AS_BlockProcessor {
public:
    ES_BlockProcessor();

    virtual int format(oasys::StringBuffer* buf, BlockInfo *block);

};

} // namespace dtn

#endif /* BSP_ENABLED */

#endif /* _ES_BLOCK_PROCESSOR_H_ */


text:
package org.elasticsearch.action.admin.indices.alias;

import org.elasticsearch.cluster.ack.ClusterStateUpdateRequest;
import org.elasticsearch.cluster.metadata.AliasAction;

import java.util.List;

/**
 * Cluster state update request that allows to add or remove aliases
 */
public class IndicesAliasesClusterStateUpdateRequest extends ClusterStateUpdateRequest<IndicesAliasesClusterStateUpdateRequest> {
    private final List<AliasAction> actions;

    public IndicesAliasesClusterStateUpdateRequest(List<AliasAction> actions) {
        this.actions = actions;
    }

    /**
     * Returns the alias actions to be performed
     */
    public List<AliasAction> actions() {
        return actions;
    }
}


text:
import json
from datetime import datetime
from email.header import decode_header as _decode_header
from email.utils import getaddresses
from functools import wraps

import pkg_resources
from flask import current_app
from pytz import utc

def _json_default(obj):
    if isinstance(obj, datetime):
        return utc.localize(obj).isoformat()
    raise TypeError(repr(obj) + ' is not JSON serializable')

def json_dumps(obj):
    return json.dumps(obj, default=_json_default, indent=4)

def jsonify(*args, **kwargs):
    return current_app.response_class(json_dumps(dict(*args, **kwargs)), mimetype='application/json')

def bool_arg(arg):
    return arg in ('yes', 'true', '1')

def decode_header(value):
    if value is None:
        return ''
    return ''.join(
        str(decoded, charset or 'utf-8') if isinstance(decoded, bytes) else decoded
        for decoded, charset in _decode_header(value)
    )

def split_addresses(value):
    return [('{0} <{1}>'.format(name, addr) if name else addr) for name, addr in getaddresses([value])]

def rest(f):
    """Decorator for simple REST endpoints.

    Functions must return one of these values:
    - a dict to jsonify
    - nothing for an empty 204 response
    - a tuple containing a status code and a dict to jsonify
    """

    @wraps(f)
    def wrapper(*args, **kwargs):
        ret = f(*args, **kwargs)
        if ret is None:
            response = '', 204
        elif isinstance(ret, current_app.response_class):
            response = ret
        elif isinstance(ret, tuple):
            # code, result_dict|msg_string
            if isinstance(ret[1], str):
                response = jsonify(msg=ret[1])
            else:
                response = jsonify(**ret[1])
            response.status_code = ret[0]
        else:
            response = jsonify(**ret)
        return response

    return wrapper

def get_version():
    try:
        return 'v' + pkg_resources.get_distribution('maildump').version
    except pkg_resources.DistributionNotFound:
        return 'dev'


text:
#pragma once
#include <aws/opensearch/OpenSearchService_EXPORTS.h>
#include <aws/opensearch/model/DomainInformationContainer.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/opensearch/model/OutboundConnectionStatus.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace OpenSearchService
{
namespace Model
{
  /**
   *
The result of a CreateOutboundConnection request. Contains
   * details about the newly created cross-cluster connection.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_OPENSEARCHSERVICE_API CreateOutboundConnectionResult
  {
  public:
    CreateOutboundConnectionResult();
    CreateOutboundConnectionResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    CreateOutboundConnectionResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
Information about the source (local) domain.

     */
    inline const DomainInformationContainer& GetLocalDomainInfo() const{ return m_localDomainInfo; }

    /**
     *
Information about the source (local) domain.

     */
    inline void SetLocalDomainInfo(const DomainInformationContainer& value) { m_localDomainInfo = value; }

    /**
     *
Information about the source (local) domain.

     */
    inline void SetLocalDomainInfo(DomainInformationContainer&& value) { m_localDomainInfo = std::move(value); }

    /**
     *
Information about the source (local) domain.

     */
    inline CreateOutboundConnectionResult& WithLocalDomainInfo(const DomainInformationContainer& value) { SetLocalDomainInfo(value); return *this;}

    /**
     *
Information about the source (local) domain.

     */
    inline CreateOutboundConnectionResult& WithLocalDomainInfo(DomainInformationContainer&& value) { SetLocalDomainInfo(std::move(value)); return *this;}

    /**
     *
Information about the destination (remote) domain.

     */
    inline const DomainInformationContainer& GetRemoteDomainInfo() const{ return m_remoteDomainInfo; }

    /**
     *
Information about the destination (remote) domain.

     */
    inline void SetRemoteDomainInfo(const DomainInformationContainer& value) { m_remoteDomainInfo = value; }

    /**
     *
Information about the destination (remote) domain.

     */
    inline void SetRemoteDomainInfo(DomainInformationContainer&& value) { m_remoteDomainInfo = std::move(value); }

    /**
     *
Information about the destination (remote) domain.

     */
    inline CreateOutboundConnectionResult& WithRemoteDomainInfo(const DomainInformationContainer& value) { SetRemoteDomainInfo(value); return *this;}

    /**
     *
Information about the destination (remote) domain.

     */
    inline CreateOutboundConnectionResult& WithRemoteDomainInfo(DomainInformationContainer&& value) { SetRemoteDomainInfo(std::move(value)); return *this;}

    /**
     *
Name of the connection.

     */
    inline const Aws::String& GetConnectionAlias() const{ return m_connectionAlias; }

    /**
     *
Name of the connection.

     */
    inline void SetConnectionAlias(const Aws::String& value) { m_connectionAlias = value; }

    /**
     *
Name of the connection.

     */
    inline void SetConnectionAlias(Aws::String&& value) { m_connectionAlias = std::move(value); }

    /**
     *
Name of the connection.

     */
    inline void SetConnectionAlias(const char* value) { m_connectionAlias.assign(value); }

    /**
     *
Name of the connection.

     */
    inline CreateOutboundConnectionResult& WithConnectionAlias(const Aws::String& value) { SetConnectionAlias(value); return *this;}

    /**
     *
Name of the connection.

     */
    inline CreateOutboundConnectionResult& WithConnectionAlias(Aws::String&& value) { SetConnectionAlias(std::move(value)); return *this;}

    /**
     *
Name of the connection.

     */
    inline CreateOutboundConnectionResult& WithConnectionAlias(const char* value) { SetConnectionAlias(value); return *this;}

    /**
     *
The status of the connection.

     */
    inline const OutboundConnectionStatus& GetConnectionStatus() const{ return m_connectionStatus; }

    /**
     *
The status of the connection.

     */
    inline void SetConnectionStatus(const OutboundConnectionStatus& value) { m_connectionStatus = value; }

    /**
     *
The status of the connection.

     */
    inline void SetConnectionStatus(OutboundConnectionStatus&& value) { m_connectionStatus = std::move(value); }

    /**
     *
The status of the connection.

     */
    inline CreateOutboundConnectionResult& WithConnectionStatus(const OutboundConnectionStatus& value) { SetConnectionStatus(value); return *this;}

    /**
     *
The status of the connection.

     */
    inline CreateOutboundConnectionResult& WithConnectionStatus(OutboundConnectionStatus&& value) { SetConnectionStatus(std::move(value)); return *this;}

    /**
     *
The unique identifier for the created outbound connection, which is used for
     * subsequent operations on the connection.

     */
    inline const Aws::String& GetConnectionId() const{ return m_connectionId; }

    /**
     *
The unique identifier for the created outbound connection, which is used for
     * subsequent operations on the connection.

     */
    inline void SetConnectionId(const Aws::String& value) { m_connectionId = value; }

    /**
     *
The unique identifier for the created outbound connection, which is used for
     * subsequent operations on the connection.

     */
    inline void SetConnectionId(Aws::String&& value) { m_connectionId = std::move(value); }

    /**
     *
The unique identifier for the created outbound connection, which is used for
     * subsequent operations on the connection.

     */
    inline void SetConnectionId(const char* value) { m_connectionId.assign(value); }

    /**
     *
The unique identifier for the created outbound connection, which is used for
     * subsequent operations on the connection.

     */
    inline CreateOutboundConnectionResult& WithConnectionId(const Aws::String& value) { SetConnectionId(value); return *this;}

    /**
     *
The unique identifier for the created outbound connection, which is used for
     * subsequent operations on the connection.

     */
    inline CreateOutboundConnectionResult& WithConnectionId(Aws::String&& value) { SetConnectionId(std::move(value)); return *this;}

    /**
     *
The unique identifier for the created outbound connection, which is used for
     * subsequent operations on the connection.

     */
    inline CreateOutboundConnectionResult& WithConnectionId(const char* value) { SetConnectionId(value); return *this;}

  private:

    DomainInformationContainer m_localDomainInfo;

    DomainInformationContainer m_remoteDomainInfo;

    Aws::String m_connectionAlias;

    OutboundConnectionStatus m_connectionStatus;

    Aws::String m_connectionId;
  };

} // namespace Model
} // namespace OpenSearchService
} // namespace Aws


text:
Korzystanie z panelu debugowania klienta HTTP
=============================================

Klient HTTP Yii 2 dostarcza panel debugowania, który można zintegrować z modułem debugowania Yii. Panel pokazuje wykonane
żądania HTTP.

Dodaj następujący kod do konfiguracji swojej aplikacji, aby włączyć panel (jeśli masz już włączony moduł debugowania,
wystarczy dodać konfigurację 'panels'):

```php
    // ...
    'bootstrap' => ['debug'],
    'modules' => [
        'debug' => [
            'class' => 'yii\\debug\\Module',
            'panels' => [
                'httpclient' => [
                    'class' => 'yii\\httpclient\\debug\\HttpClientPanel',
                ],
            ],
        ],
    ],
    // ...
```

Panel pozwala na wysłanie zalogowanego żądania HTTP i sprawdzenie jego odpowiedzi. Można otrzymać odpowiedź w postaci
tekstu lub przekazać ją bezpośrednio do przeglądarki.

> Note: tylko standardowe zalogowane żądania HTTP mogą być wysłane przez panel debugowania - nie jest to możliwe dla
  serii żądań. Należy także pamiętać, że treść zalogowanych żądań może być obcięta zgodnie z wartością
  [[\yii\httpclient\Client::$contentLoggingMaxSize]], zatem wysłanie takich żądań może zakończyć się błędem lub skutkować
  niespodziewanymi rezultatami.


text:
<?php

/* FrameworkBundle::layout.html.twig */
class __TwigTemplate_1e706c08860da468a9ca97c76e895560 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'body' => array($this, 'block_body'),
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $context = array_merge($this->env->getGlobals(), $context);

        // line 1
        echo "<!DOCTYPE html>

        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=";
        // line 4
        echo twig_escape_filter($this->env, $this->env->getCharset(), "html");
        echo "\"/>
        <title>";
        // line 5
        $this->displayBlock('title', $context, $blocks);
        echo "</title>
        <link href=\"";
        // line 6
        echo twig_escape_filter($this->env, $this->env->getExtension('templating')->getAssetUrl("bundles/framework/css/exception_layout.css"), "html");
        echo "\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />
        <link href=\"";
        // line 7
        echo twig_escape_filter($this->env, $this->env->getExtension('templating')->getAssetUrl("bundles/framework/css/exception.css"), "html");
        echo "\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />

                    env, $this->env->getExtension('templating')->getAssetUrl("bundles/framework/images/logo_symfony.gif"), "html");
        echo "\" alt=\"Symfony\" />

                  <form method=\"get\" action=\"http://symfony.com/search\">

                          env, $this->env->getExtension('templating')->getAssetUrl("bundles/framework/images/grey_magnifier.png"), "html");
        echo "\" alt=\"Search on Symfony website\" />

                      <input name=\"q\" id=\"search_id\" type=\"search\" placeholder=\"Search on Symfony website\" />

                      <button type=\"submit\">

                            OK

                      </button>

                   </form>

            ";
        // line 38
        $this->displayBlock('body', $context, $blocks);
        // line 39
        echo "

";
    }

    // line 5
    public function block_title($context, array $blocks = array())
    {
        echo "";
    }

    // line 38
    public function block_body($context, array $blocks = array())
    {
        echo "";
    }

    public function getTemplateName()
    {
        return "FrameworkBundle::layout.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }
}


text:
package org.cloudbyexample.dc.service.si.application;

import org.cloudbyexample.dc.schema.beans.application.Application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;

/**
 * The endpoint for the application flow.
 *
 * @author David Winterfeldt
 */
public class MockApplicationFlowEndpoint {

    final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Process an application.
     */
	public void processMessage(Message<Application> message) {
	    Application application =  message.getPayload();

        logger.debug("Processed application '{}' {}.  imageTemplateSize={}",
                new Object[] { application.getName(),
                               application.getVersion(),
                               application.getImageTemplates().size()});
	}

}


text:
package com.amazonaws.services.pinpointsmsvoicev2.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SetDefaultMessageTypeRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The configuration set to update with a new default message type. This field can be the ConsigurationSetName or
     * ConfigurationSetArn.
     *

     */
    private String configurationSetName;
    /**
     *

     * The type of message. Valid values are TRANSACTIONAL for messages that are critical or time-sensitive and
     * PROMOTIONAL for messages that aren't critical or time-sensitive.
     *

     */
    private String messageType;

    /**
     *

     * The configuration set to update with a new default message type. This field can be the ConsigurationSetName or
     * ConfigurationSetArn.
     *

     *
     * @param configurationSetName
     *        The configuration set to update with a new default message type. This field can be the
     *        ConsigurationSetName or ConfigurationSetArn.
     */

    public void setConfigurationSetName(String configurationSetName) {
        this.configurationSetName = configurationSetName;
    }

    /**
     *

     * The configuration set to update with a new default message type. This field can be the ConsigurationSetName or
     * ConfigurationSetArn.
     *

     *
     * @return The configuration set to update with a new default message type. This field can be the
     *         ConsigurationSetName or ConfigurationSetArn.
     */

    public String getConfigurationSetName() {
        return this.configurationSetName;
    }

    /**
     *

     * The configuration set to update with a new default message type. This field can be the ConsigurationSetName or
     * ConfigurationSetArn.
     *

     *
     * @param configurationSetName
     *        The configuration set to update with a new default message type. This field can be the
     *        ConsigurationSetName or ConfigurationSetArn.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SetDefaultMessageTypeRequest withConfigurationSetName(String configurationSetName) {
        setConfigurationSetName(configurationSetName);
        return this;
    }

    /**
     *

     * The type of message. Valid values are TRANSACTIONAL for messages that are critical or time-sensitive and
     * PROMOTIONAL for messages that aren't critical or time-sensitive.
     *

     *
     * @param messageType
     *        The type of message. Valid values are TRANSACTIONAL for messages that are critical or time-sensitive and
     *        PROMOTIONAL for messages that aren't critical or time-sensitive.
     * @see MessageType
     */

    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }

    /**
     *

     * The type of message. Valid values are TRANSACTIONAL for messages that are critical or time-sensitive and
     * PROMOTIONAL for messages that aren't critical or time-sensitive.
     *

     *
     * @return The type of message. Valid values are TRANSACTIONAL for messages that are critical or time-sensitive and
     *         PROMOTIONAL for messages that aren't critical or time-sensitive.
     * @see MessageType
     */

    public String getMessageType() {
        return this.messageType;
    }

    /**
     *

     * The type of message. Valid values are TRANSACTIONAL for messages that are critical or time-sensitive and
     * PROMOTIONAL for messages that aren't critical or time-sensitive.
     *

     *
     * @param messageType
     *        The type of message. Valid values are TRANSACTIONAL for messages that are critical or time-sensitive and
     *        PROMOTIONAL for messages that aren't critical or time-sensitive.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see MessageType
     */

    public SetDefaultMessageTypeRequest withMessageType(String messageType) {
        setMessageType(messageType);
        return this;
    }

    /**
     *

     * The type of message. Valid values are TRANSACTIONAL for messages that are critical or time-sensitive and
     * PROMOTIONAL for messages that aren't critical or time-sensitive.
     *

     *
     * @param messageType
     *        The type of message. Valid values are TRANSACTIONAL for messages that are critical or time-sensitive and
     *        PROMOTIONAL for messages that aren't critical or time-sensitive.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see MessageType
     */

    public SetDefaultMessageTypeRequest withMessageType(MessageType messageType) {
        this.messageType = messageType.toString();
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getConfigurationSetName() != null)
            sb.append("ConfigurationSetName: ").append(getConfigurationSetName()).append(",");
        if (getMessageType() != null)
            sb.append("MessageType: ").append(getMessageType());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof SetDefaultMessageTypeRequest == false)
            return false;
        SetDefaultMessageTypeRequest other = (SetDefaultMessageTypeRequest) obj;
        if (other.getConfigurationSetName() == null ^ this.getConfigurationSetName() == null)
            return false;
        if (other.getConfigurationSetName() != null && other.getConfigurationSetName().equals(this.getConfigurationSetName()) == false)
            return false;
        if (other.getMessageType() == null ^ this.getMessageType() == null)
            return false;
        if (other.getMessageType() != null && other.getMessageType().equals(this.getMessageType()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getConfigurationSetName() == null) ? 0 : getConfigurationSetName().hashCode());
        hashCode = prime * hashCode + ((getMessageType() == null) ? 0 : getMessageType().hashCode());
        return hashCode;
    }

    @Override
    public SetDefaultMessageTypeRequest clone() {
        return (SetDefaultMessageTypeRequest) super.clone();
    }

}


text:
package searcher

import (
	"github.com/blevesearch/bleve/index"
	"github.com/blevesearch/bleve/search"
)

func NewMultiTermSearcher(indexReader index.IndexReader, terms []string,
	field string, boost float64, options search.SearcherOptions, limit bool) (
	search.Searcher, error) {
	qsearchers := make([]search.Searcher, len(terms))
	qsearchersClose := func() {
		for _, searcher := range qsearchers {
			if searcher != nil {
				_ = searcher.Close()
			}
		}
	}
	for i, term := range terms {
		var err error
		qsearchers[i], err = NewTermSearcher(indexReader, term, field, boost, options)
		if err != nil {
			qsearchersClose()
			return nil, err
		}
	}
	// build disjunction searcher of these ranges
	return newMultiTermSearcherBytes(indexReader, qsearchers, field, boost,
		options, limit)
}

func NewMultiTermSearcherBytes(indexReader index.IndexReader, terms [][]byte,
	field string, boost float64, options search.SearcherOptions, limit bool) (
	search.Searcher, error) {
	qsearchers := make([]search.Searcher, len(terms))
	qsearchersClose := func() {
		for _, searcher := range qsearchers {
			if searcher != nil {
				_ = searcher.Close()
			}
		}
	}
	for i, term := range terms {
		var err error
		qsearchers[i], err = NewTermSearcherBytes(indexReader, term, field, boost, options)
		if err != nil {
			qsearchersClose()
			return nil, err
		}
	}
	return newMultiTermSearcherBytes(indexReader, qsearchers, field, boost,
		options, limit)
}

func newMultiTermSearcherBytes(indexReader index.IndexReader,
	searchers []search.Searcher, field string, boost float64,
	options search.SearcherOptions, limit bool) (
	search.Searcher, error) {

	// build disjunction searcher of these ranges
	searcher, err := newDisjunctionSearcher(indexReader, searchers, 0, options,
		limit)
	if err != nil {
		for _, s := range searchers {
			_ = s.Close()
		}
		return nil, err
	}

	return searcher, nil
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2014 Magnet Systems, Inc.
  ~ All rights reserved.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License"); you
  ~ may not use this file except in compliance with the License. You
  ~ may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  ~ implied. See the License for the specific language governing
  ~ permissions and limitations under the License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <artifactId>magnet-tools</artifactId>
    <groupId>com.magnet.tools</groupId>
    <version>1.1.0</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <artifactId>magnet-tools-templates</artifactId>
  <packaging>jar</packaging>
  <name>Magnet Tools Templates</name>

  <dependencies>
    <dependency>
      <groupId>com.magnet.tools</groupId>
      <artifactId>magnet-tools-utils</artifactId>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>com.magnet.tools</groupId>
      <artifactId>magnet-tools-utils</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
      <type>test-jar</type>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.ant</groupId>
      <artifactId>ant</artifactId>
    </dependency>

  </dependencies>

</project>


text:
package digger

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
)

type Parent struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
}

type Project struct {
	Parents     Parent `json:"parent"`
	Is_public   bool   `json:"is_public"`
	Created_on  string `json:""`
	Updates_on  string `json:""`
	Id          int    `json:"id"`
	Name        string `json:"name"`
	Identifier  string `json:"identifier"`
	Description string `json:"description"`
	Status      int    `json:"status"`
}

type projectInfo struct {
	ProjectInfo Project `json:"project"`
}
type Projects struct {
	Projects []Project `json:"projects"`
}

// Get list of all Projects
func (cl *client) GetProjectList() (*Projects, error) {
	req, err := http.NewRequest("GET", cl.path+"/projects.json", nil)
	if err != nil {
		return nil, err
	}

	req.SetBasicAuth(cl.key, "")

	resp, err := cl.Do(req)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != 200 {
		return nil, errors.New("Redmine connection error: " + resp.Status + ".")
	}

	respBody, _ := ioutil.ReadAll(resp.Body)

	var prj Projects
	err = json.Unmarshal(respBody, &prj)
	if err != nil {
		return nil, err
	}

	return &prj, nil
}

// Get Prhect by ID
func (cl *client) GetProject(id int) (*Project, error) {
	req, err := http.NewRequest("GET", cl.path+"/projects/"+strconv.Itoa(id)+".json", nil)
	if err != nil {
		return nil, err
	}

	req.SetBasicAuth(cl.key, "")

	resp, err := cl.Do(req)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != 200 {
		return nil, errors.New("Redmine connection error: " + resp.Status + ".")
	}

	respBody, _ := ioutil.ReadAll(resp.Body)

	var prj projectInfo
	err = json.Unmarshal(respBody, &prj)
	if err != nil {
		fmt.Println(err.Error())
		return nil, err
	}

	return &prj.ProjectInfo, nil
}

// Creating a project
func (cl *client) CreateProject(prj Project) error {
	var newpr projectInfo
	newpr.ProjectInfo = prj
	body, err := json.Marshal(newpr)
	if err != nil {
		return err
	}

	req, err := http.NewRequest("POST", cl.path+"/projects.json", strings.NewReader(string(body)))
	if err != nil {
		return err
	}

	req.SetBasicAuth(cl.key, "")
	req.Header.Set("Content-Type", "application/json")

	resp, err := cl.Do(req)
	if err != nil {
		return err
	}

	if resp.StatusCode != 201 && resp.StatusCode != 422 {
		return errors.New("Redmine project create error: " + resp.Status + ".")
	} else if resp.StatusCode == 422 {
		return errors.New("Validation failures: " + resp.Status + ".")
	}

	return nil
}

// Updating a project
func (cl *client) UpdateProject(id int, prj Project) error {
	var newpr projectInfo
	newpr.ProjectInfo = prj
	body, err := json.Marshal(newpr)
	if err != nil {
		return err
	}

	req, err := http.NewRequest("PUT", cl.path+"/projects/"+strconv.Itoa(id)+".json", strings.NewReader(string(body)))
	if err != nil {
		return err
	}

	req.SetBasicAuth(cl.key, "")
	req.Header.Set("Content-Type", "application/json")

	resp, err := cl.Do(req)
	if err != nil {
		return err
	}

	if resp.StatusCode != 200 {
		return errors.New("Redmine project update error: " + resp.Status + ".")
	}

	return nil
}

// Deleting a project
func (cl *client) DeleteProject(id int) error {
	req, err := http.NewRequest("DELETE", cl.path+"/projects/"+strconv.Itoa(id)+".json", strings.NewReader(""))
	if err != nil {
		return err
	}

	req.SetBasicAuth(cl.key, "")
	req.Header.Set("Content-Type", "application/json")

	resp, err := cl.Do(req)
	if err != nil {
		return err
	}

	if resp.StatusCode != 200 {
		return errors.New("Redmine project update error: " + resp.Status + ".")
	}

	return nil
}


text:
FILE_NAME=showcase-webpack
OUTPUT_DIR=../resources
MAP_DIR=../public

echo "*** Starting Webpack Build ***";
OUTPUT=${OUTPUT_DIR}/${FILE_NAME}
MAP_OUTPUT=${MAP_DIR}/${FILE_NAME}

# remove files
rm -f ${OUTPUT}.js;
rm -f ${MAP_OUTPUT}.js.map;

# run webpack
webpack --config webpack.config.js --progress

# copy files
echo "Copying Output...";
mkdir -p ${OUTPUT_DIR}
mkdir -p ${MAP_DIR}
cp build/${FILE_NAME}.js ${OUTPUT}.js;
cp build/${FILE_NAME}.js.map ${MAP_OUTPUT}.js.map;

# cleanup
rm -rf build;

echo "*** Webpack Build Complete ***";


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

    <groupId>com.orange.cloud.ldap.proxy</groupId>
    <artifactId>spring-ldap-proxy</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <name>spring-ldap-proxy</name>
    <description>ldap proxyfying in spring boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <docker.image.prefix>arthurhlt</docker.image.prefix>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>
        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.15</version>
        </dependency>
        <dependency>
            <groupId>org.forgerock.opendj</groupId>
            <artifactId>opendj-core</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.forgerock.opendj</groupId>
            <artifactId>opendj-grizzly</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
        <repository>
            <id>jcenter</id>
            <name>JCenter-Bintray</name>
            <url>http://jcenter.bintray.com</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>http://repo.spring.io/libs-snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>forgerock-staging-repository</id>
            <name>ForgeRock Release Repository</name>
            <url>http://maven.forgerock.org/repo/releases</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>forgerock-snapshots-repository</id>
            <name>ForgeRock Snapshot Repository</name>
            <url>http://maven.forgerock.org/repo/snapshots</url>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <dependencies>
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                        <version>1.2.4.RELEASE</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>0.2.3</version>
                <configuration>
                    <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
                    <dockerDirectory>src/main/docker</dockerDirectory>
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
/**
 * Helper function for updating a single entry in an array.
 */
export function immutableArrayUpdate<T>(array: T[], index: number, value: T) {
  const clone = [...array];
  if (value === clone[index]) {
    throw new Error(
        'Tried to update array with the same object - do not update in place!');
  }
  clone[index] = value;
  return clone;
}

/**
 * Helper function to update a map entry in an array.
 */
export function immutableMapUpdate<K, V>(map: Map<K, V>, key: K, value: V) {
  const clone = new Map(map);
  clone.set(key, value);
  return clone;
}

/**
 * Throws if the given number is not finite. Returns the value otherwise. You
 * should only use this to catch programmer errors, so do NOT use this to
 * validate user input. Just use isFinite directly in those cases.
 */
export function checkFinite(value: number) {
  if (!isFinite(value)) {
    throw new Error('Number was not finite');
  }
  return value;
}

/** Convert degrees to radians */
export function degToRad(degrees: number): number {
  return degrees * Math.PI / 180.0;
}

/** Convert radians to degrees */
export function radToDeg(radians: number): number {
  return radians * 180.0 / Math.PI;
}

/** Clamps 'value' to be within [lowerLimit, upperLimit] */
export function clamp(value: number, lowerLimit: number, upperLimit: number) {
  return Math.min(Math.max(value, lowerLimit), upperLimit);
}

/** Round to the given number of significant figures (digits) */
export function roundToDigits(value: number, digits: number): number {
  if (value === 0) {
    return 0;
  }
  const x =
      10 ** (Math.floor(digits) - Math.floor(Math.log10(Math.abs(value))) - 1);
  return Math.round(value * x) / x;
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='UserRating',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('timestamp', models.DateTimeField(auto_now_add=True)),
                ('rating', models.PositiveIntegerField(choices=[(5, 'very satisfied'), (4, 'satisfied'), (3, 'neither satisfied nor dissatisfied'), (2, 'dissatisfied'), (1, 'very dissatisfied')])),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='UserRatingAggregate',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('start_date', models.DateTimeField()),
                ('feedback_count', models.PositiveIntegerField()),
                ('feedback_total', models.PositiveIntegerField()),
                ('feedback_avg', models.DecimalField(max_digits=5, decimal_places=2)),
            ],
            options={
                'ordering': ('start_date',),
            },
            bases=(models.Model,),
        ),
    ]


text:
<!---
title: PHPDoc Addon
-->

# PHPDoc Addon
One of Codex it's defining features is PHPDoc integration.
The `codex/addon-phpdoc` adds **links**, **macros** and even a complete API browser.
It comes down to be able to do this kind of stuff in your documentation (using popovers, hover the class names).

#### Links
Create links using `[text](#codex:phpdoc['MyNamespace\\MyClass'])`. This will link to the API Documentation.

You can use modifiers for various extra behaviours like `[text](#codex:phpdoc['MyNamespace\\MyClass']:popover:blank)`.

| Example | Name | Code |
|:--------|:-----|:-----|
| [`Codex`](../index.md#codex:phpdoc['Codex\\Codex']:popover) | Class popover | `#codex:phpdoc['Codex\\Codex']:popover` |
| [`get`](../index.md#codex:phpdoc['Codex\\Codex::get']:popover:signature) | Method signature popover | `#codex:phpdoc['Codex\\Codex::get']:popover:signature` |
| [`get`](../index.md#codex:phpdoc['Codex\\Codex::get']:popover) | Method popover | `#codex:phpdoc['Codex\\Codex::get']:popover` |
| [`Codex`](../index.md#codex:phpdoc['Codex\\Codex']:modal) | Class modal | `#codex:phpdoc['Codex\\Codex']:modal` |
| [`Codex`](../index.md#codex:phpdoc['Codex\\Codex']:modal:method-list) | Class method list modal | `#codex:phpdoc['Codex\\Codex']:modal:method-list` |
| [`Codex`](../index.md#codex:phpdoc['Codex\\Codex']:modal:property-list) | Class property list modal | `#codex:phpdoc['Codex\\Codex']:modal:property-list` |
| [`Codex`](../index.md#codex:phpdoc['Codex\\Codex']:modal:source) | Class source modal | `#codex:phpdoc['Codex\\Codex']:modal:source` |
| [`Codex`](../index.md#codex:phpdoc['Codex\\Codex']:modal:modal-full:app) | Class source modal | `#codex:phpdoc['Codex\\Codex']:modal:app` |
| [`get`](../index.md#codex:phpdoc['Codex\\Codex::get']:modal:signature) | Method signature modal | `#codex:phpdoc['Codex\\Codex::get']:modal:signature` |
| [`get`](../index.md#codex:phpdoc['Codex\\Codex::get']:modal) | Method modal | `#codex:phpdoc['Codex\\Codex::get']:modal` |

#### Macros
```markdown
<!--*codex:phpdoc:method:signature('Codex\\Codex::url()')*-->
```
<!--*codex:phpdoc:method:signature('Codex\\Codex::url()')*-->

```markdown
<!--*codex:phpdoc:method('Codex\\Codex::get()')*-->
```
<!--*codex:phpdoc:method('Codex\\Codex::get()')*-->

#### Macros
```markdown
<!--*codex:phpdoc:method:signature('Codex\\Codex::url()')*-->
```
<!--*codex:phpdoc:method:signature('Codex\\Codex::url()')*-->

```markdown
<!--*codex:phpdoc:method('Codex\\Codex::get()')*-->
```
<!--*codex:phpdoc:method('Codex\\Codex::get()')*-->

```markdown
<!--*codex:phpdoc:list:method('Codex\\Codex')*-->
```
<!--*codex:phpdoc:list:method('Codex\\Codex')*-->

```markdown
<!--*codex:phpdoc:list:property('Codex\\Codex')*-->
```
<!--*codex:phpdoc:list:property('Codex\\Codex')*-->

```markdown
<!--*codex:phpdoc:entity('Codex\\Codex', 'with-properties')*-->
```
<!--*codex:phpdoc:entity('Codex\\Codex', 'with-properties')*-->


text:
package com.google.gerrit.server.account;

import com.google.gerrit.extensions.restapi.ResourceConflictException;
import com.google.gerrit.extensions.restapi.Response;
import com.google.gerrit.extensions.restapi.RestModifyView;
import com.google.gerrit.server.account.CreateEmail.Input;

public class PutEmail implements RestModifyView<AccountResource.Email, Input> {
  @Override
  public Response<?> apply(AccountResource.Email rsrc, Input input)
      throws ResourceConflictException {
    throw new ResourceConflictException("email exists");
  }
}


text:
using System;
using System.Collections.Generic;
using PublicHolidays.Au.Internal.Extensions;
using PublicHolidays.Au.Internal.Support;

namespace PublicHolidays.Au.Internal.PublicHolidays
{
    public sealed class ChristmasDay : IPublicHoliday, IIn
    {
        public State States => State.National;
        public Trait Traits => Trait.AllPostcodes;

        public string GetNameOfPublicHolidayIn(State state)
        {
            return nameof(ChristmasDay).ToSentence();
        }

        public IIn GetPublicHolidayDatesFor(State state)
        {
            return this;
        }

        public IEnumerable<DateTime> In(int year)
        {
            return
                new DateTime(year, 12, 25)
                    .Shift(
                        saturday => saturday.AddDays(2),
                        sunday => sunday.AddDays(1));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;

namespace CodeHub.Converters
{
    class InverseBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            return !(bool)value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            return !(bool)value;
        }
    }
}


text:
layout: default
---
{% include ganalytics.html %}
{{ content }}


text:
function write_serial_event(filename, event)

% WRITE_SERIAL_EVENT
%
% changed A.Hadjipapas 2010
%
% write to phyiscal serial port
% serial port on windows or linux platform

% Copyright (C) 2007, Christian Hesse
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: write_serial_event.m 7123 2012-12-06 21:21:38Z roboos $

[port, opt] = filetype_check_uri(filename);
temp=instrfind; %% find isntruments including serial ports

%% check if a serial port with the specified name is already available
if isempty(temp)||~any(strcmpi(temp.Port,port))
  %% if not make one
  s=serial(port);
  %% if user has specified Baudrate, apply that, %%  FIX THIS: currently no
  %% automatic implementation for more options
  if ~isempty(opt)
    s.Baudrate =str2double(opt{2}); %% set Baudrate using optional parameters
  end
  fopen(s); %% open serial port
end

%% write the contents of the field event.value to the serial port as a string
if isfield(event,'value') && ~isempty(event.value)
  msg = event.value;
else
  msg = [];
end

%% write the message to the serial port if it is open
if strcmp(s.Status,'open')
  %% if numeric use fwrite otherwise fprintf
  if isnumeric(msg)
    fwrite(s,msg);
  end

  if ischar(msg)
    fprintf(s,'%s',msg);
  end
else
  error('could not write event to serial port');
end

%% this is the old code
%
%     % serial port on windows or linux platform
%     s = [];
%     [port, opt] = filetype_check_uri(filename);
%
%     % determine whether any serial port objects are already associated with the target serial port
%     temp = instrfind;
%     if isa(temp,'instrument')
%       % find all serial ports
%       i1 = strcmp('serial',{temp(:).Type});
%       if any(i1)
%         % find all serial ports whose name matches that of the specified port
%         i2 = strmatch(lower(['Serial-',port]),lower({temp(find(i1)==1).Name}));
%         % set s to the (first) matching port if present (and open if necessary)
%         if ~isempty(i2)
%           s = temp(i2(1));
%           if ~strcmp(s.Status,'open'), fopen(s); end;
%         end
%       end
%     end
%
%     % create, configure a serial port object if necessary and open the port
%     if ~isa(s,'serial')
%       s = serial(port);
%       if ~isempty(opt) && iscell(opt), s = set(s,opt); end;
%       fopen(s);
%     end
%
%     %     % convert the event structure into an appropriate message
%     %     if isfield(event,'type') && strcmp(event.type,'ctrlchar')
%     %       % use only a single control character
%     %       msg = char(event.value(1));
%     %     else
%     %       % convert the entire event structure into a message
%     %       msg = struct2msg(event);
%     %     end
%
%     % write the message to the serial port
%     if isa(s,'serial') && strcmp(s.Status,'open')
%       fwrite(s,char(event.value));
%     else
%       error('could not write event to serial port');
%     end


text:
This project uses
[Hugo](https://gohugo.io) and the
['Code-Editor'](http://themes.gohugo.io/hugo-code-editor-theme/) theme,
I'm happy to publish any guest posts or collaborate on improving the notes
in their current form. A good way to start is by opening an Issue or submitting
a work-in-progress PR. Cheers! :beers:


text:
<!doctype html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>AcaSpot {% block title %}{% endblock %}</title>

	<link rel="shortcut icon" href="../static/img/favicon.ico" type="image/x-icon" />

	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
	<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">
    <link rel="stylesheet" href="../static/css/main.css">
	{% block head %}{% endblock %}

            <button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle">
                Toggle navigation

            </button>
            AcaSpot

Auditions

Groups

Contact

                {% if current_user.is_authenticated %}
                    Profile

                    Logout
                {% else %}
                    Login

                    Register
                {% endif %}

    {% with messages = get_flashed_messages() %}
      {% if messages %}

        {% for message in messages %}

{{ message }}

        {% endfor %}

      {% endif %}
    {% endwith %}

	{% block body %}{% endblock %}

    {% block spells %}{% endblock %}


text:
[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Cloud%20API%20Server%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Cloud%20API%20Server%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore Documentation](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Explore Source Code Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://app.pdf.co/signup?utm_source=github-readme)
[Security](https://pdf.co/security)
[Explore Web API Documentation](https://apidocs.pdf.co?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### **ConvertDocToPdfFromUrl.cmd:**

```
# Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost".
# If it's not then please replace this with with your hosting url.

@echo off

:: Path of the cURL executable
set CURL="curl.exe"

:: Direct URL of source DOC or DOCX file.
set SOURCE_FILE_URL=https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/doc-to-pdf/sample.docx
:: Result PDF file name
set RESULT_FILE_NAME=result.pdf

:: Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost".
:: If it's not then please replace this with with your hosting url.

:: Prepare URL for `DOC To PDF` API call
set QUERY="https://localhost/pdf/convert/from/doc?name=%RESULT_FILE_NAME%&url=%SOURCE_FILE_URL%"

:: Perform request and save response to a file
%CURL% -# -X GET %QUERY% >response.json

:: Display the response
type response.json

:: Use any convenient way to parse JSON response and get URL of generated file(s)

echo.
pause
```

<!-- code block end -->


text:
package net.jawr.web.resource.bundle.factory.global.postprocessor;

import net.jawr.web.JawrConstant;
import net.jawr.web.resource.bundle.global.postprocessor.google.closure.ClosureGlobalPostProcessor;
import net.jawr.web.resource.bundle.global.processor.AbstractChainedGlobalProcessor;
import net.jawr.web.resource.bundle.global.processor.AbstractGlobalProcessorChainFactory;

/**
 * This class defines the global preprocessor factory.
 *
 * @author Ibrahim Chaehoi
 *
 */
public class BasicGlobalPostprocessorChainFactory extends
		AbstractGlobalProcessorChainFactory<GlobalPostProcessingContext> implements GlobalPostprocessorChainFactory {

	/**
	 * Build the global preprocessor from the ID given in parameter
	 *
	 * @param key
	 *            the ID of the preprocessor
	 * @return a global preprocessor
	 */
	@Override
	protected AbstractChainedGlobalProcessor<GlobalPostProcessingContext> buildProcessorByKey(String key) {

		AbstractChainedGlobalProcessor<GlobalPostProcessingContext> processor = null;

		if (key.equals(JawrConstant.GLOBAL_GOOGLE_CLOSURE_POSTPROCESSOR_ID)) {
			processor = new ClosureGlobalPostProcessor();
		}

		return processor;
	}

}


text:
package org.apache.karaf.main;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import java.util.StringTokenizer;

import org.apache.karaf.main.util.SubstHelper;
import org.apache.karaf.main.util.Utils;

public class PropertiesLoader {

    private static final String INCLUDES_PROPERTY = "${includes}"; // mandatory includes

    private static final String OPTIONALS_PROPERTY = "${optionals}"; // optionals includes

    /**
     *

     * Loads the configuration properties in the configuration property file
     * associated with the framework installation; these properties
     * are accessible to the framework and to bundles and are intended
     * for configuration purposes. By default, the configuration property
     * file is located in the <tt>conf/</tt> directory of the Felix
     * installation directory and is called "<tt>config.properties</tt>".
     * The installation directory of Felix is assumed to be the parent
     * directory of the <tt>felix.jar</tt> file as found on the system class
     * path property. The precise file from which to load configuration
     * properties can be set by initializing the "<tt>felix.config.properties</tt>"
     * system property to an arbitrary URL.
     *

     *
     * @return A <tt>Properties</tt> instance or <tt>null</tt> if there was an error.
     * @throws Exception if something wrong occurs
     */
    static Properties loadConfigProperties(File file) throws Exception {
        // See if the property URL was specified as a property.
        URL configPropURL;
        try {
            configPropURL = file.toURI().toURL();
        }
        catch (MalformedURLException ex) {
            System.err.print("Main: " + ex);
            return null;
        }

        Properties configProps = loadPropertiesFile(configPropURL, false);
        copySystemProperties(configProps);

        // Perform variable substitution for system properties.
        for (Enumeration<?> e = configProps.propertyNames(); e.hasMoreElements();) {
            String name = (String) e.nextElement();
            configProps.setProperty(name,
                    SubstHelper.substVars(configProps.getProperty(name), name, null, configProps));
        }

        return configProps;
    }

    /**
     *

     * Loads the properties in the system property file associated with the
     * framework installation into <tt>System.setProperty()</tt>. These properties
     * are not directly used by the framework in anyway. By default, the system
     * property file is located in the <tt>conf/</tt> directory of the Felix
     * installation directory and is called "<tt>system.properties</tt>". The
     * installation directory of Felix is assumed to be the parent directory of
     * the <tt>felix.jar</tt> file as found on the system class path property.
     * The precise file from which to load system properties can be set by
     * initializing the "<tt>felix.system.properties</tt>" system property to an
     * arbitrary URL.
     *

     *
     * @param karafBase the karaf base folder
     * @throws IOException
     */
    static void loadSystemProperties(File file) throws IOException {
        Properties props = new Properties();
        try {
            InputStream is = new FileInputStream(file);
            props.load(is);
            is.close();
        } catch (Exception e1) {
            // Ignore
        }

        for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements();) {
            String name = (String) e.nextElement();
            String value = System.getProperty(name, props.getProperty(name));
            System.setProperty(name, SubstHelper.substVars(value, name, null, props));
        }
    }

    static void copySystemProperties(Properties configProps) {
        for (Enumeration<?> e = System.getProperties().propertyNames();
             e.hasMoreElements();) {
            String key = (String) e.nextElement();
            if (key.startsWith("felix.") ||
                    key.startsWith("karaf.") ||
                    key.startsWith("org.osgi.framework.")) {
                configProps.setProperty(key, System.getProperty(key));
            }
        }
    }

    static Properties loadPropertiesOrFail(File configFile) {
        try {
            URL configPropURL = configFile.toURI().toURL();
            return loadPropertiesFile(configPropURL, true);
        } catch (Exception e) {
            throw new RuntimeException("Error loading properties from " + configFile, e);
        }
    }

    private static Properties loadPropertiesFile(URL configPropURL, boolean failIfNotFound) throws Exception {
        Properties configProps = new Properties();
        InputStream is = null;
        try {
            is = configPropURL.openConnection().getInputStream();
            configProps.load(is);
            is.close();
        } catch (FileNotFoundException ex) {
            if (failIfNotFound) {
                throw ex;
            } else {
                System.err.println("WARN: " + configPropURL + " is not found, so not loaded");
            }
        } catch (Exception ex) {
            System.err.println("Error loading config properties from " + configPropURL);
            System.err.println("Main: " + ex);
            return configProps;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            }
            catch (IOException ex2) {
                // Nothing we can do.
            }
        }
        loadIncludes(INCLUDES_PROPERTY, true, configPropURL, configProps);
        loadIncludes(OPTIONALS_PROPERTY, false, configPropURL, configProps);
        trimValues(configProps);
        return configProps;
    }

    private static void loadIncludes(String propertyName, boolean mandatory, URL configPropURL, Properties configProps)
            throws MalformedURLException, Exception {
        String includes = (String) configProps.get(propertyName);
        if (includes != null) {
            StringTokenizer st = new StringTokenizer(includes, "\" ", true);
            if (st.countTokens() > 0) {
                String location;
                do {
                    location = Utils.nextLocation(st);
                    if (location != null) {
                        URL url = new URL(configPropURL, location);
                        Properties props = loadPropertiesFile(url, mandatory);
                        configProps.putAll(props);
                    }
                }
                while (location != null);
            }
        }
        configProps.remove(propertyName);
    }

    private static void trimValues(Properties configProps) {
        for (Enumeration<?> e = configProps.propertyNames(); e.hasMoreElements();) {
            Object key = e.nextElement();
            if (key instanceof String) {
                String v = configProps.getProperty((String) key);
                configProps.put(key, v.trim());
            }
        }
    }
}


text:
import angular from 'angular';
import 'angular-aria';
import 'angular-animate';
import 'angular-material';

angular.module('app', ['ngMaterial']);//.controller('splashController', SplashController);


text:
package com.example.plugintest.fragment;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.example.plugintest.R;
import com.limpoxe.fairy.core.PluginThemeHelper;

/**
 * 此fragment使用了特定的context,因此可以在在插件中的activity,或者宿主中的特定activity、
 * 或者宿主中的非特定activity中展示
 */

public class PluginSpecFragment extends Fragment implements OnClickListener {

	private ViewGroup mRoot;
	private Context pluginContext;
	private LayoutInflater pluginInflater;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getActivity().setTitle("测试插件中的特殊Fragment");

		// 默认是宿主程序Application主题
		try {
			pluginContext = getActivity().createPackageContext("com.example.plugintest", 0);
			// 设置主题为插件程序主题
			PluginThemeHelper.setTheme(pluginContext, R.style.PluginTheme);
			pluginInflater = (LayoutInflater) pluginContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View scrollview = pluginInflater.inflate(R.layout.plugin_layout, null);

		mRoot = (ViewGroup) scrollview.findViewById(R.id.content);

		initViews();

		return scrollview;
	}

	public void initViews() {

		Button btn1 = (Button) mRoot.findViewById(R.id.plugin_test_btn1);
		btn1.setOnClickListener(this);

		Button btn2 = (Button) mRoot.findViewById(R.id.plugin_test_btn2);
		btn2.setOnClickListener(this);

		Button btn3 = (Button) mRoot.findViewById(R.id.plugin_test_btn3);
		btn3.setOnClickListener(this);

		Button btn4 = (Button) mRoot.findViewById(R.id.plugin_test_btn4);
		btn4.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		Log.v("v.click MainFragment", "" + v.getId());
		if (v.getId() == R.id.plugin_test_btn1) {
			View view = pluginInflater.inflate(R.layout.plugin_layout, null, false);
			mRoot.addView(view);
			Toast.makeText(this.getActivity(), pluginContext.getString(R.string.hello_world1), Toast.LENGTH_LONG)
					.show();
		} else if (v.getId() == R.id.plugin_test_btn2) {
			View view = pluginInflater.inflate(com.example.pluginsharelib.R.layout.share_main, null, false);
			mRoot.addView(view);
			Toast.makeText(this.getActivity(), getString(com.example.pluginsharelib.R.string.share_string_1),
					Toast.LENGTH_LONG).show();
		} else if (v.getId() == R.id.plugin_test_btn3) {
			View view = LayoutInflater.from(getActivity()).inflate(com.example.pluginsharelib.R.layout.share_main,
					null, false);
			mRoot.addView(view);
		} else if (v.getId() == R.id.plugin_test_btn4) {
			((Button) v).setText(com.example.pluginsharelib.R.string.share_string_2);
		}
	}
}


text:
class MoveFiles < ActiveRecord::Migration
  def self.up
    courses = Course.where(['not instructor_id is null'])
    courses.each{
      | course |

      if course.directory_path == nil
        course.directory_path = FileHelper.clean_path(course.name)
      end

      csplit = course.directory_path.split("/")
      if csplit[0] == User.find(course.instructor_id).name
        csplit[0] = nil
      end

      index = 0
      path = String.new
      while index < csplit.length
        if csplit[index]
          path += FileHelper.clean_path(csplit[index])
          if index < csplit.length - 1
            path += "/"
          end
        end
        index += 1
      end

      if path.length == 0
        path = FileHelper.clean_path(course.name)
      end

      course.directory_path = path
      course.save

      FileHelper.create_directory(course)
    }

    assignments = Assignment.where(['wiki_type_id = 1 and not instructor_id is null'])
    assignments.each{
      | assignment |
      directories = Assignment.find_all_by(directory_path: assignment.directory_path)
      if directories.length ==  1
        oldpath = Rails.root + "/pg_data/"+ assignment.directory_path
         if assignment.name == 'Another assignment'
            puts assignment.directory_path
            puts assignment.directory_path.length
         end

         if assignment.directory_path == nil or assignment.directory_path.length == 0
          assignment.directory_path = FileHelper.clean_path(assignment.name)
        end

        asplit = assignment.directory_path.split("/")
        if asplit[0] == User.find(assignment.instructor_id).name
          asplit[0] = nil
        end

        if assignment.course_id > 0 and asplit[1] == Course.find(assignment.course_id).directory_path
         asplit[1] = nil
        end

        index = 0
        path = String.new
        while index < asplit.length
          if asplit[index]
            path += FileHelper.clean_path(asplit[index])
           if index < asplit.length - 1
             path += "/"
           end
         end
         index += 1
       end

      if path.length == 0
        path = FileHelper.clean_path(assignment.name)
      end

      assignment.directory_path = path
      assignment.save
      if oldpath != assignment.dir_path
        FileHelper.create_directory(assignment)
        oldcontents = Dir.glob(oldpath + "/*")
        FileUtils.mv(oldcontents,assignment.dir_path)
      end
    else
      puts "Two or more assignments exist for the same path. Assignment: "+assignment.name+" Path: "+assignment.directory_path
    end
    }
  end

  def self.down
  end
end


text:
"""Mixins for account-related views."""

from __future__ import unicode_literals

from django import forms
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from djblets.privacy.consent import (get_consent_tracker,
                                     get_consent_requirements_registry)
from djblets.privacy.consent.common import PolicyConsentRequirement
from djblets.siteconfig.models import SiteConfiguration

from reviewboard.accounts.decorators import (check_login_required,
                                             valid_prefs_required)

class CheckLoginRequiredViewMixin(object):
    """View mixin to check if a user needs to be logged in.

    This is a convenience around using the :py:func:`@check_login_required
    <reviewboard.accounts.decorators.check_login_required>` decorator for
    class-based views.
    """

    @method_decorator(check_login_required)
    def dispatch(self, *args, **kwargs):
        """Dispatch a HTTP request to the right handler.

        Args:
            *args (tuple):
                Positional arguments to pass to the handler.

            **kwargs (tuple):
                Keyword arguments to pass to the handler.

                These will be arguments provided by the URL pattern.

        Returns:
            django.http.HttpResponse:
            The resulting HTTP response to send to the client.
        """
        return super(CheckLoginRequiredViewMixin, self).dispatch(
            *args, **kwargs)

class LoginRequiredViewMixin(object):
    """View mixin to ensure a user is logged in.

    This is a convenience around using the :py:func:`@login_required
    <django.contrib.auth.decorators.login_required>` decorator for
    class-based views.
    """

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        """Dispatch a HTTP request to the right handler.

        Args:
            *args (tuple):
                Positional arguments to pass to the handler.

            **kwargs (tuple):
                Keyword arguments to pass to the handler.

                These will be arguments provided by the URL pattern.

        Returns:
            django.http.HttpResponse:
            The resulting HTTP response to send to the client.
        """
        return super(LoginRequiredViewMixin, self).dispatch(*args, **kwargs)

class UserProfileRequiredViewMixin(object):
    """View mixin to ensure a user has a profile set up.

    This is a convenience around using the :py:func:`@valid_prefs_required
    <reviewboard.accounts.decorators.valid_prefs_required>` decorator for
    class-based views.
    """

    @method_decorator(valid_prefs_required)
    def dispatch(self, *args, **kwargs):
        """Dispatch a HTTP request to the right handler.

        Args:
            *args (tuple):
                Positional arguments to pass to the handler.

            **kwargs (tuple):
                Keyword arguments to pass to the handler.

                These will be arguments provided by the URL pattern.

        Returns:
            django.http.HttpResponse:
            The resulting HTTP response to send to the client.
        """
        return super(UserProfileRequiredViewMixin, self).dispatch(
            *args, **kwargs)

class PolicyConsentFormMixin(object):
    """Form mixin to add consent to privacy policy and terms of service."""

    def __init__(self, *args, **kwargs):
        """Initialize the mixin.

        Args:
            *args (tuple):
                Additional positional arguments to pass to the superclass
                constructor.

            **kwargs (dict):
                Additional keyword arguments to pass to the superclass
                constructor.
        """
        super(PolicyConsentFormMixin, self).__init__(*args, **kwargs)

        siteconfig = SiteConfiguration.objects.get_current()
        privacy_policy_url = siteconfig.get('privacy_policy_url')
        terms_of_service_url = siteconfig.get('terms_of_service_url')

        self.policies_enabled = bool(
            siteconfig.get('privacy_enable_user_consent') and
            (privacy_policy_url or terms_of_service_url))

        if self.policies_enabled:
            if privacy_policy_url and terms_of_service_url:
                label = mark_safe(
                    _('I agree to the Privacy Policy and '
                      'Terms of Service.')
                    % (privacy_policy_url, terms_of_service_url))
            elif privacy_policy_url:
                label = mark_safe(
                    _('I agree to the Privacy Policy.')
                    % privacy_policy_url)
            elif terms_of_service_url:
                label = mark_safe(
                    _('I agree to the Terms of Service.')
                    % terms_of_service_url)

            self.fields['agree_to_policies'] = forms.BooleanField(
                label=label,
                required=True)

    def accept_policies(self, user):
        """Accept the linked policies for the given user.

        Args:
            user (django.contrib.auth.models.User):
                The user who has accepted the privacy policy and/or terms of
                service.
        """
        if self.policies_enabled:
            consent_registry = get_consent_requirements_registry()
            requirement = consent_registry.get_consent_requirement(
                PolicyConsentRequirement.requirement_id)

            consent_tracker = get_consent_tracker()
            consent_tracker.record_consent_data(
                user, requirement.build_consent_data(granted=True))