text:
package com.opensymphony.xwork2.config.providers;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.config.entities.InterceptorConfig;
import com.opensymphony.xwork2.config.entities.InterceptorMapping;
import com.opensymphony.xwork2.config.entities.InterceptorStackConfig;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import com.opensymphony.xwork2.interceptor.Interceptor;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * InterceptorBuilderTest
 *
 * @author Rainer Hermanns
 * @version $Id: InterceptorBuilderTest.java 894087 2009-12-27 18:00:13Z martinc $
 */
public class InterceptorBuilderTest extends XWorkTestCase {

    ObjectFactory objectFactory;

    @Override
    public void setUp() throws Exception {
        super.setUp();
        objectFactory = container.getInstance(ObjectFactory.class);
    }

    /**
     * Try to test this
     * <interceptor-ref name="interceptorStack1">
     * <param name="interceptor1.param1">interceptor1_value1</param>
     * <param name="interceptor1.param2">interceptor1_value2</param>
     * <param name="interceptor2.param1">interceptor2_value1</param>
     * <param name="interceptor2.param2">interceptor2_value2</param>
     * </interceptor-ref>
     *
     * @throws Exception
     */
    public void testBuildInterceptor_1() throws Exception {
        InterceptorStackConfig interceptorStackConfig1 = new InterceptorStackConfig.Builder("interceptorStack1").build();

        InterceptorConfig interceptorConfig1 = new InterceptorConfig.Builder("interceptor1", "com.opensymphony.xwork2.config.providers.InterceptorBuilderTest$MockInterceptor1").build();

        InterceptorConfig interceptorConfig2 = new InterceptorConfig.Builder("interceptor2", "com.opensymphony.xwork2.config.providers.InterceptorBuilderTest$MockInterceptor2").build();

        PackageConfig packageConfig = new PackageConfig.Builder("package1").namespace("/namespace").addInterceptorConfig(interceptorConfig1).addInterceptorConfig(interceptorConfig2).addInterceptorStackConfig(interceptorStackConfig1).build();

        List
                interceptorMappings =
                InterceptorBuilder.constructInterceptorReference(packageConfig, "interceptorStack1",
                        new LinkedHashMap<String, String>() {
                            private static final long serialVersionUID = -1358620486812957895L;

                            {
                                put("interceptor1.param1", "interceptor1_value1");
                                put("interceptor1.param2", "interceptor1_value2");
                                put("interceptor2.param1", "interceptor2_value1");
                                put("interceptor2.param2", "interceptor2_value2");
                            }
                        },null,  objectFactory);

        assertEquals(interceptorMappings.size(), 2);

        assertEquals(((InterceptorMapping) interceptorMappings.get(0)).getName(), "interceptor1");
        assertNotNull(((InterceptorMapping) interceptorMappings.get(0)).getInterceptor());
        assertEquals(((InterceptorMapping) interceptorMappings.get(0)).getInterceptor().getClass(), MockInterceptor1.class);
        assertEquals(((MockInterceptor1) ((InterceptorMapping) interceptorMappings.get(0)).getInterceptor()).getParam1(), "interceptor1_value1");
        assertEquals(((MockInterceptor1) ((InterceptorMapping) interceptorMappings.get(0)).getInterceptor()).getParam2(), "interceptor1_value2");

        assertEquals(((InterceptorMapping) interceptorMappings.get(1)).getName(), "interceptor2");
        assertNotNull(((InterceptorMapping) interceptorMappings.get(1)).getInterceptor());
        assertEquals(((InterceptorMapping) interceptorMappings.get(1)).getInterceptor().getClass(), MockInterceptor2.class);
        assertEquals(((MockInterceptor2) ((InterceptorMapping) interceptorMappings.get(1)).getInterceptor()).getParam1(), "interceptor2_value1");
        assertEquals(((MockInterceptor2) ((InterceptorMapping) interceptorMappings.get(1)).getInterceptor()).getParam2(), "interceptor2_value2");
    }

    /**
     * Try to test this
     * <interceptor-ref name="interceptorStack1">
     * <param name="interceptorStack2.interceptor1.param1">interceptor1_value1</param>
     * <param name="interceptorStack2.interceptor1.param2">interceptor1_value2</param>
     * <param name="interceptorStack3.interceptor2.param1">interceptor2_value1</param>
     * <param name="interceptorStack3.interceptor2.param2">interceptor2_value2</param>
     * </interceptor-ref>
     *
     * @throws Exception
     */
    public void testBuildInterceptor_2() throws Exception {
        InterceptorStackConfig interceptorStackConfig1 = new InterceptorStackConfig.Builder("interceptorStack1").build();

        InterceptorStackConfig interceptorStackConfig2 = new InterceptorStackConfig.Builder("interceptorStack2").build();

        InterceptorStackConfig interceptorStackConfig3 = new InterceptorStackConfig.Builder("interceptorStack3").build();

        InterceptorConfig interceptorConfig1 = new InterceptorConfig.Builder("interceptor1", "com.opensymphony.xwork2.config.providers.InterceptorBuilderTest$MockInterceptor1").build();

        InterceptorConfig interceptorConfig2 = new InterceptorConfig.Builder("interceptor2", "com.opensymphony.xwork2.config.providers.InterceptorBuilderTest$MockInterceptor2").build();

        PackageConfig packageConfig = new PackageConfig.Builder("package1").namespace("/namspace").
                addInterceptorConfig(interceptorConfig1).
                addInterceptorConfig(interceptorConfig2).
                addInterceptorStackConfig(interceptorStackConfig1).
                addInterceptorStackConfig(interceptorStackConfig2).
                addInterceptorStackConfig(interceptorStackConfig3).build();

        List interceptorMappings = InterceptorBuilder.constructInterceptorReference(packageConfig, "interceptorStack1",
                new LinkedHashMap<String, String>() {
                    private static final long serialVersionUID = -5819935102242042570L;

                    {
                        put("interceptorStack2.interceptor1.param1", "interceptor1_value1");
                        put("interceptorStack2.interceptor1.param2", "interceptor1_value2");
                        put("interceptorStack3.interceptor2.param1", "interceptor2_value1");
                        put("interceptorStack3.interceptor2.param2", "interceptor2_value2");
                    }
                }, null, objectFactory);

        assertEquals(interceptorMappings.size(), 2);

        assertEquals(((InterceptorMapping) interceptorMappings.get(0)).getName(), "interceptor1");
        assertNotNull(((InterceptorMapping) interceptorMappings.get(0)).getInterceptor());
        assertEquals(((InterceptorMapping) interceptorMappings.get(0)).getInterceptor().getClass(), MockInterceptor1.class);
        assertEquals(((MockInterceptor1) ((InterceptorMapping) interceptorMappings.get(0)).getInterceptor()).getParam1(), "interceptor1_value1");
        assertEquals(((MockInterceptor1) ((InterceptorMapping) interceptorMappings.get(0)).getInterceptor()).getParam2(), "interceptor1_value2");

        assertEquals(((InterceptorMapping) interceptorMappings.get(1)).getName(), "interceptor2");
        assertNotNull(((InterceptorMapping) interceptorMappings.get(1)).getInterceptor());
        assertEquals(((InterceptorMapping) interceptorMappings.get(1)).getInterceptor().getClass(), MockInterceptor2.class);
        assertEquals(((MockInterceptor2) ((InterceptorMapping) interceptorMappings.get(1)).getInterceptor()).getParam1(), "interceptor2_value1");
        assertEquals(((MockInterceptor2) ((InterceptorMapping) interceptorMappings.get(1)).getInterceptor()).getParam2(), "interceptor2_value2");
    }

