text:
package net.anyflow.menton.example.twitter.httphandler;

import io.netty.handler.codec.http.HttpResponseStatus;
import net.anyflow.menton.example.twitter.Database;
import net.anyflow.menton.example.twitter.MessageGenerator;
import net.anyflow.menton.example.twitter.model.Tweet;
import net.anyflow.menton.http.HttpRequestHandler;

/**
 * @author Park Hyunjeong
 */
@HttpRequestHandler.Handles(paths = { "twitter/tweet" }, httpMethods = { "DELETE" })
public class Tweet_Delete extends HttpRequestHandler {

	@Override
	public String service() {
		String id = httpRequest().parameter("id");
		if (id == null) {
			httpResponse().setStatus(HttpResponseStatus.FORBIDDEN);
			return MessageGenerator.generateJson(new Error("Invalid id"), httpResponse());
		}

		Tweet tweet = Database.instance().delete(id);
		if (tweet == null) {
			httpResponse().setStatus(HttpResponseStatus.FORBIDDEN);
			return MessageGenerator.generateJson(new Error("Invalid id"), httpResponse());
		}

		return null;
	}
}


text:
extern "Java"
{
  namespace gnu
  {
    namespace java
    {
      namespace awt
      {
        namespace peer
        {
          namespace gtk
          {
              class GtkScrollPanePeer;
          }
        }
      }
    }
  }
  namespace java
  {
    namespace awt
    {
        class Adjustable;
        class Dimension;
        class ScrollPane;
    }
  }
}

class gnu::java::awt::peer::gtk::GtkScrollPanePeer : public ::gnu::java::awt::peer::gtk::GtkContainerPeer
{

public: // actually package-private
  virtual void create(jint, jint);
  virtual void create();
  virtual void gtkScrolledWindowSetHScrollIncrement(jint);
  virtual void gtkScrolledWindowSetVScrollIncrement(jint);
public:
  GtkScrollPanePeer(::java::awt::ScrollPane *);
public: // actually package-private
  virtual void setPolicy(jint);
public:
  virtual void childResized(jint, jint);
  virtual jint getHScrollbarHeight();
  virtual jint getVScrollbarWidth();
  virtual void setScrollPosition(jint, jint);
  virtual ::java::awt::Dimension * getPreferredSize();
  virtual void setUnitIncrement(::java::awt::Adjustable *, jint);
  virtual void setValue(::java::awt::Adjustable *, jint);
  static ::java::lang::Class class$;
};

#endif // __gnu_java_awt_peer_gtk_GtkScrollPanePeer__

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace ByCedric\Allay\Tests\Stubs\Http\Controllers\Traits;

class StoreAction
{
    use \ByCedric\Allay\Http\Controllers\Traits\StoreAction;
}


text:
<?php

declare(strict_types=1);

namespace Roave\BetterReflectionTest\Util;

use PHPUnit\Framework\TestCase;
use Roave\BetterReflection\Util\FileHelper;

use function strtr;

use const DIRECTORY_SEPARATOR;

/**
 * @covers \Roave\BetterReflection\Util\FileHelper
 */
class FileHelperTest extends TestCase
{
    public function testNormalizeWindowsPath(): void
    {
        self::assertSame('directory/foo/boo/file.php', FileHelper::normalizeWindowsPath('directory\\foo/boo\\file.php'));
        self::assertSame('directory/foo/boo/file.php', FileHelper::normalizeWindowsPath('directory/foo/boo/file.php'));
    }

    public function testSystemWindowsPath(): void
    {
        $path = 'directory\\foo/boo\\foo/file.php';

        self::assertSame(strtr($path, '\\/', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR), FileHelper::normalizeSystemPath($path));
    }

    public function testSystemWindowsPathWithProtocol(): void
    {
        if (DIRECTORY_SEPARATOR !== '\\') {
            $this->markTestSkipped('Test runs only on Windows');
        }

        $path = 'phar://C:/Users/ondrej/phpstan.phar/src/TrinaryLogic.php';
        self::assertSame(
            'phar://C:\Users\ondrej\phpstan.phar\src\TrinaryLogic.php',
            FileHelper::normalizeSystemPath($path),
        );
    }
}


text:
package nitro

import (
	"context"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/256dpi/serve"
	"github.com/256dpi/xo"
)

// Context allows handlers to interact with the request.
type Context struct {
	context.Context

	// The received procedure.
	Procedure Procedure

	// The current handler.
	Handler *Handler

	// The underlying request.
	Request *http.Request

	// The underlying writer.
	Writer http.ResponseWriter
}

// Handler defines a procedure handler.
type Handler struct {
	// The handled procedure.
	Procedure Procedure

	// The request body limit.
	//
	// Default: 4K.
	Limit int64

	// The processing callback.
	Callback func(ctx *Context) error
}

// Endpoint manages the calling of procedures.
type Endpoint struct {
	handlers map[string]*Handler
	reporter func(error)
}

// NewEndpoint creates and returns a new server.
func NewEndpoint(reporter func(error)) *Endpoint {
	return &Endpoint{
		handlers: map[string]*Handler{},
		reporter: reporter,
	}
}

// Add will add the specified handler to the endpoint.
func (s *Endpoint) Add(handler *Handler) {
	// set default limit
	if handler.Limit == 0 {
		handler.Limit = serve.MustByteSize("4K")
	}

	// get name
	name := GetMeta(handler.Procedure).Name

	// add handler
	s.handlers[name] = handler
}

// ServeHTTP implements the http.Handler interface.
func (s *Endpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// check request method
	if r.Method != "POST" {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}

	// get clean url
	url := strings.Trim(r.URL.Path, "/")

	// lookup handler
	handler, ok := s.handlers[url]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// get meta
	meta := GetMeta(handler.Procedure)

	// trace
	reqCTX, span := xo.Trace(r.Context(), "PROC "+meta.Name)
	defer span.End()

	// prepare procedure
	proc := meta.Make()

	// prepare context
	ctx := &Context{
		Context:   reqCTX,
		Procedure: proc,
		Handler:   handler,
		Request:   r,
		Writer:    w,
	}

	// process context
	err := s.Process(ctx)
	if err != nil && s.reporter != nil {
		s.reporter(err)
	}
}

// Process handles the specified context.
func (s *Endpoint) Process(ctx *Context) error {
	// get meta
	meta := GetMeta(ctx.Procedure)

	// limit body
	serve.LimitBody(ctx.Writer, ctx.Request, ctx.Handler.Limit)

	// read body
	body, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return xo.W(err)
	}

	// unmarshal body
	err = meta.Coding.Unmarshal(body, ctx.Procedure)
	if err != nil {
		return err
	}

	// pre validate
	err = ctx.Procedure.Validate()
	if err != nil {
		return xo.W(err)
	}

	// set response flag
	ctx.Procedure.GetBase().Response = true

	// run callback
	err = xo.Catch(func() error {
		return ctx.Handler.Callback(ctx)
	})
	if err != nil {
		// check if safe error
		if xo.IsSafe(err) {
			err = BadRequest(err.Error(), "")
		}

		// check if rich error
		anError := AsError(err)
		if anError != nil {
			// unset original error
			err = nil
		} else {
			// create internal server error
			anError = ErrorFromStatus(http.StatusInternalServerError, "")
		}

		// set fallback status
		if http.StatusText(anError.Status) == "" {
			anError.Status = http.StatusInternalServerError
		}

		// write header
		ctx.Writer.Header().Set("Content-Type", meta.Coding.MimeType())
		ctx.Writer.WriteHeader(anError.Status)

		// write body
		body, _ := meta.Coding.Marshal(anError)
		_, _ = ctx.Writer.Write(body)

		return err
	}

	// post validate
	err = ctx.Procedure.Validate()
	if err != nil {
		return xo.W(err)
	}

	// write header
	ctx.Writer.Header().Set("Content-Type", meta.Coding.MimeType())
	ctx.Writer.WriteHeader(http.StatusOK)

	// write response
	body, _ = meta.Coding.Marshal(ctx.Procedure)
	_, _ = ctx.Writer.Write(body)

	return nil
}


text:
// Mixture of linear interpolation LMs

#ifndef LM_MIXTURE
#define LM_MIXTURE

#define END_ENUM    {   (char*)0,  0 }

class mixture: public mdiadaptlm
{
  double** l[MAX_NGRAM]; //interpolation parameters
  int* pm; //parameter mappings
  int  pmax; //#parameters
  int k1,k2; //two thresholds
  int  numslm;
  int prunethresh;
  interplm** sublm;
  char *ipfname;
  char *opfname;

  double reldist(double *l1,double *l2,int n);
  int genpmap();
  int pmap(ngram ng,int lev);
public:

  bool usefulltable;

  mixture(bool fulltable,char *sublminfo,int depth,int prunefreq=0,char* ipfile=NULL,char* opfile=NULL);

  int train();

  int savepar(char* opf);
  int loadpar(char* opf);

  inline int dub() {
    return dict->dub();
  }
  inline int dub(int value) {
    for (int i=0; i<numslm; i++) {
      //      cerr << "I'm setting dub: " << value << endl;
      sublm[i]->dub(value);
    }
    return (dict->dub(value));
  }

  void settying(int a,int b) {
    k1=a;
    k2=b;
  }
  int discount(ngram ng,int size,double& fstar,double& lambda,int cv=0);

  ~mixture() {}

  //this extension builds a commong ngramtable on demand
  int get(ngram& ng,int n,int lev);

};

#endif


text:
local self = {}

self.Name = "PolyEditor"
self.Icon = "gpad/document_graph.png"

function self:Init()
	local editor = Metro.Create("GPadMetroEditor")
	--editor:SetText("Poly Editor (INDEV, not working)")
	editor:Dock(FILL)
	return editor
end

