text:
package org.ehcache.internal.store;

import org.ehcache.config.Eviction;
import org.ehcache.config.EvictionVeto;
import org.ehcache.spi.cache.Store;
import org.ehcache.spi.test.SPITest;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;

/**
 * Test the {@link org.ehcache.spi.cache.Store.Configuration#getEvictionVeto()} contract of the
 * {@link org.ehcache.spi.cache.Store.Configuration Store.Configuration} interface.
 * <p/>
 *
 * @author Aurelien Broszniowski
 */

public class StoreConfigurationGetEvictionVetoTest<K, V> extends SPIStoreTester<K, V> {

  public StoreConfigurationGetEvictionVetoTest(final StoreFactory<K, V> factory) {
    super(factory);
  }

  @SPITest
  public void returnsCorrectEvictionVeto() throws IllegalAccessException, InstantiationException {
    final EvictionVeto<Object, Object> evictionVeto = Eviction.all();
    Store.Configuration<K, V> kvConfiguration = factory.newConfiguration(factory.getKeyType(), factory.getValueType(),
        null, evictionVeto, null);

    assertThat(evictionVeto, is(equalTo(((Object)kvConfiguration.getEvictionVeto()))));
  }
}


text:
using System;
using UnityEngine;

[Serializable]
public class CameraXZData {
    public Vector3Serializable Location = new Vector3Serializable();
    public float Zoom;

    public CameraXZData() { }

    public CameraXZData(Camera camera) {
        Location = camera.transform.position;
        Zoom = camera.orthographicSize;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace app\controllers;

use Yii;
use app\models\EarthCountries;
use app\models\TimeOffset;
use app\models\User;
use app\models\Blog;
use yii\data\ArrayDataProvider;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\web\Controller;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * UserController implements the CRUD actions for Users model.
 */
class UserController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class'   => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    public function beforeAction($action)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect([
                'site/login',
                'logined' => 'false',
            ]);
        }

        return parent::beforeAction($action);
    }

    /**
     * Lists all User models.
     * All registered users can view full users list,
     *      but yes, only admins can update/delete users from this list.
     * TODO: There MUST be normal realization of timezone offset!
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $model = $this->findModel(Yii::$app->user->id);
        if (!$model->isAdmin()) {
            return $this->redirect([
                'user/view',
                'id'    => Yii::$app->user->id,
                'error' => 'no_rights',
            ]);
        }
        $pagination = new Pagination([
            'defaultPageSize' => 10,
            'totalCount'      => User::find()->count(),
        ]);

        $dataProvider = new ActiveDataProvider([
            'query'      => User::find(),
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'pagination'   => $pagination,
        ]);
    }

    /**
     * Displays a single User model.
     *
     * @param integer $id
     *
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $blog = Blog::getBlogByAuthorId($id);
        $user = User::findOne(Yii::$app->user->identity->getId());
        $canUserSeeBlog = $blog->is_private === 0 || $user->isAdmin();

        return $this->render('view', [
            'model'          => $model,
            'blog'           => $blog,
            'canUserSeeBlog' => $canUserSeeBlog,
        ]);
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     *
     * @param integer $id
     *
     * @throws HttpException if transaction is unsuccessful
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->checkUDPrivilegies($model) && $model->load(Yii::$app->request->post())) {
            TimeOffset::setTimezoneCookie($model->timezone);
            if ($model->saveUser($model)) {
                return $this->redirect([
                    'view',
                    'id' => $model->id,
                ]);
            } else {
                throw new HttpException(400, 'Error during saving comment info in the database');
            }
        } else {
            return $this->render('update', [
                'model'         => $model,
                'timeZonesList' => $model->getTimeZoneSelect(),
            ]);
        }
    }

    /**
     * Deletes an existing Users model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * The cookie with timezone value isn't being deleted.
     *
     * @throws HttpException if transaction is unsuccessful
     *
     * @param integer $id
     *
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        if (!Yii::$app->user->isGuest) {
            if ($model->checkUDPrivilegies($model)) {
                if ($model->deleteUser($model)) {
                    return $this->goHome();
                } else {
                    throw new HttpException(400, 'Error during saving comment info in the database');
                }
            } else {
                return $this->redirect([
                    'user/view',
                    'id'    => Yii::$app->user->id,
                    'error' => 'no_rights',
                ]);
            }
        } else {
            return $this->redirect([
                'site/login',
                'logined' => 'false',
            ]);
        }
    }

    /**
     * Assigns a role to user.
     * For assign a first admin you need to run 'yii rbac/init-first-admin [id]',
     * where [id] (without brackets) is an ID of registered user
     */
    public function actionAssign($id = null, $role = null)
    {
        $model = new User;
        $isAdmin = $model->isAdmin();
        # True if current user is an admin
        if (!Yii::$app->user->isGuest) {
            if ($isAdmin) {
                $pagination = new Pagination([
                    'defaultPageSize' => 10,
                    'totalCount'      => User::find()->count(),
                ]);
                $dataProvider = new ActiveDataProvider([
                    'query'      => User::find()
                                        ->offset($pagination->offset)
                                        ->limit($pagination->limit),
                    'pagination' => [
                        'pageSize' => 10,
                    ],
                ]);
                if (is_null($dataProvider)) {
                    return $this->render('assign', [
                        'dataProvider' => $dataProvider,
                        'modelIsNull'  => true,
                    ]);
                } else {
                    if ($id != null) {
                        $model->setRole($id, $role);
                        return $this->render('assign', [
                            'dataProvider'  => $dataProvider,
                            'model'         => $model,
                            'modelIsNull'   => false,
                            'setRole'       => ($role == 'admin') ? 'Administrator' : 'Author',
                            'assigned_user' => User::findIdentity($id),
                        ]);
                    } else {
                        return $this->render('assign', [
                            'dataProvider' => $dataProvider,
                            'model'        => $model,
                            'modelIsNull'  => false,
                        ]);
                    }
                }
            } else {
                return $this->redirect([
                    'user/view',
                    'id'    => Yii::$app->user->id,
                    'error' => 'no_rights',
                ]);
            }
        } else {
            return $this->redirect([
                'site/login',
                'logined' => 'false',
            ]);
        }
    }

    /**
     * Finds the Users model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     *
     * @param integer $id
     *
     * @return User| The loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested user does not exist.');
        }
    }
}


text:
#include <aws/ssm-incidents/model/StartIncidentRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::SSMIncidents::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

StartIncidentRequest::StartIncidentRequest() :
    m_clientToken(Aws::Utils::UUID::RandomUUID()),
    m_clientTokenHasBeenSet(true),
    m_impact(0),
    m_impactHasBeenSet(false),
    m_relatedItemsHasBeenSet(false),
    m_responsePlanArnHasBeenSet(false),
    m_titleHasBeenSet(false),
    m_triggerDetailsHasBeenSet(false)
{
}

Aws::String StartIncidentRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_clientTokenHasBeenSet)
  {
   payload.WithString("clientToken", m_clientToken);

  }

  if(m_impactHasBeenSet)
  {
   payload.WithInteger("impact", m_impact);

  }

  if(m_relatedItemsHasBeenSet)
  {
   Array<JsonValue> relatedItemsJsonList(m_relatedItems.size());
   for(unsigned relatedItemsIndex = 0; relatedItemsIndex < relatedItemsJsonList.GetLength(); ++relatedItemsIndex)
   {
     relatedItemsJsonList[relatedItemsIndex].AsObject(m_relatedItems[relatedItemsIndex].Jsonize());
   }
   payload.WithArray("relatedItems", std::move(relatedItemsJsonList));

  }

  if(m_responsePlanArnHasBeenSet)
  {
   payload.WithString("responsePlanArn", m_responsePlanArn);

  }

  if(m_titleHasBeenSet)
  {
   payload.WithString("title", m_title);

  }

  if(m_triggerDetailsHasBeenSet)
  {
   payload.WithObject("triggerDetails", m_triggerDetails.Jsonize());

  }

  return payload.View().WriteReadable();
}


text:
/* -*- Mode: C++; -*- */
// C&C NLP tools
// Copyright (c) Universities of Edinburgh, Oxford and Sydney
// Copyright (c) James R. Curran
//
// This software is covered by a non-commercial use licence.
// See LICENCE.txt for the full text of the licence.
//
// If LICENCE.txt is not included in this distribution
// please email candc@it.usyd.edu.au to obtain a copy.

inline void
lower(std::string &s){
  for(std::string::iterator i = s.begin(); i != s.end(); ++i)
    *i = std::tolower(*i);
}


text:
package gwt.material.design.client.base;

import gwt.material.design.client.base.mixin.TooltipMixin;
import gwt.material.design.client.constants.Position;
import gwt.material.design.client.ui.MaterialTooltip;
import gwt.material.design.jquery.client.api.JQueryElement;

/**
 * Interface that determines the class has a {@link MaterialTooltip} attached to
 * it.
 *
 * @author gilberto-torrezan
 * @see TooltipMixin
 * @see MaterialWidget
 */
public interface HasTooltip {

    /**
     * @return the current tooltip text to be shown
     */
    String getTooltip();

    /**
     * Sets the tooltip text to be shown for the component.
     */
    void setTooltip(String tooltip);

    /**
     * Sets the tooltip text to be shown with additional classes
     */
    void setTooltip(String tooltip, String... classes);

    /**
     * @return the position where the tooltip text should appear, relative to
     * the component
     */
    Position getTooltipPosition();

    /**
     * Sets the {@link Position} where the tooltip text should appear, relative
     * to the component.
     */
    void setTooltipPosition(Position position);

    /**
     * @return the delay in ms used to show the tooltip
     */
    int getTooltipDelayMs();

    /**
     * Sets the time in ms to show the tooltip text for the component
     */
    void setTooltipDelayMs(int delayMs);

    void setTooltipHTML(String html);

    String getTooltipHTML();

    /**
     * Get the Tooltip element to ease of customization
     */
    JQueryElement getTooltipElement();
}


text:
package uqac.sma.project.strategies;

import uqac.sma.project.core.Decision;
import uqac.sma.project.core.Strategy;

public class AllC implements Strategy {

	public AllC(){}

	@Override
	public Decision play(int round, Decision lastOpponentDecision) {
		return Decision.COOPERATE;
	}

	public void finalize(){}

}


text:
@extends('clearboard.common.template')

@section('title', '404 Not Found')

@section('content')

404 Not Found

The page you requested doesn't exist.

Goto the homepage

Go back

@endsection


text:
UNIX_ApplicationSystemProvider::UNIX_ApplicationSystemProvider()
{
}

UNIX_ApplicationSystemProvider::~UNIX_ApplicationSystemProvider()
{
}

