text:
package de.elomagic.mag.google;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.drive.Drive;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 *
 * @author Carsten Rambow
 */
public final class DriveService {

    private static final Logger LOGGER = LogManager.getLogger(DriveService.class);

    private DriveService() {
    }

    /**
     * Build and return an authorized Drive client service.
     *
     * @param credential
     * @return Returns an authorized Drive client service or null when something went wrong
     */
    public static Drive getDriveService(final Credential credential) {

        Drive result = null;

        try {
            HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();//new NetHttpTransport();
            result = new Drive.Builder(httpTransport, JacksonFactory.getDefaultInstance(), credential)
                    .setApplicationName("MailAttachmentGateway")
                    .build();
        } catch(Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }

        return result;

    }
}


text:
var express = require('express');
var router = express.Router();
var auth = require('../config/auth');
var marked = require('marked');
var parseLabels = require('../utils/parseLabels.js');
var linkMoves = require('../utils/linkMoves.js');
var linkUsers = require('../utils/linkUsers.js');

marked.setOptions({
	smartypants: true
});

router.post('/', auth.ensureAuthenticated, function (req, res) {
	var text = req.body.markdown;
	text = parseLabels(text);
	text = linkMoves(text);
	linkUsers(text, function (text) {
		var html = marked(text) || '';
		res.json({
			markup: html
		});
	});
});

module.exports = router;

redpajama_set_name: RedPajamaGithub


text:
#include "outputwriter.h"
#include "utils.h"

#include <iostream>
#include <iomanip>
#include <stdexcept>
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstdio>

/*
 * OutputWriter members
 */

void OutputWriter::write(const char *data,std::size_t n) {
	writeData(data,n);
	_size+=n;
}

void OutputWriter::pad(std::size_t size) {
	static char zeros[256]; // static objects are zero-initialized
	while(size>0) {
		auto n=std::min<std::size_t>(size,256);
		write(zeros,n);
		size-=n;
	}
}

std::size_t OutputWriter::size() const {
	return _size;
}

/*
 * BinaryOutputWriter members
 */

BinaryOutputWriter::BinaryOutputWriter(const std::string &filename):
	_filename(filename),
	_os(filename,std::ios_base::out|std::ios_base::binary)
{
	if(!_os) throw std::runtime_error("Cannot open \""+filename+"\" for writing");
}

void BinaryOutputWriter::writeData(const char *data,std::size_t n) {
	_os.write(data,n);
}

void BinaryOutputWriter::abort() {
	_os.close();
	std::remove(_filename.c_str());
}

/*
 * TextOutputWriter members
 */

TextOutputWriter::TextOutputWriter(const std::string &filename,Format f):
	_filename(filename),
	_os(filename,std::ios_base::out),
	_fmt(f)
{
	if(!_os) throw std::runtime_error("Cannot open \""+filename+"\" for writing");
}

TextOutputWriter::~TextOutputWriter() {
	if(!_buf.empty()) {
		assert(_buf.size()<4);
		pad(4-_buf.size());
	}
}

void TextOutputWriter::writeData(const char *data,std::size_t n) {
	while(n>0) {
		assert(_buf.size()<4);
		auto count=std::min(4-_buf.size(),n);
		_buf.append(data,count);
		data+=count;
		n-=count;

		if(_buf.size()<4) continue;

		assert(_buf.size()==4);

		std::uint32_t word=(static_cast<unsigned char>(_buf[3])<<24)|
			(static_cast<unsigned char>(_buf[2])<<16)|
			(static_cast<unsigned char>(_buf[1])<<8)|
			static_cast<unsigned char>(_buf[0]);

		if(_fmt==Bin) _os<<Utils::bin(word)<<std::endl;
		else if(_fmt==Dec) _os<<word<<std::endl;
		else _os<<Utils::hex(word)<<std::endl;
		_buf.clear();
	}
}

void TextOutputWriter::abort() {
	_os.close();
	std::remove(_filename.c_str());
}


text:
title: AesiCompletionProcessor.computeContextInformation - aesi-eclipse
---

[aesi-eclipse](../../index.html) / [com.virtlink.aesi.eclipse.codecompletion](../index.html) / [AesiCompletionProcessor](index.html) / [computeContextInformation](.)

# computeContextInformation

`open fun computeContextInformation(textViewer: ITextViewer, offset: `[`Int`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)`): `[`Array`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/index.html)`<IContextInformation>`


text:
__source__ = 'https://leetcode.com/problems/remove-linked-list-elements/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/remove-linked-list-elements.py
# Time:  O(n)
# Space: O(1)
#
# Description: Leetcode # 203. Remove Linked List Elements
#
# Remove all elements from a linked list of integers that have value val.
#
# Example
# Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
# Return: 1 --> 2 --> 3 --> 4 --> 5
# Related Topics
# Linked List
# Similar Questions
# Remove Element Delete Node in a Linked List
#
import unittest
# Definition for singly-linked list.
class ListNode:
     def __init__(self, x):
         self.val = x
         self.next = None
     def __repr__(self):
        if self:
            return "{} -> {}".format(self.val, repr(self.next))
        else:
            return "Nil"

class Solution:
    # @param {ListNode} head
    # @param {integer} val
    # @return {ListNode}
    def removeElements(self, head, val):
        dummy = ListNode(0)
        dummy.next = head
        cur, prev = head, dummy

        while cur:
            if cur.val == val:
                prev.next = cur.next
            else:
                prev = cur
            cur = cur.next
        return dummy.next

class TestMethods(unittest.TestCase):
    def test_Local(self):
        self.assertEqual(1, 1)
        head = ListNode(3)
        head.next = ListNode(1)
        head.next.next = ListNode(1)
        print Solution().removeElements(head, 1)

if __name__ == '__main__':
    unittest.main()

Java = '''
# Thought:

# 5ms 37.28%
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode fakeHead = new ListNode(0);
        fakeHead.next = head;
        ListNode prev = fakeHead;
        while (head != null) {
            if (head.val == val) {
                prev.next = head.next;
            } else {
                prev = head;
            }
            head = head.next;
        }
        return fakeHead.next;
    }
}

# 3ms 100%
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head == null) return head;

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode cur = dummy;

        while(cur.next != null){
            if(cur.next.val == val)
                cur.next = cur.next.next;
            else{
                cur = cur.next;
            }
        }
        return dummy.next;
    }
}
'''


text:
require 'ok_nok'

include OkNok

require_relative 'ok_nok_battleships/ai'
require_relative 'ok_nok_battleships/game'
require_relative 'ok_nok_battleships/grid'
require_relative 'ok_nok_battleships/grid_maker'
require_relative 'ok_nok_battleships/orientation'
require_relative 'ok_nok_battleships/point'
require_relative 'ok_nok_battleships/quitter'
require_relative 'ok_nok_battleships/ship_location'
require_relative 'ok_nok_battleships/ui'


text:
<?php

namespace Transphpile\Exception;

class FinderException extends \RuntimeException
{
    protected $path;

    public function setPath($path)
    {
        $this->path = $path;
    }

    public function getPath()
    {
        return $this->path;
    }
}


text:
package androidx.leanback.widget;

import android.graphics.drawable.Drawable;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;

/**
 * An action contains one or two lines of text, an optional image and an optional id. It may also
 * be invoked by one or more keycodes.
 */
public class Action {

    /** Indicates that an id has not been set. */
    public static final long NO_ID = -1;

    private long mId = NO_ID;
    private Drawable mIcon;
    private CharSequence mLabel1;
    private CharSequence mLabel2;
    private ArrayList<Integer> mKeyCodes = new ArrayList<>();

    /**
     * Constructor for an Action.
     *
     * @param id The id of the Action.
     */
    public Action(long id) {
        this(id, "");
    }

    /**
     * Constructor for an Action.
     *
     * @param id The id of the Action.
     * @param label The label to display for the Action.
     */
    public Action(long id, @Nullable CharSequence label) {
        this(id, label, null);
    }

    /**
     * Constructor for an Action.
     *
     * @param id The id of the Action.
     * @param label1 The label to display on the first line of the Action.
     * @param label2 The label to display on the second line of the Action.
     */
    public Action(long id, @Nullable CharSequence label1, @Nullable CharSequence label2) {
        this(id, label1, label2, null);
    }

    /**
     * Constructor for an Action.
     *
     * @param id The id of the Action.
     * @param label1 The label to display on the first line of the Action.
     * @param label2 The label to display on the second line of the Action.
     * @param icon The icon to display for the Action.
     */
    public Action(
            long id,
            @Nullable CharSequence label1,
            @Nullable CharSequence label2,
            @Nullable Drawable icon
    ) {
        setId(id);
        setLabel1(label1);
        setLabel2(label2);
        setIcon(icon);
    }

    /**
     * Sets the id for this Action.
     */
    public final void setId(long id) {
        mId = id;
    }

    /**
     * Returns the id for this Action.
     */
    public final long getId() {
        return mId;
    }

    /**
     * Sets the first line label for this Action.
     */
    public final void setLabel1(@Nullable CharSequence label) {
        mLabel1 = label;
    }

    /**
     * Returns the first line label for this Action.
     */
    @Nullable
    public final CharSequence getLabel1() {
        return mLabel1;
    }

    /**
     * Sets the second line label for this Action.
     */
    public final void setLabel2(@Nullable CharSequence label) {
        mLabel2 = label;
    }

    /**
     * Returns the second line label for this Action.
     */
    @Nullable
    public final CharSequence getLabel2() {
        return mLabel2;
    }

    /**
     * Sets the icon drawable for this Action.
     */
    public final void setIcon(@Nullable Drawable icon) {
        mIcon = icon;
    }

    /**
     * Returns the icon drawable for this Action.
     */
    @Nullable
    public final Drawable getIcon() {
        return mIcon;
    }

    /**
     * Adds a keycode used to invoke this Action.
     */
    public final void addKeyCode(int keyCode) {
        mKeyCodes.add(keyCode);
    }

    /**
     * Removes a keycode used to invoke this Action.
     */
    public final void removeKeyCode(int keyCode) {
        mKeyCodes.remove(keyCode);
    }

    /**
     * Returns true if the Action should respond to the given keycode.
     */
    public final boolean respondsToKeyCode(int keyCode) {
        return mKeyCodes.contains(keyCode);
    }

    @Override
    @NonNull
    public String toString(){
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(mLabel1)) {
            sb.append(mLabel1);
        }
        if (!TextUtils.isEmpty(mLabel2)) {
            if (!TextUtils.isEmpty(mLabel1)) {
                sb.append(" ");
            }
            sb.append(mLabel2);
        }
        if (mIcon != null && sb.length() == 0) {
            sb.append("(action icon)");
        }
        return sb.toString();
    }
}