GPad.FileTypes:CreateType(self.Name, self)


text:
<?php

declare(strict_types=1);

/**
 * This file is part of Narrowspark Framework.
 *
 * (c) Daniel Bannert <d.bannert@anolilab.de>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Viserio\Component\HttpFoundation\Exception;

use Cake\Chronos\Chronos;
use Narrowspark\HttpStatus\Exception\ServiceUnavailableException;
use Throwable;

class MaintenanceModeException extends ServiceUnavailableException
{
    /**
     * When the application was put in maintenance mode.
     *
     * @var \Cake\Chronos\Chronos
     */
    protected $wentDownAt;

    /**
     * The number of seconds to wait before retrying.
     *
     * @var int
     */
    protected $retryAfter;

    /**
     * When the application should next be available.
     *
     * @var \Cake\Chronos\Chronos
     */
    protected $willBeAvailableAt;

    /**
     * Create a new MaintenanceModeException instance.
     *
     * @param int            $time
     * @param null|int       $retryAfter
     * @param null|string    $message
     * @param null|Throwable $previous
     */
    public function __construct(
        int $time,
        ?int $retryAfter = null,
        ?string $message = null,
        ?Throwable $previous = null
    ) {
        parent::__construct($message, $previous, [], 503);

        $this->wentDownAt = Chronos::createFromTimestamp($time);

        if ($retryAfter) {
            $this->retryAfter = $retryAfter;

            $this->willBeAvailableAt = Chronos::createFromTimestamp($time)->addSeconds($this->retryAfter);
        }
    }

    /**
     * Get time when the application went down.
     *
     * @return \Cake\Chronos\Chronos
     */
    public function getWentDownAt(): Chronos
    {
        return $this->wentDownAt;
    }

    /**
     * Get retry after down.
     *
     * @return int
     */
    public function getRetryAfter(): int
    {
        return $this->retryAfter;
    }

    /**
     * Get the time when the application is available.
     *
     * @return \Cake\Chronos\Chronos
     */
    public function getWillBeAvailableAt(): Chronos
    {
        return $this->willBeAvailableAt;
    }
}


text:
<?xml version="1.0"?>
<!-- Copyright (c) 2001 - 2008 Ampache.org
 All rights reserved.

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. -->
<!DOCTYPE cross-domain-policy
  SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <allow-access-from domain="*" />
</cross-domain-policy>


text:
package com.intellij.debugger.memory.filtering;

/**
 * @author Vitaliy.Bibaev
 */
public enum FilteringResult
{
	ALL_CHECKED,

	INTERRUPTED,

	LIMIT_REACHED
}


text:
<?php

namespace VacStatus\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

use VacStatus\Steam\Steam;
use VacStatus\Steam\SteamAPI;
use VacStatus\Models\Profile;

use Cache;
use Carbon;

class UpdateMultiAlias extends Command {

	protected $queueCacheName = "update_alias_";
	protected $name = 'update:alias';
	protected $description = 'Command description.';

	public function __construct()
	{
		parent::__construct();
	}

	public function fire()
	{
		$cacheName = $this->queueCacheName.$this->argument('aliasCacheCode');
		if(!Cache::has($cacheName)) return;

		$smallIds = Cache::pull($cacheName);

		foreach(array_chunk($smallIds, 100) as $chunkedSmallIds)
		{

			$profiles = Profile::whereIn('small_id', $chunkedSmallIds)->get();

			foreach($profiles as $profile)
			{
				$steamAPI = new SteamAPI($profile->small_id, true);
				$steamAlias = $steamAPI->fetch('alias');

				if(!isset($steamAlias['error'])) usort($steamAlias, array('VacStatus\Steam\Steam', 'aliasSort'));
				else $steamAlias = [];

				$profile->alias = json_encode($steamAlias);
				$profile->save();

				$cacheName = "profile_{$profile->small_id}";

				if(!Cache::has($cacheName)) continue;

				$profileCache = Cache::get($cacheName);
				$profileCache['alias'] = Steam::friendlyAlias($steamAlias);

				if(Cache::has($cacheName)) Cache::forget($cacheName);

				$expireTime = Carbon::now()->addMinutes(60);

				Cache::put($cacheName, $profileCache, $expireTime);
			}
		}
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return [
			['aliasCacheCode', InputArgument::REQUIRED, 'Code of the saved cache of smallIds for updating alias'],
		];
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return [];
	}

}


text:
package com.cloudcog.gears.admin.screen.admin.groups;

import org.cloudcog.kani.RepositoryContext;
import org.cloudcog.kani.i18n.Messages;
import org.cloudcog.kani.repository.user.UserDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudcog.gears.admin.controller.admin.AdminScreenController;
import com.cloudcog.gears.admin.screen.GearsWindow;
import com.cloudcog.gears.admin.screen.mainPanel.ObjectMenuBar;
import com.cloudcog.gears.admin.screen.mainPanel.handlers.SaveObjectInterface;
import com.cloudcog.gears.admin.user.GearsGroup;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;

public class GroupsPanel extends GearsWindow implements SaveObjectInterface {
	/*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */

	private static final Logger log = LoggerFactory.getLogger(GroupsPanel.class);

	@AutoGenerated
	private VerticalLayout mainLayout;

	@AutoGenerated
	private TextField groupNameText;

	private static final long serialVersionUID = 2096197583396700915L;

	GearsGroup gearsGroup;

	@Override
	public void initialize(AdminScreenController adminScreenController, Object item) {
		buildMainLayout();
		this.gearsGroup = (GearsGroup) item;
		setCompositionRoot(mainLayout);

	}

	@AutoGenerated
	private VerticalLayout buildMainLayout() {
		// common part: create layout
		mainLayout = new VerticalLayout();

		mainLayout.addComponent(new ObjectMenuBar(this));

		mainLayout.setImmediate(false);
		mainLayout.setWidth("100%"); //$NON-NLS-1$
		mainLayout.setHeight("100%"); //$NON-NLS-1$
		mainLayout.setMargin(false);

		// top-level component properties
		setWidth("100.0%"); //$NON-NLS-1$
		setHeight("100.0%"); //$NON-NLS-1$

		// groupNameText
		groupNameText = new TextField();
		groupNameText.setCaption(Messages.getString("GroupsPanel.GroupName")); //$NON-NLS-1$
		groupNameText.setImmediate(false);
		groupNameText.setDescription(Messages.getString("GroupsPanel.GroupNameDesc")); //$NON-NLS-1$
		groupNameText.setWidth("-1px"); //$NON-NLS-1$
		groupNameText.setHeight("-1px"); //$NON-NLS-1$
		mainLayout.addComponent(groupNameText);

		return mainLayout;
	}

	@Override
	public void save() {
		try {
			if (this.getData() == null) {

				this.gearsGroup = new GearsGroup(UserDAO.createGroup(RepositoryContext.getJcrSession(), groupNameText.getValue()));
			}
			RepositoryContext.getJcrSession().save();

		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

	}

}


text:
package org.basex.query.value.item;

import static org.basex.query.QueryError.*;

import java.math.*;

import org.basex.query.*;
import org.basex.query.util.collation.*;
import org.basex.query.value.type.*;
import org.basex.util.*;

/**
 * Double item ({@code xs:double}).
 *
 * @author BaseX Team 2005-20, BSD License
 * @author Christian Gruen
 */
public final class Dbl extends ANum {
  /** Value "NaN". */
  public static final Dbl NAN = new Dbl(Double.NaN);
  /** Value "0". */
  public static final Dbl ZERO = new Dbl(0);
  /** Value "1". */
  public static final Dbl ONE = new Dbl(1);
  /** Data. */
  private final double value;

  /**
   * Constructor.
   * @param value value
   */
  private Dbl(final double value) {
    super(AtomType.DBL);
    this.value = value;
  }

  /**
   * Returns an instance of this class.
   * @param value value
   * @return instance
   */
  public static Dbl get(final double value) {
    return value == 0 && Double.doubleToRawLongBits(value) == 0 ? ZERO : value == 1 ? ONE :
      Double.isNaN(value) ? NAN : new Dbl(value);
  }

  /**
   * Returns an instance of this class.
   * @param value value
   * @param ii input info
   * @return instance
   * @throws QueryException query exception
   */
  public static Dbl get(final byte[] value, final InputInfo ii) throws QueryException {
    return get(parse(value, ii));
  }

  @Override
  public byte[] string() {
    return Token.token(value);
  }

  @Override
  public boolean bool(final InputInfo ii) {
    return !Double.isNaN(value) && value != 0;
  }

  @Override
  public long itr() {
    return (long) value;
  }

  @Override
  public float flt() {
    return (float) value;
  }

  @Override
  public double dbl() {
    return value;
  }

  @Override
  public BigDecimal dec(final InputInfo ii) throws QueryException {
    if(Double.isNaN(value) || Double.isInfinite(value))
     throw valueError(AtomType.DEC, string(), ii);
    return new BigDecimal(value);
  }

  @Override
  public Dbl abs() {
    return value > 0.0d || 1 / value > 0 ? this : get(-value);
  }

  @Override
  public Dbl ceiling() {
    final double d = Math.ceil(value);
    return d == value ? this : get(d);
  }

  @Override
  public Dbl floor() {
    final double d = Math.floor(value);
    return d == value ? this : get(d);
  }

  @Override
  public Dbl round(final int scale, final boolean even) {
    final double v = rnd(scale, even);
    return v == value ? this : get(v);
  }