CIMInstance UNIX_ApplicationSystemProvider::constructInstance(
	const CIMName &className,
	const CIMNamespaceName &nameSpace,
	const UNIX_ApplicationSystem &_p) const
{
	CIMProperty p;

	CIMInstance inst(className);

	// Set path
	inst.setPath(CIMObjectPath(String(""), // hostname
			nameSpace,
			CIMName("UNIX_ApplicationSystem"),
			constructKeyBindings(_p)));

	//CIM_ManagedElement Properties
	if (_p.getInstanceID(p)) inst.addProperty(p);
	if (_p.getCaption(p)) inst.addProperty(p);
	if (_p.getDescription(p)) inst.addProperty(p);
	if (_p.getElementName(p)) inst.addProperty(p);

	//CIM_ManagedSystemElement Properties
	if (_p.getInstallDate(p)) inst.addProperty(p);
	if (_p.getName(p)) inst.addProperty(p);
	if (_p.getOperationalStatus(p)) inst.addProperty(p);
	if (_p.getStatusDescriptions(p)) inst.addProperty(p);
	if (_p.getStatus(p)) inst.addProperty(p);
	if (_p.getHealthState(p)) inst.addProperty(p);
	if (_p.getCommunicationStatus(p)) inst.addProperty(p);
	if (_p.getDetailedStatus(p)) inst.addProperty(p);
	if (_p.getOperatingStatus(p)) inst.addProperty(p);
	if (_p.getPrimaryStatus(p)) inst.addProperty(p);

	//CIM_LogicalElement Properties

	//CIM_EnabledLogicalElement Properties
	if (_p.getEnabledState(p)) inst.addProperty(p);
	if (_p.getOtherEnabledState(p)) inst.addProperty(p);
	if (_p.getRequestedState(p)) inst.addProperty(p);
	if (_p.getEnabledDefault(p)) inst.addProperty(p);
	if (_p.getTimeOfLastStateChange(p)) inst.addProperty(p);
	if (_p.getAvailableRequestedStates(p)) inst.addProperty(p);
	if (_p.getTransitioningToState(p)) inst.addProperty(p);

	//CIM_System Properties
	if (_p.getCreationClassName(p)) inst.addProperty(p);
	if (_p.getNameFormat(p)) inst.addProperty(p);
	if (_p.getPrimaryOwnerName(p)) inst.addProperty(p);
	if (_p.getPrimaryOwnerContact(p)) inst.addProperty(p);
	if (_p.getRoles(p)) inst.addProperty(p);
	if (_p.getOtherIdentifyingInfo(p)) inst.addProperty(p);
	if (_p.getIdentifyingDescriptions(p)) inst.addProperty(p);

	//UNIX_ApplicationSystem Properties
	if (_p.getDistribution(p)) inst.addProperty(p);
	if (_p.getStartupTime(p)) inst.addProperty(p);
	if (_p.getServingStatus(p)) inst.addProperty(p);
	if (_p.getLastServingStatusUpdate(p)) inst.addProperty(p);

	return inst;
}

Array<CIMKeyBinding> UNIX_ApplicationSystemProvider::constructKeyBindings(const UNIX_ApplicationSystem& _p) const
{

	Array<CIMKeyBinding> keys;

	keys.append(CIMKeyBinding(
		PROPERTY_CREATION_CLASS_NAME,
		_p.getCreationClassName(),
		CIMKeyBinding::STRING));
	keys.append(CIMKeyBinding(
		PROPERTY_NAME,
		_p.getName(),
		CIMKeyBinding::STRING));

	return keys;
}

#define UNIX_PROVIDER UNIX_ApplicationSystemProvider
#define UNIX_PROVIDER_NAME "UNIX_ApplicationSystemProvider"
#define CLASS_IMPLEMENTATION UNIX_ApplicationSystem
#define CLASS_IMPLEMENTATION_NAME "UNIX_ApplicationSystem"
#define BASE_CLASS_NAME "UNIX_ApplicationSystem"
#define NUMKEYS_CLASS_IMPLEMENTATION 2

#include "UNIXProviderBase.hpp"


text:
namespace ytools { namespace file_utils {
  class FileEnv;
}} // namespace ytools { namespace file_utils {

namespace ytools { namespace YShaderCompiler {

struct ShaderDefine {
  const char* define;
  const char* value;
};

enum ShaderOpt {
  kShaderOpt_None,
  kShaderOpt_Level0,
  kShaderOpt_Level1,
  kShaderOpt_Level2,
  kShaderOpt_Level3
};

enum ShaderType {
  kShaderType_VertexShader,
  kShaderType_PixelShader,

  NUM_SHADER_TYPES
};

bool CompileShader(const std::string& source_file,
                   const std::string& entry_point,
                   ShaderType shader_type, int target_major, int target_minor,
                   ShaderOpt opt_level, bool debug,
                   const ShaderDefine* defines, size_t num_defines,
                   std::vector<uint8_t>& output,
                   file_utils::FileEnv* file_env = NULL);

}} // namespace ytools { namespace YShaderCompiler {

#endif // YTOOLS_YSHADER_COMPILER_COMPILE_SHADER_H


text:
import joi from 'joi'

// wrapper for joi, that throws errors
export default function joiValidate (value, schema) {
  if (!schema.isJoi) {
    schema = joi.object().keys(schema)
  }
  const result = joi.validate(value, schema)
  if (result.error) {
    throw new Error(result.error)
  }
  return result.value
}


text:
require "rails_helper"

describe Eve::AgentDashboard do
  it { should be_an(Administrate::BaseDashboard) }

  describe "#display_resource" do
    let(:agent) { build(:eve_agent, name: "Pomik Haromi") }

    specify { expect(subject.display_resource(agent)).to eq("Pomik Haromi") }
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">

    <context:property-placeholder location="classpath*:config.properties" />
    <import resource="classpath*:/META-INF/persistence-context.xml" />
    <context:component-scan base-package="com.cdesigner.dao" />
    <context:component-scan base-package="com.cdesigner.service" />
    <context:component-scan base-package="com.cdesigner.util" />
    <aop:aspectj-autoproxy />
</beans>


text:
<#
The MIT License (MIT)

Copyright (c) 2015 Objectivity Bespoke Software Specialists

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

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

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

function Get-ProgramFilesx86Path {
    <#
    .SYNOPSIS
    Return 32-bit 'Program Files' path

    .DESCRIPTION
    Returns the path to 32-bit 'Program Files' (depending on architecture - C:\Program Files (x86) or C:\Program Files)

    .EXAMPLE
    Get-ProgramFilesx86Path
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param()

    if (${env:ProgramFiles(x86)}) {
        return ${env:ProgramFiles(x86)}
    }

    return $env:programfiles
}


text:
package org.gsonformat.intellij.common;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by dim on 2015/8/21.
 */
public class CheckUtil {

    private static CheckUtil sCheckUtil;
    private List<String> keyWordList = new ArrayList<String>();
    private List<String> simpleTypeList = new ArrayList<String>();
    private Set<String> declareClassNameList = new HashSet();
    private Set<String> declareFieldNameList = new HashSet();

    private CheckUtil() {
        keyWordList.add("abstract");
        keyWordList.add("assert");
        keyWordList.add("boolean");
        keyWordList.add("break");
        keyWordList.add("byte");
        keyWordList.add("case");
        keyWordList.add("catch");
        keyWordList.add("char");
        keyWordList.add("class");
        keyWordList.add("const");
        keyWordList.add("continue");
        keyWordList.add("default");
        keyWordList.add("do");
        keyWordList.add("double");
        keyWordList.add("else");
        keyWordList.add("enum");
        keyWordList.add("extends");
        keyWordList.add("final");
        keyWordList.add("finally");
        keyWordList.add("float");
        keyWordList.add("for");
        keyWordList.add("goto");
        keyWordList.add("if");
        keyWordList.add("implements");
        keyWordList.add("import");
        keyWordList.add("instanceof");
        keyWordList.add("int");
        keyWordList.add("interface");
        keyWordList.add("long");
        keyWordList.add("native");
        keyWordList.add("new");
        keyWordList.add("package");
        keyWordList.add("private");
        keyWordList.add("protected");
        keyWordList.add("public");
        keyWordList.add("return");
        keyWordList.add("strictfp");
        keyWordList.add("short");
        keyWordList.add("static");
        keyWordList.add("super");
        keyWordList.add("switch");
        keyWordList.add("synchronized");
        keyWordList.add("this");
        keyWordList.add("throw");
        keyWordList.add("throws");
        keyWordList.add("transient");
        keyWordList.add("abstract");
        keyWordList.add("void");
        keyWordList.add("volatile");
        keyWordList.add("while");

        simpleTypeList.add("String");
        simpleTypeList.add("boolean");
        simpleTypeList.add("Boolean");
        simpleTypeList.add("int");
        simpleTypeList.add("Integer");
        simpleTypeList.add("Float");
        simpleTypeList.add("float");
        simpleTypeList.add("Double");
        simpleTypeList.add("double");
        simpleTypeList.add("Long");
        simpleTypeList.add("long");
    }

    public static CheckUtil getInstant() {
        if (sCheckUtil == null) {
            sCheckUtil = new CheckUtil();
        }
        return sCheckUtil;
    }

    public void cleanDeclareData() {
        declareClassNameList.clear();
        declareFieldNameList.clear();
    }

    public boolean containsDeclareClassName(String name) {
        return declareClassNameList.contains(name);
    }

    public void addDeclareClassName(String name) {
        declareClassNameList.add(name.replace(".java",""));
    }

    public void removeDeclareClassName(String name) {
        declareClassNameList.remove(name);
    }

    public boolean containsDeclareFieldName(String name) {
        return declareFieldNameList.contains(name);
    }

    public void addDeclareFieldName(String name) {
        declareFieldNameList.add(name);
    }

    public void removeDeclareFieldName(String name) {
        declareFieldNameList.remove(name);
    }

    public boolean checkSimpleType(String s) {

        return simpleTypeList.contains(s);
    }

    public boolean checkKeyWord(String key) {
        return keyWordList.contains(key);
    }

    public String handleArg(String arg) {
        Pattern pattern = Pattern.compile("^\\d+");
        Matcher matcher = pattern.matcher(arg);
        if (matcher.find()) {
            return "value" + arg;
        } else {
            if (CheckUtil.getInstant().checkKeyWord(arg)) {
                return arg + "X";
            }
            return arg;
        }
    }
}


text:
import 'reflect-metadata';
import {addAttributeOptions} from "../../services/models";

/**
 * Checks for valid floating point numbers
 */
export function IsFloat(target: any, propertyName: string): void {

  addAttributeOptions(target, propertyName, {
    validate: {
      isFloat: true
    }
  });
}


text:
@interface FPBBudget()

@property (nonatomic) NSDate *startDate;
@property (nonatomic) NSDate *endDate;
@property (nonatomic) float totalFoodPoints;
@property (nonatomic) NSInteger numDaysNotInSchool;

@end

@implementation FPBBudget

-(instancetype)initWithStartDate:(NSDate *)startDate endDate:(NSDate *)endDate foodPoints:(float)foodPoints numDaysNotInSchool:(NSInteger)numDays
{
    self = [super init];
    if(self){
        self.startDate = startDate;
        self.endDate = endDate;
        self.totalFoodPoints = foodPoints;
        self.numDaysNotInSchool = numDays;
    }
    return self;
}
-(NSUInteger)calculateDaysLeft
{
    NSDate *fromDate;
    NSDate *toDate;

    NSCalendar *calendar = [NSCalendar currentCalendar];

    // Change start date to be start of today (endDate is already start of that end day, so that's unnecessary)
    [calendar rangeOfUnit:NSDayCalendarUnit startDate:&fromDate
                 interval:NULL forDate:self.startDate];
    [calendar rangeOfUnit:NSDayCalendarUnit startDate:&toDate
                 interval:NULL forDate:self.endDate];

    NSDateComponents *difference = [calendar components:NSDayCalendarUnit
                                               fromDate:fromDate toDate:toDate options:0];

    // use this if you don't want the calculation to include today
    //NSDateComponents *difference2 = [calendar components:NSDayCalendarUnit
                                             //  fromDate:self.startDate toDate:self.endDate options:0];

    NSUInteger daysLeft = [difference day]  - self.numDaysNotInSchool;
    return daysLeft;
}

-(float)foodPointsPerDayForNumDaysLeft:(NSUInteger)numDays totalFoodPointsLeft:(float)foodPointsLeft
{
    return foodPointsLeft / numDays;
}