    /**
     * Try to test this
     * <interceptor-ref name="interceptorStack1">
     * <param name="interceptorStack2.interceptorStack3.interceptorStack4.interceptor1.param1">interceptor1_value1</param>
     * <param name="interceptorStack2.interceptorStack3.interceptorStack4.interceptor1.param2">interceptor1_value2</param>
     * <param name="interceptorStack5.interceptor2.param1">interceptor2_value1</param>
     * <param name="interceptorStack5.interceptor2.param2">interceptor2_value2</param>
     * </interceptor-ref>
     *
     * @throws Exception
     */
    public void testBuildInterceptor_3() throws Exception {
        InterceptorConfig interceptorConfig1 = new InterceptorConfig.Builder("interceptor1", "com.opensymphony.xwork2.config.providers.InterceptorBuilderTest$MockInterceptor1").build();

        InterceptorConfig interceptorConfig2 = new InterceptorConfig.Builder("interceptor2", "com.opensymphony.xwork2.config.providers.InterceptorBuilderTest$MockInterceptor2").build();

        InterceptorStackConfig interceptorStackConfig1 = new InterceptorStackConfig.Builder("interceptorStack1").build();

        InterceptorStackConfig interceptorStackConfig2 = new InterceptorStackConfig.Builder("interceptorStack2").build();

        InterceptorStackConfig interceptorStackConfig3 = new InterceptorStackConfig.Builder("interceptorStack3").build();

        InterceptorStackConfig interceptorStackConfig4 = new InterceptorStackConfig.Builder("interceptorStack4").build();

        InterceptorStackConfig interceptorStackConfig5 = new InterceptorStackConfig.Builder("interceptorStack5").build();

        PackageConfig packageConfig = new PackageConfig.Builder("package1").
                addInterceptorConfig(interceptorConfig1).
                addInterceptorConfig(interceptorConfig2).
                addInterceptorStackConfig(interceptorStackConfig1).
                addInterceptorStackConfig(interceptorStackConfig2).
                addInterceptorStackConfig(interceptorStackConfig3).
                addInterceptorStackConfig(interceptorStackConfig4).
                addInterceptorStackConfig(interceptorStackConfig5).build();

        List interceptorMappings = InterceptorBuilder.constructInterceptorReference(
                packageConfig, "interceptorStack1",
                new LinkedHashMap<String, String>() {
                    private static final long serialVersionUID = 4675809753780875525L;

                    {
                        put("interceptorStack2.interceptorStack3.interceptorStack4.interceptor1.param1", "interceptor1_value1");
                        put("interceptorStack2.interceptorStack3.interceptorStack4.interceptor1.param2", "interceptor1_value2");
                        put("interceptorStack5.interceptor2.param1", "interceptor2_value1");
                        put("interceptorStack5.interceptor2.param2", "interceptor2_value2");
                    }
                }, null, objectFactory);

        assertEquals(interceptorMappings.size(), 2);

        assertEquals(((InterceptorMapping) interceptorMappings.get(0)).getName(), "interceptor1");
        assertNotNull(((InterceptorMapping) interceptorMappings.get(0)).getInterceptor());
        assertEquals(((InterceptorMapping) interceptorMappings.get(0)).getInterceptor().getClass(), MockInterceptor1.class);
        assertEquals(((MockInterceptor1) ((InterceptorMapping) interceptorMappings.get(0)).getInterceptor()).getParam1(), "interceptor1_value1");
        assertEquals(((MockInterceptor1) ((InterceptorMapping) interceptorMappings.get(0)).getInterceptor()).getParam2(), "interceptor1_value2");

        assertEquals(((InterceptorMapping) interceptorMappings.get(1)).getName(), "interceptor2");
        assertNotNull(((InterceptorMapping) interceptorMappings.get(1)).getInterceptor());
        assertEquals(((InterceptorMapping) interceptorMappings.get(1)).getInterceptor().getClass(), MockInterceptor2.class);
        assertEquals(((MockInterceptor2) ((InterceptorMapping) interceptorMappings.get(1)).getInterceptor()).getParam1(), "interceptor2_value1");
        assertEquals(((MockInterceptor2) ((InterceptorMapping) interceptorMappings.get(1)).getInterceptor()).getParam2(), "interceptor2_value2");
    }

    public static class MockInterceptor1 implements Interceptor {
        private static final long serialVersionUID = 2939902550126175874L;
        private String param1;
        private String param2;

        public void setParam1(String param1) {
            this.param1 = param1;
        }

        public String getParam1() {
            return this.param1;
        }

        public void setParam2(String param2) {
            this.param2 = param2;
        }

        public String getParam2() {
            return this.param2;
        }

        public void destroy() {
        }

        public void init() {
        }

        public String intercept(ActionInvocation invocation) throws Exception {
            return invocation.invoke();
        }
    }

    public static class MockInterceptor2 implements Interceptor {
        private static final long serialVersionUID = 267427973306989618L;
        private String param1;
        private String param2;

        public void setParam1(String param1) {
            this.param1 = param1;
        }

        public String getParam1() {
            return this.param1;
        }

        public void setParam2(String param2) {
            this.param2 = param2;
        }

        public String getParam2() {
            return this.param2;
        }

        public void destroy() {
        }

        public void init() {
        }

        public String intercept(ActionInvocation invocation) throws Exception {
            return invocation.invoke();
        }
    }

}


text:
import Bot from '../lib/Bot';
import initializeMessangerProfile from './messengerProfile';
import message from './message';
import postback from './postback';
import accountLinked from './accountLinked';
import accountUnlinked from './accountUnlinked';

const bot = new Bot({
  token: process.env.PAGE_TOKEN,
  verify: process.env.VERIFY_TOKEN,
  app_secret: process.env.APP_SECRET
});

initializeMessangerProfile(bot);

bot.on('error', (err) => {
  console.log(err.message);
});

bot.on('message', message(bot));
bot.on('postback', postback(bot));
bot.on('accountLinked', accountLinked(bot));
bot.on('accountUnlinked', accountUnlinked(bot));

export default bot;

redpajama_set_name: RedPajamaGithub


text: ARM Template to provision a VM complete with Visual Studio and any given Chocolatey packages.


text:
package com.gmu.tutors;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@Profile("swagger")
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket apiDocumentation(){
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    @Bean
    UiConfiguration uiConfig() {
        return new UiConfiguration("");
    }

    private ApiInfo apiInfo() {
        return new ApiInfo(
                "GMU Tutors Application",
                "Web App project to connect students to their peer tutors",
                "0.0.1",
                "",
                new Contact("Andrew Huynh", "https://github.com/SaxyPandaBear", "ahuynh11@gmu.edu"),
                "MIT",
                "",
                null
        );
    }
}


text:
1. Set up your `SAUCE_USERNAME`, `SAUCE_ACCESS_KEY` & `SAUCE_TUNNEL_IDENTIFIER` environment variables.
These are required. You can find the values for `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` in `/.circleci/env.sh`. `SAUCE_TUNNEL_IDENTIFIER` can be set to any unique value.

If you are having trouble running Saucelabs tests locally you can contact [Joey Perrott](https://github.com/josephperrott) or [Greg Magolan](https://github.com/gregmagolan) for support.

1. On OSX and Windows, you will also need to set `SAUCE_CONNECT` to the path of your `sc` binary (Sauce Connect Proxy).
You will have to download Sauce Connect Proxy if you don't already have it downloaded.
It's available on the SauceLabs website [here](https://wiki.saucelabs.com/display/DOCS/Downloading+Sauce+Connect+Proxy).
Unzip it and point the SAUCE_CONNECT env variable to the `sc` binary.

```
export SAUCE_CONNECT=/{path_to_sc}/bin/sc
```

Note: it will not work to use the Sauce Connect that's already in node_modules unless you are using Linux.
Download the one above for other platforms.

3. Once you have your environment variables set up, run the setup task in the root of the repo:

``` bash
yarn bazel run //tools/saucelabs:sauce_service_setup
```

4. You can run a particular test target through SauceLabs by prefixing the target name with "saucelabs_" and adding the `--config=saucelabs` option.
For example, `packages/core/test:test_web` becomes `packages/core/test:saucelabs_test_web`.

```
yarn bazel test //packages/core/test:saucelabs_test_web --config=saucelabs
```

5. Sauce service log may be tailed or dumped with the following targets:

``` bash
yarn bazel run //tools/saucelabs:sauce_service_tail
yarn bazel run //tools/saucelabs:sauce_service_log
```

## Additional test features

To see the test output while the tests are running (as these are long tests), add the `--test_output=streamed` option.
Note, this option will also prevent bazel from using the test cache and will force the test to run.

`bazel query` is required gather up all karma saucelabs test labels so they can be run in one command as they are tagged `manual`.

Running all karma tests in Saucelabs:

``` bash
yarn bazel run //tools/saucelabs:sauce_service_setup
TESTS=$(./node_modules/.bin/bazelisk query --output label '(kind(karma_web_test, ...) intersect attr("tags", "saucelabs", ...)) except attr("tags", "view-engine-only", ...) except attr("tags", "fixme-saucelabs", ...)')
yarn bazel test --config=saucelabs ${TESTS}
```

## Under the hood

The `//tools/saucelabs:sauce_service_setup` target does not start the Sauce Connect proxy but it does start the process that then listens for the start signal from the service manager script.
This signal is sent by the karma wrapper script `//tools/saucelabs:karma-saucelabs` which calls `./tools/saucelabs/sauce-service.sh start`.
This is necessary as the Sauce Connect Proxy process must be started outside of `bazel test` as Bazel will automatically kill any processes spawned during a test when that tests completes, which would prevent the tunnel from being shared by multiple tests.

The karma_web_test rule is to test with saucelabs with a modified `karma` attribute set to
`//tools/saucelabs:karma-saucelabs`. This runs the `/tools/saucelabs/karma-saucelabs.js` wrapper
script which configures the saucelabs environment and starts Sauce Connect before running karma.

For example,

``` python
karma_web_test(
    name = "saucelabs_core_acceptance_tests",
    timeout = "long",
    karma = "//tools/saucelabs:karma-saucelabs",
    tags = [
        "exclusive",
        "manual",
        "no-remote-exec",
        "saucelabs",
    ],
    deps = [
        "//packages/core/test/acceptance:acceptance_lib",
    ],
)
```

These saucelabs targets must have a few important tags:
*  `no-remote-exec` as they cannot be executed remotely since they require a local Sauce Connect process
*  `manual` so they are not automatically tested with `//...`
*  `exclusive` as they must be run serially in order to not over-provision Saucelabs browsers
*  `saucelabs` so that they can be easily gathered up for testing in a `bazel query`

## Debugging

**Q: How do I get the tests to run on IE? I only see Chromium.**

If you see something like this at the end of your test output, it means you're not actually running SauceLabs:

```
INFO: Build completed successfully, 43 total actions
/packages/core/test:test_web_chromium
```

This is a common error caused by forgetting to prefix your test target with "saucelabs_".
For example, `/packages/core/test:test_web` becomes `/packages/core/test:saucelabs_test_web`.

**Q: How can I tell that the SauceLabs connection was successfully made?**

There is a dashboard at saucelabs.com where you can see active tunnel connections (Angular has an account).
As soon as you actually run the test target (not after the setup task), you should see an active tunnel connection under the SAUCE_TUNNEL_IDENTIFICATION_KEY you entered.
If a tunnel connection is not there, you are not actually connecting with SauceLabs.

Note: It may *look* like the tests are running because of the Bazel output.
The progress Bazel is showing does not mean that SauceLabs is connected.
If the tests are actually running, you should see the "..." test report for passing tests.


text:
<?php

$src = 'testimages/GSE-Projekt-Auswaertiges-Amt.jpg';
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
	$targ_w = 300;
    $targ_h = 200;
	$jpeg_quality = 90;

	$img_r = imagecreatefromjpeg($src);
	$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

	imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
	$targ_w,$targ_h,$_POST['w'],$_POST['h']);

	header('Content-type: image/jpeg');
	imagejpeg($dst_r,null,$jpeg_quality);

	exit;
}