  /**
   * Returns a rounded value.
   * @param s scale
   * @param e half-to-even flag
   * @return result
   */
  private double rnd(final int s, final boolean e) {
    double v = value;
    if(v == 0 || Double.isNaN(v) || Double.isInfinite(v) || s > 322) return v;
    if(s < -308) return 0;
    if(!e && s == 0) {
      if(v >= -0.5 && v < 0.0) return -0.0;
      if(v > Long.MIN_VALUE && v < Long.MAX_VALUE) return Math.round(v);
    }

    final boolean n = v < 0;
    final double f = StrictMath.pow(10, s + 1);
    v = (n ? -v : v) * f;
    if(Double.isInfinite(v)) {
      final RoundingMode m = e ? RoundingMode.HALF_EVEN : RoundingMode.HALF_UP;
      v = new BigDecimal(value).setScale(s, m).doubleValue();
    } else {
      final double r = v % 10;
      v += r < 5 ? -r : (e ? r > 5 : r >= 5) ? 10 - r : e ? v % 20 == 15 ? 5 : -5 : 0;
      v /= f;
      if(n) v = -v;
    }
    return v;
  }

  @Override
  public boolean eq(final Item item, final Collation coll, final StaticContext sc,
      final InputInfo ii) throws QueryException {
    return value == item.dbl(ii);
  }

  @Override
  public int diff(final Item item, final Collation coll, final InputInfo ii)
      throws QueryException {
    // cannot be replaced by Double.compare (different semantics)
    final double n = item.dbl(ii);
    return Double.isNaN(n) || Double.isNaN(value) ? UNDEF : value < n ? -1 : value > n ? 1 : 0;
  }

  @Override
  public Double toJava() {
    return value;
  }

  @Override
  public boolean equals(final Object obj) {
    return this == obj || obj instanceof Dbl && value == ((Dbl) obj).value;
  }

  // STATIC METHODS ===============================================================================

  /**
   * Converts the given token into a double value.
   * @param value value to be converted
   * @param ii input info
   * @return double value
   * @throws QueryException query exception
   */
  public static double parse(final byte[] value, final InputInfo ii) throws QueryException {
    final double d = Token.toDouble(value);
    if(!Double.isNaN(d)) return d;

    final byte[] v = Token.trim(value);
    if(Token.eq(v, Token.NAN)) return Double.NaN;
    if(Token.eq(v, Token.INF)) return Double.POSITIVE_INFINITY;
    if(Token.eq(v, Token.NINF)) return Double.NEGATIVE_INFINITY;

    throw AtomType.DBL.castError(value, ii);
  }
}


text:
/**
 * more docs available: https://cloud.google.com/storage/docs/object-change-notification#_Type_Sync
 */
const Promise = require('bluebird');
const { HttpStatusError } = require('common-errors');
const find = require('lodash/find');
const config = require('../config.js');

// bucket configuration
const $gce = config.files.gce_v2;
const gce = Array.isArray($gce) ? $gce : [$gce];

function parseInput(req) {
  const message = req.body.message;
  const { bucketId: bucket, eventType, resource } = message.attributes;
  const gceSettings = find(gce, { bucket });

  if (!gceSettings) {
    return Promise.reject(new HttpStatusError(400, `failed to find gce bucket: ${bucket}`));
  }

  if (gceSettings.token !== req.query.token) {
    return Promise.reject(new HttpStatusError(400, 'token mismatch'));
  }

  let action;
  switch (eventType) {
    case 'OBJECT_FINALIZE':
      action = 'exists';
      break;

    default:
      return Promise.reject(new HttpStatusError(400, 'unsupported action'));
  }

  req.file = {
    action,
    resourceId: resource,
    filename: JSON.parse(Buffer.from(message.data, 'base64')).name,
  };
  return null;
}

module.exports = function gceWebhook(req, res, next) {
  return Promise
    .try(parseInput.bind(undefined, req))
    .asCallback(next);
};


text:
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Slider from '@material-ui/lab/Slider';

const styles = {
  root: {
    width: 300,
  },
  slider: {
    padding: '22px 0px',
  },
};

class StepSlider extends React.Component {
  state = {
    value: 3,
  };

  handleChange = (event, value) => {
    this.setState({ value });
  };

  render() {
    const { classes } = this.props;
    const { value } = this.state;

    return (
      <div className={classes.root}>
        <Slider
          className={classes.slider}
          value={value}
          min={0}
          max={6}
          step={1}
          onChange={this.handleChange}
        />
      </div>
    );
  }
}

StepSlider.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(StepSlider);


text:
using System.Collections.Generic;
using System.Linq;

namespace SportsStore.Models
{
    public class EFProductRepository : IProductRepository
    {
        private ApplicationDbContext context;

        public EFProductRepository(ApplicationDbContext ctx)
        {
            context = ctx;
        }

        public IEnumerable<Product> Products => context.Products;

        public void SaveProduct(Product product)
        {
            if (product.ProductID == 0)
            {
                context.Products.Add(product);
            }
            else
            {
                Product dbEntry = context.Products.FirstOrDefault(p => p.ProductID == product.ProductID);
                if (dbEntry != null)
                {
                    dbEntry.Name = product.Name;
                    dbEntry.Description = product.Description;
                    dbEntry.Price = product.Price;
                    dbEntry.Category = product.Category;
                }
            }
            context.SaveChanges();
        }

        public Product DeleteProduct(int productID)
        {
            Product dbEntry = context.Products.FirstOrDefault(p => p.ProductID == productID);
            if (dbEntry != null)
            {
                context.Products.Remove(dbEntry);
                context.SaveChanges();
            }

            return dbEntry;
        }
    }
}


text:
mkdir -p /etc/salt/minion.d
echo "master: $SALT_MASTER" > /etc/salt/minion.d/master.conf

cat <<EOF >/etc/salt/minion.d/grains.conf
grains:
  roles:
    - kubernetes-master
  cloud: aws
  cbr-cidr: "${MASTER_IP_RANGE}"
EOF

if [[ -n "${DOCKER_OPTS}" ]]; then
  cat <<EOF >>/etc/salt/minion.d/grains.conf
  docker_opts: '$(echo "$DOCKER_OPTS" | sed -e "s/'/''/g")'
EOF
fi

if [[ -n "${DOCKER_ROOT}" ]]; then
  cat <<EOF >>/etc/salt/minion.d/grains.conf
  docker_root: '$(echo "$DOCKER_ROOT" | sed -e "s/'/''/g")'
EOF
fi

if [[ -n "${KUBELET_ROOT}" ]]; then
  cat <<EOF >>/etc/salt/minion.d/grains.conf
  kubelet_root: '$(echo "$KUBELET_ROOT" | sed -e "s/'/''/g")'
EOF
fi

if [[ -n "${MASTER_EXTRA_SANS}" ]]; then
  cat <<EOF >>/etc/salt/minion.d/grains.conf
  master_extra_sans: '$(echo "$MASTER_EXTRA_SANS" | sed -e "s/'/''/g")'
EOF
fi

# Auto accept all keys from minions that try to join
mkdir -p /etc/salt/master.d
cat <<EOF >/etc/salt/master.d/auto-accept.conf
auto_accept: True
EOF

cat <<EOF >/etc/salt/master.d/reactor.conf
# React to new minions starting by running highstate on them.
reactor:
  - 'salt/minion/*/start':
    - /srv/reactor/highstate-new.sls
EOF

install-salt master

service salt-master start
service salt-minion start


text:
using UnityEngine;
using System;

namespace Soomla {

	public class KeyValueStorageAndroid : KeyValueStorage {

#if UNITY_ANDROID && !UNITY_EDITOR

		override protected string _getValue(string key) {
			string val = null;
			AndroidJNI.PushLocalFrame(100);
			using(AndroidJavaClass jniRewardStorage = new AndroidJavaClass("com.soomla.data.KeyValueStorage")) {
				val = jniRewardStorage.CallStatic<string>("getValue", key);
			}
			AndroidJNI.PopLocalFrame(IntPtr.Zero);
			return val;
		}

		override protected void _setValue(string key, string val) {
			AndroidJNI.PushLocalFrame(100);
			using(AndroidJavaClass jniRewardStorage = new AndroidJavaClass("com.soomla.data.KeyValueStorage")) {
				jniRewardStorage.CallStatic("setValue", key, val);
			}
			AndroidJNI.PopLocalFrame(IntPtr.Zero);
		}

