text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Joomla! Pizza, Bugs and Fun Frankfurt - Bloggerschmidt</title>

    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta name="description" content="">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="Joomla! Pizza, Bugs and Fun Frankfurt">
    <meta name="twitter:description" content="">

    <meta property="og:type" content="article">
    <meta property="og:title" content="Joomla! Pizza, Bugs and Fun Frankfurt">
    <meta property="og:description" content="">

    <link href="/favicon.ico" rel="shortcut icon" type="image/x-icon">
    <link href="/apple-touch-icon-precomposed.png" rel="apple-touch-icon">

    <link rel="stylesheet" type="text/css" href="//bloggerschmidt.de/themes/bloggerschmidt/assets/css/uno.css?v=1.0.0" />

    <link rel="canonical" href="http://bloggerschmidt.de/2015/02/24/Joomla-Pizza-Bugs-and-Fun-Frankfurt.html" />

    <meta property="og:site_name" content="Bloggerschmidt" />
    <meta property="og:type" content="article" />
    <meta property="og:title" content="Joomla! Pizza, Bugs and Fun Frankfurt" />
    <meta property="og:description" content="Das Joomla!-Projekt wird dieses Jahr 10 Jahre alt - und von Beginn an wurde das CMS ausschließlich von ehrenamtlichen Community-Mitgliedern entwickelt, die alle gemeinsam am selben Strang ziehen, um Joomla weiterzuentwickeln. Es gibt jedoch einen sehr elementaren Bereich, in..." />
    <meta property="og:url" content="http://bloggerschmidt.de/2015/02/24/Joomla-Pizza-Bugs-and-Fun-Frankfurt.html" />
    <meta property="article:published_time" content="2015-02-23T23:00:00.000Z" />
    <meta property="article:modified_time" content="2015-06-09T06:24:31.382Z" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Joomla! Pizza, Bugs and Fun Frankfurt" />
    <meta name="twitter:description" content="Das Joomla!-Projekt wird dieses Jahr 10 Jahre alt - und von Beginn an wurde das CMS ausschließlich von ehrenamtlichen Community-Mitgliedern entwickelt, die alle gemeinsam am selben Strang ziehen, um Joomla weiterzuentwickeln. Es gibt jedoch einen sehr elementaren Bereich, in..." />
    <meta name="twitter:url" content="http://bloggerschmidt.de/2015/02/24/Joomla-Pizza-Bugs-and-Fun-Frankfurt.html" />

    <meta name="generator" content="Ghost ?" />
    <link rel="alternate" type="application/rss+xml" title="Bloggerschmidt" href="http://bloggerschmidt.de/rss" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

Bloggerschmidt

Hier schreibt Alexander Schmidt, Webentwickler und CSS Guru

Blog

                      Twitter

                      Github

                      Email

        <time datetime="24.02.2015" class="post-meta__date date">24.02.2015</time> •
         von Alexander Schmidt

Joomla! Pizza, Bugs and Fun Frankfurt

Das Joomla!-Projekt wird dieses Jahr 10 Jahre alt - und von Beginn an wurde das CMS ausschließlich von ehrenamtlichen Community-Mitgliedern entwickelt, die alle gemeinsam am selben Strang ziehen, um Joomla weiterzuentwickeln. Es gibt jedoch einen sehr elementaren Bereich, in dem das Joomla-Projekt akute Unterstützung benötigt: das Bug-Squad Team. Dieses Team, kümmert sich darum:

in Joomla gefundene Fehler (im englischen "Bugs" genannt) zu melden

für die gemeldeten Fehler eine Fehlerbehebung, Patch genannt, zu schreiben

diese Patches zu testen

und den getesteten Patch in den Joomla-Kern einzubauen

Insbesondere der dritte Schritt, das Testen von Fehlerbehebungen, stellt aktuell einen Flaschenhals im Projekt dar. Weit über 100 Fehlerbehebungen können derzeit nicht in den Joomla-Kern einfließen, weil sich nicht genügend Freiwillige finden, die ein paar Minuten Zeit investieren und ausprobieren, ob der Patch funktioniert.

Um diese Situation zu verbessern, findet am 14.03.15 von 10:00 bis 17:00 Uhr das erste deutschsprachige "Pizza, Bugs and Fun"-Event statt. An diesem Tag möchten wir (der deutsche Joomla Verein) alle Joomla-begeisterten Nutzer, gleich mit welchem Vorkenntnissen, dazu einladen

zu lernen wie der Prozess der Fehlerbehebung bei Joomla funktioniert

zu lernen, wie man eine Fehlerbehebung testen kann

und dann zusammen an diesem Tag so viele Patches wie möglich zu testen

Wir möchten also eine Einführung geben, die Angst nehmen und an diesem Tag einen zählbaren Beitrag zum Joomla-Core erbringen.

Dafür wird es in ganz Deutschland, der Schweiz und Österreich lokale Treffen geben, die von den jeweiligen Joomla! Usergroups - in FFM also logischerweise von uns - ausgerichtet werden. Das einzige, was ihr mitbringen müsst, ist ein wenig Zeit, Neugier und einen Computer, um tatsächlich auch tätig werden zu können!

Solltet ihr mitmachen wollen, so meldet euch bitte hier an (siehe unten) - diese Angabe ist nötig, damit wir die Verpflegung für den Tag (dank zweier Sponsoren gibt es eine Runde Pizza und Getränke für alle Teilnehmer) planen können.

Treffpunkt wird NICHT im Goldstein sein, stattdessen hat sich Firma Hoesch & Partner GmbH dazu bereit erklärt, uns einen Konfi zur Verfügung zu stellen. Treffpunkt ist daher am 14.03.15, 10:00 Uhr hier:

Hoesch & Partner GmbH

Zentrale Frankfurt

Rüsterstraße 1

60325 Frankfurt

Anfahrt

Weitere Infos / Konferenzraum

Online event registration for Joomla! Pizza, Bugs and Fun Frankfurt powered by Eventbrite

    Bitte JavaScript aktivieren, um die Kommentare von Disqus zu lesen.

                Copyright © 2015 Alexander Schmidt. Alle Rechte vorbehalten.


text:
namespace Boxed.Mapping.Benchmark
{
    using System;
    using System.Globalization;
    using AutoMapper;
    using BenchmarkDotNet.Attributes;
    using BenchmarkDotNet.Jobs;
    using Boxed.Mapping.Benchmark.Mapping;
    using Boxed.Mapping.Benchmark.Models;

    [KeepBenchmarkFiles]
    [MemoryDiagnoser]
    [MinColumn]
    [MaxColumn]
    [HtmlExporter]
    [CsvMeasurementsExporter]
    [RPlotExporter]
    [SimpleJob(RuntimeMoniker.Net472)]
    [SimpleJob(RuntimeMoniker.NetCoreApp30)]
    public class MapArrayBenchmark
    {
        private readonly IMapper automapper;
        private readonly IMapper<MapFrom, MapTo> boilerplateMapper;
        private readonly Random random;
        private MapFrom[] mapFrom;

        public MapArrayBenchmark()
        {
            this.automapper = AutomapperConfiguration.CreateMapper();
            this.boilerplateMapper = new BoxedMapper();
            this.random = new Random();
        }

        [GlobalSetup]
        public void GlobalSetup()
        {
            this.mapFrom = new MapFrom[100];
            for (var i = 0; i < this.mapFrom.Length; ++i)
            {
                this.mapFrom[i] = new MapFrom()
                {
                    BooleanFrom = this.random.NextDouble() > 0.5D,
                    DateTimeOffsetFrom = DateTimeOffset.UtcNow,
                    IntegerFrom = this.random.Next(),
                    LongFrom = this.random.Next(),
                    StringFrom = this.random.Next().ToString(CultureInfo.InvariantCulture),
                };
            }
        }

        [Benchmark(Baseline = true)]
        public MapTo[] Baseline()
        {
            var destination = new MapTo[this.mapFrom.Length];
            for (var i = 0; i < this.mapFrom.Length; ++i)
            {
                var item = this.mapFrom[i];
                destination[i] = new MapTo()
                {
                    BooleanTo = item.BooleanFrom,
                    DateTimeOffsetTo = item.DateTimeOffsetFrom,
                    IntegerTo = item.IntegerFrom,
                    LongTo = item.LongFrom,
                    StringTo = item.StringFrom,
                };
            }

            return destination;
        }

        [Benchmark]
        public MapTo[] BoxedMapper() => this.boilerplateMapper.MapArray(this.mapFrom);

        [Benchmark]
        public MapTo[] Automapper() => this.automapper.Map<MapTo[]>(this.mapFrom);
    }
}

redpajama_set_name: RedPajamaGithub


text:
${HADOOP_HOME}/sbin/stop-dfs.sh
${HADOOP_HOME}/sbin/stop-yarn.sh
${HADOOP_HOME}/sbin/stop-all.sh

# clear data directories
mkdir -p /usr/local/hdfs/namenode/
mkdir -p /usr/local/hdfs/datanode/
rm -fr /usr/local/hdfs/namenode/*
rm -fr /usr/local/hdfs/datanode/*

# remove related logs
rm -fr ${HADOOP_HOME}/logs/*

# hdfs format
${HADOOP_HOME}/bin/hdfs namenode -format

# restart hdfs
${HADOOP_HOME}/sbin/start-dfs.sh

# restart yarn
${HADOOP_HOME}/sbin/start-yarn.sh

# restart spark
${SPARK_HOME}/sbin/start-all.sh


text:
id: node
title: Node
---

Run your test in a [Node](https://nodejs.org) environment with great developer workflow. Just start the runner with

```
npx aw -c ./path/to/aw.config.js -w --coverage
```

and start testing. It will only rerun affected tests and generate coverage accordingly.
Add files, remove files as you go and change your tests to rapidly build up a test coverage.

## Mocking

Built-in mocking. You can mock globally via the [**mocks**](#mocks) option or locally by using:

```javascript
const span = <span>my span</span>;
const [{ default: FancyButton }] = aw.mock(
  [
    // Mock components
    ['**/react/src/button.js', () => () => span]
  ],
  // Require components
  ['../src/fancy-button']
);
```

Look at the React [example](https://github.com/qlik-oss/after-work.js/tree/master/examples/react) for more details.

> If you are using `coverage` ensure you are only calling `aw.mock` in module scope or in a `before` function. If not, it will be instrumented multiple times and the last instrumentation wins, which will lead to incorrect coverage results. For example:

```javascript
import foo from 'foo';

const span = <span>my span</span>;

// Module scope 👍
const [{ default: FancyButton }] = aw.mock(
  [
    // Mock components
    [require.resolve('../src/fancy-button.js'), () => () => span]
  ],
  // Require components
  ['../src/fancy-button']
);

describe(() => {
  it('should calculate correct coverage', () => {});
});
```

or

```javascript
import foo from 'foo';

const span = <span>my span</span>;

describe(() => {
  let FancyButton;
  before(() => {
    // In before 👍
    const [{ default: FancyButton }] = aw.mock(
    [
      // Mock components
      [require.resolve('../src/fancy-button.js'), () => () => span]
    ],
    // Require components
    ['../src/fancy-button']
);

  });
  it('should calculate correct coverage', () => {});
});
```

## Snapshot Testing

We are using the awesome 📸 [**jest-snapshot**](https://github.com/facebook/jest/tree/master/packages/jest-snapshot) package.

Example

```javascript
import React from 'react';
import renderer from 'react-test-renderer';
import 'foo.scss';
import 'bar.less';
import 'baz.css';
import Button from '../src/button';