text:
PLUGIN GUIDE
============

`yossarian-bot`'s plugins are more or less ordinary
[Cinch](https://github.com/cinchrb/cinch) plugins, but with a few additional
tweaks. If you want to make sure that your plugin works optimally (and that
I'll merge it), you should follow these guidelines:

* The general outline of your plugin should look something like this:

```ruby
require 'specialmodule'
require 'anothermodule'

require_relative './yossarian_plugin'

class FooBar < YossarianPlugin
	include Cinch::Plugin
	use_blacklist
	use_auth silent: false # if you need to restrict commands to admins
	use_opped silent: true # if the bot needs to be an op

	def usage
		'!foo <bar> - Use foo with bar on baz.'
	end

	def match?(cmd)
		cmd =~ /^(!)?foo/
	end

	match /foo (.+)/, method: :foo, strip_colors: true

	def foo(bar)
		quux = baz(bar)
		m.reply quux, true
	end
end

```

* Plugin class names should be descriptive of their contents, but not overly
specific or generic. Acronyms should be preserved, not lowercased. The `BTC`
plugin is a good example of both of these rules - `Btc` and
`BitcoinPriceFetcher` are good examples of the **wrong** thing to do.

* You should **always** call `use_blacklist`. It makes sure that your plugin
obeys the list of ignored nicknames/hostmasks.

* You should call `use_auth` instead of reimplementing `yossarian-bot`'s
authentication system if your plugin needs to be restricted to only
authenticated admins. Be aware that `use_auth` restricts *all* commands in the
plugin.

* You should call `use_opped` if the bot needs to be a channel operator to
perform an action. Be aware that `use_opped` restricts *all* commands in the
plugin.

* You should (re)define `usage` and `match?(cmd)` to meet your plugin's
functionality and invocation, respectively. `yossarian-bot` uses these two
methods to provide helpful information via `!help`.

* Each `match` call should be right above the method it invokes.

* If invoked methods get input from the user, remember to `Sanitize()` it or
use `strip_colors: true` if that'll suffice. Web services do not generally like
color codes.

* When the invoked method responds to the user (and it always should), it
should *generally* highlight them. In other words, highlighting the user is the
correct behavior about 90% of the time. For output where a highlight would only
add clutter or confusion, this can be skipped. Good exmaples of this include
`UserQuotes` and `Fortune`.

* Make sure any output generated is sanitized, just as it came in (unless
the goal of the plugin is to add colors/codes). That means avoiding sending
ASCII BELs, SOHs, or any other characters that can cause unusual or unintended
behavior in either the bot or connected clients.


text:
require 'sinatra/base'

class Application < Sinatra::Application

  def initialize(app=nil)
    super(app)

    # initialize any other instance variables for you
    # application below this comment. One example would be repositories
    # to store things in a database.

  end

  get '/' do
    erb :index, locals: {array_of_foods: DB[:foods].to_a}
  end

  get '/food/new' do
    erb :"food/new"
  end

  post '/food' do
    food_id = params[:id]
    DB[:foods].where(id: food_id).insert(name: params[:name], ethnicity: params[:ethnicity], year_eaten: params[:year_eaten])
    redirect '/'
  end
end


text:
using namespace seqan;

int main()
{
    String<char> haystack = "Simon, send more money!";
    String<String<char>> needle;
	appendValue(needle,"more");
	appendValue(needle,"send");
	appendValue(needle,"mo");
    Finder<String<char>> finder(haystack);
    Pattern<String<String<char>>, WuManber> pattern(needle);
    while (find(finder, pattern))
		std::cout << '[' << beginPosition(finder) << ',' << endPosition(finder) << ")\t" << infix(finder) << std::endl;
	return 0;
}


text:
import Controller from '@ember/controller';
import { task, timeout } from 'ember-concurrency';
import $ from 'jquery';

export default Controller.extend({
  fetch: function(pageOffset, pageSize, stats) {
    return $.ajax({ url: `/colors?page=pageOffset` }).then((response) => {
      stats.totalPages = response.meta.total_pages;
      return response.colors;
    });
  },

  'timeout-ms': 5,

  setReadOffset: task(function * (dataset, offset) {
    yield timeout(this.get('timeout-ms'));
    console.log('setReadOffset', offset);
    dataset.setReadOffset(offset);
  }).restartable(),

  actions: {
    onObjectAt(dataset, index) {
      this.get('setReadOffset').perform(dataset, index);
    }
  }
});


text:
import {runCars} from '../index'

// TODO: Local cloudsearch
xdescribe('#examples-node', function() {
	this.timeout(60000)

	it('#runCars',async () => {
		expect(await runCars()).toBe(true)
	})
})


text:
Lucy
====
Lucy is a tool for sharing, coordinating, and automating code in any language. Lucy works by feeding JSON into code templates, producing customized code that compiles and runs.

Lucy is just getting started, but you can keep up with the latest news and learn about what lucy can do here:

http://lucybot.github.io/blog/

Want to get an early peek at everything lucy can do? Join the beta!

## Installation
You'll need nodejs to run lucy:

https://github.com/joyent/node/wiki/installing-node.js-via-package-manager

```bash
sudo npm install -g lucy
lucy adduser
```

## Usage
### Build an existing package
```bash
lucy build definition:package config.json
```

### Push a new definition
Note: define is currently only open to beta testers.  Join the beta for access
```bash
lucy define definition.json
```

### Add a package to an existing definition
Note: publish is currently only open to beta testers. Join the beta for access
```bash
lucy publish /path/to/directory/containing/package.json
```

## About
There are two main components to a lucy module:

* DEFINITION - this is JSON that describes what kind of code is being generated, and provides a sample configuration.

* PACKAGE - this is a set of code templates, scripts, and files that will be used to generate code. There can be multiple packages per definition.

Most users will simply run ```lucy build``` to generate code from an existing lucy package. However, you can also create your own definitions and packages to share with others. Let's walk through a "hello world" example.

Note that while we're in beta, the ```define``` and ```publish``` commands won't work unless you're signed up. Feel free to jump ahead to ```build``` though!

### Quickstart
To download all the files described in this tutorial, enter a new directory and run
```bash
lucy build hello-world-starter '{"username": "SOME_UNIQUE_ID"}'
```
choosing a unique id that won't collide with other hello-world-* definitions.

you can then run
```bash
lucy define def.json

lucy publish pkg
lucy build hello-world-YOUR_UNIQUE_ID:js config.json

lucy publish javapkg
lucy build hello-world-YOUR_UNIQUE_ID:java config.json
```

### The Definition
We start with a definition:

def.json
```js
{
  "name": "hello-world",
  "description": "A hello world example for lucy",
  "sample_input": {
    "greeting": "Hello",
    "person": "world"
  }
}
```
(you'll need to replace "hello-world" with something unique)

and run:
```bash
lucy define def.json
```
which pushes the definition to lucy's servers.

### The Package
Now we create a package by starting a new directory 'pkg'

pkg/hello.js
```js
console.log('<%- greeting %> <%- person %>');
```

pkg/package.json
```js
{
  "lucy_def": "hello-world",
  "package_name": "js",
  "files": [{
    "from": "hello.js"
  }]
}
```

and run
```bash
lucy publish pkg
```
which will zip up the directory and upload the resulting tarball.

### Build!
Now anyone can create a config.json like

config.json
```js
{
  "greeting": "Yo",
  "person": "lucy"
}
```

and run
```bash
lucy build hello-world:js config.json
```

which will generate this file in the working directory:

hello.js
```js
console.log("Yo lucy");
```

### Extend!
What's more, you (or anyone else) can add other packages to the hello-world definition, for example:

Hello.java
```java
public class Hello {
  public static void main(String[] args) {
    System.out.println("<%- greeting %> <%- person %>");
  }
}
```

package.json
```js
{
  "lucy_def": "hello-world",
  "package_name": "java",
  "files": [{
    "from": "Hello.java"
  }]
}
```

Join the beta if you're intersted in giving it a shot!


text:
package org.apache.activemq.ra;

/**
 * A helper class used to provide access to the current active
 * {@link InboundContext} instance being used to process a message in the
 * current thread so that messages can be produced using the same session.
 *
 *
 */
public final class InboundContextSupport {

    private static final ThreadLocal<InboundContext> THREAD_LOCAL = new ThreadLocal<InboundContext>();

    private InboundContextSupport() {
    }

    /**
     * Returns the current {@link InboundContext} used by the current thread
     * which is processing a message. This allows us to access the current
     * Session to send a message using the same underlying session to avoid
     * unnecessary XA or to use regular JMS transactions while using message
     * driven POJOs.
     *
     * @return
     */
    public static InboundContext getActiveSessionAndProducer() {
        return THREAD_LOCAL.get();
    }

    /**
     * Registers the session and producer which should be called before the
     * {@link javax.resource.spi.endpoint.MessageEndpoint#beforeDelivery(java.lang.reflect.Method)}
     * method is called.
     *
     * @param sessionAndProducer
     */
    public static void register(InboundContext sessionAndProducer) {
        THREAD_LOCAL.set(sessionAndProducer);
    }

    /**
     * Unregisters the session and producer which should be called after the
     * {@link javax.resource.spi.endpoint.MessageEndpoint#afterDelivery()}
     * method is called.
     *
     * @param sessionAndProducer
     */
    public static void unregister(InboundContext sessionAndProducer) {
        THREAD_LOCAL.set(null);
    }
}


text:
/**
 * Hashes the name.
 * @param name Name to hash
 * @param replica_no Number of replica, counted from 0
 * @return Hash value
 */
public static long hash(String name, int replica_no) {
	long basehash = H.h_hash(name);
	if (replica_no == 0)
		return basehash;
	if (replica_no == 1)
		return basehash + Long.MAX_VALUE;
	if (replica_no == 2)
		return basehash + (Long.MAX_VALUE) + (Long.MAX_VALUE / 2);
	if (replica_no == 3)
		return basehash + (Long.MAX_VALUE / 2);
	throw new RuntimeException("No idea how to hash that");
}


text:
package org.synyx.urlaubsverwaltung.calendarintegration.providers.exchange;

import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.exception.service.remote.ServiceRequestException;
import microsoft.exchange.webservices.data.core.service.item.Item;
import org.junit.jupiter.api.Test;

import java.net.URI;

import static microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion.Exchange2010_SP2;
import static microsoft.exchange.webservices.data.core.enumeration.service.MessageDisposition.SaveOnly;
import static microsoft.exchange.webservices.data.core.enumeration.service.SendInvitationsMode.SendToNone;
import static microsoft.exchange.webservices.data.property.complex.FolderId.getFolderIdFromString;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;

class ExchangeCalendarDependenciesTest {

    @Test
    void checkDependenciesAvailable() {
        final ExchangeService exchangeService = new ExchangeService(Exchange2010_SP2);
        exchangeService.setUrl(URI.create("http://localhost"));
        assertThrows(ServiceRequestException.class,() -> exchangeService.createItem(mock(Item.class), getFolderIdFromString("folderId"), SaveOnly, SendToNone));
    }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Tag2 on Valère JEANTET</title>
    <link>http://vjeantet.fr/tags/tag2/</link>
    <description>Recent content in Tag2 on Valère JEANTET</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>fr-FR</language>
    <copyright>All rights reserved - 2015</copyright>
    <lastBuildDate>Wed, 23 Dec 2015 13:28:02 +0200</lastBuildDate>
    <atom:link href="http://vjeantet.fr/tags/tag2/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>my post</title>
      <link>http://vjeantet.fr/post-title/</link>
      <pubDate>Wed, 23 Dec 2015 13:28:02 +0200</pubDate>

      <guid>http://vjeantet.fr/post-title/</guid>
      <description></description>
    </item>

  </channel>
</rss>


text:
<?xml version="1.0" encoding="utf-8"?>

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid
        android:color="@color/white_mostly_primary"/>

    <stroke
        android:color="@color/gray_light_very"
        android:width="@dimen/button_corner_width"/>

</shape>


text:
#include <aws/greengrass/model/ResetDeploymentsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

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

ResetDeploymentsResult::ResetDeploymentsResult()
{
}

ResetDeploymentsResult::ResetDeploymentsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

ResetDeploymentsResult& ResetDeploymentsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("DeploymentArn"))
  {
    m_deploymentArn = jsonValue.GetString("DeploymentArn");

  }

  if(jsonValue.ValueExists("DeploymentId"))
  {
    m_deploymentId = jsonValue.GetString("DeploymentId");

  }

  return *this;
}


text:
import math
import struct

from . import constants
from . import exceptions

def calculate_backward_bitnumber(normal_bitnumber):
    """Calculate the bit position in the "backward" numbering format.

    Args:
      normal_bitnumber (int): bit position in the standard format.

    Raises:
      CanException: For wrong bitnumber. See :exc:`.CanException`.

    Returns:
      The bit position (int) in the "backward" numbering format.

    The "backward" is a numbering scheme where the bits are numbered::

        63,62 61,60,59,58,57,56  55,54,53,52,51,50,49,48  47,46 etc
        Byte0                    Byte1                    Byte2

    In full detail::

        66665555 55555544 44444444 33333333 33222222 22221111 111111
        32109876 54321098 76543210 98765432 10987654 32109876 54321098 76543210
        Byte0    Byte1    Byte2    Byte3    Byte4    Byte5    Byte6    Byte7

    For reference, the standard bit numbering is::

        7,6,5,4,3,2,1,0  15,14,13,12,11,10,9,8  23,22,21,20,19,18,17,16  31,30,29,28,27,26,25,24 etc.
        Byte0            Byte1                  Byte2                    Byte3

    In full detail::

                 111111   22221111 33222222 33333333 44444444 55555544 66665555
        76543210 54321098 32109876 10987654 98765432 76543210 54321098 32109876
        Byte0    Byte1    Byte2    Byte3    Byte4    Byte5    Byte6    Byte7

    """
    if normal_bitnumber < 0:
        raise exceptions.CanException("The given normal_bitnumber is too small: {}".format(normal_bitnumber))
    if normal_bitnumber > constants.BITS_IN_FULL_DATA - 1:
        raise exceptions.CanException("The given normal_bitnumber is too large: {}".format(normal_bitnumber))
    bytenumber = normal_bitnumber // constants.BITS_PER_BYTE
    offset_in_the_byte = normal_bitnumber - bytenumber * constants.BITS_PER_BYTE  # MSbit=7, LSbit=0
    basevalue_per_byte = (constants.MAX_NUMBER_OF_CAN_DATA_BYTES - 1 - bytenumber) * constants.BITS_PER_BYTE
    return basevalue_per_byte + offset_in_the_byte

def calculate_normal_bitnumber(backward_bitnumber):
    """
    Calculate the bitnumber, from the bitnumber in backwards numbering scheme.

    This is the inverse of :func:`.calculate_backward_bitnumber`.

    Args:
      backward_bitnumber (int): The bitnumber (in backwards numbering scheme)

    Raises:
      CanException: For wrong bitnumber. See :exc:`.CanException`.

    Returns:
      The bit position (int) in the standard format.

    """
    if backward_bitnumber < 0:
        raise exceptions.CanException("The given backward_bitnumber is too small: {}".format(backward_bitnumber))
    if backward_bitnumber > constants.BITS_IN_FULL_DATA - 1:
        raise exceptions.CanException("The given backward_bitnumber is too large: {}".format(backward_bitnumber))
    bytenumber = constants.MAX_NUMBER_OF_CAN_DATA_BYTES - 1 - backward_bitnumber // constants.BITS_PER_BYTE

    # Most significant bit=7, Least significant bit=0
    offset_in_the_byte = backward_bitnumber - \
        (constants.MAX_NUMBER_OF_CAN_DATA_BYTES - 1 - bytenumber) * constants.BITS_PER_BYTE

    return offset_in_the_byte + bytenumber * constants.BITS_PER_BYTE

def generate_bit_byte_overview(inputstring, number_of_indent_spaces=4, show_reverse_bitnumbering=False):
    """Generate a nice overview of a CAN frame.

    Args:
      inputstring (str): String that should be printed. Should be 64 characters long.
      number_of_indent_spaces (int): Size of indentation

    Raises:
      ValueError when *inputstring* has wrong length.

    Returns:
      A multi-line string.

    """
    if len(inputstring) != constants.BITS_IN_FULL_DATA:
        raise ValueError("The inputstring is wrong length: {}. {!r}".format(len(inputstring), inputstring))
    paddedstring = " ".join([inputstring[i:i + 8] for i in range(0, 64, 8)])

    indent = " " * number_of_indent_spaces
    text = indent + "         111111   22221111 33222222 33333333 44444444 55555544 66665555\n"
    text += indent + "76543210 54321098 32109876 10987654 98765432 76543210 54321098 32109876\n"
    text += indent + "Byte0    Byte1    Byte2    Byte3    Byte4    Byte5    Byte6    Byte7\n"
    text += indent + paddedstring + "\n"

    if show_reverse_bitnumbering:
        text += indent + "66665555 55555544 44444444 33333333 33222222 22221111 111111\n"
        text += indent + "32109876 54321098 76543210 98765432 10987654 32109876 54321098 76543210\n"
    return text

def generate_can_integer_overview(value):
    """Generate a nice overview of an integer, interpreted as a CAN frame/fr_def.

    Args:
      value (int): Integer representing the data of a CAN frame

    Returns:
      A multi-line string.

    """
    bitstring = "{:064b}".format(value)
    return generate_bit_byte_overview(bitstring)

def can_bytes_to_int(input_bytes):
    """
    Convert bytes to an integer (after padding the bytes).

    Args:
      input_bytes (bytes object): holds 0-8 bytes of data. Will be padded with empty bytes on right side.

    Returns:
      An integer corresponding to 8 bytes of data.

    Note: An input of b"\x01" will be padded to b"\x01\x00\x00\x00\x00\x00\x00\x00". This corresponds
    to an integer of 72057594037927936.

    """
    assert len(input_bytes) <= constants.MAX_NUMBER_OF_CAN_DATA_BYTES, "Too large input to can_bytes_to_int."
    framedata8bytes = bytes(input_bytes).ljust(constants.MAX_NUMBER_OF_CAN_DATA_BYTES, constants.NULL_BYTE)
    dataint = struct.unpack(constants.FORMAT_DATA_LONGLONG, framedata8bytes)[0]
    return dataint

def int_to_can_bytes(dlc, dataint):
    """
    Convert an integer to 8 bytes, and cut it from the left according to the dlc.

    Args:
      dlc (int): how many bytes it should be encoded into
      dataint (int): holds 8 bytes of data

    Returns a bytes object: 0-8 bytes of CAN data

    For example a dataint value of 1 is converted to b'\x00\x00\x00\x00\x00\x00\x00\x01'. If the dlc is given as 1,
    then the return value will be b'\x00'.

    """
    dlc = int(dlc)
    assert dlc <= constants.MAX_NUMBER_OF_CAN_DATA_BYTES, "Too large dlc given to int_to_can_bytes."
    framedata8bytes = bytes(struct.pack(constants.FORMAT_DATA_LONGLONG, dataint))
    return framedata8bytes[0:dlc]

def twos_complement(value, bits):
    """
    Calculate two's complement for a value.

    Args:
      value (int): input value (positive or negative)
      bits (int): field size

    Returns a positive integer. If in the upper part of the range, it should be interpreted as negative.

    The allowed input value range is -2**(bits-1) to +2**(bits-1)-1. For example, 8 bits gives a range of -128 to +127.

    """
    value = int(value)
    bits = int(bits)
    maxvalue = 2 ** (bits - 1) - 1
    minvalue = - 2 ** (bits - 1)
    if value > maxvalue or value < minvalue:
        raise exceptions.CanException("Wrong value for two's complement: {} Bits: {} Range: {}-{}".format(
            value, bits, minvalue, maxvalue))
    if value >= 0:
        return value
    return value + 2 ** bits

def from_twos_complement(value, bits):
    """
    Calculate the inverse (?) of two's complement for a value.

    Args:
      value (int): input value (positive)
      bits (int): field size

    Returns a positive or negative integer, in the range range is -2**(bits-1) to +2**(bits-1)-1.
    For example, 8 bits gives an output range of -128 to +127.

    """
    value = int(value)
    bits = int(bits)
    maxvalue = (2 ** bits) - 1
    if value < 0 or value > maxvalue:
        raise exceptions.CanException("Wrong value for two's complement inverse: {} Bits: {} Range: 0-{}".format(
            value, bits, maxvalue))

    max_positive_value = 2 ** (bits - 1) - 1
    if value <= max_positive_value:
        return value
    return value - 2 ** bits

def split_seconds_to_full_and_part(seconds_float):
    """Split a time value into full and fractional parts.

    Args:
      seconds_float (float): Number of seconds

    Returns (seconds_full, useconds) which both are integers. They represent the time in
        full seconds and microseconds respectively.

    """
    if seconds_float < 0:
        raise exceptions.CanException("Invalid time interval: {}".format(seconds_float))
    seconds_full = math.floor(seconds_float)
    useconds = int((seconds_float - seconds_full) * constants.MICROSECONDS_PER_SECOND)
    return seconds_full, useconds

def check_frame_id_and_format(frame_id, frame_format):
    """Check the validity of frame_id.

    Args:
      frame_id (int): frame_id to be checked
      frame_format (str): Frame format.  Should be ``'standard'`` or ``'extended'``.

    """
    if frame_format not in [constants.CAN_FRAMEFORMAT_STANDARD, constants.CAN_FRAMEFORMAT_EXTENDED]:
        raise exceptions.CanException("Wrong frame_format. Given: {!r}".format(frame_format))
    if frame_id is None:
        raise exceptions.CanException("frame_id must be given (can not be None)")
    try:
        frame_id = int(frame_id)
    except (ValueError, TypeError) as _:
        raise exceptions.CanException("frame_id should be an integer. Given: {!r}".format(frame_id))
    if frame_id < 0:
        raise exceptions.CanException("frame_id is negative. Given: {!r}".format(frame_id))
    if frame_format == constants.CAN_FRAMEFORMAT_STANDARD and frame_id > constants.MAX_CAN_FRAME_ID_STANDARD:
        raise exceptions.CanException("frame_id is too large for standard frames. Given: {!r}".format(frame_id))
    if frame_format == constants.CAN_FRAMEFORMAT_EXTENDED and frame_id > constants.MAX_CAN_FRAME_ID_EXTENDED:
        raise exceptions.CanException("frame_id is too large for extended frames. Given: {!r}".format(frame_id))

def get_busvalue_from_bytes(input_bytes, endianness, numberofbits, startbit):
    """Get the busvalue from bytes.

    Args:
      input_bytes (bytes object): up to 8 bytes of data
      endianness (str): 'big' or 'little'
      numberofbits (int): Number of bits in the signal
      startbit (int): LSB in normal bit numbering

    Returns the bus value, which is the bits interpreted as an unsigned integer. For example '0110' is interpreted
    as the unsigned integer 6. Later, it will then be converted to whatever (maybe signed or unsigned integer).

    """
    if endianness == constants.BIG_ENDIAN:
        # Calculate number of shifts to extract the signal
        # extract_shifts (int): Number of bits to be removed from least significant side.
        # Backwards bit 63 (leftmost) must be shifted 63 steps to become rightmost bit.
        extract_shifts = calculate_backward_bitnumber(startbit)
        dataint = can_bytes_to_int(input_bytes)

        # Rightshift so the interesting bits are rightmost
        shifted = dataint >> extract_shifts  # Still BIG_ENDIAN

    else:  # The input_bytes are in LITTLE_ENDIAN. Normal bit numbering.
        bytenumber_for_startbit = startbit // constants.BITS_PER_BYTE
        assert bytenumber_for_startbit < constants.MAX_NUMBER_OF_CAN_DATA_BYTES, \
            "The startbit is wrong. Given {}.".format(startbit)
        stopbit_little = startbit + numberofbits - 1
        bytenumber_for_stopbit_little = stopbit_little // constants.BITS_PER_BYTE
        assert bytenumber_for_stopbit_little < constants.MAX_NUMBER_OF_CAN_DATA_BYTES, \
            "The stopbit is wrong for LITTLE endian. Given startbit {}, numberofbits {}.".format(startbit, numberofbits)
        number_of_bytes_to_shuffle = bytenumber_for_stopbit_little - bytenumber_for_startbit + 1
        number_of_steps_to_LSBit_in_byte = startbit % constants.BITS_PER_BYTE

        reshuffled_bytes = bytearray(constants.MAX_NUMBER_OF_CAN_DATA_BYTES)

        #print("##", bytenumber_for_startbit, bytenumber_for_stopbit_little, number_of_bytes_to_shuffle, number_of_steps_to_LSBit_in_byte)

        for i in range(number_of_bytes_to_shuffle):
            bytenumber_origin = bytenumber_for_startbit + i
            bytenumber_destination = constants.MAX_NUMBER_OF_CAN_DATA_BYTES - 1 - i  # Start from right
            #print(i, bytenumber_origin, bytenumber_destination)
            reshuffled_bytes[bytenumber_destination] = input_bytes[bytenumber_origin]

        temporary_value = can_bytes_to_int(reshuffled_bytes)

        # Rightshift so the interesting bits are rightmost
        shifted = temporary_value >> number_of_steps_to_LSBit_in_byte  # Now BIG_ENDIAN

    mask = (1 << numberofbits) - 1  # Mask with ones in 'numberofbits' positions
    return shifted & mask

def get_shiftedvalue_from_busvalue(input_value, endianness, numberofbits, startbit):
    """Get the shifted value from the bus value.

    Args:
      input_value (int): Integer corresponding to the bus value.
      endianness (str): 'big' or 'little'
      numberofbits (int): Number of bits in the signal
      startbit (int): LSB in normal bit numbering

    Returns the shifted value, which later will be put into the frame using AND/OR operations together with a mask.

    Earlier the physical value has been converted to a shifted value and then to a bus value.  For example, a
    bus value input_value '0110' is interpreted as the unsigned integer 6.

    """
    encode_shifts = calculate_backward_bitnumber(startbit)  # Origin is BIG ENDIAN

    if endianness == constants.BIG_ENDIAN:
        shifted_value = input_value << encode_shifts  # Origin is BIG ENDIAN
        return shifted_value  # Still BIG_ENDIAN

    else: # Origin is BIG ENDIAN, we should convert to LITTLE_ENDIAN.
        number_of_steps_to_LSBit_in_byte = encode_shifts % constants.BITS_PER_BYTE
        bytenumber_for_startbit = startbit // constants.BITS_PER_BYTE
        stopbit_little = startbit + numberofbits - 1
        bytenumber_for_stopbit_little = stopbit_little // constants.BITS_PER_BYTE
        assert bytenumber_for_stopbit_little < constants.MAX_NUMBER_OF_CAN_DATA_BYTES, \
            "The stopbit is wrong for LITTLE endian. Given startbit {}, numberofbits {}.".format(startbit, numberofbits)
        number_of_bytes_to_shuffle = bytenumber_for_stopbit_little - bytenumber_for_startbit + 1

        partially_shifted_value = input_value << number_of_steps_to_LSBit_in_byte
        partially_shifted_bytes = int_to_can_bytes(constants.MAX_NUMBER_OF_CAN_DATA_BYTES, partially_shifted_value)
        reshuffled_bytes = bytearray(constants.MAX_NUMBER_OF_CAN_DATA_BYTES)

        for i in range(number_of_bytes_to_shuffle):
            bytenumber_origin = constants.MAX_NUMBER_OF_CAN_DATA_BYTES - 1 - i  # Start from right
            bytenumber_destination = bytenumber_for_startbit + i
            #print(i, bytenumber_origin, bytenumber_destination)
            reshuffled_bytes[bytenumber_destination] = partially_shifted_bytes[bytenumber_origin]

        return can_bytes_to_int(reshuffled_bytes)


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.app.appmenu;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import androidx.test.filters.SmallTest;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.Feature;
import org.chromium.base.test.util.Restriction;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.tasks.tab_management.PriceTrackingUtilities;
import org.chromium.chrome.browser.ui.appmenu.AppMenuTestSupport;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.chrome.test.ChromeTabbedActivityTestRule;
import org.chromium.chrome.test.util.browser.Features;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import org.chromium.ui.modelutil.MVCListAdapter.ModelList;
import org.chromium.ui.test.util.UiRestriction;

/**
 * Tests overview mode app menu popup.
 *
 * TODO(crbug.com/1031958): Add more required tests.
 */
@RunWith(ChromeJUnit4ClassRunner.class)
@Restriction(
        {UiRestriction.RESTRICTION_TYPE_PHONE, Restriction.RESTRICTION_TYPE_NON_LOW_END_DEVICE})
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE})
public class OverviewAppMenuTest {
    @Rule
    public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule();

