text:
package se.ranzdo.bukkit.methodcommand;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;

public class RegisteredCommand {
	private String label;
	private RegisteredCommand parent;
	private String description;
	private String[] permissions;
	private boolean onlyPlayers;
	private Method method;
	private Object methodInstance;
	private CommandHandler handler;

	private boolean set = false;

	private ArrayList<ExecutableArgument> methodArguments = new ArrayList<ExecutableArgument>();
	private ArrayList<CommandArgument> arguments = new ArrayList<CommandArgument>();
	private ArrayList<RegisteredCommand> suffixes = new ArrayList<RegisteredCommand>();
	private ArrayList<Flag> flags = new ArrayList<Flag>();
	private WildcardArgument wildcard;
	private Map<String, Flag> flagsByName = new LinkedHashMap<String, Flag>();
	private Map<String, RegisteredCommand> suffixesByName = new HashMap<String, RegisteredCommand>();

	RegisteredCommand(String label, CommandHandler handler, RegisteredCommand parent) {
		this.label = label;
		this.handler = handler;
		this.parent = parent;
	}

	void addSuffixCommand(String suffix, RegisteredCommand command) {
		suffixesByName.put(suffix.toLowerCase(), command);
		suffixes.add(command);
	}

	boolean doesSuffixCommandExist(String suffix) {
		return suffixesByName.get(suffix) != null;
	}

	void execute(CommandSender sender, String[] args) {
		if(!testPermission(sender)) {
			sender.sendMessage(ChatColor.RED+"You do not have permission to do this!");
			return;
		}

		if(args.length > 0) {
			String suffixLabel = args[0].toLowerCase();
			if(suffixLabel.equals(handler.getHelpSuffix())) {
				sendHelpMessage(sender);
				return;
			}

			RegisteredCommand command = suffixesByName.get(suffixLabel);
			if(command == null) {
				executeMethod(sender, args);
			}
			else {
				String[] nargs = new String[args.length-1];
				System.arraycopy(args, 1, nargs, 0, args.length-1);
				command.execute(sender, nargs);
			}
		}
		else
			executeMethod(sender, args);

	}

	private void executeMethod(CommandSender sender, String[] args) {
		if(!set) {
			sendHelpMessage(sender);
			return;
		}

		ArrayList<Object> resultArgs = new ArrayList<Object>();
		resultArgs.add(sender);

		Arguments arguments;
		try {
			arguments = new Arguments(args, flagsByName);
		} catch (CommandError e) {
			sender.sendMessage(e.getColorizedMessage());
			return;
		}

		for(ExecutableArgument ea : this.methodArguments) {
			try {
				resultArgs.add(ea.execute(sender, arguments));
			} catch (CommandError e) {
				sender.sendMessage(e.getColorizedMessage());
				if(e.showUsage())
					sender.sendMessage(getUsage());
				return;
			}
		}

		try {
			try {
				method.invoke(methodInstance, resultArgs.toArray());
			}
			catch(InvocationTargetException e) {
				if(e.getCause() instanceof CommandError) {
					CommandError ce = (CommandError)e.getCause();
					sender.sendMessage(ce.getColorizedMessage());
					if(ce.showUsage())
						sender.sendMessage(getUsage());
				}
				else
					throw e;
			}
		} catch (Exception e) {
			sender.sendMessage(ChatColor.RED+"An internal error occurred while attempting to perform this command.");
			e.printStackTrace();
		}
	}

	private ArgumentHandler<?> getArgumenHandler(Class<?> argumentClass) {
		ArgumentHandler<?> argumentHandler = handler.getArgumentHandler(argumentClass);

		if(argumentHandler == null)
			throw new RegisterCommandMethodException(method, "Could not find a ArgumentHandler for ("+argumentClass.getName()+")");

		return argumentHandler;
	}

	public List<CommandArgument> getArguments() {
		return arguments;
	}

	public String getDescription() {
		return description;
	}

	public List<Flag> getFlags() {
		return flags;
	}

	public String[] getHelpMessage() {
		return handler.getHelpHandler().getHelpMessage(this);
	}

	public String getLabel() {
		return label;
	}

	public RegisteredCommand getParent() {
		return parent;
	}

	public String[] getPermissions() {
		return permissions;
	}

	public RegisteredCommand getSuffixCommand(String suffix) {
		return suffixesByName.get(suffix);
	}

	public List<RegisteredCommand> getSuffixes() {
		return suffixes;
	}

	public String getUsage() {
		return handler.getHelpHandler().getUsage(this);
	}

	public WildcardArgument getWildcard() {
		return wildcard;
	}

	public boolean isOnlyPlayers() {
		return onlyPlayers;
	}

	public boolean isSet() {
		return set;
	}

	public boolean onlyPlayers() {
		return onlyPlayers;
	}

	public void sendHelpMessage(CommandSender sender) {
		sender.sendMessage(getHelpMessage());
	}

	void set(Object methodInstance, Method method) {
		this.methodInstance = methodInstance;
		this.method = method;
		method.setAccessible(true);
		Command command = method.getAnnotation(Command.class);
		Flags flagsAnnotation = method.getAnnotation(Flags.class);
		this.description = command.description();
		this.permissions = command.permissions();
		this.onlyPlayers = command.onlyPlayers();

		Class<?>[] methodParameters = method.getParameterTypes();

		if(methodParameters.length == 0 ? true : !CommandSender.class.isAssignableFrom(methodParameters[0]))
			throw new RegisterCommandMethodException(method, "The first parameter in the command method must be assignable to the CommandSender interface.");

		if(flagsAnnotation != null) {
			String[] flags = flagsAnnotation.identifier();
			String[] flagdescriptions = flagsAnnotation.description();

			for(int i = 0; i < flags.length; i++) {
				Flag flag = new Flag(flags[i], i < flagdescriptions.length ? flagdescriptions[i] : "");
				this.flagsByName.put(flags[i], flag);
				this.flags.add(flag);
			}
		}

		Annotation[][] parameterAnnotations = method.getParameterAnnotations();

		for(int i = 1; i < methodParameters.length;i++) {

			//Find the CommandArgument annotation
			Arg commandArgAnnotation = null;
			for(Annotation annotation : parameterAnnotations[i]) {
				if(annotation.annotationType() == Arg.class)  {
					commandArgAnnotation = (Arg) annotation;
				}
			}

			//Find the FlagArg annotation
			FlagArg flagArgAnnotation = null;
			for(Annotation annotation : parameterAnnotations[i]) {
				if(annotation.annotationType() == FlagArg.class)  {
					flagArgAnnotation = (FlagArg) annotation;
				}
			}

			//If neither does not exist throw
			if(commandArgAnnotation == null && flagArgAnnotation == null)
				throw new RegisterCommandMethodException(method, "The command annonation is present on a method, however one of the parameters is not annotated.");

			Flag flag = null;

			if(flagArgAnnotation != null) {
				flag = this.flagsByName.get(flagArgAnnotation.value());
				if(flag == null)
					throw new RegisterCommandMethodException(method, "The flag annonation is present on a parameter, however the flag is not defined in the flags annonation.");
			}

			Class<?> argumentClass = methodParameters[i];

			if(commandArgAnnotation == null) {
				if(argumentClass != boolean.class && argumentClass != Boolean.class)
					throw new RegisterCommandMethodException(method, "The flag annonation is present on a parameter without the arg annonation, however the parameter type is not an boolean.");

				methodArguments.add(flag);

				continue;
			}

			if(flagArgAnnotation == null) {
				CommandArgument argument;
				if(i == methodParameters.length-1) {
					//Find the Wildcard annotation
					Wildcard wildcard = null;
					for(Annotation annotation : parameterAnnotations[i]) {
						if(annotation.annotationType() == Wildcard.class)  {
							wildcard = (Wildcard) annotation;
						}
					}

					if(wildcard != null) {
						boolean join = wildcard.join();
						if(!join) {
							argumentClass = argumentClass.getComponentType();
							if(argumentClass == null)
								throw new RegisterCommandMethodException(method, "The wildcard argument needs to be an array if join is false.");
						}
						this.wildcard = new WildcardArgument(commandArgAnnotation, argumentClass, getArgumenHandler(argumentClass), join);
						argument = this.wildcard;

					}
					else {
						argument = new CommandArgument(commandArgAnnotation, argumentClass, getArgumenHandler(argumentClass));
						arguments.add(argument);
					}
				}
				else {
					argument = new CommandArgument(commandArgAnnotation, argumentClass, getArgumenHandler(argumentClass));
					arguments.add(argument);
				}

				methodArguments.add(argument);
			}
			else {
				FlagArgument argument = new FlagArgument(commandArgAnnotation, argumentClass, getArgumenHandler(argumentClass), flag);
				methodArguments.add(argument);
				flag.addArgument(argument);
			}
		}

		this.set = true;
	}

	public boolean testPermission(CommandSender sender) {
		if(!set)
			return true;

		return handler.getPermissionHandler().hasPermission(sender, permissions);
	}

}


text:
package org.apache.bookkeeper.stats;

import com.codahale.metrics.Timer;
import com.codahale.metrics.MetricRegistry;
import static com.codahale.metrics.MetricRegistry.name;

public class CodahaleStatsLogger implements StatsLogger {
    protected final String basename;
    final MetricRegistry metrics;

    CodahaleStatsLogger(MetricRegistry metrics, String basename) {
        this.metrics = metrics;
        this.basename = basename;
    }

    @Override
    public OpStatsLogger getOpStatsLogger(String statName) {
        Timer success = metrics.timer(name(basename, statName));
        Timer failure = metrics.timer(name(basename, statName+"-fail"));
        return new CodahaleOpStatsLogger(success, failure);
    }

    @Override
    public Counter getCounter(String statName) {
        final com.codahale.metrics.Counter c = metrics.counter(name(basename, statName));
        return new Counter() {
            @Override
            public synchronized void clear() {
                long cur = c.getCount();
                c.dec(cur);
            }

            @Override
            public Long get() {
                return c.getCount();
            }

            @Override
            public void inc() {
                c.inc();
            }

            @Override
            public void dec() {
                c.dec();
            }

            @Override
            public void add(long delta) {
                c.inc(delta);
            }
        };
    }

    @Override
    public <T extends Number> void registerGauge(final String statName, final Gauge<T> gauge) {
        String metricName = name(basename, statName);
        metrics.remove(metricName);

        metrics.register(metricName, new com.codahale.metrics.Gauge<T>() {
                @Override
                public T getValue() {
                    return gauge.getSample();
                }
            });
    }

    @Override
    public <T extends Number> void unregisterGauge(String statName, Gauge<T> gauge) {
        // do nothing right now as the Codahale doesn't support conditional removal
    }

    private String scopeName(String scope) {
        String scopeName;
        if (0 == basename.length()) {
            scopeName = scope;
        } else {
            scopeName = name(basename, scope);
        }
        return scopeName;
    }

    @Override
    public StatsLogger scope(String scope) {
        return new CodahaleStatsLogger(metrics, scopeName(scope));
    }

    @Override
    public void removeScope(String name, StatsLogger statsLogger) {
        // no-op. the codahale stats logger doesn't the references for stats logger.
    }
}

redpajama_set_name: RedPajamaGithub


text:
Participants
------------------------------

.. automodule:: google.cloud.dialogflow_v2beta1.services.participants
    :members:
    :inherited-members:

.. automodule:: google.cloud.dialogflow_v2beta1.services.participants.pagers
    :members:
    :inherited-members:


text:
package au.gov.dto.dibp.appointments.qflowintegration;

import au.gov.dto.dibp.appointments.util.ResponseWrapper;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import org.junit.Test;

import java.util.HashMap;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

public class DefaultApiCallsSenderServiceTest {
    private static final String SUCCESSFUL_RESPONSE =
            "<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\">\n" +
            "   <s:Header/>\n" +
            "   <s:Body>\n" +
            "      <GetByPersonalIdResponse xmlns=\"http://www.qnomy.com/Services\">\n" +
            "         <GetByPersonalIdResult xmlns:b=\"http://schemas.datacontract.org/2004/07/QFlow.Library\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
            "            <b:Active>true</b:Active>\n" +
            "            <b:PersonalId>11111111111</b:PersonalId>\n" +
            "            <b:Id>1</b:Id>\n" +
            "            <b:Name>Lastname Firstname</b:Name>\n" +
            "            <b:EMail>noemail@test.com</b:EMail>\n" +
            "            <b:TelNumber1>0400000000</b:TelNumber1>" +
            "            <b:FirstName>Firstname</b:FirstName>\n" +
            "            <b:LastName>Lastname</b:LastName>\n" +
            "         </GetByPersonalIdResult>\n" +
            "      </GetByPersonalIdResponse>\n" +
            "   </s:Body>\n" +
            "</s:Envelope>";

    private static final String INVALID_SESSION_ID_RESPONSE =
            "<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\">\n" +
                    "    <s:Header>\n" +
                    "        <a:Action s:mustUnderstand=\"1\">http://www.qnomy.com/Services/IsvcCalendar/GetDynamicSuggestedSlots2QFlowAPISecurityExceptionFault\n" +
                    "        </a:Action>\n" +
                    "        <a:RelatesTo>urn:uuid:0c7958a0-a7d7-496c-b37b-af8c5778e00f</a:RelatesTo>\n" +
                    "    </s:Header>\n" +
                    "    <s:Body>\n" +
                    "        <s:Fault>\n" +
                    "            <s:Code>\n" +
                    "                <s:Value>s:Sender</s:Value>\n" +
                    "            </s:Code>\n" +
                    "            <s:Reason>\n" +
                    "                <s:Text xml:lang=\"en-US\">The current session was terminated by the server. (Invalid Session ID)</s:Text>\n" +
                    "            </s:Reason>\n" +
                    "            <s:Detail>\n" +
                    "                <QFlowAPISecurityException xmlns=\"http://schemas.datacontract.org/2004/07/QFlow.Web.API\">\n" +
                    "                    <ErrorType>InvalidAPISessionId</ErrorType>\n" +
                    "                </QFlowAPISecurityException>\n" +
                    "            </s:Detail>\n" +
                    "        </s:Fault>\n" +
                    "    </s:Body>\n" +
                    "</s:Envelope>";

    private static final String OTHER_ERROR_MESSAGE =
            "<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\">\n" +
                    "    <s:Header>\n" +
                    "        <a:Action s:mustUnderstand=\"1\">\n" +
                    "            http://www.qnomy.com/Services/IsvcCustomer/GetByPersonalIdQFlowAPIApplicationExceptionFault\n" +
                    "        </a:Action>\n" +
                    "        <a:RelatesTo>urn:uuid:f8cf6e26-2950-11e6-be23-6c40089d4690</a:RelatesTo>\n" +
                    "    </s:Header>\n" +
                    "    <s:Body>\n" +
                    "        <s:Fault>\n" +
                    "            <s:Code>\n" +
                    "                <s:Value>s:Sender</s:Value>\n" +
                    "            </s:Code>\n" +
                    "            <s:Reason>\n" +
                    "                <s:Text xml:lang=\"en-US\">Record not found</s:Text>\n" +
                    "            </s:Reason>\n" +
                    "            <s:Detail>\n" +
                    "                <QFlowAPIApplicationException xmlns=\"http://schemas.datacontract.org/2004/07/QFlow.Web.API\">\n" +
                    "                    <ErrorNumber>51010</ErrorNumber>\n" +
                    "                </QFlowAPIApplicationException>\n" +
                    "            </s:Detail>\n" +
                    "        </s:Fault>\n" +
                    "    </s:Body>\n" +
                    "</s:Envelope>";

    @Test
    public void sendsSigninThenRequestThenSignoutOnSuccess() throws Exception {
        StubApiSessionService apiSessionService = new StubApiSessionService();
        StubHttpClientAlwaysSuccessful httpClient = new StubHttpClientAlwaysSuccessful();
        ApiCallsSenderService service = new DefaultApiCallsSenderService(apiSessionService, httpClient);
        Template template = Mustache.compiler().compile("template");

        ResponseWrapper response = service.sendRequest(template, new HashMap<>(), "serviceAddress");

        assertThat(response.getCode(), equalTo(200));
        assertThat(apiSessionService.getNumberOfSessionsCreated(), equalTo(1));
        assertThat(apiSessionService.getNumberOfSessionsClosed(), equalTo(1));
    }

    @Test
    public void retriesSigninOnInvalidSessionIdResponse() throws Exception {
        StubApiSessionService apiSessionService = new StubApiSessionService();
        StubHttpClientInvalidSessionIdButEventuallySuccessful httpClient = new StubHttpClientInvalidSessionIdButEventuallySuccessful(DefaultApiCallsSenderService.MAX_ATTEMPTS);
        ApiCallsSenderService service = new DefaultApiCallsSenderService(apiSessionService, httpClient);
        Template template = Mustache.compiler().compile("");

        ResponseWrapper response = service.sendRequest(template, new HashMap<>(), "serviceAddress");

        assertThat(response.getCode(), equalTo(200));
        assertThat(response.getMessage(), equalTo(SUCCESSFUL_RESPONSE));
        assertThat(apiSessionService.getNumberOfSessionsCreated(), equalTo(DefaultApiCallsSenderService.MAX_ATTEMPTS));
        assertThat(apiSessionService.getNumberOfSessionsClosed(), equalTo(DefaultApiCallsSenderService.MAX_ATTEMPTS));
    }

    @Test
    public void givesUpAfterMaxRetriesSOnInvalidSessionIdResponse() throws Exception {
        StubApiSessionService apiSessionService = new StubApiSessionService();
        StubHttpClientInvalidSessionIdButEventuallySuccessful httpClient = new StubHttpClientInvalidSessionIdButEventuallySuccessful(DefaultApiCallsSenderService.MAX_ATTEMPTS + 1);
        ApiCallsSenderService service = new DefaultApiCallsSenderService(apiSessionService, httpClient);
        Template template = Mustache.compiler().compile("");

        ResponseWrapper response = service.sendRequest(template, new HashMap<>(), "serviceAddress");

        assertThat(response.getCode(), equalTo(500));
        assertThat(response.getMessage(), equalTo(INVALID_SESSION_ID_RESPONSE));
        assertThat(apiSessionService.getNumberOfSessionsCreated(), equalTo(DefaultApiCallsSenderService.MAX_ATTEMPTS));
        assertThat(apiSessionService.getNumberOfSessionsClosed(), equalTo(DefaultApiCallsSenderService.MAX_ATTEMPTS));
    }

    @Test(expected = ApiResponseNotSuccessfulException.class)
    public void doesNotRetrySigninOnOtherErrorResponse() throws Exception {
        StubApiSessionService apiSessionService = new StubApiSessionService();
        StubHttpClientOtherError httpClient = new StubHttpClientOtherError();
        ApiCallsSenderService service = new DefaultApiCallsSenderService(apiSessionService, httpClient);
        Template template = Mustache.compiler().compile("");

        service.sendRequest(template, new HashMap<>(), "serviceAddress");
    }

    private static class StubApiSessionService extends ApiSessionService {
        private int numberOfSessionsCreated;
        private int numberOfSessionsClosed;

        private StubApiSessionService() {
            super(null, null);
        }

        @Override
        public ApiSession createSession() {
            numberOfSessionsCreated++;
            return new ApiSession("apiSessionId", "userId");
        }

        @Override
        public void closeSession(String apiSessionId) {
            numberOfSessionsClosed++;
        }

        int getNumberOfSessionsCreated() {
            return numberOfSessionsCreated;
        }

        int getNumberOfSessionsClosed() {
            return numberOfSessionsClosed;
        }
    }

    private static class StubHttpClientAlwaysSuccessful extends HttpClient {
        @Override
        public ResponseWrapper post(String url, String messageBody, String messageId) {
            return new ResponseWrapper(200, SUCCESSFUL_RESPONSE);
        }
    }

    private class StubHttpClientInvalidSessionIdButEventuallySuccessful extends HttpClient {
        private final int numberOfFailures;
        private int numberOfRequestsSent = 0;

        StubHttpClientInvalidSessionIdButEventuallySuccessful(int numberOfFailures) {
            this.numberOfFailures = numberOfFailures;
        }

        @Override
        public ResponseWrapper post(String url, String messageBody, String messageId) {
            numberOfRequestsSent++;
            if (numberOfRequestsSent >= numberOfFailures) {
                return new ResponseWrapper(200, SUCCESSFUL_RESPONSE);
            }
            return new ResponseWrapper(500, INVALID_SESSION_ID_RESPONSE);
        }
    }

    private class StubHttpClientOtherError extends HttpClient {
        @Override
        public ResponseWrapper post(String url, String messageBody, String messageId) {
            return new ResponseWrapper(500, OTHER_ERROR_MESSAGE);
        }
    }
}


text:
package fm.last.moji.tracker.impl;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import fm.last.moji.tracker.Destination;
import fm.last.moji.tracker.TrackerException;

@RunWith(MockitoJUnitRunner.class)
public class CreateOpenOperationTest {

  private static final String DOMAIN = "domain";
  private static final String STORAGE_CLASS = "storageClass";
  private static final String KEY = "key";
  private static final String FID = "5";
  private static final String DEV_COUNT = "2";
  private static final String PATH_1 = "http://www.last.fm/1/";
  private static final String DEV_ID_1 = "1";
  private static final String PATH_2 = "http://www.last.fm/2/";
  private static final String DEV_ID_2 = "2";

  @Mock
  private RequestHandler mockRequestHandler;
  @Mock
  private Response mockResponse;
  @Mock
  private Response mockEmptyResponse;
  @Mock
  private Response mockUnknownKeyResponse;
  @Mock
  private Response mockFailResponse;

  private ArgumentCaptor<Request> captorRequest;
  private CreateOpenOperation operation;

  @Before
  public void setUp() throws TrackerException {
    captorRequest = ArgumentCaptor.forClass(Request.class);
    when(mockResponse.getStatus()).thenReturn(ResponseStatus.OK);
    when(mockResponse.getValue("fid")).thenReturn(FID);
    when(mockResponse.getValue("dev_count")).thenReturn(DEV_COUNT);
    when(mockResponse.getValue("path_1")).thenReturn(PATH_1);
    when(mockResponse.getValue("devid_1")).thenReturn(DEV_ID_1);
    when(mockResponse.getValue("path_2")).thenReturn(PATH_2);
    when(mockResponse.getValue("devid_2")).thenReturn(DEV_ID_2);

    when(mockEmptyResponse.getStatus()).thenReturn(ResponseStatus.OK);
    when(mockEmptyResponse.getValue("fid")).thenReturn(FID);
    when(mockEmptyResponse.getValue("dev_count")).thenReturn("0");

    when(mockUnknownKeyResponse.getStatus()).thenReturn(ResponseStatus.ERROR);
    when(mockUnknownKeyResponse.getMessage()).thenReturn("unknown_key unknown key");

    when(mockFailResponse.getStatus()).thenReturn(ResponseStatus.ERROR);
    when(mockFailResponse.getMessage()).thenReturn("unexpected error");
  }