describe('button', () => {
  it('renders correctly', () => {
    const tree = renderer.create(<Button>Text</Button>).toJSON();
    expect(tree).toMatchSnapshot();
    const tree1 = renderer.create(<Button>Text1</Button>).toJSON();
    expect(tree1).toMatchSnapshot();
  });
  it('renders fancy', () => {
    const tree1 = renderer.create(<Button>fancy1</Button>).toJSON();
    expect(tree1).toMatchSnapshot();
  });
});
```

## Screenshot testing

When using the preset-env option. A screenshot assertion plugin is added to Chai. This allows comparisons of images.

Example

```javascript
describe('screenshot', () => {
  it('image should be equal', async () => {
    const img = Promise.resolve('<base64-encoded-image>'); //  Promise that resolves to Buffer or a base64 encoded image
    await expect(img).to.matchImageOf('<name-of-my-img-on-disk>', {
      artifactsPath: 'tests/__artifacts__',
      tolerance: 0.002
    });
  });
});
```


text:
package com.alibaba.json.bvt.bug;

import com.alibaba.fastjson.JSON;

import junit.framework.TestCase;

public class Bug_for_Double2Tag extends TestCase {
	public void test_double() throws Exception {
		Double2Tag tag = new Double2Tag();
		String str = JSON.toJSONString(tag);
		JSON.parseObject(str, Double2Tag.class);
	}

	public static class Double2Tag {
		public String data_time;
		public String data_id;
		public String hour_id;
		public String minute_id;
		public String tag3_id;
		public double ali_fee;
		public double total_ali_fee;
		public long seller_cnt;

		public Double2Tag() {
			ali_fee = 0.0;
			total_ali_fee = 0.0;
			seller_cnt = 0;
		}

		public String getData_time() {
			return data_time;
		}

		public void setData_time(String data_time) {
			this.data_time = data_time;
		}

		public String getData_id() {
			return data_id;
		}

		public void setData_id(String data_id) {
			this.data_id = data_id;
		}

		public String getHour_id() {
			return hour_id;
		}

		public void setHour_id(String hour_id) {
			this.hour_id = hour_id;
		}

		public String getMinute_id() {
			return minute_id;
		}

		public void setMinute_id(String minute_id) {
			this.minute_id = minute_id;
		}

		public String getTag3_id() {
			return tag3_id;
		}

		public void setTag3_id(String tag3_id) {
			this.tag3_id = tag3_id;
		}

		public double getAli_fee() {
			return ali_fee;
		}

		public void setAli_fee(double ali_fee) {
			this.ali_fee = ali_fee;
		}

		public double getTotal_ali_fee() {
			return total_ali_fee;
		}

		public void setTotal_ali_fee(double total_ali_fee) {
			this.total_ali_fee = total_ali_fee;
		}

		public long getSeller_cnt() {
			return seller_cnt;
		}

		public void setSeller_cnt(long seller_cnt) {
			this.seller_cnt = seller_cnt;
		}

	}
}


text:
package com.amazonaws.services.securityhub.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.securityhub.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * AwsEc2EipDetails JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AwsEc2EipDetailsJsonUnmarshaller implements Unmarshaller<AwsEc2EipDetails, JsonUnmarshallerContext> {

    public AwsEc2EipDetails unmarshall(JsonUnmarshallerContext context) throws Exception {
        AwsEc2EipDetails awsEc2EipDetails = new AwsEc2EipDetails();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("InstanceId", targetDepth)) {
                    context.nextToken();
                    awsEc2EipDetails.setInstanceId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("PublicIp", targetDepth)) {
                    context.nextToken();
                    awsEc2EipDetails.setPublicIp(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("AllocationId", targetDepth)) {
                    context.nextToken();
                    awsEc2EipDetails.setAllocationId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("AssociationId", targetDepth)) {
                    context.nextToken();
                    awsEc2EipDetails.setAssociationId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Domain", targetDepth)) {
                    context.nextToken();
                    awsEc2EipDetails.setDomain(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("PublicIpv4Pool", targetDepth)) {
                    context.nextToken();
                    awsEc2EipDetails.setPublicIpv4Pool(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("NetworkBorderGroup", targetDepth)) {
                    context.nextToken();
                    awsEc2EipDetails.setNetworkBorderGroup(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("NetworkInterfaceId", targetDepth)) {
                    context.nextToken();
                    awsEc2EipDetails.setNetworkInterfaceId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("NetworkInterfaceOwnerId", targetDepth)) {
                    context.nextToken();
                    awsEc2EipDetails.setNetworkInterfaceOwnerId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("PrivateIpAddress", targetDepth)) {
                    context.nextToken();
                    awsEc2EipDetails.setPrivateIpAddress(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return awsEc2EipDetails;
    }

    private static AwsEc2EipDetailsJsonUnmarshaller instance;

    public static AwsEc2EipDetailsJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new AwsEc2EipDetailsJsonUnmarshaller();
        return instance;
    }
}


text:
<?php
namespace AppBundle\Controller\Backend;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Csrf\CsrfToken;

/**
 * Prospect controller.
 *
 * @Route("/admin/user")
 */
class UserController extends Controller
{
    /**
     * Lists all User entities.
     *
     * @Route("/", name="user_index")
     * @Method("GET")
     * @Template(":Backend/User:index.html.twig")
     */
    public function indexAction()
    {
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
            throw $this->createAccessDeniedException('You cannot access this page!');
        }

        $em = $this->getDoctrine()->getManager();
        $users = $em->getRepository('AppBundle:User')->findAll();
        $totalUsers = $em->getRepository('AppBundle:User')->countUsers();

        $tokenManager = $this->get('security.csrf.token_manager');
        $csrf_token = $tokenManager->refreshToken('');

        return array(
            'users' => $users,
            'csrf_token' => $csrf_token,
            'totalUsers' => $totalUsers
        );
    }

    /**
     * Disable a user
     *
     * @Route("/{id}/ajax_disable", name="ajax_disable_user", options={"expose"=true})
     * @Method({"POST"})
     */
    public function disableAction(Request $request, $id)
    {
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
            throw $this->createAccessDeniedException('You cannot access this page!');
        }

        $data = $request->request->all();
        $token = $data['csrf_token'];

        $csrf = $this->get('security.csrf.token_manager');

        if ($csrf->isTokenValid(new CsrfToken('', $token))) {
            $em = $this->getDoctrine()->getManager();
            $user = $em->getRepository('AppBundle:User')->find($id);

            if (!$user) {
                throw $this->createNotFoundException('Unable to find User entity.');
            }

            $user->setEnabled(false);
            $em->flush();

            $response_array = array(
                "id" => $id,
                "username" => $user->getUsername(),
                "enabled" => $user->isEnabled(),
                "email" => $user->getEmail(),
                "gender" => $user->getGender(),
                "lastLogin" => $user->getLastLogin(),
                "createdAt" => $user->getCreatedAt(),
                "ip" => $user->getIp(),
                'csrf' => $token
            );

            $response = json_encode($response_array);

            return new Response($response);
        }
    }

    /**
     * Enable a user
     *
     * @Route("/{id}/ajax_enable", name="ajax_enable_user", options={"expose"=true})
     * @Method({"POST"})
     */
    public function enableAction(Request $request, $id)
    {
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
            throw $this->createAccessDeniedException('You cannot access this page!');
        }

        $data = $request->request->all();
        $token = $data['csrf_token'];

        $csrf = $this->get('security.csrf.token_manager');

        if ($csrf->isTokenValid(new CsrfToken('', $token))) {
            $em = $this->getDoctrine()->getManager();
            $user = $em->getRepository('AppBundle:User')->find($id);

            if (!$user) {
                throw $this->createNotFoundException('Unable to find User entity.');
            }

            $user->setEnabled(true);
            $em->flush();

            $response_array = array(
                "id" => $id,
                "username" => $user->getUsername(),
                "enabled" => $user->isEnabled(),
                "email" => $user->getEmail(),
                "gender" => $user->getGender(),
                "lastLogin" => $user->getLastLogin(),
                "createdAt" => $user->getCreatedAt(),
                "ip" => $user->getIp(),
                'csrf' => $token
            );

            $response = json_encode($response_array);

            return new Response($response);
        }
    }

    /**
     * Returns a form new prospect
     *
     * @Route("/{id}/ajax_delete", name="ajax_delete_user", options={"expose"=true})
     * @Method({"POST"})
     * @Template(":ajax.html.twig")
     */
    public function ajax_deleteAction(Request $request, $id)
    {
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
            throw $this->createAccessDeniedException('You cannot access this page!');
        }

        $data = $request->request->all();
        $token = $data['csrf_token'];

        $csrf = $this->get('security.csrf.token_manager');

        if ($csrf->isTokenValid(new CsrfToken('', $token))) {

            $em = $this->getDoctrine()->getManager();
            $user = $em->getRepository('AppBundle:User')->find($id);

            if (!$user) {
                throw $this->createNotFoundException('Unable to find User entity.');
            }

            $em->remove($user);
            $em->flush();

            $response_array = array("id" => $id);
            $response = json_encode($response_array);

            return new Response($response);
        }
    }

}


text:
const assert = require('assert');
const request = require('supertest');
const Server = require('midd');
const useCache = require('..');
const format = require('util').format;

describe('set cache', () => {
  describe('fresh on next req', () => {
    it('should work with no maxAge', (done) => {
      createSimpleTest({ done, 'last-modified': new Date().toUTCString() });
    });

    it('should work with specified maxAge', (done) => {
      createSimpleTest({ done, maxAge: 10000, 'last-modified': new Date().toUTCString() });
    });

    it('should work with maxAge=-1', (done) => {
      createSimpleTest({ done, maxAge: -1, 'last-modified': new Date().toUTCString() });
    });

    it('should work with maxAge>one year', (done) => {
      createSimpleTest({ done, maxAge: 31536001000, 'last-modified': new Date().toUTCString() });
    });

    it('should work with specified private', (done) => {
      createSimpleTest({ done, private: true, 'last-modified': new Date().toUTCString() });
    });

    it('should work with specified last-modified', (done) => {
      const lastMod = new Date(Date.now() - 10000).toUTCString();
      createSimpleTest({ done, 'last-modified': lastMod });
    });

    it('should work with specified number-type last-modified', (done) => {
      const lastMod = Date.now() - 10000;
      createSimpleTest({ done, 'last-modified': lastMod });
    });
  });

  it('should work after cache updated', (done) => {
    const snapshot = {};
    const app = Server();
    app.on('error', done);
    app.use(useCache());
    app.use(async (req, resp, next) => {
      if (req.url === '/a') {
        if (req.fresh(snapshot)) return;
        if (!snapshot.value) {
          snapshot['last-modified'] = new Date(Date.now() - 1000);
          snapshot.value = 'hello';
        }

        resp.setCache(snapshot);
        return resp.end(snapshot.value);
      } else if (req.url === '/update') {
        snapshot['last-modified'] = new Date();
        snapshot.value = 'hello2';
        return resp.end('updated');
      }
    });

    const req = request.agent(app.listen());
    req.get('/a').expect('Cache-Control', 'public, max-age=0').expect(200, 'hello', (err, resp) => {
      if (err) return done(err);
      const lastMod = resp.headers['last-modified'];
      assert.equal(lastMod, snapshot['last-modified'].toUTCString());
      req.get('/a').set('If-Modified-Since', lastMod).expect(304, '', (err) => {
        if (err) return done(err);
        req.get('/update').expect(200, 'updated', (err) => {
          if (err) return done(err);
          req.get('/a').set('If-Modified-Since', lastMod).expect(200, 'hello2', done);
        });
      });
    });
  });
});

function createSimpleTest(options) {
  const { done, maxAge, etag, post, private: _private } = options,
    lastMod = options['last-modified'];

  const snapshot = {};
  const app = Server();
  app.on('error', done);
  app.use(useCache());
  app.use(async (req, resp, next) => {
    if (req.fresh(snapshot)) return;
    resp.setCache(options);
    Object.assign(snapshot, { etag, 'last-modified': lastMod });
    resp.end('hello');
  });

  const req = request.agent(app.listen());

  const cacheCtrl = format('%s, max-age=%s', _private ? 'private' : 'public',
    Math.min(maxAge < 0 ? 31536000 : (parseInt(maxAge / 1000, 10) || 0), 31536000));

  let r;
  if (post) r = req.post('/');
  else r = req.get('/');

  return r.expect('Cache-Control', cacheCtrl).expect(200, 'hello', (err, resp) => {
    if (err) return done(err);
    const respLastMod = resp.headers['last-modified'];
    if (!respLastMod) throw new Error('no last-modified');
    if (lastMod) {
      let setLastMod = lastMod;
      if (typeof setLastMod === 'number') setLastMod = new Date(setLastMod).toUTCString();
      assert.equal(respLastMod, setLastMod);
    }
    req.get('/').set('If-Modified-Since', respLastMod).expect(304, '', done);
  });
}


text:
//! The `conf` module contains functions for loading and saving game
//! configurations.
//!
//! A `Conf` struct is used to specify hardware setup stuff used to create
//! the window and other context information.

use std::io;
use toml;

use GameResult;

/// A structure containing configuration data
/// for the game engine.
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct Conf {
    /// The window title.
    pub window_title: String,
    /// A file path to the window's icon.
    /// It is rooted in the `resources` directory (see the `filesystem` module for details),
    /// and an empty string results in a blank/default icon.
    pub window_icon: String,
    /// The window's height
    pub window_height: u32,
    /// The window's width
    pub window_width: u32,
    /// Whether or not the graphics draw rate should be
    /// synchronized with the monitor's draw rate.
    pub vsync: bool,
    /* To implement still.
     * window_borderless: bool,
     * window_resizable: bool,
     * window_fullscreen: bool,
     *
     * Modules to enable
     * modules_audio: bool,
     * modules_event: bool,
     * modules_graphics: bool,
     * modules_image: bool,
     * modules_joystic: bool,
     * modules_keyboard: bool,
     * modules_mouse: bool,
     * modules_sound: bool,
     * modules_system: bool,
     * modules_timer: bool,
     * modules_video: bool,
     * modules_window: bool,
     * modules_thread: bool, */
}

impl Default for Conf {
    /// Create a new Conf with some vague defaults.
    ///
    /// ```rust,ignore
    /// Conf {
    ///     window_title: "An easy, good game"
    ///     window_icon: ""
    ///     window_height: 600
    ///     window_width: 800
    ///     vsync: true
    /// }
    /// ```
    fn default() -> Self {
        Conf {
            window_title: String::from("An easy, good game"),
            window_icon: String::from(""),
            window_height: 600,
            window_width: 800,
            vsync: true,
        }

    }
}