		override protected void _deleteKeyValue(string key) {
			AndroidJNI.PushLocalFrame(100);
			using(AndroidJavaClass jniRewardStorage = new AndroidJavaClass("com.soomla.data.KeyValueStorage")) {
				jniRewardStorage.CallStatic("deleteKeyValue", key);
			}
			AndroidJNI.PopLocalFrame(IntPtr.Zero);
		}
#endif
	}
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var tsutils_1 = require("tsutils");
var ts = require("typescript");
var Lint = require("../index");
var OPTION_IGNORE_PARMS = "ignore-params";
var OPTION_IGNORE_PROPERTIES = "ignore-properties";
var Rule = /** @class */ (function (_super) {
    tslib_1.__extends(Rule, _super);
    function Rule() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /* tslint:enable:object-literal-sort-keys */
    Rule.FAILURE_STRING_FACTORY = function (type) {
        return "Type " + type + " trivially inferred from a " + type + " literal, remove type annotation";
    };
    Rule.prototype.apply = function (sourceFile) {
        return this.applyWithWalker(new NoInferrableTypesWalker(sourceFile, this.ruleName, {
            ignoreParameters: this.ruleArguments.indexOf(OPTION_IGNORE_PARMS) !== -1,
            ignoreProperties: this.ruleArguments.indexOf(OPTION_IGNORE_PROPERTIES) !== -1,
        }));
    };
    /* tslint:disable:object-literal-sort-keys */
    Rule.metadata = {
        ruleName: "no-inferrable-types",
        description: "Disallows explicit type declarations for variables or parameters initialized to a number, string, or boolean.",
        rationale: "Explicit types where they can be easily inferred by the compiler make code more verbose.",
        optionsDescription: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n            Two arguments may be optionally provided:\n\n            * `", "` allows specifying an inferrable type annotation for function params.\n            This can be useful when combining with the `typedef` rule.\n            * `", "` allows specifying an inferrable type annotation for class properties."], ["\n            Two arguments may be optionally provided:\n\n            * \\`", "\\` allows specifying an inferrable type annotation for function params.\n            This can be useful when combining with the \\`typedef\\` rule.\n            * \\`", "\\` allows specifying an inferrable type annotation for class properties."])), OPTION_IGNORE_PARMS, OPTION_IGNORE_PROPERTIES),
        options: {
            type: "array",
            items: {
                type: "string",
                enum: [OPTION_IGNORE_PARMS, OPTION_IGNORE_PROPERTIES],
            },
            minLength: 0,
            maxLength: 2,
        },
        hasFix: true,
        optionExamples: [
            true,
            [true, OPTION_IGNORE_PARMS],
            [true, OPTION_IGNORE_PARMS, OPTION_IGNORE_PROPERTIES],
        ],
        type: "typescript",
        typescriptOnly: true,
    };
    return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
var NoInferrableTypesWalker = /** @class */ (function (_super) {
    tslib_1.__extends(NoInferrableTypesWalker, _super);
    function NoInferrableTypesWalker() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    NoInferrableTypesWalker.prototype.walk = function (sourceFile) {
        var _this = this;
        var cb = function (node) {
            if (shouldCheck(node, _this.options)) {
                var name = node.name, type = node.type, initializer = node.initializer;
                if (type !== undefined &&
                    initializer !== undefined &&
                    typeIsInferrable(type.kind, initializer)) {
                    var fix = Lint.Replacement.deleteFromTo(name.end, type.end);
                    _this.addFailureAtNode(type, Rule.FAILURE_STRING_FACTORY(ts.tokenToString(type.kind)), fix);
                }
            }
            return ts.forEachChild(node, cb);
        };
        return ts.forEachChild(sourceFile, cb);
    };
    return NoInferrableTypesWalker;
}(Lint.AbstractWalker));
function shouldCheck(node, _a) {
    var ignoreParameters = _a.ignoreParameters, ignoreProperties = _a.ignoreProperties;
    switch (node.kind) {
        case ts.SyntaxKind.Parameter:
            return (!ignoreParameters &&
                !tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.ReadonlyKeyword) &&
                // "ignore-properties" also works for parameter properties
                !(ignoreProperties && node.modifiers !== undefined));
        case ts.SyntaxKind.PropertyDeclaration:
            return !ignoreProperties && !tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.ReadonlyKeyword);
        case ts.SyntaxKind.VariableDeclaration:
            return true;
        default:
            return false;
    }
}
function typeIsInferrable(type, initializer) {
    switch (type) {
        case ts.SyntaxKind.BooleanKeyword:
            return (initializer.kind === ts.SyntaxKind.TrueKeyword ||
                initializer.kind === ts.SyntaxKind.FalseKeyword);
        case ts.SyntaxKind.NumberKeyword:
            return Lint.isNumeric(initializer);
        case ts.SyntaxKind.StringKeyword:
            switch (initializer.kind) {
                case ts.SyntaxKind.StringLiteral:
                case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
                case ts.SyntaxKind.TemplateExpression:
                    return true;
                default:
                    return false;
            }
        default:
            return false;
    }
}
var templateObject_1;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Patellaria pacifica Müll. Arg.

### Remarks
null


text:
alter table users add unique (name);
alter table users add unique (email);

create table sessions (
  id bigserial not null primary key,
  created_at timestamp not null,
  expiration timestamp not null,
  username varchar(255) not null references users(name) on delete cascade,
  token varchar(255) not null
);

# --- !Downs

drop table sessions;


text:
http://www.studioamanga.com/onelist

## Roadmap

- App video preview
- Apple Watch change list action (force touch)

## 2.0.2

- [x] Built with iOS 10 SDK

## 2.0.1

2016-03-12

- Optimized for iPad Pro
- Fixed crash at launch with iOS 8
- Updated icons for Comic Book Day and Games Keeper

## 2.0

2015-10-05

- **New interface**
    - New text field
    - Rounded checkboxes
    - New checkmark sign
    - Fix strikethrough
    - Storyboard launch screen
- **New icon**
- **Optimized for iOS 9**
- Added Split View support
- Added Quick Action to create new reminders
- Added Handoff support
- Requires iOS 8

## 1.7.2

2015-06-25

- Fixed Delete button on suggestions list

## 1.7.1

2015-05-27

- Added Apple Watch Glance
- Updated Apple Watch interface with two lines for items
- Fixed changing list refresh on Apple Watch

## 1.7

2015-05-12

- **Added Apple Watch application**
- Updated list to keep items marked as completed for 1 hour

## 1.6.1

2015-04-25

- Reloads reminders when entering foreground
- Removed custom crash reporting

## 1.6

2015-02-17

- **Editable lists**
    - Add new lists
    - Edit lists
    - Remove lists
    - Localization
- Added color indicator on lists

## 1.5

2014-10-08

- **Optimized for iOS 8**
- **Optimized for iPhone 6 and iPhone 6 Plus**
- Added "Go to Privacy Settings" button

## 1.4.2

2014-05-21

- Fixed item selection color on edges
- Fixed welcome and rejected screens

## 1.4.1

2014-03-22

- Improved user interface for progress HUD
- Changed checkmark color in settings to blue

## 1.4

2014-02-08

- Improved user interface for iOS 7
- Hide already added items from auto-complete

## 1.3.1

2013-10-17

- Fixed caret color

## 1.3

2013-09-18

- **New interface for iOS 7**
- Bug fixes

## 1.2.4

2013-07-28

- Bug fixes

## 1.2.3

2013-06-23

- Bug fixes

## 1.2.2

2013-06-14

- Improved user interface

## 1.2.1

2013-05-03

- Bug fixes

## 1.2

2013-02-19

- **Added Chinese localization**
- New items now appear on top of the list

## 1.1.1

2012-12-15

- Improved performances
- Bug fixes

## 1.1

2012-12-14

- **Added French localization**
- Improved user interface

## 1.0

2012-12-04

- **Initial release**


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using WikiClientLibrary.Infrastructures;
using WikiClientLibrary.Pages;
using WikiClientLibrary.Sites;

namespace WikiClientLibrary.Client
{
    /// <summary>
    /// The MediaWiki API request message consisting of parameter key-value pairs (fields).
    /// </summary>
    /// <remarks>
    /// <para>
    /// This is the primary message type used in the WikiClientLibrary.
    /// This type provides some useful functionalities such as constructing fields from anonymous objects,
    /// and simple type (e.g. <see cref="DateTime"/>) marshalling.
    /// while overriding the rest.
    /// </para>
    /// <para>
    /// This message can be later converted into
    /// <c>application/x-www-form-urlencoded</c> or <c>multipart/form-data</c> http content.
    /// </para>
    /// <para>
    /// When converting the form into <see cref="HttpContent"/>, the values are marshaled in the following way
    /// <list type="bullet">
    /// <item><description>
    /// <c>null</c> values are ignored.
    /// </description></item>
    /// <item><description>
    /// <c>string</c> values are kept intact.
    /// </description></item>
    /// <item><description>
    /// <c>bool</c> values are marshaled as <c>""</c>(<see cref="string.Empty"/>) for <c>true</c>,
    /// and are ignored for <c>false</c>.
    /// </description></item>
    /// <item><description>
    /// <see cref="DateTime"/> values are marshaled as UTC in ISO 8601 format.
    /// </description></item>
    /// <item><description>
    /// <see cref="Stream"/> values are sent as <see cref="StreamContent"/> with a dummy file name,
    /// and this will force the whole form to be marshaled as <see cref="MultipartFormDataContent"/>.
    /// </description></item>
    /// <item><description>
    /// <see cref="AutoWatchBehavior"/> values are marshaled as one of "preferences", "nochange", "watch", "unwatch".
    /// </description></item>
    /// <item><description>
    /// Other types of values are marshaled by calling <see cref="object.ToString"/> on them.
    /// </description></item>
    /// </list>
    /// Note that the message sending methods (e.g. <see cref="WikiSite.InvokeMediaWikiApiAsync(WikiClientLibrary.Client.WikiRequestMessage,System.Threading.CancellationToken)"/>)
    /// may also change the way the message is marshaled. For the detailed information, please see the message sender's
    /// documentations respectively.
    /// </para>
    /// <para>This message uses POST method to invoke API requests.</para>
    /// </remarks>
    public class MediaWikiFormRequestMessage : WikiRequestMessage
    {

        private readonly IList<KeyValuePair<string, object?>> fields;
        private IList<KeyValuePair<string, object?>>? readonlyFields;
        // Memorizes the stream position upon first request.
        private IDictionary<Stream, long>? streamPositions;

        private volatile int status;
        // Created
        private const int STATUS_CREATED = 0;
        // GetHttpContent invoked, recoverable
        private const int STATUS_RECOVERABLE = 1;
        // GetHttpContent invoked, un-recoverable
        private const int STATUS_UNRECOVERABLE = 2;

        /// <inheritdoc cref="MediaWikiFormRequestMessage(string,object,bool)"/>
        public MediaWikiFormRequestMessage(object fieldCollection) : this(null, fieldCollection, false)
        {
        }

        /// <inheritdoc cref="MediaWikiFormRequestMessage(string,object,bool)"/>
        public MediaWikiFormRequestMessage(object fieldCollection, bool forceMultipartFormData) : this(null, fieldCollection, forceMultipartFormData)
        {
        }