    @Before
    public void setUp() {
        mActivityTestRule.startMainActivityOnBlankPage();
        TestThreadUtils.runOnUiThreadBlocking(
                () -> { mActivityTestRule.getActivity().getLayoutManager().showOverview(true); });
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.EnableFeatures({ChromeFeatureList.TAB_GROUPS_ANDROID})
    @Features.DisableFeatures({ChromeFeatureList.START_SURFACE_ANDROID})
    public void testAllMenuItemsWithoutStartSurface() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        verifyTabSwitcherMenu();
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.EnableFeatures({ChromeFeatureList.TAB_GROUPS_ANDROID})
    @Features.DisableFeatures({ChromeFeatureList.START_SURFACE_ANDROID})
    public void testIncognitoAllMenuItemsWithoutStartSurface() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            mActivityTestRule.getActivity().getTabModelSelector().selectModel(true);
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        verifyTabSwitcherMenuIncognito();
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.
    EnableFeatures({ChromeFeatureList.START_SURFACE_ANDROID, ChromeFeatureList.TAB_GROUPS_ANDROID})
    public void testAllMenuItemsWithStartSurface() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        verifyTabSwitcherMenu();
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.
    EnableFeatures({ChromeFeatureList.START_SURFACE_ANDROID, ChromeFeatureList.TAB_GROUPS_ANDROID})
    public void testIncognitoAllMenuItemsWithStartSurface() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            mActivityTestRule.getActivity().getTabModelSelector().selectModel(true);
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        verifyTabSwitcherMenuIncognito();
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    // clang-format off
    @Features.EnableFeatures({ChromeFeatureList.TAB_GROUPS_ANDROID,
        ChromeFeatureList.START_SURFACE_ANDROID + "<Study"})
    @CommandLineFlags.Add({"force-fieldtrials=Study/Group",
        "force-fieldtrial-params=Study.Group:omnibox_focused_on_new_tab/true"})
    public void testNewTabIsEnabledWithStartSurfaceFinale() throws Exception {
        // clang-format on
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.new_tab_menu_id));
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    // clang-format off
    @Features.EnableFeatures({ChromeFeatureList.TAB_GROUPS_ANDROID,
        ChromeFeatureList.START_SURFACE_ANDROID + "<Study"})
    @CommandLineFlags.Add({"force-fieldtrials=Study/Group",
        "force-fieldtrial-params=Study.Group:open_ntp_instead_of_start/true"})
    public void testNewTabIsEnabledWithStartSurfaceV2() throws Exception {
        // clang-format on
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.new_tab_menu_id));
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.
    DisableFeatures({ChromeFeatureList.START_SURFACE_ANDROID, ChromeFeatureList.TAB_GROUPS_ANDROID})
    public void testGroupTabsIsDisabled() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        assertNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.menu_group_tabs));
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.EnableFeatures({ChromeFeatureList.TAB_GROUPS_ANDROID})
    @Features.DisableFeatures({ChromeFeatureList.START_SURFACE_ANDROID})
    public void testGroupTabsIsEnabled() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.menu_group_tabs));
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.EnableFeatures({ChromeFeatureList.START_SURFACE_ANDROID})
    @Features.DisableFeatures({ChromeFeatureList.TAB_GROUPS_ANDROID})
    public void testGroupTabsIsDisabledWithStartSurface() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        assertNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.menu_group_tabs));
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.
    EnableFeatures({ChromeFeatureList.START_SURFACE_ANDROID, ChromeFeatureList.TAB_GROUPS_ANDROID})
    public void testGroupTabsIsEnabledWithStartSurface() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.menu_group_tabs));
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.EnableFeatures({ChromeFeatureList.COMMERCE_PRICE_TRACKING + "<Study"})
    @Features.DisableFeatures({ChromeFeatureList.START_SURFACE_ANDROID})
    @CommandLineFlags.Add({"force-fieldtrials=Study/Group",
            "force-fieldtrial-params=Study.Group:enable_price_tracking/false"})
    public void
    testTrackPriceOnTabsIsDisabled() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            PriceTrackingUtilities.setIsSignedInAndSyncEnabledForTesting(true);
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        assertNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.track_prices_row_menu_id));
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.EnableFeatures({ChromeFeatureList.COMMERCE_PRICE_TRACKING + "<Study"})
    @Features.DisableFeatures({ChromeFeatureList.START_SURFACE_ANDROID})
    @CommandLineFlags.Add({"force-fieldtrials=Study/Group",
            "force-fieldtrial-params=Study.Group:enable_price_tracking/true"
                    + "/allow_disable_price_annotations/true"})
    public void
    testTrackPriceOnTabsIsEnabled() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            PriceTrackingUtilities.setIsSignedInAndSyncEnabledForTesting(true);
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.track_prices_row_menu_id));
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.EnableFeatures({ChromeFeatureList.COMMERCE_PRICE_TRACKING + "<Study"})
    @Features.DisableFeatures({ChromeFeatureList.START_SURFACE_ANDROID})
    @CommandLineFlags.Add({"force-fieldtrials=Study/Group",
            "force-fieldtrial-params=Study.Group:enable_price_tracking/true"
                    + "/allow_disable_price_annotations/true"})
    public void
    testTrackPriceOnTabsIsDisabledInIncognitoMode() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            PriceTrackingUtilities.setIsSignedInAndSyncEnabledForTesting(true);
            mActivityTestRule.getActivity().getTabModelSelector().selectModel(true);
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        assertNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.track_prices_row_menu_id));
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.EnableFeatures({ChromeFeatureList.COMMERCE_PRICE_TRACKING + "<Study"})
    @Features.DisableFeatures({ChromeFeatureList.START_SURFACE_ANDROID})
    @CommandLineFlags.Add({"force-fieldtrials=Study/Group",
            "force-fieldtrial-params=Study.Group:enable_price_tracking/true"
                    + "/allow_disable_price_annotations/true"})
    public void
    testTrackPriceOnTabsIsDisabledIfSyncDisabledOrNotSignedIn() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            PriceTrackingUtilities.setIsSignedInAndSyncEnabledForTesting(false);
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        assertNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.track_prices_row_menu_id));
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.EnableFeatures({ChromeFeatureList.COMMERCE_PRICE_TRACKING + "<Study"})
    @Features.DisableFeatures({ChromeFeatureList.START_SURFACE_ANDROID})
    @CommandLineFlags.Add({"force-fieldtrials=Study/Group",
            "force-fieldtrial-params=Study.Group:enable_price_tracking/true"
                    + "/allow_disable_price_annotations/false/enable_price_notification/false"})
    public void
    testTrackPriceOnTabsIsDisabledIfNoSettingsAvailable() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            PriceTrackingUtilities.setIsSignedInAndSyncEnabledForTesting(true);
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        assertNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.track_prices_row_menu_id));
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.EnableFeatures({ChromeFeatureList.START_SURFACE_ANDROID,
            ChromeFeatureList.COMMERCE_PRICE_TRACKING + "<Study"})
    @CommandLineFlags.Add({"force-fieldtrials=Study/Group",
            "force-fieldtrial-params=Study.Group:enable_price_tracking/false"})
    public void
    testTrackPriceOnTabsIsDisabledWithStartSurface() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            PriceTrackingUtilities.setIsSignedInAndSyncEnabledForTesting(true);
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        assertNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.track_prices_row_menu_id));
    }

    @Test
    @SmallTest
    @Feature({"Browser", "Main"})
    @Features.EnableFeatures({ChromeFeatureList.START_SURFACE_ANDROID,
            ChromeFeatureList.COMMERCE_PRICE_TRACKING + "<Study"})
    @CommandLineFlags.Add({"force-fieldtrials=Study/Group",
            "force-fieldtrial-params=Study.Group:enable_price_tracking/true"
                    + "/allow_disable_price_annotations/true"})
    public void
    testTrackPriceOnTabsIsEnabledWithStartSurface() throws Exception {
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            PriceTrackingUtilities.setIsSignedInAndSyncEnabledForTesting(true);
            AppMenuTestSupport.showAppMenu(mActivityTestRule.getAppMenuCoordinator(), null, false);
        });

        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.track_prices_row_menu_id));
    }

    private void verifyTabSwitcherMenu() {
        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.new_tab_menu_id));
        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.new_incognito_tab_menu_id));
        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.close_all_tabs_menu_id));
        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.menu_group_tabs));
        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.preferences_id));

        assertNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.close_all_incognito_tabs_menu_id));
        assertNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.track_prices_row_menu_id));

        ModelList menuItemsModelList =
                AppMenuTestSupport.getMenuModelList(mActivityTestRule.getAppMenuCoordinator());
        assertEquals(5, menuItemsModelList.size());
    }

    private void verifyTabSwitcherMenuIncognito() {
        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.new_tab_menu_id));
        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.new_incognito_tab_menu_id));
        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.close_all_incognito_tabs_menu_id));
        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.menu_group_tabs));
        assertNotNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.preferences_id));

        assertNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.close_all_tabs_menu_id));
        assertNull(AppMenuTestSupport.getMenuItemPropertyModel(
                mActivityTestRule.getAppMenuCoordinator(), R.id.track_prices_row_menu_id));

        ModelList menuItemsModelList =
                AppMenuTestSupport.getMenuModelList(mActivityTestRule.getAppMenuCoordinator());
        assertEquals(5, menuItemsModelList.size());
    }
}