impl Conf {
    /// Same as Conf::default()
    pub fn new() -> Self {
        Self::default()
    }

    /// Load a TOML file from the given `Read` and attempts to parse
    /// a `Conf` from it.
    pub fn from_toml_file<R: io::Read>(file: &mut R) -> GameResult<Conf> {
        let mut s = String::new();
        file.read_to_string(&mut s)?;
        let decoded = toml::from_str(&s)?;
        Ok(decoded)
    }

    /// Saves the `Conf` to the given `Write` object,
    /// formatted as TOML.
    pub fn to_toml_file<W: io::Write>(&self, file: &mut W) -> GameResult<()> {
        let s = toml::to_vec(self)?;
        file.write_all(&s)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use conf;

    /// Tries to encode and decode a `Conf` object
    /// and makes sure it gets the same result it had.
    #[test]
    fn encode_round_trip() {
        let c1 = conf::Conf::new();
        let mut writer = Vec::new();
        let _c = c1.to_toml_file(&mut writer).unwrap();
        //println!("{}", String::from_utf8_lossy(&writer));
        let mut reader = writer.as_slice();
        let c2 = conf::Conf::from_toml_file(&mut reader).unwrap();
        assert_eq!(c1, c2);
    }
}


text:
<?php
namespace TopSDK\Api;
/**
 * TOP API: taobao.tbk.shop.recommend.get request
 *
 * @author auto create
 * @since 1.0, 2015.07.18
 */
class TbkShopRecommendGetRequest
{
	/**
	 * 返回数量,默认20,最大值40
	 **/
	private $count;

	/**
	 * 需返回的字段列表
	 **/
	private $fields;

	/**
	 * 链接形式:1:PC,2:无线,默认:1
	 **/
	private $platform;

	/**
	 * 卖家Id
	 **/
	private $userId;

	private $apiParas = array();

	public function setCount($count)
	{
		$this->count = $count;
		$this->apiParas["count"] = $count;
	}

	public function getCount()
	{
		return $this->count;
	}

	public function setFields($fields)
	{
		$this->fields = $fields;
		$this->apiParas["fields"] = $fields;
	}

	public function getFields()
	{
		return $this->fields;
	}

	public function setPlatform($platform)
	{
		$this->platform = $platform;
		$this->apiParas["platform"] = $platform;
	}

	public function getPlatform()
	{
		return $this->platform;
	}

	public function setUserId($userId)
	{
		$this->userId = $userId;
		$this->apiParas["user_id"] = $userId;
	}

	public function getUserId()
	{
		return $this->userId;
	}

	public function getApiMethodName()
	{
		return "taobao.tbk.shop.recommend.get";
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function check()
	{

		RequestCheckUtil::checkNotNull($this->fields,"fields");
		RequestCheckUtil::checkNotNull($this->userId,"userId");
	}

	public function putOtherTextParam($key, $value) {
		$this->apiParas[$key] = $value;
		$this->$key = $value;
	}
}


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <meta content="en-us" http-equiv="Content-Language" />
    <meta name="description" content="" />
    <meta name="keywords" content="WordNet" />

    <title>Yawni Online</title>
    <link rel="stylesheet" type="text/css" href="/webjars/bootstrap/4.2.1/css/bootstrap.min.css"/>

    <link type="text/css" href="/assets/style.css" rel="stylesheet" media="screen, projection" />

    <link rel="stylesheet" href="/assets/jquery.autocomplete.css" type="text/css" />

Yawni Online

The main content will get bound here