        /// <inheritdoc />
        /// <param name="fieldCollection">A dictionary or anonymous object containing the key-value pairs. See <see cref="MediaWikiHelper.EnumValues"/> for more information.</param>
        /// <param name="forceMultipartFormData">Forces the message to be marshaled as multipart/form-data, regardless of the fields.</param>
        /// <exception cref="ArgumentNullException"><paramref name="fieldCollection"/> is <c>null</c>.</exception>
        public MediaWikiFormRequestMessage(string? id, object fieldCollection, bool forceMultipartFormData) : base(id)
        {
            if (fieldCollection == null) throw new ArgumentNullException(nameof(fieldCollection));
            fields = new List<KeyValuePair<string, object?>>(MediaWikiHelper.EnumValues(fieldCollection));
            AsMultipartFormData = forceMultipartFormData || fields.Any(p => p.Value is Stream);
        }

        /// <summary>
        /// Determines whether this message should be marshaled in <c>multipart/form-data</c> MIME type.
        /// </summary>
        public bool AsMultipartFormData { get; }

        /// <summary>
        /// Gets a read-only list of all the fields in the form.
        /// </summary>
        public IList<KeyValuePair<string, object?>> Fields
        {
            get
            {
                if (readonlyFields != null) return readonlyFields;
                var local = new ReadOnlyCollection<KeyValuePair<string, object?>>(fields);
                Volatile.Write(ref readonlyFields, local);
                return local;
            }
        }

        /// <inheritdoc />
        public override HttpMethod GetHttpMethod() => HttpMethod.Post;

        /// <inheritdoc />
        public override string? GetHttpQuery() => null;

        /// <inheritdoc />
        public override HttpContent GetHttpContent()
        {
            // Save & restore the stream position on each GetHttpContent call.
            switch (status)
            {
                case STATUS_CREATED:
                    IDictionary<Stream, long>? sps = null;
                    foreach (var p in fields)
                    {
                        if (p.Value is Stream s)
                        {
                            if (s.CanSeek)
                            {
                                if (sps == null) sps = new Dictionary<Stream, long>();
                                sps[s] = s.Position;
                            }
                            else
                            {
                                status = STATUS_UNRECOVERABLE;
                                goto MAIN;
                            }
                        }
                    }
                    streamPositions = sps;
                    status = STATUS_RECOVERABLE;
                    break;
                case STATUS_RECOVERABLE:
                    sps = streamPositions;
                    if (sps != null)
                    {
                        foreach (var p in fields)
                        {
                            if (p.Value is Stream s) s.Position = sps[s];
                        }
                    }
                    break;
                case STATUS_UNRECOVERABLE:
                    throw new InvalidOperationException(Prompts.ExceptionMediaWikiFormCannotRecoverState);
            }
            MAIN:
            if (AsMultipartFormData)
            {
                var content = new MultipartFormDataContent();
                foreach (var p in fields)
                {
                    switch (p.Value)
                    {
                        case string s:
                            content.Add(new StringContent(s), p.Key);
                            break;
                        case Stream stream:
                            content.Add(new StreamContent(stream), p.Key, "dummy");
                            break;
                        case null:
                            // Ignore null entries.
                            break;
                        default:
                            var stringValue = Utility.ToWikiQueryValue(p.Value);
                            if (stringValue != null)
                                content.Add(new StringContent(stringValue), p.Key);
                            break;
                    }
                }
                return content;
            }
            else
            {
                return new FormLongUrlEncodedContent(Utility.ToWikiStringValuePairs(fields)
                    .Where(p => p.Value != null));
            }
        }
    }
}


text:
from skimage import data, io, segmentation, color
from skimage.future import graph
from matplotlib import pyplot as plt
from scipy import misc
from skimage.color import rgb2gray
import numpy as np
import Helper
import Display

def spectral_cluster(filename, compactness_val=30, n=6):
    '''
    Apply spectral clustering to a given image using k-means clustering and
    display results.

    Args:
        filename: name of the image to segment.

        compactness_val: Controls the "boxyness" of each segment. Higher values
          mean a more boxed shape.

        n = number of clusters.
     '''
    img = misc.imread(filename)
    labels1 = segmentation.slic(img, compactness=compactness_val, n_segments=n)
    out1 = color.label2rgb(labels1, img, kind='overlay', colors=['red','green','blue','cyan','magenta','yellow'])

    fig, ax = plt.subplots()
    ax.imshow(out1, interpolation='nearest')
    ax.set_title("Compactness: {} | Segments: {}".format(compactness_val, n))
    plt.show()

def experiment_with_parameters():
    '''
    Apply spectral clustering to test wheat image using k-means clustering with
    different values of k and different compactness values.

    Saves the results to the Clusters folder for inspection.
    '''
    img = misc.imread("../Assets/wheat.png")

    compactness_values = [30, 50, 70, 100, 200, 300, 500, 700, 1000]
    n_segments_values = [3,4,5,6,7,8,9,10]

    for compactness_val in compactness_values:
        for n in n_segments_values:
            labels1 = segmentation.slic(img, compactness=compactness_val, n_segments=n)
            out1 = color.label2rgb(labels1, img, kind='overlay')

            fig, ax = plt.subplots()
            ax.imshow(out1, interpolation='nearest')
            ax.set_title("Compactness: {} | Segments: {}".format(compactness_val, n))
            plt.savefig("../Clusters/c{}_k{}.png".format(compactness_val, n))
            plt.close(fig)

def extract_roi(img, labels_to_keep=[1,2]):
    '''
    Given a wheat image, this method returns an image containing only the region
    of interest.

    Args:
        img: input image.

        labels_to_keep: cluster labels to be kept in image while pixels
            belonging to clusters besides these ones are removed.

    Return:
        roi_img: Input image containing only the region
        of interest.
    '''
    label_img = segmentation.slic(img, compactness=30, n_segments=6)
    labels = np.unique(label_img);print(labels)
    gray = rgb2gray(img);

    for label in labels:
        if(label not in labels_to_keep):
            logicalIndex = (label_img == label)
            gray[logicalIndex] = 0;

    #Display.show_image(gray)
    return gray


text:
package be.howest.twentytwo.parametergame.model.event.listener;

import be.howest.twentytwo.parametergame.model.event.game.PlayerKilledEvent;

public class PlayerKilledEndGameListener extends BasePlayerKilledHandler {

	// TODO: Needs access to... context?

	@Override
	public void handleEvent(PlayerKilledEvent event) {
		// TODO Auto-generated method stub

	}

}


text:
import nibabel as nib
import numpy as np
from nipype.pipeline import Node, MapNode, Workflow
from nipype.interfaces.utility import IdentityInterface, Function
from nipype.interfaces.fsl import FLIRT
import os

# Node for applying xformation matrix to functional data

def wf_transform_anat(in_file_list, in_matrix_file_list, reference):
    func2std_xform = MapNode(FLIRT(output_type='NIFTI',
                             apply_xfm=True), name="func2std_xform",
                             iterfield = ['in_file', 'in_matrix_file', 'reference'])

    inputspec = Node(IdentityInterface(fields=['in_file_list', 'in_matrix_file_list', 'reference']),
                      name="inputspec")

    inputspec.inputs.in_file_list = in_file_list
    inputspec.inputs.in_matrix_file_list = in_matrix_file_list
    inputspec.inputs.reference = reference

    wf_transform_anat = Workflow(name="wf_transform_anat")
    wf_transform_anat.connect(inputspec,'in_file_list' , func2std_xform,'in_file')
    wf_transform_anat.connect(inputspec,'in_matrix_file_list' , func2std_xform,'in_matrix_file')
    wf_transform_anat.connect(inputspec,'reference' , func2std_xform,'reference')

    return wf_transform_anat

if __name__ == "__main__":
    in_file_list_path = '/mnt/project2/home/varunk/fMRI/results/'+\
    'resultsABIDE1_2/Preprocess_Datasink/resample_anat_filenames.txt'
    in_matrix_file_list_path = '/mnt/project2/home/varunk/fMRI/results/'+\
    'resultsABIDE1_2/Preprocess_Datasink/anat2std_mat_files.txt'
    reference_path = '/mnt/project2/home/varunk/fMRI/results/resultsABIDE1_2/'+\
    'preprocess/motion_correction_bet/coreg_reg/resample_mni/MNI152_T1_2mm_brain_resample.nii'

    in_file_list = [i.decode('UTF-8') for i in np.genfromtxt(in_file_list_path, dtype=None)]
    in_matrix_file_list = [i.decode('UTF-8') for i in np.genfromtxt(in_matrix_file_list_path, dtype=None)]
    reference = [reference_path]*len(in_matrix_file_list)

    print(in_file_list,'\n',in_matrix_file_list, '\n', reference)

    wf = wf_transform_anat(in_file_list, in_matrix_file_list, reference)
    wf.base_dir = '/mnt/project2/home/varunk/fMRI/results/'
    wf.run()


text:
title: Marathon portrait session in the snow
author: Filip Bunkens
type: post
date: 2013-03-07
url: /blog/20130307_portrait-session-marathon
categories:
  - Clients
  - Photography
  - Portrait
  - 'Project #30303030'
  - Varia
tags:
  - aalst
  - clients
  - pitslamp
  - portrait session
  - portraits
  - project 30303030
  - UITpas
format: gallery
---
[![Portrait session Kristof][1]](/images/blogposts/20130126_kristof_vanroy-1400.jpg)

I got a request from the people behind UITpas to do a small Project 30303030 in the end of January. They asked if I wanted to shoot 8 portrait sessions with members of UITpas in one day.

So the 26th of January, a particular cold and snowy day in Aalst, I set out to do just that. Here are some of the results.

## Click on the photos to enlarge them

[][2]
[][3]

[][4]
[][5]

[][6]

[][7]
[][8]

[][9]

[][10]
[][11]

[][12]

[][13]
[][14]
[][15]

[][16]
[][17]
[][18]
[][19]
[][20]
[][21]
[<][22]
[][23]
[][24]
[][25]