// If not a POST request, display page below:

?><!DOCTYPE html>

  <title>Live Cropping Demo</title>
  <meta http-equiv="Content-type" content="text/html;charset=UTF-8" />

  <link rel="stylesheet" href="css/main.css" type="text/css" />
  <link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />

Server-based Cropping Behavior

		<img src="<?php echo $src; ?>" id="cropbox" />

		<form action="crop.php" method="post" onsubmit="return checkCoords();">
			<input type="hidden" id="x" name="x" />
			<input type="hidden" id="y" name="y" />
			<input type="hidden" id="w" name="w" />
			<input type="hidden" id="h" name="h" />
			<input type="submit" value="Crop Image" class="btn btn-large btn-inverse" />
		</form>


text:
                <fa-icon [icon]="farListAlt"></fa-icon>
                Problem Statement
                Instructions

                <fa-icon class="top-icon" [icon]="faChevronLeft"></fa-icon>
                <fa-icon [icon]="farListAlt" class="fa-rotate-90" id="panel-symbol"></fa-icon>
                Problem Statement
                Instructions
                <fa-icon class="bottom-icon" [icon]="faChevronLeft"></fa-icon>

        <fa-icon *ngIf="!collapsed" class="ms-auto clickable" [icon]="faChevronRight"></fa-icon>

    <ng-content *ngIf="!collapsed"></ng-content>


text:
create table foo(a int,b int,c int,d int,e int);
insert into foo values(1,2,3,4,5);
insert into foo values(2,3,4,5,6);
insert into foo values(3,4,5,6,7);
insert into foo values(4,5,6,7,8);
insert into foo values(5,6,7,8,9);
insert into foo values(9,7,6,6,5);
insert into foo values(10,20,30,40,50);

--abey the syntax
prepare st from 'select a, case  when a=? then ? end from foo;';
execute st using  1,2;

prepare st from 'select a, case c  when ? then ? else ? end from foo;';
execute st using  1,2,3;

prepare st from 'select a, case  when (b>5 and c>8 or d<? and a in (select a from foo))  then ? else ?  end from foo;';
execute st using  1,2,3;

prepare st from 'select a, case  when (a>5 and b>8 or c<9 and exists (select * from foo))  then ? else ?  end from foo;';
execute st using  1,2;

prepare st from 'select a, case  when (b>5 and c>8 or d<9 and e between ? and ?)  then ? else ?  end from foo;';
execute st using  1,2,3,4;

prepare st from 'select  case when a=? then NULL else ? end from foo;';
execute st using  1,2;

--nest case in when,then, else
prepare st from 'select  case when case when ? then ? else ? end then NULL else ? end from foo;';
execute st using  1,2,3,4;

prepare st from 'select  case when ? then case when ? then ? else ? end else ? end from foo;';
execute st using  1,2,3,4,5;

prepare st from 'select  case when ? then ? else case when ? then ? else ? end end from foo;';
execute st using  1,2,3,4,5;

--NULL VALUE
prepare st from 'select a, case  when NULL then ? else ? end from foo;';
execute st using  1,2;

prepare st from 'select a, case  when ? then NULL else ? end from foo;';
execute st using  1,2;

prepare st from 'select a, case  when ? then ? else NULL end from foo;';
execute st using  1,2;

--not abey the syntax,expected wrong
prepare st from 'select a, case  then ? else ? end from foo;';
prepare st from 'select a, case  when  then ? else ? end from foo;';
prepare st from 'select a, case  when a=? then  else ? end from foo;';
prepare st from 'select a, case  when a=? then ? else  end from foo;';
prepare st from 'select a, case  when a=? then ? else ? else ? end from foo;';
prepare st from 'select a, case  when a=? then ? else ? end else ? end from foo;';

drop table foo;


text:
package org.networklibrary.curator.consolidating;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Logger;

import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.DynamicLabel;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.graphdb.Transaction;
import org.neo4j.tooling.GlobalGraphOperations;
import org.networklibrary.core.config.Dictionary;
import org.networklibrary.curator.Task;

public class MirTargetingConsolidator implements Task {

	protected static final Logger log = Logger.getLogger(MirTargetingConsolidator.class.getName());

	protected GraphDatabaseService g = null;

	protected Set<String> edgeTypes = new HashSet<String>();
	protected Set<String> mirLabels = new HashSet<String>();
	protected String name = "cons_mir_targeting";

	private Double normfactor = null;
	private String weightName = "weight";

	private Dictionary dict;

	@Override
	public void setGraph(GraphDatabaseService g) {
		this.g = g;
	}

	@Override
	public void execute() {

		Set<RelationshipType> relTypes = new HashSet<RelationshipType>();
		Set<Node> miRs = new HashSet<Node>();

		//		try (Transaction tx = g.beginTx()){
		//			for(Node n : GlobalGraphOperations.at(g).getAllNodes()){
		//				StringBuilder b = new StringBuilder();
		//				b.append(n.getId() + " " + n.getProperty("name","unknown"));
		//				for(Label l : n.getLabels()){
		//					b.append(" " + l.name());
		//				}
		//				System.out.println(b.toString());
		//			}
		//		}

		try (Transaction tx = g.beginTx()) {
			for(RelationshipType relType : GlobalGraphOperations.at(g).getAllRelationshipTypes()) {
				// the valid relationship that are actually in the graph
				if(edgeTypes.contains(relType.name())){
					relTypes.add(relType);
				}
			}

			for(String labelName : mirLabels){

				ResourceIterator<Node> it = g.findNodes(DynamicLabel.label(labelName));
				while(it.hasNext()){
					miRs.add(it.next());
				}

			}
			tx.success();
		}

		int newRels = 0;

		for(Node miR : miRs){

			try (Transaction tx = g.beginTx()){
				Map<Node,List<Relationship>> neighbours = new HashMap<Node,List<Relationship>>();

				for(Relationship rel : miR.getRelationships(Direction.OUTGOING, relTypes.toArray(new RelationshipType[relTypes.size()])) ){
					addNeighbour(miR,neighbours,rel);
				}

				for(Entry<Node,List<Relationship>> e : neighbours.entrySet()){

					Relationship cons = miR.createRelationshipTo(e.getKey(), DynamicRelationshipType.withName(name));

					cons.setProperty("data_source", "miRTargetingConsolidator");

//					int numRels = e.getValue().size();

					double weight = calcWeight(e);

					cons.setProperty(getWeightName(), weight);
					cons.setProperty("dbs", getDbName(e.getValue()));
					++newRels;
				}
				tx.success();
			}
		}
		log.info("created " + newRels + " new Relationships");
	}

	private double calcWeight(Entry<Node, List<Relationship>> e) {
		String[] dbs = getDbName(e.getValue());

		double weight = dbs.length;

		if(normfactor != null && normfactor > 0.0){
			weight = weight / normfactor;
		}

		return weight;
	}

	private String[] getDbName(List<Relationship> rels) {

		Set<String> res = new HashSet<String>();

		for(Relationship r : rels){
			if(r.hasProperty("data_source")){
				res.add((String)r.getProperty("data_source"));
			} else {
				res.add(r.getType().name());
			}
		}

		return res.toArray(new String[res.size()]);
	}

	private void addNeighbour(Node you,Map<Node, List<Relationship>> neighbours, Relationship rel) {

		Node other = rel.getOtherNode(you);
		if(!neighbours.containsKey(other)){
			neighbours.put(other, new ArrayList<Relationship>());
		}
		neighbours.get(other).add(rel);
	}

	@Override
	public void setExtraParameters(List<String> extras) {
		log.info("processing extra parameters: " + extras.toString());

		for(String extra : extras){
			String values[] = extra.split("=",-1);

			switch(values[0]) {
			case "edgeType":
				edgeTypes.add(values[1]);
				break;

			case "mirlabel":
				mirLabels.add(values[1]);
				break;

			case "name":
				name = values[1];
				break;

			case "normfactor":
				normfactor = Double.valueOf(values[1]);
				break;

			case "weightname":
				weightName = values[1];
				break;
			}

		}

		log.info("using edgeTypes: " + edgeTypes);
		log.info("using miR Labels: " + mirLabels);
		log.info("using name: " + name);
		log.info("using normfactor: " + normfactor);
		log.info("using weightname: " + weightName);
		//		log.info("using a header: " + header);

	}

	@Override
	public void setDictionary(Dictionary dict) {
		this.dict = dict;
	}

	public String getWeightName(){
		return weightName;
	}

}


text:
Example using Windows
```
mkdir build
cd build
cmake -A x64 ..
cmake --build . --config Release
cd ..
```


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>CONSULCON2018 Madrid | 23rd - 24th November</title>
    <meta name="description" content="CONSULCON2018 Madrid | 23rd - 24th November">

    <link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">
    <link href="https://fonts.googleapis.com/css?family=Karla:400,700" rel="stylesheet">
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
    <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
    <link rel="alternate" type="application/rss+xml" title="{{ site.data.i18n[page.locale].title }}" href="{{ "/feed.xml" | prepend: site.baseurl | prepend: site.url }}">

        {{ content }}

            {{ site.data.i18n[page.locale].footer.madrid }} {{ 'now' | date: "%Y" }}.


