text:
\documentclass{emulateapj}
%\documentclass{aastex}
\submitted{{\it Submitted for publication in ApJL}}
\usepackage {graphicx}

\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphics}
\usepackage{epsfig}
\usepackage{float}
\bibliographystyle{apj}
\def\be{\begin{equation}}
\def\ee{\end{equation}}
\def\ba{\begin{eqnarray}}
\def\ea{\end{eqnarray}}

\newcommand{\documentname}{research note}
\newcommand{\avg}[1]{\langle{#1}\rangle}
\newcommand{\skel}{$\beta$-Skeleton}
\newcommand{\hMpc}{{\ifmmode{h^{-1}{\rm Mpc}}\else{$h^{-1}$Mpc }\fi}}
\newcommand{\hGpc}{{\ifmmode{h^{-1}{\rm Gpc}}\else{$h^{-1}$Gpc }\fi}}
\newcommand{\hmpc}{{\ifmmode{h^{-1}{\rm Mpc}}\else{$h^{-1}$Mpc }\fi}}
\newcommand{\hkpc}{{\ifmmode{h^{-1}{\rm kpc}}\else{$h^{-1}$kpc }\fi}}
\newcommand{\hMsun}{{\ifmmode{h^{-1}{\rm {M_{\odot}}}}\else{$h^{-1}{\rm{M_{\odot}}}$}\fi}}
\newcommand{\hmsun}{{\ifmmode{h^{-1}{\rm {M_{\odot}}}}\else{$h^{-1}{\rm{M_{\odot}}}$}\fi}}
\newcommand{\Msun}{{\ifmmode{{\rm {M_{\odot}}}}\else{${\rm{M_{\odot}}}$}\fi}}
\newcommand{\msun}{{\ifmmode{{\rm {M_{\odot}}}}\else{${\rm{M_{\odot}}}$}\fi}}
\newcommand{\kms}{{\ifmmode{{\mathrm{\,km\ s}^{-1}}}\else{\,km~s$^{-1}$}\fi}}
\newcommand{\bullb}{MACS J0025.4-1222}
\newcommand{\bulla}{1E0657---56}
\newcommand{\bullg}{SL2S J08544-0121}
\shorttitle{Bullet Groups}
\shortauthors{Fern\'andez-Trincado et al.}

\begin{document}

\title{The $\beta$-skeleton as a cosmological tool}
\author{J. E. Forero-Romero$^1$,
  Xiao-Dong Li$^2$  and Changbom Park$^{1}$}
\affil{$^1$ Departamento de F\'{i}sica, Universidad de los Andes,
  Cra. 1 No. 18A-10, Edificio Ip, Bogot\'a, Colombia\\
       $^2$ School of Physics, Korea Institute for Advanced Study,
  Heogiro 85, Seoul 130-722, Korea}
\email{je.forero@uniandes.edu.co}
\begin{abstract}
We explore the application of the $\beta$-skeleton, a concept from
geometric graph theory, as tool to describe the large scale structure
of the Universe.
\end{abstract}

\keywords{methods: numerical}

\section{Introduction}

\section{$\beta$-skeleton definition}

The \skel\ is a non-directed graph that can be defined on a set of
points in Euclidian space \citep{beta-def}.

We use the Neighboring Graph Library (NGL) \citep{Correa2011}to
compute the \skel\ of a set of points in 3D Euclidian space.  The NGL
is publicly available \footnote{{\texttt http://www.ngraph.org/}}.

\section{Simulation and Mock Catalogs}
\label{sec:simulation}

The data set is based on the Horizon Run 3 simulation data
\citep{HR3}. We use 27 mocks catalogs constructed to be close to the
number density of Luminous Red Galaxies in

\section{Numerical Experiments}
\label{sec:experiments}

We construct the \skel\ from mock catalogs in redshift space that were
reconstructed in real space using cosmological parameters
$\Omega_m^{\prime}$, $\Omega_\Lambda^\prime$ and $\omega^{\prime}$,
where the prime indicates that their values are, in general, not the
values used in the simulation. In this \documentname\ we perform a
first study where these values correspond to the simulation values.

After each mock is reconstructed into real space we filter the number
of points using two parameters. The minimal mass of halos to be
included, $M_{\rm min}$; and the fraction of halos above this mass
that will be left in the final sample, $f_{\rm in}$. We use the
following set of pairs of values for $(M_{\rm min}, f_{\rm in})=\{(,),(,),(,),(,),(,),(,)\}$, this selection fixes the total number of particles in the catalog
to $\{,\}$.

\section{Results}
\label{sec:results}

\section{Discussion}
\label{sec:discussion}

\section{Conclusions}
\label{sec:conclusions}

%\begin{figure*}
%\begin{center}
%\includegraphics[width=0.9\textwidth]{figure_1.eps}
%\end{center}
%\caption{}
%\end{figure*}

J.E.F-R acknowledges support from Vicerrector\'ia de
Investigaciones through a FAPA starting grant.

\bibliographystyle{apj}
\bibliography{references}

\end{document}


text:
export class Region {
    Id: string;
    Name: string;
}

redpajama_set_name: RedPajamaGithub


text:
package io.skysail.server.app.todos.todos.status.test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import io.skysail.server.app.todos.todos.status.Status;

import java.util.List;

import org.junit.Test;

public class StatusTest {

    @Test
    public void has_six_values() {
        Status[] values = Status.values();
        assertThat(values.length, is(6));
    }

    @Test
    public void testNextsOfNewStatus() {
        Status newStatus = Status.NEW;
        assertThat(newStatus.getNexts().size(), is(3));
        checkFollowUpStatuses(newStatus.getNexts());
    }

    @Test
    public void testNextsOfWipStatus() {
        Status newStatus = Status.WIP;
        assertThat(newStatus.getNexts().size(), is(2));
        checkFollowUpStatuses(newStatus.getNexts());
    }

    private void checkFollowUpStatuses(List<String> nextStatuses) {
        nextStatuses.stream().forEach(s -> Status.valueOf(s));
    }

}


text:
<!--
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.
-->
<ivy-module version="2.0">
  <info organisation="org.apache.lucene" module="core-demo"/>
  <configurations defaultconfmapping="compile->master">
    <conf name="compile" transitive="false"/>
  </configurations>
  <dependencies>
    <dependency org="javax.servlet" name="servlet-api" rev="${/javax.servlet/servlet-api}" conf="compile"/>
    <exclude org="*" ext="*" matcher="regexp" type="${ivy.exclude.types}"/>
  </dependencies>
</ivy-module>


text:
module Radiant
  class ExtensionMigrator < ActiveRecord::Migrator

    def self.migrate_extensions
      Extension.descendants.each do |ext|
        ext.migrator.migrate
      end
    end

    def initialize(extension)
      @extension = extension
      @migrations_path = @extension.root + '/db/migrate'
    end

    def migrate_with_extension_support(how = :up)
      raise StandardError.new("This database does not yet support migrations") unless ActiveRecord::Base.connection.supports_migrations?

      if [:up, :down].include?(how)
        @direction = how
        @target_version = nil
      else
        @target_version = how
        case
          when @target_version.nil?, current_version < @target_version
            @direction = :up
          when current_version > @target_version
            @direction = :down
          when current_version == @target_version
            return # You're on the right version
        end
      end

      migrate_without_extension_support
    end
    alias_method_chain :migrate, :extension_support

    def current_version
      @extension.meta.schema_version
    end

    def set_schema_version(version)
      @extension.meta.update_attributes(:schema_version => (down? ? version.to_i - 1 : version.to_i))
    end

  end

end


text:
package com.wildsmith.tank.menu;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.wildsmith.tank.R;
import com.wildsmith.tank.core.CoreTankPresenter;

public class TankLevelPresenter extends CoreTankPresenter {

    @Override
    protected void populateView(View view, Object item) {
        TankLevelItem tankLevel = ((TankLevelItem) item);

        ImageView imageView = (ImageView) view.findViewById(R.id.level_image);
        if (imageView != null) {
            imageView.setImageDrawable(tankLevel.getBackground());
        }

        TextView textView = (TextView) view.findViewById(R.id.level_description);
        if (textView != null) {
            textView.setText(tankLevel.getDescription());
        }

        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
    }

    @Override
    protected View inflateView(LayoutInflater inflater, ViewGroup parent) {
        View view = inflater.inflate(R.layout.tank_level_presenter_layout, parent, false);
        return view;
    }
}


text:
import urllib.request
import urllib.parse
import json

def get_result(number, birthday):
    cookie = "Hm_lvt_2be31ff7176cef646e9351788dc99055=1437448597; Hm_lpvt_2be31ff7176cef646e9351788dc99055=1437450310; PHPSESSID=fblmt7m54ehe2m0q65otdfbbg5"
    url = "http://www.5184.com/gk/common/get_mem.php"
    post_data = urllib.parse.urlencode({'csny': birthday, 'zkzh': number, 'yzm': ''})
    post_data = post_data.encode('utf-8')
    request = urllib.request.Request(url)

    # make the request header.
    request.add_header("Host", "www.5184.com")
    request.add_header("Connection", "keep-alive")
    request.add_header("Content-Length", "31")
    request.add_header("Accept", "application/json, text/javascript, */*; q=0.01")
    request.add_header("Origin", "http://www.5184.com")
    request.add_header("X-Requested-With", "XMLHttpRequest")
    request.add_header("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36")
    request.add_header("Content-Type", "application/x-www-form-urlencoded")
    request.add_header("Referer", "http://www.5184.com/gk/index.html")
    request.add_header("Accept-Encoding", "gzip,deflate,sdch")
    request.add_header("Accept-Language", "zh-CN,zh;q=0.8")
    request.add_header("Cookie", cookie)

    f = urllib.request.urlopen(request, post_data)
    r_data = f.read().decode('utf-8')

    score_json = json.loads(r_data)
    if 'student' in score_json.keys():
        student = score_json['student']
        score = score_json['course']
        file = open('score.txt', 'a')
        file.write(student['zkzh'] + ' ' + student['name'] + '>>>')
        for i in score:
            file.write(i['kmmc'] + ' ' + i['cj'] + ' ')
        file.write('\n')
        file.close()

get_result('1802101576' ,'9802')


text:
package org.apache.pig.backend.hadoop.executionengine.spark;

import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.pig.data.Tuple;
import org.apache.pig.tools.pigstats.PigStats;
import org.apache.pig.tools.pigstats.spark.SparkJobStats;
import org.apache.pig.tools.pigstats.spark.Spark1JobStats;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.PairFlatMapFunction;
import org.apache.spark.executor.TaskMetrics;
import org.apache.spark.rdd.RDD;
import org.apache.spark.scheduler.SparkListener;
import org.apache.spark.scheduler.SparkListenerApplicationEnd;
import org.apache.spark.scheduler.SparkListenerApplicationStart;
import org.apache.spark.scheduler.SparkListenerBlockManagerAdded;
import org.apache.spark.scheduler.SparkListenerBlockManagerRemoved;
import org.apache.spark.scheduler.SparkListenerBlockUpdated;
import org.apache.spark.scheduler.SparkListenerEnvironmentUpdate;
import org.apache.spark.scheduler.SparkListenerExecutorAdded;
import org.apache.spark.scheduler.SparkListenerExecutorMetricsUpdate;
import org.apache.spark.scheduler.SparkListenerExecutorRemoved;
import org.apache.spark.scheduler.SparkListenerJobEnd;
import org.apache.spark.scheduler.SparkListenerJobStart;
import org.apache.spark.scheduler.SparkListenerStageCompleted;
import org.apache.spark.scheduler.SparkListenerStageSubmitted;
import org.apache.spark.scheduler.SparkListenerTaskEnd;
import org.apache.spark.scheduler.SparkListenerTaskGettingResult;
import org.apache.spark.scheduler.SparkListenerTaskStart;
import org.apache.spark.scheduler.SparkListenerUnpersistRDD;
import scala.Tuple2;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Spark1Shims extends SparkShims {
    @Override
    public <T, R> FlatMapFunction<T, R> flatMapFunction(final FlatMapFunctionAdapter<T, R> function) {
        return new FlatMapFunction<T, R>() {
            @Override
            public Iterable<R> call(final T t) throws Exception {
                return new Iterable<R>() {
                    @Override
                    public Iterator<R> iterator() {
                        try {
                            return function.call(t);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                };

            }
        };
    }

    @Override
    public <T, K, V> PairFlatMapFunction<T, K, V> pairFlatMapFunction(final PairFlatMapFunctionAdapter<T, K, V> function) {
        return new PairFlatMapFunction<T, K, V>() {
            @Override
            public Iterable<Tuple2<K, V>> call(final T t) throws Exception {
                return new Iterable<Tuple2<K, V>>() {
                    @Override
                    public Iterator<Tuple2<K, V>> iterator() {
                        try {
                            return function.call(t);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                };

            }
        };
    }

    @Override
    public RDD<Tuple> coalesce(RDD<Tuple> rdd, int numPartitions, boolean shuffle) {
        return rdd.coalesce(numPartitions, shuffle, null);
    }

    @Override
    public SparkJobStats sparkJobStats(int jobId, PigStats.JobGraph plan, Configuration conf) {
        return new Spark1JobStats(jobId, plan, conf);
    }

    @Override
    public SparkJobStats sparkJobStats(String jobId, PigStats.JobGraph plan, Configuration conf) {
        return new Spark1JobStats(jobId, plan, conf);
    }

    @Override
    public <T> OptionalWrapper<T> wrapOptional(T tuple) {
        final Optional<T> t = (Optional<T>) tuple;

        return new OptionalWrapper<T>() {
            @Override
            public boolean isPresent() {
                return t.isPresent();
            }

            @Override
            public T get() {
                return t.get();
            }
        };
    }

    private static class JobMetricsListener implements SparkListener {
        private final Log LOG = LogFactory.getLog(JobMetricsListener.class);

        private Map<Integer, int[]> jobIdToStageId;
        private Map<Integer, Integer> stageIdToJobId;
        private Map<Integer, Map<String, List<TaskMetrics>>> allJobMetrics;
        private Set<Integer> finishedJobIds;

        JobMetricsListener(final Map<Integer, int[]> jobIdToStageId,
                           final Map<Integer, Integer> stageIdToJobId,
                           final Map<Integer, Map<String, List<TaskMetrics>>> allJobMetrics,
                           final Set<Integer> finishedJobIds) {
            this.jobIdToStageId = jobIdToStageId;
            this.stageIdToJobId = stageIdToJobId;
            this.allJobMetrics = allJobMetrics;
            this.finishedJobIds = finishedJobIds;
        }

        @Override
        public void onStageCompleted(SparkListenerStageCompleted stageCompleted) {
        }

        @Override
        public void onStageSubmitted(SparkListenerStageSubmitted stageSubmitted) {
        }

        @Override
        public void onTaskStart(SparkListenerTaskStart taskStart) {
        }

        @Override
        public void onTaskGettingResult(SparkListenerTaskGettingResult taskGettingResult) {
        }

        @Override
        public void onExecutorRemoved(SparkListenerExecutorRemoved executorRemoved) {
        }

        @Override
        public void onExecutorAdded(SparkListenerExecutorAdded executorAdded) {
        }

        @Override
        public void onBlockUpdated(SparkListenerBlockUpdated blockUpdated) {
        }

        @Override
        public synchronized void onTaskEnd(SparkListenerTaskEnd taskEnd) {
            int stageId = taskEnd.stageId();
            int stageAttemptId = taskEnd.stageAttemptId();
            String stageIdentifier = stageId + "_" + stageAttemptId;
            Integer jobId = stageIdToJobId.get(stageId);
            if (jobId == null) {
                LOG.warn("Cannot find job id for stage[" + stageId + "].");
            } else {
                Map<String, List<TaskMetrics>> jobMetrics = allJobMetrics.get(jobId);
                if (jobMetrics == null) {
                    jobMetrics = Maps.newHashMap();
                    allJobMetrics.put(jobId, jobMetrics);
                }
                List<TaskMetrics> stageMetrics = jobMetrics.get(stageIdentifier);
                if (stageMetrics == null) {
                    stageMetrics = Lists.newLinkedList();
                    jobMetrics.put(stageIdentifier, stageMetrics);
                }
                stageMetrics.add(taskEnd.taskMetrics());
            }
        }

        @Override
        public synchronized void onJobStart(SparkListenerJobStart jobStart) {
            int jobId = jobStart.jobId();
            int size = jobStart.stageIds().size();
            int[] intStageIds = new int[size];
            for (int i = 0; i < size; i++) {
                Integer stageId = (Integer) jobStart.stageIds().apply(i);
                intStageIds[i] = stageId;
                stageIdToJobId.put(stageId, jobId);
            }
            jobIdToStageId.put(jobId, intStageIds);
        }

        @Override
        public synchronized void onJobEnd(SparkListenerJobEnd jobEnd) {
            finishedJobIds.add(jobEnd.jobId());
            notify();
        }

        @Override
        public void onEnvironmentUpdate(SparkListenerEnvironmentUpdate environmentUpdate) {
        }

        @Override
        public void onBlockManagerAdded(SparkListenerBlockManagerAdded blockManagerAdded) {
        }

        @Override
        public void onBlockManagerRemoved(SparkListenerBlockManagerRemoved blockManagerRemoved) {
        }

        @Override
        public void onUnpersistRDD(SparkListenerUnpersistRDD unpersistRDD) {
        }

        @Override
        public void onApplicationStart(SparkListenerApplicationStart applicationStart) {
        }

        @Override
        public void onApplicationEnd(SparkListenerApplicationEnd applicationEnd) {
        }

        @Override
        public void onExecutorMetricsUpdate(SparkListenerExecutorMetricsUpdate executorMetricsUpdate) {
        }
    }

    @Override
    public SparkListener getJobMetricsListener(Map<Integer, int[]> jobIdToStageId,
                                                          Map<Integer, Integer> stageIdToJobId,
                                                          Map<Integer, Map<String, List<TaskMetrics>>> allJobMetrics,
                                                          Set<Integer> finishedJobIds) {
        return new JobMetricsListener(jobIdToStageId, stageIdToJobId, allJobMetrics, finishedJobIds);
    }

    @Override
    public void addSparkListener(SparkContext sc, SparkListener sparkListener) {
        sc.addSparkListener(sparkListener);
    }
}


text:
(() => {

    'use strict';

    angular.module('projectCmdo', [
        'projectCmdo.components',
        'projectCmdo.utils'
    ]);

    angular.module('projectCmdo.components', []);
    angular.module('projectCmdo.utils', []);

})();


text:
'use strict';

require('configureForRelayOSS');

jest.mock('warning');

const Relay = require('Relay');
const RelayQueryPath = require('RelayQueryPath');
const RelayRecordStore = require('RelayRecordStore');
const RelayRecordWriter = require('RelayRecordWriter');
const RelayTestUtils = require('RelayTestUtils');

describe('RelayQueryPath', () => {
  const {getNode, getVerbatimNode} = RelayTestUtils;
  let store;
  let writer;

  beforeEach(() => {
    jest.resetModuleRegistry();

    const records = {};
    store = new RelayRecordStore({records});
    writer = new RelayRecordWriter(records);

    jasmine.addMatchers(RelayTestUtils.matchers);
  });

  it('creates root paths', () => {
    const query = getNode(Relay.QL`
      query {
        node(id:"123") {
          id
        }
      }
    `);
    const fragment = Relay.QL`
      fragment on Node {
        id
        __typename
        name
      }
    `;

    const path = RelayQueryPath.create(query);
    expect(RelayQueryPath.getName(path)).toBe(query.getName());

    writer.putRecord('123', 'User');
    const pathQuery = RelayQueryPath.getQuery(store, path, getNode(fragment));
    expect(pathQuery).toEqualQueryRoot(getVerbatimNode(Relay.QL`
      query {
        node(id:"123") {
          ... on User {
            ${fragment}
            id
            __typename
          }
        }
      }
    `));
  });

  it('creates root paths for argument-less root calls with IDs', () => {
    const query = getNode(Relay.QL`
      query {
        me {
          id
        }
      }
    `);
    const fragment = Relay.QL`
      fragment on Actor {
        name
      }
    `;
    const path = RelayQueryPath.create(query);
    const pathQuery = RelayQueryPath.getQuery(store, path, getNode(fragment));
    expect(pathQuery).toEqualQueryRoot(getNode(Relay.QL`
      query {
        me {
          id
          ${fragment}
        }
      }
    `));
    expect(RelayQueryPath.getName(path)).toBe(query.getName());
  });

  it('creates root paths for argument-less root calls without IDs', () => {
    const query = getNode(Relay.QL`
      query {
        viewer {
          actor {
            id
          }
        }
      }
    `);
    const fragment = Relay.QL`
      fragment on Viewer {
        actor {
          name
        }
      }
    `;
    const path = RelayQueryPath.create(query);
    const pathQuery = RelayQueryPath.getQuery(store, path, getNode(fragment));
    expect(pathQuery).toEqualQueryRoot(getNode(Relay.QL`
      query {
        viewer {
          ${fragment}
        }
      }
    `));
    expect(RelayQueryPath.getName(path)).toBe(query.getName());
  });

  it('creates paths to non-refetchable fields', () => {
    const query = getNode(Relay.QL`
      query {
        node(id:"123") {
          id
        }
      }
    `);
    const address = getNode(Relay.QL`
      fragment on Actor {
        address {
          city
        }
      }
    `).getFieldByStorageKey('address');
    const city = getNode(Relay.QL`
      fragment on StreetAddress {
        city
      }
    `).getFieldByStorageKey('city');

    // address is not refetchable, has client ID
    writer.putRecord('123', 'User');
    const root = RelayQueryPath.create(query);
    const path = RelayQueryPath.getPath(root, address, 'client:1');
    const pathQuery = RelayQueryPath.getQuery(store, path, city);
    expect(pathQuery).toEqualQueryRoot(getVerbatimNode(Relay.QL`
      query {
        node(id:"123") {
          ... on User {
            id
            __typename
            address {
              city
            }
          }
        }
      }
    `));
    expect(RelayQueryPath.getName(path)).toBe(query.getName());
    expect(pathQuery.getName()).toBe(query.getName());
    expect(pathQuery.isAbstract()).toBe(true);
  });

  it('creates roots for refetchable fields', () => {
    const query = getNode(Relay.QL`
      query {
        viewer {
          actor {
            id
          }
        }
      }
    `);
    const actor = query.getFieldByStorageKey('actor');
    const fragment = Relay.QL`
      fragment on Node {
        name
      }
    `;

    // actor has an ID and is refetchable
    writer.putRecord('123', 'User');
    const root = RelayQueryPath.create(query);
    const path = RelayQueryPath.getPath(root, actor, '123');
    const pathQuery = RelayQueryPath.getQuery(store, path, getNode(fragment));
    expect(pathQuery).toEqualQueryRoot(getVerbatimNode(Relay.QL`
      query {
        node(id:"123") {
          ... on User {
            id
            __typename
            ... on Node {
              id
              __typename
              name
            }
          }
        }
      }
    `));
    expect(pathQuery.getName()).toBe(query.getName());
  });

  it('warns if the root record\'s type is unknown', () => {
    const query = getNode(Relay.QL`
      query {
        viewer {
          actor {
            id
          }
        }
      }
    `);
    const actor = query.getFieldByStorageKey('actor');
    const fragment = Relay.QL`
      fragment on Node {
        name
      }
    `;

    // actor has an ID and is refetchable, but the type of actor is unknown.
    const root = RelayQueryPath.create(query);
    const path = RelayQueryPath.getPath(root, actor, '123');
    const pathQuery = RelayQueryPath.getQuery(store, path, getNode(fragment));
    expect(pathQuery).toEqualQueryRoot(getVerbatimNode(Relay.QL`
      query {
        node(id:"123") {
          # not wrapped in a concrete fragment because the type is unknown.
          ... on Node {
            name
            id
            __typename
          }
          id
          __typename
        }
      }
    `));
    expect(pathQuery.getName()).toBe(query.getName());
    expect([
      'RelayQueryPath: No typename found for %s record `%s`. Generating a ' +
      'possibly invalid query.',
      'unknown',
      '123',
    ]).toBeWarnedNTimes(1);
  });

  describe('getPath()', () => {
    it('returns a client path given no `dataID`', () => {
      const query = getNode(Relay.QL`
        query {
          viewer {
            actor {
              id
            }
          }
        }
      `);
      const actor = query.getFieldByStorageKey('actor');
      const path = RelayQueryPath.getPath(query, actor);  // No `dataID`
      expect(path).toEqual({
        node: actor,
        parent: query,
        type: 'client',
      });
    });
  });
});


text:
<!DOCTYPE html>

Test for https://bugs.webkit.org/show_bug.cgi?id=26699

Instructions:

Drag the "Drag Me!" link below

Press escape

    Drag Me!


text:
namespace TraktApiSharp.Tests.Requests.Shows
{
    using FluentAssertions;
    using System.Collections;
    using System.Collections.Generic;
    using Traits;
    using TraktApiSharp.Enums;
    using TraktApiSharp.Requests.Parameters;
    using TraktApiSharp.Requests.Shows;
    using Xunit;

    [Category("Requests.Shows.Lists")]
    public class ShowsMostCollectedRequest_Tests
    {
        [Fact]
        public void Test_ShowsMostCollectedRequest_Has_Valid_UriTemplate()
        {
            var request = new ShowsMostCollectedRequest();
            request.UriTemplate.Should().Be("shows/collected{/period}{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications,networks,status}");
        }

        [Theory, ClassData(typeof(ShowsMostCollectedRequest_TestData))]
        public void Test_ShowsMostCollectedRequest_Returns_Valid_UriPathParameters(IDictionary<string, object> values,
                                                                                IDictionary<string, object> expected)
        {
            values.Should().NotBeNull().And.HaveCount(expected.Count);

            if (expected.Count > 0)
                values.Should().Contain(expected);
        }

        public class ShowsMostCollectedRequest_TestData : IEnumerable<object[]>
        {
            private static readonly TraktExtendedInfo _extendedInfo = new TraktExtendedInfo { Full = true };
            private static readonly TraktShowFilter _filter = new TraktShowFilter().WithYears(2005, 2016);
            private static readonly TraktTimePeriod _timePeriod = TraktTimePeriod.Monthly;
            private const int _page = 5;
            private const int _limit = 20;

            private static readonly ShowsMostCollectedRequest _request1 = new ShowsMostCollectedRequest();

            private static readonly ShowsMostCollectedRequest _request2 = new ShowsMostCollectedRequest
            {
                ExtendedInfo = _extendedInfo
            };

            private static readonly ShowsMostCollectedRequest _request3 = new ShowsMostCollectedRequest
            {
                Filter = _filter
            };

            private static readonly ShowsMostCollectedRequest _request4 = new ShowsMostCollectedRequest
            {
                Period = _timePeriod
            };

            private static readonly ShowsMostCollectedRequest _request5 = new ShowsMostCollectedRequest
            {
                Page = _page
            };

            private static readonly ShowsMostCollectedRequest _request6 = new ShowsMostCollectedRequest
            {
                Limit = _limit
            };

            private static readonly ShowsMostCollectedRequest _request7 = new ShowsMostCollectedRequest
            {
                ExtendedInfo = _extendedInfo,
                Filter = _filter
            };

            private static readonly ShowsMostCollectedRequest _request8 = new ShowsMostCollectedRequest
            {
                ExtendedInfo = _extendedInfo,
                Period = _timePeriod
            };

            private static readonly ShowsMostCollectedRequest _request9 = new ShowsMostCollectedRequest
            {
                ExtendedInfo = _extendedInfo,
                Page = _page
            };

            private static readonly ShowsMostCollectedRequest _request10 = new ShowsMostCollectedRequest
            {
                ExtendedInfo = _extendedInfo,
                Limit = _limit
            };

            private static readonly ShowsMostCollectedRequest _request11 = new ShowsMostCollectedRequest
            {
                ExtendedInfo = _extendedInfo,
                Page = _page,
                Limit = _limit
            };

            private static readonly ShowsMostCollectedRequest _request12 = new ShowsMostCollectedRequest
            {
                Filter = _filter,
                Period = _timePeriod
            };

            private static readonly ShowsMostCollectedRequest _request13 = new ShowsMostCollectedRequest
            {
                Filter = _filter,
                Page = _page
            };

            private static readonly ShowsMostCollectedRequest _request14 = new ShowsMostCollectedRequest
            {
                Filter = _filter,
                Limit = _limit
            };

            private static readonly ShowsMostCollectedRequest _request15 = new ShowsMostCollectedRequest
            {
                Filter = _filter,
                Page = _page,
                Limit = _limit
            };

            private static readonly ShowsMostCollectedRequest _request16 = new ShowsMostCollectedRequest
            {
                Period = _timePeriod,
                Page = _page
            };

            private static readonly ShowsMostCollectedRequest _request17 = new ShowsMostCollectedRequest
            {
                Period = _timePeriod,
                Limit = _limit
            };

            private static readonly ShowsMostCollectedRequest _request18 = new ShowsMostCollectedRequest
            {
                Period = _timePeriod,
                Page = _page,
                Limit = _limit
            };

            private static readonly ShowsMostCollectedRequest _request19 = new ShowsMostCollectedRequest
            {
                Page = _page,
                Limit = _limit
            };

            private static readonly ShowsMostCollectedRequest _request20 = new ShowsMostCollectedRequest
            {
                ExtendedInfo = _extendedInfo,
                Filter = _filter,
                Period = _timePeriod,
                Page = _page,
                Limit = _limit
            };

            private static readonly List<object[]> _data = new List<object[]>();

            public ShowsMostCollectedRequest_TestData()
            {
                SetupPathParamters();
            }

            private void SetupPathParamters()
            {
                var strExtendedInfo = _extendedInfo.ToString();
                var filterParameters = _filter.GetParameters();
                var strTimePeriod = _timePeriod.UriName;
                var strPage = _page.ToString();
                var strLimit = _limit.ToString();

                _data.Add(new object[] { _request1.GetUriPathParameters(), new Dictionary<string, object>() });

                _data.Add(new object[] { _request2.GetUriPathParameters(), new Dictionary<string, object>
                    {
                        ["extended"] = strExtendedInfo
                    }});

                _data.Add(new object[] { _request3.GetUriPathParameters(), new Dictionary<string, object>(filterParameters) });

                _data.Add(new object[] { _request4.GetUriPathParameters(), new Dictionary<string, object>
                    {
                        ["period"] = strTimePeriod
                    }});

                _data.Add(new object[] { _request5.GetUriPathParameters(), new Dictionary<string, object>
                    {
                        ["page"] = strPage
                    }});

                _data.Add(new object[] { _request6.GetUriPathParameters(), new Dictionary<string, object>
                    {
                        ["limit"] = strLimit
                    }});

                _data.Add(new object[] { _request7.GetUriPathParameters(), new Dictionary<string, object>(filterParameters)
                    {
                        ["extended"] = strExtendedInfo
                    }});

                _data.Add(new object[] { _request8.GetUriPathParameters(), new Dictionary<string, object>
                    {
                        ["extended"] = strExtendedInfo,
                        ["period"] = strTimePeriod
                    }});

                _data.Add(new object[] { _request9.GetUriPathParameters(), new Dictionary<string, object>
                    {
                        ["extended"] = strExtendedInfo,
                        ["page"] = strPage
                    }});

                _data.Add(new object[] { _request10.GetUriPathParameters(), new Dictionary<string, object>
                    {
                        ["extended"] = strExtendedInfo,
                        ["limit"] = strLimit
                    }});

                _data.Add(new object[] { _request11.GetUriPathParameters(), new Dictionary<string, object>
                    {
                        ["extended"] = strExtendedInfo,
                        ["page"] = strPage,
                        ["limit"] = strLimit
                    }});

                _data.Add(new object[] { _request12.GetUriPathParameters(), new Dictionary<string, object>(filterParameters)
                    {
                        ["period"] = strTimePeriod
                    }});

                _data.Add(new object[] { _request13.GetUriPathParameters(), new Dictionary<string, object>(filterParameters)
                    {
                        ["page"] = strPage
                    }});

                _data.Add(new object[] { _request14.GetUriPathParameters(), new Dictionary<string, object>(filterParameters)
                    {
                        ["limit"] = strLimit
                    }});

                _data.Add(new object[] { _request15.GetUriPathParameters(), new Dictionary<string, object>(filterParameters)
                    {
                        ["page"] = strPage,
                        ["limit"] = strLimit
                    }});

                _data.Add(new object[] { _request16.GetUriPathParameters(), new Dictionary<string, object>
                    {
                        ["period"] = strTimePeriod,
                        ["page"] = strPage
                    }});

                _data.Add(new object[] { _request17.GetUriPathParameters(), new Dictionary<string, object>
                    {
                        ["period"] = strTimePeriod,
                        ["limit"] = strLimit
                    }});

                _data.Add(new object[] { _request18.GetUriPathParameters(), new Dictionary<string, object>
                    {
                        ["period"] = strTimePeriod,
                        ["page"] = strPage,
                        ["limit"] = strLimit
                    }});

                _data.Add(new object[] { _request19.GetUriPathParameters(), new Dictionary<string, object>
                    {
                        ["page"] = strPage,
                        ["limit"] = strLimit
                    }});

                _data.Add(new object[] { _request20.GetUriPathParameters(), new Dictionary<string, object>(filterParameters)
                    {
                        ["extended"] = strExtendedInfo,
                        ["period"] = strTimePeriod,
                        ["page"] = strPage,
                        ["limit"] = strLimit
                    }});
            }

            public IEnumerator<object[]> GetEnumerator() => _data.GetEnumerator();

            IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
        }
    }
}


text:
#include "config.h"
#include "AppendNodeCommand.h"

#include "AXObjectCache.h"
#include "Document.h"
#include "htmlediting.h"

namespace WebCore {

AppendNodeCommand::AppendNodeCommand(PassRefPtr<ContainerNode> parent, PassRefPtr<Node> node)
    : SimpleEditCommand(parent->document())
    , m_parent(parent)
    , m_node(node)
{
    ASSERT(m_parent);
    ASSERT(m_node);
    ASSERT(!m_node->parentNode());

    ASSERT(m_parent->rendererIsEditable() || !m_parent->attached());
}

static void sendAXTextChangedIgnoringLineBreaks(Node* node, AXObjectCache::AXTextChange textChange)
{
    String nodeValue = node->nodeValue();
    // Don't consider linebreaks in this command
    if (nodeValue == "\n")
      return;

    node->document()->axObjectCache()->nodeTextChangeNotification(node, textChange, 0, nodeValue);
}

void AppendNodeCommand::doApply()
{
    if (!m_parent->rendererIsEditable() && m_parent->attached())
        return;

    ExceptionCode ec;
    m_parent->appendChild(m_node.get(), ec);

    if (AXObjectCache::accessibilityEnabled())
        sendAXTextChangedIgnoringLineBreaks(m_node.get(), AXObjectCache::AXTextInserted);
}

void AppendNodeCommand::doUnapply()
{
    if (!m_parent->rendererIsEditable())
        return;

    // Need to notify this before actually deleting the text
    if (AXObjectCache::accessibilityEnabled())
        sendAXTextChangedIgnoringLineBreaks(m_node.get(), AXObjectCache::AXTextDeleted);

    ExceptionCode ec;
    m_node->remove(ec);
}

#ifndef NDEBUG
void AppendNodeCommand::getNodesInCommand(HashSet<Node*>& nodes)
{
    addNodeAndDescendants(m_parent.get(), nodes);
    addNodeAndDescendants(m_node.get(), nodes);
}
#endif

} // namespace WebCore


text:
layout: page
title: "Bryan Loughry"
comments: true
description: "blanks"
keywords: "Bryan Loughry,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Arts and Sciences

**Classes taught**: APPM 2450

#### APPM 2450: CALCULUS 3 COMPUTER LAB

**Terms taught**: Fall 2006, Fall 2006

**Instructor rating**: 4.06

**Standard deviation in instructor rating**: 0.94

**Average grade** (4.0 scale): 0.0

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 1.56

**Standard deviation in workload** (raw): 0.56


text:
using google::protobuf::Descriptor;
using google::protobuf::DescriptorPool;
using google::protobuf::DynamicMessageFactory;
using google::protobuf::FieldDescriptor;
using google::protobuf::FileDescriptorSet;
using google::protobuf::Message;
using google::protobuf::MethodDescriptor;
using google::protobuf::Reflection;

using node::ObjectWrap;
using node::Buffer;

using std::map;
using std::string;
using std::vector;
using std::cerr;
using std::endl;

using v8::Array;
using v8::AccessorInfo;
using v8::Arguments;
using v8::Boolean;
using v8::Context;
using v8::Exception;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Integer;
using v8::Handle;
using v8::HandleScope;
using v8::InvocationCallback;
using v8::Local;
using v8::NamedPropertyGetter;
using v8::Number;
using v8::Object;
using v8::ObjectTemplate;
using v8::Persistent;
using v8::Script;
using v8::String;
using v8::ThrowException;
using v8::Value;
using v8::V8;

namespace protobuf_for_node {
  const char E_NO_ARRAY[] = "Not an array";
  const char E_NO_OBJECT[] = "Not an object";
  const char E_UNKNOWN_ENUM[] = "Unknown enum value";

  template <typename T>
  static T* UnwrapThis(const Arguments& args) {
    return ObjectWrap::Unwrap<T>(args.This());
  }

  template <typename T>
  static T* UnwrapThis(const AccessorInfo& args) {
    return ObjectWrap::Unwrap<T>(args.This());
  }

  Persistent<FunctionTemplate> SchemaTemplate;
  Persistent<FunctionTemplate> TypeTemplate;
  Persistent<FunctionTemplate> ParseTemplate;
  Persistent<FunctionTemplate> SerializeTemplate;

  class Schema : public ObjectWrap {
  public:
    Schema(Handle<Object> self, const DescriptorPool* pool)
        : pool_(pool) {
      factory_.SetDelegateToGeneratedFactory(true);
      self->SetInternalField(1, Array::New());
      Wrap(self);
    }

    virtual ~Schema() {
      if (pool_ != DescriptorPool::generated_pool())
        delete pool_;
    }

    class Type : public ObjectWrap {
    public:
      Schema* schema_;
      const Descriptor* descriptor_;

      Message* NewMessage() const {
        return schema_->NewMessage(descriptor_);
      }

      Handle<Function> Constructor() const {
        return handle_->GetInternalField(2).As<Function>();
      }

      Local<Object> NewObject(Handle<Value> properties) const {
        return Constructor()->NewInstance(1, &properties);
      }

      Type(Schema* schema, const Descriptor* descriptor, Handle<Object> self)
        : schema_(schema), descriptor_(descriptor) {
        // Generate functions for bulk conversion between a JS object
        // and an array in descriptor order:
        //   from = function(arr) { this.f0 = arr[0]; this.f1 = arr[1]; ... }
        //   to   = function()    { return [ this.f0, this.f1, ... ] }
        // This is faster than repeatedly calling Get/Set on a v8::Object.
        std::ostringstream from, to;
        from << "(function(arr) { if(arr) {";
        to << "(function() { return [ ";

        for (int i = 0; i < descriptor->field_count(); i++) {
          from <<
            "var x = arr[" << i << "]; "
            "if(x !== undefined) this['" <<
            descriptor->field(i)->camelcase_name() <<
            "'] = x; ";

          if (i > 0) to << ", ";
          to << "this['" << descriptor->field(i)->camelcase_name() << "']";
        }

        from << " }})";
        to << " ]; })";

        // managed type->schema link
        self->SetInternalField(1, schema_->handle_);

        Handle<Function> constructor =
          Script::Compile(String::New(from.str().c_str()))->Run().As<Function>();
        constructor->SetHiddenValue(String::New("type"), self);

        Handle<Function> bind =
          Script::Compile(String::New(
              "(function(self) {"
              "  var f = this;"
              "  return function(arg) {"
              "    return f.call(self, arg);"
              "  };"
              "})"))->Run().As<Function>();
        Handle<Value> arg = self;
        constructor->Set(String::New("parse"), bind->Call(ParseTemplate->GetFunction(), 1, &arg));
        constructor->Set(String::New("serialize"), bind->Call(SerializeTemplate->GetFunction(), 1, &arg));
        self->SetInternalField(2, constructor);
        self->SetInternalField(3, Script::Compile(String::New(to.str().c_str()))->Run());

        Wrap(self);
      }

#define GET(TYPE)                                                        \
      (index >= 0 ?                                                      \
       reflection->GetRepeated##TYPE(instance, field, index) :           \
       reflection->Get##TYPE(instance, field))

      static Handle<Value> ToJs(const Message& instance,
                                const Reflection* reflection,
                                const FieldDescriptor* field,
                                const Type* message_type,
                                int index) {
        switch (field->cpp_type()) {
        case FieldDescriptor::CPPTYPE_MESSAGE:
          return message_type->ToJs(GET(Message));
        case FieldDescriptor::CPPTYPE_STRING: {
          const string& value = GET(String);
          if (field->type() == FieldDescriptor::TYPE_BYTES) {
            return Buffer::New(const_cast<char *>(value.data()),
                               value.length())->handle_;
          } else {
            return String::New(value.data(), value.length());
          }
        }
        case FieldDescriptor::CPPTYPE_INT32:
          return Integer::New(GET(Int32));
        case FieldDescriptor::CPPTYPE_UINT32:
          return Integer::NewFromUnsigned(GET(UInt32));
        case FieldDescriptor::CPPTYPE_INT64:
          return Number::New(GET(Int64));
        case FieldDescriptor::CPPTYPE_UINT64:
          return Number::New(GET(UInt64));
        case FieldDescriptor::CPPTYPE_FLOAT:
          return Number::New(GET(Float));
        case FieldDescriptor::CPPTYPE_DOUBLE:
          return Number::New(GET(Double));
        case FieldDescriptor::CPPTYPE_BOOL:
          return Boolean::New(GET(Bool));
        case FieldDescriptor::CPPTYPE_ENUM:
          return String::New(GET(Enum)->name().c_str());
        }

        return Handle<Value>();  // NOTREACHED
      }
#undef GET

      Handle<Object> ToJs(const Message& instance) const {
        const Reflection* reflection = instance.GetReflection();
        const Descriptor* descriptor = instance.GetDescriptor();

        Handle<Array> properties = Array::New(descriptor->field_count());
        for (int i = 0; i < descriptor->field_count(); i++) {
          HandleScope scope;

          const FieldDescriptor* field = descriptor->field(i);
          bool repeated = field->is_repeated();
          if (repeated && !reflection->FieldSize(instance, field)) continue;
          if (!repeated && !reflection->HasField(instance, field)) continue;

          const Type* child_type =
            (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) ?
            schema_->GetType(field->message_type()) : NULL;

          Handle<Value> value;
          if (field->is_repeated()) {
            int size = reflection->FieldSize(instance, field);
            Handle<Array> array = Array::New(size);
            for (int j = 0; j < size; j++) {
              array->Set(j, ToJs(instance, reflection, field, child_type, j));
            }
            value = array;
          } else {
            value = ToJs(instance, reflection, field, child_type, -1);
          }

          properties->Set(i, value);
        }

        return NewObject(properties);
      }

      static Handle<Value> Parse(const Arguments& args) {
        Type* type = UnwrapThis<Type>(args);
        if (!Buffer::HasInstance(args[0])) {
          return ThrowException(Exception::TypeError(
             String::New("Argument should be a buffer")));
        }
        Local<Object> buffer_obj = args[0]->ToObject();

        Message* message = type->NewMessage();
        bool success =
          message->ParseFromArray(Buffer::Data(buffer_obj), Buffer::Length(buffer_obj));
        Handle<Value> result = success
          ? Handle<Value>(type->ToJs(*message))
                : v8::ThrowException(
              v8::Exception::Error(String::New("Malformed message")));

        delete message;
        return result;
      }

#define SET(TYPE, EXPR)                                                 \
      if (repeated) reflection->Add##TYPE(instance, field, EXPR);       \
      else reflection->Set##TYPE(instance, field, EXPR)

      static const char* ToProto(Message* instance,
                                 const FieldDescriptor* field,
                                 Handle<Value> value,
                                 const Type* type,
                                 bool repeated) {
        HandleScope scope;

        const Reflection* reflection = instance->GetReflection();
        switch (field->cpp_type()) {
        case FieldDescriptor::CPPTYPE_MESSAGE:
          if (!value->IsObject()) {
            return E_NO_OBJECT;
          }
          type->ToProto(repeated ?
                        reflection->AddMessage(instance, field) :
                        reflection->MutableMessage(instance, field),
                        value.As<Object>());
          break;
        case FieldDescriptor::CPPTYPE_STRING: {
          // Shortcutting Utf8value(buffer.toString())
          if (Buffer::HasInstance(value)) {
            Local<Object> buf = value->ToObject();
            SET(String, string(Buffer::Data(buf), Buffer::Length(buf)));
          } else {
            String::Utf8Value utf8(value);
            SET(String, string(*utf8, utf8.length()));
          }
          break;
        }
        case FieldDescriptor::CPPTYPE_INT32:
          SET(Int32, value->Int32Value());
          break;
        case FieldDescriptor::CPPTYPE_UINT32:
          SET(UInt32, value->Uint32Value());
          break;
        case FieldDescriptor::CPPTYPE_INT64:
          SET(Int64, value->NumberValue());
          break;
        case FieldDescriptor::CPPTYPE_UINT64:
          SET(UInt64, value->NumberValue());
          break;
        case FieldDescriptor::CPPTYPE_FLOAT:
          SET(Float, value->NumberValue());
          break;
        case FieldDescriptor::CPPTYPE_DOUBLE:
          SET(Double, value->NumberValue());
          break;
        case FieldDescriptor::CPPTYPE_BOOL:
          SET(Bool, value->BooleanValue());
          break;
        case FieldDescriptor::CPPTYPE_ENUM:
          const google::protobuf::EnumValueDescriptor* enum_value =
            value->IsNumber() ?
            field->enum_type()->FindValueByNumber(value->Int32Value()) :
            field->enum_type()->FindValueByName(*String::AsciiValue(value));
          if (!enum_value) {
            return E_UNKNOWN_ENUM;
          }
          SET(Enum, enum_value);
          break;
        }

        return NULL;
      }
#undef SET

      const char* ToProto(Message* instance, Handle<Object> src) const {
        Handle<Function> to_array = handle_->GetInternalField(3).As<Function>();
        Handle<Array> properties = to_array->Call(src, 0, NULL).As<Array>();

        const char* error = NULL;
        for (int i = 0; !error && i < descriptor_->field_count(); i++) {
          Handle<Value> value = properties->Get(i);
          if (value->IsUndefined() ||
              value->IsNull()) continue;

          const FieldDescriptor* field = descriptor_->field(i);
          const Type* child_type =
            (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) ?
            schema_->GetType(field->message_type()) : NULL;
          if (field->is_repeated()) {
            if(!value->IsArray()) {
              error = E_NO_ARRAY;
              continue;
            }

            Handle<Array> array = value.As<Array>();
            int length = array->Length();

            for (int j = 0; !error && j < length; j++) {
              error = ToProto(instance, field, array->Get(j), child_type, true);
            }
          } else {
            error = ToProto(instance, field, value, child_type, false);
          }
        }
        return error;
      }

      static Handle<Value> Serialize(const Arguments& args) {
        if (!args[0]->IsObject()) {
          return v8::ThrowException(
              v8::Exception::TypeError(v8::String::New("Not an object")));
        }

        Type* type = UnwrapThis<Type>(args);
        Message* message = type->NewMessage();
        const char* error = type->ToProto(message, args[0].As<Object>());
        Buffer* result;
        if (!error) {
          result = Buffer::New(message->ByteSize());
          message->SerializeWithCachedSizesToArray(
              (google::protobuf::uint8*)Buffer::Data(result->handle_));
        }
        delete message;

        return error
          ? v8::ThrowException(v8::Exception::Error(String::New(error)))
          : result->handle_;
      }

      static Handle<Value> ToString(const Arguments& args) {
        return String::New(UnwrapThis<Type>(args)->descriptor_->full_name().c_str());
      }
    };

    Message* NewMessage(const Descriptor* descriptor) {
      return factory_.GetPrototype(descriptor)->New();
    }

    Type* GetType(const Descriptor* descriptor) {
      Type* result = types_[descriptor];
      if (result) return result;

      result = types_[descriptor] =
        new Type(this, descriptor, TypeTemplate->GetFunction()->NewInstance());

      // managed schema->[type] link
      Handle<Array> types = handle_->GetInternalField(1).As<Array>();
      types->Set(types->Length(), result->handle_);
      return result;
    }

    const DescriptorPool* pool_;
    map<const Descriptor*, Type*> types_;
    DynamicMessageFactory factory_;

    static Handle<Value> GetType(const Local<String> name,
                                 const AccessorInfo& args) {
      Schema* schema = UnwrapThis<Schema>(args);
      const Descriptor* descriptor =
        schema->pool_->FindMessageTypeByName(*String::AsciiValue(name));

      return descriptor ?
        schema->GetType(descriptor)->Constructor() :
        Handle<Function>();
    }

    static Handle<Value> NewSchema(const Arguments& args) {
      if (!args.Length()) {
        return (new Schema(args.This(),
                           DescriptorPool::generated_pool()))->handle_;
      }

      if (!Buffer::HasInstance(args[0])) {
        return ThrowException(Exception::TypeError(
           String::New("Argument should be a buffer")));
      }
      Local<Object> buffer_obj = args[0]->ToObject();
      char *buffer_data = Buffer::Data(buffer_obj);
      size_t buffer_length = Buffer::Length(buffer_obj);

      FileDescriptorSet descriptors;
      if (!descriptors.ParseFromArray(buffer_data, buffer_length)) {
        return v8::ThrowException(
            v8::Exception::Error(String::New("Malformed descriptor")));
      }

      DescriptorPool* pool = new DescriptorPool;
      for (int i = 0; i < descriptors.file_size(); i++) {
        pool->BuildFile(descriptors.file(i));
      }

      return (new Schema(args.This(), pool))->handle_;
    }
  };

  static void Init() {
    if (!TypeTemplate.IsEmpty()) return;

    TypeTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New());
    TypeTemplate->SetClassName(String::New("Type"));
    // native self
    // owning schema (so GC can manage our lifecyle)
    // constructor
    // toArray
    TypeTemplate->InstanceTemplate()->SetInternalFieldCount(4);

    SchemaTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Schema::NewSchema));
    SchemaTemplate->SetClassName(String::New("Schema"));
    // native self
    // array of types (so GC can manage our lifecyle)
    SchemaTemplate->InstanceTemplate()->SetInternalFieldCount(2);
    SchemaTemplate->InstanceTemplate()->SetNamedPropertyHandler(Schema::GetType);

    ParseTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Schema::Type::Parse));
    SerializeTemplate = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Schema::Type::Serialize));
  }

  Local<Function> SchemaConstructor() {
    Init();
    return SchemaTemplate->GetFunction();
  }

}  // namespace protobuf_for_node

extern "C" void init(v8::Handle<v8::Object> target) {
  target->Set(v8::String::New("Schema"), protobuf_for_node::SchemaConstructor());
}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('target', '0005_auto_20190425_2129'),
    ]

    operations = [
        migrations.AddField(
            model_name='target',
            name='rules',
            field=models.TextField(blank=True, default="Make words of four letters or more using the letters in the grid.\nThe centre letter must be in every word. There's one nine-letter word. No plurals.  No\nproper nouns. No hyphenated words or words with diacritics. Our dictionary has\nabout 100k words."),
        ),
    ]


text:
"""
TripIt OAuth support.

This adds support for TripIt OAuth service. An application must
be registered first on TripIt and the settings TRIPIT_API_KEY
and TRIPIT_API_SECRET must be defined with the corresponding
values.

User screen name is used to generate username.
"""
from xml.dom import minidom

from social_auth.backends import ConsumerBasedOAuth, OAuthBackend

TRIPIT_CHECK_AUTH = 'https://api.tripit.com/v1/get/profile'

class TripItBackend(OAuthBackend):
    """TripIt OAuth authentication backend"""
    name = 'tripit'
    EXTRA_DATA = [('screen_name', 'screen_name')]

    def get_user_details(self, response):
        """Return user details from TripIt account"""
        try:
            first_name, last_name = response['name'].split(' ', 1)
        except ValueError:
            first_name = response['name']
            last_name = ''
        return {'username': response['screen_name'],
                'email': response['email'],
                'fullname': response['name'],
                'first_name': first_name,
                'last_name': last_name}

class TripItAuth(ConsumerBasedOAuth):
    """TripIt OAuth authentication mechanism"""
    AUTHORIZATION_URL = 'https://www.tripit.com/oauth/authorize'
    REQUEST_TOKEN_URL = 'https://api.tripit.com/oauth/request_token'
    ACCESS_TOKEN_URL = 'https://api.tripit.com/oauth/access_token'
    AUTH_BACKEND = TripItBackend
    SETTINGS_KEY_NAME = 'TRIPIT_API_KEY'
    SETTINGS_SECRET_NAME = 'TRIPIT_API_SECRET'

    def user_data(self, access_token, *args, **kwargs):
        """Return user data provided"""
        request = self.oauth_request(access_token, TRIPIT_CHECK_AUTH)
        content = self.fetch_response(request)
        try:
            dom = minidom.parseString(content)
        except ValueError:
            return None

        return {
            'id': dom.getElementsByTagName('Profile')[0].getAttribute('ref'),
            'name': dom.getElementsByTagName(
                'public_display_name')[0].childNodes[0].data,
            'screen_name': dom.getElementsByTagName(
                'screen_name')[0].childNodes[0].data,
            'email': dom.getElementsByTagName('is_primary')[0]
                            .parentNode.getElementsByTagName('address')[0]
                                .childNodes[0].data,
        }

# Backend definition
BACKENDS = {
    'tripit': TripItAuth,
}


text:
require "active_support/concern"

module CoreExt
  module Hash

    ##
    # DSL для удобного создания хешей.
    #
    module Builder
      extend ActiveSupport::Concern

      # Класс обёртка над элементом массива.
      class Builder
        ##
        # @param [Hash] root хеш, над которым проводятся манипуляции
        # @param [Array] path путь в root к текущему элементу
        #
        # @yieldparam [Builder] self
        #
        def initialize( root, path = [], &block )
          raise ArgumentError, "Hash expected" unless root.is_a? ::Hash
          raise ArgumentError, "Array expected" unless path.is_a? ::Array

          @root, @path = root, path
          yield self if block_given?
        end

        ##
        # Возвращает значение текущего элемента.
        #
        def __get_value
          # Крайний случай: 1 уровень хеша
          return @root if @path.empty?

          current_node = @root

          @path[ 0 ... -1 ].each do |node_name|
            current_node = current_node[ node_name ]
            return nil unless current_node.is_a? Hash
          end

          current_node[ @path.last ]
        end

        ##
        # Устанавливает значение элемента.
        #
        # @param [Object] key название
        # @param [Object] value значение
        #
        def __set_value( key, value )
          # Крайний случай: 1 уровень хеша
          @root[ key ] = value and return if @path.empty?

          current_node = @root

          @path.each do |node_name|
            current_node[ node_name ] = {} unless current_node[ node_name ].is_a? ::Hash
            current_node = current_node[ node_name ]
          end

          current_node[ key ] = value
        end

        ##
        # Возвращает дочерний элемент.
        #
        # @param [Object] key ключ
        # @return [Builder]
        #
        def []( key )
          self.class.new( @root, @path + [ key ] )
        end

        # @see #__set_value
        def []=( key, value )
          __set_value( key, value )
        end

        ##
        # Переопределяем method_missing таким образом, чтобы он вызывал {#[]}
        # и {#[]=} с именем метода в качестве названия.
        #
        def method_missing( name, *args )
          # setter?
          if name =~ /[^=]=$/
            raise ArgumentError unless args.count == 1
            self[ name.to_s.chop.to_sym ] = args.first
          else
            raise ArgumentError unless args.empty?
            self[ name ]
          end
        end
      end

      module InstanceMethods
        # @see CoreExt::Hash::Builder::ClassMethods#build
        def build( &block )
          raise ArgumentError, "block expected" unless block_given?
          Builder.new( self, &block )
          self
        end
      end

      module ClassMethods
        ##
        # Создаёт хеш.
        # @yieldparam [CoreExt::Hash::Builder::Builder]
        # @return [Hash]
        #
        # @example
        #   hash = Hash.build do |h|
        #     h.a = 1
        #     h.b = 2
        #     h.c.d = 3
        #     h[ "some_string" ] = 4
        #   end
        #
        #   hash #=> { a: 1, b: 2, c: { d: 3 }, "some string": 4 }
        #
        def build( &block )
          raise ArgumentError, "block expected" unless block_given?
          Builder.new( hash = self.new, &block )
          hash
        end
      end
    end
  end
end


text:
//
//  PrettySegmentedTableViewCell.m
//  PrettyExample
//
//  Created by Víctor on 13/03/12.

// Copyright (c) 2012 Victor Pena Placer (@vicpenap)
// http://www.victorpena.es/
//
//
// 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.

#import "PrettySegmentedControlTableViewCell.h"

@implementation PrettySegmentedControlTableViewCell
@synthesize selectedIndex;

- (void) updateButtonActions
{
    /* a bit of hacking. In this case, we don't care if the user drags the finger
     or not, we still want te segment to be selected. */
    [(UIButton *)self.customView removeTarget:self.customView
                                       action:@selector(hardDeselect)
                             forControlEvents:UIControlEventTouchDragInside | UIControlEventTouchDragOutside | UIControlEventTouchUpOutside];
    [(UIButton *)self.customView addTarget:self.customView action:@selector(fireButtonAction:event:) forControlEvents:UIControlEventTouchUpOutside];
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        selectedIndex = -1;

        UIColor *tmp = [self.selectionGradientStartColor retain];
        self.selectionGradientStartColor = self.selectionGradientEndColor;
        self.selectionGradientEndColor = tmp;
        [tmp release];

        self.textLabel.shadowColor = [UIColor blackColor];
        self.textLabel.shadowOffset = CGSizeMake(0, 1);

        self.shadowOnlyOnSelected = YES;

        [self updateButtonActions];
        [self setActionBlock:nil]; // forces tracking the selected index
    }
    return self;
}

- (void) _setSelectedIndex:(NSInteger)sselectedIndex notifySuper:(BOOL)notify
{
    selectedIndex = sselectedIndex;

    if (notify)
    {
        [super selectIndex:selectedIndex];
    }
}

- (void) restartSelectedIndex {
    [self _setSelectedIndex:0 notifySuper:YES];
}

- (void) setSelectedIndex:(NSInteger)sselectedIndex {
    [self _setSelectedIndex:sselectedIndex notifySuper:YES];
}

- (NSArray *) titles {
    return self.texts;
}

- (void) setTitles:(NSArray *)titles {
    self.numberOfElements = [titles count];
    for (int i = 0; i < self.numberOfElements; i++) {
        [self setText:[titles objectAtIndex:i] atIndex:i];
    }
    [self restartSelectedIndex];
}

- (void) setActionBlock:(void (^)(NSIndexPath *indexPath, int sselectedIndex))actionBlock {
    [super setActionBlock:^(NSIndexPath *indexPath, int sselectedIndex) {
        [self _setSelectedIndex:sselectedIndex notifySuper:NO];

        if (actionBlock)
        {
            actionBlock(indexPath, sselectedIndex);
        }
    }];
}

@end


text:
package eu.scasefp7.eclipse.core.ui.wizards;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.dialogs.PatternFilter;

import eu.scasefp7.eclipse.core.ui.preferences.DomainBoldLabelProvider;
import eu.scasefp7.eclipse.core.ui.preferences.DomainContentProvider;
import eu.scasefp7.eclipse.core.ui.preferences.internal.DomainEntry;
import eu.scasefp7.eclipse.core.ui.preferences.internal.IProjectDomains;
import eu.scasefp7.eclipse.core.ui.preferences.DomainBoldLabelProvider;

public class ProjectDomainWizardPage extends WizardPage {

	private static final String DOMAIN_PROPERTY = "eu.scasefp7.eclipse.core.projectDomain";
	private static final int DOMAIN_DEFAULT = -1;

	private Label domainLabel;

	private boolean locked;

	private Composite composite;
	private Composite cmpLabels;

	protected DomainFilteredTree filteredTree;
	protected TreeViewer treeViewer;

	protected ProjectDomainWizardPage(String pageName) {
		super(pageName);

	}
	public Label getDomainLabel(){

		return domainLabel;

	}
	@Override
	public void createControl(Composite parent) {
		initializeDialogUnits(parent);

		composite = new Composite(parent, SWT.NONE);
		GridLayout gl_composite = new GridLayout();
		gl_composite.marginWidth = 0;
		gl_composite.marginHeight = 0;
		composite.setLayout(gl_composite);
		GridData data = new GridData(GridData.FILL);
		data.grabExcessHorizontalSpace = true;
		composite.setLayoutData(data);

		int domainId = DOMAIN_DEFAULT;

		// Add the domain label
		createDomainLabel(composite, (domainId != DOMAIN_DEFAULT) ? domainId : null);

		// Add tree
		treeViewer = createTreeViewer(composite);

		// Load the saved property
		selectSavedItem();

		setControl(composite);

	}

	private void createDomainLabel(Composite parent, Object data) {
		cmpLabels = new Composite(parent, SWT.NONE);
		GridLayout gl_cmpLabels = new GridLayout(2, false);
		gl_cmpLabels.marginWidth = 0;
		cmpLabels.setLayout(gl_cmpLabels);
		cmpLabels.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));

		// Add label
		Label noteLabel = new Label(cmpLabels, SWT.NONE);
		noteLabel.setText("Project do&main:");

		domainLabel = new Label(cmpLabels, SWT.NONE);
		domainLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		domainLabel.setText("(select a domain)");
		domainLabel.setData(data);
	}

	protected class DomainFilteredTree extends FilteredTree {
		private ViewerFilter viewerFilter;

		DomainFilteredTree(Composite parent, int treeStyle, PatternFilter filter) {
			super(parent, treeStyle, filter, true);
		}

		protected void addFilter(ViewerFilter filter) {
			viewerFilter = filter;
			getViewer().addFilter(filter);

			if (filterText != null) {
				setFilterText("type filter text");
				textChanged();
			}
		}

		protected void updateToolbar(boolean visible) {
			super.updateToolbar((viewerFilter != null) || (visible));
		}

		protected void clearText() {
			setFilterText("");

			if ((!locked) && (viewerFilter != null)) {
				getViewer().removeFilter(viewerFilter);
				viewerFilter = null;
			}
			textChanged();
		}
	}

	protected TreeViewer createTreeViewer(Composite parent) {
		TreeViewer tree;

		filteredTree = new DomainFilteredTree(parent, SWT.FILL, new PatternFilter());
		filteredTree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
//		horizontalIndent = 7;
		filteredTree.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND));

		tree = filteredTree.getViewer();

		setContentAndLabelProviders(tree);
		tree.setInput(IProjectDomains.PROJECT_DOMAINS);

		tree.addSelectionChangedListener(new ISelectionChangedListener() {

			public void selectionChanged(SelectionChangedEvent event) {
				handleTreeSelectionChanged(event);
			}

		});

		//super.addListeners(tree);
		return tree;
	}

	private DomainEntry findDomainById(DomainEntry[] domains, int domainId) {
		for (DomainEntry de : domains) {
			if (de.getId() == domainId) {
				return de;
			}
			if(de.hasChildren()) {
				for (DomainEntry child : de.getChildren()) {
					if(child.getId() == domainId) {
						return child;
					}
				}
			}
		}
		return null;
	}

	protected DomainEntry getSingleSelection(ISelection selection)
	{
	  if (!selection.isEmpty()) {
	    IStructuredSelection structured = (IStructuredSelection)selection;
	    if ((structured.getFirstElement() instanceof DomainEntry)) {
	      return (DomainEntry)structured.getFirstElement();
	    }
	  }
	  return null;
	}

	protected void handleTreeSelectionChanged(SelectionChangedEvent event) {
		DomainEntry de = getSingleSelection(event.getSelection());
		updateDomainLabel(de);
	}

	protected void selectSavedItem()
	{
		DomainEntry[] domains = IProjectDomains.PROJECT_DOMAINS;
		treeViewer.setInput(domains);

		int domainId = DOMAIN_DEFAULT;

		DomainEntry domain = findDomainById(domains, domainId);
		if (domain != null) {
			treeViewer.setSelection(new StructuredSelection(domain), true);
		}

		// Set focus to tree or the filter control
		if (treeViewer.getTree().getItemCount() > 1) {
			Text filterText = filteredTree.getFilterControl();
			if (filterText != null) {
				filterText.setFocus();
			}
		} else {
			treeViewer.getControl().setFocus();
		}
	}

	protected void setContentAndLabelProviders(TreeViewer treeViewer)
	{
		treeViewer.setLabelProvider(new DomainBoldLabelProvider(filteredTree ));
		treeViewer.setContentProvider(new DomainContentProvider());
	}

	private void updateDomainLabel(DomainEntry domain) {
		if(domain == null)
			return;

		DomainEntry parent = domain.getParent();

		if(parent != null) {
			String text = parent.getName() + "/" + domain.getName();

			// Escape text for SWT
			domainLabel.setText(text.replaceAll("&", "&&")); //$NON-NLS-1$ //$NON-NLS-2$
			domainLabel.setData(domain);
		}
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ctrip;
using Ctrip.Log4;

namespace Ctrip.SOA.Comm.Log.LogImpl
{
    public class CounterLog : LogHandler
    {
        public CounterLog()
            : this(LogManager.GetLogger(Logger.EsbLoggerName)) { }

        public CounterLog(ILog log)
            : base(log) { }

        public void Info(Arch.SOA.ESB.Entity.CounterEntity counter)
        {
            Write(new CounterLogMessage { Counter = counter });
        }

        protected override void DoHandle(LogMessage logMessage)
        {
            var message = logMessage as CounterLogMessage;
            if (message != null)
            {
                var logRQ = new Arch.Gov.SysLog.Entity.Request();
                logRQ.Header.RequestType = LogType.Counter;
                logRQ.Header.UserID = "900201";
                logRQ.RequestBody = message.Counter;
                logMessage.EsbLogBody = logRQ;
            }
        }

        public class CounterLogMessage : LogMessage
        {
            public CounterLogMessage()
            {
                LogType = Ctrip.SOA.Comm.Log.LogType.Counter;
            }
            public Arch.SOA.ESB.Entity.CounterEntity Counter { get; set; }
        }
    }
}


text:
package org.kaazing.net.sse.impl;

import org.kaazing.net.impl.util.BlockingQueueImpl;
import org.kaazing.net.sse.SseEventReader;
import org.kaazing.net.sse.SseEventType;
import org.kaazing.net.sse.SseException;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SseEventReaderImpl extends SseEventReader {
    private static final String _CLASS_NAME = SseEventReaderImpl.class.getName();
    private static final Logger _LOG = Logger.getLogger(_CLASS_NAME);

    private final BlockingQueueImpl<Object>    _sharedQueue;
    private final SseEventSourceImpl           _eventSource;

    private SsePayload                         _payload;
    private SseEventType                       _eventType;
    private String                             _eventName;
    private String                             _data;

    public SseEventReaderImpl(SseEventSourceImpl        eventSource,
                              BlockingQueueImpl<Object> sharedQueue) {
        _eventSource = eventSource;
        _sharedQueue = sharedQueue;

        _payload = null;
        _eventType = null;
        _eventName = null;
        _data = null;
    }

    @Override
    public CharSequence getData() throws IOException {
        if (_payload == null) {
            return null;
        }

        if (_eventType != SseEventType.DATA) {
            String s = "readData() can only be used to read events " +
                       "of type SseEventType.DATA";
            throw new SseException(s);
        }

        return _data;
    }

    @Override
    public String getName() {
        return _eventName;
    }

    @Override
    public SseEventType getType() {
        return _eventType;
    }

    @Override
    public SseEventType next() throws IOException {
        if (_sharedQueue.isDone()) {
            _eventType = SseEventType.EOS;
            return _eventType;
        }

        synchronized (this) {
            if (!_eventSource.isConnected()) {
                _eventType = SseEventType.EOS;
                return _eventType;
            }

            try {
                _payload = null;
                _payload = (SsePayload) _sharedQueue.take();
            }
            catch (InterruptedException ex) {
                _LOG.log(Level.FINE, ex.getMessage());
            }

            if (_payload == null) {
                String s = "Reader has been interrupted maybe the connection " +
                           "is closed";
                // throw new SseException(s);
                _LOG.log(Level.FINE, _CLASS_NAME, s);

                _eventType = SseEventType.EOS;
                return _eventType;
            }

            _data = _payload.getData();
            _eventName = _payload.getEventName();
            _eventType = (_payload.getData() == null) ? SseEventType.EMPTY :
                                                        SseEventType.DATA;
        }

        return _eventType;
    }

    // ------------------ Package-Private Implementation ----------------------
    // These methods are called from other classes in this package. They are
    // not part of the public API.
    void close() throws IOException {
        _sharedQueue.done();
        _payload = null;
        _eventType = null;
        _data = null;
        _eventName = null;
    }

    void reset() throws IOException {
        _sharedQueue.reset();
        _payload = null;
        _eventType = null;
        _data = null;
        _eventName = null;
    }

    // ------------- Currently not being used methods -------------------------
    // This was earlier part of our public API. It's no longer being exposed.
    /**
     * Returns the payload of the event. Use this method to retrieve the
     * payload only if the event's type is {@link SseEventType.DATA}.
     *

     * If this method is invoked AFTER {@link #next()} method, then it will not
     * block. If this method is invoked before {@link #next()} method, then it
     * will block till a message is received. If the type of received event is
     * {@link SseEventType#EMPTY}, then this method will throw an IOException.
     *

     * An IOException is thrown if the connection is closed while blocked. An
     * IOException is thrown if this method is invoked before the connection
     * has been established.
     *

     * @return CharSequence     event's payload
     * @throws IOException      if the connection is closed; if the received
     *                          event's type is SseEventType.EMPTY; if invoked
     *                          before connection is established
     */
    @SuppressWarnings("unused")
    private CharSequence readData() throws IOException {
        if (!_eventSource.isConnected()) {
            String s = "Can't read using the MessageReader if the event " +
                       "source is not connected";
            throw new SseException(s);
        }

        synchronized (this) {
            if (_payload != null) {
                // If we are here, then it means that readData() was invoked
                // after next(). So, the _payload is already setup and we just
                // have to return the data.
                if (_eventType != SseEventType.DATA) {
                    String s = "readData() can only be used to read events " +
                               "of type SseEventType.DATA";
                    throw new SseException(s);
                }

                // Clear the _payload member variable for the internal state
                // machine.
                _payload = null;
                return _data;
            }

            // This will block the thread. If we are here, this means that
            // readData() was invoked without a previous invocation of next().
            // So, we invoke next() and ensure that the next message is a text
            // message. Otherwise, throw an exception.
            SseEventType type = next();

            if (type != SseEventType.DATA) {
                String s = "readData() can only be used to read events " +
                           "of type SseEventType.DATA";
                throw new SseException(s);
            }

            _data = _payload.getData();
            _eventName = _payload.getEventName();

            // Clear the _payload member variable for the internal state machine.
            _payload = null;
            return _data;
        }
    }
}


text:
package com.founder.fix.fixflow.core.impl.cmd;

import java.util.List;

import com.founder.fix.fixflow.core.impl.bpmn.behavior.ProcessDefinitionBehavior;
import com.founder.fix.fixflow.core.impl.bpmn.behavior.UserTaskBehavior;
import com.founder.fix.fixflow.core.impl.expression.ExpressionMgmt;
import com.founder.fix.fixflow.core.impl.identity.Authentication;
import com.founder.fix.fixflow.core.impl.identity.GroupTo;
import com.founder.fix.fixflow.core.impl.interceptor.Command;
import com.founder.fix.fixflow.core.impl.interceptor.CommandContext;
import com.founder.fix.fixflow.core.impl.task.TaskAssigneeDefinitionTo;
import com.founder.fix.fixflow.core.impl.util.StringUtil;
import com.founder.fix.fixflow.core.task.IdentityLinkType;
import com.founder.fix.fixflow.core.task.IncludeExclusion;

public class VerificationStartUserCmd implements Command<Boolean> {

	protected String userId;

	protected String processDefinitionKey;

	protected String processDefinitionId;

	public VerificationStartUserCmd(String userId, String processDefinitionKey, String processDefinitionId) {
		this.userId = userId;
		this.processDefinitionKey = processDefinitionKey;
		this.processDefinitionId = processDefinitionId;
	}

	public Boolean execute(CommandContext commandContext) {

		try {
			ProcessDefinitionBehavior processDefinitionBehavior = null;
			if (processDefinitionId != null) {
				processDefinitionBehavior = commandContext.getProcessDefinitionManager().findLatestProcessDefinitionByKey(
						processDefinitionKey);
			} else {
				if (processDefinitionKey != null) {
					processDefinitionBehavior = commandContext.getProcessDefinitionManager().findLatestProcessDefinitionByKey(
							processDefinitionKey);
				} else {
					return false;
				}

			}
			UserTaskBehavior userTask = (UserTaskBehavior) processDefinitionBehavior.getSubTask(processDefinitionBehavior
					.getNoneStartEvent());
			List<GroupTo> groupTos = Authentication.findGroupsByUser(userId);
			if (userTask != null) {
				List<TaskAssigneeDefinitionTo> taskAssigneeDefinitionTos = userTask.getTaskDefinition().getTaskAssigneeDefinitionTos();
				for (TaskAssigneeDefinitionTo taskAssigneeDefinitionTo : taskAssigneeDefinitionTos) {

					if (taskAssigneeDefinitionTo.getIdentityLinkType() == IdentityLinkType.assignee) {
						if (taskAssigneeDefinitionTo.getUserIdExpression() != null) {
							String userIdExpression=StringUtil.getString(ExpressionMgmt.execute(taskAssigneeDefinitionTo.getUserIdExpression(),processDefinitionBehavior));
							if (userIdExpression.equals(userId)) {
								return true;
							}
						}
					} else {

						String userIdString = null;
						if (taskAssigneeDefinitionTo.getUserIdExpression() != null
								&& !taskAssigneeDefinitionTo.getUserIdExpression().equals("")) {

							if (taskAssigneeDefinitionTo.getUserIdExpression().equals("processInfo.getInitiator()")||taskAssigneeDefinitionTo.getUserIdExpression().equals("processInfo.getStartAuthor()")||taskAssigneeDefinitionTo.getUserIdExpression().equals("processInfo.getInitiator();")||taskAssigneeDefinitionTo.getUserIdExpression().equals("processInfo.getStartAuthor();")) {
								return true;
							}

							userIdString = StringUtil.getString(ExpressionMgmt.execute(taskAssigneeDefinitionTo.getUserIdExpression(),
									processDefinitionBehavior));

						}

						if (userIdString != null && !userIdString.equals("")) {
							if (userIdString.equals(userId) || userIdString.equals("fixflow_allusers")||userIdString.equals("processInfo.getInitiator()")||userIdString.equals("processInfo.getStartAuthor()")||userIdString.equals("processInfo.getInitiator();")||userIdString.equals("processInfo.getStartAuthor();")) {
								return true;
							}
						}

						String groupType = taskAssigneeDefinitionTo.getGroupTypeExpression();
						String groupId = taskAssigneeDefinitionTo.getGroupIdExpression();
						IncludeExclusion groupIncludeExclusion = taskAssigneeDefinitionTo.getIncludeExclusion();

						String groupIdObj = null;

						if (groupId != null) {
							groupIdObj = StringUtil.getString(ExpressionMgmt.execute(groupId, processDefinitionBehavior));
						}

						for (GroupTo groupTo : groupTos) {
							if (groupTo.getGroupId().equals(groupIdObj) && groupTo.getGroupType().equals(groupType)) {
								if(groupIncludeExclusion.equals(IncludeExclusion.INCLUDE))
									return true;
								else
									return false;
							}
						}
					}

				}

			} else {
				return false;
			}

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

	}

}