text:
package org.apache.pulsar.broker.admin.v1;

import static com.google.common.base.Preconditions.checkNotNull;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.Encoded;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;

import com.google.common.collect.Lists;
import org.apache.pulsar.broker.PulsarServerException;
import org.apache.pulsar.broker.service.Topic;
import org.apache.pulsar.broker.service.nonpersistent.NonPersistentTopic;
import org.apache.pulsar.broker.web.RestException;
import org.apache.pulsar.common.naming.Constants;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.naming.NamespaceBundle;
import org.apache.pulsar.common.naming.NamespaceName;
import org.apache.pulsar.common.partition.PartitionedTopicMetadata;
import org.apache.pulsar.common.policies.data.NonPersistentTopicStats;
import org.apache.pulsar.common.policies.data.PersistentTopicInternalStats;
import org.apache.pulsar.common.policies.data.Policies;
import org.apache.pulsar.common.util.FutureUtil;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 */
@Path("/non-persistent")
@Produces(MediaType.APPLICATION_JSON)
@Api(value = "/non-persistent", description = "Non-Persistent topic admin apis", tags = "non-persistent topic")
@SuppressWarnings("deprecation")
public class NonPersistentTopics extends PersistentTopics {
    private static final Logger log = LoggerFactory.getLogger(NonPersistentTopics.class);

    @GET
    @Path("/{property}/{cluster}/{namespace}/{topic}/partitions")
    @ApiOperation(hidden = true, value = "Get partitioned topic metadata.")
    @ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission") })
    public PartitionedTopicMetadata getPartitionedMetadata(@PathParam("property") String property,
            @PathParam("cluster") String cluster, @PathParam("namespace") String namespace,
            @PathParam("topic") @Encoded String encodedTopic,
            @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
        validateTopicName(property, cluster, namespace, encodedTopic);
        return getPartitionedTopicMetadata(topicName, authoritative);
    }

    @GET
    @Path("{property}/{cluster}/{namespace}/{topic}/stats")
    @ApiOperation(hidden = true, value = "Get the stats for the topic.")
    @ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"),
            @ApiResponse(code = 404, message = "Topic does not exist") })
    public NonPersistentTopicStats getStats(@PathParam("property") String property,
            @PathParam("cluster") String cluster, @PathParam("namespace") String namespace,
            @PathParam("topic") @Encoded String encodedTopic,
            @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
        validateTopicName(property, cluster, namespace, encodedTopic);
        validateAdminOperationOnTopic(authoritative);
        Topic topic = getTopicReference(topicName);
        return ((NonPersistentTopic) topic).getStats();
    }

    @GET
    @Path("{property}/{cluster}/{namespace}/{topic}/internalStats")
    @ApiOperation(hidden = true, value = "Get the internal stats for the topic.")
    @ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"),
            @ApiResponse(code = 404, message = "Topic does not exist") })
    public PersistentTopicInternalStats getInternalStats(@PathParam("property") String property,
            @PathParam("cluster") String cluster, @PathParam("namespace") String namespace,
            @PathParam("topic") @Encoded String encodedTopic,
            @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
        validateTopicName(property, cluster, namespace, encodedTopic);
        validateAdminOperationOnTopic(authoritative);
        Topic topic = getTopicReference(topicName);
        return topic.getInternalStats();
    }

    @PUT
    @Path("/{property}/{cluster}/{namespace}/{topic}/partitions")
    @ApiOperation(hidden = true, value = "Create a partitioned topic.", notes = "It needs to be called before creating a producer on a partitioned topic.")
    @ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"),
            @ApiResponse(code = 409, message = "Partitioned topic already exist") })
    public void createPartitionedTopic(@PathParam("property") String property, @PathParam("cluster") String cluster,
            @PathParam("namespace") String namespace, @PathParam("topic") @Encoded String encodedTopic,
            int numPartitions, @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
        validateTopicName(property, cluster, namespace, encodedTopic);
        validateAdminAccessOnProperty(topicName.getProperty());
        if (numPartitions <= 1) {
            throw new RestException(Status.NOT_ACCEPTABLE, "Number of partitions should be more than 1");
        }
        try {
            String path = path(PARTITIONED_TOPIC_PATH_ZNODE, namespaceName.toString(), domain(),
                    topicName.getEncodedLocalName());
            byte[] data = jsonMapper().writeValueAsBytes(new PartitionedTopicMetadata(numPartitions));
            zkCreateOptimistic(path, data);
            // we wait for the data to be synced in all quorums and the observers
            Thread.sleep(PARTITIONED_TOPIC_WAIT_SYNC_TIME_MS);
            log.info("[{}] Successfully created partitioned topic {}", clientAppId(), topicName);
        } catch (KeeperException.NodeExistsException e) {
            log.warn("[{}] Failed to create already existing partitioned topic {}", clientAppId(), topicName);
            throw new RestException(Status.CONFLICT, "Partitioned topic already exist");
        } catch (Exception e) {
            log.error("[{}] Failed to create partitioned topic {}", clientAppId(), topicName, e);
            throw new RestException(e);
        }
    }

    @PUT
    @Path("/{property}/{cluster}/{namespace}/{topic}/unload")
    @ApiOperation(hidden = true, value = "Unload a topic")
    @ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"),
            @ApiResponse(code = 404, message = "Topic does not exist") })
    public void unloadTopic(@PathParam("property") String property, @PathParam("cluster") String cluster,
            @PathParam("namespace") String namespace, @PathParam("topic") @Encoded String encodedTopic,
            @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
        validateTopicName(property, cluster, namespace, encodedTopic);
        log.info("[{}] Unloading topic {}", clientAppId(), topicName);

        if (topicName.isGlobal()) {
            validateGlobalNamespaceOwnership(namespaceName);
        }
        unloadTopic(topicName, authoritative);
    }

    @GET
    @Path("/{property}/{cluster}/{namespace}")
    @ApiOperation(value = "Get the list of non-persistent topics under a namespace.", response = String.class, responseContainer = "List")
    @ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"),
            @ApiResponse(code = 404, message = "Namespace doesn't exist") })
    public List<String> getList(@PathParam("property") String property, @PathParam("cluster") String cluster,
                                @PathParam("namespace") String namespace) {
        log.info("[{}] list of topics on namespace {}/{}/{}/{}", clientAppId(), property, cluster, namespace);
        validateAdminAccessOnProperty(property);
        Policies policies = getNamespacePolicies(property, cluster, namespace);
        NamespaceName nsName = NamespaceName.get(property, cluster, namespace);

        if (!cluster.equals(Constants.GLOBAL_CLUSTER)) {
            validateClusterOwnership(cluster);
            validateClusterForProperty(property, cluster);
        } else {
            // check cluster ownership for a given global namespace: redirect if peer-cluster owns it
            validateGlobalNamespaceOwnership(nsName);
        }
        final List<CompletableFuture<List<String>>> futures = Lists.newArrayList();
        final List<String> boundaries = policies.bundles.getBoundaries();
        for (int i = 0; i < boundaries.size() - 1; i++) {
            final String bundle = String.format("%s_%s", boundaries.get(i), boundaries.get(i + 1));
            try {
                futures.add(pulsar().getAdminClient().nonPersistentTopics().getListInBundleAsync(nsName.toString(),
                        bundle));
            } catch (PulsarServerException e) {
                log.error(String.format("[%s] Failed to get list of topics under namespace %s/%s/%s/%s", clientAppId(),
                        property, cluster, namespace, bundle), e);
                throw new RestException(e);
            }
        }
        final List<String> topics = Lists.newArrayList();
        try {
            FutureUtil.waitForAll(futures).get();
            futures.forEach(topicListFuture -> {
                try {
                    if (topicListFuture.isDone() && topicListFuture.get() != null) {
                        topics.addAll(topicListFuture.get());
                    }
                } catch (InterruptedException | ExecutionException e) {
                    log.error(String.format("[%s] Failed to get list of topics under namespace %s/%s/%s", clientAppId(),
                            property, cluster, namespace), e);
                }
            });
        } catch (InterruptedException | ExecutionException e) {
            log.error(String.format("[%s] Failed to get list of topics under namespace %s/%s/%s", clientAppId(),
                    property, cluster, namespace), e);
            throw new RestException(e instanceof ExecutionException ? e.getCause() : e);
        }
        return topics;
    }

    @GET
    @Path("/{property}/{cluster}/{namespace}/{bundle}")
    @ApiOperation(value = "Get the list of non-persistent topics under a namespace bundle.", response = String.class, responseContainer = "List")
    @ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"),
            @ApiResponse(code = 404, message = "Namespace doesn't exist") })
    public List<String> getListFromBundle(@PathParam("property") String property, @PathParam("cluster") String cluster,
                                          @PathParam("namespace") String namespace, @PathParam("bundle") String bundleRange) {
        log.info("[{}] list of topics on namespace bundle {}/{}/{}/{}", clientAppId(), property, cluster, namespace,
                bundleRange);
        validateAdminAccessOnProperty(property);
        Policies policies = getNamespacePolicies(property, cluster, namespace);
        if (!cluster.equals(Constants.GLOBAL_CLUSTER)) {
            validateClusterOwnership(cluster);
            validateClusterForProperty(property, cluster);
        } else {
            // check cluster ownership for a given global namespace: redirect if peer-cluster owns it
            validateGlobalNamespaceOwnership(NamespaceName.get(property, cluster, namespace));
        }
        NamespaceName fqnn = NamespaceName.get(property, cluster, namespace);
        if (!isBundleOwnedByAnyBroker(fqnn, policies.bundles, bundleRange)) {
            log.info("[{}] Namespace bundle is not owned by any broker {}/{}/{}/{}", clientAppId(), property, cluster,
                    namespace, bundleRange);
            return null;
        }
        NamespaceBundle nsBundle = validateNamespaceBundleOwnership(fqnn, policies.bundles, bundleRange, true, true);
        try {
            final List<String> topicList = Lists.newArrayList();
            pulsar().getBrokerService().getTopics().forEach((name, topicFuture) -> {
                TopicName topicName = TopicName.get(name);
                if (nsBundle.includes(topicName)) {
                    topicList.add(name);
                }
            });
            return topicList;
        } catch (Exception e) {
            log.error("[{}] Failed to unload namespace bundle {}/{}", clientAppId(), fqnn.toString(), bundleRange, e);
            throw new RestException(e);
        }
    }

    protected void validateAdminOperationOnTopic(TopicName topicName, boolean authoritative) {
        validateAdminAccessOnProperty(topicName.getProperty());
        validateTopicOwnership(topicName, authoritative);
    }

    private Topic getTopicReference(TopicName topicName) {
        try {
            Topic topic = pulsar().getBrokerService().getTopicReference(topicName.toString());
            checkNotNull(topic);
            return topic;
        } catch (Exception e) {
            throw new RestException(Status.NOT_FOUND, "Topic not found");
        }
    }
}