text:
module Fog
  module Google
    class Monitoring
      ##
      # Describes the schema of a MonitoredResource (a resource object that can be used for monitoring, logging,
      # billing, or other purposes) using a type name and a set of labels.
      #
      # @see https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.monitoredResourceDescriptors/list
      class Real
        def list_monitored_resource_descriptors(filter: nil, page_size: nil, page_token: nil)
          @monitoring.list_project_monitored_resource_descriptors(
            "projects/#{@project}",
            :filter => filter,
            :page_size => page_size,
            :page_token => page_token
          )
        end
      end

      class Mock
        def list_monitored_resource_descriptors(_filter, _page_size, _page_token)
          # :no-coverage:
          Fog::Mock.not_implemented
          # :no-coverage:
        end
      end
    end
  end
end


text:
<?php

namespace Vushop\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        $usr= $this->get('security.context')->getToken()->getUser();
        //$name = $usr->getUsername();
        return $this->render('AdminBundle:Default:index.html.twig', array('username' => $usr->getUsername()));
    }
}


text:
package goxldeploy

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strconv"
	"testing"
)

type mock struct {
	url      string
	method   string
	response string
}

type mocks []mock

var (
	mux *http.ServeMux

	client     *Client
	mockConfig *Config
	server     *httptest.Server

	mockCollection mocks
)