text:
/*
 * PLUGIN MEDIAINFO
 *
 * French language file.
 *
 * Author: Nicobubulle (nicobubulle@gmail.com)
 */

 theUILang.mediainfo		= "Media info";


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
 *
 * 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.
 */

package org.flowable.engine.test.api.repository;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.flowable.engine.common.api.FlowableException;
import org.flowable.engine.common.api.FlowableIllegalArgumentException;
import org.flowable.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.flowable.engine.impl.test.PluggableFlowableTestCase;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;

/**
 * @author Joram Barrez
 */
public class ProcessDefinitionQueryTest extends PluggableFlowableTestCase {

    private String deploymentOneId;
    private String deploymentTwoId;

    @Override
    protected void setUp() throws Exception {
        deploymentOneId = repositoryService.createDeployment().name("org/flowable/engine/test/repository/one.bpmn20.xml").addClasspathResource("org/flowable/engine/test/repository/one.bpmn20.xml")
                .addClasspathResource("org/flowable/engine/test/repository/two.bpmn20.xml").deploy().getId();

        deploymentTwoId = repositoryService.createDeployment().name("org/flowable/engine/test/repository/one.bpmn20.xml").addClasspathResource("org/flowable/engine/test/repository/one.bpmn20.xml")
                .deploy().getId();

        super.setUp();
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
        repositoryService.deleteDeployment(deploymentOneId, true);
        repositoryService.deleteDeployment(deploymentTwoId, true);
    }

    public void testProcessDefinitionProperties() {
        List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionName().asc().orderByProcessDefinitionVersion().asc()
                .orderByProcessDefinitionCategory().asc().list();

        ProcessDefinition processDefinition = processDefinitions.get(0);
        assertEquals("one", processDefinition.getKey());
        assertEquals("One", processDefinition.getName());
        assertTrue(processDefinition.getId().startsWith("one:1"));
        assertEquals("Examples", processDefinition.getCategory());

        processDefinition = processDefinitions.get(1);
        assertEquals("one", processDefinition.getKey());
        assertEquals("One", processDefinition.getName());
        assertTrue(processDefinition.getId().startsWith("one:2"));
        assertEquals("Examples", processDefinition.getCategory());

        processDefinition = processDefinitions.get(2);
        assertEquals("two", processDefinition.getKey());
        assertEquals("Two", processDefinition.getName());
        assertTrue(processDefinition.getId().startsWith("two:1"));
        assertEquals("Examples2", processDefinition.getCategory());
    }

    public void testQueryByDeploymentId() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentOneId);
        verifyQueryResults(query, 2);
    }

    public void testQueryByInvalidDeploymentId() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().deploymentId("invalid");
        verifyQueryResults(query, 0);

        try {
            repositoryService.createProcessDefinitionQuery().deploymentId(null);
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQueryByName() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionName("Two");
        verifyQueryResults(query, 1);

        query = repositoryService.createProcessDefinitionQuery().processDefinitionName("One");
        verifyQueryResults(query, 2);
    }

    public void testQueryByInvalidName() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionName("invalid");
        verifyQueryResults(query, 0);

        try {
            repositoryService.createProcessDefinitionQuery().processDefinitionName(null);
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQueryByNameLike() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionNameLike("%w%");
        verifyQueryResults(query, 1);
    }

    public void testQueryByInvalidNameLike() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionNameLike("%invalid%");
        verifyQueryResults(query, 0);
    }

    public void testQueryByKey() {
        // process one
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionKey("one");
        verifyQueryResults(query, 2);

        // process two
        query = repositoryService.createProcessDefinitionQuery().processDefinitionKey("two");
        verifyQueryResults(query, 1);
    }

    public void testQueryByInvalidKey() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionKey("invalid");
        verifyQueryResults(query, 0);

        try {
            repositoryService.createProcessDefinitionQuery().processDefinitionKey(null);
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQueryByKeyLike() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionKeyLike("%o%");
        verifyQueryResults(query, 3);
    }

    public void testQueryByInvalidKeyLike() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionKeyLike("%invalid%");
        verifyQueryResults(query, 0);

        try {
            repositoryService.createProcessDefinitionQuery().processDefinitionKeyLike(null);
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQueryByCategory() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionCategory("Examples");
        verifyQueryResults(query, 2);
    }

    public void testQueryByCategoryLike() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionCategoryLike("%Example%");
        verifyQueryResults(query, 3);

        query = repositoryService.createProcessDefinitionQuery().processDefinitionCategoryLike("%amples2");
        verifyQueryResults(query, 1);
    }

    public void testQueryByVersion() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionVersion(2);
        verifyQueryResults(query, 1);

        query = repositoryService.createProcessDefinitionQuery().processDefinitionVersion(1);
        verifyQueryResults(query, 2);
    }

    public void testQueryByInvalidVersion() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionVersion(3);
        verifyQueryResults(query, 0);

        try {
            repositoryService.createProcessDefinitionQuery().processDefinitionVersion(-1).list();
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }

        try {
            repositoryService.createProcessDefinitionQuery().processDefinitionVersion(null).list();
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQueryByKeyAndVersion() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionKey("one").processDefinitionVersion(1);
        verifyQueryResults(query, 1);

        query = repositoryService.createProcessDefinitionQuery().processDefinitionKey("one").processDefinitionVersion(2);
        verifyQueryResults(query, 1);

        query = repositoryService.createProcessDefinitionQuery().processDefinitionKey("one").processDefinitionVersion(3);
        verifyQueryResults(query, 0);
    }

    public void testQueryByLatest() {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().latestVersion();
        verifyQueryResults(query, 2);

        query = repositoryService.createProcessDefinitionQuery().processDefinitionKey("one").latestVersion();
        verifyQueryResults(query, 1);

        query = repositoryService.createProcessDefinitionQuery().processDefinitionKey("two").latestVersion();
        verifyQueryResults(query, 1);
    }

    public void testQuerySorting() {

        // asc

        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionId().asc();
        verifyQueryResults(query, 3);

        query = repositoryService.createProcessDefinitionQuery().orderByDeploymentId().asc();
        verifyQueryResults(query, 3);

        query = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionKey().asc();
        verifyQueryResults(query, 3);

        query = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionVersion().asc();
        verifyQueryResults(query, 3);

        // desc

        query = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionId().desc();
        verifyQueryResults(query, 3);

        query = repositoryService.createProcessDefinitionQuery().orderByDeploymentId().desc();
        verifyQueryResults(query, 3);

        query = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionKey().desc();
        verifyQueryResults(query, 3);

        query = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionVersion().desc();
        verifyQueryResults(query, 3);

        // Typical use case
        query = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionKey().asc().orderByProcessDefinitionVersion().desc();
        List<ProcessDefinition> processDefinitions = query.list();
        assertEquals(3, processDefinitions.size());

        assertEquals("one", processDefinitions.get(0).getKey());
        assertEquals(2, processDefinitions.get(0).getVersion());
        assertEquals("one", processDefinitions.get(1).getKey());
        assertEquals(1, processDefinitions.get(1).getVersion());
        assertEquals("two", processDefinitions.get(2).getKey());
        assertEquals(1, processDefinitions.get(2).getVersion());
    }

    private void verifyQueryResults(ProcessDefinitionQuery query, int countExpected) {
        assertEquals(countExpected, query.list().size());
        assertEquals(countExpected, query.count());

        if (countExpected == 1) {
            assertNotNull(query.singleResult());
        } else if (countExpected > 1) {
            verifySingleResultFails(query);
        } else if (countExpected == 0) {
            assertNull(query.singleResult());
        }
    }

    private void verifySingleResultFails(ProcessDefinitionQuery query) {
        try {
            query.singleResult();
            fail();
        } catch (FlowableException e) {
        }
    }

    public void testQueryByMessageSubscription() {
        Deployment deployment = repositoryService.createDeployment().addClasspathResource("org/flowable/engine/test/api/repository/processWithNewBookingMessage.bpmn20.xml")
                .addClasspathResource("org/flowable/engine/test/api/repository/processWithNewInvoiceMessage.bpmn20.xml").deploy();

        assertEquals(1, repositoryService.createProcessDefinitionQuery().messageEventSubscriptionName("newInvoiceMessage").count());

        assertEquals(1, repositoryService.createProcessDefinitionQuery().messageEventSubscriptionName("newBookingMessage").count());

        assertEquals(0, repositoryService.createProcessDefinitionQuery().messageEventSubscriptionName("bogus").count());

        repositoryService.deleteDeployment(deployment.getId());
    }

    public void testNativeQuery() {
        assertEquals("ACT_RE_PROCDEF", managementService.getTableName(ProcessDefinition.class));
        assertEquals("ACT_RE_PROCDEF", managementService.getTableName(ProcessDefinitionEntity.class));
        String tableName = managementService.getTableName(ProcessDefinition.class);
        String baseQuerySql = "SELECT * FROM " + tableName;

        assertEquals(3, repositoryService.createNativeProcessDefinitionQuery().sql(baseQuerySql).list().size());

        assertEquals(3, repositoryService.createNativeProcessDefinitionQuery().sql(baseQuerySql + " where KEY_ like #{key}").parameter("key", "%o%").list().size());

        assertEquals(2, repositoryService.createNativeProcessDefinitionQuery().sql(baseQuerySql + " where NAME_ = #{name}").parameter("name", "One").list().size());

        // paging
        assertEquals(2, repositoryService.createNativeProcessDefinitionQuery().sql(baseQuerySql).listPage(0, 2).size());
        assertEquals(2, repositoryService.createNativeProcessDefinitionQuery().sql(baseQuerySql).listPage(1, 3).size());
    }

    public void testQueryByProcessDefinitionIds() {
        List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery().list();
        Set<String> ids = new HashSet<String>();
        for (ProcessDefinition processDefinition : processDefinitions) {
            ids.add(processDefinition.getId());
        }

        List<ProcessDefinition> queryResults = repositoryService.createProcessDefinitionQuery().processDefinitionIds(ids).list();
        assertEquals(queryResults.size(), ids.size());
        for (ProcessDefinition processDefinition : queryResults) {
            assertTrue(ids.contains(processDefinition.getId()));
        }
    }

}