  @Test
  public void requestNormal() throws TrackerException, MalformedURLException {
    when(mockRequestHandler.performRequest(captorRequest.capture())).thenReturn(mockResponse);

    operation = new CreateOpenOperation(mockRequestHandler, DOMAIN, KEY, STORAGE_CLASS, true);
    operation.execute();

    Request request = captorRequest.getValue();
    assertThat(request.getCommand(), is("create_open"));
    assertThat(request.getArguments().size(), is(4));
    assertThat(request.getArguments().get("domain"), is(DOMAIN));
    assertThat(request.getArguments().get("class"), is(STORAGE_CLASS));
    assertThat(request.getArguments().get("key"), is(KEY));
    assertThat(request.getArguments().get("multi_dest"), is("1"));
  }

  @Test
  public void requestNormalNoClass() throws TrackerException, MalformedURLException {
    when(mockRequestHandler.performRequest(captorRequest.capture())).thenReturn(mockResponse);

    operation = new CreateOpenOperation(mockRequestHandler, DOMAIN, KEY, null, true);
    operation.execute();

    Request request = captorRequest.getValue();
    assertThat(request.getCommand(), is("create_open"));
    assertThat(request.getArguments().size(), is(3));
    assertThat(request.getArguments().get("domain"), is(DOMAIN));
    assertThat(request.getArguments().get("key"), is(KEY));
    assertThat(request.getArguments().get("multi_dest"), is("1"));
  }

  @Test
  public void requestNormalNoMulti() throws TrackerException, MalformedURLException {
    when(mockRequestHandler.performRequest(captorRequest.capture())).thenReturn(mockResponse);

    operation = new CreateOpenOperation(mockRequestHandler, DOMAIN, KEY, "", false);
    operation.execute();

    Request request = captorRequest.getValue();
    assertThat(request.getCommand(), is("create_open"));
    assertThat(request.getArguments().size(), is(3));
    assertThat(request.getArguments().get("domain"), is(DOMAIN));
    assertThat(request.getArguments().get("key"), is(KEY));
    assertThat(request.getArguments().get("multi_dest"), is("0"));
  }

  @Test
  public void responseNormal() throws TrackerException, MalformedURLException {
    when(mockRequestHandler.performRequest(captorRequest.capture())).thenReturn(mockResponse);

    operation = new CreateOpenOperation(mockRequestHandler, DOMAIN, KEY, STORAGE_CLASS, true);
    operation.execute();

    List<Destination> destinations = operation.getDestinations();
    assertThat(destinations.size(), is(2));

    Destination destination1 = destinations.get(0);
    assertThat(destination1.getDevId(), is(1));
    assertThat(destination1.getFid(), is(5));
    assertThat(destination1.getPath(), is(new URL(PATH_1)));

    Destination destination2 = destinations.get(1);
    assertThat(destination2.getDevId(), is(2));
    assertThat(destination2.getFid(), is(5));
    assertThat(destination2.getPath(), is(new URL(PATH_2)));
  }

  @Test
  public void zeroDestinations() throws TrackerException {
    when(mockRequestHandler.performRequest(captorRequest.capture())).thenReturn(mockEmptyResponse);

    operation = new CreateOpenOperation(mockRequestHandler, DOMAIN, KEY, STORAGE_CLASS, true);
    operation.execute();

    List<Destination> destinations = operation.getDestinations();
    assertThat(destinations.size(), is(0));
  }

  @Test
  public void unknownKey() throws TrackerException {
    when(mockRequestHandler.performRequest(captorRequest.capture())).thenReturn(mockUnknownKeyResponse);

    operation = new CreateOpenOperation(mockRequestHandler, DOMAIN, KEY, STORAGE_CLASS, true);
    operation.execute();

    List<Destination> destinations = operation.getDestinations();
    assertThat(destinations.size(), is(0));
  }

  @Test(expected = TrackerException.class)
  public void unexpectedError() throws TrackerException {
    when(mockRequestHandler.performRequest(captorRequest.capture())).thenReturn(mockFailResponse);

    operation = new CreateOpenOperation(mockRequestHandler, DOMAIN, KEY, STORAGE_CLASS, true);
    operation.execute();
  }

}


text:
module RsrGroup
  class Catalog < Base

    def initialize(options = {})
      requires!(options, :username, :password)
      @options = options
    end

    def self.all(options = {})
      requires!(options, :username, :password)
      new(options).all
    end

    def all
      items = []

      connect(@options) do |ftp|
        begin
          tempfile = Tempfile.new

          if ftp.nlst.include?(KEYDEALER_DIR)
            ftp.chdir(KEYDEALER_DIR)
            ftp.getbinaryfile(KEYDEALER_CATALOG_FILENAME, tempfile.path)
          else
            ftp.chdir(DEFAULT_DIR)
            ftp.getbinaryfile(DEFAULT_CATALOG_FILENAME, tempfile.path)
          end
          ftp.close

          CSV.foreach(tempfile, { col_sep: ';', quote_char: "\x00" }).each do |row|
            item = process_row(row)

            if !row[12].nil? && row[12].to_sym.eql?(:Allocated)
              item[:quantity] = 0
            end

            items << item
          end
        end

        tempfile.unlink
      end

      items
    end

    private

    def sanitize(data)
      return data unless data.is_a?(String)
      data.strip
    end

    def process_row(row)
      category_name = row[3].nil? ? nil : RsrGroup::Department.new(row[3]).name

      {
        upc:             sanitize(row[1]),
        item_identifier: sanitize(row[0]),
        name:            sanitize(row[2]),
        model:           sanitize(row[9]),
        category:        category_name,
        brand:           sanitize(row[10]),
        msrp:            sanitize(row[5]),
        price:           sanitize(row[6]),
        map_price:       sanitize(row[70]),
        quantity:        (Integer(sanitize(row[8])) rescue 0),
        mfg_number:      sanitize(row[11]),
        weight:          sanitize(row[7]),
        short_description: sanitize(row[2]),
        long_description:  sanitize(row[13]),
        features: {
          shipping_length: sanitize(row[74]),
          shipping_width:  sanitize(row[75]),
          shipping_height: sanitize(row[76])
        }
      }
    end

  end
end


text:
@interface NSBezierPath (GTMBezierPathCGPathAdditions)

///  Extract a CGPathRef from a NSBezierPath.
//
//  Args:
//
//  Returns:
//    Converted CGPathRef. Must be released by client (CGPathRelease).
//    nil if failure.
- (CGPathRef)gtm_createCGPath;

@end


text:
namespace LevelGraph {
	class CVertex;
};

class CAI_ObjectLocation {
private:
	u32										m_level_vertex_id;
	GameGraph::_GRAPH_ID					m_game_vertex_id;

public:
	IC										CAI_ObjectLocation	();
	IC			void						init				();
	IC	virtual	void						reinit				();
	IC			void						game_vertex			(const GameGraph::CVertex	*game_vertex);
	IC			void						game_vertex			(const GameGraph::_GRAPH_ID	game_vertex_id);
	IC			const GameGraph::CVertex	*game_vertex		() const;
	IC			const GameGraph::_GRAPH_ID	game_vertex_id		() const;
	IC			void						level_vertex		(const LevelGraph::CVertex	*level_vertex);
	IC			void						level_vertex		(const u32					level_vertex_id);
	IC			const LevelGraph::CVertex	*level_vertex		() const;
	IC			const u32					level_vertex_id		() const;
};

#include "ai_object_location_inline.h"
#include "ai_object_location_impl.h" // alpet: èñïðàâëåíèå error LNK20**


text:
module Raven
  module Rails
    module ActionControllerCatcher

      def self.included(base)
        base.send(:alias_method, :rescue_action_in_public_without_raven, :rescue_action_in_public)
        base.send(:alias_method, :rescue_action_in_public, :rescue_action_in_public_with_raven)
        base.send(:alias_method, :rescue_action_locally_without_raven, :rescue_action_locally)
        base.send(:alias_method, :rescue_action_locally, :rescue_action_locally_with_raven)
      end

      private

      def rescue_action_in_public_with_raven(exception)
        evt = Raven::Event.capture_rack_exception(exception, request.env)
        Raven.send(evt) if evt
        rescue_action_in_public_without_raven(exception)
      end

      def rescue_action_locally_with_raven(exception)
        evt = Raven::Event.capture_rack_exception(exception, request.env)
        Raven.send(evt) if evt
        rescue_action_locally_without_raven(exception)
      end

    end
  end
end


text:
package edu.hm.hafner.analysis.parser.findbugs;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;

import edu.hm.hafner.analysis.parser.findbugs.FindBugsMessages.Pattern;

import static org.assertj.core.api.Assertions.*;

/**
 * Tests the class {@link FindBugsMessages}.
 */
class FindBugsMessagesTest {
    /** Bug ID for test. */
    private static final String NP_STORE_INTO_NONNULL_FIELD = "NP_STORE_INTO_NONNULL_FIELD";
    /** Expected number of patterns. */
    private static final int EXPECTED_PATTERNS = 458;
    /** Expected number of patterns in fb-contrib. */
    private static final int EXPECTED_CONTRIB_PATTERNS = 307;
    /** Expected number of patterns in find-sec-bugs. */
    private static final int EXPECTED_SECURITY_PATTERNS = 135;
    private static final String PATH_TRAVERSAL_IN = "PATH_TRAVERSAL_IN";

    @Test
    void shouldReadAllMessageFiles() {
        assertThat(new FindBugsMessages().size()).isEqualTo(
                EXPECTED_PATTERNS + EXPECTED_CONTRIB_PATTERNS + EXPECTED_SECURITY_PATTERNS);
    }

    @Test
    void shouldReadAllFindBugsMessages() {
        assertThat(readMessages("messages.xml")).hasSize(EXPECTED_PATTERNS);
    }

    @Test
    void shouldReadAllFindSecBugsMessages() {
        assertThat(readMessages("find-sec-bugs-messages.xml")).hasSize(EXPECTED_SECURITY_PATTERNS);
    }

    @Test
    void shouldReadAllFbContribMessages() {
        assertThat(readMessages("fb-contrib-messages.xml")).hasSize(EXPECTED_CONTRIB_PATTERNS);
    }

    @Test
    void shouldMapMessagesToTypes() {
        FindBugsMessages messages = new FindBugsMessages();
        String expectedMessage = "A value that could be null is stored into a field that has been annotated as @Nonnull.";
        assertThat(messages.getMessage(NP_STORE_INTO_NONNULL_FIELD))
                .contains(expectedMessage);

        assertThat(messages.getShortMessage(NP_STORE_INTO_NONNULL_FIELD))
                .isEqualTo("Store of null value into field annotated @Nonnull");

        assertThat(messages.getMessage("NMCS_NEEDLESS_MEMBER_COLLECTION_SYNCHRONIZATION"))
                .contains("This class defines a private collection member as synchronized. It appears");
        assertThat(messages.getShortMessage("NMCS_NEEDLESS_MEMBER_COLLECTION_SYNCHRONIZATION"))
                .isEqualTo("Class defines unneeded synchronization on member collection");
    }

