text:
import alpenglow as prs
import alpenglow.Getter as rs
import alpenglow.experiments
import alpenglow.evaluation
import pandas as pd
import math

class TestMemoryRankingLogger:
    def test_memoryRankingLogger(self):
        data = pd.read_csv(
            "python/test_alpenglow/test_data_4",
            sep=' ',
            header=None,
            names=['time', 'user', 'item', 'id', 'score', 'eval']
        )
        data['id'] += 5
        data['eval'] = 0
        data.loc[data.iloc[len(data) // 2:].index, 'eval'] = 1
        data.set_index('id')
        factorModelExperiment = alpenglow.experiments.FactorExperiment(
            top_k=100,
            seed=254938879,
            dimension=10,
            learning_rate=0.1,
            negative_rate=10
        )
        ranks = factorModelExperiment.run(data, verbose=True)
        assert set(list(ranks.columns)) == set(["time", "score", "user", "item", "prediction", "rank"])


text:
3D Game Engine
==

Modification of BennyQBD's (his youtube: thebennybox) 3D game engine in Java.

Original tutorial found here: https://www.youtube.com/playlist?list=PLEETnX-uPtBXP_B2yupUKlflXBznWIlL5

##Libraries Used##
- LWJGL (LightWeight Java Game Library, a type of OpenGL for Java)
- JBullet (Java port of Bullet physics)
- vecmath (included with JBullet)

##Build Dependencies##
- [JAVA](https://www.java.com/en/download/)
- BUILD TOOLCHAIN (Can be any one of the following, doesn't need to be all of them)
	- [Eclipse](http://eclipse.org/)
	- [NetBeans](https://netbeans.org/)
	- [IntelliJ IDEA](http://www.jetbrains.com/idea/)

##Simple Build Instructions##
###Using IDE###
- Open your preferred Java IDE, and create a new project.
- Import everything under the src folder as source files.
- Copy the res folder into your Java IDE's folder for your project.
- Copy the lib folder into it, adding any JARs inside of it into your build path.
- Make sure you set the LWJGL native libraries path to the folder of your OS inside of lib/natives/
- Build and run

##Additional Credits##
- Etay Meiri, for http://ogldev.atspace.co.uk/ which inspired the base code for the original repository.
- Everyone who's created or contributed to issues and pull requests, which make the project better!

redpajama_set_name: RedPajamaGithub


text:
* Reinitialize state when props change. (Fixes #5).

## 0.3.0

* Support for React 0.13.0.

## 0.2.0

* Add aria- attributes for accessibility.

### Breaking changes

* The values for order now are 'ascending' and 'descending' instead of 'asc' and 'desc'.

## 0.1.1

* Use css instead of less.
* Use MIT license.

## 0.1.0

* Initial release.


text:
interface MarkedStatic {
  (source: string): string;
}

/**
 * Typings for https://github.com/Trimidea/marked
 */
declare module "marked-extra" {
  var marked: MarkedStatic;
  export = marked;
}


text:
from contextlib import closing
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from ndlib.ndtype import *
from nduser.models import Channel
from ndproj.ndprojdb import NDProjectsDB
from ndproj.ndobject import NDObject
from ndramon import annotation
from webservices.ndwserror import NDWSError
import logging
logger=logging.getLogger("neurodata")

#RBTODO
# interface to check time -- a la dataset checkCube?
#        ( tstart >= self._timerange[0]) and ((tstart < tend) or tstart==0 and tend==0) and (tend <= (self._timerange[1]+1))):

class NDChannel(NDObject):

  def __init__(self, ch):
    """Constructor for a channel. It is a project and then some."""
    from ndproject import NDProject
    self.ch = ch
    self.pr = NDProject.fromName(self.project_name)
    with closing (NDProjectsDB.getProjDB(self.pr)) as db:
      self.db = db

  @classmethod
  def fromName(cls, pr, channel_name):
    try:
      pr = pr
      ch = Channel.objects.get(channel_name = channel_name, project=pr.project_name)
      return cls(ch)
    except Channel.DoesNotExist as e:
      logger.error("Channel {} does not exist. {}".format(channel_name, e))
      raise Channel.DoesNotExist

  @classmethod
  def fromJson(cls, project_name, channel):
    ch = Channel(**cls.deserialize(channel))
    ch.project_id = project_name
    return cls(ch)

  def save(self):
    try:
      self.ch.save()
    except Exception as e:
      raise

  def create(self):
    try:
      self.save()
      self.db.newNDChannel(self.channel_name)
    except NDWSError as e:
      self.ch.delete()
      raise
    except Exception as e:
      raise

  def delete(self):
    try:
      self.db.deleteNDChannel(self.channel_name)
      self.ch.delete()
    except Exception as e:
      raise

  def update(self):
    try:
      self.ch.save()
    except Exception as e:
      raise

  def serialize(self):
    return NDObject.serialize(self.ch)

  @property
  def channel_id(self):
    return self.ch.id

  @property
  def channel_name(self):
    return self.ch.channel_name

  @channel_name.setter
  def channel_name(self, value):
    # TODO KL check for unwanted chars here
    self.ch.channel_name = value

  @property
  def channel_description(self):
    return self.ch.channel_description

  @channel_description.setter
  def channel_description(self, value):
    self.ch.channel_description = value

  @property
  def project_name(self):
    return self.ch.project_id

  @project_name.setter
  def project_name(self, value):
    self.ch.project_id = value

  @property
  def channel_type(self):
    return self.ch.channel_type

  @channel_type.setter
  def channel_type(self, value):
    self.ch.channel_type = value

  @property
  def resolution(self):
    return self.ch.resolution

  @resolution.setter
  def resolution(self, value):
    self.ch.resolution = value

  @property
  def propagate(self):
    # TODO KL port logic
    return self.ch.propagate

  @propagate.setter
  def propagate(self, value):
    # TODO KL port logic
    self.ch.propagate = value
    self.update()

  @property
  def channel_datatype(self):
    return self.ch.channel_datatype

  @property
  def readonly(self):
    return self.ch.readonly

  @readonly.setter
  def readonly(self, value):
    self.ch.readonly = value

  @property
  def default(self):
    return self.ch.default

  @default.setter
  def default(self, value):
    self.ch.default = value

  @property
  def time_range(self):
    return [int(self.ch.starttime),int(self.ch.endtime)]

  @property
  def default_time_range(self):
    return [int(self.ch.starttime),int(self.ch.starttime+1)]

  @property
  def window_range(self):
    return [int(self.ch.startwindow),int(self.ch.endwindow)]

  @property
  def exceptions(self):
    return self.ch.exceptions

  @property
  def channel_model ( self ):
    return Channel.objects.get(channel_name=self.ch.channel_name, project=self.pr.project_name)

  def getExceptions ( self ):
    return self.ch.exceptions

  def isDefault (self):
    return self.ch.default

  def getS3IndexTable (self, resolution):
    """Return the S3 index table"""
    if self.pr.kvengine == MYSQL:
      return '{}_res{}_s3index'.format(self.ch.channel_name, resolution)

  def getIdsTable (self):
    if self.pr.nd_version == '0.0':
      return "ids"
    else:
      return "{}_ids".format(self.ch.channel_name)

  def getTable (self, resolution):
    """Return the appropriate table for the specified resolution"""
    if self.pr.nd_version == '0.0':
      return "res{}".format(resolution)
    else:
      if self.pr.kvengine == MYSQL:
        return "{}_res{}".format(self.ch.channel_name, resolution)
      elif self.pr.kvengine == CASSANDRA:
        return "{}_cuboids".format(self.ch.channel_name, 'cuboids')
      elif self.pr.kvengine == DYNAMODB:
        return "{}_{}_cuboids".format(self.pr.getProjectName(), self.ch.channel_name)

  def getNearIsoTable (self, resolution):
    """Return the appropriate table for the specified resolution"""
    if self.pr.nd_version == '0.0':
      return "res{}neariso".format(resolution)
    else:
      return "{}_res{}neariso".format(self.ch.channel_name, resolution)

  def getKVTable (self, resolution):
    """Return the appropriate KvPairs for the specified resolution"""
    if self.pr.nd_version == '0.0':
      return "kvpairs{}".format(resolution)
    else:
      return "{}_kvpairs{}".format(self.ch.channel_name, resolution)

  def getRamonTable(self):
    """Return the name of the ramon table"""
    if self.pr.kvengine == MYSQL:
      return "{}_ramon".format(self.ch.channel_name)
    else:
      logger.error("RAMON not support for KV Engine {}".format(self.pr.kvengine))
      raise NDWSError("RAMON not support for KV Engine {}".format(self.pr.kvengine))

  def getIdxTable (self, resolution):
    """Return the appropriate Index table for the specified resolution"""
    if self.pr.nd_version == '0.0':
      return "idx{}".format(resolution)
    else:
      if self.pr.kvengine == MYSQL:
        return "{}_idx{}".format(self.ch.channel_name, resolution)
      elif self.pr.kvengine == CASSANDRA:
        return "{}_indexes".format(self.ch.channel_name)
      elif self.pr.kvengine == DYNAMODB:
        return "{}_{}_indexes".format(self.pr.getProjectName(), self.ch.channel_name)

  def getAnnoTable (self, anno_type):
    """Return the appropriate table for the specified type"""
    if self.pr.nd_version == '0.0':
      return "{}".format(annotation.anno_dbtables[anno_type])
    else:
      return "{}_{}".format(self.ch.channel_name, annotation.anno_dbtables[anno_type])

  def getExceptionsTable (self, resolution):
    """Return the appropiate exceptions table for the specified resolution"""
    if self.pr.nd_version == '0.0':
      return "exc{}".format(resolution)
    else:
      return "{}_exc{}".format(self.ch.channel_name, resolution)

  def setPropagate (self, value):
    if value in [NOT_PROPAGATED, PROPAGATED]:
      self.ch.propagate = value
      self.setReadOnly ( READONLY_FALSE )
      self.ch.save()
    elif value in [UNDER_PROPAGATION]:
      self.ch.propagate = value
      self.setReadOnly ( READONLY_TRUE )
      self.ch.save()
    else:
      logger.error ( "Wrong Propagate Value {} for Channel {}".format( value, self.ch.channel_name ) )
      raise NDWSError ( "Wrong Propagate Value {} for Channel {}".format( value, self.ch.channel_name ) )

  def setReadOnly (self, value):
    if value in [READONLY_TRUE, READONLY_FALSE]:
      self.ch.readonly = value
      self.ch.save()
    else:
      logger.error ( "Wrong Readonly Value {} for Channel {}".format( value, self.channel_name ) )
      raise NDWSError ( "Wrong Readonly Value {} for Channel {}".format( value, self.ch.channel_name ) )

  def isPropagated (self):
    if self.ch.propagate in [PROPAGATED]:
      return True
    else:
      return False

  def deleteChannel(self):
    """Delete the channel project"""
    self.ch.delete()


text:
package org.apache.flink.streaming.api.functions.source;

import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.base.IntSerializer;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataInputViewStreamWrapper;
import org.apache.flink.core.memory.DataOutputViewStreamWrapper;
import org.apache.flink.runtime.state.FunctionInitializationContext;
import org.apache.flink.runtime.state.FunctionSnapshotContext;
import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
import org.apache.flink.streaming.api.operators.OutputTypeConfigurable;
import org.apache.flink.util.IterableUtils;
import org.apache.flink.util.Preconditions;

import javax.annotation.Nullable;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * A stream source function that returns a sequence of elements.
 *
 *
This source function serializes the elements using Flink's type information. That way, any
 * object transport using Java serialization will not be affected by the serializability of the
 * elements.
 *
 *
NOTE: This source has a parallelism of 1.
 *
 * @param <T> The type of elements returned by this function.
 */
@PublicEvolving
public class FromElementsFunction<T>
        implements SourceFunction<T>, CheckpointedFunction, OutputTypeConfigurable<T> {

    private static final long serialVersionUID = 1L;

    /** The (de)serializer to be used for the data elements. */
    private @Nullable TypeSerializer<T> serializer;

    /** The actual data elements, in serialized form. */
    private byte[] elementsSerialized;

    /** The number of serialized elements. */
    private final int numElements;

    /** The number of elements emitted already. */
    private volatile int numElementsEmitted;

    /** The number of elements to skip initially. */
    private volatile int numElementsToSkip;

    /** Flag to make the source cancelable. */
    private volatile boolean isRunning = true;

    private final transient Iterable<T> elements;

    private transient ListState<Integer> checkpointedState;

    @SafeVarargs
    public FromElementsFunction(TypeSerializer<T> serializer, T... elements) throws IOException {
        this(serializer, Arrays.asList(elements));
    }

    public FromElementsFunction(TypeSerializer<T> serializer, Iterable<T> elements)
            throws IOException {
        this.serializer = Preconditions.checkNotNull(serializer);
        this.elements = elements;
        this.numElements =
                elements instanceof Collection
                        ? ((Collection<T>) elements).size()
                        : (int) IterableUtils.toStream(elements).count();
        serializeElements();
    }

    @SafeVarargs
    public FromElementsFunction(T... elements) {
        this(Arrays.asList(elements));
    }

    public FromElementsFunction(Iterable<T> elements) {
        this.serializer = null;
        this.elements = elements;
        this.numElements =
                elements instanceof Collection
                        ? ((Collection<T>) elements).size()
                        : (int) IterableUtils.toStream(elements).count();
        checkIterable(elements, Object.class);
    }

    @VisibleForTesting
    @Nullable
    public TypeSerializer<T> getSerializer() {
        return serializer;
    }

    private void serializeElements() throws IOException {
        Preconditions.checkState(serializer != null, "serializer not set");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputViewStreamWrapper wrapper = new DataOutputViewStreamWrapper(baos);
        try {
            for (T element : elements) {
                serializer.serialize(element, wrapper);
            }
        } catch (Exception e) {
            throw new IOException("Serializing the source elements failed: " + e.getMessage(), e);
        }
        this.elementsSerialized = baos.toByteArray();
    }

    /**
     * Set element type and re-serialize element if required. Should only be called before
     * serialization/deserialization of this function.
     */
    @Override
    public void setOutputType(TypeInformation<T> outTypeInfo, ExecutionConfig executionConfig) {
        Preconditions.checkState(
                elements != null,
                "The output type should've been specified before shipping the graph to the cluster");
        checkIterable(elements, outTypeInfo.getTypeClass());
        TypeSerializer<T> newSerializer = outTypeInfo.createSerializer(executionConfig);
        if (Objects.equals(serializer, newSerializer)) {
            return;
        }
        serializer = newSerializer;
        try {
            serializeElements();
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    }

    @Override
    public void initializeState(FunctionInitializationContext context) throws Exception {
        Preconditions.checkState(
                this.checkpointedState == null,
                "The " + getClass().getSimpleName() + " has already been initialized.");

        this.checkpointedState =
                context.getOperatorStateStore()
                        .getListState(
                                new ListStateDescriptor<>(
                                        "from-elements-state", IntSerializer.INSTANCE));

        if (context.isRestored()) {
            List<Integer> retrievedStates = new ArrayList<>();
            for (Integer entry : this.checkpointedState.get()) {
                retrievedStates.add(entry);
            }

            // given that the parallelism of the function is 1, we can only have 1 state
            Preconditions.checkArgument(
                    retrievedStates.size() == 1,
                    getClass().getSimpleName() + " retrieved invalid state.");

            this.numElementsToSkip = retrievedStates.get(0);
        }
    }

    @Override
    public void run(SourceContext<T> ctx) throws Exception {
        Preconditions.checkState(serializer != null, "serializer not configured");
        ByteArrayInputStream bais = new ByteArrayInputStream(elementsSerialized);
        final DataInputView input = new DataInputViewStreamWrapper(bais);

        // if we are restored from a checkpoint and need to skip elements, skip them now.
        int toSkip = numElementsToSkip;
        if (toSkip > 0) {
            try {
                while (toSkip > 0) {
                    serializer.deserialize(input);
                    toSkip--;
                }
            } catch (Exception e) {
                throw new IOException(
                        "Failed to deserialize an element from the source. "
                                + "If you are using user-defined serialization (Value and Writable types), check the "
                                + "serialization functions.\nSerializer is "
                                + serializer,
                        e);
            }

            this.numElementsEmitted = this.numElementsToSkip;
        }

        final Object lock = ctx.getCheckpointLock();

        while (isRunning && numElementsEmitted < numElements) {
            T next;
            try {
                next = serializer.deserialize(input);
            } catch (Exception e) {
                throw new IOException(
                        "Failed to deserialize an element from the source. "
                                + "If you are using user-defined serialization (Value and Writable types), check the "
                                + "serialization functions.\nSerializer is "
                                + serializer,
                        e);
            }

            synchronized (lock) {
                ctx.collect(next);
                numElementsEmitted++;
            }
        }
    }

    @Override
    public void cancel() {
        isRunning = false;
    }

    /**
     * Gets the number of elements produced in total by this function.
     *
     * @return The number of elements produced in total.
     */
    public int getNumElements() {
        return numElements;
    }

    /**
     * Gets the number of elements emitted so far.
     *
     * @return The number of elements emitted so far.
     */
    public int getNumElementsEmitted() {
        return numElementsEmitted;
    }

    // ------------------------------------------------------------------------
    //  Checkpointing
    // ------------------------------------------------------------------------

    @Override
    public void snapshotState(FunctionSnapshotContext context) throws Exception {
        Preconditions.checkState(
                this.checkpointedState != null,
                "The " + getClass().getSimpleName() + " has not been properly initialized.");

        this.checkpointedState.clear();
        this.checkpointedState.add(this.numElementsEmitted);
    }

    // ------------------------------------------------------------------------
    //  Utilities
    // ------------------------------------------------------------------------

    /**
     * Verifies that all elements in the collection are non-null, and are of the given class, or a
     * subclass thereof.
     *
     * @param elements The collection to check.
     * @param viewedAs The class to which the elements must be assignable to.
     * @param <OUT> The generic type of the collection to be checked.
     */
    public static <OUT> void checkCollection(Collection<OUT> elements, Class<OUT> viewedAs) {
        checkIterable(elements, viewedAs);
    }

    private static <OUT> void checkIterable(Iterable<OUT> elements, Class<?> viewedAs) {
        for (OUT elem : elements) {
            if (elem == null) {
                throw new IllegalArgumentException("The collection contains a null element");
            }

            if (!viewedAs.isAssignableFrom(elem.getClass())) {
                throw new IllegalArgumentException(
                        "The elements in the collection are not all subclasses of "
                                + viewedAs.getCanonicalName());
            }
        }
    }
}


text:
pagesList=${pagesList:-"ReleaseOne"}

server=${server:-"https://bimaple.vijay:r0um2ni2@trac.assembla.com/bimaple-root"}

xsl=${xsl:-"export-wiki.xsl"}

docsDir=${docsDir:-"./wiki"}
mkdir -p $docsDir/media

tmp="/tmp/export-wiki"
rm -rf $tmp
mkdir $tmp

#####################################################################

# generated temp variables
tmpIndex="/tmp/tmp.xml"
pages=($pagesList)

# login
read -p "Wiki username: " uname
stty -echo
read -p "Wiki password: " passwd
stty echo
wget --no-check-certificate --save-cookies $tmp/wget_cookie --keep-session-cookies  --output-document $tmp/login https://$uname:$passwd@trac.assembla.com/bimaple-root

# process each page
echo "<pages>" > $tmpIndex
cnt=${#pages[@]}
for (( i = 0 ; i < cnt ; i++ ))
do
    wget --no-check-certificate --load-cookie $tmp/wget_cookie --output-document $tmp/${pages[$i]}.html ${server}/wiki/${pages[$i]}
    tidy -modify -utf8 $tmp/${pages[$i]}.html
    echo java -classpath /usr/share/java/xalan2.jar org.apache.xalan.xslt.Process -IN $tmp/${pages[$i]}.html -XSL $xsl -OUT $docsDir/${pages[$i]}.html
    #java -classpath /usr/share/java/xalan2.jar org.apache.xalan.xslt.Process -IN $tmp/${pages[$i]}.html -XSL $xsl -OUT $docsDir/${pages[$i]}.html
    xsltproc -o $docsDir/${pages[$i]}.html $xsl $tmp/${pages[$i]}.html
    echo "<page>${pages[$i]}</page>" >> $tmpIndex
done
echo "</pages>" >> $tmpIndex

# get the css and create the index page
wget --no-check-certificate --output-document $tmp/trac.css ${server}/chrome/common/css/trac.css
sed 's/url(..\//url(/' $tmp/trac.css > $docsDir/media/trac.css

wget --no-check-certificate --output-document $docsDir/media/extlink.gif ${server}/chrome/common/extlink.gif

# java -cp /usr/share/java/xalan2.jar org.apache.xalan.xslt.Process -IN $tmpIndex -XSL $xsl -OUT $docsDir/index.html

python export-images.py > $tmp/images
OLDIFS=$IFS
IFS='
'
for image in `cat $tmp/images`
do
    image_url=`echo $image | awk '{print $1}'`
    image_fname=`echo $image | awk '{print $2}'`
    wget --no-check-certificate --load-cookie $tmp/wget_cookie --output-document $docsDir/media/${image_fname} ${server}${image_url}
done
IFS=$OLDIFS

rm -rf $tmp

echo 'If you got "export-wiki.xsl (No such file or directory)" then run the script from its own directory.'


text:
        #
        Consensus Weights
        Advertised Bandwidth
        Guard Probability
        Middle Probability
        Exit Probability
        Nickname
        Fingerprint
        Exit
        Guard
        Country
        IPv4
        Autonomous System

      {% for result in results %}

        {{ result.index }}
        {{ result.cw }}
        {{ result.adv_bw }}
        {{ result.p_guard }}
        {{ result.p_middle }}
        {{ result.p_exit }}
        {{ result.nick }}

        {% if result.fp|length != 40 %}
        {{ result.fp }}
        {% else %}
        {{ result.fp[:8] }}
        {% endif %}
        {{ result.exit }}
        {{ result.guard }}
        {{ result.cc }}
        {{ result.primary_ip }}
        {{ result.as_info }}

      {% endfor %}


text:
package com.liang.weather.util;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.liang.weather.MainActivity;
import com.liang.weather.R;
import com.liang.weather.WeatherActivity;
import com.liang.weather.db.City;
import com.liang.weather.db.County;
import com.liang.weather.db.Province;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by liliang on 2017/2/4.
 */

public class ChooseAreaFragment extends Fragment {

    public static final int LEVEL_PROVINCE = 0;
    public static final int LEVEL_CITY = 1;
    public static final int LEVEL_COUNTY = 2;

    private ProgressDialog mProgressDialog;
    private TextView mTitleText;
    private Button mBackButton;
    private ListView mListView;
    private ArrayAdapter<String> mAdapter;

    private List<String> mDataList = new ArrayList<>();
    private List<Province> mProvinceList;
    private List<City> mCityList;
    private List<County> mCountyList;

    private Province selectedProvince;
    private City selectedCity;
    private int currentLevel;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.choose_area, container, false);
        mTitleText = (TextView) view.findViewById(R.id.title_text);
        mBackButton = (Button) view.findViewById(R.id.back_button);
        mListView = (ListView) view.findViewById(R.id.list_view);
        mAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1,
                mDataList);
        mListView.setAdapter(mAdapter);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mListView.setOnItemClickListener((parent, view, position, id) -> {
            if (currentLevel == LEVEL_PROVINCE) {
                selectedProvince = mProvinceList.get(position);
                queryCities();
            } else if (currentLevel == LEVEL_CITY) {
                selectedCity = mCityList.get(position);
                queryCounties();
            } else if (currentLevel == LEVEL_COUNTY) {
                String weatheId = mCountyList.get(position).getWeatherId();
                if (getActivity() instanceof MainActivity) {
                    Intent intent = new Intent(getActivity(), WeatherActivity.class);
                    intent.putExtra("weather_id", weatheId);
                    startActivity(intent);
                    getActivity().finish();
                } else if (getActivity() instanceof WeatherActivity) {
                    WeatherActivity activity = (WeatherActivity) getActivity();
                    activity.mDrawerLayout.closeDrawers();
                    activity.mSwipeRefreshLayout.setRefreshing(true);
                    activity.requestWeather(weatheId);
                }
            }
        });

        mBackButton.setOnClickListener(v -> {
            if (currentLevel == LEVEL_COUNTY) {
                queryCities();
            } else if (currentLevel == LEVEL_CITY) {
                queryProvinces();
            }
        });

        queryProvinces();
    }

    private void queryProvinces() {
        mTitleText.setText("中国");
        mBackButton.setVisibility(View.GONE);
        mProvinceList = DataSupport.findAll(Province.class);
        if (mProvinceList.size() > 0) {
            mDataList.clear();
            for (Province province : mProvinceList) {
                mDataList.add(province.getProvinceName());
            }
            mAdapter.notifyDataSetChanged();
            mListView.setSelection(0);
            currentLevel = LEVEL_PROVINCE;
        } else {
            String address = "http://guolin.tech/api/china";
            queryFromServer(address, "province");
        }
    }

    private void queryCities() {
        mTitleText.setText(selectedProvince.getProvinceName());
        mBackButton.setVisibility(View.VISIBLE);
        mCityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvince.getId()))
                .find(City.class);
        if (mCityList.size() > 0) {
            mDataList.clear();
            for (City city : mCityList) {
                mDataList.add(city.getCityName());
            }
            mAdapter.notifyDataSetChanged();
            mListView.setSelection(0);
            currentLevel = LEVEL_CITY;
        } else {
            int provinceCode = selectedProvince.getProvinceCode();
            String address = "http://guolin.tech/api/china/" + provinceCode;
            queryFromServer(address, "city");
        }
    }

    private void queryCounties() {
        mTitleText.setText(selectedCity.getCityName());
        mBackButton.setVisibility(View.VISIBLE);
        mCountyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId()))
                .find(County.class);
        if (mCountyList.size() > 0) {
            mDataList.clear();
            for (County county : mCountyList) {
                mDataList.add(county.getCountyName());
            }
            mAdapter.notifyDataSetChanged();
            mListView.setSelection(0);
            currentLevel = LEVEL_COUNTY;
        } else {
            int proinceCode = selectedProvince.getProvinceCode();
            int cityCode = selectedCity.getCityCode();
            String address = "http://guolin.tech/api/china/" + proinceCode + "/" + cityCode;
            queryFromServer(address, "county");
        }
    }

    private void queryFromServer(String address, final String type) {
        showProgressDialog();
        HttpUtil.sendOkHttpRequest(address, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getActivity().runOnUiThread(() -> {
                    closeProgressDialog();
                    Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseText = response.body().string();
                boolean result = false;
                if ("province".equals(type)) {
                    result = Utility.handleProvinceResponse(responseText);
                } else if ("city".equals(type)) {
                    result = Utility.handleCityResponse(responseText, selectedProvince.getId());
                } else if ("county".equals(type)) {
                    result = Utility.handleCountyResponse(responseText, selectedCity.getId());
                }

                if (result) {
                    getActivity().runOnUiThread(() -> {
                        closeProgressDialog();
                        if ("province".equals(type)) {
                            queryProvinces();
                        } else if ("city".equals(type)) {
                            queryCities();
                        } else if ("county".equals(type)) {
                            queryCounties();
                        }
                    });
                } else {
                    getActivity().runOnUiThread(() -> {
                        closeProgressDialog();
                        Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setMessage("正在加载...");
            mProgressDialog.setCanceledOnTouchOutside(false);
        }
        mProgressDialog.show();
    }

    private void closeProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }
}


text:
module Mutest
  # Abstract base class for test that might kill a mutation
  class Test
    include Anima.new(
      :expression,
      :id
    )
    include Adamantium::Flat

    # Identification string
    #
    # @return [String]
    alias_method :identification, :id
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Dell.Net.Http.Configurators {
    internal interface IHttpRequestMessageConfigurator {
        IHttpRequestMessageConfigurator Method(HttpMethod value);
        IHttpRequestMessageConfigurator Content(HttpContent value);
        IHttpRequestMessageConfigurator Properties(string name, object value);
        IHttpRequestMessageConfigurator Address(string value);
        IHttpRequestMessageConfigurator Header(string name, string value);
    }
}


text:
namespace JexusManager.Features.DefaultDocument
{
    using Microsoft.Web.Administration;

    public class DocumentItem : IItem<DocumentItem>
    {
        public ConfigurationElement Element { get; set; }
        public string Name { get; set; }
        public string Flag { get; set; }

        public DocumentItem(ConfigurationElement element)
        {
            Flag = element == null || element.IsLocallyStored ? "Local" : "Inherited";
            Element = element;
            if (element == null)
            {
                return;
            }

            Name = (string)element["value"];
        }

        public bool Equals(DocumentItem other)
        {
            return Match(other);
        }

        public void Apply()
        {
            Element["value"] = Name;
        }

        public bool Match(DocumentItem other)
        {
            return other != null && other.Name == Name;
        }
    }
}


text:
package com.haulmont.cuba.web.widgets.client.textfield;

import com.vaadin.shared.annotations.NoLayout;
import com.vaadin.shared.ui.textfield.TextFieldState;

public class CubaTextFieldState extends TextFieldState {

    @NoLayout
    public boolean readOnlyFocusable;

    @NoLayout
    public String caseConversion = "NONE";

    @NoLayout
    public String htmlName = null;
}


text:
package org.searchisko.api.rest;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.indices.IndexMissingException;
import org.searchisko.api.audit.annotation.AuditId;
import org.searchisko.api.model.QuerySettings;
import org.searchisko.api.rest.exception.BadFieldException;
import org.searchisko.api.rest.exception.NotAuthorizedException;
import org.searchisko.api.rest.exception.RequiredFieldException;
import org.searchisko.api.security.Role;
import org.searchisko.api.service.AuthenticationUtilService;
import org.searchisko.api.service.RegisteredQueryService;
import org.searchisko.api.service.SearchService;
import org.searchisko.api.service.StatsRecordType;
import org.searchisko.api.util.QuerySettingsParser;
import org.searchisko.api.util.SearchUtils;

import javax.annotation.security.PermitAll;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.searchisko.api.util.SearchUtils.collapseURLParams;

/**
 * Search REST API.
 *
 * @author Libor Krzyzanek
 * @author Vlastimil Elias (velias at redhat dot com)
 * @author Lukas Vlcek
 *
 */
@RequestScoped
@Path("/search")
@Produces(MediaType.APPLICATION_JSON)
public class SearchRestService extends RestServiceBase {

	@Inject
	protected SearchService searchService;

	@Inject
	protected RegisteredQueryService registeredQueryService;

	@Inject
	protected AuthenticationUtilService authenticationUtilService;

	@Inject
	protected QuerySettingsParser querySettingsParser;

	@GET
	@Path("/")
	@Produces(MediaType.APPLICATION_JSON)
	@PermitAll
	public Object search(@Context UriInfo uriInfo) {

		QuerySettings querySettings = null;
		try {

			if (uriInfo == null) {
				throw new BadFieldException("uriInfo");
			}
			MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
			querySettings = querySettingsParser.parseUriParams(params);
			String responseUuid = UUID.randomUUID().toString();

			SearchResponse searchResponse = searchService.performSearch(querySettings, responseUuid, StatsRecordType.SEARCH);
			Map<String, String> af = searchService.getIntervalValuesForDateHistogramAggregations(querySettings);
			af.put("uuid", responseUuid);
			return createResponse(searchResponse, af);
		} catch (IllegalArgumentException e) {
			throw new BadFieldException("unknown", e);
		} catch (IndexMissingException e) {
			return Response.status(Response.Status.NOT_FOUND).build();
		}
	}

	@GET
	@Path("/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	@PermitAll
	public Object searchRegisteredQuery(@PathParam("id") @AuditId String id, @Context UriInfo uriInfo) {
		try {
			if ((id = SearchUtils.trimToNull(id)) == null) {
				throw new RequiredFieldException("id");
			}

			Map<String, Object> registeredQuery = registeredQueryService.get(id);
			if (registeredQuery == null) {
				return Response.status(Response.Status.NOT_FOUND).build();
			}
			@SuppressWarnings("unchecked")
			List<String> roles = (List<String>) registeredQuery.get(RegisteredQueryService.FIELD_ALLOWED_ROLES);

			boolean allowed = true;
			if (roles != null && !roles.isEmpty() && !authenticationUtilService.isUserInRole(Role.ADMIN)) {
				if (!authenticationUtilService.isUserInAnyOfRoles(false, roles)) {
					allowed = false;
				}
			}

			if (allowed) {
				if (uriInfo == null) {
					throw new BadFieldException("uriInfo");
				}
				MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
				QuerySettings.Filters filters = querySettingsParser.parseUriParams(params).getFilters();
				Map<String, Object> collapsedParams = collapseURLParams(params);
				String responseUuid = UUID.randomUUID().toString();

				SearchResponse searchResponse = searchService.performSearchTemplate(id, collapsedParams, filters);
				Map<String, String> af = new HashMap<>();
				af.put("uuid", responseUuid);
				return createResponse(searchResponse, af);
			} else {
				throw new NotAuthorizedException("Client missing required role to execute this registered query.");
			}
		} catch (IllegalArgumentException e) {
			throw new BadFieldException("unknown", e);
		} catch (IndexMissingException e) {
			return Response.status(Response.Status.NOT_FOUND).build();
		}
	}

	@PUT
	@Path("/{search_result_uuid}/{hit_id}")
	@PermitAll
	public Object writeSearchHitUsedStatisticsRecordPUT(@PathParam("search_result_uuid") String uuid,
			@PathParam("hit_id") String contentId, @QueryParam("session_id") String sessionId) {
		return writeSearchHitUsedStatisticsRecord(uuid, contentId, sessionId);
	}

	@POST
	@Path("/{search_result_uuid}/{hit_id}")
	@PermitAll
	public Object writeSearchHitUsedStatisticsRecordPOST(@PathParam("search_result_uuid") String uuid,
			@PathParam("hit_id") String contentId, @QueryParam("session_id") String sessionId) {
		return writeSearchHitUsedStatisticsRecord(uuid, contentId, sessionId);
	}

	protected Object writeSearchHitUsedStatisticsRecord(@PathParam("search_result_uuid") String uuid,
			@PathParam("hit_id") String contentId, @QueryParam("session_id") String sessionId) {

		if ((uuid = SearchUtils.trimToNull(uuid)) == null) {
			throw new RequiredFieldException("search_result_uuid");
		}
		if ((contentId = SearchUtils.trimToNull(contentId)) == null) {
			throw new RequiredFieldException("hit_id");
		}
		sessionId = SearchUtils.trimToNull(sessionId);
		boolean result = searchService.writeSearchHitUsedStatisticsRecord(uuid, contentId, sessionId);
		// TODO: Search REST API: Return Bad Request Return code if result is false.
		return Response.ok(result ? "statistics record accepted" : "statistics record ignored").build();
	}
}


text:
package picard.sam.markduplicates;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import picard.PicardException;

import java.util.*;

/**
 * This class defines the individual test cases to run. The actual running of the test is done
 * by UmiAwareMarkDuplicatesWithMateCigarTester (see getTester).
 * @author fleharty
 */
public class UmiAwareMarkDuplicatesWithMateCigarTest extends SimpleMarkDuplicatesWithMateCigarTest {

    @Override
    protected UmiAwareMarkDuplicatesWithMateCigarTester getTester() {
        return new UmiAwareMarkDuplicatesWithMateCigarTester();
    }

    protected UmiAwareMarkDuplicatesWithMateCigarTester getTester(final boolean allowMissingUmis) {
        return new UmiAwareMarkDuplicatesWithMateCigarTester(allowMissingUmis);
    }

    @DataProvider(name = "testUmiSetsDataProvider")
    private Object[][] testUmiSetsDataProvider() {
        return new Object[][] {{
                // Test basic error correction using edit distance of 1
                Arrays.asList(new String[] {"AAAA", "AAAA", "ATTA", "AAAA", "AAAT"}), // Observed UMI
                Arrays.asList(new String[] {"AAAA", "AAAA", "ATTA", "AAAA", "AAAA"}), // Expected inferred UMI
                Arrays.asList(new Boolean[] {false, true, false, true, true}), // Should it be marked as duplicate?
                1 // Edit Distance to Join
        }, {
                // Test basic error correction using edit distance of 2
                Arrays.asList(new String[] {"AAAA", "AAAA", "ATTA", "AAAA", "AAAT"}),
                Arrays.asList(new String[] {"AAAA", "AAAA", "AAAA", "AAAA", "AAAA"}),
                Arrays.asList(new Boolean[] {false, true, true, true, true}),
                2
        }, {
                // Test basic error correction using edit distance of 1 where UMIs
                // form a chain in edit distance space so that a UMI with large
                // edit distance will get error corrected to a distant but linked (in edit space) UMI
                Arrays.asList(new String[] {"AAAA", "AAAA", "AAAT", "AAGT", "ACGT", "TCGT", "CCCC"}),
                Arrays.asList(new String[] {"AAAA", "AAAA", "AAAA", "AAAA", "AAAA", "AAAA", "CCCC"}),
                Arrays.asList(new Boolean[] {false, true, true, true, true, true, false}),
                1
        }, {
                // Test short UMIs
                Arrays.asList(new String[] {"A", "A", "T", "G", "G", "C", "C", "A"}),
                Arrays.asList(new String[] {"A", "A", "A", "A", "A", "A", "A", "A"}), // All UMIs should get corrected to A
                Arrays.asList(new Boolean[] {false, true, true, true, true, true, true, true}), // All mate pairs should be duplicates except the first
                1
        }, {
                // Test short UMIs with no allowance for errors
                Arrays.asList(new String[] {"A", "A", "T", "G", "G", "C", "C", "A"}),
                Arrays.asList(new String[] {"A", "A", "T", "G", "G", "C", "C", "A"}), // No UMIs should get corrected
                Arrays.asList(new Boolean[] {false, true, false, false, true, false, true, true}), // Only exactly duplicated UMIs will give rise to a new duplicate set
                0
        }, {
                // Test longish UMIs with relatively large allowance for error
                // UMIs "TTGACATCCA", "ATGCCATCGA", "AAGTCACCGT" should belong to the same duplicate set since
                // they are within edit distance of 4 of each other.  TTGACATCCA should be chosen as the inferred
                // UMI even though it only occurs once.  Since all UMIs only occur once, we choose the UMI that
                // is not marked as duplicate to be the inferred UMI.
                Arrays.asList(new String[] {"TTGACATCCA", "ATGCCATCGA", "AAGTCACCGT"}),
                Arrays.asList(new String[] {"TTGACATCCA", "TTGACATCCA", "TTGACATCCA"}), // All UMIs should get corrected to TTGACATCCA
                Arrays.asList(new Boolean[] {false, true, true}), // All mate pairs should be duplicates except the first
                4
        }, };
    }

    @DataProvider(name = "testBadUmiSetsDataProvider")
    private Object[][] testBadUmiSetsDataProvider() {
        return new Object[][] {{
                // The code should not support variable length UMIs, if we observe variable length UMIs
                // ensure that an exception is thrown.
                Arrays.asList(new String[] {"AAAA", "A"}),
                Arrays.asList(new String[] {"AAAA", "A"}),
                Arrays.asList(new Boolean[] {false, false}),
                4
        }, {
                // The code should not support variable length UMIs, if we observe variable length UMIs
                // ensure that an exception is thrown.
                // Arrays.asList(new String[] {"T", "GG"}),
                Arrays.asList(new String[] {"T", "GG"}),
                Arrays.asList(new String[] {"T", "GG"}),
                Arrays.asList(new Boolean[] {false, false}),
                1
        }, {
                // Test to make sure that we throw an exception with missing UMIs when allowMissingUmis is false
                // This throws an exception because the UMIs have differing lengths.
                Arrays.asList(new String[] {"TTGA", "TTAT", null}),
                Arrays.asList(new String[] {"TTGA", "TTAT", null}),
                Arrays.asList(new Boolean[] {false, false, false}),
                4
        }};
    }

    @DataProvider(name = "testEmptyUmiDataProvider")
    private Object[][] testEmptyUmiDataProvider() {
        return new Object[][] {{
                // Test to make sure we treat empty UMIs correctly when they are allowed
                Arrays.asList(new String[] {null, null, null}),
                Arrays.asList(new String[] {null, null, null}),
                Arrays.asList(new Boolean[] {false, true, true}),
                4
        }};
    }

    @Test(dataProvider = "testUmiSetsDataProvider")
    public void testUmi(List<String> umis, List<String> assignedUmi, final List<Boolean> isDuplicate, final int editDistanceToJoin) {
        UmiAwareMarkDuplicatesWithMateCigarTester tester = getTester(false);
        tester.addArg("MAX_EDIT_DISTANCE_TO_JOIN=" + editDistanceToJoin);

        for(int i = 0;i < umis.size();i++) {
            tester.addMatePairWithUmi(umis.get(i), assignedUmi.get(i), isDuplicate.get(i), isDuplicate.get(i));
        }
        tester.setExpectedAssignedUmis(assignedUmi).runTest();
    }

    @Test(dataProvider = "testEmptyUmiDataProvider")
    public void testEmptyUmis(List<String> umis, List<String> assignedUmi, final List<Boolean> isDuplicate, final int editDistanceToJoin) {
        UmiAwareMarkDuplicatesWithMateCigarTester tester = getTester(true);
        tester.addArg("MAX_EDIT_DISTANCE_TO_JOIN=" + editDistanceToJoin);

        for(int i = 0;i < umis.size();i++) {
            tester.addMatePairWithUmi(umis.get(i), assignedUmi.get(i), isDuplicate.get(i), isDuplicate.get(i));
        }
        tester.setExpectedAssignedUmis(assignedUmi).runTest();
    }

    @Test(dataProvider = "testBadUmiSetsDataProvider", expectedExceptions = PicardException.class)
    public void testBadUmis(List<String> umis, List<String> assignedUmi, final List<Boolean> isDuplicate, final int editDistanceToJoin) {
        UmiAwareMarkDuplicatesWithMateCigarTester tester = getTester(false);
        tester.addArg("MAX_EDIT_DISTANCE_TO_JOIN=" + editDistanceToJoin);

        for(int i = 0;i < umis.size();i++) {
            tester.addMatePairWithUmi(umis.get(i), assignedUmi.get(i), isDuplicate.get(i), isDuplicate.get(i));
        }
        tester.setExpectedAssignedUmis(assignedUmi).runTest();
    }
}