          Powered by Yawni © 2019


text:
$(document).ready(function(){

    $('#btn_ok').click(function(){

        window.location.href='oa-workflow-vehicle-examine-2.html';

    });

    $('#btn_no').click(function(){

        window.location.href='oa-personal-proc-approval.html';

    });

});


text:
using System.Collections.Generic;
using TeamSpark.AzureDay.WebSite.App.Entity;

namespace TeamSpark.AzureDay.WebSite.Host.Models.Home
{
	public sealed class IndexModel
	{
		public SpeakersModel Speakers { get; set; }
		public List<Partner> Partners { get; set; }
	}
}


text:
#include <errno.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <endian.h>

#include <libpdbg.h>

#include "main.h"
#include "optcmd.h"
#include "path.h"

static bool is_real_address(struct thread_regs *regs, uint64_t addr)
{
	return true;
	if ((addr & 0xf000000000000000ULL) == 0xc000000000000000ULL)
		return true;
	return false;
}

static int load8(struct pdbg_target *target, uint64_t addr, uint64_t *value)
{
	if (mem_read(target, addr, (uint8_t *)value, 8, 0, false)) {
		pdbg_log(PDBG_ERROR, "Unable to read memory address=%016" PRIx64 ".\n", addr);
		return 0;
	}

	return 1;
}

uint64_t flip_endian(uint64_t v)
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
	return be64toh(v);
#else
	return le64toh(v);
#endif
}

static int dump_stack(struct thread_regs *regs, struct pdbg_target *adu)
{
	uint64_t next_sp = regs->gprs[1];
	uint64_t pc;
	bool finished = false;
	bool prev_flip = false;

	printf("STACK:           SP                NIA\n");
	if (!(next_sp && is_real_address(regs, next_sp))) {
		printf("SP:0x%016" PRIx64 " does not appear to be a stack\n", next_sp);
		return 0;
	}

	while (!finished) {
		uint64_t sp = next_sp;
		uint64_t tmp, tmp2;
		bool flip = false;
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
		bool be = false;
#else
		bool be = true;
#endif

		if (!is_real_address(regs, sp))
			break;

		if (!load8(adu, sp, &tmp))
			return 1;
		if (!load8(adu, sp + 16, &pc))
			return 1;

		if (!tmp) {
			finished = true;
			flip = prev_flip;
			if (flip)
				be = !be;
			next_sp = 0;
			goto do_pc;
		}

		tmp2 = flip_endian(tmp);

		/*
		 * Basic endian detection.
		 * Stack grows down, so as we unwind it we expect to see
		 * increasing addresses without huge jumps.  The stack may
		 * switch endian-ness across frames in some cases (e.g., LE
		 * kernel calling BE OPAL).
		 */

		/* Check for OPAL stack -> Linux stack */
		if ((sp >= 0x30000000UL && sp < 0x40000000UL) &&
				!(tmp >= 0x30000000UL && tmp < 0x40000000UL)) {
			if (tmp >> 60 == 0xc)
				goto no_flip;
			if (tmp2 >> 60 == 0xc)
				goto do_flip;
		}

		/* Check for Linux -> userspace */
		if ((sp >> 60 == 0xc) && !(tmp >> 60 == 0xc)) {
			finished = true; /* Don't decode userspace */
			if (tmp >> 60 == 0)
				goto no_flip;
			if (tmp2 >> 60 == 0)
				goto do_flip;
		}

		/* Otherwise try to ensure sane stack */
		if (tmp < sp || (tmp - sp > 0xffffffffUL)) {
			if (tmp2 < sp || (tmp2 - sp > 0xffffffffUL)) {
				finished = true;
				goto no_flip;
			}
do_flip:
			next_sp = tmp2;
			flip = true;
			be = !be;
		} else {
no_flip:
			next_sp = tmp;
		}

do_pc:
		if (flip)
			pc = flip_endian(pc);

		printf(" 0x%016" PRIx64 " 0x%016" PRIx64 " (%s)\n",
			sp, pc, be ? "big-endian" : "little-endian");

		prev_flip = flip;
	}
	printf(" 0x%016" PRIx64 "\n", next_sp);

	return 0;
}

static int thr_start(void)
{
	struct pdbg_target *target;
	int count = 0;

	if (path_target_all_selected("thread", NULL)) {
		thread_start_all();
		return 1;
	}

	for_each_path_target_class("thread", target) {
		if (pdbg_target_status(target) != PDBG_TARGET_ENABLED)
			continue;

		thread_start(target);
		count++;
	}

	return count;
}
OPTCMD_DEFINE_CMD(start, thr_start);

static int thr_step(uint64_t steps)
{
	struct pdbg_target *target;
	int count = 0;

	if (path_target_all_selected("thread", NULL)) {
		int i;

		for (i=0; i<count; i++)
			thread_step_all();

		return 1;
	}

	for_each_path_target_class("thread", target) {
		if (pdbg_target_status(target) != PDBG_TARGET_ENABLED)
			continue;

		thread_step(target, (int)steps);
		count++;
	}

	return count;
}
OPTCMD_DEFINE_CMD_WITH_ARGS(step, thr_step, (DATA));

static int thr_stop(void)
{
	struct pdbg_target *target;
	int count = 0;

	if (path_target_all_selected("thread", NULL)) {
		thread_stop_all();
		return 1;
	}

	for_each_path_target_class("thread", target) {
		if (pdbg_target_status(target) != PDBG_TARGET_ENABLED)
			continue;

		thread_stop(target);
		count++;
	}

	return count;
}
OPTCMD_DEFINE_CMD(stop, thr_stop);

static int print_one_thread(struct pdbg_target *thread)
{
	struct thread_state tstate;
	char c;

	if (!path_target_selected(thread)) {
		printf("... ");
		return 0;
	}

	tstate = thread_status(thread);

	switch (tstate.sleep_state) {
	case PDBG_THREAD_STATE_DOZE:
		c = 'D';
		break;

	case PDBG_THREAD_STATE_NAP:
		c = 'N';
		break;

	case PDBG_THREAD_STATE_SLEEP:
		c = 'Z';
		break;

	case PDBG_THREAD_STATE_STOP:
		c = 'S';
		break;

	default:
		c = '.';
		break;
	}

	printf("%c%c%c ",
	       (tstate.active ? 'A' : '.'),
	       c,
	       (tstate.quiesced ? 'Q': '.'));
	return 1;
}

static int thread_status_print(void)
{
	struct pdbg_target *thread, *core, *pib;
	int threads_per_core = 0;
	int count = 0;

	for_each_path_target_class("thread", thread) {
		core = pdbg_target_parent("core", thread);
		assert(path_target_add(core));

		pib = pdbg_target_parent("pib", core);
		assert(path_target_add(pib));
	}

	pib = __pdbg_next_target("pib", pdbg_target_root(), NULL, true);
	assert(pib);

	core = __pdbg_next_target("core", pib, NULL, true);
	assert(core);

	pdbg_for_each_target("thread", core, thread)
		threads_per_core++;

	for_each_path_target_class("pib", pib) {
		int i;

		if (pdbg_target_status(pib) != PDBG_TARGET_ENABLED)
			continue;

		printf("\np%01dt:", pdbg_target_index(pib));
		for (i = 0; i < threads_per_core; i++)
			printf("   %d", i);
		printf("\n");

		pdbg_for_each_target("core", pib, core) {
			if (!path_target_selected(core))
				continue;
			if (pdbg_target_status(core) != PDBG_TARGET_ENABLED)
				continue;

			printf("c%02d:  ", pdbg_target_index(core));

			pdbg_for_each_target("thread", core, thread)
				count += print_one_thread(thread);
			printf("\n");
		}
	}

	return count;
}
OPTCMD_DEFINE_CMD(threadstatus, thread_status_print);

static int thr_sreset(void)
{
	struct pdbg_target *target;
	int count = 0;

	if (path_target_all_selected("thread", NULL)) {
		thread_sreset_all();
		return 1;
	}

	for_each_path_target_class("thread", target) {
		if (pdbg_target_status(target) != PDBG_TARGET_ENABLED)
			continue;

		thread_sreset(target);
		count++;
	}

	return count;
}
OPTCMD_DEFINE_CMD(sreset, thr_sreset);

struct reg_flags {
	bool do_backtrace;
};

#define REG_BACKTRACE_FLAG ("--backtrace", do_backtrace, parse_flag_noarg, false)

static int thread_regs_print(struct reg_flags flags)
{
	struct pdbg_target *pib, *core, *thread;
	struct thread_regs regs;
	int count = 0;

	for_each_path_target_class("thread", thread) {
		core = pdbg_target_parent("core", thread);
		pib = pdbg_target_parent("pib", core);

		printf("p%d c%d t%d\n",
		       pdbg_target_index(pib),
		       pdbg_target_index(core),
		       pdbg_target_index(thread));

		if (thread_getregs(thread, &regs))
			continue;

		thread_print_regs(&regs);

		if (flags.do_backtrace) {
			struct pdbg_target *adu;

			pdbg_for_each_class_target("mem", adu) {
				if (pdbg_target_probe(adu) == PDBG_TARGET_ENABLED) {
					dump_stack(&regs, adu);
					break;
				}
			}
		}

		count++;
	}

	return count;
}
OPTCMD_DEFINE_CMD_ONLY_FLAGS(regs, thread_regs_print, reg_flags, (REG_BACKTRACE_FLAG));


text:
"""Problems a file can have"""

from collections import namedtuple

Problem = namedtuple('Problem', ('code', 'message', 'fix'))

shared_problems = {
    'PROB_DIR_NOT_WRITABLE': Problem(1,
                                     'Directory not writable',
                                     'Run \'chmod 0655\' on this directory'),

    'PROB_FILE_NOT_GRPRD': Problem(2,
                                   'File not group readable',
                                   'Run \'chmod 0644\' on this file'),

    'PROB_FILE_NOT_GRPEXEC': Problem(7,
                                     'File is not group executable',
                                     'Run chmod 0755 on this file'),

    'PROB_DIR_NOT_ACCESSIBLE': Problem(8,
                                       'Directory is not accessible to the group',
                                       'Run chmod 0755 on this directory'),
}

regular_problems = {
    'PROB_FILE_IS_FASTQ': Problem(3,
                                  'File is a fastq file',
                                  'Don\'t copy fastq files, instead use \'ln -s\''),

    'PROB_BROKEN_LINK': Problem(4,
                                'Symbolic link points to nonexistant file',
                                'Delete this link'),

    'PROB_SAM_SHOULD_COMPRESS': Problem(5,
                                        '*.sam files are large',
                                        'Consider compressing'),

    'PROB_SAM_AND_BAM_EXIST': Problem(6,
                                      'The *.sam file has been compressed, but it still exists',
                                      'Delete the uncompressed copy'),

    'PROB_UNKNOWN_ERROR': Problem(9,
                                  'Unknown error occurred',
                                  'Not sure what to do'),

    'PROB_OLD_LARGE_PLAINTEXT': Problem(10,
                                        'File is an old large plaintext file',
                                        'Consider compressing'),
}

env_problems = {
    'PROB_PATH_NOT_COMPLETE': Problem(11,
                                      'The PATH environment variable does not contain all necessary paths',
                                      'Add the path to the PATH environment variable'),

    'PROB_LD_LIBRARY_PATH_NOT_COMPLETE': Problem(12,
                                                 'The LD_LIBRARY_PATH environment variable does not contain all necessary paths',
                                                 'Add the path the LD_LIBRARY_PATH variable'),

    'PROB_VAR_NOT_SET': Problem(13,
                                'This environment variable is not set',
                                'Try exporting an appropriate definition in your ~/.bash_profile'),

}

every_problem = dict(
    list(shared_problems.items()) +
    list(regular_problems.items()) +
    list(env_problems.items())
)


text:
const boneView = require("backbone-childs");
const mouse = require("mouse-pos");
import {throttle} from "lodash";
const jbone = require("jbone");

import CharCache from "./CanvasCharCache";
import SelectionClass from "./CanvasSelection";
import CanvasSeqDrawer from "./CanvasSeqDrawer";
import CanvasCoordsCache from "./CanvasCoordsCache";

const View = boneView.extend({

  tagName: "canvas",

  initialize: function(data) {
    this.g = data.g;

    this.listenTo(this.g.zoomer, "change:_alignmentScrollLeft change:_alignmentScrollTop", function(model,value, options) {
      if ((!(((typeof options !== "undefined" && options !== null) ? options.origin : undefined) != null)) || options.origin !== "canvasseq") {
        return this.render();
      }
    });

    this.listenTo(this.g.columns,"change:hidden", this.render);
    this.listenTo(this.g.zoomer,"change:alignmentWidth change:alignmentHeight", this.render);
    this.listenTo(this.g.colorscheme, "change", this.render);
    this.listenTo(this.g.selcol, "reset add", this.render);
    this.listenTo(this.model, "reset add", this.render);

    // el props
    this.el.style.display = "inline-block";
    this.el.style.overflowX = "hidden";
    this.el.style.overflowY = "hidden";
    this.el.className = "biojs_msa_seqblock";

    this.ctx = this.el.getContext('2d');
    this.cache = new CharCache(this.g);
    this.coordsCache = new CanvasCoordsCache(this.g, this.model);

    // clear the char cache
    this.listenTo(this.g.zoomer, "change:residueFont", function() {
      this.cache = new CharCache(this.g);
      return this.render();
    });

    // init selection
    this.sel = new SelectionClass(this.g,this.ctx);

    this._setColor();

    // throttle the expensive draw function
    this.throttleTime = 0;
    this.throttleCounts = 0;
    if ((document.documentElement.style.webkitAppearance != null)) {
      // webkit browser - no throttling needed
      this.throttledDraw = function() {
        const start = +new Date();
        this.draw();
        this.throttleTime += +new Date() - start;
        this.throttleCounts++;
        if (this.throttleCounts > 15) {
          const tTime = Math.ceil(this.throttleTime / this.throttleCounts);
          console.log("avgDrawTime/WebKit", tTime);
          // remove perf analyser
          return this.throttledDraw = this.draw;
        }
      };
    } else {
      // slow browsers like Gecko
      this.throttledDraw = throttle(this.throttledDraw, 30);
    }

    return this.manageEvents();
  },

  // measures the time of a redraw and thus set the throttle limit
  throttledDraw: function() {
    // +new is the fastest: http://jsperf.com/new-date-vs-date-now-vs-performance-now/6
    const start = +new Date();
    this.draw();
    this.throttleTime += +new Date() - start;
    this.throttleCounts++;

    // remove itself after analysis
    if (this.throttleCounts > 15) {
      let tTime = Math.ceil(this.throttleTime / this.throttleCounts);
      console.log("avgDrawTime", tTime);
      tTime *=  1.2; // add safety time
      tTime = Math.max(20, tTime); // limit for ultra fast computers
      return this.throttledDraw = _.throttle(this.draw, tTime);
    }
  },

  manageEvents: function() {
    const events = {};
    events.mousedown = "_onmousedown";
    events.touchstart = "_ontouchstart";

    if (this.g.config.get("registerMouseClicks")) {
      events.dblclick = "_onclick";
    }
    if (this.g.config.get("registerMouseHover")) {
      events.mousein = "_onmousein";
      events.mouseout = "_onmouseout";
    }

    events.mousewheel = "_onmousewheel";
    events.DOMMouseScroll = "_onmousewheel";
    this.delegateEvents(events);

    // listen for changes
    this.listenTo(this.g.config, "change:registerMouseHover", this.manageEvents);
    this.listenTo(this.g.config, "change:registerMouseClick", this.manageEvents);
    return this.dragStart = [];
  },

  _setColor: function() {
    return this.color = this.g.colorscheme.getSelectedScheme();
  },

  draw: function() {
    // fastest way to clear the canvas
    // http://jsperf.com/canvas-clear-speed/25
    this.el.width = this.el.width;

    // draw all the stuff
    if ((this.seqDrawer != null)  && this.model.length > 0) {
      // char based
      this.seqDrawer.drawLetters();
      // row based
      this.seqDrawer.drawRows(this.sel._appendSelection, this.sel);
      return this.seqDrawer.drawRows(this.drawFeatures, this);
    }
  },

  drawFeatures: function(data) {
    const rectWidth = this.g.zoomer.get("columnWidth");
    const rectHeight = this.g.zoomer.get("rowHeight");
    if (data.model.attributes.height > 1) {
      const ctx = this.ctx;
      data.model.attributes.features.each(function(feature) {
        ctx.fillStyle = feature.attributes.fillColor || "red";
        const len = feature.attributes.xEnd - feature.attributes.xStart + 1;
        const y = (feature.attributes.row + 1) * rectHeight;
        return ctx.fillRect(feature.attributes.xStart * rectWidth + data.xZero,y + data.yZero,rectWidth * len,rectHeight);
      });

      // draw text
      ctx.fillStyle = "black";
      ctx.font = this.g.zoomer.get("residueFont") + "px mono";
      ctx.textBaseline = 'middle';
      ctx.textAlign = "center";

      return data.model.attributes.features.each(function(feature) {
        const len = feature.attributes.xEnd - feature.attributes.xStart + 1;
        const y = (feature.attributes.row + 1) * rectHeight;
        return ctx.fillText( feature.attributes.text, data.xZero + feature.attributes.xStart *
        rectWidth + (len / 2) * rectWidth, data.yZero + rectHeight * 0.5 + y
        );
      });
    }
  },

  render: function() {

    this.el.setAttribute('height', this.g.zoomer.get("alignmentHeight") + "px");
    this.el.setAttribute('width', this.g.zoomer.getAlignmentWidth() + "px");

    this.g.zoomer._checkScrolling( this._checkScrolling([this.g.zoomer.get('_alignmentScrollLeft'),
    this.g.zoomer.get('_alignmentScrollTop')] ),{header: "canvasseq"});

    this._setColor();

    this.seqDrawer = new CanvasSeqDrawer( this.g,this.ctx,this.model,
      {width: this.el.width,
      height: this.el.height,
      color: this.color,
      cache: this.cache
    });

    this.throttledDraw();
    return this;
  },

  _onmousemove: function(e, reversed) {
    if (this.dragStart.length === 0) { return; }

    const dragEnd = mouse.abs(e);
    // relative to first click
    const relEnd = [dragEnd[0] - this.dragStart[0], dragEnd[1] - this.dragStart[1]];
    // relative to initial scroll status

    // scale events
    let scaleFactor = this.g.zoomer.get("canvasEventScale");
    if (reversed) {
      scaleFactor = 3;
    }
    for (let i = 0; i <= 1; i++) {
      relEnd[i] = relEnd[i] * scaleFactor;
    }

    // calculate new scrolling vals
    const relDist = [this.dragStartScroll[0] - relEnd[0], this.dragStartScroll[1] - relEnd[1]];

    // round values
    for (let i = 0; i <= 1; i++) {
      relDist[i] = Math.round(relDist[i]);
    }

    // update scrollbar
    const scrollCorrected = this._checkScrolling( relDist);
    this.g.zoomer._checkScrolling(scrollCorrected, {origin: "canvasseq"});

    // reset start if use scrolls out of bounds
    for (let i = 0; i <= 1; i++) {
      if (scrollCorrected[i] !== relDist[i]) {
        if (scrollCorrected[i] === 0) {
          // reset of left, top
          this.dragStart[i] = dragEnd[i];
          this.dragStartScroll[i] = 0;
        } else {
          // recalibrate on right, bottom
          this.dragStart[i] = dragEnd[i] - scrollCorrected[i];
        }
      }
    }

    this.throttledDraw();

    // abort selection events of the browser (mouse only)
    if ((e.preventDefault != null)) {
      e.preventDefault();
      return e.stopPropagation();
    }
  },

  // converts touches into old mouse event
  _ontouchmove: function(e) {
    this._onmousemove(e.changedTouches[0], true);
    e.preventDefault();
    return e.stopPropagation();
  },

  // start the dragging mode
  _onmousedown: function(e) {
    this.dragStart = mouse.abs(e);
    this.dragStartScroll = [this.g.zoomer.get('_alignmentScrollLeft'), this.g.zoomer.get('_alignmentScrollTop')];
    jbone(document.body).on('mousemove.overmove', (e) => this._onmousemove(e));
    jbone(document.body).on('mouseup.overup', () => this._cleanup());
    //jbone(document.body).on 'mouseout.overout', (e) => @_onmousewinout(e)
    return e.preventDefault();
  },

  // starts the touch mode
  _ontouchstart: function(e) {
    this.dragStart = mouse.abs(e.changedTouches[0]);
    this.dragStartScroll = [this.g.zoomer.get('_alignmentScrollLeft'), this.g.zoomer.get('_alignmentScrollTop')];
    jbone(document.body).on('touchmove.overtmove', (e) => this._ontouchmove(e));
      return jbone(document.body).on( 'touchend.overtend touchleave.overtleave touchcancel.overtcanel', (e) => this._touchCleanup(e)
    );
  },

  // checks whether mouse moved out of the window
  // -> terminate dragging
  _onmousewinout: function(e) {
    if (e.toElement === document.body.parentNode) {
      return this._cleanup();
    }
  },

  // terminates dragging
  _cleanup: function() {
    this.dragStart = [];
    // remove all listeners
    jbone(document.body).off('.overmove');
    jbone(document.body).off('.overup');
    return jbone(document.body).off('.overout');
  },

  // terminates touching
  _touchCleanup: function(e) {
    if (e.changedTouches.length > 0) {
      // maybe we can send a final event
      this._onmousemove(e.changedTouches[0], true);
    }

    this.dragStart = [];
    // remove all listeners
    jbone(document.body).off('.overtmove');
    jbone(document.body).off('.overtend');
    jbone(document.body).off('.overtleave');
    return jbone(document.body).off('.overtcancel');
  },

  // might be incompatible with some browsers
  _onmousewheel: function(e) {
    const delta = mouse.wheelDelta(e);
    this.g.zoomer.set('_alignmentScrollLeft', this.g.zoomer.get('_alignmentScrollLeft') + delta[0]);
    this.g.zoomer.set('_alignmentScrollTop', this.g.zoomer.get('_alignmentScrollTop') + delta[1]);
    return e.preventDefault();
  },

  _onclick: function(e) {
    const res = this._getClickPos(e);
    if ((typeof res !== "undefined" && res !== null)) {
      if ((res.feature != null)) {
        this.g.trigger("feature:click", res);
      } else {
        this.g.trigger("residue:click", res);
      }
    }
    return this.throttledDraw();
  },

  _onmousein: function(e) {
    const res = this._getClickPos(e);
    if ((typeof res !== "undefined" && res !== null)) {
      if ((res.feature != null)) {
        this.g.trigger("feature:mousein", res);
      } else {
        this.g.trigger("residue:mousein", res);
      }
    }
    return this.throttledDraw();
  },

  _onmouseout: function(e) {
    const res = this._getClickPos(e);
    if ((typeof res !== "undefined" && res !== null)) {
      if ((res.feature != null)) {
        this.g.trigger("feature:mouseout", res);
      } else {
        this.g.trigger("residue:mouseout", res);
      }
    }

    return this.throttledDraw();
  },

  _getClickPos: function(e) {
    const coords = mouse.rel(e);

    coords[0] += this.g.zoomer.get("_alignmentScrollLeft");
    let x = Math.floor(coords[0] / this.g.zoomer.get("columnWidth") );
    let [y, rowNumber] = this.seqDrawer._getSeqForYClick(coords[1]);

    // add hidden columns
    x += this.g.columns.calcHiddenColumns(x);
    // add hidden seqs
    y += this.model.calcHiddenSeqs(y);

    x = Math.max(0,x);
    y = Math.max(0,y);

    const seqId = this.model.at(y).get("id");

    if (rowNumber > 0) {
      // click on a feature
      const features = this.model.at(y).get("features").getFeatureOnRow(rowNumber - 1, x);
      if (!(features.length === 0)) {
        const feature = features[0];
        console.log(features[0].attributes);
        return {seqId:seqId, feature: feature, rowPos: x, evt:e};
      }
    } else {
      // click on a seq
      return {seqId:seqId, rowPos: x, evt:e};
    }
  },

  // checks whether the scrolling coordinates are valid
  // @returns: [xScroll,yScroll] valid coordinates
  _checkScrolling: function(scrollObj) {

    // 0: maxLeft, 1: maxTop
    const max = [this.coordsCache.maxScrollWidth, this.coordsCache.maxScrollHeight];

    for (let i = 0; i <= 1; i++) {
      if (scrollObj[i] > max[i]) {
        scrollObj[i] = max[i];
      }

      if (scrollObj[i] < 0) {
        scrollObj[i] = 0;
      }
    }

    return scrollObj;
  }
});
export default View;


text:
<!DOCTYPE html>