text:
'use strict';

const tmi = require('tmi.js');
const config = require('./config.json');
const COMMANDS = require('./lib/commands.js');
const USERS = require('./lib/users.js');
const CHANNELS = require('./lib/channels.js');
const DISCORD = require('./lib/discord/discordBot.js');
const DB = require('./lib/database.js');

global.db;

var options = {
  options: {
    debug: true
  },
  connection: {
    reconnect: true
  },
  identity: {
    username: config['Twitch Username'],
    password: config['Twitch Oauth']
  },
  channels: ['#talbotextreme']
};

var client = new tmi.client(options);

// Because why not?
console.log(
  '\n'
+ '\n'
+ 'Welcome to... \n'
+ '   _____     _______       _   _____     _                           \n'
+ '  |_   _|   | | ___ \\     | | |  ___|   | |                          \n'
+ '    | | __ _| | |_/ / ___ | |_| |____  _| |_ _ __ ___ _ __ ___   ___ \n'
+ '    | |/ _` | | ___ \\/ _ \\| __|  __\\ \\/ / __| \'__/ _ \\ \'_ ` _ \\ / _ \\\n'
+ '    | | (_| | | |_/ / (_) | |_| |___>  <| |_| | |  __/ | | | | |  __/\n'
+ '    \\_/\\__,_|_\\____/ \\___/ \\__\\____/_/\\_\\\\__|_|  \\___|_| |_| |_|\\___|\n'
+ '\n'
+ '                                            by @Talutha & @slm_shockz \n'
);

(async function() {
  try {

    global.db = await DB.db;
    let db = global.db;

    // These will run one after another, waiting for the previous to finish.
    // await db.tableCreation.createCommandsTable();
    // await db.tableCreation.createUserTable();
    // await db.tableCreation.createChannelSettings();

    // This will run all db creation at the same time then continue when all are
    // finished.
    console.log('Ensuring Correct Tables Exist...');

    await Promise.all([
      db.tableCreation.createCommandsTable(),
      db.tableCreation.createUserTable(),
      db.tableCreation.createChannelSettings(),
      db.tableCreation.createDiscordAnnouncersTable()
    ]);

    let newDB = await db.reload();
    db = newDB;
    console.log('All Tables Verified.');

    // Connect the client to the server..
    if (config['Enable Twitch Bot']) {
      client.connect();
    }

  } catch (err) {
    console.log('Something has gone horribly wrong with database creation.');
    console.log(err);
  }
})();

client.on('connected', function (address, port) {
  console.log('Address: ' + address + ':' + port);
  CHANNELS.joinChannels(db, client);
  // USERS.getUserList(db);
});

/*
client.on('connected', function (address, port) {
  client.say('#talbotextreme', 'Hello world, I am back...')
});
*/

// Process every chat message sent
client.on('chat', async function (channel, userstate, message, self) {
  // Don't listen to my own messages...
  if (self) return;

  // always update users on chat
  USERS.addUserToDB(db, channel, userstate);

  // If message starts with '!' process it as a command
  if (message.charAt(0) === '!') {
    COMMANDS.processCommand(db, client, channel, userstate, message);
  }
});

if (config['Enable Discord Bot']) {
  DISCORD.setUpDiscordClient();
}


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
Acta Phytotax. Sin. 6:113. 1957

#### Original name
null

### Remarks
null


text:
package org.apereo.cas.configuration.model.support.couchbase;

import lombok.extern.slf4j.Slf4j;
import org.apereo.cas.configuration.support.RequiredProperty;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;

/**
 * This is {@link BaseCouchbaseProperties}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
@Slf4j
@Getter
@Setter
public abstract class BaseCouchbaseProperties implements Serializable {

    private static final long serialVersionUID = 6550895842866988551L;

    /**
     * Flag to indicate if query is enabled.
     */
    private boolean queryEnabled = true;

    /**
     * Nodeset name.
     */
    @RequiredProperty
    private String nodeSet = "localhost:8091";

    /**
     * String representation of connection timeout.
     */
    private String timeout = "PT10S";

    /**
     * Password.
     */
    @RequiredProperty
    private String password;

    /**
     * Bucket name.
     */
    @RequiredProperty
    private String bucket = "default";
}


text:
import {Component, Input, Output, EventEmitter, ElementRef, OnChanges, ChangeDetectionStrategy, NgZone, ChangeDetectorRef, SimpleChanges, ViewEncapsulation} from '@angular/core';
import {UrlId} from '../../utils/id.helper';
import {IDomain} from '../common.interface';
import {ViewDimensions} from '../../utils/view-dimensions.helper';
import {toDate} from '../../utils/date.helper';
import {PlatformService} from '../../../../services/platform.service';
import {select, selection} from 'd3-selection';
import {scaleTime, scaleLinear, scalePoint} from 'd3-scale';
import {brushX} from 'd3-brush';
import {IScaleType} from '../../chart.interface';

@Component({
	selector: 'g[ngx-charts-timeline]',
	template: `
		<svg:g class="timeline" [attr.transform]="transform">
			<svg:filter [attr.id]="filterId.id">
				<svg:feColorMatrix in="SourceGraphic" type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0"/>
			</svg:filter>
			<svg:g class="embedded-chart">
				<ng-content></ng-content>
			</svg:g>
			<svg:rect x="0" y="0" class="brush-background" [attr.width]="view[0]" [attr.height]="height"/>
			<svg:g class="brush"></svg:g>
		</svg:g>`,
	changeDetection: ChangeDetectionStrategy.OnPush,
	styleUrls: ['timeline.component.scss'],
	encapsulation: ViewEncapsulation.None
})
export class TimelineComponent implements OnChanges {

	@Input() view;
	@Input() results;
	@Input() scheme;
	@Input() legend;
	// @Input() miniChart;
	// @Input() autoScale;
	@Input() scaleType: IScaleType;
	@Input() height = 50;

	@Output() select = new EventEmitter();
	@Output() onDomainChange = new EventEmitter();

	element: HTMLElement;
	dims: ViewDimensions;
	xDomain: IDomain;
	xScale;
	brush: any;
	transform: string;
	initialized = false;
	filterId = new UrlId();

	constructor(element: ElementRef, private zone: NgZone, private cd: ChangeDetectorRef, private platform: PlatformService) {
		this.element = element.nativeElement;
	}

	ngOnChanges(changes: SimpleChanges): void {
		this.update();

		if (!this.initialized) {
			this.addBrush();
			this.initialized = true;
		}
	}

	update(): void {
		this.zone.run(() => {
			this.dims = this.getDims();
			this.height = this.dims.height;
			let offsetY = this.view[1] - this.height;

			this.xDomain = this.getXDomain();
			this.xScale = this.getXScale();

			if (this.brush) {
				this.updateBrush();
			}

			this.transform = `translate(0 , ${ offsetY })`;

			this.filterId.generate('filter', this.platform.isBrowser);

			this.cd.markForCheck();
		});
	}

	getXDomain(): IDomain {
		let values = [];

		for (let results of this.results) {
			for (let d of results.series) {
				if (values.indexOf(d.name) < 0) {
					values.push(d.name);
				}
			}
		}

		let domain = [];
		if (this.scaleType === IScaleType.Time) {
			values = values.map(v => toDate(v));
			let min = Math.min(...values);
			let max = Math.max(...values);
			domain = [min, max];
		} else if (this.scaleType === IScaleType.Linear) {
			values = values.map(v => Number(v));
			let min = Math.min(...values);
			let max = Math.max(...values);
			domain = [min, max];
		} else if (this.scaleType === IScaleType.Ordinal) {
			domain = values;
		}

		return domain;
	}

	getXScale() {
		let scale;
		let domain = this.xDomain.map(d => {
			return <number>d;
		});
		if (this.scaleType === IScaleType.Time) {
			scale = scaleTime()
				.range([0, this.dims.width])
				.domain(domain);
		} else if (this.scaleType === IScaleType.Linear) {
			scale = scaleLinear()
				.range([0, this.dims.width])
				.domain(domain);
		} else if (this.scaleType === IScaleType.Ordinal) {
			scale = scalePoint<number>()
				.range([0, this.dims.width])
				.padding(0.1)
				.domain(domain);
		}
		return scale;
	}