 [1]: /images/blogposts/20130126_kristof_vanroy-1400.jpg
 [2]: /images/blogposts/20130126_veronik_dhaese-1336.jpg
 [3]: /images/blogposts/20130126_veronik_dhaese-1276.jpg
 [4]: /images/blogposts/20130126_veronik_dhaese-1188.jpg
 [5]: /images/blogposts/20130126_petra_fieremans-1510.jpg
 [6]: /images/blogposts/20130126_petra_fieremans-1475.jpg
 [7]: /images/blogposts/20130126_petra_fieremans-1462.jpg
 [8]: /images/blogposts/20130126_petra_fieremans-1456.jpg
 [9]: /images/blogposts/20130126_patrick_devillers-1572.jpg
 [10]: /images/blogposts/20130126_patrick_devillers-1569.jpg
 [11]: /images/blogposts/20130126_patrick_devillers-1555.jpg
 [12]: /images/blogposts/20130126_nancy_breynaert-1631.jpg
 [13]: /images/blogposts/20130126_nancy_breynaert-1593.jpg
 [14]: /images/blogposts/20130126_nancy_breynaert-1588.jpg
 [15]: /images/blogposts/20130126_Louisa_smekens-1164.jpg
 [16]: /images/blogposts/20130126_Louisa_smekens-1123.jpg
 [17]: /images/blogposts/20130126_louisa_smekens-1114.jpg
 [18]: /images/blogposts/20130126_kristof_vanroy-1400.jpg
 [19]: /images/blogposts/20130126_kristof_vanroy-1378.jpg
 [20]: /images/blogposts/20130126_elke_laureys-1729.jpg
 [21]: /images/blogposts/20130126_elke_laureys-1676.jpg
 [22]: /images/blogposts/20130126_elke_laureys-1666.jpg
 [23]: /images/blogposts/20130126_ann_de_bouvere-1089.jpg
 [24]: /images/blogposts/20130126_ann_de_bouvere-1081.jpg
 [25]: /images/blogposts/20130126_ann_de_bouvere-1060.jpg


text:
package auth

import (
	"errors"
	"net/http"
)

// Handler defines how to add authorization data to the requests
// depending on the different auth modes.
type Handler interface {
	// Append authorization data to the request depends on cred modes.
	//
	// If everything is ok, nil error will be returned.
	// Otherwise, an error will be got.
	Authorize(req *http.Request, cred *Credential) error

	// Mode returns the auth mode identity.
	Mode() string
}

// BaseHandler provides some basic functions like validation.
type BaseHandler struct{}

// Mode implements @Handler.Mode
func (b *BaseHandler) Mode() string {
	return "BASE"
}

// Authorize implements @Handler.Authorize
func (b *BaseHandler) Authorize(req *http.Request, cred *Credential) error {
	if req == nil {
		return errors.New("nil request cannot be authorized")
	}

	if cred == nil || cred.Data == nil {
		return errors.New("no credential data provided")
	}

	return nil
}


text:
import numpy
import six

from chainer import cuda
from chainer import function
from chainer.utils import type_check

class Accuracy(function.Function):

    def __init__(self, ignore_label=None):
        self.ignore_label = ignore_label

    def check_type_forward(self, in_types):
        type_check.expect(in_types.size() == 2)
        x_type, t_type = in_types

        type_check.expect(
            x_type.dtype.kind == 'f',
            t_type.dtype == numpy.int32
        )

        t_ndim = t_type.ndim.eval()
        type_check.expect(
            x_type.ndim >= t_type.ndim,
            x_type.shape[0] == t_type.shape[0],
            x_type.shape[2: t_ndim + 1] == t_type.shape[1:]
        )
        for i in six.moves.range(t_ndim + 1, x_type.ndim.eval()):
            type_check.expect(x_type.shape[i] == 1)

    def forward(self, inputs):
        xp = cuda.get_array_module(*inputs)
        y, t = inputs

        if self.ignore_label is not None:
            mask = (t == self.ignore_label)
            ignore_cnt = mask.sum()

            # will always be true when the true label is ignore_label
            # TODO(henry0312)
            #   If cupy.where returns indexes, we could make the code better.
            #   Also, we would need Advanced Indexing.
            pred = xp.where(mask, self.ignore_label,
                            y.argmax(axis=1).reshape(t.shape))
            count = (pred == t).sum() - ignore_cnt
            total = t.size - ignore_cnt

            if total == 0:
                return xp.asarray(0.0, dtype=y.dtype),
            else:
                return xp.asarray(float(count) / total, dtype=y.dtype),
        else:
            pred = y.argmax(axis=1).reshape(t.shape)
            return xp.asarray((pred == t).mean(dtype=y.dtype)),

def accuracy(y, t, ignore_label=None):
    """Computes muticlass classification accuracy of the minibatch.

    Args:
        y (Variable): Variable holding a matrix whose (i, j)-th element
            indicates the score of the class j at the i-th example.
        t (Variable): Variable holding an int32 vector of ground truth labels.
        ignore_label (int or None): Skip calculating accuracy
            if the true label is ``ignore_label``.

    Returns:
        Variable: A variable holding a scalar array of the accuracy.

    .. note:: This function is non-differentiable.

    """
    return Accuracy(ignore_label=ignore_label)(y, t)


text:
\hypertarget{class_timer}{}\doxysection{Timer Class Reference}
\label{class_timer}\index{Timer@{Timer}}
\doxysubsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
\mbox{\hyperlink{class_timer_a5f16e8da27d2a5a5242dead46de05d97}{Timer}} ()
\item
bool \mbox{\hyperlink{class_timer_a12bc7fcec14480517080d7cf6c128f46}{is\+On}} () const
\item
bool \mbox{\hyperlink{class_timer_ad5a769d16483dde076721b30bfdbeb73}{is\+Paused}} () const
\item
int \mbox{\hyperlink{class_timer_a867fa6b90d7e3e0595e1469450b95210}{get\+Ticks}} () const
\item
void \mbox{\hyperlink{class_timer_a3a8b5272198d029779dc9302a54305a8}{start}} ()
\item
void \mbox{\hyperlink{class_timer_a0289effad7b573c508bc27e405900a23}{pause}} ()
\item
void \mbox{\hyperlink{class_timer_a63f0eb44b27402196590a03781515dba}{stop}} ()
\item
void \mbox{\hyperlink{class_timer_a9020542d73357a4eef512eefaf57524b}{reset}} ()
\end{DoxyCompactItemize}

\doxysubsection{Constructor \& Destructor Documentation}
\mbox{\Hypertarget{class_timer_a5f16e8da27d2a5a5242dead46de05d97}\label{class_timer_a5f16e8da27d2a5a5242dead46de05d97}}
\index{Timer@{Timer}!Timer@{Timer}}
\index{Timer@{Timer}!Timer@{Timer}}
\doxysubsubsection{\texorpdfstring{Timer()}{Timer()}}
{\footnotesize\ttfamily Timer\+::\+Timer (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption})}

Constructor

\doxysubsection{Member Function Documentation}
\mbox{\Hypertarget{class_timer_a867fa6b90d7e3e0595e1469450b95210}\label{class_timer_a867fa6b90d7e3e0595e1469450b95210}}
\index{Timer@{Timer}!getTicks@{getTicks}}
\index{getTicks@{getTicks}!Timer@{Timer}}
\doxysubsubsection{\texorpdfstring{getTicks()}{getTicks()}}
{\footnotesize\ttfamily int Timer\+::get\+Ticks (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption}) const}

\begin{DoxyReturn}{Returns}
the number of milliseconds elapsed since the timer has started.
\end{DoxyReturn}
\mbox{\Hypertarget{class_timer_a12bc7fcec14480517080d7cf6c128f46}\label{class_timer_a12bc7fcec14480517080d7cf6c128f46}}
\index{Timer@{Timer}!isOn@{isOn}}
\index{isOn@{isOn}!Timer@{Timer}}
\doxysubsubsection{\texorpdfstring{isOn()}{isOn()}}
{\footnotesize\ttfamily bool Timer\+::is\+On (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption}) const}

Determines whether the timer is activated. \mbox{\Hypertarget{class_timer_ad5a769d16483dde076721b30bfdbeb73}\label{class_timer_ad5a769d16483dde076721b30bfdbeb73}}
\index{Timer@{Timer}!isPaused@{isPaused}}
\index{isPaused@{isPaused}!Timer@{Timer}}
\doxysubsubsection{\texorpdfstring{isPaused()}{isPaused()}}
{\footnotesize\ttfamily bool Timer\+::is\+Paused (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption}) const}

Determines whether the timer is paused. \mbox{\Hypertarget{class_timer_a0289effad7b573c508bc27e405900a23}\label{class_timer_a0289effad7b573c508bc27e405900a23}}
\index{Timer@{Timer}!pause@{pause}}
\index{pause@{pause}!Timer@{Timer}}
\doxysubsubsection{\texorpdfstring{pause()}{pause()}}
{\footnotesize\ttfamily void Timer\+::pause (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption})}

Pauses the timer. \mbox{\Hypertarget{class_timer_a9020542d73357a4eef512eefaf57524b}\label{class_timer_a9020542d73357a4eef512eefaf57524b}}
\index{Timer@{Timer}!reset@{reset}}
\index{reset@{reset}!Timer@{Timer}}
\doxysubsubsection{\texorpdfstring{reset()}{reset()}}
{\footnotesize\ttfamily void Timer\+::reset (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption})}