  <title>#lovmx</title>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta name="copyright" content="(c) 2015 #lolnub.">
  <meta name="description" content="ILvMx Orbital Magic for Cloud Apps.">
  <meta name="keywords" content="lovmx, lovmx, internet, love, virtual, magic, exchange, holospace, adventurama, bot, web 4">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="HandheldFriendly" content="True">

	<link rel="stylesheet" href="css/normalize.css">
	<link rel="stylesheet" href="css/foundation.min.css">
  <link rel="stylesheet" href="css/default.css" type="text/css" media="screen" charset="utf-8">

  <link rel="icon" type="image/png" href="/img/favicon.png">

#back

#help

!reset

	<form id="" method="post" action="/" name="submit" enctype="multipart/form-data" class="cake">
		<textarea id="magic" name="code" placeholder="#magic" rows=3 cols=28></textarea>
		<input id="data" name="data" type="file">
		<input id="secret" type="password" name="secret" placeholder="#secret" class="" size=24>

		<fieldset id="codes" class="small-grid">
			<input name="data" type="submit" class="codemagic" value="Data">
			<input name="meta" type="submit" class="codemagic" value="Meta">
			<input name="lock" type="submit" class="codemagic" value="Lock">
			<input name="list" type="submit" class="codemagic" value="List">
			<input name="pull" type="submit" class="codemagic" value="Pull">
			<input name="push" type="submit" class="codemagic" value="Push">
			<input name="code" type="submit" class="codemagic" value="Code">
			<input name="flow" type="submit" class="codemagic" value="Flow">
			<input name="wait" type="submit" class="codemagic" value="Wait">
			<input name="drop" type="submit" class="codemagic" value="Drop">
			<input name="text" type="submit" class="codemagic" value="Text">
			<input name="link" type="submit" class="codemagic" value="Link">
			<input name="html" type="submit" class="codemagic" value="Html">
			<input name="bin" type="submit" class="codemagic" value="Blob">
			<input name="cake" type="submit" class="codemagic" value="Cake">
			<input name="boom" type="submit" class="codemagic" value="Boom">
		</fieldset>