	addBrush(): void {
		if (this.brush) {
			return;
		}

		const height = this.height;
		const width = this.view[0];

		this.brush = brushX()
			.extent([[0, 0], [width, height]])
			.on('brush end', () => {
				this.zone.run(() => {
					const sel = /*selection.event.selection ||*/ this.xScale.range();
					const newDomain = sel.map(this.xScale.invert);

					this.onDomainChange.emit(newDomain);
					this.cd.markForCheck();
				});
			});

		select(this.element)
			.select('.brush')
			.call(this.brush);
	}

	updateBrush(): void {
		if (!this.brush) {
			return;
		}

		const height = this.height;
		const width = this.view[0];

		this.zone.run(() => {
			this.brush.extent([[0, 0], [width, height]]);
			select(this.element)
				.select('.brush')
				.call(this.brush);

			// clear hardcoded properties so they can be defined by CSS
			select(this.element).select('.selection')
				.attr('fill', undefined)
				.attr('stroke', undefined)
				.attr('fill-opacity', undefined);

			this.cd.markForCheck();
		});
	}

	getDims(): ViewDimensions {
		return {
			width: this.view[0],
			height: this.height,
			xOffset: 0
		};
	}

}


text:
/* @file
 * Interface for devices using PCI configuration
 */

#ifndef __DEV_PCIDEV_HH__
#define __DEV_PCIDEV_HH__

#include <cstring>

#include "dev/io_device.hh"
#include "dev/pcireg.h"
#include "dev/platform.hh"
#include "params/PciDevice.hh"
#include "sim/byteswap.hh"

#define BAR_IO_MASK 0x3
#define BAR_MEM_MASK 0xF
#define BAR_IO_SPACE_BIT 0x1
#define BAR_IO_SPACE(x) ((x) & BAR_IO_SPACE_BIT)
#define BAR_NUMBER(x) (((x) - PCI0_BASE_ADDR0) >> 0x2);

/**
 * PCI device, base implementation is only config space.
 */
class PciDev : public DmaDevice
{
    class PciConfigPort : public SimpleTimingPort
    {
      protected:
        PciDev *device;

        virtual Tick recvAtomic(PacketPtr pkt);

        virtual void getDeviceAddressRanges(AddrRangeList &resp,
                                            bool &snoop);

        Platform *platform;

        int busId;
        int deviceId;
        int functionId;

        Addr configAddr;

      public:
        PciConfigPort(PciDev *dev, int busid, int devid, int funcid,
                      Platform *p);
    };

  public:
    typedef PciDeviceParams Params;
    const Params *
    params() const
    {
        return dynamic_cast<const Params *>(_params);
    }

  protected:
    /** The current config space.  */
    PCIConfig config;

    /** The size of the BARs */
    uint32_t BARSize[6];

    /** The current address mapping of the BARs */
    Addr BARAddrs[6];

    /** Whether the BARs are really hardwired legacy IO locations. */
    bool legacyIO[6];

    /**
     * Does the given address lie within the space mapped by the given
     * base address register?
     */
    bool
    isBAR(Addr addr, int bar) const
    {
        assert(bar >= 0 && bar < 6);
        return BARAddrs[bar] <= addr && addr < BARAddrs[bar] + BARSize[bar];
    }

    /**
     * Which base address register (if any) maps the given address?
     * @return The BAR number (0-5 inclusive), or -1 if none.
     */
    int
    getBAR(Addr addr)
    {
        for (int i = 0; i <= 5; ++i)
            if (isBAR(addr, i))
                return i;

        return -1;
    }

    /**
     * Which base address register (if any) maps the given address?
     * @param addr The address to check.
     * @retval bar The BAR number (0-5 inclusive),
     *             only valid if return value is true.
     * @retval offs The offset from the base address,
     *              only valid if return value is true.
     * @return True iff address maps to a base address register's region.
     */
    bool
    getBAR(Addr addr, int &bar, Addr &offs)
    {
        int b = getBAR(addr);
        if (b < 0)
            return false;

        offs = addr - BARAddrs[b];
        bar = b;
        return true;
    }

  protected:
    Platform *plat;
    Tick pioDelay;
    Tick configDelay;
    PciConfigPort *configPort;

    /**
     * Write to the PCI config space data that is stored locally. This may be
     * overridden by the device but at some point it will eventually call this
     * for normal operations that it does not need to override.
     * @param pkt packet containing the write the offset into config space
     */
    virtual Tick writeConfig(PacketPtr pkt);

    /**
     * Read from the PCI config space data that is stored locally. This may be
     * overridden by the device but at some point it will eventually call this
     * for normal operations that it does not need to override.
     * @param pkt packet containing the write the offset into config space
     */
    virtual Tick readConfig(PacketPtr pkt);

  public:
    Addr pciToDma(Addr pciAddr) const
    { return plat->pciToDma(pciAddr); }

    void
    intrPost()
    { plat->postPciInt(letoh(config.interruptLine)); }

    void
    intrClear()
    { plat->clearPciInt(letoh(config.interruptLine)); }

    uint8_t
    interruptLine()
    { return letoh(config.interruptLine); }

    /** return the address ranges that this device responds to.
     * @params range_list range list to populate with ranges
     */
    void addressRanges(AddrRangeList &range_list);

    /**
     * Constructor for PCI Dev. This function copies data from the
     * config file object PCIConfigData and registers the device with
     * a PciConfigAll object.
     */
    PciDev(const Params *params);

    virtual void init();

    /**
     * Serialize this object to the given output stream.
     * @param os The stream to serialize to.
     */
    virtual void serialize(std::ostream &os);

    /**
     * Reconstruct the state of this object from a checkpoint.
     * @param cp The checkpoint use.
     * @param section The section name of this object
     */
    virtual void unserialize(Checkpoint *cp, const std::string &section);

    virtual unsigned int drain(Event *de);

    virtual Port *getPort(const std::string &if_name, int idx = -1)
    {
        if (if_name == "config") {
            if (configPort != NULL)
                panic("pciconfig port already connected to.");
            configPort = new PciConfigPort(this, params()->pci_bus,
                    params()->pci_dev, params()->pci_func,
                    params()->platform);
            return configPort;
        }
        return DmaDevice::getPort(if_name, idx);
    }

};
#endif // __DEV_PCIDEV_HH__


text:
rootDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && pwd )"

lernaVersionArg="$1"
if [[ -z $lernaVersionArg ]]; then
  echo '[ERROR] Please provide argument for "lerna version".'
  exit 1
fi

currentNpm=$(npm --version)
npmVersion=$(node -e "process.stdout.write(require('./package.json').engines.npm)");
isSatisfiedNpm=$(node -e "process.stdout.write(require('semver').satisfies('$currentNpm', '$npmVersion').toString())");

currentNode=$(node --version)
nodeVersion=$(node -e "process.stdout.write(require('./package.json').engines.node)");
isSatisfiedNode=$(node -e "process.stdout.write(require('semver').satisfies('$currentNode', '$nodeVersion').toString())");

# Check node version compatible with package.json
if [[ $isSatisfiedNode != 'true' ]]; then
  echo "[ERROR] Your node version($currentNode) is not compatible with package.json($nodeVersion)"
  exit 1
fi

# Check npm version compatible with package.json
if [[ $isSatisfiedNpm != 'true' ]]; then
  echo "[ERROR] Your npm version($currentNpm) is not compatible with package.json($npmVersion)"
  exit 1
fi

# Ignore Lerna's tag and push
lerna version $1 --no-push --no-git-tag-version --yes

if [[ -z $(git diff --stat) ]]; then
  echo '[ERROR] No changed packages to version.'
  exit 1
fi

# Get the current tag version
tag=v$(node -e "process.stdout.write(require('./lerna.json').version)");
message="chore(plugins): publish $tag"

if [[ $? -ne 0 ]]; then
  echo '[ERROR] Can not update package-lock.json'
  exit 1
fi

# Auto-tag and auto-commit like usual
git commit --all -m "${message}"
git tag -a ${tag} -m ${tag}
git push origin ${tag}
git push


text:
package org.springframework.context.support;

import java.text.MessageFormat;
import java.util.Locale;
import org.apache.commons.logging.Log;

abstract public class MessageSourceSupport
{
    protected MessageFormat createMessageFormat(String p0, Locale p1){ return null; }
    protected Object[] resolveArguments(Object[] p0, Locale p1){ return null; }
    protected String formatMessage(String p0, Object[] p1, Locale p2){ return null; }
    protected String renderDefaultMessage(String p0, Object[] p1, Locale p2){ return null; }
    protected boolean isAlwaysUseMessageFormat(){ return false; }
    protected final Log logger = null;
    public MessageSourceSupport(){}
    public void setAlwaysUseMessageFormat(boolean p0){}
}


text:
package org.codeforcoffee.exoplanetarchive;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.List;

public class NotesScrollingActivity extends AppCompatActivity {

    private ListView mListView;
    private Notes mNotes;
    private ArrayAdapter<Notes> mAdapter;

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

        setContentView(R.layout.activity_notes_scrolling);

        mListView = (ListView) findViewById(R.id.notes_list_view);
        mNotes = Notes.getInstance();
        mAdapter = new ArrayAdapter<Notes>(this, android.R.layout.simple_list_item_1);
        mAdapter.addAll(mNotes);
        mListView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mNotes.clear();
                mAdapter.notifyDataSetChanged();
                Snackbar.make(view, R.string.snackbar_notes_delete, Snackbar.LENGTH_SHORT)
                        .setAction("Action", null).show();
            }
        });
    }
}


text:
package com.example.notes;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;

import org.springframework.hateoas.ResourceSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/")
public class IndexController {