text:
FROM node:carbon

WORKDIR /pulsetile

# install dependencies
RUN npm install

# Expose port 3000 for node server
EXPOSE 3000

CMD npm start

redpajama_set_name: RedPajamaGithub


text:
layout: full-width
title: Contact
breadcrumb: home
published: true
---
Contact us if you have a question, complaint or need any information about the library service.

## Suffolk Libraries contact details

* Telephone: **01473 351249** (please don't text this number)
* Email: **help@suffolklibraries.co.uk**

[Find your local library.](/libraries/)

Write to:

Suffolk Libraries

Ipswich County Library

Northgate Street

Ipswich, IP1 3DE

### Press and media enquiries

James Powell: james.powell@suffolklibraries.co.uk

### Social media

* [Twitter](http://twitter.com/SuffolkLibrary)
* [Facebook](http://facebook.com/suffolklibraries)
* [Instagram](http://instagram.com/suffolklibraries)
* [Email newsletter](http://eepurl.com/xIZ5D)


text:
// source:

package nl.esciencecenter.vbrowser.vrs.task;

import java.util.List;

import nl.esciencecenter.ptk.task.ITaskMonitor;
import nl.esciencecenter.ptk.task.TransferMonitor;
import nl.esciencecenter.vbrowser.vrs.vrl.VRL;
import nl.esciencecenter.vbrowser.vrs.vrl.VRLUtil;

/**
 * VRSTransfer monitor class. Monitor object for ongoing VRS Actions and Transfers.
 */
public class VRSTaskMonitor extends TransferMonitor {
    // ========================================================================
    // instance
    // ========================================================================

    private VRSActionType actionType = VRSActionType.UNKNOWN;

    // instance methods
    protected VRSTaskMonitor(ITaskMonitor parentMonitor, VRSActionType vrsAction, String resourceType,
            List<VRL> sources, VRL destination) {
        super((vrsAction != null) ? vrsAction.toString() : "VRSTransfer", VRLUtil.toURIs(sources), destination
                .toURINoException());
        setParent(parentMonitor); // add this transfer to parent monitor
    }

    // instance methods
    public VRSTaskMonitor(VRSActionType vrsAction, List<VRL> sources, VRL destination) {
        super((vrsAction != null) ? vrsAction.toString() : "VRSTransfer", VRLUtil.toURIs(sources), destination
                .toURINoException());
    }

    public VRSActionType getTaskType() {
        return actionType;
    }

    /**
     * @return Returns the current source as VRL.
     */
    public VRL getCurrentSource() {
        java.net.URI uri = super.getSource();

        if (uri == null)
            return null;

        return new VRL(uri);
    }

}


text:
package com.xinxin.firstcodeutil.activity;

import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import com.xinxin.firstcodeutil.R;
import com.xinxin.firstcodeutil.fragment.ElementaryFragment;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by xinxin on 2016/5/5.
 */
public class AtyRxJavaDemo extends AppCompatActivity {

    @BindView(android.R.id.tabs)
    TabLayout tabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.toolBar)
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rxjava_demo);

        ButterKnife.bind(this);

        viewPager.setAdapter(new FragmentPagerAdapter(getFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                switch (position) {
                    case 0:
                        return new ElementaryFragment();
                    case 1:
                        return new ElementaryFragment();
                    case 2:
                        return new ElementaryFragment();
                    case 3:
                        return new ElementaryFragment();
                    case 4:
                        return new ElementaryFragment();
                    case 5:
                        return new ElementaryFragment();
                    default:
                        return new ElementaryFragment();
                }
            }

            @Override
            public int getCount() {
                return 6;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 0:
                        return getString(R.string.title_elementary);
                    case 1:
                        return getString(R.string.title_map);
                    case 2:
                        return getString(R.string.title_zip);
                    case 3:
                        return getString(R.string.title_token);
                    case 4:
                        return getString(R.string.title_token_advanced);
                    case 5:
                        return getString(R.string.title_cache);
                    default:
                        return getString(R.string.title_elementary);
                }
            }
        });

    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ExitStrategy.TestWebsite.Webforms.ModelBinding {

    public partial class IndexWithListView {

        /// <summary>
        /// ValidationSummary control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel ValidationSummary;

        /// <summary>
        /// List control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ListView List;

        /// <summary>
        /// ResultPanel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel ResultPanel;

        /// <summary>
        /// ResultDisplay control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::ExitStrategy.ForWebforms.Display ResultDisplay;
    }
}


text:
package org.apache.derby.impl.store.raw.data;

import org.apache.derby.impl.store.raw.data.AllocationActions;
import org.apache.derby.impl.store.raw.data.BasePage;

import org.apache.derby.iapi.store.raw.RawStoreFactory;
import org.apache.derby.iapi.services.sanity.SanityManager;
import org.apache.derby.iapi.services.io.FormatIdUtil;

import org.apache.derby.iapi.store.raw.Loggable;
import org.apache.derby.iapi.store.raw.xact.RawTransaction;
import org.apache.derby.iapi.store.raw.log.LogInstant;

import org.apache.derby.iapi.error.StandardException;

public class LoggableAllocActions implements AllocationActions {

	/**
		Set the allocation status of pageNumber to doStatus.  To undo this
		operation, set the allocation status of pageNumber to undoStatus

		@param t				The transaction
		@param allocPage		the allocation page
		@param pageNumber		the page to allocation or deallocation
		@param doStatus			set the allocation status of the page this value
		@param undoStatus		on undo, set the allocation status of the page
								this value

		@exception StandardException	Standard Derby error policy
	*/
	public void actionAllocatePage(RawTransaction t, BasePage allocPage,
								   long pageNumber, int doStatus, int undoStatus)
		 throws StandardException
	{
		Loggable lop = new AllocPageOperation((AllocPage)allocPage, pageNumber, doStatus, undoStatus);

		// mark the page as pre-dirtied so that if a checkpoint happens after
		// the log record is sent to the log stream, the cache cleaning will
		// wait for this change.
		allocPage.preDirty();

		t.logAndDo(lop);
	}

	/**
		Chain one allocation page to the next.

		@param t				The transaction
		@param allocPage		the allocation page whose next page chain needs
								to be changed
		@param pageNumber		the next allocation page's number
		@param pageOffset		the next allocation page's page offset

		@exception StandardException	Standard Derby error policy
	*/
	public void actionChainAllocPage(RawTransaction t, BasePage allocPage,
								long pageNumber, long pageOffset)
		 throws StandardException
	{
		Loggable lop = new ChainAllocPageOperation((AllocPage)allocPage, pageNumber, pageOffset);

		// mark the page as pre-dirtied so that if a checkpoint happens after
		// the log record is sent to the log stream, the cache cleaning will
		// wait for this change.
		allocPage.preDirty();

		t.logAndDo(lop);
	}

    /**
     * Compress free pages.
     *

     * Compress the free pages at the end of the range maintained by
     * this allocation page.  All pages being compressed should be FREE.
     * Only pages in the last allocation page can be compressed.
     *

     *
     * @param t				        The transaction
     * @param allocPage		        the allocation page to do compress on.
     * @param new_highest_page      The new highest page on this allocation
     *                              page.  The number is the offset of the page
     *                              in the array of pages maintained by this
     *                              allocation page, for instance a value of 0
     *                              indicates all page except the first one are
     *                              to be truncated.  If all pages are
     *                              truncated then the offset is set to -1.
     * @param num_pages_truncated   The number of allocated pages in this
     *                              allocation page prior to the truncate.
     *                              Note that all pages from NewHighestPage+1
     *                              through newHighestPage+num_pages_truncated
     *                              should be FREE.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public void actionCompressSpaceOperation(
	RawTransaction  t,
    BasePage        allocPage,
    int             new_highest_page,
    int             num_pages_truncated)
        throws StandardException
    {
        Loggable lop = null;

        // DERBY-606. As part of the fix for DERBY-606, negative values can be
        // written to CompressSpace operation Log Records. In order for this
        // fix to be backword compatible, we make sure that the implementation
        // behaves the old way in soft upgrade mode, here. This is achieved by
        // passing null to feature argument.
        if( t.getLogFactory().checkVersion(
                RawStoreFactory.DERBY_STORE_MAJOR_VERSION_10,
                RawStoreFactory.DERBY_STORE_MINOR_VERSION_3,
                null) )
        {
            lop =
                new CompressSpacePageOperation(
                    (AllocPage)allocPage,
                    new_highest_page,
                    num_pages_truncated);
        } else {
            lop = new CompressSpacePageOperation10_2(
                    (AllocPage)allocPage,
                    new_highest_page,
                    num_pages_truncated);
        }
        allocPage.preDirty();

        t.logAndDo(lop);
    }
}


text:
package com.google.android.exoplayer.dash.mpd;

import com.google.android.exoplayer.ParserException;
import com.google.android.exoplayer.upstream.Loader;
import com.google.android.exoplayer.upstream.Loader.Loadable;
import com.google.android.exoplayer.upstream.UriDataSource;
import com.google.android.exoplayer.upstream.UriLoadable;
import com.google.android.exoplayer.util.Assertions;
import com.google.android.exoplayer.util.Util;

import android.os.SystemClock;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.CancellationException;

/**
 * Resolves a {@link UtcTimingElement}.
 */
public class UtcTimingElementResolver implements Loader.Callback {

  /**
   * Callback for timing element resolution.
   */
  public interface UtcTimingCallback {

    /**
     * Invoked when the element has been resolved.
     *
     * @param utcTiming The element that was resolved.
     * @param elapsedRealtimeOffset The offset between the resolved UTC time and
     *     {@link SystemClock#elapsedRealtime()} in milliseconds, specified as the UTC time minus
     *     the local elapsed time.
     */
    void onTimestampResolved(UtcTimingElement utcTiming, long elapsedRealtimeOffset);

    /**
     * Invoked when the element was not successfully resolved.
     *
     * @param utcTiming The element that was not resolved.
     * @param e The cause of the failure.
     */
    void onTimestampError(UtcTimingElement utcTiming, IOException e);
  }

  private final UriDataSource uriDataSource;
  private final UtcTimingElement timingElement;
  private final long timingElementElapsedRealtime;
  private final UtcTimingCallback callback;

  private Loader singleUseLoader;
  private UriLoadable<Long> singleUseLoadable;

  /**
   * Resolves a {@link UtcTimingElement}.
   *
   * @param uriDataSource A source to use should loading from a URI be necessary.
   * @param timingElement The element to resolve.
   * @param timingElementElapsedRealtime The {@link SystemClock#elapsedRealtime()} timestamp at
   *     which the element was obtained. Used if the element contains a timestamp directly.
   * @param callback The callback to invoke on resolution or failure.
   */
  public static void resolveTimingElement(UriDataSource uriDataSource,
      UtcTimingElement timingElement, long timingElementElapsedRealtime,
      UtcTimingCallback callback) {
    UtcTimingElementResolver resolver = new UtcTimingElementResolver(uriDataSource, timingElement,
        timingElementElapsedRealtime, callback);
    resolver.resolve();
  }

  private UtcTimingElementResolver(UriDataSource uriDataSource, UtcTimingElement timingElement,
      long timingElementElapsedRealtime, UtcTimingCallback callback) {
    this.uriDataSource = uriDataSource;
    this.timingElement = Assertions.checkNotNull(timingElement);
    this.timingElementElapsedRealtime = timingElementElapsedRealtime;
    this.callback = Assertions.checkNotNull(callback);
  }

  private void resolve() {
    String scheme = timingElement.schemeIdUri;
    if (Util.areEqual(scheme, "urn:mpeg:dash:utc:direct:2012")) {
      resolveDirect();
    } else if (Util.areEqual(scheme, "urn:mpeg:dash:utc:http-iso:2014")) {
      resolveHttp(new Iso8601Parser());
    } else if (Util.areEqual(scheme, "urn:mpeg:dash:utc:http-xsdate:2012")
        || Util.areEqual(scheme, "urn:mpeg:dash:utc:http-xsdate:2014")) {
      resolveHttp(new XsDateTimeParser());
    } else {
      // Unsupported scheme.
      callback.onTimestampError(timingElement, new IOException("Unsupported utc timing scheme"));
    }
  }

  private void resolveDirect() {
    try {
      long utcTimestamp = Util.parseXsDateTime(timingElement.value);
      long elapsedRealtimeOffset = utcTimestamp - timingElementElapsedRealtime;
      callback.onTimestampResolved(timingElement, elapsedRealtimeOffset);
    } catch (ParseException e) {
      callback.onTimestampError(timingElement, new ParserException(e));
    }
  }

  private void resolveHttp(UriLoadable.Parser<Long> parser) {
    singleUseLoader = new Loader("utctiming");
    singleUseLoadable = new UriLoadable<>(timingElement.value, uriDataSource, parser);
    singleUseLoader.startLoading(singleUseLoadable, this);
  }

  @Override
  public void onLoadCanceled(Loadable loadable) {
    onLoadError(loadable, new IOException("Load cancelled", new CancellationException()));
  }

  @Override
  public void onLoadCompleted(Loadable loadable) {
    releaseLoader();
    long elapsedRealtimeOffset = singleUseLoadable.getResult() - SystemClock.elapsedRealtime();
    callback.onTimestampResolved(timingElement, elapsedRealtimeOffset);
  }

  @Override
  public void onLoadError(Loadable loadable, IOException exception) {
    releaseLoader();
    callback.onTimestampError(timingElement, exception);
  }

  private void releaseLoader() {
    singleUseLoader.release();
  }

  private static class XsDateTimeParser implements UriLoadable.Parser<Long> {

    @Override
    public Long parse(String connectionUrl, InputStream inputStream) throws ParserException,
        IOException {
      String firstLine = new BufferedReader(new InputStreamReader(inputStream)).readLine();
      try {
        return Util.parseXsDateTime(firstLine);
      } catch (ParseException e) {
        throw new ParserException(e);
      }
    }

  }

  private static class Iso8601Parser implements UriLoadable.Parser<Long> {

    @Override
    public Long parse(String connectionUrl, InputStream inputStream) throws ParserException,
        IOException {
      String firstLine = new BufferedReader(new InputStreamReader(inputStream)).readLine();
      try {
        // TODO: It may be necessary to handle timestamp offsets from UTC.
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("UTC"));
        return format.parse(firstLine).getTime();
      } catch (ParseException e) {
        throw new ParserException(e);
      }
    }

  }

}


text:
package org.nutz.lang.tmpl;

public class StrFormatConvertor implements StrEleConvertor {

    private String fmt;

    StrFormatConvertor(String fmt) {
        this.fmt = fmt;
    }

    @Override
    public String process(String str) {
        if (null == fmt)
            return str;
        return String.format(fmt, str);
    }

}


text:
module.exports = {
  authenticate: 'authenticate',
  join: 'join',
  leave: 'leave',
  msg: 'msg',
  privateMsg: 'privatemsg',
  ownPrivateMsg: 'ownprivatemsg',
  connect: 'connect',
  disconnect: 'disconnect',
  online: 'online',
  offline: 'offline',
  error: 'error',
}


text:
package com.snowplowanalytics.snowplow.hadoop.hive

// Scala
import scala.collection.JavaConversions

// Specs2
import org.specs2.mutable.Specification

// Hive
import org.apache.hadoop.hive.serde2.SerDeException

// SnowPlow Utils
import com.snowplowanalytics.util.Tap._

// Deserializer
import test.{SnowPlowDeserializer, SnowPlowEvent, SnowPlowTest}

class PageViewTest2 extends Specification {

  // Toggle if tests are failing and you want to inspect the struct contents
  implicit val _DEBUG = false

  val row = "2012-05-24  00:06:42  LHR5  3402  90.194.12.51  GET d3gs014xn8p70.cloudfront.net  /ice.png  200 http://www.psychicbazaar.com/oracles/119-psycards-book-and-deck-starter-pack.html?view=print#detail Mozilla/5.0%20(iPhone;%20CPU%20iPhone%20OS%205_1_1%20like%20Mac%20OS%20X)%20AppleWebKit/534.46%20(KHTML,%20like%20Gecko)%20Version/5.1%20Mobile/9B206%20Safari/7534.48.3  e=pv&page=Psycards%2520book%2520and%2520deck%2520starter%2520pack%2520-%2520Psychic%2520Bazaar&tid=019539&vp=479x283&ds=584x268&cs=UTF-8&duid=e7bccbb647296c98&vid=1&p=Web&aid=CFe23a&fp=1906624389&tz=Europe%2FLondon&cd=24&lang=en-us&refr=http%253A%252F%252Fwww.google.com%252Fsearch%253Fhl%253Den%2526q%253Dthe%252Bpsycard%252Bstory%2526oq%253Dthe%252Bpsycard%252Bstory%2526aq%253Df%2526aqi%253D%2526aql%253D%2526gs_l%253Dmobile-gws-serp.12...0.0.0.6358.0.0.0.0.0.0.0.0..0.0...0.0.JrNbKlRgHbQ%2526mvs%253D0&f_pdf=0&f_qt=1&f_realp=0&f_wma=1&f_dir=0&f_fla=1&f_java=0&f_gears=1&f_ag=0&res=320x480&cookie=1"

  val expected = new SnowPlowEvent().tap { e =>
    e.app_id = "CFe23a"
    e.platform = "Web"
    e.dt = "2012-05-24"
    e.collector_dt = "2012-05-24"
    e.collector_tm = "00:06:42"
    e.event = "page_view"
    e.event_vendor = "com.snowplowanalytics"
    e.txn_id = "019539"
    e.domain_userid = "e7bccbb647296c98"
    e.user_ipaddress = "90.194.12.51"
    e.user_fingerprint = "1906624389"
    e.domain_sessionidx = 1
    e.page_url = "http://www.psychicbazaar.com/oracles/119-psycards-book-and-deck-starter-pack.html?view=print#detail"
    e.page_title = "Psycards book and deck starter pack - Psychic Bazaar"
    e.page_referrer = "http://www.google.com/search?hl=en&q=the+psycard+story&oq=the+psycard+story&aq=f&aqi=&aql=&gs_l=mobile-gws-serp.12...0.0.0.6358.0.0.0.0.0.0.0.0..0.0...0.0.JrNbKlRgHbQ&mvs=0"
    e.page_urlscheme = "http"
    e.page_urlhost = "www.psychicbazaar.com"
    e.page_urlport = 80
    e.page_urlpath = "/oracles/119-psycards-book-and-deck-starter-pack.html"
    e.page_urlquery = "view=print"
    e.page_urlfragment = "detail"
    e.useragent = "Mozilla/5.0 (iPhone; CPU iPhone OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B206 Safari/7534.48.3"
    e.br_name = "Mobile Safari"
    e.br_family = "Safari"
    e.br_version = "5.1"
    e.br_type = "Browser (mobile)"
    e.br_renderengine = "WEBKIT"
    e.br_lang = "en-us"
    e.br_cookies = true
    e.br_cookies_bt = 1
    e.br_features = List("qt", "fla", "wma", "gears")
    e.br_features_pdf = 0
    e.br_features_flash = 1
    e.br_features_java = 0
    e.br_features_director = 0
    e.br_features_quicktime = 1
    e.br_features_realplayer = 0
    e.br_features_windowsmedia = 1
    e.br_features_gears = 1
    e.br_features_silverlight = 0
    e.br_colordepth = "24"
    e.br_viewwidth = 479
    e.br_viewheight = 283
    e.os_name = "Mac OS" // Yech, nl.bitwalker.useragentutils is not parsing this user agent correctly
    e.os_family = "Mac OS" // Yech, nl.bitwalker.useragentutils is not parsing this user agent correctly
    e.os_manufacturer = "Apple Inc."
    e.os_timezone = "Europe/London"
    e.dvce_type = "Computer" // Yech, nl.bitwalker.useragentutils is not parsing this user agent correctly
    e.dvce_ismobile = false // Yech, nl.bitwalker.useragentutils is not parsing this user agent correctly
    e.dvce_ismobile_bt = 0 // Yech, nl.bitwalker.useragentutils is not parsing this user agent correctly
    e.dvce_screenwidth = 320
    e.dvce_screenheight = 480
    e.doc_charset = "UTF-8"
    e.doc_width = 584
    e.doc_height = 268
  }

  "The SnowPlow page view row \"%s\"".format(row) should {

    val actual = SnowPlowDeserializer.deserialize(row)

    // Check all of the field values

    // The application (site, game, app etc) this event belongs to, and the tracker platform
    "have app_id (Application ID) = %s".format(expected.app_id) in {
      actual.app_id must_== expected.app_id
    }
    "have platform (Platform) = %s".format(expected.platform) in {
      actual.platform must_== expected.platform
    }

    // Date/time
    "have dt (Legacy Hive Date) = %s".format(expected.dt) in {
      actual.dt must_== expected.dt
    }
    "have collector_dt (Collector Date) = %s".format(expected.collector_dt) in {
      actual.collector_dt must_== expected.collector_dt
    }
    "have collector_tm (Collector Time) = %s".format(expected.collector_tm) in {
      actual.collector_tm must_== expected.collector_tm
    }

    // Event and transaction
    "have event (Event Type) = %s".format(expected.event) in {
      actual.event must_== expected.event
    }
    "have event_vendor (Event Vendor) = %s".format(expected.event_vendor) in {
      actual.event_vendor must_== expected.event_vendor
    }
    "have a valid (stringly-typed UUID) event_id" in {
      SnowPlowTest.stringlyTypedUuid(actual.event_id) must_== actual.event_id
    }
    "have txn_id (Transaction ID) = %s".format(expected.txn_id) in {
      actual.txn_id must_== expected.txn_id
    }

    // User and visit
    "have domain_userid (Domain User ID) = %s".format(expected.domain_userid) in {
      actual.domain_userid must_== expected.domain_userid
    }
    "have user_ipaddress (User IP Address) = %s".format(expected.user_ipaddress) in {
      actual.user_ipaddress must_== expected.user_ipaddress
    }
    "have user_fingerprint (User Fingerprint) = %s".format(expected.user_fingerprint) in {
      actual.user_fingerprint must_== expected.user_fingerprint
    }
    "have visit_id (User IP Address) = %s".format(expected.domain_sessionidx) in {
      actual.domain_sessionidx must_== expected.domain_sessionidx
    }

    // Page
    "have page_url (Page URL) = %s".format(expected.page_url) in {
      actual.page_url must_== expected.page_url
    }
    // Tracking a page view, so we have a page title
    "have page_title (Page Title) = %s".format(expected.page_title) in {
      actual.page_title must_== expected.page_title
    }
    "have page_referrer (Page Referrer) = %s".format(expected.page_referrer) in {
      actual.page_referrer must_== expected.page_referrer
    }

    // Page URL components
    "have page_urlscheme (Page URL) = %s".format(expected.page_urlscheme) in {
      actual.page_urlscheme must_== expected.page_urlscheme
    }
    // Tracking a page view, so we have a page title
    "have page_urlhost (Page URL Host) = %s".format(expected.page_urlhost) in {
      actual.page_urlhost must_== expected.page_urlhost
    }
    "have page_urlport (Page URL Port) = %s".format(expected.page_urlport) in {
      actual.page_urlport must_== expected.page_urlport
    }
    "have page_urlpath (Page URL Path) = %s".format(expected.page_urlpath) in {
      actual.page_urlpath must_== expected.page_urlpath
    }
    "have page_urlquery (Page URL Querystring) = %s".format(expected.page_urlquery) in {
      actual.page_urlquery must_== expected.page_urlquery
    }
    "have page_urlfragment (Page URL Fragment aka Anchor) = %s".format(expected.page_urlfragment) in {
      actual.page_urlfragment must_== expected.page_urlfragment
    }

    // Useragent
    "have useragent (User Agent) = %s".format(expected.useragent) in {
      actual.useragent must_== expected.useragent
    }

    // Browser (from user-agent)
    "have br_name (Browser Name) = %s".format(expected.br_name) in {
      actual.br_name must_== expected.br_name
    }
    "have br_family (Browser Family) = %s".format(expected.br_family) in {
      actual.br_family must_== expected.br_family
    }
    "have br_version (Browser Version) = %s".format(expected.br_version) in {
      actual.br_version must_== expected.br_version
    }
    "have br_type (Browser Type) = %s".format(expected.br_type) in {
      actual.br_type must_== expected.br_type
    }
    "have br_renderengine (Browser Rendering Engine) = %s".format(expected.br_renderengine) in {
      actual.br_renderengine must_== expected.br_renderengine
    }

    // Browser (from querystring)
    "have br_lang (Browser Lang) = %s".format(expected.br_lang) in {
      actual.br_lang must_== expected.br_lang
    }
    "have br_cookies (Browser Cookies Enabled?) = %s".format(expected.br_cookies) in {
      actual.br_cookies must_== expected.br_cookies
    }
    "have br_cookies_bt (Browser Cookies Enabled, Byte?) = %s".format(expected.br_cookies_bt) in {
      actual.br_cookies_bt must_== expected.br_cookies_bt
    }
    "have br_colordepth (Browser Color Depth) = %s".format(expected.br_colordepth) in {
      actual.br_colordepth must_== expected.br_colordepth
    }
    "have br_features (Browser Features) = %s".format(expected.br_features) in {
      // For some reason (Specs2) couldn't use implicit Java->Scala conversion here
      JavaConversions.asScalaBuffer(actual.br_features) must haveTheSameElementsAs(expected.br_features)
    }

    // Browser features
    "have br_features_pdf (Browser Feature PDF) = %s".format(expected.br_features_pdf) in {
      actual.br_features_pdf must_== expected.br_features_pdf
    }
    "have br_features_flash (Browser Feature Flash) = %s".format(expected.br_features_flash) in {
      actual.br_features_flash must_== expected.br_features_flash
    }
    "have br_features_java (Browser Feature Java) = %s".format(expected.br_features_java) in {
      actual.br_features_java must_== expected.br_features_java
    }
    "have br_features_director (Browser Feature Director) = %s".format(expected.br_features_director) in {
      actual.br_features_director must_== expected.br_features_director
    }
    "have br_features_quicktime (Browser Feature QuickTime) = %s".format(expected.br_features_quicktime) in {
      actual.br_features_quicktime must_== expected.br_features_quicktime
    }
    "have br_features_realplayer (Browser Feature RealPlayer) = %s".format(expected.br_features_realplayer) in {
      actual.br_features_realplayer must_== expected.br_features_realplayer
    }
    "have br_features_windowsmedia (Browser Feature Windows Media) = %s".format(expected.br_features_windowsmedia) in {
      actual.br_features_windowsmedia must_== expected.br_features_windowsmedia
    }
    "have br_features_gears (Browser Feature Google Gears) = %s".format(expected.br_features_gears) in {
      actual.br_features_gears must_== expected.br_features_gears
    }
    "have br_features_silverlight (Browser Feature Silverlight) = %s".format(expected.br_features_silverlight) in {
      actual.br_features_silverlight must_== expected.br_features_silverlight
    }
    "have br_viewwidth (Viewport Width) = %s".format(expected.br_viewwidth) in {
      actual.br_viewwidth must_== expected.br_viewwidth
    }
    "have br_viewheight (Viewport Height) = %s".format(expected.br_viewheight) in {
      actual.br_viewheight must_== expected.br_viewheight
    }

    // OS (from user-agent)
    "have os_name (OS Name) = %s".format(expected.os_name) in {
      actual.os_name must_== expected.os_name
    }
    "have os_family (OS Family) = %s".format(expected.os_family) in {
      actual.os_family must_== expected.os_family
    }
    "have os_manufacturer (OS Manufacturer) = %s".format(expected.os_manufacturer) in {
      actual.os_manufacturer must_== expected.os_manufacturer
    }
    "have os_timezone (OS Timezone) = %s".format(expected.os_timezone) in {
      actual.os_timezone must_== expected.os_timezone
    }

    // Device/Hardware (from user-agent)
    "have dvce_type (Device Type) = %s".format(expected.dvce_type) in {
      actual.dvce_type must_== expected.dvce_type
    }
    "have dvce_ismobile (Device Is Mobile?) = %s".format(expected.dvce_ismobile) in {
      actual.dvce_ismobile must_== expected.dvce_ismobile
    }
    "have dvce_ismobile_bt (Device Is Mobile, Byte?) = %s".format(expected.dvce_ismobile_bt) in {
      actual.dvce_ismobile_bt must_== expected.dvce_ismobile_bt
    }

    // Device (from querystring)
    "have dvce_screenwidth (Device Screen Width) = %s".format(expected.dvce_screenwidth) in {
      actual.dvce_screenwidth must_== expected.dvce_screenwidth
    }
    "have dvce_screenheight (Device Screen Height) = %s".format(expected.dvce_screenheight) in {
      actual.dvce_screenheight must_== expected.dvce_screenheight
    }

    // Document fields
    "have doc_charset (Document character set) = %s".format(expected.doc_charset) in {
      actual.doc_charset must_== expected.doc_charset
    }
    "have doc_width (Document Width) = %s".format(expected.doc_width) in {
      actual.doc_width must_== expected.doc_width
    }
    "have doc_height (Document Height) = %s".format(expected.doc_height) in {
      actual.doc_height must_== expected.doc_height
    }
  }
}


text:
using NUnit.Framework;
using Xamarin.Forms;
using Xamarin.CommunityToolkit.Markup.RightToLeft;

namespace Xamarin.CommunityToolkit.Markup.UnitTests
{
	[TestFixture]
	public class LabelExtensionsRightToLeftTests : MarkupBaseTestFixture<Label>
	{
		[Test]
		public void TextLeft()
			=> TestPropertiesSet(l => l?.TextLeft(), (Label.HorizontalTextAlignmentProperty, TextAlignment.Start, TextAlignment.End));

		[Test]
		public void TextRight()
			=> TestPropertiesSet(l => l?.TextRight(), (Label.HorizontalTextAlignmentProperty, TextAlignment.End, TextAlignment.Start));

		[Test]
		public void SupportDerivedFromLabel()
		{
			Assert.IsInstanceOf<DerivedFromLabel>(
				new DerivedFromLabel()
				.TextLeft()
				.TextRight());
		}

		class DerivedFromLabel : Label { }
	}
}


text:
copyright:
  years: 2015, 2016
lastupdated: "2016-10-27"

---

{:shortdesc: .shortdesc}
{:codeblock:.codeblock}

# Node.js-Ressourcen mit {{site.data.keyword.amashort}} schützen
{: #protecting-resources-nodejs}

Sie können das {{site.data.keyword.amashort}}-Server-SDK verwenden, um Ressourcen in Ihrer Node.js-App zu schützen.

## Vorbereitungen
{: #before-you-begin}

* Sie müssen mit der Entwicklung von Node.js-Anwendungen in {{site.data.keyword.Bluemix_notm}} vertraut sein. Weitere Informationen finden Sie im Abschnitt zum [Erstellen von Apps mit dem SDK für Node.js](https://console.{DomainName}/docs/runtimes/nodejs/index.html#nodejs_runtime).
* Das {{site.data.keyword.amashort}}-Server-SDK erfordert, dass Ihr Node.js-Server mit dem `Express`-Framework implementiert ist. Beachten Sie, dass es andere Frameworks gibt, die `Express`-Frameworks verwenden, wie zum Beispiel LoopBack. Sie können das {{site.data.keyword.amashort}}-Server-SDK mit einem beliebigen dieser Frameworks verwenden. Weitere Informationen zum Express-Framework finden Sie unter [Expressjs.com](http://expressjs.com/).

## Informationen zum Server-SDK
{: #about}

Das {{site.data.keyword.amashort}}-Server-SDK stellt die Passport-Strategie `MCABackendStrategy` für die Verwendung in Back-End-Anwendungen zur Verfügung, die in IBM {{site.data.keyword.Bluemix_notm}} bereitgestellt werden. Zum Schutz Ihrer App gegen unbefugten Zugriff und zum Erfassen von Überwachungsdaten müssen Sie Ihren Node.js-Server mit `MCABackendStrategy` instrumentieren. Das NPM-Modul `bms-mca-token-validation-strategy` stellt die Passport-Strategie `MCABackendStrategy` und eine Verifizierungsmethode bereit, um das von {{site.data.keyword.amashort}} ausgegebene Zugriffstoken und ID-Token zu validieren. Dieses Modul stellt außerdem automatisch Überwachungsdaten zu Sicherheitsereignissen bereit.

Das {{site.data.keyword.amashort}}-Server-SDK verwendet das `Passport`-Framework, um die Berechtigung umzusetzen.  Weitere Informationen finden Sie in [Passportjs.org](http://passportjs.org/).

## Server-SDK installieren
{: #protecting-resources-serversdk}

Öffnen Sie das Verzeichnis mit Ihrer Node.js-Anwendung in einer Befehlszeile und führen Sie die folgenden Befehle aus:

```
npm install -save express
npm install -save passport
npm install -save bms-mca-token-validation-strategy
```
{: codeblock}

## Ressourcen in Node.js schützen
{: #protecting-resources-nodesdk}

Das folgende Snippet demonstriert, wie `MCABackendStrategy` in einer einfachen Express-Anwendung zum Schutz der GET-Methoden für den Endpunkt `/protected` verwendet wird.

```JavaScript
var express = require('express');
var passport = require('passport');
var MCABackendStrategy = require('bms-mca-token-validation-strategy').MCABackendStrategy;

passport.use(new MCABackendStrategy());

var app = express();
app.use(passport.initialize());

app.get('/protected', passport.authenticate('mca-backend-strategy', {session: false }),
    function(request, response){
		console.log("Securty context", request.securityContext)
		response.send(200, "Success!");
    }
);

app.listen(process.env.PORT);
```
{: codeblock}


text:
<?xml version="1.0" encoding="utf-8"?>
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:clickable="false"
    /><!-- From: file:/E:/Work/APP/Notes-master/MaterialPreference/src/main/res/layout/mp_checkbox_preference.xml -->


text:
'''
The MIT License (MIT)

Copyright (c) <2018> <Mathias Lesche>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Check out https://www.python.org/dev/peps/pep-0008/#naming-conventions for naming
conventions

contact: mathias.lesche(at)tu-dresden.de
'''

''' python modules '''
import logging

from argparse import ArgumentParser as ArgumentParser
from argparse import RawDescriptionHelpFormatter

class MainLogger(object):
    def __init__(self, logtitle, streamh = True, fileh = False, logfilename = ''):
        self.__logfilename = logfilename
        self.__ch = ''
        self.__streamh = streamh
        self.__fh = ''
        self.__fileh = fileh
        self.set_logger(logtitle, streamh, fileh)

    def set_logger(self, logtitle, streamh, fileh):
        self.logger = logging.getLogger(logtitle)
        self.logger.setLevel(logging.DEBUG)
        self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt= '%m/%d/%Y %I:%M:%S %p')

        if fileh:
            fh = logging.FileHandler(self.__logfilename)
            fh.setLevel(logging.DEBUG)
            fh.setFormatter(self.formatter)
            self.logger.addHandler(fh)
            self.__fh = fh

        if streamh:
            ch = logging.StreamHandler()
            ch.setLevel(logging.INFO)
            ch.setFormatter(self.formatter)
            self.logger.addHandler(ch)
            self.__ch = ch

    def add_filelogger(self, filename):
        self.__logfilename = filename
        fh = logging.FileHandler(self.__logfilename)
        fh.setLevel(logging.DEBUG)
        fh.setFormatter(self.formatter)
        self.logger.addHandler(fh)
        self.__fh = fh
        self.__fileh = True

    def add_streamlogger(self):
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)
        ch.setFormatter(self.formatter)
        self.logger.addHandler(ch)
        self.__ch = ch
        self.__streamh = True

    def get_logger(self):
        return self.logger

    def close(self):
        if self.__fileh: self.logger.removeHandler(self.__fh)
        if self.__streamh: self.logger.removeHandler(self.__ch)

    def get_fileh(self):
        return self.__fileh

    fileh = property(get_fileh)

class Parser(object):
    def __init__(self):
        self.__parser = ArgumentParser(description="""
        Wrapper function for the snakemake pipeline
        """, formatter_class=RawDescriptionHelpFormatter,
        add_help = False, prog = 'snakemake_wrapper.py')

        self.initialiseParser()
        self.__drmaa = '--drmaa'
        self.__submission = ''

        self.__logger = logging.getLogger('snakemake.wrapper')
        self.parse()

    def initialiseParser(self):
        self.__parser.add_argument('-h', '--help', dest = 'h', help = 'Display help message', action= 'store_true')
        self.__wrapper = self.__parser.add_argument_group("snakemake specific arguments")
        self.__wrapper.add_argument('-d', '--drmaa', dest = 'use_drmaa', action = 'store_true', help = 'use DRMAA for submitting/controlling cluster jobs')
        #self.__parser.add_argument('-s', '--submission', dest='submission', metavar='STRING', choices = ('sge', 'slurm'), required = True, help = 'job submission system')
    #     self.__parser.add_argument('-f', '--files', type=str, metavar='FILE', dest='file', nargs= '+', help="list of fq-files(' ' separated)")
        #self.__parser.add_argument('-o', '--output', type=str, metavar='STRING', dest='output', required=True, help='id of the run which will be used as output folder')
        #self.__parser.add_argument('-u', '--undet', dest='undet', action='store_true', help='transfer undetermined')
        #self.__parser.add_argument("-e", "--email", dest = 'email', action= 'store_true', help= 'activates email notification')
        #self.__parser.add_argument('-q', '--qstat', type=str, metavar='STRING', dest='qstatname', default='tsp_fq', help='qstat name of the qsub job (default: tsp_fq)')

    def parse(self, inputstring = None):
        if inputstring == None:
            self.__options = self.__parser.parse_args()
        else:
            self.__options = self.__parser.parse_args(inputstring)

    def show_log(self, level, message):
        if level == 'debug':
            self.__logger.debug(message)
        elif level == 'info':
            self.__logger.info(message)
        elif level == 'warning':
            self.__logger.warning(message)
        elif level == 'error':
            self.__logger.error(message)
        elif level == 'critical':
            self.__logger.critical(message)

    def main(self):
        print(self.__options)
        print(self.__wrapper)

        if self.__options.h: self.__parser.print_help()

        #if not self.__options.use_drmaa: self.__drmaa = ''
        #print(self.__drmaa)
        #self.__submission = self.__options.submission
        #print(self.__submission)
        #self.__qstatname = self.__options.qstatname

        #for dirname in self.check_directory(self.__options.directory):
        #if dirname  != '': self.__files.extend(add_FilestoList_recursive(dirname, [], ('fastq.gz', 'fastq', 'fq.gz', 'fq', 'bam', 'sam')))
    ##     remove empty lines
        #self.__files = sorted(set(self.__files))
        #self.__files = [i for i in self.__files if i != '']

        #if len(self.__files) == 0:
        #self.show_log('error', "valid directory (-d) wasn't provided")
        #exit(2)
        #else:
        #self.show_log('info', '{0} files for transfer'.format(len(self.__files)))

        #self.__output = self.__options.output
        #self.show_log('info', 'storage folder on {0}: {1}'.format(Information.FQSTORAGE, self.__output))
        #self.__undet = self.__options.undet
        #self.show_log('info', 'transfer undetermined fq-files: {0}'.format(self.__undet))
        #sleep(3)

if __name__ == '__main__':
    mainlog = MainLogger('snakemake')
    parser = Parser()
    parser.main()

    mainlog.close()
    logging.shutdown()


text:
Vue.component('errors', {
	props: ['errors'],
	template: `

 [Line: {{ errors[index].line }}] Error: {{ errors[index].name }}

	`
})


text:
require 'spec_helper'

module Locomotive
  module Extensions
    module ContentEntry
      describe Csv do
        before(:each) do
          Locomotive::Site.any_instance.stubs(:create_default_pages!).returns(true)
          @content_type = FactoryGirl.build(:content_type)
          @content_type.entries_custom_fields.build label: 'Title', type: 'string'
          @content_type.entries_custom_fields.build label: 'Description', type: 'text'
          @content_type.entries_custom_fields.build label: 'Visible ?', type: 'boolean', name: 'visible'
          @content_type.valid?
          @content_type.send(:set_label_field)
          @content_type.save!
        end

        it 'should export nil fields as empty strings' do
          @entry = @content_type.entries.create!({
            title: 'Locomotive',
            visible: true
          })

          values = @entry.to_values
          expect(values).to eq(['Locomotive', '', true, I18n.l(@entry.created_at, format: :long)])
        end
      end
    end
  end
end


text:
package org.yi.happy.archive.key;

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

import org.junit.Test;
import org.yi.happy.archive.test_data.TestData;

/**
 * tests for {@link NameFullKey}.
 */
public class NameFullKeyTest {
    /**
     * convert a full name key to a locator key
     */
    @Test
    public void testToLocatorKey2() {
        FullKey key = TestData.KEY_NAME.getFullKey();
        assertTrue(key instanceof NameFullKey);

        LocatorKey have = key.toLocatorKey();
        LocatorKey want = TestData.KEY_NAME.getLocatorKey();
        assertEquals(want, have);
    }
}


text:
function [rvalue] = subsref(hIniFile, S)
% xini::subsref  - retrieve information via struct notation
%
% FORMAT:       inistruct = IniFileObject.STRUCT
%        or     section   = IniFileObject.Section
%        or     setting   = IniFileObject.Section.Setting
%
%    For multi-dimensional object arrays, the typical indexing is valid.
%    However, only singular objects may be used for instant

% Version:  v0.9c
% Build:    11050319
% Date:     May-02 2011, 6:17 PM EST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://neuroelf.net/
%
% Copyright (c) 2010, 2011, Jochen Weber
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in the
%       documentation and/or other materials provided with the distribution.
%     * Neither the name of Columbia University nor the
%       names of its contributors may be used to endorse or promote products
%       derived from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

% get method names for alias properties
global xinimeth;
if isempty(xinimeth)
    methods(hIniFile);
end

% argument check
if isempty(S)
    error( ...
        'xini:BadSubsRef', ...
        'S struct may not be empty.' ...
    );
end
slen  = length(S);
stype = S(1).type;
ssubs = S(1).subs;

% decide on kind of subscripting, first struct-like notation
switch stype, case {'.'}

    % allow cell with one char call type
    if iscell(ssubs) && ...
        numel(ssubs) == 1
        ssubs = ssubs{1};
    end

    % check for subscript type
    if ~ischar(ssubs) || ...
        isempty(ssubs)
        error( ...
            'xini:BadSubsRef', ...
            'Struct notation needs a non-empty char subscript.' ...
        );
    end

    % only works for singular object
    if numel(hIniFile) ~= 1
        error( ...
            'xini:InvalidFileID', ...
            'Struct notation only works for valid, singular objects.' ...
        );
    end

    % make content linear
    ssubs = ssubs(:)';

    % methods prevail
    mflds = fieldnames(xinimeth);
    mfound = find(strcmpi(ssubs, mflds));
    if ~isempty(mfound) && ...
        slen == 1 && ...
       (isempty(xinimeth.(mflds{mfound})) || ...
        xinimeth.(mflds{mfound}){1}(1) == '[')
        try
            rvalue = xini(hIniFile, lower(mflds{mfound}));
        catch ne_eo;
            rethrow(ne_eo);
        end
        return;
    end

    % allow rest only for "good" objects
    if hIniFile.L == 0
        error( ...
            'xini:InvalidObject', ...
            'Other calls/requests only allowed for non-root objects.' ...
        );
    end

    % complete or section ?
    if slen == 1

        % complete requested
        if strcmp(ssubs, 'STRUCT')
            rvalue = xini(hIniFile, 'getcomplete');

        % section requested
        else
            try
                rvalue = xini(hIniFile, 'getinisection', ssubs);
            catch ne_eo;
                rethrow(ne_eo);
            end
        end

    % setting or subsetting
    else

        % method call
        if ~isempty(mfound) && ...
           strcmp(S(2).type, '()')

            % check argument count
            oargs = xinimeth.(mflds{mfound});
            fargs = S(2).subs;
            if numel(fargs) > numel(oargs)
                error( ...
                    'xini:TooManyArguments', ...
                    'Too many arguments for call to %s.', ...
                    mflds{mfound} ...
                );
            end

            % check args
            argok = true;
            for ac = 1:numel(fargs)
                oarg = oargs{ac};
                if oarg(1) == '['
                    oarg(1) = [];
                end
                if isempty(regexpi(class(fargs{ac}), oarg))
                    argok = false;
                    break;
                end
            end
            if ~argok
                error( ...
                    'xini:BadArgument', ...
                    'Invalid arguments supplied in call to %s.', ...
                    mflds{mfound} ...
                );
            end
            if numel(fargs) < numel(oargs) && ...
                oargs{numel(fargs) + 1}(1) ~= '['
                error( ...
                    'xini:BadArgument', ...
                    'Missing %d. argument of type %s in call to %s.', ...
                    numel(fargs) + 1, ...
                    oargs{numel(fargs) + 1}(3:end - 1), ...
                    mflds{mfound} ...
                );
            end

            try
                rvalue = xini(hIniFile, lower(mflds{mfound}), fargs{:});
            catch ne_eo;
                rethrow(ne_eo);
            end
            return;

        % require second subscript to also be CHAR
        elseif ~strcmp(S(2).type, '.') || ...
           ~ischar(S(2).subs) || ...
            isempty(S(2).subs)
            error( ...
                'xini:BadSubsRef', ...
                'At least two CHAR struct subscripts are needed.' ...
            );
        end

        % get setting
        rvalue = xini(hIniFile, 'getinisetting', S(1).subs, S(2).subs);

        % subsetting requested
        if length(S) > 2
            try
                rvalue = subsref(rvalue, S(3:end));
            catch ne_eo;
                neuroelf_lasterr(ne_eo);
                error( ...
                    'xini:IllegalSubsRef', ...
                    'Couldn''t pass subsref to %s.%s.', ...
                    S(1).subs, ...
                    S(2).subs ...
                );
            end
        end
    end

% indexing requested
case {'()'}

    % we need non-empty cell subscript
    if ~iscell(ssubs) || ...
        isempty(ssubs)
        error( ...
            'xini:BadSubsRef', ...
            'Can''t index into xini matrix.' ...
        );
    end

    % convert hIniFile to struct
    sIniFile = struct(hIniFile);

    % try to retrieve subscripted matrix
    try
        subset   = subsref(sIniFile, S(1));
        hIniFile = class(subset, 'xini');
    catch ne_eo;
        error( ...
            'xini:BadSubsRef', ...
            'Invalid subscript (%s).', ...
            ne_eo.message ...
        );
    end

    % return sub-matrix if only one subscript
    if slen == 1
        rvalue = hIniFile;
        return;
    end

    if numel(hIniFile) ~= 1 || ...
       ~hIniFile.L
        error( ...
            'xini:InvalidFileID', ...
            'Further subscripting only works for valid, singular objects.' ...
        );
    end

    rvalue = subsref(hIniFile, S(2:end));

otherwise
    error( ...
        'xini:BadSubsRef', ...
        'Only struct notation allowed to retrieve values.' ...
    );
end


text:
using NewEdenMonitor.Data;
using NewEdenMonitor.Model;
using NewEdenMonitor.Utils;
using eZet.EveLib.EveXmlModule;
using eZet.EveLib.EveXmlModule.RequestHandlers;
using System.IO;
using System.Windows;

namespace NewEdenMonitor
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            InitializeDatabase();

            ((EveXmlRequestHandler)EveXml.Eve.RequestHandler).Cache = SqliteCache.Instance;
            ((EveXmlRequestHandler)EveXml.Map.RequestHandler).Cache = SqliteCache.Instance;
        }

        private void InitializeDatabase()
        {
            if (!Directory.Exists(Paths.DbLocation))
            {
                Directory.CreateDirectory(Paths.DbLocation);
            }

            if (!File.Exists(Paths.DbFullPath))
            {
                byte[] database = Resource.GetEmbeddedResource(Paths.DbFileName);

                using (var writer = new BinaryWriter(File.Open(Paths.DbFullPath, FileMode.Create)))
                {
                    writer.Write(database);
                }
            }
        }
    }
}


text:
using System.Collections.Generic;
using ALinq.SqlClient;

namespace ALinq.SqlClient
{
    internal class SqlSupersetValidator
    {
        // Fields
        private readonly List<SqlVisitor> validators = new List<SqlVisitor>();

        // Methods
        internal void AddValidator(SqlVisitor validator)
        {
            validators.Add(validator);
        }

        internal void Validate(SqlNode node)
        {
            foreach (SqlVisitor visitor in validators)
            {
                visitor.Visit(node);
            }
        }
    }
}


text:
import React, {
  forwardRef,
  FunctionComponent,
  MutableRefObject,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';
import {
  Animated,
  ScrollView,
  StyleSheet,
  View,
  Image,
  Dimensions,
  ImageSourcePropType,
  ScrollViewProps,
} from 'react-native';

type Props = ScrollViewProps & {
  children?: React.ElementType<any>;
  childrenStyle?: any;
  overlayColor: string;
  foregroundParallaxRatio: number;
  maxHeight: number;
  maxOverlayOpacity: number;
  minHeight: number;
  minOverlayOpacity: number;
  renderFixedForeground: () => React.ElementType<any>;
  renderForeground?: () => React.ElementType<any>;
  renderHeader: () => React.ElementType<any>;
  foregroundExtrapolate: 'clamp' | 'extend' | 'identity' | undefined;
  renderTouchableFixedForeground?: () => React.ElementType<any>;
  ScrollViewComponent: React.ElementType<ScrollViewProps>;
  scrollViewBackgroundColor: string;
  headerImage?: ImageSourcePropType;
  useNativeDriver: boolean;
  headerContainerStyle?: Object;
  fixedForegroundContainerStyles?: Object;
  disableHeaderGrow?: boolean;
};

export const ImageHeaderScrollView: FunctionComponent<Props> = forwardRef(
  (
    {
      overlayColor = 'black',
      disableHeaderGrow = false,
      foregroundParallaxRatio = 1,
      maxHeight = 125,
      maxOverlayOpacity = 0.3,
      minHeight = 80,
      minOverlayOpacity = 0,
      renderFixedForeground = () => <View />,
      foregroundExtrapolate = 'clamp',
      renderHeader: renderHeaderProps = () => <View />,
      ScrollViewComponent: ScrollViewComponentProps = ScrollView,
      scrollViewBackgroundColor = 'white',
      childrenStyle,
      style,
      contentContainerStyle,
      useNativeDriver,
      headerContainerStyle,
      headerImage,
      fixedForegroundContainerStyles,
      renderTouchableFixedForeground: renderTouchableFixedForegroundProps,
      renderForeground: renderForegroundProps,
      onScroll: onScrollProps,
      ...scrollViewProps
    },
    ref
  ) => {
    const scrollY = useRef(new Animated.Value(0)).current;
    const [pageY, setPageY] = useState(0);
    const containerRef = useRef<MutableRefObject<View>>(null).current;
    const scrollViewRef = useRef<MutableRefObject<ScrollView>>(null).current;

    useImperativeHandle(ref, () => ({
      getChildContext: () => {
        return {
          scrollY: scrollY,
          scrollPageY: pageY + minHeight,
        };
      },
    }));
    const interpolateOnImageHeight = (outputRange: Array<number>) => {
      const headerScrollDistance = maxHeight - minHeight;
      return scrollY.interpolate({
        inputRange: [0, headerScrollDistance],
        outputRange,
        extrapolate: 'clamp',
      });
    };

    const Header = () => {
      if (headerImage) {
        return (
          <Image
            source={headerImage}
            style={{
              height: maxHeight,
              width: Dimensions.get('window').width,
            }}
          />
        );
      }
      return renderHeaderProps();
    };

    const renderHeader = () => {
      const overlayOpacity = interpolateOnImageHeight([minOverlayOpacity, maxOverlayOpacity]);

      const headerScale = scrollY.interpolate({
        inputRange: [-maxHeight, 0],
        outputRange: [3, 1],
        extrapolate: 'clamp',
      });

      const headerTransformStyle = {
        height: maxHeight,
        transform: !disableHeaderGrow ? [{ scale: headerScale }] : undefined,
      };

      const overlayStyle = [
        styles.overlay,
        { opacity: overlayOpacity, backgroundColor: overlayColor },
      ];

      const disableOverlay = minOverlayOpacity === maxOverlayOpacity && maxOverlayOpacity === 0;

      return (
        <Animated.View style={[styles.header, headerTransformStyle, headerContainerStyle]}>
          {Header()}
          {!disableOverlay && <Animated.View style={overlayStyle} />}
          <View style={[styles.fixedForeground, fixedForegroundContainerStyles]}>
            {renderFixedForeground()}
          </View>
        </Animated.View>
      );
    };

    const renderForeground = () => {
      const headerTranslate = scrollY.interpolate({
        inputRange: [0, maxHeight * 2],
        outputRange: [0, -maxHeight * 2 * foregroundParallaxRatio],
        extrapolate: foregroundExtrapolate,
      });

      const headerTransformStyle = {
        height: maxHeight,
        transform: [{ translateY: headerTranslate }],
      };

      if (!renderForegroundProps) {
        return <View />;
      }

      return (
        <Animated.View style={[styles.header, headerTransformStyle]}>
          {renderForegroundProps()}
        </Animated.View>
      );
    };

    const renderTouchableFixedForeground = () => {
      const height = interpolateOnImageHeight([maxHeight, minHeight]);

      if (!renderTouchableFixedForegroundProps) {
        return <View />;
      }

      if (useNativeDriver) {
        if (__DEV__) {
          console.warn(
            'useNativeDriver=true and renderTouchableFixedForeground is not supported at the moment due to the animation of height unsupported with the native driver'
          );
        }
        return null;
      }

      return (
        <Animated.View style={[styles.header, styles.touchableFixedForeground, { height }]}>
          {renderTouchableFixedForegroundProps()}
        </Animated.View>
      );
    };

    const onContainerLayout = () => {
      if (!containerRef) {
        return;
      }
      containerRef.current.measureInWindow((_x, y) => {
        if (containerRef) {
          setPageY(y);
        }
      });
    };

    const onScroll = (e: any) => {
      if (onScrollProps) {
        onScrollProps(e);
      }
      scrollY.setValue(e.nativeEvent.contentOffset.y);
    };

    const ScrollViewComponent = useNativeDriver ? Animated.ScrollView : ScrollViewComponentProps;

    const inset = maxHeight - minHeight;

    return (
      <View
        style={[
          styles.container,
          {
            paddingTop: minHeight,
            backgroundColor: scrollViewBackgroundColor,
          },
        ]}
        ref={containerRef}
        onLayout={onContainerLayout}
      >
        {renderHeader()}
        <ScrollViewComponent
          scrollEventThrottle={useNativeDriver ? 1 : 16}
          ref={scrollViewRef}
          overScrollMode="never"
          {...scrollViewProps}
          contentContainerStyle={[
            {
              backgroundColor: scrollViewBackgroundColor,
              marginTop: inset,
              paddingBottom: inset,
            },
            contentContainerStyle,
            childrenStyle,
          ]}
          style={[styles.container, style]}
          onScroll={
            useNativeDriver
              ? Animated.event([{ nativeEvent: { contentOffset: { y: scrollY } } }], {
                  useNativeDriver: true,
                })
              : onScroll
          }
        />
        {renderTouchableFixedForeground()}
        {renderForeground()}
      </View>
    );
  }
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    overflow: 'hidden',
  },
  overlay: {
    position: 'absolute',
    top: 0,
    right: 0,
    left: 0,
    bottom: 0,
    zIndex: 100,
  },
  fixedForeground: {
    position: 'absolute',
    top: 0,
    right: 0,
    left: 0,
    bottom: 0,
    zIndex: 101,
  },
  touchableFixedForeground: {
    zIndex: 102,
  },
});