		<input name="submit" type="submit" value="Magic.">
	</form>

Welcome to Holospace.


text:
package us.mcsw.minerad.items;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import us.mcsw.core.ItemMR;
import us.mcsw.minerad.entity.EntityThrownMarker;

public class ItemNukeMarker extends ItemMR {

	public ItemNukeMarker() {
		super("nukeMarker");
	}

	@Override
	public ItemStack onItemRightClick(ItemStack it, World w, EntityPlayer pl) {
		if (!w.isRemote) {
			w.spawnEntityInWorld(new EntityThrownMarker(w, pl));
			it.stackSize--;
		}
		return it;
	}

}


text:
class GherkinGenerator
  ##
  # A multiline feature description
  #
  # = Example
  #
  #   GherkinGenerator.new("My Feature").description = <<EOS
  #   All sorts of information about my feature
  #   This info is not parsed, it's just a description of the feature
  #   EOS
  attr_accessor :description

  ##
  # Generate a new feature
  #
  # = Example
  #
  #   GherkinGenerator.new("Feature name goes here")
  def initialize(feature_name)
    @feature_name = feature_name
    @scenarios = []
    @tag = ''
  end

  ##
  # Add a scenario to the feature.  The format is a single line string
  # with capital letters for the GWTA's
  #
  # = Example
  #
  #   myFeature.add_scenario("My Scenario: Given I ... When I ... And I ... Then I ...")
  #
  def add_scenario(scenario)
    examples_keyword = 'Examples '
    scenario_parts = scenario.split examples_keyword
    if scenario_parts[1] && !@ex_yield.nil?
      examples = @ex_yield.call(scenario_parts[1])
    end
    result = Scenario.new(scenario_parts[0], examples)
    @scenarios << result
    result
  end

  ##
  # Examples in Gherkin don't suite the one-line input well.  This
  #
  # = Example
  #
  #   myFeature.exampleHandler do |reference|
  #     puts "looking up examples with ref: #{reference}"
  #     <<EOS
  #   | something | another |
  #   | abc       | def     |
  #   | def       | ghi     |
  #   EOS
  #   end
  #   myFeature.add_scenario("My Scenario With" +
  #     " Examples: Given I ... Then I ... Examples http://example.org/example1")
  #
  def example_handler(&block)
    @ex_yield = block
  end

  ##
  # Output the Gherkin formatted string, this can be saved in a Feature file.
  #
  # = Example
  #
  #   gg = GherkinGenerator.new("My Feature")
  #   gg.add_scenario("Something: When I do something Then something should have happened")
  #   gg.add_scenario("Something Else: When I do something else Then something else should have happened")
  #   puts gg.to_gherkin
  #
  def to_gherkin
    feature = 'Feature: ' + @feature_name
    desc = @description.nil? ? '' : "\n\t" + @description.sub("\n", "\n\t")
    scenarios = ''

    @scenarios.each do |item|
      scenarios << item.format_string
    end

    feature + desc + scenarios + "\n"
  end

  ##
  # Object oriented representation of scenarios.  This is designed for internal use by GherkinGenerator.
  class Scenario
    ##
    # Takes a single-line scenario and a formatted example table
    def initialize(scenario, examples)
      @scenario = scenario
      @tag = []
      @examples = if examples.nil?
                    ''
                  else
                    "\n\tExamples:\n\t\t" + examples.strip.gsub("\n", "\n\t\t")
                  end
    end

    ##
    # Adding a tag - the formatting is applied, you just supply the tag name
    def add_tag(tag)
      @tag << '@' + tag
    end

    ##
    # The output of the current scenario, a feature file is made up of a description
    # and multiple scenarios formatted as a string.
    def format_string
      keywords = %w(Given And When Then)
      steps = @scenario.split(':')[1].strip
      keywords.map do |word|
        steps = steps.split(" #{word}").join("\n\t\t#{word}")
      end
      scenario = @scenario.split(':')[0]
      tag = @tag.empty? ? '' : (@tag.join(' ') + "\n\t")
      type = @examples.empty? ? 'Scenario' : 'Scenario Outline'
      "\n\n\t" + tag + type + ': ' + scenario + "\n\t\t" + steps + @examples
    end
  end
end


text:
package org.streetartgangs.beans;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.streetartgangs.entities.StreetArtUser;

/**
 *
 * @author Marko Karjalainen <markotfk@gmail.com>
 */
@Stateless
public class UserBean implements UserBeanLocal {

    @PersistenceContext(unitName = "Gangsters-ejbPU")
    protected EntityManager em;

    @Override
    public void addUser(StreetArtUser user) {
        if (user == null) {
            throw new NullPointerException("user");
        }
        if (find(user.getDbId()) == null) {
            em.persist(user);
        }
    }

    @Override
    public StreetArtUser find(Long id) {
        if (id == null) {
            return null;
        }
        return em.find(StreetArtUser.class, id);
    }
}


text:
meta-cgl
========

This repo is a clone of the meta-cgl layer maintained by Enea (http://www.enea.com/linux)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <parent>
        <artifactId>goci-parent</artifactId>
        <groupId>uk.ac.ebi.spot</groupId>

        <version>3.3.5</version>

        <relativePath>../../goci-parent/pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>goci-db-binding</artifactId>

    <version>3.3.5</version>

    <name>GOCI Database Binding Classes</name>
    <description>Flyway migration scripts</description>

    <dependencies>
        <dependency>
            <groupId>uk.ac.ebi.spot</groupId>
            <artifactId>goci-model</artifactId>
        </dependency>
        <dependency>
            <groupId>com.oracle.ojdbc</groupId>
            <artifactId>ojdbc8</artifactId>
        </dependency>
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
    </dependencies>

</project>


text:
using System;
using System.ComponentModel;

namespace PropertyChanged
{
    /// <summary>
    /// Specifies that PropertyChanged Notification will be added to a class.
    /// <para>
    /// PropertyChanged.Fody will weave the <see cref="INotifyPropertyChanged"/> interface and implementation into the class.
    /// When the value of a property changes, the PropertyChanged notification will be raised automatically
    /// </para>
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, Inherited = false)]
    public class ImplementPropertyChangedAttribute : Attribute
    {
    }
}


text:
package eu.monnetproject.kap.laif;

import eu.monnetproject.l10n.Localizer;
import eu.monnetproject.lang.Language;
import eu.monnetproject.lemon.LemonModel;
import eu.monnetproject.lemon.LemonSerializer;
import eu.monnetproject.lemon.model.LexicalEntry;
import eu.monnetproject.lemon.model.LexicalSense;
import eu.monnetproject.lemon.model.Lexicon;
import eu.monnetproject.util.ResourceFinder;
import java.io.IOException;
import java.io.Reader;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static eu.monnetproject.util.CollectionFunctions.*;
import java.util.HashSet;

/**
 *
 * @author John McCrae
 */
public class LAIFLocalizer implements LAIFController, Localizer {

    private final Map<String, LAIFLocalizationLexicon> lexica = new HashMap<String, LAIFLocalizationLexicon>();

    public LAIFLocalizer() {
    }

    private static class LAIFLocalizationLexiconImpl extends LAIFLocalizationLexicon {

        public LAIFLocalizationLexiconImpl(String appKey) {
            super(appKey);
        }

        @Override
        protected LAIFRuleSet rules(Language lang) {
            final LAIFRuleSet r = super.rules(lang);
            if (r == null) {
                Reader artifact = null;
                try {
                    artifact = ResourceFinder.getResourceAsReader(appKey + "." + lang + ".laif");
                    if (artifact == null) {
                        return null;
                    }
                    final LAIFRuleSet ruleSet = LAIFReader.read(artifact);
                    rules.put(lang, ruleSet);
                    return ruleSet;
                } catch (IOException x) {
                    return null;
                } finally {
                    if (artifact != null) {
                        try {
                            artifact.close();
                        } catch (Exception x) {
                        }
                    }
                }
            } else {
                return r;
            }
        }

        @Override
        protected Lexicon lexica(Language lang) {
            final Lexicon l = super.lexica(lang);
            if (l != null) {
                return l;
            } else {
                try {
                    final LAIFRuleSet r = rules(lang);
                    if (r != null && r.getLexicon() != null) {
                        URL lexiconURL = r.getLexicon().toURL();
                        final LemonModel model = LemonSerializer.modelFromURL(lexiconURL);
                        for (Lexicon lexicon : model.getLexica()) {
                            if (lexicon.getLanguage().equals(lang.toString())) {
                                lexica.put(lang, lexicon);
                                return lexicon;
                            }
                        }
                    }
                    return null;
                } catch (Exception x) {
                    x.printStackTrace();
                    return null;
                }
            }
        }

        public void updateRules(Language lang, LAIFRuleSet ruleSet) {
            rules.put(lang,ruleSet);
        }

        public Set<URI> getLexicaURIs() {
            return map(new HashSet<Lexicon>(lexica.values()), new Converter<Lexicon, URI>() {

                @Override
                public URI f(Lexicon e) {
                    return e.getURI();
                }
            });
        }

        public Set<URI> getSenses(URI lexicaURI) {
            final HashSet<URI> senses = new HashSet<URI>();
            for(Lexicon lexicon : lexica.values()) {
                if(lexicon.getURI().equals(lexicaURI)) {
                for(LexicalEntry entry : lexicon.getEntrys()) {
                    for(LexicalSense sense : entry.getSenses()) {
                        senses.add(sense.getReference());
                    }
                }
                }
            }
            return senses;
        }

    }

    @Override
    public LAIFLocalizationLexicon getLexicon(String appKey) {
        if (lexica.containsKey(appKey)) {
            return lexica.get(appKey);
        } else {
            final LAIFLocalizationLexiconImpl lll = new LAIFLocalizationLexiconImpl(appKey);
            lexica.put(appKey, lll);
            return lll;
        }
    }

    @Override
    public void updateRules(String appKey, Language lang, LAIFRuleSet rules) {
        ((LAIFLocalizationLexiconImpl)getLexicon(appKey)).updateRules(lang, rules);
    }

    @Override
    public Set<URI> getLexicaURIs(String appKey) {
        return ((LAIFLocalizationLexiconImpl)getLexicon(appKey)).getLexicaURIs();
    }

    @Override
    @Deprecated
    public Set<URI> getForms(String appKey, URI lexicaURI) {
        return ((LAIFLocalizationLexiconImpl)getLexicon(appKey)).getSenses(lexicaURI);
    }
}


text:
namespace Vk.Api.Schema.Parameters.Note
{
    /// <summary>
    /// Интерфейс для представления параметров запроса для notes.delete <para/>
    /// Документация: <see href="https://vk.com/dev/notes.delete"/>
    /// </summary>
    public interface INoteDeleteParameters
    {
        /// <summary>
        /// Идентификатор заметки
        /// </summary>
        /// <remarks>
        /// Положительное число, обязательный параметр
        /// </remarks>
        int NoteId { get; set; }
    }
}


text:
package net.ontrack.core.support.json;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.std.SerializerBase;
import org.joda.time.LocalTime;

public class LocalTimeSerializer extends SerializerBase<LocalTime> {

	public LocalTimeSerializer() {
		super(LocalTime.class);
	}