Resets the timer but does not stop or unpause it. \mbox{\Hypertarget{class_timer_a3a8b5272198d029779dc9302a54305a8}\label{class_timer_a3a8b5272198d029779dc9302a54305a8}}
\index{Timer@{Timer}!start@{start}}
\index{start@{start}!Timer@{Timer}}
\doxysubsubsection{\texorpdfstring{start()}{start()}}
{\footnotesize\ttfamily void Timer\+::start (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption})}

Starts the timer or unpauses it if it is paused. \mbox{\Hypertarget{class_timer_a63f0eb44b27402196590a03781515dba}\label{class_timer_a63f0eb44b27402196590a03781515dba}}
\index{Timer@{Timer}!stop@{stop}}
\index{stop@{stop}!Timer@{Timer}}
\doxysubsubsection{\texorpdfstring{stop()}{stop()}}
{\footnotesize\ttfamily void Timer\+::stop (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption})}

Stops the timer.

The documentation for this class was generated from the following files\+:\begin{DoxyCompactItemize}
\item
\mbox{\hyperlink{_timer_8h}{Timer.\+h}}\item
Timer.\+cpp\end{DoxyCompactItemize}


text:
<?php
/**
 * Created by PhpStorm.
 * User: victor
 * Date: 20.09.16
 * Time: 22:44
 */

namespace app\models;

use yii\base\Model;
use yii\helpers\ArrayHelper;

class Dialog extends Model
{
    const MAX_LEVEL = 4;

    public $root;
    public $lvl;
    public $exactNode;
    public $questionAnswer = null;

    public function __construct(array $config, $indexSearchResult)
    {
        parent::__construct($config);
        if (null == $this->questionAnswer) {
            $this->prepareSearchResult($indexSearchResult);
        }
        $this->lvl = \Yii::$app->session->get('lvl');
        $this->exactNode = \Yii::$app->session->get('node');
    }

    private function prepareSearchResult($searchResult)
    {
        $this->prepareRoot($searchResult);
        $this->prepareLevel($searchResult);
    }

    private function prepareRoot($searchResult)
    {
        if (null == $this->root && null !== $searchResult) {
            $this->root = (count($searchResult) > 1) ? array_keys($searchResult) : current(array_keys($searchResult));
        }
        \Yii::$app->session->set('root', $this->root);
    }

    private function prepareLevel($searchResult)
    {
        if (empty($searchResult) || is_array($this->root)) {
            $this->lvl = 0;
            $this->exactNode = null;
        } else {
            $searchResult[$this->root] = self::removeDuplicates($searchResult[$this->root]);
            if (count($searchResult[$this->root]) == 1) {
                $this->lvl = ArrayHelper::getValue(current($searchResult), '0.lvl') + 1;
                $this->exactNode = ArrayHelper::getValue(current($searchResult), '0.id');
            } else {
                $levels = ArrayHelper::getColumn($searchResult[$this->root], 'lvl', false);
                $this->lvl = $this->getMaxLevel($levels);
                $this->exactNode = $this->getExactNode($searchResult[$this->root]);
            }

            if ($this->lvl > self::MAX_LEVEL) {
                $this->lvl = self::MAX_LEVEL;
            }

        }
            \Yii::$app->session->set('lvl', $this->lvl);
            \Yii::$app->session->set('node', $this->exactNode);
        /*
         *
         * 1) {n1:1;n2:2...}
         * 2) {n1:1;n2:1;n3:5...}
         *
         * lvl_exact, id_exact
         */
    }

    private function getExactNode($nodes)
    {
        ArrayHelper::multisort($nodes, 'lvl', SORT_DESC);
        $lvlPrev = $nodes[0]['lvl'];
        $nodeId = $nodes[0]['id'];
        $nodesByLvl = [];
        for ($i = 1; $i < count($nodes); $i++) {
            $nodesByLvl[] = $nodes[$i - 1]['id'];
            if ($lvlPrev !== $nodes[$i]['lvl']) {
                break;
            }
            $lvlPrev = $nodes[$i]['lvl'];
            $nodeId = $nodes[$i - 1]['id'];
        }
        \Yii::$app->session->set('foundNodes', $nodesByLvl);
        return $nodeId;
    }

    private function getMinLevel(array $levels = [])
    {
        $level = 0;
        sort($levels);
        for ($i = 0; $i < count($levels); $i++) {
            if ($i > 0 && $levels[$i] == $levels[$i - 1]) {
                if ($i == 1) {
                    $level++;
                }
                break;
            }
            $level = $levels[$i];
        }
        return $level;
    }

    private function getMaxLevel(array $levels = [])
    {
        $level = 0;
        rsort($levels);
        for ($i = 0; $i < count($levels); $i++) {
            if ($i > 0 && $levels[$i] == $levels[$i - 1]) {
                break;
            }
            $level = $levels[$i];
        }
        return $level;
    }

    public function getQuestion()
    {
        if (null !== $this->exactNode) {
            return (new Question())->find()->where(['node_id' => $this->exactNode])->one();
        }
        return null;
    }

    public static function removeDuplicates($array)
    {
        $newArray = [];
        foreach ($array as $key => $value) {
            if (!array_key_exists($value->id, $newArray)) {
                $newArray[$value->id] = $value;
            }
        }
        return array_values($newArray);
    }
}


text:
package org.synyx.urlaubsverwaltung.core.sync.absence;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * Daniel Hammann - <hammann@synyx.de>.
 */
@Service
public class AbsenceMappingServiceImpl implements AbsenceMappingService {

    private final AbsenceMappingDAO absenceMappingDAO;

    @Autowired
    public AbsenceMappingServiceImpl(AbsenceMappingDAO absenceMappingDAO) {

        this.absenceMappingDAO = absenceMappingDAO;
    }

    @Override
    public AbsenceMapping create(Integer id, AbsenceType absenceType, String eventId) {

        AbsenceMapping absenceMapping = new AbsenceMapping(id, absenceType, eventId);
        absenceMappingDAO.save(absenceMapping);

        return absenceMapping;
    }

    @Override
    public void delete(AbsenceMapping absenceMapping) {

        absenceMappingDAO.delete(absenceMapping);
    }

    @Override
    public Optional<AbsenceMapping> getAbsenceByIdAndType(Integer id, AbsenceType absenceType) {

        return Optional.ofNullable(absenceMappingDAO.findAbsenceMappingByAbsenceIdAndAbsenceType(id, absenceType));
    }
}


text:
angular.module( 'ngBoilerplate', [
  'templates-app',
  'templates-common',
  'ngBoilerplate.home',
  'ngBoilerplate.about',
  'ui.router'
])

.config( function myAppConfig ( $stateProvider, $urlRouterProvider ) {
  $urlRouterProvider.otherwise( '/home' );
})

.run( function run () {
})

.controller( 'AppCtrl', function AppCtrl ( $scope, $location , $mdSidenav) {
  $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
    if ( angular.isDefined( toState.data.pageTitle ) ) {
      $scope.pageTitle = toState.data.pageTitle + ' | Angualr Material' ;
    }
  });
  $scope.menus = [
    {
      name : "Home",
      url : "home"
    },
    {
      name : "About",
      url : "about"
    }
  ];

  $scope.toggleSidenav = function() {
    $mdSidenav('left').toggle();
  };

})

;


text:
package org.codehaus.mojo.templating;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.maven.model.Build;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.utils.ReaderFactory;

/**
 * @author Krzysztof Suszyński <krzysztof.suszynski@wavesoftware.pl>
 * @since 2015-11-17
 */
