text:
Actions are a type of function that a Reflux store can listen for. They are similar to dispatching an event in that many stores can listen for a single action, but they are called like a simple function.

### Creating Actions

There are multiple ways to create actions in RefluxJS. The two main functions are `Reflux.createAction` (for making one) and `Reflux.createActions` (for making multiple actions at once).

`Reflux.createAction` takes an optional definition object as an argument and returns the action itself.

`Reflux.createActions` takes an array of definition objects. It returns an object where each created action is a property, and the property name is the action's name.

`Reflux.createActions` also has a shortcut available where you give it an object instead of an array. It builds actions for each object property and names those actions after the property name.

Simple usage for these looks like this:

```javascript
var singleAction = Reflux.createAction();
var ManyActions = Reflux.createActions(['action1', 'action2']);
var MoreActions = Reflux.createActions({anAction:{...}});

singleAction(); // calls the singleAction with no arguments
ManyActions.action1(); // calls one of the actions made within the ManyActions object
MoreActions.anAction(); // calls the action made within the MoreActions object
```

### Action Definitions

Action definitions are passed to the action creation functions (either directly to `createAction` or as an Array of them to `createActions`). As an example, a definition object may take the following format:

```javascript
{
	actionName: 'myActionName', // <- the name of the action
	children: ['childAction'], // <- Array of child action names for async operations
	asyncResult: true, // <- true to make a shortcut to adding 'completed' and 'failed' children
	sync: false, // <- set the action to emit synchronously or asynchronously (sync by default unless there are child actions)
	preEmit: function(){...}, // shortcut for setting preEmit method (covered later)
	shouldEmit: function(){...} // shortcut for setting shouldEmit method (covered later)
}
```

None of these are mandatory. You may create an action using `Reflux.createAction` without even providing a definition at all. And furthermore there are shortcuts for setting `actionName` as well. Some of these shortcuts were shown in the above "Creating Actions" section:

1. With either action creation function just setting a string as a definition is the equivalent of using `{actionName:'myString'}` in that place.
2. With `createActions` you can send an object instead of array and it will make one action for each property given using the property keys as the `actionName` for each definition provided.

Examples of both of these would be:

```javascript
// examples of #1 above
var action = Reflux.createAction('myName');
var Actions = Reflux.createActions(['myName1', 'myName2']);
// both are equivalent to (respectively):
var action = Reflux.createAction({actionName:'myName'});
var Actions = Reflux.createActions([{actionName:'myName1'}, {actionName:'myName2'}]);

// examples of #2 above
var Actions = Reflux.createActions({'myName1':{sync:false}});
// is equivalent to:
var Actions = Reflux.createActions([{actionName:'myName1', sync:false}]);
```

You will find throughout the RefluxJS documentation that the shorthand ways for creating actions with names are extremely common, as they tend to tie in well with other shorthand methods of doing things in Reflux.

### Async vs Sync Actions

As you've read, actions can simply be invoked via `myAction()`. But internally, if the action's `sync` is set to true then the action does `myAction.trigger()` and if not it does `myAction.triggerAsync()` (you may also call these manually). The important difference is that synchronous action calls must emit immediately. Asynchronous actions emit on the next tick of the JS event loop, and may have things such as `children` child actions in their definitions which they can call.

Actions are sync by default unless specifically defined otherwise, or unless the action has child actions within it.

### Asynchronous Loading via Child Actions

You may perform actual asynchronous actions such as file loading via child actions. An action can listen for itself to be called, and then perform an asynchronous task, calling its child action when that task is complete. In simplest form it might look something like this:

```javascript
var action = Reflux.createAction({children:['delayComplete']});

action.listen(function(){
	setTimeout(this.delayComplete, 1000);
});
```

Anywhere listening to that action could then use `this.listenTo(action.delayComplete, onActionDelayComplete)`. And what arguments you send when calling the `delayComplete` child are what get sent through to the callback of the listener. This way you can do things like load files and have the completed action send the contents of the file to whatever is listening.

The most common way in which this is used is to use `createActions` and its shorthand object form while taking advantage of a Reflux store's ability to listen to many actions at once with its `this.listenables` and `this.listenToMany` (see Reflux store documentation). Where the store can be made to automatically have actions call the stores methods named after the action's `actionName` (or the camecased `onActionName`), the child actions can be tacked on to that to read `actionNmeChildAction` or `onActionNmeChildAction`. Here is a full example of that:

```javascript
var Actions = Reflux.createActions({
	'load': {children: ['completed', 'failed']}
});

Actions.load.listen( function() {
    someAsyncOperation()
        .then( this.completed )
        .catch( this.failed );
});

class MyStore extends Reflux.Store
{
	constructor()
	{
		this.listenables = Actions;
		// or
		this.listenToMany(Actions);
	}

	onLoadCompleted(data)
	{
		// use the data here
	}

	onLoadFailed(message)
	{
		// failed, with whatever message you sent
	}
}
```

### Listening

The main way in which one listens to actions in Reflux is by using functionality attached to [Reflux Stores](../stores/) such as `this.listenables` and `this.listenTo` within the store. However, it is important to note that one can listen directly to an action or child action as well:

```javascript
// listen directly to an action
myActions.actionName.listen(myCallbackFunc);

// listen to a child action
myActions.load.completed.listen(myCallbackFunc);
```

### Removing Listeners

Any time listening happens in Reflux it returns an unsubscribe function. Simply call that function to unsubscribe:

```javascript
var unsubscribe = myActions.actionName.listen(myCallbackFunc);

// later...
unsubscribe(); // no longer listening
```

### Action Hooks

There are a couple of hooks available for each action.

* `preEmit` - Is called before the action emits an event. It receives the arguments from the action invocation. If it returns something other than undefined, that will be used as arguments for `shouldEmit` and subsequent emission.

* `shouldEmit` - Is called after `preEmit` and before the action emits an event. By default it returns `true` which will let the action emit the event. You may override this if you need to check the arguments that the action receives and see if it needs to emit the event.

Example usage:

```javascript
Actions.statusUpdate.preEmit = function() { console.log(arguments); };
Actions.statusUpdate.shouldEmit = function(value) {
    return value > 0;
};

Actions.statusUpdate(0);
Actions.statusUpdate(1);
// Should output: 1
```

You can also set the hooks by sending them in a definition object as you create the action:

```javascript
var action = Reflux.createAction({
    preEmit: function(){...},
    shouldEmit: function(){...}
});
```

### Reflux.ActionMethods

If you would like to have a common set of methods available to all actions you can extend the `Reflux.ActionMethods` object, which is mixed into the actions when they are created.

Example usage:

```javascript
Reflux.ActionMethods.exampleMethod = function() { console.log(arguments); };

Actions.statusUpdate.exampleMethod('arg1');
// Should output: 'arg1'
```

### Next:

Next learn about [Reflux Stores](../stores/).


text:
package com.tomgibara.fundament;

import static java.lang.Integer.parseInt;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Assert;
import org.junit.Test;

public class BijectionTest {

	final Bijection<String, Integer> f = new Bijection<String, Integer>() {
		@Override public Class<Integer> rangeType() { return Integer.class; }
		@Override public Class<String> domainType() { return String.class;  }
		@Override public Integer apply(String t)    { return parseInt(t);   }
		@Override public String disapply(Integer r) { return r.toString();  }
		@Override public boolean isInDomain(Object obj) {
			if (!(obj instanceof String)) return false;
			String str = (String) obj;
			return str.matches("0|(:?[1-9][0-9]*)");
		}
		@Override
		public boolean isInRange(Object obj) {
			if (!(obj instanceof Integer)) return false;
			int i = (Integer) obj;
			return i >= 0;
		}
	};

	final Bijection<Integer, Integer> g = new Bijection<Integer, Integer>() {
		@Override public Class<Integer> rangeType()  { return Integer.class; }
		@Override public Class<Integer> domainType() { return Integer.class; }
		@Override public Integer apply(Integer i)    { return i * 2 + 1;     }
		@Override public Integer disapply(Integer i) { return (i - 1) / 2;   }
		@Override public boolean isInDomain(Object obj) {
			return (obj instanceof Integer);
		}
		@Override
		public boolean isInRange(Object obj) {
			if (!(obj instanceof Integer)) return false;
			int i = (Integer) obj;
			return (i & 1) == 1;
		}
	};

	@Test
	public void testComposite() {
		// test composite
		Bijection<String, Integer> h = g.compose(f);

		// test two-way mapping
		assertEquals(3, h.apply("1").intValue());
		assertEquals("1", h.disapply(3));
		// test types
		Assert.assertEquals(String.class, h.domainType());
		Assert.assertEquals(Integer.class, h.rangeType());
		// test range and domain
		assertTrue(h.isInDomain("40"));
		assertTrue(h.isInDomain("0"));
		assertFalse(h.isInDomain("-5"));
		assertFalse(h.isInDomain(null));
		assertFalse(h.isInDomain(new Object()));
		assertTrue(h.isInRange(1));
		assertTrue(h.isInRange(-1)); // even though not actually attainable in composite
		assertFalse(h.isInRange(new Object()));
		assertFalse(h.isInRange(2));

		// test inverse
		Bijection<Integer, String> i = h.inverse();

		// test two-way mapping
		assertEquals("1", i.apply(3));
		assertEquals(3, i.disapply("1").intValue());
		// test types
		Assert.assertEquals(Integer.class, i.domainType());
		Assert.assertEquals(String.class, i.rangeType());
		// test range and domain
		assertTrue(i.isInRange("40"));
		assertTrue(i.isInRange("0"));
		assertFalse(i.isInRange("-5"));
		assertFalse(i.isInRange(null));
		assertFalse(i.isInRange(new Object()));
		assertTrue(i.isInDomain(1));
		assertTrue(i.isInDomain(-1)); // even though not actually attainable in composite
		assertFalse(i.isInDomain(new Object()));
		assertFalse(i.isInDomain(2));

	}

	@Test
	public void testIdentity() {
		Bijection<String, String> i = Bijection.identity(String.class);
		assertEquals("x", i.apply("x"));
		assertEquals("x", i.disapply("x"));
		Bijection<Integer, String> c = i.compose(f.inverse());
		assertEquals(f.inverse().apply(3), c.apply(3));
	}
}

redpajama_set_name: RedPajamaGithub


text:
package cuchaz.enigma.convert;

import java.util.Collection;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;

import cuchaz.enigma.mapping.entry.ClassEntry;

public class ClassForest {