    @Test
    void issue55707() {
        FindBugsMessages messages = new FindBugsMessages();
        assertThat(messages.getShortMessage(PATH_TRAVERSAL_IN))
                .isEqualTo("Potential Path Traversal (file read)");
        assertThat(messages.getMessage(PATH_TRAVERSAL_IN))
                .contains("A file is opened to read its content. The filename comes from an <b>input</b> parameter.");
    }

    private List<Pattern> readMessages(final String fileName) {
        try (InputStream file = read(fileName)) {
            return new FindBugsMessages().parse(file);
        }
        catch (IOException | SAXException e) {
            throw new AssertionError(e);
        }
    }

    private InputStream read(final String fileName) {
        return FindBugsMessages.class.getResourceAsStream(fileName);
    }
}


text:
var express = require('express');
var MemoryStore = express.session.MemoryStore;

var database = require('./database.js');

// Configuration
var config = {port: process.env.PORT || 8080};

//
var app = express.createServer();
app.configure(function(){
  app.set('view engine', 'jade');
  app.use(express.logger(':method :url :status'));
  app.use(express.bodyParser());
  app.use(express.cookieParser());
  app.use(express.query());
  app.use(express.favicon());
  app.use(express.static(__dirname + '/public', {maxAge: 3600000}));
  app.use(express.session({
      store: new MemoryStore({
          maxAge: 24 * 60 * 60 * 1000
      }),
    secret: "asdsa"
 }));
  app.use(app.router, database);

  app.use(function (req, res) {
    res.render("404", {currentCategory: "none"});
  });
});

var controllers = require('./controllers.js');
controllers.addControllers(app);

console.log("Running on port: " + config.port);
app.listen(config.port);


text:
namespace autofill {

std::ostream& operator<<(
    std::ostream& out,
    const PasswordRequirementsSpec::CharacterClass& character_class) {
  out << "{";
  if (character_class.has_character_set())
    out << "character_set: \"" << character_class.character_set() << "\", ";
  if (character_class.has_min())
    out << "min: " << character_class.min() << ", ";
  if (character_class.has_max())
    out << "max: " << character_class.max() << ", ";
  out << "}";
  return out;
}

std::ostream& operator<<(std::ostream& out,
                         const PasswordRequirementsSpec& spec) {
  out << "{";
  if (spec.has_priority())
    out << "priority: " << spec.priority() << ", ";
  if (spec.has_spec_version())
    out << "spec_version: " << spec.spec_version() << ", ";
  if (spec.has_min_length())
    out << "min_length: " << spec.min_length() << ", ";
  if (spec.has_max_length())
    out << "max_length: " << spec.max_length() << ", ";
  if (spec.has_lower_case())
    out << "lower_case: " << spec.lower_case() << ", ";
  if (spec.has_upper_case())
    out << "upper_case: " << spec.upper_case() << ", ";
  if (spec.has_alphabetic())
    out << "alphabetic: " << spec.alphabetic() << ", ";
  if (spec.has_numeric())
    out << "numeric: " << spec.alphabetic() << ", ";
  if (spec.has_symbols())
    out << "symbols: " << spec.symbols() << ", ";
  out << "}";
  return out;
}

}  // namespace autofill


text:
<?php

require_once dirname(__DIR__).'/vendor/autoload.php';
$baseDir = dirname(__DIR__);

use fkooman\Jwt\Keys\EdDSA\SecretKey;
use LC\Common\FileIO;

try {
    // generate OAuth key
    $configDir = sprintf('%s/config', $baseDir);
    $keyFile = sprintf('%s/oauth.key', $configDir);
    if (!FileIO::exists($keyFile)) {
        throw new Exception('unable to find "'.$keyFile.'"');
    }
    $secretKey = SecretKey::fromEncodedString(FileIO::readFile($keyFile));
    echo 'Public Key: '.$secretKey->getPublicKey()->encode().PHP_EOL;
} catch (Exception $e) {
    echo sprintf('ERROR: %s', $e->getMessage()).PHP_EOL;
    exit(1);
}


