text:
package com.afollestad.appthemeengine.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.SwitchCompat;
import android.util.AttributeSet;

import com.afollestad.appthemeengine.ATE;
import com.afollestad.appthemeengine.R;

/**
 * @author Aidan Follestad (afollestad)
 */
@PreMadeView
public class ATESwitch extends SwitchCompat {

    public ATESwitch(Context context) {
        super(context);
        init(context, null);
    }

    public ATESwitch(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public ATESwitch(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        setTag("tint_accent_color,text_primary");
        String key = null;
        if (attrs != null) {
            TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ATESwitch, 0, 0);
            try {
                key = a.getString(R.styleable.ATESwitch_ateKey_switch);
            } finally {
                a.recycle();
            }
        }
        ATE.apply(context, this, key);
    }
}


text:
from distutils.core import setup
from setuptools import setup
setup(
      name = 'AstroX',
      packages = ['astrox'],
      version = '0.1.106',
      description = 'AstroX Python Server',
      author = 'Alexander Simpson',
      author_email = 'as2388@cam.ac.uk',
      url = 'https://github.com/as2388/AstroX',
      #download_url = 'https://github.com/peterldowns/mypackage/tarball/0.1',
      install_requires=[
                        'autobahn',
                        'sense-hat',
                        'pillow',
                        'twisted'
                        ],
      keywords = ['AstroPi', 'Scratch', 'ScratchX'],
      classifiers = [],
      entry_points={
      'console_scripts': [
                          'astrox = astrox.__main__:main',
                          ]
      }
)

redpajama_set_name: RedPajamaGithub


text:
package ru.stqa.pft.addressbook.model;

import com.google.common.collect.ForwardingSet;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by alisa on 10.05.2016.
 */
public class GroupSuite extends ForwardingSet<GroupData> {

  private Set<GroupData> delegateOb;

  /*
  копируем множество групп для новых методов: берем множество из существующего объекта delegateOb,к-рый передан в
  кач-ве параметра, строим новое множество с теми же эл-тами и присваиваем это множ-во в кач-ве атрибута в новый
  создаваемый этим конструктором объект (с).

  Хз, зачем ссылка на возвращаемое из метода значение, почему не groupSuite из параметра конструктора?
  */
  public GroupSuite(GroupSuite groupSuite) {
    this.delegateOb = new HashSet<GroupData>(groupSuite.delegate());
  }

  public GroupSuite() {
    this.delegateOb = new HashSet<>();
  }

  //конструктор по произв. коллекции строит объект типа groups(исп-ся в DbHelper)
  public GroupSuite(Collection<GroupData> groupSuite) {
    this.delegateOb = new HashSet<GroupData>(groupSuite);
  }

  @Override
  //обязательный для декоратора метод delegateOb
  protected Set<GroupData> delegate() {
    return delegateOb;
  }

  /** Методы withAdded и without создают соотв. копию множества
    */
  public GroupSuite withAdded(GroupData group) {
    GroupSuite groupSuite = new GroupSuite(this);
    groupSuite.add(group);
    return groupSuite;
  }

  public GroupSuite without(GroupData group) {
    GroupSuite groupSuite = new GroupSuite(this);
    groupSuite.remove(group);
    return groupSuite;
  }
}


text:
var fs = require("fs");
var path = require("path");

module.exports = function (folder, ext, callback) {
	fs.readdir(folder, function(err, list) {
		if (err) return callback(err);

		list = list.filter(function (file) {
			return path.extname(file) === '.' + ext;
		});
		callback(null, list);
	});
}


text:
package search

type Location struct {
	Pos   float64 `json:"pos"`
	Start float64 `json:"start"`
	End   float64 `json:"end"`
}

type Locations []*Location

type TermLocationMap map[string]Locations

func (t TermLocationMap) AddLocation(term string, location *Location) {
	existingLocations, exists := t[term]
	if exists {
		existingLocations = append(existingLocations, location)
		t[term] = existingLocations
	} else {
		locations := make(Locations, 1)
		locations[0] = location
		t[term] = locations
	}
}

type FieldTermLocationMap map[string]TermLocationMap

type FieldFragmentMap map[string][]string

type DocumentMatch struct {
	ID        string                 `json:"id"`
	Score     float64                `json:"score"`
	Expl      *Explanation           `json:"explanation,omitempty"`
	Locations FieldTermLocationMap   `json:"locations,omitempty"`
	Fragments FieldFragmentMap       `json:"fragments,omitempty"`
	Fields    map[string]interface{} `json:"fields,omitempty"`
}

func (dm *DocumentMatch) AddFieldValue(name string, value interface{}) {
	if dm.Fields == nil {
		dm.Fields = make(map[string]interface{})
	}
	existingVal, ok := dm.Fields[name]
	if ok {
		valSlice, ok := existingVal.([]interface{})
		if ok {
			// already a slice, append to it
			valSlice = append(valSlice, value)
		} else {
			// create a slice
			valSlice = []interface{}{existingVal, value}
		}
		dm.Fields[name] = valSlice
	} else {
		dm.Fields[name] = value
	}
}

type DocumentMatchCollection []*DocumentMatch

func (c DocumentMatchCollection) Len() int           { return len(c) }
func (c DocumentMatchCollection) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }
func (c DocumentMatchCollection) Less(i, j int) bool { return c[i].Score > c[j].Score }

