text:
<?php

/** Zend_Controller_Action */
require_once 'Zend/Controller/Action.php';

/** Zend_Wildfire_Plugin_FirePhp */
require_once 'Zend/Wildfire/Plugin/FirePhp.php';

/**
 * Tests for Zend_Log_Writer_Firebug
 *
 * @category   Zend
 * @package    Zend_Wildfire
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class ZendLogWriterFirebugController extends Zend_Controller_Action
{

    public function testloggingAction()
    {
        $logger = Zend_Registry::get('logger');

        $logger->log('Emergency: system is unusable',            Zend_Log::EMERG);
        $logger->log('Alert: action must be taken immediately',  Zend_Log::ALERT);
        $logger->log('Critical: critical conditions',            Zend_Log::CRIT);
        $logger->log('Error: error conditions',                  Zend_Log::ERR);
        $logger->log('Warning: warning conditions',              Zend_Log::WARN);
        $logger->log('Notice: normal but significant condition', Zend_Log::NOTICE);
        $logger->log('Informational: informational messages',    Zend_Log::INFO);
        $logger->log('Debug: debug messages',                    Zend_Log::DEBUG);
        $logger->log(array('$_SERVER',$_SERVER),                 Zend_Log::DEBUG);

        $logger->trace('Trace to here');

        $table = array('Summary line for the table',
                       array(
                           array('Column 1', 'Column 2'),
                           array('Row 1 c 1',' Row 1 c 2'),
                           array('Row 2 c 1',' Row 2 c 2')
                       )
                      );
        $logger->table($table);
    }

    public function testgroupedloggingAction()
    {
        $logger = Zend_Registry::get('logger');

        Zend_Wildfire_Plugin_FirePhp::group("Collapsed Group", array('Collapsed' => true));
            $logger->log('Message in collapsed group', Zend_Log::DEBUG);
        Zend_Wildfire_Plugin_FirePhp::groupEnd();

        Zend_Wildfire_Plugin_FirePhp::group("Expanded Group", array('Collapsed' => false));
            $logger->log('Message in expanded group', Zend_Log::DEBUG);
        Zend_Wildfire_Plugin_FirePhp::groupEnd();
    }

    public function testerrorcontrollerAction()
    {
        require_once 'Zend/Exception.php';
        throw new Zend_Exception('Test Exception');
    }

    public function testlargemessageAction()
    {
        $message = array();

        for ( $i=0 ; $i<300 ; $i++ ) {
            $message[] = 'This is message #' . $i;
        }

        $logger = Zend_Registry::get('logger');
        $logger->log($message, Zend_Log::INFO);
    }
}


text:
/*
 * This file was semi-automatically converted from the public-domain USGS PROJ source.
 */
package com.jhlabs.map.proj;

import java.awt.*;
import java.awt.geom.*;
import com.jhlabs.map.*;

public class SinusoidalProjection extends PseudoCylindricalProjection {

	public Point2D.Double project(double lam, double phi, Point2D.Double xy) {
		xy.x = lam * Math.cos(phi);
		xy.y = phi;
		return xy;
	}

	public Point2D.Double projectInverse(double x, double y, Point2D.Double lp) {
		lp.x = x / Math.cos(y);
		lp.y = y;
		return lp;
	}

	public double getWidth(double y) {
		return MapMath.normalizeLongitude(Math.PI) * Math.cos(y);
	}

	public boolean hasInverse() {
		return true;
	}

	public String toString() {
		return "Sinusoidal";
	}

}

redpajama_set_name: RedPajamaGithub


text:
layout: updates/post
title: "sourceMappingURL and sourceURL syntax changed"
published_on: 2013-06-13
updated_on: 2013-06-13
authors:
  - paulirish
tags:
  - news
  - devtools
---
If you use either sourcemaps or sourceURL (both covered in the [HTML5 Rocks Primer on Sourcemaps](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/)), then you may see a warning in Chrome console like `"/*@ sourceMappingURL=" source mapping URL declaration is deprecated, "/*# sourceMappingURL=" declaration should be used instead.`

![]({{site.WFBaseUrl}}/updates/images/2013/06/sourcemapping/37clIgB.png)

Here's what that's about:

###Impetus
`//@ sourceMappingURL` [was found](http://bugs.jquery.com/ticket/13274) to have a conflict with IE whenever it was
found in the page after `//@cc_on` was interpreted to turn on conditional
compilation in the IE JScript engine. A legacy version of the HTML5 Shiv is one
particular offender here.

### Spec Change
The `//@ sourceMappingURL` syntax is defined in the [Sourcemap V3 spec] (https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.lmz475t4mvbx)
It was changed there to use `//#` syntax instead.

###sourceURL
`//@ sourceURL` is also defined in the spec and was made to match the `//#` syntax
for consistency. Follow through, for details on
[what sourceURL does](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl). It's used by Ember's [minispade](https://github.com/wycats/minispade), Google's [concatenate.js](https://github.com/google/concatenate.js), and others. In Chrome, `sourceURL` is supported for inline scripts and inline styles, in addition to evaluated JS.

###Implementation in Browser DevTools = done!

* **Safari Inspector** now supports `//#` for sourceMappingURL and sourceURL
* **Firebug's** change [has
  landed](https://github.com/firebug/firebug/commit/f14828954c4f9e07e8b86f9317713e774c9ad5d5)
  for sourceURL.
* **Firefox** [landed](https://bugzilla.mozilla.org/show_bug.cgi?id=870361) the change for
  sourceMappingURL. The sourceURL [ticket is
  here](https://bugzilla.mozilla.org/show_bug.cgi?id=833744).
* **Chrome** **DevTools** [landed the
  change](https://codereview.chromium.org/15832007) for sourceMappingURL and
  sourceURL. It will also warn about use of the deprecated `//@` syntax.

While these changes make their way to stable release, you can use both syntaxes simultaneously for full tool support or migrate immediately to the `#` syntax, depending on your needs.


text:
package org.appenders.log4j2.elasticsearch.metrics;

import org.appenders.log4j2.elasticsearch.LifeCycle;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class BasicMetricOutputsRegistryTest {

    @Test
    public void isEmptyByDefault() {

        // when
        final MetricOutputsRegistry registry = new BasicMetricOutputsRegistry();

        // then
        assertEquals(0, registry.get(output -> true).size());

    }

    @Test
    public void addsGivenMetricOutput() {

        // given
        final MetricOutputsRegistry registry = new BasicMetricOutputsRegistry();

        // when
        registry.register(MetricOutputTest.dummy());

        // then
        assertEquals(1, registry.get(output -> true).size());

    }

    @Test
    public void removesGivenMetricOutput() {

        // given
        final MetricOutput metricOutput = spy(MetricOutputTest.dummy());
        final MetricOutputsRegistry registry = new BasicMetricOutputsRegistry();
        registry.register(metricOutput);

        assertEquals(1, registry.get(output -> true).size());

        // when
        registry.deregister(metricOutput.getName());

        // then
        assertEquals(0, registry.get(output -> true).size());

    }

    @Test
    public void versionIsIncrementedOnMetricOutputAddition() {

        // given
        final MetricOutputsRegistry registry = new BasicMetricOutputsRegistry();
        final MetricOutput metricOutput = spy(MetricOutputTest.dummy());

        assertEquals(1, registry.version());

        // when
        registry.register(metricOutput);

        // then
        assertEquals(2, registry.version());

    }

    @Test
    public void versionIsIncrementedOnMetricOutputRemoval() {

        // given
        final MetricOutput metricOutput1 = spy(MetricOutputTest.dummy());
        final MetricOutput metricOutput2 = spy(MetricOutputTest.dummy());
        final MetricOutputsRegistry registry = createTestMetricOutputRegistry(metricOutput1, metricOutput2);

        assertEquals(1, registry.version());

        // when
        registry.deregister(metricOutput1.getName());
        registry.deregister(metricOutput2);

        // then
        assertEquals(3, registry.version());

    }

    protected BasicMetricOutputsRegistry createTestMetricOutputRegistry(final MetricOutput... metricOutputs) {
        return new BasicMetricOutputsRegistry(metricOutputs);
    }

    @Test
    public void versionIsNotIncrementedOnUnsuccessfulMetricOutputRemoval() {

        // given
        final MetricOutput metricOutput1 = spy(MetricOutputTest.dummy());
        final MetricOutput metricOutput2 = spy(MetricOutputTest.dummy());
        final MetricOutputsRegistry registry = createTestMetricOutputRegistry(metricOutput1, metricOutput2);

        registry.clear();

        assertEquals(2, registry.version());

        // when
        registry.deregister(metricOutput1.getName());
        registry.deregister(metricOutput2);

        // then
        assertEquals(2, registry.version());

    }

    @Test
    public void initialVersionIsAlwaysEqualToOne() {

        // given
        final MetricOutputsRegistry registry1 = new BasicMetricOutputsRegistry();
        final MetricOutputsRegistry registry2 = new BasicMetricOutputsRegistry(MetricOutputTest.dummy());

        // when
        final long registry1version = registry1.version();
        final long registry2version = registry2.version();

        // then
        assertEquals(1, registry1version);
        assertEquals(1, registry2version);

    }

    @Test
    public void clearRemovesAllMetricOutputs() {

        // given
        final MetricOutputsRegistry registry = new BasicMetricOutputsRegistry(MetricOutputTest.dummy());
        registry.register(MetricOutputTest.dummy());

        assertEquals(2, registry.get(output -> true).size());

        // when
        registry.clear();

        // then
        assertEquals(3, registry.version());
        assertEquals(0, registry.get(output -> true).size());

    }

    // =========
    // LIFECYCLE
    // =========

    @Test
    public void lifecycleStartsOnlyOnce() {

        // given
        final MetricOutput metricOutput = spy(MetricOutputTest.dummy());
        when(metricOutput.accepts(any())).thenReturn(true);

        final LifeCycle lifeCycle = createLifeCycleTestObject(metricOutput);

        // when
        lifeCycle.start();
        lifeCycle.start();

        // then
        assertFalse(lifeCycle.isStopped());
        assertTrue(lifeCycle.isStarted());

        verify(LifeCycle.of(metricOutput)).start();

    }

    @Test
    public void lifecycleStopStopsOnlyOnce() {

        // given
        final MetricOutput metricOutput = spy(MetricOutputTest.dummy());
        when(metricOutput.accepts(any())).thenReturn(true);

        final LifeCycle lifeCycle = createLifeCycleTestObject(metricOutput);

        lifeCycle.start();
        assertTrue(lifeCycle.isStarted());

        // when
        lifeCycle.stop();
        lifeCycle.stop();

        // then
        assertTrue(lifeCycle.isStopped());
        assertFalse(lifeCycle.isStarted());

        verify(LifeCycle.of(metricOutput)).stop();

    }

    @Test
    public void lifecycleStart() {

        // given
        final MetricOutput metricOutput = spy(MetricOutputTest.dummy());
        when(metricOutput.accepts(any())).thenReturn(true);

        final LifeCycle lifeCycle = createLifeCycleTestObject(metricOutput);

        assertTrue(lifeCycle.isStopped());

        // when
        lifeCycle.start();
        lifeCycle.start();

        // then
        assertTrue(lifeCycle.isStarted());
        assertFalse(lifeCycle.isStopped());

        verify(LifeCycle.of(metricOutput)).start();

    }

    @Test
    public void lifecycleStop() {

        // given
        final MetricOutput metricOutput = spy(MetricOutputTest.dummy());
        when(metricOutput.accepts(any())).thenReturn(true);

        final LifeCycle lifeCycle = createLifeCycleTestObject(metricOutput);

        assertTrue(lifeCycle.isStopped());

        lifeCycle.start();
        assertTrue(lifeCycle.isStarted());

        // when
        lifeCycle.stop();
        lifeCycle.stop();

        // then
        assertFalse(lifeCycle.isStarted());
        assertTrue(lifeCycle.isStopped());

        verify(LifeCycle.of(metricOutput)).stop();

    }

    private LifeCycle createLifeCycleTestObject(final MetricOutput... metricOutputs) {
        return new BasicMetricOutputsRegistry(metricOutputs);
    }

}


text:
package org.activequant.optimizations.util;

import java.util.List;

/**
 *
 * The Permutator knows how to permute objects of type T.
 *
 * @author Ghost Rider
 *
 * @param <T> an object of which to generate permutations.
 */
public interface IPermutator<S,T> {
	public List<T> permutations(S permutateBase);
}


text:
package io.github.exaberries.boa.gui.data;

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class CueTableDataModel {
	private IntegerProperty index;
	private StringProperty name;
	private IntegerProperty fade;

	public CueTableDataModel(int index, String name, int fade) {
		this.index = new SimpleIntegerProperty(index);
		this.name = new SimpleStringProperty(name);
		this.fade = new SimpleIntegerProperty(fade);
	}

	public IntegerProperty indexProperty() {
		return index;
	}

	public StringProperty nameProperty() {
		return name;
	}

	public IntegerProperty fadeProperty() {
		return fade;
	}
}


text:
int main(int argc, char * argv[]) {
    int returnValue;

    @autoreleasepool {

#ifdef DEBUG
        BOOL inTests = NSClassFromString(@"XCTest") != nil;

        if (inTests) {
            //use a special empty delegate when we are inside the tests
            returnValue = UIApplicationMain(argc, argv, nil, @"TestsAppDelegate");
        }
        else {
            //use the normal delegate
            returnValue = UIApplicationMain(argc, argv, nil, @"AppDelegate");
        }
#endif

        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }

    return returnValue;
}


text:
import { call, ifProp, switchProp, prop } from 'styled-tools'
import { subtract, add, always } from 'lodash/fp'
import { setDisplayName } from 'recompose'
import styled, { css } from 'styled-components'

import { arrowTop, arrowBottom, arrowLeft, arrowRight } from '../../mixins'
import { getters as g } from '../../util'

export const TooltipWrapper = setDisplayName('TooltipWrapper')(styled.div`
  display: inline-block;
`)

export const TooltipPosition = setDisplayName('TooltipPosition')(styled.div`
  position: fixed;
  transform: scale(0.6);
  opacity: 0;
  z-index: 999999;
  transition: opacity 0.2s ${g.animationCurveLinearOutSlowIn},
              transform 0.2s ${g.animationCurveLinearOutSlowIn};
  ${ifProp('isVisible', css`
    opacity: 1;
    transform: none;
  `)}
  ${switchProp('position', {
    above: css`
      top: ${call(subtract, prop('y'), always(7))}px;
      left: ${prop('x')}px;
      transform-origin: bottom center;
    `,
    below: css`
      top: ${call(add, prop('y'), always(7))}px;
      left: ${prop('x')}px;
      transform-origin: top center;
    `,
    left: css`
      top: ${prop('y')}px;
      left: ${call(subtract, prop('x'), always(7))}px;
      transform-origin: center right;
    `,
    right: css`
      top: ${prop('y')}px;
      left: ${call(add, prop('x'), always(7))}px;
      transform-origin: center left;
    `,
  })}
`)

export const TooltipStyle = setDisplayName('TooltipBase')(styled.div`
  display: block;
  background: ${g.tooltipBackgroundColor};
  color: ${g.tooltipTextColor};
  font-size: ${g.tooltipFontSize}px;
  line-height: 14px;
  padding: 8px;
  border-radius: 2px;
  user-select: none;
  pointer-events: none;
  position: absolute;
  white-space: nowrap;
  text-align: center;
  ${ifProp('large', css`
    font-size: ${g.tooltipFontSizeLarge}px;
    padding: 16px;
  `)}
  ${switchProp('position', {
    above: css`
      transform: translate(-50%, -100%);
      ${call(arrowBottom('5px'), g.tooltipBackgroundColor)}
    `,
    below: css`
      transform: translate(-50%, 0);
      ${call(arrowTop('5px'), g.tooltipBackgroundColor)}
    `,
    left: css`
      transform: translate(-100%, -50%);
      ${call(arrowRight('5px'), g.tooltipBackgroundColor)}
    `,
    right: css`
      transform: translate(0%, -50%);
      ${call(arrowLeft('5px'), g.tooltipBackgroundColor)}
    `,
  })}
`)


text:
title:  "Rust on AWS Lambda"
date:   2015-11-17 15:10:00
description: "Creating a micro-service with Rust code on AWS Lambda"
tags: ["rust", "aws", "lambda"]
---

[AWS Lambda](http://aws.amazon.com/lambda/) is an amazing event-based compute service capable of running a function without worrying about the underlying infrastructure. Currently it supports Node.js, Java (and JVM based langs) & Python. It's a brilliant tool for micro-services.

In this article I'll show you how to run some Rust code on AWS Lambda even if Rust is not officially supported.

## Our micro-service

We will create a simple service that will determine if a string is a valid email address.

Let's start a new cargo project:

```
λ cargo new email-checker --bin
```

We will need the `regex` crate. In `Cargo.toml`:

```toml
[dependencies]
regex = "0.1.41"
```

Then our service implementation in `src/main.rs`:

```rust
extern crate regex;
use regex::Regex;
use std::env;

fn main() {
    println!("Starting email-checker...");

    // Create an email regular expression
    let re = Regex::new(r"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$").unwrap();

    // Match the first argument against the regular expression
    match env::args().nth(1) {
        // We have an argument
        Some(email) => {
            if re.is_match(&email) {
                println!("{} is a valid email.", email);
            } else {
                println!("{} is NOT a valid email.", email);
            }
        }
        // No argument provided
        None => {
            println!("Please provide a string to test.");
            return;
        }
    };
};
```

## Generate a Rust binary

My machine is running OS X, AWS Lambda runs Linux. I tried to cross-compile a Linux binary on Darwin but that was too much of a hassle. In order to get the same environment as my lambda function will run on, I simply created an EC2 t2.micro instance to compile my code.

Create an Amazon Linux EC2 instance, ssh onto it and run:

```
λ sudo yum install git
λ sudo yum groupinstall "Development Tools"
```

to get a working development environment. Then clone your email-checker repo and run:

```
λ cargo build --release
λ cp target/release/email-checker ./email-checker-linux
```

We now have a working Linux binary w00t! Commit and push the binary to your repo, you can terminate the instance.

## The Node.js wrapper

Since Rust is not supported by AWS Lambda, we will write a simple Javascript module that will spawn a child process with our Rust binary. That's the main trick of this article :). Note that we could ship a Haskell, Go, OCaml or whatever binary the same way.

Let's create a main.js at the root of our project:

```javascript
var child_process = require('child_process');

exports.handler = function(event, context) {
    // event is the JSON we provide to our lambda function. More on this later.
    console.log(event["email"]);

    // spawn a child process with our email-checker-linux binary and the event["email"] value for our argument.
    var proc = child_process.spawn('./email-checker-linux', [ event["email"] ], { stdio: 'inherit' });

    proc.on('close', function(code) {
        if(code !== 0) {
            return context.done(new Error("Process exited with non-zero status code"));
        }

        context.done(null);
    });
}
```

## Packaging our service

In order to upload our code to AWS lambda, we just have to create a zip file containing our `main.js` and our `email-checker-linux` binary.

## Creating a lambda function

Log in to the AWS console, click on `Lambda` in the `Compute` section and click `Get started now`.
We are then shown a list of lambda functions blueprints. We will not use a blueprint for our example so click `Skip`.
Next we need to configure our lambda function.

Fill in the name of the function, its description and choose the Node.js runtime.

![Setup lambda function](/assets/images/lambda1.png)

In the `Lambda function code` section, choose `Upload a .ZIP file` and upload the file we created previously.

In `Lambda function handler and role`, use `main.handler` for the handler and choose the `Basic execution role`. This will open a popup prompting you to create a new `IAM Role`, just allow with the default settings.

Back on our function setup, leave the `Advanced settings` as is and click `Next`.

Finally, we can review and create the function. Congratulations you created your first AWS Lambda function.

## Testing our lambda function

On the lambda function screen click `Actions` then `Configure test event`. Here we can write some JSON that will be received by our Node.js handler as the event parameter.

```json
{
  "email": "karl@marx.com"
}
```

Click `Save and test`. This will execute our lambda function. If you click `Monitoring`, you can see that we ran our function once.

To view the result, click `View logs in CloudWatch`. We're presented with a list of log lines.

![Log lines](/assets/images/lambda4.png)

Click the first line and boom `karl@marx.com` is indeed a valid email.

![Lambda function result](/assets/images/lambda5.png)

## What can we do from here?

Our email checking micro-service is still lacking an interface, we could use [Amazon API gateway](https://aws.amazon.com/api-gateway/) to create a simple endpoint where we could POST the string we want to check and return a proper response for example.

That's it! We successfully ran some Rust code on AWS Lambda. Have fun Rustaceans :)

*You can find the full code and the Linux binary [here](https://github.com/julienXX/email-checker).*


text:
<?php

namespace Service;

class Auth extends \Phalcon\DI\Injectable
{
    private $identity = null;

    public function getIdentity()
    {
        if (!is_null($this->identity)) {
            return $this->identity;
        }

        $session = $this->getDI()->get('session');
        $session->start();

        if ($session->get("userId")) {
            return $this->identity = $this->getDi()->get('em')->getRepository('User\Model\User')->find($session->get("userId"));
        }

        return $this->identity = false;
    }
}


text:
package org.keycloak.services.resources;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.Config;
import org.keycloak.exportimport.ExportImportManager;
import org.keycloak.migration.MigrationModelManager;
import org.keycloak.models.*;
import org.keycloak.models.dblock.DBLockProvider;
import org.keycloak.models.dblock.DBLockManager;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.PostMigrationEvent;
import org.keycloak.models.utils.RepresentationToModel;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.services.DefaultKeycloakSessionFactory;
import org.keycloak.services.ServicesLogger;
import org.keycloak.services.filters.KeycloakTransactionCommitter;
import org.keycloak.services.managers.ApplianceBootstrap;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.managers.UsersSyncManager;
import org.keycloak.services.resources.admin.AdminRoot;
import org.keycloak.services.scheduled.ClearExpiredEvents;
import org.keycloak.services.scheduled.ClearExpiredUserSessions;
import org.keycloak.services.scheduled.ClusterAwareScheduledTaskRunner;
import org.keycloak.services.util.JsonConfigProvider;
import org.keycloak.services.util.ObjectMapperResolver;
import org.keycloak.timer.TimerProvider;
import org.keycloak.transaction.JtaTransactionManagerLookup;
import org.keycloak.util.JsonSerialization;
import org.keycloak.common.util.SystemEnvProperties;

import javax.servlet.ServletContext;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import java.io.*;
import java.net.URI;
import java.net.URL;
import java.util.*;
import org.jboss.dmr.ModelNode;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class KeycloakApplication extends Application {
    // This param name is defined again in Keycloak Server Subsystem class
    // org.keycloak.subsystem.server.extension.KeycloakServerDeploymentProcessor.  We have this value in
    // two places to avoid dependency between Keycloak Subsystem and Keycloak Services module.
    public static final String KEYCLOAK_CONFIG_PARAM_NAME = "org.keycloak.server-subsystem.Config";

    private static final ServicesLogger logger = ServicesLogger.ROOT_LOGGER;

    protected boolean embedded = false;

    protected Set<Object> singletons = new HashSet<Object>();
    protected Set<Class<?>> classes = new HashSet<Class<?>>();

    protected KeycloakSessionFactory sessionFactory;
    protected String contextPath;

    public KeycloakApplication(@Context ServletContext context, @Context Dispatcher dispatcher) {
        try {
            if ("true".equals(context.getInitParameter("keycloak.embedded"))) {
                embedded = true;
            }

            loadConfig(context);

            this.contextPath = context.getContextPath();
            this.sessionFactory = createSessionFactory();

            dispatcher.getDefaultContextObjects().put(KeycloakApplication.class, this);
            ResteasyProviderFactory.pushContext(KeycloakApplication.class, this); // for injection
            context.setAttribute(KeycloakSessionFactory.class.getName(), this.sessionFactory);

            singletons.add(new ServerVersionResource());
            singletons.add(new RobotsResource());
            singletons.add(new RealmsResource());
            singletons.add(new AdminRoot());
            classes.add(ThemeResource.class);
            classes.add(JsResource.class);

            classes.add(KeycloakTransactionCommitter.class);

            singletons.add(new ObjectMapperResolver(Boolean.parseBoolean(System.getProperty("keycloak.jsonPrettyPrint", "false"))));

            ExportImportManager[] exportImportManager = new ExportImportManager[1];

            KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

                @Override
                public void run(KeycloakSession lockSession) {
                    DBLockManager dbLockManager = new DBLockManager(lockSession);
                    dbLockManager.checkForcedUnlock();
                    DBLockProvider dbLock = dbLockManager.getDBLock();
                    dbLock.waitForLock();
                    try {
                        exportImportManager[0] = migrateAndBootstrap();
                    } finally {
                        dbLock.releaseLock();
                    }
                }

            });

            if (exportImportManager[0].isRunExport()) {
                exportImportManager[0].runExport();
            }

            boolean bootstrapAdminUser = false;
            KeycloakSession session = sessionFactory.create();
            try {
                session.getTransactionManager().begin();
                bootstrapAdminUser = new ApplianceBootstrap(session).isNoMasterUser();

                session.getTransactionManager().commit();
            } finally {
                session.close();
            }

            sessionFactory.publish(new PostMigrationEvent());

            singletons.add(new WelcomeResource(bootstrapAdminUser));

            setupScheduledTasks(sessionFactory);
        } catch (Throwable t) {
            if (!embedded) {
                exit(1);
            }
            throw t;
        }
    }

    // Migrate model, bootstrap master realm, import realms and create admin user. This is done with acquired dbLock
    protected ExportImportManager migrateAndBootstrap() {
        ExportImportManager exportImportManager;
        logger.debug("Calling migrateModel");
        migrateModel();

        logger.debug("bootstrap");
        KeycloakSession session = sessionFactory.create();
        try {
            session.getTransactionManager().begin();
            JtaTransactionManagerLookup lookup = (JtaTransactionManagerLookup) sessionFactory.getProviderFactory(JtaTransactionManagerLookup.class);
            if (lookup != null) {
                if (lookup.getTransactionManager() != null) {
                    try {
                        Transaction transaction = lookup.getTransactionManager().getTransaction();
                        logger.debugv("bootstrap current transaction? {0}", transaction != null);
                        if (transaction != null) {
                            logger.debugv("bootstrap current transaction status? {0}", transaction.getStatus());
                        }
                    } catch (SystemException e) {
                        throw new RuntimeException(e);
                    }
                }
            }

            ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);
            exportImportManager = new ExportImportManager(session);

            boolean createMasterRealm = applianceBootstrap.isNewInstall();
            if (exportImportManager.isRunImport() && exportImportManager.isImportMasterIncluded()) {
                createMasterRealm = false;
            }

            if (createMasterRealm) {
                applianceBootstrap.createMasterRealm(contextPath);
            }
            session.getTransactionManager().commit();
        } catch (RuntimeException re) {
            if (session.getTransactionManager().isActive()) {
                session.getTransactionManager().rollback();
            }
            throw re;
        } finally {
            session.close();
        }

        if (exportImportManager.isRunImport()) {
            exportImportManager.runImport();
        } else {
            importRealms();
        }

        importAddUser();

        return exportImportManager;
    }

    protected void migrateModel() {
        KeycloakSession session = sessionFactory.create();
        try {
            session.getTransactionManager().begin();
            MigrationModelManager.migrate(session);
            session.getTransactionManager().commit();
        } catch (Exception e) {
            session.getTransactionManager().rollback();
            throw e;
        } finally {
            session.close();
        }
    }

    public String getContextPath() {
        return contextPath;
    }

    /**
     * Get base URI of WAR distribution, not JAX-RS
     *
     * @param uriInfo
     * @return
     */
    public URI getBaseUri(UriInfo uriInfo) {
        return uriInfo.getBaseUriBuilder().replacePath(getContextPath()).build();
    }

    public static void loadConfig(ServletContext context) {
        try {
            JsonNode node = null;

            String dmrConfig = loadDmrConfig(context);
            if (dmrConfig != null) {
                node = new ObjectMapper().readTree(dmrConfig);
                logger.loadingFrom("standalone.xml or domain.xml");
            }

            String configDir = System.getProperty("jboss.server.config.dir");
            if (node == null && configDir != null) {
                File f = new File(configDir + File.separator + "keycloak-server.json");
                if (f.isFile()) {
                    logger.loadingFrom(f.getAbsolutePath());
                    node = new ObjectMapper().readTree(f);
                }
            }

            if (node == null) {
                URL resource = Thread.currentThread().getContextClassLoader().getResource("META-INF/keycloak-server.json");
                if (resource != null) {
                    logger.loadingFrom(resource);
                    node = new ObjectMapper().readTree(resource);
                }
            }

            if (node != null) {
                Properties properties = new SystemEnvProperties();
                Config.init(new JsonConfigProvider(node, properties));
            } else {
                throw new RuntimeException("Keycloak config not found.");
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to load config", e);
        }
    }

    private static String loadDmrConfig(ServletContext context) {
        String dmrConfig = context.getInitParameter(KEYCLOAK_CONFIG_PARAM_NAME);
        if (dmrConfig == null) return null;

        ModelNode dmrConfigNode = ModelNode.fromString(dmrConfig);
        if (dmrConfigNode.asPropertyList().isEmpty()) return null;

        // note that we need to resolve expressions BEFORE we convert to JSON
        return dmrConfigNode.resolve().toJSONString(true);
    }

    public static KeycloakSessionFactory createSessionFactory() {
        DefaultKeycloakSessionFactory factory = new DefaultKeycloakSessionFactory();
        factory.init();
        return factory;
    }

    public static void setupScheduledTasks(final KeycloakSessionFactory sessionFactory) {
        long interval = Config.scope("scheduled").getLong("interval", 60L) * 1000;

        KeycloakSession session = sessionFactory.create();
        try {
            TimerProvider timer = session.getProvider(TimerProvider.class);
            timer.schedule(new ClusterAwareScheduledTaskRunner(sessionFactory, new ClearExpiredEvents(), interval), interval, "ClearExpiredEvents");
            timer.schedule(new ClusterAwareScheduledTaskRunner(sessionFactory, new ClearExpiredUserSessions(), interval), interval, "ClearExpiredUserSessions");
            new UsersSyncManager().bootstrapPeriodic(sessionFactory, timer);
        } finally {
            session.close();
        }
    }

    public KeycloakSessionFactory getSessionFactory() {
        return sessionFactory;
    }

    @Override
    public Set<Class<?>> getClasses() {
        return classes;
    }

    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }

    public void importRealms() {
        String files = System.getProperty("keycloak.import");
        if (files != null) {
            StringTokenizer tokenizer = new StringTokenizer(files, ",");
            while (tokenizer.hasMoreTokens()) {
                String file = tokenizer.nextToken().trim();
                RealmRepresentation rep;
                try {
                    rep = loadJson(new FileInputStream(file), RealmRepresentation.class);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }
                importRealm(rep, "file " + file);
            }
        }
    }

    public void importRealm(RealmRepresentation rep, String from) {
        KeycloakSession session = sessionFactory.create();
        boolean exists = false;
        try {
            session.getTransactionManager().begin();

            try {
                RealmManager manager = new RealmManager(session);
                manager.setContextPath(getContextPath());

                if (rep.getId() != null && manager.getRealm(rep.getId()) != null) {
                    logger.realmExists(rep.getRealm(), from);
                    exists = true;
                }

                if (manager.getRealmByName(rep.getRealm()) != null) {
                    logger.realmExists(rep.getRealm(), from);
                    exists = true;
                }
                if (!exists) {
                    RealmModel realm = manager.importRealm(rep);
                    logger.importedRealm(realm.getName(), from);
                }
                session.getTransactionManager().commit();
            } catch (Throwable t) {
                session.getTransactionManager().rollback();
                if (!exists) {
                    logger.unableToImportRealm(t, rep.getRealm(), from);
                }
            }
        } finally {
            session.close();
        }
    }

    public void importAddUser() {
        String configDir = System.getProperty("jboss.server.config.dir");
        if (configDir != null) {
            File addUserFile = new File(configDir + File.separator + "keycloak-add-user.json");
            if (addUserFile.isFile()) {
                logger.imprtingUsersFrom(addUserFile);

                List<RealmRepresentation> realms;
                try {
                    realms = JsonSerialization.readValue(new FileInputStream(addUserFile), new TypeReference<List<RealmRepresentation>>() {
                    });
                } catch (IOException e) {
                    logger.failedToLoadUsers(e);
                    return;
                }

                for (RealmRepresentation realmRep : realms) {
                    for (UserRepresentation userRep : realmRep.getUsers()) {
                        KeycloakSession session = sessionFactory.create();
                        try {
                            session.getTransactionManager().begin();

                            RealmModel realm = session.realms().getRealmByName(realmRep.getRealm());
                            if (realm == null) {
                                logger.addUserFailedRealmNotFound(userRep.getUsername(), realmRep.getRealm());
                            } else {
                                UserModel user = session.users().addUser(realm, userRep.getUsername());
                                user.setEnabled(userRep.isEnabled());
                                RepresentationToModel.createCredentials(userRep, user);
                                RepresentationToModel.createRoleMappings(userRep, user, realm);
                            }

                            session.getTransactionManager().commit();
                            logger.addUserSuccess(userRep.getUsername(), realmRep.getRealm());
                        } catch (ModelDuplicateException e) {
                            session.getTransactionManager().rollback();
                            logger.addUserFailedUserExists(userRep.getUsername(), realmRep.getRealm());
                        } catch (Throwable t) {
                            session.getTransactionManager().rollback();
                            logger.addUserFailed(t, userRep.getUsername(), realmRep.getRealm());
                        } finally {
                            session.close();
                        }
                    }
                }

                if (!addUserFile.delete()) {
                    logger.failedToDeleteFile(addUserFile.getAbsolutePath());
                }
            }
        }
    }

    private static <T> T loadJson(InputStream is, Class<T> type) {
        try {
            return JsonSerialization.readValue(is, type);
        } catch (IOException e) {
            throw new RuntimeException("Failed to parse json", e);
        }
    }

    private void exit(int status) {
        new Thread() {
            @Override
            public void run() {
                System.exit(status);
            }
        }.start();
    }

}


text:
package org.chromium.content.app;

public class NativeLibraries {
    // Set to true to use the content linker. Only useful to save memory
    // on multi-process content-based projects. Always disabled for the Android Webview.
    public static boolean USE_LINKER = false;

    // Set to true to enable content linker test support. NEVER enable this for the
    // Android webview.
    public static boolean ENABLE_LINKER_TESTS = false;

    // This is the list of native libraries to load. In the normal chromium build, this would be
    // automatically generated.
    // TODO(torne, cjhopman): Use a generated file for this.
    static String[] libraries = { "webviewchromium" };
}


text:
require 'spec_helper'

describe "remote on-the-fly urls" do

  THUMBS = {}

  before(:each) do
    @app = test_app.configure do |c|
      c.generator.add :test do
        "TEST"
      end
      c.server.before_serve do |job, env|
        uid = job.store(:path => 'yay.txt')
        THUMBS[job.serialize] = uid
      end
      c.define_url do |app, job, opts|
        uid = THUMBS[job.serialize]
        if uid
          app.datastore.url_for(uid)
        else
          app.server.url_for(job)
        end
      end
      c.datastore = Dragonfly::DataStorage::FileDataStore.new
      c.datastore.root_path = '/var/tmp/dragonfly'
      c.datastore.server_root = '/var/tmp'
    end
    @job = @app.generate(:test)
  end

  after(:each) do
    THUMBS.delete_if{true}
    FileUtils.rm_f('/var/tmp/dragonfly/yay.txt')
  end

  it "should give the url for the server" do
    @job.url.should == "/#{@job.serialize}"
  end

  it "should store the content when first called" do
    File.exist?('/var/tmp/dragonfly/yay.txt').should be_false
    @app.server.call('PATH_INFO' => @job.url, 'REQUEST_METHOD' => 'GET')
    File.read('/var/tmp/dragonfly/yay.txt').should == 'TEST'
  end

  it "should point to the external url the second time" do
    @app.server.call('PATH_INFO' => @job.url, 'REQUEST_METHOD' => 'GET')
    @job.url.should == '/dragonfly/yay.txt'
  end

end


text:
using System;
using System.Reflection;

namespace NUnit.Core.Extensibility
{
	/// <summary>
	/// The Addin class holds information about an addin.
	/// </summary>
	[Serializable]
	public class Addin
	{
		#region Private Fields
		private string typeName;
		private string name;
		private string description;
		private ExtensionType extensionType;
		private AddinStatus status;
		private string message;
		#endregion

		#region Constructor
		/// <summary>
		/// Construct an Addin for a type.
		/// </summary>
		/// <param name="type">The type to be used</param>
		public Addin( Type type )
		{
			this.typeName = type.AssemblyQualifiedName;

			object[] attrs = type.GetCustomAttributes( typeof(NUnitAddinAttribute), false );
			if ( attrs.Length == 1 )
			{
				NUnitAddinAttribute attr = (NUnitAddinAttribute)attrs[0];
				this.name = attr.Name;
				this.description = attr.Description;
				this.extensionType = attr.Type;
			}

			if ( this.name == null )
				this.name = type.Name;

			if ( this.extensionType == 0 )
				this.extensionType = ExtensionType.Core;

			this.status = AddinStatus.Enabled;
        }
		#endregion

		#region Properties
		/// <summary>
		/// The name of the Addin
		/// </summary>
		public string Name
		{
			get { return name; }
		}

		/// <summary>
		/// Brief description of what the Addin does
		/// </summary>
		public string Description
		{
			get { return description; }
		}

		/// <summary>
		/// The type or types of extension provided, using
		/// one or more members of the ExtensionType enumeration.
		/// </summary>
		public ExtensionType ExtensionType
		{
			get { return extensionType; }
		}

		/// <summary>
		/// The AssemblyQualifiedName of the type that implements
		/// the addin.
		/// </summary>
		public string TypeName
		{
			get { return typeName; }
		}

		/// <summary>
		/// The status of the addin
		/// </summary>
		public AddinStatus Status
		{
			get { return status; }
			set { status = value; }
		}

		/// <summary>
		/// Any message that clarifies the status of the Addin,
		/// such as an error message or an explanation of why
		/// the addin is disabled.
		/// </summary>
		public string Message
		{
			get { return message; }
			set { message = value; }
		}
		#endregion

        #region Object Overrides
        /// <summary>
        /// Return true if two Addins have teh same type name
        /// </summary>
        /// <param name="obj">The other addin to be compared</param>
        public override bool Equals(object obj)
        {
            Addin addin = obj as Addin;
            if (addin == null)
                return false;

            return this.typeName.Equals(addin.typeName);
        }

        /// <summary>
        /// Return a hash code for this addin
        /// </summary>
        public override int GetHashCode()
        {
            return this.typeName.GetHashCode();
        }
        #endregion
    }
}


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

package org.chromium.chrome.browser.autofill_assistant;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import org.chromium.base.Callback;
import org.chromium.chrome.browser.autofill.PersonalDataManager;
import org.chromium.chrome.browser.autofill.prefeditor.EditorDialog;
import org.chromium.chrome.browser.autofill.settings.AddressEditor;
import org.chromium.chrome.browser.payments.AutofillAddress;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.components.autofill_assistant.AssistantEditor.AssistantAddressEditor;
import org.chromium.components.autofill_assistant.AssistantOptionModel.AddressModel;
import org.chromium.content_public.browser.WebContents;

import java.util.UUID;

/**
 * Editor for addresses in Chrome using Autofill as a base.
 */
public class AssistantAddressEditorAutofill implements AssistantAddressEditor {
    private final AddressEditor mEditor;
    private final Context mContext;

    public AssistantAddressEditorAutofill(
            WebContents webContents, Activity activity, boolean shouldStoreChanges) {
        mEditor = new AddressEditor(AddressEditor.Purpose.AUTOFILL_ASSISTANT,
                /* saveToDisk= */ shouldStoreChanges);
        mEditor.setEditorDialog(new EditorDialog(activity,
                /* deleteRunnable= */ null, Profile.fromWebContents(webContents)));
        mContext = activity;
    }

    @Override
    public void createOrEditItem(@Nullable AddressModel oldItem,
            Callback<AddressModel> doneCallback, Callback<AddressModel> cancelCallback) {
        @Nullable
        AutofillAddress address = oldItem == null
                ? null
                : AssistantAutofillUtilChrome.assistantAutofillProfileToAutofillAddress(
                        oldItem.mOption, mContext);

        Callback<AutofillAddress> editorDoneCallback = editedAddress -> {
            assert (editedAddress != null && editedAddress.isComplete()
                    && editedAddress.getProfile() != null);
            String fullDescription = PersonalDataManager.getInstance()
                                             .getShippingAddressLabelWithCountryForPaymentRequest(
                                                     editedAddress.getProfile());
            String summaryDescription =
                    PersonalDataManager.getInstance()
                            .getShippingAddressLabelWithoutCountryForPaymentRequest(
                                    editedAddress.getProfile());
            if (TextUtils.isEmpty(editedAddress.getProfile().getGUID())) {
                // crbug/1332561: In the case where the address is not stored, it may come without
                // GUID. Combined with the missing "update" signal from the PersonalDataManager this
                // causes our UI to show the address twice.
                editedAddress.getProfile().setGUID(UUID.randomUUID().toString());
            }
            doneCallback.onResult(new AddressModel(
                    AssistantAutofillUtilChrome.autofillProfileToAssistantAutofillProfile(
                            editedAddress.getProfile()),
                    fullDescription, summaryDescription));
        };

        Callback<AutofillAddress> editorCancelCallback =
                editedAddress -> cancelCallback.onResult(oldItem);

        mEditor.edit(address, editorDoneCallback, editorCancelCallback);
    }
}


text:
using Xunit;
using ContactUs.Models;
using ContactUs.Services;
using System.Text.RegularExpressions;
using GFX.Core;
using System;

namespace ContactUs.Facts.Services
{
    public class TicketServiceFacts
    {

        public class Add
        {

            [Fact]
            public void NewTicket_HasCorrectId()
            {
                using (var app = new App(testing: true))
                {
                    var t = new Ticket();
                    t.Title = "Test Ticket";
                    t.Body = "Blah blah";

                    var ticket = app.Tickets.Add(t);
                    app.SaveChanges();

                    Assert.NotNull(ticket.Id);
                    Assert.True(ticket.Id.Length == 6);
                    Assert.True(Regex.IsMatch(ticket.Id, "[0-9a-f]{6}"));
                }
            }

            [Fact]
            public void NewTicket_LastActivityDateShouldBeCreatedDate()
            {
                using (var app = new App(testing: true))
                {
                    var t = new Ticket();
                    var dt = new DateTime(2015, 1, 1, 9, 0, 0);
                    SystemTime.SetDateTime(dt);

                    var ticket = app.Tickets.Add(t);
                    app.SaveChanges();

                    Assert.Equal(dt, ticket.LastActivityDate);
                }
            }
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 1 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef SRC_WRITER_IMPL_WRITERHEURISTIC_H
#define SRC_WRITER_IMPL_WRITERHEURISTIC_H
#include <atomic>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>

#include "../../data/constructs/server/ServerDefinition.h"
#include "../../interconnect/TabletServer.h"
#include "../../scanner/constructs/Heuristic.h"
#include "../SinkConditionals.h"
#include "data/extern/concurrentqueue/concurrentqueue.h"

namespace writer {

class WritePair {
 public:
  explicit WritePair(
      std::shared_ptr<cclient::data::tserver::ServerDefinition> rangeDef,
      void *ref, const cclient::impl::Configuration *conf,
      std::shared_ptr<cclient::data::TabletServerMutations> mutations)
      : rangeDef(rangeDef), conf(conf), ref(ref), mutations(mutations) {}
  explicit WritePair(const WritePair &&other)
      : rangeDef(std::move(other.rangeDef)),
        conf(other.conf),
        ref(std::move(other.ref)),
        mutations(std::move(other.mutations)) {}

  WritePair &operator=(const WritePair &&other) {
    rangeDef = (std::move(other.rangeDef));
    conf = (other.conf);
    ref = (std::move(other.ref));
    mutations = (std::move(other.mutations));
    return *this;
  }
  // ServerInterconnect *interconnect;
  std::shared_ptr<cclient::data::tserver::ServerDefinition> rangeDef;
  const cclient::impl::Configuration *conf;
  std::shared_ptr<cclient::data::TabletServerMutations> mutations;
  void *ref;
};

/*
 *
 */
class WriterHeuristic
    : public scanners::Heuristic<interconnect::ThriftTransporter> {
 public:
  WriterHeuristic(short numThreads = 10, uint32_t queueSize = 2000);
  /**
   * Add a server interconnect
   */
  void addClientInterface(
      std::shared_ptr<
          interconnect::ClientInterface<interconnect::ThriftTransporter>>
          serverIfc) {
    Heuristic::addClientInterface(serverIfc);
  }

  uint16_t write(  // ServerInterconnect *interConnect,
      std::shared_ptr<cclient::data::tserver::ServerDefinition> rangeDef,
      const cclient::impl::Configuration *conf,
      std::shared_ptr<cclient::data::TabletServerMutations> mutations) {
    if (!started) {
      std::lock_guard<std::mutex> lock(serverLock);
      if (!started) {
        for (int i = 0; i < threadCount; i++) {
          threads.push_back(std::thread(WriterHeuristic::write_thrift, this));
        }
      }
      started = true;
    }

    std::shared_ptr<WritePair> pair =
        std::make_shared<WritePair>(rangeDef, this, conf, mutations);
    mutations->setMaxFailures(2);

    while (!queue.try_enqueue(pair)) {
      if (!conditionals->isAlive()) {
        throw std::runtime_error("Closed during write");
      }
    }
    conditionals->incrementMutationCount();

    conditionals->awakeThreadsForResults();
    return conditionals->getMutationCount();
  }

  int close() {
    std::lock_guard<std::mutex> lock(serverLock);
    if (failedMutations.size() > 0) {
      return 1;
    } else if (threads.size() == 0) {
      return 0;
    } else {
      if (closed) {
        return 0;
      }

      if (started) {
        conditionals->awakeThreadsFinished();

        for (std::vector<std::thread>::iterator iter = threads.begin();
             iter != threads.end(); ++iter) {
          iter->join();
        }
      }
      conditionals->close();
      closed = true;
      return 0;
    }
  }

  uint64_t maxThreads() { return threadCount; }

  uint64_t size() { return conditionals->getMutationCount(); }
  virtual ~WriterHeuristic();

  void restart_failures(
      std::vector<std::shared_ptr<cclient::data::Mutation>> *mutations) {
    std::lock_guard<std::mutex> lock(serverLock);
    mutations->insert(mutations->end(), failedMutations.begin(),
                      failedMutations.end());
    failedMutations.clear();
  }
  void addFailedMutation(
      std::shared_ptr<cclient::data::TabletServerMutations> mutation) {
    std::lock_guard<std::mutex> lock(serverLock);
    auto mutationMap = mutation->getMutations();
    for (auto &entry : *mutationMap) {
      failedMutations.insert(failedMutations.end(), entry.second.begin(),
                             entry.second.end());
      entry.second.clear();
    }
  }

  void push_failures(
      std::vector<std::shared_ptr<cclient::data::Mutation>> *mutations) {
    std::lock_guard<std::mutex> lock(serverLock);
    failedMutations.insert(failedMutations.end(), mutations->begin(),
                           mutations->end());
  }

 protected:
  static void *write_thrift(WriterHeuristic *heuristic) {
    std::shared_ptr<WritePair> pair = nullptr;
    do {
      pair = heuristic->next();

      if (nullptr != pair) {
        interconnect::ServerInterconnect conn(pair->rangeDef, pair->conf);

        if (conn.write(pair->mutations) != nullptr) {
          // take failed mutations back so we can try later on
          ((WriterHeuristic *)pair->ref)->addFailedMutation(pair->mutations);
        }

      } else {
        break;
      }

    } while (nullptr != pair);

    return 0;
  }

  virtual std::shared_ptr<WritePair> next() {
    std::shared_ptr<WritePair> pair = nullptr;

    if (!conditionals->isAlive()) {
      return nullptr;
    }

    do {
      if (!queue.try_dequeue(pair)) {
        conditionals->waitForResults();
        if (queue.try_dequeue<>(pair)) {
          conditionals->decrementMutationCount();
          break;
        }
        if (conditionals->isClosing()) {
          return nullptr;
        }

      } else {
        conditionals->decrementMutationCount();
        break;
      }

    } while (conditionals->isAlive());

    return pair;
  }

  volatile bool started;
  moodycamel::ConcurrentQueue<std::shared_ptr<WritePair>> queue;

 private:
  SinkConditions *conditionals;
  std::vector<std::shared_ptr<cclient::data::Mutation>> failedMutations;
  std::mutex serverLock;
  std::vector<std::thread> threads;
  uint16_t threadCount;
  volatile bool closed;
};

}  // namespace writer

#endif /* SRC_WRITER_IMPL_WRITERHEURISTIC_H_ */


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

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.internal.ListWithAutoConstructFlag;
import com.amazonaws.services.cloudsearchv2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * Delete Analysis Scheme Request Marshaller
 */
public class DeleteAnalysisSchemeRequestMarshaller implements Marshaller<Request<DeleteAnalysisSchemeRequest>, DeleteAnalysisSchemeRequest> {

    public Request<DeleteAnalysisSchemeRequest> marshall(DeleteAnalysisSchemeRequest deleteAnalysisSchemeRequest) {

        if (deleteAnalysisSchemeRequest == null) {
            throw new AmazonClientException("Invalid argument passed to marshall(...)");
        }

        Request<DeleteAnalysisSchemeRequest> request = new DefaultRequest<DeleteAnalysisSchemeRequest>(deleteAnalysisSchemeRequest, "AmazonCloudSearchv2");
        request.addParameter("Action", "DeleteAnalysisScheme");
        request.addParameter("Version", "2013-01-01");

        if (deleteAnalysisSchemeRequest.getDomainName() != null) {
            request.addParameter("DomainName", StringUtils.fromString(deleteAnalysisSchemeRequest.getDomainName()));
        }
        if (deleteAnalysisSchemeRequest.getAnalysisSchemeName() != null) {
            request.addParameter("AnalysisSchemeName", StringUtils.fromString(deleteAnalysisSchemeRequest.getAnalysisSchemeName()));
        }

        return request;
    }
}


text:
CSV export feature for Wordpress WP-Quiz-Pro plugin

How to install:

Make a zip *only* of the content of /build/wp-pro-quiz-export and install it following the usual procedure on WordPress.


text:
var index = require('./index.js');

test('Nationalcode must be valid', ()=>{
    expect(index.isValid('1111111111')).toBe(true);
});

test('Nationalcode must not be valid', ()=>{
    expect(index.isValid('7512698452')).toBe(false);
});


text:
package com.google.security.zynamics.zylib.gui.zygraph.nodes;

import com.google.common.base.Preconditions;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.nodes.ZyGraphNode;

/**
 * Collects all information that is passed to the user data field of a yfiles node.
 *
 * @param <NodeType> The type of the node.
 */
public class ZyNodeData<NodeType extends ZyGraphNode<? extends IViewNode<?>>> {
  private final NodeType m_node;

  public ZyNodeData(final NodeType node) {
    Preconditions.checkNotNull(node, "Error: Node argument can't be null");

    m_node = node;
  }

  public NodeType getNode() {
    return m_node;
  }

}


text:
<?php

declare(strict_types=1);

namespace App\EventListener;

use App\Entity\AuthenticationInterface;
use App\Entity\CourseInterface;
use App\Entity\LearningMaterialInterface;
use App\Entity\SessionInterface;
use App\Entity\UserInterface;
use App\Message\CourseIndexRequest;
use App\Message\LearningMaterialIndexRequest;
use App\Message\UserIndexRequest;
use App\Service\Index\Curriculum;
use App\Service\Index\LearningMaterials;
use App\Service\Index\Mesh;
use App\Service\Index\Users;
use App\Traits\IndexableCoursesEntityInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Exception;
use Symfony\Component\Messenger\MessageBusInterface;

/**
 * Doctrine event listener.
 * Listen for every change to an entity and index them.
 */
class IndexEntityChanges
{
    /**
     * ACHTUNG!!! Do NOT change the name of $dispatchBus it tells the dependency injection system what bus to inject!!!
     */
    public function __construct(
        protected Curriculum $curriculumIndex,
        protected LearningMaterials $learningMaterialsIndex,
        protected Mesh $meshIndex,
        protected Users $usersIndex,
        protected MessageBusInterface $bus
    ) {
    }

    public function postPersist(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();

        if ($entity instanceof UserInterface) {
            $this->indexUser($entity);
        }

        if ($entity instanceof AuthenticationInterface) {
            $this->indexUser($entity->getUser());
        }

        if ($entity instanceof LearningMaterialInterface) {
            $this->indexLearningMaterial($entity);
        }

        if ($entity instanceof IndexableCoursesEntityInterface) {
            $this->indexCourses($entity->getIndexableCourses());
        }
    }
    public function postUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();

        if ($entity instanceof UserInterface) {
            $this->indexUser($entity);
        }

        if ($entity instanceof AuthenticationInterface) {
            $this->indexUser($entity->getUser());
        }

        if ($entity instanceof LearningMaterialInterface) {
            $this->indexLearningMaterial($entity);
        }

        if ($entity instanceof IndexableCoursesEntityInterface) {
            $this->indexCourses($entity->getIndexableCourses());
        }
    }

    /**
     * We have to do this work in preRemove because in postRemove we no longer
     * have access to the entity ID
     */
    public function preRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();

        if ($entity instanceof UserInterface) {
            $this->usersIndex->delete($entity->getId());
        }

        if ($entity instanceof AuthenticationInterface) {
            $this->indexUser($entity->getUser());
        }

        if ($entity instanceof CourseInterface) {
            $this->curriculumIndex->deleteCourse($entity->getId());
        }

        if ($entity instanceof SessionInterface) {
            $this->curriculumIndex->deleteSession($entity->getId());
            return; //don't re-index our just removed session
        }

        if ($entity instanceof LearningMaterialInterface) {
            $this->learningMaterialsIndex->delete($entity->getId());
        }

        if ($entity instanceof IndexableCoursesEntityInterface) {
            $this->indexCourses($entity->getIndexableCourses());
        }
    }

    protected function indexUser(UserInterface $user)
    {
        if ($this->usersIndex->isEnabled()) {
            $this->bus->dispatch(new UserIndexRequest([$user->getId()]));
        }
    }

    /**
     * @param CourseInterface[] $courses
     * @throws Exception
     */
    protected function indexCourses(array $courses): void
    {
        if ($this->curriculumIndex->isEnabled()) {
            $courseIds = array_map(fn(CourseInterface $course) => $course->getId(), $courses);
            $chunks = array_chunk($courseIds, CourseIndexRequest::MAX_COURSES);
            foreach ($chunks as $ids) {
                $this->bus->dispatch(new CourseIndexRequest($ids));
            }
        }
    }

    protected function indexLearningMaterial(LearningMaterialInterface $lm)
    {
//        temporarily disable indexing learning materials while we figure out performance
//        if ($this->learningMaterialsIndex->isEnabled()) {
//            $this->bus->dispatch(new LearningMaterialIndexRequest($lm->getId()));
//        }
    }
}


text:
var grunt = require('grunt');

/*
 ======== A Handy Little Nodeunit Reference ========
 https://github.com/caolan/nodeunit

 Test methods:
 test.expect(numAssertions)
 test.done()
 Test assertions:
 test.ok(value, [message])
 test.equal(actual, expected, [message])
 test.notEqual(actual, expected, [message])
 test.deepEqual(actual, expected, [message])
 test.notDeepEqual(actual, expected, [message])
 test.strictEqual(actual, expected, [message])
 test.notStrictEqual(actual, expected, [message])
 test.throws(block, [error], [message])
 test.doesNotThrow(block, [error], [message])
 test.ifError(value)
 */

exports.image_diff_validator = {

  setUp: function (done) {
    'use strict';

    grunt.util.spawn({
      grunt: true,
      args: ['clean', 'imageDiffValidator', '--force']
    }, done);
  },

  createDiff: function (test) {
    'use strict';
    test.expect(1);
    test.equal(grunt.file.exists('test/files/diff/different.jpeg'), true, 'Diff file was not created');

    test.done();
  },

  passSameFiles: function (test) {
    'use strict';
    test.expect(1);
    test.equal(grunt.file.exists('test/files/diff/same.jpeg'), false, 'Diff file was created for same files');

    test.done();
  }
};


text:
package com.smartfoo.android.core.bluetooth.gatt;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.support.annotation.NonNull;

import com.smartfoo.android.core.FooString;
import com.smartfoo.android.core.logging.FooLog;

import java.util.Locale;
import java.util.UUID;

public class FooGattUtils
{
    private static final String TAG = FooLog.TAG(FooGattUtils.class);

    private FooGattUtils()
    {
    }

    @NonNull
    public static String gattDeviceAddressString(BluetoothGatt gatt)
    {
        if (gatt == null)
        {
            return "00:00:00:00:00:00";
        }

        BluetoothDevice bluetoothDevice = gatt.getDevice();
        if (bluetoothDevice == null)
        {
            throw new IllegalStateException("unexpected bluetoothDevice == null");
        }

        String bluetoothDeviceAddressString = bluetoothDevice.getAddress();
        if (FooString.isNullOrEmpty(bluetoothDeviceAddressString))
        {
            throw new IllegalStateException("unexpected bluetoothDevice.getAddress() == null/\"\"");
        }

        return bluetoothDeviceAddressString;
    }

    public static long gattDeviceAddressLong(BluetoothGatt gatt)
    {
        String bluetoothDeviceAddressString = gattDeviceAddressString(gatt);
        return deviceAddressStringToLong(bluetoothDeviceAddressString);
    }

    public static long deviceAddressStringToLong(String deviceAddressString)
    {
        if (FooString.isNullOrEmpty(deviceAddressString))
        {
            throw new IllegalArgumentException("unexpected deviceAddressString == null/\"\"");
        }
        deviceAddressString = deviceAddressString.replace(":", "");
        return Long.parseLong(deviceAddressString, 16);
    }

    @NonNull
    public static String deviceAddressLongToString(long deviceAddressLong)
    {
        //noinspection PointlessBitwiseExpression
        return String.format(Locale.US, "%02X:%02X:%02X:%02X:%02X:%02X",
                (byte) ((deviceAddressLong >> 40) & 0xff),
                (byte) ((deviceAddressLong >> 32) & 0xff),
                (byte) ((deviceAddressLong >> 24) & 0xff),
                (byte) ((deviceAddressLong >> 16) & 0xff),
                (byte) ((deviceAddressLong >> 8) & 0xff),
                (byte) ((deviceAddressLong >> 0) & 0xff));
    }

    public static String bluetoothProfileStateToString(int state)
    {
        String text;
        switch (state)
        {
            case BluetoothProfile.STATE_DISCONNECTED:
                text = "STATE_DISCONNECTED";
                break;
            case BluetoothProfile.STATE_DISCONNECTING:
                text = "STATE_DISCONNECTING";
                break;
            case BluetoothProfile.STATE_CONNECTING:
                text = "STATE_CONNECTING";
                break;
            case BluetoothProfile.STATE_CONNECTED:
                text = "STATE_CONNECTED";
                break;
            default:
                text = "STATE_UNKNOWN";
                break;
        }
        return text + '(' + state + ')';
    }

    public static void throwExceptionIfInvalidBluetoothAddress(long deviceAddress)
    {
        if (!(deviceAddress != 0 && deviceAddress != -1))
        {
            throw new IllegalArgumentException("deviceAddress invalid");
        }
    }

    /**
     * @param callerName callerName
     * @param gatt       gatt
     * @return true if both gatt.disconnect() and gatt.close() were called successfully, otherwise false
     */
    public static boolean safeDisconnectAndClose(@NonNull final String callerName, final BluetoothGatt gatt)
    {
        return safeDisconnect(callerName, gatt, true) && safeClose(callerName, gatt);
    }

    /**
     * Oh oh! According to Android bug:
     * https://code.google.com/p/android/issues/detail?id=183108
     * <p>
     * Starting in 5.0, if you call disconnect and then immediately call close the
     *
     * @param callerName callerName
     * @param gatt       gatt
     * @return true if gatt.disconnect() was called successfully, otherwise false
     */
    public static boolean safeDisconnect(@NonNull final String callerName, final BluetoothGatt gatt)
    {
        return safeDisconnect(callerName, gatt, false);
    }

    private static boolean safeDisconnect(@NonNull final String callerName, final BluetoothGatt gatt, boolean ignoreException)
    {
        String debugInfo = gattDeviceAddressString(gatt) + FooString.quote(callerName) + "->safeDisconnect";
        FooLog.v(TAG, debugInfo + "(gatt=" + gatt + ')');

        if (gatt == null)
        {
            FooLog.w(TAG, debugInfo + ": gatt == null; ignoring");
            return false;
        }

        try
        {
            FooLog.v(TAG, debugInfo + ": gatt.disconnect()");
            gatt.disconnect();
        }
        catch (Exception e)
        {
            FooLog.w(TAG, debugInfo + ": gatt.disconnect() EXCEPTION; ignoring", e);
            if (!ignoreException)
            {
                return false;
            }
        }

        return true;
    }

    /**
     * @param callerName callerName
     * @param gatt       gatt
     * @return true if gatt.close() was called successfully, otherwise false
     */
    public static boolean safeClose(@NonNull final String callerName, final BluetoothGatt gatt)
    {
        String debugInfo = gattDeviceAddressString(gatt) + ' ' + callerName + "->safeClose";
        FooLog.v(TAG, debugInfo + "(gatt=" + gatt + ')');

        if (gatt == null)
        {
            FooLog.w(TAG, debugInfo + ": gatt == null; ignoring");
            return false;
        }

        try
        {
            FooLog.v(TAG, debugInfo + ": gatt.close()");
            gatt.close();
        }
        catch (Exception e)
        {
            FooLog.w(TAG, debugInfo + ": gatt.close() EXCEPTION; ignoring", e);
            return false;
        }

        return true;
    }

    public static BluetoothGattCharacteristic createBluetoothGattCharacteristic(UUID serviceUuid, UUID characteristicUuid)
    {
        BluetoothGattService service = new BluetoothGattService(serviceUuid, BluetoothGattService.SERVICE_TYPE_PRIMARY);
        BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(characteristicUuid, 0, 0);
        service.addCharacteristic(characteristic);
        return characteristic;
    }

    //
    //
    //

    /**
     * Code taken from {@link BluetoothGattCharacteristic#setValue(int, int, int)}
     *
     * @param value      New value for this characteristic
     * @param formatType Integer format type used to transform the value parameter
     * @param offset     Offset at which the value should be placed
     * @return never null
     */
    public static byte[] toBytes(int value, int formatType, int offset)
    {
        byte[] bytes = new byte[offset + getTypeLen(formatType)];

        switch (formatType)
        {
            case BluetoothGattCharacteristic.FORMAT_SINT8:
                value = intToSignedBits(value, 8);
                // Fall-through intended
            case BluetoothGattCharacteristic.FORMAT_UINT8:
                bytes[offset] = (byte) (value & 0xFF);
                break;

            case BluetoothGattCharacteristic.FORMAT_SINT16:
                value = intToSignedBits(value, 16);
                // Fall-through intended
            case BluetoothGattCharacteristic.FORMAT_UINT16:
                bytes[offset++] = (byte) (value & 0xFF);
                bytes[offset] = (byte) ((value >> 8) & 0xFF);
                break;

            case BluetoothGattCharacteristic.FORMAT_SINT32:
                value = intToSignedBits(value, 32);
                // Fall-through intended
            case BluetoothGattCharacteristic.FORMAT_UINT32:
                bytes[offset++] = (byte) (value & 0xFF);
                bytes[offset++] = (byte) ((value >> 8) & 0xFF);
                bytes[offset++] = (byte) ((value >> 16) & 0xFF);
                bytes[offset] = (byte) ((value >> 24) & 0xFF);
                break;

            default:
                throw new NumberFormatException("Unknown formatType " + formatType);
        }
        return bytes;
    }

    /**
     * Code taken from {@link BluetoothGattCharacteristic#setValue(int, int, int, int)}
     *
     * @param mantissa   Mantissa for this characteristic
     * @param exponent   exponent value for this characteristic
     * @param formatType Float format type used to transform the value parameter
     * @param offset     Offset at which the value should be placed
     * @return never null
     */
    public static byte[] toBytes(int mantissa, int exponent, int formatType, int offset)
    {
        byte[] bytes = new byte[offset + getTypeLen(formatType)];

        switch (formatType)
        {
            case BluetoothGattCharacteristic.FORMAT_SFLOAT:
                mantissa = intToSignedBits(mantissa, 12);
                exponent = intToSignedBits(exponent, 4);
                bytes[offset++] = (byte) (mantissa & 0xFF);
                bytes[offset] = (byte) ((mantissa >> 8) & 0x0F);
                bytes[offset] += (byte) ((exponent & 0x0F) << 4);
                break;

            case BluetoothGattCharacteristic.FORMAT_FLOAT:
                mantissa = intToSignedBits(mantissa, 24);
                exponent = intToSignedBits(exponent, 8);
                bytes[offset++] = (byte) (mantissa & 0xFF);
                bytes[offset++] = (byte) ((mantissa >> 8) & 0xFF);
                bytes[offset++] = (byte) ((mantissa >> 16) & 0xFF);
                bytes[offset] += (byte) (exponent & 0xFF);
                break;

            default:
                throw new NumberFormatException("Unknown formatType " + formatType);
        }

        return bytes;
    }

    /**
     * Code taken from {@link BluetoothGattCharacteristic#setValue(String)}
     *
     * @param value New value for this characteristic
     * @return true if the locally stored value has been set
     */
    public static byte[] toBytes(String value)
    {
        return (value != null) ? value.getBytes() : new byte[] {};
    }

    /**
     * Code taken from {@link BluetoothGattCharacteristic#getTypeLen(int)}
     * Returns the size of a give value type.
     */
    @SuppressWarnings("JavadocReference")
    private static int getTypeLen(int formatType)
    {
        return formatType & 0xF;
    }

    /**
     * Code taken from {@link BluetoothGattCharacteristic#intToSignedBits(int, int)}
     * Convert an integer into the signed bits of a given length.
     */
    @SuppressWarnings("JavadocReference")
    private static int intToSignedBits(int i, int size)
    {
        if (i < 0)
        {
            i = (1 << size - 1) + (i & ((1 << size - 1) - 1));
        }
        return i;
    }
}


text:
function test_suite = test_ADC
   initTestSuite;
end

function test_ADC_Success
    myAsm = OneEightySix.Assembler();
    % Addition with no carry
    myAsm.MOV('AX', 0);
    myAsm.ADC('AX', 1);
    assertEqual(myAsm.AX, 1);
    assertEqual(myAsm.OF, false);
    assertEqual(myAsm.SF, false);
    assertEqual(myAsm.ZF, false);
    assertEqual(myAsm.AF, false);
    assertEqual(myAsm.PF, false);
    assertEqual(myAsm.CF, false);

    % Addition with carry
    myAsm.MOV('BX', 65535);
    myAsm.ADC('BX', 65535);
    assertEqual(myAsm.BX, 65535);
    assertEqual(myAsm.OF, false);
    assertEqual(myAsm.SF, true);
    assertEqual(myAsm.ZF, false);
    assertEqual(myAsm.AF, true);
    assertEqual(myAsm.PF, true);
    assertEqual(myAsm.CF, false);

end


text:
package com.sleepycat.je.latch;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import com.sleepycat.je.EnvironmentFailureException;
import com.sleepycat.je.dbi.EnvironmentImpl;

/**
 * Simple thread-based non-transactional reader-writer/shared-exclusive latch.
 *
 * Latches provide simple exclusive or shared transient locks on objects.
 * Latches are expected to be held for short, defined periods of time.  No
 * deadlock detection is provided so it is the caller's responsibility to
 * sequence latch acquisition in an ordered fashion to avoid deadlocks.
 */
@SuppressWarnings("serial")
public class SharedLatch
    extends ReentrantReadWriteLock {

    private String name;
    private boolean noteLatch;
    private List<Thread> readers;

    /**
     * If true, this shared latch is only ever latched exclusively.  Used for
     * BINs.
     */
    private boolean exclusiveOnly;

    public SharedLatch(String name) {
        super(false /* fair */);
        assert (readers = Collections.synchronizedList
                (new ArrayList<Thread>())) != null;
        exclusiveOnly = false;
        this.name = name;
    }

    /**
     * Set the latch name, used for latches in objects instantiated from the
     * log.
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Indicate whether this latch should be tracked in the debugging
     * LatchSupport.latchTable.
     * Always return true so this can be called under an assert.
     */
    public boolean setNoteLatch(boolean noteLatch) {
        this.noteLatch = noteLatch;
        return true;
    }

    /**
     * Indicate whether this latch can only be set exclusively (not shared).
     * Used for BIN latches that are Shared, but should only be latched
     * exclusively.
     */
    public void setExclusiveOnly(boolean exclusiveOnly) {
        this.exclusiveOnly = exclusiveOnly;
    }

    /**
     * Acquire a latch for exclusive/write access.  If the thread already holds
     * the latch for shared access, it cannot be upgraded and
     * EnvironmentFailureException will be thrown.
     *
     * Wait for the latch if some other thread is holding it.  If there are
     * threads waiting for access, they will be granted the latch on a FIFO
     * basis if fair latches are enabled (as of JE 5.0 they are never enabled).
     * When the method returns, the latch is held for exclusive access.
     *
     * @throws EnvironmentFailureException if the latch is already held by the
     * current thread for shared access.
     */
    public void acquireExclusive() {
        try {
            if (isWriteLockedByCurrentThread()) {
                throw EnvironmentFailureException.unexpectedState
                    ("Latch already held: " + name);
            }

            writeLock().lock();

            assert (noteLatch ? noteLatch() : true);// intentional side effect;
        } finally {
            assert EnvironmentImpl.maybeForceYield();
        }
    }

    /**
     * Probe a latch for exclusive access, but don't block if it's not
     * available.
     *
     * @return true if the latch was acquired, false if it is not available.
     *
     * @throws EnvironmentFailureException if the latch is already held by the
     * calling thread.
     */
    public boolean acquireExclusiveNoWait() {
        try {
            if (isWriteLockedByCurrentThread()) {
                throw EnvironmentFailureException.unexpectedState
                    ("Latch already held: " + name);
            }

            boolean ret = writeLock().tryLock();

            /* Intentional side effect. */
            assert ((noteLatch & ret) ? noteLatch() : true);
            return ret;
        } finally {
            assert EnvironmentImpl.maybeForceYield();
        }
    }

    /**
     * Acquire a latch for shared/read access.  Nesting is allowed, that is,
     * the latch may be acquired more than once by the same thread.
     */
    public void acquireShared() {
        if (exclusiveOnly) {
            acquireExclusive();
            return;
        }

        try {
            boolean assertionsEnabled = false;
            assert assertionsEnabled = true;
            if (assertionsEnabled) {
                if (readers.add(Thread.currentThread())) {
                    readLock().lock();
                } else {
                    /* Already latched, do nothing. */
                }
            } else {
                readLock().lock();
            }

            assert (noteLatch ?  noteLatch() : true);// intentional side effect
        } finally {
            assert EnvironmentImpl.maybeForceYield();
        }
    }

    /**
     * Release an exclusive or shared latch.  If there are other thread(s)
     * waiting for the latch, they are woken up and granted the latch.
     */
    public void release() {
        try {
            if (isWriteLockedByCurrentThread()) {
                writeLock().unlock();
                /* Intentional side effect. */
                assert (noteLatch ? unNoteLatch() : true);
                return;
            }

            if (exclusiveOnly) {
                return;
            }

            boolean assertionsEnabled = false;
            assert assertionsEnabled = true;
            if (assertionsEnabled) {
                if (readers.remove(Thread.currentThread())) {
                    readLock().unlock();
                } else {
                    throw EnvironmentFailureException.unexpectedState
                        ("Latch not held: " + name);
                }
            } else {

                /*
                 * There's no way to tell if a readlock is held by the current
                 * thread so just try unlocking it.
                 */
                readLock().unlock();
            }
            /* Intentional side effect. */
            assert (noteLatch ? unNoteLatch() : true);
        } catch (IllegalMonitorStateException IMSE) {
            IMSE.printStackTrace();
            return;
        }
    }

    /**
     * Release the latch. If there are other thread(s) waiting for the latch,
     * one is woken up and granted the latch.  If the latch was not owned by
     * the caller, just return.
     */
    public void releaseIfOwner() {
        if (isWriteLockedByCurrentThread()) {
            writeLock().unlock();
            assert (noteLatch ? unNoteLatch() : true);
            return;
        }

        if (exclusiveOnly) {
            return;
        }

        assert (getReadLockCount() > 0);
        boolean assertionsEnabled = false;
        assert assertionsEnabled = true;
        if (assertionsEnabled) {
            if (readers.contains(Thread.currentThread())) {
                readLock().unlock();
                readers.remove(Thread.currentThread());
                assert (noteLatch ? unNoteLatch() : true);
            }
        } else {

            /*
             * There's no way to tell if a readlock is held by the current
             * thread so just try unlocking it.
             */
            readLock().unlock();
        }
    }

    /**
     * Return true if this thread is an owner, reader, or write.
     */
    public boolean isOwner() {
        boolean assertionsEnabled = false;
        assert assertionsEnabled = true;
        if (assertionsEnabled && !exclusiveOnly) {
            return readers.contains(Thread.currentThread()) ||
                isWriteLockedByCurrentThread();
        } else {
            return isWriteLockedByCurrentThread();
        }
    }

    /**
     * Only call under the assert system. This records latching by thread.
     */
    private boolean noteLatch() {
        return LatchSupport.latchTable.noteLatch(this);
    }

    /**
     * Only call under the assert system. This records latching by thread.
     */
    private boolean unNoteLatch() {

        return LatchSupport.latchTable.unNoteLatch(this, name);
    }
}


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.Network.Models
{
    /// <summary> Details of PrepareNetworkPolicies for Subnet. </summary>
    public partial class PrepareNetworkPoliciesRequest
    {
        /// <summary> Initializes a new instance of PrepareNetworkPoliciesRequest. </summary>
        public PrepareNetworkPoliciesRequest()
        {
            NetworkIntentPolicyConfigurations = new ChangeTrackingList<NetworkIntentPolicyConfiguration>();
        }

        /// <summary> The name of the service for which subnet is being prepared for. </summary>
        public string ServiceName { get; set; }
        /// <summary> A list of NetworkIntentPolicyConfiguration. </summary>
        public IList<NetworkIntentPolicyConfiguration> NetworkIntentPolicyConfigurations { get; }
    }
}


text:
<?php

namespace Dotdigitalgroup\Email\Setup\Install\Type;

use Dotdigitalgroup\Email\Setup\SchemaInterface as Schema;

class InsertEmailWishlistTable extends AbstractBatchInserter implements InsertTypeInterface
{
    /**
     * @var string
     */
    protected $tableName = Schema::EMAIL_WISHLIST_TABLE;

    /**
     * @inheritdoc
     */
    protected function getSelectStatement()
    {
        return $this->resourceConnection
            ->getConnection()
            ->select()
            ->distinct()
            ->from([
                'wishlist' => $this->resourceConnection->getTableName('wishlist'),
            ], [
                'wishlist_id',
                'customer_id',
                'created_at' => 'updated_at',
            ])
            ->joinInner(
                ['wi' => $this->resourceConnection->getTableName('wishlist_item')],
                'wishlist.wishlist_id = wi.wishlist_id',
                ['store_id', 'item_count' => 'count(wi.wishlist_id)']
            )
            ->group(['wi.wishlist_id', 'wi.store_id'])
            ->order('wi.wishlist_id');
    }

    /**
     * @inheritdoc
     */
    public function getInsertArray()
    {
        return [
            'wishlist_id',
            'customer_id',
            'created_at',
            'store_id',
            'item_count',
        ];
    }
}


text:
namespace FluentACS.Specs
{
    public class GoogleIdentityProviderSpec : IdentityProviderSpec
    {
        public GoogleIdentityProviderSpec()
        {
            this.DisplayName(IdentityProviderConsts.Google);
        }
    }
}


text:
<?php

namespace Tests\ForexCalculator\PrecisionProviders;

use ForexCalculator\PrecisionProviders\UniversalPrecisionProvider;
use PHPUnit_Framework_TestCase;

final class UniversalPrecisionProviderTest extends PHPUnit_Framework_TestCase
{

    /**
     * @dataProvider getDataForGetPrecision
     * @param int $expectedPrecision
     * @param int $givenPrecision
     */
    public function testGetPrecision(int $expectedPrecision, int $givenPrecision): void
    {
       $precisionProvider = new UniversalPrecisionProvider($givenPrecision);
       $this->assertEquals($expectedPrecision, $precisionProvider->getPrecision());
    }

    public function getDataForGetPrecision(): array
    {
        return [
            [0, 0],
            [2, 2],
        ];
    }

}


text:
require "import/sprite/character/hair/color_palette_seeder"

seeder = Sprite::Character::Hair::ColorPaletteSeeder.new
seeder.seed_files


text:
<?php

namespace Etu\Core\CoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Table(name="etu_notifications")
 * @ORM\Entity()
 * @Gedmo\SoftDeleteable(fieldName="deletedAt")
 */
class Notification
{
    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     */
    protected $authorId;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=50)
     */
    protected $entityType;

    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     */
    protected $entityId;

    /**
     * Template helper: class loaded to display the notification.
     *
     * @var string
     *
     * @ORM\Column(type="string", length=100)
     */
    protected $helper;

    /**
     * List of entities in the notification (given to the helper).
     *
     * @var array
     *
     * @ORM\Column(type="array")
     */
    protected $entities;

    /**
     * Source module.
     *
     * @var string
     *
     * @ORM\Column(type="string", length=100)
     */
    protected $module;

    /**
     * Is a super-notification ?
     *
     * @var bool
     *
     * @ORM\Column(type="boolean")
     */
    protected $isSuper;

    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime")
     */
    protected $expiration;

    /**
     * @var \DateTime
     *
     * @Gedmo\Timestampable(on="create")
     * @ORM\Column(type="datetime")
     */
    protected $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime", nullable = true)
     */
    protected $deletedAt;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->expiration = new \DateTime();
        $this->isSuper = false;
        $this->authorId = 0;
    }

    /**
     * @param int $authorId
     *
     * @return Notification
     */
    public function setAuthorId($authorId)
    {
        $this->authorId = $authorId;

        return $this;
    }

    /**
     * @return int
     */
    public function getAuthorId()
    {
        return $this->authorId;
    }

    /**
     * @param array $entities
     *
     * @return Notification
     */
    public function setEntities(array $entities)
    {
        $this->entities = $entities;

        return $this;
    }

    /**
     * @param object $entity
     *
     * @return Notification
     */
    public function addEntity($entity)
    {
        $this->entities[] = $entity;

        return $this;
    }

    /**
     * @param object $entity
     *
     * @return Notification
     */
    public function removeEntity($entity)
    {
        if ($key = array_search($entity, $this->entities)) {
            unset($this->entities[$key]);
        }

        return $this;
    }

    /**
     * @return int
     */
    public function countEntities()
    {
        return count($this->entities);
    }

    /**
     * @return object
     */
    public function getFirstEntity()
    {
        return $this->getEntity(1);
    }

    /**
     * @param int $number
     *
     * @return object
     */
    public function getEntity($number)
    {
        return (isset($this->entities[$number - 1])) ? $this->entities[$number - 1] : false;
    }

    /**
     * @return array
     */
    public function getEntities()
    {
        return $this->entities;
    }

    /**
     * @param int $entityId
     *
     * @return Notification
     */
    public function setEntityId($entityId)
    {
        $this->entityId = $entityId;

        return $this;
    }

    /**
     * @return int
     */
    public function getEntityId()
    {
        return $this->entityId;
    }

    /**
     * @param string $entityType
     *
     * @return Notification
     */
    public function setEntityType($entityType)
    {
        $this->entityType = $entityType;

        return $this;
    }

    /**
     * @return string
     */
    public function getEntityType()
    {
        return $this->entityType;
    }

    /**
     * @param \DateTime $expiration
     *
     * @return Notification
     */
    public function setExpiration($expiration)
    {
        $this->expiration = $expiration;

        return $this;
    }

    /**
     * @return \DateTime
     */
    public function getExpiration()
    {
        return $this->expiration;
    }

    /**
     * @param string $helper
     *
     * @return Notification
     */
    public function setHelper($helper)
    {
        $this->helper = $helper;

        return $this;
    }

    /**
     * @return string
     */
    public function getHelper()
    {
        return $this->helper;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param bool $isSuper
     *
     * @return Notification
     */
    public function setIsSuper($isSuper)
    {
        $this->isSuper = $isSuper;

        return $this;
    }

    /**
     * @return bool
     */
    public function getIsSuper()
    {
        return $this->isSuper;
    }

    /**
     * @param string $module
     *
     * @return Notification
     */
    public function setModule($module)
    {
        $this->module = $module;

        return $this;
    }

    /**
     * @return string
     */
    public function getModule()
    {
        return $this->module;
    }

    /**
     * Set createdAt.
     *
     * @param \DateTime $createdAt
     *
     * @return Notification
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt.
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Get createdAt.
     *
     * @return \DateTime
     */
    public function getDate()
    {
        return $this->createdAt;
    }

    /**
     * @param \DateTime $lastVisitHome
     *
     * @return bool
     */
    public function isNew(\DateTime $lastVisitHome)
    {
        return $lastVisitHome < $this->createdAt;
    }

    /**
     * Set deletedAt.
     *
     * @param \DateTime $deletedAt
     *
     * @return Notification
     */
    public function setDeletedAt($deletedAt)
    {
        $this->deletedAt = $deletedAt;

        return $this;
    }

    /**
     * Get deletedAt.
     *
     * @return \DateTime
     */
    public function getDeletedAt()
    {
        return $this->deletedAt;
    }
}


text:
package composeapi

import (
	"encoding/json"
	"time"
)

// Backup structure
type Backup struct {
	ID             string    `json:"id"`
	Deploymentid   string    `json:"deployment_id"`
	Name           string    `json:"name"`
	Type           string    `json:"type"`
	Status         string    `json:"status"`
	IsDownloadable bool      `json:"is_downloadable"`
	IsRestorable   bool      `json:"is_restorable"`
	CreatedAt      time.Time `json:"created_at"`
	DownloadLink   string    `json:"download_link"`
}

// backupsResponse is used to represent and remove the JSON+HAL Embedded wrapper
type backupsResponse struct {
	Embedded struct {
		Backups []Backup `json:"backups"`
	} `json:"_embedded"`
}

//GetBackupsForDeploymentJSON returns backup details for deployment
func (c *Client) GetBackupsForDeploymentJSON(deploymentid string) (string, []error) {
	return c.getJSON("deployments/" + deploymentid + "/backups")
}

//GetBackupsForDeployment returns backup details for deployment
func (c *Client) GetBackupsForDeployment(deploymentid string) (*[]Backup, []error) {
	body, errs := c.GetBackupsForDeploymentJSON(deploymentid)

	if errs != nil {
		return nil, errs
	}

	backupsResponse := backupsResponse{}
	json.Unmarshal([]byte(body), &backupsResponse)
	Backups := backupsResponse.Embedded.Backups

	return &Backups, nil
}

//StartBackupForDeploymentJSON starts backup and returns JSON response
func (c *Client) StartBackupForDeploymentJSON(deploymentid string) (string, []error) {
	response, body, errs := c.newRequest("POST", apibase+"deployments/"+deploymentid+"/backups").
		End()

	if response.StatusCode != 202 { // Expect Accepted on success - assume error on anything else
		errs = ProcessErrors(response.StatusCode, body)
	}

	return body, errs
}

//StartBackupForDeployment starts backup and returns recipe
func (c *Client) StartBackupForDeployment(deploymentid string) (*Recipe, []error) {
	body, errs := c.StartBackupForDeploymentJSON(deploymentid)
	if errs != nil {
		return nil, errs
	}

	recipe := Recipe{}
	json.Unmarshal([]byte(body), &recipe)

	return &recipe, nil
}

//GetBackupDetailsForDeploymentJSON returns the details and download link for a backup
func (c *Client) GetBackupDetailsForDeploymentJSON(deploymentid string, backupid string) (string, []error) {
	return c.getJSON("deployments/" + deploymentid + "/backups/" + backupid)
}

//GetBackupDetailsForDeployment returns backup details for deployment
func (c *Client) GetBackupDetailsForDeployment(deploymentid string, backupid string) (*Backup, []error) {
	body, errs := c.GetBackupDetailsForDeploymentJSON(deploymentid, backupid)

	if errs != nil {
		return nil, errs
	}

	backup := Backup{}
	json.Unmarshal([]byte(body), &backup)

	return &backup, nil
}

//RestoreBackupParams Parameters to be completed before creating a deployment
type RestoreBackupParams struct {
	DeploymentID string
	BackupID     string
	Name         string
	ClusterID    string
	Datacenter   string
	Version      string
	SSL          bool
}

type restoreBackupParams struct {
	DeploymentID string                        `json:"-"`
	BackupID     string                        `json:"-"`
	Deployment   restoreBackupDeploymentParams `json:"deployment"`
}

type restoreBackupDeploymentParams struct {
	Name       string `json:"name"`
	ClusterID  string `json:"cluster_id,omitempty"`
	Datacenter string `json:"datacenter,omitempty"`
	Version    string `json:"version,omitempty"`
	SSL        bool   `json:"ssl,omitempty"`
}

//RestoreBackupJSON performs the call
func (c *Client) RestoreBackupJSON(params RestoreBackupParams) (string, []error) {
	backupparams := restoreBackupParams{
		DeploymentID: params.DeploymentID,
		BackupID:     params.BackupID,
		Deployment: restoreBackupDeploymentParams{Name: params.Name,
			ClusterID:  params.ClusterID,
			Datacenter: params.Datacenter,
			Version:    params.Version,
			SSL:        params.SSL,
		},
	}

	response, body, errs := c.newRequest("POST", apibase+"deployments/"+params.DeploymentID+"/backups/"+params.BackupID+"/restore").
		Send(backupparams).
		End()

	if response.StatusCode != 202 { // Expect Accepted on success - assume error on anything else
		errs = ProcessErrors(response.StatusCode, body)
	}

	return body, errs
}

//RestoreBackup creates a deployment
func (c *Client) RestoreBackup(params RestoreBackupParams) (*Deployment, []error) {

	// This is a POST not a GET, so it builds its own request

	body, errs := c.RestoreBackupJSON(params)

	if errs != nil {
		return nil, errs
	}

	deployed := Deployment{}
	json.Unmarshal([]byte(body), &deployed)

	return &deployed, nil
}