text:
#pragma once
#include <aws/nimble/NimbleStudio_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <aws/nimble/model/StudioState.h>
#include <aws/nimble/model/StudioStatusCode.h>
#include <aws/nimble/model/StudioEncryptionConfiguration.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace NimbleStudio
{
namespace Model
{

  /**
   *
Represents a studio resource.

A studio is the core resource used with
   * Nimble Studio. You must create a studio first, before any other resource type
   * can be created. All other resources you create and manage in Nimble Studio are
   * contained within a studio.

When creating a studio, you must provides two
   * IAM roles for use with the Nimble Studio portal. These roles are assumed by your
   * users when they log in to the Nimble Studio portal via IAM Identity Center and
   * your identity source.

The user role must have the
   * AmazonNimbleStudio-StudioUser managed policy attached for the portal to function
   * properly.

The admin role must have the AmazonNimbleStudio-StudioAdmin
   * managed policy attached for the portal to function properly.

Your studio
   * roles must trust the identity.nimble.amazonaws.com service principal to function
   * properly.

See Also:
   AWS API
   * Reference

   */
  class AWS_NIMBLESTUDIO_API Studio
  {
  public:
    Studio();
    Studio(Aws::Utils::Json::JsonView jsonValue);
    Studio& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The IAM role that studio admins assume when logging in to the Nimble Studio
     * portal.

     */
    inline const Aws::String& GetAdminRoleArn() const{ return m_adminRoleArn; }

    /**
     *
The IAM role that studio admins assume when logging in to the Nimble Studio
     * portal.

     */
    inline bool AdminRoleArnHasBeenSet() const { return m_adminRoleArnHasBeenSet; }

    /**
     *
The IAM role that studio admins assume when logging in to the Nimble Studio
     * portal.

     */
    inline void SetAdminRoleArn(const Aws::String& value) { m_adminRoleArnHasBeenSet = true; m_adminRoleArn = value; }

    /**
     *
The IAM role that studio admins assume when logging in to the Nimble Studio
     * portal.

     */
    inline void SetAdminRoleArn(Aws::String&& value) { m_adminRoleArnHasBeenSet = true; m_adminRoleArn = std::move(value); }

    /**
     *
The IAM role that studio admins assume when logging in to the Nimble Studio
     * portal.

     */
    inline void SetAdminRoleArn(const char* value) { m_adminRoleArnHasBeenSet = true; m_adminRoleArn.assign(value); }

    /**
     *
The IAM role that studio admins assume when logging in to the Nimble Studio
     * portal.

     */
    inline Studio& WithAdminRoleArn(const Aws::String& value) { SetAdminRoleArn(value); return *this;}

    /**
     *
The IAM role that studio admins assume when logging in to the Nimble Studio
     * portal.

     */
    inline Studio& WithAdminRoleArn(Aws::String&& value) { SetAdminRoleArn(std::move(value)); return *this;}

    /**
     *
The IAM role that studio admins assume when logging in to the Nimble Studio
     * portal.

     */
    inline Studio& WithAdminRoleArn(const char* value) { SetAdminRoleArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) that is assigned to a studio resource and
     * uniquely identifies it. ARNs are unique across all Regions.

     */
    inline const Aws::String& GetArn() const{ return m_arn; }

    /**
     *
The Amazon Resource Name (ARN) that is assigned to a studio resource and
     * uniquely identifies it. ARNs are unique across all Regions.

     */
    inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) that is assigned to a studio resource and
     * uniquely identifies it. ARNs are unique across all Regions.

     */
    inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; }

    /**
     *
The Amazon Resource Name (ARN) that is assigned to a studio resource and
     * uniquely identifies it. ARNs are unique across all Regions.

     */
    inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) that is assigned to a studio resource and
     * uniquely identifies it. ARNs are unique across all Regions.

     */
    inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) that is assigned to a studio resource and
     * uniquely identifies it. ARNs are unique across all Regions.

     */
    inline Studio& WithArn(const Aws::String& value) { SetArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) that is assigned to a studio resource and
     * uniquely identifies it. ARNs are unique across all Regions.

     */
    inline Studio& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) that is assigned to a studio resource and
     * uniquely identifies it. ARNs are unique across all Regions.

     */
    inline Studio& WithArn(const char* value) { SetArn(value); return *this;}

    /**
     *
The Unix epoch timestamp in seconds for when the resource was created.

     */
    inline const Aws::Utils::DateTime& GetCreatedAt() const{ return m_createdAt; }

    /**
     *
The Unix epoch timestamp in seconds for when the resource was created.

     */
    inline bool CreatedAtHasBeenSet() const { return m_createdAtHasBeenSet; }

    /**
     *
The Unix epoch timestamp in seconds for when the resource was created.

     */
    inline void SetCreatedAt(const Aws::Utils::DateTime& value) { m_createdAtHasBeenSet = true; m_createdAt = value; }

    /**
     *
The Unix epoch timestamp in seconds for when the resource was created.

     */
    inline void SetCreatedAt(Aws::Utils::DateTime&& value) { m_createdAtHasBeenSet = true; m_createdAt = std::move(value); }

    /**
     *
The Unix epoch timestamp in seconds for when the resource was created.

     */
    inline Studio& WithCreatedAt(const Aws::Utils::DateTime& value) { SetCreatedAt(value); return *this;}

    /**
     *
The Unix epoch timestamp in seconds for when the resource was created.

     */
    inline Studio& WithCreatedAt(Aws::Utils::DateTime&& value) { SetCreatedAt(std::move(value)); return *this;}

    /**
     *
A friendly name for the studio.

     */
    inline const Aws::String& GetDisplayName() const{ return m_displayName; }

    /**
     *
A friendly name for the studio.

     */
    inline bool DisplayNameHasBeenSet() const { return m_displayNameHasBeenSet; }

    /**
     *
A friendly name for the studio.

     */
    inline void SetDisplayName(const Aws::String& value) { m_displayNameHasBeenSet = true; m_displayName = value; }

    /**
     *
A friendly name for the studio.

     */
    inline void SetDisplayName(Aws::String&& value) { m_displayNameHasBeenSet = true; m_displayName = std::move(value); }

    /**
     *
A friendly name for the studio.

     */
    inline void SetDisplayName(const char* value) { m_displayNameHasBeenSet = true; m_displayName.assign(value); }

    /**
     *
A friendly name for the studio.

     */
    inline Studio& WithDisplayName(const Aws::String& value) { SetDisplayName(value); return *this;}

    /**
     *
A friendly name for the studio.

     */
    inline Studio& WithDisplayName(Aws::String&& value) { SetDisplayName(std::move(value)); return *this;}

    /**
     *
A friendly name for the studio.

     */
    inline Studio& WithDisplayName(const char* value) { SetDisplayName(value); return *this;}

    /**
     *
The Amazon Web Services Region where the studio resource is located.

     */
    inline const Aws::String& GetHomeRegion() const{ return m_homeRegion; }

    /**
     *
The Amazon Web Services Region where the studio resource is located.

     */
    inline bool HomeRegionHasBeenSet() const { return m_homeRegionHasBeenSet; }

    /**
     *
The Amazon Web Services Region where the studio resource is located.

     */
    inline void SetHomeRegion(const Aws::String& value) { m_homeRegionHasBeenSet = true; m_homeRegion = value; }

    /**
     *
The Amazon Web Services Region where the studio resource is located.

     */
    inline void SetHomeRegion(Aws::String&& value) { m_homeRegionHasBeenSet = true; m_homeRegion = std::move(value); }

    /**
     *
The Amazon Web Services Region where the studio resource is located.

     */
    inline void SetHomeRegion(const char* value) { m_homeRegionHasBeenSet = true; m_homeRegion.assign(value); }

    /**
     *
The Amazon Web Services Region where the studio resource is located.

     */
    inline Studio& WithHomeRegion(const Aws::String& value) { SetHomeRegion(value); return *this;}

    /**
     *
The Amazon Web Services Region where the studio resource is located.

     */
    inline Studio& WithHomeRegion(Aws::String&& value) { SetHomeRegion(std::move(value)); return *this;}

    /**
     *
The Amazon Web Services Region where the studio resource is located.

     */
    inline Studio& WithHomeRegion(const char* value) { SetHomeRegion(value); return *this;}

    /**
     *
The IAM Identity Center application client ID used to integrate with IAM
     * Identity Center to enable IAM Identity Center users to log in to Nimble Studio
     * portal.

     */
    inline const Aws::String& GetSsoClientId() const{ return m_ssoClientId; }

    /**
     *
The IAM Identity Center application client ID used to integrate with IAM
     * Identity Center to enable IAM Identity Center users to log in to Nimble Studio
     * portal.

     */
    inline bool SsoClientIdHasBeenSet() const { return m_ssoClientIdHasBeenSet; }

    /**
     *
The IAM Identity Center application client ID used to integrate with IAM
     * Identity Center to enable IAM Identity Center users to log in to Nimble Studio
     * portal.

     */
    inline void SetSsoClientId(const Aws::String& value) { m_ssoClientIdHasBeenSet = true; m_ssoClientId = value; }

    /**
     *
The IAM Identity Center application client ID used to integrate with IAM
     * Identity Center to enable IAM Identity Center users to log in to Nimble Studio
     * portal.

     */
    inline void SetSsoClientId(Aws::String&& value) { m_ssoClientIdHasBeenSet = true; m_ssoClientId = std::move(value); }

    /**
     *
The IAM Identity Center application client ID used to integrate with IAM
     * Identity Center to enable IAM Identity Center users to log in to Nimble Studio
     * portal.

     */
    inline void SetSsoClientId(const char* value) { m_ssoClientIdHasBeenSet = true; m_ssoClientId.assign(value); }

    /**
     *
The IAM Identity Center application client ID used to integrate with IAM
     * Identity Center to enable IAM Identity Center users to log in to Nimble Studio
     * portal.

     */
    inline Studio& WithSsoClientId(const Aws::String& value) { SetSsoClientId(value); return *this;}

    /**
     *
The IAM Identity Center application client ID used to integrate with IAM
     * Identity Center to enable IAM Identity Center users to log in to Nimble Studio
     * portal.

     */
    inline Studio& WithSsoClientId(Aws::String&& value) { SetSsoClientId(std::move(value)); return *this;}

    /**
     *
The IAM Identity Center application client ID used to integrate with IAM
     * Identity Center to enable IAM Identity Center users to log in to Nimble Studio
     * portal.

     */
    inline Studio& WithSsoClientId(const char* value) { SetSsoClientId(value); return *this;}

    /**
     *
The current state of the studio resource.

     */
    inline const StudioState& GetState() const{ return m_state; }

    /**
     *
The current state of the studio resource.

     */
    inline bool StateHasBeenSet() const { return m_stateHasBeenSet; }

    /**
     *
The current state of the studio resource.

     */
    inline void SetState(const StudioState& value) { m_stateHasBeenSet = true; m_state = value; }

    /**
     *
The current state of the studio resource.

     */
    inline void SetState(StudioState&& value) { m_stateHasBeenSet = true; m_state = std::move(value); }

    /**
     *
The current state of the studio resource.

     */
    inline Studio& WithState(const StudioState& value) { SetState(value); return *this;}

    /**
     *
The current state of the studio resource.

     */
    inline Studio& WithState(StudioState&& value) { SetState(std::move(value)); return *this;}

    /**
     *
Status codes that provide additional detail on the studio state.

     */
    inline const StudioStatusCode& GetStatusCode() const{ return m_statusCode; }

    /**
     *
Status codes that provide additional detail on the studio state.

     */
    inline bool StatusCodeHasBeenSet() const { return m_statusCodeHasBeenSet; }

    /**
     *
Status codes that provide additional detail on the studio state.

     */
    inline void SetStatusCode(const StudioStatusCode& value) { m_statusCodeHasBeenSet = true; m_statusCode = value; }

    /**
     *
Status codes that provide additional detail on the studio state.

     */
    inline void SetStatusCode(StudioStatusCode&& value) { m_statusCodeHasBeenSet = true; m_statusCode = std::move(value); }

    /**
     *
Status codes that provide additional detail on the studio state.

     */
    inline Studio& WithStatusCode(const StudioStatusCode& value) { SetStatusCode(value); return *this;}

    /**
     *
Status codes that provide additional detail on the studio state.

     */
    inline Studio& WithStatusCode(StudioStatusCode&& value) { SetStatusCode(std::move(value)); return *this;}

    /**
     *
Additional detail on the studio state.

     */
    inline const Aws::String& GetStatusMessage() const{ return m_statusMessage; }

    /**
     *
Additional detail on the studio state.

     */
    inline bool StatusMessageHasBeenSet() const { return m_statusMessageHasBeenSet; }

    /**
     *
Additional detail on the studio state.

     */
    inline void SetStatusMessage(const Aws::String& value) { m_statusMessageHasBeenSet = true; m_statusMessage = value; }

    /**
     *
Additional detail on the studio state.

     */
    inline void SetStatusMessage(Aws::String&& value) { m_statusMessageHasBeenSet = true; m_statusMessage = std::move(value); }

    /**
     *
Additional detail on the studio state.

     */
    inline void SetStatusMessage(const char* value) { m_statusMessageHasBeenSet = true; m_statusMessage.assign(value); }

    /**
     *
Additional detail on the studio state.

     */
    inline Studio& WithStatusMessage(const Aws::String& value) { SetStatusMessage(value); return *this;}

    /**
     *
Additional detail on the studio state.

     */
    inline Studio& WithStatusMessage(Aws::String&& value) { SetStatusMessage(std::move(value)); return *this;}

    /**
     *
Additional detail on the studio state.

     */
    inline Studio& WithStatusMessage(const char* value) { SetStatusMessage(value); return *this;}

    /**
     *
Configuration of the encryption method that is used for the studio.

     */
    inline const StudioEncryptionConfiguration& GetStudioEncryptionConfiguration() const{ return m_studioEncryptionConfiguration; }

    /**
     *
Configuration of the encryption method that is used for the studio.

     */
    inline bool StudioEncryptionConfigurationHasBeenSet() const { return m_studioEncryptionConfigurationHasBeenSet; }

    /**
     *
Configuration of the encryption method that is used for the studio.

     */
    inline void SetStudioEncryptionConfiguration(const StudioEncryptionConfiguration& value) { m_studioEncryptionConfigurationHasBeenSet = true; m_studioEncryptionConfiguration = value; }

    /**
     *
Configuration of the encryption method that is used for the studio.

     */
    inline void SetStudioEncryptionConfiguration(StudioEncryptionConfiguration&& value) { m_studioEncryptionConfigurationHasBeenSet = true; m_studioEncryptionConfiguration = std::move(value); }

    /**
     *
Configuration of the encryption method that is used for the studio.

     */
    inline Studio& WithStudioEncryptionConfiguration(const StudioEncryptionConfiguration& value) { SetStudioEncryptionConfiguration(value); return *this;}

    /**
     *
Configuration of the encryption method that is used for the studio.

     */
    inline Studio& WithStudioEncryptionConfiguration(StudioEncryptionConfiguration&& value) { SetStudioEncryptionConfiguration(std::move(value)); return *this;}

    /**
     *
The unique identifier for a studio resource. In Nimble Studio, all other
     * resources are contained in a studio resource.

     */
    inline const Aws::String& GetStudioId() const{ return m_studioId; }

    /**
     *
The unique identifier for a studio resource. In Nimble Studio, all other
     * resources are contained in a studio resource.

     */
    inline bool StudioIdHasBeenSet() const { return m_studioIdHasBeenSet; }

    /**
     *
The unique identifier for a studio resource. In Nimble Studio, all other
     * resources are contained in a studio resource.

     */
    inline void SetStudioId(const Aws::String& value) { m_studioIdHasBeenSet = true; m_studioId = value; }

    /**
     *
The unique identifier for a studio resource. In Nimble Studio, all other
     * resources are contained in a studio resource.

     */
    inline void SetStudioId(Aws::String&& value) { m_studioIdHasBeenSet = true; m_studioId = std::move(value); }

    /**
     *
The unique identifier for a studio resource. In Nimble Studio, all other
     * resources are contained in a studio resource.

     */
    inline void SetStudioId(const char* value) { m_studioIdHasBeenSet = true; m_studioId.assign(value); }

    /**
     *
The unique identifier for a studio resource. In Nimble Studio, all other
     * resources are contained in a studio resource.

     */
    inline Studio& WithStudioId(const Aws::String& value) { SetStudioId(value); return *this;}

    /**
     *
The unique identifier for a studio resource. In Nimble Studio, all other
     * resources are contained in a studio resource.

     */
    inline Studio& WithStudioId(Aws::String&& value) { SetStudioId(std::move(value)); return *this;}

    /**
     *
The unique identifier for a studio resource. In Nimble Studio, all other
     * resources are contained in a studio resource.

     */
    inline Studio& WithStudioId(const char* value) { SetStudioId(value); return *this;}

    /**
     *
The name of the studio, as included in the URL when accessing it in the
     * Nimble Studio portal.

     */
    inline const Aws::String& GetStudioName() const{ return m_studioName; }

    /**
     *
The name of the studio, as included in the URL when accessing it in the
     * Nimble Studio portal.

     */
    inline bool StudioNameHasBeenSet() const { return m_studioNameHasBeenSet; }

    /**
     *
The name of the studio, as included in the URL when accessing it in the
     * Nimble Studio portal.

     */
    inline void SetStudioName(const Aws::String& value) { m_studioNameHasBeenSet = true; m_studioName = value; }

    /**
     *
The name of the studio, as included in the URL when accessing it in the
     * Nimble Studio portal.

     */
    inline void SetStudioName(Aws::String&& value) { m_studioNameHasBeenSet = true; m_studioName = std::move(value); }

    /**
     *
The name of the studio, as included in the URL when accessing it in the
     * Nimble Studio portal.

     */
    inline void SetStudioName(const char* value) { m_studioNameHasBeenSet = true; m_studioName.assign(value); }

    /**
     *
The name of the studio, as included in the URL when accessing it in the
     * Nimble Studio portal.

     */
    inline Studio& WithStudioName(const Aws::String& value) { SetStudioName(value); return *this;}

    /**
     *
The name of the studio, as included in the URL when accessing it in the
     * Nimble Studio portal.

     */
    inline Studio& WithStudioName(Aws::String&& value) { SetStudioName(std::move(value)); return *this;}

    /**
     *
The name of the studio, as included in the URL when accessing it in the
     * Nimble Studio portal.

     */
    inline Studio& WithStudioName(const char* value) { SetStudioName(value); return *this;}

    /**
     *
The address of the web page for the studio.

     */
    inline const Aws::String& GetStudioUrl() const{ return m_studioUrl; }

    /**
     *
The address of the web page for the studio.

     */
    inline bool StudioUrlHasBeenSet() const { return m_studioUrlHasBeenSet; }

    /**
     *
The address of the web page for the studio.

     */
    inline void SetStudioUrl(const Aws::String& value) { m_studioUrlHasBeenSet = true; m_studioUrl = value; }

    /**
     *
The address of the web page for the studio.

     */
    inline void SetStudioUrl(Aws::String&& value) { m_studioUrlHasBeenSet = true; m_studioUrl = std::move(value); }

    /**
     *
The address of the web page for the studio.

     */
    inline void SetStudioUrl(const char* value) { m_studioUrlHasBeenSet = true; m_studioUrl.assign(value); }

    /**
     *
The address of the web page for the studio.

     */
    inline Studio& WithStudioUrl(const Aws::String& value) { SetStudioUrl(value); return *this;}

    /**
     *
The address of the web page for the studio.

     */
    inline Studio& WithStudioUrl(Aws::String&& value) { SetStudioUrl(std::move(value)); return *this;}

    /**
     *
The address of the web page for the studio.

     */
    inline Studio& WithStudioUrl(const char* value) { SetStudioUrl(value); return *this;}

    /**
     *
A collection of labels, in the form of key:value pairs, that apply to this
     * resource.

     */
    inline const Aws::Map<Aws::String, Aws::String>& GetTags() const{ return m_tags; }

    /**
     *
A collection of labels, in the form of key:value pairs, that apply to this
     * resource.

     */
    inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; }

    /**
     *
A collection of labels, in the form of key:value pairs, that apply to this
     * resource.

     */
    inline void SetTags(const Aws::Map<Aws::String, Aws::String>& value) { m_tagsHasBeenSet = true; m_tags = value; }

    /**
     *
A collection of labels, in the form of key:value pairs, that apply to this
     * resource.

     */
    inline void SetTags(Aws::Map<Aws::String, Aws::String>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }

    /**
     *
A collection of labels, in the form of key:value pairs, that apply to this
     * resource.

     */
    inline Studio& WithTags(const Aws::Map<Aws::String, Aws::String>& value) { SetTags(value); return *this;}

    /**
     *
A collection of labels, in the form of key:value pairs, that apply to this
     * resource.

     */
    inline Studio& WithTags(Aws::Map<Aws::String, Aws::String>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
A collection of labels, in the form of key:value pairs, that apply to this
     * resource.

     */
    inline Studio& AddTags(const Aws::String& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; }

    /**
     *
A collection of labels, in the form of key:value pairs, that apply to this
     * resource.

     */
    inline Studio& AddTags(Aws::String&& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; }

    /**
     *
A collection of labels, in the form of key:value pairs, that apply to this
     * resource.

     */
    inline Studio& AddTags(const Aws::String& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; }

    /**
     *
A collection of labels, in the form of key:value pairs, that apply to this
     * resource.

     */
    inline Studio& AddTags(Aws::String&& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), std::move(value)); return *this; }

    /**
     *
A collection of labels, in the form of key:value pairs, that apply to this
     * resource.

     */
    inline Studio& AddTags(const char* key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; }

    /**
     *
A collection of labels, in the form of key:value pairs, that apply to this
     * resource.

     */
    inline Studio& AddTags(Aws::String&& key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; }

    /**
     *
A collection of labels, in the form of key:value pairs, that apply to this
     * resource.

     */
    inline Studio& AddTags(const char* key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; }

    /**
     *
The Unix epoch timestamp in seconds for when the resource was updated.

     */
    inline const Aws::Utils::DateTime& GetUpdatedAt() const{ return m_updatedAt; }

    /**
     *
The Unix epoch timestamp in seconds for when the resource was updated.

     */
    inline bool UpdatedAtHasBeenSet() const { return m_updatedAtHasBeenSet; }

    /**
     *
The Unix epoch timestamp in seconds for when the resource was updated.

     */
    inline void SetUpdatedAt(const Aws::Utils::DateTime& value) { m_updatedAtHasBeenSet = true; m_updatedAt = value; }

    /**
     *
The Unix epoch timestamp in seconds for when the resource was updated.

     */
    inline void SetUpdatedAt(Aws::Utils::DateTime&& value) { m_updatedAtHasBeenSet = true; m_updatedAt = std::move(value); }

    /**
     *
The Unix epoch timestamp in seconds for when the resource was updated.

     */
    inline Studio& WithUpdatedAt(const Aws::Utils::DateTime& value) { SetUpdatedAt(value); return *this;}

    /**
     *
The Unix epoch timestamp in seconds for when the resource was updated.

     */
    inline Studio& WithUpdatedAt(Aws::Utils::DateTime&& value) { SetUpdatedAt(std::move(value)); return *this;}

    /**
     *
The IAM role that studio users assume when logging in to the Nimble Studio
     * portal.

     */
    inline const Aws::String& GetUserRoleArn() const{ return m_userRoleArn; }

    /**
     *
The IAM role that studio users assume when logging in to the Nimble Studio
     * portal.

     */
    inline bool UserRoleArnHasBeenSet() const { return m_userRoleArnHasBeenSet; }

    /**
     *
The IAM role that studio users assume when logging in to the Nimble Studio
     * portal.

     */
    inline void SetUserRoleArn(const Aws::String& value) { m_userRoleArnHasBeenSet = true; m_userRoleArn = value; }

    /**
     *
The IAM role that studio users assume when logging in to the Nimble Studio
     * portal.

     */
    inline void SetUserRoleArn(Aws::String&& value) { m_userRoleArnHasBeenSet = true; m_userRoleArn = std::move(value); }

    /**
     *
The IAM role that studio users assume when logging in to the Nimble Studio
     * portal.

     */
    inline void SetUserRoleArn(const char* value) { m_userRoleArnHasBeenSet = true; m_userRoleArn.assign(value); }

    /**
     *
The IAM role that studio users assume when logging in to the Nimble Studio
     * portal.

     */
    inline Studio& WithUserRoleArn(const Aws::String& value) { SetUserRoleArn(value); return *this;}

    /**
     *
The IAM role that studio users assume when logging in to the Nimble Studio
     * portal.

     */
    inline Studio& WithUserRoleArn(Aws::String&& value) { SetUserRoleArn(std::move(value)); return *this;}

    /**
     *
The IAM role that studio users assume when logging in to the Nimble Studio
     * portal.

     */
    inline Studio& WithUserRoleArn(const char* value) { SetUserRoleArn(value); return *this;}

  private:

    Aws::String m_adminRoleArn;
    bool m_adminRoleArnHasBeenSet = false;

    Aws::String m_arn;
    bool m_arnHasBeenSet = false;

    Aws::Utils::DateTime m_createdAt;
    bool m_createdAtHasBeenSet = false;

    Aws::String m_displayName;
    bool m_displayNameHasBeenSet = false;

    Aws::String m_homeRegion;
    bool m_homeRegionHasBeenSet = false;

    Aws::String m_ssoClientId;
    bool m_ssoClientIdHasBeenSet = false;

    StudioState m_state;
    bool m_stateHasBeenSet = false;

    StudioStatusCode m_statusCode;
    bool m_statusCodeHasBeenSet = false;

    Aws::String m_statusMessage;
    bool m_statusMessageHasBeenSet = false;

    StudioEncryptionConfiguration m_studioEncryptionConfiguration;
    bool m_studioEncryptionConfigurationHasBeenSet = false;

    Aws::String m_studioId;
    bool m_studioIdHasBeenSet = false;

    Aws::String m_studioName;
    bool m_studioNameHasBeenSet = false;

    Aws::String m_studioUrl;
    bool m_studioUrlHasBeenSet = false;

    Aws::Map<Aws::String, Aws::String> m_tags;
    bool m_tagsHasBeenSet = false;

    Aws::Utils::DateTime m_updatedAt;
    bool m_updatedAtHasBeenSet = false;

    Aws::String m_userRoleArn;
    bool m_userRoleArnHasBeenSet = false;
  };

} // namespace Model
} // namespace NimbleStudio
} // namespace Aws