public class MavenProjectStub
    extends MavenProject
{
    private final File basedir;

    public MavenProjectStub( File basedir )
    {
        this.basedir = basedir;
        initiate();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public File getBasedir()
    {
        return basedir;
    }

    private void initiate()
    {
        MavenXpp3Reader pomReader = new MavenXpp3Reader();
        Model model;
        try
        {
            model = pomReader.read( ReaderFactory.newXmlReader( new File( getBasedir(), "pom.xml" ) ) );
            setModel( model );
        }
        catch ( Exception e )
        {
            throw new RuntimeException( e );
        }

        setGroupId( model.getGroupId() );
        setArtifactId( model.getArtifactId() );
        setVersion( model.getVersion() );
        setName( model.getName() );
        setUrl( model.getUrl() );
        setPackaging( model.getPackaging() );

        Build build = new Build();
        build.setFinalName( model.getArtifactId() );
        build.setDirectory( getBasedir() + "/target" );
        build.setSourceDirectory( getBasedir() + "/src/main/java" );
        build.setOutputDirectory( getBasedir() + "/target/classes" );
        build.setTestSourceDirectory( getBasedir() + "/src/test/java" );
        build.setTestOutputDirectory( getBasedir() + "/target/test-classes" );
        setBuild( build );

        List<String> compileSourceRoots = new ArrayList<String>();
        compileSourceRoots.add( getBasedir() + "/src/main/java" );
        setCompileSourceRoots( compileSourceRoots );

        List<String> testCompileSourceRoots = new ArrayList<String>();
        testCompileSourceRoots.add( getBasedir() + "/src/test/java" );
        setTestCompileSourceRoots( testCompileSourceRoots );
    }

    public static MavenProject createProjectForITExample( String exampleName )
    {
        String load = exampleName + File.separator + "pom.xml";
        URL pomUrl = MavenProjectStub.class.getClassLoader().getResource( load );
        assert pomUrl != null : "Could not load: " + load;
        String pomPath = pomUrl.getPath();
        File pomFile = new File( pomPath );
        assertThat( pomFile ).exists().isFile();

        File baseDir = pomFile.getParentFile();
        assertThat( baseDir ).exists().isDirectory();
        return new MavenProjectStub( baseDir );
    }

}


text:
Descrição
 - Uma calculadora simples implementada em Java que roda sobre um web service.

Objetivo
 - O objetivo deste projeto é a realização de duas atividades do curso de pós graduação de Engenharia de Software EAD da UFRGS, sendo que a primeira atividade é a realização de um web service simples em Java para a disciplina de SOA e a segunda atividade é a criação de um projeto em um repositório de livre escolha da disciplina de Software Livre.

Tecnologias
 - Java
 - SOA

Licença
 - MIT


text:
using System;
using UnityEngine;
using Rayman;

//指令--探索
public class GoalExplore : CompositeStrategicGoal{
	public const string TYPE = "explore";

	private CActorEntity _owner;

	//探索的目标, 如果完成则重新找个目标
	private Vector3 _destination;
	private bool _isDestinationSet;

	public GoalExplore (CActorEntity owner) : base(TYPE){
		_owner = owner;
	}

	public override void Activate (){
		base.Activate();
		RemoveAllSubgoals();

		if (!_isDestinationSet){
			_isDestinationSet = true;
			_destination = TMap.Instance.FindRandomNodeLocation();
		}

		AddSubgoal(new GoalArrivePosition(_owner, _destination));
	}

	public override int Process(){
		ActivateIfNOTActive();
		_status = ProcessSubgoals();
		if (isComplete)_isDestinationSet = false;
		return _status;
	}
}


text:
// @formatter:off

package com.spike.giantdataanalysis.benchmark.tools.jmh.samples;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.BenchmarkParams;
import org.openjdk.jmh.infra.ThreadParams;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class JMHSample_31_InfraParams {

    /*
     * There is a way to query JMH about the current running mode. This is
     * possible with three infrastructure objects we can request to be injected:
     *   - BenchmarkParams: covers the benchmark-global configuration
     *   - IterationParams: covers the current iteration configuration
     *   - ThreadParams: covers the specifics about threading
     *
     * Suppose we want to check how the ConcurrentHashMap scales under different
     * parallelism levels. We can put concurrencyLevel in @Param, but it sometimes
     * inconvenient if, say, we want it to follow the @Threads count. Here is
     * how we can query JMH about how many threads was requested for the current run,
     * and put that into concurrencyLevel argument for CHM constructor.
     */

    static final int THREAD_SLICE = 1000;

    private ConcurrentHashMap<String, String> mapSingle;
    private ConcurrentHashMap<String, String> mapFollowThreads;

    @Setup
    public void setup(BenchmarkParams params) { // MARK 注入BenchmarkParams
        int capacity = 16 * THREAD_SLICE * params.getThreads();
        mapSingle        = new ConcurrentHashMap<>(capacity, 0.75f, 1);
        mapFollowThreads = new ConcurrentHashMap<>(capacity, 0.75f, params.getThreads());
    }

    /*
     * Here is another neat trick. Generate the distinct set of keys for all threads:
     */

    @State(Scope.Thread)
    public static class Ids {
        private List<String> ids;

        @Setup
        public void setup(ThreadParams threads) { // MARK 注入ThreadParams
            ids = new ArrayList<>();
            for (int c = 0; c < THREAD_SLICE; c++) {
                ids.add("ID" + (THREAD_SLICE * threads.getThreadIndex() + c));
            }
        }
    }

    @Benchmark
    public void measureDefault(Ids ids) {
        for (String s : ids.ids) {
            mapSingle.remove(s);
            mapSingle.put(s, s);
        }
    }

    @Benchmark
    public void measureFollowThreads(Ids ids) {
        for (String s : ids.ids) {
            mapFollowThreads.remove(s);
            mapFollowThreads.put(s, s);
        }
    }

    /*
     * ============================== HOW TO RUN THIS TEST: ====================================
     *
     * You can run this test:
     *
     * a) Via the command line:
     *    $ mvn clean install
     *    $ java -jar target/benchmarks.jar JMHSample_31 -t 4 -f 5
     *    (we requested 4 threads, and 5 forks; there are also other options, see -h)
     *
     * b) Via the Java API:
     *    (see the JMH homepage for possible caveats when running from IDE:
     *      http://openjdk.java.net/projects/code-tools/jmh/)
     */

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(JMHSample_31_InfraParams.class.getSimpleName())
                .threads(4)
                .forks(5)
                .build();

        new Runner(opt).run();
    }

}


text:
//
// Copyright (c) 2016-present, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//

#include "playout_multithread.h"
#include "tree_search.h"
static BOOL check_correct = FALSE;

int seed;
void onexit() {
  printf("Random seed = %d\n", seed);
}

int main(int argc, char *argv[]) {
  int K, R;
  int nthread = 16;
  int num_gpu = 4;

  char server_type[100];
  strcpy(server_type, "local");

  if (check_correct) {
    K = 1000;
    R = 10;
  } else {
    K = 100000;
    R = 50;
  }

  SearchParamsV2 search_params;
  TreeParams tree_params;

  ts_v2_init_params(&search_params);
  tree_search_init_params(&tree_params);

  search_params.verbose = V_INFO;
  tree_params.verbose = V_INFO;
  // tree_params.verbose = V_DEBUG;
  //
  K = 1000;
  if (argc >= 2) sscanf(argv[1], "%s", server_type);
  if (argc >= 3) sscanf(argv[2], "%d", &K);
  if (argc >= 4) sscanf(argv[3], "%d", &nthread);
  if (argc >= 5) sscanf(argv[4], "%d", &num_gpu);
  if (argc >= 6) sscanf(argv[5], "%d", &R);

  if (! strcmp(server_type, "local")) {
    printf("Use local server\n");
    search_params.server_type = SERVER_LOCAL;
    search_params.num_gpu = num_gpu;
    strcpy(search_params.pipe_path, "/data/local/go/");
  } else {
    printf("Use cluster server = %s\n", server_type);
    search_params.server_type = SERVER_CLUSTER;
    search_params.num_gpu = num_gpu;
    strcpy(search_params.tier_name, server_type);
  }

  // search_params.print_search_tree = TRUE;

  tree_params.use_async = FALSE;
  search_params.cpu_only = FALSE;
  tree_params.expand_n_thres = 0;

  /*
  search_params.cpu_only = TRUE;
  tree_params.use_async = TRUE;
  tree_params.expand_n_thres = 40;
  */

  tree_params.num_rollout = K;
  tree_params.num_rollout_per_move = K;
  tree_params.num_dcnn_per_move = K;
  tree_params.num_receiver = num_gpu;
  tree_params.num_tree_thread = nthread;
  tree_params.sigma = 0.05;
  // tree_params.num_virtual_games = 10;
  tree_params.decision_mixture_ratio = 5.0;
  tree_params.rcv_max_num_move = 20;
  tree_params.use_rave = FALSE;
  tree_params.use_online_model = FALSE;
  tree_params.online_model_alpha = 0.001;
  tree_params.online_prior_mixture_ratio = 5.0;
  tree_params.rcv_acc_percent_thres = 80;
  // tree_params.sigma = 0.00;
  tree_params.use_pondering = TRUE;
  strcpy(tree_params.pattern_filename, "../models/playout-model.bin");
  tree_params.default_policy_choice = DP_V2;
  tree_params.default_policy_temperature = 0.125;

  // seed = time(NULL);
  seed = 1441648459;
  srand(seed);
  atexit(onexit);
  printf("K = %d, R = %d, nthread = %d, num_gpu = %d\n", K, R, nthread, num_gpu);

  // Random expand a few nodes.
  //
  double t;
  Board board;
  ClearBoard(&board);
  GroupId4 ids;
  AllMoves move_seq;

  void *tree_handle = ts_v2_init(&search_params, &tree_params, &board);
  ts_v2_print_params(tree_handle);
  ts_v2_search_start(tree_handle);

  char dbuf[200];
  strcpy(dbuf, "/tmp/test_playout_multithread.XXXXXX");
  if (!mkdtemp(dbuf)) {
    error("Could not create temporary directory");
  }

  printf("Saving JSON tree dumps in %s\n", dbuf);
  char* buf = dbuf + strlen(dbuf);
  *buf++ = '/';

  timeit
  for (int i = 0; i < R; ++i) {
    timeit
    // dprintf("======================= Start round %d out of %d ========================\n", i, R);
    Move m = ts_v2_pick_best(tree_handle, &move_seq, NULL);
    sprintf(buf, "mcts_tree_%d", i);
    ts_v2_tree_to_json(tree_handle, buf);
    ts_v2_prune_ours(tree_handle, m.m);

    // Save the current tree.
    // printf("Saving current tree to %s...\n", buf);
    // tree_print_out_cnn(buf, ts_get_tree_pool(tree_handle));

    if (! TryPlay(&board, m.x, m.y, board._next_player, &ids) ) error("The move given by expansion should never fail!!");
    Play(&board, &ids);

    ShowBoard(&board, SHOW_LAST_MOVE);
    printf("\n");

    if (check_correct) {
      // dprintf("======================= Finish round %d out of %d ========================\n", i, R);
      // tree_pool_check(ts_get_tree_pool(tree_handle));
    }
    endtime
  }
  endtime2(t)

  printf("Freeing\n");
  timeit
    ts_v2_search_stop(tree_handle);
    ts_v2_free(tree_handle);
  endtime

  printf("Time used for mcts = %lf\n", t);
  printf("rollout rate = %f\n", K * R / t);
  return 0;
}


text:
package io.datarouter.client.memcached.client;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.inject.Singleton;

import io.datarouter.storage.client.ClientId;

@Singleton
public class MemcachedClientHolder{

	private final Map<ClientId,DatarouterMemcachedClient> clientById = new ConcurrentHashMap<>();

	public void register(ClientId clientId, DatarouterMemcachedClient client){
		if(clientById.containsKey(clientId)){
			throw new RuntimeException(clientId + " already registered a memcached client");
		}
		clientById.put(clientId, client);
	}

	public DatarouterMemcachedClient get(ClientId clientId){
		return clientById.get(clientId);
	}

}