	private ClassIdentifier m_identifier;
	private Multimap<ClassIdentity,ClassEntry> m_forest;

	public ClassForest(ClassIdentifier identifier) {
		m_identifier = identifier;
		m_forest = HashMultimap.create();
	}

	public void addAll(Iterable<ClassEntry> entries) {
		for (ClassEntry entry : entries) {
			add(entry);
		}
	}

	public void add(ClassEntry entry) {
		try {
			m_forest.put(m_identifier.identify(entry), entry);
		} catch (ClassNotFoundException ex) {
			throw new Error("Unable to find class " + entry.getName());
		}
	}

	public Collection<ClassIdentity> identities() {
		return m_forest.keySet();
	}

	public Collection<ClassEntry> classes() {
		return m_forest.values();
	}

	public Collection<ClassEntry> getClasses(ClassIdentity identity) {
		return m_forest.get(identity);
	}

	public boolean containsIdentity(ClassIdentity identity) {
		return m_forest.containsKey(identity);
	}
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Xunit;

namespace Glob.Tests
{
    public class GlobTests
    {
        [Fact]
        public void CanParseSimpleFilename()
        {
            var glob = new Glob("*.txt");
            Assert.True(glob.IsMatch("file.txt"));
            Assert.False(glob.IsMatch("file.zip"));
            Assert.True(glob.IsMatch(@"c:\windows\file.txt"));
        }

        [Fact]
        public void CanParseDots()
        {
            var glob = new Glob("/some/dir/folder/foo.*");
            Assert.True(glob.IsMatch("/some/dir/folder/foo.txt"));
            Assert.True(glob.IsMatch("/some/dir/folder/foo.csv"));
        }

        [Fact]
        public void CanMatchSingleFile()
        {
            var glob = new Glob("*file.txt");
            Assert.True(glob.IsMatch("bigfile.txt"));
            Assert.True(glob.IsMatch("smallfile.txt"));
        }

        [Fact]
        public void CanMatchSingleFileOnExtension()
        {
            var glob = new Glob("folder/*.txt");
            Assert.True(glob.IsMatch("folder/bigfile.txt"));
            Assert.True(glob.IsMatch("folder/smallfile.txt"));
            Assert.False(glob.IsMatch("folder/smallfile.txt.min"));
        }

        [Fact]
        public void CanMatchSingleFileWithAnyNameOrExtension()
        {
            var glob = new Glob("folder/*.*");
            Assert.True(glob.IsMatch("folder/bigfile.txt"));
            Assert.True(glob.IsMatch("folder/smallfile.txt"));
            Assert.True(glob.IsMatch("folder/smallfile.txt.min"));
        }

        [Fact]
        public void CanMatchSingleFileUsingCharRange()
        {
            var glob = new Glob("*fil[e-z].txt");
            Assert.True(glob.IsMatch("bigfile.txt"));
            Assert.True(glob.IsMatch("smallfilf.txt"));
            Assert.False(glob.IsMatch("smallfila.txt"));
            Assert.False(glob.IsMatch("smallfilez.txt"));
        }

        [Fact]
        public void CanMatchSingleFileUsingNumberRange()
        {
            var glob = new Glob("*file[1-9].txt");
            Assert.True(glob.IsMatch("bigfile1.txt"));
            Assert.True(glob.IsMatch("smallfile8.txt"));
            Assert.False(glob.IsMatch("smallfile0.txt"));
            Assert.False(glob.IsMatch("smallfilea.txt"));
        }

        [Fact]
        public void CanMatchSingleFileUsingCharList()
        {
            var glob = new Glob("*file[abc].txt");
            Assert.True(glob.IsMatch("bigfilea.txt"));
            Assert.True(glob.IsMatch("smallfileb.txt"));
            Assert.False(glob.IsMatch("smallfiled.txt"));
            Assert.False(glob.IsMatch("smallfileaa.txt"));
        }

        [Fact]
        public void CanMatchSingleFileUsingInvertedCharList()
        {
            var glob = new Glob("*file[!abc].txt");
            Assert.False(glob.IsMatch("bigfilea.txt"));
            Assert.False(glob.IsMatch("smallfileb.txt"));
            Assert.True(glob.IsMatch("smallfiled.txt"));
            Assert.True(glob.IsMatch("smallfile-.txt"));
            Assert.False(glob.IsMatch("smallfileaa.txt"));
        }