text:
package com.github.nikitin_da.sticky_dictionary.ui.fragment;

import android.support.annotation.NonNull;

import com.github.nikitin_da.sticky_dictionary.R;
import com.github.nikitin_da.sticky_dictionary.model.Group;

/**
 * @author Dmitry Nikitin [nikitin.da.90@gmail.com]
 */
public class GroupCreateFragment extends BaseGroupSubmitFragment {
    @Override protected void submit(@NonNull String name) {
        Group group = new Group(mName.getText().toString());
        groupActiveModel.saveGroup(group);
    }

    @Override public Integer getActionBarTitle() {
        return R.string.group_create_title;
    }
}


text:
namespace proxy_wasm {

class TestNullVmPlugin : public NullVmPlugin {
public:
  TestNullVmPlugin() = default;
  ~TestNullVmPlugin() override = default;
};

TestNullVmPlugin *test_null_vm_plugin = nullptr;

RegisterNullVmPluginFactory register_test_null_vm_plugin("test_null_vm_plugin", []() {
  auto plugin = std::make_unique<TestNullVmPlugin>();
  test_null_vm_plugin = plugin.get();
  return plugin;
});

TEST(WasmVm, Compat) {
  std::string_view foo = "foo";
  std::string bar = "bar";

  EXPECT_NE(foo, bar);
  EXPECT_EQ(foo, "foo");

  std::optional<int> o = std::nullopt;
  EXPECT_FALSE(o);

  o = 1;
  EXPECT_TRUE(o);
}

TEST(WasmVm, Word) {
  Word w(1);
  EXPECT_EQ(w.u32(), 1);
  EXPECT_EQ(sizeof(w.u32()), sizeof(uint32_t));
  EXPECT_EQ(w, 1);
  EXPECT_EQ(sizeof(w), sizeof(uint64_t));
}

class BaseVmTest : public testing::Test {
public:
  BaseVmTest() = default;
};

TEST_F(BaseVmTest, NullVmStartup) {
  auto wasm_vm = createNullVm();
  EXPECT_TRUE(wasm_vm != nullptr);
  EXPECT_TRUE(wasm_vm->getEngineName() == "null");
  EXPECT_TRUE(wasm_vm->cloneable() == Cloneable::InstantiatedModule);
  auto wasm_vm_clone = wasm_vm->clone();
  EXPECT_TRUE(wasm_vm_clone != nullptr);
  EXPECT_TRUE(wasm_vm->load("test_null_vm_plugin", {}, {}));
  EXPECT_NE(test_null_vm_plugin, nullptr);
}

TEST_F(BaseVmTest, ByteOrder) {
  auto wasm_vm = createNullVm();
  EXPECT_TRUE(wasm_vm->load("test_null_vm_plugin", {}, {}));
  EXPECT_FALSE(wasm_vm->usesWasmByteOrder());
}

} // namespace proxy_wasm


text:
title: Recover a user password
description: Learn how to recover your Docker Datacenter credentials
keywords: docker, ucp, authentication
---

If you have administrator credentials to UCP, you can reset the password of
other users.

If that user is being managed using an LDAP service, you need to change the
user password on that system. If the user account is managed using UCP,
log in with administrator credentials into the **UCP web UI**, navigate to
the **User Management** tab, and choose the user you want to change the
password.

![](../../images/recover-a-user-password-1.png){: .with-border}

If you're an administrator and forgot your password, you can ask other users
with administrator credentials to change your password.
If you're the only administrator, use **ssh** to login directly into a manager
node managed by UCP, and run:

```none
{% raw %}
docker exec -it ucp-auth-api enzi \
  "$(docker inspect --format '{{ index .Args 0 }}' ucp-auth-api)" \
  passwd -i
{% endraw %}
```


text:
package com.certification.foundations.array;