	@Override
	public void serialize(LocalTime value, JsonGenerator jgen,
			SerializerProvider provider) throws IOException,
			JsonGenerationException {
		jgen.writeString(value.toString("HH:mm"));
	}

}


text:
RSpec.describe A9n::Struct do
  context 'without any values' do
    subject { described_class.new }

    describe '#empty?' do
      it { expect(subject).to be_empty }
    end

    describe '#keys' do
      it { expect(subject.keys).to eq([]) }
    end

    describe '#key?' do
      it { expect(subject.key?(:foo)).to eq(false) }
    end

    describe '#[]' do
      it { expect(subject[:foo]).to eq(nil) }
    end

    describe '#fetch' do
      it do
        expect { subject.fetch(:foo) }.to raise_error(KeyError)
      end

      it do
        expect(subject.fetch(:foo, 'hello')).to eq('hello')
      end
    end

    describe '#find' do
      it do
        expect { subject.find(:foo) }.to raise_error(A9n::KeyNotFoundError)
      end
    end

    it 'raises error on accessin invalid attribute' do
      expect {
        subject.foo
      }.to raise_error(A9n::KeyNotFoundError, 'Could not find foo in []')
    end
  end

  context 'with values' do
    subject { described_class.new(data) }

    let(:data) do
      {
        non_empty_foo: 'foo',
        nil_foo: nil,
        false_foo: false,
        true_foo: true,
        hash_foo: { foo: 'hello' }
      }
    end

    describe '#keys' do
      it do
        expect(subject.keys).to eq [:non_empty_foo, :nil_foo, :false_foo, :true_foo, :hash_foo]
      end
    end

    describe '#to_h' do
      it do
        expect(subject.to_h).to be_kind_of(Hash)
        expect(subject.to_h).to eq(data)
      end
    end

    describe '#to_hash' do
      it do
        expect(subject.to_hash).to be_kind_of(Hash)
        expect(subject.to_hash).to eq(data)
      end
    end

    describe '#key?' do
      it { expect(subject.key?(:nil_foo)).to eq(true) }
      it { expect(subject.key?(:unknown)).to eq(false) }
    end

    describe '#merge' do
      before { subject.merge(argument) }

      context 'hash' do
        let(:argument) { { non_empty_foo: 'hello foo' } }

        it do
          expect(subject.non_empty_foo).to eq('hello foo')
        end
      end

      context 'struct' do
        let(:argument) { described_class.new(non_empty_foo: 'hello foo') }

        it do
          expect(subject.non_empty_foo).to eq('hello foo')
        end
      end
    end

    it 'is not empty' do
      expect(subject).not_to be_empty
    end

    it 'gets non-empty value' do
      expect(subject.non_empty_foo).to eq('foo')
    end

    it 'gets nil value' do
      expect(subject.nil_foo).to eq(nil)
    end

    it 'gets true value' do
      expect(subject.true_foo).to eq(true)
    end

    it 'gets false value' do
      expect(subject.false_foo).to eq(false)
    end

    it 'gets hash value' do
      expect(subject.hash_foo).to be_kind_of(Hash)
    end

    it 'raises exception when value not exists' do
      expect {
        subject.non_existing_foo
      }.to raise_error(
        A9n::KeyNotFoundError,
        'Could not find non_existing_foo in [:non_empty_foo, :nil_foo, :false_foo, :true_foo, :hash_foo]'
      )
    end

    describe '#[]' do
      it 'returns non empty value' do
        expect(subject[:non_empty_foo]).to eq('foo')
      end

      it 'returns false value' do
        expect(subject[:false_foo]).to eq(false)
      end

      it 'returns nil value' do
        expect(subject[:nil_foo]).to eq(nil)
      end

      it 'returns nil for non existing key' do
        expect(subject[:non_existing_foo]).to eq(nil)
      end
    end

    describe '#find' do
      it 'returns non empty value' do
        expect(subject.find(:non_empty_foo)).to eq('foo')
      end

      it 'returns false value' do
        expect(subject.find('false_foo')).to eq(false)
      end

      it 'returns nil value' do
        expect(subject.find(:nil_foo)).to eq(nil)
      end

      it 'raises error for non existing key' do
        expect {
          subject.find(:non_existing_foo)
        }.to raise_error(A9n::KeyNotFoundError)
      end
    end

    describe '#fetch' do
      it 'returns non empty value' do
        expect(subject.fetch(:non_empty_foo)).to eq('foo')
      end

      it 'returns false value' do
        expect(subject.fetch(:false_foo)).to eq(false)
      end

      it 'returns nil value' do
        expect(subject.fetch(:nil_foo)).to eq(nil)
      end

      it 'returns default for non existing value' do
        expect(subject.fetch(:non_existing_foo, 'hello')).to eq('hello')
      end

      it 'raises error for non existing key' do
        expect {
          subject.fetch(:non_existing_foo)
        }.to raise_error(KeyError)
      end
    end
  end
end


text:
describe BandwidthIris::EmergencyNotificationEndpoints do
  client = nil

  before :each do
    client = Helper.get_client()
  end

  after :each do
    client.stubs.verify_stubbed_calls()
  end

  describe '#EneTests' do
    it 'should create ene order' do
      data = {
          :value => "value"
      }
      client.stubs.post("/v1.0/accounts/accountId/emergencyNotificationEndpointOrders", client.build_xml({:emergency_notification_endpoint_order => data})) {|env| [200, {}, Helper.xml['emergencyNotificationEndpointOrder']]}
      ene_order = EmergencyNotificationEndpoints.create_emergency_notification_endpoint_order(client, data)
      expect(ene_order[:order_id]).to eql("3e9a852e-2d1d-4e2d-84c3-87223a78cb70")
    end

    it 'should get ene orders' do
      client.stubs.get("/v1.0/accounts/accountId/emergencyNotificationEndpointOrders") {|env| [200, {}, Helper.xml['emergencyNotificationEndpointOrders']]}
      ene_orders = EmergencyNotificationEndpoints.get_emergency_notification_endpoint_orders(client)
      expect(ene_orders[:emergency_notification_endpoint_orders][:emergency_notification_endpoint_order][0][:order_id]).to eql("3e9a852e-2d1d-4e2d-84c3-87223a78cb70")
    end

    it 'should get ene order' do
      client.stubs.get("/v1.0/accounts/accountId/emergencyNotificationEndpointOrders/id") {|env| [200, {}, Helper.xml['emergencyNotificationEndpointOrder']]}
      ene_order = EmergencyNotificationEndpoints.get_emergency_notification_endpoint_order(client, "id")
      expect(ene_order[:order_id]).to eql("3e9a852e-2d1d-4e2d-84c3-87223a78cb70")
    end
  end
end


text:
package com.datastax.oss.driver.internal.core.loadbalancing;

import com.datastax.oss.driver.api.core.ConsistencyLevel;
import com.datastax.oss.driver.api.core.CqlIdentifier;
import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
import com.datastax.oss.driver.api.core.config.DriverExecutionProfile;
import com.datastax.oss.driver.api.core.context.DriverContext;
import com.datastax.oss.driver.api.core.cql.Statement;
import com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy;
import com.datastax.oss.driver.api.core.loadbalancing.NodeDistance;
import com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator;
import com.datastax.oss.driver.api.core.metadata.Node;
import com.datastax.oss.driver.api.core.metadata.NodeState;
import com.datastax.oss.driver.api.core.metadata.TokenMap;
import com.datastax.oss.driver.api.core.metadata.token.Token;
import com.datastax.oss.driver.api.core.session.Request;
import com.datastax.oss.driver.api.core.session.Session;
import com.datastax.oss.driver.internal.core.context.InternalDriverContext;
import com.datastax.oss.driver.internal.core.loadbalancing.helper.DefaultNodeDistanceEvaluatorHelper;
import com.datastax.oss.driver.internal.core.loadbalancing.helper.OptionalLocalDcHelper;
import com.datastax.oss.driver.internal.core.loadbalancing.nodeset.DcAgnosticNodeSet;
import com.datastax.oss.driver.internal.core.loadbalancing.nodeset.MultiDcNodeSet;
import com.datastax.oss.driver.internal.core.loadbalancing.nodeset.NodeSet;
import com.datastax.oss.driver.internal.core.loadbalancing.nodeset.SingleDcNodeSet;
import com.datastax.oss.driver.internal.core.util.ArrayUtils;
import com.datastax.oss.driver.internal.core.util.collection.CompositeQueryPlan;
import com.datastax.oss.driver.internal.core.util.collection.LazyQueryPlan;
import com.datastax.oss.driver.internal.core.util.collection.QueryPlan;
import com.datastax.oss.driver.internal.core.util.collection.SimpleQueryPlan;
import com.datastax.oss.driver.shaded.guava.common.base.Predicates;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;
import net.jcip.annotations.ThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A basic implementation of {@link LoadBalancingPolicy} that can serve as a building block for more
 * advanced use cases.
 *
 *
To activate this policy, modify the {@code basic.load-balancing-policy} section in the driver
 * configuration, for example:
 *
 *

 * datastax-java-driver {
 *   basic.load-balancing-policy {
 *     class = BasicLoadBalancingPolicy
 *     local-datacenter = datacenter1 # optional
 *   }
 * }
 *

 *
 * See {@code reference.conf} (in the manual or core driver JAR) for more details.
 *
 *
Local datacenter: This implementation will only define a local datacenter if it is
 * explicitly set either through configuration or programmatically; if the local datacenter is
 * unspecified, this implementation will effectively act as a datacenter-agnostic load balancing
 * policy and will consider all nodes in the cluster when creating query plans, regardless of their
 * datacenter.
 *
 *
Query plan: This implementation prioritizes replica nodes over non-replica ones; if
 * more than one replica is available, the replicas will be shuffled. Non-replica nodes will be
 * included in a round-robin fashion. If the local datacenter is defined (see above), query plans
 * will only include local nodes, never remote ones; if it is unspecified however, query plans may
 * contain nodes from different datacenters.
 *
 *
This class is not recommended for normal users who should always prefer {@link
 * DefaultLoadBalancingPolicy}.
 */
@ThreadSafe
public class BasicLoadBalancingPolicy implements LoadBalancingPolicy {

  private static final Logger LOG = LoggerFactory.getLogger(BasicLoadBalancingPolicy.class);

  protected static final IntUnaryOperator INCREMENT = i -> (i == Integer.MAX_VALUE) ? 0 : i + 1;
  private static final Object[] EMPTY_NODES = new Object[0];

  @NonNull protected final InternalDriverContext context;
  @NonNull protected final DriverExecutionProfile profile;
  @NonNull protected final String logPrefix;

  protected final AtomicInteger roundRobinAmount = new AtomicInteger();

  private final int maxNodesPerRemoteDc;
  private final boolean allowDcFailoverForLocalCl;
  private final ConsistencyLevel defaultConsistencyLevel;

  // private because they should be set in init() and never be modified after
  private volatile DistanceReporter distanceReporter;
  private volatile NodeDistanceEvaluator nodeDistanceEvaluator;
  private volatile String localDc;
  private volatile NodeSet liveNodes;

  public BasicLoadBalancingPolicy(@NonNull DriverContext context, @NonNull String profileName) {
    this.context = (InternalDriverContext) context;
    profile = context.getConfig().getProfile(profileName);
    logPrefix = context.getSessionName() + "|" + profileName;
    maxNodesPerRemoteDc =
        profile.getInt(DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC);
    allowDcFailoverForLocalCl =
        profile.getBoolean(
            DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_ALLOW_FOR_LOCAL_CONSISTENCY_LEVELS);
    defaultConsistencyLevel =
        this.context
            .getConsistencyLevelRegistry()
            .nameToLevel(profile.getString(DefaultDriverOption.REQUEST_CONSISTENCY));
  }