	@RequestMapping(method=RequestMethod.GET)
	public ResourceSupport index() {
		ResourceSupport index = new ResourceSupport();
		index.add(linkTo(NotesController.class).withRel("notes"));
		index.add(linkTo(TagsController.class).withRel("tags"));
		return index;
	}

}


text:
package org.apache.activemq.apollo;

import junit.framework.Test;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class ProducerFlowControlSendFailTest extends ProducerFlowControlTest {

    public static Test suite() {
        return suite(ProducerFlowControlSendFailTest.class);
    }

    public static void main(String[] args) {
        junit.textui.TestRunner.run(suite());
    }

//    protected BrokerService createBroker() throws Exception {
//        BrokerService service = new BrokerService();
//        service.setPersistent(false);
//        service.setUseJmx(false);
//
//        // Setup a destination policy where it takes only 1 message at a time.
//        PolicyMap policyMap = new PolicyMap();
//        PolicyEntry policy = new PolicyEntry();
//        policy.setMemoryLimit(1);
//        policy.setPendingSubscriberPolicy(new VMPendingSubscriberMessageStoragePolicy());
//        policy.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy());
//        policy.setProducerFlowControl(true);
//        policyMap.setDefaultEntry(policy);
//        service.setDestinationPolicy(policyMap);
//
//        service.getSystemUsage().setSendFailIfNoSpace(true);
//
//        connector = service.addConnector("tcp://localhost:0");
//        return service;
//    }

    @Override
    public void test2ndPubisherWithStandardConnectionThatIsBlocked() throws Exception {
        // with sendFailIfNoSpace set, there is no blocking of the connection
    }

    @Override // re-enable once https://issues.apache.org/jira/browse/APLO-225 is fixed
    public void ignoreAsyncPubisherRecoverAfterBlock() throws Exception {
        // sendFail means no flowControllwindow as there is no producer ack, just an exception
    }

    @Override // re-enable once https://issues.apache.org/jira/browse/APLO-225 is fixed
    public void ignorePubisherRecoverAfterBlock() throws Exception {
        ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory)createConnectionFactory();
        // with sendFail, there must be no flowControllwindow
        // sendFail is an alternative flow control mechanism that does not block
        factory.setUseAsyncSend(true);
        connection = (ActiveMQConnection)factory.createConnection();
        connections.add(connection);
        connection.start();

        final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        final MessageProducer producer = session.createProducer(queueA);

        final AtomicBoolean keepGoing = new AtomicBoolean(true);

        Thread thread = new Thread("Filler") {
            @Override
            public void run() {
                while (keepGoing.get()) {
                    try {
                        producer.send(session.createTextMessage("Test message"));
                        if (gotResourceException.get()) {
                            // do not flood the broker with requests when full as we are sending async and they
                            // will be limited by the network buffers
                            Thread.sleep(200);
                        }
                    } catch (Exception e) {
                        // with async send, there will be no exceptions
                        e.printStackTrace();
                    }
                }
            }
        };
        thread.start();
        waitForBlockedOrResourceLimit(new AtomicBoolean(false));

        // resourceException on second message, resumption if we
        // can receive 10
        MessageConsumer consumer = session.createConsumer(queueA);
        TextMessage msg;
        for (int idx = 0; idx < 10; ++idx) {
            msg = (TextMessage) consumer.receive(1000);
            if (msg != null) {
                msg.acknowledge();
            }
        }
        keepGoing.set(false);
    }

    // re-enable once https://issues.apache.org/jira/browse/APLO-225 is fixed
    public void ignorePubisherRecoverAfterBlockWithSyncSend() throws Exception {
        ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory)createConnectionFactory();
        factory.setExceptionListener(null);
        factory.setUseAsyncSend(false);
        connection = (ActiveMQConnection)factory.createConnection();
        connections.add(connection);
        connection.start();

        final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        final MessageProducer producer = session.createProducer(queueA);

        final AtomicBoolean keepGoing = new AtomicBoolean(true);
        final AtomicInteger exceptionCount = new AtomicInteger(0);
        Thread thread = new Thread("Filler") {
            @Override
            public void run() {
                while (keepGoing.get()) {
                    try {
                        producer.send(session.createTextMessage("Test message"));
                    } catch (JMSException arg0) {
                        if (arg0 instanceof ResourceAllocationException) {
                            gotResourceException.set(true);
                            exceptionCount.incrementAndGet();
                        }
                    }
                }
            }
        };
        thread.start();
        waitForBlockedOrResourceLimit(new AtomicBoolean(false));

        // resourceException on second message, resumption if we
        // can receive 10
        MessageConsumer consumer = session.createConsumer(queueA);
        TextMessage msg;
        for (int idx = 0; idx < 10; ++idx) {
            msg = (TextMessage) consumer.receive(1000);
            if (msg != null) {
                msg.acknowledge();
            }
        }
        assertTrue("we were blocked at least 5 times", 5 < exceptionCount.get());
        keepGoing.set(false);
    }

	@Override
	protected ConnectionFactory createConnectionFactory() throws Exception {
		ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) super.createConnectionFactory();
		connectionFactory.setExceptionListener(new ExceptionListener() {
				public void onException(JMSException arg0) {
					if (arg0 instanceof ResourceAllocationException) {
						gotResourceException.set(true);
					}
				}
	        });
		return connectionFactory;
	}
}


text:
namespace AutoPatcherGUI
{
    partial class apgui
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.label2 = new System.Windows.Forms.Label();
            this.button2 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(15, 25);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(416, 89);
            this.button1.TabIndex = 0;
            this.button1.Text = "PATCH";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(12, 9);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(64, 13);
            this.label2.TabIndex = 2;
            this.label2.Text = "autopatcher";
            //
            // button2
            //
            this.button2.Location = new System.Drawing.Point(15, 120);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(416, 76);
            this.button2.TabIndex = 3;
            this.button2.Text = "START";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // apgui
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(440, 208);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.button1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Name = "apgui";
            this.Text = "autopatcher";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button button2;
    }
}


text:
try:
    import json
except ImportError:
    import simplejson as json
import logging
import os
import subprocess

import XenAPIPlugin

import pluginlib_nova as pluginlib
pluginlib.configure_logging("xenstore")

class XenstoreError(pluginlib.PluginError):
    """Errors that occur when calling xenstore-* through subprocesses"""

    def __init__(self, cmd, return_code, stderr, stdout):
        msg = "cmd: %s; returncode: %d; stderr: %s; stdout: %s"
        msg = msg % (cmd, return_code, stderr, stdout)
        self.cmd = cmd
        self.return_code = return_code
        self.stderr = stderr
        self.stdout = stdout
        pluginlib.PluginError.__init__(self, msg)

def jsonify(fnc):
    def wrapper(*args, **kwargs):
        ret = fnc(*args, **kwargs)
        try:
            json.loads(ret)
        except ValueError:
            # Value should already be JSON-encoded, but some operations
            # may write raw sting values; this will catch those and
            # properly encode them.
            ret = json.dumps(ret)
        return ret
    return wrapper

def _record_exists(arg_dict):
    """Returns whether or not the given record exists. The record path
    is determined from the given path and dom_id in the arg_dict."""
    cmd = ["xenstore-exists", "/local/domain/%(dom_id)s/%(path)s" % arg_dict]
    try:
        ret, result = _run_command(cmd)
    except XenstoreError, e:
        if e.stderr == '':
            # if stderr was empty, this just means the path did not exist
            return False
        # otherwise there was a real problem
        raise
    return True

@jsonify
def read_record(self, arg_dict):
    """Returns the value stored at the given path for the given dom_id.
    These must be encoded as key/value pairs in arg_dict. You can
    optinally include a key 'ignore_missing_path'; if this is present
    and boolean True, attempting to read a non-existent path will return
    the string 'None' instead of raising an exception.
    """
    cmd = ["xenstore-read", "/local/domain/%(dom_id)s/%(path)s" % arg_dict]
    try:
        ret, result = _run_command(cmd)
        return result.strip()
    except XenstoreError, e:
        if not arg_dict.get("ignore_missing_path", False):
            raise
        if not _record_exists(arg_dict):
            return "None"
        # Just try again in case the agent write won the race against
        # the record_exists check. If this fails again, it will likely raise
        # an equally meaningful XenstoreError as the one we just caught
        ret, result = _run_command(cmd)
        return result.strip()

@jsonify
def write_record(self, arg_dict):
    """Writes to xenstore at the specified path. If there is information
    already stored in that location, it is overwritten. As in read_record,
    the dom_id and path must be specified in the arg_dict; additionally,
    you must specify a 'value' key, whose value must be a string. Typically,
    you can json-ify more complex values and store the json output.
    """
    cmd = ["xenstore-write",
           "/local/domain/%(dom_id)s/%(path)s" % arg_dict,
           arg_dict["value"]]
    _run_command(cmd)
    return arg_dict["value"]

@jsonify
def list_records(self, arg_dict):
    """Returns all the stored data at or below the given path for the
    given dom_id. The data is returned as a json-ified dict, with the
    path as the key and the stored value as the value. If the path
    doesn't exist, an empty dict is returned.
    """
    dirpath = "/local/domain/%(dom_id)s/%(path)s" % arg_dict
    cmd = ["xenstore-ls", dirpath.rstrip("/")]
    try:
        ret, recs = _run_command(cmd)
    except XenstoreError, e:
        if not _record_exists(arg_dict):
            return {}
        # Just try again in case the path was created in between
        # the "ls" and the existence check. If this fails again, it will
        # likely raise an equally meaningful XenstoreError
        ret, recs = _run_command(cmd)
    base_path = arg_dict["path"]
    paths = _paths_from_ls(recs)
    ret = {}
    for path in paths:
        if base_path:
            arg_dict["path"] = "%s/%s" % (base_path, path)
        else:
            arg_dict["path"] = path
        rec = read_record(self, arg_dict)
        try:
            val = json.loads(rec)
        except ValueError:
            val = rec
        ret[path] = val
    return ret