class SearchInRotateArray{
	public static void main(String args[]){
		int[] array=new int[]{3,4,5,6,7,8,1,2};
		System.out.println(pivotedBinarySearch(array,array.length,5));
	}
	public static int pivotedBinarySearch(int[] array,int n,int key){
		int pivot = findPivot(array,0,n-1);

		if(pivot == -1){
			return binarySearch(array, 0, n-1, key);
		}
		if(array[pivot]==key){
			return pivot;
		}
		if(array[0]<=key){
			return binarySearch(array,0,pivot-1,key);
		}
		return binarySearch(array,pivot+1,n-1,key);
	}
	public static int binarySearch(int[] array,int low,int high,int key){
		if(high < low){
			return -1;
		}
		int mid = (low+high)/2;
		if(key==array[mid]){
			return mid;
		}
		if(key>array[mid]){
			return binarySearch(array,(mid+1),high,key);
		}
		return binarySearch(array,low,mid-1,key);
	}
	public static int findPivot(int[] array,int low,int high){
		if( high < low ) return -1;
		if(high == low) return low;

		int mid = (low+high)/2;
		if( mid<high && array[mid]>array[mid+1]){
			return mid;
		}
		if( mid>low  && array[mid]<array[mid-1]){
			return mid-1;
		}
		if(array[low] >= array[mid]){
			return findPivot(array,low,mid-1);
		}
		return findPivot(array, mid+1, high);
	}
}


text:
using System.Runtime.InteropServices;
using OpenQA.Selenium.Appium;
using Xunit;

namespace Avalonia.IntegrationTests.Appium
{
    [Collection("Default")]
    public class ButtonTests
    {
        private readonly AppiumDriver<AppiumWebElement> _session;

        public ButtonTests(TestAppFixture fixture)
        {
            _session = fixture.Session;

            var tabs = _session.FindElementByAccessibilityId("MainTabs");
            var tab = tabs.FindElementByName("Button");
            tab.Click();
        }

        [Fact]
        public void DisabledButton()
        {
            var button = _session.FindElementByAccessibilityId("DisabledButton");

            Assert.Equal("Disabled Button", button.Text);
            Assert.False(button.Enabled);
        }

        [Fact]
        public void BasicButton()
        {
            var button = _session.FindElementByAccessibilityId("BasicButton");

            Assert.Equal("Basic Button", button.Text);
            Assert.True(button.Enabled);
        }

        [Fact]
        public void ButtonWithTextBlock()
        {
            var button = _session.FindElementByAccessibilityId("ButtonWithTextBlock");

            Assert.Equal("Button with TextBlock", button.Text);
        }

        [PlatformFact(TestPlatforms.Windows)]
        public void ButtonWithAcceleratorKey()
        {
            var button = _session.FindElementByAccessibilityId("ButtonWithAcceleratorKey");

            Assert.Equal("Ctrl+B", button.GetAttribute("AcceleratorKey"));
        }
    }
}


text:
local DrawablePolygon = Component.create("DrawablePolygon")

function DrawablePolygon:initialize(world, x, y, l, h, type, entity)
    self.body = love.physics.newBody(world, x, y, type)
    self.shape = love.physics.newRectangleShape(l, h)
    self.fixture = love.physics.newFixture(self.body, self.shape)
    self.fixture:setUserData(entity)
end


text:
package com.google.gwt.dev.jjs.impl.gflow.cfg;

import com.google.gwt.dev.jjs.ast.JContinueStatement;

/**
 * Node corresponding to continue statement.
 */
public class CfgContinueNode extends CfgGotoNode<JContinueStatement> {
  public CfgContinueNode(CfgNode<?> parent, JContinueStatement node) {
    super(parent, node);
  }

  @Override
  public void accept(CfgVisitor visitor) {
    visitor.visitContinueNode(this);
  }

  @Override
  protected CfgNode<?> cloneImpl() {
    return new CfgContinueNode(getParent(), getJNode());
  }
}


text:
package com.navercorp.pinpoint.bootstrap.plugin.uri;

import com.navercorp.pinpoint.common.trace.UriExtractorType;
import com.navercorp.pinpoint.common.util.ArrayUtils;

import java.util.Arrays;
import java.util.Objects;

/**
 * @author Taejin Koo
 */
public class UriMappingExtractorProvider implements UriExtractorProvider {

    private final UriExtractorType uriExtractorType;
    private final String[] mappingKeyCandidates;

    public UriMappingExtractorProvider(UriExtractorType uriExtractorType, String[] mappingKeyCandidates) {
        this.uriExtractorType = Objects.requireNonNull(uriExtractorType, "uriExtractorType");

        if (ArrayUtils.isEmpty(mappingKeyCandidates)) {
            throw new IllegalArgumentException("mappingKeyCandidates may not be empty");
        }
        this.mappingKeyCandidates = mappingKeyCandidates;
    }

    @Override
    public UriExtractorType getUriExtractorType() {
        return uriExtractorType;
    }

    public String[] getMappingKeyCandidates() {
        return mappingKeyCandidates;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("UriMappingExtractorProvider{");
        sb.append("uriExtractorType=").append(uriExtractorType);
        sb.append(", mappingKeyCandidates=").append(Arrays.toString(mappingKeyCandidates));
        sb.append('}');
        return sb.toString();
    }
}


text:
package org.eulerframework.common.util.io.file;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.eulerframework.common.util.Assert;

/**
 * 基于内存的文件读写器,适用小文件的读写
 * @author cFrost
 *
 */
public abstract class SimpleFileIOUtils {
    protected static final Logger LOGGER = LoggerFactory.getLogger(SimpleFileIOUtils.class);
    private static int supportMaxFileBytes = 100 * 1024 * 1024;

    /**
     * 改变SimpleFileIOUtils中将文件读取到内存类方法的可读取文件的最大字节数
     *
     * @param bytes 最大文件大小
     */
    public static  void setSupportMaxFileBytes(int bytes) {
        Assert.isTrue(bytes < 1024 * 1024 * 1024 *2, "最大支持2GB文件的读取");
        supportMaxFileBytes = bytes;
    }