func setupMock() {
	mux = http.NewServeMux()
	server = httptest.NewServer(mux)
	//fmt.Printf(server.Client)

	url, _ := url.Parse(server.URL)
	p, _ := strconv.Atoi(url.Port())
	mockConfig = &Config{
		User:     "admin",
		Password: "password",
		Host:     url.Hostname(),
		Port:     p, Context: "",
		Scheme: url.Scheme,
	}
	client = New(mockConfig)

}

func teardown() {
	server.Close()
}

func testMethod(t *testing.T, r *http.Request, expected string) {
	if expected != r.Method {
		t.Errorf("Request method = %v, expected %v", r.Method, expected)
	}
}

func addHandlers(s mocks) {
	for _, m := range s {
		addHandler(m)
	}
}

func addHandler(m mock) {

	mux.HandleFunc(m.url, func(w http.ResponseWriter, r *http.Request) {
		// if m.method != "" {
		// 	testMethod(, r, m.method)
		// }
		fmt.Fprint(w, m.response)
	})

}

// mock1 := mock { response: `{
// 	"id": "Environments/testDictionary1",
// 	"type": "udm.Dictionary",
// 	"$token": "7f5eeb79-73f9-4312-a4d3-0363402c109d",
// 	"$createdBy": "admin",
// 	"$createdAt": "2016-09-27T09:42:58.212+0200",
// 	"$lastModifiedBy": "admin",
// 	"$lastModifiedAt": "2016-09-27T09:42:58.212+0200",
// 	"entries": {
// 	  "test": "test",
// 	  "bank": "rabo"
// 	},
// 	"encryptedEntries": {
// 		"test": "test",
// 		"bank": "rabo"
// 	  },
// 	"restrictToContainers": ["Infrastructure/testHost"],
// 	"restrictToApplications": ["Applications/testApp", "Applications/testApp2"]
//   }`,
//   method: "GET",
//   url: "/deployit/repository/ci/Environments/testDictionary1",}

// mux.HandleFunc("/deployit/repository/ci/Environments/testDictionary1", func(w http.ResponseWriter, r *http.Request) {

// 	fmt.Fprint(w, mockTestDictionaryResponse)
// })

// mux.HandleFunc("/deployit/metadata/type/udm.Dictionary", func(w http.ResponseWriter, r *http.Request) {
// 	//testMethod(t, r, m.method)

// 	fmt.Fprint(w, mockTestDictionaryMetaResponse)
// })

// //setup mock rest interfaces
// mux.HandleFunc("/deployit/repository/ci/Environments/testDictionary1", func(w http.ResponseWriter, r *http.Request) {
// 	testMethod(t, r, "GET")
// 	fmt.Fprint(w, mockTestDictionaryResponse)
// })
// mux.HandleFunc("/deployit/metadata/type/udm.Dictionary", func(w http.ResponseWriter, r *http.Request) {
// 	testMethod(t, r, "GET")