-(float)mainCalculations
{
    NSUInteger numDaysLeft = [self calculateDaysLeft];
    float avgFoodPointsPerDay = [self foodPointsPerDayForNumDaysLeft:numDaysLeft totalFoodPointsLeft:self.totalFoodPoints];

    return avgFoodPointsPerDay;
}

@end


text:
package com.iglin.lab3_database.statistics;

import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.iglin.lab3_database.R;
import com.iglin.lab3_database.db.TimeTrackingDbContract;
import com.iglin.lab3_database.statistics.StatisticsActivity;

import java.util.ArrayList;
import java.util.List;

public class DiagramActivity  extends StatisticsActivity {

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

        setContentView(R.layout.activity_diagram);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        fillDatesHeader();

        TextView textView = (TextView) findViewById(R.id.textStatsHeader);
        textView.setText(getString(R.string.action_diag));

        updateData();
    }

    @Override
    protected void updateData() {
        Cursor cursor = contentProvider.getMostDurableActivities(startingTime, endingTime);

        List<PieEntry> entries = new ArrayList<>();

        int indexStat, indexName;
        while (cursor.moveToNext()) {
            indexStat = cursor.getColumnIndex(TimeTrackingDbContract.Statistics.COLUMN_NAME_STAT);
            indexName = cursor.getColumnIndex(TimeTrackingDbContract.Statistics.COLUMN_NAME_TEXT);
            // turn your data into Entry objects
            entries.add(new PieEntry(cursor.getInt(indexStat), cursor.getString(indexName)));
        }

        PieDataSet pieDataSet = new PieDataSet(entries, getString(R.string.category));
        pieDataSet.setColors(Color.RED, Color.BLUE, Color.GREEN, Color.MAGENTA, Color.YELLOW);
        PieChart pieChart = (PieChart) findViewById(R.id.chart);
        pieChart.setContentDescription(getString(R.string.category));
        Description description = new Description();
        description.setText(getString(R.string.diag_text));
        pieChart.setDescription(description);
        Log.i(getClass().getName(), pieDataSet.toString());
        pieChart.setData(new PieData(pieDataSet));
    }
}


text:
<?php

/* @var $this \yii\web\View */
/* @var $content string */

use backend\assets\AppAsset;
use backend\assets\FontsAsset;
use backend\assets\BootstrapPluginAsset;
use yii\helpers\Html;
use common\widgets\Alert;

AppAsset::register($this);
FontsAsset::register($this);
BootstrapPluginAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">

    <meta charset="<?= Yii::$app->charset ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>

<?php $this->beginBody() ?>

        <?= $content ?>

<?php $this->beginContent('@app/views/layouts/_footer.php'); ?>
<?= $content ?>
<?php $this->endContent(); ?>

<?php $this->endBody() ?>

<?php $this->endPage() ?>


text:
"use strict";

exports.TypeMgr = function (db, mongodb, converter, async, prefix, typecrud, col) {
	var systemprops = [
		{pname: "Campaign", pcode: "_utm_campaign"},
		{pname: "Campaign Source", pcode: "_utm_source"},
		{pname: "Campaign Medium", pcode: "_utm_medium"},
		{pname: "Campaign Term", pcode: "_utm_term"},
		{pname: "Campaign Content", pcode: "_utm_content"},
		{pname: "Time", pcode: "_ctime"},
		{pname: "Channel", pcode: "_reftype"},
		{pname: "Referer", pcode: "_ref"},
		{pname: "Country", pcode: "_country" },
		{pname: "City", pcode: "_city"},
		{pname: "Location", pcode: "_location"},
		{pname: "Operating System", pcode: "_os"},
		{pname: "OS Version", pcode: "_osver"},
		{pname: "Browser", pcode: "_browser" },
		{pname: "Browser Version", pcode: "_browserver"},
		{pname: "Device", pcode: "_deviceid" },
		{pname: "Device Type", pcode: "_devicetype" },
		{pname: "Screen Resolution", pcode: "_scr"},
		{pname: "Language", pcode: "_lang"}
	];
	this.create = function (req, res, callback) {
		// TODO: check if typename existed
		// TODO: check if fields is system
		typecrud.create(req, res, callback);
	};

	this.update = function (req, res, callback) {
		typecrud.update(req, res, callback);
	};

	this.list = function (req, res, callback) {
		var appid = req.params.appid;
		var collection = prefix + col;
		converter.toIDs(['_appid', '_isDraft'], function (ids) {
			var query = {$and: []};
			var projection = {};

			var andStatement = {};
			andStatement[ids._appid] = appid;
			query.$and.push(andStatement);

			andStatement = {$or: []};
			var orStatement = {};
			orStatement[ids._isDraft] = false;
			andStatement.$or.push(orStatement);
			orStatement = {};
			orStatement[ids._isDraft] = {$exists: false};
			andStatement.$or.push(orStatement);

			query.$and.push(andStatement);
			projection[ids._appid] = 0;
			projection[ids._isDraft] = 0;

			var cursor = db.collection(collection).find(query, projection);
			var done = false;
			var results = [];
			async.whilst(function () {
				return done === false;
			}, function (callback) {
				cursor.next(function (err, r) {
					if (err) throw err;
					if (r) {
						converter.toOriginal(r, function (r) {
							results.push(r);
							if (r.fields instanceof Array)
								r.fields = r.fields.concat(systemprops);
							callback(null);
						});
					} else {
						done = true;
						callback(null, results);
					}
				});
			}, function (err, results) {
				if (err) throw err;

				res.json(results);
				if (callback) callback(results);
			});
		});
	};

	this.delete = function(req, res, callback){
		typecrud.delete(req, res, callback);
	};

	this.match = function(req, res, callback){
		// var appid = req.params.appid;
		var atid = req.params.id;
		var collection = prefix + col;
		converter.toID('_appid', function (r) {
			var query = {_id: new mongodb.ObjectID(atid)};
			var projection = {};
			projection[r] = 0;
			db.collection(collection).find(query, projection).toArray(function (err, r) {
				if (err) throw err;

				if (r.length !== 0) {
					converter.toOriginal(r[0], function (r) {
						if (r.fields instanceof Array)
							r.fields = r.fields.concat(systemprops);
						res.json(r);
						if(callback) callback();
					});
				} else {
					res.status(200).end();
				}
			});
		});
	};
};