    /**
     * 读取文件至内存,一次读取一个字节
     * @param file 被读取的文件
     * @return 文件的二进制内容
     * @throws FileNotFoundException 文件不存在
     * @throws FileReadException 其他读取异常
     */
    public static byte[] readFileByByte(File file) throws FileNotFoundException, FileReadException {
        Assert.notNull(file, "file is null");

        LOGGER.info("Load file: " + file.getPath() + " Size: " + file.length());

        if(file.length() > supportMaxFileBytes) {
            throw new FileReadException("file too large, max file size is " + supportMaxFileBytes + " bytes.");
        }

        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            byte[] result = new byte[inputStream.available()];

            int count = 0;
            int tempInt;
            while ((tempInt = inputStream.read()) != -1) {
                result[count++] = (byte) tempInt;
            }

            return result;
        } catch (FileNotFoundException fileNotFoundException) {
            throw fileNotFoundException;
        } catch (IOException e) {
            throw new FileReadException(e);
        } finally {
            if (inputStream != null)
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
        }
    }

    /**
     * 读取文件至内存,一次读取多个字节
     * @param file 被读取的文件
     * @param number 一次读取的字节数
     * @return 文件二进制内容
     * @throws FileNotFoundException 文件不存在
     * @throws FileReadException 其他读取异常
     */
    public static byte[] readFileByMultiBytes(File file, int number) throws FileNotFoundException, FileReadException {
        Assert.notNull(file, "file is null");

        LOGGER.info("Load file: " + file.getPath() + " Size: " + file.length());

        if(file.length() > supportMaxFileBytes) {
            throw new FileReadException("file too large, max file size is " + supportMaxFileBytes + " bytes.");
        }

        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            byte[] result = new byte[inputStream.available()];

            int count = 0;
            byte[] tempbytes = new byte[number];
            int readCount;
            while ((readCount = inputStream.read(tempbytes)) != -1) {
                for (int i = 0; i < readCount; i++) {
                    result[count++] = tempbytes[i];
                }
            }

            return result;
        } catch (FileNotFoundException fileNotFoundException) {
            throw fileNotFoundException;
        } catch (IOException e) {
            throw new FileReadException(e);
        } finally {
            if (inputStream != null)
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
        }
    }

    /**
     * 写字符串
     *
     * @param filePath 文件路径
     * @param str 字符串内容
     * @param append 追加模式
     * @throws IOException IO异常
     */
    public static void writeFile(String filePath, String str, boolean append) throws IOException {
        Assert.notNull(filePath, "filePath is null");

        LOGGER.info("Write File: " + filePath);

        File file = new File(filePath);
        OutputStreamWriter outputStreamWriter = null;
        BufferedWriter bufferWritter = null;

        try {
            createFileIfNotExist(file);

            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file, append), "UTF-8");
            bufferWritter = new BufferedWriter(outputStreamWriter);
            bufferWritter.write(str);
            bufferWritter.close();
        } catch (IOException e) {
            throw e;
        } finally {
            if (bufferWritter != null)
                bufferWritter.close();
            if (outputStreamWriter != null)
                outputStreamWriter.close();
        }
    }

    /**
     * 写二进制数据
     *
     * @param filePath 文件路径
     * @param data 二进制内容
     * @param append 追加模式
     * @throws IOException IO异常
     */
    public static void writeFile(String filePath, byte[] data, boolean append) throws IOException {
        Assert.notNull(filePath, "filePath is null");

        LOGGER.info("Write File: " + filePath);

        File file = new File(filePath);
        FileOutputStream fileOutputStream = null;

        try {
            createFileIfNotExist(file);

            fileOutputStream = new FileOutputStream(file, append);
            fileOutputStream.write(data);
        } catch (IOException e) {
            throw e;
        } finally {
            if (fileOutputStream != null)
                fileOutputStream.close();
        }
    }
    /**
     * 将文件写入输出流
     * @param file 待写文件
     * @param outputStream 目标输出流
     * @param cacheBytes 读取缓存大小
     * @throws IOException 读写异常
     */
    public static void readFileToOutputStream(File file, OutputStream outputStream, int cacheBytes) throws IOException {
        ByteBuffer buff = ByteBuffer.allocate(cacheBytes);
        FileChannel fileInChannel = null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            fileInChannel = fileInputStream.getChannel();
            int length = 0;
            while((length = fileInChannel.read(buff)) != -1) {
                buff.flip();
                outputStream.write(buff.array(), 0, length);
                buff.clear();
            }
        } finally {
            if(fileInputStream != null) {
                fileInputStream.close();
            }
            if(fileInChannel != null) {
                fileInChannel.close();
            }
        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @param path 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful or file not exists. If a
     *         deletion fails, the method stops attempting to delete and returns
     *         "false".
     */
    public static boolean deleteFile(String path) {
        File file = new File(path);
        return deleteFile(file);
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @param file 将要删除的文件
     * @return boolean Returns "true" if all deletions were successful or file not exists. If a
     *         deletion fails, the method stops attempting to delete and returns
     *         "false".
     */
    public static boolean deleteFile(File file) {
        Assert.notNull(file, "file is null");

        if (!file.exists())
            return true;

        if (file.isDirectory()) {
            String[] children = file.list();
            // 递归删除目录中的子目录
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteFile(new File(file, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        //此时目录为空,可以删除
        LOGGER.info("Delete file: " + file.getPath());
        return file.delete();
    }

    /**
     * 在文件系统创建不存在的文件以及文件所在的目录
     * @param file 要创建的文件
     * @throws IOException IO异常
     */
    public static void createFileIfNotExist(File file) throws IOException {
        Assert.notNull(file, "file is null");

        if (!file.getParentFile().exists()) {
            LOGGER.info("Create dir: " + file.getParentFile().getPath());
            file.getParentFile().mkdirs();
        } else {
            LOGGER.info("File path exists: " + file.getParentFile().getPath());
        }

        if (!file.exists()) {
            file.createNewFile();
            LOGGER.info("Create new file: " + file.getPath());
        } else {
            LOGGER.info("File exists: " + file.getPath());
        }
    }
}


text:
import * as queryString from 'query-string'
import { decodeToken } from 'jsontokens'
import { BLOCKSTACK_HANDLER, getGlobalObject, updateQueryStringParameter } from '../utils'
import { fetchPrivate } from '../fetchUtil'

import { Logger } from '../logger'

/**
 * Retrieves the authentication request from the query string
 * @return {String|null} the authentication request or `null` if
 * the query string parameter `authRequest` is not found
 * @private
 * @ignore
 */
export function getAuthRequestFromURL() {
  const location = getGlobalObject('location', { throwIfUnavailable: true, usageDesc: 'getAuthRequestFromURL' })
  const queryDict = queryString.parse(location.search)
  if (queryDict.authRequest) {
    return (<string>queryDict.authRequest).split(`${BLOCKSTACK_HANDLER}:`).join('')
  } else {
    return null
  }
}

/**
 * Fetches the contents of the manifest file specified in the authentication request
 *
 * @param  {String} authRequest encoded and signed authentication request
 * @return {Promise<Object|String>} Returns a `Promise` that resolves to the JSON
 * object manifest file unless there's an error in which case rejects with an error
 * message.
 * @private
 * @ignore
 */
export async function fetchAppManifest(authRequest: string): Promise<any> {
  if (!authRequest) {
    throw new Error('Invalid auth request')
  }
  const payload = decodeToken(authRequest).payload
  if (typeof payload === 'string') {
    throw new Error('Unexpected token payload type of string')
  }
  const manifestURI = payload.manifest_uri as string
  try {
    Logger.debug(`Fetching manifest from ${manifestURI}`)
    const response = await fetchPrivate(manifestURI)
    const responseText = await response.text()
    const responseJSON = JSON.parse(responseText)
    return { ...responseJSON, manifestURI }
  } catch (error) {
    console.log(error)
    throw new Error('Could not fetch manifest.json')
  }
}

/**
 * Redirect the user's browser to the app using the `redirect_uri`
 * specified in the authentication request, passing the authentication
 * response token as a query parameter.
 *
 * @param {String} authRequest  encoded and signed authentication request token
 * @param {String} authResponse encoded and signed authentication response token
 * @return {void}
 * @throws {Error} if there is no redirect uri
 * @private
 * @ignore
 */
export function redirectUserToApp(authRequest: string, authResponse: string) {
  const payload = decodeToken(authRequest).payload
  if (typeof payload === 'string') {
    throw new Error('Unexpected token payload type of string')
  }
  let redirectURI = payload.redirect_uri as string
  Logger.debug(redirectURI)
  if (redirectURI) {
    redirectURI = updateQueryStringParameter(redirectURI, 'authResponse', authResponse)
  } else {
    throw new Error('Invalid redirect URI')
  }
  const location = getGlobalObject('location', { throwIfUnavailable: true, usageDesc: 'redirectUserToApp' })
  location.href = redirectURI
}


text:
#include "test-moo-aroot.h"

#include <stdio.h>

/* Define a subclass.  */
struct asub1 : struct aroot
{
  FILE *fp;
methods:
};


text:
function Dialog(_1,_2,_3){
if(typeof _3=="undefined"){
_3=window;
}
Dialog._geckoOpenModal(_1,_2,_3);
}
Dialog._parentEvent=function(ev){
setTimeout(function(){
if(Dialog._modal&&!Dialog._modal.closed){
Dialog._modal.focus();
}
},50);
try{
if(Dialog._modal&&!Dialog._modal.closed){
Xinha._stopEvent(ev);
}
}
catch(e){
}
};
Dialog._return=null;
Dialog._modal=null;
Dialog._arguments=null;
Dialog._geckoOpenModal=function(_5,_6,_7){
var _8=window.open(_5,"hadialog","toolbar=no,menubar=no,personalbar=no,width=10,height=10,"+"scrollbars=no,resizable=yes,modal=yes,dependable=yes");
Dialog._modal=_8;
Dialog._arguments=_7;
function capwin(w){
Xinha._addEvent(w,"click",Dialog._parentEvent);
Xinha._addEvent(w,"mousedown",Dialog._parentEvent);
Xinha._addEvent(w,"focus",Dialog._parentEvent);
}
function relwin(w){
Xinha._removeEvent(w,"click",Dialog._parentEvent);
Xinha._removeEvent(w,"mousedown",Dialog._parentEvent);
Xinha._removeEvent(w,"focus",Dialog._parentEvent);
}
capwin(window);
for(var i=0;i<window.frames.length;i++){
try{
capwin(window.frames[i]);
}
catch(e){
}
}
Dialog._return=function(_c){
if(_c&&_6){
_6(_c);
}
relwin(window);
for(var i=0;i<window.frames.length;i++){
try{
relwin(window.frames[i]);
}
catch(e){
}
}
Dialog._modal=null;
};
Dialog._modal.focus();
};


text:
[![Build Status](https://travis-ci.org/richardvenneman/zwemwater.png?branch=master)](https://travis-ci.org/richardvenneman/zwemwater)
[![Coverage Status](https://coveralls.io/repos/richardvenneman/zwemwater/badge.png?branch=master)](https://coveralls.io/r/richardvenneman/zwemwater?branch=master)
[![Gem Version](https://badge.fury.io/rb/zwemwater.png)](http://badge.fury.io/rb/zwemwater)

Zwemwater provides a simple API to get the latest known status from recognized Dutch swimming spots. It pulls data from the [Dutch zwemwater.nl website](http://zwemwater.nl).

## Usage

You can use zwemwater out of the box.

```ruby
require 'zwemwater'

zwemwater = Zwemwater.new('Lytse Wielen')
puts zwemwater.status     # { "code" => :goed }
```

When a swimming spot has an error code other than _:goed_, the date of measurement is also provided.

```ruby
zwemwater = Zwemwater.new('Blauwe Meer Dinxperlo')
puts zwemwater.status     # { "code" => :negatief_zwemadvies, "date" => #<Date: 2013-07-05> }
```

The zwemwater.nl website provides more information on swimming spots than just the status. This data is also fetched and can be accessed trough the `#data` method of a zwemwater instance.

```ruby
zwemwater = Zwemwater.new('Lytse Wielen')
puts zwemwater.data     # { "properties" => { "objectType" => "zwemplek", "id" => 1686, "status" => { "code" => "goed" }, "boundingBox" => { "minx" => 187255.29648096, "miny" => 580892.53598798, "maxx" => 187426.65648096, "maxy" => 580965.19598798}, "naam" => "Lytse Wielen", "zwemwaterlocatieId" => 965}, "geometry" => { "type" => "Point", "coordinates" => [187340.3393170484, 580935.4267625385]}, "type" => "Feature" }
```

### Listing possible queries

A list of all possible queries (locations) can be accessed trough `Zwemwater::Response#locations` after instantiation or after a manual fetch of statuses.

```ruby
Zwemwater::Service.get_statuses
puts Zwemwater::Response.locations     # ["Aakvlaai, Badstrand", "Abbertstrand", "Agnietenplas Oost", ..]
````

## TODO

* Better handling of raw zwemwater.nl data

## Supported Ruby Versions

Zwemwater is tested under 1.9.2, 1.9.3, 2.0.0, JRuby 1.7.2 (1.9 mode), and Rubinius 2.0.0 (1.9 mode).

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
// Copyright (C) 2006-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.enterprise.connector.mock.jcr;

import com.google.enterprise.connector.mock.MockRepository;
import com.google.enterprise.connector.mock.MockRepositoryEventList;

import junit.framework.Assert;
import junit.framework.TestCase;

import java.text.MessageFormat;
import java.util.logging.Logger;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;

/**
 * Unit tests for Mock JCR repository.
 */
public class MockJcrQueryManagerTest extends TestCase {
  private static final Logger logger =
      Logger.getLogger(MockJcrQueryManagerTest.class.getName());

  /**
   * Simple query test
   * @throws RepositoryException
   */
  public void testSimpleQuery() throws RepositoryException {
    MockRepositoryEventList mrel = new MockRepositoryEventList(
        "MockRepositoryEventLog1.txt");
    MockRepository r = new MockRepository(mrel);

    QueryManager qm = new MockJcrQueryManager(r.getStore());

    String statement = "{from:10, to:21}";
    String language = "mockQueryLanguage";

    Query query = qm.createQuery(statement, language);

    QueryResult qr = query.execute();

    NodeIterator ni = qr.getNodes();

    Node n;
    while (ni.hasNext()) {
      n = ni.nextNode();
      logger.info("docid " + n.getProperty("jcr:uuid").getString());

      Property p;
      PropertyIterator pi = n.getProperties();
      String indent = "  ";
      while (pi.hasNext()) {
        p = pi.nextProperty();
        logger.info(indent + p.getName() + " " + p.getString());
      }
    }
  }

  public void testXpathQuery() throws RepositoryException {
    MockRepositoryEventList mrel = new MockRepositoryEventList(
        "MockRepositoryEventLog1.txt");
    MockRepository r = new MockRepository(mrel);

    QueryManager qm = new MockJcrQueryManager(r.getStore());

    String messagePattern =
      "//*[@jcr:primaryType = 'nt:resource' and @jcr:lastModified >= " +
      "''{0}''] order by @jcr:lastModified, @jcr:uuid";

    String time = "1970-01-01T00:00:50Z";

    String language = Query.XPATH;

    Object[] arguments = { time };
    String statement = MessageFormat.format(
        messagePattern,
        arguments);
    System.out.println(statement);

    Query query = qm.createQuery(statement, language);

    QueryResult qr = query.execute();

    NodeIterator ni = qr.getNodes();

    int count = 0;
    while (ni.hasNext()) {
      ni.nextNode();
      count++;
    }
    Assert.assertEquals(2, count);
  }

}


text:
// *****************************************************************************
//
//  © Component Factory Pty Ltd 2017. All rights reserved.
//	The software and associated documentation supplied hereunder are the
//  proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
//  Mornington, Vic 3931, Australia and are supplied subject to licence terms.
//
//  Version 4.6.0.0 	www.ComponentFactory.com
// *****************************************************************************

using System;
using System.Text;
using System.Data;
using System.Drawing;
using System.Drawing.Design;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;

namespace ComponentFactory.Krypton.Ribbon
{
    /// <summary>
    /// Manage the items that can be added to the top level of a ribbon group instance.
    /// </summary>
    public class KryptonRibbonGroupContainerCollection : TypedRestrictCollection<KryptonRibbonGroupContainer>
    {
        #region Static Fields
        private static readonly Type[] _types = new Type[] { typeof(KryptonRibbonGroupLines),
                                                             typeof(KryptonRibbonGroupTriple),
                                                             typeof(KryptonRibbonGroupSeparator),
                                                             typeof(KryptonRibbonGroupGallery)};
        #endregion

        #region Restrict
        /// <summary>
        /// Gets an array of types that the collection is restricted to contain.
        /// </summary>
        public override Type[] RestrictTypes
        {
            get { return _types; }
        }
        #endregion
    }
}