// 	fmt.Fprint(w, mockTestDictionaryMetaResponse)
// })


text:
#include "xsmessagearray.h"
#include "xsmessage.h"

/*! \struct XsMessageArray
	\brief A list of XsMessage values
	\sa XsArray
*/

//! \brief Descriptor for XsMessageArray
XsArrayDescriptor const g_xsMessageArrayDescriptor = {
	//lint --e{64} ignore exact type mismatches here
	sizeof(XsMessage),
	XSEXPCASTITEMSWAP XsMessage_swap,
	XSEXPCASTITEMMAKE XsMessage_construct,
	XSEXPCASTITEMCOPY XsMessage_copyConstruct,
	XSEXPCASTITEMMAKE XsMessage_destruct,
	XSEXPCASTITEMCOPY XsMessage_copy,
	XSEXPCASTITEMCOMP XsMessage_compare
};

/*! \copydoc XsArray_construct
	\note Specialization for XsStringArray
*/
void XsMessageArray_construct(XsMessageArray* thisPtr, XsSize count, XsMessage const* src)
{
	XsArray_construct(thisPtr, &g_xsMessageArrayDescriptor, count, src);
}


text:
<?php

namespace HWI\Bundle\OAuthBundle\Tests\OAuth\ResourceOwner;

use HWI\Bundle\OAuthBundle\OAuth\ResourceOwner\StravaResourceOwner;

/**
 * StravaResourceOwnerTest
 *
 * @author Artem Genvald <genvaldartem@gmail.com>
 */
class StravaResourceOwnerTest extends GenericOAuth2ResourceOwnerTest
{
    /**
     * {@inheritDoc}
     */
    protected $userResponse = <<<json
{
    "id": "1",
    "firstname": "Foo",
    "lastname": "Bar",
    "profile_medium": "http://www.gravatar.com/avatar/default",
    "email": "foo@acme.com"
}
json;

    /**
     * {@inheritDoc}
     */
    protected $paths = array(
        'identifier'     => 'id',
        'realname'       => array('firstname', 'lastname'),
        'profilepicture' => 'profile_medium',
        'email'          => 'email'
    );

    public function testGetUserInformation()
    {
        $this->mockBuzz($this->userResponse, 'application/json; charset=utf-8');

        $userResponse = $this->resourceOwner->getUserInformation(array('access_token' => 'token'));

        $this->assertEquals('1', $userResponse->getUsername());
        $this->assertEquals('Foo Bar', $userResponse->getRealName());
        $this->assertEquals('http://www.gravatar.com/avatar/default', $userResponse->getProfilePicture());
        $this->assertEquals('foo@acme.com', $userResponse->getEmail());
        $this->assertEquals('token', $userResponse->getAccessToken());
        $this->assertNull($userResponse->getRefreshToken());
        $this->assertNull($userResponse->getExpiresIn());
    }

    /**
     * {@inheritDoc}
     */
    protected function setUpResourceOwner($name, $httpUtils, array $options)
    {
        return new StravaResourceOwner($this->buzzClient, $httpUtils, $options, $name, $this->storage);
    }
}


text:
"use strict"

var abs = Math.abs
  , min = Math.min

function almostEqual(a, b, absoluteError, relativeError) {
  var d = abs(a - b)

  if (absoluteError == null) absoluteError = almostEqual.DBL_EPSILON;
  if (relativeError == null) relativeError = absoluteError;

  if(d <= absoluteError) {
    return true
  }
  if(d <= relativeError * min(abs(a), abs(b))) {
    return true
  }
  return a === b
}

almostEqual.FLT_EPSILON = 1.19209290e-7
almostEqual.DBL_EPSILON = 2.2204460492503131e-16

module.exports = almostEqual


text:
package xworker.ai.rules.easyrule;

import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngineListener;
import org.xmeta.ActionContext;
import org.xmeta.Thing;

public class ThingRuleEngineListener implements RulesEngineListener{
	Thing thing;

	public ThingRuleEngineListener(Thing thing) {
		this.thing = thing;
	}

	private ActionContext getActionContext(Facts facts) {
		ActionContext actionContext = facts.get("actionContext");
		if(actionContext == null) {
			actionContext = new ActionContext();
		}

		return actionContext;
	}

	@Override
	public void beforeEvaluate(Rules rules, Facts facts) {
		thing.doAction("beforeEvaluate", getActionContext(facts), "rules", rules, "facts", facts);
	}

	@Override
	public void afterExecute(Rules rules, Facts facts) {
		thing.doAction("afterExecute", getActionContext(facts), "rules", rules, "facts", facts);
	}

}


text:
require 'spec_helper'

RSpec.describe DotDiff::Comparible::PageComparer do
  let(:snapshot) do
    instance_double(
      DotDiff::Snapshot, basefile: 'test', fullscreen_file: 'fullscrn_file',
                         capture_from_browser: true, diff_file: 'diff_file',
                         resave_fullscreen_file: true
    )
  end

  describe '#run' do
    it 'captures a screenshot from the browser' do
      expect(snapshot).to receive(:capture_from_browser).with(true).once
      described_class.run(snapshot, nil)
    end

    it 'checks if the basefile exists' do
      expect(File).to receive(:exist?).with(snapshot.basefile).and_return(false)
      described_class.run(snapshot, nil)
    end

    context 'when the basefile doesnt exist' do
      subject { described_class.run(snapshot, nil) }

      it 'returns true' do
        expect(File).to receive(:exist?).with(snapshot.basefile).and_return(false)
        expect(subject).to eq [true, snapshot.basefile]
      end
    end

    context 'when the new and base image size are different' do
      let(:container) do
        instance_double(DotDiff::Image::Container,
                        total_pixels: 2_073_600,
                        both_images_same_dimensions?: false,
                        dimensions_mismatch_msg: 'Some dimensions mismatch')
      end

      before do
        expect(File).to receive(:exist?).with(snapshot.basefile).and_return(true)
        expect(DotDiff::Image::Container).to receive(:new)
          .with(snapshot.basefile, 'fullscrn_file').and_return(container)
      end

      it 'returns false with a message' do
        expect(described_class.run(snapshot, nil)).to eq [false, 'Some dimensions mismatch']
      end
    end

    context 'when the basefile exists' do
      let(:container) do
        instance_double(DotDiff::Image::Container,
                        total_pixels: 2_073_600,
                        both_images_same_dimensions?: true)
      end

      subject { described_class.run(snapshot, nil) }

      before do
        expect(DotDiff::CommandWrapper).to receive(:new).and_return(command_wrapper)
        expect(command_wrapper).to receive(:run).with('test', 'fullscrn_file', 'diff_file').and_return(nil)
        expect(File).to receive(:exist?).with(snapshot.basefile).and_return(true)
        expect(DotDiff::Image::Container).to receive(:new)
          .with(snapshot.basefile, 'fullscrn_file').and_return(container)
      end

      context 'and the command fails to return pixels' do
        let(:command_wrapper) do
          instance_double(DotDiff::CommandWrapper, passed?: false, failed?: true, message: 'Some failure')
        end

        it 'returns false and the error message' do
          expect(subject).to eq [false, 'Some failure']
        end
      end

      context 'and the command succeeds' do
        let(:command_wrapper) do
          instance_double(DotDiff::CommandWrapper, pixels: 321.0, passed?: true, failed?: false, message: '321')
        end

        context 'when pixels under threshold' do
          let(:calc) do
            instance_double(DotDiff::ThresholdCalculator, message: 'Some msg', under_threshold?: true)
          end

          before do
            expect(DotDiff).to receive(:pixel_threshold).and_return(322)
            expect(DotDiff::ThresholdCalculator).to receive(:new).with(322, 2_073_600, 321.0).and_return(calc)
          end

          it 'returns true' do
            expect(subject).to eq [true, 'Some msg']
          end
        end

        context 'when pixels over threshold' do
          let(:calc) do
            instance_double(DotDiff::ThresholdCalculator, message: 'Some msg', under_threshold?: false)
          end

          before do
            expect(DotDiff).to receive(:pixel_threshold).and_return(320)
            expect(DotDiff::ThresholdCalculator).to receive(:new).with(320, 2_073_600, 321.0).and_return(calc)
          end

          it 'returns false' do
            expect(subject).to eq [false, 'Some msg']
          end
        end
      end
    end
  end

  describe '#new_image_path' do
    subject { described_class.new(snapshot, nil) }

    it 'returns cropped file path' do
      expect(subject.new_image_path).to eq 'fullscrn_file'
    end
  end
end


text:
using namespace libzerocoin;

std::map<uint32_t, CBigNum> mapAccumulatorValues;
std::list<uint256> listAccCheckpointsNoDB;

uint32_t ParseChecksum(uint256 nChecksum, CoinDenomination denomination)
{
    //shift to the beginning bit of this denomination and trim any remaining bits by returning 32 bits only
    int pos = distance(zerocoinDenomList.begin(), find(zerocoinDenomList.begin(), zerocoinDenomList.end(), denomination));
    nChecksum = nChecksum >> (32*((zerocoinDenomList.size() - 1) - pos));
    return nChecksum.Get32();
}

uint32_t GetChecksum(const CBigNum &bnValue)
{
    CDataStream ss(SER_GETHASH, 0);
    ss << bnValue;
    uint256 hash = Hash(ss.begin(), ss.end());

    return hash.Get32();
}

bool GetAccumulatorValueFromChecksum(uint32_t nChecksum, bool fMemoryOnly, CBigNum& bnAccValue)
{
    if (mapAccumulatorValues.count(nChecksum)) {
        bnAccValue = mapAccumulatorValues.at(nChecksum);
        return true;
    }

    if (fMemoryOnly)
        return false;

    if (!zerocoinDB->ReadAccumulatorValue(nChecksum, bnAccValue)) {
        bnAccValue = 0;
    }

    return true;
}

bool GetAccumulatorValueFromDB(uint256 nCheckpoint, CoinDenomination denom, CBigNum& bnAccValue)
{
    uint32_t nChecksum = ParseChecksum(nCheckpoint, denom);
    return GetAccumulatorValueFromChecksum(nChecksum, false, bnAccValue);
}

void AddAccumulatorChecksum(const uint32_t nChecksum, const CBigNum &bnValue, bool fMemoryOnly)
{
    if(!fMemoryOnly)
        zerocoinDB->WriteAccumulatorValue(nChecksum, bnValue);
    mapAccumulatorValues.insert(make_pair(nChecksum, bnValue));
}