@jsonify
def delete_record(self, arg_dict):
    """Just like it sounds: it removes the record for the specified
    VM and the specified path from xenstore.
    """
    cmd = ["xenstore-rm", "/local/domain/%(dom_id)s/%(path)s" % arg_dict]
    ret, result = _run_command(cmd)
    return result

def _paths_from_ls(recs):
    """The xenstore-ls command returns a listing that isn't terribly
    useful. This method cleans that up into a dict with each path
    as the key, and the associated string as the value.
    """
    ret = {}
    last_nm = ""
    level = 0
    path = []
    ret = []
    for ln in recs.splitlines():
        nm, val = ln.rstrip().split(" = ")
        barename = nm.lstrip()
        this_level = len(nm) - len(barename)
        if this_level == 0:
            ret.append(barename)
            level = 0
            path = []
        elif this_level == level:
            # child of same parent
            ret.append("%s/%s" % ("/".join(path), barename))
        elif this_level > level:
            path.append(last_nm)
            ret.append("%s/%s" % ("/".join(path), barename))
            level = this_level
        elif this_level < level:
            path = path[:this_level]
            ret.append("%s/%s" % ("/".join(path), barename))
            level = this_level
        last_nm = barename
    return ret

def _run_command(cmd):
    """Abstracts out the basics of issuing system commands. If the command
    returns anything in stderr, a PluginError is raised with that information.
    Otherwise, a tuple of (return code, stdout data) is returned.
    """
    logging.info(' '.join(cmd))
    pipe = subprocess.PIPE
    proc = subprocess.Popen(cmd, stdin=pipe, stdout=pipe, stderr=pipe,
            close_fds=True)
    out, err = proc.communicate()
    if proc.returncode is not os.EX_OK:
        raise XenstoreError(cmd, proc.returncode, err, out)
    return proc.returncode, out

if __name__ == "__main__":
    XenAPIPlugin.dispatch(
        {"read_record": read_record,
        "write_record": write_record,
        "list_records": list_records,
        "delete_record": delete_record})


text:
#import "MSGraphServiceFreeBusyStatus.h"

@implementation MSGraphServiceFreeBusyStatusSerializer

+(MSGraphServiceFreeBusyStatus) fromString:(NSString *) string {

    static NSDictionary *stringMappings=nil;

    if(stringMappings==nil)
    {
        stringMappings=[[NSDictionary alloc] initWithObjectsAndKeys:
         [NSNumber numberWithInt:MSGraphServiceFreeBusyStatusFree], @"free", [NSNumber numberWithInt:MSGraphServiceFreeBusyStatusTentative], @"tentative", [NSNumber numberWithInt:MSGraphServiceFreeBusyStatusBusy], @"busy", [NSNumber numberWithInt:MSGraphServiceFreeBusyStatusOof], @"oof", [NSNumber numberWithInt:MSGraphServiceFreeBusyStatusWorkingElsewhere], @"workingElsewhere", [NSNumber numberWithInt:MSGraphServiceFreeBusyStatusUnknown], @"unknown",
            nil
        ];
    }

    return [stringMappings[string] intValue];

}

+(NSString *) toString: (MSGraphServiceFreeBusyStatus) value {

    static NSDictionary *stringMappings=nil;

    if(stringMappings==nil)
    {
        stringMappings=[[NSDictionary alloc] initWithObjectsAndKeys:
         @"free", [NSNumber numberWithInt:MSGraphServiceFreeBusyStatusFree], @"tentative", [NSNumber numberWithInt:MSGraphServiceFreeBusyStatusTentative], @"busy", [NSNumber numberWithInt:MSGraphServiceFreeBusyStatusBusy], @"oof", [NSNumber numberWithInt:MSGraphServiceFreeBusyStatusOof], @"workingElsewhere", [NSNumber numberWithInt:MSGraphServiceFreeBusyStatusWorkingElsewhere], @"unknown", [NSNumber numberWithInt:MSGraphServiceFreeBusyStatusUnknown],
            nil
        ];
    }

    return stringMappings[[NSNumber numberWithInt:value]];
}

@end


text:
<?php

class Denkmal_Paging_Venue_GeoPoint extends Denkmal_Paging_Venue_Abstract {

    /**
     * @param CM_Geo_Point $point
     * @param int          $distanceMax
     */
    public function __construct(CM_Geo_Point $point, $distanceMax) {
        $lat = $point->getLatitude();
        $lon = $point->getLongitude();
        $earthRadius = 6371009;

        $pi180 = M_PI / 180;
        $metersPerDegreeEquator = $earthRadius * $pi180;
        $metersPerDegree = $metersPerDegreeEquator * cos($lat * $pi180);

        $latMin = $lat - $distanceMax / $metersPerDegreeEquator;
        $latMax = $lat + $distanceMax / $metersPerDegreeEquator;
        $lonMin = $lon - $distanceMax / $metersPerDegree;
        $lonMax = $lon + $distanceMax / $metersPerDegree;

        $where = "MBRContains(LineString(Point($latMax, $lonMax), Point($latMin, $lonMin)), Point(`latitude`, `longitude`))";
        $where .= ' AND `suspended` = 0';
        $order = "((POW($lat - `latitude`, 2)) + (POW($lon - `longitude`, 2))) ASC";
        $source = new CM_PagingSource_Sql('id', 'denkmal_model_venue', $where, $order);
        parent::__construct($source);
    }
}


text:
A simple extension that integrates MediaCrush into Chrome. Right click any image to upload it directly to MediaCrush.

https://mediacru.sh

What's MediaCrush? It's a website designed to host images, videos, and audio as fast as possible. It has all kinds of tricks to speed up hosting without reducing the quality of your files. We also take your privacy very seriously - we'll never store anything about you, and we always use HTTPS.


text:
<Record>
<Term>Epidural Abscess</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Abscess</ParentTerm>
<ParentTerm>Central Nervous System Bacterial Infections</ParentTerm>
<ParentTerm>Perimeningeal Infections</ParentTerm>
<ParentTerm>Central Nervous System Infections</ParentTerm>
<ParentTerm>Spinal Cord Diseases</ParentTerm>
<ClassificationPath>Nervous System Diseases/Central Nervous System Diseases/Central Nervous System Infections/Perimeningeal Infections/Epidural Abscess</ClassificationPath>
<ClassificationPath>Nervous System Diseases/Central Nervous System Diseases/Central Nervous System Infections/Central Nervous System Bacterial Infections/Epidural Abscess</ClassificationPath>
<ClassificationPath>Nervous System Diseases/Central Nervous System Diseases/Spinal Cord Diseases/Epidural Abscess</ClassificationPath>
<ClassificationPath>Bacterial Infections and Mycoses/Infection/Suppuration/Abscess/Epidural Abscess</ClassificationPath>
<ClassificationPath>Bacterial Infections and Mycoses/Bacterial Infections/Central Nervous System Bacterial Infections/Epidural Abscess</ClassificationPath>
<ClassificationPath>Nervous System Diseases/Central Nervous System Diseases/Central Nervous System Infections/Epidural Abscess</ClassificationPath>
<BroaderTerm>Abscess</BroaderTerm>
<BroaderTerm>Infection</BroaderTerm>
<BroaderTerm>Central Nervous System Diseases</BroaderTerm>
<BroaderTerm>Central Nervous System Bacterial Infections</BroaderTerm>
<BroaderTerm>Perimeningeal Infections</BroaderTerm>
<BroaderTerm>Bacterial Infections</BroaderTerm>
<BroaderTerm>Suppuration</BroaderTerm>
<BroaderTerm>Epidural Abscess</BroaderTerm>
<BroaderTerm>Central Nervous System Infections</BroaderTerm>
<BroaderTerm>Nervous System Diseases</BroaderTerm>
<BroaderTerm>Bacterial Infections and Mycoses</BroaderTerm>
<BroaderTerm>Spinal Cord Diseases</BroaderTerm>
<Synonym>Cranial Epidural Abscess</Synonym>
<Synonym>Cranial Extradural Abscess</Synonym>
<Synonym>Intracranial Extradural Abscess</Synonym>
<Synonym>Spinal Extradural Abscess</Synonym>
<Synonym>Intracranial Epidural Abscess</Synonym>
<Synonym>Spinal Epidural Abscess</Synonym>
<Synonym>Extradural Abscess</Synonym>
<Synonym>Epidural Abscess</Synonym>
<Synonym>Intracranial Extradural Abscesses</Synonym>
<Description>Circumscribed collections of suppurative material occurring in the spinal or intracranial EPIDURAL SPACE. The majority of epidural abscesses occur in the spinal canal and are associated with OSTEOMYELITIS of a vertebral body; ANALGESIA, EPIDURAL; and other conditions. Clinical manifestations include local and radicular pain, weakness, sensory loss, URINARY INCONTINENCE, and FECAL INCONTINENCE. Cranial epidural abscesses are usually associated with OSTEOMYELITIS of a cranial bone, SINUSITIS, or OTITIS MEDIA. (From Adams et al., Principles of Neurology, 6th ed, p710 and pp1240-1; J Neurol Neurosurg Psychiatry 1998 Aug;65(2):209-12)</Description>
<Source>MeSH</Source>
</Record>