text:
import Q = require('q');
import assert = require('assert');
import trm = require('../../lib/taskRunner');
import psm = require('../../lib/psRunner');
import path = require('path');
var shell = require('shelljs');
var ps = shell.which('powershell');
console.log(ps);
describe('VSBuild Suite', function () {
    this.timeout(20000);

    before((done) => {
        // init here
        done();
    });

    after(function () {
    });

    if (ps) {
        it('(Select-MSBuildLocation) maps vs versions', (done) => {
            psm.runPS(path.join(__dirname, 'Select-MSBuildLocation.MapsVSVersions.ps1'), done);
        })
        it('(Select-MSBuildLocation) throws if ms build version not found', (done) => {
            psm.runPS(path.join(__dirname, 'Select-MSBuildLocation.ThrowsIfMSBuildVersionNotFound.ps1'), done);
        })
        it('(Select-MSBuildLocation) throws if unknown vs version', (done) => {
            psm.runPS(path.join(__dirname, 'Select-MSBuildLocation.ThrowsIfUnknownVSVersion.ps1'), done);
        })
        it('(Select-VSVersion) falls back to latest', (done) => {
            psm.runPS(path.join(__dirname, 'Select-VSVersion.FallsBackToLatest.ps1'), done);
        })
        it('(Select-VSVersion) finds latest', (done) => {
            psm.runPS(path.join(__dirname, 'Select-VSVersion.FindsLatest.ps1'), done);
        })
        it('(Select-VSVersion) finds preferred', (done) => {
            psm.runPS(path.join(__dirname, 'Select-VSVersion.FindsPreferred.ps1'), done);
        })
        it('(Select-VSVersion) warns if vs not found', (done) => {
            psm.runPS(path.join(__dirname, 'Select-VSVersion.WarnsIfVSNotFound.ps1'), done);
        })
        it('passes arguments', (done) => {
            psm.runPS(path.join(__dirname, 'PassesArguments.ps1'), done);
        })
        it('warns if deprecated input specified', (done) => {
            psm.runPS(path.join(__dirname, 'WarnsIfDeprecatedInputSpecified.ps1'), done);
        })
    }
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>E-Index</title>
<meta name="date" content="2015-04-17">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E F G H I M O P R S T U V

E

elas - Variable in class application.Config

The elasticity value of the simulation

A C D E F G H I M O P R S T U V

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
module CRCBrute
       ( crcBruteUtf8
       ) where

import Control.Monad
import Data.Word
import Foreign.C.Types
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.Marshal.Array
import Foreign.Marshal.Utils (copyBytes, fromBool)
import Foreign.Storable
import Data.IORef
import Control.Exception
import Control.Concurrent
import Control.Concurrent.STM hiding (check)
import Control.Concurrent.Async.Pool
import System.CPUTime
import qualified Data.ByteString as B
import qualified Data.ByteString.Unsafe as B
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Vector.Storable as VS

import Utils

type Periodic = CULLong -> IO CInt
type Check = IO CInt

newtype {-# CTYPE "utf8_c" #-} CUTF8Char = CUTF8Char { unCUTF8Char :: Char }
                                         deriving (Show, Eq)

instance Storable CUTF8Char where
  sizeOf _ = 4

  alignment _ = alignment (undefined :: CInt)

  poke p c'@(CUTF8Char c) = B.unsafeUseAsCStringLen (T.encodeUtf8 $ T.singleton c) $ \(cptr, l) -> do
    copyBytes (castPtr p) cptr l
    mapM_ (\i -> poke (castPtr $ p `plusPtr` i) (0 :: Word8)) [l..sizeOf c' - 1]

  peek p = do
    a <- peekArray (sizeOf (undefined :: CUTF8Char)) $ castPtr p
    return $ CUTF8Char $ T.head $ T.decodeUtf8 $ B.pack a

type Table = Ptr (Ptr CUTF8Char)

foreign import capi "crc-brute.h makeCrcTable" c_makeCrcTable :: IO ()
foreign import capi "crc-brute.h crcBruteUtf8" c_crcBruteUtf8 :: Table -> Ptr CInt -> CInt -> Ptr CInt
                                                                -> Word32
                                                                -> FunPtr Periodic -> FunPtr Check
                                                                -> Ptr CUTF8Char
                                                                -> IO CInt

foreign import ccall "wrapper" mkPeriodic :: Periodic -> IO (FunPtr Periodic)
foreign import ccall "wrapper" mkCheck :: Check -> IO (FunPtr Check)

withPtr :: Storable a => [a] -> (Ptr a -> IO b) -> IO b
withPtr = withForeignPtr . fst . VS.unsafeToForeignPtr0 . VS.fromList

mkTable :: [[Char]] -> ([Ptr CUTF8Char] -> IO a) -> IO a
mkTable table func = with [] table
  where -- there's surely a name for a monadic recursion like this
        with vecs [] = func $ reverse vecs
        with vecs (vec:t) = withPtr (map CUTF8Char vec) $ \p -> with (p:vecs) t

crcBruteUtf8 :: Bool -> [(Int, [Char])] -> Word32 -> (T.Text -> Bool) -> IO (Maybe T.Text)
crcBruteUtf8 verbose table target check = mkTable (map snd table) $ \tablePtrs -> do
  c_makeCrcTable
  threads <- getNumCapabilities
  withTaskGroup threads $ \tg -> do
    res <- newEmptyTMVarIO
    stop <- newTVarIO False
    num <- newTVarIO (0 :: Int)

    let plen = sum $ map fst table

        widths = map (fromIntegral . findWidths . snd) table
        findWidths (h:t) = if all ((== w) . width) t
                         then w
                         else error "findWidth: dynamic width is not supported"
          where w = width h
                width c = B.length $ T.encodeUtf8 $ T.singleton c
        findWidths _ = error "findWidth: empty list"

        stopWorker ws = do
          atomically $ writeTVar stop True
          mapM_ wait ws

        workRanges = perms $ zip (map fst table) (map pure [0..])
        workLen = length workRanges

        worker perm = allocaArray plen $ \str -> do
          workn <- atomically $ do
            modifyTVar num (+1)
            readTVar num
          let prefix = "worker " ++ show workn ++ "/" ++ show workLen ++ ": "
          when verbose $ putStrLn $ prefix ++ "starting"
          time <- getCPUTime >>= newIORef

          let periodic n = do
                stop' <- atomically $ readTVar stop
                fromBool <$> if stop' then return False else do
                  when verbose $ do
                    new <- getCPUTime
                    old <- readIORef time
                    let int = fromIntegral (new - old) / 10^(12-3::Int) :: Double
                    when verbose $ putStrLn $ prefix ++ "done " ++ show n ++ " hashes in " ++ show int ++ " ms"
                    writeIORef time new
                  return True

              checkWrap = do
                when verbose $ putStrLn $ prefix ++ "found possible solution"
                ws <- T.pack <$> map unCUTF8Char <$> peekArray plen str
                let ret = check ws
                when ret $ do
                  when verbose $ putStrLn $ prefix ++ "found solution!"
                  atomically $ putTMVar res ws
                return $ fromBool ret

              table' = map (tablePtrs !!) perm
              widths' = map (widths !!) perm
              ranges' = map (fromIntegral . length . snd . (table !!)) perm

          void $
            withPtr table' $ \table'' ->
            withPtr widths' $ \widths'' ->
            withPtr ranges' $ \ranges'' ->
            bracket (mkPeriodic periodic) freeHaskellFunPtr $ \periodic'' ->
            bracket (mkCheck checkWrap) freeHaskellFunPtr $ \check'' ->
            c_crcBruteUtf8 table'' widths'' (fromIntegral plen) ranges'' target periodic'' check'' str
          when verbose $ putStrLn $ prefix ++ "finished"

    bracket (mapM (async tg . worker) workRanges) stopWorker $ \ws -> do
      atomically $ (Just <$> takeTMVar res) `orElse` (Nothing <$ mapM_ waitSTM ws)


text:
void parseOperators(listOfOperators **mList, char *pathToOperators);

#endif //BDC_OPERATORPARSER_H


text:
package me.chanjar.weixin.mp.bean.card.membercard;

import com.google.gson.annotations.SerializedName;
import lombok.Data;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;

import java.io.Serializable;

/**
 * 更新会员卡请求对象.
 *
 * @author yuanqixun
 */
@Data
public class MemberCardUpdateRequest implements Serializable {
  private static final long serialVersionUID = -1025759626161614466L;

  @SerializedName("card_id")
  private String cardId;

  @SerializedName("member_card")
  private MemberCardUpdate memberCardUpdate;

  @Override
  public String toString() {
    return WxMpGsonBuilder.create().toJson(this);
  }
}


text: export * from 'rxjs-compat/operator/publishLast';


text:
#ifndef MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_H
#define MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_H

#include "mitkDiffusionImageSource.h"
#include "mitkDiffusionImage.h"

namespace mitk {
/**
 * @class DiffusionImageToDiffusionImageFilter
 * @brief Base class for all DiffusionImage filters
 *
 * The class inherits the mitk::ImageToImageFilter to gain access to the filtering pipline.
 */
template <typename DiffusionPixelType>
class DiffusionImageToDiffusionImageFilter
    : public DiffusionImageSource< DiffusionPixelType >
{
public:
  /** typedefs for compatibility */
  typedef mitk::DiffusionImage< DiffusionPixelType >     InputImageType;
  typedef typename InputImageType::Pointer               InputImagePointerType;

  mitkClassMacro( DiffusionImageToDiffusionImageFilter,
                  DiffusionImageSource<DiffusionPixelType> )

  itkNewMacro(Self)

  typedef typename Superclass::OutputType                OutputImageType;
  typedef typename OutputImageType::Pointer              OutputImagePointerType;

  using itk::ProcessObject::SetInput;
  virtual void SetInput( const InputImageType* image);
  virtual void SetInput( unsigned int, const InputImageType* image);

  const InputImageType* GetInput(void);
  const InputImageType* GetInput(unsigned int);

protected:
  DiffusionImageToDiffusionImageFilter();
  virtual ~DiffusionImageToDiffusionImageFilter() {}

  virtual void PrintSelf(std::ostream &os, itk::Indent indent) const {}
  virtual void GenerateInputRequestedRegion() {}

private:
  // purposely not implemented
  void operator=(const Self&);
};

} // end namespace mitk

#include "mitkDiffusionImageToDiffusionImageFilter.cpp"

#endif // MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_H


text: In this tutorial, we attempt to beat the returns of the S&P500 Index using leverage and systematic risk management.


text:
package com.github.antag99.retinazer.component;

import com.github.antag99.retinazer.Component;

public class Comp3 implements Component {}


text:
module SettingsEmailsHelper
end


text:
package se.chalmers.dat255.grupp12;

import org.junit.*;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;

/**
 * Date: 2013-10-10
 * Time: 14:13
 */
public class DatabaseTest {

	private Database db;

	@Before
	public void setUp() {
		db = Database.getInstance();
	}

	@Test
	public void testGetInsertUser() throws Exception {
		String userEmail = "johanmail1";
		User johan = db.insertUser(new User("Johan", userEmail));
		User newUser = db.getUser(johan.getId());
		assertEquals("Inserted user is the same as get by id returns", newUser, johan);

		newUser = db.getUser(userEmail);
		assertEquals("Inserted user is the same as get by mail returns", newUser, johan);
	}

	@Test(expected = DataNotFoundException.class)
	public void testDeleteUser() throws Exception {
		User johan = new User("Johan", "johanmail3");
		db.insertUser(johan);
		db.deleteUser(johan.getId());

		// Will throw DataNotFoundException if user doesn't exist
		db.getUser(johan.getId());
	}

	@Test
	public void testUpdateUser() throws Exception {
		User johan = new User("Johan Lindskogen", "johanmail4");
		db.insertUser(johan);
		User newJohan = new User("Johan Hage", "johanmail5");
		db.updateUser(johan, newJohan);
		User u2 = db.getUser(newJohan.getId());
		assertEquals("User from database is same as new user", newJohan, u2);
	}

	@Test
	public void testGetLists() throws Exception {
		User u = db.insertUser(new User("Johan", "johanmail6"));
		TaskList list = new TaskList("List1");
		TaskList list2 = new TaskList("List2");
		TaskList list3 = new TaskList("List3");
		db.insertList(list, u);
		db.insertList(list2, u);
		db.insertList(list3, u);
		List<TaskList> lists = db.getLists(u);
		assertTrue("List1 is in db", lists.contains(list));
		assertTrue("List2 is in db", lists.contains(list2));
		assertTrue("List3 is in db", lists.contains(list3));
	}

	@Test
	public void testGetInsertList() throws Exception {
		User u = db.insertUser(new User("Johan", "johanmail7"));
		TaskList list = new TaskList("List");
		db.insertList(list, u);
		TaskList list2 = db.getList(list.getId());
		assertEquals("List is inserted and got correctly", list, list2);
	}

	@Test
	public void testUpdateList() throws Exception {
		User johan = new User("Johan Lindskogen", "johanmail8");
		db.insertUser(johan);
		TaskList list1 = new TaskList("list1");
		db.insertList(list1, johan);
		TaskList newList = new TaskList("list2");
		db.updateList(list1.getId(), newList);
		TaskList l2 = db.getList(list1.getId());
		assertEquals("User from database is same as new user", newList, l2);
	}

	@Test(expected = DataNotFoundException.class)
	public void testDeleteList() throws Exception {
		User johan = new User("Johan", "johanmail9");
		db.insertUser(johan);
		TaskList list = new TaskList("title");

		db.insertList(list, johan);
		db.deleteList(list.getId());

		// Will throw DataNotFoundException if list doesn't exist
		db.getList(list.getId());
	}

	@Test
	public void testGetInsertTask() throws Exception {
		User u = db.insertUser(new User("Johan", "johanmail10"));
		TaskList list = new TaskList("List");
		list.add(new Task("Tasktitle", 10, "Buy stuff", false));
		db.insertList(list, u);
		TaskList list2 = db.getList(list.getId());
		assertEquals("List is inserted and got correctly", list, list2);
	}

	@Test
	public void testUpdateTask() throws Exception {
		User u = db.insertUser(new User("Johan", "johanmail11"));
		TaskList list = new TaskList("List");
		Task task = new Task("Tasktitle", 10, "Buy stuff", false);
		list.add(task);
		db.insertList(list, u);
		Task newTask = new Task("New tasktitle", 11, "Buy more stuff", true);
		db.updateTask(task.getId(), newTask);
		assertEquals("Task is updated correctly", newTask, db.getTask(newTask.getId()));
	}

	@Test(expected = DataNotFoundException.class)
	public void testDeleteTask() throws Exception {
		User johan = new User("Johan", "johanmail12");
		db.insertUser(johan);
		TaskList list = new TaskList("title");
		Task task = new Task("Task", 10, "Buy stuff", false);
		db.insertList(list, johan);
		db.deleteTask(task.getId());

		// Will throw DataNotFoundException if task doesn't exist
		db.getTask(task.getId());
	}

	@Test
	public void testAssignUserToTask() throws Exception {
		User johan = new User("Johan Lindskogen", "johanmail13");
		db.insertUser(johan);
		TaskList list = new TaskList("title");
		Task task = new Task("Task", 10, "Buy stuff", false);
		list.add(task);
		db.insertList(list, johan);

		db.assignUserToTask(task.getId(), johan);

		List<Task> taskList = db.getUserTasks(johan);
		assertTrue("User was assigned to task", taskList.contains(task));
	}

	@Test
	public void testAssignUserToList() throws Exception {
		User johan = new User("Johan Lindskogen", "johanmail14");
		User johan2 = new User("Johan Hage", "johanmail15");
		db.insertUser(johan);
		db.insertUser(johan2);
		TaskList list = new TaskList("title");
		db.insertList(list, johan);

		db.assignUserToList(johan2, list.getId());

		TaskList dblist = db.getList(list.getId());
		List<TaskList> taskLists = db.getLists(johan2);
		assertTrue("User was assigned to list", taskLists.contains(list) && dblist.getCollaborators().contains(johan2));

		int size = dblist.getCollaborators().size();
		db.assignUserToList(johan2, list.getId());
		dblist = db.getList(list.getId());
		assertTrue("User assign was not duplicated", dblist.getCollaborators().size() == size);

	}

	@Test
	public void testGetUserTasks() throws Exception {
		User johan = new User("Johan Lindskogen", "johanmail16");
		db.insertUser(johan);
		TaskList list = new TaskList("title");

		List<Task> tasks = new ArrayList<Task>();
		tasks.add(new Task("title1"));
		tasks.add(new Task("title2"));
		tasks.add(new Task("title3"));

		for (Task task : tasks) {
			list.add(task);
		}
		db.insertList(list, johan);

		for (Task task : tasks) {
			db.assignUserToTask(task.getId(), johan);
		}

		List<Task> taskList = db.getUserTasks(johan);

		assertTrue("Tasks assigned to User are saved and got correctly", taskList.containsAll(tasks));
	}

	@Test
	public void testGetUsers() throws Exception {
		User johan1 = db.insertUser(new User("Johan", "johansmail17"));
		User johan2 = db.insertUser(new User("Johan", "johansmail18"));
		User johan3 = db.insertUser(new User("Johan", "johansmail19"));
		TaskList list = db.insertList(new TaskList("title"), johan1);
		db.assignUserToList(johan2,list.getId());
		db.assignUserToList(johan3,list.getId());

		List<User> users = db.getUsers(list.getId());

		assertTrue("Users successfully added to the list", users.contains(johan1) &&
				users.contains(johan2) &&  users.contains(johan3));
	}

	@Test
	public void testRemoveUserFromList() throws Exception {
		User johan = new User("Johan", "johanmail20");
		db.insertUser(johan);
		TaskList list = db.insertList(new TaskList("title"),johan);
		User johan2 = new User("Johan2", "johanmail21");
		db.insertUser(johan2);

		db.assignUserToList(johan2, list.getId());
		assertTrue("User successfully added to list", db.getUsers(list.getId()).contains(johan2));

		db.removeUserFromList(johan2.getId(), list.getId());
		assertFalse("User successfully removed from list", db.getUsers(list.getId()).contains(johan2));
	}

	@Test(expected = DataNotFoundException.class)
	public void testRemoveUserAndDeleteList() throws Exception{
		User johan = new User("Johan", "johanmail22");
		User ville = new User("ville", "johanmail23");
		db.insertUser(johan);
		db.insertUser(ville);
		TaskList list = db.insertList(new TaskList("title"), johan);

		db.assignUserToList(ville, list.getId());
		assertTrue("User successfully added to list", db.getUsers(list.getId()).contains(ville));

		db.deleteList(list.getId());
		assertFalse("User successfully removed from list", db.getUsers(list.getId()).contains(ville));

		db.getList(list.getId());
	}
}


text:
![CocoaPods Logo](https://raw.github.com/CocoaPods/shared_resources/master/assets/cocoapods-banner-readme.png)

### CocoaPods: The Cocoa dependency manager

[![Build Status](http://img.shields.io/travis/CocoaPods/CocoaPods/master.svg?style=flat)](https://travis-ci.org/CocoaPods/CocoaPods)
[![Gem Version](http://img.shields.io/gem/v/cocoapods.svg?style=flat)](http://badge.fury.io/rb/cocoapods)
[![Code Climate](http://img.shields.io/codeclimate/github/CocoaPods/CocoaPods.svg?style=flat)](https://codeclimate.com/github/CocoaPods/CocoaPods)

CocoaPods manages dependencies for your Xcode projects.

You specify the dependencies for your project in one easy text file. CocoaPods
resolves dependencies between libraries, fetches source code for the
dependencies, and creates and maintains an Xcode workspace to build your
project.

Installing and updating CocoaPods is very easy. Don't miss the [Installation
guide](http://guides.cocoapods.org/using/getting-started.html#installation) and the
[Getting started guide](https://guides.cocoapods.org/using/getting-started.html).

## Project Goals

Ultimately, the goal of CocoaPods is to improve the engagement in, and
discoverability of, third party open-source libraries. The following list
includes the project goals which have influenced, and continue to
drive the design of CocoaPods.

- Being able to work in the system without creating extra work for
  library authors. Making it possible to maintain a simple transparent
  podspec outside of the library's repository.
- Not imposing any judgement of 'correctness' on how authors decide to
  structure their library.
- CocoaPods should not impose any specific requirements on source-code
  management systems. (Currently supported are git, svn, mercurial, bazaar, and
  various types of archives downloaded over HTTP.)
- Provide the ability to work in a distributed way, but also provide
  features only possible with a centralised solution to foster a community.
- Being able to build tools on top of the system, including those typically
  deployed to other operating systems, such as web-services.
- Providing opinionated and automated integration, but making that completely
  optional. It's perfectly possible to manually integrate the CocoaPods
  Xcode project as you see fit, with or without a workspace.
- Not depending on Apple to fix issues with Xcode or otherwise force
  authors to have to do a lot of Xcode work not related to their
  library's functionality.

## Sponsors

Lovingly sponsored by a collection of companies, see the footer of [CocoaPods.org](https://cocoapods.org) for an up-to-date list.

## Collaborate

All CocoaPods development happens on GitHub. Contributions make for good karma and
we [welcome new](https://blog.cocoapods.org/starting-open-source/) contributors with joy. We take contributors seriously, and thus have a
contributor [code of conduct](CODE_OF_CONDUCT.md).

## Links

| Link | Description |
| :----- | :------ |
[CocoaPods.org](https://cocoapods.org/) | Homepage and search for Pods.
[@CocoaPods](https://twitter.com/CocoaPods) | Follow CocoaPods on Twitter to stay up to date.
[Blog](https://blog.cocoapods.org) | The CocoaPods blog.
[Mailing List](http://groups.google.com/group/cocoapods) | Feel free to ask any kind of question.
[Guides](https://guides.cocoapods.org) | Everything you want to know about CocoaPods.
[Changelog](https://github.com/CocoaPods/CocoaPods/blob/master/CHANGELOG.md) | See the changes introduced in each CocoaPods version.
[New Pods RSS](https://feeds.cocoapods.org/new-pods.rss) | Don't miss any new Pods.
[Code of Conduct](CODE_OF_CONDUCT.md) | Find out the standards we hold ourselves to.

## Projects

CocoaPods is composed of the following projects:

| Status | Project | Description | Info |
| :----- | :------ | :--- | :--- |
| [![Build Status](http://img.shields.io/travis/CocoaPods/CocoaPods/master.svg?style=flat)](http://travis-ci.org/CocoaPods/CocoaPods) | [CocoaPods](https://github.com/CocoaPods/CocoaPods) | The CocoaPods command line tool. | [guides](https://guides.cocoapods.org)
| [![Build Status](http://img.shields.io/travis/CocoaPods/Core/master.svg?style=flat)](http://travis-ci.org/CocoaPods/Core) | [CocoaPods Core](https://github.com/CocoaPods/Core) | Support for working with specifications and podfiles. | [docs](http://docs.cocoapods.org/cocoapods_core)
| [![Build Status](http://img.shields.io/travis/CocoaPods/cocoapods-downloader/master.svg?style=flat)](http://travis-ci.org/CocoaPods/cocoapods-downloader) |[CocoaPods Downloader](https://github.com/CocoaPods/cocoapods-downloader) |  Downloaders for various source types. |  [docs](http://docs.cocoapods.org/cocoapods_downloader/index.html)
| [![Build Status](http://img.shields.io/travis/CocoaPods/Xcodeproj/master.svg?style=flat)](https://travis-ci.org/CocoaPods/Xcodeproj) | [Xcodeproj](https://github.com/CocoaPods/Xcodeproj) | Create and modify Xcode projects from Ruby. |  [docs](http://docs.cocoapods.org/xcodeproj/index.html)
| [![Build Status](http://img.shields.io/travis/CocoaPods/CLAide/master.svg?style=flat)](https://travis-ci.org/CocoaPods/CLAide) | [CLAide](https://github.com/CocoaPods/CLAide) | A small command-line interface framework.  | [docs](http://docs.cocoapods.org/claide/index.html)
| [![Build Status](http://img.shields.io/travis/CocoaPods/Molinillo/master.svg?style=flat)](https://travis-ci.org/CocoaPods/Molinillo) | [Molinillo](https://github.com/CocoaPods/Molinillo) | A powerful generic dependency resolver.  | [docs](http://www.rubydoc.info/gems/molinillo)
|  | [Master Repo ](https://github.com/CocoaPods/Specs) | Master repository of specifications. | [guide](http://docs.cocoapods.org/guides/contributing_to_the_master_repo.html)


text:
// DOM-IGNORE-BEGIN

//DOM-IGNORE-END

#include "system_config.h"
#include <stdint.h>
#include <stdbool.h>

/*****************************************************************/
/*                  Structures and defines                       */
/*****************************************************************/

#ifdef __XC8__
    // Description: This macro is used to initialize a PIC18 SPI module with a 4x prescale divider
    #define   SYNC_MODE_FAST    0x00
    // Description: This macro is used to initialize a PIC18 SPI module with a 16x prescale divider
    #define   SYNC_MODE_MED     0x01
    // Description: This macro is used to initialize a PIC18 SPI module with a 64x prescale divider
    #define   SYNC_MODE_SLOW    0x02
#elif defined __XC32__
    // Description: This macro is used to initialize a PIC32 SPI module
    #define   SYNC_MODE_FAST    0x3E
    // Description: This macro is used to initialize a PIC32 SPI module
    #define   SYNC_MODE_SLOW    0x3C
#else
    // Description: This macro indicates the SPI enable bit for 16-bit PICs
    #ifndef MASTER_ENABLE_ON
        #define  MASTER_ENABLE_ON       0x0020
    #endif

    // Description: This macro is used to initialize a 16-bit PIC SPI module
    #ifndef SYNC_MODE_FAST
        #define   SYNC_MODE_FAST    0x3E
    #endif
    // Description: This macro is used to initialize a 16-bit PIC SPI module
    #ifndef SYNC_MODE_SLOW
        #define   SYNC_MODE_SLOW    0x3C
    #endif

    // Description: This macro is used to initialize a 16-bit PIC SPI module secondary prescaler
    #ifndef SEC_PRESCAL_1_1
        #define  SEC_PRESCAL_1_1        0x001c
    #endif
    // Description: This macro is used to initialize a 16-bit PIC SPI module primary prescaler
    #ifndef PRI_PRESCAL_1_1
        #define  PRI_PRESCAL_1_1        0x0003
    #endif
#endif

// Description: This macro represents an SD card start single data block token (used for single block writes)
#define FILEIO_SD_DATA_START_TOKEN                  0xFE

// Description: This macro represents an SD card start multi-block data token (used for multi-block writes)
#define FILEIO_SD_DATA_START_MULTI_BLOCK_TOKEN      0xFC

// Description: This macro represents an SD card stop transmission token.  This is used when finishing a multi block write sequence.
#define FILEIO_SD_DATA_STOP_TRAN_TOKEN              0xFD

// Description: This macro represents an SD card data accepted token
#define FILEIO_SD_DATA_ACCEPTED                     0x05

// Description: This macro indicates that the SD card expects to transmit or receive more data
#define FILEIO_SD_MORE_DATA_EXPECTED                !0

// Description: This macro indicates that the SD card does not expect to transmit or receive more data
#define FILEIO_SD_NO_DATA_EXPECTED                  0

// Description: This macro represents a floating SPI bus condition
#define FILEIO_SD_FLOATING_BUS_TOKEN                0xFF

// The SDMMC Commands

// Description: This macro defines the command code to reset the SD card
#define     FILEIO_SD_COMMAND_GO_IDLE_STATE                          0
// Description: This macro defines the command code to initialize the SD card
#define     FILEIO_SD_COMMAND_SEND_OP_COND                           1
// Description: This macro defined the command code to check for sector addressing
#define     FILEIO_SD_COMMAND_SEND_IF_COND                           8
// Description: This macro defines the command code to get the Card Specific Data
#define     FILEIO_SD_COMMAND_SEND_CSD                               9
// Description: This macro defines the command code to get the Card Information
#define     FILEIO_SD_COMMAND_SEND_CID                               10
// Description: This macro defines the command code to stop transmission during a multi-block read
#define     FILEIO_SD_COMMAND_STOP_TRANSMISSION                      12
// Description: This macro defines the command code to get the card status information
#define     FILEIO_SD_COMMAND_SEND_STATUS                            13
// Description: This macro defines the command code to set the block length of the card
#define     FILEIO_SD_COMMAND_SET_BLOCK_LENGTH                       16
// Description: This macro defines the command code to read one block from the card
#define     FILEIO_SD_COMMAND_READ_SINGLE_BLOCK                      17
// Description: This macro defines the command code to read multiple blocks from the card
#define     FILEIO_SD_COMMAND_READ_MULTI_BLOCK                       18
// Description: This macro defines the command code to tell the media how many blocks to pre-erase (for faster multi-block writes to follow)
//Note: This is an "application specific" command.  This tells the media how many blocks to pre-erase for the subsequent WRITE_MULTI_BLOCK
#define     FILEIO_SD_COMMAND_SET_WRITE_BLOCK_ERASE_COUNT            23
// Description: This macro defines the command code to write one block to the card
#define     FILEIO_SD_COMMAND_WRITE_SINGLE_BLOCK                     24
// Description: This macro defines the command code to write multiple blocks to the card
#define     FILEIO_SD_COMMAND_WRITE_MULTI_BLOCK                      25
// Description: This macro defines the command code to set the address of the start of an erase operation
#define     FILEIO_SD_COMMAND_TAG_SECTOR_START                       32
// Description: This macro defines the command code to set the address of the end of an erase operation
#define     FILEIO_SD_COMMAND_TAG_SECTOR_END                         33
// Description: This macro defines the command code to erase all previously selected blocks
#define     FILEIO_SD_COMMAND_ERASE                                  38
//Description: This macro defines the command code to intitialize an SD card and provide the CSD register value.
//Note: this is an "application specific" command (specific to SD cards) and must be preceded by cmdAPP_CMD.
#define     FILEIO_SD_COMMAND_SD_SEND_OP_COND                        41
// Description: This macro defines the command code to begin application specific command inputs
#define     FILEIO_SD_COMMAND_APP_CMD                                55
// Description: This macro defines the command code to get the OCR register information from the card
#define     FILEIO_SD_COMMAND_READ_OCR                               58
// Description: This macro defines the command code to disable CRC checking
#define     FILEIO_SD_COMMAND_CRC_ON_OFF                             59

// Description: Enumeration of different SD response types
typedef enum
{
    FILEIO_SD_RESPONSE_R1,     // R1 type response
    FILEIO_SD_RESPONSE_R1b,    // R1b type response
    FILEIO_SD_RESPONSE_R2,     // R2 type response
    FILEIO_SD_RESPONSE_R3,     // R3 type response
    FILEIO_SD_RESPONSE_R7      // R7 type response
}RESP;

// Summary: SD card command data structure
// Description: The FILEIO_SD_COMMAND structure is used to create a command table of information needed for each relevant SD command
typedef struct
{
    uint8_t      CmdCode;          // The command code
    uint8_t      CRC;              // The CRC value for that command
    RESP    responsetype;       // The response type
    uint8_t    moredataexpected;   // Set to MOREDATA or NODATA, depending on whether more data is expected or not
} FILEIO_SD_COMMAND;

// Summary: An SD command packet
// Description: This union represents different ways to access an SD card command packet
typedef union
{
    // This structure allows array-style access of command uint8_ts
    struct
    {
        #ifdef __XC8__
            uint8_t field[6];      // uint8_t array
        #else
            uint8_t field[7];
        #endif
    };
    // This structure allows uint8_t-wise access of packet command uint8_ts
    struct
    {
        uint8_t crc;               // The CRC uint8_t
        #if defined __XC16__
            uint8_t c30filler;     // Filler space (since bitwise declarations can't cross a uint16_t boundary)
        #elif defined __XC32__
            uint8_t c32filler[3];  // Filler space (since bitwise declarations can't cross a uint32_t boundary)
        #endif

        uint8_t addr0;             // Address uint8_t 0
        uint8_t addr1;             // Address uint8_t 1
        uint8_t addr2;             // Address uint8_t 2
        uint8_t addr3;             // Address uint8_t 3
        uint8_t cmd;               // Command code uint8_t
    };
    // This structure allows bitwise access to elements of the command uint8_ts
    struct
    {
        uint8_t  END_BIT:1;        // Packet end bit
        uint8_t  CRC7:7;           // CRC value
        uint32_t     address;      // Address
        uint8_t  CMD_INDEX:6;      // Command code
        uint8_t  TRANSMIT_BIT:1;   // Transmit bit
        uint8_t  START_BIT:1;      // Packet start bit
    };
} FILEIO_SD_CMD_PACKET;

// Summary: The format of an R1 type response
// Description: This union represents different ways to access an SD card R1 type response packet.
typedef union
{
    uint8_t _byte;                         // uint8_t-wise access
    // This structure allows bitwise access of the response
    struct
    {
        unsigned IN_IDLE_STATE:1;       // Card is in idle state
        unsigned ERASE_RESET:1;         // Erase reset flag
        unsigned ILLEGAL_CMD:1;         // Illegal command flag
        unsigned CRC_ERR:1;             // CRC error flag
        unsigned ERASE_SEQ_ERR:1;       // Erase sequence error flag
        unsigned ADDRESS_ERR:1;         // Address error flag
        unsigned PARAM_ERR:1;           // Parameter flag
        unsigned B7:1;                  // Unused bit 7
    };
} FILEIO_SD_RESPONSE_1;

// Summary: The format of an R2 type response
// Description: This union represents different ways to access an SD card R2 type response packet
typedef union
{
    uint16_t _uint16_t;
    struct
    {
        uint8_t      _byte0;
        uint8_t      _byte1;
    };
    struct
    {
        unsigned IN_IDLE_STATE:1;
        unsigned ERASE_RESET:1;
        unsigned ILLEGAL_CMD:1;
        unsigned CRC_ERR:1;
        unsigned ERASE_SEQ_ERR:1;
        unsigned ADDRESS_ERR:1;
        unsigned PARAM_ERR:1;
        unsigned B7:1;
        unsigned CARD_IS_LOCKED:1;
        unsigned WP_ERASE_SKIP_LK_FAIL:1;
        unsigned ERROR:1;
        unsigned CC_ERROR:1;
        unsigned CARD_ECC_FAIL:1;
        unsigned WP_VIOLATION:1;
        unsigned ERASE_PARAM:1;
        unsigned OUTRANGE_CSD_OVERWRITE:1;
    };
} FILEIO_SD_RESPONSE_2;

// Summary: The format of an R7 or R3 type response
// Description: This union represents different ways to access an SD card R7 type response packet.
typedef union
{
    struct
    {
        uint8_t _byte;                         // byte-wise access
        union
        {
            //Note: The SD card argument response field is 32-bit, big endian format.
            //However, the C compiler stores 32-bit values in little endian in RAM.
            //When writing to the _returnVal/argument bytes, make sure to byte
            //swap the order from which it arrived over the SPI from the SD card.
            uint32_t _returnVal;
            struct
            {
                uint8_t _byte0;
                uint8_t _byte1;
                uint8_t _byte2;
                uint8_t _byte3;
            };
        }argument;
    } bytewise;
    // This structure allows bitwise access of the response
    struct
    {
        struct
        {
            unsigned IN_IDLE_STATE:1;       // Card is in idle state
            unsigned ERASE_RESET:1;         // Erase reset flag
            unsigned ILLEGAL_CMD:1;         // Illegal command flag
            unsigned CRC_ERR:1;             // CRC error flag
            unsigned ERASE_SEQ_ERR:1;       // Erase sequence error flag
            unsigned ADDRESS_ERR:1;         // Address error flag
            unsigned PARAM_ERR:1;           // Parameter flag
            unsigned B7:1;                  // Unused bit 7
        }bits;
        uint32_t _returnVal;
    } bitwise;
} FILEIO_SD_RESPONSE_7;

// Summary: A union of responses from an SD card
// Description: The FILEIO_SD_RESPONSE union represents any of the possible responses that an SD card can return after
//              being issued a command.
typedef union
{
    FILEIO_SD_RESPONSE_1  r1;
    FILEIO_SD_RESPONSE_2  r2;
    FILEIO_SD_RESPONSE_7  r7;
}FILEIO_SD_RESPONSE;

// Description: A delay prescaler
#define FILEIO_SD_DELAY_PRESCALER       (uint8_t)8

// Description: An approximation of the number of cycles per delay loop of overhead
#define FILEIO_SD_DELAY_OVERHEAD        (uint8_t)5

// Description: An approximate calculation of how many times to loop to delay 1 ms in the Delayms function
#define FILEIO_SD_MILLISECOND_DELAY     (uint16_t)((SYS_CLK_FrequencyInstructionGet()/FILEIO_SD_DELAY_PRESCALER/(uint16_t)1000) - FILEIO_SD_DELAY_OVERHEAD)

// Description: Media Response Delay Timeout Values
#define FILEIO_SD_NCR_TIMEOUT     (uint16_t)20          //uint8_t times before command response is expected (must be at least 8)
#define FILEIO_SD_NAC_TIMEOUT     (uint32_t)0x40000     //SPI uint8_t times we should wait when performing read operations (should be at least 100ms for SD cards)
#define FILEIO_SD_WRITE_TIMEOUT   (uint32_t)0xA0000     //SPI uint8_t times to wait before timing out when the media is performing a write operation (should be at least 250ms for SD cards).

// Summary: An enumeration of SD commands
// Description: This enumeration corresponds to the position of each command in the sdmmc_cmdtable array
//              These macros indicate to the FILEIO_SD_SendCmd function which element of the sdmmc_cmdtable array
//              to retrieve command code information from.
typedef enum
{
    FILEIO_SD_GO_IDLE_STATE,
    FILEIO_SD_SEND_OP_COND,
    FILEIO_SD_SEND_IF_COND,
    FILEIO_SD_SEND_CSD,
    FILEIO_SD_SEND_CID,
    FILEIO_SD_STOP_TRANSMISSION,
    FILEIO_SD_SEND_STATUS,
    FILEIO_SD_SET_BLOCK_LENGTH,
    FILEIO_SD_READ_SINGLE_BLOCK,
    FILEIO_SD_READ_MULTI_BLOCK,
    FILEIO_SD_WRITE_SINGLE_BLOCK,
    FILEIO_SD_WRITE_MULTI_BLOCK,
    FILEIO_SD_TAG_SECTOR_START,
    FILEIO_SD_TAG_SECTOR_END,
    FILEIO_SD_ERASE,
    FILEIO_SD_APP_CMD,
    FILEIO_SD_READ_OCR,
    FILEIO_SD_CRC_ON_OFF,
    FILEIO_SD_SD_SEND_OP_COND,
    FILEIO_SD_SET_WRITE_BLOCK_ERASE_COUNT
} FILEIO_SD_COMMAND_INDEX;

#define FILEIO_SD_MODE_NORMAL  0
#define FILEIO_SD_MODE_HC      1

//Constants
#define FILEIO_SD_MEDIA_BLOCK_SIZE            512u  //Should always be 512 for v1 and v2 devices.
#define FILEIO_SD_WRITE_RESPONSE_TOKEN_MASK   0x1F  //Bit mask to AND with the write token response uint8_t from the media, to clear the don't care bits.

/***************************************************************************/
/*                               Macros                                    */
/***************************************************************************/

// Description: A macro to send clock cycles to dummy-write the CRC
#define FILEIO_SD_CRCSend(i)              DRV_SPI_Put(i,0xFF);DRV_SPI_Put(i,0xFF);

// Description: A macro to send 8 clock cycles for SD timing requirements
#define FILEIO_SD_Send8ClockCycles(i)       DRV_SPI_Put(i,0xFF);

/*****************************************************************************/
/*                            Private Prototypes                             */
/*****************************************************************************/


text:
using Android.App;
using Android.OS;
using Android.Widget;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI.Controls;
using System;

namespace ArcGISRuntime.Samples.ServiceFeatureTableManualCache
{
    [Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Service feature table (manual cache)",
        category: "Data",
        description: "Display a feature layer from a service using the **manual cache** feature request mode.",
        instructions: "Run the sample and pan and zoom around the map. Observe the features loaded from the table.",
        tags: new[] { "cache", "feature request mode", "performance" })]
    public class ServiceFeatureTableManualCache : Activity
    {
        // Hold a reference to the map view
        private MapView _myMapView;

        private ServiceFeatureTable _incidentsFeatureTable;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            Title = "Feature service table (manual cache)";

            // Create the UI, setup the control references and execute initialization
            CreateLayout();
            Initialize();
        }

        private void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(BasemapStyle.ArcGISTopographic);

            // Create and set initial map location
            MapPoint initialLocation = new MapPoint(
                -13630484, 4545415, SpatialReferences.WebMercator);
            myMap.InitialViewpoint = new Viewpoint(initialLocation, 500000);

            // Create uri to the used feature service
            Uri serviceUri = new Uri(
               "https://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0");

            // Create feature table for the incident feature service
            _incidentsFeatureTable = new ServiceFeatureTable(serviceUri)
            {

                // Define the request mode
                FeatureRequestMode = FeatureRequestMode.ManualCache
            };

            // When feature table is loaded, populate data
            _incidentsFeatureTable.LoadStatusChanged += OnLoadedPopulateData;

            // Create FeatureLayer that uses the created table
            FeatureLayer incidentsFeatureLayer = new FeatureLayer(_incidentsFeatureTable);

            // Add created layer to the map
            myMap.OperationalLayers.Add(incidentsFeatureLayer);

            // Assign the map to the MapView
            _myMapView.Map = myMap;
        }

        private async void OnLoadedPopulateData(object sender, Esri.ArcGISRuntime.LoadStatusEventArgs e)
        {
            // If layer isn't loaded, do nothing
            if (e.Status != Esri.ArcGISRuntime.LoadStatus.Loaded)
                return;

            // Create new query object that contains parameters to query specific request types
            QueryParameters queryParameters = new QueryParameters()
            {
                WhereClause = "req_Type = 'Tree Maintenance or Damage'"
            };

            // Create list of the fields that are returned from the service
            string[] outputFields = { "*" };

            try
            {
                // Populate feature table with the data based on query
                await _incidentsFeatureTable.PopulateFromServiceAsync(queryParameters, true, outputFields);
            }
            catch (Exception ex)
            {
                new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show();
            }
        }

        private void CreateLayout()
        {
            // Create a new vertical layout for the app
            LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical };

            // Add the map view to the layout
            _myMapView = new MapView(this);
            layout.AddView(_myMapView);

            // Show the layout in the app
            SetContentView(layout);
        }
    }
}


text:
layout: default
---
Version 3.4
===========

- [What's New in 3.4](release-notes-new-features34.html)
- [Known Issues in 3.4](release-notes-known-issues34.html)
- [Incompatible changes in 3.4](release-notes-upgrading-changes34.html)


text:
<?xml version="1.0" encoding="UTF-8"?>
<module codename="org.netbeans.modules.spellchecker.dictionary_en">
    <module_version install_time="1370462928971" last="true" origin="installer" specification_version="1.13.1">
        <file crc="3063149510" name="config/Modules/org-netbeans-modules-spellchecker-dictionary_en.xml"/>
        <file crc="1095946908" name="modules/dict/dictionary_en.description"/>
        <file crc="1395082238" name="modules/dict/dictionary_en_GB.description"/>
        <file crc="1095946908" name="modules/dict/dictionary_en_US.description"/>
        <file crc="1358256909" name="modules/dict/ispell-enwl-3.1.20.zip"/>
        <file crc="2367010539" name="modules/locale/org-netbeans-modules-spellchecker-dictionary_en_ja.jar"/>
        <file crc="2286077998" name="modules/locale/org-netbeans-modules-spellchecker-dictionary_en_pt_BR.jar"/>
        <file crc="1640939906" name="modules/locale/org-netbeans-modules-spellchecker-dictionary_en_ru.jar"/>
        <file crc="1779026131" name="modules/locale/org-netbeans-modules-spellchecker-dictionary_en_zh_CN.jar"/>
        <file crc="3383801068" name="modules/org-netbeans-modules-spellchecker-dictionary_en.jar"/>
    </module_version>
</module>


text:
using Adam.Web.Extensions.UI.Controls;
using Adam.Web.UI.Controls;

namespace CbxSw.UserFullName.ControlBuilder
{
	/// <summary>
	/// This <see cref="FieldControlBuilder"/> allows users to search on the field <see cref="UserFullNameFieldName"/>.
	/// </summary>
	public class CustomUserListFieldControlBuilder : ExtendedUserListFieldControlBuilder
	{
		public const string UserFullNameFieldName = "UserFullName";

		protected override ListEditorBase CreateListEditor(FieldControlBuildInfo buildInfo)
		{
			var editor = (SearchListEditor)base.CreateListEditor(buildInfo);
			editor.SearchTemplate = $"fieldname({UserFullNameFieldName})=? or name=?";
			return editor;
		}
	}
}


text:
import {Component, OnInit} from '@angular/core';
import {JobTemplate} from "../shared/job-template";
import {JobTemplateService} from "../shared/job-template.service";

@Component({
  selector: 'template-list',
  templateUrl: './template-list.component.html',
})

export class TemplateListComponent implements OnInit {
  jobTemplates: JobTemplate[];
  error: Error;

  constructor(private jobTemplateService: JobTemplateService) { }

  ngOnInit(): void {
    this.getJobTemplates();
  }

  getJobTemplates(): void {
    this.jobTemplateService.getJobTemplates().then(jobTemplates => {
      this.jobTemplates = jobTemplates
    });
  }

  onRunFailed(error: Error):void {
      this.error = error;
  }
}


text:
import hazelcast
import threading

client = hazelcast.HazelcastClient()

queue = client.get_queue("queue")

def produce():
    for i in range(100):
        queue.offer("value-" + str(i))

def consume():
    consumed_count = 0
    while consumed_count < 100:
        head = queue.take().result()
        print("Consuming {}".format(head))
        consumed_count += 1

producer_thread = threading.Thread(target=produce)
consumer_thread = threading.Thread(target=consume)

producer_thread.start()
consumer_thread.start()

producer_thread.join()
consumer_thread.join()

client.shutdown()


text:
using System;

namespace Celsiusfahrenheit
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Console.Write ("Celsius: ");
            string line = Console.ReadLine ();
            float value = 0;
            try {
                value = float.Parse(line);
            } catch (Exception ex) {
                Console.WriteLine ("Invalid input value.");
                Environment.Exit (1);
            }
            Console.WriteLine ((value * 1.8 + 32).ToString());
        }
    }
}


text:
package au.gov.ga.geodesy.domain.model;

import java.time.Instant;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Version;

@Entity
@Table(name = "SITE")
@Inheritance(strategy = InheritanceType.JOINED)
abstract public class Site {

    @Version
    private Integer version;

    /**
     * RDBMS surrogate key
     */
    @Id
    @Column(name = "ID")
    @GeneratedValue(generator = "surrogateKeyGenerator")
    @SequenceGenerator(name = "surrogateKeyGenerator", sequenceName = "seq_surrogate_keys")
    protected Integer id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "DESCRIPTION")
    private String description;

    @Column(name = "DATE_INSTALLED")
    private Instant dateInstalled;

    public Integer getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Instant getDateInstalled() {
        return dateInstalled;
    }

    public void setDateInstalled(Instant dateInstalled) {
        this.dateInstalled = dateInstalled;
    }
}


text:
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColor.h"
#include "include/core/SkImage.h"
#include "include/core/SkM44.h"
#include "include/core/SkMatrix.h"
#include "include/core/SkSurface.h"
#include "include/effects/SkGradientShader.h"
#include "tools/timer/TimeUtils.h"

// Adapted from https://codepen.io/adamdupuis/pen/qLYzqB
class CrBug224618GM : public skiagm::GM {
public:
    CrBug224618GM() : fTime(0.f) {}

protected:
    SkString onShortName() override {
        return SkString("crbug_224618");
    }

    SkISize onISize() override {
        return SkISize::Make(kMaxVW, kMaxVW);
    }

    // This animates the FOV in viewer, to ensure the panorama covering rects are stable across
    // a variety of perspective matrices
    bool onAnimate(double nanos) override {
        fTime = TimeUtils::Scaled(1e-9f * nanos, 0.5f);
        return true;
    }

    void onOnceBeforeDraw() override {
        static const SkColor kColors[2] = {SK_ColorTRANSPARENT, SkColorSetARGB(128, 255, 255, 255)};
        sk_sp<SkShader> gradient = SkGradientShader::MakeRadial(
                {200.f, 200.f}, 25.f, kColors, nullptr, 2, SkTileMode::kMirror,
                SkGradientShader::kInterpolateColorsInPremul_Flag, nullptr);

        sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(400, 400);

        SkPaint bgPaint;
        bgPaint.setShader(gradient);
        surface->getCanvas()->drawPaint(bgPaint);

        fCubeImage = surface->makeImageSnapshot();
    }

    void onDraw(SkCanvas* canvas) override {
        SkScalar viewportWidth = SkScalarMod(fTime, 10.f) / 10.f * (kMaxVW - kMinVW) + kMinVW;
        SkScalar radius = viewportWidth / 2.f; // round?
        // See https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/perspective
        SkM44 proj{1.f, 0.f, 0.f, 0.f,
                   0.f, 1.f, 0.f, 0.f,
                   0.f, 0.f, 1.f, 0.f,
                   0.f, 0.f, -1.f / radius, 1.f};
        SkM44 zoom             = SkM44::Translate(0.f, 0.f, radius);
        SkM44 postZoom         = SkM44::Translate(0.f, 0.f, -radius - 1.f);
        SkM44 rotateHorizontal = SkM44::Rotate({0, 1, 0}, 2.356194490192345f);

        // w in degrees will need to be converted to radians
        SkV4 axisAngles[6] = {
            {0.f, 1.f, 0.f, -90.f}, // rotateY(-90deg)
            {1.f, 0.f, 0.f, 0.f},   // <none>
            {0.f, 1.f, 0.f, 90.f},  // rotateY(90deg)
            {0.f, 1.f, 0.f, 180.f}, // rotateY(180deg)
            {1.f, 0.f, 0.f, -90.f}, // rotateX(-90deg)
            {1.f, 0.f, 0.f, 90.f},  // rotateX(90deg)
        };
        SkColor faceColors[6] = {
            SK_ColorRED,
            SK_ColorGREEN,
            SK_ColorBLUE,
            SK_ColorYELLOW,
            SkColorSetARGB(0xFF, 0xFF, 0xA5, 0x00), // orange css
            SkColorSetARGB(0xFF, 0x80, 0x00, 0x80)  // purple css
        };

        for (int i = 0; i < 6; ++i) {
            SkM44 model = SkM44::Rotate({axisAngles[i].x, axisAngles[i].y, axisAngles[i].z},
                                            SkDegreesToRadians(axisAngles[i].w));
            model = SkM44::Translate(radius, radius) * proj *    // project and place content
                    zoom * rotateHorizontal * model * postZoom * // main model matrix
                    SkM44::Translate(-radius, -radius);          // center content

            canvas->save();
            canvas->concat(model);

            SkPaint fillPaint;
            fillPaint.setAntiAlias(true);
            fillPaint.setColor(faceColors[i]);

            // Leverages FillRectOp on GPU backend
            canvas->drawRect(SkRect::MakeWH(viewportWidth, viewportWidth), fillPaint);

            // Leverages TextureOp on GPU backend, to ensure sure both quad paths handle clipping
            canvas->drawImageRect(fCubeImage.get(),
                                  SkRect::MakeWH(fCubeImage->width(), fCubeImage->height()),
                                  SkRect::MakeWH(viewportWidth, viewportWidth),
                                  SkSamplingOptions(SkFilterMode::kLinear), &fillPaint,
                                  SkCanvas::kFast_SrcRectConstraint);

            canvas->restore();
        }
    }
private:
    static const int kMaxVW = 800;
    static const int kMinVW = 300;

    SkScalar fTime;
    sk_sp<SkImage> fCubeImage;
};

DEF_GM(return new CrBug224618GM();)


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

  angular
    .module('mnSettings', [
      'mnSettingsNotifications',
      'mnLdap',
      'mnSettingsSampleBuckets',
      'mnSettingsCluster',
      'mnSettingsAutoFailover',
      'mnSettingsAutoCompaction',
      'mnAudit',
      'mnSettingsCluster',
      'mnSettingsAlerts',
      'mnSettingsNotificationsService',
      'mnInternalRoles',
      'ui.router',
      'mnPluggableUiRegistry',
      'mnElementCrane',
      'mnSession'
    ])
    .config(mnSettingsConfig);

  function mnSettingsConfig($stateProvider) {

    $stateProvider
      .state('app.admin.settings', {
        url: '/settings',
        abstract: true,
        views: {
          "main@app.admin": {
            templateUrl: 'app/mn_admin/mn_settings/mn_settings.html',
            controller: 'mnSettingsController as settingsCtl'
          }
        },
        data: {
          title: "Settings"
        }
      })
      .state('app.admin.settings.cluster', {
        url: '/cluster',
        controller: 'mnSettingsClusterController as settingsClusterCtl',
        templateUrl: 'app/mn_admin/mn_settings/cluster/mn_settings_cluster.html'
      })
      .state('app.admin.settings.notifications', {
        url: '/notifications',
        controller: 'mnSettingsNotificationsController as settingsNotificationsCtl',
        templateUrl: 'app/mn_admin/mn_settings/notifications/mn_settings_notifications.html',
        data: {
          permissions: 'cluster.settings.read'
        }
      })
      .state('app.admin.settings.autoFailover', {
        url: '/autoFailover',
        controller: 'mnSettingsAutoFailoverController as settingsAutoFailoverCtl',
        templateUrl: 'app/mn_admin/mn_settings/auto_failover/mn_settings_auto_failover.html',
        data: {
          permissions: 'cluster.settings.read'
        }
      })
      .state('app.admin.settings.alerts', {
        url: '/alerts',
        controller: 'mnSettingsAlertsController as settingsAlertsCtl',
        templateUrl: 'app/mn_admin/mn_settings/alerts/mn_settings_alerts.html',
        data: {
          permissions: 'cluster.settings.read'
        }
      })
      .state('app.admin.settings.autoCompaction', {
        url: '/autoCompaction',
        controller: 'mnSettingsAutoCompactionController as settingsAutoCompactionCtl',
        templateUrl: 'app/mn_admin/mn_settings/auto_compaction/mn_settings_auto_compaction.html',
        data: {
          permissions: 'cluster.settings.read'
        }
      })
      .state('app.admin.settings.sampleBuckets', {
        url: '/sampleBuckets',
        controller: 'mnSettingsSampleBucketsController as settingsSampleBucketsCtl',
        templateUrl: 'app/mn_admin/mn_settings/sample_buckets/mn_settings_sample_buckets.html',
        data: {
          permissions: 'cluster.samples.read'
        }
      });
  }
})();


text:
package com.wmba.collections;

import android.os.Parcel;
import android.os.Parcelable;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * Represents an immutable parcelable map.
 * This is basically a decorator around Hashmap.
 *
 * @param <K> a type of keys.
 * @param <V> a type of values.
 */
public class ImmutableMap<K, V> implements Map<K, V>, Parcelable {
  private static final ImmutableMap<Object, Object> EMPTY = new ImmutableMap<>(new LinkedHashMap<>());
  private static final ClassLoader CLASS_LOADER = ImmutableMap.class.getClassLoader();

  private final Map<K, V> map;

  /**
   * Constructs a SolidMap from a given map.
   *
   * @param map a source map.
   */
  public ImmutableMap(Map<K, V> map) {
    this.map = Collections.unmodifiableMap(new LinkedHashMap<>(map));
  }

  /**
   * Constructs a SolidMap from a given iterable stream of entries.
   *
   * @param iterable a source iterable.
   */
  public ImmutableMap(Iterable<? extends Entry<K, V>> iterable) {
    LinkedHashMap<K, V> m = new LinkedHashMap<>();
    for (Entry<K, V> entry : iterable)
      m.put(entry.getKey(), entry.getValue());
    this.map = Collections.unmodifiableMap(m);
  }

  /**
   * Returns an empty {@link ImmutableMap}.
   *
   * @param <K> a type of keys.
   * @param <V> a type of values.
   * @return an empty {@link ImmutableMap}.
   */
  public static <K, V> ImmutableMap<K, V> empty() {
    //noinspection unchecked
    return (ImmutableMap<K, V>)EMPTY;
  }

  @Deprecated
  @Override public void clear() {
    throw new UnsupportedOperationException();
  }

  @Override public boolean containsKey(Object key) {
    return map.containsKey(key);
  }

  @Override public boolean containsValue(Object value) {
    return map.containsKey(value);
  }

  @Override public Set<Entry<K, V>> entrySet() {
    return map.entrySet();
  }

  @Override public V get(Object key) {
    return map.get(key);
  }

  @Override public boolean isEmpty() {
    return map.isEmpty();
  }

  @Override public Set<K> keySet() {
    return map.keySet();
  }

  @Deprecated
  @Override public V put(K key, V value) {
    throw new UnsupportedOperationException();
  }

  @Deprecated
  @Override public void putAll(Map<? extends K, ? extends V> map) {
    throw new UnsupportedOperationException();
  }

  @Deprecated
  @Override public V remove(Object key) {
    throw new UnsupportedOperationException();
  }

  @Override public int size() {
    return map.size();
  }

  @Override public Collection<V> values() {
    return map.values();
  }

  @Override public int describeContents() {
    return 0;
  }

  public ImmutableMap(Parcel in) {
    LinkedHashMap<K, V> temp = new LinkedHashMap<>();
    in.readMap(temp, CLASS_LOADER);
    //noinspection unchecked
    map = Collections.unmodifiableMap(temp);
  }

  @Override public void writeToParcel(Parcel dest, int flags) {
    dest.writeMap(map);
  }

  public static final Creator<ImmutableMap> CREATOR = new Creator<ImmutableMap>() {
    @Override public ImmutableMap createFromParcel(Parcel in) {
      return new ImmutableMap(in);
    }

    @Override public ImmutableMap[] newArray(int size) {
      return new ImmutableMap[size];
    }
  };

  @Override public boolean equals(Object object) {
    if (this == object)
      return true;

    if (object instanceof Map) {
      Map<?, ?> other = (Map<?, ?>)object;
      if (size() != other.size())
        return false;

      for (Entry<K, V> entry : entrySet()) {
        K key = entry.getKey();
        V value = entry.getValue();
        Object value2 = other.get(key);
        if (value == null) {
          if (value2 != null || !other.containsKey(key))
            return false;
        }
        else if (!value.equals(value2))
          return false;
      }
      return true;
    }
    return false;
  }

  @Override public int hashCode() {
    return map.hashCode();
  }

  @Override public String toString() {
    return "ImmutableMap{" +
        "map=" + map +
        '}';
  }
}


text:
import trigger as tgr
import yaml
import os
import time

def execute_trigger():

    with open('triggers/triggers.yml', 'r') as trigger_yml:
	    trigger_cfg = yaml.load(trigger_yml)

    triggers = trigger_cfg['triggers']

    for trigger in triggers:
        trigger_id = trigger.keys()[0]
    	trigger_params = trigger.values()[0]
    	object_type = trigger_params['object_type']
    	event_type = trigger_params['event_type']
    	params = trigger_params['params']

        pre_trigger_verify_traffic(trigger_id)

        tgr.trigger(object_type, event_type, params)

        post_trigger_verify_traffic(trigger_id)

def pre_trigger_verify_traffic(trigger_id):
    os.system("python traffic_tester.py -f conf/config.ini -a start -t %s" %(trigger_id))
    time.sleep(30)
    os.system("python traffic_tester.py -f conf/config.ini -a stop -t %s" %(trigger_id))

def post_trigger_verify_traffic(trigger_id):
    os.system("python traffic_tester.py -f conf/config.ini -a start -t %s" %(trigger_id))
    time.sleep(30)
    os.system("python traffic_tester.py -f conf/config.ini -a stop -t %s" %(trigger_id))

def main():
	execute_trigger()

if __name__ == '__main__':
	main()


text:
pub use kinds::{Copy, Send, Sized, Share};
pub use ops::{Add, Sub, Mul, Div, Rem, Neg, Not};
pub use ops::{BitAnd, BitOr, BitXor};
pub use ops::{Drop, Deref, DerefMut};
pub use ops::{Shl, Shr, Index};
pub use option::{Option, Some, None};
pub use result::{Result, Ok, Err};

// Reexported functions
pub use iter::range;
pub use mem::drop;

// Reexported types and traits

pub use char::Char;
pub use clone::Clone;
pub use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Less, Equal, Greater, Equiv};
pub use container::{Container, Mutable, Map, MutableMap, Set, MutableSet};
pub use iter::{FromIterator, Extendable};
pub use iter::{Iterator, DoubleEndedIterator, RandomAccessIterator, CloneableIterator};
pub use iter::{OrdIterator, MutableDoubleEndedIterator, ExactSize};
pub use num::{Num, NumCast, CheckedAdd, CheckedSub, CheckedMul};
pub use num::{Signed, Unsigned};
pub use num::{Primitive, Int, ToPrimitive, FromPrimitive};
pub use ptr::RawPtr;
pub use str::{Str, StrSlice};
pub use tuple::{Tuple1, Tuple2, Tuple3, Tuple4};
pub use tuple::{Tuple5, Tuple6, Tuple7, Tuple8};
pub use tuple::{Tuple9, Tuple10, Tuple11, Tuple12};
pub use slice::{ImmutableEqVector, ImmutableTotalOrdVector};
pub use slice::{MutableVector};
pub use slice::{Vector, ImmutableVector};


text:
package com.azure.cosmos.implementation.encryption;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

public class ShanonEntropyGauge {
    private final Map<BigInteger, Integer> freq;
    private int cnt = 0;

    public ShanonEntropyGauge() {
        this.freq = new HashMap<>();
    }

    public void add(byte[] input) {
        BigInteger number = new BigInteger(1, input);
        freq.compute(number, (bigInteger, cnt) -> {
            if (cnt == null) {
                return 1;
            } else {
                return cnt + 1;
            }
        });
        cnt++;
    }

    public double calculate() {
        // compute Shannon entropy
        double entropy = 0.0;
        for (Map.Entry<BigInteger, Integer> entry: freq.entrySet()) {
            double p = 1.0 * entry.getValue() / cnt;
            entropy -= p * Math.log(p) / Math.log(2);
        }

        return entropy;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" android:drawable="@drawable/add_selected"></item>
    <item android:drawable="@drawable/add_noraml"></item>

</selector>