void DatabaseChecksums(AccumulatorMap& mapAccumulators)
{
    uint256 nCheckpoint = 0;
    for (auto& denom : zerocoinDenomList) {
        CBigNum bnValue = mapAccumulators.GetValue(denom);
        uint32_t nCheckSum = GetChecksum(bnValue);
        AddAccumulatorChecksum(nCheckSum, bnValue, false);
        nCheckpoint = nCheckpoint << 32 | nCheckSum;
    }
}

bool EraseChecksum(uint32_t nChecksum)
{
    //erase from both memory and database
    mapAccumulatorValues.erase(nChecksum);
    return zerocoinDB->EraseAccumulatorValue(nChecksum);
}

bool EraseAccumulatorValues(const uint256& nCheckpointErase, const uint256& nCheckpointPrevious)
{
    for (auto& denomination : zerocoinDenomList) {
        uint32_t nChecksumErase = ParseChecksum(nCheckpointErase, denomination);
        uint32_t nChecksumPrevious = ParseChecksum(nCheckpointPrevious, denomination);

        //if the previous checksum is the same, then it should remain in the database and map
        if(nChecksumErase == nChecksumPrevious)
            continue;

        if (!EraseChecksum(nChecksumErase))
            return false;
    }

    return true;
}

bool LoadAccumulatorValuesFromDB(const uint256 nCheckpoint)
{
    for (auto& denomination : zerocoinDenomList) {
        uint32_t nChecksum = ParseChecksum(nCheckpoint, denomination);

        //if read is not successful then we are not in a state to verify zerocoin transactions
        CBigNum bnValue;
        if (!zerocoinDB->ReadAccumulatorValue(nChecksum, bnValue)) {
            LogPrint("zero","%s : Missing databased value for checksum %d\n", __func__, nChecksum);
            if (!count(listAccCheckpointsNoDB.begin(), listAccCheckpointsNoDB.end(), nCheckpoint))
                listAccCheckpointsNoDB.push_back(nCheckpoint);
            return false;
        }
        mapAccumulatorValues.insert(make_pair(nChecksum, bnValue));
    }
    return true;
}

//Erase accumulator checkpoints for a certain block range
bool EraseCheckpoints(int nStartHeight, int nEndHeight)
{
    if (chainActive.Height() < nStartHeight)
        return false;

    nEndHeight = min(chainActive.Height(), nEndHeight);

    CBlockIndex* pindex = chainActive[nStartHeight];
    uint256 nCheckpointPrev = pindex->pprev->nAccumulatorCheckpoint;

    //Keep a list of checkpoints from the previous block so that we don't delete them
    list<uint32_t> listCheckpointsPrev;
    for (auto denom : zerocoinDenomList)
        listCheckpointsPrev.emplace_back(ParseChecksum(nCheckpointPrev, denom));

    while (true) {
        uint256 nCheckpointDelete = pindex->nAccumulatorCheckpoint;

        for (auto denom : zerocoinDenomList) {
            uint32_t nChecksumDelete = ParseChecksum(nCheckpointDelete, denom);
            if (count(listCheckpointsPrev.begin(), listCheckpointsPrev.end(), nCheckpointDelete))
                continue;
            EraseChecksum(nChecksumDelete);
        }
        LogPrintf("%s : erasing checksums for block %d\n", __func__, pindex->nHeight);

        if (pindex->nHeight + 1 <= nEndHeight)
            pindex = chainActive.Next(pindex);
        else
            break;
    }

    return true;
}

//Get checkpoint value for a specific block height
bool CalculateAccumulatorCheckpoint(int nHeight, uint256& nCheckpoint)
{
    if (nHeight < Params().Zerocoin_StartHeight()) {
        nCheckpoint = 0;
        return true;
    }

    //the checkpoint is updated every ten blocks, return current active checkpoint if not update block
    if (nHeight % 10 != 0) {
        nCheckpoint = chainActive[nHeight - 1]->nAccumulatorCheckpoint;
        return true;
    }

    //set the accumulators to last checkpoint value
    AccumulatorMap mapAccumulators;
    if (!mapAccumulators.Load(chainActive[nHeight - 1]->nAccumulatorCheckpoint)) {
        if (chainActive[nHeight - 1]->nAccumulatorCheckpoint == 0) {
            //Before zerocoin is fully activated so set to init state
            mapAccumulators.Reset();
        } else {
            LogPrintf("%s: failed to reset to previous checkpoint\n", __func__);
            return false;
        }
    }

    //Whether this should filter out invalid/fraudulent outpoints
    bool fFilterInvalid = nHeight >= Params().Zerocoin_Block_RecalculateAccumulators();

    //Accumulate all coins over the last ten blocks that havent been accumulated (height - 20 through height - 11)
    int nTotalMintsFound = 0;
    CBlockIndex *pindex = chainActive[nHeight - 20];

    //On a specific block, a recalculation of the accumulators will be forced
    if (nHeight == Params().Zerocoin_Block_RecalculateAccumulators()) {
        pindex = chainActive[Params().Zerocoin_Block_LastGoodCheckpoint() - 10];
        mapAccumulators.Reset();
        if (!mapAccumulators.Load(chainActive[Params().Zerocoin_Block_LastGoodCheckpoint()]->nAccumulatorCheckpoint)) {
            LogPrintf("%s: failed to reset to previous checkpoint when recalculating accumulators\n", __func__);
            return false;
        }
        LogPrintf("*** %s recalculating checkpoint\n", __func__);

        // Erase the checkpoints from the period of time that bad mints were being made
        if (!EraseCheckpoints(Params().Zerocoin_Block_LastGoodCheckpoint() + 1, nHeight)) {
            LogPrintf("%s : failed to erase Checkpoints while recalculating checkpoints\n", __func__);
            return false;
        }
    }

    while (pindex->nHeight < nHeight - 10) {
        // checking whether we should stop this process due to a shutdown request
        if (ShutdownRequested()) {
            return false;
        }

        //make sure this block is eligible for accumulation
        if (pindex->nHeight < Params().Zerocoin_StartHeight()) {
            pindex = chainActive[pindex->nHeight + 1];
            continue;
        }

        //grab mints from this block
        CBlock block;
        if(!ReadBlockFromDisk(block, pindex)) {
            LogPrint("zero","%s: failed to read block from disk\n", __func__);
            return false;
        }

        std::list<PublicCoin> listPubcoins;
        if (!BlockToPubcoinList(block, listPubcoins, fFilterInvalid)) {
            LogPrint("zero","%s: failed to get zerocoin mintlist from block %n\n", __func__, pindex->nHeight);
            return false;
        }

        nTotalMintsFound += listPubcoins.size();
        LogPrint("zero", "%s found %d mints\n", __func__, listPubcoins.size());

        //add the pubcoins to accumulator
        for (const PublicCoin pubcoin : listPubcoins) {
            if(!mapAccumulators.Accumulate(pubcoin, true)) {
                LogPrintf("%s: failed to add pubcoin to accumulator at height %n\n", __func__, pindex->nHeight);
                return false;
            }
        }
        pindex = chainActive.Next(pindex);
    }

    // if there were no new mints found, the accumulator checkpoint will be the same as the last checkpoint
    if (nTotalMintsFound == 0) {
        nCheckpoint = chainActive[nHeight - 1]->nAccumulatorCheckpoint;
    }
    else
        nCheckpoint = mapAccumulators.GetCheckpoint();

    // make sure that these values are databased because reorgs may have deleted the checksums from DB
    DatabaseChecksums(mapAccumulators);

    LogPrint("zero", "%s checkpoint=%s\n", __func__, nCheckpoint.GetHex());
    return true;
}

bool InvalidCheckpointRange(int nHeight)
{
    return nHeight > Params().Zerocoin_Block_LastGoodCheckpoint() && nHeight < Params().Zerocoin_Block_RecalculateAccumulators();
}