        [Fact]
        public void CanMatchBinFolderGlob()
        {
            var root = new DirectoryInfo(@"C:\");
            var allBinFolders = root.GlobDirectories("**/bin");

            Assert.True(allBinFolders.Any(), "There should be some bin folders");
        }

        [Fact]
        public void CanMatchDllExtension()
        {

            var root = new DirectoryInfo(@"C:\");
            var allDllFiles = root.GlobFiles("**/*.dll");

            Assert.True(allDllFiles.Any(), "There should be some DLL files");
        }

        [Fact]
        public void CanMatchInfoInFileSystemInfo()
        {

            var root = new DirectoryInfo(@"C:\");
            var allInfoFilesAndFolders = root.GlobFileSystemInfos("**/*info");

            Assert.True(allInfoFilesAndFolders.Any(), "There should be some 'allInfoFilesAndFolders'");
        }

        [Fact]
        public void CanMatchConfigFilesInMsDirectory()
        {
            var globPattern = @"**/*.config";

            var root = new DirectoryInfo(@"C:\Windows\Microsoft.NET");
            var result = root.GlobFiles(globPattern).ToList();

            Assert.NotNull(result);
            Assert.True(result.Any(x => x.Name == "machine.config"), $"There should be some machine.config files in '{root.FullName}'");
        }

        [Fact]
        public void CanMatchConfigFilesOrFoldersInMsDirectory()
        {
            var globPattern = @"**/*[Cc]onfig";

            var root = new DirectoryInfo(@"C:\Windows\Microsoft.NET");
            var result = root.GlobFileSystemInfos(globPattern).ToList();

            Assert.NotNull(result);
            Assert.True(result.Any(x => x.Name == "security.config"), $"There should be some security.config files in '{root.FullName}'");
            Assert.True(result.Any(x => x.Name == "machine.config"), $"There should some folder with 'Config' in '{root.FullName}'");
        }

        [Fact]
        public void CanMatchDirectoriesInMsDirectory()
        {
            var globPattern = @"**/*v*.0*";

            var root = new DirectoryInfo(@"C:\Windows\Microsoft.NET");
            var result = root.GlobDirectories(globPattern).ToList();

            Assert.NotNull(result);
            Assert.True(result.Any(), $"There should be some directories that match glob: {globPattern} in '{root.FullName}'");
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ClipSynth
{
	public partial class Favorites : Window
	{
        public bool CancelClose;

		public Favorites()
		{
            CancelClose = true;

			this.InitializeComponent();
		}

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = CancelClose;
            Hide();
        }
	}
}


text:
'use strict';

angular.module('sy-tools.footer', [])

.directive('footer', ['$log', '$window', '$timeout', function($log, $window, $timeout) {
    return {
        restrict: 'E',
        link: function(scope, element) {

        	var applyHeight = function() {
        		var height = element[0].offsetHeight;
            	element.css('margin-top', '-'+height+'px');
            	angular.element('#page-wrapper > div:first-child').css('padding-bottom', height+'px');
            };

            angular.element($window).bind('resize', function() {
                $timeout(function() {
                    applyHeight();
                });
            });

            applyHeight();

        }
    };
}]);


text:
#ifndef __CONFIG_H
#define __CONFIG_H

/* No NOR flash, this definition should be put before common header */
#define CONFIG_SYS_NO_FLASH

#include "at91-sama5_common.h"

/* The value in the common file is too far away for the VInCo platform */
#ifdef CONFIG_SYS_TEXT_BASE
#undef CONFIG_SYS_TEXT_BASE
#endif
#define CONFIG_SYS_TEXT_BASE		0x20f00000

/* serial console */
#define CONFIG_ATMEL_USART
#define CONFIG_USART_BASE		ATMEL_BASE_USART3
#define	CONFIG_USART_ID			ATMEL_ID_USART3

/* SDRAM */
#define CONFIG_NR_DRAM_BANKS		1
#define CONFIG_SYS_SDRAM_BASE           ATMEL_BASE_DDRCS
#define CONFIG_SYS_SDRAM_SIZE		0x4000000

#define CONFIG_SYS_INIT_SP_ADDR \
	(CONFIG_SYS_SDRAM_BASE + 4 * 1024 - GENERATED_GBL_DATA_SIZE)

#define CONFIG_SYS_LOAD_ADDR		0x22000000 /* load address */

/* SerialFlash */

#ifdef CONFIG_CMD_SF
#define CONFIG_ATMEL_SPI
#define CONFIG_ATMEL_SPI0
#define CONFIG_SPI_FLASH_STMICRO
#define CONFIG_SF_DEFAULT_BUS		0
#define CONFIG_SF_DEFAULT_CS		0
#define CONFIG_SF_DEFAULT_SPEED		50000000
#define CONFIG_ENV_SPI_MAX_HZ		50000000
#define CONFIG_SF_DEFAULT_MODE		(SPI_MODE_0)
#define CONFIG_ENV_SPI_MODE		(SPI_MODE_0)
#endif

/* MMC */

#ifdef CONFIG_CMD_MMC
#define CONFIG_SUPPORT_EMMC_BOOT
#define CONFIG_MMC
#define CONFIG_GENERIC_MMC
#define CONFIG_GENERIC_ATMEL_MCI
#define ATMEL_BASE_MMCI			ATMEL_BASE_MCI1
#define CONFIG_SYS_MMC_CLK_OD		500000

/* For generating MMC partitions */
#define CONFIG_PARTITION_UUIDS
#define CONFIG_RANDOM_UUID
#define CONFIG_EFI_PARTITION
#define CONFIG_CMD_GPT

#endif

/* USB */

#ifdef CONFIG_CMD_USB
#define CONFIG_USB_EHCI
#define CONFIG_USB_EHCI_ATMEL
#define CONFIG_SYS_USB_EHCI_MAX_ROOT_PORTS	3
#endif

/* USB device */
#define CONFIG_USB_ETHER
#define CONFIG_USB_ETH_RNDIS
#define CONFIG_USBNET_MANUFACTURER      "L+G VInCo"

#if defined(CONFIG_CMD_USB) || defined(CONFIG_CMD_MMC)
#define CONFIG_DOS_PARTITION
#endif

/* Ethernet Hardware */
#define CONFIG_PHY_SMSC
#define CONFIG_MACB
#define CONFIG_RMII
#define CONFIG_NET_RETRY_COUNT		20
#define CONFIG_MACB_SEARCH_PHY

#define CONFIG_USB_HOST_ETHER
#define CONFIG_USB_ETHER_SMSC95XX
#define CONFIG_USB_ETHER_RNDIS

#ifdef CONFIG_SYS_USE_SERIALFLASH
/* bootstrap + u-boot + env + linux in serial flash */
#define CONFIG_ENV_SPI_BUS	CONFIG_SF_DEFAULT_BUS
#define CONFIG_ENV_SPI_CS	CONFIG_SF_DEFAULT_CS
/* Use our own mapping for the VInCo platform */
#undef CONFIG_ENV_OFFSET
#undef CONFIG_ENV_SIZE

#define CONFIG_ENV_OFFSET       0x10000
#define CONFIG_ENV_SIZE         0x10000

/* Update the bootcommand according to our mapping for the VInCo platform */
#undef CONFIG_BOOTCOMMAND
#define CONFIG_BOOTCOMMAND  "mmc dev 0 0;" \
			    "mmc read ${loadaddr} ${k_offset} ${k_blksize};" \
			    "mmc read ${oftaddr} ${dtb_offset} ${dtb_blksize};" \
			    "bootz ${loadaddr} -  ${oftaddr}"

#undef CONFIG_BOOTARGS
#define CONFIG_BOOTARGS	    "console=ttyS0,115200 earlyprintk rw root=/dev/mmcblk0p2 rootfstype=ext4 rootwait quiet lpj=1990656"

#define CONFIG_EXTRA_ENV_SETTINGS \
	"kernel_start=0x20000\0" \
	"kernel_size=0x800000\0" \
	"mmcblksize=0x200\0" \
	"oftaddr=0x21000000\0" \
	"loadaddr=0x22000000\0" \
	"update_uboot=tftp ${loadaddr} u-boot.bin;sf probe 0;" \
	"sf erase 0x20000 0x4B000; sf write ${loadaddr} 0x20000 0x4B000\0" \
	"create_partition=setexpr dtb_start ${kernel_start} + 0x400000;" \
	"setexpr rootfs_start ${kernel_start} + ${kernel_size};" \
	"setenv partitions 'name=kernel,size=${kernel_size}," \
	"start=${kernel_start};name=rootfs,size=-';" \
	"gpt write mmc 0 ${partitions} \0"\
	"f2blk_size=setexpr fileblksize ${filesize} / ${mmcblksize};" \
	"setexpr fileblksize ${fileblksize} + 1\0" \
	"store_kernel=tftp ${loadaddr} zImage; run f2blk_size;" \
	"setexpr k_blksize ${fileblksize};" \
	"setexpr k_offset ${kernel_start} / ${mmcblksize};" \
	"mmc write ${fileaddr} ${k_offset} ${fileblksize}\0" \
	"store_dtb=tftp ${loadaddr} at91-vinco.dtb; run f2blk_size;" \
	"setexpr dtb_blksize ${fileblksize};" \
	"setexpr dtb_offset ${dtb_start} / ${mmcblksize};" \
	"mmc write ${fileaddr} ${dtb_offset} ${fileblksize}\0" \
	"store_rootfs=tftp ${loadaddr} vinco-gateway-image-vinco.ext4;" \
	"setexpr rootfs_offset ${rootfs_start} / ${mmcblksize};" \
	"mmc write ${fileaddr} ${rootfs_offset} ${fileblksize}\0" \
	"bootdelay=0\0"

#endif

#endif


text:
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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.
 -->

<!--
   Configuration file used to run a local James server from the IDE.
   See http://james.apache.org/server/3/config.html for usage.
-->

<smtpservers>
  <smtpserver enabled="true">
    <jmxName>smtpserver</jmxName>
    <bind>0.0.0.0:2525</bind>
    <connectionBacklog>200</connectionBacklog>
    <tls socketTLS="false" startTLS="false">
      <keystore>file://conf/keystore</keystore>
      <secret>yoursecret</secret>
      <provider>org.bouncycastle.jce.provider.BouncyCastleProvider</provider>
    </tls>
    <connectiontimeout>360</connectiontimeout>
    <connectionLimit> 0 </connectionLimit>
    <connectionLimitPerIP> 0 </connectionLimitPerIP>
    <authorizedAddresses>127.0.0.0/8</authorizedAddresses>
    <authRequired>true</authRequired>
    <verifyIdentity>true</verifyIdentity>
    <maxmessagesize>0</maxmessagesize>
    <addressBracketsEnforcement>true</addressBracketsEnforcement>
    <handlerchain enableJmx="true">
      <handler class="org.apache.james.smtpserver.fastfail.ValidRcptHandler"/>
      <handler class="org.apache.james.smtpserver.CoreCmdHandlerLoader"/>
    </handlerchain>
  </smtpserver>
</smtpservers>


text:
description: Setup for voting app example
keywords: docker-machine, multi-container, services, swarm mode, cluster, voting app
title: Set up Dockerized machines
---

The first step in getting the voting app deployed is to set up Docker machines
for the swarm nodes. You could create these Docker hosts on different physical
machines, virtual machines, or cloud providers.

For this example, we use [Docker Machine](/machine/get-started.md) to create two
virtual machines on a single system. (See [Docker Machine
Overview](/machine/overview.md) to learn more.) We'll also verify the setup, and
run some basic commmands to interact with the machines.

## Create manager and worker machines

The Docker Machine command to create a local virtual machine is:

```
docker-machine create --driver virtualbox <HOSTNAME>
```

Create two machines and name them to anticipate what their roles will be in the swarm:

* manager

* worker

Here is an example of creating the `manager`. Create this one, then do the same for `worker`.

```
$  docker-machine create --driver virtualbox manager
Running pre-create checks...
Creating machine...
(manager) Copying /Users/victoria/.docker/machine/cache/boot2docker.iso to /Users/victoria/.docker/machine/machines/manager/boot2docker.iso...
(manager) Creating VirtualBox VM...
(manager) Creating SSH key...
(manager) Starting the VM...
(manager) Check network to re-create if needed...
(manager) Waiting for an IP...
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with boot2docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
Checking connection to Docker...
Docker is up and running!
To see how to connect your Docker Client to the Docker Engine running on this virtual machine, run: docker-machine env manager
```

## Verify machines are running and get IP addresses

Use `docker-machine ls` to verify that the machines are
running and to get their IP addresses.

```
$ docker-machine ls
NAME       ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER        ERRORS
manager   *        virtualbox   Running   tcp://192.168.99.100:2376           v1.13.0-rc6
worker    -        virtualbox   Running   tcp://192.168.99.101:2376           v1.13.0-rc6
```

You now have two "Dockerized" machines, each running
Docker Engine, accessible through the
[Docker CLI](/engine/reference/commandline/docker.md), and available
to become swarm nodes.

You can also get the IP address of a particular machine:

```
$ docker-machine ip manager
192.168.99.100
```

You will need the IP address of the manager for a later step.

## Interacting with the machines

There are several ways to interact with these machines directly on the command line or programatically. We'll cover two methods for managing the machines directly from the command line:

#### Manage the machines from a pre-configured shell

You can use `docker-machine` to set up environment variables in a shell that connect to the Docker client on a virtual machine. With this setup, the Docker commands you type in your local shell will run on the given machine. We'll set up a shell to talk to our manager machine.

1.  Run `docker-machine env manager` to get environment variables for the manager.

    ```
    $ docker-machine env manager
    export DOCKER_TLS_VERIFY="1"
    export DOCKER_HOST="tcp://192.168.99.100:2376"
    export DOCKER_CERT_PATH="/Users/victoriabialas/.docker/machine/machines/manager"
    export DOCKER_MACHINE_NAME="manager"
    export DOCKER_API_VERSION="1.25"
    # Run this command to configure your shell:
    # eval $(docker-machine env manager)
    ```

2.  Connect your shell to the manager.
    ```
    $ eval $(docker-machine env manager)
    ```

    This sets environment variables for the current shell that the Docker client will read which specify the TLS settings.

    **Note**: If you are using `fish`, or a Windows shell such as
    Powershell/`cmd.exe` the above method will not work as described.
    Instead, see the [env command reference documentation](/machine/reference/env.md) to learn how to set the environment variables for your shell.

3.  Run `docker-machine ls` again.

    ```
    $ docker-machine ls
    NAME      ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER        ERRORS
    manager   *        virtualbox   Running   tcp://192.168.99.100:2376           v1.13.0-rc6
    worker    -        virtualbox   Running   tcp://192.168.99.101:2376           v1.13.0-rc6
    ```

    The asterisk next `manager` indicates that the current shell is connected to that machine. Docker commands run in this shell will execute on the `manager.` (Note that you could change this by re-running the above commands to connect to the `worker`, or open multiple terminals to talk to multiple machines.)

#### ssh into a machine

You can use the command `docker-machine ssh <MACHINE-NAME>` to log into a machine:

```
$ docker-machine ssh manager
                        ##         .
                  ## ## ##        ==
               ## ## ## ## ##    ===
           /"""""""""""""""""\___/ ===
      ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
           \______ o           __/
             \    \         __/
              \____\_______/
 _                 _   ____     _            _
| |__   ___   ___ | |_|___ \ __| | ___   ___| | _____ _ __
| '_ \ / _ \ / _ \| __| __) / _` |/ _ \ / __| |/ / _ \ '__|
| |_) | (_) | (_) | |_ / __/ (_| | (_) | (__|   <  __/ |
|_.__/ \___/ \___/ \__|_____\__,_|\___/ \___|_|\_\___|_|

  WARNING: this is a build from test.docker.com, not a stable release.

Boot2Docker version 1.13.0-rc6, build HEAD : 5ab2289 - Wed Jan 11 23:37:52 UTC 2017
Docker version 1.13.0-rc6, build 2f2d055
```

We'll use this method later in the example.

## What's next?

In the next step, we'll [create a swarm](create-swarm.md) across these two Docker machines.


text:
import {LighthouseError} from '../lib/lh-error.js';
import {TraceProcessor} from '../lib/tracehouse/trace-processor.js';

// TraceProcessor throws generic errors, but we'd like our special localized and code-specific LighthouseError
// objects to be thrown instead.
class LHTraceProcessor extends TraceProcessor {
  /**
   * @return {Error}
   */
  static createNoNavstartError() {
    return new LighthouseError(LighthouseError.errors.NO_NAVSTART);
  }

  /**
   * This isn't currently used, but will be when the time origin of trace processing is changed.
   * @see {TraceProcessor.computeTimeOrigin}
   * @see https://github.com/GoogleChrome/lighthouse/pull/11253#discussion_r507985527
   * @return {Error}
   */
  static createNoResourceSendRequestError() {
    return new LighthouseError(LighthouseError.errors.NO_RESOURCE_REQUEST);
  }

  /**
   * @return {Error}
   */
  static createNoTracingStartedError() {
    return new LighthouseError(LighthouseError.errors.NO_TRACING_STARTED);
  }

  /**
   * @return {Error}
   */
  static createNoFirstContentfulPaintError() {
    return new LighthouseError(LighthouseError.errors.NO_FCP);
  }
}

export default LHTraceProcessor;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Test dojox.Grid Editing</title>

	dojox.Grid Basic Editing test

	<button onclick="grid.refresh()">Refresh</button>
	<button onclick="grid.edit.focusEditor()">Focus Editor</button>
	<button onclick="grid.focus.next()">Next Focus</button>
	<button onclick="addRow()">Add Row</button>
	<button onclick="grid.removeSelectedRows()">Remove</button>
	<button onclick="grid.edit.apply()">Apply</button>
	<button onclick="grid.edit.cancel()">Cancel</button>
	<button onclick="grid.singleClickEdit = !grid.singleClickEdit">Toggle singleClickEdit</button>


text:
import tempfile
import unittest
import uuid
from cloudinitd.cb_iaas import iaas_get_con
from cloudinitd.user_api import CloudInitD
import os
import cloudinitd
import cloudinitd.cli.boot
import  time

class CloudInitDTests(unittest.TestCase):

    def setUp(self):
        self.bkfab  = None
        self.bkssh = None
        self.plan_basedir = cloudinitd.nosetests.g_plans_dir
        if 'CLOUDINITD_TESTENV' in os.environ:
            self.bkfab = os.environ['CLOUDINITD_FAB']
            self.bkssh = os.environ['CLOUDINITD_SSH']

    def tearDown(self):
        if self.bkfab:
            os.environ['CLOUDINITD_FAB'] = self.bkfab
            os.environ['CLOUDINITD_SSH'] = self.bkssh
        cloudinitd.close_log_handlers()

    def _find_str(self, filename, needle):

        file = open(filename, "r")
        try:
            found = False
            while not found:
                line = file.readline()
                if not line:
                    return None
                ndx = line.find(needle)
                if ndx >= 0:
                    return line
        finally:
            file.close()

    def _dump_output(self, filename):
        file = open(filename, "r")
        print file.readlines()
        file.close()

    def test_basic(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "boot",  "%s/terminate/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)

        n = "Starting up run"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)
        runname = line[len(n):].strip()
        print "run name is %s" % (runname)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "status",  "%s" % (runname)])
        self.assertEqual(rc, 0)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)

    def test_terminate_variable(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "boot",  "%s/terminate_variable/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)

        n = "Starting up run"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)
        runname = line[len(n):].strip()
        print "run name is %s" % (runname)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)

    def test_list_commands(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "commands"])
        self.assertEqual(rc, 0)

    def test_help(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["--help"])
        self.assertEqual(rc, 0)

    def test_basic_validate(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile,  "--validate", "boot",  "%s/simplebadplan/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertNotEqual(rc, 0)

    def test_bad_files(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile,  "--validate", "boot",  "%s/badfiles/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertNotEqual(rc, 0)

    def test_bad_validate(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile,  "--validate", "boot",  "%s/baddeps/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertNotEqual(rc, 0)

    def test_bad_dryrun(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile,  "--dryrun", "boot",  "%s/baddeps/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertNotEqual(rc, 0)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "boot",  "%s/baddeps/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertNotEqual(rc, 0)

    def test_ssh_into_dep(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "boot",  "%s/intohostname/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)
        runname = self._get_runname(outfile)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)

    def test_reload(self):

        if 'CLOUDINITD_TESTENV' in os.environ:
            #this wont work in fake mode
            return

        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "-v", "-v", "-v", "boot",  "%s/reloadplan/badtop.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        n = "Starting up run"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)
        runname = line[len(n):].strip()
        print "run name is %s" % (runname)
        self.assertNotEqual(rc, 0)

        rc = cloudinitd.cli.boot.main(["--name", runname, "reload",  "%s/reloadplan/goodtop.conf" % (self.plan_basedir)])
        self.assertEqual(rc, 0)
        rc = cloudinitd.cli.boot.main(["repair",  runname])
        self.assertEqual(rc, 0)
        rc = cloudinitd.cli.boot.main(["terminate",  runname])
        self.assertEqual(rc, 0)

    def test_validate_nolaunch(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)

        key = None
        secret = None
        url = None
        try:
            key = os.environ['CLOUDINITD_IAAS_ACCESS_KEY']
            secret = os.environ['CLOUDINITD_IAAS_SECRET_KEY']
            url = os.environ['CLOUDINITD_IAAS_URL']
        except:
            pass

        # XXX this test may fail for nimbus
        con = cloudinitd.cb_iaas.iaas_get_con(None, key=key, secret=secret, iaasurl=url)
        i_list = con.get_all_instances()
        rc = cloudinitd.cli.boot.main(["-O", outfile, "--validate", "boot",  "%s/badlevels/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertNotEqual(rc, 0)
        after_list = con.get_all_instances()
        self.assertEqual(len(i_list), len(after_list))

    def _get_runname(self, fname):
        n = "Starting up run"
        line = self._find_str(fname, n)
        self.assertNotEqual(line, None)
        runname = line[len(n):].strip()
        print "run name is %s" % (runname)
        return runname

    def test_list_simple(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "boot",  "%s/terminate/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)

        runname = self._get_runname(outfile)

        rc = cloudinitd.cli.boot.main(["-O", outfile, "list"])
        self.assertEqual(rc, 0)
        line = self._find_str(outfile, runname)
        self.assertNotEqual(line, None)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)

    def test_cleanup_list(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "boot",  "%s/terminate/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)

        runname = self._get_runname(outfile)

        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "list"])
        self.assertEqual(rc, 0)
        line = self._find_str(outfile, runname)
        self.assertEqual(line, None)

    def test_reboot_simple(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "-l", "info", "boot",  "%s/terminate/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)
        runname = self._get_runname(outfile)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "-l", "debug", "reboot",  "%s" % (runname)])
        self.assertEqual(rc, 0)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "status",  "%s" % (runname)])
        self.assertEqual(rc, 0)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)

    def bad_name_test(self):
        runname = str(uuid.uuid4()).split("-")[0]
        rc = cloudinitd.cli.boot.main(["status",  "%s" % (runname)])
        self.assertNotEqual(rc, 0)
        rc = cloudinitd.cli.boot.main(["terminate",  "%s" % (runname)])
        self.assertNotEqual(rc, 0)
        rc = cloudinitd.cli.boot.main(["reboot",  "%s" % (runname)])
        self.assertNotEqual(rc, 0)

    def bad_boot_args_test(self):
        rc = cloudinitd.cli.boot.main(["boot"])
        self.assertNotEqual(rc, 0)

    def check_boot_output_test(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-v","-v","-v","-v", "-O", outfile, "boot",  "%s/terminate/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)
        runname = self._get_runname(outfile)

        n = "instance:"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)
        n = "hostname:"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)

        n = "SUCCESS"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)

        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)

    def check_status_output_test(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "boot",  "%s/terminate/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)
        runname = self._get_runname(outfile)

        rc = cloudinitd.cli.boot.main(["-O", outfile, "-v","-v","-v","-v", "status", runname])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)
        n = "instance:"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)
        n = "hostname:"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)

        n = "SUCCESS"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)

        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)

    def simple_iceage_test(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "boot",  "%s/terminate/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)
        runname = self._get_runname(outfile)

        rc = cloudinitd.cli.boot.main(["-O", outfile, "history", runname])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)

        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)

    def check_terminate_output_test(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "boot",  "%s/terminate/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)
        runname = self._get_runname(outfile)

        rc = cloudinitd.cli.boot.main(["-O", outfile, "-v", "-v", "-v", "terminate",  "%s" % (runname)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)
        n = "instance:"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)
        n = "hostname:"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)
        ndx = line.find("None")
        self.assertTrue(ndx >= 0)

        n = "SUCCESS"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)

    def check_status_shutdown_error_test(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        dir = os.path.expanduser("~/.cloudinitd/")
        conf_file = self.plan_basedir + "/terminate/top.conf"
        cb = CloudInitD(dir, conf_file, terminate=False, boot=True, ready=True)
        cb.start()
        cb.block_until_complete(poll_period=1.0)
        runname = cb.run_name
        svc = cb.get_service("sampleservice")
        p = svc.shutdown()
        rc = p.poll()
        while not rc:
            rc = p.poll()
            time.sleep(0.1)

        if 'CLOUDINITD_TESTENV' in os.environ:
            bkfab = os.environ['CLOUDINITD_FAB']
            bkssh = os.environ['CLOUDINITD_SSH']
            os.environ['CLOUDINITD_FAB'] = "/bin/false"
            os.environ['CLOUDINITD_SSH'] = "/bin/false"

        rc = cloudinitd.cli.boot.main(["-O", outfile, "-v","-v","-v","-v", "status", runname])
        if 'CLOUDINITD_TESTENV' in os.environ:
            os.environ['CLOUDINITD_FAB'] = bkfab
            os.environ['CLOUDINITD_SSH'] = bkssh
        self._dump_output(outfile)
        n = "ERROR"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)

        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)

    def check_status_error_test(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        dir = os.path.expanduser("~/.cloudinitd/")
        conf_file = self.plan_basedir + "/terminate/top.conf"
        cb = CloudInitD(dir, conf_file, terminate=False, boot=True, ready=True)
        cb.start()
        cb.block_until_complete(poll_period=1.0)
        runname = cb.run_name
        svc = cb.get_service("sampleservice")

        secret = svc.get_attr_from_bag('iaas_secret')
        key = svc.get_attr_from_bag('iaas_key')
        iaas_url = svc.get_attr_from_bag('iaas_url')
        instance_id = svc.get_attr_from_bag('instance_id')
        con = iaas_get_con(None, key=key, secret=secret, iaasurl=iaas_url)
        instance = con.find_instance(instance_id)
        instance.terminate()

        if 'CLOUDINITD_TESTENV' in os.environ:
            bkfab = os.environ['CLOUDINITD_FAB']
            bkssh = os.environ['CLOUDINITD_SSH']
            os.environ['CLOUDINITD_FAB'] = "/bin/false"
            os.environ['CLOUDINITD_SSH'] = "/bin/false"

        rc = cloudinitd.cli.boot.main(["-O", outfile, "-v","-v","-v","-v", "status", runname])
        if 'CLOUDINITD_TESTENV' in os.environ:
            os.environ['CLOUDINITD_FAB'] = bkfab
            os.environ['CLOUDINITD_SSH'] = bkssh
        self._dump_output(outfile)
        n = "ERROR"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)

        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        if 'CLOUDINITD_TESTENV' in os.environ:
            # in fake mode we cannot detect that an instance was killed
            self.assertEqual(rc, 0)
        else:
            self.assertNotEqual(rc, 0)

    def check_repair_error_test(self):
        if 'CLOUDINITD_TESTENV' in os.environ:
            # we cannot run this one in fake mode yet
            return
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        dir = os.path.expanduser("~/.cloudinitd/")
        conf_file = self.plan_basedir + "/multileveldeps/top.conf"
        cb = CloudInitD(dir, conf_file, terminate=False, boot=True, ready=True)
        cb.start()
        cb.block_until_complete(poll_period=1.0)
        runname = cb.run_name
        svc = cb.get_service("l2service")

        secret = svc.get_attr_from_bag('iaas_secret')
        key = svc.get_attr_from_bag('iaas_key')
        url = svc.get_attr_from_bag('iaas_url')
        instance_id = svc.get_attr_from_bag('instance_id')
        con = iaas_get_con(svc._svc, key=key, secret=secret, iaasurl=url)
        instance = con.find_instance(instance_id)
        instance.terminate()

        print "start repair"
        rc = cloudinitd.cli.boot.main(["-O", outfile, "-v","-v","-v","repair", runname])
        self._dump_output(outfile)
        n = "ERROR"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)

        print "start terminate"
        rc = cloudinitd.cli.boot.main(["terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)

    def test_multiterminate(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "boot",  "%s/oneservice/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)
        n = "Starting up run"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)
        runname1 = line[len(n):].strip()

        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "boot",  "%s/oneservice/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)
        n = "Starting up run"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)
        runname2 = line[len(n):].strip()

        print "run name is %s and %s" % (runname1, runname2)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  runname1, runname2])
        self.assertEqual(rc, 0)

    def check_service_log_test(self):

        dir = os.path.expanduser("~/.cloudinitd/")
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "-v", "-l", "info", "boot",  "%s/oneservice/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)
        n = "Starting up run"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)
        runname = line[len(n):].strip()

        logfilename = dir + "/" + runname + "/sampleservice.log"
        self.assertTrue(os.path.exists(logfilename), "%s should exist" % (logfilename))
        os.path.getsize(logfilename)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)

    def test_outputwriter(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "-o", "/dev/null", "boot",  "%s/terminate/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)
        n = "Starting up run"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)
        runname = line[len(n):].strip()
        print "run name is %s" % (runname)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "-o", "/dev/null", "status",  "%s" % (runname)])
        self.assertEqual(rc, 0)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)

    def termfails_test(self):

        if 'CLOUDINITD_TESTENV' in os.environ:
            return
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "-o", "/dev/null", "boot",  "%s/termfail/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)

        n = "Starting up run"
        line = self._find_str(outfile, n)
        self.assertNotEqual(line, None)
        runname = line[len(n):].strip()
        print "run name is %s" % (runname)

        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        self._dump_output(outfile)
        line = self._find_str(outfile, "ERROR")
        self.assertNotEqual(line, None)

    def test_globals_success(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "--globalvar", "var1=world", "boot",  "%s/globals/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertEqual(rc, 0)

        runname = self._get_runname(outfile)

        rc = cloudinitd.cli.boot.main(["-O", outfile, "--globalvar", "var1=world", "terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)

    def test_globals_fail(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "boot",  "%s/globals/top.conf" % (self.plan_basedir)])
        self._dump_output(outfile)
        self.assertNotEqual(rc, 0)

        runname = self._get_runname(outfile)

        rc = cloudinitd.cli.boot.main(["-O", outfile, "terminate",  "%s" % (runname)])
        line = self._find_str(outfile, "global variable var1 is not")
        self.assertNotEqual(line, None)

    def test_globals_file_success(self):
        (osf, outfile) = tempfile.mkstemp()
        os.close(osf)
        rc = cloudinitd.cli.boot.main(["-O", outfile, "--globalvarfile", "%s/globals/globals.ini" % (self.plan_basedir), "boot",  "%s/globals/top.conf" % (self.plan_basedir)])

        self._dump_output(outfile)
        self.assertEqual(rc, 0)

        runname = self._get_runname(outfile)

        rc = cloudinitd.cli.boot.main(["-O", outfile, "--globalvar", "var1=world", "terminate",  "%s" % (runname)])
        self.assertEqual(rc, 0)


text:
<?php
   define('BASE_DIR', dirname(__FILE__));
   require_once(BASE_DIR.'/config.php');

   //Text labels here
   define('BTN_DOWNLOAD', 'Download');
   define('BTN_DELETE', 'Delete');
   define('BTN_CONVERT', 'Start Convert');
   define('BTN_DELETEALL', 'Delete All');
   define('BTN_DELETESEL', 'Delete Sel');
   define('BTN_SELECTALL', 'Select All');
   define('BTN_SELECTNONE', 'Select None');
   define('BTN_GETZIP', 'Get Zip');
   define('BTN_UPDATESIZES', 'Update Sizes');
   define('TXT_PREVIEW', 'Preview');
   define('TXT_THUMB', 'Thumb');
   define('TXT_FILES', 'Files');

   define('CONVERT_CMD', 'convertCmd.txt');

   //Set size defaults and try to get from cookies
   $previewSize = 640;
   $thumbSize = 96;
   if(isset($_COOKIE["previewSize"])) {
      $previewSize = $_COOKIE["previewSize"];
   }
   if(isset($_COOKIE["thumbSize"])) {
      $thumbSize = $_COOKIE["thumbSize"];
   }
   $dSelect = "";
   $pFile = "";
   $tFile = "";
   $debugString = "";

   if(isset($_GET['preview'])) {
      $tFile = $_GET['preview'];
      $pFile = dataFilename($tFile);
   }

   if (isset($_GET['zipprogress'])) {
      $zipname = $_GET['zipprogress'];
      $ret = @file_get_contents("$zipname.count");
      if ($ret) {
         echo $ret;
      }
      else {
         echo "complete";
      }
      return;
   }

   $zipname = false;
   //Process any POST data
   // 1 file based commands
   if (isset($_POST['zipdownload'])) {
      $zipname = $_POST['zipdownload'];
      header("Content-Type: application/zip");
      header("Content-Disposition: attachment; filename=\"".substr($zipname,strlen(MEDIA_PATH)+1)."\"");
      readfile("$zipname");
      if(file_exists($zipname)){
          unlink($zipname);
      }
      return;
   }
   else if (isset($_POST['delete1'])) {
      deleteFile($_POST['delete1']);
      maintainFolders(MEDIA_PATH, false, false);
   } else if (isset($_POST['convert'])) {
      $tFile = $_POST['convert'];
      startVideoConvert($tFile);
      $tFile = "";
   } else if (isset($_POST['download1'])) {
      $dFile = $_POST['download1'];
      if(getFileType($dFile) != 't') {
         $dxFile = dataFilename($dFile);
         if(dataFileext($dFile) == "jpg") {
            header("Content-Type: image/jpeg");
         } else {
            header("Content-Type: video/mp4");
         }
         header("Content-Disposition: attachment; filename=\"" . dataFilename($dFile) . "\"");
         readfile(MEDIA_PATH . "/$dxFile");
         return;
      } else {
         $zipname = getZip(array($dFile));
      }
   } else if (isset($_POST['action'])){
      //global commands
      switch($_POST['action']) {
         case 'deleteAll':
            maintainFolders(MEDIA_PATH, true, true);
            break;
         case 'selectAll':
            $dSelect = "checked";
            break;
         case 'selectNone':
            $dSelect = "";
            break;
         case 'deleteSel':
            if(!empty($_POST['check_list'])) {
               foreach($_POST['check_list'] as $check) {
                  deleteFile($check);
               }
            }
            maintainFolders(MEDIA_PATH, false, false);
            break;
         case 'updateSizes':
            if(!empty($_POST['previewSize'])) {
               $previewSize = $_POST['previewSize'];
               if ($previewSize < 100 || $previewSize > 1920) $previewSize = 640;
               setcookie("previewSize", $previewSize, time() + (86400 * 365), "/");
            }
            if(!empty($_POST['thumbSize'])) {
               $thumbSize = $_POST['thumbSize'];
               if ($thumbSize < 32 || $thumbSize > 320) $thumbSize = 96;
               setcookie("thumbSize", $thumbSize, time() + (86400 * 365), "/");
            }
            break;
         case 'zipSel':
            if (!empty($_POST['check_list'])) {
               $zipname = getZip($_POST['check_list']);
            }
            break;
      }
   }

   function getZip($files) {
      $zipname = MEDIA_PATH . '/cam_' . date("Ymd_His") . '.zip';
      writeLog("Making zip $zipname");
      $zipfiles = fopen($zipname.".files", "w");
      foreach ($files as $file) {
         if (getFileType($file) == 't') {
            $lapses = findLapseFiles($file);
            if (!empty($lapses)) {
               foreach($lapses as $lapse) {
                  fprintf($zipfiles, "$lapse\n");
               }
            }
         } else {
            $base = dataFilename($file);
            if (file_exists(MEDIA_PATH . "/$base")) {
               fprintf($zipfiles, MEDIA_PATH . "/$base\n");
            }
         }
      }
      fclose($zipfiles);
      file_put_contents("$zipname.count", "0/100");
      exec("./raspizip.sh $zipname $zipname.files > /dev/null &");
      return $zipname;
   }

   function startVideoConvert($bFile) {
      global $debugString;
      $tFiles = findLapseFiles($bFile);
      $tmp = BASE_DIR . '/' . MEDIA_PATH . '/' . getFileType($bFile) . getFileIndex($bFile);
      if (!file_exists($tmp)) {
         mkdir($tmp, 0777, true);
      }
      $i= 1;
      foreach($tFiles as $tFile) {
         copy($tFile, $tmp . '/' . sprintf('i_%05d', $i) . '.jpg');
         $i++;
      }
      $vFile = substr(dataFilename($bFile), 0, -3) . 'mp4';
      $cmd = $_POST['convertCmd'];
      $fp = fopen(BASE_DIR . '/' . CONVERT_CMD, 'w');
      fwrite($fp, $cmd);
      fclose($fp);
      $cmd = "(" . str_replace("i_%05d", "$tmp/i_%05d", $cmd) . ' ' . BASE_DIR . '/' . MEDIA_PATH . "/$vFile ; rm -rf $tmp;) >/dev/null 2>&1 &";
      writeLog("start lapse convert:$cmd");
      system($cmd);
      copy(MEDIA_PATH . "/$bFile", MEDIA_PATH . '/' . $vFile . '.v' . getFileIndex($bFile) .THUMBNAIL_EXT);
      writeLog("Convert finished");
   }

   // function to deletes files and folders recursively
   // $deleteMainFiles true r false to delete files from the top level folder
   // $deleteSubFiles true or false to delete files from subfolders
   // Empty subfolders get removed.
   // $root true or false. If true (default) then top dir not removed
   function maintainFolders($path, $deleteMainFiles, $deleteSubFiles, $root = true) {
      $empty=true;
      foreach (glob("$path/*") as $file) {
         if (is_dir($file)) {
            if (!maintainFolders($file, $deleteMainFiles, $deleteSubFiles, false)) $empty=false;
         }  else {
            if (($deleteSubFiles && !$root) || ($deleteMainFiles && $root)) {
              unlink($file);
            } else {
               $empty=false;
            }
         }
      }
      return $empty && !$root && rmdir($path);
   }

   //function to draw 1 file on the page
   function drawFile($f, $ts, $sel) {
      $fType = getFileType($f);
      $rFile = dataFilename($f);
      $fNumber = getFileIndex($f);
      $lapseCount = "";
      switch ($fType) {
         case 'v': $fIcon = 'video.png'; break;
         case 't':
            $fIcon = 'timelapse.png';
            $lapseCount = '(' . count(findLapseFiles($f)). ')';
            break;
         case 'i': $fIcon = 'image.png'; break;
         default : $fIcon = 'image.png'; break;
      }
      if (file_exists(MEDIA_PATH . "/$rFile")) {
         $fsz = round ((filesize(MEDIA_PATH . "/$rFile")) / 1024);
         $fModTime = filemtime(MEDIA_PATH . "/$rFile");
      } else {
         $fsz = 0;
         $fModTime = filemtime(MEDIA_PATH . "/$f");
      }
      $fDate = @date('Y-m-d', $fModTime);
      $fTime = @date('H:i:s', $fModTime);
      $fWidth = max($ts + 4, 140);
      echo "<fieldset class='fileicon' style='width:" . $fWidth . "px;'>";
      echo "<legend class='fileicon'>";
      echo "<button type='submit' name='delete1' value='$f' class='fileicondelete' style='background-image:url(delete.png);
'></button>";
      echo "  $fNumber ";
      echo "";
      echo "<input type='checkbox' name='check_list[]' $sel value='$f' style='float:right;'/>";
      echo "</legend>";
      if ($fsz > 0) echo "$fsz Kb $lapseCount"; else echo 'Busy';
      echo "
$fDate
$fTime
";
      if ($fsz > 0) echo "";
      echo "";
      if ($fsz > 0) echo "";
      echo "</fieldset> ";
   }

   function diskUsage() {
      //Get disk data
      $totalSize = round(disk_total_space(BASE_DIR . '/' . MEDIA_PATH) / 1048576); //MB
      $currentAvailable = round(disk_free_space(BASE_DIR . '/' . MEDIA_PATH) / 1048576); //MB
      $percentUsed = round(($totalSize - $currentAvailable)/$totalSize * 100, 1);
      if ($percentUsed > 98)
         $colour = 'Red';
      else if ($percentUsed > 90)
         $colour = 'Orange';
      else
         $colour = 'LightGreen';
      echo '
';
         echo "Used:$percentUsed%  Total:$totalSize(MB)";
         echo "

";
      echo '
';
   }

?>
<!DOCTYPE html>

      <meta name="viewport" content="width=550, initial-scale=1">
      <title>RPi Cam Download</title>
      <link rel="stylesheet" href="css/style_minified.css" />
      <link rel="stylesheet" href="css/preview.css" />
      <link rel="stylesheet" href="css/extrastyle.css" />

      <form action="preview.php" method="POST">
      <?php
         if ($pFile != "") {
            echo "
" . TXT_PREVIEW . ":  " . getFileType($tFile) . getFileIndex($tFile);
            echo "  <button class='btn btn-primary' type='submit' name='download1' value='$tFile'>" . BTN_DOWNLOAD . "</button>";
            echo " <button class='btn btn-danger' type='submit' name='delete1' value='$tFile'>" . BTN_DELETE . "</button>";
            if(getFileType($tFile) == "t") {
               $convertCmd = file_get_contents(BASE_DIR . '/' . CONVERT_CMD);
               echo " <button class='btn btn-primary' type='submit' name='convert' value='$tFile'>" . BTN_CONVERT . "</button>";
               echo "

Convert using: <input type='text' size=72 name = 'convertCmd' id='convertCmd' value='$convertCmd'>

";
            } else {
               echo "

";
            }
            if(substr($pFile, -3) == "jpg") {
               echo "";
            } else {
               echo "<video width='" . $previewSize . "px' controls><source src='" . MEDIA_PATH . "/$pFile' type='video/mp4'>Your browser does not support the video tag.</video>";
            }
         }
         echo "
" . TXT_FILES . "  ";
         echo "  <button class='btn btn-primary' type='submit' name='action' value='selectNone'>" . BTN_SELECTNONE . "</button>";
         echo "  <button class='btn btn-primary' type='submit' name='action' value='selectAll'>" . BTN_SELECTALL . "</button>";
         echo "  <button class='btn btn-primary' type='submit' name='action' value='zipSel'>" . BTN_GETZIP . "</button>";
         echo "  <button class='btn btn-danger' type='submit' name='action' value='deleteSel' onclick=\"return confirm('Are you sure?');\">" . BTN_DELETESEL . "</button>";
         echo "  <button class='btn btn-danger' type='submit' name='action' value='deleteAll' onclick=\"return confirm('Are you sure?');\">" . BTN_DELETEALL . "</button>";
         echo "
";
         diskUsage();
         if ($debugString !="") echo "$debugString
";
         $files = scandir(MEDIA_PATH);
         if(count($files) == 2) echo "
No videos/images saved
";
         //var_dump($files);
         else {
            foreach($files as $file) {
               var_dump($file);
               if(($file != '.') && ($file != '..') && isThumbnail($file, -7)) {
                  drawFile($file, $thumbSize, $dSelect);
               }
            }
         }
         echo "

" . TXT_PREVIEW . " <input type='text' size='4' name='previewSize' value='$previewSize'>";
         echo "  " . TXT_THUMB . " <input type='text' size='3' name='thumbSize' value='$thumbSize'>";
         echo "  <button class='btn btn-primary' type='submit' name='action' value='updateSizes'>" . BTN_UPDATESIZES . "</button>";
      ?>
      </form>

      <form id="zipform" method="post" action="preview.php" style="display:none;">
         <input id="zipdownload" type="hidden" name="zipdownload"/>
      </form>

      <?php
      if ($zipname) {
         echo '';
      } else {
         echo '';
      }
      ?>


text:
/**
 *
 */
package me.learn.personal.month4;

import java.util.Stack;

/**
 * Title 394 :
 *
 * Given an encoded string, return its decoded string.
 *
 * The encoding rule is: k[encoded_string], where the encoded_string inside the
 * square brackets is being repeated exactly k times. Note that k is guaranteed
 * to be a positive integer.
 *
 * You may assume that the input string is always valid; No extra white spaces,
 * square brackets are well-formed, etc.
 *
 * Furthermore, you may assume that the original data does not contain any
 * digits and that digits are only for those repeat numbers, k. For example,
 * there won't be input like 3a or 2[4].
 *
 *
 *
 * Example 1:
 *
 * Input: s = "3[a]2[bc]" Output: "aaabcbc"
 *
 * Example 2:
 *
 * Input: s = "3[a2[c]]" Output: "accaccacc"
 *
 * Example 3:
 *
 * Input: s = "2[abc]3[cd]ef" Output: "abcabccdcdcdef"
 *
 * Example 4:
 *
 * Input: s = "abc3[cd]xyz" Output: "abccdcdcdxyz"
 *
 *
 * @author bramanarayan
 * @date Jul 29, 2020
 */
public class DecodeString {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

			DecodeString solution = new DecodeString();
			System.out.println(solution.decodeString("3[a]2[bc]"));
	}

	// Below uses one stack only.
	// You can solve clutter free using 2 stacks , though
	public String decodeString(String s) {

		Stack<String> st = new Stack<String>();

		int n = s.length();
		for (int i = 0; i < n; i++) {

			char ch = s.charAt(i);

			// DIGIT DECODING
			if (Character.isDigit(ch)) {
				// read all the number of times of repeat
				int j = i;
				StringBuilder sb = new StringBuilder();
				while (j < n && Character.isDigit(s.charAt(j))) {
					sb.append(s.charAt(j));
					j++;
				}
				i = j-1;
				st.push(sb.toString());
			} else if (ch == '[') {
				st.push(String.valueOf(ch));
			} else if (ch == ']') {
				StringBuilder sb = new StringBuilder();
				while (!st.isEmpty() && !st.peek().equals("[")) {
					sb.append(st.pop());
				}
				st.pop(); // this pops ]
				if (st.peek().matches("\\d+")) {
					String temp = sb.toString();
					int count = Integer.parseInt(st.pop());
					// repeat string n times
					for (int k = 1; k < count; k++) {
						sb.append(temp);
					}
					st.push(sb.toString());
				} else {
					st.push(sb.toString());
				}

			} else {
				// single character
				st.push(String.valueOf(ch));
			}
		}

		// prepare output
		StringBuilder resultBuilder = new StringBuilder();
		while(!st.isEmpty()) {
			resultBuilder.append(st.pop());
		}
		return resultBuilder.reverse().toString();

	}

}


text:
"""Generic resource pool implementation."""
from __future__ import absolute_import, unicode_literals

import os

from collections import deque

from . import exceptions
from .five import Empty, LifoQueue as _LifoQueue
from .utils.compat import register_after_fork
from .utils.functional import lazy

def _after_fork_cleanup_resource(resource):
    try:
        resource.force_close_all()
    except Exception:
        pass

class LifoQueue(_LifoQueue):
    """Last in first out version of Queue."""

    def _init(self, maxsize):
        self.queue = deque()

class Resource(object):
    """Pool of resources."""

    LimitExceeded = exceptions.LimitExceeded

    close_after_fork = False

    def __init__(self, limit=None, preload=None, close_after_fork=None):
        self._limit = limit
        self.preload = preload or 0
        self._closed = False
        self.close_after_fork = (
            close_after_fork
            if close_after_fork is not None else self.close_after_fork
        )

        self._resource = LifoQueue()
        self._dirty = set()
        if self.close_after_fork and register_after_fork is not None:
            register_after_fork(self, _after_fork_cleanup_resource)
        self.setup()

    def setup(self):
        raise NotImplementedError('subclass responsibility')

    def _add_when_empty(self):
        if self.limit and len(self._dirty) >= self.limit:
            raise self.LimitExceeded(self.limit)
        # All taken, put new on the queue and
        # try get again, this way the first in line
        # will get the resource.
        self._resource.put_nowait(self.new())

    def acquire(self, block=False, timeout=None):
        """Acquire resource.

        Arguments:
            block (bool): If the limit is exceeded,
                then block until there is an available item.
            timeout (float): Timeout to wait
                if ``block`` is true.  Default is :const:`None` (forever).

        Raises:
            LimitExceeded: if block is false and the limit has been exceeded.
        """
        if self._closed:
            raise RuntimeError('Acquire on closed pool')
        if self.limit:
            while 1:
                try:
                    R = self._resource.get(block=block, timeout=timeout)
                except Empty:
                    self._add_when_empty()
                else:
                    try:
                        R = self.prepare(R)
                    except BaseException:
                        if isinstance(R, lazy):
                            # not evaluated yet, just put it back
                            self._resource.put_nowait(R)
                        else:
                            # evaluted so must try to release/close first.
                            self.release(R)
                        raise
                    self._dirty.add(R)
                    break
        else:
            R = self.prepare(self.new())

        def release():
            """Release resource so it can be used by another thread.

            Warnings:
                The caller is responsible for discarding the object,
                and to never use the resource again.  A new resource must
                be acquired if so needed.
            """
            self.release(R)
        R.release = release

        return R

    def prepare(self, resource):
        return resource

    def close_resource(self, resource):
        resource.close()

    def release_resource(self, resource):
        pass

    def replace(self, resource):
        """Replace existing resource with a new instance.

        This can be used in case of defective resources.
        """
        if self.limit:
            self._dirty.discard(resource)
        self.close_resource(resource)

    def release(self, resource):
        if self.limit:
            self._dirty.discard(resource)
            self._resource.put_nowait(resource)
            self.release_resource(resource)
        else:
            self.close_resource(resource)

    def collect_resource(self, resource):
        pass

    def force_close_all(self):
        """Close and remove all resources in the pool (also those in use).

        Used to close resources from parent processes after fork
        (e.g. sockets/connections).
        """
        if self._closed:
            return
        self._closed = True
        dirty = self._dirty
        resource = self._resource
        while 1:  # - acquired
            try:
                dres = dirty.pop()
            except KeyError:
                break
            try:
                self.collect_resource(dres)
            except AttributeError:  # Issue #78
                pass
        while 1:  # - available
            # deque supports '.clear', but lists do not, so for that
            # reason we use pop here, so that the underlying object can
            # be any object supporting '.pop' and '.append'.
            try:
                res = resource.queue.pop()
            except IndexError:
                break
            try:
                self.collect_resource(res)
            except AttributeError:
                pass  # Issue #78

    def resize(self, limit, force=False, ignore_errors=False, reset=False):
        prev_limit = self._limit
        if (self._dirty and limit < self._limit) and not ignore_errors:
            if not force:
                raise RuntimeError(
                    "Can't shrink pool when in use: was={0} now={1}".format(
                        limit, self._limit))
            reset = True
        self._limit = limit
        if reset:
            try:
                self.force_close_all()
            except Exception:
                pass
        self.setup()
        if limit < prev_limit:
            self._shrink_down()

    def _shrink_down(self):
        resource = self._resource
        # Items to the left are last recently used, so we remove those first.
        with resource.mutex:
            while len(resource.queue) > self.limit:
                self.collect_resource(resource.queue.popleft())

    @property
    def limit(self):
        return self._limit

    @limit.setter
    def limit(self, limit):
        self.resize(limit)

    if os.environ.get('KOMBU_DEBUG_POOL'):  # pragma: no cover
        _orig_acquire = acquire
        _orig_release = release

        _next_resource_id = 0

        def acquire(self, *args, **kwargs):  # noqa
            import traceback
            id = self._next_resource_id = self._next_resource_id + 1
            print('+{0} ACQUIRE {1}'.format(id, self.__class__.__name__))
            r = self._orig_acquire(*args, **kwargs)
            r._resource_id = id
            print('-{0} ACQUIRE {1}'.format(id, self.__class__.__name__))
            if not hasattr(r, 'acquired_by'):
                r.acquired_by = []
            r.acquired_by.append(traceback.format_stack())
            return r

        def release(self, resource):  # noqa
            id = resource._resource_id
            print('+{0} RELEASE {1}'.format(id, self.__class__.__name__))
            r = self._orig_release(resource)
            print('-{0} RELEASE {1}'.format(id, self.__class__.__name__))
            self._next_resource_id -= 1
            return r


text:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace PowerShellEditorServices.Test.E2E
{
    internal class LoggingStream : Stream
    {
        private static readonly string s_banner = new('=', 20);

        private readonly Stream _underlyingStream;

        public LoggingStream(Stream underlyingStream) => _underlyingStream = underlyingStream;

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (disposing)
            {
                _underlyingStream.Dispose();
            }
        }

        public override bool CanRead => _underlyingStream.CanRead;

        public override bool CanSeek => _underlyingStream.CanSeek;

        public override bool CanWrite => _underlyingStream.CanWrite;

        public override long Length => _underlyingStream.Length;

        public override long Position { get => _underlyingStream.Position; set => _underlyingStream.Position = value; }

        public override void Flush() => _underlyingStream.Flush();

        public override int Read(byte[] buffer, int offset, int count)
        {
            int actualCount = _underlyingStream.Read(buffer, offset, count);
            LogData("READ", buffer, offset, actualCount);
            return actualCount;
        }

        public override long Seek(long offset, SeekOrigin origin) => _underlyingStream.Seek(offset, origin);

        public override void SetLength(long value) => _underlyingStream.SetLength(value);

        public override void Write(byte[] buffer, int offset, int count)
        {
            LogData("WRITE", buffer, offset, count);
            _underlyingStream.Write(buffer, offset, count);
        }

        private static void LogData(string header, byte[] buffer, int offset, int count)
        {
            Debug.WriteLine($"{header} |{s_banner.Substring(0, Math.Max(s_banner.Length - header.Length - 2, 0))}");
            string data = Encoding.UTF8.GetString(buffer, offset, count);
            Debug.WriteLine(data);
            Debug.WriteLine(s_banner);
            Debug.WriteLine("\n");
        }
    }
}


text:
//
//  ConfirmUploadImageController.m
//  FaceBattle-iOS
//
//  Created by kino on 16/6/5.
//
//

#import "ConfirmUploadImageController.h"

#import "BattleEngine.h"

#import "MBProgressHUD.h"

@interface ConfirmUploadImageController ()

@property (weak, nonatomic) IBOutlet UIImageView *chooseImageView;

@property (weak, nonatomic) IBOutlet UIButton *sureButton;
@property (weak, nonatomic) IBOutlet UIButton *cancelButton;

@property (strong, nonatomic) MBProgressHUD *uploadHud;

@end

@implementation ConfirmUploadImageController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.fd_prefersNavigationBarHidden = YES;

    _chooseImageView.image = self.chooseImage;

    [_sureButton applyRoundBorderStyle:8 borderColor:[UIColor clearColor]];
    [_cancelButton applyRoundBorderStyle:8 borderColor:[UIColor clearColor]];

    useWeakSelf
    [[_sureButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {

        _uploadHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        _uploadHud.mode = MBProgressHUDModeAnnularDeterminate;
        _uploadHud.label.text = @"Uploading...";

        if (self.joinBid) {
            [BattleEngine joinBattleWithPhoto:[self resizeImage:self.chooseImage] bid:self.joinBid progress:^(NSProgress *progress) {
                _uploadHud.progress = (progress.completedUnitCount * 1.f / progress.totalUnitCount * 1.f);
                NSLog(@"current = %f",progress.completedUnitCount * 1.f / progress.totalUnitCount * 1.f);
            } onComplete:^(id responseResult) {
                [_uploadHud hideAnimated:YES];
                [weakSelf showSuccessMessage:@"Upload Success!"];

                __block UIViewController *willJumpController;
                [weakSelf.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

                    if ([NSStringFromClass([obj class]) isEqualToString:@"BattleHomeController"]) {
                        willJumpController = obj;
                    }
                }];

                if (willJumpController) {
                    [weakSelf.navigationController popToViewController:willJumpController animated:YES];
                }else{
                    [weakSelf popController];
                }
            } onError:^(NSError *error) {
                [weakSelf showFailureMessage:error.domain];
                [_uploadHud hideAnimated:YES];
            } translater:nil];

        }else{
            [BattleEngine uploadPhotoToBattleWithImage:[self resizeImage:self.chooseImage] type:self.chooseType progress:^(NSProgress *progress) {
                _uploadHud.progress = (progress.completedUnitCount * 1.f / progress.totalUnitCount * 1.f);
                NSLog(@"current = %f",progress.completedUnitCount * 1.f / progress.totalUnitCount * 1.f);
            } onComplete:^(id responseResult) {

                [_uploadHud hideAnimated:YES];
                [weakSelf showSuccessMessage:@"Upload Success!"];

                __block UIViewController *willJumpController;
                [weakSelf.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

                    if ([NSStringFromClass([obj class]) isEqualToString:@"BattleHomeController"]) {
                        willJumpController = obj;
                    }
                }];

                if (willJumpController) {
                    [weakSelf.navigationController popToViewController:willJumpController animated:YES];
                }else{
                    [weakSelf popController];
                }

            } onError:^(NSError *error) {
                [weakSelf showFailureMessage:error.domain];
                [_uploadHud hideAnimated:YES];
            } translater:nil];
        }

    }];

    [[_cancelButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self popControllerWithAnimatiom:NavigationTransAnimationUpToDown];
    }];

}

//
//UIImage *willUploadImage = [self resizeImage:image];
//
///**
// *  上传头像
// *
// *  @param 50 size
// */
////    UIImage *scaleImage = [imageToUse imageByResizeToSize:CGSizeMake(200, 200)];
////
////    [[_viewModel updateUserProfileWithAvatar:scaleImage] subscribeNext:^(id x) {
////        AppUser *user = [UserManager sharedManager].curUser;
////        user.avatarUrl = x;
////
////    } error:^(NSError *error) {
////        [self showFailureMessage:error.domain];
////    }];
//}

- (UIImage *)resizeImage:(UIImage *)image{
    UIImage *newImage = image;
    float scaleX = image.size.width / 800.f;
    if (scaleX > 1.f) {
        newImage = [image scaleToSize:CGSizeMake(image.size.width / scaleX, image.size.height / scaleX)];
    }

    float scaleY = newImage.size.height / 1000.f;
    if (scaleY > 1.f) {
        newImage = [newImage scaleToSize:CGSizeMake(newImage.size.width / scaleY, newImage.size.height / scaleY)];
    }
    return newImage;
}

@end


text:
{{ splash.header_text }}

        <splash-designer-form access="{{splash.primary_access_id}}" btntext="{{ splash.btn_text }}"></splash-designer-form>

By logging in, you agree to our terms of use

{{splash.address}}

{{ splash.website }}


text:
package com.palmelf.eoffice.dao.hrm;

import com.palmelf.core.dao.BaseDao;
import com.palmelf.core.web.paging.PagingBean;
import com.palmelf.eoffice.model.hrm.SalaryItem;

import java.util.List;

public abstract interface SalaryItemDao extends BaseDao<SalaryItem> {
	public abstract List<SalaryItem> getAllExcludeId(String paramString,
			PagingBean paramPagingBean);
}


text:
<?php

namespace models\commands;

use libraries\palaso\CodeGuard;

class ProjectCommands
{

	/**
	 * @param array $projectIds
	 * @return int Total number of projects removed.
	 */
	public static function deleteProjects($projectIds) {
		CodeGuard::checkTypeAndThrow($projectIds, 'array');
		$count = 0;
		foreach ($projectIds as $projectId) {
			CodeGuard::checkTypeAndThrow($projectId, 'string');
			$project = new \models\ProjectModel($projectId);
			$project->remove();
			$count++;
		}
		return $count;
	}

	public static function renameProject($projectId, $oldName, $newName) {
		// TODO: Write this. (Move renaming logic over from sf->project_update). RM 2013-08
	}

}

?>


text:
from datetime import datetime
import unittest2 as unittest

from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.thirdparty.mock import Mock
from webkitpy.tool.bot.feeders import *
from webkitpy.tool.mocktool import MockTool

class FeedersTest(unittest.TestCase):
    def test_commit_queue_feeder(self):
        feeder = CommitQueueFeeder(MockTool())
        expected_logs = """Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com)
Warning, attachment 10001 on bug 50000 has invalid committer (non-committer@example.com)
MOCK setting flag 'commit-queue' to '-' on attachment '10001' with comment 'Rejecting attachment 10001 from commit-queue.\n\nnon-committer@example.com does not have committer permissions according to http://trac.webkit.org/browser/trunk/Tools/Scripts/webkitpy/common/config/committers.py.

- If you do not have committer rights please read http://webkit.org/coding/contributing.html for instructions on how to use bugzilla flags.

- If you have committer rights please correct the error in Tools/Scripts/webkitpy/common/config/committers.py by adding yourself to the file (no review needed).  The commit-queue restarts itself every 2 hours.  After restart the commit-queue will correctly respect your committer rights.'
MOCK: update_work_items: commit-queue [10005, 10000]
Feeding commit-queue items [10005, 10000]
"""
        OutputCapture().assert_outputs(self, feeder.feed, expected_logs=expected_logs)

    def _mock_attachment(self, is_rollout, attach_date):
        attachment = Mock()
        attachment.is_rollout = lambda: is_rollout
        attachment.attach_date = lambda: attach_date
        return attachment

    def test_patch_cmp(self):
        long_ago_date = datetime(1900, 1, 21)
        recent_date = datetime(2010, 1, 21)
        attachment1 = self._mock_attachment(is_rollout=False, attach_date=recent_date)
        attachment2 = self._mock_attachment(is_rollout=False, attach_date=long_ago_date)
        attachment3 = self._mock_attachment(is_rollout=True, attach_date=recent_date)
        attachment4 = self._mock_attachment(is_rollout=True, attach_date=long_ago_date)
        attachments = [attachment1, attachment2, attachment3, attachment4]
        expected_sort = [attachment4, attachment3, attachment2, attachment1]
        queue = CommitQueueFeeder(MockTool())
        attachments.sort(queue._patch_cmp)
        self.assertEqual(attachments, expected_sort)

    def test_patches_with_acceptable_review_flag(self):
        class MockPatch(object):
            def __init__(self, patch_id, review):
                self.id = patch_id
                self.review = lambda: review

        feeder = CommitQueueFeeder(MockTool())
        patches = [MockPatch(1, None), MockPatch(2, '-'), MockPatch(3, "+")]
        self.assertEqual([patch.id for patch in feeder._patches_with_acceptable_review_flag(patches)], [1, 3])


text:
@interface PodsDummy_Pods_SwiftySensors_tvOS : NSObject
@end
@implementation PodsDummy_Pods_SwiftySensors_tvOS
@end


text:
<?php

namespace BL\SGIBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use BL\SGIBundle\Entity\FieldsTrackAltinv;
use BL\SGIBundle\Form\FieldsTrackAltinvType;

/**
 * FieldsTrackAltinv controller.
 *
 * @Route("/fieldstrackaltinv")
 */
class FieldsTrackAltinvController extends Controller
{
    /**
     * Lists all FieldsTrackAltinv entities.
     *
     * @Route("/", name="fieldstrackaltinv_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $fieldsTrackAltinvs = $em->getRepository('SGIBundle:FieldsTrackAltinv')->findAll();

        return $this->render('fieldstrackaltinv/index.html.twig', array(
            'fieldsTrackAltinvs' => $fieldsTrackAltinvs,
        ));
    }

    /**
     * Creates a new FieldsTrackAltinv entity.
     *
     * @Route("/new", name="fieldstrackaltinv_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $fieldsTrackAltinv = new FieldsTrackAltinv();
        $form = $this->createForm('BL\SGIBundle\Form\FieldsTrackAltinvType', $fieldsTrackAltinv);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($fieldsTrackAltinv);
            $em->flush();

            return $this->redirectToRoute('fieldstrackaltinv_show', array('id' => $fieldstrackaltinv->getId()));
        }

        return $this->render('fieldstrackaltinv/new.html.twig', array(
            'fieldsTrackAltinv' => $fieldsTrackAltinv,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a FieldsTrackAltinv entity.
     *
     * @Route("/{id}", name="fieldstrackaltinv_show")
     * @Method("GET")
     */
    public function showAction(FieldsTrackAltinv $fieldsTrackAltinv)
    {
        $deleteForm = $this->createDeleteForm($fieldsTrackAltinv);

        return $this->render('fieldstrackaltinv/show.html.twig', array(
            'fieldsTrackAltinv' => $fieldsTrackAltinv,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing FieldsTrackAltinv entity.
     *
     * @Route("/{id}/edit", name="fieldstrackaltinv_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, FieldsTrackAltinv $fieldsTrackAltinv)
    {
        $deleteForm = $this->createDeleteForm($fieldsTrackAltinv);
        $editForm = $this->createForm('BL\SGIBundle\Form\FieldsTrackAltinvType', $fieldsTrackAltinv);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($fieldsTrackAltinv);
            $em->flush();

            return $this->redirectToRoute('fieldstrackaltinv_edit', array('id' => $fieldsTrackAltinv->getId()));
        }

        return $this->render('fieldstrackaltinv/edit.html.twig', array(
            'fieldsTrackAltinv' => $fieldsTrackAltinv,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a FieldsTrackAltinv entity.
     *
     * @Route("/{id}", name="fieldstrackaltinv_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, FieldsTrackAltinv $fieldsTrackAltinv)
    {
        $form = $this->createDeleteForm($fieldsTrackAltinv);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($fieldsTrackAltinv);
            $em->flush();
        }

        return $this->redirectToRoute('fieldstrackaltinv_index');
    }

    /**
     * Creates a form to delete a FieldsTrackAltinv entity.
     *
     * @param FieldsTrackAltinv $fieldsTrackAltinv The FieldsTrackAltinv entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(FieldsTrackAltinv $fieldsTrackAltinv)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('fieldstrackaltinv_delete', array('id' => $fieldsTrackAltinv->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }
}


text:
<?php

namespace PhpCollection;

/**
 * Implementation for ObjectBasics for entity-like objects.
 *
 * Two objects are considered equal if they refer to the same instance.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
trait EntityLikeObject
{
    public function hash()
    {
        return spl_object_hash($this);
    }

    public function equals(ObjectBasics $other)
    {
        return $this === $other;
    }
}


text:
/*
 *
 * Upvote
 *
 */

import { FC, memo } from 'react'

import { buildLog } from '@/utils/logger'

import AnimatedCount from '@/widgets/AnimatedCount'
import UpvoteBtn from './UpvoteBtn'

import { Wrapper, UpWrapper, CountWrapper } from './styles/blog_list_layout'

/* eslint-disable-next-line */
const log = buildLog('c:Upvote:index')

type TProps = {
  testid?: string
  count?: number
  viewerHasUpvoted?: boolean
  onAction?: (viewerHasUpvoted: boolean) => void
}

const Upvote: FC<TProps> = ({
  testid = 'upvote',
  count = 0,
  viewerHasUpvoted = false,
  onAction = log,
}) => {
  return (
    <Wrapper testid={testid}>
      <UpWrapper>
        <UpvoteBtn
          viewerHasUpvoted={viewerHasUpvoted}
          onAction={onAction}
          count={count}
        />
      </UpWrapper>
      <CountWrapper>
        <AnimatedCount count={count} active={viewerHasUpvoted} />
      </CountWrapper>
    </Wrapper>
  )
}

export default memo(Upvote)