  /**
   * Returns the local datacenter name, if known; empty otherwise.
   *
   *
When this method returns null, then datacenter awareness is completely disabled. All
   * non-ignored nodes will be considered "local" regardless of their actual datacenters, and will
   * have equal chances of being selected for query plans.
   *
   *
After the policy is {@linkplain #init(Map, DistanceReporter) initialized} this method will
   * return the local datacenter that was discovered by calling {@link #discoverLocalDc(Map)}.
   * Before initialization, this method always returns null.
   */
  @Nullable
  protected String getLocalDatacenter() {
    return localDc;
  }

  /** @return The nodes currently considered as live. */
  protected NodeSet getLiveNodes() {
    return liveNodes;
  }

  @Override
  public void init(@NonNull Map<UUID, Node> nodes, @NonNull DistanceReporter distanceReporter) {
    this.distanceReporter = distanceReporter;
    localDc = discoverLocalDc(nodes).orElse(null);
    nodeDistanceEvaluator = createNodeDistanceEvaluator(localDc, nodes);
    liveNodes =
        localDc == null
            ? new DcAgnosticNodeSet()
            : maxNodesPerRemoteDc <= 0 ? new SingleDcNodeSet(localDc) : new MultiDcNodeSet();
    for (Node node : nodes.values()) {
      NodeDistance distance = computeNodeDistance(node);
      distanceReporter.setDistance(node, distance);
      if (distance != NodeDistance.IGNORED && node.getState() != NodeState.DOWN) {
        // This includes state == UNKNOWN. If the node turns out to be unreachable, this will be
        // detected when we try to open a pool to it, it will get marked down and this will be
        // signaled back to this policy, which will then remove it from the live set.
        liveNodes.add(node);
      }
    }
  }

  /**
   * Returns the local datacenter, if it can be discovered, or returns {@link Optional#empty empty}
   * otherwise.
   *
   *
This method is called only once, during {@linkplain LoadBalancingPolicy#init(Map,
   * LoadBalancingPolicy.DistanceReporter) initialization}.
   *
   *
Implementors may choose to throw {@link IllegalStateException} instead of returning {@link
   * Optional#empty empty}, if they require a local datacenter to be defined in order to operate
   * properly.
   *
   *
If this method returns empty, then datacenter awareness will be completely disabled. All
   * non-ignored nodes will be considered "local" regardless of their actual datacenters, and will
   * have equal chances of being selected for query plans.
   *
   * @param nodes All the nodes that were known to exist in the cluster (regardless of their state)
   *     when the load balancing policy was initialized. This argument is provided in case
   *     implementors need to inspect the cluster topology to discover the local datacenter.
   * @return The local datacenter, or {@link Optional#empty empty} if none found.
   * @throws IllegalStateException if the local datacenter could not be discovered, and this policy
   *     cannot operate without it.
   */
  @NonNull
  protected Optional<String> discoverLocalDc(@NonNull Map<UUID, Node> nodes) {
    return new OptionalLocalDcHelper(context, profile, logPrefix).discoverLocalDc(nodes);
  }

  /**
   * Creates a new node distance evaluator to use with this policy.
   *
   *
This method is called only once, during {@linkplain LoadBalancingPolicy#init(Map,
   * LoadBalancingPolicy.DistanceReporter) initialization}, and only after local datacenter
   * discovery has been attempted.
   *
   * @param localDc The local datacenter that was just discovered, or null if none found.
   * @param nodes All the nodes that were known to exist in the cluster (regardless of their state)
   *     when the load balancing policy was initialized. This argument is provided in case
   *     implementors need to inspect the cluster topology to create the evaluator.
   * @return the distance evaluator to use.
   */
  @NonNull
  protected NodeDistanceEvaluator createNodeDistanceEvaluator(
      @Nullable String localDc, @NonNull Map<UUID, Node> nodes) {
    return new DefaultNodeDistanceEvaluatorHelper(context, profile, logPrefix)
        .createNodeDistanceEvaluator(localDc, nodes);
  }

  @NonNull
  @Override
  public Queue<Node> newQueryPlan(@Nullable Request request, @Nullable Session session) {
    // Take a snapshot since the set is concurrent:
    Object[] currentNodes = liveNodes.dc(localDc).toArray();

    Set<Node> allReplicas = getReplicas(request, session);
    int replicaCount = 0; // in currentNodes

    if (!allReplicas.isEmpty()) {
      // Move replicas to the beginning
      for (int i = 0; i < currentNodes.length; i++) {
        Node node = (Node) currentNodes[i];
        if (allReplicas.contains(node)) {
          ArrayUtils.bubbleUp(currentNodes, i, replicaCount);
          replicaCount += 1;
        }
      }

      if (replicaCount > 1) {
        shuffleHead(currentNodes, replicaCount);
      }
    }

    LOG.trace("[{}] Prioritizing {} local replicas", logPrefix, replicaCount);

    // Round-robin the remaining nodes
    ArrayUtils.rotate(
        currentNodes,
        replicaCount,
        currentNodes.length - replicaCount,
        roundRobinAmount.getAndUpdate(INCREMENT));

    QueryPlan plan = currentNodes.length == 0 ? QueryPlan.EMPTY : new SimpleQueryPlan(currentNodes);
    return maybeAddDcFailover(request, plan);
  }

  @NonNull
  protected Set<Node> getReplicas(@Nullable Request request, @Nullable Session session) {
    if (request == null || session == null) {
      return Collections.emptySet();
    }

    Optional<TokenMap> maybeTokenMap = context.getMetadataManager().getMetadata().getTokenMap();
    if (!maybeTokenMap.isPresent()) {
      return Collections.emptySet();
    }

    // Note: we're on the hot path and the getXxx methods are potentially more than simple getters,
    // so we only call each method when strictly necessary (which is why the code below looks a bit
    // weird).
    CqlIdentifier keyspace;
    Token token;
    ByteBuffer key;
    try {
      keyspace = request.getKeyspace();
      if (keyspace == null) {
        keyspace = request.getRoutingKeyspace();
      }
      if (keyspace == null && session.getKeyspace().isPresent()) {
        keyspace = session.getKeyspace().get();
      }
      if (keyspace == null) {
        return Collections.emptySet();
      }

      token = request.getRoutingToken();
      key = (token == null) ? request.getRoutingKey() : null;
      if (token == null && key == null) {
        return Collections.emptySet();
      }
    } catch (Exception e) {
      // Protect against poorly-implemented Request instances
      LOG.error("Unexpected error while trying to compute query plan", e);
      return Collections.emptySet();
    }

    TokenMap tokenMap = maybeTokenMap.get();
    return token != null
        ? tokenMap.getReplicas(keyspace, token)
        : tokenMap.getReplicas(keyspace, key);
  }

  @NonNull
  protected Queue<Node> maybeAddDcFailover(@Nullable Request request, @NonNull Queue<Node> local) {
    if (maxNodesPerRemoteDc <= 0 || localDc == null) {
      return local;
    }
    if (!allowDcFailoverForLocalCl && request instanceof Statement) {
      Statement<?> statement = (Statement<?>) request;
      ConsistencyLevel consistency = statement.getConsistencyLevel();
      if (consistency == null) {
        consistency = defaultConsistencyLevel;
      }
      if (consistency.isDcLocal()) {
        return local;
      }
    }
    QueryPlan remote =
        new LazyQueryPlan() {

          @Override
          protected Object[] computeNodes() {
            Object[] remoteNodes =
                liveNodes.dcs().stream()
                    .filter(Predicates.not(Predicates.equalTo(localDc)))
                    .flatMap(dc -> liveNodes.dc(dc).stream().limit(maxNodesPerRemoteDc))
                    .toArray();

            int remoteNodesLength = remoteNodes.length;
            if (remoteNodesLength == 0) {
              return EMPTY_NODES;
            }
            shuffleHead(remoteNodes, remoteNodesLength);
            return remoteNodes;
          }
        };

    return new CompositeQueryPlan(local, remote);
  }

  /** Exposed as a protected method so that it can be accessed by tests */
  protected void shuffleHead(Object[] currentNodes, int headLength) {
    ArrayUtils.shuffleHead(currentNodes, headLength);
  }

  @Override
  public void onAdd(@NonNull Node node) {
    NodeDistance distance = computeNodeDistance(node);
    // Setting to a non-ignored distance triggers the session to open a pool, which will in turn
    // set the node UP when the first channel gets opened, then #onUp will be called, and the
    // node will be eventually added to the live set.
    distanceReporter.setDistance(node, distance);
    LOG.debug("[{}] {} was added, setting distance to {}", logPrefix, node, distance);
  }

  @Override
  public void onUp(@NonNull Node node) {
    NodeDistance distance = computeNodeDistance(node);
    if (node.getDistance() != distance) {
      distanceReporter.setDistance(node, distance);
    }
    if (distance != NodeDistance.IGNORED && liveNodes.add(node)) {
      LOG.debug("[{}] {} came back UP, added to live set", logPrefix, node);
    }
  }

  @Override
  public void onDown(@NonNull Node node) {
    if (liveNodes.remove(node)) {
      LOG.debug("[{}] {} went DOWN, removed from live set", logPrefix, node);
    }
  }

  @Override
  public void onRemove(@NonNull Node node) {
    if (liveNodes.remove(node)) {
      LOG.debug("[{}] {} was removed, removed from live set", logPrefix, node);
    }
  }

  /**
   * Computes the distance of the given node.
   *
   *
This method is called during {@linkplain #init(Map, DistanceReporter) initialization}, when
   * a node {@linkplain #onAdd(Node) is added}, and when a node {@linkplain #onUp(Node) is back UP}.
   */
  protected NodeDistance computeNodeDistance(@NonNull Node node) {
    // We interrogate the custom evaluator every time since it could be dynamic
    // and change its verdict between two invocations of this method.
    NodeDistance distance = nodeDistanceEvaluator.evaluateDistance(node, localDc);
    if (distance != null) {
      return distance;
    }
    // no local DC defined: all nodes are considered LOCAL.
    if (localDc == null) {
      return NodeDistance.LOCAL;
    }
    // otherwise, the node is LOCAL if its datacenter is the local datacenter.
    if (Objects.equals(node.getDatacenter(), localDc)) {
      return NodeDistance.LOCAL;
    }
    // otherwise, the node will be either REMOTE or IGNORED, depending
    // on how many remote nodes we accept per DC.
    if (maxNodesPerRemoteDc > 0) {
      Object[] remoteNodes = liveNodes.dc(node.getDatacenter()).toArray();
      for (int i = 0; i < maxNodesPerRemoteDc; i++) {
        if (i == remoteNodes.length) {
          // there is still room for one more REMOTE node in this DC
          return NodeDistance.REMOTE;
        } else if (remoteNodes[i] == node) {
          return NodeDistance.REMOTE;
        }
      }
    }
    return NodeDistance.IGNORED;
  }

  @Override
  public void close() {
    // nothing to do
  }
}


text:
HBaseThrift
===========

Sample code for working with HBase Thrift.