bool GenerateAccumulatorWitness(const PublicCoin &coin, Accumulator& accumulator, AccumulatorWitness& witness, int nSecurityLevel, int& nMintsAdded, string& strError)
{
    uint256 txid;
    if (!zerocoinDB->ReadCoinMint(coin.getValue(), txid)) {
        LogPrint("zero","%s failed to read mint from db\n", __func__);
        return false;
    }

    CTransaction txMinted;
    uint256 hashBlock;
    if (!GetTransaction(txid, txMinted, hashBlock)) {
        LogPrint("zero","%s failed to read tx\n", __func__);
        return false;
    }

    int nHeightMintAdded= mapBlockIndex[hashBlock]->nHeight;
    uint256 nCheckpointBeforeMint = 0;
    CBlockIndex* pindex = chainActive[nHeightMintAdded];
    int nChanges = 0;

    //find the checksum when this was added to the accumulator officially, which will be two checksum changes later
    //reminder that checksums are generated when the block height is a multiple of 10
    while (pindex->nHeight < chainActive.Tip()->nHeight - 1) {
        if (pindex->nHeight == nHeightMintAdded) {
            pindex = chainActive[pindex->nHeight + 1];
            continue;
        }

        //check if the next checksum was generated
        if (pindex->nHeight % 10 == 0) {
            nChanges++;

            if (nChanges == 1) {
                nCheckpointBeforeMint = pindex->nAccumulatorCheckpoint;
                break;
            }
        }
        pindex = chainActive.Next(pindex);
    }

    //the height to start accumulating coins to add to witness
    int nAccStartHeight = nHeightMintAdded - (nHeightMintAdded % 10);

    //If the checkpoint is from the recalculated checkpoint period, then adjust it
    int nHeight_LastGoodCheckpoint = Params().Zerocoin_Block_LastGoodCheckpoint();
    int nHeight_Recalculate = Params().Zerocoin_Block_RecalculateAccumulators();
    if (pindex->nHeight < nHeight_Recalculate - 10 && pindex->nHeight > nHeight_LastGoodCheckpoint) {
        //The checkpoint before the mint will be the last good checkpoint
        nCheckpointBeforeMint = chainActive[nHeight_LastGoodCheckpoint]->nAccumulatorCheckpoint;
        nAccStartHeight = nHeight_LastGoodCheckpoint - 10;
    }

    //Get the accumulator that is right before the cluster of blocks containing our mint was added to the accumulator
    CBigNum bnAccValue = 0;
    if (GetAccumulatorValueFromDB(nCheckpointBeforeMint, coin.getDenomination(), bnAccValue)) {
        if (bnAccValue > 0) {
            accumulator.setValue(bnAccValue);
            witness.resetValue(accumulator, coin);
        }
    }

    //security level: this is an important prevention of tracing the coins via timing. Security level represents how many checkpoints
    //of accumulated coins are added *beyond* the checkpoint that the mint being spent was added too. If each spend added the exact same
    //amounts of checkpoints after the mint was accumulated, then you could know the range of blocks that the mint originated from.
    if (nSecurityLevel < 100) {
        //add some randomness to the user's selection so that it is not always the same
        nSecurityLevel += CBigNum::randBignum(10).getint();

        //security level 100 represents adding all available coins that have been accumulated - user did not select this
        if (nSecurityLevel >= 100)
            nSecurityLevel = 99;
    }

    //add the pubcoins (zerocoinmints that have been published to the chain) up to the next checksum starting from the block
    pindex = chainActive[nAccStartHeight];
    int nChainHeight = chainActive.Height();
    int nHeightStop = nChainHeight % 10;
    nHeightStop = nChainHeight - nHeightStop - 20; // at least two checkpoints deep
    int nCheckpointsAdded = 0;
    nMintsAdded = 0;
    while (pindex->nHeight < nHeightStop + 1) {
        if (pindex->nHeight != nAccStartHeight && pindex->pprev->nAccumulatorCheckpoint != pindex->nAccumulatorCheckpoint)
            ++nCheckpointsAdded;

        //if a new checkpoint was generated on this block, and we have added the specified amount of checkpointed accumulators,
        //then initialize the accumulator at this point and break
        if (!InvalidCheckpointRange(pindex->nHeight) && (pindex->nHeight >= nHeightStop || (nSecurityLevel != 100 && nCheckpointsAdded >= nSecurityLevel))) {
            uint32_t nChecksum = ParseChecksum(chainActive[pindex->nHeight + 10]->nAccumulatorCheckpoint, coin.getDenomination());
            CBigNum bnAccValue = 0;
            if (!zerocoinDB->ReadAccumulatorValue(nChecksum, bnAccValue)) {
                LogPrintf("%s : failed to find checksum in database for accumulator\n", __func__);
                return false;
            }
            accumulator.setValue(bnAccValue);
            break;
        }

        // if this block contains mints of the denomination that is being spent, then add them to the witness
        if (pindex->MintedDenomination(coin.getDenomination())) {
            //grab mints from this block
            CBlock block;
            if(!ReadBlockFromDisk(block, pindex)) {
                LogPrintf("%s: failed to read block from disk while adding pubcoins to witness\n", __func__);
                return false;
            }

            list<PublicCoin> listPubcoins;
            if(!BlockToPubcoinList(block, listPubcoins, true)) {
                LogPrintf("%s: failed to get zerocoin mintlist from block %n\n", __func__, pindex->nHeight);
                return false;
            }

            //add the mints to the witness
            for (const PublicCoin pubcoin : listPubcoins) {
                if (pubcoin.getDenomination() != coin.getDenomination())
                    continue;

                if (pindex->nHeight == nHeightMintAdded && pubcoin.getValue() == coin.getValue())
                    continue;

                witness.addRawValue(pubcoin.getValue());
                ++nMintsAdded;
            }
        }

        pindex = chainActive[pindex->nHeight + 1];
    }

    if (nMintsAdded < Params().Zerocoin_RequiredAccumulation()) {
        strError = _(strprintf("Less than %d mints added, unable to create spend", Params().Zerocoin_RequiredAccumulation()).c_str());
        LogPrintf("%s : %s\n", __func__, strError);
        return false;
    }

    // calculate how many mints of this denomination existed in the accumulator we initialized
    int nZerocoinStartHeight = GetZerocoinStartHeight();
    pindex = chainActive[nZerocoinStartHeight];
    while (pindex->nHeight < nAccStartHeight) {
        nMintsAdded += count(pindex->vMintDenominationsInBlock.begin(), pindex->vMintDenominationsInBlock.end(), coin.getDenomination());
        pindex = chainActive[pindex->nHeight + 1];
    }

    LogPrint("zero","%s : %d mints added to witness\n", __func__, nMintsAdded);
    return true;
}


text:
require File.expand_path(File.join(File.dirname(__FILE__), *%w[.. validator]))

# TODO: Would be "cool" if each format rule was save as a JS var,
# and referenced with class Validatious style:
#
#   <head>:
#     var ssn-se = /^\d{6}-{4}$/;
#     <<< format validator here >>>
#   <body>:
#     <input type="text" class="format-with_ssn-se" ... />
#
# Same for inclusion/exclusion too. Easy to implement, but low prio.
#
module ValidatiousOnRails
  module Validatious
    class FormatValidator < ClientSideValidator

      def initialize(validation, options = {})
        name, alias_name = self.class.generate_name(validation, :with, self.class.generate_id(validation.options[:with].inspect))
        super name, options
        self.message = self.class.generate_message(validation)
        self.accept_empty = validation.options[:allow_nil]
        self.fn = %{
          #{self.class.validate_blank(validation)}
          return #{validation.options[:with].inspect.gsub(/\\A/,'^').gsub(/\\z/,'$')}.test(value);
        }
        self.fn.freeze
      end

    end
  end
end


text:
<?php

namespace spec\Sylius\Bundle\ProductBundle\Form\Type;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class ProductTypeSpec extends ObjectBehavior
{
    function let()
    {
        $this->beConstructedWith('Product', array('sylius'));
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Bundle\ProductBundle\Form\Type\ProductType');
    }

    function it_is_a_form_type()
    {
        $this->shouldImplement('Symfony\Component\Form\FormTypeInterface');
    }

    function it_builds_form_with_proper_fields(FormBuilder $builder)
    {
        $builder
            ->add(Argument::cetera())
            ->willReturn($builder)
        ;

        $builder
            ->add('masterVariant', 'sylius_product_variant', Argument::any())
            ->willReturn($builder)
        ;

        $builder
            ->add('name', 'text', Argument::any())
            ->willReturn($builder)
        ;

        $builder
            ->add('description', 'textarea', Argument::any())
            ->willReturn($builder)
        ;

        $builder
            ->add('attributes', 'collection', Argument::any())
            ->willReturn($builder)
        ;

        $builder
            ->add('options', 'sylius_product_option_choice', Argument::any())
            ->willReturn($builder)
        ;

        $builder
            ->add('associations', 'collection', Argument::withEntry('type', 'sylius_product_association'))
            ->willReturn($builder)
        ;

        $builder
            ->add('metaKeywords', 'text', Argument::any())
            ->willReturn($builder)
        ;

        $builder
            ->add('metaDescription', 'text', Argument::any())
            ->willReturn($builder)
        ;

        $this->buildForm($builder, array());
    }

    function it_defines_assigned_data_class(OptionsResolverInterface $resolver)
    {
        $resolver
            ->setDefaults(array(
                'data_class' => 'Product',
                'validation_groups' => array('sylius')
            ))
            ->shouldBeCalled();

        $this->setDefaultOptions($resolver);
    }

    function it_has_valid_name()
    {
        $this->getName()->shouldReturn('sylius_product');
    }
}


text:
import Vue from 'vue'
import HomePage from 'src/components/HomePage'

describe('HomePage.vue', () => {
  it('should render correct contents', () => {
    const vm = new Vue({
      el: document.createElement('div'),
      render: (h) => h(HomePage)
    })
    expect(vm.$el.querySelector('.home h1').textContent)
      .to.equal('groupwrite.io')
  })
})


text:
package org.kuali.coeus.sys.framework.validation;

import java.io.Serializable;
import java.util.Arrays;

/**
 * This class is used to report a soft error (i.e. a warning)
 */
public class SoftError implements Serializable {
    private static final long serialVersionUID = 4044942237931712580L;

    private String errorKey;
    private String[] errorParms;

    /**
     * Constructs a SoftError
     * @param errorkey
     * @param errorParms
     */
    public SoftError(String errorkey, String[] errorParms) {
        this.errorKey = errorkey;
        this.errorParms = errorParms;
    }

    /**
     * Gets the errorKey attribute.
     * @return Returns the errorKey.
     */
    public String getErrorKey() {
        return errorKey;
    }

    /**
     * Gets the errorParms attribute.
     * @return Returns the errorParms.
     */
    public String[] getErrorParms() {
        return errorParms;
    }

    @Override
    public int hashCode() {
        final int PRIME = 31;
        int result = 1;
        result = PRIME * result + ((errorKey == null) ? 0 : errorKey.hashCode());
        result = PRIME * result + Arrays.hashCode(errorParms);
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof SoftError)) {
            return false;
        }
        SoftError other = (SoftError) obj;
        if (errorKey == null) {
            if (other.errorKey != null) {
                return false;
            }
        } else if (!errorKey.equals(other.errorKey)) {
            return false;
        }
        if (!Arrays.equals(errorParms, other.errorParms)) {
            return false;
        }
        return true;
    }

}


text:
package com.evolveum.midpoint.web.page.admin.workflow;

import com.evolveum.midpoint.security.api.AuthorizationConstants;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.application.AuthorizationAction;
import com.evolveum.midpoint.web.application.PageDescriptor;
import com.evolveum.midpoint.web.application.Url;
import com.evolveum.midpoint.web.util.OnePageParameterEncoder;

/**
 * Created by Viliam Repan (lazyman).
 */
@PageDescriptor(
        urls = {
                @Url(mountUrl = "/admin/workItemsAttorney")
        },
        encoder = OnePageParameterEncoder.class,
        action = {
                @AuthorizationAction(actionUri = PageAdminWorkItems.AUTH_APPROVALS_ALL,
                        label = PageAdminWorkItems.AUTH_APPROVALS_ALL_LABEL,
                        description = PageAdminWorkItems.AUTH_APPROVALS_ALL_DESCRIPTION),
                @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_ATTORNEY_WORK_ITEMS_URL,
                        label = "PageAttorneySelection.auth.workItems.attorney.label",
                        description = "PageAttorneySelection.auth.workItems.attorney.description")
        })
public class PageWorkItemsAttorney extends PageWorkItems {

    private static final Trace LOGGER = TraceManager.getTrace(PageWorkItemsAttorney.class);

    private static final String DOT_CLASS = PageWorkItems.class.getName() + ".";

    public PageWorkItemsAttorney() {
        super(WorkItemsPageType.ATTORNEY);
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.resources.generated;

import com.azure.core.util.Context;

/** Samples for Features Unregister. */
public final class FeaturesUnregisterSamples {
    /*
     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Features/stable/2021-07-01/examples/unregisterFeature.json
     */
    /**
     * Sample code: Register feature.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void registerFeature(com.azure.resourcemanager.AzureResourceManager azure) {
        azure
            .genericResources()
            .manager()
            .featureClient()
            .getFeatures()
            .unregisterWithResponse("Resource Provider Namespace", "feature", Context.NONE);
    }
}