type Searcher interface {
	Next() (*DocumentMatch, error)
	Advance(ID string) (*DocumentMatch, error)
	Close() error
	Weight() float64
	SetQueryNorm(float64)
	Count() uint64
	Min() int
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Lebretonia procumbens Wight & Arn.

### Remarks
null


text:
package io.pravega.controller.store.stream;

import com.google.common.collect.ImmutableMap;
import io.pravega.client.stream.impl.StreamImpl;
import io.pravega.common.Exceptions;
import io.pravega.common.concurrent.Futures;
import io.pravega.controller.store.ZKStoreHelper;
import io.pravega.controller.store.client.StoreType;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.utils.ZKPaths;

import java.util.Base64;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

@SuppressWarnings("deprecation")
@Slf4j
public class ZookeeperBucketStore implements BucketStore {
    private static final String ROOT_PATH = "/";
    private static final String OWNERSHIP_CHILD_PATH = "ownership";
    private final ImmutableMap<ServiceType, Integer> bucketCountMap;
    @Getter
    private final ZKStoreHelper storeHelper;

    ZookeeperBucketStore(ImmutableMap<ServiceType, Integer> bucketCountMap, CuratorFramework client, Executor executor) {
        this.bucketCountMap = bucketCountMap;
        storeHelper = new ZKStoreHelper(client, executor);
    }

    public boolean isZKConnected() {
        return storeHelper.isZKConnected();
    }

    @Override
    public StoreType getStoreType() {
        return StoreType.Zookeeper;
    }

    @Override
    public int getBucketCount(ServiceType serviceType) {
        return bucketCountMap.get(serviceType);
    }

    public CompletableFuture<Void> createBucketsRoot(ServiceType serviceType) {
        String bucketRootPath = getBucketRootPath(serviceType);
        String bucketOwnershipPath = getBucketOwnershipPath(serviceType);
        return Futures.toVoid(storeHelper.createZNodeIfNotExist(bucketRootPath)
                          .thenCompose(x -> storeHelper.createZNodeIfNotExist(bucketOwnershipPath)));
    }

    public CompletableFuture<Void> createBucket(ServiceType serviceType, int bucketId) {
        String bucketPath = getBucketPath(serviceType, bucketId);
        return Futures.toVoid(createBucketsRoot(serviceType)
                          .thenCompose(x -> storeHelper.createZNodeIfNotExist(bucketPath)));
    }

    @Override
    public CompletableFuture<Set<String>> getStreamsForBucket(ServiceType serviceType, int bucket, Executor executor) {
        String bucketPath = getBucketPath(serviceType, bucket);

        return storeHelper.getChildren(bucketPath)
                          .thenApply(list -> list.stream().map(this::decodedScopedStreamName).collect(Collectors.toSet()));
    }

    @Override
    public CompletableFuture<Void> addStreamToBucketStore(final ServiceType serviceType, final String scope, final String stream,
                                                          final Executor executor) {
        int bucketCount = bucketCountMap.get(serviceType);
        int bucket = BucketStore.getBucket(scope, stream, bucketCount);
        String bucketPath = getBucketPath(serviceType, bucket);
        String streamPath = ZKPaths.makePath(bucketPath, encodedScopedStreamName(scope, stream));

        return storeHelper.checkExists(streamPath)
            .thenCompose(exists -> {
                if (exists) {
                    return CompletableFuture.completedFuture(null);
                } else {
                    return Futures.toVoid(storeHelper.createZNodeIfNotExist(streamPath));
                }
            });
    }

    @Override
    public CompletableFuture<Void> removeStreamFromBucketStore(final ServiceType serviceType, final String scope,
                                                               final String stream, final Executor executor) {
        int bucketCount = bucketCountMap.get(serviceType);
        int bucket = BucketStore.getBucket(scope, stream, bucketCount);
        String bucketPath = getBucketPath(serviceType, bucket);
        String streamPath = ZKPaths.makePath(bucketPath, encodedScopedStreamName(scope, stream));

        return Futures.exceptionallyExpecting(storeHelper.deleteNode(streamPath),
                e -> Exceptions.unwrap(e) instanceof StoreException.DataNotFoundException, null);
    }

    public CompletableFuture<Boolean> takeBucketOwnership(final ServiceType serviceType, int bucketId, String processId) {
        String bucketPath = ZKPaths.makePath(getBucketOwnershipPath(serviceType), "" + bucketId);
        return storeHelper.createEphemeralZNode(bucketPath, SerializationUtils.serialize(processId))
                          .thenCompose(created -> {
                              if (!created) {
                                  return storeHelper.getData(bucketPath, x -> x)
                                                    .thenApply(data -> (SerializationUtils.deserialize(data.getObject())).equals(processId));
                              } else {
                                  return CompletableFuture.completedFuture(true);
                              }
                          });
    }

    public PathChildrenCache getBucketPathChildrenCache(ServiceType serviceType, int bucketId) {
        return storeHelper.getPathChildrenCache(getBucketPath(serviceType, bucketId), true);
    }

    public PathChildrenCache getServiceOwnershipPathChildrenCache(ServiceType serviceType) {
        return storeHelper.getPathChildrenCache(getBucketOwnershipPath(serviceType), true);
    }

    public StreamImpl getStreamFromPath(String path) {
        String scopedStream = decodedScopedStreamName(ZKPaths.getNodeFromPath(path));
        String[] splits = scopedStream.split("/");
        return new StreamImpl(splits[0], splits[1]);
    }

    private String encodedScopedStreamName(String scope, String stream) {
        String scopedStreamName = BucketStore.getScopedStreamName(scope, stream);
        return Base64.getEncoder().encodeToString(scopedStreamName.getBytes());
    }

    private String decodedScopedStreamName(String encodedScopedStreamName) {
        return new String(Base64.getDecoder().decode(encodedScopedStreamName));
    }

    private String getBucketRootPath(final ServiceType serviceType) {
        return ZKPaths.makePath(ROOT_PATH, serviceType.getName());
    }

    private String getBucketOwnershipPath(final ServiceType serviceType) {
        String bucketRootPath = getBucketRootPath(serviceType);
        return ZKPaths.makePath(bucketRootPath, OWNERSHIP_CHILD_PATH);
    }

    private String getBucketPath(final ServiceType serviceType, final int bucket) {
        String bucketRootPath = ZKPaths.makePath(ROOT_PATH, serviceType.getName());
        return ZKPaths.makePath(bucketRootPath, "" + bucket);
    }
}


text:
package org.javarosa.core.model.test;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.javarosa.core.model.FormElementStateListener;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.IDataReference;
import org.javarosa.core.model.IFormElement;
import org.javarosa.core.model.QuestionDef;
import org.javarosa.core.model.data.IntegerData;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.services.PrototypeManager;
import org.javarosa.core.test.FormParseInit;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryPrompt;

/**
 * See testAnswerConstraint() for an example of how to write the
 * constraint unit type tests.
 * @author adewinter
 *
 */
public class FormDefTest extends TestCase {
	QuestionDef q = null;
	FormEntryPrompt fep = null;
	FormParseInit fpi = null;

	public FormDefTest(String name) {
		super(name);
		System.out.println("Running " + this.getClass().getName() + " test: " + name + "...");
	}

	public void setUp(){
		fpi = new FormParseInit();
		q = fpi.getFirstQuestionDef();
		fep = new FormEntryPrompt(fpi.getFormDef(), fpi.getFormEntryModel().getFormIndex());
	}

	static PrototypeFactory pf;

	static {
		PrototypeManager.registerPrototype("org.javarosa.model.xform.XPathReference");
		pf = ExtUtil.defaultPrototypes();
	}

	public static Test suite() {
		TestSuite aSuite = new TestSuite();

		for (int i = 1; i <= NUM_TESTS; i++) {
			final int testID = i;
			aSuite.addTest(new FormDefTest(doTest(testID)));
		}

		return aSuite;
	}

	private void testSerialize (QuestionDef q, String msg) {
		//ExternalizableTest.testExternalizable(q, this, pf, "QuestionDef [" + msg + "]");
	}

	public final static int NUM_TESTS = 1;

	public static String doTest (int i) {
		switch (i) {
		case 1: return "testAnswerConstraint";
		}
		throw new IllegalStateException("Unexpected index");
	}

	public void testAnswerConstraint(){
		IntegerData ans = new IntegerData(13);
		FormEntryController fec = fpi.getFormEntryController();
		fec.jumpToIndex(FormIndex.createBeginningOfFormIndex());

		do{

			QuestionDef q = fpi.getCurrentQuestion();
			if(q==null || q.getTextID() == null || q.getTextID() == "")continue;
			if(q.getTextID().equals("constraint-test")){
				int response = fec.answerQuestion(ans, true);
				if(response == FormEntryController.ANSWER_CONSTRAINT_VIOLATED){
					fail("Answer Constraint test failed.");
				}else if(response == FormEntryController.ANSWER_OK){
					break;
				}else{
					fail("Bad response from fec.answerQuestion()");
				}
			}
		}while(fec.stepToNextEvent()!=FormEntryController.EVENT_END_OF_FORM);
	}

	public IDataReference newRef(String xpath){
			IDataReference ref = new DummyReference();
			ref.setReference(xpath);
			pf.addClass(DummyReference.class);
			return ref;
	}

}


text:
#ifndef CCB_IO_STREAM_HH
#define CCB_IO_STREAM_HH

#include <ctime>
#include <memory>
#include <nlohmann/json.hpp>
#include <string>

#include "com/centreon/broker/io/data.hh"
#include "com/centreon/broker/namespace.hh"

CCB_BEGIN()

namespace io {
/**
 *  @class stream stream.hh "com/centreon/broker/io/stream.hh"
 *  @brief Class used to exchange data.
 *
 *  Interface to exchange data.
 *
 *  The read() method is used to get data while waiting for it. It
 *  should work as follow:
 *    - has data:        shared pointer is properly set, true returned
 *    - spurious wake:   null shared pointer, true returned
 *    - timeout:         null shared pointer, false returned
 *    - known shutdown:  throw io::exceptions::shutdown
 *    - error:           any exception
 *
 *  The write() method is used to send data through the stream. It
 *  should return the number of event fully written through (taking into
 *  account any buffering, or underlayer) to the end device. If that
 *  information is not available or meaningful, it should always return '1'.
 *
 *  Behind a stream, we can have threads doing complicated things. Before
 *  destroying a stream, we have to stop all these threads correctly, to flush
 *  pending events, all these things are the purpose of the stop() internal
 *  function.
 */
class stream {
  const std::string _name;

 protected:
  std::shared_ptr<stream> _substream;

 public:
  stream(const std::string& name);
  virtual ~stream() noexcept = default;
  virtual int32_t stop() = 0;
  stream(const stream&) = delete;
  stream& operator=(const stream&) = delete;
  virtual int flush();
  virtual std::string peer() const;
  virtual bool read(std::shared_ptr<io::data>& d,
                    time_t deadline = (time_t)-1) = 0;
  virtual void set_substream(std::shared_ptr<stream> substream);
  std::shared_ptr<stream> get_substream();
  virtual void statistics(nlohmann::json& tree) const;
  virtual void update();
  bool validate(std::shared_ptr<io::data> const& d, std::string const& error);
  virtual int write(std::shared_ptr<data> const& d) = 0;
  const std::string& get_name() const { return _name; }
};
}  // namespace io

CCB_END()

#endif  // !CCB_IO_STREAM_HH


text:
Spree::Core::Engine.add_routes do
  namespace :admin do
    resource :drop_ship_settings
    resources :shipments
    resources :suppliers
  end
end


text:
package edu.rutgers.css.Rutgers.interfaces;

import com.google.android.gms.common.api.GoogleApiClient;

public interface GoogleApiClientProvider {
    GoogleApiClient getGoogleApiClient();
    boolean servicesConnected();
    void registerListener(GoogleApiClient.ConnectionCallbacks listener);
    void unregisterListener(GoogleApiClient.ConnectionCallbacks listener);
}


text:
FROM crux/python:onbuild

ENTRYPOINT ["autodock-cron"]
CMD []


text:
1.1.0 (November 30, 2016)
=========================

Changes
-------

* Switch from Jannson to RapidJSON for our JSON library (allowing for a configuration schema in
  1.2.0).
* Upgrade :ref:`recommended version <v1.5:install_requirements>` of various other libraries.
* Configurable DNS refresh rate for DNS service discovery types.
* Upstream circuit breaker configuration can be :ref:`overridden via runtime
  <v1.5:config_cluster_manager_cluster_runtime>`.
* :ref:`Zone aware routing support <v1.5:arch_overview_load_balancing_zone_aware_routing>`.
* Generic header matching routing rule.
* HTTP/2 graceful connection draining (double GOAWAY).
* DynamoDB filter :ref:`per shard statistics <v1.5:config_http_filters_dynamo>` (pre-release AWS
  feature).
* Initial release of the :ref:`fault injection HTTP filter <v1.5:config_http_filters_fault_injection>`.
* HTTP :ref:`rate limit filter <v1.5:config_http_filters_rate_limit>` enhancements (note that the
  configuration for HTTP rate limiting is going to be overhauled in 1.2.0).
* Added :ref:`refused-stream retry policy <v1.5:config_http_filters_router_x-envoy-retry-on>`.
* Multiple :ref:`priority queues <v1.5:arch_overview_http_routing_priority>` for upstream clusters
  (configurable on a per route basis, with separate connection pools, circuit breakers, etc.).
* Added max connection circuit breaking to the :ref:`TCP proxy filter <v1.5:arch_overview_tcp_proxy>`.
* Added :ref:`CLI <v1.5:operations_cli>` options for setting the logging file flush interval as well
  as the drain/shutdown time during hot restart.
* A very large number of performance enhancements for core HTTP/TCP proxy flows as well as a
  few new configuration flags to allow disabling expensive features if they are not needed
  (specifically request ID generation and dynamic response code stats).
* Support Mongo 3.2 in the :ref:`Mongo sniffing filter <v1.5:config_network_filters_mongo_proxy>`.
* Lots of other small fixes and enhancements not listed.


text:
package com.compomics.sigpep.playground;

import com.compomics.sigpep.analysis.query.ProteomeCoverage;
import com.compomics.dbtools.DatabaseException;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @TODO: JavaDoc missing.
 * @TODO: all code in this class is commented out...
 *

 * Created by IntelliJ IDEA.

 * User: mmueller

 * Date: 30-Nov-2007

 * Time: 13:38:33

 */
public class Query {

//    public static void main(String[] args) {
//
//        String barcodesInput = "/home/mmueller/data/sigpep/barcodes_9606_zmin2_zmax2_acc1_argc,lysc,v8de.tab";
//
//        try {
//            BufferedReader br = new BufferedReader(new FileReader(barcodesInput));
//
//            Set<Integer> peptideIds = new HashSet<Integer>();
//
//            String line;
//            while ((line = br.readLine()) != null) {
//                try{
//
//                String[] columns = line.split("\t");
//                Integer peptideId = new Integer(columns[0]);
//                Integer transitionCount = new Integer(columns[6]);
//
////                System.out.println(columns.length);
//
//                if(transitionCount > 0){
//
//                    peptideIds.add(peptideId);
//                }
//
//                } catch (NumberFormatException e){
//                    System.out.println(e.getMessage());
//
//                }
//            }
//
//            ProteomeCoverage pc = new ProteomeCoverage("mmueller",
//                    "".toCharArray(), 9606, "/home/mmueller/data/sigpep");
//
//            pc.reportSignaturePeptideProteomeCoverageSummary();
//            pc.reportPeptideSetProteomeCoverageSummary("argc,lysc,v8de", peptideIds);
//
//
//        } catch (IOException e) {
//            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
//        } catch (DatabaseException e) {
//            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
//        }
//
//
//    }

}


text:
var App = require('app');
require('models/cluster');

describe('App.Cluster', function () {

  var cluster;

  beforeEach(function () {
    cluster = App.Cluster.createRecord();
  });

  describe('#isKerberosEnabled', function () {

    [
      {
        securityType: 'KERBEROS',
        isKerberosEnabled: true,
        title: 'Kerberos enabled'
      },
      {
        securityType: 'NONE',
        isKerberosEnabled: false,
        title: 'Kerberos disabled'
      }
    ].forEach(function (item) {

      it(item.title, function () {
        cluster.set('securityType', item.securityType);
        expect(cluster.get('isKerberosEnabled')).to.equal(item.isKerberosEnabled);
      });

    });

    describe('#isCredentialStorePersistent', function () {

      [
        {
          propertyValue: 'false',
          isCredentialStorePersistent: false,
          title: 'no persistent credential store'
        },
        {
          propertyValue: true,
          isCredentialStorePersistent: false,
          title: 'malformed value'
        },
        {
          propertyValue: 'true',
          isCredentialStorePersistent: true,
          title: 'persistent credential store'
        }
      ].forEach(function (item) {

        it(item.title, function () {
          cluster.set('credentialStoreProperties', {
            'storage.persistent': item.propertyValue
          });
          expect(cluster.get('isCredentialStorePersistent')).to.equal(item.isCredentialStorePersistent);
        });

      });

    });

  });

});


text:
% Train logistic regression
% Before running this script, you need to be sure file mnist_data.mat
% exists in the current directory.
% If it doesn't exist, please run mnistUrlToMatFile first.
clear; close all; clc;

num_labels = 10;

% Load data from MNIST files
load mnist_data.mat;

lambda = 0.1;
[all_theta] = oneVsAll(XTrain, yTrain, num_labels, lambda); % Train logistic regression
save lr_theta.mat all_theta;


text:
use strict;
use Data::Dumper;
use File::Slurp;
use Getopt::Long;

my $year;
my $month;
my $verbose;

my $result = GetOptions ("month=i" => \$month, # numeric
					  	 "year=i" => \$year, # numeric
					  	 "verbose" => \$verbose); # flag
$verbose=0 if($verbose eq "");

# validate date
die "INPUT ERROR: Values of month and year should all be numerical\n" if($result!=1);
die "INPUT ERROR: Month should be between 1 and 12\n" if ($month<1 || $month >12);

# the month in the log filenames have 2 digits so if it's less or equal to 9 add a zero infront
if($month < 10){
	$month = "0".$month;
}else{
	$month = $month;
}

my $level2Path = "../data/";

my @logFileLines = read_file($level2Path."L2_".$year."-".$month."_grouped-sessions.csv");

my $fileLines = @logFileLines;
my $sessionNoOfReq = 0;

print STDERR "Deleting single request sessions\n" if($verbose);

my $progressCnt=0;
my $progress=0;
my $progressMod = int($fileLines/100);

for (my $i=0; $i<$fileLines; $i++){

	if($verbose){
		$progressCnt++;
		if($progressCnt%$progressMod==0){
			print STDERR "\r",$progress++,"% completed";
		}
	}

	if(@logFileLines[$i] eq "\n"){

		if($sessionNoOfReq==1){
			delete @logFileLines[$i];
			delete @logFileLines[$i-1];
		}
		$sessionNoOfReq=0;
	}else{
		$sessionNoOfReq++;
	}
}

print STDERR "\r100","% completed\n" if($verbose);

# if the last session is a single request session then delete it
my $line3 = @logFileLines[$fileLines-2];
my $line2 = @logFileLines[$fileLines-1];
my $line1 = @logFileLines[$fileLines];

if($line1 eq ""){
	if(defined($line2) && ($line3 eq "\n" || $line3 eq "\r")){
		delete (@logFileLines[$fileLines]);
		delete (@logFileLines[$fileLines-1]);
	}
}elsif(defined($line1) && ($line2 eq "\n" || $line2 eq "\r")){
	delete (@logFileLines[$fileLines]);
}

my $out_file = $level2Path."L2_".$year."-".$month."_mult_req-sessions.csv";

print STDERR "Printing final session file to '".$level2Path."L2_".$year."-".$month."_mult_req-sessions.csv'\n" if($verbose);

open(OUT_FILE, '>:utf8', $out_file ) or die "Can't open out file: $out_file\n";

foreach my $elmnt (@logFileLines){
	if(defined($elmnt)){
		print OUT_FILE $elmnt;
	}
}

__END__

=pod

=head1 NAME

del_single_request_sessions.pl

=head1 SYNOPSIS

This script will parse a file 'L2_year-month_grouped-sessions.csv' and produce a file
'L2_year-month_mult_req-sessions.csv'. This script will essentially remove all the
single request sessions that have failed to be grouped to a neighbour session.

=head1 DEPENDENCIES

This script depends totally on the extract_proxy_free.pl, get_sessions.pl and
group_single_request_sessions.pl which should be run in that sequence before running
this script.

=head1 USE

perl del_single_request_sessions.pl -m 4 -y 2011 -verbose

The above example will parse file L2_2011-04_grouped-sessions.csv and produce
L2_2011-04_mult_req-sessions.csv

=cut


text:
using UnityEngine;

using System;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// Provides the ability to bind a property on one object to the value of
/// another property on another object. This class uses an event-driven
/// model, which waits for an event to be raised indicating that a property
/// has been changed, rather than polling the property each frame.
/// </summary>
[Serializable]
[AddComponentMenu( "Daikon Forge/Data Binding/Event-Driven Property Binding" )]
public class dfEventDrivenPropertyBinding : dfPropertyBinding
{

	#region Public fields

	/// <summary>
	/// The name of an event on the DataSource that will be raised when
	/// the desired property is changed, allowing for an event-driven
	/// rather than polling-driven binding. This value can be left blank
	/// (or null), but if specified it *must* match the name of an event
	/// on the source that will indicate that the property specified by
	/// DataSource has been changed.
	/// </summary>
	public string SourceEventName;

	/// <summary>
	/// The name of an event on the DataTarget that will be raised when
	/// the desired property is changed, allowing for an event-driven
	/// rather than polling-driven binding. This value can be left blank
	/// (or null), but if specified it *must* match the name of an event
	/// on the source that will indicate that the property specified by
	/// DataTarget has been changed.
	/// </summary>
	public string TargetEventName;

	#endregion

	#region Private runtime variables

	protected dfEventBinding sourceEventBinding;
	protected dfEventBinding targetEventBinding;

	#endregion

	#region Unity events

	public override void Update()
	{
		// Do nothing, override the default polling behavior
	}

	#endregion

	#region Static helper methods

	/// <summary>
	/// Creates a dfEventDrivenPropertyBinding component that binds the source and target properties
	/// </summary>
	/// <param name="sourceComponent">The component instance that will act as the data source</param>
	/// <param name="sourceProperty">The name of the property on the source component that will be bound</param>
	/// <param name="targetComponent">The component instance that will act as the data target</param>
	/// <param name="targetProperty">The name of the property on the target component that will be bound</param>
	/// <returns>An active and bound dfEventDrivenPropertyBinding instance</returns>
	public static dfEventDrivenPropertyBinding Bind( Component sourceComponent, string sourceProperty, string sourceEvent, Component targetComponent, string targetProperty, string targetEvent )
	{
		return Bind( sourceComponent.gameObject, sourceComponent, sourceProperty, sourceEvent, targetComponent, targetProperty, targetEvent );
	}

	/// <summary>
	/// Creates a dfEventDrivenPropertyBinding component that binds the source and target properties
	/// </summary>
	/// <param name="hostObject">The GameObject instance to attach the dfEventDrivenPropertyBinding component to. Required.</param>
	/// <param name="sourceComponent">The component instance that will act as the data source. Required.</param>
	/// <param name="sourceProperty">The name of the property on the source component that will be bound. Required.</param>
	/// <param name="sourceEvent">The name of the event on the source component that will indicate that the source value should be copied to the target property. Required.</param>
	/// <param name="targetComponent">The component instance that will act as the data target. Required.</param>
	/// <param name="targetProperty">The name of the property on the target component that will be bound. Required.</param>
	/// <param name="targetEvent">The name of the property on the target component that will indicate that the target value should be copied to the source property.
	/// This value is optional, and should be set to NULL if two-way binding is not needed.</param>
	/// <returns>An active and bound dfEventDrivenPropertyBinding instance</returns>
	public static dfEventDrivenPropertyBinding Bind( GameObject hostObject, Component sourceComponent, string sourceProperty, string sourceEvent, Component targetComponent, string targetProperty, string targetEvent )
	{

		if( hostObject == null )
			throw new ArgumentNullException( "hostObject" );

		if( sourceComponent == null )
			throw new ArgumentNullException( "sourceComponent" );

		if( targetComponent == null )
			throw new ArgumentNullException( "targetComponent" );

		if( string.IsNullOrEmpty( sourceProperty ) )
			throw new ArgumentNullException( "sourceProperty" );

		if( string.IsNullOrEmpty( targetProperty ) )
			throw new ArgumentNullException( "targetProperty" );

		// Make sure that an event name is specified for the source. Note that the same
		// check is not performed for the target event, because having a one-way binding
		// is a valid condition.
		if( string.IsNullOrEmpty( sourceEvent ) )
			throw new ArgumentNullException( "sourceEvent" );

		var binding = hostObject.AddComponent<dfEventDrivenPropertyBinding>();
		binding.DataSource = new dfComponentMemberInfo() { Component = sourceComponent, MemberName = sourceProperty };
		binding.DataTarget = new dfComponentMemberInfo() { Component = targetComponent, MemberName = targetProperty };
		binding.SourceEventName = sourceEvent;
		binding.TargetEventName = targetEvent;

		binding.Bind();

		return binding;

	}

	#endregion

	#region Public methods

	/// <summary>
	/// Bind the source and target properties
	/// </summary>
	public override void Bind()
	{

		if( isBound )
			return;

		if( !DataSource.IsValid || !DataTarget.IsValid )
		{
			Debug.LogError( string.Format( "Invalid data binding configuration - Source:{0}, Target:{1}", DataSource, DataTarget ) );
			return;
		}

		sourceProperty = DataSource.GetProperty();
		targetProperty = DataTarget.GetProperty();

		if( ( sourceProperty != null ) && ( targetProperty != null ) )
		{

			// Create an EventBinding component to mirror the source property
			if( !string.IsNullOrEmpty( SourceEventName ) && SourceEventName.Trim() != "" )
			{
				bindSourceEvent();
			}

			// Create an EventBinding component to mirror the target property
			if( !string.IsNullOrEmpty( TargetEventName ) && TargetEventName.Trim() != "" )
			{
				bindTargetEvent();
			}
			else
			{

				// Determine whether to use the format string
				if( targetProperty.PropertyType == typeof( string ) )
				{
					if( sourceProperty.PropertyType != typeof( string ) )
					{
						useFormatString = !string.IsNullOrEmpty( FormatString );
					}
				}

			}

			// Ensure that both properties are synced at start
			MirrorSourceProperty();

			// Flag the binding as valid
			isBound = ( sourceEventBinding != null );

		}

	}

	/// <summary>
	/// Unbind the source and target properties
	/// </summary>
	public override void Unbind()
	{

		if( !isBound )
			return;

		isBound = false;

		if( sourceEventBinding != null )
		{
			sourceEventBinding.Unbind();
			Destroy( sourceEventBinding );
			sourceEventBinding = null;
		}

		if( targetEventBinding != null )
		{
			targetEventBinding.Unbind();
			Destroy( targetEventBinding );
			targetEventBinding = null;
		}

	}

	/// <summary>
	/// Copies the value of the source property to the target property
	/// </summary>
	public void MirrorSourceProperty()
	{
		targetProperty.Value = formatValue( sourceProperty.Value );
	}

	/// <summary>
	/// Copies the value of the target property back to the source property
	/// </summary>
	public void MirrorTargetProperty()
	{
		sourceProperty.Value = targetProperty.Value;
	}

	#endregion

	#region Private utility methods

	private object formatValue( object value )
	{

		try
		{

			if( useFormatString && !string.IsNullOrEmpty( FormatString ) )
			{
				return string.Format( FormatString, value );
			}

		}
		catch( FormatException err )
		{
			Debug.LogError( err, this );
			if( Application.isPlaying )
				this.enabled = false;
		}

		return value;

	}

	private void bindSourceEvent()
	{

		sourceEventBinding = gameObject.AddComponent<dfEventBinding>();
		sourceEventBinding.hideFlags = HideFlags.HideAndDontSave | HideFlags.HideInInspector;

		sourceEventBinding.DataSource = new dfComponentMemberInfo()
		{
			Component = DataSource.Component,
			MemberName = SourceEventName
		};

		sourceEventBinding.DataTarget = new dfComponentMemberInfo()
		{
			Component = this,
			MemberName = "MirrorSourceProperty"
		};

		sourceEventBinding.Bind();

	}

	private void bindTargetEvent()
	{

		targetEventBinding = gameObject.AddComponent<dfEventBinding>();
		targetEventBinding.hideFlags = HideFlags.HideAndDontSave | HideFlags.HideInInspector;

		targetEventBinding.DataSource = new dfComponentMemberInfo()
		{
			Component = DataTarget.Component,
			MemberName = TargetEventName
		};

		targetEventBinding.DataTarget = new dfComponentMemberInfo()
		{
			Component = this,
			MemberName = "MirrorTargetProperty"
		};

		targetEventBinding.Bind();

	}

	#endregion

	#region System.Object overrides

	/// <summary>
	/// Returns a formatted string summarizing this object's state
	/// </summary>
	public override string ToString()
	{

		string sourceType = DataSource != null && DataSource.Component != null ? DataSource.Component.GetType().Name : "[null]";
		string sourceMember = DataSource != null && !string.IsNullOrEmpty( DataSource.MemberName ) ? DataSource.MemberName : "[null]";

		string targetType = DataTarget != null && DataTarget.Component != null ? DataTarget.Component.GetType().Name : "[null]";
		string targetMember = DataTarget != null && !string.IsNullOrEmpty( DataTarget.MemberName ) ? DataTarget.MemberName : "[null]";

		return string.Format( "Bind {0}.{1} -> {2}.{3}", sourceType, sourceMember, targetType, targetMember );

	}

	#endregion

}


text:
package com.google.errorprone.bugpatterns;

import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** @author eaftan@google.com (Eddie Aftandilian) */
@RunWith(JUnit4.class)
public class ArrayHashCodeTest {

  private final CompilationTestHelper compilationHelper =
      CompilationTestHelper.newInstance(ArrayHashCode.class, getClass());

  @Test
  public void testPositiveCase() {
    compilationHelper.addSourceFile("ArrayHashCodePositiveCases.java").doTest();
  }

  @Test
  public void testNegativeCase() {
    compilationHelper.addSourceFile("ArrayHashCodeNegativeCases.java").doTest();
  }

  /** Tests java.util.Objects hashCode methods, which are only in JDK 7 and above. */
  @Test
  public void testJava7NegativeCase() {
    compilationHelper.addSourceFile("ArrayHashCodeNegativeCases2.java").doTest();
  }
}


text:
#include <linux/types.h>

struct device_node;

#if defined(CONFIG_OF) && defined(CONFIG_COMMON_CLK)
int of_clk_set_defaults(struct device_node *node, bool clk_supplier);
#else
static inline int of_clk_set_defaults(struct device_node *node,
				      bool clk_supplier)
{
	return 0;
}
#endif


text:
package io.shiftleft.semanticcpg.language.types.structure

import io.shiftleft.codepropertygraph.generated.nodes._
import io.shiftleft.semanticcpg.language._
import io.shiftleft.semanticcpg.testing.MockCpg
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class NamespaceTests extends AnyWordSpec with Matchers {

  val cpg = MockCpg()
    .withFile("filename.c")
    .withNamespace("io.shiftleft.testcode.namespace", inFile = Some("filename.c"))
    .withTypeDecl("NamespaceTest", inNamespace = Some("io.shiftleft.testcode.namespace"))
    .cpg

  "generic cpg" should {
    "find package io.shiftleft.testcode.namespace" in {
      val queryResult: List[Namespace] = cpg.namespace.toList

      queryResult.map(_.name) should contain("io.shiftleft.testcode.namespace")
    }

    "find a namespace block for io.shiftleft.testcode.namespace" in {
      val queryResult: List[NamespaceBlock] = cpg.namespaceBlock.toList
      queryResult.map(_.name) should contain("io.shiftleft.testcode.namespace")
    }

    "be able to traverse from namespace block to type decl" in {
      val queryResult: List[TypeDecl] = cpg.namespaceBlock
        .nameExact("io.shiftleft.testcode.namespace")
        .typeDecl
        .toList
      queryResult.map(_.name) should contain("NamespaceTest")
    }

    "be able to expand to class NamespaceTest from via its namespace." in {
      val queryResult: List[TypeDecl] =
        cpg.namespace.name("io.shiftleft.testcode.namespace").typeDecl.toList

      queryResult.size shouldBe 1
      queryResult.head.name shouldBe "NamespaceTest"
    }

    "be able to expand to file which defines namespace." in {
      val queryResult: List[File] =
        cpg.namespace.name("io.shiftleft.testcode.namespace").file.toList

      queryResult.size shouldBe 1
      queryResult.head.name shouldBe "filename.c"
    }
  }

}


text:
[![Build Status](https://travis-ci.org/kartotherian/overzoom.svg?branch=master)](https://travis-ci.org/kartotherian/overzoom)

# @kartotherian/overzoom
Overzoom tile source for Kartotherian map tile server


text:
title: Protestos no Brasil
author: fellipe
layout: post
permalink: /protestos-no-brasil/
categories:
  - Uncategorized
---
[][1]

Todo mundo reclama que ninguém faz nada. Todo mundo reclama que não há o que fazer. Aí os caras partem pra cima, fazem passeata, organizam milhares de pessoas em cidades diferentes e vão pras ruas reclamar, e todo mundo critica.

Veja, eram MILHARES de pessoas, e houve alguns quebra quebra… se fosse num estádio de futebol todos estariam dizendo: Ah, é a minoria, uns vandalos, a torcida do \___ (ponha aqui o nome do seu time) não é assim.

Se eu estivesse no Brasil, com certeza estaria nas ruas, com uma faixa pedindo prisão aos mensaleiros, baixar impostos, tapar o buraco na rua, ou dar mais segurança para meus conterraneos Curitibanos que tem sido assaltados, roubados e até assassinados por bandidinhos meia boca.

Vao quebrar algumas coisas, vão… mas não se compara a quantidade de dinheiro desviada pelos impostos.

Vao atrasar seu caminho pro trabalho? Vao sim, mas voce atrasa pra ir em vários lugares por causa da bosta do transito que os politicos nao arrumam e voce nao reclama.

Eu levaria minha esposa para um movimento como esse? Não, não acho seguro, mas como homem, jovem e brasileiro, estou orgulhoso de ver alguém fazendo algo.

Participe, ou não participe, mas nao os acuse de estarem “atrapalhando sua vida”, eles pelo menos estão fazendo algo, e não, NAO se protesta com flores, perfume e sentados numa praça. Há que fazer barulho pra aparecer.

  “O que me preocupa não é nem o grito dos corruptos, dos violentos, dos desonestos, dos sem caráter, dos sem ética… O que me preocupa é o silêncio dos bons.”

 [1]: /img/posts/2013/06/martin-luther-king21.jpg


text:
<?php

/* AcmeCovoiturageBundle:map:Map.html.twig */
class __TwigTemplate_e1c7036321768015e70c25343b69b0a71adf9300f20b63deff72c1a874ecb8f5 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        $this->parent = $this->loadTemplate("::base.html.twig", "AcmeCovoiturageBundle:map:Map.html.twig", 1);
        $this->blocks = array(
            'styleMap' => array($this, 'block_styleMap'),
            'body' => array($this, 'block_body'),
            'javascriptsMap' => array($this, 'block_javascriptsMap'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    public function block_styleMap($context, array $blocks = array())
    {
        // line 3
        echo "   ";
    }

    // line 13
    public function block_body($context, array $blocks = array())
    {
        // line 15
        echo "

";
    }

    // line 18
    public function block_javascriptsMap($context, array $blocks = array())
    {
        echo "

";
    }

    public function getTemplateName()
    {
        return "AcmeCovoiturageBundle:map:Map.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  92 => 41,  85 => 39,  68 => 27,  55 => 18,  49 => 15,  46 => 13,  33 => 3,  30 => 2,  11 => 1,);
    }
}
/* {% extends '::base.html.twig' %}*/
/* {% block styleMap %}*/
/*    {% endblock %}*/
/* {% block body -%}*/
/* */
/* */
/*

*/
/* {% endblock %}*/
/* {% block javascriptsMap %} */
/*     */
/* */
/* {% endblock %}*/


text:
<?php

namespace Iluminar\VPS\Core;

class Volume extends VPS
{
    protected $endpoint = 'volumes';
    protected $id;

    public function __construct($id)
    {
        parent::setHeader();
        $this->id = $id;
    }
}


text:
// ReSharper disable All

namespace OpenTl.Schema
{
    using System;
	using System.Collections;

	using OpenTl.Schema;

    public interface IPostAddress : IObject
    {
       byte[] StreetLine1AsBinary {get; set;}
       string StreetLine1 {get; set;}

       byte[] StreetLine2AsBinary {get; set;}
       string StreetLine2 {get; set;}

       byte[] CityAsBinary {get; set;}
       string City {get; set;}

       byte[] StateAsBinary {get; set;}
       string State {get; set;}

       byte[] CountryIso2AsBinary {get; set;}
       string CountryIso2 {get; set;}

       byte[] PostCodeAsBinary {get; set;}
       string PostCode {get; set;}

    }
}


text:
using System.Threading.Tasks;
using JustSaying.Messaging.MessageHandling;
using JustSaying.TestingFramework;

namespace JustSaying.AwsTools.UnitTests.MessageHandling.SqsNotificationListener.Support
{
    public class SignallingHandler<T> : IHandlerAsync<T>
    {
        private readonly TaskCompletionSource<object> _doneSignal;
        private readonly IHandlerAsync<T> _inner;

        public SignallingHandler(TaskCompletionSource<object> doneSignal, IHandlerAsync<T> inner)
        {
            _doneSignal = doneSignal;
            _inner = inner;
        }

        public async Task<bool> Handle(T message)
        {
            try
            {
                return await _inner.Handle(message);
            }
            finally
            {
                Tasks.DelaySendDone(_doneSignal);
            }
        }
    }
}


text:
package nick.dev.sina.app.content;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v7.graphics.Palette;
import android.widget.ImageView;

import com.nick.scalpel.ScalpelAutoActivity;
import com.nick.scalpel.annotation.binding.FindView;
import com.nick.scalpel.annotation.binding.OnClick;

import dev.nick.imageloader.ImageLoader;
import dev.nick.imageloader.LoadingListener;
import dev.nick.imageloader.display.DisplayOption;
import dev.nick.imageloader.display.ImageQuality;
import dev.nick.imageloader.loader.result.BitmapResult;
import dev.nick.imageloader.logger.LoggerManager;
import nick.dev.sina.R;
import nick.dev.sina.app.widget.ColorUtils;

public class FeedImageViewerActivity extends ScalpelAutoActivity {

    @FindView(id = R.id.image)
    @OnClick(action = "finish")
    ImageView mImageView;

    @FindView(id = R.id.fab)
    FloatingActionButton mFab;

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

        setContentView(R.layout.image_viewer);

        String thumb = getIntent().getStringExtra("thumb");

        //   ImageLoader.shared(this).displayImage(thumb, mImageView);

        String url = getIntent().getStringExtra("url");

        ImageLoader.shared()
                .load()
                .from(url)
                .listener(new LoadingListener.Stub() {
                    @Override
                    public void onComplete(@Nullable BitmapResult result) {
                        LoggerManager.getLogger(FeedImageViewerActivity.class).funcEnter();
                        if (result != null && result.result != null) {
                            Palette.from(result.result).generate(new Palette.PaletteAsyncListener() {
                                @Override
                                public void onGenerated(Palette palette) {
                                    LoggerManager.getLogger(FeedImageViewerActivity.class).funcEnter();
                                    int defColor = ContextCompat.getColor(FeedImageViewerActivity.this, R.color.primary_light);
                                    int themeColor = ColorUtils.colorBurn(palette.getLightVibrantColor(defColor));
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                        getWindow().setStatusBarColor(themeColor);
                                        getWindow().setNavigationBarColor(themeColor);
                                    }
                                }
                            });
                        }
                    }
                })
                .option(DisplayOption.builder()
                        .imageQuality(ImageQuality.RAW)
                        .oneAfterOne()
                        .build())
                .into(mImageView)
                .start();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.activity_out);
    }
}


text:
class StoriesController < ApplicationController

  after_filter :static_content

  def index
    all_stories = EmergencyStory.order("index,id ASC").all
    @selected_story = all_stories.select {|s| s.selected}.first
    @stories = all_stories.collect.select {|s| !s.selected}
  end

end


text:
@interface ImActorModelModulesUpdatesInternalGroupCreated () {
 @public
  APGroup *group_;
  id<JavaUtilList> users_;
  id<AMCommandCallback> callback_;
}

@end

J2OBJC_FIELD_SETTER(ImActorModelModulesUpdatesInternalGroupCreated, group_, APGroup *)
J2OBJC_FIELD_SETTER(ImActorModelModulesUpdatesInternalGroupCreated, users_, id<JavaUtilList>)
J2OBJC_FIELD_SETTER(ImActorModelModulesUpdatesInternalGroupCreated, callback_, id<AMCommandCallback>)

@implementation ImActorModelModulesUpdatesInternalGroupCreated

- (instancetype)initWithAPGroup:(APGroup *)group
               withJavaUtilList:(id<JavaUtilList>)users
          withAMCommandCallback:(id<AMCommandCallback>)callback {
  ImActorModelModulesUpdatesInternalGroupCreated_initWithAPGroup_withJavaUtilList_withAMCommandCallback_(self, group, users, callback);
  return self;
}

- (APGroup *)getGroup {
  return group_;
}

- (id<JavaUtilList>)getUsers {
  return users_;
}

- (id<AMCommandCallback>)getCallback {
  return callback_;
}

@end

void ImActorModelModulesUpdatesInternalGroupCreated_initWithAPGroup_withJavaUtilList_withAMCommandCallback_(ImActorModelModulesUpdatesInternalGroupCreated *self, APGroup *group, id<JavaUtilList> users, id<AMCommandCallback> callback) {
  (void) ImActorModelModulesUpdatesInternalInternalUpdate_init(self);
  self->group_ = group;
  self->users_ = users;
  self->callback_ = callback;
}

ImActorModelModulesUpdatesInternalGroupCreated *new_ImActorModelModulesUpdatesInternalGroupCreated_initWithAPGroup_withJavaUtilList_withAMCommandCallback_(APGroup *group, id<JavaUtilList> users, id<AMCommandCallback> callback) {
  ImActorModelModulesUpdatesInternalGroupCreated *self = [ImActorModelModulesUpdatesInternalGroupCreated alloc];
  ImActorModelModulesUpdatesInternalGroupCreated_initWithAPGroup_withJavaUtilList_withAMCommandCallback_(self, group, users, callback);
  return self;
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(ImActorModelModulesUpdatesInternalGroupCreated)


text:
import Ember from 'ember';
import layout from '../../templates/components/form-for/custom-tag';

const {
  Component
} = Ember;

export default Component.extend({
  layout,
  attributeBindings: ['id', 'role']
});


text:
(function() {
  'use strict';

angular
  .module('mytodo')
  .factory('MemberService', ['$http','$q', function ($http, $q) {
    var service = {};

    service.createMember = function (formData) {
      var deferred = $q.defer();
      $http.post('/api/members/signup', formData)
        .success(function (data) {
          deferred.resolve(data);
        })
        .error(function (data) {
          deferred.reject('Error: ', data);
        });
        return deferred.promise;
    };

    service.loginMember = function (formData) {
      var deferred = $q.defer();
      $http.post('/api/members/login', formData)
        .success(function (data) {
          deferred.resolve(data);
        })
        .error(function (data) {
          deferred.reject('Error: ', data);
        });
        return deferred.promise;
    };

    return service;
  }]);
})();


text:
#import <ABI42_0_0React/ABI42_0_0RCTInvalidating.h>
#import <ABI42_0_0React/ABI42_0_0RCTURLRequestHandler.h>

/**
 * This is the default ABI42_0_0RCTURLRequestHandler implementation for HTTP requests.
 */
@interface ABI42_0_0RCTHTTPRequestHandler : NSObject <ABI42_0_0RCTURLRequestHandler, ABI42_0_0RCTInvalidating>

@end


text:
import mock
import pytest

from mercury.rpc.controller import RPCController

@pytest.fixture()
def frontend_controller(async_mongodb):
    jobs_collection = async_mongodb.rpc_jobs
    tasks_collection = async_mongodb.rpc_tasks
    inventory_client = mock.Mock()
    controller = RPCController(inventory_client,
                               jobs_collection,
                               tasks_collection)
    return controller

class TestFrontendController(object):

    @pytest.mark.asyncio
    async def test_get_job(self, frontend_controller):
        job = await frontend_controller.get_job('job-1')
        assert job.get('job_id') == 'job-1'

    @pytest.mark.asyncio
    async def test_get_job_none(self, frontend_controller):
        job = await frontend_controller.get_job('job-x')
        assert job == None


text:
using System;
using Newtonsoft.Json;

namespace WatsonServices.Models.VisualRecognition
{
    public class ClassifierOwnerJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(ClassifierOwner);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            try
            {
                // "IBM" should be capitalized but "me" should be lowercase
                writer.WriteValue(
                    (ClassifierOwner)value == ClassifierOwner.IBM
                    ? ((ClassifierOwner)value).ToString()
                    : ((ClassifierOwner)value).ToString().ToLowerInvariant());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}


text:
@implementation DHSplitTextureSceneMesh
- (void) generateVerticesAndIndicesForView:(UIView *)view containerView:(UIView *)containerView columnCount:(NSInteger)columnCount rowCount:(NSInteger)rowCount columnMajored:(BOOL)columnMajor rotateTexture:(BOOL)rotateTexture
{
    self.vertexCount = columnCount * rowCount * 4;
    self.indexCount = columnCount * rowCount * 6;
    self.verticesSize = self.vertexCount * sizeof(SceneMeshVertex);
    self.indicesSize = self.indexCount * sizeof(GLuint);

    vertices = malloc(self.verticesSize);
    indices = malloc(self.indicesSize);

    if (columnMajor) {
        [self generateColumnMajoredVerticesForSplitTextureForView:view columnCount:columnCount rowCount:rowCount rotateTexture:rotateTexture];
    } else {
        [self generateRowMajoredVerticesForSplitTextureForView:view columnCount:columnCount rowCount:rowCount rotateTexture:rotateTexture];
    }

    if (rotateTexture == NO) {
        float angle = atan(view.transform.c / view.transform.a);
        GLKMatrix4 transformMatrix = GLKMatrix4MakeTranslation(-(self.originX + view.bounds.size.width / 2), -(containerView.frame.size.height - CGRectGetMaxY(view.frame) + view.bounds.size.height / 2), 0);
        GLKMatrix4 rotationMatrix = GLKMatrix4MakeRotation(angle, 0, 0, 1);
        transformMatrix = GLKMatrix4Multiply(rotationMatrix, transformMatrix);
        GLKMatrix4 translateBackMatrix = GLKMatrix4MakeTranslation(self.originX + view.frame.size.width / 2, containerView.frame.size.height - CGRectGetMaxY(view.frame) + view.frame.size.height / 2, 0);
        transformMatrix = GLKMatrix4Multiply(translateBackMatrix, transformMatrix);

        for (int i = 0; i < self.vertexCount; i++) {
            GLKVector4 rotatedPos = GLKVector4Make(vertices[i].position.x, vertices[i].position.y, vertices[i].position.z, 1);
            rotatedPos = GLKMatrix4MultiplyVector4(transformMatrix, rotatedPos);
            vertices[i].position = GLKVector3Make(rotatedPos.x, rotatedPos.y, rotatedPos.z );
        }
    }

    int index = 0;
    for (int x = 0; x < columnCount; x++) {
        for (int y = 0; y < rowCount; y++) {
            index = x * (int)rowCount + y;
            indices[index * 6 + 0] = index * 4;
            indices[index * 6 + 1] = index * 4 + 1;
            indices[index * 6 + 2] = index * 4 + 2;
            indices[index * 6 + 3] = index * 4 + 2;
            indices[index * 6 + 4] = index * 4 + 1;
            indices[index * 6 + 5] = index * 4 + 3;
        }
    }
}

- (void) generateColumnMajoredVerticesForSplitTextureForView:(UIView *)view columnCount:(NSInteger)columnCount rowCount:(NSInteger)rowCount rotateTexture:(BOOL)rotateTexture
{
    CGRect rect = view.bounds;
    if (rotateTexture) {
        rect = view.frame;
    }
    NSInteger index = 0;
    CGFloat ux = 1.f / columnCount;
    CGFloat uy = 1.f / rowCount;
    for (int x = 0; x < columnCount; x++) {
        CGFloat vx = ux * x;
        for (int y = 0; y < rowCount; y++) {
            CGFloat vy = uy * y;
            index = (x * rowCount + y) * 4;
            vertices[index + 0].position = GLKVector3Make(self.originX + vx * rect.size.width, self.originY + vy * rect.size.height, 0);
            vertices[index + 0].texCoords = GLKVector2Make(vx, 1 - vy);

            vertices[index + 1].position = GLKVector3Make(self.originX + (vx + ux) * rect.size.width, self.originY + vy * rect.size.height, 0);
            vertices[index + 1].texCoords = GLKVector2Make(vx + ux, 1 - vy);

            vertices[index + 2].position = GLKVector3Make(self.originX + vx * rect.size.width, self.originY + (vy + uy) * rect.size.height, 0);
            vertices[index + 2].texCoords = GLKVector2Make(vx, 1 - (vy + uy));

            vertices[index + 3].position = GLKVector3Make(self.originX + (vx + ux) * rect.size.width, self.originY + (vy + uy) * rect.size.height, 0);
            vertices[index + 3].texCoords = GLKVector2Make(vx + ux, 1 - (vy + uy));

            vertices[index + 0].columnStartPosition = vertices[index + 0].position;
            vertices[index + 1].columnStartPosition = vertices[index + 0].position;
            vertices[index + 2].columnStartPosition = vertices[index + 0].position;
            vertices[index + 3].columnStartPosition = vertices[index + 0].position;
            [self setupForVertexAtX:x y:y index:index];

            vertices[index + 0].normal = GLKVector3Make(0, 0, 1);
            vertices[index + 1].normal = GLKVector3Make(0, 0, 1);
            vertices[index + 2].normal = GLKVector3Make(0, 0, 1);
            vertices[index + 3].normal = GLKVector3Make(0, 0, 1);
        }
    }
}

- (void) generateRowMajoredVerticesForSplitTextureForView:(UIView *)view columnCount:(NSInteger)columnCount rowCount:(NSInteger)rowCount rotateTexture:(BOOL)rotateTexture
{
    CGRect rect = view.bounds;
    if (rotateTexture) {
        rect = view.frame;
    }
    NSInteger index = 0;
    CGFloat ux = 1.f / columnCount;
    CGFloat uy = 1.f / rowCount;
    for (int y = 0; y < rowCount; y++) {
        CGFloat vy = uy * y;
        for (int x = 0; x < columnCount; x++) {
            CGFloat vx = ux * x;
            index = (y * columnCount + x) * 4;
            vertices[index + 0].position = GLKVector3Make(self.originX + vx * rect.size.width, self.originY + vy * rect.size.height, 0);
            vertices[index + 0].texCoords = GLKVector2Make(vx, 1 - vy);

            vertices[index + 1].position = GLKVector3Make(self.originX + (vx + ux) * rect.size.width, self.originY + vy * rect.size.height, 0);
            vertices[index + 1].texCoords = GLKVector2Make(vx + ux, 1 - vy);

            vertices[index + 2].position = GLKVector3Make(self.originX + vx * rect.size.width, self.originY + (vy + uy) * rect.size.height, 0);
            vertices[index + 2].texCoords = GLKVector2Make(vx, 1 - (vy + uy));

            vertices[index + 3].position = GLKVector3Make(self.originX + (vx + ux) * rect.size.width, self.originY + (vy + uy) * rect.size.height, 0);
            vertices[index + 3].texCoords = GLKVector2Make(vx + ux, 1 - (vy + uy));

            vertices[index + 0].columnStartPosition = vertices[index + 0].position;
            vertices[index + 1].columnStartPosition = vertices[index + 0].position;
            vertices[index + 2].columnStartPosition = vertices[index + 0].position;
            vertices[index + 3].columnStartPosition = vertices[index + 0].position;
            [self setupForVertexAtX:x y:y index:index];
            vertices[index + 0].normal = GLKVector3Make(0, 0, 1);
            vertices[index + 1].normal = GLKVector3Make(0, 0, 1);
            vertices[index + 2].normal = GLKVector3Make(0, 0, 1);
            vertices[index + 3].normal = GLKVector3Make(0, 0, 1);
        }
    }
}
@end


text:
package org.apache.airavata.sharing.registry;

import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.sharing.registry.models.*;
import org.apache.airavata.sharing.registry.service.cpi.SharingRegistryService;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSSLTransportFactory;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import java.util.ArrayList;
import java.util.Arrays;

public class CipresTest {
    public static void main(String[] args) throws InterruptedException, TException, ApplicationSettingsException {
        System.out.println("Hello World!");
        //should use the correct host name and port here
        String serverHost = "wb-airavata.scigap.org";

        int serverPort = 7878;
        TTransport transport = null;
        TProtocol protocol = null;
        try {

            SharingRegistryService.Client sharingServiceClient;

            //Non Secure Client
//            transport = new TSocket(serverHost, serverPort);
//            transport.open();
//            protocol = new TBinaryProtocol(transport);
//            sharingServiceClient= new SharingRegistryService.Client(protocol);

            //TLS enabled client
            TSSLTransportFactory.TSSLTransportParameters params =
                    new TSSLTransportFactory.TSSLTransportParameters();
            params.setKeyStore(ServerSettings.getKeyStorePath(), ServerSettings.getKeyStorePassword());
            params.setTrustStore(ServerSettings.getTrustStorePath(), ServerSettings.getTrustStorePassword());
            transport = TSSLTransportFactory.getClientSocket(serverHost, serverPort, 10000, params);
            protocol = new TBinaryProtocol(transport);
            sharingServiceClient = new SharingRegistryService.Client(protocol);

            try {
                sharingServiceClient.deleteDomain("test-domain");
            } catch (SharingRegistryException sre1) {
                System.out.println("deleteDomain failed" + sre1.getMessage() + "\n");
            }
            Domain domain = new Domain();
            //has to be one word
            domain.setName("test-domain");
            //optional
            domain.setDescription("test domain description");
            //domain id will be same as domain name
            String domainId = sharingServiceClient.createDomain(domain);
            System.out.println("After domain creation...\n");

            User user1 = new User();
            String userName1 = "test-user-1";
            String userId1 = "test-user-1";
            //required
            user1.setUserId(userId1);
            //required
            user1.setUserName(userName1);
            //required
            user1.setDomainId(domainId);
            //required
            user1.setFirstName("John");
            //required
            user1.setLastName("Doe");
            //required
            user1.setEmail("john.doe@abc.com");
            //optional - this should be bytes of the users image icon
            //byte[] icon = new byte[10];
            //user1.setIcon(icon);
            sharingServiceClient.createUser(user1);
            User user2 = new User();
            String userName2 = "test-user-2";
            String userId2 = "test-user-2";
            //required
            user2.setUserId(userId2);
            //required
            user2.setUserName(userName2);
            //required
            user2.setDomainId(domainId);
            //required
            user2.setFirstName("John");
            //required
            user2.setLastName("Doe");
            //required
            user2.setEmail("john.doe@abc.com");
            //optional - this should be bytes of the users image icon
            //byte[] icon = new byte[20];
            //user2.setIcon(icon);
            sharingServiceClient.createUser(user2);
            User user3 = new User();
            String userName3 = "test-user-3";
            String userId3 = "test-user-3";
            //required
            user3.setUserId(userId3);
            //required
            user3.setUserName(userName3);
            //required
            user3.setDomainId(domainId);
            //required
            user3.setFirstName("John");
            //required
            user3.setLastName("Doe");
            //required
            user3.setEmail("john.doe@abc.com");
            //optional - this should be bytes of the users image icon
            //byte[] icon = new byte[30];
            //user3.setIcon(icon);
            sharingServiceClient.createUser(user3);
            System.out.println("After user creation...\n");

            UserGroup userGroup1 = new UserGroup();
            //required
            userGroup1.setGroupId("test-group-1");
            //required
            userGroup1.setDomainId(domainId);
            //required
            userGroup1.setName("test-group-1");
            //optional
            //userGroup1.setDescription("test group description");
            //required
            userGroup1.setOwnerId("test-user-1");
            //required
            userGroup1.setGroupType(GroupType.USER_LEVEL_GROUP);
            sharingServiceClient.createGroup(userGroup1);
            //Similarly create another group "userGroup2" with the owner being "test-user-2".
            UserGroup userGroup2 = new UserGroup();
            //required
            userGroup2.setGroupId("test-group-2");
            //required
            userGroup2.setDomainId(domainId);
            //required
            userGroup2.setName("test-group-2");
            //optional
            //userGroup2.setDescription("test group description");
            //required
            userGroup2.setOwnerId("test-user-2");
            //required
            userGroup2.setGroupType(GroupType.USER_LEVEL_GROUP);
            sharingServiceClient.createGroup(userGroup2);
            System.out.println("After group creation...\n");

            sharingServiceClient.addUsersToGroup(domainId, Arrays.asList("test-user-3"), "test-group-2");
            System.out.println("After adding user to group...\n");

            sharingServiceClient.addChildGroupsToParentGroup(domainId, Arrays.asList("test-group-2"), "test-group-1");

            PermissionType permissionType1 = new PermissionType();
            //required
            permissionType1.setPermissionTypeId("READ");
            //required
            permissionType1.setDomainId(domainId);
            //required
            permissionType1.setName("READ");
            //optional
            permissionType1.setDescription("READ description");
            sharingServiceClient.createPermissionType(permissionType1);
            PermissionType permissionType2 = new PermissionType();
            permissionType2.setPermissionTypeId("WRITE");
            permissionType2.setDomainId(domainId);
            permissionType2.setName("WRITE");
            permissionType2.setDescription("WRITE description");
            sharingServiceClient.createPermissionType(permissionType2);
            PermissionType permissionType3 = new PermissionType();
            permissionType3.setPermissionTypeId("CLONE");
            permissionType3.setDomainId(domainId);
            permissionType3.setName("CLONE");
            permissionType3.setDescription("CLONE description");
            sharingServiceClient.createPermissionType(permissionType3);
            System.out.println("After adding groups to parent group...\n");

            EntityType entityType1 = new EntityType();
            //required
            entityType1.setEntityTypeId("PROJECT");
            //required
            entityType1.setDomainId(domainId);
            //required
            entityType1.setName("PROJECT");
            //optional
            entityType1.setDescription("PROJECT entity type description");
            sharingServiceClient.createEntityType(entityType1);
            EntityType entityType2 = new EntityType();
            entityType2.setEntityTypeId("EXPERIMENT");
            entityType2.setDomainId(domainId);
            entityType2.setName("EXPERIMENT");
            entityType2.setDescription("EXPERIMENT entity type");
            sharingServiceClient.createEntityType(entityType2);
            EntityType entityType3 = new EntityType();
            entityType3.setEntityTypeId("FILE");
            entityType3.setDomainId(domainId);
            entityType3.setName("FILE");
            entityType3.setDescription("FILE entity type");
            sharingServiceClient.createEntityType(entityType3);
            System.out.println("After project entity creation...\n");

            Entity entity1 = new Entity();
            //required
            entity1.setEntityId("test-project-1");
            //required
            entity1.setDomainId(domainId);
            //required
            entity1.setEntityTypeId("PROJECT");
            //required
            entity1.setOwnerId("test-user-1");
            //required
            entity1.setName("test-project-1");
            //optional
            entity1.setDescription("test project 1 description");
            //optional
            entity1.setFullText("test project 1 stampede gaussian seagrid");
            //optional - If not set this will be default to current system time
            entity1.setOriginalEntityCreationTime(System.currentTimeMillis());
            sharingServiceClient.createEntity(entity1);
            System.out.println("After currentTimeMillis()...\n");
            Entity entity2 = new Entity();
            entity2.setEntityId("test-experiment-1");
            entity2.setDomainId(domainId);
            entity2.setEntityTypeId("EXPERIMENT");
            entity2.setOwnerId("test-user-1");
            entity2.setName("test-experiment-1");
            entity2.setDescription("test experiment 1 description");
            entity2.setParentEntityId("test-project-1");
            entity2.setFullText("test experiment 1 benzene");
            System.out.println("Before sharingServiceClient.createEntity entity2...\n");
            sharingServiceClient.createEntity(entity2);
            System.out.println("After sharingServiceClient.createEntity entity2...\n");
            Entity entity3 = new Entity();
            entity3.setEntityId("test-experiment-2");
            entity3.setDomainId(domainId);
            entity3.setEntityTypeId("EXPERIMENT");
            entity3.setOwnerId("test-user-1");
            entity3.setName("test-experiment-2");
            entity3.setDescription("test experiment 2 description");
            entity3.setParentEntityId("test-project-1");
            entity3.setFullText("test experiment 1 3-methyl 1-butanol stampede");
            sharingServiceClient.createEntity(entity3);
            System.out.println("After sharingServiceClient.createEntity entity3...\n");
            Entity entity4 = new Entity();
            entity4.setEntityId("test-file-1");
            entity4.setDomainId(domainId);
            entity4.setEntityTypeId("FILE");
            entity4.setOwnerId("test-user-1");
            entity4.setName("test-file-1");
            entity4.setDescription("test file 1 description");
            entity4.setParentEntityId("test-experiment-2");
            entity4.setFullText("test input file 1 for experiment 2");
            sharingServiceClient.createEntity(entity4);
            System.out.println("After sharingServiceClient.createEntity entity4...\n");
            System.out.println("After test entity creation...\n");

            //shared with cascading permissions
            //System.out.println("Before shareEntityWithUsers WRITE...\n");
            //sharingServiceClient.shareEntityWithUsers(domainId, "test-project-1", Arrays.asList("test-user-2"), "WRITE", true);
            System.out.println("Before shareEntityWithGroups READ...\n");
            long time = System.currentTimeMillis();
            sharingServiceClient.shareEntityWithGroups(domainId, "test-experiment-2", Arrays.asList("test-group-2"), "READ", true);
            System.out.println("Time for sharing " + (System.currentTimeMillis() - time));
            //shared with non cascading permissions
            System.out.println("Before shareEntityWithGroups CLONE...\n");
            time = System.currentTimeMillis();
            sharingServiceClient.shareEntityWithGroups(domainId, "test-experiment-2", Arrays.asList("test-group-2"), "CLONE", false);
            System.out.println("Time for sharing " + (System.currentTimeMillis() - time));

            //test-project-1 is explicitly shared with test-user-2 with WRITE permission
            System.out.println("Before userHasAccess 1...\n");
            System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-project-1", "WRITE"));
            //test-user-2 has WRITE permission to test-experiment-1 and test-experiment-2 indirectly
            System.out.println("Before userHasAccess 2...\n");
            System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-experiment-1", "WRITE"));
            System.out.println("Before userHasAccess 3...\n");
            System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-experiment-2", "WRITE"));
            //test-user-2 does not have READ permission to test-experiment-1 and test-experiment-2
            System.out.println("Before userHasAccess 4...\n");
            System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-experiment-1", "READ"));
            System.out.println(domainId + " test-user-2 " + " test-experiment-2 " + " READ ");
            System.out.println("Before userHasAccess 5...\n");
            System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-experiment-2", "READ"));
            //test-user-3 does not have READ permission to test-project-1
            System.out.println("Before userHasAccess 6...\n");
            System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-project-1", "READ"));
            //test-experiment-2 is shared with test-group-2 with READ permission. Therefore test-user-3 has READ permission
            System.out.println("Before userHasAccess 7...\n");
            System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-experiment-2", "READ"));
            //test-user-3 does not have WRITE permission to test-experiment-2
            System.out.println("Before userHasAccess 8...\n");
            System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-experiment-2", "WRITE"));
            //test-user-3 has CLONE permission to test-experiment-2
            System.out.println("Before userHasAccess 9...\n");
            System.out.println((sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-experiment-2", "CLONE")));
            //test-user-3 does not have CLONE permission to test-file-1
            System.out.println("Before userHasAccess 10...\n");
            System.out.println((sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-file-1", "CLONE")));
            System.out.println("After cascading permissions...\n");

            ArrayList<SearchCriteria> filters = new ArrayList<>();
            //ArrayList<SearchCriteria> filters = new List<>();
            SearchCriteria searchCriteria = new SearchCriteria();
            searchCriteria.setSearchCondition(SearchCondition.LIKE);
            searchCriteria.setValue("experiment stampede methyl");
            //searchCriteria.setValue("stampede");
            //searchCriteria.setSearchField(EntitySearchField.NAME);
            searchCriteria.setSearchField(EntitySearchField.FULL_TEXT);
            filters.add(searchCriteria);
            searchCriteria = new SearchCriteria();
            searchCriteria.setSearchCondition(SearchCondition.EQUAL);
            searchCriteria.setValue("READ");
            searchCriteria.setSearchField(EntitySearchField.PERMISSION_TYPE_ID);
            filters.add(searchCriteria);
            System.out.println(sharingServiceClient.searchEntities(domainId, "test-user-2", filters, 0, -1).size());
            System.out.println(sharingServiceClient.searchEntities(domainId, "test-user-2", filters, 0, -1));
            System.out.println("After searchEntities...\n");

            //System.out.println("After searchEntities...\n");
            User userA = new User();
            String userNameA = "UserA";
            String userIdA = "UserA";
            //required
            userA.setUserId(userIdA);
            //required
            userA.setUserName(userNameA);
            //required
            userA.setDomainId(domainId);
            //required
            userA.setFirstName("User");
            //required
            userA.setLastName("A");
            //required
            userA.setEmail("user.a@example.com");
            //optional - this should be bytes of the users image icon
            //byte[] icon = new byte[10];
            //userA.setIcon(icon);
            sharingServiceClient.createUser(userA);
            User userB = new User();
            String userNameB = "UserB";
            String userIdB = "UserB";
            //required
            userB.setUserId(userIdB);
            //required
            userB.setUserName(userNameB);
            //required
            userB.setDomainId(domainId);
            //required
            userB.setFirstName("User");
            //required
            userB.setLastName("B");
            //required
            userB.setEmail("user.b@example.com");
            //optional - this should be bytes of the users image icon
            //byte[] icon = new byte[10];
            //userB.setIcon(icon);
            sharingServiceClient.createUser(userB);
            User userC = new User();
            String userNameC = "UserC";
            String userIdC = "UserC";
            //required
            userC.setUserId(userIdC);
            //required
            userC.setUserName(userNameC);
            //required
            userC.setDomainId(domainId);
            //required
            userC.setFirstName("User");
            //required
            userC.setLastName("C");
            //required
            userC.setEmail("user.c@example.com");
            //optional - this should be bytes of the users image icon
            //byte[] icon = new byte[10];
            //userC.setIcon(icon);
            sharingServiceClient.createUser(userC);
            User userD = new User();
            String userNameD = "UserD";
            String userIdD = "UserD";
            //required
            userD.setUserId(userIdD);
            //required
            userD.setUserName(userNameD);
            //required
            userD.setDomainId(domainId);
            //required
            userD.setFirstName("User");
            //required
            userD.setLastName("D");
            //required
            userD.setEmail("user.d@example.com");
            //optional - this should be bytes of the users image icon
            //byte[] icon = new byte[10];
            //userD.setIcon(icon);
            sharingServiceClient.createUser(userD);
            System.out.println("After user creation...\n");

            UserGroup Group1 = new UserGroup();
            //required
            Group1.setGroupId("Group1");
            //required
            Group1.setDomainId(domainId);
            //required
            Group1.setName("Group1");
            //optional
            //userGroup1.setDescription("test group description");
            //required
            Group1.setOwnerId("UserA");
            //required
            Group1.setGroupType(GroupType.USER_LEVEL_GROUP);
            sharingServiceClient.createGroup(Group1);
            System.out.println("After Group1 creation...\n");

            sharingServiceClient.addUsersToGroup(domainId, Arrays.asList("UserB"), "Group1");
            sharingServiceClient.addUsersToGroup(domainId, Arrays.asList("UserC"), "Group1");
            sharingServiceClient.addUsersToGroup(domainId, Arrays.asList("UserD"), "Group1");

            System.out.println("After adding users to Group1 creation...\n");

            EntityType entityTypeFolder = new EntityType();
            //required
            entityTypeFolder.setEntityTypeId("FOLDER");
            //required
            entityTypeFolder.setDomainId(domainId);
            //required
            entityTypeFolder.setName("FOLDER");
            //optional
            //entityTypeFolder.setDescription("PROJECT entity type description");
            sharingServiceClient.createEntityType(entityTypeFolder);
            System.out.println("After creating FOLDER entity type...\n");

            EntityType entityTypeInputData = new EntityType();
            //required
            entityTypeInputData.setEntityTypeId("INPUTDATA");
            //required
            entityTypeInputData.setDomainId(domainId);
            //required
            entityTypeInputData.setName("INPUTDATA");
            //optional
            //entityTypeFolder.setDescription("PROJECT entity type description");
            sharingServiceClient.createEntityType(entityTypeInputData);
            System.out.println("After creating INPUTDATA entity type...\n");

            Entity entityB1 = new Entity();
            //required
            entityB1.setEntityId("UserBProject1");
            //required
            entityB1.setDomainId(domainId);
            //required
            entityB1.setEntityTypeId("PROJECT");
            //required
            entityB1.setOwnerId("UserB");
            //required
            entityB1.setName("UserBProject1");
            //optional
            entityB1.setDescription("User B's Project 1");
            //optional
            entityB1.setFullText("test project 1");
            //optional - If not set this will be default to current system time
            entityB1.setOriginalEntityCreationTime(System.currentTimeMillis());
            sharingServiceClient.createEntity(entityB1);
            System.out.println("After creating UserBProject1 ...\n");

            Entity entityC1 = new Entity();
            //required
            entityC1.setEntityId("UserCProject2");
            //required
            entityC1.setDomainId(domainId);
            //required
            entityC1.setEntityTypeId("PROJECT");
            //required
            entityC1.setOwnerId("UserC");
            //required
            entityC1.setName("UserCProject2");
            //optional
            entityC1.setDescription("User C's Project 2");
            //optional
            entityC1.setFullText("test project 2");
            //optional - If not set this will be default to current system time
            entityC1.setOriginalEntityCreationTime(System.currentTimeMillis());
            sharingServiceClient.createEntity(entityC1);
            System.out.println("After creating UserCProject2 ...\n");

            Entity entityF1 = new Entity();
            entityF1.setEntityId("Folder1");
            entityF1.setDomainId(domainId);
            entityF1.setEntityTypeId("FOLDER");
            entityF1.setOwnerId("UserB");
            entityF1.setName("UserBFolder1");
            entityF1.setDescription("UserB's Folder 1");
            entityF1.setParentEntityId("UserBProject1");
            entityF1.setFullText("test experiment 1 ethidium");
            sharingServiceClient.createEntity(entityF1);
            System.out.println("After creating Folder1 ...\n");

            Entity entityD1 = new Entity();
            entityD1.setEntityId("Data1");
            entityD1.setDomainId(domainId);
            entityD1.setEntityTypeId("INPUTDATA");
            entityD1.setOwnerId("UserB");
            entityD1.setName("UserBData1");
            entityD1.setDescription("UserB's Data 1");
            entityD1.setParentEntityId("Folder1");
            entityD1.setFullText("Data 1 for User B Folder 1");
            sharingServiceClient.createEntity(entityD1);
            System.out.println("After creating Data1 ...\n");

            Entity entityF2 = new Entity();
            entityF2.setEntityId("Folder2");
            entityF2.setDomainId(domainId);
            entityF2.setEntityTypeId("FOLDER");
            entityF2.setOwnerId("UserC");
            entityF2.setName("UserCFolder2");
            entityF2.setDescription("UserC's Folder 2");
            entityF2.setParentEntityId("UserCProject2");
            entityF2.setFullText("test experiment 2 ethidium");
            sharingServiceClient.createEntity(entityF2);
            System.out.println("After creating Folder2 ...\n");

            Entity entityD2 = new Entity();
            entityD2.setEntityId("Data2");
            entityD2.setDomainId(domainId);
            entityD2.setEntityTypeId("INPUTDATA");
            entityD2.setOwnerId("UserC");
            entityD2.setName("UserCData2");
            entityD2.setDescription("UserC's Data 2");
            entityD2.setParentEntityId("Folder2");
            entityD2.setFullText("Data 2 for User C Folder 1");
            sharingServiceClient.createEntity(entityD2);
            System.out.println("After creating Data2 ...\n");

            //sharingServiceClient.shareEntityWithGroups(domainId, "test-experiment-2", Arrays.asList("test-group-2"), "READ", true);
            time = System.currentTimeMillis();
            sharingServiceClient.shareEntityWithGroups(domainId, "Folder1", Arrays.asList("Group1"), "READ", true);
            System.out.println("Time for sharing " + (System.currentTimeMillis() - time));
            System.out.println("After READ sharing UserBFolder1 with Group1 ...\n");
            //sharingServiceClient.shareEntityWithGroups(domainId, "Folder2", Arrays.asList("Group1"), "READ", true);
            //System.out.println("After READ sharing UserCFolder2 with Group1 ...\n");

            Entity entityD3 = new Entity();
            entityD3.setEntityId("Data3");
            entityD3.setDomainId(domainId);
            entityD3.setEntityTypeId("INPUTDATA");
            entityD3.setOwnerId("UserC");
            entityD3.setName("UserCData3");
            entityD3.setDescription("UserC's Data 3");
            entityD3.setParentEntityId("Folder2");
            entityD3.setFullText("Data 3 for User C Folder 2");
            sharingServiceClient.createEntity(entityD3);
            System.out.println("After creating Data3 ...\n");

            System.out.println("Does UserC have READ access to Data1 ...\n");
            System.out.println(sharingServiceClient.userHasAccess(domainId, "UserC", "Data1", "READ"));
            System.out.println("Does UserC have READ access to Data2 ...\n");
            System.out.println(sharingServiceClient.userHasAccess(domainId, "UserC", "Data2", "READ"));
            System.out.println("Does UserC have READ access to Data3 ...\n");
            System.out.println(sharingServiceClient.userHasAccess(domainId, "UserC", "Data3", "READ"));
            System.out.println("Does UserB have READ access to Data3 ...\n");
            System.out.println(sharingServiceClient.userHasAccess(domainId, "UserB", "Data3", "READ"));

            ArrayList<SearchCriteria> sharedfilters = new ArrayList<>();
            searchCriteria = new SearchCriteria();
            searchCriteria.setSearchCondition(SearchCondition.EQUAL);
            searchCriteria.setValue("READ");
            searchCriteria.setSearchField(EntitySearchField.PERMISSION_TYPE_ID);
            sharedfilters.add(searchCriteria);
            System.out.println("items READable by UserC ...\n");
            System.out.println(sharingServiceClient.searchEntities(domainId, "UserC", sharedfilters, 0, -1).size());
            System.out.println(sharingServiceClient.searchEntities(domainId, "UserC", sharedfilters, 0, -1));
            searchCriteria = new SearchCriteria();
            //searchCriteria.setSearchCondition(SearchCondition.EQUAL);
            searchCriteria.setSearchCondition(SearchCondition.NOT);
            searchCriteria.setValue("UserC");
            searchCriteria.setSearchField(EntitySearchField.OWNER_ID);
            sharedfilters.add(searchCriteria);
            System.out.println("items READable, and not owned by UserC by UserC ...\n");
            System.out.println(sharingServiceClient.searchEntities(domainId, "UserC", sharedfilters, 0, -1).size());
            System.out.println(sharingServiceClient.searchEntities(domainId, "UserC", sharedfilters, 0, -1));
            System.out.println("After searchEntities 2...\n");

            System.out.println(sharingServiceClient.searchEntities(domainId, "UserC", sharedfilters, 0, -1).size());
            System.out.println(sharingServiceClient.searchEntities(domainId, "UserC", sharedfilters, 0, -1));
            System.out.println("After searchEntities 2...\n");

            sharingServiceClient.removeUsersFromGroup(domainId, Arrays.asList("UserD"), "Group1");
            System.out.println("After removing UserD from Group1 ...\n");

            sharingServiceClient.deleteGroup(domainId, "Group1");
            System.out.println("After deleting Group1 ...\n");

            System.out.println("End of try clause...\n");
        } catch (TTransportException ex1) {
            System.out.println("TTransportException...\n");
            System.out.println(ex1);
            System.out.println(ex1.getCause());
            ex1.printStackTrace();
            System.out.println(ex1.getMessage());
        } catch (SharingRegistryException ex2) {
            System.out.println("SharingRegistryException...\n");
            System.out.println(ex2.getMessage());
        } catch (TException ex3) {
            System.out.println("TException...\n");
            System.out.println(ex3.getMessage());
        } finally {
            System.out.println("In finally...\n");
            transport.close();
        }
    }
}


text:
/**
 * SECTION:element-webmmux
 *
 * webmmux muxes VP8 video and Vorbis audio streams into a WebM file.
 *
 * <refsect2>
 * <title>Example launch line</title>
 * |[
 * gst-launch-1.0 webmmux name=mux ! filesink location=newfile.webm         \
 *   uridecodebin uri=file:///path/to/somefile.ogv name=demux                \
 *   demux. ! videoconvert ! vp8enc ! queue ! mux.video_0    \
 *   demux. ! progressreport ! audioconvert ! audiorate ! vorbisenc ! queue ! mux.audio_0
 * ]| This pipeline re-encodes a video file of any format into a WebM file.
 * |[
 * gst-launch-1.0 webmmux name=mux ! filesink location=test.webm            \
 *   videotestsrc num-buffers=250 ! video/x-raw,framerate=25/1 ! videoconvert ! vp8enc ! queue ! mux.video_0 \
 *   audiotestsrc samplesperbuffer=44100 num-buffers=10 ! audio/x-raw,rate=44100 ! vorbisenc ! queue ! mux.audio_0
 * ]| This pipeline muxes a test video and a sine wave into a WebM file.
 * </refsect2>
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "webm-mux.h"

#define COMMON_VIDEO_CAPS \
  "width = (int) [ 16, MAX ], " \
  "height = (int) [ 16, MAX ], " \
  "framerate = (fraction) [ 0, MAX ]"

#define COMMON_AUDIO_CAPS \
  "channels = (int) [ 1, MAX ], " \
  "rate = (int) [ 1, MAX ]"

G_DEFINE_TYPE (GstWebMMux, gst_webm_mux, GST_TYPE_MATROSKA_MUX);

static GstStaticPadTemplate webm_src_templ = GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("video/webm; audio/webm")
    );

static GstStaticPadTemplate webm_videosink_templ =
    GST_STATIC_PAD_TEMPLATE ("video_%u",
    GST_PAD_SINK,
    GST_PAD_REQUEST,
    GST_STATIC_CAPS ("video/x-vp8, " COMMON_VIDEO_CAPS ";"
        "video/x-vp9, " COMMON_VIDEO_CAPS ";" "video/x-av1, " COMMON_VIDEO_CAPS)
    );

static GstStaticPadTemplate webm_audiosink_templ =
    GST_STATIC_PAD_TEMPLATE ("audio_%u",
    GST_PAD_SINK,
    GST_PAD_REQUEST,
    GST_STATIC_CAPS ("audio/x-vorbis, " COMMON_AUDIO_CAPS ";"
        "audio/x-opus, " COMMON_AUDIO_CAPS)
    );

static void
gst_webm_mux_class_init (GstWebMMuxClass * klass)
{
  GstElementClass *gstelement_class = (GstElementClass *) klass;

  gst_element_class_add_static_pad_template (gstelement_class,
      &webm_videosink_templ);
  gst_element_class_add_static_pad_template (gstelement_class,
      &webm_audiosink_templ);
  gst_element_class_add_static_pad_template (gstelement_class, &webm_src_templ);
  gst_element_class_set_static_metadata (gstelement_class, "WebM muxer",
      "Codec/Muxer",
      "Muxes video and audio streams into a WebM stream",
      "GStreamer maintainers <gstreamer-devel@lists.freedesktop.org>");
}

static void
gst_webm_mux_init (GstWebMMux * mux)
{
  GST_MATROSKA_MUX (mux)->doctype = GST_MATROSKA_DOCTYPE_WEBM;
  GST_MATROSKA_MUX (mux)->is_webm = TRUE;
}


text:
package routers

import (
	"github.com/gogits/gogs/models"
	"github.com/gogits/gogs/modules/base"
	"github.com/gogits/gogs/modules/middleware"
	"github.com/gogits/gogs/modules/setting"
	"github.com/gogits/gogs/routers/user"
)

const (
	HOME base.TplName = "home"
)

func Home(ctx *middleware.Context) {
	if ctx.IsSigned {
		user.Dashboard(ctx)
		return
	}

	// Check auto-login.
	userName := ctx.GetCookie(setting.CookieUserName)
	if len(userName) != 0 {
		ctx.Redirect("/user/login")
		return
	}

	ctx.Data["PageIsHome"] = true

	// Show recent updated repositories for new visitors.
	repos, err := models.GetRecentUpdatedRepositories()
	if err != nil {
		ctx.Handle(500, "dashboard.Home(GetRecentUpdatedRepositories)", err)
		return
	}

	for _, repo := range repos {
		if err = repo.GetOwner(); err != nil {
			ctx.Handle(500, "dashboard.Home(GetOwner)", err)
			return
		}
	}
	ctx.Data["Repos"] = repos
	ctx.HTML(200, HOME)
}

func NotFound(ctx *middleware.Context) {
	ctx.Data["Title"] = "Page Not Found"
	ctx.Data["PageIsNotFound"] = true
	ctx.Handle(404, "home.NotFound", nil)
}